8a9f5143bbd1fc16779a95047fb4d9fd4f2e4699
[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().
3522          */
3523         if (!env->bypass_spec_v1 && var_off) {
3524                 char tn_buf[48];
3525
3526                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3527                 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3528                                 ptr_regno, tn_buf);
3529                 return -EACCES;
3530         }
3531
3532         if (!var_off) {
3533                 off += reg->var_off.value;
3534                 err = check_stack_read_fixed_off(env, state, off, size,
3535                                                  dst_regno);
3536         } else {
3537                 /* Variable offset stack reads need more conservative handling
3538                  * than fixed offset ones. Note that dst_regno >= 0 on this
3539                  * branch.
3540                  */
3541                 err = check_stack_read_var_off(env, ptr_regno, off, size,
3542                                                dst_regno);
3543         }
3544         return err;
3545 }
3546
3547
3548 /* check_stack_write dispatches to check_stack_write_fixed_off or
3549  * check_stack_write_var_off.
3550  *
3551  * 'ptr_regno' is the register used as a pointer into the stack.
3552  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3553  * 'value_regno' is the register whose value we're writing to the stack. It can
3554  * be -1, meaning that we're not writing from a register.
3555  *
3556  * The caller must ensure that the offset falls within the maximum stack size.
3557  */
3558 static int check_stack_write(struct bpf_verifier_env *env,
3559                              int ptr_regno, int off, int size,
3560                              int value_regno, int insn_idx)
3561 {
3562         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3563         struct bpf_func_state *state = func(env, reg);
3564         int err;
3565
3566         if (tnum_is_const(reg->var_off)) {
3567                 off += reg->var_off.value;
3568                 err = check_stack_write_fixed_off(env, state, off, size,
3569                                                   value_regno, insn_idx);
3570         } else {
3571                 /* Variable offset stack reads need more conservative handling
3572                  * than fixed offset ones.
3573                  */
3574                 err = check_stack_write_var_off(env, state,
3575                                                 ptr_regno, off, size,
3576                                                 value_regno, insn_idx);
3577         }
3578         return err;
3579 }
3580
3581 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3582                                  int off, int size, enum bpf_access_type type)
3583 {
3584         struct bpf_reg_state *regs = cur_regs(env);
3585         struct bpf_map *map = regs[regno].map_ptr;
3586         u32 cap = bpf_map_flags_to_cap(map);
3587
3588         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3589                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3590                         map->value_size, off, size);
3591                 return -EACCES;
3592         }
3593
3594         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3595                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3596                         map->value_size, off, size);
3597                 return -EACCES;
3598         }
3599
3600         return 0;
3601 }
3602
3603 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3604 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3605                               int off, int size, u32 mem_size,
3606                               bool zero_size_allowed)
3607 {
3608         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3609         struct bpf_reg_state *reg;
3610
3611         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3612                 return 0;
3613
3614         reg = &cur_regs(env)[regno];
3615         switch (reg->type) {
3616         case PTR_TO_MAP_KEY:
3617                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3618                         mem_size, off, size);
3619                 break;
3620         case PTR_TO_MAP_VALUE:
3621                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3622                         mem_size, off, size);
3623                 break;
3624         case PTR_TO_PACKET:
3625         case PTR_TO_PACKET_META:
3626         case PTR_TO_PACKET_END:
3627                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3628                         off, size, regno, reg->id, off, mem_size);
3629                 break;
3630         case PTR_TO_MEM:
3631         default:
3632                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3633                         mem_size, off, size);
3634         }
3635
3636         return -EACCES;
3637 }
3638
3639 /* check read/write into a memory region with possible variable offset */
3640 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3641                                    int off, int size, u32 mem_size,
3642                                    bool zero_size_allowed)
3643 {
3644         struct bpf_verifier_state *vstate = env->cur_state;
3645         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3646         struct bpf_reg_state *reg = &state->regs[regno];
3647         int err;
3648
3649         /* We may have adjusted the register pointing to memory region, so we
3650          * need to try adding each of min_value and max_value to off
3651          * to make sure our theoretical access will be safe.
3652          *
3653          * The minimum value is only important with signed
3654          * comparisons where we can't assume the floor of a
3655          * value is 0.  If we are using signed variables for our
3656          * index'es we need to make sure that whatever we use
3657          * will have a set floor within our range.
3658          */
3659         if (reg->smin_value < 0 &&
3660             (reg->smin_value == S64_MIN ||
3661              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3662               reg->smin_value + off < 0)) {
3663                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3664                         regno);
3665                 return -EACCES;
3666         }
3667         err = __check_mem_access(env, regno, reg->smin_value + off, size,
3668                                  mem_size, zero_size_allowed);
3669         if (err) {
3670                 verbose(env, "R%d min value is outside of the allowed memory range\n",
3671                         regno);
3672                 return err;
3673         }
3674
3675         /* If we haven't set a max value then we need to bail since we can't be
3676          * sure we won't do bad things.
3677          * If reg->umax_value + off could overflow, treat that as unbounded too.
3678          */
3679         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3680                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3681                         regno);
3682                 return -EACCES;
3683         }
3684         err = __check_mem_access(env, regno, reg->umax_value + off, size,
3685                                  mem_size, zero_size_allowed);
3686         if (err) {
3687                 verbose(env, "R%d max value is outside of the allowed memory range\n",
3688                         regno);
3689                 return err;
3690         }
3691
3692         return 0;
3693 }
3694
3695 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3696                                const struct bpf_reg_state *reg, int regno,
3697                                bool fixed_off_ok)
3698 {
3699         /* Access to this pointer-typed register or passing it to a helper
3700          * is only allowed in its original, unmodified form.
3701          */
3702
3703         if (reg->off < 0) {
3704                 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3705                         reg_type_str(env, reg->type), regno, reg->off);
3706                 return -EACCES;
3707         }
3708
3709         if (!fixed_off_ok && reg->off) {
3710                 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3711                         reg_type_str(env, reg->type), regno, reg->off);
3712                 return -EACCES;
3713         }
3714
3715         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3716                 char tn_buf[48];
3717
3718                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3719                 verbose(env, "variable %s access var_off=%s disallowed\n",
3720                         reg_type_str(env, reg->type), tn_buf);
3721                 return -EACCES;
3722         }
3723
3724         return 0;
3725 }
3726
3727 int check_ptr_off_reg(struct bpf_verifier_env *env,
3728                       const struct bpf_reg_state *reg, int regno)
3729 {
3730         return __check_ptr_off_reg(env, reg, regno, false);
3731 }
3732
3733 static int map_kptr_match_type(struct bpf_verifier_env *env,
3734                                struct bpf_map_value_off_desc *off_desc,
3735                                struct bpf_reg_state *reg, u32 regno)
3736 {
3737         const char *targ_name = kernel_type_name(off_desc->kptr.btf, off_desc->kptr.btf_id);
3738         int perm_flags = PTR_MAYBE_NULL;
3739         const char *reg_name = "";
3740
3741         /* Only unreferenced case accepts untrusted pointers */
3742         if (off_desc->type == BPF_KPTR_UNREF)
3743                 perm_flags |= PTR_UNTRUSTED;
3744
3745         if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3746                 goto bad_type;
3747
3748         if (!btf_is_kernel(reg->btf)) {
3749                 verbose(env, "R%d must point to kernel BTF\n", regno);
3750                 return -EINVAL;
3751         }
3752         /* We need to verify reg->type and reg->btf, before accessing reg->btf */
3753         reg_name = kernel_type_name(reg->btf, reg->btf_id);
3754
3755         /* For ref_ptr case, release function check should ensure we get one
3756          * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3757          * normal store of unreferenced kptr, we must ensure var_off is zero.
3758          * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3759          * reg->off and reg->ref_obj_id are not needed here.
3760          */
3761         if (__check_ptr_off_reg(env, reg, regno, true))
3762                 return -EACCES;
3763
3764         /* A full type match is needed, as BTF can be vmlinux or module BTF, and
3765          * we also need to take into account the reg->off.
3766          *
3767          * We want to support cases like:
3768          *
3769          * struct foo {
3770          *         struct bar br;
3771          *         struct baz bz;
3772          * };
3773          *
3774          * struct foo *v;
3775          * v = func();        // PTR_TO_BTF_ID
3776          * val->foo = v;      // reg->off is zero, btf and btf_id match type
3777          * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3778          *                    // first member type of struct after comparison fails
3779          * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3780          *                    // to match type
3781          *
3782          * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3783          * is zero. We must also ensure that btf_struct_ids_match does not walk
3784          * the struct to match type against first member of struct, i.e. reject
3785          * second case from above. Hence, when type is BPF_KPTR_REF, we set
3786          * strict mode to true for type match.
3787          */
3788         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3789                                   off_desc->kptr.btf, off_desc->kptr.btf_id,
3790                                   off_desc->type == BPF_KPTR_REF))
3791                 goto bad_type;
3792         return 0;
3793 bad_type:
3794         verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3795                 reg_type_str(env, reg->type), reg_name);
3796         verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3797         if (off_desc->type == BPF_KPTR_UNREF)
3798                 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3799                         targ_name);
3800         else
3801                 verbose(env, "\n");
3802         return -EINVAL;
3803 }
3804
3805 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3806                                  int value_regno, int insn_idx,
3807                                  struct bpf_map_value_off_desc *off_desc)
3808 {
3809         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3810         int class = BPF_CLASS(insn->code);
3811         struct bpf_reg_state *val_reg;
3812
3813         /* Things we already checked for in check_map_access and caller:
3814          *  - Reject cases where variable offset may touch kptr
3815          *  - size of access (must be BPF_DW)
3816          *  - tnum_is_const(reg->var_off)
3817          *  - off_desc->offset == off + reg->var_off.value
3818          */
3819         /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3820         if (BPF_MODE(insn->code) != BPF_MEM) {
3821                 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3822                 return -EACCES;
3823         }
3824
3825         /* We only allow loading referenced kptr, since it will be marked as
3826          * untrusted, similar to unreferenced kptr.
3827          */
3828         if (class != BPF_LDX && off_desc->type == BPF_KPTR_REF) {
3829                 verbose(env, "store to referenced kptr disallowed\n");
3830                 return -EACCES;
3831         }
3832
3833         if (class == BPF_LDX) {
3834                 val_reg = reg_state(env, value_regno);
3835                 /* We can simply mark the value_regno receiving the pointer
3836                  * value from map as PTR_TO_BTF_ID, with the correct type.
3837                  */
3838                 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, off_desc->kptr.btf,
3839                                 off_desc->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3840                 /* For mark_ptr_or_null_reg */
3841                 val_reg->id = ++env->id_gen;
3842         } else if (class == BPF_STX) {
3843                 val_reg = reg_state(env, value_regno);
3844                 if (!register_is_null(val_reg) &&
3845                     map_kptr_match_type(env, off_desc, val_reg, value_regno))
3846                         return -EACCES;
3847         } else if (class == BPF_ST) {
3848                 if (insn->imm) {
3849                         verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3850                                 off_desc->offset);
3851                         return -EACCES;
3852                 }
3853         } else {
3854                 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3855                 return -EACCES;
3856         }
3857         return 0;
3858 }
3859
3860 /* check read/write into a map element with possible variable offset */
3861 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3862                             int off, int size, bool zero_size_allowed,
3863                             enum bpf_access_src src)
3864 {
3865         struct bpf_verifier_state *vstate = env->cur_state;
3866         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3867         struct bpf_reg_state *reg = &state->regs[regno];
3868         struct bpf_map *map = reg->map_ptr;
3869         int err;
3870
3871         err = check_mem_region_access(env, regno, off, size, map->value_size,
3872                                       zero_size_allowed);
3873         if (err)
3874                 return err;
3875
3876         if (map_value_has_spin_lock(map)) {
3877                 u32 lock = map->spin_lock_off;
3878
3879                 /* if any part of struct bpf_spin_lock can be touched by
3880                  * load/store reject this program.
3881                  * To check that [x1, x2) overlaps with [y1, y2)
3882                  * it is sufficient to check x1 < y2 && y1 < x2.
3883                  */
3884                 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3885                      lock < reg->umax_value + off + size) {
3886                         verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3887                         return -EACCES;
3888                 }
3889         }
3890         if (map_value_has_timer(map)) {
3891                 u32 t = map->timer_off;
3892
3893                 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3894                      t < reg->umax_value + off + size) {
3895                         verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3896                         return -EACCES;
3897                 }
3898         }
3899         if (map_value_has_kptrs(map)) {
3900                 struct bpf_map_value_off *tab = map->kptr_off_tab;
3901                 int i;
3902
3903                 for (i = 0; i < tab->nr_off; i++) {
3904                         u32 p = tab->off[i].offset;
3905
3906                         if (reg->smin_value + off < p + sizeof(u64) &&
3907                             p < reg->umax_value + off + size) {
3908                                 if (src != ACCESS_DIRECT) {
3909                                         verbose(env, "kptr cannot be accessed indirectly by helper\n");
3910                                         return -EACCES;
3911                                 }
3912                                 if (!tnum_is_const(reg->var_off)) {
3913                                         verbose(env, "kptr access cannot have variable offset\n");
3914                                         return -EACCES;
3915                                 }
3916                                 if (p != off + reg->var_off.value) {
3917                                         verbose(env, "kptr access misaligned expected=%u off=%llu\n",
3918                                                 p, off + reg->var_off.value);
3919                                         return -EACCES;
3920                                 }
3921                                 if (size != bpf_size_to_bytes(BPF_DW)) {
3922                                         verbose(env, "kptr access size must be BPF_DW\n");
3923                                         return -EACCES;
3924                                 }
3925                                 break;
3926                         }
3927                 }
3928         }
3929         return err;
3930 }
3931
3932 #define MAX_PACKET_OFF 0xffff
3933
3934 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3935                                        const struct bpf_call_arg_meta *meta,
3936                                        enum bpf_access_type t)
3937 {
3938         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3939
3940         switch (prog_type) {
3941         /* Program types only with direct read access go here! */
3942         case BPF_PROG_TYPE_LWT_IN:
3943         case BPF_PROG_TYPE_LWT_OUT:
3944         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3945         case BPF_PROG_TYPE_SK_REUSEPORT:
3946         case BPF_PROG_TYPE_FLOW_DISSECTOR:
3947         case BPF_PROG_TYPE_CGROUP_SKB:
3948                 if (t == BPF_WRITE)
3949                         return false;
3950                 fallthrough;
3951
3952         /* Program types with direct read + write access go here! */
3953         case BPF_PROG_TYPE_SCHED_CLS:
3954         case BPF_PROG_TYPE_SCHED_ACT:
3955         case BPF_PROG_TYPE_XDP:
3956         case BPF_PROG_TYPE_LWT_XMIT:
3957         case BPF_PROG_TYPE_SK_SKB:
3958         case BPF_PROG_TYPE_SK_MSG:
3959                 if (meta)
3960                         return meta->pkt_access;
3961
3962                 env->seen_direct_write = true;
3963                 return true;
3964
3965         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3966                 if (t == BPF_WRITE)
3967                         env->seen_direct_write = true;
3968
3969                 return true;
3970
3971         default:
3972                 return false;
3973         }
3974 }
3975
3976 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3977                                int size, bool zero_size_allowed)
3978 {
3979         struct bpf_reg_state *regs = cur_regs(env);
3980         struct bpf_reg_state *reg = &regs[regno];
3981         int err;
3982
3983         /* We may have added a variable offset to the packet pointer; but any
3984          * reg->range we have comes after that.  We are only checking the fixed
3985          * offset.
3986          */
3987
3988         /* We don't allow negative numbers, because we aren't tracking enough
3989          * detail to prove they're safe.
3990          */
3991         if (reg->smin_value < 0) {
3992                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3993                         regno);
3994                 return -EACCES;
3995         }
3996
3997         err = reg->range < 0 ? -EINVAL :
3998               __check_mem_access(env, regno, off, size, reg->range,
3999                                  zero_size_allowed);
4000         if (err) {
4001                 verbose(env, "R%d offset is outside of the packet\n", regno);
4002                 return err;
4003         }
4004
4005         /* __check_mem_access has made sure "off + size - 1" is within u16.
4006          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4007          * otherwise find_good_pkt_pointers would have refused to set range info
4008          * that __check_mem_access would have rejected this pkt access.
4009          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4010          */
4011         env->prog->aux->max_pkt_offset =
4012                 max_t(u32, env->prog->aux->max_pkt_offset,
4013                       off + reg->umax_value + size - 1);
4014
4015         return err;
4016 }
4017
4018 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
4019 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4020                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
4021                             struct btf **btf, u32 *btf_id)
4022 {
4023         struct bpf_insn_access_aux info = {
4024                 .reg_type = *reg_type,
4025                 .log = &env->log,
4026         };
4027
4028         if (env->ops->is_valid_access &&
4029             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4030                 /* A non zero info.ctx_field_size indicates that this field is a
4031                  * candidate for later verifier transformation to load the whole
4032                  * field and then apply a mask when accessed with a narrower
4033                  * access than actual ctx access size. A zero info.ctx_field_size
4034                  * will only allow for whole field access and rejects any other
4035                  * type of narrower access.
4036                  */
4037                 *reg_type = info.reg_type;
4038
4039                 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4040                         *btf = info.btf;
4041                         *btf_id = info.btf_id;
4042                 } else {
4043                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4044                 }
4045                 /* remember the offset of last byte accessed in ctx */
4046                 if (env->prog->aux->max_ctx_offset < off + size)
4047                         env->prog->aux->max_ctx_offset = off + size;
4048                 return 0;
4049         }
4050
4051         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4052         return -EACCES;
4053 }
4054
4055 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4056                                   int size)
4057 {
4058         if (size < 0 || off < 0 ||
4059             (u64)off + size > sizeof(struct bpf_flow_keys)) {
4060                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4061                         off, size);
4062                 return -EACCES;
4063         }
4064         return 0;
4065 }
4066
4067 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4068                              u32 regno, int off, int size,
4069                              enum bpf_access_type t)
4070 {
4071         struct bpf_reg_state *regs = cur_regs(env);
4072         struct bpf_reg_state *reg = &regs[regno];
4073         struct bpf_insn_access_aux info = {};
4074         bool valid;
4075
4076         if (reg->smin_value < 0) {
4077                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4078                         regno);
4079                 return -EACCES;
4080         }
4081
4082         switch (reg->type) {
4083         case PTR_TO_SOCK_COMMON:
4084                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4085                 break;
4086         case PTR_TO_SOCKET:
4087                 valid = bpf_sock_is_valid_access(off, size, t, &info);
4088                 break;
4089         case PTR_TO_TCP_SOCK:
4090                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4091                 break;
4092         case PTR_TO_XDP_SOCK:
4093                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4094                 break;
4095         default:
4096                 valid = false;
4097         }
4098
4099
4100         if (valid) {
4101                 env->insn_aux_data[insn_idx].ctx_field_size =
4102                         info.ctx_field_size;
4103                 return 0;
4104         }
4105
4106         verbose(env, "R%d invalid %s access off=%d size=%d\n",
4107                 regno, reg_type_str(env, reg->type), off, size);
4108
4109         return -EACCES;
4110 }
4111
4112 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4113 {
4114         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4115 }
4116
4117 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4118 {
4119         const struct bpf_reg_state *reg = reg_state(env, regno);
4120
4121         return reg->type == PTR_TO_CTX;
4122 }
4123
4124 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4125 {
4126         const struct bpf_reg_state *reg = reg_state(env, regno);
4127
4128         return type_is_sk_pointer(reg->type);
4129 }
4130
4131 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4132 {
4133         const struct bpf_reg_state *reg = reg_state(env, regno);
4134
4135         return type_is_pkt_pointer(reg->type);
4136 }
4137
4138 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4139 {
4140         const struct bpf_reg_state *reg = reg_state(env, regno);
4141
4142         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4143         return reg->type == PTR_TO_FLOW_KEYS;
4144 }
4145
4146 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4147                                    const struct bpf_reg_state *reg,
4148                                    int off, int size, bool strict)
4149 {
4150         struct tnum reg_off;
4151         int ip_align;
4152
4153         /* Byte size accesses are always allowed. */
4154         if (!strict || size == 1)
4155                 return 0;
4156
4157         /* For platforms that do not have a Kconfig enabling
4158          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4159          * NET_IP_ALIGN is universally set to '2'.  And on platforms
4160          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4161          * to this code only in strict mode where we want to emulate
4162          * the NET_IP_ALIGN==2 checking.  Therefore use an
4163          * unconditional IP align value of '2'.
4164          */
4165         ip_align = 2;
4166
4167         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4168         if (!tnum_is_aligned(reg_off, size)) {
4169                 char tn_buf[48];
4170
4171                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4172                 verbose(env,
4173                         "misaligned packet access off %d+%s+%d+%d size %d\n",
4174                         ip_align, tn_buf, reg->off, off, size);
4175                 return -EACCES;
4176         }
4177
4178         return 0;
4179 }
4180
4181 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4182                                        const struct bpf_reg_state *reg,
4183                                        const char *pointer_desc,
4184                                        int off, int size, bool strict)
4185 {
4186         struct tnum reg_off;
4187
4188         /* Byte size accesses are always allowed. */
4189         if (!strict || size == 1)
4190                 return 0;
4191
4192         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4193         if (!tnum_is_aligned(reg_off, size)) {
4194                 char tn_buf[48];
4195
4196                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4197                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4198                         pointer_desc, tn_buf, reg->off, off, size);
4199                 return -EACCES;
4200         }
4201
4202         return 0;
4203 }
4204
4205 static int check_ptr_alignment(struct bpf_verifier_env *env,
4206                                const struct bpf_reg_state *reg, int off,
4207                                int size, bool strict_alignment_once)
4208 {
4209         bool strict = env->strict_alignment || strict_alignment_once;
4210         const char *pointer_desc = "";
4211
4212         switch (reg->type) {
4213         case PTR_TO_PACKET:
4214         case PTR_TO_PACKET_META:
4215                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4216                  * right in front, treat it the very same way.
4217                  */
4218                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
4219         case PTR_TO_FLOW_KEYS:
4220                 pointer_desc = "flow keys ";
4221                 break;
4222         case PTR_TO_MAP_KEY:
4223                 pointer_desc = "key ";
4224                 break;
4225         case PTR_TO_MAP_VALUE:
4226                 pointer_desc = "value ";
4227                 break;
4228         case PTR_TO_CTX:
4229                 pointer_desc = "context ";
4230                 break;
4231         case PTR_TO_STACK:
4232                 pointer_desc = "stack ";
4233                 /* The stack spill tracking logic in check_stack_write_fixed_off()
4234                  * and check_stack_read_fixed_off() relies on stack accesses being
4235                  * aligned.
4236                  */
4237                 strict = true;
4238                 break;
4239         case PTR_TO_SOCKET:
4240                 pointer_desc = "sock ";
4241                 break;
4242         case PTR_TO_SOCK_COMMON:
4243                 pointer_desc = "sock_common ";
4244                 break;
4245         case PTR_TO_TCP_SOCK:
4246                 pointer_desc = "tcp_sock ";
4247                 break;
4248         case PTR_TO_XDP_SOCK:
4249                 pointer_desc = "xdp_sock ";
4250                 break;
4251         default:
4252                 break;
4253         }
4254         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4255                                            strict);
4256 }
4257
4258 static int update_stack_depth(struct bpf_verifier_env *env,
4259                               const struct bpf_func_state *func,
4260                               int off)
4261 {
4262         u16 stack = env->subprog_info[func->subprogno].stack_depth;
4263
4264         if (stack >= -off)
4265                 return 0;
4266
4267         /* update known max for given subprogram */
4268         env->subprog_info[func->subprogno].stack_depth = -off;
4269         return 0;
4270 }
4271
4272 /* starting from main bpf function walk all instructions of the function
4273  * and recursively walk all callees that given function can call.
4274  * Ignore jump and exit insns.
4275  * Since recursion is prevented by check_cfg() this algorithm
4276  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4277  */
4278 static int check_max_stack_depth(struct bpf_verifier_env *env)
4279 {
4280         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4281         struct bpf_subprog_info *subprog = env->subprog_info;
4282         struct bpf_insn *insn = env->prog->insnsi;
4283         bool tail_call_reachable = false;
4284         int ret_insn[MAX_CALL_FRAMES];
4285         int ret_prog[MAX_CALL_FRAMES];
4286         int j;
4287
4288 process_func:
4289         /* protect against potential stack overflow that might happen when
4290          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4291          * depth for such case down to 256 so that the worst case scenario
4292          * would result in 8k stack size (32 which is tailcall limit * 256 =
4293          * 8k).
4294          *
4295          * To get the idea what might happen, see an example:
4296          * func1 -> sub rsp, 128
4297          *  subfunc1 -> sub rsp, 256
4298          *  tailcall1 -> add rsp, 256
4299          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4300          *   subfunc2 -> sub rsp, 64
4301          *   subfunc22 -> sub rsp, 128
4302          *   tailcall2 -> add rsp, 128
4303          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4304          *
4305          * tailcall will unwind the current stack frame but it will not get rid
4306          * of caller's stack as shown on the example above.
4307          */
4308         if (idx && subprog[idx].has_tail_call && depth >= 256) {
4309                 verbose(env,
4310                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4311                         depth);
4312                 return -EACCES;
4313         }
4314         /* round up to 32-bytes, since this is granularity
4315          * of interpreter stack size
4316          */
4317         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4318         if (depth > MAX_BPF_STACK) {
4319                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
4320                         frame + 1, depth);
4321                 return -EACCES;
4322         }
4323 continue_func:
4324         subprog_end = subprog[idx + 1].start;
4325         for (; i < subprog_end; i++) {
4326                 int next_insn;
4327
4328                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4329                         continue;
4330                 /* remember insn and function to return to */
4331                 ret_insn[frame] = i + 1;
4332                 ret_prog[frame] = idx;
4333
4334                 /* find the callee */
4335                 next_insn = i + insn[i].imm + 1;
4336                 idx = find_subprog(env, next_insn);
4337                 if (idx < 0) {
4338                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4339                                   next_insn);
4340                         return -EFAULT;
4341                 }
4342                 if (subprog[idx].is_async_cb) {
4343                         if (subprog[idx].has_tail_call) {
4344                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4345                                 return -EFAULT;
4346                         }
4347                          /* async callbacks don't increase bpf prog stack size */
4348                         continue;
4349                 }
4350                 i = next_insn;
4351
4352                 if (subprog[idx].has_tail_call)
4353                         tail_call_reachable = true;
4354
4355                 frame++;
4356                 if (frame >= MAX_CALL_FRAMES) {
4357                         verbose(env, "the call stack of %d frames is too deep !\n",
4358                                 frame);
4359                         return -E2BIG;
4360                 }
4361                 goto process_func;
4362         }
4363         /* if tail call got detected across bpf2bpf calls then mark each of the
4364          * currently present subprog frames as tail call reachable subprogs;
4365          * this info will be utilized by JIT so that we will be preserving the
4366          * tail call counter throughout bpf2bpf calls combined with tailcalls
4367          */
4368         if (tail_call_reachable)
4369                 for (j = 0; j < frame; j++)
4370                         subprog[ret_prog[j]].tail_call_reachable = true;
4371         if (subprog[0].tail_call_reachable)
4372                 env->prog->aux->tail_call_reachable = true;
4373
4374         /* end of for() loop means the last insn of the 'subprog'
4375          * was reached. Doesn't matter whether it was JA or EXIT
4376          */
4377         if (frame == 0)
4378                 return 0;
4379         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4380         frame--;
4381         i = ret_insn[frame];
4382         idx = ret_prog[frame];
4383         goto continue_func;
4384 }
4385
4386 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4387 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4388                                   const struct bpf_insn *insn, int idx)
4389 {
4390         int start = idx + insn->imm + 1, subprog;
4391
4392         subprog = find_subprog(env, start);
4393         if (subprog < 0) {
4394                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4395                           start);
4396                 return -EFAULT;
4397         }
4398         return env->subprog_info[subprog].stack_depth;
4399 }
4400 #endif
4401
4402 static int __check_buffer_access(struct bpf_verifier_env *env,
4403                                  const char *buf_info,
4404                                  const struct bpf_reg_state *reg,
4405                                  int regno, int off, int size)
4406 {
4407         if (off < 0) {
4408                 verbose(env,
4409                         "R%d invalid %s buffer access: off=%d, size=%d\n",
4410                         regno, buf_info, off, size);
4411                 return -EACCES;
4412         }
4413         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4414                 char tn_buf[48];
4415
4416                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4417                 verbose(env,
4418                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4419                         regno, off, tn_buf);
4420                 return -EACCES;
4421         }
4422
4423         return 0;
4424 }
4425
4426 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4427                                   const struct bpf_reg_state *reg,
4428                                   int regno, int off, int size)
4429 {
4430         int err;
4431
4432         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4433         if (err)
4434                 return err;
4435
4436         if (off + size > env->prog->aux->max_tp_access)
4437                 env->prog->aux->max_tp_access = off + size;
4438
4439         return 0;
4440 }
4441
4442 static int check_buffer_access(struct bpf_verifier_env *env,
4443                                const struct bpf_reg_state *reg,
4444                                int regno, int off, int size,
4445                                bool zero_size_allowed,
4446                                u32 *max_access)
4447 {
4448         const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4449         int err;
4450
4451         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4452         if (err)
4453                 return err;
4454
4455         if (off + size > *max_access)
4456                 *max_access = off + size;
4457
4458         return 0;
4459 }
4460
4461 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4462 static void zext_32_to_64(struct bpf_reg_state *reg)
4463 {
4464         reg->var_off = tnum_subreg(reg->var_off);
4465         __reg_assign_32_into_64(reg);
4466 }
4467
4468 /* truncate register to smaller size (in bytes)
4469  * must be called with size < BPF_REG_SIZE
4470  */
4471 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4472 {
4473         u64 mask;
4474
4475         /* clear high bits in bit representation */
4476         reg->var_off = tnum_cast(reg->var_off, size);
4477
4478         /* fix arithmetic bounds */
4479         mask = ((u64)1 << (size * 8)) - 1;
4480         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4481                 reg->umin_value &= mask;
4482                 reg->umax_value &= mask;
4483         } else {
4484                 reg->umin_value = 0;
4485                 reg->umax_value = mask;
4486         }
4487         reg->smin_value = reg->umin_value;
4488         reg->smax_value = reg->umax_value;
4489
4490         /* If size is smaller than 32bit register the 32bit register
4491          * values are also truncated so we push 64-bit bounds into
4492          * 32-bit bounds. Above were truncated < 32-bits already.
4493          */
4494         if (size >= 4)
4495                 return;
4496         __reg_combine_64_into_32(reg);
4497 }
4498
4499 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4500 {
4501         /* A map is considered read-only if the following condition are true:
4502          *
4503          * 1) BPF program side cannot change any of the map content. The
4504          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4505          *    and was set at map creation time.
4506          * 2) The map value(s) have been initialized from user space by a
4507          *    loader and then "frozen", such that no new map update/delete
4508          *    operations from syscall side are possible for the rest of
4509          *    the map's lifetime from that point onwards.
4510          * 3) Any parallel/pending map update/delete operations from syscall
4511          *    side have been completed. Only after that point, it's safe to
4512          *    assume that map value(s) are immutable.
4513          */
4514         return (map->map_flags & BPF_F_RDONLY_PROG) &&
4515                READ_ONCE(map->frozen) &&
4516                !bpf_map_write_active(map);
4517 }
4518
4519 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4520 {
4521         void *ptr;
4522         u64 addr;
4523         int err;
4524
4525         err = map->ops->map_direct_value_addr(map, &addr, off);
4526         if (err)
4527                 return err;
4528         ptr = (void *)(long)addr + off;
4529
4530         switch (size) {
4531         case sizeof(u8):
4532                 *val = (u64)*(u8 *)ptr;
4533                 break;
4534         case sizeof(u16):
4535                 *val = (u64)*(u16 *)ptr;
4536                 break;
4537         case sizeof(u32):
4538                 *val = (u64)*(u32 *)ptr;
4539                 break;
4540         case sizeof(u64):
4541                 *val = *(u64 *)ptr;
4542                 break;
4543         default:
4544                 return -EINVAL;
4545         }
4546         return 0;
4547 }
4548
4549 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4550                                    struct bpf_reg_state *regs,
4551                                    int regno, int off, int size,
4552                                    enum bpf_access_type atype,
4553                                    int value_regno)
4554 {
4555         struct bpf_reg_state *reg = regs + regno;
4556         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4557         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4558         enum bpf_type_flag flag = 0;
4559         u32 btf_id;
4560         int ret;
4561
4562         if (off < 0) {
4563                 verbose(env,
4564                         "R%d is ptr_%s invalid negative access: off=%d\n",
4565                         regno, tname, off);
4566                 return -EACCES;
4567         }
4568         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4569                 char tn_buf[48];
4570
4571                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4572                 verbose(env,
4573                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4574                         regno, tname, off, tn_buf);
4575                 return -EACCES;
4576         }
4577
4578         if (reg->type & MEM_USER) {
4579                 verbose(env,
4580                         "R%d is ptr_%s access user memory: off=%d\n",
4581                         regno, tname, off);
4582                 return -EACCES;
4583         }
4584
4585         if (reg->type & MEM_PERCPU) {
4586                 verbose(env,
4587                         "R%d is ptr_%s access percpu memory: off=%d\n",
4588                         regno, tname, off);
4589                 return -EACCES;
4590         }
4591
4592         if (env->ops->btf_struct_access) {
4593                 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4594                                                   off, size, atype, &btf_id, &flag);
4595         } else {
4596                 if (atype != BPF_READ) {
4597                         verbose(env, "only read is supported\n");
4598                         return -EACCES;
4599                 }
4600
4601                 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4602                                         atype, &btf_id, &flag);
4603         }
4604
4605         if (ret < 0)
4606                 return ret;
4607
4608         /* If this is an untrusted pointer, all pointers formed by walking it
4609          * also inherit the untrusted flag.
4610          */
4611         if (type_flag(reg->type) & PTR_UNTRUSTED)
4612                 flag |= PTR_UNTRUSTED;
4613
4614         if (atype == BPF_READ && value_regno >= 0)
4615                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4616
4617         return 0;
4618 }
4619
4620 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4621                                    struct bpf_reg_state *regs,
4622                                    int regno, int off, int size,
4623                                    enum bpf_access_type atype,
4624                                    int value_regno)
4625 {
4626         struct bpf_reg_state *reg = regs + regno;
4627         struct bpf_map *map = reg->map_ptr;
4628         enum bpf_type_flag flag = 0;
4629         const struct btf_type *t;
4630         const char *tname;
4631         u32 btf_id;
4632         int ret;
4633
4634         if (!btf_vmlinux) {
4635                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4636                 return -ENOTSUPP;
4637         }
4638
4639         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4640                 verbose(env, "map_ptr access not supported for map type %d\n",
4641                         map->map_type);
4642                 return -ENOTSUPP;
4643         }
4644
4645         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4646         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4647
4648         if (!env->allow_ptr_to_map_access) {
4649                 verbose(env,
4650                         "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4651                         tname);
4652                 return -EPERM;
4653         }
4654
4655         if (off < 0) {
4656                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4657                         regno, tname, off);
4658                 return -EACCES;
4659         }
4660
4661         if (atype != BPF_READ) {
4662                 verbose(env, "only read from %s is supported\n", tname);
4663                 return -EACCES;
4664         }
4665
4666         ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag);
4667         if (ret < 0)
4668                 return ret;
4669
4670         if (value_regno >= 0)
4671                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4672
4673         return 0;
4674 }
4675
4676 /* Check that the stack access at the given offset is within bounds. The
4677  * maximum valid offset is -1.
4678  *
4679  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4680  * -state->allocated_stack for reads.
4681  */
4682 static int check_stack_slot_within_bounds(int off,
4683                                           struct bpf_func_state *state,
4684                                           enum bpf_access_type t)
4685 {
4686         int min_valid_off;
4687
4688         if (t == BPF_WRITE)
4689                 min_valid_off = -MAX_BPF_STACK;
4690         else
4691                 min_valid_off = -state->allocated_stack;
4692
4693         if (off < min_valid_off || off > -1)
4694                 return -EACCES;
4695         return 0;
4696 }
4697
4698 /* Check that the stack access at 'regno + off' falls within the maximum stack
4699  * bounds.
4700  *
4701  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4702  */
4703 static int check_stack_access_within_bounds(
4704                 struct bpf_verifier_env *env,
4705                 int regno, int off, int access_size,
4706                 enum bpf_access_src src, enum bpf_access_type type)
4707 {
4708         struct bpf_reg_state *regs = cur_regs(env);
4709         struct bpf_reg_state *reg = regs + regno;
4710         struct bpf_func_state *state = func(env, reg);
4711         int min_off, max_off;
4712         int err;
4713         char *err_extra;
4714
4715         if (src == ACCESS_HELPER)
4716                 /* We don't know if helpers are reading or writing (or both). */
4717                 err_extra = " indirect access to";
4718         else if (type == BPF_READ)
4719                 err_extra = " read from";
4720         else
4721                 err_extra = " write to";
4722
4723         if (tnum_is_const(reg->var_off)) {
4724                 min_off = reg->var_off.value + off;
4725                 if (access_size > 0)
4726                         max_off = min_off + access_size - 1;
4727                 else
4728                         max_off = min_off;
4729         } else {
4730                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4731                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
4732                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4733                                 err_extra, regno);
4734                         return -EACCES;
4735                 }
4736                 min_off = reg->smin_value + off;
4737                 if (access_size > 0)
4738                         max_off = reg->smax_value + off + access_size - 1;
4739                 else
4740                         max_off = min_off;
4741         }
4742
4743         err = check_stack_slot_within_bounds(min_off, state, type);
4744         if (!err)
4745                 err = check_stack_slot_within_bounds(max_off, state, type);
4746
4747         if (err) {
4748                 if (tnum_is_const(reg->var_off)) {
4749                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4750                                 err_extra, regno, off, access_size);
4751                 } else {
4752                         char tn_buf[48];
4753
4754                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4755                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4756                                 err_extra, regno, tn_buf, access_size);
4757                 }
4758         }
4759         return err;
4760 }
4761
4762 /* check whether memory at (regno + off) is accessible for t = (read | write)
4763  * if t==write, value_regno is a register which value is stored into memory
4764  * if t==read, value_regno is a register which will receive the value from memory
4765  * if t==write && value_regno==-1, some unknown value is stored into memory
4766  * if t==read && value_regno==-1, don't care what we read from memory
4767  */
4768 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4769                             int off, int bpf_size, enum bpf_access_type t,
4770                             int value_regno, bool strict_alignment_once)
4771 {
4772         struct bpf_reg_state *regs = cur_regs(env);
4773         struct bpf_reg_state *reg = regs + regno;
4774         struct bpf_func_state *state;
4775         int size, err = 0;
4776
4777         size = bpf_size_to_bytes(bpf_size);
4778         if (size < 0)
4779                 return size;
4780
4781         /* alignment checks will add in reg->off themselves */
4782         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4783         if (err)
4784                 return err;
4785
4786         /* for access checks, reg->off is just part of off */
4787         off += reg->off;
4788
4789         if (reg->type == PTR_TO_MAP_KEY) {
4790                 if (t == BPF_WRITE) {
4791                         verbose(env, "write to change key R%d not allowed\n", regno);
4792                         return -EACCES;
4793                 }
4794
4795                 err = check_mem_region_access(env, regno, off, size,
4796                                               reg->map_ptr->key_size, false);
4797                 if (err)
4798                         return err;
4799                 if (value_regno >= 0)
4800                         mark_reg_unknown(env, regs, value_regno);
4801         } else if (reg->type == PTR_TO_MAP_VALUE) {
4802                 struct bpf_map_value_off_desc *kptr_off_desc = NULL;
4803
4804                 if (t == BPF_WRITE && value_regno >= 0 &&
4805                     is_pointer_value(env, value_regno)) {
4806                         verbose(env, "R%d leaks addr into map\n", value_regno);
4807                         return -EACCES;
4808                 }
4809                 err = check_map_access_type(env, regno, off, size, t);
4810                 if (err)
4811                         return err;
4812                 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4813                 if (err)
4814                         return err;
4815                 if (tnum_is_const(reg->var_off))
4816                         kptr_off_desc = bpf_map_kptr_off_contains(reg->map_ptr,
4817                                                                   off + reg->var_off.value);
4818                 if (kptr_off_desc) {
4819                         err = check_map_kptr_access(env, regno, value_regno, insn_idx,
4820                                                     kptr_off_desc);
4821                 } else if (t == BPF_READ && value_regno >= 0) {
4822                         struct bpf_map *map = reg->map_ptr;
4823
4824                         /* if map is read-only, track its contents as scalars */
4825                         if (tnum_is_const(reg->var_off) &&
4826                             bpf_map_is_rdonly(map) &&
4827                             map->ops->map_direct_value_addr) {
4828                                 int map_off = off + reg->var_off.value;
4829                                 u64 val = 0;
4830
4831                                 err = bpf_map_direct_read(map, map_off, size,
4832                                                           &val);
4833                                 if (err)
4834                                         return err;
4835
4836                                 regs[value_regno].type = SCALAR_VALUE;
4837                                 __mark_reg_known(&regs[value_regno], val);
4838                         } else {
4839                                 mark_reg_unknown(env, regs, value_regno);
4840                         }
4841                 }
4842         } else if (base_type(reg->type) == PTR_TO_MEM) {
4843                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4844
4845                 if (type_may_be_null(reg->type)) {
4846                         verbose(env, "R%d invalid mem access '%s'\n", regno,
4847                                 reg_type_str(env, reg->type));
4848                         return -EACCES;
4849                 }
4850
4851                 if (t == BPF_WRITE && rdonly_mem) {
4852                         verbose(env, "R%d cannot write into %s\n",
4853                                 regno, reg_type_str(env, reg->type));
4854                         return -EACCES;
4855                 }
4856
4857                 if (t == BPF_WRITE && value_regno >= 0 &&
4858                     is_pointer_value(env, value_regno)) {
4859                         verbose(env, "R%d leaks addr into mem\n", value_regno);
4860                         return -EACCES;
4861                 }
4862
4863                 err = check_mem_region_access(env, regno, off, size,
4864                                               reg->mem_size, false);
4865                 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4866                         mark_reg_unknown(env, regs, value_regno);
4867         } else if (reg->type == PTR_TO_CTX) {
4868                 enum bpf_reg_type reg_type = SCALAR_VALUE;
4869                 struct btf *btf = NULL;
4870                 u32 btf_id = 0;
4871
4872                 if (t == BPF_WRITE && value_regno >= 0 &&
4873                     is_pointer_value(env, value_regno)) {
4874                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
4875                         return -EACCES;
4876                 }
4877
4878                 err = check_ptr_off_reg(env, reg, regno);
4879                 if (err < 0)
4880                         return err;
4881
4882                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
4883                                        &btf_id);
4884                 if (err)
4885                         verbose_linfo(env, insn_idx, "; ");
4886                 if (!err && t == BPF_READ && value_regno >= 0) {
4887                         /* ctx access returns either a scalar, or a
4888                          * PTR_TO_PACKET[_META,_END]. In the latter
4889                          * case, we know the offset is zero.
4890                          */
4891                         if (reg_type == SCALAR_VALUE) {
4892                                 mark_reg_unknown(env, regs, value_regno);
4893                         } else {
4894                                 mark_reg_known_zero(env, regs,
4895                                                     value_regno);
4896                                 if (type_may_be_null(reg_type))
4897                                         regs[value_regno].id = ++env->id_gen;
4898                                 /* A load of ctx field could have different
4899                                  * actual load size with the one encoded in the
4900                                  * insn. When the dst is PTR, it is for sure not
4901                                  * a sub-register.
4902                                  */
4903                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4904                                 if (base_type(reg_type) == PTR_TO_BTF_ID) {
4905                                         regs[value_regno].btf = btf;
4906                                         regs[value_regno].btf_id = btf_id;
4907                                 }
4908                         }
4909                         regs[value_regno].type = reg_type;
4910                 }
4911
4912         } else if (reg->type == PTR_TO_STACK) {
4913                 /* Basic bounds checks. */
4914                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4915                 if (err)
4916                         return err;
4917
4918                 state = func(env, reg);
4919                 err = update_stack_depth(env, state, off);
4920                 if (err)
4921                         return err;
4922
4923                 if (t == BPF_READ)
4924                         err = check_stack_read(env, regno, off, size,
4925                                                value_regno);
4926                 else
4927                         err = check_stack_write(env, regno, off, size,
4928                                                 value_regno, insn_idx);
4929         } else if (reg_is_pkt_pointer(reg)) {
4930                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4931                         verbose(env, "cannot write into packet\n");
4932                         return -EACCES;
4933                 }
4934                 if (t == BPF_WRITE && value_regno >= 0 &&
4935                     is_pointer_value(env, value_regno)) {
4936                         verbose(env, "R%d leaks addr into packet\n",
4937                                 value_regno);
4938                         return -EACCES;
4939                 }
4940                 err = check_packet_access(env, regno, off, size, false);
4941                 if (!err && t == BPF_READ && value_regno >= 0)
4942                         mark_reg_unknown(env, regs, value_regno);
4943         } else if (reg->type == PTR_TO_FLOW_KEYS) {
4944                 if (t == BPF_WRITE && value_regno >= 0 &&
4945                     is_pointer_value(env, value_regno)) {
4946                         verbose(env, "R%d leaks addr into flow keys\n",
4947                                 value_regno);
4948                         return -EACCES;
4949                 }
4950
4951                 err = check_flow_keys_access(env, off, size);
4952                 if (!err && t == BPF_READ && value_regno >= 0)
4953                         mark_reg_unknown(env, regs, value_regno);
4954         } else if (type_is_sk_pointer(reg->type)) {
4955                 if (t == BPF_WRITE) {
4956                         verbose(env, "R%d cannot write into %s\n",
4957                                 regno, reg_type_str(env, reg->type));
4958                         return -EACCES;
4959                 }
4960                 err = check_sock_access(env, insn_idx, regno, off, size, t);
4961                 if (!err && value_regno >= 0)
4962                         mark_reg_unknown(env, regs, value_regno);
4963         } else if (reg->type == PTR_TO_TP_BUFFER) {
4964                 err = check_tp_buffer_access(env, reg, regno, off, size);
4965                 if (!err && t == BPF_READ && value_regno >= 0)
4966                         mark_reg_unknown(env, regs, value_regno);
4967         } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
4968                    !type_may_be_null(reg->type)) {
4969                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4970                                               value_regno);
4971         } else if (reg->type == CONST_PTR_TO_MAP) {
4972                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4973                                               value_regno);
4974         } else if (base_type(reg->type) == PTR_TO_BUF) {
4975                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4976                 u32 *max_access;
4977
4978                 if (rdonly_mem) {
4979                         if (t == BPF_WRITE) {
4980                                 verbose(env, "R%d cannot write into %s\n",
4981                                         regno, reg_type_str(env, reg->type));
4982                                 return -EACCES;
4983                         }
4984                         max_access = &env->prog->aux->max_rdonly_access;
4985                 } else {
4986                         max_access = &env->prog->aux->max_rdwr_access;
4987                 }
4988
4989                 err = check_buffer_access(env, reg, regno, off, size, false,
4990                                           max_access);
4991
4992                 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4993                         mark_reg_unknown(env, regs, value_regno);
4994         } else {
4995                 verbose(env, "R%d invalid mem access '%s'\n", regno,
4996                         reg_type_str(env, reg->type));
4997                 return -EACCES;
4998         }
4999
5000         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5001             regs[value_regno].type == SCALAR_VALUE) {
5002                 /* b/h/w load zero-extends, mark upper bits as known 0 */
5003                 coerce_reg_to_size(&regs[value_regno], size);
5004         }
5005         return err;
5006 }
5007
5008 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5009 {
5010         int load_reg;
5011         int err;
5012
5013         switch (insn->imm) {
5014         case BPF_ADD:
5015         case BPF_ADD | BPF_FETCH:
5016         case BPF_AND:
5017         case BPF_AND | BPF_FETCH:
5018         case BPF_OR:
5019         case BPF_OR | BPF_FETCH:
5020         case BPF_XOR:
5021         case BPF_XOR | BPF_FETCH:
5022         case BPF_XCHG:
5023         case BPF_CMPXCHG:
5024                 break;
5025         default:
5026                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5027                 return -EINVAL;
5028         }
5029
5030         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5031                 verbose(env, "invalid atomic operand size\n");
5032                 return -EINVAL;
5033         }
5034
5035         /* check src1 operand */
5036         err = check_reg_arg(env, insn->src_reg, SRC_OP);
5037         if (err)
5038                 return err;
5039
5040         /* check src2 operand */
5041         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5042         if (err)
5043                 return err;
5044
5045         if (insn->imm == BPF_CMPXCHG) {
5046                 /* Check comparison of R0 with memory location */
5047                 const u32 aux_reg = BPF_REG_0;
5048
5049                 err = check_reg_arg(env, aux_reg, SRC_OP);
5050                 if (err)
5051                         return err;
5052
5053                 if (is_pointer_value(env, aux_reg)) {
5054                         verbose(env, "R%d leaks addr into mem\n", aux_reg);
5055                         return -EACCES;
5056                 }
5057         }
5058
5059         if (is_pointer_value(env, insn->src_reg)) {
5060                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5061                 return -EACCES;
5062         }
5063
5064         if (is_ctx_reg(env, insn->dst_reg) ||
5065             is_pkt_reg(env, insn->dst_reg) ||
5066             is_flow_key_reg(env, insn->dst_reg) ||
5067             is_sk_reg(env, insn->dst_reg)) {
5068                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5069                         insn->dst_reg,
5070                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5071                 return -EACCES;
5072         }
5073
5074         if (insn->imm & BPF_FETCH) {
5075                 if (insn->imm == BPF_CMPXCHG)
5076                         load_reg = BPF_REG_0;
5077                 else
5078                         load_reg = insn->src_reg;
5079
5080                 /* check and record load of old value */
5081                 err = check_reg_arg(env, load_reg, DST_OP);
5082                 if (err)
5083                         return err;
5084         } else {
5085                 /* This instruction accesses a memory location but doesn't
5086                  * actually load it into a register.
5087                  */
5088                 load_reg = -1;
5089         }
5090
5091         /* Check whether we can read the memory, with second call for fetch
5092          * case to simulate the register fill.
5093          */
5094         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5095                                BPF_SIZE(insn->code), BPF_READ, -1, true);
5096         if (!err && load_reg >= 0)
5097                 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5098                                        BPF_SIZE(insn->code), BPF_READ, load_reg,
5099                                        true);
5100         if (err)
5101                 return err;
5102
5103         /* Check whether we can write into the same memory. */
5104         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5105                                BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5106         if (err)
5107                 return err;
5108
5109         return 0;
5110 }
5111
5112 /* When register 'regno' is used to read the stack (either directly or through
5113  * a helper function) make sure that it's within stack boundary and, depending
5114  * on the access type, that all elements of the stack are initialized.
5115  *
5116  * 'off' includes 'regno->off', but not its dynamic part (if any).
5117  *
5118  * All registers that have been spilled on the stack in the slots within the
5119  * read offsets are marked as read.
5120  */
5121 static int check_stack_range_initialized(
5122                 struct bpf_verifier_env *env, int regno, int off,
5123                 int access_size, bool zero_size_allowed,
5124                 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5125 {
5126         struct bpf_reg_state *reg = reg_state(env, regno);
5127         struct bpf_func_state *state = func(env, reg);
5128         int err, min_off, max_off, i, j, slot, spi;
5129         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5130         enum bpf_access_type bounds_check_type;
5131         /* Some accesses can write anything into the stack, others are
5132          * read-only.
5133          */
5134         bool clobber = false;
5135
5136         if (access_size == 0 && !zero_size_allowed) {
5137                 verbose(env, "invalid zero-sized read\n");
5138                 return -EACCES;
5139         }
5140
5141         if (type == ACCESS_HELPER) {
5142                 /* The bounds checks for writes are more permissive than for
5143                  * reads. However, if raw_mode is not set, we'll do extra
5144                  * checks below.
5145                  */
5146                 bounds_check_type = BPF_WRITE;
5147                 clobber = true;
5148         } else {
5149                 bounds_check_type = BPF_READ;
5150         }
5151         err = check_stack_access_within_bounds(env, regno, off, access_size,
5152                                                type, bounds_check_type);
5153         if (err)
5154                 return err;
5155
5156
5157         if (tnum_is_const(reg->var_off)) {
5158                 min_off = max_off = reg->var_off.value + off;
5159         } else {
5160                 /* Variable offset is prohibited for unprivileged mode for
5161                  * simplicity since it requires corresponding support in
5162                  * Spectre masking for stack ALU.
5163                  * See also retrieve_ptr_limit().
5164                  */
5165                 if (!env->bypass_spec_v1) {
5166                         char tn_buf[48];
5167
5168                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5169                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5170                                 regno, err_extra, tn_buf);
5171                         return -EACCES;
5172                 }
5173                 /* Only initialized buffer on stack is allowed to be accessed
5174                  * with variable offset. With uninitialized buffer it's hard to
5175                  * guarantee that whole memory is marked as initialized on
5176                  * helper return since specific bounds are unknown what may
5177                  * cause uninitialized stack leaking.
5178                  */
5179                 if (meta && meta->raw_mode)
5180                         meta = NULL;
5181
5182                 min_off = reg->smin_value + off;
5183                 max_off = reg->smax_value + off;
5184         }
5185
5186         if (meta && meta->raw_mode) {
5187                 meta->access_size = access_size;
5188                 meta->regno = regno;
5189                 return 0;
5190         }
5191
5192         for (i = min_off; i < max_off + access_size; i++) {
5193                 u8 *stype;
5194
5195                 slot = -i - 1;
5196                 spi = slot / BPF_REG_SIZE;
5197                 if (state->allocated_stack <= slot)
5198                         goto err;
5199                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5200                 if (*stype == STACK_MISC)
5201                         goto mark;
5202                 if (*stype == STACK_ZERO) {
5203                         if (clobber) {
5204                                 /* helper can write anything into the stack */
5205                                 *stype = STACK_MISC;
5206                         }
5207                         goto mark;
5208                 }
5209
5210                 if (is_spilled_reg(&state->stack[spi]) &&
5211                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5212                      env->allow_ptr_leaks)) {
5213                         if (clobber) {
5214                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5215                                 for (j = 0; j < BPF_REG_SIZE; j++)
5216                                         scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5217                         }
5218                         goto mark;
5219                 }
5220
5221 err:
5222                 if (tnum_is_const(reg->var_off)) {
5223                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5224                                 err_extra, regno, min_off, i - min_off, access_size);
5225                 } else {
5226                         char tn_buf[48];
5227
5228                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5229                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5230                                 err_extra, regno, tn_buf, i - min_off, access_size);
5231                 }
5232                 return -EACCES;
5233 mark:
5234                 /* reading any byte out of 8-byte 'spill_slot' will cause
5235                  * the whole slot to be marked as 'read'
5236                  */
5237                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5238                               state->stack[spi].spilled_ptr.parent,
5239                               REG_LIVE_READ64);
5240                 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5241                  * be sure that whether stack slot is written to or not. Hence,
5242                  * we must still conservatively propagate reads upwards even if
5243                  * helper may write to the entire memory range.
5244                  */
5245         }
5246         return update_stack_depth(env, state, min_off);
5247 }
5248
5249 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5250                                    int access_size, bool zero_size_allowed,
5251                                    struct bpf_call_arg_meta *meta)
5252 {
5253         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5254         u32 *max_access;
5255
5256         switch (base_type(reg->type)) {
5257         case PTR_TO_PACKET:
5258         case PTR_TO_PACKET_META:
5259                 return check_packet_access(env, regno, reg->off, access_size,
5260                                            zero_size_allowed);
5261         case PTR_TO_MAP_KEY:
5262                 if (meta && meta->raw_mode) {
5263                         verbose(env, "R%d cannot write into %s\n", regno,
5264                                 reg_type_str(env, reg->type));
5265                         return -EACCES;
5266                 }
5267                 return check_mem_region_access(env, regno, reg->off, access_size,
5268                                                reg->map_ptr->key_size, false);
5269         case PTR_TO_MAP_VALUE:
5270                 if (check_map_access_type(env, regno, reg->off, access_size,
5271                                           meta && meta->raw_mode ? BPF_WRITE :
5272                                           BPF_READ))
5273                         return -EACCES;
5274                 return check_map_access(env, regno, reg->off, access_size,
5275                                         zero_size_allowed, ACCESS_HELPER);
5276         case PTR_TO_MEM:
5277                 if (type_is_rdonly_mem(reg->type)) {
5278                         if (meta && meta->raw_mode) {
5279                                 verbose(env, "R%d cannot write into %s\n", regno,
5280                                         reg_type_str(env, reg->type));
5281                                 return -EACCES;
5282                         }
5283                 }
5284                 return check_mem_region_access(env, regno, reg->off,
5285                                                access_size, reg->mem_size,
5286                                                zero_size_allowed);
5287         case PTR_TO_BUF:
5288                 if (type_is_rdonly_mem(reg->type)) {
5289                         if (meta && meta->raw_mode) {
5290                                 verbose(env, "R%d cannot write into %s\n", regno,
5291                                         reg_type_str(env, reg->type));
5292                                 return -EACCES;
5293                         }
5294
5295                         max_access = &env->prog->aux->max_rdonly_access;
5296                 } else {
5297                         max_access = &env->prog->aux->max_rdwr_access;
5298                 }
5299                 return check_buffer_access(env, reg, regno, reg->off,
5300                                            access_size, zero_size_allowed,
5301                                            max_access);
5302         case PTR_TO_STACK:
5303                 return check_stack_range_initialized(
5304                                 env,
5305                                 regno, reg->off, access_size,
5306                                 zero_size_allowed, ACCESS_HELPER, meta);
5307         case PTR_TO_CTX:
5308                 /* in case the function doesn't know how to access the context,
5309                  * (because we are in a program of type SYSCALL for example), we
5310                  * can not statically check its size.
5311                  * Dynamically check it now.
5312                  */
5313                 if (!env->ops->convert_ctx_access) {
5314                         enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5315                         int offset = access_size - 1;
5316
5317                         /* Allow zero-byte read from PTR_TO_CTX */
5318                         if (access_size == 0)
5319                                 return zero_size_allowed ? 0 : -EACCES;
5320
5321                         return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5322                                                 atype, -1, false);
5323                 }
5324
5325                 fallthrough;
5326         default: /* scalar_value or invalid ptr */
5327                 /* Allow zero-byte read from NULL, regardless of pointer type */
5328                 if (zero_size_allowed && access_size == 0 &&
5329                     register_is_null(reg))
5330                         return 0;
5331
5332                 verbose(env, "R%d type=%s ", regno,
5333                         reg_type_str(env, reg->type));
5334                 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5335                 return -EACCES;
5336         }
5337 }
5338
5339 static int check_mem_size_reg(struct bpf_verifier_env *env,
5340                               struct bpf_reg_state *reg, u32 regno,
5341                               bool zero_size_allowed,
5342                               struct bpf_call_arg_meta *meta)
5343 {
5344         int err;
5345
5346         /* This is used to refine r0 return value bounds for helpers
5347          * that enforce this value as an upper bound on return values.
5348          * See do_refine_retval_range() for helpers that can refine
5349          * the return value. C type of helper is u32 so we pull register
5350          * bound from umax_value however, if negative verifier errors
5351          * out. Only upper bounds can be learned because retval is an
5352          * int type and negative retvals are allowed.
5353          */
5354         meta->msize_max_value = reg->umax_value;
5355
5356         /* The register is SCALAR_VALUE; the access check
5357          * happens using its boundaries.
5358          */
5359         if (!tnum_is_const(reg->var_off))
5360                 /* For unprivileged variable accesses, disable raw
5361                  * mode so that the program is required to
5362                  * initialize all the memory that the helper could
5363                  * just partially fill up.
5364                  */
5365                 meta = NULL;
5366
5367         if (reg->smin_value < 0) {
5368                 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5369                         regno);
5370                 return -EACCES;
5371         }
5372
5373         if (reg->umin_value == 0) {
5374                 err = check_helper_mem_access(env, regno - 1, 0,
5375                                               zero_size_allowed,
5376                                               meta);
5377                 if (err)
5378                         return err;
5379         }
5380
5381         if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5382                 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5383                         regno);
5384                 return -EACCES;
5385         }
5386         err = check_helper_mem_access(env, regno - 1,
5387                                       reg->umax_value,
5388                                       zero_size_allowed, meta);
5389         if (!err)
5390                 err = mark_chain_precision(env, regno);
5391         return err;
5392 }
5393
5394 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5395                    u32 regno, u32 mem_size)
5396 {
5397         bool may_be_null = type_may_be_null(reg->type);
5398         struct bpf_reg_state saved_reg;
5399         struct bpf_call_arg_meta meta;
5400         int err;
5401
5402         if (register_is_null(reg))
5403                 return 0;
5404
5405         memset(&meta, 0, sizeof(meta));
5406         /* Assuming that the register contains a value check if the memory
5407          * access is safe. Temporarily save and restore the register's state as
5408          * the conversion shouldn't be visible to a caller.
5409          */
5410         if (may_be_null) {
5411                 saved_reg = *reg;
5412                 mark_ptr_not_null_reg(reg);
5413         }
5414
5415         err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5416         /* Check access for BPF_WRITE */
5417         meta.raw_mode = true;
5418         err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5419
5420         if (may_be_null)
5421                 *reg = saved_reg;
5422
5423         return err;
5424 }
5425
5426 int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5427                              u32 regno)
5428 {
5429         struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5430         bool may_be_null = type_may_be_null(mem_reg->type);
5431         struct bpf_reg_state saved_reg;
5432         struct bpf_call_arg_meta meta;
5433         int err;
5434
5435         WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5436
5437         memset(&meta, 0, sizeof(meta));
5438
5439         if (may_be_null) {
5440                 saved_reg = *mem_reg;
5441                 mark_ptr_not_null_reg(mem_reg);
5442         }
5443
5444         err = check_mem_size_reg(env, reg, regno, true, &meta);
5445         /* Check access for BPF_WRITE */
5446         meta.raw_mode = true;
5447         err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5448
5449         if (may_be_null)
5450                 *mem_reg = saved_reg;
5451         return err;
5452 }
5453
5454 /* Implementation details:
5455  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
5456  * Two bpf_map_lookups (even with the same key) will have different reg->id.
5457  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
5458  * value_or_null->value transition, since the verifier only cares about
5459  * the range of access to valid map value pointer and doesn't care about actual
5460  * address of the map element.
5461  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5462  * reg->id > 0 after value_or_null->value transition. By doing so
5463  * two bpf_map_lookups will be considered two different pointers that
5464  * point to different bpf_spin_locks.
5465  * The verifier allows taking only one bpf_spin_lock at a time to avoid
5466  * dead-locks.
5467  * Since only one bpf_spin_lock is allowed the checks are simpler than
5468  * reg_is_refcounted() logic. The verifier needs to remember only
5469  * one spin_lock instead of array of acquired_refs.
5470  * cur_state->active_spin_lock remembers which map value element got locked
5471  * and clears it after bpf_spin_unlock.
5472  */
5473 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5474                              bool is_lock)
5475 {
5476         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5477         struct bpf_verifier_state *cur = env->cur_state;
5478         bool is_const = tnum_is_const(reg->var_off);
5479         struct bpf_map *map = reg->map_ptr;
5480         u64 val = reg->var_off.value;
5481
5482         if (!is_const) {
5483                 verbose(env,
5484                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5485                         regno);
5486                 return -EINVAL;
5487         }
5488         if (!map->btf) {
5489                 verbose(env,
5490                         "map '%s' has to have BTF in order to use bpf_spin_lock\n",
5491                         map->name);
5492                 return -EINVAL;
5493         }
5494         if (!map_value_has_spin_lock(map)) {
5495                 if (map->spin_lock_off == -E2BIG)
5496                         verbose(env,
5497                                 "map '%s' has more than one 'struct bpf_spin_lock'\n",
5498                                 map->name);
5499                 else if (map->spin_lock_off == -ENOENT)
5500                         verbose(env,
5501                                 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
5502                                 map->name);
5503                 else
5504                         verbose(env,
5505                                 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
5506                                 map->name);
5507                 return -EINVAL;
5508         }
5509         if (map->spin_lock_off != val + reg->off) {
5510                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
5511                         val + reg->off);
5512                 return -EINVAL;
5513         }
5514         if (is_lock) {
5515                 if (cur->active_spin_lock) {
5516                         verbose(env,
5517                                 "Locking two bpf_spin_locks are not allowed\n");
5518                         return -EINVAL;
5519                 }
5520                 cur->active_spin_lock = reg->id;
5521         } else {
5522                 if (!cur->active_spin_lock) {
5523                         verbose(env, "bpf_spin_unlock without taking a lock\n");
5524                         return -EINVAL;
5525                 }
5526                 if (cur->active_spin_lock != reg->id) {
5527                         verbose(env, "bpf_spin_unlock of different lock\n");
5528                         return -EINVAL;
5529                 }
5530                 cur->active_spin_lock = 0;
5531         }
5532         return 0;
5533 }
5534
5535 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5536                               struct bpf_call_arg_meta *meta)
5537 {
5538         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5539         bool is_const = tnum_is_const(reg->var_off);
5540         struct bpf_map *map = reg->map_ptr;
5541         u64 val = reg->var_off.value;
5542
5543         if (!is_const) {
5544                 verbose(env,
5545                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5546                         regno);
5547                 return -EINVAL;
5548         }
5549         if (!map->btf) {
5550                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5551                         map->name);
5552                 return -EINVAL;
5553         }
5554         if (!map_value_has_timer(map)) {
5555                 if (map->timer_off == -E2BIG)
5556                         verbose(env,
5557                                 "map '%s' has more than one 'struct bpf_timer'\n",
5558                                 map->name);
5559                 else if (map->timer_off == -ENOENT)
5560                         verbose(env,
5561                                 "map '%s' doesn't have 'struct bpf_timer'\n",
5562                                 map->name);
5563                 else
5564                         verbose(env,
5565                                 "map '%s' is not a struct type or bpf_timer is mangled\n",
5566                                 map->name);
5567                 return -EINVAL;
5568         }
5569         if (map->timer_off != val + reg->off) {
5570                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5571                         val + reg->off, map->timer_off);
5572                 return -EINVAL;
5573         }
5574         if (meta->map_ptr) {
5575                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5576                 return -EFAULT;
5577         }
5578         meta->map_uid = reg->map_uid;
5579         meta->map_ptr = map;
5580         return 0;
5581 }
5582
5583 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5584                              struct bpf_call_arg_meta *meta)
5585 {
5586         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5587         struct bpf_map_value_off_desc *off_desc;
5588         struct bpf_map *map_ptr = reg->map_ptr;
5589         u32 kptr_off;
5590         int ret;
5591
5592         if (!tnum_is_const(reg->var_off)) {
5593                 verbose(env,
5594                         "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5595                         regno);
5596                 return -EINVAL;
5597         }
5598         if (!map_ptr->btf) {
5599                 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5600                         map_ptr->name);
5601                 return -EINVAL;
5602         }
5603         if (!map_value_has_kptrs(map_ptr)) {
5604                 ret = PTR_ERR_OR_ZERO(map_ptr->kptr_off_tab);
5605                 if (ret == -E2BIG)
5606                         verbose(env, "map '%s' has more than %d kptr\n", map_ptr->name,
5607                                 BPF_MAP_VALUE_OFF_MAX);
5608                 else if (ret == -EEXIST)
5609                         verbose(env, "map '%s' has repeating kptr BTF tags\n", map_ptr->name);
5610                 else
5611                         verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5612                 return -EINVAL;
5613         }
5614
5615         meta->map_ptr = map_ptr;
5616         kptr_off = reg->off + reg->var_off.value;
5617         off_desc = bpf_map_kptr_off_contains(map_ptr, kptr_off);
5618         if (!off_desc) {
5619                 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5620                 return -EACCES;
5621         }
5622         if (off_desc->type != BPF_KPTR_REF) {
5623                 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5624                 return -EACCES;
5625         }
5626         meta->kptr_off_desc = off_desc;
5627         return 0;
5628 }
5629
5630 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5631 {
5632         return type == ARG_CONST_SIZE ||
5633                type == ARG_CONST_SIZE_OR_ZERO;
5634 }
5635
5636 static bool arg_type_is_release(enum bpf_arg_type type)
5637 {
5638         return type & OBJ_RELEASE;
5639 }
5640
5641 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5642 {
5643         return base_type(type) == ARG_PTR_TO_DYNPTR;
5644 }
5645
5646 static int int_ptr_type_to_size(enum bpf_arg_type type)
5647 {
5648         if (type == ARG_PTR_TO_INT)
5649                 return sizeof(u32);
5650         else if (type == ARG_PTR_TO_LONG)
5651                 return sizeof(u64);
5652
5653         return -EINVAL;
5654 }
5655
5656 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5657                                  const struct bpf_call_arg_meta *meta,
5658                                  enum bpf_arg_type *arg_type)
5659 {
5660         if (!meta->map_ptr) {
5661                 /* kernel subsystem misconfigured verifier */
5662                 verbose(env, "invalid map_ptr to access map->type\n");
5663                 return -EACCES;
5664         }
5665
5666         switch (meta->map_ptr->map_type) {
5667         case BPF_MAP_TYPE_SOCKMAP:
5668         case BPF_MAP_TYPE_SOCKHASH:
5669                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5670                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5671                 } else {
5672                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
5673                         return -EINVAL;
5674                 }
5675                 break;
5676         case BPF_MAP_TYPE_BLOOM_FILTER:
5677                 if (meta->func_id == BPF_FUNC_map_peek_elem)
5678                         *arg_type = ARG_PTR_TO_MAP_VALUE;
5679                 break;
5680         default:
5681                 break;
5682         }
5683         return 0;
5684 }
5685
5686 struct bpf_reg_types {
5687         const enum bpf_reg_type types[10];
5688         u32 *btf_id;
5689 };
5690
5691 static const struct bpf_reg_types map_key_value_types = {
5692         .types = {
5693                 PTR_TO_STACK,
5694                 PTR_TO_PACKET,
5695                 PTR_TO_PACKET_META,
5696                 PTR_TO_MAP_KEY,
5697                 PTR_TO_MAP_VALUE,
5698         },
5699 };
5700
5701 static const struct bpf_reg_types sock_types = {
5702         .types = {
5703                 PTR_TO_SOCK_COMMON,
5704                 PTR_TO_SOCKET,
5705                 PTR_TO_TCP_SOCK,
5706                 PTR_TO_XDP_SOCK,
5707         },
5708 };
5709
5710 #ifdef CONFIG_NET
5711 static const struct bpf_reg_types btf_id_sock_common_types = {
5712         .types = {
5713                 PTR_TO_SOCK_COMMON,
5714                 PTR_TO_SOCKET,
5715                 PTR_TO_TCP_SOCK,
5716                 PTR_TO_XDP_SOCK,
5717                 PTR_TO_BTF_ID,
5718         },
5719         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5720 };
5721 #endif
5722
5723 static const struct bpf_reg_types mem_types = {
5724         .types = {
5725                 PTR_TO_STACK,
5726                 PTR_TO_PACKET,
5727                 PTR_TO_PACKET_META,
5728                 PTR_TO_MAP_KEY,
5729                 PTR_TO_MAP_VALUE,
5730                 PTR_TO_MEM,
5731                 PTR_TO_MEM | MEM_ALLOC,
5732                 PTR_TO_BUF,
5733         },
5734 };
5735
5736 static const struct bpf_reg_types int_ptr_types = {
5737         .types = {
5738                 PTR_TO_STACK,
5739                 PTR_TO_PACKET,
5740                 PTR_TO_PACKET_META,
5741                 PTR_TO_MAP_KEY,
5742                 PTR_TO_MAP_VALUE,
5743         },
5744 };
5745
5746 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5747 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5748 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5749 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
5750 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5751 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5752 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5753 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_BTF_ID | MEM_PERCPU } };
5754 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5755 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5756 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5757 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5758 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5759 static const struct bpf_reg_types dynptr_types = {
5760         .types = {
5761                 PTR_TO_STACK,
5762                 PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL,
5763         }
5764 };
5765
5766 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5767         [ARG_PTR_TO_MAP_KEY]            = &map_key_value_types,
5768         [ARG_PTR_TO_MAP_VALUE]          = &map_key_value_types,
5769         [ARG_CONST_SIZE]                = &scalar_types,
5770         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
5771         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
5772         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
5773         [ARG_PTR_TO_CTX]                = &context_types,
5774         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
5775 #ifdef CONFIG_NET
5776         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
5777 #endif
5778         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
5779         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
5780         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
5781         [ARG_PTR_TO_MEM]                = &mem_types,
5782         [ARG_PTR_TO_ALLOC_MEM]          = &alloc_mem_types,
5783         [ARG_PTR_TO_INT]                = &int_ptr_types,
5784         [ARG_PTR_TO_LONG]               = &int_ptr_types,
5785         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
5786         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
5787         [ARG_PTR_TO_STACK]              = &stack_ptr_types,
5788         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
5789         [ARG_PTR_TO_TIMER]              = &timer_types,
5790         [ARG_PTR_TO_KPTR]               = &kptr_types,
5791         [ARG_PTR_TO_DYNPTR]             = &dynptr_types,
5792 };
5793
5794 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5795                           enum bpf_arg_type arg_type,
5796                           const u32 *arg_btf_id,
5797                           struct bpf_call_arg_meta *meta)
5798 {
5799         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5800         enum bpf_reg_type expected, type = reg->type;
5801         const struct bpf_reg_types *compatible;
5802         int i, j;
5803
5804         compatible = compatible_reg_types[base_type(arg_type)];
5805         if (!compatible) {
5806                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5807                 return -EFAULT;
5808         }
5809
5810         /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5811          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5812          *
5813          * Same for MAYBE_NULL:
5814          *
5815          * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5816          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5817          *
5818          * Therefore we fold these flags depending on the arg_type before comparison.
5819          */
5820         if (arg_type & MEM_RDONLY)
5821                 type &= ~MEM_RDONLY;
5822         if (arg_type & PTR_MAYBE_NULL)
5823                 type &= ~PTR_MAYBE_NULL;
5824
5825         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5826                 expected = compatible->types[i];
5827                 if (expected == NOT_INIT)
5828                         break;
5829
5830                 if (type == expected)
5831                         goto found;
5832         }
5833
5834         verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5835         for (j = 0; j + 1 < i; j++)
5836                 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5837         verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5838         return -EACCES;
5839
5840 found:
5841         if (reg->type == PTR_TO_BTF_ID) {
5842                 /* For bpf_sk_release, it needs to match against first member
5843                  * 'struct sock_common', hence make an exception for it. This
5844                  * allows bpf_sk_release to work for multiple socket types.
5845                  */
5846                 bool strict_type_match = arg_type_is_release(arg_type) &&
5847                                          meta->func_id != BPF_FUNC_sk_release;
5848
5849                 if (!arg_btf_id) {
5850                         if (!compatible->btf_id) {
5851                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5852                                 return -EFAULT;
5853                         }
5854                         arg_btf_id = compatible->btf_id;
5855                 }
5856
5857                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
5858                         if (map_kptr_match_type(env, meta->kptr_off_desc, reg, regno))
5859                                 return -EACCES;
5860                 } else {
5861                         if (arg_btf_id == BPF_PTR_POISON) {
5862                                 verbose(env, "verifier internal error:");
5863                                 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
5864                                         regno);
5865                                 return -EACCES;
5866                         }
5867
5868                         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5869                                                   btf_vmlinux, *arg_btf_id,
5870                                                   strict_type_match)) {
5871                                 verbose(env, "R%d is of type %s but %s is expected\n",
5872                                         regno, kernel_type_name(reg->btf, reg->btf_id),
5873                                         kernel_type_name(btf_vmlinux, *arg_btf_id));
5874                                 return -EACCES;
5875                         }
5876                 }
5877         }
5878
5879         return 0;
5880 }
5881
5882 int check_func_arg_reg_off(struct bpf_verifier_env *env,
5883                            const struct bpf_reg_state *reg, int regno,
5884                            enum bpf_arg_type arg_type)
5885 {
5886         enum bpf_reg_type type = reg->type;
5887         bool fixed_off_ok = false;
5888
5889         switch ((u32)type) {
5890         /* Pointer types where reg offset is explicitly allowed: */
5891         case PTR_TO_STACK:
5892                 if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
5893                         verbose(env, "cannot pass in dynptr at an offset\n");
5894                         return -EINVAL;
5895                 }
5896                 fallthrough;
5897         case PTR_TO_PACKET:
5898         case PTR_TO_PACKET_META:
5899         case PTR_TO_MAP_KEY:
5900         case PTR_TO_MAP_VALUE:
5901         case PTR_TO_MEM:
5902         case PTR_TO_MEM | MEM_RDONLY:
5903         case PTR_TO_MEM | MEM_ALLOC:
5904         case PTR_TO_BUF:
5905         case PTR_TO_BUF | MEM_RDONLY:
5906         case SCALAR_VALUE:
5907                 /* Some of the argument types nevertheless require a
5908                  * zero register offset.
5909                  */
5910                 if (base_type(arg_type) != ARG_PTR_TO_ALLOC_MEM)
5911                         return 0;
5912                 break;
5913         /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
5914          * fixed offset.
5915          */
5916         case PTR_TO_BTF_ID:
5917                 /* When referenced PTR_TO_BTF_ID is passed to release function,
5918                  * it's fixed offset must be 0. In the other cases, fixed offset
5919                  * can be non-zero.
5920                  */
5921                 if (arg_type_is_release(arg_type) && reg->off) {
5922                         verbose(env, "R%d must have zero offset when passed to release func\n",
5923                                 regno);
5924                         return -EINVAL;
5925                 }
5926                 /* For arg is release pointer, fixed_off_ok must be false, but
5927                  * we already checked and rejected reg->off != 0 above, so set
5928                  * to true to allow fixed offset for all other cases.
5929                  */
5930                 fixed_off_ok = true;
5931                 break;
5932         default:
5933                 break;
5934         }
5935         return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
5936 }
5937
5938 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
5939 {
5940         struct bpf_func_state *state = func(env, reg);
5941         int spi = get_spi(reg->off);
5942
5943         return state->stack[spi].spilled_ptr.id;
5944 }
5945
5946 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5947                           struct bpf_call_arg_meta *meta,
5948                           const struct bpf_func_proto *fn)
5949 {
5950         u32 regno = BPF_REG_1 + arg;
5951         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5952         enum bpf_arg_type arg_type = fn->arg_type[arg];
5953         enum bpf_reg_type type = reg->type;
5954         u32 *arg_btf_id = NULL;
5955         int err = 0;
5956
5957         if (arg_type == ARG_DONTCARE)
5958                 return 0;
5959
5960         err = check_reg_arg(env, regno, SRC_OP);
5961         if (err)
5962                 return err;
5963
5964         if (arg_type == ARG_ANYTHING) {
5965                 if (is_pointer_value(env, regno)) {
5966                         verbose(env, "R%d leaks addr into helper function\n",
5967                                 regno);
5968                         return -EACCES;
5969                 }
5970                 return 0;
5971         }
5972
5973         if (type_is_pkt_pointer(type) &&
5974             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5975                 verbose(env, "helper access to the packet is not allowed\n");
5976                 return -EACCES;
5977         }
5978
5979         if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
5980                 err = resolve_map_arg_type(env, meta, &arg_type);
5981                 if (err)
5982                         return err;
5983         }
5984
5985         if (register_is_null(reg) && type_may_be_null(arg_type))
5986                 /* A NULL register has a SCALAR_VALUE type, so skip
5987                  * type checking.
5988                  */
5989                 goto skip_type_check;
5990
5991         /* arg_btf_id and arg_size are in a union. */
5992         if (base_type(arg_type) == ARG_PTR_TO_BTF_ID)
5993                 arg_btf_id = fn->arg_btf_id[arg];
5994
5995         err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
5996         if (err)
5997                 return err;
5998
5999         err = check_func_arg_reg_off(env, reg, regno, arg_type);
6000         if (err)
6001                 return err;
6002
6003 skip_type_check:
6004         if (arg_type_is_release(arg_type)) {
6005                 if (arg_type_is_dynptr(arg_type)) {
6006                         struct bpf_func_state *state = func(env, reg);
6007                         int spi = get_spi(reg->off);
6008
6009                         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
6010                             !state->stack[spi].spilled_ptr.id) {
6011                                 verbose(env, "arg %d is an unacquired reference\n", regno);
6012                                 return -EINVAL;
6013                         }
6014                 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
6015                         verbose(env, "R%d must be referenced when passed to release function\n",
6016                                 regno);
6017                         return -EINVAL;
6018                 }
6019                 if (meta->release_regno) {
6020                         verbose(env, "verifier internal error: more than one release argument\n");
6021                         return -EFAULT;
6022                 }
6023                 meta->release_regno = regno;
6024         }
6025
6026         if (reg->ref_obj_id) {
6027                 if (meta->ref_obj_id) {
6028                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6029                                 regno, reg->ref_obj_id,
6030                                 meta->ref_obj_id);
6031                         return -EFAULT;
6032                 }
6033                 meta->ref_obj_id = reg->ref_obj_id;
6034         }
6035
6036         switch (base_type(arg_type)) {
6037         case ARG_CONST_MAP_PTR:
6038                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6039                 if (meta->map_ptr) {
6040                         /* Use map_uid (which is unique id of inner map) to reject:
6041                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6042                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6043                          * if (inner_map1 && inner_map2) {
6044                          *     timer = bpf_map_lookup_elem(inner_map1);
6045                          *     if (timer)
6046                          *         // mismatch would have been allowed
6047                          *         bpf_timer_init(timer, inner_map2);
6048                          * }
6049                          *
6050                          * Comparing map_ptr is enough to distinguish normal and outer maps.
6051                          */
6052                         if (meta->map_ptr != reg->map_ptr ||
6053                             meta->map_uid != reg->map_uid) {
6054                                 verbose(env,
6055                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6056                                         meta->map_uid, reg->map_uid);
6057                                 return -EINVAL;
6058                         }
6059                 }
6060                 meta->map_ptr = reg->map_ptr;
6061                 meta->map_uid = reg->map_uid;
6062                 break;
6063         case ARG_PTR_TO_MAP_KEY:
6064                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
6065                  * check that [key, key + map->key_size) are within
6066                  * stack limits and initialized
6067                  */
6068                 if (!meta->map_ptr) {
6069                         /* in function declaration map_ptr must come before
6070                          * map_key, so that it's verified and known before
6071                          * we have to check map_key here. Otherwise it means
6072                          * that kernel subsystem misconfigured verifier
6073                          */
6074                         verbose(env, "invalid map_ptr to access map->key\n");
6075                         return -EACCES;
6076                 }
6077                 err = check_helper_mem_access(env, regno,
6078                                               meta->map_ptr->key_size, false,
6079                                               NULL);
6080                 break;
6081         case ARG_PTR_TO_MAP_VALUE:
6082                 if (type_may_be_null(arg_type) && register_is_null(reg))
6083                         return 0;
6084
6085                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
6086                  * check [value, value + map->value_size) validity
6087                  */
6088                 if (!meta->map_ptr) {
6089                         /* kernel subsystem misconfigured verifier */
6090                         verbose(env, "invalid map_ptr to access map->value\n");
6091                         return -EACCES;
6092                 }
6093                 meta->raw_mode = arg_type & MEM_UNINIT;
6094                 err = check_helper_mem_access(env, regno,
6095                                               meta->map_ptr->value_size, false,
6096                                               meta);
6097                 break;
6098         case ARG_PTR_TO_PERCPU_BTF_ID:
6099                 if (!reg->btf_id) {
6100                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6101                         return -EACCES;
6102                 }
6103                 meta->ret_btf = reg->btf;
6104                 meta->ret_btf_id = reg->btf_id;
6105                 break;
6106         case ARG_PTR_TO_SPIN_LOCK:
6107                 if (meta->func_id == BPF_FUNC_spin_lock) {
6108                         if (process_spin_lock(env, regno, true))
6109                                 return -EACCES;
6110                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
6111                         if (process_spin_lock(env, regno, false))
6112                                 return -EACCES;
6113                 } else {
6114                         verbose(env, "verifier internal error\n");
6115                         return -EFAULT;
6116                 }
6117                 break;
6118         case ARG_PTR_TO_TIMER:
6119                 if (process_timer_func(env, regno, meta))
6120                         return -EACCES;
6121                 break;
6122         case ARG_PTR_TO_FUNC:
6123                 meta->subprogno = reg->subprogno;
6124                 break;
6125         case ARG_PTR_TO_MEM:
6126                 /* The access to this pointer is only checked when we hit the
6127                  * next is_mem_size argument below.
6128                  */
6129                 meta->raw_mode = arg_type & MEM_UNINIT;
6130                 if (arg_type & MEM_FIXED_SIZE) {
6131                         err = check_helper_mem_access(env, regno,
6132                                                       fn->arg_size[arg], false,
6133                                                       meta);
6134                 }
6135                 break;
6136         case ARG_CONST_SIZE:
6137                 err = check_mem_size_reg(env, reg, regno, false, meta);
6138                 break;
6139         case ARG_CONST_SIZE_OR_ZERO:
6140                 err = check_mem_size_reg(env, reg, regno, true, meta);
6141                 break;
6142         case ARG_PTR_TO_DYNPTR:
6143                 /* We only need to check for initialized / uninitialized helper
6144                  * dynptr args if the dynptr is not PTR_TO_DYNPTR, as the
6145                  * assumption is that if it is, that a helper function
6146                  * initialized the dynptr on behalf of the BPF program.
6147                  */
6148                 if (base_type(reg->type) == PTR_TO_DYNPTR)
6149                         break;
6150                 if (arg_type & MEM_UNINIT) {
6151                         if (!is_dynptr_reg_valid_uninit(env, reg)) {
6152                                 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6153                                 return -EINVAL;
6154                         }
6155
6156                         /* We only support one dynptr being uninitialized at the moment,
6157                          * which is sufficient for the helper functions we have right now.
6158                          */
6159                         if (meta->uninit_dynptr_regno) {
6160                                 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6161                                 return -EFAULT;
6162                         }
6163
6164                         meta->uninit_dynptr_regno = regno;
6165                 } else if (!is_dynptr_reg_valid_init(env, reg)) {
6166                         verbose(env,
6167                                 "Expected an initialized dynptr as arg #%d\n",
6168                                 arg + 1);
6169                         return -EINVAL;
6170                 } else if (!is_dynptr_type_expected(env, reg, arg_type)) {
6171                         const char *err_extra = "";
6172
6173                         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6174                         case DYNPTR_TYPE_LOCAL:
6175                                 err_extra = "local";
6176                                 break;
6177                         case DYNPTR_TYPE_RINGBUF:
6178                                 err_extra = "ringbuf";
6179                                 break;
6180                         default:
6181                                 err_extra = "<unknown>";
6182                                 break;
6183                         }
6184                         verbose(env,
6185                                 "Expected a dynptr of type %s as arg #%d\n",
6186                                 err_extra, arg + 1);
6187                         return -EINVAL;
6188                 }
6189                 break;
6190         case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6191                 if (!tnum_is_const(reg->var_off)) {
6192                         verbose(env, "R%d is not a known constant'\n",
6193                                 regno);
6194                         return -EACCES;
6195                 }
6196                 meta->mem_size = reg->var_off.value;
6197                 err = mark_chain_precision(env, regno);
6198                 if (err)
6199                         return err;
6200                 break;
6201         case ARG_PTR_TO_INT:
6202         case ARG_PTR_TO_LONG:
6203         {
6204                 int size = int_ptr_type_to_size(arg_type);
6205
6206                 err = check_helper_mem_access(env, regno, size, false, meta);
6207                 if (err)
6208                         return err;
6209                 err = check_ptr_alignment(env, reg, 0, size, true);
6210                 break;
6211         }
6212         case ARG_PTR_TO_CONST_STR:
6213         {
6214                 struct bpf_map *map = reg->map_ptr;
6215                 int map_off;
6216                 u64 map_addr;
6217                 char *str_ptr;
6218
6219                 if (!bpf_map_is_rdonly(map)) {
6220                         verbose(env, "R%d does not point to a readonly map'\n", regno);
6221                         return -EACCES;
6222                 }
6223
6224                 if (!tnum_is_const(reg->var_off)) {
6225                         verbose(env, "R%d is not a constant address'\n", regno);
6226                         return -EACCES;
6227                 }
6228
6229                 if (!map->ops->map_direct_value_addr) {
6230                         verbose(env, "no direct value access support for this map type\n");
6231                         return -EACCES;
6232                 }
6233
6234                 err = check_map_access(env, regno, reg->off,
6235                                        map->value_size - reg->off, false,
6236                                        ACCESS_HELPER);
6237                 if (err)
6238                         return err;
6239
6240                 map_off = reg->off + reg->var_off.value;
6241                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6242                 if (err) {
6243                         verbose(env, "direct value access on string failed\n");
6244                         return err;
6245                 }
6246
6247                 str_ptr = (char *)(long)(map_addr);
6248                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6249                         verbose(env, "string is not zero-terminated\n");
6250                         return -EINVAL;
6251                 }
6252                 break;
6253         }
6254         case ARG_PTR_TO_KPTR:
6255                 if (process_kptr_func(env, regno, meta))
6256                         return -EACCES;
6257                 break;
6258         }
6259
6260         return err;
6261 }
6262
6263 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6264 {
6265         enum bpf_attach_type eatype = env->prog->expected_attach_type;
6266         enum bpf_prog_type type = resolve_prog_type(env->prog);
6267
6268         if (func_id != BPF_FUNC_map_update_elem)
6269                 return false;
6270
6271         /* It's not possible to get access to a locked struct sock in these
6272          * contexts, so updating is safe.
6273          */
6274         switch (type) {
6275         case BPF_PROG_TYPE_TRACING:
6276                 if (eatype == BPF_TRACE_ITER)
6277                         return true;
6278                 break;
6279         case BPF_PROG_TYPE_SOCKET_FILTER:
6280         case BPF_PROG_TYPE_SCHED_CLS:
6281         case BPF_PROG_TYPE_SCHED_ACT:
6282         case BPF_PROG_TYPE_XDP:
6283         case BPF_PROG_TYPE_SK_REUSEPORT:
6284         case BPF_PROG_TYPE_FLOW_DISSECTOR:
6285         case BPF_PROG_TYPE_SK_LOOKUP:
6286                 return true;
6287         default:
6288                 break;
6289         }
6290
6291         verbose(env, "cannot update sockmap in this context\n");
6292         return false;
6293 }
6294
6295 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6296 {
6297         return env->prog->jit_requested &&
6298                bpf_jit_supports_subprog_tailcalls();
6299 }
6300
6301 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6302                                         struct bpf_map *map, int func_id)
6303 {
6304         if (!map)
6305                 return 0;
6306
6307         /* We need a two way check, first is from map perspective ... */
6308         switch (map->map_type) {
6309         case BPF_MAP_TYPE_PROG_ARRAY:
6310                 if (func_id != BPF_FUNC_tail_call)
6311                         goto error;
6312                 break;
6313         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6314                 if (func_id != BPF_FUNC_perf_event_read &&
6315                     func_id != BPF_FUNC_perf_event_output &&
6316                     func_id != BPF_FUNC_skb_output &&
6317                     func_id != BPF_FUNC_perf_event_read_value &&
6318                     func_id != BPF_FUNC_xdp_output)
6319                         goto error;
6320                 break;
6321         case BPF_MAP_TYPE_RINGBUF:
6322                 if (func_id != BPF_FUNC_ringbuf_output &&
6323                     func_id != BPF_FUNC_ringbuf_reserve &&
6324                     func_id != BPF_FUNC_ringbuf_query &&
6325                     func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6326                     func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6327                     func_id != BPF_FUNC_ringbuf_discard_dynptr)
6328                         goto error;
6329                 break;
6330         case BPF_MAP_TYPE_USER_RINGBUF:
6331                 if (func_id != BPF_FUNC_user_ringbuf_drain)
6332                         goto error;
6333                 break;
6334         case BPF_MAP_TYPE_STACK_TRACE:
6335                 if (func_id != BPF_FUNC_get_stackid)
6336                         goto error;
6337                 break;
6338         case BPF_MAP_TYPE_CGROUP_ARRAY:
6339                 if (func_id != BPF_FUNC_skb_under_cgroup &&
6340                     func_id != BPF_FUNC_current_task_under_cgroup)
6341                         goto error;
6342                 break;
6343         case BPF_MAP_TYPE_CGROUP_STORAGE:
6344         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6345                 if (func_id != BPF_FUNC_get_local_storage)
6346                         goto error;
6347                 break;
6348         case BPF_MAP_TYPE_DEVMAP:
6349         case BPF_MAP_TYPE_DEVMAP_HASH:
6350                 if (func_id != BPF_FUNC_redirect_map &&
6351                     func_id != BPF_FUNC_map_lookup_elem)
6352                         goto error;
6353                 break;
6354         /* Restrict bpf side of cpumap and xskmap, open when use-cases
6355          * appear.
6356          */
6357         case BPF_MAP_TYPE_CPUMAP:
6358                 if (func_id != BPF_FUNC_redirect_map)
6359                         goto error;
6360                 break;
6361         case BPF_MAP_TYPE_XSKMAP:
6362                 if (func_id != BPF_FUNC_redirect_map &&
6363                     func_id != BPF_FUNC_map_lookup_elem)
6364                         goto error;
6365                 break;
6366         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6367         case BPF_MAP_TYPE_HASH_OF_MAPS:
6368                 if (func_id != BPF_FUNC_map_lookup_elem)
6369                         goto error;
6370                 break;
6371         case BPF_MAP_TYPE_SOCKMAP:
6372                 if (func_id != BPF_FUNC_sk_redirect_map &&
6373                     func_id != BPF_FUNC_sock_map_update &&
6374                     func_id != BPF_FUNC_map_delete_elem &&
6375                     func_id != BPF_FUNC_msg_redirect_map &&
6376                     func_id != BPF_FUNC_sk_select_reuseport &&
6377                     func_id != BPF_FUNC_map_lookup_elem &&
6378                     !may_update_sockmap(env, func_id))
6379                         goto error;
6380                 break;
6381         case BPF_MAP_TYPE_SOCKHASH:
6382                 if (func_id != BPF_FUNC_sk_redirect_hash &&
6383                     func_id != BPF_FUNC_sock_hash_update &&
6384                     func_id != BPF_FUNC_map_delete_elem &&
6385                     func_id != BPF_FUNC_msg_redirect_hash &&
6386                     func_id != BPF_FUNC_sk_select_reuseport &&
6387                     func_id != BPF_FUNC_map_lookup_elem &&
6388                     !may_update_sockmap(env, func_id))
6389                         goto error;
6390                 break;
6391         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6392                 if (func_id != BPF_FUNC_sk_select_reuseport)
6393                         goto error;
6394                 break;
6395         case BPF_MAP_TYPE_QUEUE:
6396         case BPF_MAP_TYPE_STACK:
6397                 if (func_id != BPF_FUNC_map_peek_elem &&
6398                     func_id != BPF_FUNC_map_pop_elem &&
6399                     func_id != BPF_FUNC_map_push_elem)
6400                         goto error;
6401                 break;
6402         case BPF_MAP_TYPE_SK_STORAGE:
6403                 if (func_id != BPF_FUNC_sk_storage_get &&
6404                     func_id != BPF_FUNC_sk_storage_delete)
6405                         goto error;
6406                 break;
6407         case BPF_MAP_TYPE_INODE_STORAGE:
6408                 if (func_id != BPF_FUNC_inode_storage_get &&
6409                     func_id != BPF_FUNC_inode_storage_delete)
6410                         goto error;
6411                 break;
6412         case BPF_MAP_TYPE_TASK_STORAGE:
6413                 if (func_id != BPF_FUNC_task_storage_get &&
6414                     func_id != BPF_FUNC_task_storage_delete)
6415                         goto error;
6416                 break;
6417         case BPF_MAP_TYPE_BLOOM_FILTER:
6418                 if (func_id != BPF_FUNC_map_peek_elem &&
6419                     func_id != BPF_FUNC_map_push_elem)
6420                         goto error;
6421                 break;
6422         default:
6423                 break;
6424         }
6425
6426         /* ... and second from the function itself. */
6427         switch (func_id) {
6428         case BPF_FUNC_tail_call:
6429                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6430                         goto error;
6431                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6432                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6433                         return -EINVAL;
6434                 }
6435                 break;
6436         case BPF_FUNC_perf_event_read:
6437         case BPF_FUNC_perf_event_output:
6438         case BPF_FUNC_perf_event_read_value:
6439         case BPF_FUNC_skb_output:
6440         case BPF_FUNC_xdp_output:
6441                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6442                         goto error;
6443                 break;
6444         case BPF_FUNC_ringbuf_output:
6445         case BPF_FUNC_ringbuf_reserve:
6446         case BPF_FUNC_ringbuf_query:
6447         case BPF_FUNC_ringbuf_reserve_dynptr:
6448         case BPF_FUNC_ringbuf_submit_dynptr:
6449         case BPF_FUNC_ringbuf_discard_dynptr:
6450                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6451                         goto error;
6452                 break;
6453         case BPF_FUNC_user_ringbuf_drain:
6454                 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6455                         goto error;
6456                 break;
6457         case BPF_FUNC_get_stackid:
6458                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6459                         goto error;
6460                 break;
6461         case BPF_FUNC_current_task_under_cgroup:
6462         case BPF_FUNC_skb_under_cgroup:
6463                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6464                         goto error;
6465                 break;
6466         case BPF_FUNC_redirect_map:
6467                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6468                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6469                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
6470                     map->map_type != BPF_MAP_TYPE_XSKMAP)
6471                         goto error;
6472                 break;
6473         case BPF_FUNC_sk_redirect_map:
6474         case BPF_FUNC_msg_redirect_map:
6475         case BPF_FUNC_sock_map_update:
6476                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6477                         goto error;
6478                 break;
6479         case BPF_FUNC_sk_redirect_hash:
6480         case BPF_FUNC_msg_redirect_hash:
6481         case BPF_FUNC_sock_hash_update:
6482                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6483                         goto error;
6484                 break;
6485         case BPF_FUNC_get_local_storage:
6486                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6487                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6488                         goto error;
6489                 break;
6490         case BPF_FUNC_sk_select_reuseport:
6491                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6492                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6493                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
6494                         goto error;
6495                 break;
6496         case BPF_FUNC_map_pop_elem:
6497                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6498                     map->map_type != BPF_MAP_TYPE_STACK)
6499                         goto error;
6500                 break;
6501         case BPF_FUNC_map_peek_elem:
6502         case BPF_FUNC_map_push_elem:
6503                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6504                     map->map_type != BPF_MAP_TYPE_STACK &&
6505                     map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6506                         goto error;
6507                 break;
6508         case BPF_FUNC_map_lookup_percpu_elem:
6509                 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6510                     map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6511                     map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6512                         goto error;
6513                 break;
6514         case BPF_FUNC_sk_storage_get:
6515         case BPF_FUNC_sk_storage_delete:
6516                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6517                         goto error;
6518                 break;
6519         case BPF_FUNC_inode_storage_get:
6520         case BPF_FUNC_inode_storage_delete:
6521                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6522                         goto error;
6523                 break;
6524         case BPF_FUNC_task_storage_get:
6525         case BPF_FUNC_task_storage_delete:
6526                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6527                         goto error;
6528                 break;
6529         default:
6530                 break;
6531         }
6532
6533         return 0;
6534 error:
6535         verbose(env, "cannot pass map_type %d into func %s#%d\n",
6536                 map->map_type, func_id_name(func_id), func_id);
6537         return -EINVAL;
6538 }
6539
6540 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6541 {
6542         int count = 0;
6543
6544         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6545                 count++;
6546         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6547                 count++;
6548         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6549                 count++;
6550         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6551                 count++;
6552         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6553                 count++;
6554
6555         /* We only support one arg being in raw mode at the moment,
6556          * which is sufficient for the helper functions we have
6557          * right now.
6558          */
6559         return count <= 1;
6560 }
6561
6562 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6563 {
6564         bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6565         bool has_size = fn->arg_size[arg] != 0;
6566         bool is_next_size = false;
6567
6568         if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6569                 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6570
6571         if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6572                 return is_next_size;
6573
6574         return has_size == is_next_size || is_next_size == is_fixed;
6575 }
6576
6577 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6578 {
6579         /* bpf_xxx(..., buf, len) call will access 'len'
6580          * bytes from memory 'buf'. Both arg types need
6581          * to be paired, so make sure there's no buggy
6582          * helper function specification.
6583          */
6584         if (arg_type_is_mem_size(fn->arg1_type) ||
6585             check_args_pair_invalid(fn, 0) ||
6586             check_args_pair_invalid(fn, 1) ||
6587             check_args_pair_invalid(fn, 2) ||
6588             check_args_pair_invalid(fn, 3) ||
6589             check_args_pair_invalid(fn, 4))
6590                 return false;
6591
6592         return true;
6593 }
6594
6595 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6596 {
6597         int i;
6598
6599         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6600                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
6601                         return false;
6602
6603                 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6604                     /* arg_btf_id and arg_size are in a union. */
6605                     (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6606                      !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6607                         return false;
6608         }
6609
6610         return true;
6611 }
6612
6613 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6614 {
6615         return check_raw_mode_ok(fn) &&
6616                check_arg_pair_ok(fn) &&
6617                check_btf_id_ok(fn) ? 0 : -EINVAL;
6618 }
6619
6620 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6621  * are now invalid, so turn them into unknown SCALAR_VALUE.
6622  */
6623 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6624 {
6625         struct bpf_func_state *state;
6626         struct bpf_reg_state *reg;
6627
6628         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6629                 if (reg_is_pkt_pointer_any(reg))
6630                         __mark_reg_unknown(env, reg);
6631         }));
6632 }
6633
6634 enum {
6635         AT_PKT_END = -1,
6636         BEYOND_PKT_END = -2,
6637 };
6638
6639 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6640 {
6641         struct bpf_func_state *state = vstate->frame[vstate->curframe];
6642         struct bpf_reg_state *reg = &state->regs[regn];
6643
6644         if (reg->type != PTR_TO_PACKET)
6645                 /* PTR_TO_PACKET_META is not supported yet */
6646                 return;
6647
6648         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6649          * How far beyond pkt_end it goes is unknown.
6650          * if (!range_open) it's the case of pkt >= pkt_end
6651          * if (range_open) it's the case of pkt > pkt_end
6652          * hence this pointer is at least 1 byte bigger than pkt_end
6653          */
6654         if (range_open)
6655                 reg->range = BEYOND_PKT_END;
6656         else
6657                 reg->range = AT_PKT_END;
6658 }
6659
6660 /* The pointer with the specified id has released its reference to kernel
6661  * resources. Identify all copies of the same pointer and clear the reference.
6662  */
6663 static int release_reference(struct bpf_verifier_env *env,
6664                              int ref_obj_id)
6665 {
6666         struct bpf_func_state *state;
6667         struct bpf_reg_state *reg;
6668         int err;
6669
6670         err = release_reference_state(cur_func(env), ref_obj_id);
6671         if (err)
6672                 return err;
6673
6674         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6675                 if (reg->ref_obj_id == ref_obj_id) {
6676                         if (!env->allow_ptr_leaks)
6677                                 __mark_reg_not_init(env, reg);
6678                         else
6679                                 __mark_reg_unknown(env, reg);
6680                 }
6681         }));
6682
6683         return 0;
6684 }
6685
6686 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6687                                     struct bpf_reg_state *regs)
6688 {
6689         int i;
6690
6691         /* after the call registers r0 - r5 were scratched */
6692         for (i = 0; i < CALLER_SAVED_REGS; i++) {
6693                 mark_reg_not_init(env, regs, caller_saved[i]);
6694                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6695         }
6696 }
6697
6698 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6699                                    struct bpf_func_state *caller,
6700                                    struct bpf_func_state *callee,
6701                                    int insn_idx);
6702
6703 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6704                              int *insn_idx, int subprog,
6705                              set_callee_state_fn set_callee_state_cb)
6706 {
6707         struct bpf_verifier_state *state = env->cur_state;
6708         struct bpf_func_info_aux *func_info_aux;
6709         struct bpf_func_state *caller, *callee;
6710         int err;
6711         bool is_global = false;
6712
6713         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6714                 verbose(env, "the call stack of %d frames is too deep\n",
6715                         state->curframe + 2);
6716                 return -E2BIG;
6717         }
6718
6719         caller = state->frame[state->curframe];
6720         if (state->frame[state->curframe + 1]) {
6721                 verbose(env, "verifier bug. Frame %d already allocated\n",
6722                         state->curframe + 1);
6723                 return -EFAULT;
6724         }
6725
6726         func_info_aux = env->prog->aux->func_info_aux;
6727         if (func_info_aux)
6728                 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6729         err = btf_check_subprog_call(env, subprog, caller->regs);
6730         if (err == -EFAULT)
6731                 return err;
6732         if (is_global) {
6733                 if (err) {
6734                         verbose(env, "Caller passes invalid args into func#%d\n",
6735                                 subprog);
6736                         return err;
6737                 } else {
6738                         if (env->log.level & BPF_LOG_LEVEL)
6739                                 verbose(env,
6740                                         "Func#%d is global and valid. Skipping.\n",
6741                                         subprog);
6742                         clear_caller_saved_regs(env, caller->regs);
6743
6744                         /* All global functions return a 64-bit SCALAR_VALUE */
6745                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
6746                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6747
6748                         /* continue with next insn after call */
6749                         return 0;
6750                 }
6751         }
6752
6753         if (insn->code == (BPF_JMP | BPF_CALL) &&
6754             insn->src_reg == 0 &&
6755             insn->imm == BPF_FUNC_timer_set_callback) {
6756                 struct bpf_verifier_state *async_cb;
6757
6758                 /* there is no real recursion here. timer callbacks are async */
6759                 env->subprog_info[subprog].is_async_cb = true;
6760                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6761                                          *insn_idx, subprog);
6762                 if (!async_cb)
6763                         return -EFAULT;
6764                 callee = async_cb->frame[0];
6765                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
6766
6767                 /* Convert bpf_timer_set_callback() args into timer callback args */
6768                 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6769                 if (err)
6770                         return err;
6771
6772                 clear_caller_saved_regs(env, caller->regs);
6773                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6774                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6775                 /* continue with next insn after call */
6776                 return 0;
6777         }
6778
6779         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6780         if (!callee)
6781                 return -ENOMEM;
6782         state->frame[state->curframe + 1] = callee;
6783
6784         /* callee cannot access r0, r6 - r9 for reading and has to write
6785          * into its own stack before reading from it.
6786          * callee can read/write into caller's stack
6787          */
6788         init_func_state(env, callee,
6789                         /* remember the callsite, it will be used by bpf_exit */
6790                         *insn_idx /* callsite */,
6791                         state->curframe + 1 /* frameno within this callchain */,
6792                         subprog /* subprog number within this prog */);
6793
6794         /* Transfer references to the callee */
6795         err = copy_reference_state(callee, caller);
6796         if (err)
6797                 goto err_out;
6798
6799         err = set_callee_state_cb(env, caller, callee, *insn_idx);
6800         if (err)
6801                 goto err_out;
6802
6803         clear_caller_saved_regs(env, caller->regs);
6804
6805         /* only increment it after check_reg_arg() finished */
6806         state->curframe++;
6807
6808         /* and go analyze first insn of the callee */
6809         *insn_idx = env->subprog_info[subprog].start - 1;
6810
6811         if (env->log.level & BPF_LOG_LEVEL) {
6812                 verbose(env, "caller:\n");
6813                 print_verifier_state(env, caller, true);
6814                 verbose(env, "callee:\n");
6815                 print_verifier_state(env, callee, true);
6816         }
6817         return 0;
6818
6819 err_out:
6820         free_func_state(callee);
6821         state->frame[state->curframe + 1] = NULL;
6822         return err;
6823 }
6824
6825 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6826                                    struct bpf_func_state *caller,
6827                                    struct bpf_func_state *callee)
6828 {
6829         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6830          *      void *callback_ctx, u64 flags);
6831          * callback_fn(struct bpf_map *map, void *key, void *value,
6832          *      void *callback_ctx);
6833          */
6834         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6835
6836         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6837         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6838         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6839
6840         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6841         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6842         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6843
6844         /* pointer to stack or null */
6845         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6846
6847         /* unused */
6848         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6849         return 0;
6850 }
6851
6852 static int set_callee_state(struct bpf_verifier_env *env,
6853                             struct bpf_func_state *caller,
6854                             struct bpf_func_state *callee, int insn_idx)
6855 {
6856         int i;
6857
6858         /* copy r1 - r5 args that callee can access.  The copy includes parent
6859          * pointers, which connects us up to the liveness chain
6860          */
6861         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6862                 callee->regs[i] = caller->regs[i];
6863         return 0;
6864 }
6865
6866 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6867                            int *insn_idx)
6868 {
6869         int subprog, target_insn;
6870
6871         target_insn = *insn_idx + insn->imm + 1;
6872         subprog = find_subprog(env, target_insn);
6873         if (subprog < 0) {
6874                 verbose(env, "verifier bug. No program starts at insn %d\n",
6875                         target_insn);
6876                 return -EFAULT;
6877         }
6878
6879         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6880 }
6881
6882 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6883                                        struct bpf_func_state *caller,
6884                                        struct bpf_func_state *callee,
6885                                        int insn_idx)
6886 {
6887         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6888         struct bpf_map *map;
6889         int err;
6890
6891         if (bpf_map_ptr_poisoned(insn_aux)) {
6892                 verbose(env, "tail_call abusing map_ptr\n");
6893                 return -EINVAL;
6894         }
6895
6896         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6897         if (!map->ops->map_set_for_each_callback_args ||
6898             !map->ops->map_for_each_callback) {
6899                 verbose(env, "callback function not allowed for map\n");
6900                 return -ENOTSUPP;
6901         }
6902
6903         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6904         if (err)
6905                 return err;
6906
6907         callee->in_callback_fn = true;
6908         callee->callback_ret_range = tnum_range(0, 1);
6909         return 0;
6910 }
6911
6912 static int set_loop_callback_state(struct bpf_verifier_env *env,
6913                                    struct bpf_func_state *caller,
6914                                    struct bpf_func_state *callee,
6915                                    int insn_idx)
6916 {
6917         /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6918          *          u64 flags);
6919          * callback_fn(u32 index, void *callback_ctx);
6920          */
6921         callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6922         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6923
6924         /* unused */
6925         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6926         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6927         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6928
6929         callee->in_callback_fn = true;
6930         callee->callback_ret_range = tnum_range(0, 1);
6931         return 0;
6932 }
6933
6934 static int set_timer_callback_state(struct bpf_verifier_env *env,
6935                                     struct bpf_func_state *caller,
6936                                     struct bpf_func_state *callee,
6937                                     int insn_idx)
6938 {
6939         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6940
6941         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6942          * callback_fn(struct bpf_map *map, void *key, void *value);
6943          */
6944         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6945         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6946         callee->regs[BPF_REG_1].map_ptr = map_ptr;
6947
6948         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6949         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6950         callee->regs[BPF_REG_2].map_ptr = map_ptr;
6951
6952         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6953         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6954         callee->regs[BPF_REG_3].map_ptr = map_ptr;
6955
6956         /* unused */
6957         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6958         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6959         callee->in_async_callback_fn = true;
6960         callee->callback_ret_range = tnum_range(0, 1);
6961         return 0;
6962 }
6963
6964 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6965                                        struct bpf_func_state *caller,
6966                                        struct bpf_func_state *callee,
6967                                        int insn_idx)
6968 {
6969         /* bpf_find_vma(struct task_struct *task, u64 addr,
6970          *               void *callback_fn, void *callback_ctx, u64 flags)
6971          * (callback_fn)(struct task_struct *task,
6972          *               struct vm_area_struct *vma, void *callback_ctx);
6973          */
6974         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6975
6976         callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6977         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6978         callee->regs[BPF_REG_2].btf =  btf_vmlinux;
6979         callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
6980
6981         /* pointer to stack or null */
6982         callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6983
6984         /* unused */
6985         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6986         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6987         callee->in_callback_fn = true;
6988         callee->callback_ret_range = tnum_range(0, 1);
6989         return 0;
6990 }
6991
6992 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
6993                                            struct bpf_func_state *caller,
6994                                            struct bpf_func_state *callee,
6995                                            int insn_idx)
6996 {
6997         /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
6998          *                        callback_ctx, u64 flags);
6999          * callback_fn(struct bpf_dynptr_t* dynptr, void *callback_ctx);
7000          */
7001         __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
7002         callee->regs[BPF_REG_1].type = PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL;
7003         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7004         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7005
7006         /* unused */
7007         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7008         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7009         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7010
7011         callee->in_callback_fn = true;
7012         callee->callback_ret_range = tnum_range(0, 1);
7013         return 0;
7014 }
7015
7016 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7017 {
7018         struct bpf_verifier_state *state = env->cur_state;
7019         struct bpf_func_state *caller, *callee;
7020         struct bpf_reg_state *r0;
7021         int err;
7022
7023         callee = state->frame[state->curframe];
7024         r0 = &callee->regs[BPF_REG_0];
7025         if (r0->type == PTR_TO_STACK) {
7026                 /* technically it's ok to return caller's stack pointer
7027                  * (or caller's caller's pointer) back to the caller,
7028                  * since these pointers are valid. Only current stack
7029                  * pointer will be invalid as soon as function exits,
7030                  * but let's be conservative
7031                  */
7032                 verbose(env, "cannot return stack pointer to the caller\n");
7033                 return -EINVAL;
7034         }
7035
7036         caller = state->frame[state->curframe - 1];
7037         if (callee->in_callback_fn) {
7038                 /* enforce R0 return value range [0, 1]. */
7039                 struct tnum range = callee->callback_ret_range;
7040
7041                 if (r0->type != SCALAR_VALUE) {
7042                         verbose(env, "R0 not a scalar value\n");
7043                         return -EACCES;
7044                 }
7045                 if (!tnum_in(range, r0->var_off)) {
7046                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7047                         return -EINVAL;
7048                 }
7049         } else {
7050                 /* return to the caller whatever r0 had in the callee */
7051                 caller->regs[BPF_REG_0] = *r0;
7052         }
7053
7054         /* callback_fn frame should have released its own additions to parent's
7055          * reference state at this point, or check_reference_leak would
7056          * complain, hence it must be the same as the caller. There is no need
7057          * to copy it back.
7058          */
7059         if (!callee->in_callback_fn) {
7060                 /* Transfer references to the caller */
7061                 err = copy_reference_state(caller, callee);
7062                 if (err)
7063                         return err;
7064         }
7065
7066         *insn_idx = callee->callsite + 1;
7067         if (env->log.level & BPF_LOG_LEVEL) {
7068                 verbose(env, "returning from callee:\n");
7069                 print_verifier_state(env, callee, true);
7070                 verbose(env, "to caller at %d:\n", *insn_idx);
7071                 print_verifier_state(env, caller, true);
7072         }
7073         /* clear everything in the callee */
7074         free_func_state(callee);
7075         state->frame[state->curframe--] = NULL;
7076         return 0;
7077 }
7078
7079 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7080                                    int func_id,
7081                                    struct bpf_call_arg_meta *meta)
7082 {
7083         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
7084
7085         if (ret_type != RET_INTEGER ||
7086             (func_id != BPF_FUNC_get_stack &&
7087              func_id != BPF_FUNC_get_task_stack &&
7088              func_id != BPF_FUNC_probe_read_str &&
7089              func_id != BPF_FUNC_probe_read_kernel_str &&
7090              func_id != BPF_FUNC_probe_read_user_str))
7091                 return;
7092
7093         ret_reg->smax_value = meta->msize_max_value;
7094         ret_reg->s32_max_value = meta->msize_max_value;
7095         ret_reg->smin_value = -MAX_ERRNO;
7096         ret_reg->s32_min_value = -MAX_ERRNO;
7097         reg_bounds_sync(ret_reg);
7098 }
7099
7100 static int
7101 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7102                 int func_id, int insn_idx)
7103 {
7104         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7105         struct bpf_map *map = meta->map_ptr;
7106
7107         if (func_id != BPF_FUNC_tail_call &&
7108             func_id != BPF_FUNC_map_lookup_elem &&
7109             func_id != BPF_FUNC_map_update_elem &&
7110             func_id != BPF_FUNC_map_delete_elem &&
7111             func_id != BPF_FUNC_map_push_elem &&
7112             func_id != BPF_FUNC_map_pop_elem &&
7113             func_id != BPF_FUNC_map_peek_elem &&
7114             func_id != BPF_FUNC_for_each_map_elem &&
7115             func_id != BPF_FUNC_redirect_map &&
7116             func_id != BPF_FUNC_map_lookup_percpu_elem)
7117                 return 0;
7118
7119         if (map == NULL) {
7120                 verbose(env, "kernel subsystem misconfigured verifier\n");
7121                 return -EINVAL;
7122         }
7123
7124         /* In case of read-only, some additional restrictions
7125          * need to be applied in order to prevent altering the
7126          * state of the map from program side.
7127          */
7128         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7129             (func_id == BPF_FUNC_map_delete_elem ||
7130              func_id == BPF_FUNC_map_update_elem ||
7131              func_id == BPF_FUNC_map_push_elem ||
7132              func_id == BPF_FUNC_map_pop_elem)) {
7133                 verbose(env, "write into map forbidden\n");
7134                 return -EACCES;
7135         }
7136
7137         if (!BPF_MAP_PTR(aux->map_ptr_state))
7138                 bpf_map_ptr_store(aux, meta->map_ptr,
7139                                   !meta->map_ptr->bypass_spec_v1);
7140         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7141                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7142                                   !meta->map_ptr->bypass_spec_v1);
7143         return 0;
7144 }
7145
7146 static int
7147 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7148                 int func_id, int insn_idx)
7149 {
7150         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7151         struct bpf_reg_state *regs = cur_regs(env), *reg;
7152         struct bpf_map *map = meta->map_ptr;
7153         u64 val, max;
7154         int err;
7155
7156         if (func_id != BPF_FUNC_tail_call)
7157                 return 0;
7158         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7159                 verbose(env, "kernel subsystem misconfigured verifier\n");
7160                 return -EINVAL;
7161         }
7162
7163         reg = &regs[BPF_REG_3];
7164         val = reg->var_off.value;
7165         max = map->max_entries;
7166
7167         if (!(register_is_const(reg) && val < max)) {
7168                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7169                 return 0;
7170         }
7171
7172         err = mark_chain_precision(env, BPF_REG_3);
7173         if (err)
7174                 return err;
7175         if (bpf_map_key_unseen(aux))
7176                 bpf_map_key_store(aux, val);
7177         else if (!bpf_map_key_poisoned(aux) &&
7178                   bpf_map_key_immediate(aux) != val)
7179                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7180         return 0;
7181 }
7182
7183 static int check_reference_leak(struct bpf_verifier_env *env)
7184 {
7185         struct bpf_func_state *state = cur_func(env);
7186         bool refs_lingering = false;
7187         int i;
7188
7189         if (state->frameno && !state->in_callback_fn)
7190                 return 0;
7191
7192         for (i = 0; i < state->acquired_refs; i++) {
7193                 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7194                         continue;
7195                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7196                         state->refs[i].id, state->refs[i].insn_idx);
7197                 refs_lingering = true;
7198         }
7199         return refs_lingering ? -EINVAL : 0;
7200 }
7201
7202 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7203                                    struct bpf_reg_state *regs)
7204 {
7205         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
7206         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
7207         struct bpf_map *fmt_map = fmt_reg->map_ptr;
7208         int err, fmt_map_off, num_args;
7209         u64 fmt_addr;
7210         char *fmt;
7211
7212         /* data must be an array of u64 */
7213         if (data_len_reg->var_off.value % 8)
7214                 return -EINVAL;
7215         num_args = data_len_reg->var_off.value / 8;
7216
7217         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7218          * and map_direct_value_addr is set.
7219          */
7220         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7221         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7222                                                   fmt_map_off);
7223         if (err) {
7224                 verbose(env, "verifier bug\n");
7225                 return -EFAULT;
7226         }
7227         fmt = (char *)(long)fmt_addr + fmt_map_off;
7228
7229         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7230          * can focus on validating the format specifiers.
7231          */
7232         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7233         if (err < 0)
7234                 verbose(env, "Invalid format string\n");
7235
7236         return err;
7237 }
7238
7239 static int check_get_func_ip(struct bpf_verifier_env *env)
7240 {
7241         enum bpf_prog_type type = resolve_prog_type(env->prog);
7242         int func_id = BPF_FUNC_get_func_ip;
7243
7244         if (type == BPF_PROG_TYPE_TRACING) {
7245                 if (!bpf_prog_has_trampoline(env->prog)) {
7246                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7247                                 func_id_name(func_id), func_id);
7248                         return -ENOTSUPP;
7249                 }
7250                 return 0;
7251         } else if (type == BPF_PROG_TYPE_KPROBE) {
7252                 return 0;
7253         }
7254
7255         verbose(env, "func %s#%d not supported for program type %d\n",
7256                 func_id_name(func_id), func_id, type);
7257         return -ENOTSUPP;
7258 }
7259
7260 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7261 {
7262         return &env->insn_aux_data[env->insn_idx];
7263 }
7264
7265 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7266 {
7267         struct bpf_reg_state *regs = cur_regs(env);
7268         struct bpf_reg_state *reg = &regs[BPF_REG_4];
7269         bool reg_is_null = register_is_null(reg);
7270
7271         if (reg_is_null)
7272                 mark_chain_precision(env, BPF_REG_4);
7273
7274         return reg_is_null;
7275 }
7276
7277 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7278 {
7279         struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7280
7281         if (!state->initialized) {
7282                 state->initialized = 1;
7283                 state->fit_for_inline = loop_flag_is_zero(env);
7284                 state->callback_subprogno = subprogno;
7285                 return;
7286         }
7287
7288         if (!state->fit_for_inline)
7289                 return;
7290
7291         state->fit_for_inline = (loop_flag_is_zero(env) &&
7292                                  state->callback_subprogno == subprogno);
7293 }
7294
7295 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7296                              int *insn_idx_p)
7297 {
7298         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7299         const struct bpf_func_proto *fn = NULL;
7300         enum bpf_return_type ret_type;
7301         enum bpf_type_flag ret_flag;
7302         struct bpf_reg_state *regs;
7303         struct bpf_call_arg_meta meta;
7304         int insn_idx = *insn_idx_p;
7305         bool changes_data;
7306         int i, err, func_id;
7307
7308         /* find function prototype */
7309         func_id = insn->imm;
7310         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7311                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7312                         func_id);
7313                 return -EINVAL;
7314         }
7315
7316         if (env->ops->get_func_proto)
7317                 fn = env->ops->get_func_proto(func_id, env->prog);
7318         if (!fn) {
7319                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7320                         func_id);
7321                 return -EINVAL;
7322         }
7323
7324         /* eBPF programs must be GPL compatible to use GPL-ed functions */
7325         if (!env->prog->gpl_compatible && fn->gpl_only) {
7326                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7327                 return -EINVAL;
7328         }
7329
7330         if (fn->allowed && !fn->allowed(env->prog)) {
7331                 verbose(env, "helper call is not allowed in probe\n");
7332                 return -EINVAL;
7333         }
7334
7335         /* With LD_ABS/IND some JITs save/restore skb from r1. */
7336         changes_data = bpf_helper_changes_pkt_data(fn->func);
7337         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7338                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7339                         func_id_name(func_id), func_id);
7340                 return -EINVAL;
7341         }
7342
7343         memset(&meta, 0, sizeof(meta));
7344         meta.pkt_access = fn->pkt_access;
7345
7346         err = check_func_proto(fn, func_id);
7347         if (err) {
7348                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7349                         func_id_name(func_id), func_id);
7350                 return err;
7351         }
7352
7353         meta.func_id = func_id;
7354         /* check args */
7355         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7356                 err = check_func_arg(env, i, &meta, fn);
7357                 if (err)
7358                         return err;
7359         }
7360
7361         err = record_func_map(env, &meta, func_id, insn_idx);
7362         if (err)
7363                 return err;
7364
7365         err = record_func_key(env, &meta, func_id, insn_idx);
7366         if (err)
7367                 return err;
7368
7369         /* Mark slots with STACK_MISC in case of raw mode, stack offset
7370          * is inferred from register state.
7371          */
7372         for (i = 0; i < meta.access_size; i++) {
7373                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7374                                        BPF_WRITE, -1, false);
7375                 if (err)
7376                         return err;
7377         }
7378
7379         regs = cur_regs(env);
7380
7381         if (meta.uninit_dynptr_regno) {
7382                 /* we write BPF_DW bits (8 bytes) at a time */
7383                 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7384                         err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7385                                                i, BPF_DW, BPF_WRITE, -1, false);
7386                         if (err)
7387                                 return err;
7388                 }
7389
7390                 err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
7391                                               fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7392                                               insn_idx);
7393                 if (err)
7394                         return err;
7395         }
7396
7397         if (meta.release_regno) {
7398                 err = -EINVAL;
7399                 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7400                         err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
7401                 else if (meta.ref_obj_id)
7402                         err = release_reference(env, meta.ref_obj_id);
7403                 /* meta.ref_obj_id can only be 0 if register that is meant to be
7404                  * released is NULL, which must be > R0.
7405                  */
7406                 else if (register_is_null(&regs[meta.release_regno]))
7407                         err = 0;
7408                 if (err) {
7409                         verbose(env, "func %s#%d reference has not been acquired before\n",
7410                                 func_id_name(func_id), func_id);
7411                         return err;
7412                 }
7413         }
7414
7415         switch (func_id) {
7416         case BPF_FUNC_tail_call:
7417                 err = check_reference_leak(env);
7418                 if (err) {
7419                         verbose(env, "tail_call would lead to reference leak\n");
7420                         return err;
7421                 }
7422                 break;
7423         case BPF_FUNC_get_local_storage:
7424                 /* check that flags argument in get_local_storage(map, flags) is 0,
7425                  * this is required because get_local_storage() can't return an error.
7426                  */
7427                 if (!register_is_null(&regs[BPF_REG_2])) {
7428                         verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7429                         return -EINVAL;
7430                 }
7431                 break;
7432         case BPF_FUNC_for_each_map_elem:
7433                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7434                                         set_map_elem_callback_state);
7435                 break;
7436         case BPF_FUNC_timer_set_callback:
7437                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7438                                         set_timer_callback_state);
7439                 break;
7440         case BPF_FUNC_find_vma:
7441                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7442                                         set_find_vma_callback_state);
7443                 break;
7444         case BPF_FUNC_snprintf:
7445                 err = check_bpf_snprintf_call(env, regs);
7446                 break;
7447         case BPF_FUNC_loop:
7448                 update_loop_inline_state(env, meta.subprogno);
7449                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7450                                         set_loop_callback_state);
7451                 break;
7452         case BPF_FUNC_dynptr_from_mem:
7453                 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7454                         verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7455                                 reg_type_str(env, regs[BPF_REG_1].type));
7456                         return -EACCES;
7457                 }
7458                 break;
7459         case BPF_FUNC_set_retval:
7460                 if (prog_type == BPF_PROG_TYPE_LSM &&
7461                     env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7462                         if (!env->prog->aux->attach_func_proto->type) {
7463                                 /* Make sure programs that attach to void
7464                                  * hooks don't try to modify return value.
7465                                  */
7466                                 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7467                                 return -EINVAL;
7468                         }
7469                 }
7470                 break;
7471         case BPF_FUNC_dynptr_data:
7472                 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7473                         if (arg_type_is_dynptr(fn->arg_type[i])) {
7474                                 struct bpf_reg_state *reg = &regs[BPF_REG_1 + i];
7475
7476                                 if (meta.ref_obj_id) {
7477                                         verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7478                                         return -EFAULT;
7479                                 }
7480
7481                                 if (base_type(reg->type) != PTR_TO_DYNPTR)
7482                                         /* Find the id of the dynptr we're
7483                                          * tracking the reference of
7484                                          */
7485                                         meta.ref_obj_id = stack_slot_get_id(env, reg);
7486                                 break;
7487                         }
7488                 }
7489                 if (i == MAX_BPF_FUNC_REG_ARGS) {
7490                         verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7491                         return -EFAULT;
7492                 }
7493                 break;
7494         case BPF_FUNC_user_ringbuf_drain:
7495                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7496                                         set_user_ringbuf_callback_state);
7497                 break;
7498         }
7499
7500         if (err)
7501                 return err;
7502
7503         /* reset caller saved regs */
7504         for (i = 0; i < CALLER_SAVED_REGS; i++) {
7505                 mark_reg_not_init(env, regs, caller_saved[i]);
7506                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7507         }
7508
7509         /* helper call returns 64-bit value. */
7510         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7511
7512         /* update return register (already marked as written above) */
7513         ret_type = fn->ret_type;
7514         ret_flag = type_flag(ret_type);
7515
7516         switch (base_type(ret_type)) {
7517         case RET_INTEGER:
7518                 /* sets type to SCALAR_VALUE */
7519                 mark_reg_unknown(env, regs, BPF_REG_0);
7520                 break;
7521         case RET_VOID:
7522                 regs[BPF_REG_0].type = NOT_INIT;
7523                 break;
7524         case RET_PTR_TO_MAP_VALUE:
7525                 /* There is no offset yet applied, variable or fixed */
7526                 mark_reg_known_zero(env, regs, BPF_REG_0);
7527                 /* remember map_ptr, so that check_map_access()
7528                  * can check 'value_size' boundary of memory access
7529                  * to map element returned from bpf_map_lookup_elem()
7530                  */
7531                 if (meta.map_ptr == NULL) {
7532                         verbose(env,
7533                                 "kernel subsystem misconfigured verifier\n");
7534                         return -EINVAL;
7535                 }
7536                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
7537                 regs[BPF_REG_0].map_uid = meta.map_uid;
7538                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7539                 if (!type_may_be_null(ret_type) &&
7540                     map_value_has_spin_lock(meta.map_ptr)) {
7541                         regs[BPF_REG_0].id = ++env->id_gen;
7542                 }
7543                 break;
7544         case RET_PTR_TO_SOCKET:
7545                 mark_reg_known_zero(env, regs, BPF_REG_0);
7546                 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7547                 break;
7548         case RET_PTR_TO_SOCK_COMMON:
7549                 mark_reg_known_zero(env, regs, BPF_REG_0);
7550                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7551                 break;
7552         case RET_PTR_TO_TCP_SOCK:
7553                 mark_reg_known_zero(env, regs, BPF_REG_0);
7554                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7555                 break;
7556         case RET_PTR_TO_ALLOC_MEM:
7557                 mark_reg_known_zero(env, regs, BPF_REG_0);
7558                 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7559                 regs[BPF_REG_0].mem_size = meta.mem_size;
7560                 break;
7561         case RET_PTR_TO_MEM_OR_BTF_ID:
7562         {
7563                 const struct btf_type *t;
7564
7565                 mark_reg_known_zero(env, regs, BPF_REG_0);
7566                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7567                 if (!btf_type_is_struct(t)) {
7568                         u32 tsize;
7569                         const struct btf_type *ret;
7570                         const char *tname;
7571
7572                         /* resolve the type size of ksym. */
7573                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7574                         if (IS_ERR(ret)) {
7575                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7576                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
7577                                         tname, PTR_ERR(ret));
7578                                 return -EINVAL;
7579                         }
7580                         regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7581                         regs[BPF_REG_0].mem_size = tsize;
7582                 } else {
7583                         /* MEM_RDONLY may be carried from ret_flag, but it
7584                          * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7585                          * it will confuse the check of PTR_TO_BTF_ID in
7586                          * check_mem_access().
7587                          */
7588                         ret_flag &= ~MEM_RDONLY;
7589
7590                         regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7591                         regs[BPF_REG_0].btf = meta.ret_btf;
7592                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7593                 }
7594                 break;
7595         }
7596         case RET_PTR_TO_BTF_ID:
7597         {
7598                 struct btf *ret_btf;
7599                 int ret_btf_id;
7600
7601                 mark_reg_known_zero(env, regs, BPF_REG_0);
7602                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7603                 if (func_id == BPF_FUNC_kptr_xchg) {
7604                         ret_btf = meta.kptr_off_desc->kptr.btf;
7605                         ret_btf_id = meta.kptr_off_desc->kptr.btf_id;
7606                 } else {
7607                         if (fn->ret_btf_id == BPF_PTR_POISON) {
7608                                 verbose(env, "verifier internal error:");
7609                                 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
7610                                         func_id_name(func_id));
7611                                 return -EINVAL;
7612                         }
7613                         ret_btf = btf_vmlinux;
7614                         ret_btf_id = *fn->ret_btf_id;
7615                 }
7616                 if (ret_btf_id == 0) {
7617                         verbose(env, "invalid return type %u of func %s#%d\n",
7618                                 base_type(ret_type), func_id_name(func_id),
7619                                 func_id);
7620                         return -EINVAL;
7621                 }
7622                 regs[BPF_REG_0].btf = ret_btf;
7623                 regs[BPF_REG_0].btf_id = ret_btf_id;
7624                 break;
7625         }
7626         default:
7627                 verbose(env, "unknown return type %u of func %s#%d\n",
7628                         base_type(ret_type), func_id_name(func_id), func_id);
7629                 return -EINVAL;
7630         }
7631
7632         if (type_may_be_null(regs[BPF_REG_0].type))
7633                 regs[BPF_REG_0].id = ++env->id_gen;
7634
7635         if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7636                 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7637                         func_id_name(func_id), func_id);
7638                 return -EFAULT;
7639         }
7640
7641         if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7642                 /* For release_reference() */
7643                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7644         } else if (is_acquire_function(func_id, meta.map_ptr)) {
7645                 int id = acquire_reference_state(env, insn_idx);
7646
7647                 if (id < 0)
7648                         return id;
7649                 /* For mark_ptr_or_null_reg() */
7650                 regs[BPF_REG_0].id = id;
7651                 /* For release_reference() */
7652                 regs[BPF_REG_0].ref_obj_id = id;
7653         }
7654
7655         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7656
7657         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7658         if (err)
7659                 return err;
7660
7661         if ((func_id == BPF_FUNC_get_stack ||
7662              func_id == BPF_FUNC_get_task_stack) &&
7663             !env->prog->has_callchain_buf) {
7664                 const char *err_str;
7665
7666 #ifdef CONFIG_PERF_EVENTS
7667                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
7668                 err_str = "cannot get callchain buffer for func %s#%d\n";
7669 #else
7670                 err = -ENOTSUPP;
7671                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7672 #endif
7673                 if (err) {
7674                         verbose(env, err_str, func_id_name(func_id), func_id);
7675                         return err;
7676                 }
7677
7678                 env->prog->has_callchain_buf = true;
7679         }
7680
7681         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7682                 env->prog->call_get_stack = true;
7683
7684         if (func_id == BPF_FUNC_get_func_ip) {
7685                 if (check_get_func_ip(env))
7686                         return -ENOTSUPP;
7687                 env->prog->call_get_func_ip = true;
7688         }
7689
7690         if (changes_data)
7691                 clear_all_pkt_pointers(env);
7692         return 0;
7693 }
7694
7695 /* mark_btf_func_reg_size() is used when the reg size is determined by
7696  * the BTF func_proto's return value size and argument.
7697  */
7698 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7699                                    size_t reg_size)
7700 {
7701         struct bpf_reg_state *reg = &cur_regs(env)[regno];
7702
7703         if (regno == BPF_REG_0) {
7704                 /* Function return value */
7705                 reg->live |= REG_LIVE_WRITTEN;
7706                 reg->subreg_def = reg_size == sizeof(u64) ?
7707                         DEF_NOT_SUBREG : env->insn_idx + 1;
7708         } else {
7709                 /* Function argument */
7710                 if (reg_size == sizeof(u64)) {
7711                         mark_insn_zext(env, reg);
7712                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7713                 } else {
7714                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7715                 }
7716         }
7717 }
7718
7719 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7720                             int *insn_idx_p)
7721 {
7722         const struct btf_type *t, *func, *func_proto, *ptr_type;
7723         struct bpf_reg_state *regs = cur_regs(env);
7724         struct bpf_kfunc_arg_meta meta = { 0 };
7725         const char *func_name, *ptr_type_name;
7726         u32 i, nargs, func_id, ptr_type_id;
7727         int err, insn_idx = *insn_idx_p;
7728         const struct btf_param *args;
7729         struct btf *desc_btf;
7730         u32 *kfunc_flags;
7731         bool acq;
7732
7733         /* skip for now, but return error when we find this in fixup_kfunc_call */
7734         if (!insn->imm)
7735                 return 0;
7736
7737         desc_btf = find_kfunc_desc_btf(env, insn->off);
7738         if (IS_ERR(desc_btf))
7739                 return PTR_ERR(desc_btf);
7740
7741         func_id = insn->imm;
7742         func = btf_type_by_id(desc_btf, func_id);
7743         func_name = btf_name_by_offset(desc_btf, func->name_off);
7744         func_proto = btf_type_by_id(desc_btf, func->type);
7745
7746         kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
7747         if (!kfunc_flags) {
7748                 verbose(env, "calling kernel function %s is not allowed\n",
7749                         func_name);
7750                 return -EACCES;
7751         }
7752         if (*kfunc_flags & KF_DESTRUCTIVE && !capable(CAP_SYS_BOOT)) {
7753                 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capabilities\n");
7754                 return -EACCES;
7755         }
7756
7757         acq = *kfunc_flags & KF_ACQUIRE;
7758
7759         meta.flags = *kfunc_flags;
7760
7761         /* Check the arguments */
7762         err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs, &meta);
7763         if (err < 0)
7764                 return err;
7765         /* In case of release function, we get register number of refcounted
7766          * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
7767          */
7768         if (err) {
7769                 err = release_reference(env, regs[err].ref_obj_id);
7770                 if (err) {
7771                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
7772                                 func_name, func_id);
7773                         return err;
7774                 }
7775         }
7776
7777         for (i = 0; i < CALLER_SAVED_REGS; i++)
7778                 mark_reg_not_init(env, regs, caller_saved[i]);
7779
7780         /* Check return type */
7781         t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
7782
7783         if (acq && !btf_type_is_struct_ptr(desc_btf, t)) {
7784                 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
7785                 return -EINVAL;
7786         }
7787
7788         if (btf_type_is_scalar(t)) {
7789                 mark_reg_unknown(env, regs, BPF_REG_0);
7790                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7791         } else if (btf_type_is_ptr(t)) {
7792                 ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
7793                                                    &ptr_type_id);
7794                 if (!btf_type_is_struct(ptr_type)) {
7795                         if (!meta.r0_size) {
7796                                 ptr_type_name = btf_name_by_offset(desc_btf,
7797                                                                    ptr_type->name_off);
7798                                 verbose(env,
7799                                         "kernel function %s returns pointer type %s %s is not supported\n",
7800                                         func_name,
7801                                         btf_type_str(ptr_type),
7802                                         ptr_type_name);
7803                                 return -EINVAL;
7804                         }
7805
7806                         mark_reg_known_zero(env, regs, BPF_REG_0);
7807                         regs[BPF_REG_0].type = PTR_TO_MEM;
7808                         regs[BPF_REG_0].mem_size = meta.r0_size;
7809
7810                         if (meta.r0_rdonly)
7811                                 regs[BPF_REG_0].type |= MEM_RDONLY;
7812
7813                         /* Ensures we don't access the memory after a release_reference() */
7814                         if (meta.ref_obj_id)
7815                                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7816                 } else {
7817                         mark_reg_known_zero(env, regs, BPF_REG_0);
7818                         regs[BPF_REG_0].btf = desc_btf;
7819                         regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7820                         regs[BPF_REG_0].btf_id = ptr_type_id;
7821                 }
7822                 if (*kfunc_flags & KF_RET_NULL) {
7823                         regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7824                         /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7825                         regs[BPF_REG_0].id = ++env->id_gen;
7826                 }
7827                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
7828                 if (acq) {
7829                         int id = acquire_reference_state(env, insn_idx);
7830
7831                         if (id < 0)
7832                                 return id;
7833                         regs[BPF_REG_0].id = id;
7834                         regs[BPF_REG_0].ref_obj_id = id;
7835                 }
7836         } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7837
7838         nargs = btf_type_vlen(func_proto);
7839         args = (const struct btf_param *)(func_proto + 1);
7840         for (i = 0; i < nargs; i++) {
7841                 u32 regno = i + 1;
7842
7843                 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
7844                 if (btf_type_is_ptr(t))
7845                         mark_btf_func_reg_size(env, regno, sizeof(void *));
7846                 else
7847                         /* scalar. ensured by btf_check_kfunc_arg_match() */
7848                         mark_btf_func_reg_size(env, regno, t->size);
7849         }
7850
7851         return 0;
7852 }
7853
7854 static bool signed_add_overflows(s64 a, s64 b)
7855 {
7856         /* Do the add in u64, where overflow is well-defined */
7857         s64 res = (s64)((u64)a + (u64)b);
7858
7859         if (b < 0)
7860                 return res > a;
7861         return res < a;
7862 }
7863
7864 static bool signed_add32_overflows(s32 a, s32 b)
7865 {
7866         /* Do the add in u32, where overflow is well-defined */
7867         s32 res = (s32)((u32)a + (u32)b);
7868
7869         if (b < 0)
7870                 return res > a;
7871         return res < a;
7872 }
7873
7874 static bool signed_sub_overflows(s64 a, s64 b)
7875 {
7876         /* Do the sub in u64, where overflow is well-defined */
7877         s64 res = (s64)((u64)a - (u64)b);
7878
7879         if (b < 0)
7880                 return res < a;
7881         return res > a;
7882 }
7883
7884 static bool signed_sub32_overflows(s32 a, s32 b)
7885 {
7886         /* Do the sub in u32, where overflow is well-defined */
7887         s32 res = (s32)((u32)a - (u32)b);
7888
7889         if (b < 0)
7890                 return res < a;
7891         return res > a;
7892 }
7893
7894 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7895                                   const struct bpf_reg_state *reg,
7896                                   enum bpf_reg_type type)
7897 {
7898         bool known = tnum_is_const(reg->var_off);
7899         s64 val = reg->var_off.value;
7900         s64 smin = reg->smin_value;
7901
7902         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7903                 verbose(env, "math between %s pointer and %lld is not allowed\n",
7904                         reg_type_str(env, type), val);
7905                 return false;
7906         }
7907
7908         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7909                 verbose(env, "%s pointer offset %d is not allowed\n",
7910                         reg_type_str(env, type), reg->off);
7911                 return false;
7912         }
7913
7914         if (smin == S64_MIN) {
7915                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
7916                         reg_type_str(env, type));
7917                 return false;
7918         }
7919
7920         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
7921                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
7922                         smin, reg_type_str(env, type));
7923                 return false;
7924         }
7925
7926         return true;
7927 }
7928
7929 enum {
7930         REASON_BOUNDS   = -1,
7931         REASON_TYPE     = -2,
7932         REASON_PATHS    = -3,
7933         REASON_LIMIT    = -4,
7934         REASON_STACK    = -5,
7935 };
7936
7937 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
7938                               u32 *alu_limit, bool mask_to_left)
7939 {
7940         u32 max = 0, ptr_limit = 0;
7941
7942         switch (ptr_reg->type) {
7943         case PTR_TO_STACK:
7944                 /* Offset 0 is out-of-bounds, but acceptable start for the
7945                  * left direction, see BPF_REG_FP. Also, unknown scalar
7946                  * offset where we would need to deal with min/max bounds is
7947                  * currently prohibited for unprivileged.
7948                  */
7949                 max = MAX_BPF_STACK + mask_to_left;
7950                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
7951                 break;
7952         case PTR_TO_MAP_VALUE:
7953                 max = ptr_reg->map_ptr->value_size;
7954                 ptr_limit = (mask_to_left ?
7955                              ptr_reg->smin_value :
7956                              ptr_reg->umax_value) + ptr_reg->off;
7957                 break;
7958         default:
7959                 return REASON_TYPE;
7960         }
7961
7962         if (ptr_limit >= max)
7963                 return REASON_LIMIT;
7964         *alu_limit = ptr_limit;
7965         return 0;
7966 }
7967
7968 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7969                                     const struct bpf_insn *insn)
7970 {
7971         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
7972 }
7973
7974 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7975                                        u32 alu_state, u32 alu_limit)
7976 {
7977         /* If we arrived here from different branches with different
7978          * state or limits to sanitize, then this won't work.
7979          */
7980         if (aux->alu_state &&
7981             (aux->alu_state != alu_state ||
7982              aux->alu_limit != alu_limit))
7983                 return REASON_PATHS;
7984
7985         /* Corresponding fixup done in do_misc_fixups(). */
7986         aux->alu_state = alu_state;
7987         aux->alu_limit = alu_limit;
7988         return 0;
7989 }
7990
7991 static int sanitize_val_alu(struct bpf_verifier_env *env,
7992                             struct bpf_insn *insn)
7993 {
7994         struct bpf_insn_aux_data *aux = cur_aux(env);
7995
7996         if (can_skip_alu_sanitation(env, insn))
7997                 return 0;
7998
7999         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
8000 }
8001
8002 static bool sanitize_needed(u8 opcode)
8003 {
8004         return opcode == BPF_ADD || opcode == BPF_SUB;
8005 }
8006
8007 struct bpf_sanitize_info {
8008         struct bpf_insn_aux_data aux;
8009         bool mask_to_left;
8010 };
8011
8012 static struct bpf_verifier_state *
8013 sanitize_speculative_path(struct bpf_verifier_env *env,
8014                           const struct bpf_insn *insn,
8015                           u32 next_idx, u32 curr_idx)
8016 {
8017         struct bpf_verifier_state *branch;
8018         struct bpf_reg_state *regs;
8019
8020         branch = push_stack(env, next_idx, curr_idx, true);
8021         if (branch && insn) {
8022                 regs = branch->frame[branch->curframe]->regs;
8023                 if (BPF_SRC(insn->code) == BPF_K) {
8024                         mark_reg_unknown(env, regs, insn->dst_reg);
8025                 } else if (BPF_SRC(insn->code) == BPF_X) {
8026                         mark_reg_unknown(env, regs, insn->dst_reg);
8027                         mark_reg_unknown(env, regs, insn->src_reg);
8028                 }
8029         }
8030         return branch;
8031 }
8032
8033 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
8034                             struct bpf_insn *insn,
8035                             const struct bpf_reg_state *ptr_reg,
8036                             const struct bpf_reg_state *off_reg,
8037                             struct bpf_reg_state *dst_reg,
8038                             struct bpf_sanitize_info *info,
8039                             const bool commit_window)
8040 {
8041         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
8042         struct bpf_verifier_state *vstate = env->cur_state;
8043         bool off_is_imm = tnum_is_const(off_reg->var_off);
8044         bool off_is_neg = off_reg->smin_value < 0;
8045         bool ptr_is_dst_reg = ptr_reg == dst_reg;
8046         u8 opcode = BPF_OP(insn->code);
8047         u32 alu_state, alu_limit;
8048         struct bpf_reg_state tmp;
8049         bool ret;
8050         int err;
8051
8052         if (can_skip_alu_sanitation(env, insn))
8053                 return 0;
8054
8055         /* We already marked aux for masking from non-speculative
8056          * paths, thus we got here in the first place. We only care
8057          * to explore bad access from here.
8058          */
8059         if (vstate->speculative)
8060                 goto do_sim;
8061
8062         if (!commit_window) {
8063                 if (!tnum_is_const(off_reg->var_off) &&
8064                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
8065                         return REASON_BOUNDS;
8066
8067                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
8068                                      (opcode == BPF_SUB && !off_is_neg);
8069         }
8070
8071         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
8072         if (err < 0)
8073                 return err;
8074
8075         if (commit_window) {
8076                 /* In commit phase we narrow the masking window based on
8077                  * the observed pointer move after the simulated operation.
8078                  */
8079                 alu_state = info->aux.alu_state;
8080                 alu_limit = abs(info->aux.alu_limit - alu_limit);
8081         } else {
8082                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
8083                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
8084                 alu_state |= ptr_is_dst_reg ?
8085                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
8086
8087                 /* Limit pruning on unknown scalars to enable deep search for
8088                  * potential masking differences from other program paths.
8089                  */
8090                 if (!off_is_imm)
8091                         env->explore_alu_limits = true;
8092         }
8093
8094         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
8095         if (err < 0)
8096                 return err;
8097 do_sim:
8098         /* If we're in commit phase, we're done here given we already
8099          * pushed the truncated dst_reg into the speculative verification
8100          * stack.
8101          *
8102          * Also, when register is a known constant, we rewrite register-based
8103          * operation to immediate-based, and thus do not need masking (and as
8104          * a consequence, do not need to simulate the zero-truncation either).
8105          */
8106         if (commit_window || off_is_imm)
8107                 return 0;
8108
8109         /* Simulate and find potential out-of-bounds access under
8110          * speculative execution from truncation as a result of
8111          * masking when off was not within expected range. If off
8112          * sits in dst, then we temporarily need to move ptr there
8113          * to simulate dst (== 0) +/-= ptr. Needed, for example,
8114          * for cases where we use K-based arithmetic in one direction
8115          * and truncated reg-based in the other in order to explore
8116          * bad access.
8117          */
8118         if (!ptr_is_dst_reg) {
8119                 tmp = *dst_reg;
8120                 copy_register_state(dst_reg, ptr_reg);
8121         }
8122         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
8123                                         env->insn_idx);
8124         if (!ptr_is_dst_reg && ret)
8125                 *dst_reg = tmp;
8126         return !ret ? REASON_STACK : 0;
8127 }
8128
8129 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
8130 {
8131         struct bpf_verifier_state *vstate = env->cur_state;
8132
8133         /* If we simulate paths under speculation, we don't update the
8134          * insn as 'seen' such that when we verify unreachable paths in
8135          * the non-speculative domain, sanitize_dead_code() can still
8136          * rewrite/sanitize them.
8137          */
8138         if (!vstate->speculative)
8139                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8140 }
8141
8142 static int sanitize_err(struct bpf_verifier_env *env,
8143                         const struct bpf_insn *insn, int reason,
8144                         const struct bpf_reg_state *off_reg,
8145                         const struct bpf_reg_state *dst_reg)
8146 {
8147         static const char *err = "pointer arithmetic with it prohibited for !root";
8148         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
8149         u32 dst = insn->dst_reg, src = insn->src_reg;
8150
8151         switch (reason) {
8152         case REASON_BOUNDS:
8153                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
8154                         off_reg == dst_reg ? dst : src, err);
8155                 break;
8156         case REASON_TYPE:
8157                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
8158                         off_reg == dst_reg ? src : dst, err);
8159                 break;
8160         case REASON_PATHS:
8161                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
8162                         dst, op, err);
8163                 break;
8164         case REASON_LIMIT:
8165                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
8166                         dst, op, err);
8167                 break;
8168         case REASON_STACK:
8169                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
8170                         dst, err);
8171                 break;
8172         default:
8173                 verbose(env, "verifier internal error: unknown reason (%d)\n",
8174                         reason);
8175                 break;
8176         }
8177
8178         return -EACCES;
8179 }
8180
8181 /* check that stack access falls within stack limits and that 'reg' doesn't
8182  * have a variable offset.
8183  *
8184  * Variable offset is prohibited for unprivileged mode for simplicity since it
8185  * requires corresponding support in Spectre masking for stack ALU.  See also
8186  * retrieve_ptr_limit().
8187  *
8188  *
8189  * 'off' includes 'reg->off'.
8190  */
8191 static int check_stack_access_for_ptr_arithmetic(
8192                                 struct bpf_verifier_env *env,
8193                                 int regno,
8194                                 const struct bpf_reg_state *reg,
8195                                 int off)
8196 {
8197         if (!tnum_is_const(reg->var_off)) {
8198                 char tn_buf[48];
8199
8200                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8201                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
8202                         regno, tn_buf, off);
8203                 return -EACCES;
8204         }
8205
8206         if (off >= 0 || off < -MAX_BPF_STACK) {
8207                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
8208                         "prohibited for !root; off=%d\n", regno, off);
8209                 return -EACCES;
8210         }
8211
8212         return 0;
8213 }
8214
8215 static int sanitize_check_bounds(struct bpf_verifier_env *env,
8216                                  const struct bpf_insn *insn,
8217                                  const struct bpf_reg_state *dst_reg)
8218 {
8219         u32 dst = insn->dst_reg;
8220
8221         /* For unprivileged we require that resulting offset must be in bounds
8222          * in order to be able to sanitize access later on.
8223          */
8224         if (env->bypass_spec_v1)
8225                 return 0;
8226
8227         switch (dst_reg->type) {
8228         case PTR_TO_STACK:
8229                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
8230                                         dst_reg->off + dst_reg->var_off.value))
8231                         return -EACCES;
8232                 break;
8233         case PTR_TO_MAP_VALUE:
8234                 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
8235                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
8236                                 "prohibited for !root\n", dst);
8237                         return -EACCES;
8238                 }
8239                 break;
8240         default:
8241                 break;
8242         }
8243
8244         return 0;
8245 }
8246
8247 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
8248  * Caller should also handle BPF_MOV case separately.
8249  * If we return -EACCES, caller may want to try again treating pointer as a
8250  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
8251  */
8252 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
8253                                    struct bpf_insn *insn,
8254                                    const struct bpf_reg_state *ptr_reg,
8255                                    const struct bpf_reg_state *off_reg)
8256 {
8257         struct bpf_verifier_state *vstate = env->cur_state;
8258         struct bpf_func_state *state = vstate->frame[vstate->curframe];
8259         struct bpf_reg_state *regs = state->regs, *dst_reg;
8260         bool known = tnum_is_const(off_reg->var_off);
8261         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
8262             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
8263         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
8264             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
8265         struct bpf_sanitize_info info = {};
8266         u8 opcode = BPF_OP(insn->code);
8267         u32 dst = insn->dst_reg;
8268         int ret;
8269
8270         dst_reg = &regs[dst];
8271
8272         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
8273             smin_val > smax_val || umin_val > umax_val) {
8274                 /* Taint dst register if offset had invalid bounds derived from
8275                  * e.g. dead branches.
8276                  */
8277                 __mark_reg_unknown(env, dst_reg);
8278                 return 0;
8279         }
8280
8281         if (BPF_CLASS(insn->code) != BPF_ALU64) {
8282                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
8283                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8284                         __mark_reg_unknown(env, dst_reg);
8285                         return 0;
8286                 }
8287
8288                 verbose(env,
8289                         "R%d 32-bit pointer arithmetic prohibited\n",
8290                         dst);
8291                 return -EACCES;
8292         }
8293
8294         if (ptr_reg->type & PTR_MAYBE_NULL) {
8295                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
8296                         dst, reg_type_str(env, ptr_reg->type));
8297                 return -EACCES;
8298         }
8299
8300         switch (base_type(ptr_reg->type)) {
8301         case CONST_PTR_TO_MAP:
8302                 /* smin_val represents the known value */
8303                 if (known && smin_val == 0 && opcode == BPF_ADD)
8304                         break;
8305                 fallthrough;
8306         case PTR_TO_PACKET_END:
8307         case PTR_TO_SOCKET:
8308         case PTR_TO_SOCK_COMMON:
8309         case PTR_TO_TCP_SOCK:
8310         case PTR_TO_XDP_SOCK:
8311                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
8312                         dst, reg_type_str(env, ptr_reg->type));
8313                 return -EACCES;
8314         default:
8315                 break;
8316         }
8317
8318         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
8319          * The id may be overwritten later if we create a new variable offset.
8320          */
8321         dst_reg->type = ptr_reg->type;
8322         dst_reg->id = ptr_reg->id;
8323
8324         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
8325             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
8326                 return -EINVAL;
8327
8328         /* pointer types do not carry 32-bit bounds at the moment. */
8329         __mark_reg32_unbounded(dst_reg);
8330
8331         if (sanitize_needed(opcode)) {
8332                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
8333                                        &info, false);
8334                 if (ret < 0)
8335                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
8336         }
8337
8338         switch (opcode) {
8339         case BPF_ADD:
8340                 /* We can take a fixed offset as long as it doesn't overflow
8341                  * the s32 'off' field
8342                  */
8343                 if (known && (ptr_reg->off + smin_val ==
8344                               (s64)(s32)(ptr_reg->off + smin_val))) {
8345                         /* pointer += K.  Accumulate it into fixed offset */
8346                         dst_reg->smin_value = smin_ptr;
8347                         dst_reg->smax_value = smax_ptr;
8348                         dst_reg->umin_value = umin_ptr;
8349                         dst_reg->umax_value = umax_ptr;
8350                         dst_reg->var_off = ptr_reg->var_off;
8351                         dst_reg->off = ptr_reg->off + smin_val;
8352                         dst_reg->raw = ptr_reg->raw;
8353                         break;
8354                 }
8355                 /* A new variable offset is created.  Note that off_reg->off
8356                  * == 0, since it's a scalar.
8357                  * dst_reg gets the pointer type and since some positive
8358                  * integer value was added to the pointer, give it a new 'id'
8359                  * if it's a PTR_TO_PACKET.
8360                  * this creates a new 'base' pointer, off_reg (variable) gets
8361                  * added into the variable offset, and we copy the fixed offset
8362                  * from ptr_reg.
8363                  */
8364                 if (signed_add_overflows(smin_ptr, smin_val) ||
8365                     signed_add_overflows(smax_ptr, smax_val)) {
8366                         dst_reg->smin_value = S64_MIN;
8367                         dst_reg->smax_value = S64_MAX;
8368                 } else {
8369                         dst_reg->smin_value = smin_ptr + smin_val;
8370                         dst_reg->smax_value = smax_ptr + smax_val;
8371                 }
8372                 if (umin_ptr + umin_val < umin_ptr ||
8373                     umax_ptr + umax_val < umax_ptr) {
8374                         dst_reg->umin_value = 0;
8375                         dst_reg->umax_value = U64_MAX;
8376                 } else {
8377                         dst_reg->umin_value = umin_ptr + umin_val;
8378                         dst_reg->umax_value = umax_ptr + umax_val;
8379                 }
8380                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
8381                 dst_reg->off = ptr_reg->off;
8382                 dst_reg->raw = ptr_reg->raw;
8383                 if (reg_is_pkt_pointer(ptr_reg)) {
8384                         dst_reg->id = ++env->id_gen;
8385                         /* something was added to pkt_ptr, set range to zero */
8386                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8387                 }
8388                 break;
8389         case BPF_SUB:
8390                 if (dst_reg == off_reg) {
8391                         /* scalar -= pointer.  Creates an unknown scalar */
8392                         verbose(env, "R%d tried to subtract pointer from scalar\n",
8393                                 dst);
8394                         return -EACCES;
8395                 }
8396                 /* We don't allow subtraction from FP, because (according to
8397                  * test_verifier.c test "invalid fp arithmetic", JITs might not
8398                  * be able to deal with it.
8399                  */
8400                 if (ptr_reg->type == PTR_TO_STACK) {
8401                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
8402                                 dst);
8403                         return -EACCES;
8404                 }
8405                 if (known && (ptr_reg->off - smin_val ==
8406                               (s64)(s32)(ptr_reg->off - smin_val))) {
8407                         /* pointer -= K.  Subtract it from fixed offset */
8408                         dst_reg->smin_value = smin_ptr;
8409                         dst_reg->smax_value = smax_ptr;
8410                         dst_reg->umin_value = umin_ptr;
8411                         dst_reg->umax_value = umax_ptr;
8412                         dst_reg->var_off = ptr_reg->var_off;
8413                         dst_reg->id = ptr_reg->id;
8414                         dst_reg->off = ptr_reg->off - smin_val;
8415                         dst_reg->raw = ptr_reg->raw;
8416                         break;
8417                 }
8418                 /* A new variable offset is created.  If the subtrahend is known
8419                  * nonnegative, then any reg->range we had before is still good.
8420                  */
8421                 if (signed_sub_overflows(smin_ptr, smax_val) ||
8422                     signed_sub_overflows(smax_ptr, smin_val)) {
8423                         /* Overflow possible, we know nothing */
8424                         dst_reg->smin_value = S64_MIN;
8425                         dst_reg->smax_value = S64_MAX;
8426                 } else {
8427                         dst_reg->smin_value = smin_ptr - smax_val;
8428                         dst_reg->smax_value = smax_ptr - smin_val;
8429                 }
8430                 if (umin_ptr < umax_val) {
8431                         /* Overflow possible, we know nothing */
8432                         dst_reg->umin_value = 0;
8433                         dst_reg->umax_value = U64_MAX;
8434                 } else {
8435                         /* Cannot overflow (as long as bounds are consistent) */
8436                         dst_reg->umin_value = umin_ptr - umax_val;
8437                         dst_reg->umax_value = umax_ptr - umin_val;
8438                 }
8439                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
8440                 dst_reg->off = ptr_reg->off;
8441                 dst_reg->raw = ptr_reg->raw;
8442                 if (reg_is_pkt_pointer(ptr_reg)) {
8443                         dst_reg->id = ++env->id_gen;
8444                         /* something was added to pkt_ptr, set range to zero */
8445                         if (smin_val < 0)
8446                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8447                 }
8448                 break;
8449         case BPF_AND:
8450         case BPF_OR:
8451         case BPF_XOR:
8452                 /* bitwise ops on pointers are troublesome, prohibit. */
8453                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
8454                         dst, bpf_alu_string[opcode >> 4]);
8455                 return -EACCES;
8456         default:
8457                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
8458                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
8459                         dst, bpf_alu_string[opcode >> 4]);
8460                 return -EACCES;
8461         }
8462
8463         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
8464                 return -EINVAL;
8465         reg_bounds_sync(dst_reg);
8466         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
8467                 return -EACCES;
8468         if (sanitize_needed(opcode)) {
8469                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
8470                                        &info, true);
8471                 if (ret < 0)
8472                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
8473         }
8474
8475         return 0;
8476 }
8477
8478 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
8479                                  struct bpf_reg_state *src_reg)
8480 {
8481         s32 smin_val = src_reg->s32_min_value;
8482         s32 smax_val = src_reg->s32_max_value;
8483         u32 umin_val = src_reg->u32_min_value;
8484         u32 umax_val = src_reg->u32_max_value;
8485
8486         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
8487             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
8488                 dst_reg->s32_min_value = S32_MIN;
8489                 dst_reg->s32_max_value = S32_MAX;
8490         } else {
8491                 dst_reg->s32_min_value += smin_val;
8492                 dst_reg->s32_max_value += smax_val;
8493         }
8494         if (dst_reg->u32_min_value + umin_val < umin_val ||
8495             dst_reg->u32_max_value + umax_val < umax_val) {
8496                 dst_reg->u32_min_value = 0;
8497                 dst_reg->u32_max_value = U32_MAX;
8498         } else {
8499                 dst_reg->u32_min_value += umin_val;
8500                 dst_reg->u32_max_value += umax_val;
8501         }
8502 }
8503
8504 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
8505                                struct bpf_reg_state *src_reg)
8506 {
8507         s64 smin_val = src_reg->smin_value;
8508         s64 smax_val = src_reg->smax_value;
8509         u64 umin_val = src_reg->umin_value;
8510         u64 umax_val = src_reg->umax_value;
8511
8512         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
8513             signed_add_overflows(dst_reg->smax_value, smax_val)) {
8514                 dst_reg->smin_value = S64_MIN;
8515                 dst_reg->smax_value = S64_MAX;
8516         } else {
8517                 dst_reg->smin_value += smin_val;
8518                 dst_reg->smax_value += smax_val;
8519         }
8520         if (dst_reg->umin_value + umin_val < umin_val ||
8521             dst_reg->umax_value + umax_val < umax_val) {
8522                 dst_reg->umin_value = 0;
8523                 dst_reg->umax_value = U64_MAX;
8524         } else {
8525                 dst_reg->umin_value += umin_val;
8526                 dst_reg->umax_value += umax_val;
8527         }
8528 }
8529
8530 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
8531                                  struct bpf_reg_state *src_reg)
8532 {
8533         s32 smin_val = src_reg->s32_min_value;
8534         s32 smax_val = src_reg->s32_max_value;
8535         u32 umin_val = src_reg->u32_min_value;
8536         u32 umax_val = src_reg->u32_max_value;
8537
8538         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
8539             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
8540                 /* Overflow possible, we know nothing */
8541                 dst_reg->s32_min_value = S32_MIN;
8542                 dst_reg->s32_max_value = S32_MAX;
8543         } else {
8544                 dst_reg->s32_min_value -= smax_val;
8545                 dst_reg->s32_max_value -= smin_val;
8546         }
8547         if (dst_reg->u32_min_value < umax_val) {
8548                 /* Overflow possible, we know nothing */
8549                 dst_reg->u32_min_value = 0;
8550                 dst_reg->u32_max_value = U32_MAX;
8551         } else {
8552                 /* Cannot overflow (as long as bounds are consistent) */
8553                 dst_reg->u32_min_value -= umax_val;
8554                 dst_reg->u32_max_value -= umin_val;
8555         }
8556 }
8557
8558 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
8559                                struct bpf_reg_state *src_reg)
8560 {
8561         s64 smin_val = src_reg->smin_value;
8562         s64 smax_val = src_reg->smax_value;
8563         u64 umin_val = src_reg->umin_value;
8564         u64 umax_val = src_reg->umax_value;
8565
8566         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
8567             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
8568                 /* Overflow possible, we know nothing */
8569                 dst_reg->smin_value = S64_MIN;
8570                 dst_reg->smax_value = S64_MAX;
8571         } else {
8572                 dst_reg->smin_value -= smax_val;
8573                 dst_reg->smax_value -= smin_val;
8574         }
8575         if (dst_reg->umin_value < umax_val) {
8576                 /* Overflow possible, we know nothing */
8577                 dst_reg->umin_value = 0;
8578                 dst_reg->umax_value = U64_MAX;
8579         } else {
8580                 /* Cannot overflow (as long as bounds are consistent) */
8581                 dst_reg->umin_value -= umax_val;
8582                 dst_reg->umax_value -= umin_val;
8583         }
8584 }
8585
8586 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
8587                                  struct bpf_reg_state *src_reg)
8588 {
8589         s32 smin_val = src_reg->s32_min_value;
8590         u32 umin_val = src_reg->u32_min_value;
8591         u32 umax_val = src_reg->u32_max_value;
8592
8593         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
8594                 /* Ain't nobody got time to multiply that sign */
8595                 __mark_reg32_unbounded(dst_reg);
8596                 return;
8597         }
8598         /* Both values are positive, so we can work with unsigned and
8599          * copy the result to signed (unless it exceeds S32_MAX).
8600          */
8601         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
8602                 /* Potential overflow, we know nothing */
8603                 __mark_reg32_unbounded(dst_reg);
8604                 return;
8605         }
8606         dst_reg->u32_min_value *= umin_val;
8607         dst_reg->u32_max_value *= umax_val;
8608         if (dst_reg->u32_max_value > S32_MAX) {
8609                 /* Overflow possible, we know nothing */
8610                 dst_reg->s32_min_value = S32_MIN;
8611                 dst_reg->s32_max_value = S32_MAX;
8612         } else {
8613                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8614                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8615         }
8616 }
8617
8618 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
8619                                struct bpf_reg_state *src_reg)
8620 {
8621         s64 smin_val = src_reg->smin_value;
8622         u64 umin_val = src_reg->umin_value;
8623         u64 umax_val = src_reg->umax_value;
8624
8625         if (smin_val < 0 || dst_reg->smin_value < 0) {
8626                 /* Ain't nobody got time to multiply that sign */
8627                 __mark_reg64_unbounded(dst_reg);
8628                 return;
8629         }
8630         /* Both values are positive, so we can work with unsigned and
8631          * copy the result to signed (unless it exceeds S64_MAX).
8632          */
8633         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
8634                 /* Potential overflow, we know nothing */
8635                 __mark_reg64_unbounded(dst_reg);
8636                 return;
8637         }
8638         dst_reg->umin_value *= umin_val;
8639         dst_reg->umax_value *= umax_val;
8640         if (dst_reg->umax_value > S64_MAX) {
8641                 /* Overflow possible, we know nothing */
8642                 dst_reg->smin_value = S64_MIN;
8643                 dst_reg->smax_value = S64_MAX;
8644         } else {
8645                 dst_reg->smin_value = dst_reg->umin_value;
8646                 dst_reg->smax_value = dst_reg->umax_value;
8647         }
8648 }
8649
8650 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
8651                                  struct bpf_reg_state *src_reg)
8652 {
8653         bool src_known = tnum_subreg_is_const(src_reg->var_off);
8654         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8655         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8656         s32 smin_val = src_reg->s32_min_value;
8657         u32 umax_val = src_reg->u32_max_value;
8658
8659         if (src_known && dst_known) {
8660                 __mark_reg32_known(dst_reg, var32_off.value);
8661                 return;
8662         }
8663
8664         /* We get our minimum from the var_off, since that's inherently
8665          * bitwise.  Our maximum is the minimum of the operands' maxima.
8666          */
8667         dst_reg->u32_min_value = var32_off.value;
8668         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
8669         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8670                 /* Lose signed bounds when ANDing negative numbers,
8671                  * ain't nobody got time for that.
8672                  */
8673                 dst_reg->s32_min_value = S32_MIN;
8674                 dst_reg->s32_max_value = S32_MAX;
8675         } else {
8676                 /* ANDing two positives gives a positive, so safe to
8677                  * cast result into s64.
8678                  */
8679                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8680                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8681         }
8682 }
8683
8684 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
8685                                struct bpf_reg_state *src_reg)
8686 {
8687         bool src_known = tnum_is_const(src_reg->var_off);
8688         bool dst_known = tnum_is_const(dst_reg->var_off);
8689         s64 smin_val = src_reg->smin_value;
8690         u64 umax_val = src_reg->umax_value;
8691
8692         if (src_known && dst_known) {
8693                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8694                 return;
8695         }
8696
8697         /* We get our minimum from the var_off, since that's inherently
8698          * bitwise.  Our maximum is the minimum of the operands' maxima.
8699          */
8700         dst_reg->umin_value = dst_reg->var_off.value;
8701         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
8702         if (dst_reg->smin_value < 0 || smin_val < 0) {
8703                 /* Lose signed bounds when ANDing negative numbers,
8704                  * ain't nobody got time for that.
8705                  */
8706                 dst_reg->smin_value = S64_MIN;
8707                 dst_reg->smax_value = S64_MAX;
8708         } else {
8709                 /* ANDing two positives gives a positive, so safe to
8710                  * cast result into s64.
8711                  */
8712                 dst_reg->smin_value = dst_reg->umin_value;
8713                 dst_reg->smax_value = dst_reg->umax_value;
8714         }
8715         /* We may learn something more from the var_off */
8716         __update_reg_bounds(dst_reg);
8717 }
8718
8719 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
8720                                 struct bpf_reg_state *src_reg)
8721 {
8722         bool src_known = tnum_subreg_is_const(src_reg->var_off);
8723         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8724         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8725         s32 smin_val = src_reg->s32_min_value;
8726         u32 umin_val = src_reg->u32_min_value;
8727
8728         if (src_known && dst_known) {
8729                 __mark_reg32_known(dst_reg, var32_off.value);
8730                 return;
8731         }
8732
8733         /* We get our maximum from the var_off, and our minimum is the
8734          * maximum of the operands' minima
8735          */
8736         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
8737         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8738         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8739                 /* Lose signed bounds when ORing negative numbers,
8740                  * ain't nobody got time for that.
8741                  */
8742                 dst_reg->s32_min_value = S32_MIN;
8743                 dst_reg->s32_max_value = S32_MAX;
8744         } else {
8745                 /* ORing two positives gives a positive, so safe to
8746                  * cast result into s64.
8747                  */
8748                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8749                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8750         }
8751 }
8752
8753 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
8754                               struct bpf_reg_state *src_reg)
8755 {
8756         bool src_known = tnum_is_const(src_reg->var_off);
8757         bool dst_known = tnum_is_const(dst_reg->var_off);
8758         s64 smin_val = src_reg->smin_value;
8759         u64 umin_val = src_reg->umin_value;
8760
8761         if (src_known && dst_known) {
8762                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8763                 return;
8764         }
8765
8766         /* We get our maximum from the var_off, and our minimum is the
8767          * maximum of the operands' minima
8768          */
8769         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
8770         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8771         if (dst_reg->smin_value < 0 || smin_val < 0) {
8772                 /* Lose signed bounds when ORing negative numbers,
8773                  * ain't nobody got time for that.
8774                  */
8775                 dst_reg->smin_value = S64_MIN;
8776                 dst_reg->smax_value = S64_MAX;
8777         } else {
8778                 /* ORing two positives gives a positive, so safe to
8779                  * cast result into s64.
8780                  */
8781                 dst_reg->smin_value = dst_reg->umin_value;
8782                 dst_reg->smax_value = dst_reg->umax_value;
8783         }
8784         /* We may learn something more from the var_off */
8785         __update_reg_bounds(dst_reg);
8786 }
8787
8788 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
8789                                  struct bpf_reg_state *src_reg)
8790 {
8791         bool src_known = tnum_subreg_is_const(src_reg->var_off);
8792         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8793         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8794         s32 smin_val = src_reg->s32_min_value;
8795
8796         if (src_known && dst_known) {
8797                 __mark_reg32_known(dst_reg, var32_off.value);
8798                 return;
8799         }
8800
8801         /* We get both minimum and maximum from the var32_off. */
8802         dst_reg->u32_min_value = var32_off.value;
8803         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8804
8805         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8806                 /* XORing two positive sign numbers gives a positive,
8807                  * so safe to cast u32 result into s32.
8808                  */
8809                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8810                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8811         } else {
8812                 dst_reg->s32_min_value = S32_MIN;
8813                 dst_reg->s32_max_value = S32_MAX;
8814         }
8815 }
8816
8817 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8818                                struct bpf_reg_state *src_reg)
8819 {
8820         bool src_known = tnum_is_const(src_reg->var_off);
8821         bool dst_known = tnum_is_const(dst_reg->var_off);
8822         s64 smin_val = src_reg->smin_value;
8823
8824         if (src_known && dst_known) {
8825                 /* dst_reg->var_off.value has been updated earlier */
8826                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8827                 return;
8828         }
8829
8830         /* We get both minimum and maximum from the var_off. */
8831         dst_reg->umin_value = dst_reg->var_off.value;
8832         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8833
8834         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8835                 /* XORing two positive sign numbers gives a positive,
8836                  * so safe to cast u64 result into s64.
8837                  */
8838                 dst_reg->smin_value = dst_reg->umin_value;
8839                 dst_reg->smax_value = dst_reg->umax_value;
8840         } else {
8841                 dst_reg->smin_value = S64_MIN;
8842                 dst_reg->smax_value = S64_MAX;
8843         }
8844
8845         __update_reg_bounds(dst_reg);
8846 }
8847
8848 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8849                                    u64 umin_val, u64 umax_val)
8850 {
8851         /* We lose all sign bit information (except what we can pick
8852          * up from var_off)
8853          */
8854         dst_reg->s32_min_value = S32_MIN;
8855         dst_reg->s32_max_value = S32_MAX;
8856         /* If we might shift our top bit out, then we know nothing */
8857         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8858                 dst_reg->u32_min_value = 0;
8859                 dst_reg->u32_max_value = U32_MAX;
8860         } else {
8861                 dst_reg->u32_min_value <<= umin_val;
8862                 dst_reg->u32_max_value <<= umax_val;
8863         }
8864 }
8865
8866 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8867                                  struct bpf_reg_state *src_reg)
8868 {
8869         u32 umax_val = src_reg->u32_max_value;
8870         u32 umin_val = src_reg->u32_min_value;
8871         /* u32 alu operation will zext upper bits */
8872         struct tnum subreg = tnum_subreg(dst_reg->var_off);
8873
8874         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8875         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8876         /* Not required but being careful mark reg64 bounds as unknown so
8877          * that we are forced to pick them up from tnum and zext later and
8878          * if some path skips this step we are still safe.
8879          */
8880         __mark_reg64_unbounded(dst_reg);
8881         __update_reg32_bounds(dst_reg);
8882 }
8883
8884 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8885                                    u64 umin_val, u64 umax_val)
8886 {
8887         /* Special case <<32 because it is a common compiler pattern to sign
8888          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8889          * positive we know this shift will also be positive so we can track
8890          * bounds correctly. Otherwise we lose all sign bit information except
8891          * what we can pick up from var_off. Perhaps we can generalize this
8892          * later to shifts of any length.
8893          */
8894         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8895                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8896         else
8897                 dst_reg->smax_value = S64_MAX;
8898
8899         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8900                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8901         else
8902                 dst_reg->smin_value = S64_MIN;
8903
8904         /* If we might shift our top bit out, then we know nothing */
8905         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8906                 dst_reg->umin_value = 0;
8907                 dst_reg->umax_value = U64_MAX;
8908         } else {
8909                 dst_reg->umin_value <<= umin_val;
8910                 dst_reg->umax_value <<= umax_val;
8911         }
8912 }
8913
8914 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8915                                struct bpf_reg_state *src_reg)
8916 {
8917         u64 umax_val = src_reg->umax_value;
8918         u64 umin_val = src_reg->umin_value;
8919
8920         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
8921         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8922         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8923
8924         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
8925         /* We may learn something more from the var_off */
8926         __update_reg_bounds(dst_reg);
8927 }
8928
8929 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
8930                                  struct bpf_reg_state *src_reg)
8931 {
8932         struct tnum subreg = tnum_subreg(dst_reg->var_off);
8933         u32 umax_val = src_reg->u32_max_value;
8934         u32 umin_val = src_reg->u32_min_value;
8935
8936         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8937          * be negative, then either:
8938          * 1) src_reg might be zero, so the sign bit of the result is
8939          *    unknown, so we lose our signed bounds
8940          * 2) it's known negative, thus the unsigned bounds capture the
8941          *    signed bounds
8942          * 3) the signed bounds cross zero, so they tell us nothing
8943          *    about the result
8944          * If the value in dst_reg is known nonnegative, then again the
8945          * unsigned bounds capture the signed bounds.
8946          * Thus, in all cases it suffices to blow away our signed bounds
8947          * and rely on inferring new ones from the unsigned bounds and
8948          * var_off of the result.
8949          */
8950         dst_reg->s32_min_value = S32_MIN;
8951         dst_reg->s32_max_value = S32_MAX;
8952
8953         dst_reg->var_off = tnum_rshift(subreg, umin_val);
8954         dst_reg->u32_min_value >>= umax_val;
8955         dst_reg->u32_max_value >>= umin_val;
8956
8957         __mark_reg64_unbounded(dst_reg);
8958         __update_reg32_bounds(dst_reg);
8959 }
8960
8961 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
8962                                struct bpf_reg_state *src_reg)
8963 {
8964         u64 umax_val = src_reg->umax_value;
8965         u64 umin_val = src_reg->umin_value;
8966
8967         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8968          * be negative, then either:
8969          * 1) src_reg might be zero, so the sign bit of the result is
8970          *    unknown, so we lose our signed bounds
8971          * 2) it's known negative, thus the unsigned bounds capture the
8972          *    signed bounds
8973          * 3) the signed bounds cross zero, so they tell us nothing
8974          *    about the result
8975          * If the value in dst_reg is known nonnegative, then again the
8976          * unsigned bounds capture the signed bounds.
8977          * Thus, in all cases it suffices to blow away our signed bounds
8978          * and rely on inferring new ones from the unsigned bounds and
8979          * var_off of the result.
8980          */
8981         dst_reg->smin_value = S64_MIN;
8982         dst_reg->smax_value = S64_MAX;
8983         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8984         dst_reg->umin_value >>= umax_val;
8985         dst_reg->umax_value >>= umin_val;
8986
8987         /* Its not easy to operate on alu32 bounds here because it depends
8988          * on bits being shifted in. Take easy way out and mark unbounded
8989          * so we can recalculate later from tnum.
8990          */
8991         __mark_reg32_unbounded(dst_reg);
8992         __update_reg_bounds(dst_reg);
8993 }
8994
8995 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
8996                                   struct bpf_reg_state *src_reg)
8997 {
8998         u64 umin_val = src_reg->u32_min_value;
8999
9000         /* Upon reaching here, src_known is true and
9001          * umax_val is equal to umin_val.
9002          */
9003         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
9004         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
9005
9006         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
9007
9008         /* blow away the dst_reg umin_value/umax_value and rely on
9009          * dst_reg var_off to refine the result.
9010          */
9011         dst_reg->u32_min_value = 0;
9012         dst_reg->u32_max_value = U32_MAX;
9013
9014         __mark_reg64_unbounded(dst_reg);
9015         __update_reg32_bounds(dst_reg);
9016 }
9017
9018 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
9019                                 struct bpf_reg_state *src_reg)
9020 {
9021         u64 umin_val = src_reg->umin_value;
9022
9023         /* Upon reaching here, src_known is true and umax_val is equal
9024          * to umin_val.
9025          */
9026         dst_reg->smin_value >>= umin_val;
9027         dst_reg->smax_value >>= umin_val;
9028
9029         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
9030
9031         /* blow away the dst_reg umin_value/umax_value and rely on
9032          * dst_reg var_off to refine the result.
9033          */
9034         dst_reg->umin_value = 0;
9035         dst_reg->umax_value = U64_MAX;
9036
9037         /* Its not easy to operate on alu32 bounds here because it depends
9038          * on bits being shifted in from upper 32-bits. Take easy way out
9039          * and mark unbounded so we can recalculate later from tnum.
9040          */
9041         __mark_reg32_unbounded(dst_reg);
9042         __update_reg_bounds(dst_reg);
9043 }
9044
9045 /* WARNING: This function does calculations on 64-bit values, but the actual
9046  * execution may occur on 32-bit values. Therefore, things like bitshifts
9047  * need extra checks in the 32-bit case.
9048  */
9049 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
9050                                       struct bpf_insn *insn,
9051                                       struct bpf_reg_state *dst_reg,
9052                                       struct bpf_reg_state src_reg)
9053 {
9054         struct bpf_reg_state *regs = cur_regs(env);
9055         u8 opcode = BPF_OP(insn->code);
9056         bool src_known;
9057         s64 smin_val, smax_val;
9058         u64 umin_val, umax_val;
9059         s32 s32_min_val, s32_max_val;
9060         u32 u32_min_val, u32_max_val;
9061         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
9062         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
9063         int ret;
9064
9065         smin_val = src_reg.smin_value;
9066         smax_val = src_reg.smax_value;
9067         umin_val = src_reg.umin_value;
9068         umax_val = src_reg.umax_value;
9069
9070         s32_min_val = src_reg.s32_min_value;
9071         s32_max_val = src_reg.s32_max_value;
9072         u32_min_val = src_reg.u32_min_value;
9073         u32_max_val = src_reg.u32_max_value;
9074
9075         if (alu32) {
9076                 src_known = tnum_subreg_is_const(src_reg.var_off);
9077                 if ((src_known &&
9078                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
9079                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
9080                         /* Taint dst register if offset had invalid bounds
9081                          * derived from e.g. dead branches.
9082                          */
9083                         __mark_reg_unknown(env, dst_reg);
9084                         return 0;
9085                 }
9086         } else {
9087                 src_known = tnum_is_const(src_reg.var_off);
9088                 if ((src_known &&
9089                      (smin_val != smax_val || umin_val != umax_val)) ||
9090                     smin_val > smax_val || umin_val > umax_val) {
9091                         /* Taint dst register if offset had invalid bounds
9092                          * derived from e.g. dead branches.
9093                          */
9094                         __mark_reg_unknown(env, dst_reg);
9095                         return 0;
9096                 }
9097         }
9098
9099         if (!src_known &&
9100             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
9101                 __mark_reg_unknown(env, dst_reg);
9102                 return 0;
9103         }
9104
9105         if (sanitize_needed(opcode)) {
9106                 ret = sanitize_val_alu(env, insn);
9107                 if (ret < 0)
9108                         return sanitize_err(env, insn, ret, NULL, NULL);
9109         }
9110
9111         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
9112          * There are two classes of instructions: The first class we track both
9113          * alu32 and alu64 sign/unsigned bounds independently this provides the
9114          * greatest amount of precision when alu operations are mixed with jmp32
9115          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
9116          * and BPF_OR. This is possible because these ops have fairly easy to
9117          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
9118          * See alu32 verifier tests for examples. The second class of
9119          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
9120          * with regards to tracking sign/unsigned bounds because the bits may
9121          * cross subreg boundaries in the alu64 case. When this happens we mark
9122          * the reg unbounded in the subreg bound space and use the resulting
9123          * tnum to calculate an approximation of the sign/unsigned bounds.
9124          */
9125         switch (opcode) {
9126         case BPF_ADD:
9127                 scalar32_min_max_add(dst_reg, &src_reg);
9128                 scalar_min_max_add(dst_reg, &src_reg);
9129                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
9130                 break;
9131         case BPF_SUB:
9132                 scalar32_min_max_sub(dst_reg, &src_reg);
9133                 scalar_min_max_sub(dst_reg, &src_reg);
9134                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
9135                 break;
9136         case BPF_MUL:
9137                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
9138                 scalar32_min_max_mul(dst_reg, &src_reg);
9139                 scalar_min_max_mul(dst_reg, &src_reg);
9140                 break;
9141         case BPF_AND:
9142                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
9143                 scalar32_min_max_and(dst_reg, &src_reg);
9144                 scalar_min_max_and(dst_reg, &src_reg);
9145                 break;
9146         case BPF_OR:
9147                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
9148                 scalar32_min_max_or(dst_reg, &src_reg);
9149                 scalar_min_max_or(dst_reg, &src_reg);
9150                 break;
9151         case BPF_XOR:
9152                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
9153                 scalar32_min_max_xor(dst_reg, &src_reg);
9154                 scalar_min_max_xor(dst_reg, &src_reg);
9155                 break;
9156         case BPF_LSH:
9157                 if (umax_val >= insn_bitness) {
9158                         /* Shifts greater than 31 or 63 are undefined.
9159                          * This includes shifts by a negative number.
9160                          */
9161                         mark_reg_unknown(env, regs, insn->dst_reg);
9162                         break;
9163                 }
9164                 if (alu32)
9165                         scalar32_min_max_lsh(dst_reg, &src_reg);
9166                 else
9167                         scalar_min_max_lsh(dst_reg, &src_reg);
9168                 break;
9169         case BPF_RSH:
9170                 if (umax_val >= insn_bitness) {
9171                         /* Shifts greater than 31 or 63 are undefined.
9172                          * This includes shifts by a negative number.
9173                          */
9174                         mark_reg_unknown(env, regs, insn->dst_reg);
9175                         break;
9176                 }
9177                 if (alu32)
9178                         scalar32_min_max_rsh(dst_reg, &src_reg);
9179                 else
9180                         scalar_min_max_rsh(dst_reg, &src_reg);
9181                 break;
9182         case BPF_ARSH:
9183                 if (umax_val >= insn_bitness) {
9184                         /* Shifts greater than 31 or 63 are undefined.
9185                          * This includes shifts by a negative number.
9186                          */
9187                         mark_reg_unknown(env, regs, insn->dst_reg);
9188                         break;
9189                 }
9190                 if (alu32)
9191                         scalar32_min_max_arsh(dst_reg, &src_reg);
9192                 else
9193                         scalar_min_max_arsh(dst_reg, &src_reg);
9194                 break;
9195         default:
9196                 mark_reg_unknown(env, regs, insn->dst_reg);
9197                 break;
9198         }
9199
9200         /* ALU32 ops are zero extended into 64bit register */
9201         if (alu32)
9202                 zext_32_to_64(dst_reg);
9203         reg_bounds_sync(dst_reg);
9204         return 0;
9205 }
9206
9207 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
9208  * and var_off.
9209  */
9210 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
9211                                    struct bpf_insn *insn)
9212 {
9213         struct bpf_verifier_state *vstate = env->cur_state;
9214         struct bpf_func_state *state = vstate->frame[vstate->curframe];
9215         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
9216         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
9217         u8 opcode = BPF_OP(insn->code);
9218         int err;
9219
9220         dst_reg = &regs[insn->dst_reg];
9221         src_reg = NULL;
9222         if (dst_reg->type != SCALAR_VALUE)
9223                 ptr_reg = dst_reg;
9224         else
9225                 /* Make sure ID is cleared otherwise dst_reg min/max could be
9226                  * incorrectly propagated into other registers by find_equal_scalars()
9227                  */
9228                 dst_reg->id = 0;
9229         if (BPF_SRC(insn->code) == BPF_X) {
9230                 src_reg = &regs[insn->src_reg];
9231                 if (src_reg->type != SCALAR_VALUE) {
9232                         if (dst_reg->type != SCALAR_VALUE) {
9233                                 /* Combining two pointers by any ALU op yields
9234                                  * an arbitrary scalar. Disallow all math except
9235                                  * pointer subtraction
9236                                  */
9237                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9238                                         mark_reg_unknown(env, regs, insn->dst_reg);
9239                                         return 0;
9240                                 }
9241                                 verbose(env, "R%d pointer %s pointer prohibited\n",
9242                                         insn->dst_reg,
9243                                         bpf_alu_string[opcode >> 4]);
9244                                 return -EACCES;
9245                         } else {
9246                                 /* scalar += pointer
9247                                  * This is legal, but we have to reverse our
9248                                  * src/dest handling in computing the range
9249                                  */
9250                                 err = mark_chain_precision(env, insn->dst_reg);
9251                                 if (err)
9252                                         return err;
9253                                 return adjust_ptr_min_max_vals(env, insn,
9254                                                                src_reg, dst_reg);
9255                         }
9256                 } else if (ptr_reg) {
9257                         /* pointer += scalar */
9258                         err = mark_chain_precision(env, insn->src_reg);
9259                         if (err)
9260                                 return err;
9261                         return adjust_ptr_min_max_vals(env, insn,
9262                                                        dst_reg, src_reg);
9263                 } else if (dst_reg->precise) {
9264                         /* if dst_reg is precise, src_reg should be precise as well */
9265                         err = mark_chain_precision(env, insn->src_reg);
9266                         if (err)
9267                                 return err;
9268                 }
9269         } else {
9270                 /* Pretend the src is a reg with a known value, since we only
9271                  * need to be able to read from this state.
9272                  */
9273                 off_reg.type = SCALAR_VALUE;
9274                 __mark_reg_known(&off_reg, insn->imm);
9275                 src_reg = &off_reg;
9276                 if (ptr_reg) /* pointer += K */
9277                         return adjust_ptr_min_max_vals(env, insn,
9278                                                        ptr_reg, src_reg);
9279         }
9280
9281         /* Got here implies adding two SCALAR_VALUEs */
9282         if (WARN_ON_ONCE(ptr_reg)) {
9283                 print_verifier_state(env, state, true);
9284                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
9285                 return -EINVAL;
9286         }
9287         if (WARN_ON(!src_reg)) {
9288                 print_verifier_state(env, state, true);
9289                 verbose(env, "verifier internal error: no src_reg\n");
9290                 return -EINVAL;
9291         }
9292         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
9293 }
9294
9295 /* check validity of 32-bit and 64-bit arithmetic operations */
9296 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
9297 {
9298         struct bpf_reg_state *regs = cur_regs(env);
9299         u8 opcode = BPF_OP(insn->code);
9300         int err;
9301
9302         if (opcode == BPF_END || opcode == BPF_NEG) {
9303                 if (opcode == BPF_NEG) {
9304                         if (BPF_SRC(insn->code) != BPF_K ||
9305                             insn->src_reg != BPF_REG_0 ||
9306                             insn->off != 0 || insn->imm != 0) {
9307                                 verbose(env, "BPF_NEG uses reserved fields\n");
9308                                 return -EINVAL;
9309                         }
9310                 } else {
9311                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
9312                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
9313                             BPF_CLASS(insn->code) == BPF_ALU64) {
9314                                 verbose(env, "BPF_END uses reserved fields\n");
9315                                 return -EINVAL;
9316                         }
9317                 }
9318
9319                 /* check src operand */
9320                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9321                 if (err)
9322                         return err;
9323
9324                 if (is_pointer_value(env, insn->dst_reg)) {
9325                         verbose(env, "R%d pointer arithmetic prohibited\n",
9326                                 insn->dst_reg);
9327                         return -EACCES;
9328                 }
9329
9330                 /* check dest operand */
9331                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
9332                 if (err)
9333                         return err;
9334
9335         } else if (opcode == BPF_MOV) {
9336
9337                 if (BPF_SRC(insn->code) == BPF_X) {
9338                         if (insn->imm != 0 || insn->off != 0) {
9339                                 verbose(env, "BPF_MOV uses reserved fields\n");
9340                                 return -EINVAL;
9341                         }
9342
9343                         /* check src operand */
9344                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
9345                         if (err)
9346                                 return err;
9347                 } else {
9348                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9349                                 verbose(env, "BPF_MOV uses reserved fields\n");
9350                                 return -EINVAL;
9351                         }
9352                 }
9353
9354                 /* check dest operand, mark as required later */
9355                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9356                 if (err)
9357                         return err;
9358
9359                 if (BPF_SRC(insn->code) == BPF_X) {
9360                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
9361                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
9362
9363                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
9364                                 /* case: R1 = R2
9365                                  * copy register state to dest reg
9366                                  */
9367                                 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
9368                                         /* Assign src and dst registers the same ID
9369                                          * that will be used by find_equal_scalars()
9370                                          * to propagate min/max range.
9371                                          */
9372                                         src_reg->id = ++env->id_gen;
9373                                 copy_register_state(dst_reg, src_reg);
9374                                 dst_reg->live |= REG_LIVE_WRITTEN;
9375                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
9376                         } else {
9377                                 /* R1 = (u32) R2 */
9378                                 if (is_pointer_value(env, insn->src_reg)) {
9379                                         verbose(env,
9380                                                 "R%d partial copy of pointer\n",
9381                                                 insn->src_reg);
9382                                         return -EACCES;
9383                                 } else if (src_reg->type == SCALAR_VALUE) {
9384                                         copy_register_state(dst_reg, src_reg);
9385                                         /* Make sure ID is cleared otherwise
9386                                          * dst_reg min/max could be incorrectly
9387                                          * propagated into src_reg by find_equal_scalars()
9388                                          */
9389                                         dst_reg->id = 0;
9390                                         dst_reg->live |= REG_LIVE_WRITTEN;
9391                                         dst_reg->subreg_def = env->insn_idx + 1;
9392                                 } else {
9393                                         mark_reg_unknown(env, regs,
9394                                                          insn->dst_reg);
9395                                 }
9396                                 zext_32_to_64(dst_reg);
9397                                 reg_bounds_sync(dst_reg);
9398                         }
9399                 } else {
9400                         /* case: R = imm
9401                          * remember the value we stored into this reg
9402                          */
9403                         /* clear any state __mark_reg_known doesn't set */
9404                         mark_reg_unknown(env, regs, insn->dst_reg);
9405                         regs[insn->dst_reg].type = SCALAR_VALUE;
9406                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
9407                                 __mark_reg_known(regs + insn->dst_reg,
9408                                                  insn->imm);
9409                         } else {
9410                                 __mark_reg_known(regs + insn->dst_reg,
9411                                                  (u32)insn->imm);
9412                         }
9413                 }
9414
9415         } else if (opcode > BPF_END) {
9416                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
9417                 return -EINVAL;
9418
9419         } else {        /* all other ALU ops: and, sub, xor, add, ... */
9420
9421                 if (BPF_SRC(insn->code) == BPF_X) {
9422                         if (insn->imm != 0 || insn->off != 0) {
9423                                 verbose(env, "BPF_ALU uses reserved fields\n");
9424                                 return -EINVAL;
9425                         }
9426                         /* check src1 operand */
9427                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
9428                         if (err)
9429                                 return err;
9430                 } else {
9431                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9432                                 verbose(env, "BPF_ALU uses reserved fields\n");
9433                                 return -EINVAL;
9434                         }
9435                 }
9436
9437                 /* check src2 operand */
9438                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9439                 if (err)
9440                         return err;
9441
9442                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
9443                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
9444                         verbose(env, "div by zero\n");
9445                         return -EINVAL;
9446                 }
9447
9448                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
9449                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
9450                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
9451
9452                         if (insn->imm < 0 || insn->imm >= size) {
9453                                 verbose(env, "invalid shift %d\n", insn->imm);
9454                                 return -EINVAL;
9455                         }
9456                 }
9457
9458                 /* check dest operand */
9459                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9460                 if (err)
9461                         return err;
9462
9463                 return adjust_reg_min_max_vals(env, insn);
9464         }
9465
9466         return 0;
9467 }
9468
9469 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
9470                                    struct bpf_reg_state *dst_reg,
9471                                    enum bpf_reg_type type,
9472                                    bool range_right_open)
9473 {
9474         struct bpf_func_state *state;
9475         struct bpf_reg_state *reg;
9476         int new_range;
9477
9478         if (dst_reg->off < 0 ||
9479             (dst_reg->off == 0 && range_right_open))
9480                 /* This doesn't give us any range */
9481                 return;
9482
9483         if (dst_reg->umax_value > MAX_PACKET_OFF ||
9484             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
9485                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
9486                  * than pkt_end, but that's because it's also less than pkt.
9487                  */
9488                 return;
9489
9490         new_range = dst_reg->off;
9491         if (range_right_open)
9492                 new_range++;
9493
9494         /* Examples for register markings:
9495          *
9496          * pkt_data in dst register:
9497          *
9498          *   r2 = r3;
9499          *   r2 += 8;
9500          *   if (r2 > pkt_end) goto <handle exception>
9501          *   <access okay>
9502          *
9503          *   r2 = r3;
9504          *   r2 += 8;
9505          *   if (r2 < pkt_end) goto <access okay>
9506          *   <handle exception>
9507          *
9508          *   Where:
9509          *     r2 == dst_reg, pkt_end == src_reg
9510          *     r2=pkt(id=n,off=8,r=0)
9511          *     r3=pkt(id=n,off=0,r=0)
9512          *
9513          * pkt_data in src register:
9514          *
9515          *   r2 = r3;
9516          *   r2 += 8;
9517          *   if (pkt_end >= r2) goto <access okay>
9518          *   <handle exception>
9519          *
9520          *   r2 = r3;
9521          *   r2 += 8;
9522          *   if (pkt_end <= r2) goto <handle exception>
9523          *   <access okay>
9524          *
9525          *   Where:
9526          *     pkt_end == dst_reg, r2 == src_reg
9527          *     r2=pkt(id=n,off=8,r=0)
9528          *     r3=pkt(id=n,off=0,r=0)
9529          *
9530          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
9531          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
9532          * and [r3, r3 + 8-1) respectively is safe to access depending on
9533          * the check.
9534          */
9535
9536         /* If our ids match, then we must have the same max_value.  And we
9537          * don't care about the other reg's fixed offset, since if it's too big
9538          * the range won't allow anything.
9539          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
9540          */
9541         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9542                 if (reg->type == type && reg->id == dst_reg->id)
9543                         /* keep the maximum range already checked */
9544                         reg->range = max(reg->range, new_range);
9545         }));
9546 }
9547
9548 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
9549 {
9550         struct tnum subreg = tnum_subreg(reg->var_off);
9551         s32 sval = (s32)val;
9552
9553         switch (opcode) {
9554         case BPF_JEQ:
9555                 if (tnum_is_const(subreg))
9556                         return !!tnum_equals_const(subreg, val);
9557                 break;
9558         case BPF_JNE:
9559                 if (tnum_is_const(subreg))
9560                         return !tnum_equals_const(subreg, val);
9561                 break;
9562         case BPF_JSET:
9563                 if ((~subreg.mask & subreg.value) & val)
9564                         return 1;
9565                 if (!((subreg.mask | subreg.value) & val))
9566                         return 0;
9567                 break;
9568         case BPF_JGT:
9569                 if (reg->u32_min_value > val)
9570                         return 1;
9571                 else if (reg->u32_max_value <= val)
9572                         return 0;
9573                 break;
9574         case BPF_JSGT:
9575                 if (reg->s32_min_value > sval)
9576                         return 1;
9577                 else if (reg->s32_max_value <= sval)
9578                         return 0;
9579                 break;
9580         case BPF_JLT:
9581                 if (reg->u32_max_value < val)
9582                         return 1;
9583                 else if (reg->u32_min_value >= val)
9584                         return 0;
9585                 break;
9586         case BPF_JSLT:
9587                 if (reg->s32_max_value < sval)
9588                         return 1;
9589                 else if (reg->s32_min_value >= sval)
9590                         return 0;
9591                 break;
9592         case BPF_JGE:
9593                 if (reg->u32_min_value >= val)
9594                         return 1;
9595                 else if (reg->u32_max_value < val)
9596                         return 0;
9597                 break;
9598         case BPF_JSGE:
9599                 if (reg->s32_min_value >= sval)
9600                         return 1;
9601                 else if (reg->s32_max_value < sval)
9602                         return 0;
9603                 break;
9604         case BPF_JLE:
9605                 if (reg->u32_max_value <= val)
9606                         return 1;
9607                 else if (reg->u32_min_value > val)
9608                         return 0;
9609                 break;
9610         case BPF_JSLE:
9611                 if (reg->s32_max_value <= sval)
9612                         return 1;
9613                 else if (reg->s32_min_value > sval)
9614                         return 0;
9615                 break;
9616         }
9617
9618         return -1;
9619 }
9620
9621
9622 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
9623 {
9624         s64 sval = (s64)val;
9625
9626         switch (opcode) {
9627         case BPF_JEQ:
9628                 if (tnum_is_const(reg->var_off))
9629                         return !!tnum_equals_const(reg->var_off, val);
9630                 break;
9631         case BPF_JNE:
9632                 if (tnum_is_const(reg->var_off))
9633                         return !tnum_equals_const(reg->var_off, val);
9634                 break;
9635         case BPF_JSET:
9636                 if ((~reg->var_off.mask & reg->var_off.value) & val)
9637                         return 1;
9638                 if (!((reg->var_off.mask | reg->var_off.value) & val))
9639                         return 0;
9640                 break;
9641         case BPF_JGT:
9642                 if (reg->umin_value > val)
9643                         return 1;
9644                 else if (reg->umax_value <= val)
9645                         return 0;
9646                 break;
9647         case BPF_JSGT:
9648                 if (reg->smin_value > sval)
9649                         return 1;
9650                 else if (reg->smax_value <= sval)
9651                         return 0;
9652                 break;
9653         case BPF_JLT:
9654                 if (reg->umax_value < val)
9655                         return 1;
9656                 else if (reg->umin_value >= val)
9657                         return 0;
9658                 break;
9659         case BPF_JSLT:
9660                 if (reg->smax_value < sval)
9661                         return 1;
9662                 else if (reg->smin_value >= sval)
9663                         return 0;
9664                 break;
9665         case BPF_JGE:
9666                 if (reg->umin_value >= val)
9667                         return 1;
9668                 else if (reg->umax_value < val)
9669                         return 0;
9670                 break;
9671         case BPF_JSGE:
9672                 if (reg->smin_value >= sval)
9673                         return 1;
9674                 else if (reg->smax_value < sval)
9675                         return 0;
9676                 break;
9677         case BPF_JLE:
9678                 if (reg->umax_value <= val)
9679                         return 1;
9680                 else if (reg->umin_value > val)
9681                         return 0;
9682                 break;
9683         case BPF_JSLE:
9684                 if (reg->smax_value <= sval)
9685                         return 1;
9686                 else if (reg->smin_value > sval)
9687                         return 0;
9688                 break;
9689         }
9690
9691         return -1;
9692 }
9693
9694 /* compute branch direction of the expression "if (reg opcode val) goto target;"
9695  * and return:
9696  *  1 - branch will be taken and "goto target" will be executed
9697  *  0 - branch will not be taken and fall-through to next insn
9698  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
9699  *      range [0,10]
9700  */
9701 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
9702                            bool is_jmp32)
9703 {
9704         if (__is_pointer_value(false, reg)) {
9705                 if (!reg_type_not_null(reg->type))
9706                         return -1;
9707
9708                 /* If pointer is valid tests against zero will fail so we can
9709                  * use this to direct branch taken.
9710                  */
9711                 if (val != 0)
9712                         return -1;
9713
9714                 switch (opcode) {
9715                 case BPF_JEQ:
9716                         return 0;
9717                 case BPF_JNE:
9718                         return 1;
9719                 default:
9720                         return -1;
9721                 }
9722         }
9723
9724         if (is_jmp32)
9725                 return is_branch32_taken(reg, val, opcode);
9726         return is_branch64_taken(reg, val, opcode);
9727 }
9728
9729 static int flip_opcode(u32 opcode)
9730 {
9731         /* How can we transform "a <op> b" into "b <op> a"? */
9732         static const u8 opcode_flip[16] = {
9733                 /* these stay the same */
9734                 [BPF_JEQ  >> 4] = BPF_JEQ,
9735                 [BPF_JNE  >> 4] = BPF_JNE,
9736                 [BPF_JSET >> 4] = BPF_JSET,
9737                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
9738                 [BPF_JGE  >> 4] = BPF_JLE,
9739                 [BPF_JGT  >> 4] = BPF_JLT,
9740                 [BPF_JLE  >> 4] = BPF_JGE,
9741                 [BPF_JLT  >> 4] = BPF_JGT,
9742                 [BPF_JSGE >> 4] = BPF_JSLE,
9743                 [BPF_JSGT >> 4] = BPF_JSLT,
9744                 [BPF_JSLE >> 4] = BPF_JSGE,
9745                 [BPF_JSLT >> 4] = BPF_JSGT
9746         };
9747         return opcode_flip[opcode >> 4];
9748 }
9749
9750 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
9751                                    struct bpf_reg_state *src_reg,
9752                                    u8 opcode)
9753 {
9754         struct bpf_reg_state *pkt;
9755
9756         if (src_reg->type == PTR_TO_PACKET_END) {
9757                 pkt = dst_reg;
9758         } else if (dst_reg->type == PTR_TO_PACKET_END) {
9759                 pkt = src_reg;
9760                 opcode = flip_opcode(opcode);
9761         } else {
9762                 return -1;
9763         }
9764
9765         if (pkt->range >= 0)
9766                 return -1;
9767
9768         switch (opcode) {
9769         case BPF_JLE:
9770                 /* pkt <= pkt_end */
9771                 fallthrough;
9772         case BPF_JGT:
9773                 /* pkt > pkt_end */
9774                 if (pkt->range == BEYOND_PKT_END)
9775                         /* pkt has at last one extra byte beyond pkt_end */
9776                         return opcode == BPF_JGT;
9777                 break;
9778         case BPF_JLT:
9779                 /* pkt < pkt_end */
9780                 fallthrough;
9781         case BPF_JGE:
9782                 /* pkt >= pkt_end */
9783                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9784                         return opcode == BPF_JGE;
9785                 break;
9786         }
9787         return -1;
9788 }
9789
9790 /* Adjusts the register min/max values in the case that the dst_reg is the
9791  * variable register that we are working on, and src_reg is a constant or we're
9792  * simply doing a BPF_K check.
9793  * In JEQ/JNE cases we also adjust the var_off values.
9794  */
9795 static void reg_set_min_max(struct bpf_reg_state *true_reg,
9796                             struct bpf_reg_state *false_reg,
9797                             u64 val, u32 val32,
9798                             u8 opcode, bool is_jmp32)
9799 {
9800         struct tnum false_32off = tnum_subreg(false_reg->var_off);
9801         struct tnum false_64off = false_reg->var_off;
9802         struct tnum true_32off = tnum_subreg(true_reg->var_off);
9803         struct tnum true_64off = true_reg->var_off;
9804         s64 sval = (s64)val;
9805         s32 sval32 = (s32)val32;
9806
9807         /* If the dst_reg is a pointer, we can't learn anything about its
9808          * variable offset from the compare (unless src_reg were a pointer into
9809          * the same object, but we don't bother with that.
9810          * Since false_reg and true_reg have the same type by construction, we
9811          * only need to check one of them for pointerness.
9812          */
9813         if (__is_pointer_value(false, false_reg))
9814                 return;
9815
9816         switch (opcode) {
9817         /* JEQ/JNE comparison doesn't change the register equivalence.
9818          *
9819          * r1 = r2;
9820          * if (r1 == 42) goto label;
9821          * ...
9822          * label: // here both r1 and r2 are known to be 42.
9823          *
9824          * Hence when marking register as known preserve it's ID.
9825          */
9826         case BPF_JEQ:
9827                 if (is_jmp32) {
9828                         __mark_reg32_known(true_reg, val32);
9829                         true_32off = tnum_subreg(true_reg->var_off);
9830                 } else {
9831                         ___mark_reg_known(true_reg, val);
9832                         true_64off = true_reg->var_off;
9833                 }
9834                 break;
9835         case BPF_JNE:
9836                 if (is_jmp32) {
9837                         __mark_reg32_known(false_reg, val32);
9838                         false_32off = tnum_subreg(false_reg->var_off);
9839                 } else {
9840                         ___mark_reg_known(false_reg, val);
9841                         false_64off = false_reg->var_off;
9842                 }
9843                 break;
9844         case BPF_JSET:
9845                 if (is_jmp32) {
9846                         false_32off = tnum_and(false_32off, tnum_const(~val32));
9847                         if (is_power_of_2(val32))
9848                                 true_32off = tnum_or(true_32off,
9849                                                      tnum_const(val32));
9850                 } else {
9851                         false_64off = tnum_and(false_64off, tnum_const(~val));
9852                         if (is_power_of_2(val))
9853                                 true_64off = tnum_or(true_64off,
9854                                                      tnum_const(val));
9855                 }
9856                 break;
9857         case BPF_JGE:
9858         case BPF_JGT:
9859         {
9860                 if (is_jmp32) {
9861                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
9862                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9863
9864                         false_reg->u32_max_value = min(false_reg->u32_max_value,
9865                                                        false_umax);
9866                         true_reg->u32_min_value = max(true_reg->u32_min_value,
9867                                                       true_umin);
9868                 } else {
9869                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
9870                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9871
9872                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
9873                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
9874                 }
9875                 break;
9876         }
9877         case BPF_JSGE:
9878         case BPF_JSGT:
9879         {
9880                 if (is_jmp32) {
9881                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
9882                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
9883
9884                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9885                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9886                 } else {
9887                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
9888                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9889
9890                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
9891                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
9892                 }
9893                 break;
9894         }
9895         case BPF_JLE:
9896         case BPF_JLT:
9897         {
9898                 if (is_jmp32) {
9899                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
9900                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9901
9902                         false_reg->u32_min_value = max(false_reg->u32_min_value,
9903                                                        false_umin);
9904                         true_reg->u32_max_value = min(true_reg->u32_max_value,
9905                                                       true_umax);
9906                 } else {
9907                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
9908                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9909
9910                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
9911                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
9912                 }
9913                 break;
9914         }
9915         case BPF_JSLE:
9916         case BPF_JSLT:
9917         {
9918                 if (is_jmp32) {
9919                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
9920                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
9921
9922                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
9923                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
9924                 } else {
9925                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
9926                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
9927
9928                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
9929                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
9930                 }
9931                 break;
9932         }
9933         default:
9934                 return;
9935         }
9936
9937         if (is_jmp32) {
9938                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
9939                                              tnum_subreg(false_32off));
9940                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
9941                                             tnum_subreg(true_32off));
9942                 __reg_combine_32_into_64(false_reg);
9943                 __reg_combine_32_into_64(true_reg);
9944         } else {
9945                 false_reg->var_off = false_64off;
9946                 true_reg->var_off = true_64off;
9947                 __reg_combine_64_into_32(false_reg);
9948                 __reg_combine_64_into_32(true_reg);
9949         }
9950 }
9951
9952 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
9953  * the variable reg.
9954  */
9955 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
9956                                 struct bpf_reg_state *false_reg,
9957                                 u64 val, u32 val32,
9958                                 u8 opcode, bool is_jmp32)
9959 {
9960         opcode = flip_opcode(opcode);
9961         /* This uses zero as "not present in table"; luckily the zero opcode,
9962          * BPF_JA, can't get here.
9963          */
9964         if (opcode)
9965                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
9966 }
9967
9968 /* Regs are known to be equal, so intersect their min/max/var_off */
9969 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9970                                   struct bpf_reg_state *dst_reg)
9971 {
9972         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9973                                                         dst_reg->umin_value);
9974         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9975                                                         dst_reg->umax_value);
9976         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9977                                                         dst_reg->smin_value);
9978         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9979                                                         dst_reg->smax_value);
9980         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9981                                                              dst_reg->var_off);
9982         reg_bounds_sync(src_reg);
9983         reg_bounds_sync(dst_reg);
9984 }
9985
9986 static void reg_combine_min_max(struct bpf_reg_state *true_src,
9987                                 struct bpf_reg_state *true_dst,
9988                                 struct bpf_reg_state *false_src,
9989                                 struct bpf_reg_state *false_dst,
9990                                 u8 opcode)
9991 {
9992         switch (opcode) {
9993         case BPF_JEQ:
9994                 __reg_combine_min_max(true_src, true_dst);
9995                 break;
9996         case BPF_JNE:
9997                 __reg_combine_min_max(false_src, false_dst);
9998                 break;
9999         }
10000 }
10001
10002 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
10003                                  struct bpf_reg_state *reg, u32 id,
10004                                  bool is_null)
10005 {
10006         if (type_may_be_null(reg->type) && reg->id == id &&
10007             !WARN_ON_ONCE(!reg->id)) {
10008                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
10009                                  !tnum_equals_const(reg->var_off, 0) ||
10010                                  reg->off)) {
10011                         /* Old offset (both fixed and variable parts) should
10012                          * have been known-zero, because we don't allow pointer
10013                          * arithmetic on pointers that might be NULL. If we
10014                          * see this happening, don't convert the register.
10015                          */
10016                         return;
10017                 }
10018                 if (is_null) {
10019                         reg->type = SCALAR_VALUE;
10020                         /* We don't need id and ref_obj_id from this point
10021                          * onwards anymore, thus we should better reset it,
10022                          * so that state pruning has chances to take effect.
10023                          */
10024                         reg->id = 0;
10025                         reg->ref_obj_id = 0;
10026
10027                         return;
10028                 }
10029
10030                 mark_ptr_not_null_reg(reg);
10031
10032                 if (!reg_may_point_to_spin_lock(reg)) {
10033                         /* For not-NULL ptr, reg->ref_obj_id will be reset
10034                          * in release_reference().
10035                          *
10036                          * reg->id is still used by spin_lock ptr. Other
10037                          * than spin_lock ptr type, reg->id can be reset.
10038                          */
10039                         reg->id = 0;
10040                 }
10041         }
10042 }
10043
10044 /* The logic is similar to find_good_pkt_pointers(), both could eventually
10045  * be folded together at some point.
10046  */
10047 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
10048                                   bool is_null)
10049 {
10050         struct bpf_func_state *state = vstate->frame[vstate->curframe];
10051         struct bpf_reg_state *regs = state->regs, *reg;
10052         u32 ref_obj_id = regs[regno].ref_obj_id;
10053         u32 id = regs[regno].id;
10054
10055         if (ref_obj_id && ref_obj_id == id && is_null)
10056                 /* regs[regno] is in the " == NULL" branch.
10057                  * No one could have freed the reference state before
10058                  * doing the NULL check.
10059                  */
10060                 WARN_ON_ONCE(release_reference_state(state, id));
10061
10062         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10063                 mark_ptr_or_null_reg(state, reg, id, is_null);
10064         }));
10065 }
10066
10067 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
10068                                    struct bpf_reg_state *dst_reg,
10069                                    struct bpf_reg_state *src_reg,
10070                                    struct bpf_verifier_state *this_branch,
10071                                    struct bpf_verifier_state *other_branch)
10072 {
10073         if (BPF_SRC(insn->code) != BPF_X)
10074                 return false;
10075
10076         /* Pointers are always 64-bit. */
10077         if (BPF_CLASS(insn->code) == BPF_JMP32)
10078                 return false;
10079
10080         switch (BPF_OP(insn->code)) {
10081         case BPF_JGT:
10082                 if ((dst_reg->type == PTR_TO_PACKET &&
10083                      src_reg->type == PTR_TO_PACKET_END) ||
10084                     (dst_reg->type == PTR_TO_PACKET_META &&
10085                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10086                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
10087                         find_good_pkt_pointers(this_branch, dst_reg,
10088                                                dst_reg->type, false);
10089                         mark_pkt_end(other_branch, insn->dst_reg, true);
10090                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10091                             src_reg->type == PTR_TO_PACKET) ||
10092                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10093                             src_reg->type == PTR_TO_PACKET_META)) {
10094                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
10095                         find_good_pkt_pointers(other_branch, src_reg,
10096                                                src_reg->type, true);
10097                         mark_pkt_end(this_branch, insn->src_reg, false);
10098                 } else {
10099                         return false;
10100                 }
10101                 break;
10102         case BPF_JLT:
10103                 if ((dst_reg->type == PTR_TO_PACKET &&
10104                      src_reg->type == PTR_TO_PACKET_END) ||
10105                     (dst_reg->type == PTR_TO_PACKET_META &&
10106                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10107                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
10108                         find_good_pkt_pointers(other_branch, dst_reg,
10109                                                dst_reg->type, true);
10110                         mark_pkt_end(this_branch, insn->dst_reg, false);
10111                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10112                             src_reg->type == PTR_TO_PACKET) ||
10113                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10114                             src_reg->type == PTR_TO_PACKET_META)) {
10115                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
10116                         find_good_pkt_pointers(this_branch, src_reg,
10117                                                src_reg->type, false);
10118                         mark_pkt_end(other_branch, insn->src_reg, true);
10119                 } else {
10120                         return false;
10121                 }
10122                 break;
10123         case BPF_JGE:
10124                 if ((dst_reg->type == PTR_TO_PACKET &&
10125                      src_reg->type == PTR_TO_PACKET_END) ||
10126                     (dst_reg->type == PTR_TO_PACKET_META &&
10127                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10128                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
10129                         find_good_pkt_pointers(this_branch, dst_reg,
10130                                                dst_reg->type, true);
10131                         mark_pkt_end(other_branch, insn->dst_reg, false);
10132                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10133                             src_reg->type == PTR_TO_PACKET) ||
10134                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10135                             src_reg->type == PTR_TO_PACKET_META)) {
10136                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
10137                         find_good_pkt_pointers(other_branch, src_reg,
10138                                                src_reg->type, false);
10139                         mark_pkt_end(this_branch, insn->src_reg, true);
10140                 } else {
10141                         return false;
10142                 }
10143                 break;
10144         case BPF_JLE:
10145                 if ((dst_reg->type == PTR_TO_PACKET &&
10146                      src_reg->type == PTR_TO_PACKET_END) ||
10147                     (dst_reg->type == PTR_TO_PACKET_META &&
10148                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10149                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
10150                         find_good_pkt_pointers(other_branch, dst_reg,
10151                                                dst_reg->type, false);
10152                         mark_pkt_end(this_branch, insn->dst_reg, true);
10153                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10154                             src_reg->type == PTR_TO_PACKET) ||
10155                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10156                             src_reg->type == PTR_TO_PACKET_META)) {
10157                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
10158                         find_good_pkt_pointers(this_branch, src_reg,
10159                                                src_reg->type, true);
10160                         mark_pkt_end(other_branch, insn->src_reg, false);
10161                 } else {
10162                         return false;
10163                 }
10164                 break;
10165         default:
10166                 return false;
10167         }
10168
10169         return true;
10170 }
10171
10172 static void find_equal_scalars(struct bpf_verifier_state *vstate,
10173                                struct bpf_reg_state *known_reg)
10174 {
10175         struct bpf_func_state *state;
10176         struct bpf_reg_state *reg;
10177
10178         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10179                 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10180                         copy_register_state(reg, known_reg);
10181         }));
10182 }
10183
10184 static int check_cond_jmp_op(struct bpf_verifier_env *env,
10185                              struct bpf_insn *insn, int *insn_idx)
10186 {
10187         struct bpf_verifier_state *this_branch = env->cur_state;
10188         struct bpf_verifier_state *other_branch;
10189         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
10190         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
10191         u8 opcode = BPF_OP(insn->code);
10192         bool is_jmp32;
10193         int pred = -1;
10194         int err;
10195
10196         /* Only conditional jumps are expected to reach here. */
10197         if (opcode == BPF_JA || opcode > BPF_JSLE) {
10198                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
10199                 return -EINVAL;
10200         }
10201
10202         if (BPF_SRC(insn->code) == BPF_X) {
10203                 if (insn->imm != 0) {
10204                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10205                         return -EINVAL;
10206                 }
10207
10208                 /* check src1 operand */
10209                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10210                 if (err)
10211                         return err;
10212
10213                 if (is_pointer_value(env, insn->src_reg)) {
10214                         verbose(env, "R%d pointer comparison prohibited\n",
10215                                 insn->src_reg);
10216                         return -EACCES;
10217                 }
10218                 src_reg = &regs[insn->src_reg];
10219         } else {
10220                 if (insn->src_reg != BPF_REG_0) {
10221                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10222                         return -EINVAL;
10223                 }
10224         }
10225
10226         /* check src2 operand */
10227         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10228         if (err)
10229                 return err;
10230
10231         dst_reg = &regs[insn->dst_reg];
10232         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
10233
10234         if (BPF_SRC(insn->code) == BPF_K) {
10235                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
10236         } else if (src_reg->type == SCALAR_VALUE &&
10237                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
10238                 pred = is_branch_taken(dst_reg,
10239                                        tnum_subreg(src_reg->var_off).value,
10240                                        opcode,
10241                                        is_jmp32);
10242         } else if (src_reg->type == SCALAR_VALUE &&
10243                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
10244                 pred = is_branch_taken(dst_reg,
10245                                        src_reg->var_off.value,
10246                                        opcode,
10247                                        is_jmp32);
10248         } else if (reg_is_pkt_pointer_any(dst_reg) &&
10249                    reg_is_pkt_pointer_any(src_reg) &&
10250                    !is_jmp32) {
10251                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
10252         }
10253
10254         if (pred >= 0) {
10255                 /* If we get here with a dst_reg pointer type it is because
10256                  * above is_branch_taken() special cased the 0 comparison.
10257                  */
10258                 if (!__is_pointer_value(false, dst_reg))
10259                         err = mark_chain_precision(env, insn->dst_reg);
10260                 if (BPF_SRC(insn->code) == BPF_X && !err &&
10261                     !__is_pointer_value(false, src_reg))
10262                         err = mark_chain_precision(env, insn->src_reg);
10263                 if (err)
10264                         return err;
10265         }
10266
10267         if (pred == 1) {
10268                 /* Only follow the goto, ignore fall-through. If needed, push
10269                  * the fall-through branch for simulation under speculative
10270                  * execution.
10271                  */
10272                 if (!env->bypass_spec_v1 &&
10273                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
10274                                                *insn_idx))
10275                         return -EFAULT;
10276                 *insn_idx += insn->off;
10277                 return 0;
10278         } else if (pred == 0) {
10279                 /* Only follow the fall-through branch, since that's where the
10280                  * program will go. If needed, push the goto branch for
10281                  * simulation under speculative execution.
10282                  */
10283                 if (!env->bypass_spec_v1 &&
10284                     !sanitize_speculative_path(env, insn,
10285                                                *insn_idx + insn->off + 1,
10286                                                *insn_idx))
10287                         return -EFAULT;
10288                 return 0;
10289         }
10290
10291         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
10292                                   false);
10293         if (!other_branch)
10294                 return -EFAULT;
10295         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
10296
10297         /* detect if we are comparing against a constant value so we can adjust
10298          * our min/max values for our dst register.
10299          * this is only legit if both are scalars (or pointers to the same
10300          * object, I suppose, but we don't support that right now), because
10301          * otherwise the different base pointers mean the offsets aren't
10302          * comparable.
10303          */
10304         if (BPF_SRC(insn->code) == BPF_X) {
10305                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
10306
10307                 if (dst_reg->type == SCALAR_VALUE &&
10308                     src_reg->type == SCALAR_VALUE) {
10309                         if (tnum_is_const(src_reg->var_off) ||
10310                             (is_jmp32 &&
10311                              tnum_is_const(tnum_subreg(src_reg->var_off))))
10312                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10313                                                 dst_reg,
10314                                                 src_reg->var_off.value,
10315                                                 tnum_subreg(src_reg->var_off).value,
10316                                                 opcode, is_jmp32);
10317                         else if (tnum_is_const(dst_reg->var_off) ||
10318                                  (is_jmp32 &&
10319                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
10320                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
10321                                                     src_reg,
10322                                                     dst_reg->var_off.value,
10323                                                     tnum_subreg(dst_reg->var_off).value,
10324                                                     opcode, is_jmp32);
10325                         else if (!is_jmp32 &&
10326                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
10327                                 /* Comparing for equality, we can combine knowledge */
10328                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
10329                                                     &other_branch_regs[insn->dst_reg],
10330                                                     src_reg, dst_reg, opcode);
10331                         if (src_reg->id &&
10332                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
10333                                 find_equal_scalars(this_branch, src_reg);
10334                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
10335                         }
10336
10337                 }
10338         } else if (dst_reg->type == SCALAR_VALUE) {
10339                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10340                                         dst_reg, insn->imm, (u32)insn->imm,
10341                                         opcode, is_jmp32);
10342         }
10343
10344         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
10345             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
10346                 find_equal_scalars(this_branch, dst_reg);
10347                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
10348         }
10349
10350         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
10351          * NOTE: these optimizations below are related with pointer comparison
10352          *       which will never be JMP32.
10353          */
10354         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
10355             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
10356             type_may_be_null(dst_reg->type)) {
10357                 /* Mark all identical registers in each branch as either
10358                  * safe or unknown depending R == 0 or R != 0 conditional.
10359                  */
10360                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
10361                                       opcode == BPF_JNE);
10362                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
10363                                       opcode == BPF_JEQ);
10364         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
10365                                            this_branch, other_branch) &&
10366                    is_pointer_value(env, insn->dst_reg)) {
10367                 verbose(env, "R%d pointer comparison prohibited\n",
10368                         insn->dst_reg);
10369                 return -EACCES;
10370         }
10371         if (env->log.level & BPF_LOG_LEVEL)
10372                 print_insn_state(env, this_branch->frame[this_branch->curframe]);
10373         return 0;
10374 }
10375
10376 /* verify BPF_LD_IMM64 instruction */
10377 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
10378 {
10379         struct bpf_insn_aux_data *aux = cur_aux(env);
10380         struct bpf_reg_state *regs = cur_regs(env);
10381         struct bpf_reg_state *dst_reg;
10382         struct bpf_map *map;
10383         int err;
10384
10385         if (BPF_SIZE(insn->code) != BPF_DW) {
10386                 verbose(env, "invalid BPF_LD_IMM insn\n");
10387                 return -EINVAL;
10388         }
10389         if (insn->off != 0) {
10390                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
10391                 return -EINVAL;
10392         }
10393
10394         err = check_reg_arg(env, insn->dst_reg, DST_OP);
10395         if (err)
10396                 return err;
10397
10398         dst_reg = &regs[insn->dst_reg];
10399         if (insn->src_reg == 0) {
10400                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
10401
10402                 dst_reg->type = SCALAR_VALUE;
10403                 __mark_reg_known(&regs[insn->dst_reg], imm);
10404                 return 0;
10405         }
10406
10407         /* All special src_reg cases are listed below. From this point onwards
10408          * we either succeed and assign a corresponding dst_reg->type after
10409          * zeroing the offset, or fail and reject the program.
10410          */
10411         mark_reg_known_zero(env, regs, insn->dst_reg);
10412
10413         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
10414                 dst_reg->type = aux->btf_var.reg_type;
10415                 switch (base_type(dst_reg->type)) {
10416                 case PTR_TO_MEM:
10417                         dst_reg->mem_size = aux->btf_var.mem_size;
10418                         break;
10419                 case PTR_TO_BTF_ID:
10420                         dst_reg->btf = aux->btf_var.btf;
10421                         dst_reg->btf_id = aux->btf_var.btf_id;
10422                         break;
10423                 default:
10424                         verbose(env, "bpf verifier is misconfigured\n");
10425                         return -EFAULT;
10426                 }
10427                 return 0;
10428         }
10429
10430         if (insn->src_reg == BPF_PSEUDO_FUNC) {
10431                 struct bpf_prog_aux *aux = env->prog->aux;
10432                 u32 subprogno = find_subprog(env,
10433                                              env->insn_idx + insn->imm + 1);
10434
10435                 if (!aux->func_info) {
10436                         verbose(env, "missing btf func_info\n");
10437                         return -EINVAL;
10438                 }
10439                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
10440                         verbose(env, "callback function not static\n");
10441                         return -EINVAL;
10442                 }
10443
10444                 dst_reg->type = PTR_TO_FUNC;
10445                 dst_reg->subprogno = subprogno;
10446                 return 0;
10447         }
10448
10449         map = env->used_maps[aux->map_index];
10450         dst_reg->map_ptr = map;
10451
10452         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
10453             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
10454                 dst_reg->type = PTR_TO_MAP_VALUE;
10455                 dst_reg->off = aux->map_off;
10456                 if (map_value_has_spin_lock(map))
10457                         dst_reg->id = ++env->id_gen;
10458         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
10459                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
10460                 dst_reg->type = CONST_PTR_TO_MAP;
10461         } else {
10462                 verbose(env, "bpf verifier is misconfigured\n");
10463                 return -EINVAL;
10464         }
10465
10466         return 0;
10467 }
10468
10469 static bool may_access_skb(enum bpf_prog_type type)
10470 {
10471         switch (type) {
10472         case BPF_PROG_TYPE_SOCKET_FILTER:
10473         case BPF_PROG_TYPE_SCHED_CLS:
10474         case BPF_PROG_TYPE_SCHED_ACT:
10475                 return true;
10476         default:
10477                 return false;
10478         }
10479 }
10480
10481 /* verify safety of LD_ABS|LD_IND instructions:
10482  * - they can only appear in the programs where ctx == skb
10483  * - since they are wrappers of function calls, they scratch R1-R5 registers,
10484  *   preserve R6-R9, and store return value into R0
10485  *
10486  * Implicit input:
10487  *   ctx == skb == R6 == CTX
10488  *
10489  * Explicit input:
10490  *   SRC == any register
10491  *   IMM == 32-bit immediate
10492  *
10493  * Output:
10494  *   R0 - 8/16/32-bit skb data converted to cpu endianness
10495  */
10496 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
10497 {
10498         struct bpf_reg_state *regs = cur_regs(env);
10499         static const int ctx_reg = BPF_REG_6;
10500         u8 mode = BPF_MODE(insn->code);
10501         int i, err;
10502
10503         if (!may_access_skb(resolve_prog_type(env->prog))) {
10504                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
10505                 return -EINVAL;
10506         }
10507
10508         if (!env->ops->gen_ld_abs) {
10509                 verbose(env, "bpf verifier is misconfigured\n");
10510                 return -EINVAL;
10511         }
10512
10513         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
10514             BPF_SIZE(insn->code) == BPF_DW ||
10515             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
10516                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
10517                 return -EINVAL;
10518         }
10519
10520         /* check whether implicit source operand (register R6) is readable */
10521         err = check_reg_arg(env, ctx_reg, SRC_OP);
10522         if (err)
10523                 return err;
10524
10525         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
10526          * gen_ld_abs() may terminate the program at runtime, leading to
10527          * reference leak.
10528          */
10529         err = check_reference_leak(env);
10530         if (err) {
10531                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
10532                 return err;
10533         }
10534
10535         if (env->cur_state->active_spin_lock) {
10536                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
10537                 return -EINVAL;
10538         }
10539
10540         if (regs[ctx_reg].type != PTR_TO_CTX) {
10541                 verbose(env,
10542                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
10543                 return -EINVAL;
10544         }
10545
10546         if (mode == BPF_IND) {
10547                 /* check explicit source operand */
10548                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10549                 if (err)
10550                         return err;
10551         }
10552
10553         err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
10554         if (err < 0)
10555                 return err;
10556
10557         /* reset caller saved regs to unreadable */
10558         for (i = 0; i < CALLER_SAVED_REGS; i++) {
10559                 mark_reg_not_init(env, regs, caller_saved[i]);
10560                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10561         }
10562
10563         /* mark destination R0 register as readable, since it contains
10564          * the value fetched from the packet.
10565          * Already marked as written above.
10566          */
10567         mark_reg_unknown(env, regs, BPF_REG_0);
10568         /* ld_abs load up to 32-bit skb data. */
10569         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
10570         return 0;
10571 }
10572
10573 static int check_return_code(struct bpf_verifier_env *env)
10574 {
10575         struct tnum enforce_attach_type_range = tnum_unknown;
10576         const struct bpf_prog *prog = env->prog;
10577         struct bpf_reg_state *reg;
10578         struct tnum range = tnum_range(0, 1);
10579         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10580         int err;
10581         struct bpf_func_state *frame = env->cur_state->frame[0];
10582         const bool is_subprog = frame->subprogno;
10583
10584         /* LSM and struct_ops func-ptr's return type could be "void" */
10585         if (!is_subprog) {
10586                 switch (prog_type) {
10587                 case BPF_PROG_TYPE_LSM:
10588                         if (prog->expected_attach_type == BPF_LSM_CGROUP)
10589                                 /* See below, can be 0 or 0-1 depending on hook. */
10590                                 break;
10591                         fallthrough;
10592                 case BPF_PROG_TYPE_STRUCT_OPS:
10593                         if (!prog->aux->attach_func_proto->type)
10594                                 return 0;
10595                         break;
10596                 default:
10597                         break;
10598                 }
10599         }
10600
10601         /* eBPF calling convention is such that R0 is used
10602          * to return the value from eBPF program.
10603          * Make sure that it's readable at this time
10604          * of bpf_exit, which means that program wrote
10605          * something into it earlier
10606          */
10607         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
10608         if (err)
10609                 return err;
10610
10611         if (is_pointer_value(env, BPF_REG_0)) {
10612                 verbose(env, "R0 leaks addr as return value\n");
10613                 return -EACCES;
10614         }
10615
10616         reg = cur_regs(env) + BPF_REG_0;
10617
10618         if (frame->in_async_callback_fn) {
10619                 /* enforce return zero from async callbacks like timer */
10620                 if (reg->type != SCALAR_VALUE) {
10621                         verbose(env, "In async callback the register R0 is not a known value (%s)\n",
10622                                 reg_type_str(env, reg->type));
10623                         return -EINVAL;
10624                 }
10625
10626                 if (!tnum_in(tnum_const(0), reg->var_off)) {
10627                         verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
10628                         return -EINVAL;
10629                 }
10630                 return 0;
10631         }
10632
10633         if (is_subprog) {
10634                 if (reg->type != SCALAR_VALUE) {
10635                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
10636                                 reg_type_str(env, reg->type));
10637                         return -EINVAL;
10638                 }
10639                 return 0;
10640         }
10641
10642         switch (prog_type) {
10643         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10644                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
10645                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
10646                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
10647                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
10648                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
10649                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
10650                         range = tnum_range(1, 1);
10651                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
10652                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
10653                         range = tnum_range(0, 3);
10654                 break;
10655         case BPF_PROG_TYPE_CGROUP_SKB:
10656                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
10657                         range = tnum_range(0, 3);
10658                         enforce_attach_type_range = tnum_range(2, 3);
10659                 }
10660                 break;
10661         case BPF_PROG_TYPE_CGROUP_SOCK:
10662         case BPF_PROG_TYPE_SOCK_OPS:
10663         case BPF_PROG_TYPE_CGROUP_DEVICE:
10664         case BPF_PROG_TYPE_CGROUP_SYSCTL:
10665         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10666                 break;
10667         case BPF_PROG_TYPE_RAW_TRACEPOINT:
10668                 if (!env->prog->aux->attach_btf_id)
10669                         return 0;
10670                 range = tnum_const(0);
10671                 break;
10672         case BPF_PROG_TYPE_TRACING:
10673                 switch (env->prog->expected_attach_type) {
10674                 case BPF_TRACE_FENTRY:
10675                 case BPF_TRACE_FEXIT:
10676                         range = tnum_const(0);
10677                         break;
10678                 case BPF_TRACE_RAW_TP:
10679                 case BPF_MODIFY_RETURN:
10680                         return 0;
10681                 case BPF_TRACE_ITER:
10682                         break;
10683                 default:
10684                         return -ENOTSUPP;
10685                 }
10686                 break;
10687         case BPF_PROG_TYPE_SK_LOOKUP:
10688                 range = tnum_range(SK_DROP, SK_PASS);
10689                 break;
10690
10691         case BPF_PROG_TYPE_LSM:
10692                 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
10693                         /* Regular BPF_PROG_TYPE_LSM programs can return
10694                          * any value.
10695                          */
10696                         return 0;
10697                 }
10698                 if (!env->prog->aux->attach_func_proto->type) {
10699                         /* Make sure programs that attach to void
10700                          * hooks don't try to modify return value.
10701                          */
10702                         range = tnum_range(1, 1);
10703                 }
10704                 break;
10705
10706         case BPF_PROG_TYPE_EXT:
10707                 /* freplace program can return anything as its return value
10708                  * depends on the to-be-replaced kernel func or bpf program.
10709                  */
10710         default:
10711                 return 0;
10712         }
10713
10714         if (reg->type != SCALAR_VALUE) {
10715                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
10716                         reg_type_str(env, reg->type));
10717                 return -EINVAL;
10718         }
10719
10720         if (!tnum_in(range, reg->var_off)) {
10721                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
10722                 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
10723                     prog_type == BPF_PROG_TYPE_LSM &&
10724                     !prog->aux->attach_func_proto->type)
10725                         verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10726                 return -EINVAL;
10727         }
10728
10729         if (!tnum_is_unknown(enforce_attach_type_range) &&
10730             tnum_in(enforce_attach_type_range, reg->var_off))
10731                 env->prog->enforce_expected_attach_type = 1;
10732         return 0;
10733 }
10734
10735 /* non-recursive DFS pseudo code
10736  * 1  procedure DFS-iterative(G,v):
10737  * 2      label v as discovered
10738  * 3      let S be a stack
10739  * 4      S.push(v)
10740  * 5      while S is not empty
10741  * 6            t <- S.pop()
10742  * 7            if t is what we're looking for:
10743  * 8                return t
10744  * 9            for all edges e in G.adjacentEdges(t) do
10745  * 10               if edge e is already labelled
10746  * 11                   continue with the next edge
10747  * 12               w <- G.adjacentVertex(t,e)
10748  * 13               if vertex w is not discovered and not explored
10749  * 14                   label e as tree-edge
10750  * 15                   label w as discovered
10751  * 16                   S.push(w)
10752  * 17                   continue at 5
10753  * 18               else if vertex w is discovered
10754  * 19                   label e as back-edge
10755  * 20               else
10756  * 21                   // vertex w is explored
10757  * 22                   label e as forward- or cross-edge
10758  * 23           label t as explored
10759  * 24           S.pop()
10760  *
10761  * convention:
10762  * 0x10 - discovered
10763  * 0x11 - discovered and fall-through edge labelled
10764  * 0x12 - discovered and fall-through and branch edges labelled
10765  * 0x20 - explored
10766  */
10767
10768 enum {
10769         DISCOVERED = 0x10,
10770         EXPLORED = 0x20,
10771         FALLTHROUGH = 1,
10772         BRANCH = 2,
10773 };
10774
10775 static u32 state_htab_size(struct bpf_verifier_env *env)
10776 {
10777         return env->prog->len;
10778 }
10779
10780 static struct bpf_verifier_state_list **explored_state(
10781                                         struct bpf_verifier_env *env,
10782                                         int idx)
10783 {
10784         struct bpf_verifier_state *cur = env->cur_state;
10785         struct bpf_func_state *state = cur->frame[cur->curframe];
10786
10787         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
10788 }
10789
10790 static void init_explored_state(struct bpf_verifier_env *env, int idx)
10791 {
10792         env->insn_aux_data[idx].prune_point = true;
10793 }
10794
10795 enum {
10796         DONE_EXPLORING = 0,
10797         KEEP_EXPLORING = 1,
10798 };
10799
10800 /* t, w, e - match pseudo-code above:
10801  * t - index of current instruction
10802  * w - next instruction
10803  * e - edge
10804  */
10805 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10806                      bool loop_ok)
10807 {
10808         int *insn_stack = env->cfg.insn_stack;
10809         int *insn_state = env->cfg.insn_state;
10810
10811         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
10812                 return DONE_EXPLORING;
10813
10814         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
10815                 return DONE_EXPLORING;
10816
10817         if (w < 0 || w >= env->prog->len) {
10818                 verbose_linfo(env, t, "%d: ", t);
10819                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
10820                 return -EINVAL;
10821         }
10822
10823         if (e == BRANCH)
10824                 /* mark branch target for state pruning */
10825                 init_explored_state(env, w);
10826
10827         if (insn_state[w] == 0) {
10828                 /* tree-edge */
10829                 insn_state[t] = DISCOVERED | e;
10830                 insn_state[w] = DISCOVERED;
10831                 if (env->cfg.cur_stack >= env->prog->len)
10832                         return -E2BIG;
10833                 insn_stack[env->cfg.cur_stack++] = w;
10834                 return KEEP_EXPLORING;
10835         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10836                 if (loop_ok && env->bpf_capable)
10837                         return DONE_EXPLORING;
10838                 verbose_linfo(env, t, "%d: ", t);
10839                 verbose_linfo(env, w, "%d: ", w);
10840                 verbose(env, "back-edge from insn %d to %d\n", t, w);
10841                 return -EINVAL;
10842         } else if (insn_state[w] == EXPLORED) {
10843                 /* forward- or cross-edge */
10844                 insn_state[t] = DISCOVERED | e;
10845         } else {
10846                 verbose(env, "insn state internal bug\n");
10847                 return -EFAULT;
10848         }
10849         return DONE_EXPLORING;
10850 }
10851
10852 static int visit_func_call_insn(int t, int insn_cnt,
10853                                 struct bpf_insn *insns,
10854                                 struct bpf_verifier_env *env,
10855                                 bool visit_callee)
10856 {
10857         int ret;
10858
10859         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10860         if (ret)
10861                 return ret;
10862
10863         if (t + 1 < insn_cnt)
10864                 init_explored_state(env, t + 1);
10865         if (visit_callee) {
10866                 init_explored_state(env, t);
10867                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10868                                 /* It's ok to allow recursion from CFG point of
10869                                  * view. __check_func_call() will do the actual
10870                                  * check.
10871                                  */
10872                                 bpf_pseudo_func(insns + t));
10873         }
10874         return ret;
10875 }
10876
10877 /* Visits the instruction at index t and returns one of the following:
10878  *  < 0 - an error occurred
10879  *  DONE_EXPLORING - the instruction was fully explored
10880  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
10881  */
10882 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10883 {
10884         struct bpf_insn *insns = env->prog->insnsi;
10885         int ret;
10886
10887         if (bpf_pseudo_func(insns + t))
10888                 return visit_func_call_insn(t, insn_cnt, insns, env, true);
10889
10890         /* All non-branch instructions have a single fall-through edge. */
10891         if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10892             BPF_CLASS(insns[t].code) != BPF_JMP32)
10893                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
10894
10895         switch (BPF_OP(insns[t].code)) {
10896         case BPF_EXIT:
10897                 return DONE_EXPLORING;
10898
10899         case BPF_CALL:
10900                 if (insns[t].imm == BPF_FUNC_timer_set_callback)
10901                         /* Mark this call insn to trigger is_state_visited() check
10902                          * before call itself is processed by __check_func_call().
10903                          * Otherwise new async state will be pushed for further
10904                          * exploration.
10905                          */
10906                         init_explored_state(env, t);
10907                 return visit_func_call_insn(t, insn_cnt, insns, env,
10908                                             insns[t].src_reg == BPF_PSEUDO_CALL);
10909
10910         case BPF_JA:
10911                 if (BPF_SRC(insns[t].code) != BPF_K)
10912                         return -EINVAL;
10913
10914                 /* unconditional jump with single edge */
10915                 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10916                                 true);
10917                 if (ret)
10918                         return ret;
10919
10920                 /* unconditional jmp is not a good pruning point,
10921                  * but it's marked, since backtracking needs
10922                  * to record jmp history in is_state_visited().
10923                  */
10924                 init_explored_state(env, t + insns[t].off + 1);
10925                 /* tell verifier to check for equivalent states
10926                  * after every call and jump
10927                  */
10928                 if (t + 1 < insn_cnt)
10929                         init_explored_state(env, t + 1);
10930
10931                 return ret;
10932
10933         default:
10934                 /* conditional jump with two edges */
10935                 init_explored_state(env, t);
10936                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
10937                 if (ret)
10938                         return ret;
10939
10940                 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
10941         }
10942 }
10943
10944 /* non-recursive depth-first-search to detect loops in BPF program
10945  * loop == back-edge in directed graph
10946  */
10947 static int check_cfg(struct bpf_verifier_env *env)
10948 {
10949         int insn_cnt = env->prog->len;
10950         int *insn_stack, *insn_state;
10951         int ret = 0;
10952         int i;
10953
10954         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10955         if (!insn_state)
10956                 return -ENOMEM;
10957
10958         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10959         if (!insn_stack) {
10960                 kvfree(insn_state);
10961                 return -ENOMEM;
10962         }
10963
10964         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10965         insn_stack[0] = 0; /* 0 is the first instruction */
10966         env->cfg.cur_stack = 1;
10967
10968         while (env->cfg.cur_stack > 0) {
10969                 int t = insn_stack[env->cfg.cur_stack - 1];
10970
10971                 ret = visit_insn(t, insn_cnt, env);
10972                 switch (ret) {
10973                 case DONE_EXPLORING:
10974                         insn_state[t] = EXPLORED;
10975                         env->cfg.cur_stack--;
10976                         break;
10977                 case KEEP_EXPLORING:
10978                         break;
10979                 default:
10980                         if (ret > 0) {
10981                                 verbose(env, "visit_insn internal bug\n");
10982                                 ret = -EFAULT;
10983                         }
10984                         goto err_free;
10985                 }
10986         }
10987
10988         if (env->cfg.cur_stack < 0) {
10989                 verbose(env, "pop stack internal bug\n");
10990                 ret = -EFAULT;
10991                 goto err_free;
10992         }
10993
10994         for (i = 0; i < insn_cnt; i++) {
10995                 if (insn_state[i] != EXPLORED) {
10996                         verbose(env, "unreachable insn %d\n", i);
10997                         ret = -EINVAL;
10998                         goto err_free;
10999                 }
11000         }
11001         ret = 0; /* cfg looks good */
11002
11003 err_free:
11004         kvfree(insn_state);
11005         kvfree(insn_stack);
11006         env->cfg.insn_state = env->cfg.insn_stack = NULL;
11007         return ret;
11008 }
11009
11010 static int check_abnormal_return(struct bpf_verifier_env *env)
11011 {
11012         int i;
11013
11014         for (i = 1; i < env->subprog_cnt; i++) {
11015                 if (env->subprog_info[i].has_ld_abs) {
11016                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
11017                         return -EINVAL;
11018                 }
11019                 if (env->subprog_info[i].has_tail_call) {
11020                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
11021                         return -EINVAL;
11022                 }
11023         }
11024         return 0;
11025 }
11026
11027 /* The minimum supported BTF func info size */
11028 #define MIN_BPF_FUNCINFO_SIZE   8
11029 #define MAX_FUNCINFO_REC_SIZE   252
11030
11031 static int check_btf_func(struct bpf_verifier_env *env,
11032                           const union bpf_attr *attr,
11033                           bpfptr_t uattr)
11034 {
11035         const struct btf_type *type, *func_proto, *ret_type;
11036         u32 i, nfuncs, urec_size, min_size;
11037         u32 krec_size = sizeof(struct bpf_func_info);
11038         struct bpf_func_info *krecord;
11039         struct bpf_func_info_aux *info_aux = NULL;
11040         struct bpf_prog *prog;
11041         const struct btf *btf;
11042         bpfptr_t urecord;
11043         u32 prev_offset = 0;
11044         bool scalar_return;
11045         int ret = -ENOMEM;
11046
11047         nfuncs = attr->func_info_cnt;
11048         if (!nfuncs) {
11049                 if (check_abnormal_return(env))
11050                         return -EINVAL;
11051                 return 0;
11052         }
11053
11054         if (nfuncs != env->subprog_cnt) {
11055                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
11056                 return -EINVAL;
11057         }
11058
11059         urec_size = attr->func_info_rec_size;
11060         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
11061             urec_size > MAX_FUNCINFO_REC_SIZE ||
11062             urec_size % sizeof(u32)) {
11063                 verbose(env, "invalid func info rec size %u\n", urec_size);
11064                 return -EINVAL;
11065         }
11066
11067         prog = env->prog;
11068         btf = prog->aux->btf;
11069
11070         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
11071         min_size = min_t(u32, krec_size, urec_size);
11072
11073         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
11074         if (!krecord)
11075                 return -ENOMEM;
11076         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
11077         if (!info_aux)
11078                 goto err_free;
11079
11080         for (i = 0; i < nfuncs; i++) {
11081                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
11082                 if (ret) {
11083                         if (ret == -E2BIG) {
11084                                 verbose(env, "nonzero tailing record in func info");
11085                                 /* set the size kernel expects so loader can zero
11086                                  * out the rest of the record.
11087                                  */
11088                                 if (copy_to_bpfptr_offset(uattr,
11089                                                           offsetof(union bpf_attr, func_info_rec_size),
11090                                                           &min_size, sizeof(min_size)))
11091                                         ret = -EFAULT;
11092                         }
11093                         goto err_free;
11094                 }
11095
11096                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
11097                         ret = -EFAULT;
11098                         goto err_free;
11099                 }
11100
11101                 /* check insn_off */
11102                 ret = -EINVAL;
11103                 if (i == 0) {
11104                         if (krecord[i].insn_off) {
11105                                 verbose(env,
11106                                         "nonzero insn_off %u for the first func info record",
11107                                         krecord[i].insn_off);
11108                                 goto err_free;
11109                         }
11110                 } else if (krecord[i].insn_off <= prev_offset) {
11111                         verbose(env,
11112                                 "same or smaller insn offset (%u) than previous func info record (%u)",
11113                                 krecord[i].insn_off, prev_offset);
11114                         goto err_free;
11115                 }
11116
11117                 if (env->subprog_info[i].start != krecord[i].insn_off) {
11118                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
11119                         goto err_free;
11120                 }
11121
11122                 /* check type_id */
11123                 type = btf_type_by_id(btf, krecord[i].type_id);
11124                 if (!type || !btf_type_is_func(type)) {
11125                         verbose(env, "invalid type id %d in func info",
11126                                 krecord[i].type_id);
11127                         goto err_free;
11128                 }
11129                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
11130
11131                 func_proto = btf_type_by_id(btf, type->type);
11132                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
11133                         /* btf_func_check() already verified it during BTF load */
11134                         goto err_free;
11135                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
11136                 scalar_return =
11137                         btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
11138                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
11139                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
11140                         goto err_free;
11141                 }
11142                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
11143                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
11144                         goto err_free;
11145                 }
11146
11147                 prev_offset = krecord[i].insn_off;
11148                 bpfptr_add(&urecord, urec_size);
11149         }
11150
11151         prog->aux->func_info = krecord;
11152         prog->aux->func_info_cnt = nfuncs;
11153         prog->aux->func_info_aux = info_aux;
11154         return 0;
11155
11156 err_free:
11157         kvfree(krecord);
11158         kfree(info_aux);
11159         return ret;
11160 }
11161
11162 static void adjust_btf_func(struct bpf_verifier_env *env)
11163 {
11164         struct bpf_prog_aux *aux = env->prog->aux;
11165         int i;
11166
11167         if (!aux->func_info)
11168                 return;
11169
11170         for (i = 0; i < env->subprog_cnt; i++)
11171                 aux->func_info[i].insn_off = env->subprog_info[i].start;
11172 }
11173
11174 #define MIN_BPF_LINEINFO_SIZE   offsetofend(struct bpf_line_info, line_col)
11175 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
11176
11177 static int check_btf_line(struct bpf_verifier_env *env,
11178                           const union bpf_attr *attr,
11179                           bpfptr_t uattr)
11180 {
11181         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
11182         struct bpf_subprog_info *sub;
11183         struct bpf_line_info *linfo;
11184         struct bpf_prog *prog;
11185         const struct btf *btf;
11186         bpfptr_t ulinfo;
11187         int err;
11188
11189         nr_linfo = attr->line_info_cnt;
11190         if (!nr_linfo)
11191                 return 0;
11192         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
11193                 return -EINVAL;
11194
11195         rec_size = attr->line_info_rec_size;
11196         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
11197             rec_size > MAX_LINEINFO_REC_SIZE ||
11198             rec_size & (sizeof(u32) - 1))
11199                 return -EINVAL;
11200
11201         /* Need to zero it in case the userspace may
11202          * pass in a smaller bpf_line_info object.
11203          */
11204         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
11205                          GFP_KERNEL | __GFP_NOWARN);
11206         if (!linfo)
11207                 return -ENOMEM;
11208
11209         prog = env->prog;
11210         btf = prog->aux->btf;
11211
11212         s = 0;
11213         sub = env->subprog_info;
11214         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
11215         expected_size = sizeof(struct bpf_line_info);
11216         ncopy = min_t(u32, expected_size, rec_size);
11217         for (i = 0; i < nr_linfo; i++) {
11218                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
11219                 if (err) {
11220                         if (err == -E2BIG) {
11221                                 verbose(env, "nonzero tailing record in line_info");
11222                                 if (copy_to_bpfptr_offset(uattr,
11223                                                           offsetof(union bpf_attr, line_info_rec_size),
11224                                                           &expected_size, sizeof(expected_size)))
11225                                         err = -EFAULT;
11226                         }
11227                         goto err_free;
11228                 }
11229
11230                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
11231                         err = -EFAULT;
11232                         goto err_free;
11233                 }
11234
11235                 /*
11236                  * Check insn_off to ensure
11237                  * 1) strictly increasing AND
11238                  * 2) bounded by prog->len
11239                  *
11240                  * The linfo[0].insn_off == 0 check logically falls into
11241                  * the later "missing bpf_line_info for func..." case
11242                  * because the first linfo[0].insn_off must be the
11243                  * first sub also and the first sub must have
11244                  * subprog_info[0].start == 0.
11245                  */
11246                 if ((i && linfo[i].insn_off <= prev_offset) ||
11247                     linfo[i].insn_off >= prog->len) {
11248                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
11249                                 i, linfo[i].insn_off, prev_offset,
11250                                 prog->len);
11251                         err = -EINVAL;
11252                         goto err_free;
11253                 }
11254
11255                 if (!prog->insnsi[linfo[i].insn_off].code) {
11256                         verbose(env,
11257                                 "Invalid insn code at line_info[%u].insn_off\n",
11258                                 i);
11259                         err = -EINVAL;
11260                         goto err_free;
11261                 }
11262
11263                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
11264                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
11265                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
11266                         err = -EINVAL;
11267                         goto err_free;
11268                 }
11269
11270                 if (s != env->subprog_cnt) {
11271                         if (linfo[i].insn_off == sub[s].start) {
11272                                 sub[s].linfo_idx = i;
11273                                 s++;
11274                         } else if (sub[s].start < linfo[i].insn_off) {
11275                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
11276                                 err = -EINVAL;
11277                                 goto err_free;
11278                         }
11279                 }
11280
11281                 prev_offset = linfo[i].insn_off;
11282                 bpfptr_add(&ulinfo, rec_size);
11283         }
11284
11285         if (s != env->subprog_cnt) {
11286                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
11287                         env->subprog_cnt - s, s);
11288                 err = -EINVAL;
11289                 goto err_free;
11290         }
11291
11292         prog->aux->linfo = linfo;
11293         prog->aux->nr_linfo = nr_linfo;
11294
11295         return 0;
11296
11297 err_free:
11298         kvfree(linfo);
11299         return err;
11300 }
11301
11302 #define MIN_CORE_RELO_SIZE      sizeof(struct bpf_core_relo)
11303 #define MAX_CORE_RELO_SIZE      MAX_FUNCINFO_REC_SIZE
11304
11305 static int check_core_relo(struct bpf_verifier_env *env,
11306                            const union bpf_attr *attr,
11307                            bpfptr_t uattr)
11308 {
11309         u32 i, nr_core_relo, ncopy, expected_size, rec_size;
11310         struct bpf_core_relo core_relo = {};
11311         struct bpf_prog *prog = env->prog;
11312         const struct btf *btf = prog->aux->btf;
11313         struct bpf_core_ctx ctx = {
11314                 .log = &env->log,
11315                 .btf = btf,
11316         };
11317         bpfptr_t u_core_relo;
11318         int err;
11319
11320         nr_core_relo = attr->core_relo_cnt;
11321         if (!nr_core_relo)
11322                 return 0;
11323         if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
11324                 return -EINVAL;
11325
11326         rec_size = attr->core_relo_rec_size;
11327         if (rec_size < MIN_CORE_RELO_SIZE ||
11328             rec_size > MAX_CORE_RELO_SIZE ||
11329             rec_size % sizeof(u32))
11330                 return -EINVAL;
11331
11332         u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
11333         expected_size = sizeof(struct bpf_core_relo);
11334         ncopy = min_t(u32, expected_size, rec_size);
11335
11336         /* Unlike func_info and line_info, copy and apply each CO-RE
11337          * relocation record one at a time.
11338          */
11339         for (i = 0; i < nr_core_relo; i++) {
11340                 /* future proofing when sizeof(bpf_core_relo) changes */
11341                 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
11342                 if (err) {
11343                         if (err == -E2BIG) {
11344                                 verbose(env, "nonzero tailing record in core_relo");
11345                                 if (copy_to_bpfptr_offset(uattr,
11346                                                           offsetof(union bpf_attr, core_relo_rec_size),
11347                                                           &expected_size, sizeof(expected_size)))
11348                                         err = -EFAULT;
11349                         }
11350                         break;
11351                 }
11352
11353                 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
11354                         err = -EFAULT;
11355                         break;
11356                 }
11357
11358                 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
11359                         verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
11360                                 i, core_relo.insn_off, prog->len);
11361                         err = -EINVAL;
11362                         break;
11363                 }
11364
11365                 err = bpf_core_apply(&ctx, &core_relo, i,
11366                                      &prog->insnsi[core_relo.insn_off / 8]);
11367                 if (err)
11368                         break;
11369                 bpfptr_add(&u_core_relo, rec_size);
11370         }
11371         return err;
11372 }
11373
11374 static int check_btf_info(struct bpf_verifier_env *env,
11375                           const union bpf_attr *attr,
11376                           bpfptr_t uattr)
11377 {
11378         struct btf *btf;
11379         int err;
11380
11381         if (!attr->func_info_cnt && !attr->line_info_cnt) {
11382                 if (check_abnormal_return(env))
11383                         return -EINVAL;
11384                 return 0;
11385         }
11386
11387         btf = btf_get_by_fd(attr->prog_btf_fd);
11388         if (IS_ERR(btf))
11389                 return PTR_ERR(btf);
11390         if (btf_is_kernel(btf)) {
11391                 btf_put(btf);
11392                 return -EACCES;
11393         }
11394         env->prog->aux->btf = btf;
11395
11396         err = check_btf_func(env, attr, uattr);
11397         if (err)
11398                 return err;
11399
11400         err = check_btf_line(env, attr, uattr);
11401         if (err)
11402                 return err;
11403
11404         err = check_core_relo(env, attr, uattr);
11405         if (err)
11406                 return err;
11407
11408         return 0;
11409 }
11410
11411 /* check %cur's range satisfies %old's */
11412 static bool range_within(struct bpf_reg_state *old,
11413                          struct bpf_reg_state *cur)
11414 {
11415         return old->umin_value <= cur->umin_value &&
11416                old->umax_value >= cur->umax_value &&
11417                old->smin_value <= cur->smin_value &&
11418                old->smax_value >= cur->smax_value &&
11419                old->u32_min_value <= cur->u32_min_value &&
11420                old->u32_max_value >= cur->u32_max_value &&
11421                old->s32_min_value <= cur->s32_min_value &&
11422                old->s32_max_value >= cur->s32_max_value;
11423 }
11424
11425 /* If in the old state two registers had the same id, then they need to have
11426  * the same id in the new state as well.  But that id could be different from
11427  * the old state, so we need to track the mapping from old to new ids.
11428  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
11429  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
11430  * regs with a different old id could still have new id 9, we don't care about
11431  * that.
11432  * So we look through our idmap to see if this old id has been seen before.  If
11433  * so, we require the new id to match; otherwise, we add the id pair to the map.
11434  */
11435 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
11436 {
11437         unsigned int i;
11438
11439         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
11440                 if (!idmap[i].old) {
11441                         /* Reached an empty slot; haven't seen this id before */
11442                         idmap[i].old = old_id;
11443                         idmap[i].cur = cur_id;
11444                         return true;
11445                 }
11446                 if (idmap[i].old == old_id)
11447                         return idmap[i].cur == cur_id;
11448         }
11449         /* We ran out of idmap slots, which should be impossible */
11450         WARN_ON_ONCE(1);
11451         return false;
11452 }
11453
11454 static void clean_func_state(struct bpf_verifier_env *env,
11455                              struct bpf_func_state *st)
11456 {
11457         enum bpf_reg_liveness live;
11458         int i, j;
11459
11460         for (i = 0; i < BPF_REG_FP; i++) {
11461                 live = st->regs[i].live;
11462                 /* liveness must not touch this register anymore */
11463                 st->regs[i].live |= REG_LIVE_DONE;
11464                 if (!(live & REG_LIVE_READ))
11465                         /* since the register is unused, clear its state
11466                          * to make further comparison simpler
11467                          */
11468                         __mark_reg_not_init(env, &st->regs[i]);
11469         }
11470
11471         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
11472                 live = st->stack[i].spilled_ptr.live;
11473                 /* liveness must not touch this stack slot anymore */
11474                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
11475                 if (!(live & REG_LIVE_READ)) {
11476                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
11477                         for (j = 0; j < BPF_REG_SIZE; j++)
11478                                 st->stack[i].slot_type[j] = STACK_INVALID;
11479                 }
11480         }
11481 }
11482
11483 static void clean_verifier_state(struct bpf_verifier_env *env,
11484                                  struct bpf_verifier_state *st)
11485 {
11486         int i;
11487
11488         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
11489                 /* all regs in this state in all frames were already marked */
11490                 return;
11491
11492         for (i = 0; i <= st->curframe; i++)
11493                 clean_func_state(env, st->frame[i]);
11494 }
11495
11496 /* the parentage chains form a tree.
11497  * the verifier states are added to state lists at given insn and
11498  * pushed into state stack for future exploration.
11499  * when the verifier reaches bpf_exit insn some of the verifer states
11500  * stored in the state lists have their final liveness state already,
11501  * but a lot of states will get revised from liveness point of view when
11502  * the verifier explores other branches.
11503  * Example:
11504  * 1: r0 = 1
11505  * 2: if r1 == 100 goto pc+1
11506  * 3: r0 = 2
11507  * 4: exit
11508  * when the verifier reaches exit insn the register r0 in the state list of
11509  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
11510  * of insn 2 and goes exploring further. At the insn 4 it will walk the
11511  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
11512  *
11513  * Since the verifier pushes the branch states as it sees them while exploring
11514  * the program the condition of walking the branch instruction for the second
11515  * time means that all states below this branch were already explored and
11516  * their final liveness marks are already propagated.
11517  * Hence when the verifier completes the search of state list in is_state_visited()
11518  * we can call this clean_live_states() function to mark all liveness states
11519  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
11520  * will not be used.
11521  * This function also clears the registers and stack for states that !READ
11522  * to simplify state merging.
11523  *
11524  * Important note here that walking the same branch instruction in the callee
11525  * doesn't meant that the states are DONE. The verifier has to compare
11526  * the callsites
11527  */
11528 static void clean_live_states(struct bpf_verifier_env *env, int insn,
11529                               struct bpf_verifier_state *cur)
11530 {
11531         struct bpf_verifier_state_list *sl;
11532         int i;
11533
11534         sl = *explored_state(env, insn);
11535         while (sl) {
11536                 if (sl->state.branches)
11537                         goto next;
11538                 if (sl->state.insn_idx != insn ||
11539                     sl->state.curframe != cur->curframe)
11540                         goto next;
11541                 for (i = 0; i <= cur->curframe; i++)
11542                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
11543                                 goto next;
11544                 clean_verifier_state(env, &sl->state);
11545 next:
11546                 sl = sl->next;
11547         }
11548 }
11549
11550 /* Returns true if (rold safe implies rcur safe) */
11551 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
11552                     struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
11553 {
11554         bool equal;
11555
11556         if (!(rold->live & REG_LIVE_READ))
11557                 /* explored state didn't use this */
11558                 return true;
11559
11560         equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
11561
11562         if (rold->type == PTR_TO_STACK)
11563                 /* two stack pointers are equal only if they're pointing to
11564                  * the same stack frame, since fp-8 in foo != fp-8 in bar
11565                  */
11566                 return equal && rold->frameno == rcur->frameno;
11567
11568         if (equal)
11569                 return true;
11570
11571         if (rold->type == NOT_INIT)
11572                 /* explored state can't have used this */
11573                 return true;
11574         if (rcur->type == NOT_INIT)
11575                 return false;
11576         switch (base_type(rold->type)) {
11577         case SCALAR_VALUE:
11578                 if (env->explore_alu_limits)
11579                         return false;
11580                 if (rcur->type == SCALAR_VALUE) {
11581                         if (!rold->precise && !rcur->precise)
11582                                 return true;
11583                         /* new val must satisfy old val knowledge */
11584                         return range_within(rold, rcur) &&
11585                                tnum_in(rold->var_off, rcur->var_off);
11586                 } else {
11587                         /* We're trying to use a pointer in place of a scalar.
11588                          * Even if the scalar was unbounded, this could lead to
11589                          * pointer leaks because scalars are allowed to leak
11590                          * while pointers are not. We could make this safe in
11591                          * special cases if root is calling us, but it's
11592                          * probably not worth the hassle.
11593                          */
11594                         return false;
11595                 }
11596         case PTR_TO_MAP_KEY:
11597         case PTR_TO_MAP_VALUE:
11598                 /* a PTR_TO_MAP_VALUE could be safe to use as a
11599                  * PTR_TO_MAP_VALUE_OR_NULL into the same map.
11600                  * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
11601                  * checked, doing so could have affected others with the same
11602                  * id, and we can't check for that because we lost the id when
11603                  * we converted to a PTR_TO_MAP_VALUE.
11604                  */
11605                 if (type_may_be_null(rold->type)) {
11606                         if (!type_may_be_null(rcur->type))
11607                                 return false;
11608                         if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
11609                                 return false;
11610                         /* Check our ids match any regs they're supposed to */
11611                         return check_ids(rold->id, rcur->id, idmap);
11612                 }
11613
11614                 /* If the new min/max/var_off satisfy the old ones and
11615                  * everything else matches, we are OK.
11616                  * 'id' is not compared, since it's only used for maps with
11617                  * bpf_spin_lock inside map element and in such cases if
11618                  * the rest of the prog is valid for one map element then
11619                  * it's valid for all map elements regardless of the key
11620                  * used in bpf_map_lookup()
11621                  */
11622                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
11623                        range_within(rold, rcur) &&
11624                        tnum_in(rold->var_off, rcur->var_off);
11625         case PTR_TO_PACKET_META:
11626         case PTR_TO_PACKET:
11627                 if (rcur->type != rold->type)
11628                         return false;
11629                 /* We must have at least as much range as the old ptr
11630                  * did, so that any accesses which were safe before are
11631                  * still safe.  This is true even if old range < old off,
11632                  * since someone could have accessed through (ptr - k), or
11633                  * even done ptr -= k in a register, to get a safe access.
11634                  */
11635                 if (rold->range > rcur->range)
11636                         return false;
11637                 /* If the offsets don't match, we can't trust our alignment;
11638                  * nor can we be sure that we won't fall out of range.
11639                  */
11640                 if (rold->off != rcur->off)
11641                         return false;
11642                 /* id relations must be preserved */
11643                 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
11644                         return false;
11645                 /* new val must satisfy old val knowledge */
11646                 return range_within(rold, rcur) &&
11647                        tnum_in(rold->var_off, rcur->var_off);
11648         case PTR_TO_CTX:
11649         case CONST_PTR_TO_MAP:
11650         case PTR_TO_PACKET_END:
11651         case PTR_TO_FLOW_KEYS:
11652         case PTR_TO_SOCKET:
11653         case PTR_TO_SOCK_COMMON:
11654         case PTR_TO_TCP_SOCK:
11655         case PTR_TO_XDP_SOCK:
11656                 /* Only valid matches are exact, which memcmp() above
11657                  * would have accepted
11658                  */
11659         default:
11660                 /* Don't know what's going on, just say it's not safe */
11661                 return false;
11662         }
11663
11664         /* Shouldn't get here; if we do, say it's not safe */
11665         WARN_ON_ONCE(1);
11666         return false;
11667 }
11668
11669 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
11670                       struct bpf_func_state *cur, struct bpf_id_pair *idmap)
11671 {
11672         int i, spi;
11673
11674         /* walk slots of the explored stack and ignore any additional
11675          * slots in the current stack, since explored(safe) state
11676          * didn't use them
11677          */
11678         for (i = 0; i < old->allocated_stack; i++) {
11679                 spi = i / BPF_REG_SIZE;
11680
11681                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
11682                         i += BPF_REG_SIZE - 1;
11683                         /* explored state didn't use this */
11684                         continue;
11685                 }
11686
11687                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
11688                         continue;
11689
11690                 /* explored stack has more populated slots than current stack
11691                  * and these slots were used
11692                  */
11693                 if (i >= cur->allocated_stack)
11694                         return false;
11695
11696                 /* if old state was safe with misc data in the stack
11697                  * it will be safe with zero-initialized stack.
11698                  * The opposite is not true
11699                  */
11700                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
11701                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
11702                         continue;
11703                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
11704                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
11705                         /* Ex: old explored (safe) state has STACK_SPILL in
11706                          * this stack slot, but current has STACK_MISC ->
11707                          * this verifier states are not equivalent,
11708                          * return false to continue verification of this path
11709                          */
11710                         return false;
11711                 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
11712                         continue;
11713                 if (!is_spilled_reg(&old->stack[spi]))
11714                         continue;
11715                 if (!regsafe(env, &old->stack[spi].spilled_ptr,
11716                              &cur->stack[spi].spilled_ptr, idmap))
11717                         /* when explored and current stack slot are both storing
11718                          * spilled registers, check that stored pointers types
11719                          * are the same as well.
11720                          * Ex: explored safe path could have stored
11721                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
11722                          * but current path has stored:
11723                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
11724                          * such verifier states are not equivalent.
11725                          * return false to continue verification of this path
11726                          */
11727                         return false;
11728         }
11729         return true;
11730 }
11731
11732 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
11733 {
11734         if (old->acquired_refs != cur->acquired_refs)
11735                 return false;
11736         return !memcmp(old->refs, cur->refs,
11737                        sizeof(*old->refs) * old->acquired_refs);
11738 }
11739
11740 /* compare two verifier states
11741  *
11742  * all states stored in state_list are known to be valid, since
11743  * verifier reached 'bpf_exit' instruction through them
11744  *
11745  * this function is called when verifier exploring different branches of
11746  * execution popped from the state stack. If it sees an old state that has
11747  * more strict register state and more strict stack state then this execution
11748  * branch doesn't need to be explored further, since verifier already
11749  * concluded that more strict state leads to valid finish.
11750  *
11751  * Therefore two states are equivalent if register state is more conservative
11752  * and explored stack state is more conservative than the current one.
11753  * Example:
11754  *       explored                   current
11755  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
11756  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
11757  *
11758  * In other words if current stack state (one being explored) has more
11759  * valid slots than old one that already passed validation, it means
11760  * the verifier can stop exploring and conclude that current state is valid too
11761  *
11762  * Similarly with registers. If explored state has register type as invalid
11763  * whereas register type in current state is meaningful, it means that
11764  * the current state will reach 'bpf_exit' instruction safely
11765  */
11766 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
11767                               struct bpf_func_state *cur)
11768 {
11769         int i;
11770
11771         memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11772         for (i = 0; i < MAX_BPF_REG; i++)
11773                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
11774                              env->idmap_scratch))
11775                         return false;
11776
11777         if (!stacksafe(env, old, cur, env->idmap_scratch))
11778                 return false;
11779
11780         if (!refsafe(old, cur))
11781                 return false;
11782
11783         return true;
11784 }
11785
11786 static bool states_equal(struct bpf_verifier_env *env,
11787                          struct bpf_verifier_state *old,
11788                          struct bpf_verifier_state *cur)
11789 {
11790         int i;
11791
11792         if (old->curframe != cur->curframe)
11793                 return false;
11794
11795         /* Verification state from speculative execution simulation
11796          * must never prune a non-speculative execution one.
11797          */
11798         if (old->speculative && !cur->speculative)
11799                 return false;
11800
11801         if (old->active_spin_lock != cur->active_spin_lock)
11802                 return false;
11803
11804         /* for states to be equal callsites have to be the same
11805          * and all frame states need to be equivalent
11806          */
11807         for (i = 0; i <= old->curframe; i++) {
11808                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
11809                         return false;
11810                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
11811                         return false;
11812         }
11813         return true;
11814 }
11815
11816 /* Return 0 if no propagation happened. Return negative error code if error
11817  * happened. Otherwise, return the propagated bit.
11818  */
11819 static int propagate_liveness_reg(struct bpf_verifier_env *env,
11820                                   struct bpf_reg_state *reg,
11821                                   struct bpf_reg_state *parent_reg)
11822 {
11823         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11824         u8 flag = reg->live & REG_LIVE_READ;
11825         int err;
11826
11827         /* When comes here, read flags of PARENT_REG or REG could be any of
11828          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11829          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11830          */
11831         if (parent_flag == REG_LIVE_READ64 ||
11832             /* Or if there is no read flag from REG. */
11833             !flag ||
11834             /* Or if the read flag from REG is the same as PARENT_REG. */
11835             parent_flag == flag)
11836                 return 0;
11837
11838         err = mark_reg_read(env, reg, parent_reg, flag);
11839         if (err)
11840                 return err;
11841
11842         return flag;
11843 }
11844
11845 /* A write screens off any subsequent reads; but write marks come from the
11846  * straight-line code between a state and its parent.  When we arrive at an
11847  * equivalent state (jump target or such) we didn't arrive by the straight-line
11848  * code, so read marks in the state must propagate to the parent regardless
11849  * of the state's write marks. That's what 'parent == state->parent' comparison
11850  * in mark_reg_read() is for.
11851  */
11852 static int propagate_liveness(struct bpf_verifier_env *env,
11853                               const struct bpf_verifier_state *vstate,
11854                               struct bpf_verifier_state *vparent)
11855 {
11856         struct bpf_reg_state *state_reg, *parent_reg;
11857         struct bpf_func_state *state, *parent;
11858         int i, frame, err = 0;
11859
11860         if (vparent->curframe != vstate->curframe) {
11861                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
11862                      vparent->curframe, vstate->curframe);
11863                 return -EFAULT;
11864         }
11865         /* Propagate read liveness of registers... */
11866         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
11867         for (frame = 0; frame <= vstate->curframe; frame++) {
11868                 parent = vparent->frame[frame];
11869                 state = vstate->frame[frame];
11870                 parent_reg = parent->regs;
11871                 state_reg = state->regs;
11872                 /* We don't need to worry about FP liveness, it's read-only */
11873                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
11874                         err = propagate_liveness_reg(env, &state_reg[i],
11875                                                      &parent_reg[i]);
11876                         if (err < 0)
11877                                 return err;
11878                         if (err == REG_LIVE_READ64)
11879                                 mark_insn_zext(env, &parent_reg[i]);
11880                 }
11881
11882                 /* Propagate stack slots. */
11883                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11884                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
11885                         parent_reg = &parent->stack[i].spilled_ptr;
11886                         state_reg = &state->stack[i].spilled_ptr;
11887                         err = propagate_liveness_reg(env, state_reg,
11888                                                      parent_reg);
11889                         if (err < 0)
11890                                 return err;
11891                 }
11892         }
11893         return 0;
11894 }
11895
11896 /* find precise scalars in the previous equivalent state and
11897  * propagate them into the current state
11898  */
11899 static int propagate_precision(struct bpf_verifier_env *env,
11900                                const struct bpf_verifier_state *old)
11901 {
11902         struct bpf_reg_state *state_reg;
11903         struct bpf_func_state *state;
11904         int i, err = 0, fr;
11905
11906         for (fr = old->curframe; fr >= 0; fr--) {
11907                 state = old->frame[fr];
11908                 state_reg = state->regs;
11909                 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11910                         if (state_reg->type != SCALAR_VALUE ||
11911                             !state_reg->precise ||
11912                             !(state_reg->live & REG_LIVE_READ))
11913                                 continue;
11914                         if (env->log.level & BPF_LOG_LEVEL2)
11915                                 verbose(env, "frame %d: propagating r%d\n", fr, i);
11916                         err = mark_chain_precision_frame(env, fr, i);
11917                         if (err < 0)
11918                                 return err;
11919                 }
11920
11921                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
11922                         if (!is_spilled_reg(&state->stack[i]))
11923                                 continue;
11924                         state_reg = &state->stack[i].spilled_ptr;
11925                         if (state_reg->type != SCALAR_VALUE ||
11926                             !state_reg->precise ||
11927                             !(state_reg->live & REG_LIVE_READ))
11928                                 continue;
11929                         if (env->log.level & BPF_LOG_LEVEL2)
11930                                 verbose(env, "frame %d: propagating fp%d\n",
11931                                         fr, (-i - 1) * BPF_REG_SIZE);
11932                         err = mark_chain_precision_stack_frame(env, fr, i);
11933                         if (err < 0)
11934                                 return err;
11935                 }
11936         }
11937         return 0;
11938 }
11939
11940 static bool states_maybe_looping(struct bpf_verifier_state *old,
11941                                  struct bpf_verifier_state *cur)
11942 {
11943         struct bpf_func_state *fold, *fcur;
11944         int i, fr = cur->curframe;
11945
11946         if (old->curframe != fr)
11947                 return false;
11948
11949         fold = old->frame[fr];
11950         fcur = cur->frame[fr];
11951         for (i = 0; i < MAX_BPF_REG; i++)
11952                 if (memcmp(&fold->regs[i], &fcur->regs[i],
11953                            offsetof(struct bpf_reg_state, parent)))
11954                         return false;
11955         return true;
11956 }
11957
11958
11959 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
11960 {
11961         struct bpf_verifier_state_list *new_sl;
11962         struct bpf_verifier_state_list *sl, **pprev;
11963         struct bpf_verifier_state *cur = env->cur_state, *new;
11964         int i, j, err, states_cnt = 0;
11965         bool add_new_state = env->test_state_freq ? true : false;
11966
11967         cur->last_insn_idx = env->prev_insn_idx;
11968         if (!env->insn_aux_data[insn_idx].prune_point)
11969                 /* this 'insn_idx' instruction wasn't marked, so we will not
11970                  * be doing state search here
11971                  */
11972                 return 0;
11973
11974         /* bpf progs typically have pruning point every 4 instructions
11975          * http://vger.kernel.org/bpfconf2019.html#session-1
11976          * Do not add new state for future pruning if the verifier hasn't seen
11977          * at least 2 jumps and at least 8 instructions.
11978          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11979          * In tests that amounts to up to 50% reduction into total verifier
11980          * memory consumption and 20% verifier time speedup.
11981          */
11982         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11983             env->insn_processed - env->prev_insn_processed >= 8)
11984                 add_new_state = true;
11985
11986         pprev = explored_state(env, insn_idx);
11987         sl = *pprev;
11988
11989         clean_live_states(env, insn_idx, cur);
11990
11991         while (sl) {
11992                 states_cnt++;
11993                 if (sl->state.insn_idx != insn_idx)
11994                         goto next;
11995
11996                 if (sl->state.branches) {
11997                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
11998
11999                         if (frame->in_async_callback_fn &&
12000                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
12001                                 /* Different async_entry_cnt means that the verifier is
12002                                  * processing another entry into async callback.
12003                                  * Seeing the same state is not an indication of infinite
12004                                  * loop or infinite recursion.
12005                                  * But finding the same state doesn't mean that it's safe
12006                                  * to stop processing the current state. The previous state
12007                                  * hasn't yet reached bpf_exit, since state.branches > 0.
12008                                  * Checking in_async_callback_fn alone is not enough either.
12009                                  * Since the verifier still needs to catch infinite loops
12010                                  * inside async callbacks.
12011                                  */
12012                         } else if (states_maybe_looping(&sl->state, cur) &&
12013                                    states_equal(env, &sl->state, cur)) {
12014                                 verbose_linfo(env, insn_idx, "; ");
12015                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
12016                                 return -EINVAL;
12017                         }
12018                         /* if the verifier is processing a loop, avoid adding new state
12019                          * too often, since different loop iterations have distinct
12020                          * states and may not help future pruning.
12021                          * This threshold shouldn't be too low to make sure that
12022                          * a loop with large bound will be rejected quickly.
12023                          * The most abusive loop will be:
12024                          * r1 += 1
12025                          * if r1 < 1000000 goto pc-2
12026                          * 1M insn_procssed limit / 100 == 10k peak states.
12027                          * This threshold shouldn't be too high either, since states
12028                          * at the end of the loop are likely to be useful in pruning.
12029                          */
12030                         if (env->jmps_processed - env->prev_jmps_processed < 20 &&
12031                             env->insn_processed - env->prev_insn_processed < 100)
12032                                 add_new_state = false;
12033                         goto miss;
12034                 }
12035                 if (states_equal(env, &sl->state, cur)) {
12036                         sl->hit_cnt++;
12037                         /* reached equivalent register/stack state,
12038                          * prune the search.
12039                          * Registers read by the continuation are read by us.
12040                          * If we have any write marks in env->cur_state, they
12041                          * will prevent corresponding reads in the continuation
12042                          * from reaching our parent (an explored_state).  Our
12043                          * own state will get the read marks recorded, but
12044                          * they'll be immediately forgotten as we're pruning
12045                          * this state and will pop a new one.
12046                          */
12047                         err = propagate_liveness(env, &sl->state, cur);
12048
12049                         /* if previous state reached the exit with precision and
12050                          * current state is equivalent to it (except precsion marks)
12051                          * the precision needs to be propagated back in
12052                          * the current state.
12053                          */
12054                         err = err ? : push_jmp_history(env, cur);
12055                         err = err ? : propagate_precision(env, &sl->state);
12056                         if (err)
12057                                 return err;
12058                         return 1;
12059                 }
12060 miss:
12061                 /* when new state is not going to be added do not increase miss count.
12062                  * Otherwise several loop iterations will remove the state
12063                  * recorded earlier. The goal of these heuristics is to have
12064                  * states from some iterations of the loop (some in the beginning
12065                  * and some at the end) to help pruning.
12066                  */
12067                 if (add_new_state)
12068                         sl->miss_cnt++;
12069                 /* heuristic to determine whether this state is beneficial
12070                  * to keep checking from state equivalence point of view.
12071                  * Higher numbers increase max_states_per_insn and verification time,
12072                  * but do not meaningfully decrease insn_processed.
12073                  */
12074                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
12075                         /* the state is unlikely to be useful. Remove it to
12076                          * speed up verification
12077                          */
12078                         *pprev = sl->next;
12079                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
12080                                 u32 br = sl->state.branches;
12081
12082                                 WARN_ONCE(br,
12083                                           "BUG live_done but branches_to_explore %d\n",
12084                                           br);
12085                                 free_verifier_state(&sl->state, false);
12086                                 kfree(sl);
12087                                 env->peak_states--;
12088                         } else {
12089                                 /* cannot free this state, since parentage chain may
12090                                  * walk it later. Add it for free_list instead to
12091                                  * be freed at the end of verification
12092                                  */
12093                                 sl->next = env->free_list;
12094                                 env->free_list = sl;
12095                         }
12096                         sl = *pprev;
12097                         continue;
12098                 }
12099 next:
12100                 pprev = &sl->next;
12101                 sl = *pprev;
12102         }
12103
12104         if (env->max_states_per_insn < states_cnt)
12105                 env->max_states_per_insn = states_cnt;
12106
12107         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
12108                 return push_jmp_history(env, cur);
12109
12110         if (!add_new_state)
12111                 return push_jmp_history(env, cur);
12112
12113         /* There were no equivalent states, remember the current one.
12114          * Technically the current state is not proven to be safe yet,
12115          * but it will either reach outer most bpf_exit (which means it's safe)
12116          * or it will be rejected. When there are no loops the verifier won't be
12117          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
12118          * again on the way to bpf_exit.
12119          * When looping the sl->state.branches will be > 0 and this state
12120          * will not be considered for equivalence until branches == 0.
12121          */
12122         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
12123         if (!new_sl)
12124                 return -ENOMEM;
12125         env->total_states++;
12126         env->peak_states++;
12127         env->prev_jmps_processed = env->jmps_processed;
12128         env->prev_insn_processed = env->insn_processed;
12129
12130         /* add new state to the head of linked list */
12131         new = &new_sl->state;
12132         err = copy_verifier_state(new, cur);
12133         if (err) {
12134                 free_verifier_state(new, false);
12135                 kfree(new_sl);
12136                 return err;
12137         }
12138         new->insn_idx = insn_idx;
12139         WARN_ONCE(new->branches != 1,
12140                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
12141
12142         cur->parent = new;
12143         cur->first_insn_idx = insn_idx;
12144         clear_jmp_history(cur);
12145         new_sl->next = *explored_state(env, insn_idx);
12146         *explored_state(env, insn_idx) = new_sl;
12147         /* connect new state to parentage chain. Current frame needs all
12148          * registers connected. Only r6 - r9 of the callers are alive (pushed
12149          * to the stack implicitly by JITs) so in callers' frames connect just
12150          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
12151          * the state of the call instruction (with WRITTEN set), and r0 comes
12152          * from callee with its full parentage chain, anyway.
12153          */
12154         /* clear write marks in current state: the writes we did are not writes
12155          * our child did, so they don't screen off its reads from us.
12156          * (There are no read marks in current state, because reads always mark
12157          * their parent and current state never has children yet.  Only
12158          * explored_states can get read marks.)
12159          */
12160         for (j = 0; j <= cur->curframe; j++) {
12161                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
12162                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
12163                 for (i = 0; i < BPF_REG_FP; i++)
12164                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
12165         }
12166
12167         /* all stack frames are accessible from callee, clear them all */
12168         for (j = 0; j <= cur->curframe; j++) {
12169                 struct bpf_func_state *frame = cur->frame[j];
12170                 struct bpf_func_state *newframe = new->frame[j];
12171
12172                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
12173                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
12174                         frame->stack[i].spilled_ptr.parent =
12175                                                 &newframe->stack[i].spilled_ptr;
12176                 }
12177         }
12178         return 0;
12179 }
12180
12181 /* Return true if it's OK to have the same insn return a different type. */
12182 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
12183 {
12184         switch (base_type(type)) {
12185         case PTR_TO_CTX:
12186         case PTR_TO_SOCKET:
12187         case PTR_TO_SOCK_COMMON:
12188         case PTR_TO_TCP_SOCK:
12189         case PTR_TO_XDP_SOCK:
12190         case PTR_TO_BTF_ID:
12191                 return false;
12192         default:
12193                 return true;
12194         }
12195 }
12196
12197 /* If an instruction was previously used with particular pointer types, then we
12198  * need to be careful to avoid cases such as the below, where it may be ok
12199  * for one branch accessing the pointer, but not ok for the other branch:
12200  *
12201  * R1 = sock_ptr
12202  * goto X;
12203  * ...
12204  * R1 = some_other_valid_ptr;
12205  * goto X;
12206  * ...
12207  * R2 = *(u32 *)(R1 + 0);
12208  */
12209 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
12210 {
12211         return src != prev && (!reg_type_mismatch_ok(src) ||
12212                                !reg_type_mismatch_ok(prev));
12213 }
12214
12215 static int do_check(struct bpf_verifier_env *env)
12216 {
12217         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12218         struct bpf_verifier_state *state = env->cur_state;
12219         struct bpf_insn *insns = env->prog->insnsi;
12220         struct bpf_reg_state *regs;
12221         int insn_cnt = env->prog->len;
12222         bool do_print_state = false;
12223         int prev_insn_idx = -1;
12224
12225         for (;;) {
12226                 struct bpf_insn *insn;
12227                 u8 class;
12228                 int err;
12229
12230                 env->prev_insn_idx = prev_insn_idx;
12231                 if (env->insn_idx >= insn_cnt) {
12232                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
12233                                 env->insn_idx, insn_cnt);
12234                         return -EFAULT;
12235                 }
12236
12237                 insn = &insns[env->insn_idx];
12238                 class = BPF_CLASS(insn->code);
12239
12240                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
12241                         verbose(env,
12242                                 "BPF program is too large. Processed %d insn\n",
12243                                 env->insn_processed);
12244                         return -E2BIG;
12245                 }
12246
12247                 err = is_state_visited(env, env->insn_idx);
12248                 if (err < 0)
12249                         return err;
12250                 if (err == 1) {
12251                         /* found equivalent state, can prune the search */
12252                         if (env->log.level & BPF_LOG_LEVEL) {
12253                                 if (do_print_state)
12254                                         verbose(env, "\nfrom %d to %d%s: safe\n",
12255                                                 env->prev_insn_idx, env->insn_idx,
12256                                                 env->cur_state->speculative ?
12257                                                 " (speculative execution)" : "");
12258                                 else
12259                                         verbose(env, "%d: safe\n", env->insn_idx);
12260                         }
12261                         goto process_bpf_exit;
12262                 }
12263
12264                 if (signal_pending(current))
12265                         return -EAGAIN;
12266
12267                 if (need_resched())
12268                         cond_resched();
12269
12270                 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
12271                         verbose(env, "\nfrom %d to %d%s:",
12272                                 env->prev_insn_idx, env->insn_idx,
12273                                 env->cur_state->speculative ?
12274                                 " (speculative execution)" : "");
12275                         print_verifier_state(env, state->frame[state->curframe], true);
12276                         do_print_state = false;
12277                 }
12278
12279                 if (env->log.level & BPF_LOG_LEVEL) {
12280                         const struct bpf_insn_cbs cbs = {
12281                                 .cb_call        = disasm_kfunc_name,
12282                                 .cb_print       = verbose,
12283                                 .private_data   = env,
12284                         };
12285
12286                         if (verifier_state_scratched(env))
12287                                 print_insn_state(env, state->frame[state->curframe]);
12288
12289                         verbose_linfo(env, env->insn_idx, "; ");
12290                         env->prev_log_len = env->log.len_used;
12291                         verbose(env, "%d: ", env->insn_idx);
12292                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12293                         env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
12294                         env->prev_log_len = env->log.len_used;
12295                 }
12296
12297                 if (bpf_prog_is_dev_bound(env->prog->aux)) {
12298                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
12299                                                            env->prev_insn_idx);
12300                         if (err)
12301                                 return err;
12302                 }
12303
12304                 regs = cur_regs(env);
12305                 sanitize_mark_insn_seen(env);
12306                 prev_insn_idx = env->insn_idx;
12307
12308                 if (class == BPF_ALU || class == BPF_ALU64) {
12309                         err = check_alu_op(env, insn);
12310                         if (err)
12311                                 return err;
12312
12313                 } else if (class == BPF_LDX) {
12314                         enum bpf_reg_type *prev_src_type, src_reg_type;
12315
12316                         /* check for reserved fields is already done */
12317
12318                         /* check src operand */
12319                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
12320                         if (err)
12321                                 return err;
12322
12323                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12324                         if (err)
12325                                 return err;
12326
12327                         src_reg_type = regs[insn->src_reg].type;
12328
12329                         /* check that memory (src_reg + off) is readable,
12330                          * the state of dst_reg will be updated by this func
12331                          */
12332                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
12333                                                insn->off, BPF_SIZE(insn->code),
12334                                                BPF_READ, insn->dst_reg, false);
12335                         if (err)
12336                                 return err;
12337
12338                         prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12339
12340                         if (*prev_src_type == NOT_INIT) {
12341                                 /* saw a valid insn
12342                                  * dst_reg = *(u32 *)(src_reg + off)
12343                                  * save type to validate intersecting paths
12344                                  */
12345                                 *prev_src_type = src_reg_type;
12346
12347                         } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
12348                                 /* ABuser program is trying to use the same insn
12349                                  * dst_reg = *(u32*) (src_reg + off)
12350                                  * with different pointer types:
12351                                  * src_reg == ctx in one branch and
12352                                  * src_reg == stack|map in some other branch.
12353                                  * Reject it.
12354                                  */
12355                                 verbose(env, "same insn cannot be used with different pointers\n");
12356                                 return -EINVAL;
12357                         }
12358
12359                 } else if (class == BPF_STX) {
12360                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
12361
12362                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
12363                                 err = check_atomic(env, env->insn_idx, insn);
12364                                 if (err)
12365                                         return err;
12366                                 env->insn_idx++;
12367                                 continue;
12368                         }
12369
12370                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
12371                                 verbose(env, "BPF_STX uses reserved fields\n");
12372                                 return -EINVAL;
12373                         }
12374
12375                         /* check src1 operand */
12376                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
12377                         if (err)
12378                                 return err;
12379                         /* check src2 operand */
12380                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12381                         if (err)
12382                                 return err;
12383
12384                         dst_reg_type = regs[insn->dst_reg].type;
12385
12386                         /* check that memory (dst_reg + off) is writeable */
12387                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12388                                                insn->off, BPF_SIZE(insn->code),
12389                                                BPF_WRITE, insn->src_reg, false);
12390                         if (err)
12391                                 return err;
12392
12393                         prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12394
12395                         if (*prev_dst_type == NOT_INIT) {
12396                                 *prev_dst_type = dst_reg_type;
12397                         } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
12398                                 verbose(env, "same insn cannot be used with different pointers\n");
12399                                 return -EINVAL;
12400                         }
12401
12402                 } else if (class == BPF_ST) {
12403                         if (BPF_MODE(insn->code) != BPF_MEM ||
12404                             insn->src_reg != BPF_REG_0) {
12405                                 verbose(env, "BPF_ST uses reserved fields\n");
12406                                 return -EINVAL;
12407                         }
12408                         /* check src operand */
12409                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12410                         if (err)
12411                                 return err;
12412
12413                         if (is_ctx_reg(env, insn->dst_reg)) {
12414                                 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
12415                                         insn->dst_reg,
12416                                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
12417                                 return -EACCES;
12418                         }
12419
12420                         /* check that memory (dst_reg + off) is writeable */
12421                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12422                                                insn->off, BPF_SIZE(insn->code),
12423                                                BPF_WRITE, -1, false);
12424                         if (err)
12425                                 return err;
12426
12427                 } else if (class == BPF_JMP || class == BPF_JMP32) {
12428                         u8 opcode = BPF_OP(insn->code);
12429
12430                         env->jmps_processed++;
12431                         if (opcode == BPF_CALL) {
12432                                 if (BPF_SRC(insn->code) != BPF_K ||
12433                                     (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
12434                                      && insn->off != 0) ||
12435                                     (insn->src_reg != BPF_REG_0 &&
12436                                      insn->src_reg != BPF_PSEUDO_CALL &&
12437                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
12438                                     insn->dst_reg != BPF_REG_0 ||
12439                                     class == BPF_JMP32) {
12440                                         verbose(env, "BPF_CALL uses reserved fields\n");
12441                                         return -EINVAL;
12442                                 }
12443
12444                                 if (env->cur_state->active_spin_lock &&
12445                                     (insn->src_reg == BPF_PSEUDO_CALL ||
12446                                      insn->imm != BPF_FUNC_spin_unlock)) {
12447                                         verbose(env, "function calls are not allowed while holding a lock\n");
12448                                         return -EINVAL;
12449                                 }
12450                                 if (insn->src_reg == BPF_PSEUDO_CALL)
12451                                         err = check_func_call(env, insn, &env->insn_idx);
12452                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
12453                                         err = check_kfunc_call(env, insn, &env->insn_idx);
12454                                 else
12455                                         err = check_helper_call(env, insn, &env->insn_idx);
12456                                 if (err)
12457                                         return err;
12458                         } else if (opcode == BPF_JA) {
12459                                 if (BPF_SRC(insn->code) != BPF_K ||
12460                                     insn->imm != 0 ||
12461                                     insn->src_reg != BPF_REG_0 ||
12462                                     insn->dst_reg != BPF_REG_0 ||
12463                                     class == BPF_JMP32) {
12464                                         verbose(env, "BPF_JA uses reserved fields\n");
12465                                         return -EINVAL;
12466                                 }
12467
12468                                 env->insn_idx += insn->off + 1;
12469                                 continue;
12470
12471                         } else if (opcode == BPF_EXIT) {
12472                                 if (BPF_SRC(insn->code) != BPF_K ||
12473                                     insn->imm != 0 ||
12474                                     insn->src_reg != BPF_REG_0 ||
12475                                     insn->dst_reg != BPF_REG_0 ||
12476                                     class == BPF_JMP32) {
12477                                         verbose(env, "BPF_EXIT uses reserved fields\n");
12478                                         return -EINVAL;
12479                                 }
12480
12481                                 if (env->cur_state->active_spin_lock) {
12482                                         verbose(env, "bpf_spin_unlock is missing\n");
12483                                         return -EINVAL;
12484                                 }
12485
12486                                 /* We must do check_reference_leak here before
12487                                  * prepare_func_exit to handle the case when
12488                                  * state->curframe > 0, it may be a callback
12489                                  * function, for which reference_state must
12490                                  * match caller reference state when it exits.
12491                                  */
12492                                 err = check_reference_leak(env);
12493                                 if (err)
12494                                         return err;
12495
12496                                 if (state->curframe) {
12497                                         /* exit from nested function */
12498                                         err = prepare_func_exit(env, &env->insn_idx);
12499                                         if (err)
12500                                                 return err;
12501                                         do_print_state = true;
12502                                         continue;
12503                                 }
12504
12505                                 err = check_return_code(env);
12506                                 if (err)
12507                                         return err;
12508 process_bpf_exit:
12509                                 mark_verifier_state_scratched(env);
12510                                 update_branch_counts(env, env->cur_state);
12511                                 err = pop_stack(env, &prev_insn_idx,
12512                                                 &env->insn_idx, pop_log);
12513                                 if (err < 0) {
12514                                         if (err != -ENOENT)
12515                                                 return err;
12516                                         break;
12517                                 } else {
12518                                         do_print_state = true;
12519                                         continue;
12520                                 }
12521                         } else {
12522                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
12523                                 if (err)
12524                                         return err;
12525                         }
12526                 } else if (class == BPF_LD) {
12527                         u8 mode = BPF_MODE(insn->code);
12528
12529                         if (mode == BPF_ABS || mode == BPF_IND) {
12530                                 err = check_ld_abs(env, insn);
12531                                 if (err)
12532                                         return err;
12533
12534                         } else if (mode == BPF_IMM) {
12535                                 err = check_ld_imm(env, insn);
12536                                 if (err)
12537                                         return err;
12538
12539                                 env->insn_idx++;
12540                                 sanitize_mark_insn_seen(env);
12541                         } else {
12542                                 verbose(env, "invalid BPF_LD mode\n");
12543                                 return -EINVAL;
12544                         }
12545                 } else {
12546                         verbose(env, "unknown insn class %d\n", class);
12547                         return -EINVAL;
12548                 }
12549
12550                 env->insn_idx++;
12551         }
12552
12553         return 0;
12554 }
12555
12556 static int find_btf_percpu_datasec(struct btf *btf)
12557 {
12558         const struct btf_type *t;
12559         const char *tname;
12560         int i, n;
12561
12562         /*
12563          * Both vmlinux and module each have their own ".data..percpu"
12564          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
12565          * types to look at only module's own BTF types.
12566          */
12567         n = btf_nr_types(btf);
12568         if (btf_is_module(btf))
12569                 i = btf_nr_types(btf_vmlinux);
12570         else
12571                 i = 1;
12572
12573         for(; i < n; i++) {
12574                 t = btf_type_by_id(btf, i);
12575                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
12576                         continue;
12577
12578                 tname = btf_name_by_offset(btf, t->name_off);
12579                 if (!strcmp(tname, ".data..percpu"))
12580                         return i;
12581         }
12582
12583         return -ENOENT;
12584 }
12585
12586 /* replace pseudo btf_id with kernel symbol address */
12587 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
12588                                struct bpf_insn *insn,
12589                                struct bpf_insn_aux_data *aux)
12590 {
12591         const struct btf_var_secinfo *vsi;
12592         const struct btf_type *datasec;
12593         struct btf_mod_pair *btf_mod;
12594         const struct btf_type *t;
12595         const char *sym_name;
12596         bool percpu = false;
12597         u32 type, id = insn->imm;
12598         struct btf *btf;
12599         s32 datasec_id;
12600         u64 addr;
12601         int i, btf_fd, err;
12602
12603         btf_fd = insn[1].imm;
12604         if (btf_fd) {
12605                 btf = btf_get_by_fd(btf_fd);
12606                 if (IS_ERR(btf)) {
12607                         verbose(env, "invalid module BTF object FD specified.\n");
12608                         return -EINVAL;
12609                 }
12610         } else {
12611                 if (!btf_vmlinux) {
12612                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
12613                         return -EINVAL;
12614                 }
12615                 btf = btf_vmlinux;
12616                 btf_get(btf);
12617         }
12618
12619         t = btf_type_by_id(btf, id);
12620         if (!t) {
12621                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
12622                 err = -ENOENT;
12623                 goto err_put;
12624         }
12625
12626         if (!btf_type_is_var(t)) {
12627                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
12628                 err = -EINVAL;
12629                 goto err_put;
12630         }
12631
12632         sym_name = btf_name_by_offset(btf, t->name_off);
12633         addr = kallsyms_lookup_name(sym_name);
12634         if (!addr) {
12635                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
12636                         sym_name);
12637                 err = -ENOENT;
12638                 goto err_put;
12639         }
12640
12641         datasec_id = find_btf_percpu_datasec(btf);
12642         if (datasec_id > 0) {
12643                 datasec = btf_type_by_id(btf, datasec_id);
12644                 for_each_vsi(i, datasec, vsi) {
12645                         if (vsi->type == id) {
12646                                 percpu = true;
12647                                 break;
12648                         }
12649                 }
12650         }
12651
12652         insn[0].imm = (u32)addr;
12653         insn[1].imm = addr >> 32;
12654
12655         type = t->type;
12656         t = btf_type_skip_modifiers(btf, type, NULL);
12657         if (percpu) {
12658                 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
12659                 aux->btf_var.btf = btf;
12660                 aux->btf_var.btf_id = type;
12661         } else if (!btf_type_is_struct(t)) {
12662                 const struct btf_type *ret;
12663                 const char *tname;
12664                 u32 tsize;
12665
12666                 /* resolve the type size of ksym. */
12667                 ret = btf_resolve_size(btf, t, &tsize);
12668                 if (IS_ERR(ret)) {
12669                         tname = btf_name_by_offset(btf, t->name_off);
12670                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
12671                                 tname, PTR_ERR(ret));
12672                         err = -EINVAL;
12673                         goto err_put;
12674                 }
12675                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
12676                 aux->btf_var.mem_size = tsize;
12677         } else {
12678                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
12679                 aux->btf_var.btf = btf;
12680                 aux->btf_var.btf_id = type;
12681         }
12682
12683         /* check whether we recorded this BTF (and maybe module) already */
12684         for (i = 0; i < env->used_btf_cnt; i++) {
12685                 if (env->used_btfs[i].btf == btf) {
12686                         btf_put(btf);
12687                         return 0;
12688                 }
12689         }
12690
12691         if (env->used_btf_cnt >= MAX_USED_BTFS) {
12692                 err = -E2BIG;
12693                 goto err_put;
12694         }
12695
12696         btf_mod = &env->used_btfs[env->used_btf_cnt];
12697         btf_mod->btf = btf;
12698         btf_mod->module = NULL;
12699
12700         /* if we reference variables from kernel module, bump its refcount */
12701         if (btf_is_module(btf)) {
12702                 btf_mod->module = btf_try_get_module(btf);
12703                 if (!btf_mod->module) {
12704                         err = -ENXIO;
12705                         goto err_put;
12706                 }
12707         }
12708
12709         env->used_btf_cnt++;
12710
12711         return 0;
12712 err_put:
12713         btf_put(btf);
12714         return err;
12715 }
12716
12717 static bool is_tracing_prog_type(enum bpf_prog_type type)
12718 {
12719         switch (type) {
12720         case BPF_PROG_TYPE_KPROBE:
12721         case BPF_PROG_TYPE_TRACEPOINT:
12722         case BPF_PROG_TYPE_PERF_EVENT:
12723         case BPF_PROG_TYPE_RAW_TRACEPOINT:
12724         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
12725                 return true;
12726         default:
12727                 return false;
12728         }
12729 }
12730
12731 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
12732                                         struct bpf_map *map,
12733                                         struct bpf_prog *prog)
12734
12735 {
12736         enum bpf_prog_type prog_type = resolve_prog_type(prog);
12737
12738         if (map_value_has_spin_lock(map)) {
12739                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12740                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12741                         return -EINVAL;
12742                 }
12743
12744                 if (is_tracing_prog_type(prog_type)) {
12745                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12746                         return -EINVAL;
12747                 }
12748
12749                 if (prog->aux->sleepable) {
12750                         verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12751                         return -EINVAL;
12752                 }
12753         }
12754
12755         if (map_value_has_timer(map)) {
12756                 if (is_tracing_prog_type(prog_type)) {
12757                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
12758                         return -EINVAL;
12759                 }
12760         }
12761
12762         if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
12763             !bpf_offload_prog_map_match(prog, map)) {
12764                 verbose(env, "offload device mismatch between prog and map\n");
12765                 return -EINVAL;
12766         }
12767
12768         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12769                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12770                 return -EINVAL;
12771         }
12772
12773         if (prog->aux->sleepable)
12774                 switch (map->map_type) {
12775                 case BPF_MAP_TYPE_HASH:
12776                 case BPF_MAP_TYPE_LRU_HASH:
12777                 case BPF_MAP_TYPE_ARRAY:
12778                 case BPF_MAP_TYPE_PERCPU_HASH:
12779                 case BPF_MAP_TYPE_PERCPU_ARRAY:
12780                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12781                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12782                 case BPF_MAP_TYPE_HASH_OF_MAPS:
12783                 case BPF_MAP_TYPE_RINGBUF:
12784                 case BPF_MAP_TYPE_USER_RINGBUF:
12785                 case BPF_MAP_TYPE_INODE_STORAGE:
12786                 case BPF_MAP_TYPE_SK_STORAGE:
12787                 case BPF_MAP_TYPE_TASK_STORAGE:
12788                         break;
12789                 default:
12790                         verbose(env,
12791                                 "Sleepable programs can only use array, hash, and ringbuf maps\n");
12792                         return -EINVAL;
12793                 }
12794
12795         return 0;
12796 }
12797
12798 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12799 {
12800         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12801                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12802 }
12803
12804 /* find and rewrite pseudo imm in ld_imm64 instructions:
12805  *
12806  * 1. if it accesses map FD, replace it with actual map pointer.
12807  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12808  *
12809  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
12810  */
12811 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
12812 {
12813         struct bpf_insn *insn = env->prog->insnsi;
12814         int insn_cnt = env->prog->len;
12815         int i, j, err;
12816
12817         err = bpf_prog_calc_tag(env->prog);
12818         if (err)
12819                 return err;
12820
12821         for (i = 0; i < insn_cnt; i++, insn++) {
12822                 if (BPF_CLASS(insn->code) == BPF_LDX &&
12823                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
12824                         verbose(env, "BPF_LDX uses reserved fields\n");
12825                         return -EINVAL;
12826                 }
12827
12828                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
12829                         struct bpf_insn_aux_data *aux;
12830                         struct bpf_map *map;
12831                         struct fd f;
12832                         u64 addr;
12833                         u32 fd;
12834
12835                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
12836                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12837                             insn[1].off != 0) {
12838                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
12839                                 return -EINVAL;
12840                         }
12841
12842                         if (insn[0].src_reg == 0)
12843                                 /* valid generic load 64-bit imm */
12844                                 goto next_insn;
12845
12846                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12847                                 aux = &env->insn_aux_data[i];
12848                                 err = check_pseudo_btf_id(env, insn, aux);
12849                                 if (err)
12850                                         return err;
12851                                 goto next_insn;
12852                         }
12853
12854                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12855                                 aux = &env->insn_aux_data[i];
12856                                 aux->ptr_type = PTR_TO_FUNC;
12857                                 goto next_insn;
12858                         }
12859
12860                         /* In final convert_pseudo_ld_imm64() step, this is
12861                          * converted into regular 64-bit imm load insn.
12862                          */
12863                         switch (insn[0].src_reg) {
12864                         case BPF_PSEUDO_MAP_VALUE:
12865                         case BPF_PSEUDO_MAP_IDX_VALUE:
12866                                 break;
12867                         case BPF_PSEUDO_MAP_FD:
12868                         case BPF_PSEUDO_MAP_IDX:
12869                                 if (insn[1].imm == 0)
12870                                         break;
12871                                 fallthrough;
12872                         default:
12873                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12874                                 return -EINVAL;
12875                         }
12876
12877                         switch (insn[0].src_reg) {
12878                         case BPF_PSEUDO_MAP_IDX_VALUE:
12879                         case BPF_PSEUDO_MAP_IDX:
12880                                 if (bpfptr_is_null(env->fd_array)) {
12881                                         verbose(env, "fd_idx without fd_array is invalid\n");
12882                                         return -EPROTO;
12883                                 }
12884                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
12885                                                             insn[0].imm * sizeof(fd),
12886                                                             sizeof(fd)))
12887                                         return -EFAULT;
12888                                 break;
12889                         default:
12890                                 fd = insn[0].imm;
12891                                 break;
12892                         }
12893
12894                         f = fdget(fd);
12895                         map = __bpf_map_get(f);
12896                         if (IS_ERR(map)) {
12897                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
12898                                         insn[0].imm);
12899                                 return PTR_ERR(map);
12900                         }
12901
12902                         err = check_map_prog_compatibility(env, map, env->prog);
12903                         if (err) {
12904                                 fdput(f);
12905                                 return err;
12906                         }
12907
12908                         aux = &env->insn_aux_data[i];
12909                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12910                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12911                                 addr = (unsigned long)map;
12912                         } else {
12913                                 u32 off = insn[1].imm;
12914
12915                                 if (off >= BPF_MAX_VAR_OFF) {
12916                                         verbose(env, "direct value offset of %u is not allowed\n", off);
12917                                         fdput(f);
12918                                         return -EINVAL;
12919                                 }
12920
12921                                 if (!map->ops->map_direct_value_addr) {
12922                                         verbose(env, "no direct value access support for this map type\n");
12923                                         fdput(f);
12924                                         return -EINVAL;
12925                                 }
12926
12927                                 err = map->ops->map_direct_value_addr(map, &addr, off);
12928                                 if (err) {
12929                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12930                                                 map->value_size, off);
12931                                         fdput(f);
12932                                         return err;
12933                                 }
12934
12935                                 aux->map_off = off;
12936                                 addr += off;
12937                         }
12938
12939                         insn[0].imm = (u32)addr;
12940                         insn[1].imm = addr >> 32;
12941
12942                         /* check whether we recorded this map already */
12943                         for (j = 0; j < env->used_map_cnt; j++) {
12944                                 if (env->used_maps[j] == map) {
12945                                         aux->map_index = j;
12946                                         fdput(f);
12947                                         goto next_insn;
12948                                 }
12949                         }
12950
12951                         if (env->used_map_cnt >= MAX_USED_MAPS) {
12952                                 fdput(f);
12953                                 return -E2BIG;
12954                         }
12955
12956                         /* hold the map. If the program is rejected by verifier,
12957                          * the map will be released by release_maps() or it
12958                          * will be used by the valid program until it's unloaded
12959                          * and all maps are released in free_used_maps()
12960                          */
12961                         bpf_map_inc(map);
12962
12963                         aux->map_index = env->used_map_cnt;
12964                         env->used_maps[env->used_map_cnt++] = map;
12965
12966                         if (bpf_map_is_cgroup_storage(map) &&
12967                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
12968                                 verbose(env, "only one cgroup storage of each type is allowed\n");
12969                                 fdput(f);
12970                                 return -EBUSY;
12971                         }
12972
12973                         fdput(f);
12974 next_insn:
12975                         insn++;
12976                         i++;
12977                         continue;
12978                 }
12979
12980                 /* Basic sanity check before we invest more work here. */
12981                 if (!bpf_opcode_in_insntable(insn->code)) {
12982                         verbose(env, "unknown opcode %02x\n", insn->code);
12983                         return -EINVAL;
12984                 }
12985         }
12986
12987         /* now all pseudo BPF_LD_IMM64 instructions load valid
12988          * 'struct bpf_map *' into a register instead of user map_fd.
12989          * These pointers will be used later by verifier to validate map access.
12990          */
12991         return 0;
12992 }
12993
12994 /* drop refcnt of maps used by the rejected program */
12995 static void release_maps(struct bpf_verifier_env *env)
12996 {
12997         __bpf_free_used_maps(env->prog->aux, env->used_maps,
12998                              env->used_map_cnt);
12999 }
13000
13001 /* drop refcnt of maps used by the rejected program */
13002 static void release_btfs(struct bpf_verifier_env *env)
13003 {
13004         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
13005                              env->used_btf_cnt);
13006 }
13007
13008 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
13009 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
13010 {
13011         struct bpf_insn *insn = env->prog->insnsi;
13012         int insn_cnt = env->prog->len;
13013         int i;
13014
13015         for (i = 0; i < insn_cnt; i++, insn++) {
13016                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
13017                         continue;
13018                 if (insn->src_reg == BPF_PSEUDO_FUNC)
13019                         continue;
13020                 insn->src_reg = 0;
13021         }
13022 }
13023
13024 /* single env->prog->insni[off] instruction was replaced with the range
13025  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
13026  * [0, off) and [off, end) to new locations, so the patched range stays zero
13027  */
13028 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
13029                                  struct bpf_insn_aux_data *new_data,
13030                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
13031 {
13032         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
13033         struct bpf_insn *insn = new_prog->insnsi;
13034         u32 old_seen = old_data[off].seen;
13035         u32 prog_len;
13036         int i;
13037
13038         /* aux info at OFF always needs adjustment, no matter fast path
13039          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
13040          * original insn at old prog.
13041          */
13042         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
13043
13044         if (cnt == 1)
13045                 return;
13046         prog_len = new_prog->len;
13047
13048         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
13049         memcpy(new_data + off + cnt - 1, old_data + off,
13050                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
13051         for (i = off; i < off + cnt - 1; i++) {
13052                 /* Expand insni[off]'s seen count to the patched range. */
13053                 new_data[i].seen = old_seen;
13054                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
13055         }
13056         env->insn_aux_data = new_data;
13057         vfree(old_data);
13058 }
13059
13060 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
13061 {
13062         int i;
13063
13064         if (len == 1)
13065                 return;
13066         /* NOTE: fake 'exit' subprog should be updated as well. */
13067         for (i = 0; i <= env->subprog_cnt; i++) {
13068                 if (env->subprog_info[i].start <= off)
13069                         continue;
13070                 env->subprog_info[i].start += len - 1;
13071         }
13072 }
13073
13074 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
13075 {
13076         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
13077         int i, sz = prog->aux->size_poke_tab;
13078         struct bpf_jit_poke_descriptor *desc;
13079
13080         for (i = 0; i < sz; i++) {
13081                 desc = &tab[i];
13082                 if (desc->insn_idx <= off)
13083                         continue;
13084                 desc->insn_idx += len - 1;
13085         }
13086 }
13087
13088 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
13089                                             const struct bpf_insn *patch, u32 len)
13090 {
13091         struct bpf_prog *new_prog;
13092         struct bpf_insn_aux_data *new_data = NULL;
13093
13094         if (len > 1) {
13095                 new_data = vzalloc(array_size(env->prog->len + len - 1,
13096                                               sizeof(struct bpf_insn_aux_data)));
13097                 if (!new_data)
13098                         return NULL;
13099         }
13100
13101         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
13102         if (IS_ERR(new_prog)) {
13103                 if (PTR_ERR(new_prog) == -ERANGE)
13104                         verbose(env,
13105                                 "insn %d cannot be patched due to 16-bit range\n",
13106                                 env->insn_aux_data[off].orig_idx);
13107                 vfree(new_data);
13108                 return NULL;
13109         }
13110         adjust_insn_aux_data(env, new_data, new_prog, off, len);
13111         adjust_subprog_starts(env, off, len);
13112         adjust_poke_descs(new_prog, off, len);
13113         return new_prog;
13114 }
13115
13116 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
13117                                               u32 off, u32 cnt)
13118 {
13119         int i, j;
13120
13121         /* find first prog starting at or after off (first to remove) */
13122         for (i = 0; i < env->subprog_cnt; i++)
13123                 if (env->subprog_info[i].start >= off)
13124                         break;
13125         /* find first prog starting at or after off + cnt (first to stay) */
13126         for (j = i; j < env->subprog_cnt; j++)
13127                 if (env->subprog_info[j].start >= off + cnt)
13128                         break;
13129         /* if j doesn't start exactly at off + cnt, we are just removing
13130          * the front of previous prog
13131          */
13132         if (env->subprog_info[j].start != off + cnt)
13133                 j--;
13134
13135         if (j > i) {
13136                 struct bpf_prog_aux *aux = env->prog->aux;
13137                 int move;
13138
13139                 /* move fake 'exit' subprog as well */
13140                 move = env->subprog_cnt + 1 - j;
13141
13142                 memmove(env->subprog_info + i,
13143                         env->subprog_info + j,
13144                         sizeof(*env->subprog_info) * move);
13145                 env->subprog_cnt -= j - i;
13146
13147                 /* remove func_info */
13148                 if (aux->func_info) {
13149                         move = aux->func_info_cnt - j;
13150
13151                         memmove(aux->func_info + i,
13152                                 aux->func_info + j,
13153                                 sizeof(*aux->func_info) * move);
13154                         aux->func_info_cnt -= j - i;
13155                         /* func_info->insn_off is set after all code rewrites,
13156                          * in adjust_btf_func() - no need to adjust
13157                          */
13158                 }
13159         } else {
13160                 /* convert i from "first prog to remove" to "first to adjust" */
13161                 if (env->subprog_info[i].start == off)
13162                         i++;
13163         }
13164
13165         /* update fake 'exit' subprog as well */
13166         for (; i <= env->subprog_cnt; i++)
13167                 env->subprog_info[i].start -= cnt;
13168
13169         return 0;
13170 }
13171
13172 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
13173                                       u32 cnt)
13174 {
13175         struct bpf_prog *prog = env->prog;
13176         u32 i, l_off, l_cnt, nr_linfo;
13177         struct bpf_line_info *linfo;
13178
13179         nr_linfo = prog->aux->nr_linfo;
13180         if (!nr_linfo)
13181                 return 0;
13182
13183         linfo = prog->aux->linfo;
13184
13185         /* find first line info to remove, count lines to be removed */
13186         for (i = 0; i < nr_linfo; i++)
13187                 if (linfo[i].insn_off >= off)
13188                         break;
13189
13190         l_off = i;
13191         l_cnt = 0;
13192         for (; i < nr_linfo; i++)
13193                 if (linfo[i].insn_off < off + cnt)
13194                         l_cnt++;
13195                 else
13196                         break;
13197
13198         /* First live insn doesn't match first live linfo, it needs to "inherit"
13199          * last removed linfo.  prog is already modified, so prog->len == off
13200          * means no live instructions after (tail of the program was removed).
13201          */
13202         if (prog->len != off && l_cnt &&
13203             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
13204                 l_cnt--;
13205                 linfo[--i].insn_off = off + cnt;
13206         }
13207
13208         /* remove the line info which refer to the removed instructions */
13209         if (l_cnt) {
13210                 memmove(linfo + l_off, linfo + i,
13211                         sizeof(*linfo) * (nr_linfo - i));
13212
13213                 prog->aux->nr_linfo -= l_cnt;
13214                 nr_linfo = prog->aux->nr_linfo;
13215         }
13216
13217         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
13218         for (i = l_off; i < nr_linfo; i++)
13219                 linfo[i].insn_off -= cnt;
13220
13221         /* fix up all subprogs (incl. 'exit') which start >= off */
13222         for (i = 0; i <= env->subprog_cnt; i++)
13223                 if (env->subprog_info[i].linfo_idx > l_off) {
13224                         /* program may have started in the removed region but
13225                          * may not be fully removed
13226                          */
13227                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
13228                                 env->subprog_info[i].linfo_idx -= l_cnt;
13229                         else
13230                                 env->subprog_info[i].linfo_idx = l_off;
13231                 }
13232
13233         return 0;
13234 }
13235
13236 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
13237 {
13238         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13239         unsigned int orig_prog_len = env->prog->len;
13240         int err;
13241
13242         if (bpf_prog_is_dev_bound(env->prog->aux))
13243                 bpf_prog_offload_remove_insns(env, off, cnt);
13244
13245         err = bpf_remove_insns(env->prog, off, cnt);
13246         if (err)
13247                 return err;
13248
13249         err = adjust_subprog_starts_after_remove(env, off, cnt);
13250         if (err)
13251                 return err;
13252
13253         err = bpf_adj_linfo_after_remove(env, off, cnt);
13254         if (err)
13255                 return err;
13256
13257         memmove(aux_data + off, aux_data + off + cnt,
13258                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
13259
13260         return 0;
13261 }
13262
13263 /* The verifier does more data flow analysis than llvm and will not
13264  * explore branches that are dead at run time. Malicious programs can
13265  * have dead code too. Therefore replace all dead at-run-time code
13266  * with 'ja -1'.
13267  *
13268  * Just nops are not optimal, e.g. if they would sit at the end of the
13269  * program and through another bug we would manage to jump there, then
13270  * we'd execute beyond program memory otherwise. Returning exception
13271  * code also wouldn't work since we can have subprogs where the dead
13272  * code could be located.
13273  */
13274 static void sanitize_dead_code(struct bpf_verifier_env *env)
13275 {
13276         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13277         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
13278         struct bpf_insn *insn = env->prog->insnsi;
13279         const int insn_cnt = env->prog->len;
13280         int i;
13281
13282         for (i = 0; i < insn_cnt; i++) {
13283                 if (aux_data[i].seen)
13284                         continue;
13285                 memcpy(insn + i, &trap, sizeof(trap));
13286                 aux_data[i].zext_dst = false;
13287         }
13288 }
13289
13290 static bool insn_is_cond_jump(u8 code)
13291 {
13292         u8 op;
13293
13294         if (BPF_CLASS(code) == BPF_JMP32)
13295                 return true;
13296
13297         if (BPF_CLASS(code) != BPF_JMP)
13298                 return false;
13299
13300         op = BPF_OP(code);
13301         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
13302 }
13303
13304 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
13305 {
13306         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13307         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13308         struct bpf_insn *insn = env->prog->insnsi;
13309         const int insn_cnt = env->prog->len;
13310         int i;
13311
13312         for (i = 0; i < insn_cnt; i++, insn++) {
13313                 if (!insn_is_cond_jump(insn->code))
13314                         continue;
13315
13316                 if (!aux_data[i + 1].seen)
13317                         ja.off = insn->off;
13318                 else if (!aux_data[i + 1 + insn->off].seen)
13319                         ja.off = 0;
13320                 else
13321                         continue;
13322
13323                 if (bpf_prog_is_dev_bound(env->prog->aux))
13324                         bpf_prog_offload_replace_insn(env, i, &ja);
13325
13326                 memcpy(insn, &ja, sizeof(ja));
13327         }
13328 }
13329
13330 static int opt_remove_dead_code(struct bpf_verifier_env *env)
13331 {
13332         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13333         int insn_cnt = env->prog->len;
13334         int i, err;
13335
13336         for (i = 0; i < insn_cnt; i++) {
13337                 int j;
13338
13339                 j = 0;
13340                 while (i + j < insn_cnt && !aux_data[i + j].seen)
13341                         j++;
13342                 if (!j)
13343                         continue;
13344
13345                 err = verifier_remove_insns(env, i, j);
13346                 if (err)
13347                         return err;
13348                 insn_cnt = env->prog->len;
13349         }
13350
13351         return 0;
13352 }
13353
13354 static int opt_remove_nops(struct bpf_verifier_env *env)
13355 {
13356         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13357         struct bpf_insn *insn = env->prog->insnsi;
13358         int insn_cnt = env->prog->len;
13359         int i, err;
13360
13361         for (i = 0; i < insn_cnt; i++) {
13362                 if (memcmp(&insn[i], &ja, sizeof(ja)))
13363                         continue;
13364
13365                 err = verifier_remove_insns(env, i, 1);
13366                 if (err)
13367                         return err;
13368                 insn_cnt--;
13369                 i--;
13370         }
13371
13372         return 0;
13373 }
13374
13375 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
13376                                          const union bpf_attr *attr)
13377 {
13378         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
13379         struct bpf_insn_aux_data *aux = env->insn_aux_data;
13380         int i, patch_len, delta = 0, len = env->prog->len;
13381         struct bpf_insn *insns = env->prog->insnsi;
13382         struct bpf_prog *new_prog;
13383         bool rnd_hi32;
13384
13385         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
13386         zext_patch[1] = BPF_ZEXT_REG(0);
13387         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
13388         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
13389         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
13390         for (i = 0; i < len; i++) {
13391                 int adj_idx = i + delta;
13392                 struct bpf_insn insn;
13393                 int load_reg;
13394
13395                 insn = insns[adj_idx];
13396                 load_reg = insn_def_regno(&insn);
13397                 if (!aux[adj_idx].zext_dst) {
13398                         u8 code, class;
13399                         u32 imm_rnd;
13400
13401                         if (!rnd_hi32)
13402                                 continue;
13403
13404                         code = insn.code;
13405                         class = BPF_CLASS(code);
13406                         if (load_reg == -1)
13407                                 continue;
13408
13409                         /* NOTE: arg "reg" (the fourth one) is only used for
13410                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
13411                          *       here.
13412                          */
13413                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
13414                                 if (class == BPF_LD &&
13415                                     BPF_MODE(code) == BPF_IMM)
13416                                         i++;
13417                                 continue;
13418                         }
13419
13420                         /* ctx load could be transformed into wider load. */
13421                         if (class == BPF_LDX &&
13422                             aux[adj_idx].ptr_type == PTR_TO_CTX)
13423                                 continue;
13424
13425                         imm_rnd = get_random_u32();
13426                         rnd_hi32_patch[0] = insn;
13427                         rnd_hi32_patch[1].imm = imm_rnd;
13428                         rnd_hi32_patch[3].dst_reg = load_reg;
13429                         patch = rnd_hi32_patch;
13430                         patch_len = 4;
13431                         goto apply_patch_buffer;
13432                 }
13433
13434                 /* Add in an zero-extend instruction if a) the JIT has requested
13435                  * it or b) it's a CMPXCHG.
13436                  *
13437                  * The latter is because: BPF_CMPXCHG always loads a value into
13438                  * R0, therefore always zero-extends. However some archs'
13439                  * equivalent instruction only does this load when the
13440                  * comparison is successful. This detail of CMPXCHG is
13441                  * orthogonal to the general zero-extension behaviour of the
13442                  * CPU, so it's treated independently of bpf_jit_needs_zext.
13443                  */
13444                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
13445                         continue;
13446
13447                 /* Zero-extension is done by the caller. */
13448                 if (bpf_pseudo_kfunc_call(&insn))
13449                         continue;
13450
13451                 if (WARN_ON(load_reg == -1)) {
13452                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
13453                         return -EFAULT;
13454                 }
13455
13456                 zext_patch[0] = insn;
13457                 zext_patch[1].dst_reg = load_reg;
13458                 zext_patch[1].src_reg = load_reg;
13459                 patch = zext_patch;
13460                 patch_len = 2;
13461 apply_patch_buffer:
13462                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
13463                 if (!new_prog)
13464                         return -ENOMEM;
13465                 env->prog = new_prog;
13466                 insns = new_prog->insnsi;
13467                 aux = env->insn_aux_data;
13468                 delta += patch_len - 1;
13469         }
13470
13471         return 0;
13472 }
13473
13474 /* convert load instructions that access fields of a context type into a
13475  * sequence of instructions that access fields of the underlying structure:
13476  *     struct __sk_buff    -> struct sk_buff
13477  *     struct bpf_sock_ops -> struct sock
13478  */
13479 static int convert_ctx_accesses(struct bpf_verifier_env *env)
13480 {
13481         const struct bpf_verifier_ops *ops = env->ops;
13482         int i, cnt, size, ctx_field_size, delta = 0;
13483         const int insn_cnt = env->prog->len;
13484         struct bpf_insn insn_buf[16], *insn;
13485         u32 target_size, size_default, off;
13486         struct bpf_prog *new_prog;
13487         enum bpf_access_type type;
13488         bool is_narrower_load;
13489
13490         if (ops->gen_prologue || env->seen_direct_write) {
13491                 if (!ops->gen_prologue) {
13492                         verbose(env, "bpf verifier is misconfigured\n");
13493                         return -EINVAL;
13494                 }
13495                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
13496                                         env->prog);
13497                 if (cnt >= ARRAY_SIZE(insn_buf)) {
13498                         verbose(env, "bpf verifier is misconfigured\n");
13499                         return -EINVAL;
13500                 } else if (cnt) {
13501                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
13502                         if (!new_prog)
13503                                 return -ENOMEM;
13504
13505                         env->prog = new_prog;
13506                         delta += cnt - 1;
13507                 }
13508         }
13509
13510         if (bpf_prog_is_dev_bound(env->prog->aux))
13511                 return 0;
13512
13513         insn = env->prog->insnsi + delta;
13514
13515         for (i = 0; i < insn_cnt; i++, insn++) {
13516                 bpf_convert_ctx_access_t convert_ctx_access;
13517                 bool ctx_access;
13518
13519                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
13520                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
13521                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
13522                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
13523                         type = BPF_READ;
13524                         ctx_access = true;
13525                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
13526                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
13527                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
13528                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
13529                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
13530                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
13531                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
13532                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
13533                         type = BPF_WRITE;
13534                         ctx_access = BPF_CLASS(insn->code) == BPF_STX;
13535                 } else {
13536                         continue;
13537                 }
13538
13539                 if (type == BPF_WRITE &&
13540                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
13541                         struct bpf_insn patch[] = {
13542                                 *insn,
13543                                 BPF_ST_NOSPEC(),
13544                         };
13545
13546                         cnt = ARRAY_SIZE(patch);
13547                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
13548                         if (!new_prog)
13549                                 return -ENOMEM;
13550
13551                         delta    += cnt - 1;
13552                         env->prog = new_prog;
13553                         insn      = new_prog->insnsi + i + delta;
13554                         continue;
13555                 }
13556
13557                 if (!ctx_access)
13558                         continue;
13559
13560                 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
13561                 case PTR_TO_CTX:
13562                         if (!ops->convert_ctx_access)
13563                                 continue;
13564                         convert_ctx_access = ops->convert_ctx_access;
13565                         break;
13566                 case PTR_TO_SOCKET:
13567                 case PTR_TO_SOCK_COMMON:
13568                         convert_ctx_access = bpf_sock_convert_ctx_access;
13569                         break;
13570                 case PTR_TO_TCP_SOCK:
13571                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
13572                         break;
13573                 case PTR_TO_XDP_SOCK:
13574                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
13575                         break;
13576                 case PTR_TO_BTF_ID:
13577                 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
13578                         if (type == BPF_READ) {
13579                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
13580                                         BPF_SIZE((insn)->code);
13581                                 env->prog->aux->num_exentries++;
13582                         }
13583                         continue;
13584                 default:
13585                         continue;
13586                 }
13587
13588                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
13589                 size = BPF_LDST_BYTES(insn);
13590
13591                 /* If the read access is a narrower load of the field,
13592                  * convert to a 4/8-byte load, to minimum program type specific
13593                  * convert_ctx_access changes. If conversion is successful,
13594                  * we will apply proper mask to the result.
13595                  */
13596                 is_narrower_load = size < ctx_field_size;
13597                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
13598                 off = insn->off;
13599                 if (is_narrower_load) {
13600                         u8 size_code;
13601
13602                         if (type == BPF_WRITE) {
13603                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
13604                                 return -EINVAL;
13605                         }
13606
13607                         size_code = BPF_H;
13608                         if (ctx_field_size == 4)
13609                                 size_code = BPF_W;
13610                         else if (ctx_field_size == 8)
13611                                 size_code = BPF_DW;
13612
13613                         insn->off = off & ~(size_default - 1);
13614                         insn->code = BPF_LDX | BPF_MEM | size_code;
13615                 }
13616
13617                 target_size = 0;
13618                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
13619                                          &target_size);
13620                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
13621                     (ctx_field_size && !target_size)) {
13622                         verbose(env, "bpf verifier is misconfigured\n");
13623                         return -EINVAL;
13624                 }
13625
13626                 if (is_narrower_load && size < target_size) {
13627                         u8 shift = bpf_ctx_narrow_access_offset(
13628                                 off, size, size_default) * 8;
13629                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
13630                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
13631                                 return -EINVAL;
13632                         }
13633                         if (ctx_field_size <= 4) {
13634                                 if (shift)
13635                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
13636                                                                         insn->dst_reg,
13637                                                                         shift);
13638                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13639                                                                 (1 << size * 8) - 1);
13640                         } else {
13641                                 if (shift)
13642                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
13643                                                                         insn->dst_reg,
13644                                                                         shift);
13645                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
13646                                                                 (1ULL << size * 8) - 1);
13647                         }
13648                 }
13649
13650                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13651                 if (!new_prog)
13652                         return -ENOMEM;
13653
13654                 delta += cnt - 1;
13655
13656                 /* keep walking new program and skip insns we just inserted */
13657                 env->prog = new_prog;
13658                 insn      = new_prog->insnsi + i + delta;
13659         }
13660
13661         return 0;
13662 }
13663
13664 static int jit_subprogs(struct bpf_verifier_env *env)
13665 {
13666         struct bpf_prog *prog = env->prog, **func, *tmp;
13667         int i, j, subprog_start, subprog_end = 0, len, subprog;
13668         struct bpf_map *map_ptr;
13669         struct bpf_insn *insn;
13670         void *old_bpf_func;
13671         int err, num_exentries;
13672
13673         if (env->subprog_cnt <= 1)
13674                 return 0;
13675
13676         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13677                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
13678                         continue;
13679
13680                 /* Upon error here we cannot fall back to interpreter but
13681                  * need a hard reject of the program. Thus -EFAULT is
13682                  * propagated in any case.
13683                  */
13684                 subprog = find_subprog(env, i + insn->imm + 1);
13685                 if (subprog < 0) {
13686                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
13687                                   i + insn->imm + 1);
13688                         return -EFAULT;
13689                 }
13690                 /* temporarily remember subprog id inside insn instead of
13691                  * aux_data, since next loop will split up all insns into funcs
13692                  */
13693                 insn->off = subprog;
13694                 /* remember original imm in case JIT fails and fallback
13695                  * to interpreter will be needed
13696                  */
13697                 env->insn_aux_data[i].call_imm = insn->imm;
13698                 /* point imm to __bpf_call_base+1 from JITs point of view */
13699                 insn->imm = 1;
13700                 if (bpf_pseudo_func(insn))
13701                         /* jit (e.g. x86_64) may emit fewer instructions
13702                          * if it learns a u32 imm is the same as a u64 imm.
13703                          * Force a non zero here.
13704                          */
13705                         insn[1].imm = 1;
13706         }
13707
13708         err = bpf_prog_alloc_jited_linfo(prog);
13709         if (err)
13710                 goto out_undo_insn;
13711
13712         err = -ENOMEM;
13713         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
13714         if (!func)
13715                 goto out_undo_insn;
13716
13717         for (i = 0; i < env->subprog_cnt; i++) {
13718                 subprog_start = subprog_end;
13719                 subprog_end = env->subprog_info[i + 1].start;
13720
13721                 len = subprog_end - subprog_start;
13722                 /* bpf_prog_run() doesn't call subprogs directly,
13723                  * hence main prog stats include the runtime of subprogs.
13724                  * subprogs don't have IDs and not reachable via prog_get_next_id
13725                  * func[i]->stats will never be accessed and stays NULL
13726                  */
13727                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
13728                 if (!func[i])
13729                         goto out_free;
13730                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
13731                        len * sizeof(struct bpf_insn));
13732                 func[i]->type = prog->type;
13733                 func[i]->len = len;
13734                 if (bpf_prog_calc_tag(func[i]))
13735                         goto out_free;
13736                 func[i]->is_func = 1;
13737                 func[i]->aux->func_idx = i;
13738                 /* Below members will be freed only at prog->aux */
13739                 func[i]->aux->btf = prog->aux->btf;
13740                 func[i]->aux->func_info = prog->aux->func_info;
13741                 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
13742                 func[i]->aux->poke_tab = prog->aux->poke_tab;
13743                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13744
13745                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
13746                         struct bpf_jit_poke_descriptor *poke;
13747
13748                         poke = &prog->aux->poke_tab[j];
13749                         if (poke->insn_idx < subprog_end &&
13750                             poke->insn_idx >= subprog_start)
13751                                 poke->aux = func[i]->aux;
13752                 }
13753
13754                 func[i]->aux->name[0] = 'F';
13755                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13756                 func[i]->jit_requested = 1;
13757                 func[i]->blinding_requested = prog->blinding_requested;
13758                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13759                 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
13760                 func[i]->aux->linfo = prog->aux->linfo;
13761                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13762                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13763                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
13764                 num_exentries = 0;
13765                 insn = func[i]->insnsi;
13766                 for (j = 0; j < func[i]->len; j++, insn++) {
13767                         if (BPF_CLASS(insn->code) == BPF_LDX &&
13768                             BPF_MODE(insn->code) == BPF_PROBE_MEM)
13769                                 num_exentries++;
13770                 }
13771                 func[i]->aux->num_exentries = num_exentries;
13772                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
13773                 func[i] = bpf_int_jit_compile(func[i]);
13774                 if (!func[i]->jited) {
13775                         err = -ENOTSUPP;
13776                         goto out_free;
13777                 }
13778                 cond_resched();
13779         }
13780
13781         /* at this point all bpf functions were successfully JITed
13782          * now populate all bpf_calls with correct addresses and
13783          * run last pass of JIT
13784          */
13785         for (i = 0; i < env->subprog_cnt; i++) {
13786                 insn = func[i]->insnsi;
13787                 for (j = 0; j < func[i]->len; j++, insn++) {
13788                         if (bpf_pseudo_func(insn)) {
13789                                 subprog = insn->off;
13790                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13791                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13792                                 continue;
13793                         }
13794                         if (!bpf_pseudo_call(insn))
13795                                 continue;
13796                         subprog = insn->off;
13797                         insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
13798                 }
13799
13800                 /* we use the aux data to keep a list of the start addresses
13801                  * of the JITed images for each function in the program
13802                  *
13803                  * for some architectures, such as powerpc64, the imm field
13804                  * might not be large enough to hold the offset of the start
13805                  * address of the callee's JITed image from __bpf_call_base
13806                  *
13807                  * in such cases, we can lookup the start address of a callee
13808                  * by using its subprog id, available from the off field of
13809                  * the call instruction, as an index for this list
13810                  */
13811                 func[i]->aux->func = func;
13812                 func[i]->aux->func_cnt = env->subprog_cnt;
13813         }
13814         for (i = 0; i < env->subprog_cnt; i++) {
13815                 old_bpf_func = func[i]->bpf_func;
13816                 tmp = bpf_int_jit_compile(func[i]);
13817                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13818                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
13819                         err = -ENOTSUPP;
13820                         goto out_free;
13821                 }
13822                 cond_resched();
13823         }
13824
13825         /* finally lock prog and jit images for all functions and
13826          * populate kallsysm
13827          */
13828         for (i = 0; i < env->subprog_cnt; i++) {
13829                 bpf_prog_lock_ro(func[i]);
13830                 bpf_prog_kallsyms_add(func[i]);
13831         }
13832
13833         /* Last step: make now unused interpreter insns from main
13834          * prog consistent for later dump requests, so they can
13835          * later look the same as if they were interpreted only.
13836          */
13837         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13838                 if (bpf_pseudo_func(insn)) {
13839                         insn[0].imm = env->insn_aux_data[i].call_imm;
13840                         insn[1].imm = insn->off;
13841                         insn->off = 0;
13842                         continue;
13843                 }
13844                 if (!bpf_pseudo_call(insn))
13845                         continue;
13846                 insn->off = env->insn_aux_data[i].call_imm;
13847                 subprog = find_subprog(env, i + insn->off + 1);
13848                 insn->imm = subprog;
13849         }
13850
13851         prog->jited = 1;
13852         prog->bpf_func = func[0]->bpf_func;
13853         prog->jited_len = func[0]->jited_len;
13854         prog->aux->func = func;
13855         prog->aux->func_cnt = env->subprog_cnt;
13856         bpf_prog_jit_attempt_done(prog);
13857         return 0;
13858 out_free:
13859         /* We failed JIT'ing, so at this point we need to unregister poke
13860          * descriptors from subprogs, so that kernel is not attempting to
13861          * patch it anymore as we're freeing the subprog JIT memory.
13862          */
13863         for (i = 0; i < prog->aux->size_poke_tab; i++) {
13864                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
13865                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13866         }
13867         /* At this point we're guaranteed that poke descriptors are not
13868          * live anymore. We can just unlink its descriptor table as it's
13869          * released with the main prog.
13870          */
13871         for (i = 0; i < env->subprog_cnt; i++) {
13872                 if (!func[i])
13873                         continue;
13874                 func[i]->aux->poke_tab = NULL;
13875                 bpf_jit_free(func[i]);
13876         }
13877         kfree(func);
13878 out_undo_insn:
13879         /* cleanup main prog to be interpreted */
13880         prog->jit_requested = 0;
13881         prog->blinding_requested = 0;
13882         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13883                 if (!bpf_pseudo_call(insn))
13884                         continue;
13885                 insn->off = 0;
13886                 insn->imm = env->insn_aux_data[i].call_imm;
13887         }
13888         bpf_prog_jit_attempt_done(prog);
13889         return err;
13890 }
13891
13892 static int fixup_call_args(struct bpf_verifier_env *env)
13893 {
13894 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13895         struct bpf_prog *prog = env->prog;
13896         struct bpf_insn *insn = prog->insnsi;
13897         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13898         int i, depth;
13899 #endif
13900         int err = 0;
13901
13902         if (env->prog->jit_requested &&
13903             !bpf_prog_is_dev_bound(env->prog->aux)) {
13904                 err = jit_subprogs(env);
13905                 if (err == 0)
13906                         return 0;
13907                 if (err == -EFAULT)
13908                         return err;
13909         }
13910 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13911         if (has_kfunc_call) {
13912                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13913                 return -EINVAL;
13914         }
13915         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13916                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
13917                  * have to be rejected, since interpreter doesn't support them yet.
13918                  */
13919                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13920                 return -EINVAL;
13921         }
13922         for (i = 0; i < prog->len; i++, insn++) {
13923                 if (bpf_pseudo_func(insn)) {
13924                         /* When JIT fails the progs with callback calls
13925                          * have to be rejected, since interpreter doesn't support them yet.
13926                          */
13927                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
13928                         return -EINVAL;
13929                 }
13930
13931                 if (!bpf_pseudo_call(insn))
13932                         continue;
13933                 depth = get_callee_stack_depth(env, insn, i);
13934                 if (depth < 0)
13935                         return depth;
13936                 bpf_patch_call_args(insn, depth);
13937         }
13938         err = 0;
13939 #endif
13940         return err;
13941 }
13942
13943 static int fixup_kfunc_call(struct bpf_verifier_env *env,
13944                             struct bpf_insn *insn)
13945 {
13946         const struct bpf_kfunc_desc *desc;
13947
13948         if (!insn->imm) {
13949                 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13950                 return -EINVAL;
13951         }
13952
13953         /* insn->imm has the btf func_id. Replace it with
13954          * an address (relative to __bpf_base_call).
13955          */
13956         desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
13957         if (!desc) {
13958                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13959                         insn->imm);
13960                 return -EFAULT;
13961         }
13962
13963         insn->imm = desc->imm;
13964
13965         return 0;
13966 }
13967
13968 /* Do various post-verification rewrites in a single program pass.
13969  * These rewrites simplify JIT and interpreter implementations.
13970  */
13971 static int do_misc_fixups(struct bpf_verifier_env *env)
13972 {
13973         struct bpf_prog *prog = env->prog;
13974         enum bpf_attach_type eatype = prog->expected_attach_type;
13975         enum bpf_prog_type prog_type = resolve_prog_type(prog);
13976         struct bpf_insn *insn = prog->insnsi;
13977         const struct bpf_func_proto *fn;
13978         const int insn_cnt = prog->len;
13979         const struct bpf_map_ops *ops;
13980         struct bpf_insn_aux_data *aux;
13981         struct bpf_insn insn_buf[16];
13982         struct bpf_prog *new_prog;
13983         struct bpf_map *map_ptr;
13984         int i, ret, cnt, delta = 0;
13985
13986         for (i = 0; i < insn_cnt; i++, insn++) {
13987                 /* Make divide-by-zero exceptions impossible. */
13988                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
13989                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
13990                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
13991                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
13992                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
13993                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
13994                         struct bpf_insn *patchlet;
13995                         struct bpf_insn chk_and_div[] = {
13996                                 /* [R,W]x div 0 -> 0 */
13997                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13998                                              BPF_JNE | BPF_K, insn->src_reg,
13999                                              0, 2, 0),
14000                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
14001                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
14002                                 *insn,
14003                         };
14004                         struct bpf_insn chk_and_mod[] = {
14005                                 /* [R,W]x mod 0 -> [R,W]x */
14006                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
14007                                              BPF_JEQ | BPF_K, insn->src_reg,
14008                                              0, 1 + (is64 ? 0 : 1), 0),
14009                                 *insn,
14010                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
14011                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
14012                         };
14013
14014                         patchlet = isdiv ? chk_and_div : chk_and_mod;
14015                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
14016                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
14017
14018                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
14019                         if (!new_prog)
14020                                 return -ENOMEM;
14021
14022                         delta    += cnt - 1;
14023                         env->prog = prog = new_prog;
14024                         insn      = new_prog->insnsi + i + delta;
14025                         continue;
14026                 }
14027
14028                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
14029                 if (BPF_CLASS(insn->code) == BPF_LD &&
14030                     (BPF_MODE(insn->code) == BPF_ABS ||
14031                      BPF_MODE(insn->code) == BPF_IND)) {
14032                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
14033                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14034                                 verbose(env, "bpf verifier is misconfigured\n");
14035                                 return -EINVAL;
14036                         }
14037
14038                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14039                         if (!new_prog)
14040                                 return -ENOMEM;
14041
14042                         delta    += cnt - 1;
14043                         env->prog = prog = new_prog;
14044                         insn      = new_prog->insnsi + i + delta;
14045                         continue;
14046                 }
14047
14048                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
14049                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
14050                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
14051                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
14052                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
14053                         struct bpf_insn *patch = &insn_buf[0];
14054                         bool issrc, isneg, isimm;
14055                         u32 off_reg;
14056
14057                         aux = &env->insn_aux_data[i + delta];
14058                         if (!aux->alu_state ||
14059                             aux->alu_state == BPF_ALU_NON_POINTER)
14060                                 continue;
14061
14062                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
14063                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
14064                                 BPF_ALU_SANITIZE_SRC;
14065                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
14066
14067                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
14068                         if (isimm) {
14069                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14070                         } else {
14071                                 if (isneg)
14072                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14073                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14074                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
14075                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
14076                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
14077                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
14078                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
14079                         }
14080                         if (!issrc)
14081                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
14082                         insn->src_reg = BPF_REG_AX;
14083                         if (isneg)
14084                                 insn->code = insn->code == code_add ?
14085                                              code_sub : code_add;
14086                         *patch++ = *insn;
14087                         if (issrc && isneg && !isimm)
14088                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14089                         cnt = patch - insn_buf;
14090
14091                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14092                         if (!new_prog)
14093                                 return -ENOMEM;
14094
14095                         delta    += cnt - 1;
14096                         env->prog = prog = new_prog;
14097                         insn      = new_prog->insnsi + i + delta;
14098                         continue;
14099                 }
14100
14101                 if (insn->code != (BPF_JMP | BPF_CALL))
14102                         continue;
14103                 if (insn->src_reg == BPF_PSEUDO_CALL)
14104                         continue;
14105                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14106                         ret = fixup_kfunc_call(env, insn);
14107                         if (ret)
14108                                 return ret;
14109                         continue;
14110                 }
14111
14112                 if (insn->imm == BPF_FUNC_get_route_realm)
14113                         prog->dst_needed = 1;
14114                 if (insn->imm == BPF_FUNC_get_prandom_u32)
14115                         bpf_user_rnd_init_once();
14116                 if (insn->imm == BPF_FUNC_override_return)
14117                         prog->kprobe_override = 1;
14118                 if (insn->imm == BPF_FUNC_tail_call) {
14119                         /* If we tail call into other programs, we
14120                          * cannot make any assumptions since they can
14121                          * be replaced dynamically during runtime in
14122                          * the program array.
14123                          */
14124                         prog->cb_access = 1;
14125                         if (!allow_tail_call_in_subprogs(env))
14126                                 prog->aux->stack_depth = MAX_BPF_STACK;
14127                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
14128
14129                         /* mark bpf_tail_call as different opcode to avoid
14130                          * conditional branch in the interpreter for every normal
14131                          * call and to prevent accidental JITing by JIT compiler
14132                          * that doesn't support bpf_tail_call yet
14133                          */
14134                         insn->imm = 0;
14135                         insn->code = BPF_JMP | BPF_TAIL_CALL;
14136
14137                         aux = &env->insn_aux_data[i + delta];
14138                         if (env->bpf_capable && !prog->blinding_requested &&
14139                             prog->jit_requested &&
14140                             !bpf_map_key_poisoned(aux) &&
14141                             !bpf_map_ptr_poisoned(aux) &&
14142                             !bpf_map_ptr_unpriv(aux)) {
14143                                 struct bpf_jit_poke_descriptor desc = {
14144                                         .reason = BPF_POKE_REASON_TAIL_CALL,
14145                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
14146                                         .tail_call.key = bpf_map_key_immediate(aux),
14147                                         .insn_idx = i + delta,
14148                                 };
14149
14150                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
14151                                 if (ret < 0) {
14152                                         verbose(env, "adding tail call poke descriptor failed\n");
14153                                         return ret;
14154                                 }
14155
14156                                 insn->imm = ret + 1;
14157                                 continue;
14158                         }
14159
14160                         if (!bpf_map_ptr_unpriv(aux))
14161                                 continue;
14162
14163                         /* instead of changing every JIT dealing with tail_call
14164                          * emit two extra insns:
14165                          * if (index >= max_entries) goto out;
14166                          * index &= array->index_mask;
14167                          * to avoid out-of-bounds cpu speculation
14168                          */
14169                         if (bpf_map_ptr_poisoned(aux)) {
14170                                 verbose(env, "tail_call abusing map_ptr\n");
14171                                 return -EINVAL;
14172                         }
14173
14174                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14175                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
14176                                                   map_ptr->max_entries, 2);
14177                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
14178                                                     container_of(map_ptr,
14179                                                                  struct bpf_array,
14180                                                                  map)->index_mask);
14181                         insn_buf[2] = *insn;
14182                         cnt = 3;
14183                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14184                         if (!new_prog)
14185                                 return -ENOMEM;
14186
14187                         delta    += cnt - 1;
14188                         env->prog = prog = new_prog;
14189                         insn      = new_prog->insnsi + i + delta;
14190                         continue;
14191                 }
14192
14193                 if (insn->imm == BPF_FUNC_timer_set_callback) {
14194                         /* The verifier will process callback_fn as many times as necessary
14195                          * with different maps and the register states prepared by
14196                          * set_timer_callback_state will be accurate.
14197                          *
14198                          * The following use case is valid:
14199                          *   map1 is shared by prog1, prog2, prog3.
14200                          *   prog1 calls bpf_timer_init for some map1 elements
14201                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
14202                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
14203                          *   prog3 calls bpf_timer_start for some map1 elements.
14204                          *     Those that were not both bpf_timer_init-ed and
14205                          *     bpf_timer_set_callback-ed will return -EINVAL.
14206                          */
14207                         struct bpf_insn ld_addrs[2] = {
14208                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
14209                         };
14210
14211                         insn_buf[0] = ld_addrs[0];
14212                         insn_buf[1] = ld_addrs[1];
14213                         insn_buf[2] = *insn;
14214                         cnt = 3;
14215
14216                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14217                         if (!new_prog)
14218                                 return -ENOMEM;
14219
14220                         delta    += cnt - 1;
14221                         env->prog = prog = new_prog;
14222                         insn      = new_prog->insnsi + i + delta;
14223                         goto patch_call_imm;
14224                 }
14225
14226                 if (insn->imm == BPF_FUNC_task_storage_get ||
14227                     insn->imm == BPF_FUNC_sk_storage_get ||
14228                     insn->imm == BPF_FUNC_inode_storage_get) {
14229                         if (env->prog->aux->sleepable)
14230                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
14231                         else
14232                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
14233                         insn_buf[1] = *insn;
14234                         cnt = 2;
14235
14236                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14237                         if (!new_prog)
14238                                 return -ENOMEM;
14239
14240                         delta += cnt - 1;
14241                         env->prog = prog = new_prog;
14242                         insn = new_prog->insnsi + i + delta;
14243                         goto patch_call_imm;
14244                 }
14245
14246                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
14247                  * and other inlining handlers are currently limited to 64 bit
14248                  * only.
14249                  */
14250                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14251                     (insn->imm == BPF_FUNC_map_lookup_elem ||
14252                      insn->imm == BPF_FUNC_map_update_elem ||
14253                      insn->imm == BPF_FUNC_map_delete_elem ||
14254                      insn->imm == BPF_FUNC_map_push_elem   ||
14255                      insn->imm == BPF_FUNC_map_pop_elem    ||
14256                      insn->imm == BPF_FUNC_map_peek_elem   ||
14257                      insn->imm == BPF_FUNC_redirect_map    ||
14258                      insn->imm == BPF_FUNC_for_each_map_elem ||
14259                      insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
14260                         aux = &env->insn_aux_data[i + delta];
14261                         if (bpf_map_ptr_poisoned(aux))
14262                                 goto patch_call_imm;
14263
14264                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14265                         ops = map_ptr->ops;
14266                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
14267                             ops->map_gen_lookup) {
14268                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
14269                                 if (cnt == -EOPNOTSUPP)
14270                                         goto patch_map_ops_generic;
14271                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14272                                         verbose(env, "bpf verifier is misconfigured\n");
14273                                         return -EINVAL;
14274                                 }
14275
14276                                 new_prog = bpf_patch_insn_data(env, i + delta,
14277                                                                insn_buf, cnt);
14278                                 if (!new_prog)
14279                                         return -ENOMEM;
14280
14281                                 delta    += cnt - 1;
14282                                 env->prog = prog = new_prog;
14283                                 insn      = new_prog->insnsi + i + delta;
14284                                 continue;
14285                         }
14286
14287                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
14288                                      (void *(*)(struct bpf_map *map, void *key))NULL));
14289                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
14290                                      (int (*)(struct bpf_map *map, void *key))NULL));
14291                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
14292                                      (int (*)(struct bpf_map *map, void *key, void *value,
14293                                               u64 flags))NULL));
14294                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
14295                                      (int (*)(struct bpf_map *map, void *value,
14296                                               u64 flags))NULL));
14297                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
14298                                      (int (*)(struct bpf_map *map, void *value))NULL));
14299                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
14300                                      (int (*)(struct bpf_map *map, void *value))NULL));
14301                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
14302                                      (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
14303                         BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
14304                                      (int (*)(struct bpf_map *map,
14305                                               bpf_callback_t callback_fn,
14306                                               void *callback_ctx,
14307                                               u64 flags))NULL));
14308                         BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
14309                                      (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
14310
14311 patch_map_ops_generic:
14312                         switch (insn->imm) {
14313                         case BPF_FUNC_map_lookup_elem:
14314                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
14315                                 continue;
14316                         case BPF_FUNC_map_update_elem:
14317                                 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
14318                                 continue;
14319                         case BPF_FUNC_map_delete_elem:
14320                                 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
14321                                 continue;
14322                         case BPF_FUNC_map_push_elem:
14323                                 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
14324                                 continue;
14325                         case BPF_FUNC_map_pop_elem:
14326                                 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
14327                                 continue;
14328                         case BPF_FUNC_map_peek_elem:
14329                                 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
14330                                 continue;
14331                         case BPF_FUNC_redirect_map:
14332                                 insn->imm = BPF_CALL_IMM(ops->map_redirect);
14333                                 continue;
14334                         case BPF_FUNC_for_each_map_elem:
14335                                 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
14336                                 continue;
14337                         case BPF_FUNC_map_lookup_percpu_elem:
14338                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
14339                                 continue;
14340                         }
14341
14342                         goto patch_call_imm;
14343                 }
14344
14345                 /* Implement bpf_jiffies64 inline. */
14346                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14347                     insn->imm == BPF_FUNC_jiffies64) {
14348                         struct bpf_insn ld_jiffies_addr[2] = {
14349                                 BPF_LD_IMM64(BPF_REG_0,
14350                                              (unsigned long)&jiffies),
14351                         };
14352
14353                         insn_buf[0] = ld_jiffies_addr[0];
14354                         insn_buf[1] = ld_jiffies_addr[1];
14355                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
14356                                                   BPF_REG_0, 0);
14357                         cnt = 3;
14358
14359                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
14360                                                        cnt);
14361                         if (!new_prog)
14362                                 return -ENOMEM;
14363
14364                         delta    += cnt - 1;
14365                         env->prog = prog = new_prog;
14366                         insn      = new_prog->insnsi + i + delta;
14367                         continue;
14368                 }
14369
14370                 /* Implement bpf_get_func_arg inline. */
14371                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14372                     insn->imm == BPF_FUNC_get_func_arg) {
14373                         /* Load nr_args from ctx - 8 */
14374                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14375                         insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
14376                         insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
14377                         insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
14378                         insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
14379                         insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14380                         insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
14381                         insn_buf[7] = BPF_JMP_A(1);
14382                         insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
14383                         cnt = 9;
14384
14385                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14386                         if (!new_prog)
14387                                 return -ENOMEM;
14388
14389                         delta    += cnt - 1;
14390                         env->prog = prog = new_prog;
14391                         insn      = new_prog->insnsi + i + delta;
14392                         continue;
14393                 }
14394
14395                 /* Implement bpf_get_func_ret inline. */
14396                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14397                     insn->imm == BPF_FUNC_get_func_ret) {
14398                         if (eatype == BPF_TRACE_FEXIT ||
14399                             eatype == BPF_MODIFY_RETURN) {
14400                                 /* Load nr_args from ctx - 8 */
14401                                 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14402                                 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
14403                                 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
14404                                 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14405                                 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
14406                                 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
14407                                 cnt = 6;
14408                         } else {
14409                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
14410                                 cnt = 1;
14411                         }
14412
14413                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14414                         if (!new_prog)
14415                                 return -ENOMEM;
14416
14417                         delta    += cnt - 1;
14418                         env->prog = prog = new_prog;
14419                         insn      = new_prog->insnsi + i + delta;
14420                         continue;
14421                 }
14422
14423                 /* Implement get_func_arg_cnt inline. */
14424                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14425                     insn->imm == BPF_FUNC_get_func_arg_cnt) {
14426                         /* Load nr_args from ctx - 8 */
14427                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14428
14429                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14430                         if (!new_prog)
14431                                 return -ENOMEM;
14432
14433                         env->prog = prog = new_prog;
14434                         insn      = new_prog->insnsi + i + delta;
14435                         continue;
14436                 }
14437
14438                 /* Implement bpf_get_func_ip inline. */
14439                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14440                     insn->imm == BPF_FUNC_get_func_ip) {
14441                         /* Load IP address from ctx - 16 */
14442                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
14443
14444                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14445                         if (!new_prog)
14446                                 return -ENOMEM;
14447
14448                         env->prog = prog = new_prog;
14449                         insn      = new_prog->insnsi + i + delta;
14450                         continue;
14451                 }
14452
14453 patch_call_imm:
14454                 fn = env->ops->get_func_proto(insn->imm, env->prog);
14455                 /* all functions that have prototype and verifier allowed
14456                  * programs to call them, must be real in-kernel functions
14457                  */
14458                 if (!fn->func) {
14459                         verbose(env,
14460                                 "kernel subsystem misconfigured func %s#%d\n",
14461                                 func_id_name(insn->imm), insn->imm);
14462                         return -EFAULT;
14463                 }
14464                 insn->imm = fn->func - __bpf_call_base;
14465         }
14466
14467         /* Since poke tab is now finalized, publish aux to tracker. */
14468         for (i = 0; i < prog->aux->size_poke_tab; i++) {
14469                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
14470                 if (!map_ptr->ops->map_poke_track ||
14471                     !map_ptr->ops->map_poke_untrack ||
14472                     !map_ptr->ops->map_poke_run) {
14473                         verbose(env, "bpf verifier is misconfigured\n");
14474                         return -EINVAL;
14475                 }
14476
14477                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
14478                 if (ret < 0) {
14479                         verbose(env, "tracking tail call prog failed\n");
14480                         return ret;
14481                 }
14482         }
14483
14484         sort_kfunc_descs_by_imm(env->prog);
14485
14486         return 0;
14487 }
14488
14489 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
14490                                         int position,
14491                                         s32 stack_base,
14492                                         u32 callback_subprogno,
14493                                         u32 *cnt)
14494 {
14495         s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
14496         s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
14497         s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
14498         int reg_loop_max = BPF_REG_6;
14499         int reg_loop_cnt = BPF_REG_7;
14500         int reg_loop_ctx = BPF_REG_8;
14501
14502         struct bpf_prog *new_prog;
14503         u32 callback_start;
14504         u32 call_insn_offset;
14505         s32 callback_offset;
14506
14507         /* This represents an inlined version of bpf_iter.c:bpf_loop,
14508          * be careful to modify this code in sync.
14509          */
14510         struct bpf_insn insn_buf[] = {
14511                 /* Return error and jump to the end of the patch if
14512                  * expected number of iterations is too big.
14513                  */
14514                 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
14515                 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
14516                 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
14517                 /* spill R6, R7, R8 to use these as loop vars */
14518                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
14519                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
14520                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
14521                 /* initialize loop vars */
14522                 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
14523                 BPF_MOV32_IMM(reg_loop_cnt, 0),
14524                 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
14525                 /* loop header,
14526                  * if reg_loop_cnt >= reg_loop_max skip the loop body
14527                  */
14528                 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
14529                 /* callback call,
14530                  * correct callback offset would be set after patching
14531                  */
14532                 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
14533                 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
14534                 BPF_CALL_REL(0),
14535                 /* increment loop counter */
14536                 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
14537                 /* jump to loop header if callback returned 0 */
14538                 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
14539                 /* return value of bpf_loop,
14540                  * set R0 to the number of iterations
14541                  */
14542                 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
14543                 /* restore original values of R6, R7, R8 */
14544                 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
14545                 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
14546                 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
14547         };
14548
14549         *cnt = ARRAY_SIZE(insn_buf);
14550         new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
14551         if (!new_prog)
14552                 return new_prog;
14553
14554         /* callback start is known only after patching */
14555         callback_start = env->subprog_info[callback_subprogno].start;
14556         /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
14557         call_insn_offset = position + 12;
14558         callback_offset = callback_start - call_insn_offset - 1;
14559         new_prog->insnsi[call_insn_offset].imm = callback_offset;
14560
14561         return new_prog;
14562 }
14563
14564 static bool is_bpf_loop_call(struct bpf_insn *insn)
14565 {
14566         return insn->code == (BPF_JMP | BPF_CALL) &&
14567                 insn->src_reg == 0 &&
14568                 insn->imm == BPF_FUNC_loop;
14569 }
14570
14571 /* For all sub-programs in the program (including main) check
14572  * insn_aux_data to see if there are bpf_loop calls that require
14573  * inlining. If such calls are found the calls are replaced with a
14574  * sequence of instructions produced by `inline_bpf_loop` function and
14575  * subprog stack_depth is increased by the size of 3 registers.
14576  * This stack space is used to spill values of the R6, R7, R8.  These
14577  * registers are used to store the loop bound, counter and context
14578  * variables.
14579  */
14580 static int optimize_bpf_loop(struct bpf_verifier_env *env)
14581 {
14582         struct bpf_subprog_info *subprogs = env->subprog_info;
14583         int i, cur_subprog = 0, cnt, delta = 0;
14584         struct bpf_insn *insn = env->prog->insnsi;
14585         int insn_cnt = env->prog->len;
14586         u16 stack_depth = subprogs[cur_subprog].stack_depth;
14587         u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14588         u16 stack_depth_extra = 0;
14589
14590         for (i = 0; i < insn_cnt; i++, insn++) {
14591                 struct bpf_loop_inline_state *inline_state =
14592                         &env->insn_aux_data[i + delta].loop_inline_state;
14593
14594                 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
14595                         struct bpf_prog *new_prog;
14596
14597                         stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
14598                         new_prog = inline_bpf_loop(env,
14599                                                    i + delta,
14600                                                    -(stack_depth + stack_depth_extra),
14601                                                    inline_state->callback_subprogno,
14602                                                    &cnt);
14603                         if (!new_prog)
14604                                 return -ENOMEM;
14605
14606                         delta     += cnt - 1;
14607                         env->prog  = new_prog;
14608                         insn       = new_prog->insnsi + i + delta;
14609                 }
14610
14611                 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
14612                         subprogs[cur_subprog].stack_depth += stack_depth_extra;
14613                         cur_subprog++;
14614                         stack_depth = subprogs[cur_subprog].stack_depth;
14615                         stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14616                         stack_depth_extra = 0;
14617                 }
14618         }
14619
14620         env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14621
14622         return 0;
14623 }
14624
14625 static void free_states(struct bpf_verifier_env *env)
14626 {
14627         struct bpf_verifier_state_list *sl, *sln;
14628         int i;
14629
14630         sl = env->free_list;
14631         while (sl) {
14632                 sln = sl->next;
14633                 free_verifier_state(&sl->state, false);
14634                 kfree(sl);
14635                 sl = sln;
14636         }
14637         env->free_list = NULL;
14638
14639         if (!env->explored_states)
14640                 return;
14641
14642         for (i = 0; i < state_htab_size(env); i++) {
14643                 sl = env->explored_states[i];
14644
14645                 while (sl) {
14646                         sln = sl->next;
14647                         free_verifier_state(&sl->state, false);
14648                         kfree(sl);
14649                         sl = sln;
14650                 }
14651                 env->explored_states[i] = NULL;
14652         }
14653 }
14654
14655 static int do_check_common(struct bpf_verifier_env *env, int subprog)
14656 {
14657         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14658         struct bpf_verifier_state *state;
14659         struct bpf_reg_state *regs;
14660         int ret, i;
14661
14662         env->prev_linfo = NULL;
14663         env->pass_cnt++;
14664
14665         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
14666         if (!state)
14667                 return -ENOMEM;
14668         state->curframe = 0;
14669         state->speculative = false;
14670         state->branches = 1;
14671         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
14672         if (!state->frame[0]) {
14673                 kfree(state);
14674                 return -ENOMEM;
14675         }
14676         env->cur_state = state;
14677         init_func_state(env, state->frame[0],
14678                         BPF_MAIN_FUNC /* callsite */,
14679                         0 /* frameno */,
14680                         subprog);
14681
14682         regs = state->frame[state->curframe]->regs;
14683         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
14684                 ret = btf_prepare_func_args(env, subprog, regs);
14685                 if (ret)
14686                         goto out;
14687                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
14688                         if (regs[i].type == PTR_TO_CTX)
14689                                 mark_reg_known_zero(env, regs, i);
14690                         else if (regs[i].type == SCALAR_VALUE)
14691                                 mark_reg_unknown(env, regs, i);
14692                         else if (base_type(regs[i].type) == PTR_TO_MEM) {
14693                                 const u32 mem_size = regs[i].mem_size;
14694
14695                                 mark_reg_known_zero(env, regs, i);
14696                                 regs[i].mem_size = mem_size;
14697                                 regs[i].id = ++env->id_gen;
14698                         }
14699                 }
14700         } else {
14701                 /* 1st arg to a function */
14702                 regs[BPF_REG_1].type = PTR_TO_CTX;
14703                 mark_reg_known_zero(env, regs, BPF_REG_1);
14704                 ret = btf_check_subprog_arg_match(env, subprog, regs);
14705                 if (ret == -EFAULT)
14706                         /* unlikely verifier bug. abort.
14707                          * ret == 0 and ret < 0 are sadly acceptable for
14708                          * main() function due to backward compatibility.
14709                          * Like socket filter program may be written as:
14710                          * int bpf_prog(struct pt_regs *ctx)
14711                          * and never dereference that ctx in the program.
14712                          * 'struct pt_regs' is a type mismatch for socket
14713                          * filter that should be using 'struct __sk_buff'.
14714                          */
14715                         goto out;
14716         }
14717
14718         ret = do_check(env);
14719 out:
14720         /* check for NULL is necessary, since cur_state can be freed inside
14721          * do_check() under memory pressure.
14722          */
14723         if (env->cur_state) {
14724                 free_verifier_state(env->cur_state, true);
14725                 env->cur_state = NULL;
14726         }
14727         while (!pop_stack(env, NULL, NULL, false));
14728         if (!ret && pop_log)
14729                 bpf_vlog_reset(&env->log, 0);
14730         free_states(env);
14731         return ret;
14732 }
14733
14734 /* Verify all global functions in a BPF program one by one based on their BTF.
14735  * All global functions must pass verification. Otherwise the whole program is rejected.
14736  * Consider:
14737  * int bar(int);
14738  * int foo(int f)
14739  * {
14740  *    return bar(f);
14741  * }
14742  * int bar(int b)
14743  * {
14744  *    ...
14745  * }
14746  * foo() will be verified first for R1=any_scalar_value. During verification it
14747  * will be assumed that bar() already verified successfully and call to bar()
14748  * from foo() will be checked for type match only. Later bar() will be verified
14749  * independently to check that it's safe for R1=any_scalar_value.
14750  */
14751 static int do_check_subprogs(struct bpf_verifier_env *env)
14752 {
14753         struct bpf_prog_aux *aux = env->prog->aux;
14754         int i, ret;
14755
14756         if (!aux->func_info)
14757                 return 0;
14758
14759         for (i = 1; i < env->subprog_cnt; i++) {
14760                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
14761                         continue;
14762                 env->insn_idx = env->subprog_info[i].start;
14763                 WARN_ON_ONCE(env->insn_idx == 0);
14764                 ret = do_check_common(env, i);
14765                 if (ret) {
14766                         return ret;
14767                 } else if (env->log.level & BPF_LOG_LEVEL) {
14768                         verbose(env,
14769                                 "Func#%d is safe for any args that match its prototype\n",
14770                                 i);
14771                 }
14772         }
14773         return 0;
14774 }
14775
14776 static int do_check_main(struct bpf_verifier_env *env)
14777 {
14778         int ret;
14779
14780         env->insn_idx = 0;
14781         ret = do_check_common(env, 0);
14782         if (!ret)
14783                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14784         return ret;
14785 }
14786
14787
14788 static void print_verification_stats(struct bpf_verifier_env *env)
14789 {
14790         int i;
14791
14792         if (env->log.level & BPF_LOG_STATS) {
14793                 verbose(env, "verification time %lld usec\n",
14794                         div_u64(env->verification_time, 1000));
14795                 verbose(env, "stack depth ");
14796                 for (i = 0; i < env->subprog_cnt; i++) {
14797                         u32 depth = env->subprog_info[i].stack_depth;
14798
14799                         verbose(env, "%d", depth);
14800                         if (i + 1 < env->subprog_cnt)
14801                                 verbose(env, "+");
14802                 }
14803                 verbose(env, "\n");
14804         }
14805         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
14806                 "total_states %d peak_states %d mark_read %d\n",
14807                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
14808                 env->max_states_per_insn, env->total_states,
14809                 env->peak_states, env->longest_mark_read_walk);
14810 }
14811
14812 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
14813 {
14814         const struct btf_type *t, *func_proto;
14815         const struct bpf_struct_ops *st_ops;
14816         const struct btf_member *member;
14817         struct bpf_prog *prog = env->prog;
14818         u32 btf_id, member_idx;
14819         const char *mname;
14820
14821         if (!prog->gpl_compatible) {
14822                 verbose(env, "struct ops programs must have a GPL compatible license\n");
14823                 return -EINVAL;
14824         }
14825
14826         btf_id = prog->aux->attach_btf_id;
14827         st_ops = bpf_struct_ops_find(btf_id);
14828         if (!st_ops) {
14829                 verbose(env, "attach_btf_id %u is not a supported struct\n",
14830                         btf_id);
14831                 return -ENOTSUPP;
14832         }
14833
14834         t = st_ops->type;
14835         member_idx = prog->expected_attach_type;
14836         if (member_idx >= btf_type_vlen(t)) {
14837                 verbose(env, "attach to invalid member idx %u of struct %s\n",
14838                         member_idx, st_ops->name);
14839                 return -EINVAL;
14840         }
14841
14842         member = &btf_type_member(t)[member_idx];
14843         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
14844         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
14845                                                NULL);
14846         if (!func_proto) {
14847                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
14848                         mname, member_idx, st_ops->name);
14849                 return -EINVAL;
14850         }
14851
14852         if (st_ops->check_member) {
14853                 int err = st_ops->check_member(t, member);
14854
14855                 if (err) {
14856                         verbose(env, "attach to unsupported member %s of struct %s\n",
14857                                 mname, st_ops->name);
14858                         return err;
14859                 }
14860         }
14861
14862         prog->aux->attach_func_proto = func_proto;
14863         prog->aux->attach_func_name = mname;
14864         env->ops = st_ops->verifier_ops;
14865
14866         return 0;
14867 }
14868 #define SECURITY_PREFIX "security_"
14869
14870 static int check_attach_modify_return(unsigned long addr, const char *func_name)
14871 {
14872         if (within_error_injection_list(addr) ||
14873             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
14874                 return 0;
14875
14876         return -EINVAL;
14877 }
14878
14879 /* list of non-sleepable functions that are otherwise on
14880  * ALLOW_ERROR_INJECTION list
14881  */
14882 BTF_SET_START(btf_non_sleepable_error_inject)
14883 /* Three functions below can be called from sleepable and non-sleepable context.
14884  * Assume non-sleepable from bpf safety point of view.
14885  */
14886 BTF_ID(func, __filemap_add_folio)
14887 BTF_ID(func, should_fail_alloc_page)
14888 BTF_ID(func, should_failslab)
14889 BTF_SET_END(btf_non_sleepable_error_inject)
14890
14891 static int check_non_sleepable_error_inject(u32 btf_id)
14892 {
14893         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14894 }
14895
14896 int bpf_check_attach_target(struct bpf_verifier_log *log,
14897                             const struct bpf_prog *prog,
14898                             const struct bpf_prog *tgt_prog,
14899                             u32 btf_id,
14900                             struct bpf_attach_target_info *tgt_info)
14901 {
14902         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
14903         const char prefix[] = "btf_trace_";
14904         int ret = 0, subprog = -1, i;
14905         const struct btf_type *t;
14906         bool conservative = true;
14907         const char *tname;
14908         struct btf *btf;
14909         long addr = 0;
14910
14911         if (!btf_id) {
14912                 bpf_log(log, "Tracing programs must provide btf_id\n");
14913                 return -EINVAL;
14914         }
14915         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
14916         if (!btf) {
14917                 bpf_log(log,
14918                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
14919                 return -EINVAL;
14920         }
14921         t = btf_type_by_id(btf, btf_id);
14922         if (!t) {
14923                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
14924                 return -EINVAL;
14925         }
14926         tname = btf_name_by_offset(btf, t->name_off);
14927         if (!tname) {
14928                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
14929                 return -EINVAL;
14930         }
14931         if (tgt_prog) {
14932                 struct bpf_prog_aux *aux = tgt_prog->aux;
14933
14934                 for (i = 0; i < aux->func_info_cnt; i++)
14935                         if (aux->func_info[i].type_id == btf_id) {
14936                                 subprog = i;
14937                                 break;
14938                         }
14939                 if (subprog == -1) {
14940                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
14941                         return -EINVAL;
14942                 }
14943                 conservative = aux->func_info_aux[subprog].unreliable;
14944                 if (prog_extension) {
14945                         if (conservative) {
14946                                 bpf_log(log,
14947                                         "Cannot replace static functions\n");
14948                                 return -EINVAL;
14949                         }
14950                         if (!prog->jit_requested) {
14951                                 bpf_log(log,
14952                                         "Extension programs should be JITed\n");
14953                                 return -EINVAL;
14954                         }
14955                 }
14956                 if (!tgt_prog->jited) {
14957                         bpf_log(log, "Can attach to only JITed progs\n");
14958                         return -EINVAL;
14959                 }
14960                 if (tgt_prog->type == prog->type) {
14961                         /* Cannot fentry/fexit another fentry/fexit program.
14962                          * Cannot attach program extension to another extension.
14963                          * It's ok to attach fentry/fexit to extension program.
14964                          */
14965                         bpf_log(log, "Cannot recursively attach\n");
14966                         return -EINVAL;
14967                 }
14968                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
14969                     prog_extension &&
14970                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
14971                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
14972                         /* Program extensions can extend all program types
14973                          * except fentry/fexit. The reason is the following.
14974                          * The fentry/fexit programs are used for performance
14975                          * analysis, stats and can be attached to any program
14976                          * type except themselves. When extension program is
14977                          * replacing XDP function it is necessary to allow
14978                          * performance analysis of all functions. Both original
14979                          * XDP program and its program extension. Hence
14980                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
14981                          * allowed. If extending of fentry/fexit was allowed it
14982                          * would be possible to create long call chain
14983                          * fentry->extension->fentry->extension beyond
14984                          * reasonable stack size. Hence extending fentry is not
14985                          * allowed.
14986                          */
14987                         bpf_log(log, "Cannot extend fentry/fexit\n");
14988                         return -EINVAL;
14989                 }
14990         } else {
14991                 if (prog_extension) {
14992                         bpf_log(log, "Cannot replace kernel functions\n");
14993                         return -EINVAL;
14994                 }
14995         }
14996
14997         switch (prog->expected_attach_type) {
14998         case BPF_TRACE_RAW_TP:
14999                 if (tgt_prog) {
15000                         bpf_log(log,
15001                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
15002                         return -EINVAL;
15003                 }
15004                 if (!btf_type_is_typedef(t)) {
15005                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
15006                                 btf_id);
15007                         return -EINVAL;
15008                 }
15009                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
15010                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
15011                                 btf_id, tname);
15012                         return -EINVAL;
15013                 }
15014                 tname += sizeof(prefix) - 1;
15015                 t = btf_type_by_id(btf, t->type);
15016                 if (!btf_type_is_ptr(t))
15017                         /* should never happen in valid vmlinux build */
15018                         return -EINVAL;
15019                 t = btf_type_by_id(btf, t->type);
15020                 if (!btf_type_is_func_proto(t))
15021                         /* should never happen in valid vmlinux build */
15022                         return -EINVAL;
15023
15024                 break;
15025         case BPF_TRACE_ITER:
15026                 if (!btf_type_is_func(t)) {
15027                         bpf_log(log, "attach_btf_id %u is not a function\n",
15028                                 btf_id);
15029                         return -EINVAL;
15030                 }
15031                 t = btf_type_by_id(btf, t->type);
15032                 if (!btf_type_is_func_proto(t))
15033                         return -EINVAL;
15034                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15035                 if (ret)
15036                         return ret;
15037                 break;
15038         default:
15039                 if (!prog_extension)
15040                         return -EINVAL;
15041                 fallthrough;
15042         case BPF_MODIFY_RETURN:
15043         case BPF_LSM_MAC:
15044         case BPF_LSM_CGROUP:
15045         case BPF_TRACE_FENTRY:
15046         case BPF_TRACE_FEXIT:
15047                 if (!btf_type_is_func(t)) {
15048                         bpf_log(log, "attach_btf_id %u is not a function\n",
15049                                 btf_id);
15050                         return -EINVAL;
15051                 }
15052                 if (prog_extension &&
15053                     btf_check_type_match(log, prog, btf, t))
15054                         return -EINVAL;
15055                 t = btf_type_by_id(btf, t->type);
15056                 if (!btf_type_is_func_proto(t))
15057                         return -EINVAL;
15058
15059                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
15060                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
15061                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
15062                         return -EINVAL;
15063
15064                 if (tgt_prog && conservative)
15065                         t = NULL;
15066
15067                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15068                 if (ret < 0)
15069                         return ret;
15070
15071                 if (tgt_prog) {
15072                         if (subprog == 0)
15073                                 addr = (long) tgt_prog->bpf_func;
15074                         else
15075                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
15076                 } else {
15077                         addr = kallsyms_lookup_name(tname);
15078                         if (!addr) {
15079                                 bpf_log(log,
15080                                         "The address of function %s cannot be found\n",
15081                                         tname);
15082                                 return -ENOENT;
15083                         }
15084                 }
15085
15086                 if (prog->aux->sleepable) {
15087                         ret = -EINVAL;
15088                         switch (prog->type) {
15089                         case BPF_PROG_TYPE_TRACING:
15090                                 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
15091                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
15092                                  */
15093                                 if (!check_non_sleepable_error_inject(btf_id) &&
15094                                     within_error_injection_list(addr))
15095                                         ret = 0;
15096                                 break;
15097                         case BPF_PROG_TYPE_LSM:
15098                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
15099                                  * Only some of them are sleepable.
15100                                  */
15101                                 if (bpf_lsm_is_sleepable_hook(btf_id))
15102                                         ret = 0;
15103                                 break;
15104                         default:
15105                                 break;
15106                         }
15107                         if (ret) {
15108                                 bpf_log(log, "%s is not sleepable\n", tname);
15109                                 return ret;
15110                         }
15111                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
15112                         if (tgt_prog) {
15113                                 bpf_log(log, "can't modify return codes of BPF programs\n");
15114                                 return -EINVAL;
15115                         }
15116                         ret = check_attach_modify_return(addr, tname);
15117                         if (ret) {
15118                                 bpf_log(log, "%s() is not modifiable\n", tname);
15119                                 return ret;
15120                         }
15121                 }
15122
15123                 break;
15124         }
15125         tgt_info->tgt_addr = addr;
15126         tgt_info->tgt_name = tname;
15127         tgt_info->tgt_type = t;
15128         return 0;
15129 }
15130
15131 BTF_SET_START(btf_id_deny)
15132 BTF_ID_UNUSED
15133 #ifdef CONFIG_SMP
15134 BTF_ID(func, migrate_disable)
15135 BTF_ID(func, migrate_enable)
15136 #endif
15137 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
15138 BTF_ID(func, rcu_read_unlock_strict)
15139 #endif
15140 BTF_SET_END(btf_id_deny)
15141
15142 static int check_attach_btf_id(struct bpf_verifier_env *env)
15143 {
15144         struct bpf_prog *prog = env->prog;
15145         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
15146         struct bpf_attach_target_info tgt_info = {};
15147         u32 btf_id = prog->aux->attach_btf_id;
15148         struct bpf_trampoline *tr;
15149         int ret;
15150         u64 key;
15151
15152         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
15153                 if (prog->aux->sleepable)
15154                         /* attach_btf_id checked to be zero already */
15155                         return 0;
15156                 verbose(env, "Syscall programs can only be sleepable\n");
15157                 return -EINVAL;
15158         }
15159
15160         if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
15161             prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
15162                 verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
15163                 return -EINVAL;
15164         }
15165
15166         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
15167                 return check_struct_ops_btf_id(env);
15168
15169         if (prog->type != BPF_PROG_TYPE_TRACING &&
15170             prog->type != BPF_PROG_TYPE_LSM &&
15171             prog->type != BPF_PROG_TYPE_EXT)
15172                 return 0;
15173
15174         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
15175         if (ret)
15176                 return ret;
15177
15178         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
15179                 /* to make freplace equivalent to their targets, they need to
15180                  * inherit env->ops and expected_attach_type for the rest of the
15181                  * verification
15182                  */
15183                 env->ops = bpf_verifier_ops[tgt_prog->type];
15184                 prog->expected_attach_type = tgt_prog->expected_attach_type;
15185         }
15186
15187         /* store info about the attachment target that will be used later */
15188         prog->aux->attach_func_proto = tgt_info.tgt_type;
15189         prog->aux->attach_func_name = tgt_info.tgt_name;
15190
15191         if (tgt_prog) {
15192                 prog->aux->saved_dst_prog_type = tgt_prog->type;
15193                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
15194         }
15195
15196         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
15197                 prog->aux->attach_btf_trace = true;
15198                 return 0;
15199         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
15200                 if (!bpf_iter_prog_supported(prog))
15201                         return -EINVAL;
15202                 return 0;
15203         }
15204
15205         if (prog->type == BPF_PROG_TYPE_LSM) {
15206                 ret = bpf_lsm_verify_prog(&env->log, prog);
15207                 if (ret < 0)
15208                         return ret;
15209         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
15210                    btf_id_set_contains(&btf_id_deny, btf_id)) {
15211                 return -EINVAL;
15212         }
15213
15214         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
15215         tr = bpf_trampoline_get(key, &tgt_info);
15216         if (!tr)
15217                 return -ENOMEM;
15218
15219         prog->aux->dst_trampoline = tr;
15220         return 0;
15221 }
15222
15223 struct btf *bpf_get_btf_vmlinux(void)
15224 {
15225         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
15226                 mutex_lock(&bpf_verifier_lock);
15227                 if (!btf_vmlinux)
15228                         btf_vmlinux = btf_parse_vmlinux();
15229                 mutex_unlock(&bpf_verifier_lock);
15230         }
15231         return btf_vmlinux;
15232 }
15233
15234 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
15235 {
15236         u64 start_time = ktime_get_ns();
15237         struct bpf_verifier_env *env;
15238         struct bpf_verifier_log *log;
15239         int i, len, ret = -EINVAL;
15240         bool is_priv;
15241
15242         /* no program is valid */
15243         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
15244                 return -EINVAL;
15245
15246         /* 'struct bpf_verifier_env' can be global, but since it's not small,
15247          * allocate/free it every time bpf_check() is called
15248          */
15249         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
15250         if (!env)
15251                 return -ENOMEM;
15252         log = &env->log;
15253
15254         len = (*prog)->len;
15255         env->insn_aux_data =
15256                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
15257         ret = -ENOMEM;
15258         if (!env->insn_aux_data)
15259                 goto err_free_env;
15260         for (i = 0; i < len; i++)
15261                 env->insn_aux_data[i].orig_idx = i;
15262         env->prog = *prog;
15263         env->ops = bpf_verifier_ops[env->prog->type];
15264         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
15265         is_priv = bpf_capable();
15266
15267         bpf_get_btf_vmlinux();
15268
15269         /* grab the mutex to protect few globals used by verifier */
15270         if (!is_priv)
15271                 mutex_lock(&bpf_verifier_lock);
15272
15273         if (attr->log_level || attr->log_buf || attr->log_size) {
15274                 /* user requested verbose verifier output
15275                  * and supplied buffer to store the verification trace
15276                  */
15277                 log->level = attr->log_level;
15278                 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
15279                 log->len_total = attr->log_size;
15280
15281                 /* log attributes have to be sane */
15282                 if (!bpf_verifier_log_attr_valid(log)) {
15283                         ret = -EINVAL;
15284                         goto err_unlock;
15285                 }
15286         }
15287
15288         mark_verifier_state_clean(env);
15289
15290         if (IS_ERR(btf_vmlinux)) {
15291                 /* Either gcc or pahole or kernel are broken. */
15292                 verbose(env, "in-kernel BTF is malformed\n");
15293                 ret = PTR_ERR(btf_vmlinux);
15294                 goto skip_full_check;
15295         }
15296
15297         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
15298         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
15299                 env->strict_alignment = true;
15300         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
15301                 env->strict_alignment = false;
15302
15303         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
15304         env->allow_uninit_stack = bpf_allow_uninit_stack();
15305         env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
15306         env->bypass_spec_v1 = bpf_bypass_spec_v1();
15307         env->bypass_spec_v4 = bpf_bypass_spec_v4();
15308         env->bpf_capable = bpf_capable();
15309
15310         if (is_priv)
15311                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
15312
15313         env->explored_states = kvcalloc(state_htab_size(env),
15314                                        sizeof(struct bpf_verifier_state_list *),
15315                                        GFP_USER);
15316         ret = -ENOMEM;
15317         if (!env->explored_states)
15318                 goto skip_full_check;
15319
15320         ret = add_subprog_and_kfunc(env);
15321         if (ret < 0)
15322                 goto skip_full_check;
15323
15324         ret = check_subprogs(env);
15325         if (ret < 0)
15326                 goto skip_full_check;
15327
15328         ret = check_btf_info(env, attr, uattr);
15329         if (ret < 0)
15330                 goto skip_full_check;
15331
15332         ret = check_attach_btf_id(env);
15333         if (ret)
15334                 goto skip_full_check;
15335
15336         ret = resolve_pseudo_ldimm64(env);
15337         if (ret < 0)
15338                 goto skip_full_check;
15339
15340         if (bpf_prog_is_dev_bound(env->prog->aux)) {
15341                 ret = bpf_prog_offload_verifier_prep(env->prog);
15342                 if (ret)
15343                         goto skip_full_check;
15344         }
15345
15346         ret = check_cfg(env);
15347         if (ret < 0)
15348                 goto skip_full_check;
15349
15350         ret = do_check_subprogs(env);
15351         ret = ret ?: do_check_main(env);
15352
15353         if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
15354                 ret = bpf_prog_offload_finalize(env);
15355
15356 skip_full_check:
15357         kvfree(env->explored_states);
15358
15359         if (ret == 0)
15360                 ret = check_max_stack_depth(env);
15361
15362         /* instruction rewrites happen after this point */
15363         if (ret == 0)
15364                 ret = optimize_bpf_loop(env);
15365
15366         if (is_priv) {
15367                 if (ret == 0)
15368                         opt_hard_wire_dead_code_branches(env);
15369                 if (ret == 0)
15370                         ret = opt_remove_dead_code(env);
15371                 if (ret == 0)
15372                         ret = opt_remove_nops(env);
15373         } else {
15374                 if (ret == 0)
15375                         sanitize_dead_code(env);
15376         }
15377
15378         if (ret == 0)
15379                 /* program is valid, convert *(u32*)(ctx + off) accesses */
15380                 ret = convert_ctx_accesses(env);
15381
15382         if (ret == 0)
15383                 ret = do_misc_fixups(env);
15384
15385         /* do 32-bit optimization after insn patching has done so those patched
15386          * insns could be handled correctly.
15387          */
15388         if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
15389                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
15390                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
15391                                                                      : false;
15392         }
15393
15394         if (ret == 0)
15395                 ret = fixup_call_args(env);
15396
15397         env->verification_time = ktime_get_ns() - start_time;
15398         print_verification_stats(env);
15399         env->prog->aux->verified_insns = env->insn_processed;
15400
15401         if (log->level && bpf_verifier_log_full(log))
15402                 ret = -ENOSPC;
15403         if (log->level && !log->ubuf) {
15404                 ret = -EFAULT;
15405                 goto err_release_maps;
15406         }
15407
15408         if (ret)
15409                 goto err_release_maps;
15410
15411         if (env->used_map_cnt) {
15412                 /* if program passed verifier, update used_maps in bpf_prog_info */
15413                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
15414                                                           sizeof(env->used_maps[0]),
15415                                                           GFP_KERNEL);
15416
15417                 if (!env->prog->aux->used_maps) {
15418                         ret = -ENOMEM;
15419                         goto err_release_maps;
15420                 }
15421
15422                 memcpy(env->prog->aux->used_maps, env->used_maps,
15423                        sizeof(env->used_maps[0]) * env->used_map_cnt);
15424                 env->prog->aux->used_map_cnt = env->used_map_cnt;
15425         }
15426         if (env->used_btf_cnt) {
15427                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
15428                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
15429                                                           sizeof(env->used_btfs[0]),
15430                                                           GFP_KERNEL);
15431                 if (!env->prog->aux->used_btfs) {
15432                         ret = -ENOMEM;
15433                         goto err_release_maps;
15434                 }
15435
15436                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
15437                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
15438                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
15439         }
15440         if (env->used_map_cnt || env->used_btf_cnt) {
15441                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
15442                  * bpf_ld_imm64 instructions
15443                  */
15444                 convert_pseudo_ld_imm64(env);
15445         }
15446
15447         adjust_btf_func(env);
15448
15449 err_release_maps:
15450         if (!env->prog->aux->used_maps)
15451                 /* if we didn't copy map pointers into bpf_prog_info, release
15452                  * them now. Otherwise free_used_maps() will release them.
15453                  */
15454                 release_maps(env);
15455         if (!env->prog->aux->used_btfs)
15456                 release_btfs(env);
15457
15458         /* extension progs temporarily inherit the attach_type of their targets
15459            for verification purposes, so set it back to zero before returning
15460          */
15461         if (env->prog->type == BPF_PROG_TYPE_EXT)
15462                 env->prog->expected_attach_type = 0;
15463
15464         *prog = env->prog;
15465 err_unlock:
15466         if (!is_priv)
15467                 mutex_unlock(&bpf_verifier_lock);
15468         vfree(env->insn_aux_data);
15469 err_free_env:
15470         kfree(env);
15471         return ret;
15472 }