d533488b75c66699935c6c6d43a436881440ba42
[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 bytes;
1004
1005         if (ZERO_OR_NULL_PTR(src))
1006                 goto out;
1007
1008         if (unlikely(check_mul_overflow(n, size, &bytes)))
1009                 return NULL;
1010
1011         if (ksize(dst) < bytes) {
1012                 kfree(dst);
1013                 dst = kmalloc_track_caller(bytes, flags);
1014                 if (!dst)
1015                         return NULL;
1016         }
1017
1018         memcpy(dst, src, bytes);
1019 out:
1020         return dst ? dst : ZERO_SIZE_PTR;
1021 }
1022
1023 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1024  * small to hold new_n items. new items are zeroed out if the array grows.
1025  *
1026  * Contrary to krealloc_array, does not free arr if new_n is zero.
1027  */
1028 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1029 {
1030         void *new_arr;
1031
1032         if (!new_n || old_n == new_n)
1033                 goto out;
1034
1035         new_arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
1036         if (!new_arr) {
1037                 kfree(arr);
1038                 return NULL;
1039         }
1040         arr = new_arr;
1041
1042         if (new_n > old_n)
1043                 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1044
1045 out:
1046         return arr ? arr : ZERO_SIZE_PTR;
1047 }
1048
1049 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1050 {
1051         dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1052                                sizeof(struct bpf_reference_state), GFP_KERNEL);
1053         if (!dst->refs)
1054                 return -ENOMEM;
1055
1056         dst->acquired_refs = src->acquired_refs;
1057         return 0;
1058 }
1059
1060 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1061 {
1062         size_t n = src->allocated_stack / BPF_REG_SIZE;
1063
1064         dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1065                                 GFP_KERNEL);
1066         if (!dst->stack)
1067                 return -ENOMEM;
1068
1069         dst->allocated_stack = src->allocated_stack;
1070         return 0;
1071 }
1072
1073 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1074 {
1075         state->refs = realloc_array(state->refs, state->acquired_refs, n,
1076                                     sizeof(struct bpf_reference_state));
1077         if (!state->refs)
1078                 return -ENOMEM;
1079
1080         state->acquired_refs = n;
1081         return 0;
1082 }
1083
1084 static int grow_stack_state(struct bpf_func_state *state, int size)
1085 {
1086         size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1087
1088         if (old_n >= n)
1089                 return 0;
1090
1091         state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1092         if (!state->stack)
1093                 return -ENOMEM;
1094
1095         state->allocated_stack = size;
1096         return 0;
1097 }
1098
1099 /* Acquire a pointer id from the env and update the state->refs to include
1100  * this new pointer reference.
1101  * On success, returns a valid pointer id to associate with the register
1102  * On failure, returns a negative errno.
1103  */
1104 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1105 {
1106         struct bpf_func_state *state = cur_func(env);
1107         int new_ofs = state->acquired_refs;
1108         int id, err;
1109
1110         err = resize_reference_state(state, state->acquired_refs + 1);
1111         if (err)
1112                 return err;
1113         id = ++env->id_gen;
1114         state->refs[new_ofs].id = id;
1115         state->refs[new_ofs].insn_idx = insn_idx;
1116         state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1117
1118         return id;
1119 }
1120
1121 /* release function corresponding to acquire_reference_state(). Idempotent. */
1122 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1123 {
1124         int i, last_idx;
1125
1126         last_idx = state->acquired_refs - 1;
1127         for (i = 0; i < state->acquired_refs; i++) {
1128                 if (state->refs[i].id == ptr_id) {
1129                         /* Cannot release caller references in callbacks */
1130                         if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1131                                 return -EINVAL;
1132                         if (last_idx && i != last_idx)
1133                                 memcpy(&state->refs[i], &state->refs[last_idx],
1134                                        sizeof(*state->refs));
1135                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1136                         state->acquired_refs--;
1137                         return 0;
1138                 }
1139         }
1140         return -EINVAL;
1141 }
1142
1143 static void free_func_state(struct bpf_func_state *state)
1144 {
1145         if (!state)
1146                 return;
1147         kfree(state->refs);
1148         kfree(state->stack);
1149         kfree(state);
1150 }
1151
1152 static void clear_jmp_history(struct bpf_verifier_state *state)
1153 {
1154         kfree(state->jmp_history);
1155         state->jmp_history = NULL;
1156         state->jmp_history_cnt = 0;
1157 }
1158
1159 static void free_verifier_state(struct bpf_verifier_state *state,
1160                                 bool free_self)
1161 {
1162         int i;
1163
1164         for (i = 0; i <= state->curframe; i++) {
1165                 free_func_state(state->frame[i]);
1166                 state->frame[i] = NULL;
1167         }
1168         clear_jmp_history(state);
1169         if (free_self)
1170                 kfree(state);
1171 }
1172
1173 /* copy verifier state from src to dst growing dst stack space
1174  * when necessary to accommodate larger src stack
1175  */
1176 static int copy_func_state(struct bpf_func_state *dst,
1177                            const struct bpf_func_state *src)
1178 {
1179         int err;
1180
1181         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1182         err = copy_reference_state(dst, src);
1183         if (err)
1184                 return err;
1185         return copy_stack_state(dst, src);
1186 }
1187
1188 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1189                                const struct bpf_verifier_state *src)
1190 {
1191         struct bpf_func_state *dst;
1192         int i, err;
1193
1194         dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1195                                             src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1196                                             GFP_USER);
1197         if (!dst_state->jmp_history)
1198                 return -ENOMEM;
1199         dst_state->jmp_history_cnt = src->jmp_history_cnt;
1200
1201         /* if dst has more stack frames then src frame, free them */
1202         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1203                 free_func_state(dst_state->frame[i]);
1204                 dst_state->frame[i] = NULL;
1205         }
1206         dst_state->speculative = src->speculative;
1207         dst_state->curframe = src->curframe;
1208         dst_state->active_spin_lock = src->active_spin_lock;
1209         dst_state->branches = src->branches;
1210         dst_state->parent = src->parent;
1211         dst_state->first_insn_idx = src->first_insn_idx;
1212         dst_state->last_insn_idx = src->last_insn_idx;
1213         for (i = 0; i <= src->curframe; i++) {
1214                 dst = dst_state->frame[i];
1215                 if (!dst) {
1216                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1217                         if (!dst)
1218                                 return -ENOMEM;
1219                         dst_state->frame[i] = dst;
1220                 }
1221                 err = copy_func_state(dst, src->frame[i]);
1222                 if (err)
1223                         return err;
1224         }
1225         return 0;
1226 }
1227
1228 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1229 {
1230         while (st) {
1231                 u32 br = --st->branches;
1232
1233                 /* WARN_ON(br > 1) technically makes sense here,
1234                  * but see comment in push_stack(), hence:
1235                  */
1236                 WARN_ONCE((int)br < 0,
1237                           "BUG update_branch_counts:branches_to_explore=%d\n",
1238                           br);
1239                 if (br)
1240                         break;
1241                 st = st->parent;
1242         }
1243 }
1244
1245 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1246                      int *insn_idx, bool pop_log)
1247 {
1248         struct bpf_verifier_state *cur = env->cur_state;
1249         struct bpf_verifier_stack_elem *elem, *head = env->head;
1250         int err;
1251
1252         if (env->head == NULL)
1253                 return -ENOENT;
1254
1255         if (cur) {
1256                 err = copy_verifier_state(cur, &head->st);
1257                 if (err)
1258                         return err;
1259         }
1260         if (pop_log)
1261                 bpf_vlog_reset(&env->log, head->log_pos);
1262         if (insn_idx)
1263                 *insn_idx = head->insn_idx;
1264         if (prev_insn_idx)
1265                 *prev_insn_idx = head->prev_insn_idx;
1266         elem = head->next;
1267         free_verifier_state(&head->st, false);
1268         kfree(head);
1269         env->head = elem;
1270         env->stack_size--;
1271         return 0;
1272 }
1273
1274 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1275                                              int insn_idx, int prev_insn_idx,
1276                                              bool speculative)
1277 {
1278         struct bpf_verifier_state *cur = env->cur_state;
1279         struct bpf_verifier_stack_elem *elem;
1280         int err;
1281
1282         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1283         if (!elem)
1284                 goto err;
1285
1286         elem->insn_idx = insn_idx;
1287         elem->prev_insn_idx = prev_insn_idx;
1288         elem->next = env->head;
1289         elem->log_pos = env->log.len_used;
1290         env->head = elem;
1291         env->stack_size++;
1292         err = copy_verifier_state(&elem->st, cur);
1293         if (err)
1294                 goto err;
1295         elem->st.speculative |= speculative;
1296         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1297                 verbose(env, "The sequence of %d jumps is too complex.\n",
1298                         env->stack_size);
1299                 goto err;
1300         }
1301         if (elem->st.parent) {
1302                 ++elem->st.parent->branches;
1303                 /* WARN_ON(branches > 2) technically makes sense here,
1304                  * but
1305                  * 1. speculative states will bump 'branches' for non-branch
1306                  * instructions
1307                  * 2. is_state_visited() heuristics may decide not to create
1308                  * a new state for a sequence of branches and all such current
1309                  * and cloned states will be pointing to a single parent state
1310                  * which might have large 'branches' count.
1311                  */
1312         }
1313         return &elem->st;
1314 err:
1315         free_verifier_state(env->cur_state, true);
1316         env->cur_state = NULL;
1317         /* pop all elements and return */
1318         while (!pop_stack(env, NULL, NULL, false));
1319         return NULL;
1320 }
1321
1322 #define CALLER_SAVED_REGS 6
1323 static const int caller_saved[CALLER_SAVED_REGS] = {
1324         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1325 };
1326
1327 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1328                                 struct bpf_reg_state *reg);
1329
1330 /* This helper doesn't clear reg->id */
1331 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1332 {
1333         reg->var_off = tnum_const(imm);
1334         reg->smin_value = (s64)imm;
1335         reg->smax_value = (s64)imm;
1336         reg->umin_value = imm;
1337         reg->umax_value = imm;
1338
1339         reg->s32_min_value = (s32)imm;
1340         reg->s32_max_value = (s32)imm;
1341         reg->u32_min_value = (u32)imm;
1342         reg->u32_max_value = (u32)imm;
1343 }
1344
1345 /* Mark the unknown part of a register (variable offset or scalar value) as
1346  * known to have the value @imm.
1347  */
1348 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1349 {
1350         /* Clear id, off, and union(map_ptr, range) */
1351         memset(((u8 *)reg) + sizeof(reg->type), 0,
1352                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1353         ___mark_reg_known(reg, imm);
1354 }
1355
1356 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1357 {
1358         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1359         reg->s32_min_value = (s32)imm;
1360         reg->s32_max_value = (s32)imm;
1361         reg->u32_min_value = (u32)imm;
1362         reg->u32_max_value = (u32)imm;
1363 }
1364
1365 /* Mark the 'variable offset' part of a register as zero.  This should be
1366  * used only on registers holding a pointer type.
1367  */
1368 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1369 {
1370         __mark_reg_known(reg, 0);
1371 }
1372
1373 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1374 {
1375         __mark_reg_known(reg, 0);
1376         reg->type = SCALAR_VALUE;
1377 }
1378
1379 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1380                                 struct bpf_reg_state *regs, u32 regno)
1381 {
1382         if (WARN_ON(regno >= MAX_BPF_REG)) {
1383                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1384                 /* Something bad happened, let's kill all regs */
1385                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1386                         __mark_reg_not_init(env, regs + regno);
1387                 return;
1388         }
1389         __mark_reg_known_zero(regs + regno);
1390 }
1391
1392 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1393 {
1394         if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1395                 const struct bpf_map *map = reg->map_ptr;
1396
1397                 if (map->inner_map_meta) {
1398                         reg->type = CONST_PTR_TO_MAP;
1399                         reg->map_ptr = map->inner_map_meta;
1400                         /* transfer reg's id which is unique for every map_lookup_elem
1401                          * as UID of the inner map.
1402                          */
1403                         if (map_value_has_timer(map->inner_map_meta))
1404                                 reg->map_uid = reg->id;
1405                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1406                         reg->type = PTR_TO_XDP_SOCK;
1407                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1408                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1409                         reg->type = PTR_TO_SOCKET;
1410                 } else {
1411                         reg->type = PTR_TO_MAP_VALUE;
1412                 }
1413                 return;
1414         }
1415
1416         reg->type &= ~PTR_MAYBE_NULL;
1417 }
1418
1419 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1420 {
1421         return type_is_pkt_pointer(reg->type);
1422 }
1423
1424 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1425 {
1426         return reg_is_pkt_pointer(reg) ||
1427                reg->type == PTR_TO_PACKET_END;
1428 }
1429
1430 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1431 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1432                                     enum bpf_reg_type which)
1433 {
1434         /* The register can already have a range from prior markings.
1435          * This is fine as long as it hasn't been advanced from its
1436          * origin.
1437          */
1438         return reg->type == which &&
1439                reg->id == 0 &&
1440                reg->off == 0 &&
1441                tnum_equals_const(reg->var_off, 0);
1442 }
1443
1444 /* Reset the min/max bounds of a register */
1445 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1446 {
1447         reg->smin_value = S64_MIN;
1448         reg->smax_value = S64_MAX;
1449         reg->umin_value = 0;
1450         reg->umax_value = U64_MAX;
1451
1452         reg->s32_min_value = S32_MIN;
1453         reg->s32_max_value = S32_MAX;
1454         reg->u32_min_value = 0;
1455         reg->u32_max_value = U32_MAX;
1456 }
1457
1458 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1459 {
1460         reg->smin_value = S64_MIN;
1461         reg->smax_value = S64_MAX;
1462         reg->umin_value = 0;
1463         reg->umax_value = U64_MAX;
1464 }
1465
1466 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1467 {
1468         reg->s32_min_value = S32_MIN;
1469         reg->s32_max_value = S32_MAX;
1470         reg->u32_min_value = 0;
1471         reg->u32_max_value = U32_MAX;
1472 }
1473
1474 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1475 {
1476         struct tnum var32_off = tnum_subreg(reg->var_off);
1477
1478         /* min signed is max(sign bit) | min(other bits) */
1479         reg->s32_min_value = max_t(s32, reg->s32_min_value,
1480                         var32_off.value | (var32_off.mask & S32_MIN));
1481         /* max signed is min(sign bit) | max(other bits) */
1482         reg->s32_max_value = min_t(s32, reg->s32_max_value,
1483                         var32_off.value | (var32_off.mask & S32_MAX));
1484         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1485         reg->u32_max_value = min(reg->u32_max_value,
1486                                  (u32)(var32_off.value | var32_off.mask));
1487 }
1488
1489 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1490 {
1491         /* min signed is max(sign bit) | min(other bits) */
1492         reg->smin_value = max_t(s64, reg->smin_value,
1493                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1494         /* max signed is min(sign bit) | max(other bits) */
1495         reg->smax_value = min_t(s64, reg->smax_value,
1496                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1497         reg->umin_value = max(reg->umin_value, reg->var_off.value);
1498         reg->umax_value = min(reg->umax_value,
1499                               reg->var_off.value | reg->var_off.mask);
1500 }
1501
1502 static void __update_reg_bounds(struct bpf_reg_state *reg)
1503 {
1504         __update_reg32_bounds(reg);
1505         __update_reg64_bounds(reg);
1506 }
1507
1508 /* Uses signed min/max values to inform unsigned, and vice-versa */
1509 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1510 {
1511         /* Learn sign from signed bounds.
1512          * If we cannot cross the sign boundary, then signed and unsigned bounds
1513          * are the same, so combine.  This works even in the negative case, e.g.
1514          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1515          */
1516         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1517                 reg->s32_min_value = reg->u32_min_value =
1518                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1519                 reg->s32_max_value = reg->u32_max_value =
1520                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1521                 return;
1522         }
1523         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1524          * boundary, so we must be careful.
1525          */
1526         if ((s32)reg->u32_max_value >= 0) {
1527                 /* Positive.  We can't learn anything from the smin, but smax
1528                  * is positive, hence safe.
1529                  */
1530                 reg->s32_min_value = reg->u32_min_value;
1531                 reg->s32_max_value = reg->u32_max_value =
1532                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1533         } else if ((s32)reg->u32_min_value < 0) {
1534                 /* Negative.  We can't learn anything from the smax, but smin
1535                  * is negative, hence safe.
1536                  */
1537                 reg->s32_min_value = reg->u32_min_value =
1538                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1539                 reg->s32_max_value = reg->u32_max_value;
1540         }
1541 }
1542
1543 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1544 {
1545         /* Learn sign from signed bounds.
1546          * If we cannot cross the sign boundary, then signed and unsigned bounds
1547          * are the same, so combine.  This works even in the negative case, e.g.
1548          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1549          */
1550         if (reg->smin_value >= 0 || reg->smax_value < 0) {
1551                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1552                                                           reg->umin_value);
1553                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1554                                                           reg->umax_value);
1555                 return;
1556         }
1557         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1558          * boundary, so we must be careful.
1559          */
1560         if ((s64)reg->umax_value >= 0) {
1561                 /* Positive.  We can't learn anything from the smin, but smax
1562                  * is positive, hence safe.
1563                  */
1564                 reg->smin_value = reg->umin_value;
1565                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1566                                                           reg->umax_value);
1567         } else if ((s64)reg->umin_value < 0) {
1568                 /* Negative.  We can't learn anything from the smax, but smin
1569                  * is negative, hence safe.
1570                  */
1571                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1572                                                           reg->umin_value);
1573                 reg->smax_value = reg->umax_value;
1574         }
1575 }
1576
1577 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1578 {
1579         __reg32_deduce_bounds(reg);
1580         __reg64_deduce_bounds(reg);
1581 }
1582
1583 /* Attempts to improve var_off based on unsigned min/max information */
1584 static void __reg_bound_offset(struct bpf_reg_state *reg)
1585 {
1586         struct tnum var64_off = tnum_intersect(reg->var_off,
1587                                                tnum_range(reg->umin_value,
1588                                                           reg->umax_value));
1589         struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1590                                                 tnum_range(reg->u32_min_value,
1591                                                            reg->u32_max_value));
1592
1593         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1594 }
1595
1596 static void reg_bounds_sync(struct bpf_reg_state *reg)
1597 {
1598         /* We might have learned new bounds from the var_off. */
1599         __update_reg_bounds(reg);
1600         /* We might have learned something about the sign bit. */
1601         __reg_deduce_bounds(reg);
1602         /* We might have learned some bits from the bounds. */
1603         __reg_bound_offset(reg);
1604         /* Intersecting with the old var_off might have improved our bounds
1605          * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1606          * then new var_off is (0; 0x7f...fc) which improves our umax.
1607          */
1608         __update_reg_bounds(reg);
1609 }
1610
1611 static bool __reg32_bound_s64(s32 a)
1612 {
1613         return a >= 0 && a <= S32_MAX;
1614 }
1615
1616 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1617 {
1618         reg->umin_value = reg->u32_min_value;
1619         reg->umax_value = reg->u32_max_value;
1620
1621         /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1622          * be positive otherwise set to worse case bounds and refine later
1623          * from tnum.
1624          */
1625         if (__reg32_bound_s64(reg->s32_min_value) &&
1626             __reg32_bound_s64(reg->s32_max_value)) {
1627                 reg->smin_value = reg->s32_min_value;
1628                 reg->smax_value = reg->s32_max_value;
1629         } else {
1630                 reg->smin_value = 0;
1631                 reg->smax_value = U32_MAX;
1632         }
1633 }
1634
1635 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1636 {
1637         /* special case when 64-bit register has upper 32-bit register
1638          * zeroed. Typically happens after zext or <<32, >>32 sequence
1639          * allowing us to use 32-bit bounds directly,
1640          */
1641         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1642                 __reg_assign_32_into_64(reg);
1643         } else {
1644                 /* Otherwise the best we can do is push lower 32bit known and
1645                  * unknown bits into register (var_off set from jmp logic)
1646                  * then learn as much as possible from the 64-bit tnum
1647                  * known and unknown bits. The previous smin/smax bounds are
1648                  * invalid here because of jmp32 compare so mark them unknown
1649                  * so they do not impact tnum bounds calculation.
1650                  */
1651                 __mark_reg64_unbounded(reg);
1652         }
1653         reg_bounds_sync(reg);
1654 }
1655
1656 static bool __reg64_bound_s32(s64 a)
1657 {
1658         return a >= S32_MIN && a <= S32_MAX;
1659 }
1660
1661 static bool __reg64_bound_u32(u64 a)
1662 {
1663         return a >= U32_MIN && a <= U32_MAX;
1664 }
1665
1666 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1667 {
1668         __mark_reg32_unbounded(reg);
1669         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1670                 reg->s32_min_value = (s32)reg->smin_value;
1671                 reg->s32_max_value = (s32)reg->smax_value;
1672         }
1673         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1674                 reg->u32_min_value = (u32)reg->umin_value;
1675                 reg->u32_max_value = (u32)reg->umax_value;
1676         }
1677         reg_bounds_sync(reg);
1678 }
1679
1680 /* Mark a register as having a completely unknown (scalar) value. */
1681 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1682                                struct bpf_reg_state *reg)
1683 {
1684         /*
1685          * Clear type, id, off, and union(map_ptr, range) and
1686          * padding between 'type' and union
1687          */
1688         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1689         reg->type = SCALAR_VALUE;
1690         reg->var_off = tnum_unknown;
1691         reg->frameno = 0;
1692         reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1693         __mark_reg_unbounded(reg);
1694 }
1695
1696 static void mark_reg_unknown(struct bpf_verifier_env *env,
1697                              struct bpf_reg_state *regs, u32 regno)
1698 {
1699         if (WARN_ON(regno >= MAX_BPF_REG)) {
1700                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1701                 /* Something bad happened, let's kill all regs except FP */
1702                 for (regno = 0; regno < BPF_REG_FP; regno++)
1703                         __mark_reg_not_init(env, regs + regno);
1704                 return;
1705         }
1706         __mark_reg_unknown(env, regs + regno);
1707 }
1708
1709 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1710                                 struct bpf_reg_state *reg)
1711 {
1712         __mark_reg_unknown(env, reg);
1713         reg->type = NOT_INIT;
1714 }
1715
1716 static void mark_reg_not_init(struct bpf_verifier_env *env,
1717                               struct bpf_reg_state *regs, u32 regno)
1718 {
1719         if (WARN_ON(regno >= MAX_BPF_REG)) {
1720                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1721                 /* Something bad happened, let's kill all regs except FP */
1722                 for (regno = 0; regno < BPF_REG_FP; regno++)
1723                         __mark_reg_not_init(env, regs + regno);
1724                 return;
1725         }
1726         __mark_reg_not_init(env, regs + regno);
1727 }
1728
1729 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1730                             struct bpf_reg_state *regs, u32 regno,
1731                             enum bpf_reg_type reg_type,
1732                             struct btf *btf, u32 btf_id,
1733                             enum bpf_type_flag flag)
1734 {
1735         if (reg_type == SCALAR_VALUE) {
1736                 mark_reg_unknown(env, regs, regno);
1737                 return;
1738         }
1739         mark_reg_known_zero(env, regs, regno);
1740         regs[regno].type = PTR_TO_BTF_ID | flag;
1741         regs[regno].btf = btf;
1742         regs[regno].btf_id = btf_id;
1743 }
1744
1745 #define DEF_NOT_SUBREG  (0)
1746 static void init_reg_state(struct bpf_verifier_env *env,
1747                            struct bpf_func_state *state)
1748 {
1749         struct bpf_reg_state *regs = state->regs;
1750         int i;
1751
1752         for (i = 0; i < MAX_BPF_REG; i++) {
1753                 mark_reg_not_init(env, regs, i);
1754                 regs[i].live = REG_LIVE_NONE;
1755                 regs[i].parent = NULL;
1756                 regs[i].subreg_def = DEF_NOT_SUBREG;
1757         }
1758
1759         /* frame pointer */
1760         regs[BPF_REG_FP].type = PTR_TO_STACK;
1761         mark_reg_known_zero(env, regs, BPF_REG_FP);
1762         regs[BPF_REG_FP].frameno = state->frameno;
1763 }
1764
1765 #define BPF_MAIN_FUNC (-1)
1766 static void init_func_state(struct bpf_verifier_env *env,
1767                             struct bpf_func_state *state,
1768                             int callsite, int frameno, int subprogno)
1769 {
1770         state->callsite = callsite;
1771         state->frameno = frameno;
1772         state->subprogno = subprogno;
1773         state->callback_ret_range = tnum_range(0, 0);
1774         init_reg_state(env, state);
1775         mark_verifier_state_scratched(env);
1776 }
1777
1778 /* Similar to push_stack(), but for async callbacks */
1779 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1780                                                 int insn_idx, int prev_insn_idx,
1781                                                 int subprog)
1782 {
1783         struct bpf_verifier_stack_elem *elem;
1784         struct bpf_func_state *frame;
1785
1786         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1787         if (!elem)
1788                 goto err;
1789
1790         elem->insn_idx = insn_idx;
1791         elem->prev_insn_idx = prev_insn_idx;
1792         elem->next = env->head;
1793         elem->log_pos = env->log.len_used;
1794         env->head = elem;
1795         env->stack_size++;
1796         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1797                 verbose(env,
1798                         "The sequence of %d jumps is too complex for async cb.\n",
1799                         env->stack_size);
1800                 goto err;
1801         }
1802         /* Unlike push_stack() do not copy_verifier_state().
1803          * The caller state doesn't matter.
1804          * This is async callback. It starts in a fresh stack.
1805          * Initialize it similar to do_check_common().
1806          */
1807         elem->st.branches = 1;
1808         frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1809         if (!frame)
1810                 goto err;
1811         init_func_state(env, frame,
1812                         BPF_MAIN_FUNC /* callsite */,
1813                         0 /* frameno within this callchain */,
1814                         subprog /* subprog number within this prog */);
1815         elem->st.frame[0] = frame;
1816         return &elem->st;
1817 err:
1818         free_verifier_state(env->cur_state, true);
1819         env->cur_state = NULL;
1820         /* pop all elements and return */
1821         while (!pop_stack(env, NULL, NULL, false));
1822         return NULL;
1823 }
1824
1825
1826 enum reg_arg_type {
1827         SRC_OP,         /* register is used as source operand */
1828         DST_OP,         /* register is used as destination operand */
1829         DST_OP_NO_MARK  /* same as above, check only, don't mark */
1830 };
1831
1832 static int cmp_subprogs(const void *a, const void *b)
1833 {
1834         return ((struct bpf_subprog_info *)a)->start -
1835                ((struct bpf_subprog_info *)b)->start;
1836 }
1837
1838 static int find_subprog(struct bpf_verifier_env *env, int off)
1839 {
1840         struct bpf_subprog_info *p;
1841
1842         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1843                     sizeof(env->subprog_info[0]), cmp_subprogs);
1844         if (!p)
1845                 return -ENOENT;
1846         return p - env->subprog_info;
1847
1848 }
1849
1850 static int add_subprog(struct bpf_verifier_env *env, int off)
1851 {
1852         int insn_cnt = env->prog->len;
1853         int ret;
1854
1855         if (off >= insn_cnt || off < 0) {
1856                 verbose(env, "call to invalid destination\n");
1857                 return -EINVAL;
1858         }
1859         ret = find_subprog(env, off);
1860         if (ret >= 0)
1861                 return ret;
1862         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1863                 verbose(env, "too many subprograms\n");
1864                 return -E2BIG;
1865         }
1866         /* determine subprog starts. The end is one before the next starts */
1867         env->subprog_info[env->subprog_cnt++].start = off;
1868         sort(env->subprog_info, env->subprog_cnt,
1869              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1870         return env->subprog_cnt - 1;
1871 }
1872
1873 #define MAX_KFUNC_DESCS 256
1874 #define MAX_KFUNC_BTFS  256
1875
1876 struct bpf_kfunc_desc {
1877         struct btf_func_model func_model;
1878         u32 func_id;
1879         s32 imm;
1880         u16 offset;
1881 };
1882
1883 struct bpf_kfunc_btf {
1884         struct btf *btf;
1885         struct module *module;
1886         u16 offset;
1887 };
1888
1889 struct bpf_kfunc_desc_tab {
1890         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1891         u32 nr_descs;
1892 };
1893
1894 struct bpf_kfunc_btf_tab {
1895         struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1896         u32 nr_descs;
1897 };
1898
1899 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1900 {
1901         const struct bpf_kfunc_desc *d0 = a;
1902         const struct bpf_kfunc_desc *d1 = b;
1903
1904         /* func_id is not greater than BTF_MAX_TYPE */
1905         return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1906 }
1907
1908 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1909 {
1910         const struct bpf_kfunc_btf *d0 = a;
1911         const struct bpf_kfunc_btf *d1 = b;
1912
1913         return d0->offset - d1->offset;
1914 }
1915
1916 static const struct bpf_kfunc_desc *
1917 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1918 {
1919         struct bpf_kfunc_desc desc = {
1920                 .func_id = func_id,
1921                 .offset = offset,
1922         };
1923         struct bpf_kfunc_desc_tab *tab;
1924
1925         tab = prog->aux->kfunc_tab;
1926         return bsearch(&desc, tab->descs, tab->nr_descs,
1927                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1928 }
1929
1930 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1931                                          s16 offset)
1932 {
1933         struct bpf_kfunc_btf kf_btf = { .offset = offset };
1934         struct bpf_kfunc_btf_tab *tab;
1935         struct bpf_kfunc_btf *b;
1936         struct module *mod;
1937         struct btf *btf;
1938         int btf_fd;
1939
1940         tab = env->prog->aux->kfunc_btf_tab;
1941         b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1942                     sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1943         if (!b) {
1944                 if (tab->nr_descs == MAX_KFUNC_BTFS) {
1945                         verbose(env, "too many different module BTFs\n");
1946                         return ERR_PTR(-E2BIG);
1947                 }
1948
1949                 if (bpfptr_is_null(env->fd_array)) {
1950                         verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1951                         return ERR_PTR(-EPROTO);
1952                 }
1953
1954                 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1955                                             offset * sizeof(btf_fd),
1956                                             sizeof(btf_fd)))
1957                         return ERR_PTR(-EFAULT);
1958
1959                 btf = btf_get_by_fd(btf_fd);
1960                 if (IS_ERR(btf)) {
1961                         verbose(env, "invalid module BTF fd specified\n");
1962                         return btf;
1963                 }
1964
1965                 if (!btf_is_module(btf)) {
1966                         verbose(env, "BTF fd for kfunc is not a module BTF\n");
1967                         btf_put(btf);
1968                         return ERR_PTR(-EINVAL);
1969                 }
1970
1971                 mod = btf_try_get_module(btf);
1972                 if (!mod) {
1973                         btf_put(btf);
1974                         return ERR_PTR(-ENXIO);
1975                 }
1976
1977                 b = &tab->descs[tab->nr_descs++];
1978                 b->btf = btf;
1979                 b->module = mod;
1980                 b->offset = offset;
1981
1982                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1983                      kfunc_btf_cmp_by_off, NULL);
1984         }
1985         return b->btf;
1986 }
1987
1988 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1989 {
1990         if (!tab)
1991                 return;
1992
1993         while (tab->nr_descs--) {
1994                 module_put(tab->descs[tab->nr_descs].module);
1995                 btf_put(tab->descs[tab->nr_descs].btf);
1996         }
1997         kfree(tab);
1998 }
1999
2000 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2001 {
2002         if (offset) {
2003                 if (offset < 0) {
2004                         /* In the future, this can be allowed to increase limit
2005                          * of fd index into fd_array, interpreted as u16.
2006                          */
2007                         verbose(env, "negative offset disallowed for kernel module function call\n");
2008                         return ERR_PTR(-EINVAL);
2009                 }
2010
2011                 return __find_kfunc_desc_btf(env, offset);
2012         }
2013         return btf_vmlinux ?: ERR_PTR(-ENOENT);
2014 }
2015
2016 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2017 {
2018         const struct btf_type *func, *func_proto;
2019         struct bpf_kfunc_btf_tab *btf_tab;
2020         struct bpf_kfunc_desc_tab *tab;
2021         struct bpf_prog_aux *prog_aux;
2022         struct bpf_kfunc_desc *desc;
2023         const char *func_name;
2024         struct btf *desc_btf;
2025         unsigned long call_imm;
2026         unsigned long addr;
2027         int err;
2028
2029         prog_aux = env->prog->aux;
2030         tab = prog_aux->kfunc_tab;
2031         btf_tab = prog_aux->kfunc_btf_tab;
2032         if (!tab) {
2033                 if (!btf_vmlinux) {
2034                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2035                         return -ENOTSUPP;
2036                 }
2037
2038                 if (!env->prog->jit_requested) {
2039                         verbose(env, "JIT is required for calling kernel function\n");
2040                         return -ENOTSUPP;
2041                 }
2042
2043                 if (!bpf_jit_supports_kfunc_call()) {
2044                         verbose(env, "JIT does not support calling kernel function\n");
2045                         return -ENOTSUPP;
2046                 }
2047
2048                 if (!env->prog->gpl_compatible) {
2049                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2050                         return -EINVAL;
2051                 }
2052
2053                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2054                 if (!tab)
2055                         return -ENOMEM;
2056                 prog_aux->kfunc_tab = tab;
2057         }
2058
2059         /* func_id == 0 is always invalid, but instead of returning an error, be
2060          * conservative and wait until the code elimination pass before returning
2061          * error, so that invalid calls that get pruned out can be in BPF programs
2062          * loaded from userspace.  It is also required that offset be untouched
2063          * for such calls.
2064          */
2065         if (!func_id && !offset)
2066                 return 0;
2067
2068         if (!btf_tab && offset) {
2069                 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2070                 if (!btf_tab)
2071                         return -ENOMEM;
2072                 prog_aux->kfunc_btf_tab = btf_tab;
2073         }
2074
2075         desc_btf = find_kfunc_desc_btf(env, offset);
2076         if (IS_ERR(desc_btf)) {
2077                 verbose(env, "failed to find BTF for kernel function\n");
2078                 return PTR_ERR(desc_btf);
2079         }
2080
2081         if (find_kfunc_desc(env->prog, func_id, offset))
2082                 return 0;
2083
2084         if (tab->nr_descs == MAX_KFUNC_DESCS) {
2085                 verbose(env, "too many different kernel function calls\n");
2086                 return -E2BIG;
2087         }
2088
2089         func = btf_type_by_id(desc_btf, func_id);
2090         if (!func || !btf_type_is_func(func)) {
2091                 verbose(env, "kernel btf_id %u is not a function\n",
2092                         func_id);
2093                 return -EINVAL;
2094         }
2095         func_proto = btf_type_by_id(desc_btf, func->type);
2096         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2097                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2098                         func_id);
2099                 return -EINVAL;
2100         }
2101
2102         func_name = btf_name_by_offset(desc_btf, func->name_off);
2103         addr = kallsyms_lookup_name(func_name);
2104         if (!addr) {
2105                 verbose(env, "cannot find address for kernel function %s\n",
2106                         func_name);
2107                 return -EINVAL;
2108         }
2109
2110         call_imm = BPF_CALL_IMM(addr);
2111         /* Check whether or not the relative offset overflows desc->imm */
2112         if ((unsigned long)(s32)call_imm != call_imm) {
2113                 verbose(env, "address of kernel function %s is out of range\n",
2114                         func_name);
2115                 return -EINVAL;
2116         }
2117
2118         desc = &tab->descs[tab->nr_descs++];
2119         desc->func_id = func_id;
2120         desc->imm = call_imm;
2121         desc->offset = offset;
2122         err = btf_distill_func_proto(&env->log, desc_btf,
2123                                      func_proto, func_name,
2124                                      &desc->func_model);
2125         if (!err)
2126                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2127                      kfunc_desc_cmp_by_id_off, NULL);
2128         return err;
2129 }
2130
2131 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2132 {
2133         const struct bpf_kfunc_desc *d0 = a;
2134         const struct bpf_kfunc_desc *d1 = b;
2135
2136         if (d0->imm > d1->imm)
2137                 return 1;
2138         else if (d0->imm < d1->imm)
2139                 return -1;
2140         return 0;
2141 }
2142
2143 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2144 {
2145         struct bpf_kfunc_desc_tab *tab;
2146
2147         tab = prog->aux->kfunc_tab;
2148         if (!tab)
2149                 return;
2150
2151         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2152              kfunc_desc_cmp_by_imm, NULL);
2153 }
2154
2155 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2156 {
2157         return !!prog->aux->kfunc_tab;
2158 }
2159
2160 const struct btf_func_model *
2161 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2162                          const struct bpf_insn *insn)
2163 {
2164         const struct bpf_kfunc_desc desc = {
2165                 .imm = insn->imm,
2166         };
2167         const struct bpf_kfunc_desc *res;
2168         struct bpf_kfunc_desc_tab *tab;
2169
2170         tab = prog->aux->kfunc_tab;
2171         res = bsearch(&desc, tab->descs, tab->nr_descs,
2172                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2173
2174         return res ? &res->func_model : NULL;
2175 }
2176
2177 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2178 {
2179         struct bpf_subprog_info *subprog = env->subprog_info;
2180         struct bpf_insn *insn = env->prog->insnsi;
2181         int i, ret, insn_cnt = env->prog->len;
2182
2183         /* Add entry function. */
2184         ret = add_subprog(env, 0);
2185         if (ret)
2186                 return ret;
2187
2188         for (i = 0; i < insn_cnt; i++, insn++) {
2189                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2190                     !bpf_pseudo_kfunc_call(insn))
2191                         continue;
2192
2193                 if (!env->bpf_capable) {
2194                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2195                         return -EPERM;
2196                 }
2197
2198                 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2199                         ret = add_subprog(env, i + insn->imm + 1);
2200                 else
2201                         ret = add_kfunc_call(env, insn->imm, insn->off);
2202
2203                 if (ret < 0)
2204                         return ret;
2205         }
2206
2207         /* Add a fake 'exit' subprog which could simplify subprog iteration
2208          * logic. 'subprog_cnt' should not be increased.
2209          */
2210         subprog[env->subprog_cnt].start = insn_cnt;
2211
2212         if (env->log.level & BPF_LOG_LEVEL2)
2213                 for (i = 0; i < env->subprog_cnt; i++)
2214                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
2215
2216         return 0;
2217 }
2218
2219 static int check_subprogs(struct bpf_verifier_env *env)
2220 {
2221         int i, subprog_start, subprog_end, off, cur_subprog = 0;
2222         struct bpf_subprog_info *subprog = env->subprog_info;
2223         struct bpf_insn *insn = env->prog->insnsi;
2224         int insn_cnt = env->prog->len;
2225
2226         /* now check that all jumps are within the same subprog */
2227         subprog_start = subprog[cur_subprog].start;
2228         subprog_end = subprog[cur_subprog + 1].start;
2229         for (i = 0; i < insn_cnt; i++) {
2230                 u8 code = insn[i].code;
2231
2232                 if (code == (BPF_JMP | BPF_CALL) &&
2233                     insn[i].imm == BPF_FUNC_tail_call &&
2234                     insn[i].src_reg != BPF_PSEUDO_CALL)
2235                         subprog[cur_subprog].has_tail_call = true;
2236                 if (BPF_CLASS(code) == BPF_LD &&
2237                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2238                         subprog[cur_subprog].has_ld_abs = true;
2239                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2240                         goto next;
2241                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2242                         goto next;
2243                 off = i + insn[i].off + 1;
2244                 if (off < subprog_start || off >= subprog_end) {
2245                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
2246                         return -EINVAL;
2247                 }
2248 next:
2249                 if (i == subprog_end - 1) {
2250                         /* to avoid fall-through from one subprog into another
2251                          * the last insn of the subprog should be either exit
2252                          * or unconditional jump back
2253                          */
2254                         if (code != (BPF_JMP | BPF_EXIT) &&
2255                             code != (BPF_JMP | BPF_JA)) {
2256                                 verbose(env, "last insn is not an exit or jmp\n");
2257                                 return -EINVAL;
2258                         }
2259                         subprog_start = subprog_end;
2260                         cur_subprog++;
2261                         if (cur_subprog < env->subprog_cnt)
2262                                 subprog_end = subprog[cur_subprog + 1].start;
2263                 }
2264         }
2265         return 0;
2266 }
2267
2268 /* Parentage chain of this register (or stack slot) should take care of all
2269  * issues like callee-saved registers, stack slot allocation time, etc.
2270  */
2271 static int mark_reg_read(struct bpf_verifier_env *env,
2272                          const struct bpf_reg_state *state,
2273                          struct bpf_reg_state *parent, u8 flag)
2274 {
2275         bool writes = parent == state->parent; /* Observe write marks */
2276         int cnt = 0;
2277
2278         while (parent) {
2279                 /* if read wasn't screened by an earlier write ... */
2280                 if (writes && state->live & REG_LIVE_WRITTEN)
2281                         break;
2282                 if (parent->live & REG_LIVE_DONE) {
2283                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2284                                 reg_type_str(env, parent->type),
2285                                 parent->var_off.value, parent->off);
2286                         return -EFAULT;
2287                 }
2288                 /* The first condition is more likely to be true than the
2289                  * second, checked it first.
2290                  */
2291                 if ((parent->live & REG_LIVE_READ) == flag ||
2292                     parent->live & REG_LIVE_READ64)
2293                         /* The parentage chain never changes and
2294                          * this parent was already marked as LIVE_READ.
2295                          * There is no need to keep walking the chain again and
2296                          * keep re-marking all parents as LIVE_READ.
2297                          * This case happens when the same register is read
2298                          * multiple times without writes into it in-between.
2299                          * Also, if parent has the stronger REG_LIVE_READ64 set,
2300                          * then no need to set the weak REG_LIVE_READ32.
2301                          */
2302                         break;
2303                 /* ... then we depend on parent's value */
2304                 parent->live |= flag;
2305                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2306                 if (flag == REG_LIVE_READ64)
2307                         parent->live &= ~REG_LIVE_READ32;
2308                 state = parent;
2309                 parent = state->parent;
2310                 writes = true;
2311                 cnt++;
2312         }
2313
2314         if (env->longest_mark_read_walk < cnt)
2315                 env->longest_mark_read_walk = cnt;
2316         return 0;
2317 }
2318
2319 /* This function is supposed to be used by the following 32-bit optimization
2320  * code only. It returns TRUE if the source or destination register operates
2321  * on 64-bit, otherwise return FALSE.
2322  */
2323 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2324                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2325 {
2326         u8 code, class, op;
2327
2328         code = insn->code;
2329         class = BPF_CLASS(code);
2330         op = BPF_OP(code);
2331         if (class == BPF_JMP) {
2332                 /* BPF_EXIT for "main" will reach here. Return TRUE
2333                  * conservatively.
2334                  */
2335                 if (op == BPF_EXIT)
2336                         return true;
2337                 if (op == BPF_CALL) {
2338                         /* BPF to BPF call will reach here because of marking
2339                          * caller saved clobber with DST_OP_NO_MARK for which we
2340                          * don't care the register def because they are anyway
2341                          * marked as NOT_INIT already.
2342                          */
2343                         if (insn->src_reg == BPF_PSEUDO_CALL)
2344                                 return false;
2345                         /* Helper call will reach here because of arg type
2346                          * check, conservatively return TRUE.
2347                          */
2348                         if (t == SRC_OP)
2349                                 return true;
2350
2351                         return false;
2352                 }
2353         }
2354
2355         if (class == BPF_ALU64 || class == BPF_JMP ||
2356             /* BPF_END always use BPF_ALU class. */
2357             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2358                 return true;
2359
2360         if (class == BPF_ALU || class == BPF_JMP32)
2361                 return false;
2362
2363         if (class == BPF_LDX) {
2364                 if (t != SRC_OP)
2365                         return BPF_SIZE(code) == BPF_DW;
2366                 /* LDX source must be ptr. */
2367                 return true;
2368         }
2369
2370         if (class == BPF_STX) {
2371                 /* BPF_STX (including atomic variants) has multiple source
2372                  * operands, one of which is a ptr. Check whether the caller is
2373                  * asking about it.
2374                  */
2375                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2376                         return true;
2377                 return BPF_SIZE(code) == BPF_DW;
2378         }
2379
2380         if (class == BPF_LD) {
2381                 u8 mode = BPF_MODE(code);
2382
2383                 /* LD_IMM64 */
2384                 if (mode == BPF_IMM)
2385                         return true;
2386
2387                 /* Both LD_IND and LD_ABS return 32-bit data. */
2388                 if (t != SRC_OP)
2389                         return  false;
2390
2391                 /* Implicit ctx ptr. */
2392                 if (regno == BPF_REG_6)
2393                         return true;
2394
2395                 /* Explicit source could be any width. */
2396                 return true;
2397         }
2398
2399         if (class == BPF_ST)
2400                 /* The only source register for BPF_ST is a ptr. */
2401                 return true;
2402
2403         /* Conservatively return true at default. */
2404         return true;
2405 }
2406
2407 /* Return the regno defined by the insn, or -1. */
2408 static int insn_def_regno(const struct bpf_insn *insn)
2409 {
2410         switch (BPF_CLASS(insn->code)) {
2411         case BPF_JMP:
2412         case BPF_JMP32:
2413         case BPF_ST:
2414                 return -1;
2415         case BPF_STX:
2416                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2417                     (insn->imm & BPF_FETCH)) {
2418                         if (insn->imm == BPF_CMPXCHG)
2419                                 return BPF_REG_0;
2420                         else
2421                                 return insn->src_reg;
2422                 } else {
2423                         return -1;
2424                 }
2425         default:
2426                 return insn->dst_reg;
2427         }
2428 }
2429
2430 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2431 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2432 {
2433         int dst_reg = insn_def_regno(insn);
2434
2435         if (dst_reg == -1)
2436                 return false;
2437
2438         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2439 }
2440
2441 static void mark_insn_zext(struct bpf_verifier_env *env,
2442                            struct bpf_reg_state *reg)
2443 {
2444         s32 def_idx = reg->subreg_def;
2445
2446         if (def_idx == DEF_NOT_SUBREG)
2447                 return;
2448
2449         env->insn_aux_data[def_idx - 1].zext_dst = true;
2450         /* The dst will be zero extended, so won't be sub-register anymore. */
2451         reg->subreg_def = DEF_NOT_SUBREG;
2452 }
2453
2454 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2455                          enum reg_arg_type t)
2456 {
2457         struct bpf_verifier_state *vstate = env->cur_state;
2458         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2459         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2460         struct bpf_reg_state *reg, *regs = state->regs;
2461         bool rw64;
2462
2463         if (regno >= MAX_BPF_REG) {
2464                 verbose(env, "R%d is invalid\n", regno);
2465                 return -EINVAL;
2466         }
2467
2468         mark_reg_scratched(env, regno);
2469
2470         reg = &regs[regno];
2471         rw64 = is_reg64(env, insn, regno, reg, t);
2472         if (t == SRC_OP) {
2473                 /* check whether register used as source operand can be read */
2474                 if (reg->type == NOT_INIT) {
2475                         verbose(env, "R%d !read_ok\n", regno);
2476                         return -EACCES;
2477                 }
2478                 /* We don't need to worry about FP liveness because it's read-only */
2479                 if (regno == BPF_REG_FP)
2480                         return 0;
2481
2482                 if (rw64)
2483                         mark_insn_zext(env, reg);
2484
2485                 return mark_reg_read(env, reg, reg->parent,
2486                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2487         } else {
2488                 /* check whether register used as dest operand can be written to */
2489                 if (regno == BPF_REG_FP) {
2490                         verbose(env, "frame pointer is read only\n");
2491                         return -EACCES;
2492                 }
2493                 reg->live |= REG_LIVE_WRITTEN;
2494                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2495                 if (t == DST_OP)
2496                         mark_reg_unknown(env, regs, regno);
2497         }
2498         return 0;
2499 }
2500
2501 /* for any branch, call, exit record the history of jmps in the given state */
2502 static int push_jmp_history(struct bpf_verifier_env *env,
2503                             struct bpf_verifier_state *cur)
2504 {
2505         u32 cnt = cur->jmp_history_cnt;
2506         struct bpf_idx_pair *p;
2507
2508         cnt++;
2509         p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2510         if (!p)
2511                 return -ENOMEM;
2512         p[cnt - 1].idx = env->insn_idx;
2513         p[cnt - 1].prev_idx = env->prev_insn_idx;
2514         cur->jmp_history = p;
2515         cur->jmp_history_cnt = cnt;
2516         return 0;
2517 }
2518
2519 /* Backtrack one insn at a time. If idx is not at the top of recorded
2520  * history then previous instruction came from straight line execution.
2521  */
2522 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2523                              u32 *history)
2524 {
2525         u32 cnt = *history;
2526
2527         if (cnt && st->jmp_history[cnt - 1].idx == i) {
2528                 i = st->jmp_history[cnt - 1].prev_idx;
2529                 (*history)--;
2530         } else {
2531                 i--;
2532         }
2533         return i;
2534 }
2535
2536 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2537 {
2538         const struct btf_type *func;
2539         struct btf *desc_btf;
2540
2541         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2542                 return NULL;
2543
2544         desc_btf = find_kfunc_desc_btf(data, insn->off);
2545         if (IS_ERR(desc_btf))
2546                 return "<error>";
2547
2548         func = btf_type_by_id(desc_btf, insn->imm);
2549         return btf_name_by_offset(desc_btf, func->name_off);
2550 }
2551
2552 /* For given verifier state backtrack_insn() is called from the last insn to
2553  * the first insn. Its purpose is to compute a bitmask of registers and
2554  * stack slots that needs precision in the parent verifier state.
2555  */
2556 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2557                           u32 *reg_mask, u64 *stack_mask)
2558 {
2559         const struct bpf_insn_cbs cbs = {
2560                 .cb_call        = disasm_kfunc_name,
2561                 .cb_print       = verbose,
2562                 .private_data   = env,
2563         };
2564         struct bpf_insn *insn = env->prog->insnsi + idx;
2565         u8 class = BPF_CLASS(insn->code);
2566         u8 opcode = BPF_OP(insn->code);
2567         u8 mode = BPF_MODE(insn->code);
2568         u32 dreg = 1u << insn->dst_reg;
2569         u32 sreg = 1u << insn->src_reg;
2570         u32 spi;
2571
2572         if (insn->code == 0)
2573                 return 0;
2574         if (env->log.level & BPF_LOG_LEVEL2) {
2575                 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2576                 verbose(env, "%d: ", idx);
2577                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2578         }
2579
2580         if (class == BPF_ALU || class == BPF_ALU64) {
2581                 if (!(*reg_mask & dreg))
2582                         return 0;
2583                 if (opcode == BPF_MOV) {
2584                         if (BPF_SRC(insn->code) == BPF_X) {
2585                                 /* dreg = sreg
2586                                  * dreg needs precision after this insn
2587                                  * sreg needs precision before this insn
2588                                  */
2589                                 *reg_mask &= ~dreg;
2590                                 *reg_mask |= sreg;
2591                         } else {
2592                                 /* dreg = K
2593                                  * dreg needs precision after this insn.
2594                                  * Corresponding register is already marked
2595                                  * as precise=true in this verifier state.
2596                                  * No further markings in parent are necessary
2597                                  */
2598                                 *reg_mask &= ~dreg;
2599                         }
2600                 } else {
2601                         if (BPF_SRC(insn->code) == BPF_X) {
2602                                 /* dreg += sreg
2603                                  * both dreg and sreg need precision
2604                                  * before this insn
2605                                  */
2606                                 *reg_mask |= sreg;
2607                         } /* else dreg += K
2608                            * dreg still needs precision before this insn
2609                            */
2610                 }
2611         } else if (class == BPF_LDX) {
2612                 if (!(*reg_mask & dreg))
2613                         return 0;
2614                 *reg_mask &= ~dreg;
2615
2616                 /* scalars can only be spilled into stack w/o losing precision.
2617                  * Load from any other memory can be zero extended.
2618                  * The desire to keep that precision is already indicated
2619                  * by 'precise' mark in corresponding register of this state.
2620                  * No further tracking necessary.
2621                  */
2622                 if (insn->src_reg != BPF_REG_FP)
2623                         return 0;
2624
2625                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2626                  * that [fp - off] slot contains scalar that needs to be
2627                  * tracked with precision
2628                  */
2629                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2630                 if (spi >= 64) {
2631                         verbose(env, "BUG spi %d\n", spi);
2632                         WARN_ONCE(1, "verifier backtracking bug");
2633                         return -EFAULT;
2634                 }
2635                 *stack_mask |= 1ull << spi;
2636         } else if (class == BPF_STX || class == BPF_ST) {
2637                 if (*reg_mask & dreg)
2638                         /* stx & st shouldn't be using _scalar_ dst_reg
2639                          * to access memory. It means backtracking
2640                          * encountered a case of pointer subtraction.
2641                          */
2642                         return -ENOTSUPP;
2643                 /* scalars can only be spilled into stack */
2644                 if (insn->dst_reg != BPF_REG_FP)
2645                         return 0;
2646                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2647                 if (spi >= 64) {
2648                         verbose(env, "BUG spi %d\n", spi);
2649                         WARN_ONCE(1, "verifier backtracking bug");
2650                         return -EFAULT;
2651                 }
2652                 if (!(*stack_mask & (1ull << spi)))
2653                         return 0;
2654                 *stack_mask &= ~(1ull << spi);
2655                 if (class == BPF_STX)
2656                         *reg_mask |= sreg;
2657         } else if (class == BPF_JMP || class == BPF_JMP32) {
2658                 if (opcode == BPF_CALL) {
2659                         if (insn->src_reg == BPF_PSEUDO_CALL)
2660                                 return -ENOTSUPP;
2661                         /* regular helper call sets R0 */
2662                         *reg_mask &= ~1;
2663                         if (*reg_mask & 0x3f) {
2664                                 /* if backtracing was looking for registers R1-R5
2665                                  * they should have been found already.
2666                                  */
2667                                 verbose(env, "BUG regs %x\n", *reg_mask);
2668                                 WARN_ONCE(1, "verifier backtracking bug");
2669                                 return -EFAULT;
2670                         }
2671                 } else if (opcode == BPF_EXIT) {
2672                         return -ENOTSUPP;
2673                 }
2674         } else if (class == BPF_LD) {
2675                 if (!(*reg_mask & dreg))
2676                         return 0;
2677                 *reg_mask &= ~dreg;
2678                 /* It's ld_imm64 or ld_abs or ld_ind.
2679                  * For ld_imm64 no further tracking of precision
2680                  * into parent is necessary
2681                  */
2682                 if (mode == BPF_IND || mode == BPF_ABS)
2683                         /* to be analyzed */
2684                         return -ENOTSUPP;
2685         }
2686         return 0;
2687 }
2688
2689 /* the scalar precision tracking algorithm:
2690  * . at the start all registers have precise=false.
2691  * . scalar ranges are tracked as normal through alu and jmp insns.
2692  * . once precise value of the scalar register is used in:
2693  *   .  ptr + scalar alu
2694  *   . if (scalar cond K|scalar)
2695  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2696  *   backtrack through the verifier states and mark all registers and
2697  *   stack slots with spilled constants that these scalar regisers
2698  *   should be precise.
2699  * . during state pruning two registers (or spilled stack slots)
2700  *   are equivalent if both are not precise.
2701  *
2702  * Note the verifier cannot simply walk register parentage chain,
2703  * since many different registers and stack slots could have been
2704  * used to compute single precise scalar.
2705  *
2706  * The approach of starting with precise=true for all registers and then
2707  * backtrack to mark a register as not precise when the verifier detects
2708  * that program doesn't care about specific value (e.g., when helper
2709  * takes register as ARG_ANYTHING parameter) is not safe.
2710  *
2711  * It's ok to walk single parentage chain of the verifier states.
2712  * It's possible that this backtracking will go all the way till 1st insn.
2713  * All other branches will be explored for needing precision later.
2714  *
2715  * The backtracking needs to deal with cases like:
2716  *   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)
2717  * r9 -= r8
2718  * r5 = r9
2719  * if r5 > 0x79f goto pc+7
2720  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2721  * r5 += 1
2722  * ...
2723  * call bpf_perf_event_output#25
2724  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2725  *
2726  * and this case:
2727  * r6 = 1
2728  * call foo // uses callee's r6 inside to compute r0
2729  * r0 += r6
2730  * if r0 == 0 goto
2731  *
2732  * to track above reg_mask/stack_mask needs to be independent for each frame.
2733  *
2734  * Also if parent's curframe > frame where backtracking started,
2735  * the verifier need to mark registers in both frames, otherwise callees
2736  * may incorrectly prune callers. This is similar to
2737  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2738  *
2739  * For now backtracking falls back into conservative marking.
2740  */
2741 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2742                                      struct bpf_verifier_state *st)
2743 {
2744         struct bpf_func_state *func;
2745         struct bpf_reg_state *reg;
2746         int i, j;
2747
2748         /* big hammer: mark all scalars precise in this path.
2749          * pop_stack may still get !precise scalars.
2750          */
2751         for (; st; st = st->parent)
2752                 for (i = 0; i <= st->curframe; i++) {
2753                         func = st->frame[i];
2754                         for (j = 0; j < BPF_REG_FP; j++) {
2755                                 reg = &func->regs[j];
2756                                 if (reg->type != SCALAR_VALUE)
2757                                         continue;
2758                                 reg->precise = true;
2759                         }
2760                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2761                                 if (!is_spilled_reg(&func->stack[j]))
2762                                         continue;
2763                                 reg = &func->stack[j].spilled_ptr;
2764                                 if (reg->type != SCALAR_VALUE)
2765                                         continue;
2766                                 reg->precise = true;
2767                         }
2768                 }
2769 }
2770
2771 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2772                                   int spi)
2773 {
2774         struct bpf_verifier_state *st = env->cur_state;
2775         int first_idx = st->first_insn_idx;
2776         int last_idx = env->insn_idx;
2777         struct bpf_func_state *func;
2778         struct bpf_reg_state *reg;
2779         u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2780         u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2781         bool skip_first = true;
2782         bool new_marks = false;
2783         int i, err;
2784
2785         if (!env->bpf_capable)
2786                 return 0;
2787
2788         func = st->frame[st->curframe];
2789         if (regno >= 0) {
2790                 reg = &func->regs[regno];
2791                 if (reg->type != SCALAR_VALUE) {
2792                         WARN_ONCE(1, "backtracing misuse");
2793                         return -EFAULT;
2794                 }
2795                 if (!reg->precise)
2796                         new_marks = true;
2797                 else
2798                         reg_mask = 0;
2799                 reg->precise = true;
2800         }
2801
2802         while (spi >= 0) {
2803                 if (!is_spilled_reg(&func->stack[spi])) {
2804                         stack_mask = 0;
2805                         break;
2806                 }
2807                 reg = &func->stack[spi].spilled_ptr;
2808                 if (reg->type != SCALAR_VALUE) {
2809                         stack_mask = 0;
2810                         break;
2811                 }
2812                 if (!reg->precise)
2813                         new_marks = true;
2814                 else
2815                         stack_mask = 0;
2816                 reg->precise = true;
2817                 break;
2818         }
2819
2820         if (!new_marks)
2821                 return 0;
2822         if (!reg_mask && !stack_mask)
2823                 return 0;
2824         for (;;) {
2825                 DECLARE_BITMAP(mask, 64);
2826                 u32 history = st->jmp_history_cnt;
2827
2828                 if (env->log.level & BPF_LOG_LEVEL2)
2829                         verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2830                 for (i = last_idx;;) {
2831                         if (skip_first) {
2832                                 err = 0;
2833                                 skip_first = false;
2834                         } else {
2835                                 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2836                         }
2837                         if (err == -ENOTSUPP) {
2838                                 mark_all_scalars_precise(env, st);
2839                                 return 0;
2840                         } else if (err) {
2841                                 return err;
2842                         }
2843                         if (!reg_mask && !stack_mask)
2844                                 /* Found assignment(s) into tracked register in this state.
2845                                  * Since this state is already marked, just return.
2846                                  * Nothing to be tracked further in the parent state.
2847                                  */
2848                                 return 0;
2849                         if (i == first_idx)
2850                                 break;
2851                         i = get_prev_insn_idx(st, i, &history);
2852                         if (i >= env->prog->len) {
2853                                 /* This can happen if backtracking reached insn 0
2854                                  * and there are still reg_mask or stack_mask
2855                                  * to backtrack.
2856                                  * It means the backtracking missed the spot where
2857                                  * particular register was initialized with a constant.
2858                                  */
2859                                 verbose(env, "BUG backtracking idx %d\n", i);
2860                                 WARN_ONCE(1, "verifier backtracking bug");
2861                                 return -EFAULT;
2862                         }
2863                 }
2864                 st = st->parent;
2865                 if (!st)
2866                         break;
2867
2868                 new_marks = false;
2869                 func = st->frame[st->curframe];
2870                 bitmap_from_u64(mask, reg_mask);
2871                 for_each_set_bit(i, mask, 32) {
2872                         reg = &func->regs[i];
2873                         if (reg->type != SCALAR_VALUE) {
2874                                 reg_mask &= ~(1u << i);
2875                                 continue;
2876                         }
2877                         if (!reg->precise)
2878                                 new_marks = true;
2879                         reg->precise = true;
2880                 }
2881
2882                 bitmap_from_u64(mask, stack_mask);
2883                 for_each_set_bit(i, mask, 64) {
2884                         if (i >= func->allocated_stack / BPF_REG_SIZE) {
2885                                 /* the sequence of instructions:
2886                                  * 2: (bf) r3 = r10
2887                                  * 3: (7b) *(u64 *)(r3 -8) = r0
2888                                  * 4: (79) r4 = *(u64 *)(r10 -8)
2889                                  * doesn't contain jmps. It's backtracked
2890                                  * as a single block.
2891                                  * During backtracking insn 3 is not recognized as
2892                                  * stack access, so at the end of backtracking
2893                                  * stack slot fp-8 is still marked in stack_mask.
2894                                  * However the parent state may not have accessed
2895                                  * fp-8 and it's "unallocated" stack space.
2896                                  * In such case fallback to conservative.
2897                                  */
2898                                 mark_all_scalars_precise(env, st);
2899                                 return 0;
2900                         }
2901
2902                         if (!is_spilled_reg(&func->stack[i])) {
2903                                 stack_mask &= ~(1ull << i);
2904                                 continue;
2905                         }
2906                         reg = &func->stack[i].spilled_ptr;
2907                         if (reg->type != SCALAR_VALUE) {
2908                                 stack_mask &= ~(1ull << i);
2909                                 continue;
2910                         }
2911                         if (!reg->precise)
2912                                 new_marks = true;
2913                         reg->precise = true;
2914                 }
2915                 if (env->log.level & BPF_LOG_LEVEL2) {
2916                         verbose(env, "parent %s regs=%x stack=%llx marks:",
2917                                 new_marks ? "didn't have" : "already had",
2918                                 reg_mask, stack_mask);
2919                         print_verifier_state(env, func, true);
2920                 }
2921
2922                 if (!reg_mask && !stack_mask)
2923                         break;
2924                 if (!new_marks)
2925                         break;
2926
2927                 last_idx = st->last_insn_idx;
2928                 first_idx = st->first_insn_idx;
2929         }
2930         return 0;
2931 }
2932
2933 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2934 {
2935         return __mark_chain_precision(env, regno, -1);
2936 }
2937
2938 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2939 {
2940         return __mark_chain_precision(env, -1, spi);
2941 }
2942
2943 static bool is_spillable_regtype(enum bpf_reg_type type)
2944 {
2945         switch (base_type(type)) {
2946         case PTR_TO_MAP_VALUE:
2947         case PTR_TO_STACK:
2948         case PTR_TO_CTX:
2949         case PTR_TO_PACKET:
2950         case PTR_TO_PACKET_META:
2951         case PTR_TO_PACKET_END:
2952         case PTR_TO_FLOW_KEYS:
2953         case CONST_PTR_TO_MAP:
2954         case PTR_TO_SOCKET:
2955         case PTR_TO_SOCK_COMMON:
2956         case PTR_TO_TCP_SOCK:
2957         case PTR_TO_XDP_SOCK:
2958         case PTR_TO_BTF_ID:
2959         case PTR_TO_BUF:
2960         case PTR_TO_MEM:
2961         case PTR_TO_FUNC:
2962         case PTR_TO_MAP_KEY:
2963                 return true;
2964         default:
2965                 return false;
2966         }
2967 }
2968
2969 /* Does this register contain a constant zero? */
2970 static bool register_is_null(struct bpf_reg_state *reg)
2971 {
2972         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2973 }
2974
2975 static bool register_is_const(struct bpf_reg_state *reg)
2976 {
2977         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2978 }
2979
2980 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2981 {
2982         return tnum_is_unknown(reg->var_off) &&
2983                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2984                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2985                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2986                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2987 }
2988
2989 static bool register_is_bounded(struct bpf_reg_state *reg)
2990 {
2991         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2992 }
2993
2994 static bool __is_pointer_value(bool allow_ptr_leaks,
2995                                const struct bpf_reg_state *reg)
2996 {
2997         if (allow_ptr_leaks)
2998                 return false;
2999
3000         return reg->type != SCALAR_VALUE;
3001 }
3002
3003 static void save_register_state(struct bpf_func_state *state,
3004                                 int spi, struct bpf_reg_state *reg,
3005                                 int size)
3006 {
3007         int i;
3008
3009         state->stack[spi].spilled_ptr = *reg;
3010         if (size == BPF_REG_SIZE)
3011                 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3012
3013         for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3014                 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3015
3016         /* size < 8 bytes spill */
3017         for (; i; i--)
3018                 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3019 }
3020
3021 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3022  * stack boundary and alignment are checked in check_mem_access()
3023  */
3024 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3025                                        /* stack frame we're writing to */
3026                                        struct bpf_func_state *state,
3027                                        int off, int size, int value_regno,
3028                                        int insn_idx)
3029 {
3030         struct bpf_func_state *cur; /* state of the current function */
3031         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3032         u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3033         struct bpf_reg_state *reg = NULL;
3034
3035         err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3036         if (err)
3037                 return err;
3038         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3039          * so it's aligned access and [off, off + size) are within stack limits
3040          */
3041         if (!env->allow_ptr_leaks &&
3042             state->stack[spi].slot_type[0] == STACK_SPILL &&
3043             size != BPF_REG_SIZE) {
3044                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3045                 return -EACCES;
3046         }
3047
3048         cur = env->cur_state->frame[env->cur_state->curframe];
3049         if (value_regno >= 0)
3050                 reg = &cur->regs[value_regno];
3051         if (!env->bypass_spec_v4) {
3052                 bool sanitize = reg && is_spillable_regtype(reg->type);
3053
3054                 for (i = 0; i < size; i++) {
3055                         if (state->stack[spi].slot_type[i] == STACK_INVALID) {
3056                                 sanitize = true;
3057                                 break;
3058                         }
3059                 }
3060
3061                 if (sanitize)
3062                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3063         }
3064
3065         mark_stack_slot_scratched(env, spi);
3066         if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3067             !register_is_null(reg) && env->bpf_capable) {
3068                 if (dst_reg != BPF_REG_FP) {
3069                         /* The backtracking logic can only recognize explicit
3070                          * stack slot address like [fp - 8]. Other spill of
3071                          * scalar via different register has to be conservative.
3072                          * Backtrack from here and mark all registers as precise
3073                          * that contributed into 'reg' being a constant.
3074                          */
3075                         err = mark_chain_precision(env, value_regno);
3076                         if (err)
3077                                 return err;
3078                 }
3079                 save_register_state(state, spi, reg, size);
3080         } else if (reg && is_spillable_regtype(reg->type)) {
3081                 /* register containing pointer is being spilled into stack */
3082                 if (size != BPF_REG_SIZE) {
3083                         verbose_linfo(env, insn_idx, "; ");
3084                         verbose(env, "invalid size of register spill\n");
3085                         return -EACCES;
3086                 }
3087                 if (state != cur && reg->type == PTR_TO_STACK) {
3088                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3089                         return -EINVAL;
3090                 }
3091                 save_register_state(state, spi, reg, size);
3092         } else {
3093                 u8 type = STACK_MISC;
3094
3095                 /* regular write of data into stack destroys any spilled ptr */
3096                 state->stack[spi].spilled_ptr.type = NOT_INIT;
3097                 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3098                 if (is_spilled_reg(&state->stack[spi]))
3099                         for (i = 0; i < BPF_REG_SIZE; i++)
3100                                 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3101
3102                 /* only mark the slot as written if all 8 bytes were written
3103                  * otherwise read propagation may incorrectly stop too soon
3104                  * when stack slots are partially written.
3105                  * This heuristic means that read propagation will be
3106                  * conservative, since it will add reg_live_read marks
3107                  * to stack slots all the way to first state when programs
3108                  * writes+reads less than 8 bytes
3109                  */
3110                 if (size == BPF_REG_SIZE)
3111                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3112
3113                 /* when we zero initialize stack slots mark them as such */
3114                 if (reg && register_is_null(reg)) {
3115                         /* backtracking doesn't work for STACK_ZERO yet. */
3116                         err = mark_chain_precision(env, value_regno);
3117                         if (err)
3118                                 return err;
3119                         type = STACK_ZERO;
3120                 }
3121
3122                 /* Mark slots affected by this stack write. */
3123                 for (i = 0; i < size; i++)
3124                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3125                                 type;
3126         }
3127         return 0;
3128 }
3129
3130 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3131  * known to contain a variable offset.
3132  * This function checks whether the write is permitted and conservatively
3133  * tracks the effects of the write, considering that each stack slot in the
3134  * dynamic range is potentially written to.
3135  *
3136  * 'off' includes 'regno->off'.
3137  * 'value_regno' can be -1, meaning that an unknown value is being written to
3138  * the stack.
3139  *
3140  * Spilled pointers in range are not marked as written because we don't know
3141  * what's going to be actually written. This means that read propagation for
3142  * future reads cannot be terminated by this write.
3143  *
3144  * For privileged programs, uninitialized stack slots are considered
3145  * initialized by this write (even though we don't know exactly what offsets
3146  * are going to be written to). The idea is that we don't want the verifier to
3147  * reject future reads that access slots written to through variable offsets.
3148  */
3149 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3150                                      /* func where register points to */
3151                                      struct bpf_func_state *state,
3152                                      int ptr_regno, int off, int size,
3153                                      int value_regno, int insn_idx)
3154 {
3155         struct bpf_func_state *cur; /* state of the current function */
3156         int min_off, max_off;
3157         int i, err;
3158         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3159         bool writing_zero = false;
3160         /* set if the fact that we're writing a zero is used to let any
3161          * stack slots remain STACK_ZERO
3162          */
3163         bool zero_used = false;
3164
3165         cur = env->cur_state->frame[env->cur_state->curframe];
3166         ptr_reg = &cur->regs[ptr_regno];
3167         min_off = ptr_reg->smin_value + off;
3168         max_off = ptr_reg->smax_value + off + size;
3169         if (value_regno >= 0)
3170                 value_reg = &cur->regs[value_regno];
3171         if (value_reg && register_is_null(value_reg))
3172                 writing_zero = true;
3173
3174         err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3175         if (err)
3176                 return err;
3177
3178
3179         /* Variable offset writes destroy any spilled pointers in range. */
3180         for (i = min_off; i < max_off; i++) {
3181                 u8 new_type, *stype;
3182                 int slot, spi;
3183
3184                 slot = -i - 1;
3185                 spi = slot / BPF_REG_SIZE;
3186                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3187                 mark_stack_slot_scratched(env, spi);
3188
3189                 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3190                         /* Reject the write if range we may write to has not
3191                          * been initialized beforehand. If we didn't reject
3192                          * here, the ptr status would be erased below (even
3193                          * though not all slots are actually overwritten),
3194                          * possibly opening the door to leaks.
3195                          *
3196                          * We do however catch STACK_INVALID case below, and
3197                          * only allow reading possibly uninitialized memory
3198                          * later for CAP_PERFMON, as the write may not happen to
3199                          * that slot.
3200                          */
3201                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3202                                 insn_idx, i);
3203                         return -EINVAL;
3204                 }
3205
3206                 /* Erase all spilled pointers. */
3207                 state->stack[spi].spilled_ptr.type = NOT_INIT;
3208
3209                 /* Update the slot type. */
3210                 new_type = STACK_MISC;
3211                 if (writing_zero && *stype == STACK_ZERO) {
3212                         new_type = STACK_ZERO;
3213                         zero_used = true;
3214                 }
3215                 /* If the slot is STACK_INVALID, we check whether it's OK to
3216                  * pretend that it will be initialized by this write. The slot
3217                  * might not actually be written to, and so if we mark it as
3218                  * initialized future reads might leak uninitialized memory.
3219                  * For privileged programs, we will accept such reads to slots
3220                  * that may or may not be written because, if we're reject
3221                  * them, the error would be too confusing.
3222                  */
3223                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3224                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3225                                         insn_idx, i);
3226                         return -EINVAL;
3227                 }
3228                 *stype = new_type;
3229         }
3230         if (zero_used) {
3231                 /* backtracking doesn't work for STACK_ZERO yet. */
3232                 err = mark_chain_precision(env, value_regno);
3233                 if (err)
3234                         return err;
3235         }
3236         return 0;
3237 }
3238
3239 /* When register 'dst_regno' is assigned some values from stack[min_off,
3240  * max_off), we set the register's type according to the types of the
3241  * respective stack slots. If all the stack values are known to be zeros, then
3242  * so is the destination reg. Otherwise, the register is considered to be
3243  * SCALAR. This function does not deal with register filling; the caller must
3244  * ensure that all spilled registers in the stack range have been marked as
3245  * read.
3246  */
3247 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3248                                 /* func where src register points to */
3249                                 struct bpf_func_state *ptr_state,
3250                                 int min_off, int max_off, int dst_regno)
3251 {
3252         struct bpf_verifier_state *vstate = env->cur_state;
3253         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3254         int i, slot, spi;
3255         u8 *stype;
3256         int zeros = 0;
3257
3258         for (i = min_off; i < max_off; i++) {
3259                 slot = -i - 1;
3260                 spi = slot / BPF_REG_SIZE;
3261                 stype = ptr_state->stack[spi].slot_type;
3262                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3263                         break;
3264                 zeros++;
3265         }
3266         if (zeros == max_off - min_off) {
3267                 /* any access_size read into register is zero extended,
3268                  * so the whole register == const_zero
3269                  */
3270                 __mark_reg_const_zero(&state->regs[dst_regno]);
3271                 /* backtracking doesn't support STACK_ZERO yet,
3272                  * so mark it precise here, so that later
3273                  * backtracking can stop here.
3274                  * Backtracking may not need this if this register
3275                  * doesn't participate in pointer adjustment.
3276                  * Forward propagation of precise flag is not
3277                  * necessary either. This mark is only to stop
3278                  * backtracking. Any register that contributed
3279                  * to const 0 was marked precise before spill.
3280                  */
3281                 state->regs[dst_regno].precise = true;
3282         } else {
3283                 /* have read misc data from the stack */
3284                 mark_reg_unknown(env, state->regs, dst_regno);
3285         }
3286         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3287 }
3288
3289 /* Read the stack at 'off' and put the results into the register indicated by
3290  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3291  * spilled reg.
3292  *
3293  * 'dst_regno' can be -1, meaning that the read value is not going to a
3294  * register.
3295  *
3296  * The access is assumed to be within the current stack bounds.
3297  */
3298 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3299                                       /* func where src register points to */
3300                                       struct bpf_func_state *reg_state,
3301                                       int off, int size, int dst_regno)
3302 {
3303         struct bpf_verifier_state *vstate = env->cur_state;
3304         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3305         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3306         struct bpf_reg_state *reg;
3307         u8 *stype, type;
3308
3309         stype = reg_state->stack[spi].slot_type;
3310         reg = &reg_state->stack[spi].spilled_ptr;
3311
3312         if (is_spilled_reg(&reg_state->stack[spi])) {
3313                 u8 spill_size = 1;
3314
3315                 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3316                         spill_size++;
3317
3318                 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3319                         if (reg->type != SCALAR_VALUE) {
3320                                 verbose_linfo(env, env->insn_idx, "; ");
3321                                 verbose(env, "invalid size of register fill\n");
3322                                 return -EACCES;
3323                         }
3324
3325                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3326                         if (dst_regno < 0)
3327                                 return 0;
3328
3329                         if (!(off % BPF_REG_SIZE) && size == spill_size) {
3330                                 /* The earlier check_reg_arg() has decided the
3331                                  * subreg_def for this insn.  Save it first.
3332                                  */
3333                                 s32 subreg_def = state->regs[dst_regno].subreg_def;
3334
3335                                 state->regs[dst_regno] = *reg;
3336                                 state->regs[dst_regno].subreg_def = subreg_def;
3337                         } else {
3338                                 for (i = 0; i < size; i++) {
3339                                         type = stype[(slot - i) % BPF_REG_SIZE];
3340                                         if (type == STACK_SPILL)
3341                                                 continue;
3342                                         if (type == STACK_MISC)
3343                                                 continue;
3344                                         verbose(env, "invalid read from stack off %d+%d size %d\n",
3345                                                 off, i, size);
3346                                         return -EACCES;
3347                                 }
3348                                 mark_reg_unknown(env, state->regs, dst_regno);
3349                         }
3350                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3351                         return 0;
3352                 }
3353
3354                 if (dst_regno >= 0) {
3355                         /* restore register state from stack */
3356                         state->regs[dst_regno] = *reg;
3357                         /* mark reg as written since spilled pointer state likely
3358                          * has its liveness marks cleared by is_state_visited()
3359                          * which resets stack/reg liveness for state transitions
3360                          */
3361                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3362                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3363                         /* If dst_regno==-1, the caller is asking us whether
3364                          * it is acceptable to use this value as a SCALAR_VALUE
3365                          * (e.g. for XADD).
3366                          * We must not allow unprivileged callers to do that
3367                          * with spilled pointers.
3368                          */
3369                         verbose(env, "leaking pointer from stack off %d\n",
3370                                 off);
3371                         return -EACCES;
3372                 }
3373                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3374         } else {
3375                 for (i = 0; i < size; i++) {
3376                         type = stype[(slot - i) % BPF_REG_SIZE];
3377                         if (type == STACK_MISC)
3378                                 continue;
3379                         if (type == STACK_ZERO)
3380                                 continue;
3381                         verbose(env, "invalid read from stack off %d+%d size %d\n",
3382                                 off, i, size);
3383                         return -EACCES;
3384                 }
3385                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3386                 if (dst_regno >= 0)
3387                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3388         }
3389         return 0;
3390 }
3391
3392 enum bpf_access_src {
3393         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3394         ACCESS_HELPER = 2,  /* the access is performed by a helper */
3395 };
3396
3397 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3398                                          int regno, int off, int access_size,
3399                                          bool zero_size_allowed,
3400                                          enum bpf_access_src type,
3401                                          struct bpf_call_arg_meta *meta);
3402
3403 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3404 {
3405         return cur_regs(env) + regno;
3406 }
3407
3408 /* Read the stack at 'ptr_regno + off' and put the result into the register
3409  * 'dst_regno'.
3410  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3411  * but not its variable offset.
3412  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3413  *
3414  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3415  * filling registers (i.e. reads of spilled register cannot be detected when
3416  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3417  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3418  * offset; for a fixed offset check_stack_read_fixed_off should be used
3419  * instead.
3420  */
3421 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3422                                     int ptr_regno, int off, int size, int dst_regno)
3423 {
3424         /* The state of the source register. */
3425         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3426         struct bpf_func_state *ptr_state = func(env, reg);
3427         int err;
3428         int min_off, max_off;
3429
3430         /* Note that we pass a NULL meta, so raw access will not be permitted.
3431          */
3432         err = check_stack_range_initialized(env, ptr_regno, off, size,
3433                                             false, ACCESS_DIRECT, NULL);
3434         if (err)
3435                 return err;
3436
3437         min_off = reg->smin_value + off;
3438         max_off = reg->smax_value + off;
3439         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3440         return 0;
3441 }
3442
3443 /* check_stack_read dispatches to check_stack_read_fixed_off or
3444  * check_stack_read_var_off.
3445  *
3446  * The caller must ensure that the offset falls within the allocated stack
3447  * bounds.
3448  *
3449  * 'dst_regno' is a register which will receive the value from the stack. It
3450  * can be -1, meaning that the read value is not going to a register.
3451  */
3452 static int check_stack_read(struct bpf_verifier_env *env,
3453                             int ptr_regno, int off, int size,
3454                             int dst_regno)
3455 {
3456         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3457         struct bpf_func_state *state = func(env, reg);
3458         int err;
3459         /* Some accesses are only permitted with a static offset. */
3460         bool var_off = !tnum_is_const(reg->var_off);
3461
3462         /* The offset is required to be static when reads don't go to a
3463          * register, in order to not leak pointers (see
3464          * check_stack_read_fixed_off).
3465          */
3466         if (dst_regno < 0 && var_off) {
3467                 char tn_buf[48];
3468
3469                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3470                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3471                         tn_buf, off, size);
3472                 return -EACCES;
3473         }
3474         /* Variable offset is prohibited for unprivileged mode for simplicity
3475          * since it requires corresponding support in Spectre masking for stack
3476          * ALU. See also retrieve_ptr_limit().
3477          */
3478         if (!env->bypass_spec_v1 && var_off) {
3479                 char tn_buf[48];
3480
3481                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3482                 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3483                                 ptr_regno, tn_buf);
3484                 return -EACCES;
3485         }
3486
3487         if (!var_off) {
3488                 off += reg->var_off.value;
3489                 err = check_stack_read_fixed_off(env, state, off, size,
3490                                                  dst_regno);
3491         } else {
3492                 /* Variable offset stack reads need more conservative handling
3493                  * than fixed offset ones. Note that dst_regno >= 0 on this
3494                  * branch.
3495                  */
3496                 err = check_stack_read_var_off(env, ptr_regno, off, size,
3497                                                dst_regno);
3498         }
3499         return err;
3500 }
3501
3502
3503 /* check_stack_write dispatches to check_stack_write_fixed_off or
3504  * check_stack_write_var_off.
3505  *
3506  * 'ptr_regno' is the register used as a pointer into the stack.
3507  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3508  * 'value_regno' is the register whose value we're writing to the stack. It can
3509  * be -1, meaning that we're not writing from a register.
3510  *
3511  * The caller must ensure that the offset falls within the maximum stack size.
3512  */
3513 static int check_stack_write(struct bpf_verifier_env *env,
3514                              int ptr_regno, int off, int size,
3515                              int value_regno, int insn_idx)
3516 {
3517         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3518         struct bpf_func_state *state = func(env, reg);
3519         int err;
3520
3521         if (tnum_is_const(reg->var_off)) {
3522                 off += reg->var_off.value;
3523                 err = check_stack_write_fixed_off(env, state, off, size,
3524                                                   value_regno, insn_idx);
3525         } else {
3526                 /* Variable offset stack reads need more conservative handling
3527                  * than fixed offset ones.
3528                  */
3529                 err = check_stack_write_var_off(env, state,
3530                                                 ptr_regno, off, size,
3531                                                 value_regno, insn_idx);
3532         }
3533         return err;
3534 }
3535
3536 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3537                                  int off, int size, enum bpf_access_type type)
3538 {
3539         struct bpf_reg_state *regs = cur_regs(env);
3540         struct bpf_map *map = regs[regno].map_ptr;
3541         u32 cap = bpf_map_flags_to_cap(map);
3542
3543         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3544                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3545                         map->value_size, off, size);
3546                 return -EACCES;
3547         }
3548
3549         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3550                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3551                         map->value_size, off, size);
3552                 return -EACCES;
3553         }
3554
3555         return 0;
3556 }
3557
3558 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3559 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3560                               int off, int size, u32 mem_size,
3561                               bool zero_size_allowed)
3562 {
3563         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3564         struct bpf_reg_state *reg;
3565
3566         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3567                 return 0;
3568
3569         reg = &cur_regs(env)[regno];
3570         switch (reg->type) {
3571         case PTR_TO_MAP_KEY:
3572                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3573                         mem_size, off, size);
3574                 break;
3575         case PTR_TO_MAP_VALUE:
3576                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3577                         mem_size, off, size);
3578                 break;
3579         case PTR_TO_PACKET:
3580         case PTR_TO_PACKET_META:
3581         case PTR_TO_PACKET_END:
3582                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3583                         off, size, regno, reg->id, off, mem_size);
3584                 break;
3585         case PTR_TO_MEM:
3586         default:
3587                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3588                         mem_size, off, size);
3589         }
3590
3591         return -EACCES;
3592 }
3593
3594 /* check read/write into a memory region with possible variable offset */
3595 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3596                                    int off, int size, u32 mem_size,
3597                                    bool zero_size_allowed)
3598 {
3599         struct bpf_verifier_state *vstate = env->cur_state;
3600         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3601         struct bpf_reg_state *reg = &state->regs[regno];
3602         int err;
3603
3604         /* We may have adjusted the register pointing to memory region, so we
3605          * need to try adding each of min_value and max_value to off
3606          * to make sure our theoretical access will be safe.
3607          *
3608          * The minimum value is only important with signed
3609          * comparisons where we can't assume the floor of a
3610          * value is 0.  If we are using signed variables for our
3611          * index'es we need to make sure that whatever we use
3612          * will have a set floor within our range.
3613          */
3614         if (reg->smin_value < 0 &&
3615             (reg->smin_value == S64_MIN ||
3616              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3617               reg->smin_value + off < 0)) {
3618                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3619                         regno);
3620                 return -EACCES;
3621         }
3622         err = __check_mem_access(env, regno, reg->smin_value + off, size,
3623                                  mem_size, zero_size_allowed);
3624         if (err) {
3625                 verbose(env, "R%d min value is outside of the allowed memory range\n",
3626                         regno);
3627                 return err;
3628         }
3629
3630         /* If we haven't set a max value then we need to bail since we can't be
3631          * sure we won't do bad things.
3632          * If reg->umax_value + off could overflow, treat that as unbounded too.
3633          */
3634         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3635                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3636                         regno);
3637                 return -EACCES;
3638         }
3639         err = __check_mem_access(env, regno, reg->umax_value + off, size,
3640                                  mem_size, zero_size_allowed);
3641         if (err) {
3642                 verbose(env, "R%d max value is outside of the allowed memory range\n",
3643                         regno);
3644                 return err;
3645         }
3646
3647         return 0;
3648 }
3649
3650 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3651                                const struct bpf_reg_state *reg, int regno,
3652                                bool fixed_off_ok)
3653 {
3654         /* Access to this pointer-typed register or passing it to a helper
3655          * is only allowed in its original, unmodified form.
3656          */
3657
3658         if (reg->off < 0) {
3659                 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3660                         reg_type_str(env, reg->type), regno, reg->off);
3661                 return -EACCES;
3662         }
3663
3664         if (!fixed_off_ok && reg->off) {
3665                 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3666                         reg_type_str(env, reg->type), regno, reg->off);
3667                 return -EACCES;
3668         }
3669
3670         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3671                 char tn_buf[48];
3672
3673                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3674                 verbose(env, "variable %s access var_off=%s disallowed\n",
3675                         reg_type_str(env, reg->type), tn_buf);
3676                 return -EACCES;
3677         }
3678
3679         return 0;
3680 }
3681
3682 int check_ptr_off_reg(struct bpf_verifier_env *env,
3683                       const struct bpf_reg_state *reg, int regno)
3684 {
3685         return __check_ptr_off_reg(env, reg, regno, false);
3686 }
3687
3688 static int map_kptr_match_type(struct bpf_verifier_env *env,
3689                                struct bpf_map_value_off_desc *off_desc,
3690                                struct bpf_reg_state *reg, u32 regno)
3691 {
3692         const char *targ_name = kernel_type_name(off_desc->kptr.btf, off_desc->kptr.btf_id);
3693         int perm_flags = PTR_MAYBE_NULL;
3694         const char *reg_name = "";
3695
3696         /* Only unreferenced case accepts untrusted pointers */
3697         if (off_desc->type == BPF_KPTR_UNREF)
3698                 perm_flags |= PTR_UNTRUSTED;
3699
3700         if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3701                 goto bad_type;
3702
3703         if (!btf_is_kernel(reg->btf)) {
3704                 verbose(env, "R%d must point to kernel BTF\n", regno);
3705                 return -EINVAL;
3706         }
3707         /* We need to verify reg->type and reg->btf, before accessing reg->btf */
3708         reg_name = kernel_type_name(reg->btf, reg->btf_id);
3709
3710         /* For ref_ptr case, release function check should ensure we get one
3711          * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3712          * normal store of unreferenced kptr, we must ensure var_off is zero.
3713          * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3714          * reg->off and reg->ref_obj_id are not needed here.
3715          */
3716         if (__check_ptr_off_reg(env, reg, regno, true))
3717                 return -EACCES;
3718
3719         /* A full type match is needed, as BTF can be vmlinux or module BTF, and
3720          * we also need to take into account the reg->off.
3721          *
3722          * We want to support cases like:
3723          *
3724          * struct foo {
3725          *         struct bar br;
3726          *         struct baz bz;
3727          * };
3728          *
3729          * struct foo *v;
3730          * v = func();        // PTR_TO_BTF_ID
3731          * val->foo = v;      // reg->off is zero, btf and btf_id match type
3732          * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3733          *                    // first member type of struct after comparison fails
3734          * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3735          *                    // to match type
3736          *
3737          * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3738          * is zero. We must also ensure that btf_struct_ids_match does not walk
3739          * the struct to match type against first member of struct, i.e. reject
3740          * second case from above. Hence, when type is BPF_KPTR_REF, we set
3741          * strict mode to true for type match.
3742          */
3743         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3744                                   off_desc->kptr.btf, off_desc->kptr.btf_id,
3745                                   off_desc->type == BPF_KPTR_REF))
3746                 goto bad_type;
3747         return 0;
3748 bad_type:
3749         verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3750                 reg_type_str(env, reg->type), reg_name);
3751         verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3752         if (off_desc->type == BPF_KPTR_UNREF)
3753                 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3754                         targ_name);
3755         else
3756                 verbose(env, "\n");
3757         return -EINVAL;
3758 }
3759
3760 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3761                                  int value_regno, int insn_idx,
3762                                  struct bpf_map_value_off_desc *off_desc)
3763 {
3764         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3765         int class = BPF_CLASS(insn->code);
3766         struct bpf_reg_state *val_reg;
3767
3768         /* Things we already checked for in check_map_access and caller:
3769          *  - Reject cases where variable offset may touch kptr
3770          *  - size of access (must be BPF_DW)
3771          *  - tnum_is_const(reg->var_off)
3772          *  - off_desc->offset == off + reg->var_off.value
3773          */
3774         /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3775         if (BPF_MODE(insn->code) != BPF_MEM) {
3776                 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3777                 return -EACCES;
3778         }
3779
3780         /* We only allow loading referenced kptr, since it will be marked as
3781          * untrusted, similar to unreferenced kptr.
3782          */
3783         if (class != BPF_LDX && off_desc->type == BPF_KPTR_REF) {
3784                 verbose(env, "store to referenced kptr disallowed\n");
3785                 return -EACCES;
3786         }
3787
3788         if (class == BPF_LDX) {
3789                 val_reg = reg_state(env, value_regno);
3790                 /* We can simply mark the value_regno receiving the pointer
3791                  * value from map as PTR_TO_BTF_ID, with the correct type.
3792                  */
3793                 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, off_desc->kptr.btf,
3794                                 off_desc->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3795                 /* For mark_ptr_or_null_reg */
3796                 val_reg->id = ++env->id_gen;
3797         } else if (class == BPF_STX) {
3798                 val_reg = reg_state(env, value_regno);
3799                 if (!register_is_null(val_reg) &&
3800                     map_kptr_match_type(env, off_desc, val_reg, value_regno))
3801                         return -EACCES;
3802         } else if (class == BPF_ST) {
3803                 if (insn->imm) {
3804                         verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3805                                 off_desc->offset);
3806                         return -EACCES;
3807                 }
3808         } else {
3809                 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3810                 return -EACCES;
3811         }
3812         return 0;
3813 }
3814
3815 /* check read/write into a map element with possible variable offset */
3816 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3817                             int off, int size, bool zero_size_allowed,
3818                             enum bpf_access_src src)
3819 {
3820         struct bpf_verifier_state *vstate = env->cur_state;
3821         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3822         struct bpf_reg_state *reg = &state->regs[regno];
3823         struct bpf_map *map = reg->map_ptr;
3824         int err;
3825
3826         err = check_mem_region_access(env, regno, off, size, map->value_size,
3827                                       zero_size_allowed);
3828         if (err)
3829                 return err;
3830
3831         if (map_value_has_spin_lock(map)) {
3832                 u32 lock = map->spin_lock_off;
3833
3834                 /* if any part of struct bpf_spin_lock can be touched by
3835                  * load/store reject this program.
3836                  * To check that [x1, x2) overlaps with [y1, y2)
3837                  * it is sufficient to check x1 < y2 && y1 < x2.
3838                  */
3839                 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3840                      lock < reg->umax_value + off + size) {
3841                         verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3842                         return -EACCES;
3843                 }
3844         }
3845         if (map_value_has_timer(map)) {
3846                 u32 t = map->timer_off;
3847
3848                 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3849                      t < reg->umax_value + off + size) {
3850                         verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3851                         return -EACCES;
3852                 }
3853         }
3854         if (map_value_has_kptrs(map)) {
3855                 struct bpf_map_value_off *tab = map->kptr_off_tab;
3856                 int i;
3857
3858                 for (i = 0; i < tab->nr_off; i++) {
3859                         u32 p = tab->off[i].offset;
3860
3861                         if (reg->smin_value + off < p + sizeof(u64) &&
3862                             p < reg->umax_value + off + size) {
3863                                 if (src != ACCESS_DIRECT) {
3864                                         verbose(env, "kptr cannot be accessed indirectly by helper\n");
3865                                         return -EACCES;
3866                                 }
3867                                 if (!tnum_is_const(reg->var_off)) {
3868                                         verbose(env, "kptr access cannot have variable offset\n");
3869                                         return -EACCES;
3870                                 }
3871                                 if (p != off + reg->var_off.value) {
3872                                         verbose(env, "kptr access misaligned expected=%u off=%llu\n",
3873                                                 p, off + reg->var_off.value);
3874                                         return -EACCES;
3875                                 }
3876                                 if (size != bpf_size_to_bytes(BPF_DW)) {
3877                                         verbose(env, "kptr access size must be BPF_DW\n");
3878                                         return -EACCES;
3879                                 }
3880                                 break;
3881                         }
3882                 }
3883         }
3884         return err;
3885 }
3886
3887 #define MAX_PACKET_OFF 0xffff
3888
3889 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3890                                        const struct bpf_call_arg_meta *meta,
3891                                        enum bpf_access_type t)
3892 {
3893         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3894
3895         switch (prog_type) {
3896         /* Program types only with direct read access go here! */
3897         case BPF_PROG_TYPE_LWT_IN:
3898         case BPF_PROG_TYPE_LWT_OUT:
3899         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3900         case BPF_PROG_TYPE_SK_REUSEPORT:
3901         case BPF_PROG_TYPE_FLOW_DISSECTOR:
3902         case BPF_PROG_TYPE_CGROUP_SKB:
3903                 if (t == BPF_WRITE)
3904                         return false;
3905                 fallthrough;
3906
3907         /* Program types with direct read + write access go here! */
3908         case BPF_PROG_TYPE_SCHED_CLS:
3909         case BPF_PROG_TYPE_SCHED_ACT:
3910         case BPF_PROG_TYPE_XDP:
3911         case BPF_PROG_TYPE_LWT_XMIT:
3912         case BPF_PROG_TYPE_SK_SKB:
3913         case BPF_PROG_TYPE_SK_MSG:
3914                 if (meta)
3915                         return meta->pkt_access;
3916
3917                 env->seen_direct_write = true;
3918                 return true;
3919
3920         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3921                 if (t == BPF_WRITE)
3922                         env->seen_direct_write = true;
3923
3924                 return true;
3925
3926         default:
3927                 return false;
3928         }
3929 }
3930
3931 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3932                                int size, bool zero_size_allowed)
3933 {
3934         struct bpf_reg_state *regs = cur_regs(env);
3935         struct bpf_reg_state *reg = &regs[regno];
3936         int err;
3937
3938         /* We may have added a variable offset to the packet pointer; but any
3939          * reg->range we have comes after that.  We are only checking the fixed
3940          * offset.
3941          */
3942
3943         /* We don't allow negative numbers, because we aren't tracking enough
3944          * detail to prove they're safe.
3945          */
3946         if (reg->smin_value < 0) {
3947                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3948                         regno);
3949                 return -EACCES;
3950         }
3951
3952         err = reg->range < 0 ? -EINVAL :
3953               __check_mem_access(env, regno, off, size, reg->range,
3954                                  zero_size_allowed);
3955         if (err) {
3956                 verbose(env, "R%d offset is outside of the packet\n", regno);
3957                 return err;
3958         }
3959
3960         /* __check_mem_access has made sure "off + size - 1" is within u16.
3961          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3962          * otherwise find_good_pkt_pointers would have refused to set range info
3963          * that __check_mem_access would have rejected this pkt access.
3964          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3965          */
3966         env->prog->aux->max_pkt_offset =
3967                 max_t(u32, env->prog->aux->max_pkt_offset,
3968                       off + reg->umax_value + size - 1);
3969
3970         return err;
3971 }
3972
3973 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
3974 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3975                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
3976                             struct btf **btf, u32 *btf_id)
3977 {
3978         struct bpf_insn_access_aux info = {
3979                 .reg_type = *reg_type,
3980                 .log = &env->log,
3981         };
3982
3983         if (env->ops->is_valid_access &&
3984             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3985                 /* A non zero info.ctx_field_size indicates that this field is a
3986                  * candidate for later verifier transformation to load the whole
3987                  * field and then apply a mask when accessed with a narrower
3988                  * access than actual ctx access size. A zero info.ctx_field_size
3989                  * will only allow for whole field access and rejects any other
3990                  * type of narrower access.
3991                  */
3992                 *reg_type = info.reg_type;
3993
3994                 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
3995                         *btf = info.btf;
3996                         *btf_id = info.btf_id;
3997                 } else {
3998                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3999                 }
4000                 /* remember the offset of last byte accessed in ctx */
4001                 if (env->prog->aux->max_ctx_offset < off + size)
4002                         env->prog->aux->max_ctx_offset = off + size;
4003                 return 0;
4004         }
4005
4006         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4007         return -EACCES;
4008 }
4009
4010 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4011                                   int size)
4012 {
4013         if (size < 0 || off < 0 ||
4014             (u64)off + size > sizeof(struct bpf_flow_keys)) {
4015                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4016                         off, size);
4017                 return -EACCES;
4018         }
4019         return 0;
4020 }
4021
4022 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4023                              u32 regno, int off, int size,
4024                              enum bpf_access_type t)
4025 {
4026         struct bpf_reg_state *regs = cur_regs(env);
4027         struct bpf_reg_state *reg = &regs[regno];
4028         struct bpf_insn_access_aux info = {};
4029         bool valid;
4030
4031         if (reg->smin_value < 0) {
4032                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4033                         regno);
4034                 return -EACCES;
4035         }
4036
4037         switch (reg->type) {
4038         case PTR_TO_SOCK_COMMON:
4039                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4040                 break;
4041         case PTR_TO_SOCKET:
4042                 valid = bpf_sock_is_valid_access(off, size, t, &info);
4043                 break;
4044         case PTR_TO_TCP_SOCK:
4045                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4046                 break;
4047         case PTR_TO_XDP_SOCK:
4048                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4049                 break;
4050         default:
4051                 valid = false;
4052         }
4053
4054
4055         if (valid) {
4056                 env->insn_aux_data[insn_idx].ctx_field_size =
4057                         info.ctx_field_size;
4058                 return 0;
4059         }
4060
4061         verbose(env, "R%d invalid %s access off=%d size=%d\n",
4062                 regno, reg_type_str(env, reg->type), off, size);
4063
4064         return -EACCES;
4065 }
4066
4067 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4068 {
4069         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4070 }
4071
4072 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4073 {
4074         const struct bpf_reg_state *reg = reg_state(env, regno);
4075
4076         return reg->type == PTR_TO_CTX;
4077 }
4078
4079 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4080 {
4081         const struct bpf_reg_state *reg = reg_state(env, regno);
4082
4083         return type_is_sk_pointer(reg->type);
4084 }
4085
4086 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4087 {
4088         const struct bpf_reg_state *reg = reg_state(env, regno);
4089
4090         return type_is_pkt_pointer(reg->type);
4091 }
4092
4093 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4094 {
4095         const struct bpf_reg_state *reg = reg_state(env, regno);
4096
4097         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4098         return reg->type == PTR_TO_FLOW_KEYS;
4099 }
4100
4101 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4102                                    const struct bpf_reg_state *reg,
4103                                    int off, int size, bool strict)
4104 {
4105         struct tnum reg_off;
4106         int ip_align;
4107
4108         /* Byte size accesses are always allowed. */
4109         if (!strict || size == 1)
4110                 return 0;
4111
4112         /* For platforms that do not have a Kconfig enabling
4113          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4114          * NET_IP_ALIGN is universally set to '2'.  And on platforms
4115          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4116          * to this code only in strict mode where we want to emulate
4117          * the NET_IP_ALIGN==2 checking.  Therefore use an
4118          * unconditional IP align value of '2'.
4119          */
4120         ip_align = 2;
4121
4122         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4123         if (!tnum_is_aligned(reg_off, size)) {
4124                 char tn_buf[48];
4125
4126                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4127                 verbose(env,
4128                         "misaligned packet access off %d+%s+%d+%d size %d\n",
4129                         ip_align, tn_buf, reg->off, off, size);
4130                 return -EACCES;
4131         }
4132
4133         return 0;
4134 }
4135
4136 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4137                                        const struct bpf_reg_state *reg,
4138                                        const char *pointer_desc,
4139                                        int off, int size, bool strict)
4140 {
4141         struct tnum reg_off;
4142
4143         /* Byte size accesses are always allowed. */
4144         if (!strict || size == 1)
4145                 return 0;
4146
4147         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4148         if (!tnum_is_aligned(reg_off, size)) {
4149                 char tn_buf[48];
4150
4151                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4152                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4153                         pointer_desc, tn_buf, reg->off, off, size);
4154                 return -EACCES;
4155         }
4156
4157         return 0;
4158 }
4159
4160 static int check_ptr_alignment(struct bpf_verifier_env *env,
4161                                const struct bpf_reg_state *reg, int off,
4162                                int size, bool strict_alignment_once)
4163 {
4164         bool strict = env->strict_alignment || strict_alignment_once;
4165         const char *pointer_desc = "";
4166
4167         switch (reg->type) {
4168         case PTR_TO_PACKET:
4169         case PTR_TO_PACKET_META:
4170                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4171                  * right in front, treat it the very same way.
4172                  */
4173                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
4174         case PTR_TO_FLOW_KEYS:
4175                 pointer_desc = "flow keys ";
4176                 break;
4177         case PTR_TO_MAP_KEY:
4178                 pointer_desc = "key ";
4179                 break;
4180         case PTR_TO_MAP_VALUE:
4181                 pointer_desc = "value ";
4182                 break;
4183         case PTR_TO_CTX:
4184                 pointer_desc = "context ";
4185                 break;
4186         case PTR_TO_STACK:
4187                 pointer_desc = "stack ";
4188                 /* The stack spill tracking logic in check_stack_write_fixed_off()
4189                  * and check_stack_read_fixed_off() relies on stack accesses being
4190                  * aligned.
4191                  */
4192                 strict = true;
4193                 break;
4194         case PTR_TO_SOCKET:
4195                 pointer_desc = "sock ";
4196                 break;
4197         case PTR_TO_SOCK_COMMON:
4198                 pointer_desc = "sock_common ";
4199                 break;
4200         case PTR_TO_TCP_SOCK:
4201                 pointer_desc = "tcp_sock ";
4202                 break;
4203         case PTR_TO_XDP_SOCK:
4204                 pointer_desc = "xdp_sock ";
4205                 break;
4206         default:
4207                 break;
4208         }
4209         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4210                                            strict);
4211 }
4212
4213 static int update_stack_depth(struct bpf_verifier_env *env,
4214                               const struct bpf_func_state *func,
4215                               int off)
4216 {
4217         u16 stack = env->subprog_info[func->subprogno].stack_depth;
4218
4219         if (stack >= -off)
4220                 return 0;
4221
4222         /* update known max for given subprogram */
4223         env->subprog_info[func->subprogno].stack_depth = -off;
4224         return 0;
4225 }
4226
4227 /* starting from main bpf function walk all instructions of the function
4228  * and recursively walk all callees that given function can call.
4229  * Ignore jump and exit insns.
4230  * Since recursion is prevented by check_cfg() this algorithm
4231  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4232  */
4233 static int check_max_stack_depth(struct bpf_verifier_env *env)
4234 {
4235         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4236         struct bpf_subprog_info *subprog = env->subprog_info;
4237         struct bpf_insn *insn = env->prog->insnsi;
4238         bool tail_call_reachable = false;
4239         int ret_insn[MAX_CALL_FRAMES];
4240         int ret_prog[MAX_CALL_FRAMES];
4241         int j;
4242
4243 process_func:
4244         /* protect against potential stack overflow that might happen when
4245          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4246          * depth for such case down to 256 so that the worst case scenario
4247          * would result in 8k stack size (32 which is tailcall limit * 256 =
4248          * 8k).
4249          *
4250          * To get the idea what might happen, see an example:
4251          * func1 -> sub rsp, 128
4252          *  subfunc1 -> sub rsp, 256
4253          *  tailcall1 -> add rsp, 256
4254          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4255          *   subfunc2 -> sub rsp, 64
4256          *   subfunc22 -> sub rsp, 128
4257          *   tailcall2 -> add rsp, 128
4258          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4259          *
4260          * tailcall will unwind the current stack frame but it will not get rid
4261          * of caller's stack as shown on the example above.
4262          */
4263         if (idx && subprog[idx].has_tail_call && depth >= 256) {
4264                 verbose(env,
4265                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4266                         depth);
4267                 return -EACCES;
4268         }
4269         /* round up to 32-bytes, since this is granularity
4270          * of interpreter stack size
4271          */
4272         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4273         if (depth > MAX_BPF_STACK) {
4274                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
4275                         frame + 1, depth);
4276                 return -EACCES;
4277         }
4278 continue_func:
4279         subprog_end = subprog[idx + 1].start;
4280         for (; i < subprog_end; i++) {
4281                 int next_insn;
4282
4283                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4284                         continue;
4285                 /* remember insn and function to return to */
4286                 ret_insn[frame] = i + 1;
4287                 ret_prog[frame] = idx;
4288
4289                 /* find the callee */
4290                 next_insn = i + insn[i].imm + 1;
4291                 idx = find_subprog(env, next_insn);
4292                 if (idx < 0) {
4293                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4294                                   next_insn);
4295                         return -EFAULT;
4296                 }
4297                 if (subprog[idx].is_async_cb) {
4298                         if (subprog[idx].has_tail_call) {
4299                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4300                                 return -EFAULT;
4301                         }
4302                          /* async callbacks don't increase bpf prog stack size */
4303                         continue;
4304                 }
4305                 i = next_insn;
4306
4307                 if (subprog[idx].has_tail_call)
4308                         tail_call_reachable = true;
4309
4310                 frame++;
4311                 if (frame >= MAX_CALL_FRAMES) {
4312                         verbose(env, "the call stack of %d frames is too deep !\n",
4313                                 frame);
4314                         return -E2BIG;
4315                 }
4316                 goto process_func;
4317         }
4318         /* if tail call got detected across bpf2bpf calls then mark each of the
4319          * currently present subprog frames as tail call reachable subprogs;
4320          * this info will be utilized by JIT so that we will be preserving the
4321          * tail call counter throughout bpf2bpf calls combined with tailcalls
4322          */
4323         if (tail_call_reachable)
4324                 for (j = 0; j < frame; j++)
4325                         subprog[ret_prog[j]].tail_call_reachable = true;
4326         if (subprog[0].tail_call_reachable)
4327                 env->prog->aux->tail_call_reachable = true;
4328
4329         /* end of for() loop means the last insn of the 'subprog'
4330          * was reached. Doesn't matter whether it was JA or EXIT
4331          */
4332         if (frame == 0)
4333                 return 0;
4334         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4335         frame--;
4336         i = ret_insn[frame];
4337         idx = ret_prog[frame];
4338         goto continue_func;
4339 }
4340
4341 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4342 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4343                                   const struct bpf_insn *insn, int idx)
4344 {
4345         int start = idx + insn->imm + 1, subprog;
4346
4347         subprog = find_subprog(env, start);
4348         if (subprog < 0) {
4349                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4350                           start);
4351                 return -EFAULT;
4352         }
4353         return env->subprog_info[subprog].stack_depth;
4354 }
4355 #endif
4356
4357 static int __check_buffer_access(struct bpf_verifier_env *env,
4358                                  const char *buf_info,
4359                                  const struct bpf_reg_state *reg,
4360                                  int regno, int off, int size)
4361 {
4362         if (off < 0) {
4363                 verbose(env,
4364                         "R%d invalid %s buffer access: off=%d, size=%d\n",
4365                         regno, buf_info, off, size);
4366                 return -EACCES;
4367         }
4368         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4369                 char tn_buf[48];
4370
4371                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4372                 verbose(env,
4373                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4374                         regno, off, tn_buf);
4375                 return -EACCES;
4376         }
4377
4378         return 0;
4379 }
4380
4381 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4382                                   const struct bpf_reg_state *reg,
4383                                   int regno, int off, int size)
4384 {
4385         int err;
4386
4387         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4388         if (err)
4389                 return err;
4390
4391         if (off + size > env->prog->aux->max_tp_access)
4392                 env->prog->aux->max_tp_access = off + size;
4393
4394         return 0;
4395 }
4396
4397 static int check_buffer_access(struct bpf_verifier_env *env,
4398                                const struct bpf_reg_state *reg,
4399                                int regno, int off, int size,
4400                                bool zero_size_allowed,
4401                                u32 *max_access)
4402 {
4403         const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4404         int err;
4405
4406         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4407         if (err)
4408                 return err;
4409
4410         if (off + size > *max_access)
4411                 *max_access = off + size;
4412
4413         return 0;
4414 }
4415
4416 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4417 static void zext_32_to_64(struct bpf_reg_state *reg)
4418 {
4419         reg->var_off = tnum_subreg(reg->var_off);
4420         __reg_assign_32_into_64(reg);
4421 }
4422
4423 /* truncate register to smaller size (in bytes)
4424  * must be called with size < BPF_REG_SIZE
4425  */
4426 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4427 {
4428         u64 mask;
4429
4430         /* clear high bits in bit representation */
4431         reg->var_off = tnum_cast(reg->var_off, size);
4432
4433         /* fix arithmetic bounds */
4434         mask = ((u64)1 << (size * 8)) - 1;
4435         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4436                 reg->umin_value &= mask;
4437                 reg->umax_value &= mask;
4438         } else {
4439                 reg->umin_value = 0;
4440                 reg->umax_value = mask;
4441         }
4442         reg->smin_value = reg->umin_value;
4443         reg->smax_value = reg->umax_value;
4444
4445         /* If size is smaller than 32bit register the 32bit register
4446          * values are also truncated so we push 64-bit bounds into
4447          * 32-bit bounds. Above were truncated < 32-bits already.
4448          */
4449         if (size >= 4)
4450                 return;
4451         __reg_combine_64_into_32(reg);
4452 }
4453
4454 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4455 {
4456         /* A map is considered read-only if the following condition are true:
4457          *
4458          * 1) BPF program side cannot change any of the map content. The
4459          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4460          *    and was set at map creation time.
4461          * 2) The map value(s) have been initialized from user space by a
4462          *    loader and then "frozen", such that no new map update/delete
4463          *    operations from syscall side are possible for the rest of
4464          *    the map's lifetime from that point onwards.
4465          * 3) Any parallel/pending map update/delete operations from syscall
4466          *    side have been completed. Only after that point, it's safe to
4467          *    assume that map value(s) are immutable.
4468          */
4469         return (map->map_flags & BPF_F_RDONLY_PROG) &&
4470                READ_ONCE(map->frozen) &&
4471                !bpf_map_write_active(map);
4472 }
4473
4474 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4475 {
4476         void *ptr;
4477         u64 addr;
4478         int err;
4479
4480         err = map->ops->map_direct_value_addr(map, &addr, off);
4481         if (err)
4482                 return err;
4483         ptr = (void *)(long)addr + off;
4484
4485         switch (size) {
4486         case sizeof(u8):
4487                 *val = (u64)*(u8 *)ptr;
4488                 break;
4489         case sizeof(u16):
4490                 *val = (u64)*(u16 *)ptr;
4491                 break;
4492         case sizeof(u32):
4493                 *val = (u64)*(u32 *)ptr;
4494                 break;
4495         case sizeof(u64):
4496                 *val = *(u64 *)ptr;
4497                 break;
4498         default:
4499                 return -EINVAL;
4500         }
4501         return 0;
4502 }
4503
4504 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4505                                    struct bpf_reg_state *regs,
4506                                    int regno, int off, int size,
4507                                    enum bpf_access_type atype,
4508                                    int value_regno)
4509 {
4510         struct bpf_reg_state *reg = regs + regno;
4511         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4512         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4513         enum bpf_type_flag flag = 0;
4514         u32 btf_id;
4515         int ret;
4516
4517         if (off < 0) {
4518                 verbose(env,
4519                         "R%d is ptr_%s invalid negative access: off=%d\n",
4520                         regno, tname, off);
4521                 return -EACCES;
4522         }
4523         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4524                 char tn_buf[48];
4525
4526                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4527                 verbose(env,
4528                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4529                         regno, tname, off, tn_buf);
4530                 return -EACCES;
4531         }
4532
4533         if (reg->type & MEM_USER) {
4534                 verbose(env,
4535                         "R%d is ptr_%s access user memory: off=%d\n",
4536                         regno, tname, off);
4537                 return -EACCES;
4538         }
4539
4540         if (reg->type & MEM_PERCPU) {
4541                 verbose(env,
4542                         "R%d is ptr_%s access percpu memory: off=%d\n",
4543                         regno, tname, off);
4544                 return -EACCES;
4545         }
4546
4547         if (env->ops->btf_struct_access) {
4548                 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4549                                                   off, size, atype, &btf_id, &flag);
4550         } else {
4551                 if (atype != BPF_READ) {
4552                         verbose(env, "only read is supported\n");
4553                         return -EACCES;
4554                 }
4555
4556                 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4557                                         atype, &btf_id, &flag);
4558         }
4559
4560         if (ret < 0)
4561                 return ret;
4562
4563         /* If this is an untrusted pointer, all pointers formed by walking it
4564          * also inherit the untrusted flag.
4565          */
4566         if (type_flag(reg->type) & PTR_UNTRUSTED)
4567                 flag |= PTR_UNTRUSTED;
4568
4569         if (atype == BPF_READ && value_regno >= 0)
4570                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4571
4572         return 0;
4573 }
4574
4575 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4576                                    struct bpf_reg_state *regs,
4577                                    int regno, int off, int size,
4578                                    enum bpf_access_type atype,
4579                                    int value_regno)
4580 {
4581         struct bpf_reg_state *reg = regs + regno;
4582         struct bpf_map *map = reg->map_ptr;
4583         enum bpf_type_flag flag = 0;
4584         const struct btf_type *t;
4585         const char *tname;
4586         u32 btf_id;
4587         int ret;
4588
4589         if (!btf_vmlinux) {
4590                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4591                 return -ENOTSUPP;
4592         }
4593
4594         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4595                 verbose(env, "map_ptr access not supported for map type %d\n",
4596                         map->map_type);
4597                 return -ENOTSUPP;
4598         }
4599
4600         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4601         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4602
4603         if (!env->allow_ptr_to_map_access) {
4604                 verbose(env,
4605                         "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4606                         tname);
4607                 return -EPERM;
4608         }
4609
4610         if (off < 0) {
4611                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4612                         regno, tname, off);
4613                 return -EACCES;
4614         }
4615
4616         if (atype != BPF_READ) {
4617                 verbose(env, "only read from %s is supported\n", tname);
4618                 return -EACCES;
4619         }
4620
4621         ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag);
4622         if (ret < 0)
4623                 return ret;
4624
4625         if (value_regno >= 0)
4626                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4627
4628         return 0;
4629 }
4630
4631 /* Check that the stack access at the given offset is within bounds. The
4632  * maximum valid offset is -1.
4633  *
4634  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4635  * -state->allocated_stack for reads.
4636  */
4637 static int check_stack_slot_within_bounds(int off,
4638                                           struct bpf_func_state *state,
4639                                           enum bpf_access_type t)
4640 {
4641         int min_valid_off;
4642
4643         if (t == BPF_WRITE)
4644                 min_valid_off = -MAX_BPF_STACK;
4645         else
4646                 min_valid_off = -state->allocated_stack;
4647
4648         if (off < min_valid_off || off > -1)
4649                 return -EACCES;
4650         return 0;
4651 }
4652
4653 /* Check that the stack access at 'regno + off' falls within the maximum stack
4654  * bounds.
4655  *
4656  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4657  */
4658 static int check_stack_access_within_bounds(
4659                 struct bpf_verifier_env *env,
4660                 int regno, int off, int access_size,
4661                 enum bpf_access_src src, enum bpf_access_type type)
4662 {
4663         struct bpf_reg_state *regs = cur_regs(env);
4664         struct bpf_reg_state *reg = regs + regno;
4665         struct bpf_func_state *state = func(env, reg);
4666         int min_off, max_off;
4667         int err;
4668         char *err_extra;
4669
4670         if (src == ACCESS_HELPER)
4671                 /* We don't know if helpers are reading or writing (or both). */
4672                 err_extra = " indirect access to";
4673         else if (type == BPF_READ)
4674                 err_extra = " read from";
4675         else
4676                 err_extra = " write to";
4677
4678         if (tnum_is_const(reg->var_off)) {
4679                 min_off = reg->var_off.value + off;
4680                 if (access_size > 0)
4681                         max_off = min_off + access_size - 1;
4682                 else
4683                         max_off = min_off;
4684         } else {
4685                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4686                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
4687                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4688                                 err_extra, regno);
4689                         return -EACCES;
4690                 }
4691                 min_off = reg->smin_value + off;
4692                 if (access_size > 0)
4693                         max_off = reg->smax_value + off + access_size - 1;
4694                 else
4695                         max_off = min_off;
4696         }
4697
4698         err = check_stack_slot_within_bounds(min_off, state, type);
4699         if (!err)
4700                 err = check_stack_slot_within_bounds(max_off, state, type);
4701
4702         if (err) {
4703                 if (tnum_is_const(reg->var_off)) {
4704                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4705                                 err_extra, regno, off, access_size);
4706                 } else {
4707                         char tn_buf[48];
4708
4709                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4710                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4711                                 err_extra, regno, tn_buf, access_size);
4712                 }
4713         }
4714         return err;
4715 }
4716
4717 /* check whether memory at (regno + off) is accessible for t = (read | write)
4718  * if t==write, value_regno is a register which value is stored into memory
4719  * if t==read, value_regno is a register which will receive the value from memory
4720  * if t==write && value_regno==-1, some unknown value is stored into memory
4721  * if t==read && value_regno==-1, don't care what we read from memory
4722  */
4723 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4724                             int off, int bpf_size, enum bpf_access_type t,
4725                             int value_regno, bool strict_alignment_once)
4726 {
4727         struct bpf_reg_state *regs = cur_regs(env);
4728         struct bpf_reg_state *reg = regs + regno;
4729         struct bpf_func_state *state;
4730         int size, err = 0;
4731
4732         size = bpf_size_to_bytes(bpf_size);
4733         if (size < 0)
4734                 return size;
4735
4736         /* alignment checks will add in reg->off themselves */
4737         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4738         if (err)
4739                 return err;
4740
4741         /* for access checks, reg->off is just part of off */
4742         off += reg->off;
4743
4744         if (reg->type == PTR_TO_MAP_KEY) {
4745                 if (t == BPF_WRITE) {
4746                         verbose(env, "write to change key R%d not allowed\n", regno);
4747                         return -EACCES;
4748                 }
4749
4750                 err = check_mem_region_access(env, regno, off, size,
4751                                               reg->map_ptr->key_size, false);
4752                 if (err)
4753                         return err;
4754                 if (value_regno >= 0)
4755                         mark_reg_unknown(env, regs, value_regno);
4756         } else if (reg->type == PTR_TO_MAP_VALUE) {
4757                 struct bpf_map_value_off_desc *kptr_off_desc = NULL;
4758
4759                 if (t == BPF_WRITE && value_regno >= 0 &&
4760                     is_pointer_value(env, value_regno)) {
4761                         verbose(env, "R%d leaks addr into map\n", value_regno);
4762                         return -EACCES;
4763                 }
4764                 err = check_map_access_type(env, regno, off, size, t);
4765                 if (err)
4766                         return err;
4767                 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4768                 if (err)
4769                         return err;
4770                 if (tnum_is_const(reg->var_off))
4771                         kptr_off_desc = bpf_map_kptr_off_contains(reg->map_ptr,
4772                                                                   off + reg->var_off.value);
4773                 if (kptr_off_desc) {
4774                         err = check_map_kptr_access(env, regno, value_regno, insn_idx,
4775                                                     kptr_off_desc);
4776                 } else if (t == BPF_READ && value_regno >= 0) {
4777                         struct bpf_map *map = reg->map_ptr;
4778
4779                         /* if map is read-only, track its contents as scalars */
4780                         if (tnum_is_const(reg->var_off) &&
4781                             bpf_map_is_rdonly(map) &&
4782                             map->ops->map_direct_value_addr) {
4783                                 int map_off = off + reg->var_off.value;
4784                                 u64 val = 0;
4785
4786                                 err = bpf_map_direct_read(map, map_off, size,
4787                                                           &val);
4788                                 if (err)
4789                                         return err;
4790
4791                                 regs[value_regno].type = SCALAR_VALUE;
4792                                 __mark_reg_known(&regs[value_regno], val);
4793                         } else {
4794                                 mark_reg_unknown(env, regs, value_regno);
4795                         }
4796                 }
4797         } else if (base_type(reg->type) == PTR_TO_MEM) {
4798                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4799
4800                 if (type_may_be_null(reg->type)) {
4801                         verbose(env, "R%d invalid mem access '%s'\n", regno,
4802                                 reg_type_str(env, reg->type));
4803                         return -EACCES;
4804                 }
4805
4806                 if (t == BPF_WRITE && rdonly_mem) {
4807                         verbose(env, "R%d cannot write into %s\n",
4808                                 regno, reg_type_str(env, reg->type));
4809                         return -EACCES;
4810                 }
4811
4812                 if (t == BPF_WRITE && value_regno >= 0 &&
4813                     is_pointer_value(env, value_regno)) {
4814                         verbose(env, "R%d leaks addr into mem\n", value_regno);
4815                         return -EACCES;
4816                 }
4817
4818                 err = check_mem_region_access(env, regno, off, size,
4819                                               reg->mem_size, false);
4820                 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4821                         mark_reg_unknown(env, regs, value_regno);
4822         } else if (reg->type == PTR_TO_CTX) {
4823                 enum bpf_reg_type reg_type = SCALAR_VALUE;
4824                 struct btf *btf = NULL;
4825                 u32 btf_id = 0;
4826
4827                 if (t == BPF_WRITE && value_regno >= 0 &&
4828                     is_pointer_value(env, value_regno)) {
4829                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
4830                         return -EACCES;
4831                 }
4832
4833                 err = check_ptr_off_reg(env, reg, regno);
4834                 if (err < 0)
4835                         return err;
4836
4837                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
4838                                        &btf_id);
4839                 if (err)
4840                         verbose_linfo(env, insn_idx, "; ");
4841                 if (!err && t == BPF_READ && value_regno >= 0) {
4842                         /* ctx access returns either a scalar, or a
4843                          * PTR_TO_PACKET[_META,_END]. In the latter
4844                          * case, we know the offset is zero.
4845                          */
4846                         if (reg_type == SCALAR_VALUE) {
4847                                 mark_reg_unknown(env, regs, value_regno);
4848                         } else {
4849                                 mark_reg_known_zero(env, regs,
4850                                                     value_regno);
4851                                 if (type_may_be_null(reg_type))
4852                                         regs[value_regno].id = ++env->id_gen;
4853                                 /* A load of ctx field could have different
4854                                  * actual load size with the one encoded in the
4855                                  * insn. When the dst is PTR, it is for sure not
4856                                  * a sub-register.
4857                                  */
4858                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4859                                 if (base_type(reg_type) == PTR_TO_BTF_ID) {
4860                                         regs[value_regno].btf = btf;
4861                                         regs[value_regno].btf_id = btf_id;
4862                                 }
4863                         }
4864                         regs[value_regno].type = reg_type;
4865                 }
4866
4867         } else if (reg->type == PTR_TO_STACK) {
4868                 /* Basic bounds checks. */
4869                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4870                 if (err)
4871                         return err;
4872
4873                 state = func(env, reg);
4874                 err = update_stack_depth(env, state, off);
4875                 if (err)
4876                         return err;
4877
4878                 if (t == BPF_READ)
4879                         err = check_stack_read(env, regno, off, size,
4880                                                value_regno);
4881                 else
4882                         err = check_stack_write(env, regno, off, size,
4883                                                 value_regno, insn_idx);
4884         } else if (reg_is_pkt_pointer(reg)) {
4885                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4886                         verbose(env, "cannot write into packet\n");
4887                         return -EACCES;
4888                 }
4889                 if (t == BPF_WRITE && value_regno >= 0 &&
4890                     is_pointer_value(env, value_regno)) {
4891                         verbose(env, "R%d leaks addr into packet\n",
4892                                 value_regno);
4893                         return -EACCES;
4894                 }
4895                 err = check_packet_access(env, regno, off, size, false);
4896                 if (!err && t == BPF_READ && value_regno >= 0)
4897                         mark_reg_unknown(env, regs, value_regno);
4898         } else if (reg->type == PTR_TO_FLOW_KEYS) {
4899                 if (t == BPF_WRITE && value_regno >= 0 &&
4900                     is_pointer_value(env, value_regno)) {
4901                         verbose(env, "R%d leaks addr into flow keys\n",
4902                                 value_regno);
4903                         return -EACCES;
4904                 }
4905
4906                 err = check_flow_keys_access(env, off, size);
4907                 if (!err && t == BPF_READ && value_regno >= 0)
4908                         mark_reg_unknown(env, regs, value_regno);
4909         } else if (type_is_sk_pointer(reg->type)) {
4910                 if (t == BPF_WRITE) {
4911                         verbose(env, "R%d cannot write into %s\n",
4912                                 regno, reg_type_str(env, reg->type));
4913                         return -EACCES;
4914                 }
4915                 err = check_sock_access(env, insn_idx, regno, off, size, t);
4916                 if (!err && value_regno >= 0)
4917                         mark_reg_unknown(env, regs, value_regno);
4918         } else if (reg->type == PTR_TO_TP_BUFFER) {
4919                 err = check_tp_buffer_access(env, reg, regno, off, size);
4920                 if (!err && t == BPF_READ && value_regno >= 0)
4921                         mark_reg_unknown(env, regs, value_regno);
4922         } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
4923                    !type_may_be_null(reg->type)) {
4924                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4925                                               value_regno);
4926         } else if (reg->type == CONST_PTR_TO_MAP) {
4927                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4928                                               value_regno);
4929         } else if (base_type(reg->type) == PTR_TO_BUF) {
4930                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4931                 u32 *max_access;
4932
4933                 if (rdonly_mem) {
4934                         if (t == BPF_WRITE) {
4935                                 verbose(env, "R%d cannot write into %s\n",
4936                                         regno, reg_type_str(env, reg->type));
4937                                 return -EACCES;
4938                         }
4939                         max_access = &env->prog->aux->max_rdonly_access;
4940                 } else {
4941                         max_access = &env->prog->aux->max_rdwr_access;
4942                 }
4943
4944                 err = check_buffer_access(env, reg, regno, off, size, false,
4945                                           max_access);
4946
4947                 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4948                         mark_reg_unknown(env, regs, value_regno);
4949         } else {
4950                 verbose(env, "R%d invalid mem access '%s'\n", regno,
4951                         reg_type_str(env, reg->type));
4952                 return -EACCES;
4953         }
4954
4955         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4956             regs[value_regno].type == SCALAR_VALUE) {
4957                 /* b/h/w load zero-extends, mark upper bits as known 0 */
4958                 coerce_reg_to_size(&regs[value_regno], size);
4959         }
4960         return err;
4961 }
4962
4963 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4964 {
4965         int load_reg;
4966         int err;
4967
4968         switch (insn->imm) {
4969         case BPF_ADD:
4970         case BPF_ADD | BPF_FETCH:
4971         case BPF_AND:
4972         case BPF_AND | BPF_FETCH:
4973         case BPF_OR:
4974         case BPF_OR | BPF_FETCH:
4975         case BPF_XOR:
4976         case BPF_XOR | BPF_FETCH:
4977         case BPF_XCHG:
4978         case BPF_CMPXCHG:
4979                 break;
4980         default:
4981                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4982                 return -EINVAL;
4983         }
4984
4985         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4986                 verbose(env, "invalid atomic operand size\n");
4987                 return -EINVAL;
4988         }
4989
4990         /* check src1 operand */
4991         err = check_reg_arg(env, insn->src_reg, SRC_OP);
4992         if (err)
4993                 return err;
4994
4995         /* check src2 operand */
4996         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4997         if (err)
4998                 return err;
4999
5000         if (insn->imm == BPF_CMPXCHG) {
5001                 /* Check comparison of R0 with memory location */
5002                 const u32 aux_reg = BPF_REG_0;
5003
5004                 err = check_reg_arg(env, aux_reg, SRC_OP);
5005                 if (err)
5006                         return err;
5007
5008                 if (is_pointer_value(env, aux_reg)) {
5009                         verbose(env, "R%d leaks addr into mem\n", aux_reg);
5010                         return -EACCES;
5011                 }
5012         }
5013
5014         if (is_pointer_value(env, insn->src_reg)) {
5015                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5016                 return -EACCES;
5017         }
5018
5019         if (is_ctx_reg(env, insn->dst_reg) ||
5020             is_pkt_reg(env, insn->dst_reg) ||
5021             is_flow_key_reg(env, insn->dst_reg) ||
5022             is_sk_reg(env, insn->dst_reg)) {
5023                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5024                         insn->dst_reg,
5025                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5026                 return -EACCES;
5027         }
5028
5029         if (insn->imm & BPF_FETCH) {
5030                 if (insn->imm == BPF_CMPXCHG)
5031                         load_reg = BPF_REG_0;
5032                 else
5033                         load_reg = insn->src_reg;
5034
5035                 /* check and record load of old value */
5036                 err = check_reg_arg(env, load_reg, DST_OP);
5037                 if (err)
5038                         return err;
5039         } else {
5040                 /* This instruction accesses a memory location but doesn't
5041                  * actually load it into a register.
5042                  */
5043                 load_reg = -1;
5044         }
5045
5046         /* Check whether we can read the memory, with second call for fetch
5047          * case to simulate the register fill.
5048          */
5049         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5050                                BPF_SIZE(insn->code), BPF_READ, -1, true);
5051         if (!err && load_reg >= 0)
5052                 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5053                                        BPF_SIZE(insn->code), BPF_READ, load_reg,
5054                                        true);
5055         if (err)
5056                 return err;
5057
5058         /* Check whether we can write into the same memory. */
5059         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5060                                BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5061         if (err)
5062                 return err;
5063
5064         return 0;
5065 }
5066
5067 /* When register 'regno' is used to read the stack (either directly or through
5068  * a helper function) make sure that it's within stack boundary and, depending
5069  * on the access type, that all elements of the stack are initialized.
5070  *
5071  * 'off' includes 'regno->off', but not its dynamic part (if any).
5072  *
5073  * All registers that have been spilled on the stack in the slots within the
5074  * read offsets are marked as read.
5075  */
5076 static int check_stack_range_initialized(
5077                 struct bpf_verifier_env *env, int regno, int off,
5078                 int access_size, bool zero_size_allowed,
5079                 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5080 {
5081         struct bpf_reg_state *reg = reg_state(env, regno);
5082         struct bpf_func_state *state = func(env, reg);
5083         int err, min_off, max_off, i, j, slot, spi;
5084         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5085         enum bpf_access_type bounds_check_type;
5086         /* Some accesses can write anything into the stack, others are
5087          * read-only.
5088          */
5089         bool clobber = false;
5090
5091         if (access_size == 0 && !zero_size_allowed) {
5092                 verbose(env, "invalid zero-sized read\n");
5093                 return -EACCES;
5094         }
5095
5096         if (type == ACCESS_HELPER) {
5097                 /* The bounds checks for writes are more permissive than for
5098                  * reads. However, if raw_mode is not set, we'll do extra
5099                  * checks below.
5100                  */
5101                 bounds_check_type = BPF_WRITE;
5102                 clobber = true;
5103         } else {
5104                 bounds_check_type = BPF_READ;
5105         }
5106         err = check_stack_access_within_bounds(env, regno, off, access_size,
5107                                                type, bounds_check_type);
5108         if (err)
5109                 return err;
5110
5111
5112         if (tnum_is_const(reg->var_off)) {
5113                 min_off = max_off = reg->var_off.value + off;
5114         } else {
5115                 /* Variable offset is prohibited for unprivileged mode for
5116                  * simplicity since it requires corresponding support in
5117                  * Spectre masking for stack ALU.
5118                  * See also retrieve_ptr_limit().
5119                  */
5120                 if (!env->bypass_spec_v1) {
5121                         char tn_buf[48];
5122
5123                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5124                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5125                                 regno, err_extra, tn_buf);
5126                         return -EACCES;
5127                 }
5128                 /* Only initialized buffer on stack is allowed to be accessed
5129                  * with variable offset. With uninitialized buffer it's hard to
5130                  * guarantee that whole memory is marked as initialized on
5131                  * helper return since specific bounds are unknown what may
5132                  * cause uninitialized stack leaking.
5133                  */
5134                 if (meta && meta->raw_mode)
5135                         meta = NULL;
5136
5137                 min_off = reg->smin_value + off;
5138                 max_off = reg->smax_value + off;
5139         }
5140
5141         if (meta && meta->raw_mode) {
5142                 meta->access_size = access_size;
5143                 meta->regno = regno;
5144                 return 0;
5145         }
5146
5147         for (i = min_off; i < max_off + access_size; i++) {
5148                 u8 *stype;
5149
5150                 slot = -i - 1;
5151                 spi = slot / BPF_REG_SIZE;
5152                 if (state->allocated_stack <= slot)
5153                         goto err;
5154                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5155                 if (*stype == STACK_MISC)
5156                         goto mark;
5157                 if (*stype == STACK_ZERO) {
5158                         if (clobber) {
5159                                 /* helper can write anything into the stack */
5160                                 *stype = STACK_MISC;
5161                         }
5162                         goto mark;
5163                 }
5164
5165                 if (is_spilled_reg(&state->stack[spi]) &&
5166                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5167                      env->allow_ptr_leaks)) {
5168                         if (clobber) {
5169                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5170                                 for (j = 0; j < BPF_REG_SIZE; j++)
5171                                         scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5172                         }
5173                         goto mark;
5174                 }
5175
5176 err:
5177                 if (tnum_is_const(reg->var_off)) {
5178                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5179                                 err_extra, regno, min_off, i - min_off, access_size);
5180                 } else {
5181                         char tn_buf[48];
5182
5183                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5184                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5185                                 err_extra, regno, tn_buf, i - min_off, access_size);
5186                 }
5187                 return -EACCES;
5188 mark:
5189                 /* reading any byte out of 8-byte 'spill_slot' will cause
5190                  * the whole slot to be marked as 'read'
5191                  */
5192                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5193                               state->stack[spi].spilled_ptr.parent,
5194                               REG_LIVE_READ64);
5195                 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5196                  * be sure that whether stack slot is written to or not. Hence,
5197                  * we must still conservatively propagate reads upwards even if
5198                  * helper may write to the entire memory range.
5199                  */
5200         }
5201         return update_stack_depth(env, state, min_off);
5202 }
5203
5204 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5205                                    int access_size, bool zero_size_allowed,
5206                                    struct bpf_call_arg_meta *meta)
5207 {
5208         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5209         u32 *max_access;
5210
5211         switch (base_type(reg->type)) {
5212         case PTR_TO_PACKET:
5213         case PTR_TO_PACKET_META:
5214                 return check_packet_access(env, regno, reg->off, access_size,
5215                                            zero_size_allowed);
5216         case PTR_TO_MAP_KEY:
5217                 if (meta && meta->raw_mode) {
5218                         verbose(env, "R%d cannot write into %s\n", regno,
5219                                 reg_type_str(env, reg->type));
5220                         return -EACCES;
5221                 }
5222                 return check_mem_region_access(env, regno, reg->off, access_size,
5223                                                reg->map_ptr->key_size, false);
5224         case PTR_TO_MAP_VALUE:
5225                 if (check_map_access_type(env, regno, reg->off, access_size,
5226                                           meta && meta->raw_mode ? BPF_WRITE :
5227                                           BPF_READ))
5228                         return -EACCES;
5229                 return check_map_access(env, regno, reg->off, access_size,
5230                                         zero_size_allowed, ACCESS_HELPER);
5231         case PTR_TO_MEM:
5232                 if (type_is_rdonly_mem(reg->type)) {
5233                         if (meta && meta->raw_mode) {
5234                                 verbose(env, "R%d cannot write into %s\n", regno,
5235                                         reg_type_str(env, reg->type));
5236                                 return -EACCES;
5237                         }
5238                 }
5239                 return check_mem_region_access(env, regno, reg->off,
5240                                                access_size, reg->mem_size,
5241                                                zero_size_allowed);
5242         case PTR_TO_BUF:
5243                 if (type_is_rdonly_mem(reg->type)) {
5244                         if (meta && meta->raw_mode) {
5245                                 verbose(env, "R%d cannot write into %s\n", regno,
5246                                         reg_type_str(env, reg->type));
5247                                 return -EACCES;
5248                         }
5249
5250                         max_access = &env->prog->aux->max_rdonly_access;
5251                 } else {
5252                         max_access = &env->prog->aux->max_rdwr_access;
5253                 }
5254                 return check_buffer_access(env, reg, regno, reg->off,
5255                                            access_size, zero_size_allowed,
5256                                            max_access);
5257         case PTR_TO_STACK:
5258                 return check_stack_range_initialized(
5259                                 env,
5260                                 regno, reg->off, access_size,
5261                                 zero_size_allowed, ACCESS_HELPER, meta);
5262         case PTR_TO_CTX:
5263                 /* in case the function doesn't know how to access the context,
5264                  * (because we are in a program of type SYSCALL for example), we
5265                  * can not statically check its size.
5266                  * Dynamically check it now.
5267                  */
5268                 if (!env->ops->convert_ctx_access) {
5269                         enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5270                         int offset = access_size - 1;
5271
5272                         /* Allow zero-byte read from PTR_TO_CTX */
5273                         if (access_size == 0)
5274                                 return zero_size_allowed ? 0 : -EACCES;
5275
5276                         return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5277                                                 atype, -1, false);
5278                 }
5279
5280                 fallthrough;
5281         default: /* scalar_value or invalid ptr */
5282                 /* Allow zero-byte read from NULL, regardless of pointer type */
5283                 if (zero_size_allowed && access_size == 0 &&
5284                     register_is_null(reg))
5285                         return 0;
5286
5287                 verbose(env, "R%d type=%s ", regno,
5288                         reg_type_str(env, reg->type));
5289                 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5290                 return -EACCES;
5291         }
5292 }
5293
5294 static int check_mem_size_reg(struct bpf_verifier_env *env,
5295                               struct bpf_reg_state *reg, u32 regno,
5296                               bool zero_size_allowed,
5297                               struct bpf_call_arg_meta *meta)
5298 {
5299         int err;
5300
5301         /* This is used to refine r0 return value bounds for helpers
5302          * that enforce this value as an upper bound on return values.
5303          * See do_refine_retval_range() for helpers that can refine
5304          * the return value. C type of helper is u32 so we pull register
5305          * bound from umax_value however, if negative verifier errors
5306          * out. Only upper bounds can be learned because retval is an
5307          * int type and negative retvals are allowed.
5308          */
5309         meta->msize_max_value = reg->umax_value;
5310
5311         /* The register is SCALAR_VALUE; the access check
5312          * happens using its boundaries.
5313          */
5314         if (!tnum_is_const(reg->var_off))
5315                 /* For unprivileged variable accesses, disable raw
5316                  * mode so that the program is required to
5317                  * initialize all the memory that the helper could
5318                  * just partially fill up.
5319                  */
5320                 meta = NULL;
5321
5322         if (reg->smin_value < 0) {
5323                 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5324                         regno);
5325                 return -EACCES;
5326         }
5327
5328         if (reg->umin_value == 0) {
5329                 err = check_helper_mem_access(env, regno - 1, 0,
5330                                               zero_size_allowed,
5331                                               meta);
5332                 if (err)
5333                         return err;
5334         }
5335
5336         if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5337                 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5338                         regno);
5339                 return -EACCES;
5340         }
5341         err = check_helper_mem_access(env, regno - 1,
5342                                       reg->umax_value,
5343                                       zero_size_allowed, meta);
5344         if (!err)
5345                 err = mark_chain_precision(env, regno);
5346         return err;
5347 }
5348
5349 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5350                    u32 regno, u32 mem_size)
5351 {
5352         bool may_be_null = type_may_be_null(reg->type);
5353         struct bpf_reg_state saved_reg;
5354         struct bpf_call_arg_meta meta;
5355         int err;
5356
5357         if (register_is_null(reg))
5358                 return 0;
5359
5360         memset(&meta, 0, sizeof(meta));
5361         /* Assuming that the register contains a value check if the memory
5362          * access is safe. Temporarily save and restore the register's state as
5363          * the conversion shouldn't be visible to a caller.
5364          */
5365         if (may_be_null) {
5366                 saved_reg = *reg;
5367                 mark_ptr_not_null_reg(reg);
5368         }
5369
5370         err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5371         /* Check access for BPF_WRITE */
5372         meta.raw_mode = true;
5373         err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5374
5375         if (may_be_null)
5376                 *reg = saved_reg;
5377
5378         return err;
5379 }
5380
5381 int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5382                              u32 regno)
5383 {
5384         struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5385         bool may_be_null = type_may_be_null(mem_reg->type);
5386         struct bpf_reg_state saved_reg;
5387         struct bpf_call_arg_meta meta;
5388         int err;
5389
5390         WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5391
5392         memset(&meta, 0, sizeof(meta));
5393
5394         if (may_be_null) {
5395                 saved_reg = *mem_reg;
5396                 mark_ptr_not_null_reg(mem_reg);
5397         }
5398
5399         err = check_mem_size_reg(env, reg, regno, true, &meta);
5400         /* Check access for BPF_WRITE */
5401         meta.raw_mode = true;
5402         err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5403
5404         if (may_be_null)
5405                 *mem_reg = saved_reg;
5406         return err;
5407 }
5408
5409 /* Implementation details:
5410  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
5411  * Two bpf_map_lookups (even with the same key) will have different reg->id.
5412  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
5413  * value_or_null->value transition, since the verifier only cares about
5414  * the range of access to valid map value pointer and doesn't care about actual
5415  * address of the map element.
5416  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5417  * reg->id > 0 after value_or_null->value transition. By doing so
5418  * two bpf_map_lookups will be considered two different pointers that
5419  * point to different bpf_spin_locks.
5420  * The verifier allows taking only one bpf_spin_lock at a time to avoid
5421  * dead-locks.
5422  * Since only one bpf_spin_lock is allowed the checks are simpler than
5423  * reg_is_refcounted() logic. The verifier needs to remember only
5424  * one spin_lock instead of array of acquired_refs.
5425  * cur_state->active_spin_lock remembers which map value element got locked
5426  * and clears it after bpf_spin_unlock.
5427  */
5428 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5429                              bool is_lock)
5430 {
5431         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5432         struct bpf_verifier_state *cur = env->cur_state;
5433         bool is_const = tnum_is_const(reg->var_off);
5434         struct bpf_map *map = reg->map_ptr;
5435         u64 val = reg->var_off.value;
5436
5437         if (!is_const) {
5438                 verbose(env,
5439                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5440                         regno);
5441                 return -EINVAL;
5442         }
5443         if (!map->btf) {
5444                 verbose(env,
5445                         "map '%s' has to have BTF in order to use bpf_spin_lock\n",
5446                         map->name);
5447                 return -EINVAL;
5448         }
5449         if (!map_value_has_spin_lock(map)) {
5450                 if (map->spin_lock_off == -E2BIG)
5451                         verbose(env,
5452                                 "map '%s' has more than one 'struct bpf_spin_lock'\n",
5453                                 map->name);
5454                 else if (map->spin_lock_off == -ENOENT)
5455                         verbose(env,
5456                                 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
5457                                 map->name);
5458                 else
5459                         verbose(env,
5460                                 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
5461                                 map->name);
5462                 return -EINVAL;
5463         }
5464         if (map->spin_lock_off != val + reg->off) {
5465                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
5466                         val + reg->off);
5467                 return -EINVAL;
5468         }
5469         if (is_lock) {
5470                 if (cur->active_spin_lock) {
5471                         verbose(env,
5472                                 "Locking two bpf_spin_locks are not allowed\n");
5473                         return -EINVAL;
5474                 }
5475                 cur->active_spin_lock = reg->id;
5476         } else {
5477                 if (!cur->active_spin_lock) {
5478                         verbose(env, "bpf_spin_unlock without taking a lock\n");
5479                         return -EINVAL;
5480                 }
5481                 if (cur->active_spin_lock != reg->id) {
5482                         verbose(env, "bpf_spin_unlock of different lock\n");
5483                         return -EINVAL;
5484                 }
5485                 cur->active_spin_lock = 0;
5486         }
5487         return 0;
5488 }
5489
5490 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5491                               struct bpf_call_arg_meta *meta)
5492 {
5493         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5494         bool is_const = tnum_is_const(reg->var_off);
5495         struct bpf_map *map = reg->map_ptr;
5496         u64 val = reg->var_off.value;
5497
5498         if (!is_const) {
5499                 verbose(env,
5500                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5501                         regno);
5502                 return -EINVAL;
5503         }
5504         if (!map->btf) {
5505                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5506                         map->name);
5507                 return -EINVAL;
5508         }
5509         if (!map_value_has_timer(map)) {
5510                 if (map->timer_off == -E2BIG)
5511                         verbose(env,
5512                                 "map '%s' has more than one 'struct bpf_timer'\n",
5513                                 map->name);
5514                 else if (map->timer_off == -ENOENT)
5515                         verbose(env,
5516                                 "map '%s' doesn't have 'struct bpf_timer'\n",
5517                                 map->name);
5518                 else
5519                         verbose(env,
5520                                 "map '%s' is not a struct type or bpf_timer is mangled\n",
5521                                 map->name);
5522                 return -EINVAL;
5523         }
5524         if (map->timer_off != val + reg->off) {
5525                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5526                         val + reg->off, map->timer_off);
5527                 return -EINVAL;
5528         }
5529         if (meta->map_ptr) {
5530                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5531                 return -EFAULT;
5532         }
5533         meta->map_uid = reg->map_uid;
5534         meta->map_ptr = map;
5535         return 0;
5536 }
5537
5538 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5539                              struct bpf_call_arg_meta *meta)
5540 {
5541         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5542         struct bpf_map_value_off_desc *off_desc;
5543         struct bpf_map *map_ptr = reg->map_ptr;
5544         u32 kptr_off;
5545         int ret;
5546
5547         if (!tnum_is_const(reg->var_off)) {
5548                 verbose(env,
5549                         "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5550                         regno);
5551                 return -EINVAL;
5552         }
5553         if (!map_ptr->btf) {
5554                 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5555                         map_ptr->name);
5556                 return -EINVAL;
5557         }
5558         if (!map_value_has_kptrs(map_ptr)) {
5559                 ret = PTR_ERR_OR_ZERO(map_ptr->kptr_off_tab);
5560                 if (ret == -E2BIG)
5561                         verbose(env, "map '%s' has more than %d kptr\n", map_ptr->name,
5562                                 BPF_MAP_VALUE_OFF_MAX);
5563                 else if (ret == -EEXIST)
5564                         verbose(env, "map '%s' has repeating kptr BTF tags\n", map_ptr->name);
5565                 else
5566                         verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5567                 return -EINVAL;
5568         }
5569
5570         meta->map_ptr = map_ptr;
5571         kptr_off = reg->off + reg->var_off.value;
5572         off_desc = bpf_map_kptr_off_contains(map_ptr, kptr_off);
5573         if (!off_desc) {
5574                 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5575                 return -EACCES;
5576         }
5577         if (off_desc->type != BPF_KPTR_REF) {
5578                 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5579                 return -EACCES;
5580         }
5581         meta->kptr_off_desc = off_desc;
5582         return 0;
5583 }
5584
5585 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5586 {
5587         return type == ARG_CONST_SIZE ||
5588                type == ARG_CONST_SIZE_OR_ZERO;
5589 }
5590
5591 static bool arg_type_is_release(enum bpf_arg_type type)
5592 {
5593         return type & OBJ_RELEASE;
5594 }
5595
5596 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5597 {
5598         return base_type(type) == ARG_PTR_TO_DYNPTR;
5599 }
5600
5601 static int int_ptr_type_to_size(enum bpf_arg_type type)
5602 {
5603         if (type == ARG_PTR_TO_INT)
5604                 return sizeof(u32);
5605         else if (type == ARG_PTR_TO_LONG)
5606                 return sizeof(u64);
5607
5608         return -EINVAL;
5609 }
5610
5611 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5612                                  const struct bpf_call_arg_meta *meta,
5613                                  enum bpf_arg_type *arg_type)
5614 {
5615         if (!meta->map_ptr) {
5616                 /* kernel subsystem misconfigured verifier */
5617                 verbose(env, "invalid map_ptr to access map->type\n");
5618                 return -EACCES;
5619         }
5620
5621         switch (meta->map_ptr->map_type) {
5622         case BPF_MAP_TYPE_SOCKMAP:
5623         case BPF_MAP_TYPE_SOCKHASH:
5624                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5625                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5626                 } else {
5627                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
5628                         return -EINVAL;
5629                 }
5630                 break;
5631         case BPF_MAP_TYPE_BLOOM_FILTER:
5632                 if (meta->func_id == BPF_FUNC_map_peek_elem)
5633                         *arg_type = ARG_PTR_TO_MAP_VALUE;
5634                 break;
5635         default:
5636                 break;
5637         }
5638         return 0;
5639 }
5640
5641 struct bpf_reg_types {
5642         const enum bpf_reg_type types[10];
5643         u32 *btf_id;
5644 };
5645
5646 static const struct bpf_reg_types map_key_value_types = {
5647         .types = {
5648                 PTR_TO_STACK,
5649                 PTR_TO_PACKET,
5650                 PTR_TO_PACKET_META,
5651                 PTR_TO_MAP_KEY,
5652                 PTR_TO_MAP_VALUE,
5653         },
5654 };
5655
5656 static const struct bpf_reg_types sock_types = {
5657         .types = {
5658                 PTR_TO_SOCK_COMMON,
5659                 PTR_TO_SOCKET,
5660                 PTR_TO_TCP_SOCK,
5661                 PTR_TO_XDP_SOCK,
5662         },
5663 };
5664
5665 #ifdef CONFIG_NET
5666 static const struct bpf_reg_types btf_id_sock_common_types = {
5667         .types = {
5668                 PTR_TO_SOCK_COMMON,
5669                 PTR_TO_SOCKET,
5670                 PTR_TO_TCP_SOCK,
5671                 PTR_TO_XDP_SOCK,
5672                 PTR_TO_BTF_ID,
5673         },
5674         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5675 };
5676 #endif
5677
5678 static const struct bpf_reg_types mem_types = {
5679         .types = {
5680                 PTR_TO_STACK,
5681                 PTR_TO_PACKET,
5682                 PTR_TO_PACKET_META,
5683                 PTR_TO_MAP_KEY,
5684                 PTR_TO_MAP_VALUE,
5685                 PTR_TO_MEM,
5686                 PTR_TO_MEM | MEM_ALLOC,
5687                 PTR_TO_BUF,
5688         },
5689 };
5690
5691 static const struct bpf_reg_types int_ptr_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 fullsock_types = { .types = { PTR_TO_SOCKET } };
5702 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5703 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5704 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
5705 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5706 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5707 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5708 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_BTF_ID | MEM_PERCPU } };
5709 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5710 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5711 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5712 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5713 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5714 static const struct bpf_reg_types dynptr_types = {
5715         .types = {
5716                 PTR_TO_STACK,
5717                 PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL,
5718         }
5719 };
5720
5721 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5722         [ARG_PTR_TO_MAP_KEY]            = &map_key_value_types,
5723         [ARG_PTR_TO_MAP_VALUE]          = &map_key_value_types,
5724         [ARG_CONST_SIZE]                = &scalar_types,
5725         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
5726         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
5727         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
5728         [ARG_PTR_TO_CTX]                = &context_types,
5729         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
5730 #ifdef CONFIG_NET
5731         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
5732 #endif
5733         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
5734         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
5735         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
5736         [ARG_PTR_TO_MEM]                = &mem_types,
5737         [ARG_PTR_TO_ALLOC_MEM]          = &alloc_mem_types,
5738         [ARG_PTR_TO_INT]                = &int_ptr_types,
5739         [ARG_PTR_TO_LONG]               = &int_ptr_types,
5740         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
5741         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
5742         [ARG_PTR_TO_STACK]              = &stack_ptr_types,
5743         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
5744         [ARG_PTR_TO_TIMER]              = &timer_types,
5745         [ARG_PTR_TO_KPTR]               = &kptr_types,
5746         [ARG_PTR_TO_DYNPTR]             = &dynptr_types,
5747 };
5748
5749 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5750                           enum bpf_arg_type arg_type,
5751                           const u32 *arg_btf_id,
5752                           struct bpf_call_arg_meta *meta)
5753 {
5754         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5755         enum bpf_reg_type expected, type = reg->type;
5756         const struct bpf_reg_types *compatible;
5757         int i, j;
5758
5759         compatible = compatible_reg_types[base_type(arg_type)];
5760         if (!compatible) {
5761                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5762                 return -EFAULT;
5763         }
5764
5765         /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5766          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5767          *
5768          * Same for MAYBE_NULL:
5769          *
5770          * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5771          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5772          *
5773          * Therefore we fold these flags depending on the arg_type before comparison.
5774          */
5775         if (arg_type & MEM_RDONLY)
5776                 type &= ~MEM_RDONLY;
5777         if (arg_type & PTR_MAYBE_NULL)
5778                 type &= ~PTR_MAYBE_NULL;
5779
5780         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5781                 expected = compatible->types[i];
5782                 if (expected == NOT_INIT)
5783                         break;
5784
5785                 if (type == expected)
5786                         goto found;
5787         }
5788
5789         verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5790         for (j = 0; j + 1 < i; j++)
5791                 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5792         verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5793         return -EACCES;
5794
5795 found:
5796         if (reg->type == PTR_TO_BTF_ID) {
5797                 /* For bpf_sk_release, it needs to match against first member
5798                  * 'struct sock_common', hence make an exception for it. This
5799                  * allows bpf_sk_release to work for multiple socket types.
5800                  */
5801                 bool strict_type_match = arg_type_is_release(arg_type) &&
5802                                          meta->func_id != BPF_FUNC_sk_release;
5803
5804                 if (!arg_btf_id) {
5805                         if (!compatible->btf_id) {
5806                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5807                                 return -EFAULT;
5808                         }
5809                         arg_btf_id = compatible->btf_id;
5810                 }
5811
5812                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
5813                         if (map_kptr_match_type(env, meta->kptr_off_desc, reg, regno))
5814                                 return -EACCES;
5815                 } else {
5816                         if (arg_btf_id == BPF_PTR_POISON) {
5817                                 verbose(env, "verifier internal error:");
5818                                 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
5819                                         regno);
5820                                 return -EACCES;
5821                         }
5822
5823                         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5824                                                   btf_vmlinux, *arg_btf_id,
5825                                                   strict_type_match)) {
5826                                 verbose(env, "R%d is of type %s but %s is expected\n",
5827                                         regno, kernel_type_name(reg->btf, reg->btf_id),
5828                                         kernel_type_name(btf_vmlinux, *arg_btf_id));
5829                                 return -EACCES;
5830                         }
5831                 }
5832         }
5833
5834         return 0;
5835 }
5836
5837 int check_func_arg_reg_off(struct bpf_verifier_env *env,
5838                            const struct bpf_reg_state *reg, int regno,
5839                            enum bpf_arg_type arg_type)
5840 {
5841         enum bpf_reg_type type = reg->type;
5842         bool fixed_off_ok = false;
5843
5844         switch ((u32)type) {
5845         /* Pointer types where reg offset is explicitly allowed: */
5846         case PTR_TO_STACK:
5847                 if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
5848                         verbose(env, "cannot pass in dynptr at an offset\n");
5849                         return -EINVAL;
5850                 }
5851                 fallthrough;
5852         case PTR_TO_PACKET:
5853         case PTR_TO_PACKET_META:
5854         case PTR_TO_MAP_KEY:
5855         case PTR_TO_MAP_VALUE:
5856         case PTR_TO_MEM:
5857         case PTR_TO_MEM | MEM_RDONLY:
5858         case PTR_TO_MEM | MEM_ALLOC:
5859         case PTR_TO_BUF:
5860         case PTR_TO_BUF | MEM_RDONLY:
5861         case SCALAR_VALUE:
5862                 /* Some of the argument types nevertheless require a
5863                  * zero register offset.
5864                  */
5865                 if (base_type(arg_type) != ARG_PTR_TO_ALLOC_MEM)
5866                         return 0;
5867                 break;
5868         /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
5869          * fixed offset.
5870          */
5871         case PTR_TO_BTF_ID:
5872                 /* When referenced PTR_TO_BTF_ID is passed to release function,
5873                  * it's fixed offset must be 0. In the other cases, fixed offset
5874                  * can be non-zero.
5875                  */
5876                 if (arg_type_is_release(arg_type) && reg->off) {
5877                         verbose(env, "R%d must have zero offset when passed to release func\n",
5878                                 regno);
5879                         return -EINVAL;
5880                 }
5881                 /* For arg is release pointer, fixed_off_ok must be false, but
5882                  * we already checked and rejected reg->off != 0 above, so set
5883                  * to true to allow fixed offset for all other cases.
5884                  */
5885                 fixed_off_ok = true;
5886                 break;
5887         default:
5888                 break;
5889         }
5890         return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
5891 }
5892
5893 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
5894 {
5895         struct bpf_func_state *state = func(env, reg);
5896         int spi = get_spi(reg->off);
5897
5898         return state->stack[spi].spilled_ptr.id;
5899 }
5900
5901 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5902                           struct bpf_call_arg_meta *meta,
5903                           const struct bpf_func_proto *fn)
5904 {
5905         u32 regno = BPF_REG_1 + arg;
5906         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5907         enum bpf_arg_type arg_type = fn->arg_type[arg];
5908         enum bpf_reg_type type = reg->type;
5909         u32 *arg_btf_id = NULL;
5910         int err = 0;
5911
5912         if (arg_type == ARG_DONTCARE)
5913                 return 0;
5914
5915         err = check_reg_arg(env, regno, SRC_OP);
5916         if (err)
5917                 return err;
5918
5919         if (arg_type == ARG_ANYTHING) {
5920                 if (is_pointer_value(env, regno)) {
5921                         verbose(env, "R%d leaks addr into helper function\n",
5922                                 regno);
5923                         return -EACCES;
5924                 }
5925                 return 0;
5926         }
5927
5928         if (type_is_pkt_pointer(type) &&
5929             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5930                 verbose(env, "helper access to the packet is not allowed\n");
5931                 return -EACCES;
5932         }
5933
5934         if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
5935                 err = resolve_map_arg_type(env, meta, &arg_type);
5936                 if (err)
5937                         return err;
5938         }
5939
5940         if (register_is_null(reg) && type_may_be_null(arg_type))
5941                 /* A NULL register has a SCALAR_VALUE type, so skip
5942                  * type checking.
5943                  */
5944                 goto skip_type_check;
5945
5946         /* arg_btf_id and arg_size are in a union. */
5947         if (base_type(arg_type) == ARG_PTR_TO_BTF_ID)
5948                 arg_btf_id = fn->arg_btf_id[arg];
5949
5950         err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
5951         if (err)
5952                 return err;
5953
5954         err = check_func_arg_reg_off(env, reg, regno, arg_type);
5955         if (err)
5956                 return err;
5957
5958 skip_type_check:
5959         if (arg_type_is_release(arg_type)) {
5960                 if (arg_type_is_dynptr(arg_type)) {
5961                         struct bpf_func_state *state = func(env, reg);
5962                         int spi = get_spi(reg->off);
5963
5964                         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
5965                             !state->stack[spi].spilled_ptr.id) {
5966                                 verbose(env, "arg %d is an unacquired reference\n", regno);
5967                                 return -EINVAL;
5968                         }
5969                 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
5970                         verbose(env, "R%d must be referenced when passed to release function\n",
5971                                 regno);
5972                         return -EINVAL;
5973                 }
5974                 if (meta->release_regno) {
5975                         verbose(env, "verifier internal error: more than one release argument\n");
5976                         return -EFAULT;
5977                 }
5978                 meta->release_regno = regno;
5979         }
5980
5981         if (reg->ref_obj_id) {
5982                 if (meta->ref_obj_id) {
5983                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5984                                 regno, reg->ref_obj_id,
5985                                 meta->ref_obj_id);
5986                         return -EFAULT;
5987                 }
5988                 meta->ref_obj_id = reg->ref_obj_id;
5989         }
5990
5991         switch (base_type(arg_type)) {
5992         case ARG_CONST_MAP_PTR:
5993                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
5994                 if (meta->map_ptr) {
5995                         /* Use map_uid (which is unique id of inner map) to reject:
5996                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5997                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5998                          * if (inner_map1 && inner_map2) {
5999                          *     timer = bpf_map_lookup_elem(inner_map1);
6000                          *     if (timer)
6001                          *         // mismatch would have been allowed
6002                          *         bpf_timer_init(timer, inner_map2);
6003                          * }
6004                          *
6005                          * Comparing map_ptr is enough to distinguish normal and outer maps.
6006                          */
6007                         if (meta->map_ptr != reg->map_ptr ||
6008                             meta->map_uid != reg->map_uid) {
6009                                 verbose(env,
6010                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6011                                         meta->map_uid, reg->map_uid);
6012                                 return -EINVAL;
6013                         }
6014                 }
6015                 meta->map_ptr = reg->map_ptr;
6016                 meta->map_uid = reg->map_uid;
6017                 break;
6018         case ARG_PTR_TO_MAP_KEY:
6019                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
6020                  * check that [key, key + map->key_size) are within
6021                  * stack limits and initialized
6022                  */
6023                 if (!meta->map_ptr) {
6024                         /* in function declaration map_ptr must come before
6025                          * map_key, so that it's verified and known before
6026                          * we have to check map_key here. Otherwise it means
6027                          * that kernel subsystem misconfigured verifier
6028                          */
6029                         verbose(env, "invalid map_ptr to access map->key\n");
6030                         return -EACCES;
6031                 }
6032                 err = check_helper_mem_access(env, regno,
6033                                               meta->map_ptr->key_size, false,
6034                                               NULL);
6035                 break;
6036         case ARG_PTR_TO_MAP_VALUE:
6037                 if (type_may_be_null(arg_type) && register_is_null(reg))
6038                         return 0;
6039
6040                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
6041                  * check [value, value + map->value_size) validity
6042                  */
6043                 if (!meta->map_ptr) {
6044                         /* kernel subsystem misconfigured verifier */
6045                         verbose(env, "invalid map_ptr to access map->value\n");
6046                         return -EACCES;
6047                 }
6048                 meta->raw_mode = arg_type & MEM_UNINIT;
6049                 err = check_helper_mem_access(env, regno,
6050                                               meta->map_ptr->value_size, false,
6051                                               meta);
6052                 break;
6053         case ARG_PTR_TO_PERCPU_BTF_ID:
6054                 if (!reg->btf_id) {
6055                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6056                         return -EACCES;
6057                 }
6058                 meta->ret_btf = reg->btf;
6059                 meta->ret_btf_id = reg->btf_id;
6060                 break;
6061         case ARG_PTR_TO_SPIN_LOCK:
6062                 if (meta->func_id == BPF_FUNC_spin_lock) {
6063                         if (process_spin_lock(env, regno, true))
6064                                 return -EACCES;
6065                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
6066                         if (process_spin_lock(env, regno, false))
6067                                 return -EACCES;
6068                 } else {
6069                         verbose(env, "verifier internal error\n");
6070                         return -EFAULT;
6071                 }
6072                 break;
6073         case ARG_PTR_TO_TIMER:
6074                 if (process_timer_func(env, regno, meta))
6075                         return -EACCES;
6076                 break;
6077         case ARG_PTR_TO_FUNC:
6078                 meta->subprogno = reg->subprogno;
6079                 break;
6080         case ARG_PTR_TO_MEM:
6081                 /* The access to this pointer is only checked when we hit the
6082                  * next is_mem_size argument below.
6083                  */
6084                 meta->raw_mode = arg_type & MEM_UNINIT;
6085                 if (arg_type & MEM_FIXED_SIZE) {
6086                         err = check_helper_mem_access(env, regno,
6087                                                       fn->arg_size[arg], false,
6088                                                       meta);
6089                 }
6090                 break;
6091         case ARG_CONST_SIZE:
6092                 err = check_mem_size_reg(env, reg, regno, false, meta);
6093                 break;
6094         case ARG_CONST_SIZE_OR_ZERO:
6095                 err = check_mem_size_reg(env, reg, regno, true, meta);
6096                 break;
6097         case ARG_PTR_TO_DYNPTR:
6098                 /* We only need to check for initialized / uninitialized helper
6099                  * dynptr args if the dynptr is not PTR_TO_DYNPTR, as the
6100                  * assumption is that if it is, that a helper function
6101                  * initialized the dynptr on behalf of the BPF program.
6102                  */
6103                 if (base_type(reg->type) == PTR_TO_DYNPTR)
6104                         break;
6105                 if (arg_type & MEM_UNINIT) {
6106                         if (!is_dynptr_reg_valid_uninit(env, reg)) {
6107                                 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6108                                 return -EINVAL;
6109                         }
6110
6111                         /* We only support one dynptr being uninitialized at the moment,
6112                          * which is sufficient for the helper functions we have right now.
6113                          */
6114                         if (meta->uninit_dynptr_regno) {
6115                                 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6116                                 return -EFAULT;
6117                         }
6118
6119                         meta->uninit_dynptr_regno = regno;
6120                 } else if (!is_dynptr_reg_valid_init(env, reg)) {
6121                         verbose(env,
6122                                 "Expected an initialized dynptr as arg #%d\n",
6123                                 arg + 1);
6124                         return -EINVAL;
6125                 } else if (!is_dynptr_type_expected(env, reg, arg_type)) {
6126                         const char *err_extra = "";
6127
6128                         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6129                         case DYNPTR_TYPE_LOCAL:
6130                                 err_extra = "local";
6131                                 break;
6132                         case DYNPTR_TYPE_RINGBUF:
6133                                 err_extra = "ringbuf";
6134                                 break;
6135                         default:
6136                                 err_extra = "<unknown>";
6137                                 break;
6138                         }
6139                         verbose(env,
6140                                 "Expected a dynptr of type %s as arg #%d\n",
6141                                 err_extra, arg + 1);
6142                         return -EINVAL;
6143                 }
6144                 break;
6145         case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6146                 if (!tnum_is_const(reg->var_off)) {
6147                         verbose(env, "R%d is not a known constant'\n",
6148                                 regno);
6149                         return -EACCES;
6150                 }
6151                 meta->mem_size = reg->var_off.value;
6152                 err = mark_chain_precision(env, regno);
6153                 if (err)
6154                         return err;
6155                 break;
6156         case ARG_PTR_TO_INT:
6157         case ARG_PTR_TO_LONG:
6158         {
6159                 int size = int_ptr_type_to_size(arg_type);
6160
6161                 err = check_helper_mem_access(env, regno, size, false, meta);
6162                 if (err)
6163                         return err;
6164                 err = check_ptr_alignment(env, reg, 0, size, true);
6165                 break;
6166         }
6167         case ARG_PTR_TO_CONST_STR:
6168         {
6169                 struct bpf_map *map = reg->map_ptr;
6170                 int map_off;
6171                 u64 map_addr;
6172                 char *str_ptr;
6173
6174                 if (!bpf_map_is_rdonly(map)) {
6175                         verbose(env, "R%d does not point to a readonly map'\n", regno);
6176                         return -EACCES;
6177                 }
6178
6179                 if (!tnum_is_const(reg->var_off)) {
6180                         verbose(env, "R%d is not a constant address'\n", regno);
6181                         return -EACCES;
6182                 }
6183
6184                 if (!map->ops->map_direct_value_addr) {
6185                         verbose(env, "no direct value access support for this map type\n");
6186                         return -EACCES;
6187                 }
6188
6189                 err = check_map_access(env, regno, reg->off,
6190                                        map->value_size - reg->off, false,
6191                                        ACCESS_HELPER);
6192                 if (err)
6193                         return err;
6194
6195                 map_off = reg->off + reg->var_off.value;
6196                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6197                 if (err) {
6198                         verbose(env, "direct value access on string failed\n");
6199                         return err;
6200                 }
6201
6202                 str_ptr = (char *)(long)(map_addr);
6203                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6204                         verbose(env, "string is not zero-terminated\n");
6205                         return -EINVAL;
6206                 }
6207                 break;
6208         }
6209         case ARG_PTR_TO_KPTR:
6210                 if (process_kptr_func(env, regno, meta))
6211                         return -EACCES;
6212                 break;
6213         }
6214
6215         return err;
6216 }
6217
6218 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6219 {
6220         enum bpf_attach_type eatype = env->prog->expected_attach_type;
6221         enum bpf_prog_type type = resolve_prog_type(env->prog);
6222
6223         if (func_id != BPF_FUNC_map_update_elem)
6224                 return false;
6225
6226         /* It's not possible to get access to a locked struct sock in these
6227          * contexts, so updating is safe.
6228          */
6229         switch (type) {
6230         case BPF_PROG_TYPE_TRACING:
6231                 if (eatype == BPF_TRACE_ITER)
6232                         return true;
6233                 break;
6234         case BPF_PROG_TYPE_SOCKET_FILTER:
6235         case BPF_PROG_TYPE_SCHED_CLS:
6236         case BPF_PROG_TYPE_SCHED_ACT:
6237         case BPF_PROG_TYPE_XDP:
6238         case BPF_PROG_TYPE_SK_REUSEPORT:
6239         case BPF_PROG_TYPE_FLOW_DISSECTOR:
6240         case BPF_PROG_TYPE_SK_LOOKUP:
6241                 return true;
6242         default:
6243                 break;
6244         }
6245
6246         verbose(env, "cannot update sockmap in this context\n");
6247         return false;
6248 }
6249
6250 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6251 {
6252         return env->prog->jit_requested &&
6253                bpf_jit_supports_subprog_tailcalls();
6254 }
6255
6256 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6257                                         struct bpf_map *map, int func_id)
6258 {
6259         if (!map)
6260                 return 0;
6261
6262         /* We need a two way check, first is from map perspective ... */
6263         switch (map->map_type) {
6264         case BPF_MAP_TYPE_PROG_ARRAY:
6265                 if (func_id != BPF_FUNC_tail_call)
6266                         goto error;
6267                 break;
6268         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6269                 if (func_id != BPF_FUNC_perf_event_read &&
6270                     func_id != BPF_FUNC_perf_event_output &&
6271                     func_id != BPF_FUNC_skb_output &&
6272                     func_id != BPF_FUNC_perf_event_read_value &&
6273                     func_id != BPF_FUNC_xdp_output)
6274                         goto error;
6275                 break;
6276         case BPF_MAP_TYPE_RINGBUF:
6277                 if (func_id != BPF_FUNC_ringbuf_output &&
6278                     func_id != BPF_FUNC_ringbuf_reserve &&
6279                     func_id != BPF_FUNC_ringbuf_query &&
6280                     func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6281                     func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6282                     func_id != BPF_FUNC_ringbuf_discard_dynptr)
6283                         goto error;
6284                 break;
6285         case BPF_MAP_TYPE_USER_RINGBUF:
6286                 if (func_id != BPF_FUNC_user_ringbuf_drain)
6287                         goto error;
6288                 break;
6289         case BPF_MAP_TYPE_STACK_TRACE:
6290                 if (func_id != BPF_FUNC_get_stackid)
6291                         goto error;
6292                 break;
6293         case BPF_MAP_TYPE_CGROUP_ARRAY:
6294                 if (func_id != BPF_FUNC_skb_under_cgroup &&
6295                     func_id != BPF_FUNC_current_task_under_cgroup)
6296                         goto error;
6297                 break;
6298         case BPF_MAP_TYPE_CGROUP_STORAGE:
6299         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6300                 if (func_id != BPF_FUNC_get_local_storage)
6301                         goto error;
6302                 break;
6303         case BPF_MAP_TYPE_DEVMAP:
6304         case BPF_MAP_TYPE_DEVMAP_HASH:
6305                 if (func_id != BPF_FUNC_redirect_map &&
6306                     func_id != BPF_FUNC_map_lookup_elem)
6307                         goto error;
6308                 break;
6309         /* Restrict bpf side of cpumap and xskmap, open when use-cases
6310          * appear.
6311          */
6312         case BPF_MAP_TYPE_CPUMAP:
6313                 if (func_id != BPF_FUNC_redirect_map)
6314                         goto error;
6315                 break;
6316         case BPF_MAP_TYPE_XSKMAP:
6317                 if (func_id != BPF_FUNC_redirect_map &&
6318                     func_id != BPF_FUNC_map_lookup_elem)
6319                         goto error;
6320                 break;
6321         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6322         case BPF_MAP_TYPE_HASH_OF_MAPS:
6323                 if (func_id != BPF_FUNC_map_lookup_elem)
6324                         goto error;
6325                 break;
6326         case BPF_MAP_TYPE_SOCKMAP:
6327                 if (func_id != BPF_FUNC_sk_redirect_map &&
6328                     func_id != BPF_FUNC_sock_map_update &&
6329                     func_id != BPF_FUNC_map_delete_elem &&
6330                     func_id != BPF_FUNC_msg_redirect_map &&
6331                     func_id != BPF_FUNC_sk_select_reuseport &&
6332                     func_id != BPF_FUNC_map_lookup_elem &&
6333                     !may_update_sockmap(env, func_id))
6334                         goto error;
6335                 break;
6336         case BPF_MAP_TYPE_SOCKHASH:
6337                 if (func_id != BPF_FUNC_sk_redirect_hash &&
6338                     func_id != BPF_FUNC_sock_hash_update &&
6339                     func_id != BPF_FUNC_map_delete_elem &&
6340                     func_id != BPF_FUNC_msg_redirect_hash &&
6341                     func_id != BPF_FUNC_sk_select_reuseport &&
6342                     func_id != BPF_FUNC_map_lookup_elem &&
6343                     !may_update_sockmap(env, func_id))
6344                         goto error;
6345                 break;
6346         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6347                 if (func_id != BPF_FUNC_sk_select_reuseport)
6348                         goto error;
6349                 break;
6350         case BPF_MAP_TYPE_QUEUE:
6351         case BPF_MAP_TYPE_STACK:
6352                 if (func_id != BPF_FUNC_map_peek_elem &&
6353                     func_id != BPF_FUNC_map_pop_elem &&
6354                     func_id != BPF_FUNC_map_push_elem)
6355                         goto error;
6356                 break;
6357         case BPF_MAP_TYPE_SK_STORAGE:
6358                 if (func_id != BPF_FUNC_sk_storage_get &&
6359                     func_id != BPF_FUNC_sk_storage_delete)
6360                         goto error;
6361                 break;
6362         case BPF_MAP_TYPE_INODE_STORAGE:
6363                 if (func_id != BPF_FUNC_inode_storage_get &&
6364                     func_id != BPF_FUNC_inode_storage_delete)
6365                         goto error;
6366                 break;
6367         case BPF_MAP_TYPE_TASK_STORAGE:
6368                 if (func_id != BPF_FUNC_task_storage_get &&
6369                     func_id != BPF_FUNC_task_storage_delete)
6370                         goto error;
6371                 break;
6372         case BPF_MAP_TYPE_BLOOM_FILTER:
6373                 if (func_id != BPF_FUNC_map_peek_elem &&
6374                     func_id != BPF_FUNC_map_push_elem)
6375                         goto error;
6376                 break;
6377         default:
6378                 break;
6379         }
6380
6381         /* ... and second from the function itself. */
6382         switch (func_id) {
6383         case BPF_FUNC_tail_call:
6384                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6385                         goto error;
6386                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6387                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6388                         return -EINVAL;
6389                 }
6390                 break;
6391         case BPF_FUNC_perf_event_read:
6392         case BPF_FUNC_perf_event_output:
6393         case BPF_FUNC_perf_event_read_value:
6394         case BPF_FUNC_skb_output:
6395         case BPF_FUNC_xdp_output:
6396                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6397                         goto error;
6398                 break;
6399         case BPF_FUNC_ringbuf_output:
6400         case BPF_FUNC_ringbuf_reserve:
6401         case BPF_FUNC_ringbuf_query:
6402         case BPF_FUNC_ringbuf_reserve_dynptr:
6403         case BPF_FUNC_ringbuf_submit_dynptr:
6404         case BPF_FUNC_ringbuf_discard_dynptr:
6405                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6406                         goto error;
6407                 break;
6408         case BPF_FUNC_user_ringbuf_drain:
6409                 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6410                         goto error;
6411                 break;
6412         case BPF_FUNC_get_stackid:
6413                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6414                         goto error;
6415                 break;
6416         case BPF_FUNC_current_task_under_cgroup:
6417         case BPF_FUNC_skb_under_cgroup:
6418                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6419                         goto error;
6420                 break;
6421         case BPF_FUNC_redirect_map:
6422                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6423                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6424                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
6425                     map->map_type != BPF_MAP_TYPE_XSKMAP)
6426                         goto error;
6427                 break;
6428         case BPF_FUNC_sk_redirect_map:
6429         case BPF_FUNC_msg_redirect_map:
6430         case BPF_FUNC_sock_map_update:
6431                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6432                         goto error;
6433                 break;
6434         case BPF_FUNC_sk_redirect_hash:
6435         case BPF_FUNC_msg_redirect_hash:
6436         case BPF_FUNC_sock_hash_update:
6437                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6438                         goto error;
6439                 break;
6440         case BPF_FUNC_get_local_storage:
6441                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6442                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6443                         goto error;
6444                 break;
6445         case BPF_FUNC_sk_select_reuseport:
6446                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6447                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6448                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
6449                         goto error;
6450                 break;
6451         case BPF_FUNC_map_pop_elem:
6452                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6453                     map->map_type != BPF_MAP_TYPE_STACK)
6454                         goto error;
6455                 break;
6456         case BPF_FUNC_map_peek_elem:
6457         case BPF_FUNC_map_push_elem:
6458                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6459                     map->map_type != BPF_MAP_TYPE_STACK &&
6460                     map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6461                         goto error;
6462                 break;
6463         case BPF_FUNC_map_lookup_percpu_elem:
6464                 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6465                     map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6466                     map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6467                         goto error;
6468                 break;
6469         case BPF_FUNC_sk_storage_get:
6470         case BPF_FUNC_sk_storage_delete:
6471                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6472                         goto error;
6473                 break;
6474         case BPF_FUNC_inode_storage_get:
6475         case BPF_FUNC_inode_storage_delete:
6476                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6477                         goto error;
6478                 break;
6479         case BPF_FUNC_task_storage_get:
6480         case BPF_FUNC_task_storage_delete:
6481                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6482                         goto error;
6483                 break;
6484         default:
6485                 break;
6486         }
6487
6488         return 0;
6489 error:
6490         verbose(env, "cannot pass map_type %d into func %s#%d\n",
6491                 map->map_type, func_id_name(func_id), func_id);
6492         return -EINVAL;
6493 }
6494
6495 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6496 {
6497         int count = 0;
6498
6499         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6500                 count++;
6501         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6502                 count++;
6503         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6504                 count++;
6505         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6506                 count++;
6507         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6508                 count++;
6509
6510         /* We only support one arg being in raw mode at the moment,
6511          * which is sufficient for the helper functions we have
6512          * right now.
6513          */
6514         return count <= 1;
6515 }
6516
6517 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6518 {
6519         bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6520         bool has_size = fn->arg_size[arg] != 0;
6521         bool is_next_size = false;
6522
6523         if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6524                 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6525
6526         if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6527                 return is_next_size;
6528
6529         return has_size == is_next_size || is_next_size == is_fixed;
6530 }
6531
6532 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6533 {
6534         /* bpf_xxx(..., buf, len) call will access 'len'
6535          * bytes from memory 'buf'. Both arg types need
6536          * to be paired, so make sure there's no buggy
6537          * helper function specification.
6538          */
6539         if (arg_type_is_mem_size(fn->arg1_type) ||
6540             check_args_pair_invalid(fn, 0) ||
6541             check_args_pair_invalid(fn, 1) ||
6542             check_args_pair_invalid(fn, 2) ||
6543             check_args_pair_invalid(fn, 3) ||
6544             check_args_pair_invalid(fn, 4))
6545                 return false;
6546
6547         return true;
6548 }
6549
6550 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6551 {
6552         int i;
6553
6554         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6555                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
6556                         return false;
6557
6558                 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6559                     /* arg_btf_id and arg_size are in a union. */
6560                     (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6561                      !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6562                         return false;
6563         }
6564
6565         return true;
6566 }
6567
6568 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6569 {
6570         return check_raw_mode_ok(fn) &&
6571                check_arg_pair_ok(fn) &&
6572                check_btf_id_ok(fn) ? 0 : -EINVAL;
6573 }
6574
6575 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6576  * are now invalid, so turn them into unknown SCALAR_VALUE.
6577  */
6578 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6579 {
6580         struct bpf_func_state *state;
6581         struct bpf_reg_state *reg;
6582
6583         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6584                 if (reg_is_pkt_pointer_any(reg))
6585                         __mark_reg_unknown(env, reg);
6586         }));
6587 }
6588
6589 enum {
6590         AT_PKT_END = -1,
6591         BEYOND_PKT_END = -2,
6592 };
6593
6594 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6595 {
6596         struct bpf_func_state *state = vstate->frame[vstate->curframe];
6597         struct bpf_reg_state *reg = &state->regs[regn];
6598
6599         if (reg->type != PTR_TO_PACKET)
6600                 /* PTR_TO_PACKET_META is not supported yet */
6601                 return;
6602
6603         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6604          * How far beyond pkt_end it goes is unknown.
6605          * if (!range_open) it's the case of pkt >= pkt_end
6606          * if (range_open) it's the case of pkt > pkt_end
6607          * hence this pointer is at least 1 byte bigger than pkt_end
6608          */
6609         if (range_open)
6610                 reg->range = BEYOND_PKT_END;
6611         else
6612                 reg->range = AT_PKT_END;
6613 }
6614
6615 /* The pointer with the specified id has released its reference to kernel
6616  * resources. Identify all copies of the same pointer and clear the reference.
6617  */
6618 static int release_reference(struct bpf_verifier_env *env,
6619                              int ref_obj_id)
6620 {
6621         struct bpf_func_state *state;
6622         struct bpf_reg_state *reg;
6623         int err;
6624
6625         err = release_reference_state(cur_func(env), ref_obj_id);
6626         if (err)
6627                 return err;
6628
6629         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6630                 if (reg->ref_obj_id == ref_obj_id) {
6631                         if (!env->allow_ptr_leaks)
6632                                 __mark_reg_not_init(env, reg);
6633                         else
6634                                 __mark_reg_unknown(env, reg);
6635                 }
6636         }));
6637
6638         return 0;
6639 }
6640
6641 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6642                                     struct bpf_reg_state *regs)
6643 {
6644         int i;
6645
6646         /* after the call registers r0 - r5 were scratched */
6647         for (i = 0; i < CALLER_SAVED_REGS; i++) {
6648                 mark_reg_not_init(env, regs, caller_saved[i]);
6649                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6650         }
6651 }
6652
6653 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6654                                    struct bpf_func_state *caller,
6655                                    struct bpf_func_state *callee,
6656                                    int insn_idx);
6657
6658 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6659                              int *insn_idx, int subprog,
6660                              set_callee_state_fn set_callee_state_cb)
6661 {
6662         struct bpf_verifier_state *state = env->cur_state;
6663         struct bpf_func_info_aux *func_info_aux;
6664         struct bpf_func_state *caller, *callee;
6665         int err;
6666         bool is_global = false;
6667
6668         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6669                 verbose(env, "the call stack of %d frames is too deep\n",
6670                         state->curframe + 2);
6671                 return -E2BIG;
6672         }
6673
6674         caller = state->frame[state->curframe];
6675         if (state->frame[state->curframe + 1]) {
6676                 verbose(env, "verifier bug. Frame %d already allocated\n",
6677                         state->curframe + 1);
6678                 return -EFAULT;
6679         }
6680
6681         func_info_aux = env->prog->aux->func_info_aux;
6682         if (func_info_aux)
6683                 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6684         err = btf_check_subprog_call(env, subprog, caller->regs);
6685         if (err == -EFAULT)
6686                 return err;
6687         if (is_global) {
6688                 if (err) {
6689                         verbose(env, "Caller passes invalid args into func#%d\n",
6690                                 subprog);
6691                         return err;
6692                 } else {
6693                         if (env->log.level & BPF_LOG_LEVEL)
6694                                 verbose(env,
6695                                         "Func#%d is global and valid. Skipping.\n",
6696                                         subprog);
6697                         clear_caller_saved_regs(env, caller->regs);
6698
6699                         /* All global functions return a 64-bit SCALAR_VALUE */
6700                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
6701                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6702
6703                         /* continue with next insn after call */
6704                         return 0;
6705                 }
6706         }
6707
6708         if (insn->code == (BPF_JMP | BPF_CALL) &&
6709             insn->src_reg == 0 &&
6710             insn->imm == BPF_FUNC_timer_set_callback) {
6711                 struct bpf_verifier_state *async_cb;
6712
6713                 /* there is no real recursion here. timer callbacks are async */
6714                 env->subprog_info[subprog].is_async_cb = true;
6715                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6716                                          *insn_idx, subprog);
6717                 if (!async_cb)
6718                         return -EFAULT;
6719                 callee = async_cb->frame[0];
6720                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
6721
6722                 /* Convert bpf_timer_set_callback() args into timer callback args */
6723                 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6724                 if (err)
6725                         return err;
6726
6727                 clear_caller_saved_regs(env, caller->regs);
6728                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6729                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6730                 /* continue with next insn after call */
6731                 return 0;
6732         }
6733
6734         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6735         if (!callee)
6736                 return -ENOMEM;
6737         state->frame[state->curframe + 1] = callee;
6738
6739         /* callee cannot access r0, r6 - r9 for reading and has to write
6740          * into its own stack before reading from it.
6741          * callee can read/write into caller's stack
6742          */
6743         init_func_state(env, callee,
6744                         /* remember the callsite, it will be used by bpf_exit */
6745                         *insn_idx /* callsite */,
6746                         state->curframe + 1 /* frameno within this callchain */,
6747                         subprog /* subprog number within this prog */);
6748
6749         /* Transfer references to the callee */
6750         err = copy_reference_state(callee, caller);
6751         if (err)
6752                 goto err_out;
6753
6754         err = set_callee_state_cb(env, caller, callee, *insn_idx);
6755         if (err)
6756                 goto err_out;
6757
6758         clear_caller_saved_regs(env, caller->regs);
6759
6760         /* only increment it after check_reg_arg() finished */
6761         state->curframe++;
6762
6763         /* and go analyze first insn of the callee */
6764         *insn_idx = env->subprog_info[subprog].start - 1;
6765
6766         if (env->log.level & BPF_LOG_LEVEL) {
6767                 verbose(env, "caller:\n");
6768                 print_verifier_state(env, caller, true);
6769                 verbose(env, "callee:\n");
6770                 print_verifier_state(env, callee, true);
6771         }
6772         return 0;
6773
6774 err_out:
6775         free_func_state(callee);
6776         state->frame[state->curframe + 1] = NULL;
6777         return err;
6778 }
6779
6780 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6781                                    struct bpf_func_state *caller,
6782                                    struct bpf_func_state *callee)
6783 {
6784         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6785          *      void *callback_ctx, u64 flags);
6786          * callback_fn(struct bpf_map *map, void *key, void *value,
6787          *      void *callback_ctx);
6788          */
6789         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6790
6791         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6792         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6793         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6794
6795         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6796         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6797         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6798
6799         /* pointer to stack or null */
6800         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6801
6802         /* unused */
6803         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6804         return 0;
6805 }
6806
6807 static int set_callee_state(struct bpf_verifier_env *env,
6808                             struct bpf_func_state *caller,
6809                             struct bpf_func_state *callee, int insn_idx)
6810 {
6811         int i;
6812
6813         /* copy r1 - r5 args that callee can access.  The copy includes parent
6814          * pointers, which connects us up to the liveness chain
6815          */
6816         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6817                 callee->regs[i] = caller->regs[i];
6818         return 0;
6819 }
6820
6821 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6822                            int *insn_idx)
6823 {
6824         int subprog, target_insn;
6825
6826         target_insn = *insn_idx + insn->imm + 1;
6827         subprog = find_subprog(env, target_insn);
6828         if (subprog < 0) {
6829                 verbose(env, "verifier bug. No program starts at insn %d\n",
6830                         target_insn);
6831                 return -EFAULT;
6832         }
6833
6834         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6835 }
6836
6837 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6838                                        struct bpf_func_state *caller,
6839                                        struct bpf_func_state *callee,
6840                                        int insn_idx)
6841 {
6842         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6843         struct bpf_map *map;
6844         int err;
6845
6846         if (bpf_map_ptr_poisoned(insn_aux)) {
6847                 verbose(env, "tail_call abusing map_ptr\n");
6848                 return -EINVAL;
6849         }
6850
6851         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6852         if (!map->ops->map_set_for_each_callback_args ||
6853             !map->ops->map_for_each_callback) {
6854                 verbose(env, "callback function not allowed for map\n");
6855                 return -ENOTSUPP;
6856         }
6857
6858         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6859         if (err)
6860                 return err;
6861
6862         callee->in_callback_fn = true;
6863         callee->callback_ret_range = tnum_range(0, 1);
6864         return 0;
6865 }
6866
6867 static int set_loop_callback_state(struct bpf_verifier_env *env,
6868                                    struct bpf_func_state *caller,
6869                                    struct bpf_func_state *callee,
6870                                    int insn_idx)
6871 {
6872         /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6873          *          u64 flags);
6874          * callback_fn(u32 index, void *callback_ctx);
6875          */
6876         callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6877         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6878
6879         /* unused */
6880         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6881         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6882         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6883
6884         callee->in_callback_fn = true;
6885         callee->callback_ret_range = tnum_range(0, 1);
6886         return 0;
6887 }
6888
6889 static int set_timer_callback_state(struct bpf_verifier_env *env,
6890                                     struct bpf_func_state *caller,
6891                                     struct bpf_func_state *callee,
6892                                     int insn_idx)
6893 {
6894         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6895
6896         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6897          * callback_fn(struct bpf_map *map, void *key, void *value);
6898          */
6899         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6900         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6901         callee->regs[BPF_REG_1].map_ptr = map_ptr;
6902
6903         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6904         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6905         callee->regs[BPF_REG_2].map_ptr = map_ptr;
6906
6907         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6908         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6909         callee->regs[BPF_REG_3].map_ptr = map_ptr;
6910
6911         /* unused */
6912         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6913         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6914         callee->in_async_callback_fn = true;
6915         callee->callback_ret_range = tnum_range(0, 1);
6916         return 0;
6917 }
6918
6919 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6920                                        struct bpf_func_state *caller,
6921                                        struct bpf_func_state *callee,
6922                                        int insn_idx)
6923 {
6924         /* bpf_find_vma(struct task_struct *task, u64 addr,
6925          *               void *callback_fn, void *callback_ctx, u64 flags)
6926          * (callback_fn)(struct task_struct *task,
6927          *               struct vm_area_struct *vma, void *callback_ctx);
6928          */
6929         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6930
6931         callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6932         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6933         callee->regs[BPF_REG_2].btf =  btf_vmlinux;
6934         callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
6935
6936         /* pointer to stack or null */
6937         callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6938
6939         /* unused */
6940         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6941         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6942         callee->in_callback_fn = true;
6943         callee->callback_ret_range = tnum_range(0, 1);
6944         return 0;
6945 }
6946
6947 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
6948                                            struct bpf_func_state *caller,
6949                                            struct bpf_func_state *callee,
6950                                            int insn_idx)
6951 {
6952         /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
6953          *                        callback_ctx, u64 flags);
6954          * callback_fn(struct bpf_dynptr_t* dynptr, void *callback_ctx);
6955          */
6956         __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
6957         callee->regs[BPF_REG_1].type = PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL;
6958         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6959         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6960
6961         /* unused */
6962         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6963         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6964         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6965
6966         callee->in_callback_fn = true;
6967         callee->callback_ret_range = tnum_range(0, 1);
6968         return 0;
6969 }
6970
6971 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
6972 {
6973         struct bpf_verifier_state *state = env->cur_state;
6974         struct bpf_func_state *caller, *callee;
6975         struct bpf_reg_state *r0;
6976         int err;
6977
6978         callee = state->frame[state->curframe];
6979         r0 = &callee->regs[BPF_REG_0];
6980         if (r0->type == PTR_TO_STACK) {
6981                 /* technically it's ok to return caller's stack pointer
6982                  * (or caller's caller's pointer) back to the caller,
6983                  * since these pointers are valid. Only current stack
6984                  * pointer will be invalid as soon as function exits,
6985                  * but let's be conservative
6986                  */
6987                 verbose(env, "cannot return stack pointer to the caller\n");
6988                 return -EINVAL;
6989         }
6990
6991         caller = state->frame[state->curframe - 1];
6992         if (callee->in_callback_fn) {
6993                 /* enforce R0 return value range [0, 1]. */
6994                 struct tnum range = callee->callback_ret_range;
6995
6996                 if (r0->type != SCALAR_VALUE) {
6997                         verbose(env, "R0 not a scalar value\n");
6998                         return -EACCES;
6999                 }
7000                 if (!tnum_in(range, r0->var_off)) {
7001                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7002                         return -EINVAL;
7003                 }
7004         } else {
7005                 /* return to the caller whatever r0 had in the callee */
7006                 caller->regs[BPF_REG_0] = *r0;
7007         }
7008
7009         /* callback_fn frame should have released its own additions to parent's
7010          * reference state at this point, or check_reference_leak would
7011          * complain, hence it must be the same as the caller. There is no need
7012          * to copy it back.
7013          */
7014         if (!callee->in_callback_fn) {
7015                 /* Transfer references to the caller */
7016                 err = copy_reference_state(caller, callee);
7017                 if (err)
7018                         return err;
7019         }
7020
7021         *insn_idx = callee->callsite + 1;
7022         if (env->log.level & BPF_LOG_LEVEL) {
7023                 verbose(env, "returning from callee:\n");
7024                 print_verifier_state(env, callee, true);
7025                 verbose(env, "to caller at %d:\n", *insn_idx);
7026                 print_verifier_state(env, caller, true);
7027         }
7028         /* clear everything in the callee */
7029         free_func_state(callee);
7030         state->frame[state->curframe--] = NULL;
7031         return 0;
7032 }
7033
7034 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7035                                    int func_id,
7036                                    struct bpf_call_arg_meta *meta)
7037 {
7038         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
7039
7040         if (ret_type != RET_INTEGER ||
7041             (func_id != BPF_FUNC_get_stack &&
7042              func_id != BPF_FUNC_get_task_stack &&
7043              func_id != BPF_FUNC_probe_read_str &&
7044              func_id != BPF_FUNC_probe_read_kernel_str &&
7045              func_id != BPF_FUNC_probe_read_user_str))
7046                 return;
7047
7048         ret_reg->smax_value = meta->msize_max_value;
7049         ret_reg->s32_max_value = meta->msize_max_value;
7050         ret_reg->smin_value = -MAX_ERRNO;
7051         ret_reg->s32_min_value = -MAX_ERRNO;
7052         reg_bounds_sync(ret_reg);
7053 }
7054
7055 static int
7056 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7057                 int func_id, int insn_idx)
7058 {
7059         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7060         struct bpf_map *map = meta->map_ptr;
7061
7062         if (func_id != BPF_FUNC_tail_call &&
7063             func_id != BPF_FUNC_map_lookup_elem &&
7064             func_id != BPF_FUNC_map_update_elem &&
7065             func_id != BPF_FUNC_map_delete_elem &&
7066             func_id != BPF_FUNC_map_push_elem &&
7067             func_id != BPF_FUNC_map_pop_elem &&
7068             func_id != BPF_FUNC_map_peek_elem &&
7069             func_id != BPF_FUNC_for_each_map_elem &&
7070             func_id != BPF_FUNC_redirect_map &&
7071             func_id != BPF_FUNC_map_lookup_percpu_elem)
7072                 return 0;
7073
7074         if (map == NULL) {
7075                 verbose(env, "kernel subsystem misconfigured verifier\n");
7076                 return -EINVAL;
7077         }
7078
7079         /* In case of read-only, some additional restrictions
7080          * need to be applied in order to prevent altering the
7081          * state of the map from program side.
7082          */
7083         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7084             (func_id == BPF_FUNC_map_delete_elem ||
7085              func_id == BPF_FUNC_map_update_elem ||
7086              func_id == BPF_FUNC_map_push_elem ||
7087              func_id == BPF_FUNC_map_pop_elem)) {
7088                 verbose(env, "write into map forbidden\n");
7089                 return -EACCES;
7090         }
7091
7092         if (!BPF_MAP_PTR(aux->map_ptr_state))
7093                 bpf_map_ptr_store(aux, meta->map_ptr,
7094                                   !meta->map_ptr->bypass_spec_v1);
7095         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7096                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7097                                   !meta->map_ptr->bypass_spec_v1);
7098         return 0;
7099 }
7100
7101 static int
7102 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7103                 int func_id, int insn_idx)
7104 {
7105         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7106         struct bpf_reg_state *regs = cur_regs(env), *reg;
7107         struct bpf_map *map = meta->map_ptr;
7108         u64 val, max;
7109         int err;
7110
7111         if (func_id != BPF_FUNC_tail_call)
7112                 return 0;
7113         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7114                 verbose(env, "kernel subsystem misconfigured verifier\n");
7115                 return -EINVAL;
7116         }
7117
7118         reg = &regs[BPF_REG_3];
7119         val = reg->var_off.value;
7120         max = map->max_entries;
7121
7122         if (!(register_is_const(reg) && val < max)) {
7123                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7124                 return 0;
7125         }
7126
7127         err = mark_chain_precision(env, BPF_REG_3);
7128         if (err)
7129                 return err;
7130         if (bpf_map_key_unseen(aux))
7131                 bpf_map_key_store(aux, val);
7132         else if (!bpf_map_key_poisoned(aux) &&
7133                   bpf_map_key_immediate(aux) != val)
7134                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7135         return 0;
7136 }
7137
7138 static int check_reference_leak(struct bpf_verifier_env *env)
7139 {
7140         struct bpf_func_state *state = cur_func(env);
7141         bool refs_lingering = false;
7142         int i;
7143
7144         if (state->frameno && !state->in_callback_fn)
7145                 return 0;
7146
7147         for (i = 0; i < state->acquired_refs; i++) {
7148                 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7149                         continue;
7150                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7151                         state->refs[i].id, state->refs[i].insn_idx);
7152                 refs_lingering = true;
7153         }
7154         return refs_lingering ? -EINVAL : 0;
7155 }
7156
7157 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7158                                    struct bpf_reg_state *regs)
7159 {
7160         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
7161         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
7162         struct bpf_map *fmt_map = fmt_reg->map_ptr;
7163         int err, fmt_map_off, num_args;
7164         u64 fmt_addr;
7165         char *fmt;
7166
7167         /* data must be an array of u64 */
7168         if (data_len_reg->var_off.value % 8)
7169                 return -EINVAL;
7170         num_args = data_len_reg->var_off.value / 8;
7171
7172         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7173          * and map_direct_value_addr is set.
7174          */
7175         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7176         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7177                                                   fmt_map_off);
7178         if (err) {
7179                 verbose(env, "verifier bug\n");
7180                 return -EFAULT;
7181         }
7182         fmt = (char *)(long)fmt_addr + fmt_map_off;
7183
7184         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7185          * can focus on validating the format specifiers.
7186          */
7187         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7188         if (err < 0)
7189                 verbose(env, "Invalid format string\n");
7190
7191         return err;
7192 }
7193
7194 static int check_get_func_ip(struct bpf_verifier_env *env)
7195 {
7196         enum bpf_prog_type type = resolve_prog_type(env->prog);
7197         int func_id = BPF_FUNC_get_func_ip;
7198
7199         if (type == BPF_PROG_TYPE_TRACING) {
7200                 if (!bpf_prog_has_trampoline(env->prog)) {
7201                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7202                                 func_id_name(func_id), func_id);
7203                         return -ENOTSUPP;
7204                 }
7205                 return 0;
7206         } else if (type == BPF_PROG_TYPE_KPROBE) {
7207                 return 0;
7208         }
7209
7210         verbose(env, "func %s#%d not supported for program type %d\n",
7211                 func_id_name(func_id), func_id, type);
7212         return -ENOTSUPP;
7213 }
7214
7215 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7216 {
7217         return &env->insn_aux_data[env->insn_idx];
7218 }
7219
7220 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7221 {
7222         struct bpf_reg_state *regs = cur_regs(env);
7223         struct bpf_reg_state *reg = &regs[BPF_REG_4];
7224         bool reg_is_null = register_is_null(reg);
7225
7226         if (reg_is_null)
7227                 mark_chain_precision(env, BPF_REG_4);
7228
7229         return reg_is_null;
7230 }
7231
7232 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7233 {
7234         struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7235
7236         if (!state->initialized) {
7237                 state->initialized = 1;
7238                 state->fit_for_inline = loop_flag_is_zero(env);
7239                 state->callback_subprogno = subprogno;
7240                 return;
7241         }
7242
7243         if (!state->fit_for_inline)
7244                 return;
7245
7246         state->fit_for_inline = (loop_flag_is_zero(env) &&
7247                                  state->callback_subprogno == subprogno);
7248 }
7249
7250 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7251                              int *insn_idx_p)
7252 {
7253         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7254         const struct bpf_func_proto *fn = NULL;
7255         enum bpf_return_type ret_type;
7256         enum bpf_type_flag ret_flag;
7257         struct bpf_reg_state *regs;
7258         struct bpf_call_arg_meta meta;
7259         int insn_idx = *insn_idx_p;
7260         bool changes_data;
7261         int i, err, func_id;
7262
7263         /* find function prototype */
7264         func_id = insn->imm;
7265         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7266                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7267                         func_id);
7268                 return -EINVAL;
7269         }
7270
7271         if (env->ops->get_func_proto)
7272                 fn = env->ops->get_func_proto(func_id, env->prog);
7273         if (!fn) {
7274                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7275                         func_id);
7276                 return -EINVAL;
7277         }
7278
7279         /* eBPF programs must be GPL compatible to use GPL-ed functions */
7280         if (!env->prog->gpl_compatible && fn->gpl_only) {
7281                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7282                 return -EINVAL;
7283         }
7284
7285         if (fn->allowed && !fn->allowed(env->prog)) {
7286                 verbose(env, "helper call is not allowed in probe\n");
7287                 return -EINVAL;
7288         }
7289
7290         /* With LD_ABS/IND some JITs save/restore skb from r1. */
7291         changes_data = bpf_helper_changes_pkt_data(fn->func);
7292         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7293                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7294                         func_id_name(func_id), func_id);
7295                 return -EINVAL;
7296         }
7297
7298         memset(&meta, 0, sizeof(meta));
7299         meta.pkt_access = fn->pkt_access;
7300
7301         err = check_func_proto(fn, func_id);
7302         if (err) {
7303                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7304                         func_id_name(func_id), func_id);
7305                 return err;
7306         }
7307
7308         meta.func_id = func_id;
7309         /* check args */
7310         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7311                 err = check_func_arg(env, i, &meta, fn);
7312                 if (err)
7313                         return err;
7314         }
7315
7316         err = record_func_map(env, &meta, func_id, insn_idx);
7317         if (err)
7318                 return err;
7319
7320         err = record_func_key(env, &meta, func_id, insn_idx);
7321         if (err)
7322                 return err;
7323
7324         /* Mark slots with STACK_MISC in case of raw mode, stack offset
7325          * is inferred from register state.
7326          */
7327         for (i = 0; i < meta.access_size; i++) {
7328                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7329                                        BPF_WRITE, -1, false);
7330                 if (err)
7331                         return err;
7332         }
7333
7334         regs = cur_regs(env);
7335
7336         if (meta.uninit_dynptr_regno) {
7337                 /* we write BPF_DW bits (8 bytes) at a time */
7338                 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7339                         err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7340                                                i, BPF_DW, BPF_WRITE, -1, false);
7341                         if (err)
7342                                 return err;
7343                 }
7344
7345                 err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
7346                                               fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7347                                               insn_idx);
7348                 if (err)
7349                         return err;
7350         }
7351
7352         if (meta.release_regno) {
7353                 err = -EINVAL;
7354                 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7355                         err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
7356                 else if (meta.ref_obj_id)
7357                         err = release_reference(env, meta.ref_obj_id);
7358                 /* meta.ref_obj_id can only be 0 if register that is meant to be
7359                  * released is NULL, which must be > R0.
7360                  */
7361                 else if (register_is_null(&regs[meta.release_regno]))
7362                         err = 0;
7363                 if (err) {
7364                         verbose(env, "func %s#%d reference has not been acquired before\n",
7365                                 func_id_name(func_id), func_id);
7366                         return err;
7367                 }
7368         }
7369
7370         switch (func_id) {
7371         case BPF_FUNC_tail_call:
7372                 err = check_reference_leak(env);
7373                 if (err) {
7374                         verbose(env, "tail_call would lead to reference leak\n");
7375                         return err;
7376                 }
7377                 break;
7378         case BPF_FUNC_get_local_storage:
7379                 /* check that flags argument in get_local_storage(map, flags) is 0,
7380                  * this is required because get_local_storage() can't return an error.
7381                  */
7382                 if (!register_is_null(&regs[BPF_REG_2])) {
7383                         verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7384                         return -EINVAL;
7385                 }
7386                 break;
7387         case BPF_FUNC_for_each_map_elem:
7388                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7389                                         set_map_elem_callback_state);
7390                 break;
7391         case BPF_FUNC_timer_set_callback:
7392                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7393                                         set_timer_callback_state);
7394                 break;
7395         case BPF_FUNC_find_vma:
7396                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7397                                         set_find_vma_callback_state);
7398                 break;
7399         case BPF_FUNC_snprintf:
7400                 err = check_bpf_snprintf_call(env, regs);
7401                 break;
7402         case BPF_FUNC_loop:
7403                 update_loop_inline_state(env, meta.subprogno);
7404                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7405                                         set_loop_callback_state);
7406                 break;
7407         case BPF_FUNC_dynptr_from_mem:
7408                 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7409                         verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7410                                 reg_type_str(env, regs[BPF_REG_1].type));
7411                         return -EACCES;
7412                 }
7413                 break;
7414         case BPF_FUNC_set_retval:
7415                 if (prog_type == BPF_PROG_TYPE_LSM &&
7416                     env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7417                         if (!env->prog->aux->attach_func_proto->type) {
7418                                 /* Make sure programs that attach to void
7419                                  * hooks don't try to modify return value.
7420                                  */
7421                                 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7422                                 return -EINVAL;
7423                         }
7424                 }
7425                 break;
7426         case BPF_FUNC_dynptr_data:
7427                 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7428                         if (arg_type_is_dynptr(fn->arg_type[i])) {
7429                                 struct bpf_reg_state *reg = &regs[BPF_REG_1 + i];
7430
7431                                 if (meta.ref_obj_id) {
7432                                         verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7433                                         return -EFAULT;
7434                                 }
7435
7436                                 if (base_type(reg->type) != PTR_TO_DYNPTR)
7437                                         /* Find the id of the dynptr we're
7438                                          * tracking the reference of
7439                                          */
7440                                         meta.ref_obj_id = stack_slot_get_id(env, reg);
7441                                 break;
7442                         }
7443                 }
7444                 if (i == MAX_BPF_FUNC_REG_ARGS) {
7445                         verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7446                         return -EFAULT;
7447                 }
7448                 break;
7449         case BPF_FUNC_user_ringbuf_drain:
7450                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7451                                         set_user_ringbuf_callback_state);
7452                 break;
7453         }
7454
7455         if (err)
7456                 return err;
7457
7458         /* reset caller saved regs */
7459         for (i = 0; i < CALLER_SAVED_REGS; i++) {
7460                 mark_reg_not_init(env, regs, caller_saved[i]);
7461                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7462         }
7463
7464         /* helper call returns 64-bit value. */
7465         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7466
7467         /* update return register (already marked as written above) */
7468         ret_type = fn->ret_type;
7469         ret_flag = type_flag(ret_type);
7470
7471         switch (base_type(ret_type)) {
7472         case RET_INTEGER:
7473                 /* sets type to SCALAR_VALUE */
7474                 mark_reg_unknown(env, regs, BPF_REG_0);
7475                 break;
7476         case RET_VOID:
7477                 regs[BPF_REG_0].type = NOT_INIT;
7478                 break;
7479         case RET_PTR_TO_MAP_VALUE:
7480                 /* There is no offset yet applied, variable or fixed */
7481                 mark_reg_known_zero(env, regs, BPF_REG_0);
7482                 /* remember map_ptr, so that check_map_access()
7483                  * can check 'value_size' boundary of memory access
7484                  * to map element returned from bpf_map_lookup_elem()
7485                  */
7486                 if (meta.map_ptr == NULL) {
7487                         verbose(env,
7488                                 "kernel subsystem misconfigured verifier\n");
7489                         return -EINVAL;
7490                 }
7491                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
7492                 regs[BPF_REG_0].map_uid = meta.map_uid;
7493                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7494                 if (!type_may_be_null(ret_type) &&
7495                     map_value_has_spin_lock(meta.map_ptr)) {
7496                         regs[BPF_REG_0].id = ++env->id_gen;
7497                 }
7498                 break;
7499         case RET_PTR_TO_SOCKET:
7500                 mark_reg_known_zero(env, regs, BPF_REG_0);
7501                 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7502                 break;
7503         case RET_PTR_TO_SOCK_COMMON:
7504                 mark_reg_known_zero(env, regs, BPF_REG_0);
7505                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7506                 break;
7507         case RET_PTR_TO_TCP_SOCK:
7508                 mark_reg_known_zero(env, regs, BPF_REG_0);
7509                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7510                 break;
7511         case RET_PTR_TO_ALLOC_MEM:
7512                 mark_reg_known_zero(env, regs, BPF_REG_0);
7513                 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7514                 regs[BPF_REG_0].mem_size = meta.mem_size;
7515                 break;
7516         case RET_PTR_TO_MEM_OR_BTF_ID:
7517         {
7518                 const struct btf_type *t;
7519
7520                 mark_reg_known_zero(env, regs, BPF_REG_0);
7521                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7522                 if (!btf_type_is_struct(t)) {
7523                         u32 tsize;
7524                         const struct btf_type *ret;
7525                         const char *tname;
7526
7527                         /* resolve the type size of ksym. */
7528                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7529                         if (IS_ERR(ret)) {
7530                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7531                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
7532                                         tname, PTR_ERR(ret));
7533                                 return -EINVAL;
7534                         }
7535                         regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7536                         regs[BPF_REG_0].mem_size = tsize;
7537                 } else {
7538                         /* MEM_RDONLY may be carried from ret_flag, but it
7539                          * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7540                          * it will confuse the check of PTR_TO_BTF_ID in
7541                          * check_mem_access().
7542                          */
7543                         ret_flag &= ~MEM_RDONLY;
7544
7545                         regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7546                         regs[BPF_REG_0].btf = meta.ret_btf;
7547                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7548                 }
7549                 break;
7550         }
7551         case RET_PTR_TO_BTF_ID:
7552         {
7553                 struct btf *ret_btf;
7554                 int ret_btf_id;
7555
7556                 mark_reg_known_zero(env, regs, BPF_REG_0);
7557                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7558                 if (func_id == BPF_FUNC_kptr_xchg) {
7559                         ret_btf = meta.kptr_off_desc->kptr.btf;
7560                         ret_btf_id = meta.kptr_off_desc->kptr.btf_id;
7561                 } else {
7562                         if (fn->ret_btf_id == BPF_PTR_POISON) {
7563                                 verbose(env, "verifier internal error:");
7564                                 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
7565                                         func_id_name(func_id));
7566                                 return -EINVAL;
7567                         }
7568                         ret_btf = btf_vmlinux;
7569                         ret_btf_id = *fn->ret_btf_id;
7570                 }
7571                 if (ret_btf_id == 0) {
7572                         verbose(env, "invalid return type %u of func %s#%d\n",
7573                                 base_type(ret_type), func_id_name(func_id),
7574                                 func_id);
7575                         return -EINVAL;
7576                 }
7577                 regs[BPF_REG_0].btf = ret_btf;
7578                 regs[BPF_REG_0].btf_id = ret_btf_id;
7579                 break;
7580         }
7581         default:
7582                 verbose(env, "unknown return type %u of func %s#%d\n",
7583                         base_type(ret_type), func_id_name(func_id), func_id);
7584                 return -EINVAL;
7585         }
7586
7587         if (type_may_be_null(regs[BPF_REG_0].type))
7588                 regs[BPF_REG_0].id = ++env->id_gen;
7589
7590         if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7591                 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7592                         func_id_name(func_id), func_id);
7593                 return -EFAULT;
7594         }
7595
7596         if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7597                 /* For release_reference() */
7598                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7599         } else if (is_acquire_function(func_id, meta.map_ptr)) {
7600                 int id = acquire_reference_state(env, insn_idx);
7601
7602                 if (id < 0)
7603                         return id;
7604                 /* For mark_ptr_or_null_reg() */
7605                 regs[BPF_REG_0].id = id;
7606                 /* For release_reference() */
7607                 regs[BPF_REG_0].ref_obj_id = id;
7608         }
7609
7610         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7611
7612         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7613         if (err)
7614                 return err;
7615
7616         if ((func_id == BPF_FUNC_get_stack ||
7617              func_id == BPF_FUNC_get_task_stack) &&
7618             !env->prog->has_callchain_buf) {
7619                 const char *err_str;
7620
7621 #ifdef CONFIG_PERF_EVENTS
7622                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
7623                 err_str = "cannot get callchain buffer for func %s#%d\n";
7624 #else
7625                 err = -ENOTSUPP;
7626                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7627 #endif
7628                 if (err) {
7629                         verbose(env, err_str, func_id_name(func_id), func_id);
7630                         return err;
7631                 }
7632
7633                 env->prog->has_callchain_buf = true;
7634         }
7635
7636         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7637                 env->prog->call_get_stack = true;
7638
7639         if (func_id == BPF_FUNC_get_func_ip) {
7640                 if (check_get_func_ip(env))
7641                         return -ENOTSUPP;
7642                 env->prog->call_get_func_ip = true;
7643         }
7644
7645         if (changes_data)
7646                 clear_all_pkt_pointers(env);
7647         return 0;
7648 }
7649
7650 /* mark_btf_func_reg_size() is used when the reg size is determined by
7651  * the BTF func_proto's return value size and argument.
7652  */
7653 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7654                                    size_t reg_size)
7655 {
7656         struct bpf_reg_state *reg = &cur_regs(env)[regno];
7657
7658         if (regno == BPF_REG_0) {
7659                 /* Function return value */
7660                 reg->live |= REG_LIVE_WRITTEN;
7661                 reg->subreg_def = reg_size == sizeof(u64) ?
7662                         DEF_NOT_SUBREG : env->insn_idx + 1;
7663         } else {
7664                 /* Function argument */
7665                 if (reg_size == sizeof(u64)) {
7666                         mark_insn_zext(env, reg);
7667                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7668                 } else {
7669                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7670                 }
7671         }
7672 }
7673
7674 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7675                             int *insn_idx_p)
7676 {
7677         const struct btf_type *t, *func, *func_proto, *ptr_type;
7678         struct bpf_reg_state *regs = cur_regs(env);
7679         struct bpf_kfunc_arg_meta meta = { 0 };
7680         const char *func_name, *ptr_type_name;
7681         u32 i, nargs, func_id, ptr_type_id;
7682         int err, insn_idx = *insn_idx_p;
7683         const struct btf_param *args;
7684         struct btf *desc_btf;
7685         u32 *kfunc_flags;
7686         bool acq;
7687
7688         /* skip for now, but return error when we find this in fixup_kfunc_call */
7689         if (!insn->imm)
7690                 return 0;
7691
7692         desc_btf = find_kfunc_desc_btf(env, insn->off);
7693         if (IS_ERR(desc_btf))
7694                 return PTR_ERR(desc_btf);
7695
7696         func_id = insn->imm;
7697         func = btf_type_by_id(desc_btf, func_id);
7698         func_name = btf_name_by_offset(desc_btf, func->name_off);
7699         func_proto = btf_type_by_id(desc_btf, func->type);
7700
7701         kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
7702         if (!kfunc_flags) {
7703                 verbose(env, "calling kernel function %s is not allowed\n",
7704                         func_name);
7705                 return -EACCES;
7706         }
7707         if (*kfunc_flags & KF_DESTRUCTIVE && !capable(CAP_SYS_BOOT)) {
7708                 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capabilities\n");
7709                 return -EACCES;
7710         }
7711
7712         acq = *kfunc_flags & KF_ACQUIRE;
7713
7714         meta.flags = *kfunc_flags;
7715
7716         /* Check the arguments */
7717         err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs, &meta);
7718         if (err < 0)
7719                 return err;
7720         /* In case of release function, we get register number of refcounted
7721          * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
7722          */
7723         if (err) {
7724                 err = release_reference(env, regs[err].ref_obj_id);
7725                 if (err) {
7726                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
7727                                 func_name, func_id);
7728                         return err;
7729                 }
7730         }
7731
7732         for (i = 0; i < CALLER_SAVED_REGS; i++)
7733                 mark_reg_not_init(env, regs, caller_saved[i]);
7734
7735         /* Check return type */
7736         t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
7737
7738         if (acq && !btf_type_is_struct_ptr(desc_btf, t)) {
7739                 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
7740                 return -EINVAL;
7741         }
7742
7743         if (btf_type_is_scalar(t)) {
7744                 mark_reg_unknown(env, regs, BPF_REG_0);
7745                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7746         } else if (btf_type_is_ptr(t)) {
7747                 ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
7748                                                    &ptr_type_id);
7749                 if (!btf_type_is_struct(ptr_type)) {
7750                         if (!meta.r0_size) {
7751                                 ptr_type_name = btf_name_by_offset(desc_btf,
7752                                                                    ptr_type->name_off);
7753                                 verbose(env,
7754                                         "kernel function %s returns pointer type %s %s is not supported\n",
7755                                         func_name,
7756                                         btf_type_str(ptr_type),
7757                                         ptr_type_name);
7758                                 return -EINVAL;
7759                         }
7760
7761                         mark_reg_known_zero(env, regs, BPF_REG_0);
7762                         regs[BPF_REG_0].type = PTR_TO_MEM;
7763                         regs[BPF_REG_0].mem_size = meta.r0_size;
7764
7765                         if (meta.r0_rdonly)
7766                                 regs[BPF_REG_0].type |= MEM_RDONLY;
7767
7768                         /* Ensures we don't access the memory after a release_reference() */
7769                         if (meta.ref_obj_id)
7770                                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7771                 } else {
7772                         mark_reg_known_zero(env, regs, BPF_REG_0);
7773                         regs[BPF_REG_0].btf = desc_btf;
7774                         regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7775                         regs[BPF_REG_0].btf_id = ptr_type_id;
7776                 }
7777                 if (*kfunc_flags & KF_RET_NULL) {
7778                         regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7779                         /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7780                         regs[BPF_REG_0].id = ++env->id_gen;
7781                 }
7782                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
7783                 if (acq) {
7784                         int id = acquire_reference_state(env, insn_idx);
7785
7786                         if (id < 0)
7787                                 return id;
7788                         regs[BPF_REG_0].id = id;
7789                         regs[BPF_REG_0].ref_obj_id = id;
7790                 }
7791         } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7792
7793         nargs = btf_type_vlen(func_proto);
7794         args = (const struct btf_param *)(func_proto + 1);
7795         for (i = 0; i < nargs; i++) {
7796                 u32 regno = i + 1;
7797
7798                 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
7799                 if (btf_type_is_ptr(t))
7800                         mark_btf_func_reg_size(env, regno, sizeof(void *));
7801                 else
7802                         /* scalar. ensured by btf_check_kfunc_arg_match() */
7803                         mark_btf_func_reg_size(env, regno, t->size);
7804         }
7805
7806         return 0;
7807 }
7808
7809 static bool signed_add_overflows(s64 a, s64 b)
7810 {
7811         /* Do the add in u64, where overflow is well-defined */
7812         s64 res = (s64)((u64)a + (u64)b);
7813
7814         if (b < 0)
7815                 return res > a;
7816         return res < a;
7817 }
7818
7819 static bool signed_add32_overflows(s32 a, s32 b)
7820 {
7821         /* Do the add in u32, where overflow is well-defined */
7822         s32 res = (s32)((u32)a + (u32)b);
7823
7824         if (b < 0)
7825                 return res > a;
7826         return res < a;
7827 }
7828
7829 static bool signed_sub_overflows(s64 a, s64 b)
7830 {
7831         /* Do the sub in u64, where overflow is well-defined */
7832         s64 res = (s64)((u64)a - (u64)b);
7833
7834         if (b < 0)
7835                 return res < a;
7836         return res > a;
7837 }
7838
7839 static bool signed_sub32_overflows(s32 a, s32 b)
7840 {
7841         /* Do the sub in u32, where overflow is well-defined */
7842         s32 res = (s32)((u32)a - (u32)b);
7843
7844         if (b < 0)
7845                 return res < a;
7846         return res > a;
7847 }
7848
7849 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7850                                   const struct bpf_reg_state *reg,
7851                                   enum bpf_reg_type type)
7852 {
7853         bool known = tnum_is_const(reg->var_off);
7854         s64 val = reg->var_off.value;
7855         s64 smin = reg->smin_value;
7856
7857         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7858                 verbose(env, "math between %s pointer and %lld is not allowed\n",
7859                         reg_type_str(env, type), val);
7860                 return false;
7861         }
7862
7863         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7864                 verbose(env, "%s pointer offset %d is not allowed\n",
7865                         reg_type_str(env, type), reg->off);
7866                 return false;
7867         }
7868
7869         if (smin == S64_MIN) {
7870                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
7871                         reg_type_str(env, type));
7872                 return false;
7873         }
7874
7875         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
7876                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
7877                         smin, reg_type_str(env, type));
7878                 return false;
7879         }
7880
7881         return true;
7882 }
7883
7884 enum {
7885         REASON_BOUNDS   = -1,
7886         REASON_TYPE     = -2,
7887         REASON_PATHS    = -3,
7888         REASON_LIMIT    = -4,
7889         REASON_STACK    = -5,
7890 };
7891
7892 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
7893                               u32 *alu_limit, bool mask_to_left)
7894 {
7895         u32 max = 0, ptr_limit = 0;
7896
7897         switch (ptr_reg->type) {
7898         case PTR_TO_STACK:
7899                 /* Offset 0 is out-of-bounds, but acceptable start for the
7900                  * left direction, see BPF_REG_FP. Also, unknown scalar
7901                  * offset where we would need to deal with min/max bounds is
7902                  * currently prohibited for unprivileged.
7903                  */
7904                 max = MAX_BPF_STACK + mask_to_left;
7905                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
7906                 break;
7907         case PTR_TO_MAP_VALUE:
7908                 max = ptr_reg->map_ptr->value_size;
7909                 ptr_limit = (mask_to_left ?
7910                              ptr_reg->smin_value :
7911                              ptr_reg->umax_value) + ptr_reg->off;
7912                 break;
7913         default:
7914                 return REASON_TYPE;
7915         }
7916
7917         if (ptr_limit >= max)
7918                 return REASON_LIMIT;
7919         *alu_limit = ptr_limit;
7920         return 0;
7921 }
7922
7923 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7924                                     const struct bpf_insn *insn)
7925 {
7926         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
7927 }
7928
7929 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7930                                        u32 alu_state, u32 alu_limit)
7931 {
7932         /* If we arrived here from different branches with different
7933          * state or limits to sanitize, then this won't work.
7934          */
7935         if (aux->alu_state &&
7936             (aux->alu_state != alu_state ||
7937              aux->alu_limit != alu_limit))
7938                 return REASON_PATHS;
7939
7940         /* Corresponding fixup done in do_misc_fixups(). */
7941         aux->alu_state = alu_state;
7942         aux->alu_limit = alu_limit;
7943         return 0;
7944 }
7945
7946 static int sanitize_val_alu(struct bpf_verifier_env *env,
7947                             struct bpf_insn *insn)
7948 {
7949         struct bpf_insn_aux_data *aux = cur_aux(env);
7950
7951         if (can_skip_alu_sanitation(env, insn))
7952                 return 0;
7953
7954         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
7955 }
7956
7957 static bool sanitize_needed(u8 opcode)
7958 {
7959         return opcode == BPF_ADD || opcode == BPF_SUB;
7960 }
7961
7962 struct bpf_sanitize_info {
7963         struct bpf_insn_aux_data aux;
7964         bool mask_to_left;
7965 };
7966
7967 static struct bpf_verifier_state *
7968 sanitize_speculative_path(struct bpf_verifier_env *env,
7969                           const struct bpf_insn *insn,
7970                           u32 next_idx, u32 curr_idx)
7971 {
7972         struct bpf_verifier_state *branch;
7973         struct bpf_reg_state *regs;
7974
7975         branch = push_stack(env, next_idx, curr_idx, true);
7976         if (branch && insn) {
7977                 regs = branch->frame[branch->curframe]->regs;
7978                 if (BPF_SRC(insn->code) == BPF_K) {
7979                         mark_reg_unknown(env, regs, insn->dst_reg);
7980                 } else if (BPF_SRC(insn->code) == BPF_X) {
7981                         mark_reg_unknown(env, regs, insn->dst_reg);
7982                         mark_reg_unknown(env, regs, insn->src_reg);
7983                 }
7984         }
7985         return branch;
7986 }
7987
7988 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
7989                             struct bpf_insn *insn,
7990                             const struct bpf_reg_state *ptr_reg,
7991                             const struct bpf_reg_state *off_reg,
7992                             struct bpf_reg_state *dst_reg,
7993                             struct bpf_sanitize_info *info,
7994                             const bool commit_window)
7995 {
7996         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
7997         struct bpf_verifier_state *vstate = env->cur_state;
7998         bool off_is_imm = tnum_is_const(off_reg->var_off);
7999         bool off_is_neg = off_reg->smin_value < 0;
8000         bool ptr_is_dst_reg = ptr_reg == dst_reg;
8001         u8 opcode = BPF_OP(insn->code);
8002         u32 alu_state, alu_limit;
8003         struct bpf_reg_state tmp;
8004         bool ret;
8005         int err;
8006
8007         if (can_skip_alu_sanitation(env, insn))
8008                 return 0;
8009
8010         /* We already marked aux for masking from non-speculative
8011          * paths, thus we got here in the first place. We only care
8012          * to explore bad access from here.
8013          */
8014         if (vstate->speculative)
8015                 goto do_sim;
8016
8017         if (!commit_window) {
8018                 if (!tnum_is_const(off_reg->var_off) &&
8019                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
8020                         return REASON_BOUNDS;
8021
8022                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
8023                                      (opcode == BPF_SUB && !off_is_neg);
8024         }
8025
8026         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
8027         if (err < 0)
8028                 return err;
8029
8030         if (commit_window) {
8031                 /* In commit phase we narrow the masking window based on
8032                  * the observed pointer move after the simulated operation.
8033                  */
8034                 alu_state = info->aux.alu_state;
8035                 alu_limit = abs(info->aux.alu_limit - alu_limit);
8036         } else {
8037                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
8038                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
8039                 alu_state |= ptr_is_dst_reg ?
8040                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
8041
8042                 /* Limit pruning on unknown scalars to enable deep search for
8043                  * potential masking differences from other program paths.
8044                  */
8045                 if (!off_is_imm)
8046                         env->explore_alu_limits = true;
8047         }
8048
8049         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
8050         if (err < 0)
8051                 return err;
8052 do_sim:
8053         /* If we're in commit phase, we're done here given we already
8054          * pushed the truncated dst_reg into the speculative verification
8055          * stack.
8056          *
8057          * Also, when register is a known constant, we rewrite register-based
8058          * operation to immediate-based, and thus do not need masking (and as
8059          * a consequence, do not need to simulate the zero-truncation either).
8060          */
8061         if (commit_window || off_is_imm)
8062                 return 0;
8063
8064         /* Simulate and find potential out-of-bounds access under
8065          * speculative execution from truncation as a result of
8066          * masking when off was not within expected range. If off
8067          * sits in dst, then we temporarily need to move ptr there
8068          * to simulate dst (== 0) +/-= ptr. Needed, for example,
8069          * for cases where we use K-based arithmetic in one direction
8070          * and truncated reg-based in the other in order to explore
8071          * bad access.
8072          */
8073         if (!ptr_is_dst_reg) {
8074                 tmp = *dst_reg;
8075                 *dst_reg = *ptr_reg;
8076         }
8077         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
8078                                         env->insn_idx);
8079         if (!ptr_is_dst_reg && ret)
8080                 *dst_reg = tmp;
8081         return !ret ? REASON_STACK : 0;
8082 }
8083
8084 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
8085 {
8086         struct bpf_verifier_state *vstate = env->cur_state;
8087
8088         /* If we simulate paths under speculation, we don't update the
8089          * insn as 'seen' such that when we verify unreachable paths in
8090          * the non-speculative domain, sanitize_dead_code() can still
8091          * rewrite/sanitize them.
8092          */
8093         if (!vstate->speculative)
8094                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8095 }
8096
8097 static int sanitize_err(struct bpf_verifier_env *env,
8098                         const struct bpf_insn *insn, int reason,
8099                         const struct bpf_reg_state *off_reg,
8100                         const struct bpf_reg_state *dst_reg)
8101 {
8102         static const char *err = "pointer arithmetic with it prohibited for !root";
8103         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
8104         u32 dst = insn->dst_reg, src = insn->src_reg;
8105
8106         switch (reason) {
8107         case REASON_BOUNDS:
8108                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
8109                         off_reg == dst_reg ? dst : src, err);
8110                 break;
8111         case REASON_TYPE:
8112                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
8113                         off_reg == dst_reg ? src : dst, err);
8114                 break;
8115         case REASON_PATHS:
8116                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
8117                         dst, op, err);
8118                 break;
8119         case REASON_LIMIT:
8120                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
8121                         dst, op, err);
8122                 break;
8123         case REASON_STACK:
8124                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
8125                         dst, err);
8126                 break;
8127         default:
8128                 verbose(env, "verifier internal error: unknown reason (%d)\n",
8129                         reason);
8130                 break;
8131         }
8132
8133         return -EACCES;
8134 }
8135
8136 /* check that stack access falls within stack limits and that 'reg' doesn't
8137  * have a variable offset.
8138  *
8139  * Variable offset is prohibited for unprivileged mode for simplicity since it
8140  * requires corresponding support in Spectre masking for stack ALU.  See also
8141  * retrieve_ptr_limit().
8142  *
8143  *
8144  * 'off' includes 'reg->off'.
8145  */
8146 static int check_stack_access_for_ptr_arithmetic(
8147                                 struct bpf_verifier_env *env,
8148                                 int regno,
8149                                 const struct bpf_reg_state *reg,
8150                                 int off)
8151 {
8152         if (!tnum_is_const(reg->var_off)) {
8153                 char tn_buf[48];
8154
8155                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8156                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
8157                         regno, tn_buf, off);
8158                 return -EACCES;
8159         }
8160
8161         if (off >= 0 || off < -MAX_BPF_STACK) {
8162                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
8163                         "prohibited for !root; off=%d\n", regno, off);
8164                 return -EACCES;
8165         }
8166
8167         return 0;
8168 }
8169
8170 static int sanitize_check_bounds(struct bpf_verifier_env *env,
8171                                  const struct bpf_insn *insn,
8172                                  const struct bpf_reg_state *dst_reg)
8173 {
8174         u32 dst = insn->dst_reg;
8175
8176         /* For unprivileged we require that resulting offset must be in bounds
8177          * in order to be able to sanitize access later on.
8178          */
8179         if (env->bypass_spec_v1)
8180                 return 0;
8181
8182         switch (dst_reg->type) {
8183         case PTR_TO_STACK:
8184                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
8185                                         dst_reg->off + dst_reg->var_off.value))
8186                         return -EACCES;
8187                 break;
8188         case PTR_TO_MAP_VALUE:
8189                 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
8190                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
8191                                 "prohibited for !root\n", dst);
8192                         return -EACCES;
8193                 }
8194                 break;
8195         default:
8196                 break;
8197         }
8198
8199         return 0;
8200 }
8201
8202 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
8203  * Caller should also handle BPF_MOV case separately.
8204  * If we return -EACCES, caller may want to try again treating pointer as a
8205  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
8206  */
8207 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
8208                                    struct bpf_insn *insn,
8209                                    const struct bpf_reg_state *ptr_reg,
8210                                    const struct bpf_reg_state *off_reg)
8211 {
8212         struct bpf_verifier_state *vstate = env->cur_state;
8213         struct bpf_func_state *state = vstate->frame[vstate->curframe];
8214         struct bpf_reg_state *regs = state->regs, *dst_reg;
8215         bool known = tnum_is_const(off_reg->var_off);
8216         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
8217             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
8218         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
8219             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
8220         struct bpf_sanitize_info info = {};
8221         u8 opcode = BPF_OP(insn->code);
8222         u32 dst = insn->dst_reg;
8223         int ret;
8224
8225         dst_reg = &regs[dst];
8226
8227         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
8228             smin_val > smax_val || umin_val > umax_val) {
8229                 /* Taint dst register if offset had invalid bounds derived from
8230                  * e.g. dead branches.
8231                  */
8232                 __mark_reg_unknown(env, dst_reg);
8233                 return 0;
8234         }
8235
8236         if (BPF_CLASS(insn->code) != BPF_ALU64) {
8237                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
8238                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8239                         __mark_reg_unknown(env, dst_reg);
8240                         return 0;
8241                 }
8242
8243                 verbose(env,
8244                         "R%d 32-bit pointer arithmetic prohibited\n",
8245                         dst);
8246                 return -EACCES;
8247         }
8248
8249         if (ptr_reg->type & PTR_MAYBE_NULL) {
8250                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
8251                         dst, reg_type_str(env, ptr_reg->type));
8252                 return -EACCES;
8253         }
8254
8255         switch (base_type(ptr_reg->type)) {
8256         case CONST_PTR_TO_MAP:
8257                 /* smin_val represents the known value */
8258                 if (known && smin_val == 0 && opcode == BPF_ADD)
8259                         break;
8260                 fallthrough;
8261         case PTR_TO_PACKET_END:
8262         case PTR_TO_SOCKET:
8263         case PTR_TO_SOCK_COMMON:
8264         case PTR_TO_TCP_SOCK:
8265         case PTR_TO_XDP_SOCK:
8266                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
8267                         dst, reg_type_str(env, ptr_reg->type));
8268                 return -EACCES;
8269         default:
8270                 break;
8271         }
8272
8273         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
8274          * The id may be overwritten later if we create a new variable offset.
8275          */
8276         dst_reg->type = ptr_reg->type;
8277         dst_reg->id = ptr_reg->id;
8278
8279         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
8280             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
8281                 return -EINVAL;
8282
8283         /* pointer types do not carry 32-bit bounds at the moment. */
8284         __mark_reg32_unbounded(dst_reg);
8285
8286         if (sanitize_needed(opcode)) {
8287                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
8288                                        &info, false);
8289                 if (ret < 0)
8290                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
8291         }
8292
8293         switch (opcode) {
8294         case BPF_ADD:
8295                 /* We can take a fixed offset as long as it doesn't overflow
8296                  * the s32 'off' field
8297                  */
8298                 if (known && (ptr_reg->off + smin_val ==
8299                               (s64)(s32)(ptr_reg->off + smin_val))) {
8300                         /* pointer += K.  Accumulate it into fixed offset */
8301                         dst_reg->smin_value = smin_ptr;
8302                         dst_reg->smax_value = smax_ptr;
8303                         dst_reg->umin_value = umin_ptr;
8304                         dst_reg->umax_value = umax_ptr;
8305                         dst_reg->var_off = ptr_reg->var_off;
8306                         dst_reg->off = ptr_reg->off + smin_val;
8307                         dst_reg->raw = ptr_reg->raw;
8308                         break;
8309                 }
8310                 /* A new variable offset is created.  Note that off_reg->off
8311                  * == 0, since it's a scalar.
8312                  * dst_reg gets the pointer type and since some positive
8313                  * integer value was added to the pointer, give it a new 'id'
8314                  * if it's a PTR_TO_PACKET.
8315                  * this creates a new 'base' pointer, off_reg (variable) gets
8316                  * added into the variable offset, and we copy the fixed offset
8317                  * from ptr_reg.
8318                  */
8319                 if (signed_add_overflows(smin_ptr, smin_val) ||
8320                     signed_add_overflows(smax_ptr, smax_val)) {
8321                         dst_reg->smin_value = S64_MIN;
8322                         dst_reg->smax_value = S64_MAX;
8323                 } else {
8324                         dst_reg->smin_value = smin_ptr + smin_val;
8325                         dst_reg->smax_value = smax_ptr + smax_val;
8326                 }
8327                 if (umin_ptr + umin_val < umin_ptr ||
8328                     umax_ptr + umax_val < umax_ptr) {
8329                         dst_reg->umin_value = 0;
8330                         dst_reg->umax_value = U64_MAX;
8331                 } else {
8332                         dst_reg->umin_value = umin_ptr + umin_val;
8333                         dst_reg->umax_value = umax_ptr + umax_val;
8334                 }
8335                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
8336                 dst_reg->off = ptr_reg->off;
8337                 dst_reg->raw = ptr_reg->raw;
8338                 if (reg_is_pkt_pointer(ptr_reg)) {
8339                         dst_reg->id = ++env->id_gen;
8340                         /* something was added to pkt_ptr, set range to zero */
8341                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8342                 }
8343                 break;
8344         case BPF_SUB:
8345                 if (dst_reg == off_reg) {
8346                         /* scalar -= pointer.  Creates an unknown scalar */
8347                         verbose(env, "R%d tried to subtract pointer from scalar\n",
8348                                 dst);
8349                         return -EACCES;
8350                 }
8351                 /* We don't allow subtraction from FP, because (according to
8352                  * test_verifier.c test "invalid fp arithmetic", JITs might not
8353                  * be able to deal with it.
8354                  */
8355                 if (ptr_reg->type == PTR_TO_STACK) {
8356                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
8357                                 dst);
8358                         return -EACCES;
8359                 }
8360                 if (known && (ptr_reg->off - smin_val ==
8361                               (s64)(s32)(ptr_reg->off - smin_val))) {
8362                         /* pointer -= K.  Subtract it from fixed offset */
8363                         dst_reg->smin_value = smin_ptr;
8364                         dst_reg->smax_value = smax_ptr;
8365                         dst_reg->umin_value = umin_ptr;
8366                         dst_reg->umax_value = umax_ptr;
8367                         dst_reg->var_off = ptr_reg->var_off;
8368                         dst_reg->id = ptr_reg->id;
8369                         dst_reg->off = ptr_reg->off - smin_val;
8370                         dst_reg->raw = ptr_reg->raw;
8371                         break;
8372                 }
8373                 /* A new variable offset is created.  If the subtrahend is known
8374                  * nonnegative, then any reg->range we had before is still good.
8375                  */
8376                 if (signed_sub_overflows(smin_ptr, smax_val) ||
8377                     signed_sub_overflows(smax_ptr, smin_val)) {
8378                         /* Overflow possible, we know nothing */
8379                         dst_reg->smin_value = S64_MIN;
8380                         dst_reg->smax_value = S64_MAX;
8381                 } else {
8382                         dst_reg->smin_value = smin_ptr - smax_val;
8383                         dst_reg->smax_value = smax_ptr - smin_val;
8384                 }
8385                 if (umin_ptr < umax_val) {
8386                         /* Overflow possible, we know nothing */
8387                         dst_reg->umin_value = 0;
8388                         dst_reg->umax_value = U64_MAX;
8389                 } else {
8390                         /* Cannot overflow (as long as bounds are consistent) */
8391                         dst_reg->umin_value = umin_ptr - umax_val;
8392                         dst_reg->umax_value = umax_ptr - umin_val;
8393                 }
8394                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
8395                 dst_reg->off = ptr_reg->off;
8396                 dst_reg->raw = ptr_reg->raw;
8397                 if (reg_is_pkt_pointer(ptr_reg)) {
8398                         dst_reg->id = ++env->id_gen;
8399                         /* something was added to pkt_ptr, set range to zero */
8400                         if (smin_val < 0)
8401                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8402                 }
8403                 break;
8404         case BPF_AND:
8405         case BPF_OR:
8406         case BPF_XOR:
8407                 /* bitwise ops on pointers are troublesome, prohibit. */
8408                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
8409                         dst, bpf_alu_string[opcode >> 4]);
8410                 return -EACCES;
8411         default:
8412                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
8413                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
8414                         dst, bpf_alu_string[opcode >> 4]);
8415                 return -EACCES;
8416         }
8417
8418         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
8419                 return -EINVAL;
8420         reg_bounds_sync(dst_reg);
8421         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
8422                 return -EACCES;
8423         if (sanitize_needed(opcode)) {
8424                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
8425                                        &info, true);
8426                 if (ret < 0)
8427                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
8428         }
8429
8430         return 0;
8431 }
8432
8433 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
8434                                  struct bpf_reg_state *src_reg)
8435 {
8436         s32 smin_val = src_reg->s32_min_value;
8437         s32 smax_val = src_reg->s32_max_value;
8438         u32 umin_val = src_reg->u32_min_value;
8439         u32 umax_val = src_reg->u32_max_value;
8440
8441         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
8442             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
8443                 dst_reg->s32_min_value = S32_MIN;
8444                 dst_reg->s32_max_value = S32_MAX;
8445         } else {
8446                 dst_reg->s32_min_value += smin_val;
8447                 dst_reg->s32_max_value += smax_val;
8448         }
8449         if (dst_reg->u32_min_value + umin_val < umin_val ||
8450             dst_reg->u32_max_value + umax_val < umax_val) {
8451                 dst_reg->u32_min_value = 0;
8452                 dst_reg->u32_max_value = U32_MAX;
8453         } else {
8454                 dst_reg->u32_min_value += umin_val;
8455                 dst_reg->u32_max_value += umax_val;
8456         }
8457 }
8458
8459 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
8460                                struct bpf_reg_state *src_reg)
8461 {
8462         s64 smin_val = src_reg->smin_value;
8463         s64 smax_val = src_reg->smax_value;
8464         u64 umin_val = src_reg->umin_value;
8465         u64 umax_val = src_reg->umax_value;
8466
8467         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
8468             signed_add_overflows(dst_reg->smax_value, smax_val)) {
8469                 dst_reg->smin_value = S64_MIN;
8470                 dst_reg->smax_value = S64_MAX;
8471         } else {
8472                 dst_reg->smin_value += smin_val;
8473                 dst_reg->smax_value += smax_val;
8474         }
8475         if (dst_reg->umin_value + umin_val < umin_val ||
8476             dst_reg->umax_value + umax_val < umax_val) {
8477                 dst_reg->umin_value = 0;
8478                 dst_reg->umax_value = U64_MAX;
8479         } else {
8480                 dst_reg->umin_value += umin_val;
8481                 dst_reg->umax_value += umax_val;
8482         }
8483 }
8484
8485 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
8486                                  struct bpf_reg_state *src_reg)
8487 {
8488         s32 smin_val = src_reg->s32_min_value;
8489         s32 smax_val = src_reg->s32_max_value;
8490         u32 umin_val = src_reg->u32_min_value;
8491         u32 umax_val = src_reg->u32_max_value;
8492
8493         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
8494             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
8495                 /* Overflow possible, we know nothing */
8496                 dst_reg->s32_min_value = S32_MIN;
8497                 dst_reg->s32_max_value = S32_MAX;
8498         } else {
8499                 dst_reg->s32_min_value -= smax_val;
8500                 dst_reg->s32_max_value -= smin_val;
8501         }
8502         if (dst_reg->u32_min_value < umax_val) {
8503                 /* Overflow possible, we know nothing */
8504                 dst_reg->u32_min_value = 0;
8505                 dst_reg->u32_max_value = U32_MAX;
8506         } else {
8507                 /* Cannot overflow (as long as bounds are consistent) */
8508                 dst_reg->u32_min_value -= umax_val;
8509                 dst_reg->u32_max_value -= umin_val;
8510         }
8511 }
8512
8513 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
8514                                struct bpf_reg_state *src_reg)
8515 {
8516         s64 smin_val = src_reg->smin_value;
8517         s64 smax_val = src_reg->smax_value;
8518         u64 umin_val = src_reg->umin_value;
8519         u64 umax_val = src_reg->umax_value;
8520
8521         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
8522             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
8523                 /* Overflow possible, we know nothing */
8524                 dst_reg->smin_value = S64_MIN;
8525                 dst_reg->smax_value = S64_MAX;
8526         } else {
8527                 dst_reg->smin_value -= smax_val;
8528                 dst_reg->smax_value -= smin_val;
8529         }
8530         if (dst_reg->umin_value < umax_val) {
8531                 /* Overflow possible, we know nothing */
8532                 dst_reg->umin_value = 0;
8533                 dst_reg->umax_value = U64_MAX;
8534         } else {
8535                 /* Cannot overflow (as long as bounds are consistent) */
8536                 dst_reg->umin_value -= umax_val;
8537                 dst_reg->umax_value -= umin_val;
8538         }
8539 }
8540
8541 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
8542                                  struct bpf_reg_state *src_reg)
8543 {
8544         s32 smin_val = src_reg->s32_min_value;
8545         u32 umin_val = src_reg->u32_min_value;
8546         u32 umax_val = src_reg->u32_max_value;
8547
8548         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
8549                 /* Ain't nobody got time to multiply that sign */
8550                 __mark_reg32_unbounded(dst_reg);
8551                 return;
8552         }
8553         /* Both values are positive, so we can work with unsigned and
8554          * copy the result to signed (unless it exceeds S32_MAX).
8555          */
8556         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
8557                 /* Potential overflow, we know nothing */
8558                 __mark_reg32_unbounded(dst_reg);
8559                 return;
8560         }
8561         dst_reg->u32_min_value *= umin_val;
8562         dst_reg->u32_max_value *= umax_val;
8563         if (dst_reg->u32_max_value > S32_MAX) {
8564                 /* Overflow possible, we know nothing */
8565                 dst_reg->s32_min_value = S32_MIN;
8566                 dst_reg->s32_max_value = S32_MAX;
8567         } else {
8568                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8569                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8570         }
8571 }
8572
8573 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
8574                                struct bpf_reg_state *src_reg)
8575 {
8576         s64 smin_val = src_reg->smin_value;
8577         u64 umin_val = src_reg->umin_value;
8578         u64 umax_val = src_reg->umax_value;
8579
8580         if (smin_val < 0 || dst_reg->smin_value < 0) {
8581                 /* Ain't nobody got time to multiply that sign */
8582                 __mark_reg64_unbounded(dst_reg);
8583                 return;
8584         }
8585         /* Both values are positive, so we can work with unsigned and
8586          * copy the result to signed (unless it exceeds S64_MAX).
8587          */
8588         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
8589                 /* Potential overflow, we know nothing */
8590                 __mark_reg64_unbounded(dst_reg);
8591                 return;
8592         }
8593         dst_reg->umin_value *= umin_val;
8594         dst_reg->umax_value *= umax_val;
8595         if (dst_reg->umax_value > S64_MAX) {
8596                 /* Overflow possible, we know nothing */
8597                 dst_reg->smin_value = S64_MIN;
8598                 dst_reg->smax_value = S64_MAX;
8599         } else {
8600                 dst_reg->smin_value = dst_reg->umin_value;
8601                 dst_reg->smax_value = dst_reg->umax_value;
8602         }
8603 }
8604
8605 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
8606                                  struct bpf_reg_state *src_reg)
8607 {
8608         bool src_known = tnum_subreg_is_const(src_reg->var_off);
8609         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8610         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8611         s32 smin_val = src_reg->s32_min_value;
8612         u32 umax_val = src_reg->u32_max_value;
8613
8614         if (src_known && dst_known) {
8615                 __mark_reg32_known(dst_reg, var32_off.value);
8616                 return;
8617         }
8618
8619         /* We get our minimum from the var_off, since that's inherently
8620          * bitwise.  Our maximum is the minimum of the operands' maxima.
8621          */
8622         dst_reg->u32_min_value = var32_off.value;
8623         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
8624         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8625                 /* Lose signed bounds when ANDing negative numbers,
8626                  * ain't nobody got time for that.
8627                  */
8628                 dst_reg->s32_min_value = S32_MIN;
8629                 dst_reg->s32_max_value = S32_MAX;
8630         } else {
8631                 /* ANDing two positives gives a positive, so safe to
8632                  * cast result into s64.
8633                  */
8634                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8635                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8636         }
8637 }
8638
8639 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
8640                                struct bpf_reg_state *src_reg)
8641 {
8642         bool src_known = tnum_is_const(src_reg->var_off);
8643         bool dst_known = tnum_is_const(dst_reg->var_off);
8644         s64 smin_val = src_reg->smin_value;
8645         u64 umax_val = src_reg->umax_value;
8646
8647         if (src_known && dst_known) {
8648                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8649                 return;
8650         }
8651
8652         /* We get our minimum from the var_off, since that's inherently
8653          * bitwise.  Our maximum is the minimum of the operands' maxima.
8654          */
8655         dst_reg->umin_value = dst_reg->var_off.value;
8656         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
8657         if (dst_reg->smin_value < 0 || smin_val < 0) {
8658                 /* Lose signed bounds when ANDing negative numbers,
8659                  * ain't nobody got time for that.
8660                  */
8661                 dst_reg->smin_value = S64_MIN;
8662                 dst_reg->smax_value = S64_MAX;
8663         } else {
8664                 /* ANDing two positives gives a positive, so safe to
8665                  * cast result into s64.
8666                  */
8667                 dst_reg->smin_value = dst_reg->umin_value;
8668                 dst_reg->smax_value = dst_reg->umax_value;
8669         }
8670         /* We may learn something more from the var_off */
8671         __update_reg_bounds(dst_reg);
8672 }
8673
8674 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
8675                                 struct bpf_reg_state *src_reg)
8676 {
8677         bool src_known = tnum_subreg_is_const(src_reg->var_off);
8678         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8679         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8680         s32 smin_val = src_reg->s32_min_value;
8681         u32 umin_val = src_reg->u32_min_value;
8682
8683         if (src_known && dst_known) {
8684                 __mark_reg32_known(dst_reg, var32_off.value);
8685                 return;
8686         }
8687
8688         /* We get our maximum from the var_off, and our minimum is the
8689          * maximum of the operands' minima
8690          */
8691         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
8692         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8693         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8694                 /* Lose signed bounds when ORing negative numbers,
8695                  * ain't nobody got time for that.
8696                  */
8697                 dst_reg->s32_min_value = S32_MIN;
8698                 dst_reg->s32_max_value = S32_MAX;
8699         } else {
8700                 /* ORing two positives gives a positive, so safe to
8701                  * cast result into s64.
8702                  */
8703                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8704                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8705         }
8706 }
8707
8708 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
8709                               struct bpf_reg_state *src_reg)
8710 {
8711         bool src_known = tnum_is_const(src_reg->var_off);
8712         bool dst_known = tnum_is_const(dst_reg->var_off);
8713         s64 smin_val = src_reg->smin_value;
8714         u64 umin_val = src_reg->umin_value;
8715
8716         if (src_known && dst_known) {
8717                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8718                 return;
8719         }
8720
8721         /* We get our maximum from the var_off, and our minimum is the
8722          * maximum of the operands' minima
8723          */
8724         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
8725         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8726         if (dst_reg->smin_value < 0 || smin_val < 0) {
8727                 /* Lose signed bounds when ORing negative numbers,
8728                  * ain't nobody got time for that.
8729                  */
8730                 dst_reg->smin_value = S64_MIN;
8731                 dst_reg->smax_value = S64_MAX;
8732         } else {
8733                 /* ORing two positives gives a positive, so safe to
8734                  * cast result into s64.
8735                  */
8736                 dst_reg->smin_value = dst_reg->umin_value;
8737                 dst_reg->smax_value = dst_reg->umax_value;
8738         }
8739         /* We may learn something more from the var_off */
8740         __update_reg_bounds(dst_reg);
8741 }
8742
8743 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
8744                                  struct bpf_reg_state *src_reg)
8745 {
8746         bool src_known = tnum_subreg_is_const(src_reg->var_off);
8747         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8748         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8749         s32 smin_val = src_reg->s32_min_value;
8750
8751         if (src_known && dst_known) {
8752                 __mark_reg32_known(dst_reg, var32_off.value);
8753                 return;
8754         }
8755
8756         /* We get both minimum and maximum from the var32_off. */
8757         dst_reg->u32_min_value = var32_off.value;
8758         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8759
8760         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8761                 /* XORing two positive sign numbers gives a positive,
8762                  * so safe to cast u32 result into s32.
8763                  */
8764                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8765                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8766         } else {
8767                 dst_reg->s32_min_value = S32_MIN;
8768                 dst_reg->s32_max_value = S32_MAX;
8769         }
8770 }
8771
8772 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8773                                struct bpf_reg_state *src_reg)
8774 {
8775         bool src_known = tnum_is_const(src_reg->var_off);
8776         bool dst_known = tnum_is_const(dst_reg->var_off);
8777         s64 smin_val = src_reg->smin_value;
8778
8779         if (src_known && dst_known) {
8780                 /* dst_reg->var_off.value has been updated earlier */
8781                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8782                 return;
8783         }
8784
8785         /* We get both minimum and maximum from the var_off. */
8786         dst_reg->umin_value = dst_reg->var_off.value;
8787         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8788
8789         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8790                 /* XORing two positive sign numbers gives a positive,
8791                  * so safe to cast u64 result into s64.
8792                  */
8793                 dst_reg->smin_value = dst_reg->umin_value;
8794                 dst_reg->smax_value = dst_reg->umax_value;
8795         } else {
8796                 dst_reg->smin_value = S64_MIN;
8797                 dst_reg->smax_value = S64_MAX;
8798         }
8799
8800         __update_reg_bounds(dst_reg);
8801 }
8802
8803 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8804                                    u64 umin_val, u64 umax_val)
8805 {
8806         /* We lose all sign bit information (except what we can pick
8807          * up from var_off)
8808          */
8809         dst_reg->s32_min_value = S32_MIN;
8810         dst_reg->s32_max_value = S32_MAX;
8811         /* If we might shift our top bit out, then we know nothing */
8812         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8813                 dst_reg->u32_min_value = 0;
8814                 dst_reg->u32_max_value = U32_MAX;
8815         } else {
8816                 dst_reg->u32_min_value <<= umin_val;
8817                 dst_reg->u32_max_value <<= umax_val;
8818         }
8819 }
8820
8821 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8822                                  struct bpf_reg_state *src_reg)
8823 {
8824         u32 umax_val = src_reg->u32_max_value;
8825         u32 umin_val = src_reg->u32_min_value;
8826         /* u32 alu operation will zext upper bits */
8827         struct tnum subreg = tnum_subreg(dst_reg->var_off);
8828
8829         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8830         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8831         /* Not required but being careful mark reg64 bounds as unknown so
8832          * that we are forced to pick them up from tnum and zext later and
8833          * if some path skips this step we are still safe.
8834          */
8835         __mark_reg64_unbounded(dst_reg);
8836         __update_reg32_bounds(dst_reg);
8837 }
8838
8839 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8840                                    u64 umin_val, u64 umax_val)
8841 {
8842         /* Special case <<32 because it is a common compiler pattern to sign
8843          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8844          * positive we know this shift will also be positive so we can track
8845          * bounds correctly. Otherwise we lose all sign bit information except
8846          * what we can pick up from var_off. Perhaps we can generalize this
8847          * later to shifts of any length.
8848          */
8849         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8850                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8851         else
8852                 dst_reg->smax_value = S64_MAX;
8853
8854         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8855                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8856         else
8857                 dst_reg->smin_value = S64_MIN;
8858
8859         /* If we might shift our top bit out, then we know nothing */
8860         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8861                 dst_reg->umin_value = 0;
8862                 dst_reg->umax_value = U64_MAX;
8863         } else {
8864                 dst_reg->umin_value <<= umin_val;
8865                 dst_reg->umax_value <<= umax_val;
8866         }
8867 }
8868
8869 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8870                                struct bpf_reg_state *src_reg)
8871 {
8872         u64 umax_val = src_reg->umax_value;
8873         u64 umin_val = src_reg->umin_value;
8874
8875         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
8876         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8877         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8878
8879         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
8880         /* We may learn something more from the var_off */
8881         __update_reg_bounds(dst_reg);
8882 }
8883
8884 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
8885                                  struct bpf_reg_state *src_reg)
8886 {
8887         struct tnum subreg = tnum_subreg(dst_reg->var_off);
8888         u32 umax_val = src_reg->u32_max_value;
8889         u32 umin_val = src_reg->u32_min_value;
8890
8891         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8892          * be negative, then either:
8893          * 1) src_reg might be zero, so the sign bit of the result is
8894          *    unknown, so we lose our signed bounds
8895          * 2) it's known negative, thus the unsigned bounds capture the
8896          *    signed bounds
8897          * 3) the signed bounds cross zero, so they tell us nothing
8898          *    about the result
8899          * If the value in dst_reg is known nonnegative, then again the
8900          * unsigned bounds capture the signed bounds.
8901          * Thus, in all cases it suffices to blow away our signed bounds
8902          * and rely on inferring new ones from the unsigned bounds and
8903          * var_off of the result.
8904          */
8905         dst_reg->s32_min_value = S32_MIN;
8906         dst_reg->s32_max_value = S32_MAX;
8907
8908         dst_reg->var_off = tnum_rshift(subreg, umin_val);
8909         dst_reg->u32_min_value >>= umax_val;
8910         dst_reg->u32_max_value >>= umin_val;
8911
8912         __mark_reg64_unbounded(dst_reg);
8913         __update_reg32_bounds(dst_reg);
8914 }
8915
8916 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
8917                                struct bpf_reg_state *src_reg)
8918 {
8919         u64 umax_val = src_reg->umax_value;
8920         u64 umin_val = src_reg->umin_value;
8921
8922         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8923          * be negative, then either:
8924          * 1) src_reg might be zero, so the sign bit of the result is
8925          *    unknown, so we lose our signed bounds
8926          * 2) it's known negative, thus the unsigned bounds capture the
8927          *    signed bounds
8928          * 3) the signed bounds cross zero, so they tell us nothing
8929          *    about the result
8930          * If the value in dst_reg is known nonnegative, then again the
8931          * unsigned bounds capture the signed bounds.
8932          * Thus, in all cases it suffices to blow away our signed bounds
8933          * and rely on inferring new ones from the unsigned bounds and
8934          * var_off of the result.
8935          */
8936         dst_reg->smin_value = S64_MIN;
8937         dst_reg->smax_value = S64_MAX;
8938         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8939         dst_reg->umin_value >>= umax_val;
8940         dst_reg->umax_value >>= umin_val;
8941
8942         /* Its not easy to operate on alu32 bounds here because it depends
8943          * on bits being shifted in. Take easy way out and mark unbounded
8944          * so we can recalculate later from tnum.
8945          */
8946         __mark_reg32_unbounded(dst_reg);
8947         __update_reg_bounds(dst_reg);
8948 }
8949
8950 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
8951                                   struct bpf_reg_state *src_reg)
8952 {
8953         u64 umin_val = src_reg->u32_min_value;
8954
8955         /* Upon reaching here, src_known is true and
8956          * umax_val is equal to umin_val.
8957          */
8958         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
8959         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
8960
8961         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
8962
8963         /* blow away the dst_reg umin_value/umax_value and rely on
8964          * dst_reg var_off to refine the result.
8965          */
8966         dst_reg->u32_min_value = 0;
8967         dst_reg->u32_max_value = U32_MAX;
8968
8969         __mark_reg64_unbounded(dst_reg);
8970         __update_reg32_bounds(dst_reg);
8971 }
8972
8973 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
8974                                 struct bpf_reg_state *src_reg)
8975 {
8976         u64 umin_val = src_reg->umin_value;
8977
8978         /* Upon reaching here, src_known is true and umax_val is equal
8979          * to umin_val.
8980          */
8981         dst_reg->smin_value >>= umin_val;
8982         dst_reg->smax_value >>= umin_val;
8983
8984         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
8985
8986         /* blow away the dst_reg umin_value/umax_value and rely on
8987          * dst_reg var_off to refine the result.
8988          */
8989         dst_reg->umin_value = 0;
8990         dst_reg->umax_value = U64_MAX;
8991
8992         /* Its not easy to operate on alu32 bounds here because it depends
8993          * on bits being shifted in from upper 32-bits. Take easy way out
8994          * and mark unbounded so we can recalculate later from tnum.
8995          */
8996         __mark_reg32_unbounded(dst_reg);
8997         __update_reg_bounds(dst_reg);
8998 }
8999
9000 /* WARNING: This function does calculations on 64-bit values, but the actual
9001  * execution may occur on 32-bit values. Therefore, things like bitshifts
9002  * need extra checks in the 32-bit case.
9003  */
9004 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
9005                                       struct bpf_insn *insn,
9006                                       struct bpf_reg_state *dst_reg,
9007                                       struct bpf_reg_state src_reg)
9008 {
9009         struct bpf_reg_state *regs = cur_regs(env);
9010         u8 opcode = BPF_OP(insn->code);
9011         bool src_known;
9012         s64 smin_val, smax_val;
9013         u64 umin_val, umax_val;
9014         s32 s32_min_val, s32_max_val;
9015         u32 u32_min_val, u32_max_val;
9016         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
9017         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
9018         int ret;
9019
9020         smin_val = src_reg.smin_value;
9021         smax_val = src_reg.smax_value;
9022         umin_val = src_reg.umin_value;
9023         umax_val = src_reg.umax_value;
9024
9025         s32_min_val = src_reg.s32_min_value;
9026         s32_max_val = src_reg.s32_max_value;
9027         u32_min_val = src_reg.u32_min_value;
9028         u32_max_val = src_reg.u32_max_value;
9029
9030         if (alu32) {
9031                 src_known = tnum_subreg_is_const(src_reg.var_off);
9032                 if ((src_known &&
9033                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
9034                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
9035                         /* Taint dst register if offset had invalid bounds
9036                          * derived from e.g. dead branches.
9037                          */
9038                         __mark_reg_unknown(env, dst_reg);
9039                         return 0;
9040                 }
9041         } else {
9042                 src_known = tnum_is_const(src_reg.var_off);
9043                 if ((src_known &&
9044                      (smin_val != smax_val || umin_val != umax_val)) ||
9045                     smin_val > smax_val || umin_val > umax_val) {
9046                         /* Taint dst register if offset had invalid bounds
9047                          * derived from e.g. dead branches.
9048                          */
9049                         __mark_reg_unknown(env, dst_reg);
9050                         return 0;
9051                 }
9052         }
9053
9054         if (!src_known &&
9055             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
9056                 __mark_reg_unknown(env, dst_reg);
9057                 return 0;
9058         }
9059
9060         if (sanitize_needed(opcode)) {
9061                 ret = sanitize_val_alu(env, insn);
9062                 if (ret < 0)
9063                         return sanitize_err(env, insn, ret, NULL, NULL);
9064         }
9065
9066         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
9067          * There are two classes of instructions: The first class we track both
9068          * alu32 and alu64 sign/unsigned bounds independently this provides the
9069          * greatest amount of precision when alu operations are mixed with jmp32
9070          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
9071          * and BPF_OR. This is possible because these ops have fairly easy to
9072          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
9073          * See alu32 verifier tests for examples. The second class of
9074          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
9075          * with regards to tracking sign/unsigned bounds because the bits may
9076          * cross subreg boundaries in the alu64 case. When this happens we mark
9077          * the reg unbounded in the subreg bound space and use the resulting
9078          * tnum to calculate an approximation of the sign/unsigned bounds.
9079          */
9080         switch (opcode) {
9081         case BPF_ADD:
9082                 scalar32_min_max_add(dst_reg, &src_reg);
9083                 scalar_min_max_add(dst_reg, &src_reg);
9084                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
9085                 break;
9086         case BPF_SUB:
9087                 scalar32_min_max_sub(dst_reg, &src_reg);
9088                 scalar_min_max_sub(dst_reg, &src_reg);
9089                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
9090                 break;
9091         case BPF_MUL:
9092                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
9093                 scalar32_min_max_mul(dst_reg, &src_reg);
9094                 scalar_min_max_mul(dst_reg, &src_reg);
9095                 break;
9096         case BPF_AND:
9097                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
9098                 scalar32_min_max_and(dst_reg, &src_reg);
9099                 scalar_min_max_and(dst_reg, &src_reg);
9100                 break;
9101         case BPF_OR:
9102                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
9103                 scalar32_min_max_or(dst_reg, &src_reg);
9104                 scalar_min_max_or(dst_reg, &src_reg);
9105                 break;
9106         case BPF_XOR:
9107                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
9108                 scalar32_min_max_xor(dst_reg, &src_reg);
9109                 scalar_min_max_xor(dst_reg, &src_reg);
9110                 break;
9111         case BPF_LSH:
9112                 if (umax_val >= insn_bitness) {
9113                         /* Shifts greater than 31 or 63 are undefined.
9114                          * This includes shifts by a negative number.
9115                          */
9116                         mark_reg_unknown(env, regs, insn->dst_reg);
9117                         break;
9118                 }
9119                 if (alu32)
9120                         scalar32_min_max_lsh(dst_reg, &src_reg);
9121                 else
9122                         scalar_min_max_lsh(dst_reg, &src_reg);
9123                 break;
9124         case BPF_RSH:
9125                 if (umax_val >= insn_bitness) {
9126                         /* Shifts greater than 31 or 63 are undefined.
9127                          * This includes shifts by a negative number.
9128                          */
9129                         mark_reg_unknown(env, regs, insn->dst_reg);
9130                         break;
9131                 }
9132                 if (alu32)
9133                         scalar32_min_max_rsh(dst_reg, &src_reg);
9134                 else
9135                         scalar_min_max_rsh(dst_reg, &src_reg);
9136                 break;
9137         case BPF_ARSH:
9138                 if (umax_val >= insn_bitness) {
9139                         /* Shifts greater than 31 or 63 are undefined.
9140                          * This includes shifts by a negative number.
9141                          */
9142                         mark_reg_unknown(env, regs, insn->dst_reg);
9143                         break;
9144                 }
9145                 if (alu32)
9146                         scalar32_min_max_arsh(dst_reg, &src_reg);
9147                 else
9148                         scalar_min_max_arsh(dst_reg, &src_reg);
9149                 break;
9150         default:
9151                 mark_reg_unknown(env, regs, insn->dst_reg);
9152                 break;
9153         }
9154
9155         /* ALU32 ops are zero extended into 64bit register */
9156         if (alu32)
9157                 zext_32_to_64(dst_reg);
9158         reg_bounds_sync(dst_reg);
9159         return 0;
9160 }
9161
9162 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
9163  * and var_off.
9164  */
9165 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
9166                                    struct bpf_insn *insn)
9167 {
9168         struct bpf_verifier_state *vstate = env->cur_state;
9169         struct bpf_func_state *state = vstate->frame[vstate->curframe];
9170         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
9171         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
9172         u8 opcode = BPF_OP(insn->code);
9173         int err;
9174
9175         dst_reg = &regs[insn->dst_reg];
9176         src_reg = NULL;
9177         if (dst_reg->type != SCALAR_VALUE)
9178                 ptr_reg = dst_reg;
9179         else
9180                 /* Make sure ID is cleared otherwise dst_reg min/max could be
9181                  * incorrectly propagated into other registers by find_equal_scalars()
9182                  */
9183                 dst_reg->id = 0;
9184         if (BPF_SRC(insn->code) == BPF_X) {
9185                 src_reg = &regs[insn->src_reg];
9186                 if (src_reg->type != SCALAR_VALUE) {
9187                         if (dst_reg->type != SCALAR_VALUE) {
9188                                 /* Combining two pointers by any ALU op yields
9189                                  * an arbitrary scalar. Disallow all math except
9190                                  * pointer subtraction
9191                                  */
9192                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9193                                         mark_reg_unknown(env, regs, insn->dst_reg);
9194                                         return 0;
9195                                 }
9196                                 verbose(env, "R%d pointer %s pointer prohibited\n",
9197                                         insn->dst_reg,
9198                                         bpf_alu_string[opcode >> 4]);
9199                                 return -EACCES;
9200                         } else {
9201                                 /* scalar += pointer
9202                                  * This is legal, but we have to reverse our
9203                                  * src/dest handling in computing the range
9204                                  */
9205                                 err = mark_chain_precision(env, insn->dst_reg);
9206                                 if (err)
9207                                         return err;
9208                                 return adjust_ptr_min_max_vals(env, insn,
9209                                                                src_reg, dst_reg);
9210                         }
9211                 } else if (ptr_reg) {
9212                         /* pointer += scalar */
9213                         err = mark_chain_precision(env, insn->src_reg);
9214                         if (err)
9215                                 return err;
9216                         return adjust_ptr_min_max_vals(env, insn,
9217                                                        dst_reg, src_reg);
9218                 }
9219         } else {
9220                 /* Pretend the src is a reg with a known value, since we only
9221                  * need to be able to read from this state.
9222                  */
9223                 off_reg.type = SCALAR_VALUE;
9224                 __mark_reg_known(&off_reg, insn->imm);
9225                 src_reg = &off_reg;
9226                 if (ptr_reg) /* pointer += K */
9227                         return adjust_ptr_min_max_vals(env, insn,
9228                                                        ptr_reg, src_reg);
9229         }
9230
9231         /* Got here implies adding two SCALAR_VALUEs */
9232         if (WARN_ON_ONCE(ptr_reg)) {
9233                 print_verifier_state(env, state, true);
9234                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
9235                 return -EINVAL;
9236         }
9237         if (WARN_ON(!src_reg)) {
9238                 print_verifier_state(env, state, true);
9239                 verbose(env, "verifier internal error: no src_reg\n");
9240                 return -EINVAL;
9241         }
9242         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
9243 }
9244
9245 /* check validity of 32-bit and 64-bit arithmetic operations */
9246 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
9247 {
9248         struct bpf_reg_state *regs = cur_regs(env);
9249         u8 opcode = BPF_OP(insn->code);
9250         int err;
9251
9252         if (opcode == BPF_END || opcode == BPF_NEG) {
9253                 if (opcode == BPF_NEG) {
9254                         if (BPF_SRC(insn->code) != BPF_K ||
9255                             insn->src_reg != BPF_REG_0 ||
9256                             insn->off != 0 || insn->imm != 0) {
9257                                 verbose(env, "BPF_NEG uses reserved fields\n");
9258                                 return -EINVAL;
9259                         }
9260                 } else {
9261                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
9262                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
9263                             BPF_CLASS(insn->code) == BPF_ALU64) {
9264                                 verbose(env, "BPF_END uses reserved fields\n");
9265                                 return -EINVAL;
9266                         }
9267                 }
9268
9269                 /* check src operand */
9270                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9271                 if (err)
9272                         return err;
9273
9274                 if (is_pointer_value(env, insn->dst_reg)) {
9275                         verbose(env, "R%d pointer arithmetic prohibited\n",
9276                                 insn->dst_reg);
9277                         return -EACCES;
9278                 }
9279
9280                 /* check dest operand */
9281                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
9282                 if (err)
9283                         return err;
9284
9285         } else if (opcode == BPF_MOV) {
9286
9287                 if (BPF_SRC(insn->code) == BPF_X) {
9288                         if (insn->imm != 0 || insn->off != 0) {
9289                                 verbose(env, "BPF_MOV uses reserved fields\n");
9290                                 return -EINVAL;
9291                         }
9292
9293                         /* check src operand */
9294                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
9295                         if (err)
9296                                 return err;
9297                 } else {
9298                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9299                                 verbose(env, "BPF_MOV uses reserved fields\n");
9300                                 return -EINVAL;
9301                         }
9302                 }
9303
9304                 /* check dest operand, mark as required later */
9305                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9306                 if (err)
9307                         return err;
9308
9309                 if (BPF_SRC(insn->code) == BPF_X) {
9310                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
9311                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
9312
9313                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
9314                                 /* case: R1 = R2
9315                                  * copy register state to dest reg
9316                                  */
9317                                 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
9318                                         /* Assign src and dst registers the same ID
9319                                          * that will be used by find_equal_scalars()
9320                                          * to propagate min/max range.
9321                                          */
9322                                         src_reg->id = ++env->id_gen;
9323                                 *dst_reg = *src_reg;
9324                                 dst_reg->live |= REG_LIVE_WRITTEN;
9325                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
9326                         } else {
9327                                 /* R1 = (u32) R2 */
9328                                 if (is_pointer_value(env, insn->src_reg)) {
9329                                         verbose(env,
9330                                                 "R%d partial copy of pointer\n",
9331                                                 insn->src_reg);
9332                                         return -EACCES;
9333                                 } else if (src_reg->type == SCALAR_VALUE) {
9334                                         *dst_reg = *src_reg;
9335                                         /* Make sure ID is cleared otherwise
9336                                          * dst_reg min/max could be incorrectly
9337                                          * propagated into src_reg by find_equal_scalars()
9338                                          */
9339                                         dst_reg->id = 0;
9340                                         dst_reg->live |= REG_LIVE_WRITTEN;
9341                                         dst_reg->subreg_def = env->insn_idx + 1;
9342                                 } else {
9343                                         mark_reg_unknown(env, regs,
9344                                                          insn->dst_reg);
9345                                 }
9346                                 zext_32_to_64(dst_reg);
9347                                 reg_bounds_sync(dst_reg);
9348                         }
9349                 } else {
9350                         /* case: R = imm
9351                          * remember the value we stored into this reg
9352                          */
9353                         /* clear any state __mark_reg_known doesn't set */
9354                         mark_reg_unknown(env, regs, insn->dst_reg);
9355                         regs[insn->dst_reg].type = SCALAR_VALUE;
9356                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
9357                                 __mark_reg_known(regs + insn->dst_reg,
9358                                                  insn->imm);
9359                         } else {
9360                                 __mark_reg_known(regs + insn->dst_reg,
9361                                                  (u32)insn->imm);
9362                         }
9363                 }
9364
9365         } else if (opcode > BPF_END) {
9366                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
9367                 return -EINVAL;
9368
9369         } else {        /* all other ALU ops: and, sub, xor, add, ... */
9370
9371                 if (BPF_SRC(insn->code) == BPF_X) {
9372                         if (insn->imm != 0 || insn->off != 0) {
9373                                 verbose(env, "BPF_ALU uses reserved fields\n");
9374                                 return -EINVAL;
9375                         }
9376                         /* check src1 operand */
9377                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
9378                         if (err)
9379                                 return err;
9380                 } else {
9381                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9382                                 verbose(env, "BPF_ALU uses reserved fields\n");
9383                                 return -EINVAL;
9384                         }
9385                 }
9386
9387                 /* check src2 operand */
9388                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9389                 if (err)
9390                         return err;
9391
9392                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
9393                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
9394                         verbose(env, "div by zero\n");
9395                         return -EINVAL;
9396                 }
9397
9398                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
9399                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
9400                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
9401
9402                         if (insn->imm < 0 || insn->imm >= size) {
9403                                 verbose(env, "invalid shift %d\n", insn->imm);
9404                                 return -EINVAL;
9405                         }
9406                 }
9407
9408                 /* check dest operand */
9409                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9410                 if (err)
9411                         return err;
9412
9413                 return adjust_reg_min_max_vals(env, insn);
9414         }
9415
9416         return 0;
9417 }
9418
9419 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
9420                                    struct bpf_reg_state *dst_reg,
9421                                    enum bpf_reg_type type,
9422                                    bool range_right_open)
9423 {
9424         struct bpf_func_state *state;
9425         struct bpf_reg_state *reg;
9426         int new_range;
9427
9428         if (dst_reg->off < 0 ||
9429             (dst_reg->off == 0 && range_right_open))
9430                 /* This doesn't give us any range */
9431                 return;
9432
9433         if (dst_reg->umax_value > MAX_PACKET_OFF ||
9434             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
9435                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
9436                  * than pkt_end, but that's because it's also less than pkt.
9437                  */
9438                 return;
9439
9440         new_range = dst_reg->off;
9441         if (range_right_open)
9442                 new_range++;
9443
9444         /* Examples for register markings:
9445          *
9446          * pkt_data in dst register:
9447          *
9448          *   r2 = r3;
9449          *   r2 += 8;
9450          *   if (r2 > pkt_end) goto <handle exception>
9451          *   <access okay>
9452          *
9453          *   r2 = r3;
9454          *   r2 += 8;
9455          *   if (r2 < pkt_end) goto <access okay>
9456          *   <handle exception>
9457          *
9458          *   Where:
9459          *     r2 == dst_reg, pkt_end == src_reg
9460          *     r2=pkt(id=n,off=8,r=0)
9461          *     r3=pkt(id=n,off=0,r=0)
9462          *
9463          * pkt_data in src register:
9464          *
9465          *   r2 = r3;
9466          *   r2 += 8;
9467          *   if (pkt_end >= r2) goto <access okay>
9468          *   <handle exception>
9469          *
9470          *   r2 = r3;
9471          *   r2 += 8;
9472          *   if (pkt_end <= r2) goto <handle exception>
9473          *   <access okay>
9474          *
9475          *   Where:
9476          *     pkt_end == dst_reg, r2 == src_reg
9477          *     r2=pkt(id=n,off=8,r=0)
9478          *     r3=pkt(id=n,off=0,r=0)
9479          *
9480          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
9481          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
9482          * and [r3, r3 + 8-1) respectively is safe to access depending on
9483          * the check.
9484          */
9485
9486         /* If our ids match, then we must have the same max_value.  And we
9487          * don't care about the other reg's fixed offset, since if it's too big
9488          * the range won't allow anything.
9489          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
9490          */
9491         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9492                 if (reg->type == type && reg->id == dst_reg->id)
9493                         /* keep the maximum range already checked */
9494                         reg->range = max(reg->range, new_range);
9495         }));
9496 }
9497
9498 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
9499 {
9500         struct tnum subreg = tnum_subreg(reg->var_off);
9501         s32 sval = (s32)val;
9502
9503         switch (opcode) {
9504         case BPF_JEQ:
9505                 if (tnum_is_const(subreg))
9506                         return !!tnum_equals_const(subreg, val);
9507                 break;
9508         case BPF_JNE:
9509                 if (tnum_is_const(subreg))
9510                         return !tnum_equals_const(subreg, val);
9511                 break;
9512         case BPF_JSET:
9513                 if ((~subreg.mask & subreg.value) & val)
9514                         return 1;
9515                 if (!((subreg.mask | subreg.value) & val))
9516                         return 0;
9517                 break;
9518         case BPF_JGT:
9519                 if (reg->u32_min_value > val)
9520                         return 1;
9521                 else if (reg->u32_max_value <= val)
9522                         return 0;
9523                 break;
9524         case BPF_JSGT:
9525                 if (reg->s32_min_value > sval)
9526                         return 1;
9527                 else if (reg->s32_max_value <= sval)
9528                         return 0;
9529                 break;
9530         case BPF_JLT:
9531                 if (reg->u32_max_value < val)
9532                         return 1;
9533                 else if (reg->u32_min_value >= val)
9534                         return 0;
9535                 break;
9536         case BPF_JSLT:
9537                 if (reg->s32_max_value < sval)
9538                         return 1;
9539                 else if (reg->s32_min_value >= sval)
9540                         return 0;
9541                 break;
9542         case BPF_JGE:
9543                 if (reg->u32_min_value >= val)
9544                         return 1;
9545                 else if (reg->u32_max_value < val)
9546                         return 0;
9547                 break;
9548         case BPF_JSGE:
9549                 if (reg->s32_min_value >= sval)
9550                         return 1;
9551                 else if (reg->s32_max_value < sval)
9552                         return 0;
9553                 break;
9554         case BPF_JLE:
9555                 if (reg->u32_max_value <= val)
9556                         return 1;
9557                 else if (reg->u32_min_value > val)
9558                         return 0;
9559                 break;
9560         case BPF_JSLE:
9561                 if (reg->s32_max_value <= sval)
9562                         return 1;
9563                 else if (reg->s32_min_value > sval)
9564                         return 0;
9565                 break;
9566         }
9567
9568         return -1;
9569 }
9570
9571
9572 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
9573 {
9574         s64 sval = (s64)val;
9575
9576         switch (opcode) {
9577         case BPF_JEQ:
9578                 if (tnum_is_const(reg->var_off))
9579                         return !!tnum_equals_const(reg->var_off, val);
9580                 break;
9581         case BPF_JNE:
9582                 if (tnum_is_const(reg->var_off))
9583                         return !tnum_equals_const(reg->var_off, val);
9584                 break;
9585         case BPF_JSET:
9586                 if ((~reg->var_off.mask & reg->var_off.value) & val)
9587                         return 1;
9588                 if (!((reg->var_off.mask | reg->var_off.value) & val))
9589                         return 0;
9590                 break;
9591         case BPF_JGT:
9592                 if (reg->umin_value > val)
9593                         return 1;
9594                 else if (reg->umax_value <= val)
9595                         return 0;
9596                 break;
9597         case BPF_JSGT:
9598                 if (reg->smin_value > sval)
9599                         return 1;
9600                 else if (reg->smax_value <= sval)
9601                         return 0;
9602                 break;
9603         case BPF_JLT:
9604                 if (reg->umax_value < val)
9605                         return 1;
9606                 else if (reg->umin_value >= val)
9607                         return 0;
9608                 break;
9609         case BPF_JSLT:
9610                 if (reg->smax_value < sval)
9611                         return 1;
9612                 else if (reg->smin_value >= sval)
9613                         return 0;
9614                 break;
9615         case BPF_JGE:
9616                 if (reg->umin_value >= val)
9617                         return 1;
9618                 else if (reg->umax_value < val)
9619                         return 0;
9620                 break;
9621         case BPF_JSGE:
9622                 if (reg->smin_value >= sval)
9623                         return 1;
9624                 else if (reg->smax_value < sval)
9625                         return 0;
9626                 break;
9627         case BPF_JLE:
9628                 if (reg->umax_value <= val)
9629                         return 1;
9630                 else if (reg->umin_value > val)
9631                         return 0;
9632                 break;
9633         case BPF_JSLE:
9634                 if (reg->smax_value <= sval)
9635                         return 1;
9636                 else if (reg->smin_value > sval)
9637                         return 0;
9638                 break;
9639         }
9640
9641         return -1;
9642 }
9643
9644 /* compute branch direction of the expression "if (reg opcode val) goto target;"
9645  * and return:
9646  *  1 - branch will be taken and "goto target" will be executed
9647  *  0 - branch will not be taken and fall-through to next insn
9648  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
9649  *      range [0,10]
9650  */
9651 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
9652                            bool is_jmp32)
9653 {
9654         if (__is_pointer_value(false, reg)) {
9655                 if (!reg_type_not_null(reg->type))
9656                         return -1;
9657
9658                 /* If pointer is valid tests against zero will fail so we can
9659                  * use this to direct branch taken.
9660                  */
9661                 if (val != 0)
9662                         return -1;
9663
9664                 switch (opcode) {
9665                 case BPF_JEQ:
9666                         return 0;
9667                 case BPF_JNE:
9668                         return 1;
9669                 default:
9670                         return -1;
9671                 }
9672         }
9673
9674         if (is_jmp32)
9675                 return is_branch32_taken(reg, val, opcode);
9676         return is_branch64_taken(reg, val, opcode);
9677 }
9678
9679 static int flip_opcode(u32 opcode)
9680 {
9681         /* How can we transform "a <op> b" into "b <op> a"? */
9682         static const u8 opcode_flip[16] = {
9683                 /* these stay the same */
9684                 [BPF_JEQ  >> 4] = BPF_JEQ,
9685                 [BPF_JNE  >> 4] = BPF_JNE,
9686                 [BPF_JSET >> 4] = BPF_JSET,
9687                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
9688                 [BPF_JGE  >> 4] = BPF_JLE,
9689                 [BPF_JGT  >> 4] = BPF_JLT,
9690                 [BPF_JLE  >> 4] = BPF_JGE,
9691                 [BPF_JLT  >> 4] = BPF_JGT,
9692                 [BPF_JSGE >> 4] = BPF_JSLE,
9693                 [BPF_JSGT >> 4] = BPF_JSLT,
9694                 [BPF_JSLE >> 4] = BPF_JSGE,
9695                 [BPF_JSLT >> 4] = BPF_JSGT
9696         };
9697         return opcode_flip[opcode >> 4];
9698 }
9699
9700 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
9701                                    struct bpf_reg_state *src_reg,
9702                                    u8 opcode)
9703 {
9704         struct bpf_reg_state *pkt;
9705
9706         if (src_reg->type == PTR_TO_PACKET_END) {
9707                 pkt = dst_reg;
9708         } else if (dst_reg->type == PTR_TO_PACKET_END) {
9709                 pkt = src_reg;
9710                 opcode = flip_opcode(opcode);
9711         } else {
9712                 return -1;
9713         }
9714
9715         if (pkt->range >= 0)
9716                 return -1;
9717
9718         switch (opcode) {
9719         case BPF_JLE:
9720                 /* pkt <= pkt_end */
9721                 fallthrough;
9722         case BPF_JGT:
9723                 /* pkt > pkt_end */
9724                 if (pkt->range == BEYOND_PKT_END)
9725                         /* pkt has at last one extra byte beyond pkt_end */
9726                         return opcode == BPF_JGT;
9727                 break;
9728         case BPF_JLT:
9729                 /* pkt < pkt_end */
9730                 fallthrough;
9731         case BPF_JGE:
9732                 /* pkt >= pkt_end */
9733                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9734                         return opcode == BPF_JGE;
9735                 break;
9736         }
9737         return -1;
9738 }
9739
9740 /* Adjusts the register min/max values in the case that the dst_reg is the
9741  * variable register that we are working on, and src_reg is a constant or we're
9742  * simply doing a BPF_K check.
9743  * In JEQ/JNE cases we also adjust the var_off values.
9744  */
9745 static void reg_set_min_max(struct bpf_reg_state *true_reg,
9746                             struct bpf_reg_state *false_reg,
9747                             u64 val, u32 val32,
9748                             u8 opcode, bool is_jmp32)
9749 {
9750         struct tnum false_32off = tnum_subreg(false_reg->var_off);
9751         struct tnum false_64off = false_reg->var_off;
9752         struct tnum true_32off = tnum_subreg(true_reg->var_off);
9753         struct tnum true_64off = true_reg->var_off;
9754         s64 sval = (s64)val;
9755         s32 sval32 = (s32)val32;
9756
9757         /* If the dst_reg is a pointer, we can't learn anything about its
9758          * variable offset from the compare (unless src_reg were a pointer into
9759          * the same object, but we don't bother with that.
9760          * Since false_reg and true_reg have the same type by construction, we
9761          * only need to check one of them for pointerness.
9762          */
9763         if (__is_pointer_value(false, false_reg))
9764                 return;
9765
9766         switch (opcode) {
9767         /* JEQ/JNE comparison doesn't change the register equivalence.
9768          *
9769          * r1 = r2;
9770          * if (r1 == 42) goto label;
9771          * ...
9772          * label: // here both r1 and r2 are known to be 42.
9773          *
9774          * Hence when marking register as known preserve it's ID.
9775          */
9776         case BPF_JEQ:
9777                 if (is_jmp32) {
9778                         __mark_reg32_known(true_reg, val32);
9779                         true_32off = tnum_subreg(true_reg->var_off);
9780                 } else {
9781                         ___mark_reg_known(true_reg, val);
9782                         true_64off = true_reg->var_off;
9783                 }
9784                 break;
9785         case BPF_JNE:
9786                 if (is_jmp32) {
9787                         __mark_reg32_known(false_reg, val32);
9788                         false_32off = tnum_subreg(false_reg->var_off);
9789                 } else {
9790                         ___mark_reg_known(false_reg, val);
9791                         false_64off = false_reg->var_off;
9792                 }
9793                 break;
9794         case BPF_JSET:
9795                 if (is_jmp32) {
9796                         false_32off = tnum_and(false_32off, tnum_const(~val32));
9797                         if (is_power_of_2(val32))
9798                                 true_32off = tnum_or(true_32off,
9799                                                      tnum_const(val32));
9800                 } else {
9801                         false_64off = tnum_and(false_64off, tnum_const(~val));
9802                         if (is_power_of_2(val))
9803                                 true_64off = tnum_or(true_64off,
9804                                                      tnum_const(val));
9805                 }
9806                 break;
9807         case BPF_JGE:
9808         case BPF_JGT:
9809         {
9810                 if (is_jmp32) {
9811                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
9812                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9813
9814                         false_reg->u32_max_value = min(false_reg->u32_max_value,
9815                                                        false_umax);
9816                         true_reg->u32_min_value = max(true_reg->u32_min_value,
9817                                                       true_umin);
9818                 } else {
9819                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
9820                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9821
9822                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
9823                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
9824                 }
9825                 break;
9826         }
9827         case BPF_JSGE:
9828         case BPF_JSGT:
9829         {
9830                 if (is_jmp32) {
9831                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
9832                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
9833
9834                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9835                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9836                 } else {
9837                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
9838                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9839
9840                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
9841                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
9842                 }
9843                 break;
9844         }
9845         case BPF_JLE:
9846         case BPF_JLT:
9847         {
9848                 if (is_jmp32) {
9849                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
9850                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9851
9852                         false_reg->u32_min_value = max(false_reg->u32_min_value,
9853                                                        false_umin);
9854                         true_reg->u32_max_value = min(true_reg->u32_max_value,
9855                                                       true_umax);
9856                 } else {
9857                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
9858                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9859
9860                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
9861                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
9862                 }
9863                 break;
9864         }
9865         case BPF_JSLE:
9866         case BPF_JSLT:
9867         {
9868                 if (is_jmp32) {
9869                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
9870                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
9871
9872                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
9873                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
9874                 } else {
9875                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
9876                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
9877
9878                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
9879                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
9880                 }
9881                 break;
9882         }
9883         default:
9884                 return;
9885         }
9886
9887         if (is_jmp32) {
9888                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
9889                                              tnum_subreg(false_32off));
9890                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
9891                                             tnum_subreg(true_32off));
9892                 __reg_combine_32_into_64(false_reg);
9893                 __reg_combine_32_into_64(true_reg);
9894         } else {
9895                 false_reg->var_off = false_64off;
9896                 true_reg->var_off = true_64off;
9897                 __reg_combine_64_into_32(false_reg);
9898                 __reg_combine_64_into_32(true_reg);
9899         }
9900 }
9901
9902 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
9903  * the variable reg.
9904  */
9905 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
9906                                 struct bpf_reg_state *false_reg,
9907                                 u64 val, u32 val32,
9908                                 u8 opcode, bool is_jmp32)
9909 {
9910         opcode = flip_opcode(opcode);
9911         /* This uses zero as "not present in table"; luckily the zero opcode,
9912          * BPF_JA, can't get here.
9913          */
9914         if (opcode)
9915                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
9916 }
9917
9918 /* Regs are known to be equal, so intersect their min/max/var_off */
9919 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9920                                   struct bpf_reg_state *dst_reg)
9921 {
9922         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9923                                                         dst_reg->umin_value);
9924         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9925                                                         dst_reg->umax_value);
9926         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9927                                                         dst_reg->smin_value);
9928         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9929                                                         dst_reg->smax_value);
9930         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9931                                                              dst_reg->var_off);
9932         reg_bounds_sync(src_reg);
9933         reg_bounds_sync(dst_reg);
9934 }
9935
9936 static void reg_combine_min_max(struct bpf_reg_state *true_src,
9937                                 struct bpf_reg_state *true_dst,
9938                                 struct bpf_reg_state *false_src,
9939                                 struct bpf_reg_state *false_dst,
9940                                 u8 opcode)
9941 {
9942         switch (opcode) {
9943         case BPF_JEQ:
9944                 __reg_combine_min_max(true_src, true_dst);
9945                 break;
9946         case BPF_JNE:
9947                 __reg_combine_min_max(false_src, false_dst);
9948                 break;
9949         }
9950 }
9951
9952 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
9953                                  struct bpf_reg_state *reg, u32 id,
9954                                  bool is_null)
9955 {
9956         if (type_may_be_null(reg->type) && reg->id == id &&
9957             !WARN_ON_ONCE(!reg->id)) {
9958                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
9959                                  !tnum_equals_const(reg->var_off, 0) ||
9960                                  reg->off)) {
9961                         /* Old offset (both fixed and variable parts) should
9962                          * have been known-zero, because we don't allow pointer
9963                          * arithmetic on pointers that might be NULL. If we
9964                          * see this happening, don't convert the register.
9965                          */
9966                         return;
9967                 }
9968                 if (is_null) {
9969                         reg->type = SCALAR_VALUE;
9970                         /* We don't need id and ref_obj_id from this point
9971                          * onwards anymore, thus we should better reset it,
9972                          * so that state pruning has chances to take effect.
9973                          */
9974                         reg->id = 0;
9975                         reg->ref_obj_id = 0;
9976
9977                         return;
9978                 }
9979
9980                 mark_ptr_not_null_reg(reg);
9981
9982                 if (!reg_may_point_to_spin_lock(reg)) {
9983                         /* For not-NULL ptr, reg->ref_obj_id will be reset
9984                          * in release_reference().
9985                          *
9986                          * reg->id is still used by spin_lock ptr. Other
9987                          * than spin_lock ptr type, reg->id can be reset.
9988                          */
9989                         reg->id = 0;
9990                 }
9991         }
9992 }
9993
9994 /* The logic is similar to find_good_pkt_pointers(), both could eventually
9995  * be folded together at some point.
9996  */
9997 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
9998                                   bool is_null)
9999 {
10000         struct bpf_func_state *state = vstate->frame[vstate->curframe];
10001         struct bpf_reg_state *regs = state->regs, *reg;
10002         u32 ref_obj_id = regs[regno].ref_obj_id;
10003         u32 id = regs[regno].id;
10004
10005         if (ref_obj_id && ref_obj_id == id && is_null)
10006                 /* regs[regno] is in the " == NULL" branch.
10007                  * No one could have freed the reference state before
10008                  * doing the NULL check.
10009                  */
10010                 WARN_ON_ONCE(release_reference_state(state, id));
10011
10012         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10013                 mark_ptr_or_null_reg(state, reg, id, is_null);
10014         }));
10015 }
10016
10017 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
10018                                    struct bpf_reg_state *dst_reg,
10019                                    struct bpf_reg_state *src_reg,
10020                                    struct bpf_verifier_state *this_branch,
10021                                    struct bpf_verifier_state *other_branch)
10022 {
10023         if (BPF_SRC(insn->code) != BPF_X)
10024                 return false;
10025
10026         /* Pointers are always 64-bit. */
10027         if (BPF_CLASS(insn->code) == BPF_JMP32)
10028                 return false;
10029
10030         switch (BPF_OP(insn->code)) {
10031         case BPF_JGT:
10032                 if ((dst_reg->type == PTR_TO_PACKET &&
10033                      src_reg->type == PTR_TO_PACKET_END) ||
10034                     (dst_reg->type == PTR_TO_PACKET_META &&
10035                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10036                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
10037                         find_good_pkt_pointers(this_branch, dst_reg,
10038                                                dst_reg->type, false);
10039                         mark_pkt_end(other_branch, insn->dst_reg, true);
10040                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10041                             src_reg->type == PTR_TO_PACKET) ||
10042                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10043                             src_reg->type == PTR_TO_PACKET_META)) {
10044                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
10045                         find_good_pkt_pointers(other_branch, src_reg,
10046                                                src_reg->type, true);
10047                         mark_pkt_end(this_branch, insn->src_reg, false);
10048                 } else {
10049                         return false;
10050                 }
10051                 break;
10052         case BPF_JLT:
10053                 if ((dst_reg->type == PTR_TO_PACKET &&
10054                      src_reg->type == PTR_TO_PACKET_END) ||
10055                     (dst_reg->type == PTR_TO_PACKET_META &&
10056                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10057                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
10058                         find_good_pkt_pointers(other_branch, dst_reg,
10059                                                dst_reg->type, true);
10060                         mark_pkt_end(this_branch, insn->dst_reg, false);
10061                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10062                             src_reg->type == PTR_TO_PACKET) ||
10063                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10064                             src_reg->type == PTR_TO_PACKET_META)) {
10065                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
10066                         find_good_pkt_pointers(this_branch, src_reg,
10067                                                src_reg->type, false);
10068                         mark_pkt_end(other_branch, insn->src_reg, true);
10069                 } else {
10070                         return false;
10071                 }
10072                 break;
10073         case BPF_JGE:
10074                 if ((dst_reg->type == PTR_TO_PACKET &&
10075                      src_reg->type == PTR_TO_PACKET_END) ||
10076                     (dst_reg->type == PTR_TO_PACKET_META &&
10077                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10078                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
10079                         find_good_pkt_pointers(this_branch, dst_reg,
10080                                                dst_reg->type, true);
10081                         mark_pkt_end(other_branch, insn->dst_reg, false);
10082                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10083                             src_reg->type == PTR_TO_PACKET) ||
10084                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10085                             src_reg->type == PTR_TO_PACKET_META)) {
10086                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
10087                         find_good_pkt_pointers(other_branch, src_reg,
10088                                                src_reg->type, false);
10089                         mark_pkt_end(this_branch, insn->src_reg, true);
10090                 } else {
10091                         return false;
10092                 }
10093                 break;
10094         case BPF_JLE:
10095                 if ((dst_reg->type == PTR_TO_PACKET &&
10096                      src_reg->type == PTR_TO_PACKET_END) ||
10097                     (dst_reg->type == PTR_TO_PACKET_META &&
10098                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10099                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
10100                         find_good_pkt_pointers(other_branch, dst_reg,
10101                                                dst_reg->type, false);
10102                         mark_pkt_end(this_branch, insn->dst_reg, true);
10103                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10104                             src_reg->type == PTR_TO_PACKET) ||
10105                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10106                             src_reg->type == PTR_TO_PACKET_META)) {
10107                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
10108                         find_good_pkt_pointers(this_branch, src_reg,
10109                                                src_reg->type, true);
10110                         mark_pkt_end(other_branch, insn->src_reg, false);
10111                 } else {
10112                         return false;
10113                 }
10114                 break;
10115         default:
10116                 return false;
10117         }
10118
10119         return true;
10120 }
10121
10122 static void find_equal_scalars(struct bpf_verifier_state *vstate,
10123                                struct bpf_reg_state *known_reg)
10124 {
10125         struct bpf_func_state *state;
10126         struct bpf_reg_state *reg;
10127
10128         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10129                 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10130                         *reg = *known_reg;
10131         }));
10132 }
10133
10134 static int check_cond_jmp_op(struct bpf_verifier_env *env,
10135                              struct bpf_insn *insn, int *insn_idx)
10136 {
10137         struct bpf_verifier_state *this_branch = env->cur_state;
10138         struct bpf_verifier_state *other_branch;
10139         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
10140         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
10141         u8 opcode = BPF_OP(insn->code);
10142         bool is_jmp32;
10143         int pred = -1;
10144         int err;
10145
10146         /* Only conditional jumps are expected to reach here. */
10147         if (opcode == BPF_JA || opcode > BPF_JSLE) {
10148                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
10149                 return -EINVAL;
10150         }
10151
10152         if (BPF_SRC(insn->code) == BPF_X) {
10153                 if (insn->imm != 0) {
10154                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10155                         return -EINVAL;
10156                 }
10157
10158                 /* check src1 operand */
10159                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10160                 if (err)
10161                         return err;
10162
10163                 if (is_pointer_value(env, insn->src_reg)) {
10164                         verbose(env, "R%d pointer comparison prohibited\n",
10165                                 insn->src_reg);
10166                         return -EACCES;
10167                 }
10168                 src_reg = &regs[insn->src_reg];
10169         } else {
10170                 if (insn->src_reg != BPF_REG_0) {
10171                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10172                         return -EINVAL;
10173                 }
10174         }
10175
10176         /* check src2 operand */
10177         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10178         if (err)
10179                 return err;
10180
10181         dst_reg = &regs[insn->dst_reg];
10182         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
10183
10184         if (BPF_SRC(insn->code) == BPF_K) {
10185                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
10186         } else if (src_reg->type == SCALAR_VALUE &&
10187                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
10188                 pred = is_branch_taken(dst_reg,
10189                                        tnum_subreg(src_reg->var_off).value,
10190                                        opcode,
10191                                        is_jmp32);
10192         } else if (src_reg->type == SCALAR_VALUE &&
10193                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
10194                 pred = is_branch_taken(dst_reg,
10195                                        src_reg->var_off.value,
10196                                        opcode,
10197                                        is_jmp32);
10198         } else if (reg_is_pkt_pointer_any(dst_reg) &&
10199                    reg_is_pkt_pointer_any(src_reg) &&
10200                    !is_jmp32) {
10201                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
10202         }
10203
10204         if (pred >= 0) {
10205                 /* If we get here with a dst_reg pointer type it is because
10206                  * above is_branch_taken() special cased the 0 comparison.
10207                  */
10208                 if (!__is_pointer_value(false, dst_reg))
10209                         err = mark_chain_precision(env, insn->dst_reg);
10210                 if (BPF_SRC(insn->code) == BPF_X && !err &&
10211                     !__is_pointer_value(false, src_reg))
10212                         err = mark_chain_precision(env, insn->src_reg);
10213                 if (err)
10214                         return err;
10215         }
10216
10217         if (pred == 1) {
10218                 /* Only follow the goto, ignore fall-through. If needed, push
10219                  * the fall-through branch for simulation under speculative
10220                  * execution.
10221                  */
10222                 if (!env->bypass_spec_v1 &&
10223                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
10224                                                *insn_idx))
10225                         return -EFAULT;
10226                 *insn_idx += insn->off;
10227                 return 0;
10228         } else if (pred == 0) {
10229                 /* Only follow the fall-through branch, since that's where the
10230                  * program will go. If needed, push the goto branch for
10231                  * simulation under speculative execution.
10232                  */
10233                 if (!env->bypass_spec_v1 &&
10234                     !sanitize_speculative_path(env, insn,
10235                                                *insn_idx + insn->off + 1,
10236                                                *insn_idx))
10237                         return -EFAULT;
10238                 return 0;
10239         }
10240
10241         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
10242                                   false);
10243         if (!other_branch)
10244                 return -EFAULT;
10245         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
10246
10247         /* detect if we are comparing against a constant value so we can adjust
10248          * our min/max values for our dst register.
10249          * this is only legit if both are scalars (or pointers to the same
10250          * object, I suppose, but we don't support that right now), because
10251          * otherwise the different base pointers mean the offsets aren't
10252          * comparable.
10253          */
10254         if (BPF_SRC(insn->code) == BPF_X) {
10255                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
10256
10257                 if (dst_reg->type == SCALAR_VALUE &&
10258                     src_reg->type == SCALAR_VALUE) {
10259                         if (tnum_is_const(src_reg->var_off) ||
10260                             (is_jmp32 &&
10261                              tnum_is_const(tnum_subreg(src_reg->var_off))))
10262                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10263                                                 dst_reg,
10264                                                 src_reg->var_off.value,
10265                                                 tnum_subreg(src_reg->var_off).value,
10266                                                 opcode, is_jmp32);
10267                         else if (tnum_is_const(dst_reg->var_off) ||
10268                                  (is_jmp32 &&
10269                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
10270                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
10271                                                     src_reg,
10272                                                     dst_reg->var_off.value,
10273                                                     tnum_subreg(dst_reg->var_off).value,
10274                                                     opcode, is_jmp32);
10275                         else if (!is_jmp32 &&
10276                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
10277                                 /* Comparing for equality, we can combine knowledge */
10278                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
10279                                                     &other_branch_regs[insn->dst_reg],
10280                                                     src_reg, dst_reg, opcode);
10281                         if (src_reg->id &&
10282                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
10283                                 find_equal_scalars(this_branch, src_reg);
10284                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
10285                         }
10286
10287                 }
10288         } else if (dst_reg->type == SCALAR_VALUE) {
10289                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10290                                         dst_reg, insn->imm, (u32)insn->imm,
10291                                         opcode, is_jmp32);
10292         }
10293
10294         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
10295             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
10296                 find_equal_scalars(this_branch, dst_reg);
10297                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
10298         }
10299
10300         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
10301          * NOTE: these optimizations below are related with pointer comparison
10302          *       which will never be JMP32.
10303          */
10304         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
10305             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
10306             type_may_be_null(dst_reg->type)) {
10307                 /* Mark all identical registers in each branch as either
10308                  * safe or unknown depending R == 0 or R != 0 conditional.
10309                  */
10310                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
10311                                       opcode == BPF_JNE);
10312                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
10313                                       opcode == BPF_JEQ);
10314         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
10315                                            this_branch, other_branch) &&
10316                    is_pointer_value(env, insn->dst_reg)) {
10317                 verbose(env, "R%d pointer comparison prohibited\n",
10318                         insn->dst_reg);
10319                 return -EACCES;
10320         }
10321         if (env->log.level & BPF_LOG_LEVEL)
10322                 print_insn_state(env, this_branch->frame[this_branch->curframe]);
10323         return 0;
10324 }
10325
10326 /* verify BPF_LD_IMM64 instruction */
10327 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
10328 {
10329         struct bpf_insn_aux_data *aux = cur_aux(env);
10330         struct bpf_reg_state *regs = cur_regs(env);
10331         struct bpf_reg_state *dst_reg;
10332         struct bpf_map *map;
10333         int err;
10334
10335         if (BPF_SIZE(insn->code) != BPF_DW) {
10336                 verbose(env, "invalid BPF_LD_IMM insn\n");
10337                 return -EINVAL;
10338         }
10339         if (insn->off != 0) {
10340                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
10341                 return -EINVAL;
10342         }
10343
10344         err = check_reg_arg(env, insn->dst_reg, DST_OP);
10345         if (err)
10346                 return err;
10347
10348         dst_reg = &regs[insn->dst_reg];
10349         if (insn->src_reg == 0) {
10350                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
10351
10352                 dst_reg->type = SCALAR_VALUE;
10353                 __mark_reg_known(&regs[insn->dst_reg], imm);
10354                 return 0;
10355         }
10356
10357         /* All special src_reg cases are listed below. From this point onwards
10358          * we either succeed and assign a corresponding dst_reg->type after
10359          * zeroing the offset, or fail and reject the program.
10360          */
10361         mark_reg_known_zero(env, regs, insn->dst_reg);
10362
10363         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
10364                 dst_reg->type = aux->btf_var.reg_type;
10365                 switch (base_type(dst_reg->type)) {
10366                 case PTR_TO_MEM:
10367                         dst_reg->mem_size = aux->btf_var.mem_size;
10368                         break;
10369                 case PTR_TO_BTF_ID:
10370                         dst_reg->btf = aux->btf_var.btf;
10371                         dst_reg->btf_id = aux->btf_var.btf_id;
10372                         break;
10373                 default:
10374                         verbose(env, "bpf verifier is misconfigured\n");
10375                         return -EFAULT;
10376                 }
10377                 return 0;
10378         }
10379
10380         if (insn->src_reg == BPF_PSEUDO_FUNC) {
10381                 struct bpf_prog_aux *aux = env->prog->aux;
10382                 u32 subprogno = find_subprog(env,
10383                                              env->insn_idx + insn->imm + 1);
10384
10385                 if (!aux->func_info) {
10386                         verbose(env, "missing btf func_info\n");
10387                         return -EINVAL;
10388                 }
10389                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
10390                         verbose(env, "callback function not static\n");
10391                         return -EINVAL;
10392                 }
10393
10394                 dst_reg->type = PTR_TO_FUNC;
10395                 dst_reg->subprogno = subprogno;
10396                 return 0;
10397         }
10398
10399         map = env->used_maps[aux->map_index];
10400         dst_reg->map_ptr = map;
10401
10402         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
10403             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
10404                 dst_reg->type = PTR_TO_MAP_VALUE;
10405                 dst_reg->off = aux->map_off;
10406                 if (map_value_has_spin_lock(map))
10407                         dst_reg->id = ++env->id_gen;
10408         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
10409                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
10410                 dst_reg->type = CONST_PTR_TO_MAP;
10411         } else {
10412                 verbose(env, "bpf verifier is misconfigured\n");
10413                 return -EINVAL;
10414         }
10415
10416         return 0;
10417 }
10418
10419 static bool may_access_skb(enum bpf_prog_type type)
10420 {
10421         switch (type) {
10422         case BPF_PROG_TYPE_SOCKET_FILTER:
10423         case BPF_PROG_TYPE_SCHED_CLS:
10424         case BPF_PROG_TYPE_SCHED_ACT:
10425                 return true;
10426         default:
10427                 return false;
10428         }
10429 }
10430
10431 /* verify safety of LD_ABS|LD_IND instructions:
10432  * - they can only appear in the programs where ctx == skb
10433  * - since they are wrappers of function calls, they scratch R1-R5 registers,
10434  *   preserve R6-R9, and store return value into R0
10435  *
10436  * Implicit input:
10437  *   ctx == skb == R6 == CTX
10438  *
10439  * Explicit input:
10440  *   SRC == any register
10441  *   IMM == 32-bit immediate
10442  *
10443  * Output:
10444  *   R0 - 8/16/32-bit skb data converted to cpu endianness
10445  */
10446 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
10447 {
10448         struct bpf_reg_state *regs = cur_regs(env);
10449         static const int ctx_reg = BPF_REG_6;
10450         u8 mode = BPF_MODE(insn->code);
10451         int i, err;
10452
10453         if (!may_access_skb(resolve_prog_type(env->prog))) {
10454                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
10455                 return -EINVAL;
10456         }
10457
10458         if (!env->ops->gen_ld_abs) {
10459                 verbose(env, "bpf verifier is misconfigured\n");
10460                 return -EINVAL;
10461         }
10462
10463         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
10464             BPF_SIZE(insn->code) == BPF_DW ||
10465             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
10466                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
10467                 return -EINVAL;
10468         }
10469
10470         /* check whether implicit source operand (register R6) is readable */
10471         err = check_reg_arg(env, ctx_reg, SRC_OP);
10472         if (err)
10473                 return err;
10474
10475         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
10476          * gen_ld_abs() may terminate the program at runtime, leading to
10477          * reference leak.
10478          */
10479         err = check_reference_leak(env);
10480         if (err) {
10481                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
10482                 return err;
10483         }
10484
10485         if (env->cur_state->active_spin_lock) {
10486                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
10487                 return -EINVAL;
10488         }
10489
10490         if (regs[ctx_reg].type != PTR_TO_CTX) {
10491                 verbose(env,
10492                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
10493                 return -EINVAL;
10494         }
10495
10496         if (mode == BPF_IND) {
10497                 /* check explicit source operand */
10498                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10499                 if (err)
10500                         return err;
10501         }
10502
10503         err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
10504         if (err < 0)
10505                 return err;
10506
10507         /* reset caller saved regs to unreadable */
10508         for (i = 0; i < CALLER_SAVED_REGS; i++) {
10509                 mark_reg_not_init(env, regs, caller_saved[i]);
10510                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10511         }
10512
10513         /* mark destination R0 register as readable, since it contains
10514          * the value fetched from the packet.
10515          * Already marked as written above.
10516          */
10517         mark_reg_unknown(env, regs, BPF_REG_0);
10518         /* ld_abs load up to 32-bit skb data. */
10519         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
10520         return 0;
10521 }
10522
10523 static int check_return_code(struct bpf_verifier_env *env)
10524 {
10525         struct tnum enforce_attach_type_range = tnum_unknown;
10526         const struct bpf_prog *prog = env->prog;
10527         struct bpf_reg_state *reg;
10528         struct tnum range = tnum_range(0, 1);
10529         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10530         int err;
10531         struct bpf_func_state *frame = env->cur_state->frame[0];
10532         const bool is_subprog = frame->subprogno;
10533
10534         /* LSM and struct_ops func-ptr's return type could be "void" */
10535         if (!is_subprog) {
10536                 switch (prog_type) {
10537                 case BPF_PROG_TYPE_LSM:
10538                         if (prog->expected_attach_type == BPF_LSM_CGROUP)
10539                                 /* See below, can be 0 or 0-1 depending on hook. */
10540                                 break;
10541                         fallthrough;
10542                 case BPF_PROG_TYPE_STRUCT_OPS:
10543                         if (!prog->aux->attach_func_proto->type)
10544                                 return 0;
10545                         break;
10546                 default:
10547                         break;
10548                 }
10549         }
10550
10551         /* eBPF calling convention is such that R0 is used
10552          * to return the value from eBPF program.
10553          * Make sure that it's readable at this time
10554          * of bpf_exit, which means that program wrote
10555          * something into it earlier
10556          */
10557         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
10558         if (err)
10559                 return err;
10560
10561         if (is_pointer_value(env, BPF_REG_0)) {
10562                 verbose(env, "R0 leaks addr as return value\n");
10563                 return -EACCES;
10564         }
10565
10566         reg = cur_regs(env) + BPF_REG_0;
10567
10568         if (frame->in_async_callback_fn) {
10569                 /* enforce return zero from async callbacks like timer */
10570                 if (reg->type != SCALAR_VALUE) {
10571                         verbose(env, "In async callback the register R0 is not a known value (%s)\n",
10572                                 reg_type_str(env, reg->type));
10573                         return -EINVAL;
10574                 }
10575
10576                 if (!tnum_in(tnum_const(0), reg->var_off)) {
10577                         verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
10578                         return -EINVAL;
10579                 }
10580                 return 0;
10581         }
10582
10583         if (is_subprog) {
10584                 if (reg->type != SCALAR_VALUE) {
10585                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
10586                                 reg_type_str(env, reg->type));
10587                         return -EINVAL;
10588                 }
10589                 return 0;
10590         }
10591
10592         switch (prog_type) {
10593         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10594                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
10595                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
10596                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
10597                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
10598                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
10599                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
10600                         range = tnum_range(1, 1);
10601                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
10602                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
10603                         range = tnum_range(0, 3);
10604                 break;
10605         case BPF_PROG_TYPE_CGROUP_SKB:
10606                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
10607                         range = tnum_range(0, 3);
10608                         enforce_attach_type_range = tnum_range(2, 3);
10609                 }
10610                 break;
10611         case BPF_PROG_TYPE_CGROUP_SOCK:
10612         case BPF_PROG_TYPE_SOCK_OPS:
10613         case BPF_PROG_TYPE_CGROUP_DEVICE:
10614         case BPF_PROG_TYPE_CGROUP_SYSCTL:
10615         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10616                 break;
10617         case BPF_PROG_TYPE_RAW_TRACEPOINT:
10618                 if (!env->prog->aux->attach_btf_id)
10619                         return 0;
10620                 range = tnum_const(0);
10621                 break;
10622         case BPF_PROG_TYPE_TRACING:
10623                 switch (env->prog->expected_attach_type) {
10624                 case BPF_TRACE_FENTRY:
10625                 case BPF_TRACE_FEXIT:
10626                         range = tnum_const(0);
10627                         break;
10628                 case BPF_TRACE_RAW_TP:
10629                 case BPF_MODIFY_RETURN:
10630                         return 0;
10631                 case BPF_TRACE_ITER:
10632                         break;
10633                 default:
10634                         return -ENOTSUPP;
10635                 }
10636                 break;
10637         case BPF_PROG_TYPE_SK_LOOKUP:
10638                 range = tnum_range(SK_DROP, SK_PASS);
10639                 break;
10640
10641         case BPF_PROG_TYPE_LSM:
10642                 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
10643                         /* Regular BPF_PROG_TYPE_LSM programs can return
10644                          * any value.
10645                          */
10646                         return 0;
10647                 }
10648                 if (!env->prog->aux->attach_func_proto->type) {
10649                         /* Make sure programs that attach to void
10650                          * hooks don't try to modify return value.
10651                          */
10652                         range = tnum_range(1, 1);
10653                 }
10654                 break;
10655
10656         case BPF_PROG_TYPE_EXT:
10657                 /* freplace program can return anything as its return value
10658                  * depends on the to-be-replaced kernel func or bpf program.
10659                  */
10660         default:
10661                 return 0;
10662         }
10663
10664         if (reg->type != SCALAR_VALUE) {
10665                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
10666                         reg_type_str(env, reg->type));
10667                 return -EINVAL;
10668         }
10669
10670         if (!tnum_in(range, reg->var_off)) {
10671                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
10672                 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
10673                     prog_type == BPF_PROG_TYPE_LSM &&
10674                     !prog->aux->attach_func_proto->type)
10675                         verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10676                 return -EINVAL;
10677         }
10678
10679         if (!tnum_is_unknown(enforce_attach_type_range) &&
10680             tnum_in(enforce_attach_type_range, reg->var_off))
10681                 env->prog->enforce_expected_attach_type = 1;
10682         return 0;
10683 }
10684
10685 /* non-recursive DFS pseudo code
10686  * 1  procedure DFS-iterative(G,v):
10687  * 2      label v as discovered
10688  * 3      let S be a stack
10689  * 4      S.push(v)
10690  * 5      while S is not empty
10691  * 6            t <- S.pop()
10692  * 7            if t is what we're looking for:
10693  * 8                return t
10694  * 9            for all edges e in G.adjacentEdges(t) do
10695  * 10               if edge e is already labelled
10696  * 11                   continue with the next edge
10697  * 12               w <- G.adjacentVertex(t,e)
10698  * 13               if vertex w is not discovered and not explored
10699  * 14                   label e as tree-edge
10700  * 15                   label w as discovered
10701  * 16                   S.push(w)
10702  * 17                   continue at 5
10703  * 18               else if vertex w is discovered
10704  * 19                   label e as back-edge
10705  * 20               else
10706  * 21                   // vertex w is explored
10707  * 22                   label e as forward- or cross-edge
10708  * 23           label t as explored
10709  * 24           S.pop()
10710  *
10711  * convention:
10712  * 0x10 - discovered
10713  * 0x11 - discovered and fall-through edge labelled
10714  * 0x12 - discovered and fall-through and branch edges labelled
10715  * 0x20 - explored
10716  */
10717
10718 enum {
10719         DISCOVERED = 0x10,
10720         EXPLORED = 0x20,
10721         FALLTHROUGH = 1,
10722         BRANCH = 2,
10723 };
10724
10725 static u32 state_htab_size(struct bpf_verifier_env *env)
10726 {
10727         return env->prog->len;
10728 }
10729
10730 static struct bpf_verifier_state_list **explored_state(
10731                                         struct bpf_verifier_env *env,
10732                                         int idx)
10733 {
10734         struct bpf_verifier_state *cur = env->cur_state;
10735         struct bpf_func_state *state = cur->frame[cur->curframe];
10736
10737         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
10738 }
10739
10740 static void init_explored_state(struct bpf_verifier_env *env, int idx)
10741 {
10742         env->insn_aux_data[idx].prune_point = true;
10743 }
10744
10745 enum {
10746         DONE_EXPLORING = 0,
10747         KEEP_EXPLORING = 1,
10748 };
10749
10750 /* t, w, e - match pseudo-code above:
10751  * t - index of current instruction
10752  * w - next instruction
10753  * e - edge
10754  */
10755 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10756                      bool loop_ok)
10757 {
10758         int *insn_stack = env->cfg.insn_stack;
10759         int *insn_state = env->cfg.insn_state;
10760
10761         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
10762                 return DONE_EXPLORING;
10763
10764         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
10765                 return DONE_EXPLORING;
10766
10767         if (w < 0 || w >= env->prog->len) {
10768                 verbose_linfo(env, t, "%d: ", t);
10769                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
10770                 return -EINVAL;
10771         }
10772
10773         if (e == BRANCH)
10774                 /* mark branch target for state pruning */
10775                 init_explored_state(env, w);
10776
10777         if (insn_state[w] == 0) {
10778                 /* tree-edge */
10779                 insn_state[t] = DISCOVERED | e;
10780                 insn_state[w] = DISCOVERED;
10781                 if (env->cfg.cur_stack >= env->prog->len)
10782                         return -E2BIG;
10783                 insn_stack[env->cfg.cur_stack++] = w;
10784                 return KEEP_EXPLORING;
10785         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10786                 if (loop_ok && env->bpf_capable)
10787                         return DONE_EXPLORING;
10788                 verbose_linfo(env, t, "%d: ", t);
10789                 verbose_linfo(env, w, "%d: ", w);
10790                 verbose(env, "back-edge from insn %d to %d\n", t, w);
10791                 return -EINVAL;
10792         } else if (insn_state[w] == EXPLORED) {
10793                 /* forward- or cross-edge */
10794                 insn_state[t] = DISCOVERED | e;
10795         } else {
10796                 verbose(env, "insn state internal bug\n");
10797                 return -EFAULT;
10798         }
10799         return DONE_EXPLORING;
10800 }
10801
10802 static int visit_func_call_insn(int t, int insn_cnt,
10803                                 struct bpf_insn *insns,
10804                                 struct bpf_verifier_env *env,
10805                                 bool visit_callee)
10806 {
10807         int ret;
10808
10809         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10810         if (ret)
10811                 return ret;
10812
10813         if (t + 1 < insn_cnt)
10814                 init_explored_state(env, t + 1);
10815         if (visit_callee) {
10816                 init_explored_state(env, t);
10817                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10818                                 /* It's ok to allow recursion from CFG point of
10819                                  * view. __check_func_call() will do the actual
10820                                  * check.
10821                                  */
10822                                 bpf_pseudo_func(insns + t));
10823         }
10824         return ret;
10825 }
10826
10827 /* Visits the instruction at index t and returns one of the following:
10828  *  < 0 - an error occurred
10829  *  DONE_EXPLORING - the instruction was fully explored
10830  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
10831  */
10832 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10833 {
10834         struct bpf_insn *insns = env->prog->insnsi;
10835         int ret;
10836
10837         if (bpf_pseudo_func(insns + t))
10838                 return visit_func_call_insn(t, insn_cnt, insns, env, true);
10839
10840         /* All non-branch instructions have a single fall-through edge. */
10841         if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10842             BPF_CLASS(insns[t].code) != BPF_JMP32)
10843                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
10844
10845         switch (BPF_OP(insns[t].code)) {
10846         case BPF_EXIT:
10847                 return DONE_EXPLORING;
10848
10849         case BPF_CALL:
10850                 if (insns[t].imm == BPF_FUNC_timer_set_callback)
10851                         /* Mark this call insn to trigger is_state_visited() check
10852                          * before call itself is processed by __check_func_call().
10853                          * Otherwise new async state will be pushed for further
10854                          * exploration.
10855                          */
10856                         init_explored_state(env, t);
10857                 return visit_func_call_insn(t, insn_cnt, insns, env,
10858                                             insns[t].src_reg == BPF_PSEUDO_CALL);
10859
10860         case BPF_JA:
10861                 if (BPF_SRC(insns[t].code) != BPF_K)
10862                         return -EINVAL;
10863
10864                 /* unconditional jump with single edge */
10865                 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10866                                 true);
10867                 if (ret)
10868                         return ret;
10869
10870                 /* unconditional jmp is not a good pruning point,
10871                  * but it's marked, since backtracking needs
10872                  * to record jmp history in is_state_visited().
10873                  */
10874                 init_explored_state(env, t + insns[t].off + 1);
10875                 /* tell verifier to check for equivalent states
10876                  * after every call and jump
10877                  */
10878                 if (t + 1 < insn_cnt)
10879                         init_explored_state(env, t + 1);
10880
10881                 return ret;
10882
10883         default:
10884                 /* conditional jump with two edges */
10885                 init_explored_state(env, t);
10886                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
10887                 if (ret)
10888                         return ret;
10889
10890                 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
10891         }
10892 }
10893
10894 /* non-recursive depth-first-search to detect loops in BPF program
10895  * loop == back-edge in directed graph
10896  */
10897 static int check_cfg(struct bpf_verifier_env *env)
10898 {
10899         int insn_cnt = env->prog->len;
10900         int *insn_stack, *insn_state;
10901         int ret = 0;
10902         int i;
10903
10904         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10905         if (!insn_state)
10906                 return -ENOMEM;
10907
10908         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10909         if (!insn_stack) {
10910                 kvfree(insn_state);
10911                 return -ENOMEM;
10912         }
10913
10914         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10915         insn_stack[0] = 0; /* 0 is the first instruction */
10916         env->cfg.cur_stack = 1;
10917
10918         while (env->cfg.cur_stack > 0) {
10919                 int t = insn_stack[env->cfg.cur_stack - 1];
10920
10921                 ret = visit_insn(t, insn_cnt, env);
10922                 switch (ret) {
10923                 case DONE_EXPLORING:
10924                         insn_state[t] = EXPLORED;
10925                         env->cfg.cur_stack--;
10926                         break;
10927                 case KEEP_EXPLORING:
10928                         break;
10929                 default:
10930                         if (ret > 0) {
10931                                 verbose(env, "visit_insn internal bug\n");
10932                                 ret = -EFAULT;
10933                         }
10934                         goto err_free;
10935                 }
10936         }
10937
10938         if (env->cfg.cur_stack < 0) {
10939                 verbose(env, "pop stack internal bug\n");
10940                 ret = -EFAULT;
10941                 goto err_free;
10942         }
10943
10944         for (i = 0; i < insn_cnt; i++) {
10945                 if (insn_state[i] != EXPLORED) {
10946                         verbose(env, "unreachable insn %d\n", i);
10947                         ret = -EINVAL;
10948                         goto err_free;
10949                 }
10950         }
10951         ret = 0; /* cfg looks good */
10952
10953 err_free:
10954         kvfree(insn_state);
10955         kvfree(insn_stack);
10956         env->cfg.insn_state = env->cfg.insn_stack = NULL;
10957         return ret;
10958 }
10959
10960 static int check_abnormal_return(struct bpf_verifier_env *env)
10961 {
10962         int i;
10963
10964         for (i = 1; i < env->subprog_cnt; i++) {
10965                 if (env->subprog_info[i].has_ld_abs) {
10966                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
10967                         return -EINVAL;
10968                 }
10969                 if (env->subprog_info[i].has_tail_call) {
10970                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
10971                         return -EINVAL;
10972                 }
10973         }
10974         return 0;
10975 }
10976
10977 /* The minimum supported BTF func info size */
10978 #define MIN_BPF_FUNCINFO_SIZE   8
10979 #define MAX_FUNCINFO_REC_SIZE   252
10980
10981 static int check_btf_func(struct bpf_verifier_env *env,
10982                           const union bpf_attr *attr,
10983                           bpfptr_t uattr)
10984 {
10985         const struct btf_type *type, *func_proto, *ret_type;
10986         u32 i, nfuncs, urec_size, min_size;
10987         u32 krec_size = sizeof(struct bpf_func_info);
10988         struct bpf_func_info *krecord;
10989         struct bpf_func_info_aux *info_aux = NULL;
10990         struct bpf_prog *prog;
10991         const struct btf *btf;
10992         bpfptr_t urecord;
10993         u32 prev_offset = 0;
10994         bool scalar_return;
10995         int ret = -ENOMEM;
10996
10997         nfuncs = attr->func_info_cnt;
10998         if (!nfuncs) {
10999                 if (check_abnormal_return(env))
11000                         return -EINVAL;
11001                 return 0;
11002         }
11003
11004         if (nfuncs != env->subprog_cnt) {
11005                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
11006                 return -EINVAL;
11007         }
11008
11009         urec_size = attr->func_info_rec_size;
11010         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
11011             urec_size > MAX_FUNCINFO_REC_SIZE ||
11012             urec_size % sizeof(u32)) {
11013                 verbose(env, "invalid func info rec size %u\n", urec_size);
11014                 return -EINVAL;
11015         }
11016
11017         prog = env->prog;
11018         btf = prog->aux->btf;
11019
11020         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
11021         min_size = min_t(u32, krec_size, urec_size);
11022
11023         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
11024         if (!krecord)
11025                 return -ENOMEM;
11026         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
11027         if (!info_aux)
11028                 goto err_free;
11029
11030         for (i = 0; i < nfuncs; i++) {
11031                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
11032                 if (ret) {
11033                         if (ret == -E2BIG) {
11034                                 verbose(env, "nonzero tailing record in func info");
11035                                 /* set the size kernel expects so loader can zero
11036                                  * out the rest of the record.
11037                                  */
11038                                 if (copy_to_bpfptr_offset(uattr,
11039                                                           offsetof(union bpf_attr, func_info_rec_size),
11040                                                           &min_size, sizeof(min_size)))
11041                                         ret = -EFAULT;
11042                         }
11043                         goto err_free;
11044                 }
11045
11046                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
11047                         ret = -EFAULT;
11048                         goto err_free;
11049                 }
11050
11051                 /* check insn_off */
11052                 ret = -EINVAL;
11053                 if (i == 0) {
11054                         if (krecord[i].insn_off) {
11055                                 verbose(env,
11056                                         "nonzero insn_off %u for the first func info record",
11057                                         krecord[i].insn_off);
11058                                 goto err_free;
11059                         }
11060                 } else if (krecord[i].insn_off <= prev_offset) {
11061                         verbose(env,
11062                                 "same or smaller insn offset (%u) than previous func info record (%u)",
11063                                 krecord[i].insn_off, prev_offset);
11064                         goto err_free;
11065                 }
11066
11067                 if (env->subprog_info[i].start != krecord[i].insn_off) {
11068                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
11069                         goto err_free;
11070                 }
11071
11072                 /* check type_id */
11073                 type = btf_type_by_id(btf, krecord[i].type_id);
11074                 if (!type || !btf_type_is_func(type)) {
11075                         verbose(env, "invalid type id %d in func info",
11076                                 krecord[i].type_id);
11077                         goto err_free;
11078                 }
11079                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
11080
11081                 func_proto = btf_type_by_id(btf, type->type);
11082                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
11083                         /* btf_func_check() already verified it during BTF load */
11084                         goto err_free;
11085                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
11086                 scalar_return =
11087                         btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
11088                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
11089                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
11090                         goto err_free;
11091                 }
11092                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
11093                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
11094                         goto err_free;
11095                 }
11096
11097                 prev_offset = krecord[i].insn_off;
11098                 bpfptr_add(&urecord, urec_size);
11099         }
11100
11101         prog->aux->func_info = krecord;
11102         prog->aux->func_info_cnt = nfuncs;
11103         prog->aux->func_info_aux = info_aux;
11104         return 0;
11105
11106 err_free:
11107         kvfree(krecord);
11108         kfree(info_aux);
11109         return ret;
11110 }
11111
11112 static void adjust_btf_func(struct bpf_verifier_env *env)
11113 {
11114         struct bpf_prog_aux *aux = env->prog->aux;
11115         int i;
11116
11117         if (!aux->func_info)
11118                 return;
11119
11120         for (i = 0; i < env->subprog_cnt; i++)
11121                 aux->func_info[i].insn_off = env->subprog_info[i].start;
11122 }
11123
11124 #define MIN_BPF_LINEINFO_SIZE   offsetofend(struct bpf_line_info, line_col)
11125 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
11126
11127 static int check_btf_line(struct bpf_verifier_env *env,
11128                           const union bpf_attr *attr,
11129                           bpfptr_t uattr)
11130 {
11131         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
11132         struct bpf_subprog_info *sub;
11133         struct bpf_line_info *linfo;
11134         struct bpf_prog *prog;
11135         const struct btf *btf;
11136         bpfptr_t ulinfo;
11137         int err;
11138
11139         nr_linfo = attr->line_info_cnt;
11140         if (!nr_linfo)
11141                 return 0;
11142         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
11143                 return -EINVAL;
11144
11145         rec_size = attr->line_info_rec_size;
11146         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
11147             rec_size > MAX_LINEINFO_REC_SIZE ||
11148             rec_size & (sizeof(u32) - 1))
11149                 return -EINVAL;
11150
11151         /* Need to zero it in case the userspace may
11152          * pass in a smaller bpf_line_info object.
11153          */
11154         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
11155                          GFP_KERNEL | __GFP_NOWARN);
11156         if (!linfo)
11157                 return -ENOMEM;
11158
11159         prog = env->prog;
11160         btf = prog->aux->btf;
11161
11162         s = 0;
11163         sub = env->subprog_info;
11164         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
11165         expected_size = sizeof(struct bpf_line_info);
11166         ncopy = min_t(u32, expected_size, rec_size);
11167         for (i = 0; i < nr_linfo; i++) {
11168                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
11169                 if (err) {
11170                         if (err == -E2BIG) {
11171                                 verbose(env, "nonzero tailing record in line_info");
11172                                 if (copy_to_bpfptr_offset(uattr,
11173                                                           offsetof(union bpf_attr, line_info_rec_size),
11174                                                           &expected_size, sizeof(expected_size)))
11175                                         err = -EFAULT;
11176                         }
11177                         goto err_free;
11178                 }
11179
11180                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
11181                         err = -EFAULT;
11182                         goto err_free;
11183                 }
11184
11185                 /*
11186                  * Check insn_off to ensure
11187                  * 1) strictly increasing AND
11188                  * 2) bounded by prog->len
11189                  *
11190                  * The linfo[0].insn_off == 0 check logically falls into
11191                  * the later "missing bpf_line_info for func..." case
11192                  * because the first linfo[0].insn_off must be the
11193                  * first sub also and the first sub must have
11194                  * subprog_info[0].start == 0.
11195                  */
11196                 if ((i && linfo[i].insn_off <= prev_offset) ||
11197                     linfo[i].insn_off >= prog->len) {
11198                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
11199                                 i, linfo[i].insn_off, prev_offset,
11200                                 prog->len);
11201                         err = -EINVAL;
11202                         goto err_free;
11203                 }
11204
11205                 if (!prog->insnsi[linfo[i].insn_off].code) {
11206                         verbose(env,
11207                                 "Invalid insn code at line_info[%u].insn_off\n",
11208                                 i);
11209                         err = -EINVAL;
11210                         goto err_free;
11211                 }
11212
11213                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
11214                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
11215                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
11216                         err = -EINVAL;
11217                         goto err_free;
11218                 }
11219
11220                 if (s != env->subprog_cnt) {
11221                         if (linfo[i].insn_off == sub[s].start) {
11222                                 sub[s].linfo_idx = i;
11223                                 s++;
11224                         } else if (sub[s].start < linfo[i].insn_off) {
11225                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
11226                                 err = -EINVAL;
11227                                 goto err_free;
11228                         }
11229                 }
11230
11231                 prev_offset = linfo[i].insn_off;
11232                 bpfptr_add(&ulinfo, rec_size);
11233         }
11234
11235         if (s != env->subprog_cnt) {
11236                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
11237                         env->subprog_cnt - s, s);
11238                 err = -EINVAL;
11239                 goto err_free;
11240         }
11241
11242         prog->aux->linfo = linfo;
11243         prog->aux->nr_linfo = nr_linfo;
11244
11245         return 0;
11246
11247 err_free:
11248         kvfree(linfo);
11249         return err;
11250 }
11251
11252 #define MIN_CORE_RELO_SIZE      sizeof(struct bpf_core_relo)
11253 #define MAX_CORE_RELO_SIZE      MAX_FUNCINFO_REC_SIZE
11254
11255 static int check_core_relo(struct bpf_verifier_env *env,
11256                            const union bpf_attr *attr,
11257                            bpfptr_t uattr)
11258 {
11259         u32 i, nr_core_relo, ncopy, expected_size, rec_size;
11260         struct bpf_core_relo core_relo = {};
11261         struct bpf_prog *prog = env->prog;
11262         const struct btf *btf = prog->aux->btf;
11263         struct bpf_core_ctx ctx = {
11264                 .log = &env->log,
11265                 .btf = btf,
11266         };
11267         bpfptr_t u_core_relo;
11268         int err;
11269
11270         nr_core_relo = attr->core_relo_cnt;
11271         if (!nr_core_relo)
11272                 return 0;
11273         if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
11274                 return -EINVAL;
11275
11276         rec_size = attr->core_relo_rec_size;
11277         if (rec_size < MIN_CORE_RELO_SIZE ||
11278             rec_size > MAX_CORE_RELO_SIZE ||
11279             rec_size % sizeof(u32))
11280                 return -EINVAL;
11281
11282         u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
11283         expected_size = sizeof(struct bpf_core_relo);
11284         ncopy = min_t(u32, expected_size, rec_size);
11285
11286         /* Unlike func_info and line_info, copy and apply each CO-RE
11287          * relocation record one at a time.
11288          */
11289         for (i = 0; i < nr_core_relo; i++) {
11290                 /* future proofing when sizeof(bpf_core_relo) changes */
11291                 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
11292                 if (err) {
11293                         if (err == -E2BIG) {
11294                                 verbose(env, "nonzero tailing record in core_relo");
11295                                 if (copy_to_bpfptr_offset(uattr,
11296                                                           offsetof(union bpf_attr, core_relo_rec_size),
11297                                                           &expected_size, sizeof(expected_size)))
11298                                         err = -EFAULT;
11299                         }
11300                         break;
11301                 }
11302
11303                 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
11304                         err = -EFAULT;
11305                         break;
11306                 }
11307
11308                 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
11309                         verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
11310                                 i, core_relo.insn_off, prog->len);
11311                         err = -EINVAL;
11312                         break;
11313                 }
11314
11315                 err = bpf_core_apply(&ctx, &core_relo, i,
11316                                      &prog->insnsi[core_relo.insn_off / 8]);
11317                 if (err)
11318                         break;
11319                 bpfptr_add(&u_core_relo, rec_size);
11320         }
11321         return err;
11322 }
11323
11324 static int check_btf_info(struct bpf_verifier_env *env,
11325                           const union bpf_attr *attr,
11326                           bpfptr_t uattr)
11327 {
11328         struct btf *btf;
11329         int err;
11330
11331         if (!attr->func_info_cnt && !attr->line_info_cnt) {
11332                 if (check_abnormal_return(env))
11333                         return -EINVAL;
11334                 return 0;
11335         }
11336
11337         btf = btf_get_by_fd(attr->prog_btf_fd);
11338         if (IS_ERR(btf))
11339                 return PTR_ERR(btf);
11340         if (btf_is_kernel(btf)) {
11341                 btf_put(btf);
11342                 return -EACCES;
11343         }
11344         env->prog->aux->btf = btf;
11345
11346         err = check_btf_func(env, attr, uattr);
11347         if (err)
11348                 return err;
11349
11350         err = check_btf_line(env, attr, uattr);
11351         if (err)
11352                 return err;
11353
11354         err = check_core_relo(env, attr, uattr);
11355         if (err)
11356                 return err;
11357
11358         return 0;
11359 }
11360
11361 /* check %cur's range satisfies %old's */
11362 static bool range_within(struct bpf_reg_state *old,
11363                          struct bpf_reg_state *cur)
11364 {
11365         return old->umin_value <= cur->umin_value &&
11366                old->umax_value >= cur->umax_value &&
11367                old->smin_value <= cur->smin_value &&
11368                old->smax_value >= cur->smax_value &&
11369                old->u32_min_value <= cur->u32_min_value &&
11370                old->u32_max_value >= cur->u32_max_value &&
11371                old->s32_min_value <= cur->s32_min_value &&
11372                old->s32_max_value >= cur->s32_max_value;
11373 }
11374
11375 /* If in the old state two registers had the same id, then they need to have
11376  * the same id in the new state as well.  But that id could be different from
11377  * the old state, so we need to track the mapping from old to new ids.
11378  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
11379  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
11380  * regs with a different old id could still have new id 9, we don't care about
11381  * that.
11382  * So we look through our idmap to see if this old id has been seen before.  If
11383  * so, we require the new id to match; otherwise, we add the id pair to the map.
11384  */
11385 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
11386 {
11387         unsigned int i;
11388
11389         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
11390                 if (!idmap[i].old) {
11391                         /* Reached an empty slot; haven't seen this id before */
11392                         idmap[i].old = old_id;
11393                         idmap[i].cur = cur_id;
11394                         return true;
11395                 }
11396                 if (idmap[i].old == old_id)
11397                         return idmap[i].cur == cur_id;
11398         }
11399         /* We ran out of idmap slots, which should be impossible */
11400         WARN_ON_ONCE(1);
11401         return false;
11402 }
11403
11404 static void clean_func_state(struct bpf_verifier_env *env,
11405                              struct bpf_func_state *st)
11406 {
11407         enum bpf_reg_liveness live;
11408         int i, j;
11409
11410         for (i = 0; i < BPF_REG_FP; i++) {
11411                 live = st->regs[i].live;
11412                 /* liveness must not touch this register anymore */
11413                 st->regs[i].live |= REG_LIVE_DONE;
11414                 if (!(live & REG_LIVE_READ))
11415                         /* since the register is unused, clear its state
11416                          * to make further comparison simpler
11417                          */
11418                         __mark_reg_not_init(env, &st->regs[i]);
11419         }
11420
11421         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
11422                 live = st->stack[i].spilled_ptr.live;
11423                 /* liveness must not touch this stack slot anymore */
11424                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
11425                 if (!(live & REG_LIVE_READ)) {
11426                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
11427                         for (j = 0; j < BPF_REG_SIZE; j++)
11428                                 st->stack[i].slot_type[j] = STACK_INVALID;
11429                 }
11430         }
11431 }
11432
11433 static void clean_verifier_state(struct bpf_verifier_env *env,
11434                                  struct bpf_verifier_state *st)
11435 {
11436         int i;
11437
11438         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
11439                 /* all regs in this state in all frames were already marked */
11440                 return;
11441
11442         for (i = 0; i <= st->curframe; i++)
11443                 clean_func_state(env, st->frame[i]);
11444 }
11445
11446 /* the parentage chains form a tree.
11447  * the verifier states are added to state lists at given insn and
11448  * pushed into state stack for future exploration.
11449  * when the verifier reaches bpf_exit insn some of the verifer states
11450  * stored in the state lists have their final liveness state already,
11451  * but a lot of states will get revised from liveness point of view when
11452  * the verifier explores other branches.
11453  * Example:
11454  * 1: r0 = 1
11455  * 2: if r1 == 100 goto pc+1
11456  * 3: r0 = 2
11457  * 4: exit
11458  * when the verifier reaches exit insn the register r0 in the state list of
11459  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
11460  * of insn 2 and goes exploring further. At the insn 4 it will walk the
11461  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
11462  *
11463  * Since the verifier pushes the branch states as it sees them while exploring
11464  * the program the condition of walking the branch instruction for the second
11465  * time means that all states below this branch were already explored and
11466  * their final liveness marks are already propagated.
11467  * Hence when the verifier completes the search of state list in is_state_visited()
11468  * we can call this clean_live_states() function to mark all liveness states
11469  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
11470  * will not be used.
11471  * This function also clears the registers and stack for states that !READ
11472  * to simplify state merging.
11473  *
11474  * Important note here that walking the same branch instruction in the callee
11475  * doesn't meant that the states are DONE. The verifier has to compare
11476  * the callsites
11477  */
11478 static void clean_live_states(struct bpf_verifier_env *env, int insn,
11479                               struct bpf_verifier_state *cur)
11480 {
11481         struct bpf_verifier_state_list *sl;
11482         int i;
11483
11484         sl = *explored_state(env, insn);
11485         while (sl) {
11486                 if (sl->state.branches)
11487                         goto next;
11488                 if (sl->state.insn_idx != insn ||
11489                     sl->state.curframe != cur->curframe)
11490                         goto next;
11491                 for (i = 0; i <= cur->curframe; i++)
11492                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
11493                                 goto next;
11494                 clean_verifier_state(env, &sl->state);
11495 next:
11496                 sl = sl->next;
11497         }
11498 }
11499
11500 /* Returns true if (rold safe implies rcur safe) */
11501 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
11502                     struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
11503 {
11504         bool equal;
11505
11506         if (!(rold->live & REG_LIVE_READ))
11507                 /* explored state didn't use this */
11508                 return true;
11509
11510         equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
11511
11512         if (rold->type == PTR_TO_STACK)
11513                 /* two stack pointers are equal only if they're pointing to
11514                  * the same stack frame, since fp-8 in foo != fp-8 in bar
11515                  */
11516                 return equal && rold->frameno == rcur->frameno;
11517
11518         if (equal)
11519                 return true;
11520
11521         if (rold->type == NOT_INIT)
11522                 /* explored state can't have used this */
11523                 return true;
11524         if (rcur->type == NOT_INIT)
11525                 return false;
11526         switch (base_type(rold->type)) {
11527         case SCALAR_VALUE:
11528                 if (env->explore_alu_limits)
11529                         return false;
11530                 if (rcur->type == SCALAR_VALUE) {
11531                         if (!rold->precise && !rcur->precise)
11532                                 return true;
11533                         /* new val must satisfy old val knowledge */
11534                         return range_within(rold, rcur) &&
11535                                tnum_in(rold->var_off, rcur->var_off);
11536                 } else {
11537                         /* We're trying to use a pointer in place of a scalar.
11538                          * Even if the scalar was unbounded, this could lead to
11539                          * pointer leaks because scalars are allowed to leak
11540                          * while pointers are not. We could make this safe in
11541                          * special cases if root is calling us, but it's
11542                          * probably not worth the hassle.
11543                          */
11544                         return false;
11545                 }
11546         case PTR_TO_MAP_KEY:
11547         case PTR_TO_MAP_VALUE:
11548                 /* a PTR_TO_MAP_VALUE could be safe to use as a
11549                  * PTR_TO_MAP_VALUE_OR_NULL into the same map.
11550                  * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
11551                  * checked, doing so could have affected others with the same
11552                  * id, and we can't check for that because we lost the id when
11553                  * we converted to a PTR_TO_MAP_VALUE.
11554                  */
11555                 if (type_may_be_null(rold->type)) {
11556                         if (!type_may_be_null(rcur->type))
11557                                 return false;
11558                         if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
11559                                 return false;
11560                         /* Check our ids match any regs they're supposed to */
11561                         return check_ids(rold->id, rcur->id, idmap);
11562                 }
11563
11564                 /* If the new min/max/var_off satisfy the old ones and
11565                  * everything else matches, we are OK.
11566                  * 'id' is not compared, since it's only used for maps with
11567                  * bpf_spin_lock inside map element and in such cases if
11568                  * the rest of the prog is valid for one map element then
11569                  * it's valid for all map elements regardless of the key
11570                  * used in bpf_map_lookup()
11571                  */
11572                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
11573                        range_within(rold, rcur) &&
11574                        tnum_in(rold->var_off, rcur->var_off);
11575         case PTR_TO_PACKET_META:
11576         case PTR_TO_PACKET:
11577                 if (rcur->type != rold->type)
11578                         return false;
11579                 /* We must have at least as much range as the old ptr
11580                  * did, so that any accesses which were safe before are
11581                  * still safe.  This is true even if old range < old off,
11582                  * since someone could have accessed through (ptr - k), or
11583                  * even done ptr -= k in a register, to get a safe access.
11584                  */
11585                 if (rold->range > rcur->range)
11586                         return false;
11587                 /* If the offsets don't match, we can't trust our alignment;
11588                  * nor can we be sure that we won't fall out of range.
11589                  */
11590                 if (rold->off != rcur->off)
11591                         return false;
11592                 /* id relations must be preserved */
11593                 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
11594                         return false;
11595                 /* new val must satisfy old val knowledge */
11596                 return range_within(rold, rcur) &&
11597                        tnum_in(rold->var_off, rcur->var_off);
11598         case PTR_TO_CTX:
11599         case CONST_PTR_TO_MAP:
11600         case PTR_TO_PACKET_END:
11601         case PTR_TO_FLOW_KEYS:
11602         case PTR_TO_SOCKET:
11603         case PTR_TO_SOCK_COMMON:
11604         case PTR_TO_TCP_SOCK:
11605         case PTR_TO_XDP_SOCK:
11606                 /* Only valid matches are exact, which memcmp() above
11607                  * would have accepted
11608                  */
11609         default:
11610                 /* Don't know what's going on, just say it's not safe */
11611                 return false;
11612         }
11613
11614         /* Shouldn't get here; if we do, say it's not safe */
11615         WARN_ON_ONCE(1);
11616         return false;
11617 }
11618
11619 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
11620                       struct bpf_func_state *cur, struct bpf_id_pair *idmap)
11621 {
11622         int i, spi;
11623
11624         /* walk slots of the explored stack and ignore any additional
11625          * slots in the current stack, since explored(safe) state
11626          * didn't use them
11627          */
11628         for (i = 0; i < old->allocated_stack; i++) {
11629                 spi = i / BPF_REG_SIZE;
11630
11631                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
11632                         i += BPF_REG_SIZE - 1;
11633                         /* explored state didn't use this */
11634                         continue;
11635                 }
11636
11637                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
11638                         continue;
11639
11640                 /* explored stack has more populated slots than current stack
11641                  * and these slots were used
11642                  */
11643                 if (i >= cur->allocated_stack)
11644                         return false;
11645
11646                 /* if old state was safe with misc data in the stack
11647                  * it will be safe with zero-initialized stack.
11648                  * The opposite is not true
11649                  */
11650                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
11651                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
11652                         continue;
11653                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
11654                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
11655                         /* Ex: old explored (safe) state has STACK_SPILL in
11656                          * this stack slot, but current has STACK_MISC ->
11657                          * this verifier states are not equivalent,
11658                          * return false to continue verification of this path
11659                          */
11660                         return false;
11661                 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
11662                         continue;
11663                 if (!is_spilled_reg(&old->stack[spi]))
11664                         continue;
11665                 if (!regsafe(env, &old->stack[spi].spilled_ptr,
11666                              &cur->stack[spi].spilled_ptr, idmap))
11667                         /* when explored and current stack slot are both storing
11668                          * spilled registers, check that stored pointers types
11669                          * are the same as well.
11670                          * Ex: explored safe path could have stored
11671                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
11672                          * but current path has stored:
11673                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
11674                          * such verifier states are not equivalent.
11675                          * return false to continue verification of this path
11676                          */
11677                         return false;
11678         }
11679         return true;
11680 }
11681
11682 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
11683 {
11684         if (old->acquired_refs != cur->acquired_refs)
11685                 return false;
11686         return !memcmp(old->refs, cur->refs,
11687                        sizeof(*old->refs) * old->acquired_refs);
11688 }
11689
11690 /* compare two verifier states
11691  *
11692  * all states stored in state_list are known to be valid, since
11693  * verifier reached 'bpf_exit' instruction through them
11694  *
11695  * this function is called when verifier exploring different branches of
11696  * execution popped from the state stack. If it sees an old state that has
11697  * more strict register state and more strict stack state then this execution
11698  * branch doesn't need to be explored further, since verifier already
11699  * concluded that more strict state leads to valid finish.
11700  *
11701  * Therefore two states are equivalent if register state is more conservative
11702  * and explored stack state is more conservative than the current one.
11703  * Example:
11704  *       explored                   current
11705  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
11706  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
11707  *
11708  * In other words if current stack state (one being explored) has more
11709  * valid slots than old one that already passed validation, it means
11710  * the verifier can stop exploring and conclude that current state is valid too
11711  *
11712  * Similarly with registers. If explored state has register type as invalid
11713  * whereas register type in current state is meaningful, it means that
11714  * the current state will reach 'bpf_exit' instruction safely
11715  */
11716 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
11717                               struct bpf_func_state *cur)
11718 {
11719         int i;
11720
11721         memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11722         for (i = 0; i < MAX_BPF_REG; i++)
11723                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
11724                              env->idmap_scratch))
11725                         return false;
11726
11727         if (!stacksafe(env, old, cur, env->idmap_scratch))
11728                 return false;
11729
11730         if (!refsafe(old, cur))
11731                 return false;
11732
11733         return true;
11734 }
11735
11736 static bool states_equal(struct bpf_verifier_env *env,
11737                          struct bpf_verifier_state *old,
11738                          struct bpf_verifier_state *cur)
11739 {
11740         int i;
11741
11742         if (old->curframe != cur->curframe)
11743                 return false;
11744
11745         /* Verification state from speculative execution simulation
11746          * must never prune a non-speculative execution one.
11747          */
11748         if (old->speculative && !cur->speculative)
11749                 return false;
11750
11751         if (old->active_spin_lock != cur->active_spin_lock)
11752                 return false;
11753
11754         /* for states to be equal callsites have to be the same
11755          * and all frame states need to be equivalent
11756          */
11757         for (i = 0; i <= old->curframe; i++) {
11758                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
11759                         return false;
11760                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
11761                         return false;
11762         }
11763         return true;
11764 }
11765
11766 /* Return 0 if no propagation happened. Return negative error code if error
11767  * happened. Otherwise, return the propagated bit.
11768  */
11769 static int propagate_liveness_reg(struct bpf_verifier_env *env,
11770                                   struct bpf_reg_state *reg,
11771                                   struct bpf_reg_state *parent_reg)
11772 {
11773         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11774         u8 flag = reg->live & REG_LIVE_READ;
11775         int err;
11776
11777         /* When comes here, read flags of PARENT_REG or REG could be any of
11778          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11779          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11780          */
11781         if (parent_flag == REG_LIVE_READ64 ||
11782             /* Or if there is no read flag from REG. */
11783             !flag ||
11784             /* Or if the read flag from REG is the same as PARENT_REG. */
11785             parent_flag == flag)
11786                 return 0;
11787
11788         err = mark_reg_read(env, reg, parent_reg, flag);
11789         if (err)
11790                 return err;
11791
11792         return flag;
11793 }
11794
11795 /* A write screens off any subsequent reads; but write marks come from the
11796  * straight-line code between a state and its parent.  When we arrive at an
11797  * equivalent state (jump target or such) we didn't arrive by the straight-line
11798  * code, so read marks in the state must propagate to the parent regardless
11799  * of the state's write marks. That's what 'parent == state->parent' comparison
11800  * in mark_reg_read() is for.
11801  */
11802 static int propagate_liveness(struct bpf_verifier_env *env,
11803                               const struct bpf_verifier_state *vstate,
11804                               struct bpf_verifier_state *vparent)
11805 {
11806         struct bpf_reg_state *state_reg, *parent_reg;
11807         struct bpf_func_state *state, *parent;
11808         int i, frame, err = 0;
11809
11810         if (vparent->curframe != vstate->curframe) {
11811                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
11812                      vparent->curframe, vstate->curframe);
11813                 return -EFAULT;
11814         }
11815         /* Propagate read liveness of registers... */
11816         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
11817         for (frame = 0; frame <= vstate->curframe; frame++) {
11818                 parent = vparent->frame[frame];
11819                 state = vstate->frame[frame];
11820                 parent_reg = parent->regs;
11821                 state_reg = state->regs;
11822                 /* We don't need to worry about FP liveness, it's read-only */
11823                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
11824                         err = propagate_liveness_reg(env, &state_reg[i],
11825                                                      &parent_reg[i]);
11826                         if (err < 0)
11827                                 return err;
11828                         if (err == REG_LIVE_READ64)
11829                                 mark_insn_zext(env, &parent_reg[i]);
11830                 }
11831
11832                 /* Propagate stack slots. */
11833                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11834                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
11835                         parent_reg = &parent->stack[i].spilled_ptr;
11836                         state_reg = &state->stack[i].spilled_ptr;
11837                         err = propagate_liveness_reg(env, state_reg,
11838                                                      parent_reg);
11839                         if (err < 0)
11840                                 return err;
11841                 }
11842         }
11843         return 0;
11844 }
11845
11846 /* find precise scalars in the previous equivalent state and
11847  * propagate them into the current state
11848  */
11849 static int propagate_precision(struct bpf_verifier_env *env,
11850                                const struct bpf_verifier_state *old)
11851 {
11852         struct bpf_reg_state *state_reg;
11853         struct bpf_func_state *state;
11854         int i, err = 0;
11855
11856         state = old->frame[old->curframe];
11857         state_reg = state->regs;
11858         for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11859                 if (state_reg->type != SCALAR_VALUE ||
11860                     !state_reg->precise)
11861                         continue;
11862                 if (env->log.level & BPF_LOG_LEVEL2)
11863                         verbose(env, "propagating r%d\n", i);
11864                 err = mark_chain_precision(env, i);
11865                 if (err < 0)
11866                         return err;
11867         }
11868
11869         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
11870                 if (!is_spilled_reg(&state->stack[i]))
11871                         continue;
11872                 state_reg = &state->stack[i].spilled_ptr;
11873                 if (state_reg->type != SCALAR_VALUE ||
11874                     !state_reg->precise)
11875                         continue;
11876                 if (env->log.level & BPF_LOG_LEVEL2)
11877                         verbose(env, "propagating fp%d\n",
11878                                 (-i - 1) * BPF_REG_SIZE);
11879                 err = mark_chain_precision_stack(env, i);
11880                 if (err < 0)
11881                         return err;
11882         }
11883         return 0;
11884 }
11885
11886 static bool states_maybe_looping(struct bpf_verifier_state *old,
11887                                  struct bpf_verifier_state *cur)
11888 {
11889         struct bpf_func_state *fold, *fcur;
11890         int i, fr = cur->curframe;
11891
11892         if (old->curframe != fr)
11893                 return false;
11894
11895         fold = old->frame[fr];
11896         fcur = cur->frame[fr];
11897         for (i = 0; i < MAX_BPF_REG; i++)
11898                 if (memcmp(&fold->regs[i], &fcur->regs[i],
11899                            offsetof(struct bpf_reg_state, parent)))
11900                         return false;
11901         return true;
11902 }
11903
11904
11905 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
11906 {
11907         struct bpf_verifier_state_list *new_sl;
11908         struct bpf_verifier_state_list *sl, **pprev;
11909         struct bpf_verifier_state *cur = env->cur_state, *new;
11910         int i, j, err, states_cnt = 0;
11911         bool add_new_state = env->test_state_freq ? true : false;
11912
11913         cur->last_insn_idx = env->prev_insn_idx;
11914         if (!env->insn_aux_data[insn_idx].prune_point)
11915                 /* this 'insn_idx' instruction wasn't marked, so we will not
11916                  * be doing state search here
11917                  */
11918                 return 0;
11919
11920         /* bpf progs typically have pruning point every 4 instructions
11921          * http://vger.kernel.org/bpfconf2019.html#session-1
11922          * Do not add new state for future pruning if the verifier hasn't seen
11923          * at least 2 jumps and at least 8 instructions.
11924          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11925          * In tests that amounts to up to 50% reduction into total verifier
11926          * memory consumption and 20% verifier time speedup.
11927          */
11928         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11929             env->insn_processed - env->prev_insn_processed >= 8)
11930                 add_new_state = true;
11931
11932         pprev = explored_state(env, insn_idx);
11933         sl = *pprev;
11934
11935         clean_live_states(env, insn_idx, cur);
11936
11937         while (sl) {
11938                 states_cnt++;
11939                 if (sl->state.insn_idx != insn_idx)
11940                         goto next;
11941
11942                 if (sl->state.branches) {
11943                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
11944
11945                         if (frame->in_async_callback_fn &&
11946                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
11947                                 /* Different async_entry_cnt means that the verifier is
11948                                  * processing another entry into async callback.
11949                                  * Seeing the same state is not an indication of infinite
11950                                  * loop or infinite recursion.
11951                                  * But finding the same state doesn't mean that it's safe
11952                                  * to stop processing the current state. The previous state
11953                                  * hasn't yet reached bpf_exit, since state.branches > 0.
11954                                  * Checking in_async_callback_fn alone is not enough either.
11955                                  * Since the verifier still needs to catch infinite loops
11956                                  * inside async callbacks.
11957                                  */
11958                         } else if (states_maybe_looping(&sl->state, cur) &&
11959                                    states_equal(env, &sl->state, cur)) {
11960                                 verbose_linfo(env, insn_idx, "; ");
11961                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
11962                                 return -EINVAL;
11963                         }
11964                         /* if the verifier is processing a loop, avoid adding new state
11965                          * too often, since different loop iterations have distinct
11966                          * states and may not help future pruning.
11967                          * This threshold shouldn't be too low to make sure that
11968                          * a loop with large bound will be rejected quickly.
11969                          * The most abusive loop will be:
11970                          * r1 += 1
11971                          * if r1 < 1000000 goto pc-2
11972                          * 1M insn_procssed limit / 100 == 10k peak states.
11973                          * This threshold shouldn't be too high either, since states
11974                          * at the end of the loop are likely to be useful in pruning.
11975                          */
11976                         if (env->jmps_processed - env->prev_jmps_processed < 20 &&
11977                             env->insn_processed - env->prev_insn_processed < 100)
11978                                 add_new_state = false;
11979                         goto miss;
11980                 }
11981                 if (states_equal(env, &sl->state, cur)) {
11982                         sl->hit_cnt++;
11983                         /* reached equivalent register/stack state,
11984                          * prune the search.
11985                          * Registers read by the continuation are read by us.
11986                          * If we have any write marks in env->cur_state, they
11987                          * will prevent corresponding reads in the continuation
11988                          * from reaching our parent (an explored_state).  Our
11989                          * own state will get the read marks recorded, but
11990                          * they'll be immediately forgotten as we're pruning
11991                          * this state and will pop a new one.
11992                          */
11993                         err = propagate_liveness(env, &sl->state, cur);
11994
11995                         /* if previous state reached the exit with precision and
11996                          * current state is equivalent to it (except precsion marks)
11997                          * the precision needs to be propagated back in
11998                          * the current state.
11999                          */
12000                         err = err ? : push_jmp_history(env, cur);
12001                         err = err ? : propagate_precision(env, &sl->state);
12002                         if (err)
12003                                 return err;
12004                         return 1;
12005                 }
12006 miss:
12007                 /* when new state is not going to be added do not increase miss count.
12008                  * Otherwise several loop iterations will remove the state
12009                  * recorded earlier. The goal of these heuristics is to have
12010                  * states from some iterations of the loop (some in the beginning
12011                  * and some at the end) to help pruning.
12012                  */
12013                 if (add_new_state)
12014                         sl->miss_cnt++;
12015                 /* heuristic to determine whether this state is beneficial
12016                  * to keep checking from state equivalence point of view.
12017                  * Higher numbers increase max_states_per_insn and verification time,
12018                  * but do not meaningfully decrease insn_processed.
12019                  */
12020                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
12021                         /* the state is unlikely to be useful. Remove it to
12022                          * speed up verification
12023                          */
12024                         *pprev = sl->next;
12025                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
12026                                 u32 br = sl->state.branches;
12027
12028                                 WARN_ONCE(br,
12029                                           "BUG live_done but branches_to_explore %d\n",
12030                                           br);
12031                                 free_verifier_state(&sl->state, false);
12032                                 kfree(sl);
12033                                 env->peak_states--;
12034                         } else {
12035                                 /* cannot free this state, since parentage chain may
12036                                  * walk it later. Add it for free_list instead to
12037                                  * be freed at the end of verification
12038                                  */
12039                                 sl->next = env->free_list;
12040                                 env->free_list = sl;
12041                         }
12042                         sl = *pprev;
12043                         continue;
12044                 }
12045 next:
12046                 pprev = &sl->next;
12047                 sl = *pprev;
12048         }
12049
12050         if (env->max_states_per_insn < states_cnt)
12051                 env->max_states_per_insn = states_cnt;
12052
12053         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
12054                 return push_jmp_history(env, cur);
12055
12056         if (!add_new_state)
12057                 return push_jmp_history(env, cur);
12058
12059         /* There were no equivalent states, remember the current one.
12060          * Technically the current state is not proven to be safe yet,
12061          * but it will either reach outer most bpf_exit (which means it's safe)
12062          * or it will be rejected. When there are no loops the verifier won't be
12063          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
12064          * again on the way to bpf_exit.
12065          * When looping the sl->state.branches will be > 0 and this state
12066          * will not be considered for equivalence until branches == 0.
12067          */
12068         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
12069         if (!new_sl)
12070                 return -ENOMEM;
12071         env->total_states++;
12072         env->peak_states++;
12073         env->prev_jmps_processed = env->jmps_processed;
12074         env->prev_insn_processed = env->insn_processed;
12075
12076         /* add new state to the head of linked list */
12077         new = &new_sl->state;
12078         err = copy_verifier_state(new, cur);
12079         if (err) {
12080                 free_verifier_state(new, false);
12081                 kfree(new_sl);
12082                 return err;
12083         }
12084         new->insn_idx = insn_idx;
12085         WARN_ONCE(new->branches != 1,
12086                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
12087
12088         cur->parent = new;
12089         cur->first_insn_idx = insn_idx;
12090         clear_jmp_history(cur);
12091         new_sl->next = *explored_state(env, insn_idx);
12092         *explored_state(env, insn_idx) = new_sl;
12093         /* connect new state to parentage chain. Current frame needs all
12094          * registers connected. Only r6 - r9 of the callers are alive (pushed
12095          * to the stack implicitly by JITs) so in callers' frames connect just
12096          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
12097          * the state of the call instruction (with WRITTEN set), and r0 comes
12098          * from callee with its full parentage chain, anyway.
12099          */
12100         /* clear write marks in current state: the writes we did are not writes
12101          * our child did, so they don't screen off its reads from us.
12102          * (There are no read marks in current state, because reads always mark
12103          * their parent and current state never has children yet.  Only
12104          * explored_states can get read marks.)
12105          */
12106         for (j = 0; j <= cur->curframe; j++) {
12107                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
12108                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
12109                 for (i = 0; i < BPF_REG_FP; i++)
12110                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
12111         }
12112
12113         /* all stack frames are accessible from callee, clear them all */
12114         for (j = 0; j <= cur->curframe; j++) {
12115                 struct bpf_func_state *frame = cur->frame[j];
12116                 struct bpf_func_state *newframe = new->frame[j];
12117
12118                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
12119                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
12120                         frame->stack[i].spilled_ptr.parent =
12121                                                 &newframe->stack[i].spilled_ptr;
12122                 }
12123         }
12124         return 0;
12125 }
12126
12127 /* Return true if it's OK to have the same insn return a different type. */
12128 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
12129 {
12130         switch (base_type(type)) {
12131         case PTR_TO_CTX:
12132         case PTR_TO_SOCKET:
12133         case PTR_TO_SOCK_COMMON:
12134         case PTR_TO_TCP_SOCK:
12135         case PTR_TO_XDP_SOCK:
12136         case PTR_TO_BTF_ID:
12137                 return false;
12138         default:
12139                 return true;
12140         }
12141 }
12142
12143 /* If an instruction was previously used with particular pointer types, then we
12144  * need to be careful to avoid cases such as the below, where it may be ok
12145  * for one branch accessing the pointer, but not ok for the other branch:
12146  *
12147  * R1 = sock_ptr
12148  * goto X;
12149  * ...
12150  * R1 = some_other_valid_ptr;
12151  * goto X;
12152  * ...
12153  * R2 = *(u32 *)(R1 + 0);
12154  */
12155 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
12156 {
12157         return src != prev && (!reg_type_mismatch_ok(src) ||
12158                                !reg_type_mismatch_ok(prev));
12159 }
12160
12161 static int do_check(struct bpf_verifier_env *env)
12162 {
12163         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12164         struct bpf_verifier_state *state = env->cur_state;
12165         struct bpf_insn *insns = env->prog->insnsi;
12166         struct bpf_reg_state *regs;
12167         int insn_cnt = env->prog->len;
12168         bool do_print_state = false;
12169         int prev_insn_idx = -1;
12170
12171         for (;;) {
12172                 struct bpf_insn *insn;
12173                 u8 class;
12174                 int err;
12175
12176                 env->prev_insn_idx = prev_insn_idx;
12177                 if (env->insn_idx >= insn_cnt) {
12178                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
12179                                 env->insn_idx, insn_cnt);
12180                         return -EFAULT;
12181                 }
12182
12183                 insn = &insns[env->insn_idx];
12184                 class = BPF_CLASS(insn->code);
12185
12186                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
12187                         verbose(env,
12188                                 "BPF program is too large. Processed %d insn\n",
12189                                 env->insn_processed);
12190                         return -E2BIG;
12191                 }
12192
12193                 err = is_state_visited(env, env->insn_idx);
12194                 if (err < 0)
12195                         return err;
12196                 if (err == 1) {
12197                         /* found equivalent state, can prune the search */
12198                         if (env->log.level & BPF_LOG_LEVEL) {
12199                                 if (do_print_state)
12200                                         verbose(env, "\nfrom %d to %d%s: safe\n",
12201                                                 env->prev_insn_idx, env->insn_idx,
12202                                                 env->cur_state->speculative ?
12203                                                 " (speculative execution)" : "");
12204                                 else
12205                                         verbose(env, "%d: safe\n", env->insn_idx);
12206                         }
12207                         goto process_bpf_exit;
12208                 }
12209
12210                 if (signal_pending(current))
12211                         return -EAGAIN;
12212
12213                 if (need_resched())
12214                         cond_resched();
12215
12216                 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
12217                         verbose(env, "\nfrom %d to %d%s:",
12218                                 env->prev_insn_idx, env->insn_idx,
12219                                 env->cur_state->speculative ?
12220                                 " (speculative execution)" : "");
12221                         print_verifier_state(env, state->frame[state->curframe], true);
12222                         do_print_state = false;
12223                 }
12224
12225                 if (env->log.level & BPF_LOG_LEVEL) {
12226                         const struct bpf_insn_cbs cbs = {
12227                                 .cb_call        = disasm_kfunc_name,
12228                                 .cb_print       = verbose,
12229                                 .private_data   = env,
12230                         };
12231
12232                         if (verifier_state_scratched(env))
12233                                 print_insn_state(env, state->frame[state->curframe]);
12234
12235                         verbose_linfo(env, env->insn_idx, "; ");
12236                         env->prev_log_len = env->log.len_used;
12237                         verbose(env, "%d: ", env->insn_idx);
12238                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12239                         env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
12240                         env->prev_log_len = env->log.len_used;
12241                 }
12242
12243                 if (bpf_prog_is_dev_bound(env->prog->aux)) {
12244                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
12245                                                            env->prev_insn_idx);
12246                         if (err)
12247                                 return err;
12248                 }
12249
12250                 regs = cur_regs(env);
12251                 sanitize_mark_insn_seen(env);
12252                 prev_insn_idx = env->insn_idx;
12253
12254                 if (class == BPF_ALU || class == BPF_ALU64) {
12255                         err = check_alu_op(env, insn);
12256                         if (err)
12257                                 return err;
12258
12259                 } else if (class == BPF_LDX) {
12260                         enum bpf_reg_type *prev_src_type, src_reg_type;
12261
12262                         /* check for reserved fields is already done */
12263
12264                         /* check src operand */
12265                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
12266                         if (err)
12267                                 return err;
12268
12269                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12270                         if (err)
12271                                 return err;
12272
12273                         src_reg_type = regs[insn->src_reg].type;
12274
12275                         /* check that memory (src_reg + off) is readable,
12276                          * the state of dst_reg will be updated by this func
12277                          */
12278                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
12279                                                insn->off, BPF_SIZE(insn->code),
12280                                                BPF_READ, insn->dst_reg, false);
12281                         if (err)
12282                                 return err;
12283
12284                         prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12285
12286                         if (*prev_src_type == NOT_INIT) {
12287                                 /* saw a valid insn
12288                                  * dst_reg = *(u32 *)(src_reg + off)
12289                                  * save type to validate intersecting paths
12290                                  */
12291                                 *prev_src_type = src_reg_type;
12292
12293                         } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
12294                                 /* ABuser program is trying to use the same insn
12295                                  * dst_reg = *(u32*) (src_reg + off)
12296                                  * with different pointer types:
12297                                  * src_reg == ctx in one branch and
12298                                  * src_reg == stack|map in some other branch.
12299                                  * Reject it.
12300                                  */
12301                                 verbose(env, "same insn cannot be used with different pointers\n");
12302                                 return -EINVAL;
12303                         }
12304
12305                 } else if (class == BPF_STX) {
12306                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
12307
12308                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
12309                                 err = check_atomic(env, env->insn_idx, insn);
12310                                 if (err)
12311                                         return err;
12312                                 env->insn_idx++;
12313                                 continue;
12314                         }
12315
12316                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
12317                                 verbose(env, "BPF_STX uses reserved fields\n");
12318                                 return -EINVAL;
12319                         }
12320
12321                         /* check src1 operand */
12322                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
12323                         if (err)
12324                                 return err;
12325                         /* check src2 operand */
12326                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12327                         if (err)
12328                                 return err;
12329
12330                         dst_reg_type = regs[insn->dst_reg].type;
12331
12332                         /* check that memory (dst_reg + off) is writeable */
12333                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12334                                                insn->off, BPF_SIZE(insn->code),
12335                                                BPF_WRITE, insn->src_reg, false);
12336                         if (err)
12337                                 return err;
12338
12339                         prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12340
12341                         if (*prev_dst_type == NOT_INIT) {
12342                                 *prev_dst_type = dst_reg_type;
12343                         } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
12344                                 verbose(env, "same insn cannot be used with different pointers\n");
12345                                 return -EINVAL;
12346                         }
12347
12348                 } else if (class == BPF_ST) {
12349                         if (BPF_MODE(insn->code) != BPF_MEM ||
12350                             insn->src_reg != BPF_REG_0) {
12351                                 verbose(env, "BPF_ST uses reserved fields\n");
12352                                 return -EINVAL;
12353                         }
12354                         /* check src operand */
12355                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12356                         if (err)
12357                                 return err;
12358
12359                         if (is_ctx_reg(env, insn->dst_reg)) {
12360                                 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
12361                                         insn->dst_reg,
12362                                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
12363                                 return -EACCES;
12364                         }
12365
12366                         /* check that memory (dst_reg + off) is writeable */
12367                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12368                                                insn->off, BPF_SIZE(insn->code),
12369                                                BPF_WRITE, -1, false);
12370                         if (err)
12371                                 return err;
12372
12373                 } else if (class == BPF_JMP || class == BPF_JMP32) {
12374                         u8 opcode = BPF_OP(insn->code);
12375
12376                         env->jmps_processed++;
12377                         if (opcode == BPF_CALL) {
12378                                 if (BPF_SRC(insn->code) != BPF_K ||
12379                                     (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
12380                                      && insn->off != 0) ||
12381                                     (insn->src_reg != BPF_REG_0 &&
12382                                      insn->src_reg != BPF_PSEUDO_CALL &&
12383                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
12384                                     insn->dst_reg != BPF_REG_0 ||
12385                                     class == BPF_JMP32) {
12386                                         verbose(env, "BPF_CALL uses reserved fields\n");
12387                                         return -EINVAL;
12388                                 }
12389
12390                                 if (env->cur_state->active_spin_lock &&
12391                                     (insn->src_reg == BPF_PSEUDO_CALL ||
12392                                      insn->imm != BPF_FUNC_spin_unlock)) {
12393                                         verbose(env, "function calls are not allowed while holding a lock\n");
12394                                         return -EINVAL;
12395                                 }
12396                                 if (insn->src_reg == BPF_PSEUDO_CALL)
12397                                         err = check_func_call(env, insn, &env->insn_idx);
12398                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
12399                                         err = check_kfunc_call(env, insn, &env->insn_idx);
12400                                 else
12401                                         err = check_helper_call(env, insn, &env->insn_idx);
12402                                 if (err)
12403                                         return err;
12404                         } else if (opcode == BPF_JA) {
12405                                 if (BPF_SRC(insn->code) != BPF_K ||
12406                                     insn->imm != 0 ||
12407                                     insn->src_reg != BPF_REG_0 ||
12408                                     insn->dst_reg != BPF_REG_0 ||
12409                                     class == BPF_JMP32) {
12410                                         verbose(env, "BPF_JA uses reserved fields\n");
12411                                         return -EINVAL;
12412                                 }
12413
12414                                 env->insn_idx += insn->off + 1;
12415                                 continue;
12416
12417                         } else if (opcode == BPF_EXIT) {
12418                                 if (BPF_SRC(insn->code) != BPF_K ||
12419                                     insn->imm != 0 ||
12420                                     insn->src_reg != BPF_REG_0 ||
12421                                     insn->dst_reg != BPF_REG_0 ||
12422                                     class == BPF_JMP32) {
12423                                         verbose(env, "BPF_EXIT uses reserved fields\n");
12424                                         return -EINVAL;
12425                                 }
12426
12427                                 if (env->cur_state->active_spin_lock) {
12428                                         verbose(env, "bpf_spin_unlock is missing\n");
12429                                         return -EINVAL;
12430                                 }
12431
12432                                 /* We must do check_reference_leak here before
12433                                  * prepare_func_exit to handle the case when
12434                                  * state->curframe > 0, it may be a callback
12435                                  * function, for which reference_state must
12436                                  * match caller reference state when it exits.
12437                                  */
12438                                 err = check_reference_leak(env);
12439                                 if (err)
12440                                         return err;
12441
12442                                 if (state->curframe) {
12443                                         /* exit from nested function */
12444                                         err = prepare_func_exit(env, &env->insn_idx);
12445                                         if (err)
12446                                                 return err;
12447                                         do_print_state = true;
12448                                         continue;
12449                                 }
12450
12451                                 err = check_return_code(env);
12452                                 if (err)
12453                                         return err;
12454 process_bpf_exit:
12455                                 mark_verifier_state_scratched(env);
12456                                 update_branch_counts(env, env->cur_state);
12457                                 err = pop_stack(env, &prev_insn_idx,
12458                                                 &env->insn_idx, pop_log);
12459                                 if (err < 0) {
12460                                         if (err != -ENOENT)
12461                                                 return err;
12462                                         break;
12463                                 } else {
12464                                         do_print_state = true;
12465                                         continue;
12466                                 }
12467                         } else {
12468                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
12469                                 if (err)
12470                                         return err;
12471                         }
12472                 } else if (class == BPF_LD) {
12473                         u8 mode = BPF_MODE(insn->code);
12474
12475                         if (mode == BPF_ABS || mode == BPF_IND) {
12476                                 err = check_ld_abs(env, insn);
12477                                 if (err)
12478                                         return err;
12479
12480                         } else if (mode == BPF_IMM) {
12481                                 err = check_ld_imm(env, insn);
12482                                 if (err)
12483                                         return err;
12484
12485                                 env->insn_idx++;
12486                                 sanitize_mark_insn_seen(env);
12487                         } else {
12488                                 verbose(env, "invalid BPF_LD mode\n");
12489                                 return -EINVAL;
12490                         }
12491                 } else {
12492                         verbose(env, "unknown insn class %d\n", class);
12493                         return -EINVAL;
12494                 }
12495
12496                 env->insn_idx++;
12497         }
12498
12499         return 0;
12500 }
12501
12502 static int find_btf_percpu_datasec(struct btf *btf)
12503 {
12504         const struct btf_type *t;
12505         const char *tname;
12506         int i, n;
12507
12508         /*
12509          * Both vmlinux and module each have their own ".data..percpu"
12510          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
12511          * types to look at only module's own BTF types.
12512          */
12513         n = btf_nr_types(btf);
12514         if (btf_is_module(btf))
12515                 i = btf_nr_types(btf_vmlinux);
12516         else
12517                 i = 1;
12518
12519         for(; i < n; i++) {
12520                 t = btf_type_by_id(btf, i);
12521                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
12522                         continue;
12523
12524                 tname = btf_name_by_offset(btf, t->name_off);
12525                 if (!strcmp(tname, ".data..percpu"))
12526                         return i;
12527         }
12528
12529         return -ENOENT;
12530 }
12531
12532 /* replace pseudo btf_id with kernel symbol address */
12533 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
12534                                struct bpf_insn *insn,
12535                                struct bpf_insn_aux_data *aux)
12536 {
12537         const struct btf_var_secinfo *vsi;
12538         const struct btf_type *datasec;
12539         struct btf_mod_pair *btf_mod;
12540         const struct btf_type *t;
12541         const char *sym_name;
12542         bool percpu = false;
12543         u32 type, id = insn->imm;
12544         struct btf *btf;
12545         s32 datasec_id;
12546         u64 addr;
12547         int i, btf_fd, err;
12548
12549         btf_fd = insn[1].imm;
12550         if (btf_fd) {
12551                 btf = btf_get_by_fd(btf_fd);
12552                 if (IS_ERR(btf)) {
12553                         verbose(env, "invalid module BTF object FD specified.\n");
12554                         return -EINVAL;
12555                 }
12556         } else {
12557                 if (!btf_vmlinux) {
12558                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
12559                         return -EINVAL;
12560                 }
12561                 btf = btf_vmlinux;
12562                 btf_get(btf);
12563         }
12564
12565         t = btf_type_by_id(btf, id);
12566         if (!t) {
12567                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
12568                 err = -ENOENT;
12569                 goto err_put;
12570         }
12571
12572         if (!btf_type_is_var(t)) {
12573                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
12574                 err = -EINVAL;
12575                 goto err_put;
12576         }
12577
12578         sym_name = btf_name_by_offset(btf, t->name_off);
12579         addr = kallsyms_lookup_name(sym_name);
12580         if (!addr) {
12581                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
12582                         sym_name);
12583                 err = -ENOENT;
12584                 goto err_put;
12585         }
12586
12587         datasec_id = find_btf_percpu_datasec(btf);
12588         if (datasec_id > 0) {
12589                 datasec = btf_type_by_id(btf, datasec_id);
12590                 for_each_vsi(i, datasec, vsi) {
12591                         if (vsi->type == id) {
12592                                 percpu = true;
12593                                 break;
12594                         }
12595                 }
12596         }
12597
12598         insn[0].imm = (u32)addr;
12599         insn[1].imm = addr >> 32;
12600
12601         type = t->type;
12602         t = btf_type_skip_modifiers(btf, type, NULL);
12603         if (percpu) {
12604                 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
12605                 aux->btf_var.btf = btf;
12606                 aux->btf_var.btf_id = type;
12607         } else if (!btf_type_is_struct(t)) {
12608                 const struct btf_type *ret;
12609                 const char *tname;
12610                 u32 tsize;
12611
12612                 /* resolve the type size of ksym. */
12613                 ret = btf_resolve_size(btf, t, &tsize);
12614                 if (IS_ERR(ret)) {
12615                         tname = btf_name_by_offset(btf, t->name_off);
12616                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
12617                                 tname, PTR_ERR(ret));
12618                         err = -EINVAL;
12619                         goto err_put;
12620                 }
12621                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
12622                 aux->btf_var.mem_size = tsize;
12623         } else {
12624                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
12625                 aux->btf_var.btf = btf;
12626                 aux->btf_var.btf_id = type;
12627         }
12628
12629         /* check whether we recorded this BTF (and maybe module) already */
12630         for (i = 0; i < env->used_btf_cnt; i++) {
12631                 if (env->used_btfs[i].btf == btf) {
12632                         btf_put(btf);
12633                         return 0;
12634                 }
12635         }
12636
12637         if (env->used_btf_cnt >= MAX_USED_BTFS) {
12638                 err = -E2BIG;
12639                 goto err_put;
12640         }
12641
12642         btf_mod = &env->used_btfs[env->used_btf_cnt];
12643         btf_mod->btf = btf;
12644         btf_mod->module = NULL;
12645
12646         /* if we reference variables from kernel module, bump its refcount */
12647         if (btf_is_module(btf)) {
12648                 btf_mod->module = btf_try_get_module(btf);
12649                 if (!btf_mod->module) {
12650                         err = -ENXIO;
12651                         goto err_put;
12652                 }
12653         }
12654
12655         env->used_btf_cnt++;
12656
12657         return 0;
12658 err_put:
12659         btf_put(btf);
12660         return err;
12661 }
12662
12663 static bool is_tracing_prog_type(enum bpf_prog_type type)
12664 {
12665         switch (type) {
12666         case BPF_PROG_TYPE_KPROBE:
12667         case BPF_PROG_TYPE_TRACEPOINT:
12668         case BPF_PROG_TYPE_PERF_EVENT:
12669         case BPF_PROG_TYPE_RAW_TRACEPOINT:
12670         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
12671                 return true;
12672         default:
12673                 return false;
12674         }
12675 }
12676
12677 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
12678                                         struct bpf_map *map,
12679                                         struct bpf_prog *prog)
12680
12681 {
12682         enum bpf_prog_type prog_type = resolve_prog_type(prog);
12683
12684         if (map_value_has_spin_lock(map)) {
12685                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12686                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12687                         return -EINVAL;
12688                 }
12689
12690                 if (is_tracing_prog_type(prog_type)) {
12691                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12692                         return -EINVAL;
12693                 }
12694
12695                 if (prog->aux->sleepable) {
12696                         verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12697                         return -EINVAL;
12698                 }
12699         }
12700
12701         if (map_value_has_timer(map)) {
12702                 if (is_tracing_prog_type(prog_type)) {
12703                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
12704                         return -EINVAL;
12705                 }
12706         }
12707
12708         if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
12709             !bpf_offload_prog_map_match(prog, map)) {
12710                 verbose(env, "offload device mismatch between prog and map\n");
12711                 return -EINVAL;
12712         }
12713
12714         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12715                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12716                 return -EINVAL;
12717         }
12718
12719         if (prog->aux->sleepable)
12720                 switch (map->map_type) {
12721                 case BPF_MAP_TYPE_HASH:
12722                 case BPF_MAP_TYPE_LRU_HASH:
12723                 case BPF_MAP_TYPE_ARRAY:
12724                 case BPF_MAP_TYPE_PERCPU_HASH:
12725                 case BPF_MAP_TYPE_PERCPU_ARRAY:
12726                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12727                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12728                 case BPF_MAP_TYPE_HASH_OF_MAPS:
12729                 case BPF_MAP_TYPE_RINGBUF:
12730                 case BPF_MAP_TYPE_USER_RINGBUF:
12731                 case BPF_MAP_TYPE_INODE_STORAGE:
12732                 case BPF_MAP_TYPE_SK_STORAGE:
12733                 case BPF_MAP_TYPE_TASK_STORAGE:
12734                         break;
12735                 default:
12736                         verbose(env,
12737                                 "Sleepable programs can only use array, hash, and ringbuf maps\n");
12738                         return -EINVAL;
12739                 }
12740
12741         return 0;
12742 }
12743
12744 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12745 {
12746         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12747                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12748 }
12749
12750 /* find and rewrite pseudo imm in ld_imm64 instructions:
12751  *
12752  * 1. if it accesses map FD, replace it with actual map pointer.
12753  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12754  *
12755  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
12756  */
12757 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
12758 {
12759         struct bpf_insn *insn = env->prog->insnsi;
12760         int insn_cnt = env->prog->len;
12761         int i, j, err;
12762
12763         err = bpf_prog_calc_tag(env->prog);
12764         if (err)
12765                 return err;
12766
12767         for (i = 0; i < insn_cnt; i++, insn++) {
12768                 if (BPF_CLASS(insn->code) == BPF_LDX &&
12769                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
12770                         verbose(env, "BPF_LDX uses reserved fields\n");
12771                         return -EINVAL;
12772                 }
12773
12774                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
12775                         struct bpf_insn_aux_data *aux;
12776                         struct bpf_map *map;
12777                         struct fd f;
12778                         u64 addr;
12779                         u32 fd;
12780
12781                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
12782                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12783                             insn[1].off != 0) {
12784                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
12785                                 return -EINVAL;
12786                         }
12787
12788                         if (insn[0].src_reg == 0)
12789                                 /* valid generic load 64-bit imm */
12790                                 goto next_insn;
12791
12792                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12793                                 aux = &env->insn_aux_data[i];
12794                                 err = check_pseudo_btf_id(env, insn, aux);
12795                                 if (err)
12796                                         return err;
12797                                 goto next_insn;
12798                         }
12799
12800                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12801                                 aux = &env->insn_aux_data[i];
12802                                 aux->ptr_type = PTR_TO_FUNC;
12803                                 goto next_insn;
12804                         }
12805
12806                         /* In final convert_pseudo_ld_imm64() step, this is
12807                          * converted into regular 64-bit imm load insn.
12808                          */
12809                         switch (insn[0].src_reg) {
12810                         case BPF_PSEUDO_MAP_VALUE:
12811                         case BPF_PSEUDO_MAP_IDX_VALUE:
12812                                 break;
12813                         case BPF_PSEUDO_MAP_FD:
12814                         case BPF_PSEUDO_MAP_IDX:
12815                                 if (insn[1].imm == 0)
12816                                         break;
12817                                 fallthrough;
12818                         default:
12819                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12820                                 return -EINVAL;
12821                         }
12822
12823                         switch (insn[0].src_reg) {
12824                         case BPF_PSEUDO_MAP_IDX_VALUE:
12825                         case BPF_PSEUDO_MAP_IDX:
12826                                 if (bpfptr_is_null(env->fd_array)) {
12827                                         verbose(env, "fd_idx without fd_array is invalid\n");
12828                                         return -EPROTO;
12829                                 }
12830                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
12831                                                             insn[0].imm * sizeof(fd),
12832                                                             sizeof(fd)))
12833                                         return -EFAULT;
12834                                 break;
12835                         default:
12836                                 fd = insn[0].imm;
12837                                 break;
12838                         }
12839
12840                         f = fdget(fd);
12841                         map = __bpf_map_get(f);
12842                         if (IS_ERR(map)) {
12843                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
12844                                         insn[0].imm);
12845                                 return PTR_ERR(map);
12846                         }
12847
12848                         err = check_map_prog_compatibility(env, map, env->prog);
12849                         if (err) {
12850                                 fdput(f);
12851                                 return err;
12852                         }
12853
12854                         aux = &env->insn_aux_data[i];
12855                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12856                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12857                                 addr = (unsigned long)map;
12858                         } else {
12859                                 u32 off = insn[1].imm;
12860
12861                                 if (off >= BPF_MAX_VAR_OFF) {
12862                                         verbose(env, "direct value offset of %u is not allowed\n", off);
12863                                         fdput(f);
12864                                         return -EINVAL;
12865                                 }
12866
12867                                 if (!map->ops->map_direct_value_addr) {
12868                                         verbose(env, "no direct value access support for this map type\n");
12869                                         fdput(f);
12870                                         return -EINVAL;
12871                                 }
12872
12873                                 err = map->ops->map_direct_value_addr(map, &addr, off);
12874                                 if (err) {
12875                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12876                                                 map->value_size, off);
12877                                         fdput(f);
12878                                         return err;
12879                                 }
12880
12881                                 aux->map_off = off;
12882                                 addr += off;
12883                         }
12884
12885                         insn[0].imm = (u32)addr;
12886                         insn[1].imm = addr >> 32;
12887
12888                         /* check whether we recorded this map already */
12889                         for (j = 0; j < env->used_map_cnt; j++) {
12890                                 if (env->used_maps[j] == map) {
12891                                         aux->map_index = j;
12892                                         fdput(f);
12893                                         goto next_insn;
12894                                 }
12895                         }
12896
12897                         if (env->used_map_cnt >= MAX_USED_MAPS) {
12898                                 fdput(f);
12899                                 return -E2BIG;
12900                         }
12901
12902                         /* hold the map. If the program is rejected by verifier,
12903                          * the map will be released by release_maps() or it
12904                          * will be used by the valid program until it's unloaded
12905                          * and all maps are released in free_used_maps()
12906                          */
12907                         bpf_map_inc(map);
12908
12909                         aux->map_index = env->used_map_cnt;
12910                         env->used_maps[env->used_map_cnt++] = map;
12911
12912                         if (bpf_map_is_cgroup_storage(map) &&
12913                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
12914                                 verbose(env, "only one cgroup storage of each type is allowed\n");
12915                                 fdput(f);
12916                                 return -EBUSY;
12917                         }
12918
12919                         fdput(f);
12920 next_insn:
12921                         insn++;
12922                         i++;
12923                         continue;
12924                 }
12925
12926                 /* Basic sanity check before we invest more work here. */
12927                 if (!bpf_opcode_in_insntable(insn->code)) {
12928                         verbose(env, "unknown opcode %02x\n", insn->code);
12929                         return -EINVAL;
12930                 }
12931         }
12932
12933         /* now all pseudo BPF_LD_IMM64 instructions load valid
12934          * 'struct bpf_map *' into a register instead of user map_fd.
12935          * These pointers will be used later by verifier to validate map access.
12936          */
12937         return 0;
12938 }
12939
12940 /* drop refcnt of maps used by the rejected program */
12941 static void release_maps(struct bpf_verifier_env *env)
12942 {
12943         __bpf_free_used_maps(env->prog->aux, env->used_maps,
12944                              env->used_map_cnt);
12945 }
12946
12947 /* drop refcnt of maps used by the rejected program */
12948 static void release_btfs(struct bpf_verifier_env *env)
12949 {
12950         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
12951                              env->used_btf_cnt);
12952 }
12953
12954 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
12955 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
12956 {
12957         struct bpf_insn *insn = env->prog->insnsi;
12958         int insn_cnt = env->prog->len;
12959         int i;
12960
12961         for (i = 0; i < insn_cnt; i++, insn++) {
12962                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
12963                         continue;
12964                 if (insn->src_reg == BPF_PSEUDO_FUNC)
12965                         continue;
12966                 insn->src_reg = 0;
12967         }
12968 }
12969
12970 /* single env->prog->insni[off] instruction was replaced with the range
12971  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
12972  * [0, off) and [off, end) to new locations, so the patched range stays zero
12973  */
12974 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
12975                                  struct bpf_insn_aux_data *new_data,
12976                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
12977 {
12978         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
12979         struct bpf_insn *insn = new_prog->insnsi;
12980         u32 old_seen = old_data[off].seen;
12981         u32 prog_len;
12982         int i;
12983
12984         /* aux info at OFF always needs adjustment, no matter fast path
12985          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
12986          * original insn at old prog.
12987          */
12988         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
12989
12990         if (cnt == 1)
12991                 return;
12992         prog_len = new_prog->len;
12993
12994         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
12995         memcpy(new_data + off + cnt - 1, old_data + off,
12996                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
12997         for (i = off; i < off + cnt - 1; i++) {
12998                 /* Expand insni[off]'s seen count to the patched range. */
12999                 new_data[i].seen = old_seen;
13000                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
13001         }
13002         env->insn_aux_data = new_data;
13003         vfree(old_data);
13004 }
13005
13006 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
13007 {
13008         int i;
13009
13010         if (len == 1)
13011                 return;
13012         /* NOTE: fake 'exit' subprog should be updated as well. */
13013         for (i = 0; i <= env->subprog_cnt; i++) {
13014                 if (env->subprog_info[i].start <= off)
13015                         continue;
13016                 env->subprog_info[i].start += len - 1;
13017         }
13018 }
13019
13020 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
13021 {
13022         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
13023         int i, sz = prog->aux->size_poke_tab;
13024         struct bpf_jit_poke_descriptor *desc;
13025
13026         for (i = 0; i < sz; i++) {
13027                 desc = &tab[i];
13028                 if (desc->insn_idx <= off)
13029                         continue;
13030                 desc->insn_idx += len - 1;
13031         }
13032 }
13033
13034 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
13035                                             const struct bpf_insn *patch, u32 len)
13036 {
13037         struct bpf_prog *new_prog;
13038         struct bpf_insn_aux_data *new_data = NULL;
13039
13040         if (len > 1) {
13041                 new_data = vzalloc(array_size(env->prog->len + len - 1,
13042                                               sizeof(struct bpf_insn_aux_data)));
13043                 if (!new_data)
13044                         return NULL;
13045         }
13046
13047         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
13048         if (IS_ERR(new_prog)) {
13049                 if (PTR_ERR(new_prog) == -ERANGE)
13050                         verbose(env,
13051                                 "insn %d cannot be patched due to 16-bit range\n",
13052                                 env->insn_aux_data[off].orig_idx);
13053                 vfree(new_data);
13054                 return NULL;
13055         }
13056         adjust_insn_aux_data(env, new_data, new_prog, off, len);
13057         adjust_subprog_starts(env, off, len);
13058         adjust_poke_descs(new_prog, off, len);
13059         return new_prog;
13060 }
13061
13062 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
13063                                               u32 off, u32 cnt)
13064 {
13065         int i, j;
13066
13067         /* find first prog starting at or after off (first to remove) */
13068         for (i = 0; i < env->subprog_cnt; i++)
13069                 if (env->subprog_info[i].start >= off)
13070                         break;
13071         /* find first prog starting at or after off + cnt (first to stay) */
13072         for (j = i; j < env->subprog_cnt; j++)
13073                 if (env->subprog_info[j].start >= off + cnt)
13074                         break;
13075         /* if j doesn't start exactly at off + cnt, we are just removing
13076          * the front of previous prog
13077          */
13078         if (env->subprog_info[j].start != off + cnt)
13079                 j--;
13080
13081         if (j > i) {
13082                 struct bpf_prog_aux *aux = env->prog->aux;
13083                 int move;
13084
13085                 /* move fake 'exit' subprog as well */
13086                 move = env->subprog_cnt + 1 - j;
13087
13088                 memmove(env->subprog_info + i,
13089                         env->subprog_info + j,
13090                         sizeof(*env->subprog_info) * move);
13091                 env->subprog_cnt -= j - i;
13092
13093                 /* remove func_info */
13094                 if (aux->func_info) {
13095                         move = aux->func_info_cnt - j;
13096
13097                         memmove(aux->func_info + i,
13098                                 aux->func_info + j,
13099                                 sizeof(*aux->func_info) * move);
13100                         aux->func_info_cnt -= j - i;
13101                         /* func_info->insn_off is set after all code rewrites,
13102                          * in adjust_btf_func() - no need to adjust
13103                          */
13104                 }
13105         } else {
13106                 /* convert i from "first prog to remove" to "first to adjust" */
13107                 if (env->subprog_info[i].start == off)
13108                         i++;
13109         }
13110
13111         /* update fake 'exit' subprog as well */
13112         for (; i <= env->subprog_cnt; i++)
13113                 env->subprog_info[i].start -= cnt;
13114
13115         return 0;
13116 }
13117
13118 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
13119                                       u32 cnt)
13120 {
13121         struct bpf_prog *prog = env->prog;
13122         u32 i, l_off, l_cnt, nr_linfo;
13123         struct bpf_line_info *linfo;
13124
13125         nr_linfo = prog->aux->nr_linfo;
13126         if (!nr_linfo)
13127                 return 0;
13128
13129         linfo = prog->aux->linfo;
13130
13131         /* find first line info to remove, count lines to be removed */
13132         for (i = 0; i < nr_linfo; i++)
13133                 if (linfo[i].insn_off >= off)
13134                         break;
13135
13136         l_off = i;
13137         l_cnt = 0;
13138         for (; i < nr_linfo; i++)
13139                 if (linfo[i].insn_off < off + cnt)
13140                         l_cnt++;
13141                 else
13142                         break;
13143
13144         /* First live insn doesn't match first live linfo, it needs to "inherit"
13145          * last removed linfo.  prog is already modified, so prog->len == off
13146          * means no live instructions after (tail of the program was removed).
13147          */
13148         if (prog->len != off && l_cnt &&
13149             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
13150                 l_cnt--;
13151                 linfo[--i].insn_off = off + cnt;
13152         }
13153
13154         /* remove the line info which refer to the removed instructions */
13155         if (l_cnt) {
13156                 memmove(linfo + l_off, linfo + i,
13157                         sizeof(*linfo) * (nr_linfo - i));
13158
13159                 prog->aux->nr_linfo -= l_cnt;
13160                 nr_linfo = prog->aux->nr_linfo;
13161         }
13162
13163         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
13164         for (i = l_off; i < nr_linfo; i++)
13165                 linfo[i].insn_off -= cnt;
13166
13167         /* fix up all subprogs (incl. 'exit') which start >= off */
13168         for (i = 0; i <= env->subprog_cnt; i++)
13169                 if (env->subprog_info[i].linfo_idx > l_off) {
13170                         /* program may have started in the removed region but
13171                          * may not be fully removed
13172                          */
13173                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
13174                                 env->subprog_info[i].linfo_idx -= l_cnt;
13175                         else
13176                                 env->subprog_info[i].linfo_idx = l_off;
13177                 }
13178
13179         return 0;
13180 }
13181
13182 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
13183 {
13184         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13185         unsigned int orig_prog_len = env->prog->len;
13186         int err;
13187
13188         if (bpf_prog_is_dev_bound(env->prog->aux))
13189                 bpf_prog_offload_remove_insns(env, off, cnt);
13190
13191         err = bpf_remove_insns(env->prog, off, cnt);
13192         if (err)
13193                 return err;
13194
13195         err = adjust_subprog_starts_after_remove(env, off, cnt);
13196         if (err)
13197                 return err;
13198
13199         err = bpf_adj_linfo_after_remove(env, off, cnt);
13200         if (err)
13201                 return err;
13202
13203         memmove(aux_data + off, aux_data + off + cnt,
13204                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
13205
13206         return 0;
13207 }
13208
13209 /* The verifier does more data flow analysis than llvm and will not
13210  * explore branches that are dead at run time. Malicious programs can
13211  * have dead code too. Therefore replace all dead at-run-time code
13212  * with 'ja -1'.
13213  *
13214  * Just nops are not optimal, e.g. if they would sit at the end of the
13215  * program and through another bug we would manage to jump there, then
13216  * we'd execute beyond program memory otherwise. Returning exception
13217  * code also wouldn't work since we can have subprogs where the dead
13218  * code could be located.
13219  */
13220 static void sanitize_dead_code(struct bpf_verifier_env *env)
13221 {
13222         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13223         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
13224         struct bpf_insn *insn = env->prog->insnsi;
13225         const int insn_cnt = env->prog->len;
13226         int i;
13227
13228         for (i = 0; i < insn_cnt; i++) {
13229                 if (aux_data[i].seen)
13230                         continue;
13231                 memcpy(insn + i, &trap, sizeof(trap));
13232                 aux_data[i].zext_dst = false;
13233         }
13234 }
13235
13236 static bool insn_is_cond_jump(u8 code)
13237 {
13238         u8 op;
13239
13240         if (BPF_CLASS(code) == BPF_JMP32)
13241                 return true;
13242
13243         if (BPF_CLASS(code) != BPF_JMP)
13244                 return false;
13245
13246         op = BPF_OP(code);
13247         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
13248 }
13249
13250 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
13251 {
13252         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13253         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13254         struct bpf_insn *insn = env->prog->insnsi;
13255         const int insn_cnt = env->prog->len;
13256         int i;
13257
13258         for (i = 0; i < insn_cnt; i++, insn++) {
13259                 if (!insn_is_cond_jump(insn->code))
13260                         continue;
13261
13262                 if (!aux_data[i + 1].seen)
13263                         ja.off = insn->off;
13264                 else if (!aux_data[i + 1 + insn->off].seen)
13265                         ja.off = 0;
13266                 else
13267                         continue;
13268
13269                 if (bpf_prog_is_dev_bound(env->prog->aux))
13270                         bpf_prog_offload_replace_insn(env, i, &ja);
13271
13272                 memcpy(insn, &ja, sizeof(ja));
13273         }
13274 }
13275
13276 static int opt_remove_dead_code(struct bpf_verifier_env *env)
13277 {
13278         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13279         int insn_cnt = env->prog->len;
13280         int i, err;
13281
13282         for (i = 0; i < insn_cnt; i++) {
13283                 int j;
13284
13285                 j = 0;
13286                 while (i + j < insn_cnt && !aux_data[i + j].seen)
13287                         j++;
13288                 if (!j)
13289                         continue;
13290
13291                 err = verifier_remove_insns(env, i, j);
13292                 if (err)
13293                         return err;
13294                 insn_cnt = env->prog->len;
13295         }
13296
13297         return 0;
13298 }
13299
13300 static int opt_remove_nops(struct bpf_verifier_env *env)
13301 {
13302         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13303         struct bpf_insn *insn = env->prog->insnsi;
13304         int insn_cnt = env->prog->len;
13305         int i, err;
13306
13307         for (i = 0; i < insn_cnt; i++) {
13308                 if (memcmp(&insn[i], &ja, sizeof(ja)))
13309                         continue;
13310
13311                 err = verifier_remove_insns(env, i, 1);
13312                 if (err)
13313                         return err;
13314                 insn_cnt--;
13315                 i--;
13316         }
13317
13318         return 0;
13319 }
13320
13321 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
13322                                          const union bpf_attr *attr)
13323 {
13324         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
13325         struct bpf_insn_aux_data *aux = env->insn_aux_data;
13326         int i, patch_len, delta = 0, len = env->prog->len;
13327         struct bpf_insn *insns = env->prog->insnsi;
13328         struct bpf_prog *new_prog;
13329         bool rnd_hi32;
13330
13331         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
13332         zext_patch[1] = BPF_ZEXT_REG(0);
13333         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
13334         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
13335         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
13336         for (i = 0; i < len; i++) {
13337                 int adj_idx = i + delta;
13338                 struct bpf_insn insn;
13339                 int load_reg;
13340
13341                 insn = insns[adj_idx];
13342                 load_reg = insn_def_regno(&insn);
13343                 if (!aux[adj_idx].zext_dst) {
13344                         u8 code, class;
13345                         u32 imm_rnd;
13346
13347                         if (!rnd_hi32)
13348                                 continue;
13349
13350                         code = insn.code;
13351                         class = BPF_CLASS(code);
13352                         if (load_reg == -1)
13353                                 continue;
13354
13355                         /* NOTE: arg "reg" (the fourth one) is only used for
13356                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
13357                          *       here.
13358                          */
13359                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
13360                                 if (class == BPF_LD &&
13361                                     BPF_MODE(code) == BPF_IMM)
13362                                         i++;
13363                                 continue;
13364                         }
13365
13366                         /* ctx load could be transformed into wider load. */
13367                         if (class == BPF_LDX &&
13368                             aux[adj_idx].ptr_type == PTR_TO_CTX)
13369                                 continue;
13370
13371                         imm_rnd = get_random_u32();
13372                         rnd_hi32_patch[0] = insn;
13373                         rnd_hi32_patch[1].imm = imm_rnd;
13374                         rnd_hi32_patch[3].dst_reg = load_reg;
13375                         patch = rnd_hi32_patch;
13376                         patch_len = 4;
13377                         goto apply_patch_buffer;
13378                 }
13379
13380                 /* Add in an zero-extend instruction if a) the JIT has requested
13381                  * it or b) it's a CMPXCHG.
13382                  *
13383                  * The latter is because: BPF_CMPXCHG always loads a value into
13384                  * R0, therefore always zero-extends. However some archs'
13385                  * equivalent instruction only does this load when the
13386                  * comparison is successful. This detail of CMPXCHG is
13387                  * orthogonal to the general zero-extension behaviour of the
13388                  * CPU, so it's treated independently of bpf_jit_needs_zext.
13389                  */
13390                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
13391                         continue;
13392
13393                 if (WARN_ON(load_reg == -1)) {
13394                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
13395                         return -EFAULT;
13396                 }
13397
13398                 zext_patch[0] = insn;
13399                 zext_patch[1].dst_reg = load_reg;
13400                 zext_patch[1].src_reg = load_reg;
13401                 patch = zext_patch;
13402                 patch_len = 2;
13403 apply_patch_buffer:
13404                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
13405                 if (!new_prog)
13406                         return -ENOMEM;
13407                 env->prog = new_prog;
13408                 insns = new_prog->insnsi;
13409                 aux = env->insn_aux_data;
13410                 delta += patch_len - 1;
13411         }
13412
13413         return 0;
13414 }
13415
13416 /* convert load instructions that access fields of a context type into a
13417  * sequence of instructions that access fields of the underlying structure:
13418  *     struct __sk_buff    -> struct sk_buff
13419  *     struct bpf_sock_ops -> struct sock
13420  */
13421 static int convert_ctx_accesses(struct bpf_verifier_env *env)
13422 {
13423         const struct bpf_verifier_ops *ops = env->ops;
13424         int i, cnt, size, ctx_field_size, delta = 0;
13425         const int insn_cnt = env->prog->len;
13426         struct bpf_insn insn_buf[16], *insn;
13427         u32 target_size, size_default, off;
13428         struct bpf_prog *new_prog;
13429         enum bpf_access_type type;
13430         bool is_narrower_load;
13431
13432         if (ops->gen_prologue || env->seen_direct_write) {
13433                 if (!ops->gen_prologue) {
13434                         verbose(env, "bpf verifier is misconfigured\n");
13435                         return -EINVAL;
13436                 }
13437                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
13438                                         env->prog);
13439                 if (cnt >= ARRAY_SIZE(insn_buf)) {
13440                         verbose(env, "bpf verifier is misconfigured\n");
13441                         return -EINVAL;
13442                 } else if (cnt) {
13443                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
13444                         if (!new_prog)
13445                                 return -ENOMEM;
13446
13447                         env->prog = new_prog;
13448                         delta += cnt - 1;
13449                 }
13450         }
13451
13452         if (bpf_prog_is_dev_bound(env->prog->aux))
13453                 return 0;
13454
13455         insn = env->prog->insnsi + delta;
13456
13457         for (i = 0; i < insn_cnt; i++, insn++) {
13458                 bpf_convert_ctx_access_t convert_ctx_access;
13459                 bool ctx_access;
13460
13461                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
13462                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
13463                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
13464                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
13465                         type = BPF_READ;
13466                         ctx_access = true;
13467                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
13468                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
13469                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
13470                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
13471                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
13472                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
13473                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
13474                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
13475                         type = BPF_WRITE;
13476                         ctx_access = BPF_CLASS(insn->code) == BPF_STX;
13477                 } else {
13478                         continue;
13479                 }
13480
13481                 if (type == BPF_WRITE &&
13482                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
13483                         struct bpf_insn patch[] = {
13484                                 *insn,
13485                                 BPF_ST_NOSPEC(),
13486                         };
13487
13488                         cnt = ARRAY_SIZE(patch);
13489                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
13490                         if (!new_prog)
13491                                 return -ENOMEM;
13492
13493                         delta    += cnt - 1;
13494                         env->prog = new_prog;
13495                         insn      = new_prog->insnsi + i + delta;
13496                         continue;
13497                 }
13498
13499                 if (!ctx_access)
13500                         continue;
13501
13502                 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
13503                 case PTR_TO_CTX:
13504                         if (!ops->convert_ctx_access)
13505                                 continue;
13506                         convert_ctx_access = ops->convert_ctx_access;
13507                         break;
13508                 case PTR_TO_SOCKET:
13509                 case PTR_TO_SOCK_COMMON:
13510                         convert_ctx_access = bpf_sock_convert_ctx_access;
13511                         break;
13512                 case PTR_TO_TCP_SOCK:
13513                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
13514                         break;
13515                 case PTR_TO_XDP_SOCK:
13516                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
13517                         break;
13518                 case PTR_TO_BTF_ID:
13519                 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
13520                         if (type == BPF_READ) {
13521                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
13522                                         BPF_SIZE((insn)->code);
13523                                 env->prog->aux->num_exentries++;
13524                         }
13525                         continue;
13526                 default:
13527                         continue;
13528                 }
13529
13530                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
13531                 size = BPF_LDST_BYTES(insn);
13532
13533                 /* If the read access is a narrower load of the field,
13534                  * convert to a 4/8-byte load, to minimum program type specific
13535                  * convert_ctx_access changes. If conversion is successful,
13536                  * we will apply proper mask to the result.
13537                  */
13538                 is_narrower_load = size < ctx_field_size;
13539                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
13540                 off = insn->off;
13541                 if (is_narrower_load) {
13542                         u8 size_code;
13543
13544                         if (type == BPF_WRITE) {
13545                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
13546                                 return -EINVAL;
13547                         }
13548
13549                         size_code = BPF_H;
13550                         if (ctx_field_size == 4)
13551                                 size_code = BPF_W;
13552                         else if (ctx_field_size == 8)
13553                                 size_code = BPF_DW;
13554
13555                         insn->off = off & ~(size_default - 1);
13556                         insn->code = BPF_LDX | BPF_MEM | size_code;
13557                 }
13558
13559                 target_size = 0;
13560                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
13561                                          &target_size);
13562                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
13563                     (ctx_field_size && !target_size)) {
13564                         verbose(env, "bpf verifier is misconfigured\n");
13565                         return -EINVAL;
13566                 }
13567
13568                 if (is_narrower_load && size < target_size) {
13569                         u8 shift = bpf_ctx_narrow_access_offset(
13570                                 off, size, size_default) * 8;
13571                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
13572                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
13573                                 return -EINVAL;
13574                         }
13575                         if (ctx_field_size <= 4) {
13576                                 if (shift)
13577                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
13578                                                                         insn->dst_reg,
13579                                                                         shift);
13580                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13581                                                                 (1 << size * 8) - 1);
13582                         } else {
13583                                 if (shift)
13584                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
13585                                                                         insn->dst_reg,
13586                                                                         shift);
13587                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
13588                                                                 (1ULL << size * 8) - 1);
13589                         }
13590                 }
13591
13592                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13593                 if (!new_prog)
13594                         return -ENOMEM;
13595
13596                 delta += cnt - 1;
13597
13598                 /* keep walking new program and skip insns we just inserted */
13599                 env->prog = new_prog;
13600                 insn      = new_prog->insnsi + i + delta;
13601         }
13602
13603         return 0;
13604 }
13605
13606 static int jit_subprogs(struct bpf_verifier_env *env)
13607 {
13608         struct bpf_prog *prog = env->prog, **func, *tmp;
13609         int i, j, subprog_start, subprog_end = 0, len, subprog;
13610         struct bpf_map *map_ptr;
13611         struct bpf_insn *insn;
13612         void *old_bpf_func;
13613         int err, num_exentries;
13614
13615         if (env->subprog_cnt <= 1)
13616                 return 0;
13617
13618         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13619                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
13620                         continue;
13621
13622                 /* Upon error here we cannot fall back to interpreter but
13623                  * need a hard reject of the program. Thus -EFAULT is
13624                  * propagated in any case.
13625                  */
13626                 subprog = find_subprog(env, i + insn->imm + 1);
13627                 if (subprog < 0) {
13628                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
13629                                   i + insn->imm + 1);
13630                         return -EFAULT;
13631                 }
13632                 /* temporarily remember subprog id inside insn instead of
13633                  * aux_data, since next loop will split up all insns into funcs
13634                  */
13635                 insn->off = subprog;
13636                 /* remember original imm in case JIT fails and fallback
13637                  * to interpreter will be needed
13638                  */
13639                 env->insn_aux_data[i].call_imm = insn->imm;
13640                 /* point imm to __bpf_call_base+1 from JITs point of view */
13641                 insn->imm = 1;
13642                 if (bpf_pseudo_func(insn))
13643                         /* jit (e.g. x86_64) may emit fewer instructions
13644                          * if it learns a u32 imm is the same as a u64 imm.
13645                          * Force a non zero here.
13646                          */
13647                         insn[1].imm = 1;
13648         }
13649
13650         err = bpf_prog_alloc_jited_linfo(prog);
13651         if (err)
13652                 goto out_undo_insn;
13653
13654         err = -ENOMEM;
13655         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
13656         if (!func)
13657                 goto out_undo_insn;
13658
13659         for (i = 0; i < env->subprog_cnt; i++) {
13660                 subprog_start = subprog_end;
13661                 subprog_end = env->subprog_info[i + 1].start;
13662
13663                 len = subprog_end - subprog_start;
13664                 /* bpf_prog_run() doesn't call subprogs directly,
13665                  * hence main prog stats include the runtime of subprogs.
13666                  * subprogs don't have IDs and not reachable via prog_get_next_id
13667                  * func[i]->stats will never be accessed and stays NULL
13668                  */
13669                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
13670                 if (!func[i])
13671                         goto out_free;
13672                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
13673                        len * sizeof(struct bpf_insn));
13674                 func[i]->type = prog->type;
13675                 func[i]->len = len;
13676                 if (bpf_prog_calc_tag(func[i]))
13677                         goto out_free;
13678                 func[i]->is_func = 1;
13679                 func[i]->aux->func_idx = i;
13680                 /* Below members will be freed only at prog->aux */
13681                 func[i]->aux->btf = prog->aux->btf;
13682                 func[i]->aux->func_info = prog->aux->func_info;
13683                 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
13684                 func[i]->aux->poke_tab = prog->aux->poke_tab;
13685                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13686
13687                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
13688                         struct bpf_jit_poke_descriptor *poke;
13689
13690                         poke = &prog->aux->poke_tab[j];
13691                         if (poke->insn_idx < subprog_end &&
13692                             poke->insn_idx >= subprog_start)
13693                                 poke->aux = func[i]->aux;
13694                 }
13695
13696                 func[i]->aux->name[0] = 'F';
13697                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13698                 func[i]->jit_requested = 1;
13699                 func[i]->blinding_requested = prog->blinding_requested;
13700                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13701                 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
13702                 func[i]->aux->linfo = prog->aux->linfo;
13703                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13704                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13705                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
13706                 num_exentries = 0;
13707                 insn = func[i]->insnsi;
13708                 for (j = 0; j < func[i]->len; j++, insn++) {
13709                         if (BPF_CLASS(insn->code) == BPF_LDX &&
13710                             BPF_MODE(insn->code) == BPF_PROBE_MEM)
13711                                 num_exentries++;
13712                 }
13713                 func[i]->aux->num_exentries = num_exentries;
13714                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
13715                 func[i] = bpf_int_jit_compile(func[i]);
13716                 if (!func[i]->jited) {
13717                         err = -ENOTSUPP;
13718                         goto out_free;
13719                 }
13720                 cond_resched();
13721         }
13722
13723         /* at this point all bpf functions were successfully JITed
13724          * now populate all bpf_calls with correct addresses and
13725          * run last pass of JIT
13726          */
13727         for (i = 0; i < env->subprog_cnt; i++) {
13728                 insn = func[i]->insnsi;
13729                 for (j = 0; j < func[i]->len; j++, insn++) {
13730                         if (bpf_pseudo_func(insn)) {
13731                                 subprog = insn->off;
13732                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13733                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13734                                 continue;
13735                         }
13736                         if (!bpf_pseudo_call(insn))
13737                                 continue;
13738                         subprog = insn->off;
13739                         insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
13740                 }
13741
13742                 /* we use the aux data to keep a list of the start addresses
13743                  * of the JITed images for each function in the program
13744                  *
13745                  * for some architectures, such as powerpc64, the imm field
13746                  * might not be large enough to hold the offset of the start
13747                  * address of the callee's JITed image from __bpf_call_base
13748                  *
13749                  * in such cases, we can lookup the start address of a callee
13750                  * by using its subprog id, available from the off field of
13751                  * the call instruction, as an index for this list
13752                  */
13753                 func[i]->aux->func = func;
13754                 func[i]->aux->func_cnt = env->subprog_cnt;
13755         }
13756         for (i = 0; i < env->subprog_cnt; i++) {
13757                 old_bpf_func = func[i]->bpf_func;
13758                 tmp = bpf_int_jit_compile(func[i]);
13759                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13760                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
13761                         err = -ENOTSUPP;
13762                         goto out_free;
13763                 }
13764                 cond_resched();
13765         }
13766
13767         /* finally lock prog and jit images for all functions and
13768          * populate kallsysm
13769          */
13770         for (i = 0; i < env->subprog_cnt; i++) {
13771                 bpf_prog_lock_ro(func[i]);
13772                 bpf_prog_kallsyms_add(func[i]);
13773         }
13774
13775         /* Last step: make now unused interpreter insns from main
13776          * prog consistent for later dump requests, so they can
13777          * later look the same as if they were interpreted only.
13778          */
13779         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13780                 if (bpf_pseudo_func(insn)) {
13781                         insn[0].imm = env->insn_aux_data[i].call_imm;
13782                         insn[1].imm = insn->off;
13783                         insn->off = 0;
13784                         continue;
13785                 }
13786                 if (!bpf_pseudo_call(insn))
13787                         continue;
13788                 insn->off = env->insn_aux_data[i].call_imm;
13789                 subprog = find_subprog(env, i + insn->off + 1);
13790                 insn->imm = subprog;
13791         }
13792
13793         prog->jited = 1;
13794         prog->bpf_func = func[0]->bpf_func;
13795         prog->jited_len = func[0]->jited_len;
13796         prog->aux->func = func;
13797         prog->aux->func_cnt = env->subprog_cnt;
13798         bpf_prog_jit_attempt_done(prog);
13799         return 0;
13800 out_free:
13801         /* We failed JIT'ing, so at this point we need to unregister poke
13802          * descriptors from subprogs, so that kernel is not attempting to
13803          * patch it anymore as we're freeing the subprog JIT memory.
13804          */
13805         for (i = 0; i < prog->aux->size_poke_tab; i++) {
13806                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
13807                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13808         }
13809         /* At this point we're guaranteed that poke descriptors are not
13810          * live anymore. We can just unlink its descriptor table as it's
13811          * released with the main prog.
13812          */
13813         for (i = 0; i < env->subprog_cnt; i++) {
13814                 if (!func[i])
13815                         continue;
13816                 func[i]->aux->poke_tab = NULL;
13817                 bpf_jit_free(func[i]);
13818         }
13819         kfree(func);
13820 out_undo_insn:
13821         /* cleanup main prog to be interpreted */
13822         prog->jit_requested = 0;
13823         prog->blinding_requested = 0;
13824         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13825                 if (!bpf_pseudo_call(insn))
13826                         continue;
13827                 insn->off = 0;
13828                 insn->imm = env->insn_aux_data[i].call_imm;
13829         }
13830         bpf_prog_jit_attempt_done(prog);
13831         return err;
13832 }
13833
13834 static int fixup_call_args(struct bpf_verifier_env *env)
13835 {
13836 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13837         struct bpf_prog *prog = env->prog;
13838         struct bpf_insn *insn = prog->insnsi;
13839         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13840         int i, depth;
13841 #endif
13842         int err = 0;
13843
13844         if (env->prog->jit_requested &&
13845             !bpf_prog_is_dev_bound(env->prog->aux)) {
13846                 err = jit_subprogs(env);
13847                 if (err == 0)
13848                         return 0;
13849                 if (err == -EFAULT)
13850                         return err;
13851         }
13852 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13853         if (has_kfunc_call) {
13854                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13855                 return -EINVAL;
13856         }
13857         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13858                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
13859                  * have to be rejected, since interpreter doesn't support them yet.
13860                  */
13861                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13862                 return -EINVAL;
13863         }
13864         for (i = 0; i < prog->len; i++, insn++) {
13865                 if (bpf_pseudo_func(insn)) {
13866                         /* When JIT fails the progs with callback calls
13867                          * have to be rejected, since interpreter doesn't support them yet.
13868                          */
13869                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
13870                         return -EINVAL;
13871                 }
13872
13873                 if (!bpf_pseudo_call(insn))
13874                         continue;
13875                 depth = get_callee_stack_depth(env, insn, i);
13876                 if (depth < 0)
13877                         return depth;
13878                 bpf_patch_call_args(insn, depth);
13879         }
13880         err = 0;
13881 #endif
13882         return err;
13883 }
13884
13885 static int fixup_kfunc_call(struct bpf_verifier_env *env,
13886                             struct bpf_insn *insn)
13887 {
13888         const struct bpf_kfunc_desc *desc;
13889
13890         if (!insn->imm) {
13891                 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13892                 return -EINVAL;
13893         }
13894
13895         /* insn->imm has the btf func_id. Replace it with
13896          * an address (relative to __bpf_base_call).
13897          */
13898         desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
13899         if (!desc) {
13900                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13901                         insn->imm);
13902                 return -EFAULT;
13903         }
13904
13905         insn->imm = desc->imm;
13906
13907         return 0;
13908 }
13909
13910 /* Do various post-verification rewrites in a single program pass.
13911  * These rewrites simplify JIT and interpreter implementations.
13912  */
13913 static int do_misc_fixups(struct bpf_verifier_env *env)
13914 {
13915         struct bpf_prog *prog = env->prog;
13916         enum bpf_attach_type eatype = prog->expected_attach_type;
13917         enum bpf_prog_type prog_type = resolve_prog_type(prog);
13918         struct bpf_insn *insn = prog->insnsi;
13919         const struct bpf_func_proto *fn;
13920         const int insn_cnt = prog->len;
13921         const struct bpf_map_ops *ops;
13922         struct bpf_insn_aux_data *aux;
13923         struct bpf_insn insn_buf[16];
13924         struct bpf_prog *new_prog;
13925         struct bpf_map *map_ptr;
13926         int i, ret, cnt, delta = 0;
13927
13928         for (i = 0; i < insn_cnt; i++, insn++) {
13929                 /* Make divide-by-zero exceptions impossible. */
13930                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
13931                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
13932                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
13933                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
13934                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
13935                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
13936                         struct bpf_insn *patchlet;
13937                         struct bpf_insn chk_and_div[] = {
13938                                 /* [R,W]x div 0 -> 0 */
13939                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13940                                              BPF_JNE | BPF_K, insn->src_reg,
13941                                              0, 2, 0),
13942                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
13943                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13944                                 *insn,
13945                         };
13946                         struct bpf_insn chk_and_mod[] = {
13947                                 /* [R,W]x mod 0 -> [R,W]x */
13948                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13949                                              BPF_JEQ | BPF_K, insn->src_reg,
13950                                              0, 1 + (is64 ? 0 : 1), 0),
13951                                 *insn,
13952                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13953                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
13954                         };
13955
13956                         patchlet = isdiv ? chk_and_div : chk_and_mod;
13957                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
13958                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
13959
13960                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
13961                         if (!new_prog)
13962                                 return -ENOMEM;
13963
13964                         delta    += cnt - 1;
13965                         env->prog = prog = new_prog;
13966                         insn      = new_prog->insnsi + i + delta;
13967                         continue;
13968                 }
13969
13970                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
13971                 if (BPF_CLASS(insn->code) == BPF_LD &&
13972                     (BPF_MODE(insn->code) == BPF_ABS ||
13973                      BPF_MODE(insn->code) == BPF_IND)) {
13974                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
13975                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13976                                 verbose(env, "bpf verifier is misconfigured\n");
13977                                 return -EINVAL;
13978                         }
13979
13980                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13981                         if (!new_prog)
13982                                 return -ENOMEM;
13983
13984                         delta    += cnt - 1;
13985                         env->prog = prog = new_prog;
13986                         insn      = new_prog->insnsi + i + delta;
13987                         continue;
13988                 }
13989
13990                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
13991                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
13992                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
13993                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
13994                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
13995                         struct bpf_insn *patch = &insn_buf[0];
13996                         bool issrc, isneg, isimm;
13997                         u32 off_reg;
13998
13999                         aux = &env->insn_aux_data[i + delta];
14000                         if (!aux->alu_state ||
14001                             aux->alu_state == BPF_ALU_NON_POINTER)
14002                                 continue;
14003
14004                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
14005                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
14006                                 BPF_ALU_SANITIZE_SRC;
14007                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
14008
14009                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
14010                         if (isimm) {
14011                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14012                         } else {
14013                                 if (isneg)
14014                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14015                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14016                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
14017                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
14018                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
14019                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
14020                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
14021                         }
14022                         if (!issrc)
14023                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
14024                         insn->src_reg = BPF_REG_AX;
14025                         if (isneg)
14026                                 insn->code = insn->code == code_add ?
14027                                              code_sub : code_add;
14028                         *patch++ = *insn;
14029                         if (issrc && isneg && !isimm)
14030                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14031                         cnt = patch - insn_buf;
14032
14033                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14034                         if (!new_prog)
14035                                 return -ENOMEM;
14036
14037                         delta    += cnt - 1;
14038                         env->prog = prog = new_prog;
14039                         insn      = new_prog->insnsi + i + delta;
14040                         continue;
14041                 }
14042
14043                 if (insn->code != (BPF_JMP | BPF_CALL))
14044                         continue;
14045                 if (insn->src_reg == BPF_PSEUDO_CALL)
14046                         continue;
14047                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14048                         ret = fixup_kfunc_call(env, insn);
14049                         if (ret)
14050                                 return ret;
14051                         continue;
14052                 }
14053
14054                 if (insn->imm == BPF_FUNC_get_route_realm)
14055                         prog->dst_needed = 1;
14056                 if (insn->imm == BPF_FUNC_get_prandom_u32)
14057                         bpf_user_rnd_init_once();
14058                 if (insn->imm == BPF_FUNC_override_return)
14059                         prog->kprobe_override = 1;
14060                 if (insn->imm == BPF_FUNC_tail_call) {
14061                         /* If we tail call into other programs, we
14062                          * cannot make any assumptions since they can
14063                          * be replaced dynamically during runtime in
14064                          * the program array.
14065                          */
14066                         prog->cb_access = 1;
14067                         if (!allow_tail_call_in_subprogs(env))
14068                                 prog->aux->stack_depth = MAX_BPF_STACK;
14069                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
14070
14071                         /* mark bpf_tail_call as different opcode to avoid
14072                          * conditional branch in the interpreter for every normal
14073                          * call and to prevent accidental JITing by JIT compiler
14074                          * that doesn't support bpf_tail_call yet
14075                          */
14076                         insn->imm = 0;
14077                         insn->code = BPF_JMP | BPF_TAIL_CALL;
14078
14079                         aux = &env->insn_aux_data[i + delta];
14080                         if (env->bpf_capable && !prog->blinding_requested &&
14081                             prog->jit_requested &&
14082                             !bpf_map_key_poisoned(aux) &&
14083                             !bpf_map_ptr_poisoned(aux) &&
14084                             !bpf_map_ptr_unpriv(aux)) {
14085                                 struct bpf_jit_poke_descriptor desc = {
14086                                         .reason = BPF_POKE_REASON_TAIL_CALL,
14087                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
14088                                         .tail_call.key = bpf_map_key_immediate(aux),
14089                                         .insn_idx = i + delta,
14090                                 };
14091
14092                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
14093                                 if (ret < 0) {
14094                                         verbose(env, "adding tail call poke descriptor failed\n");
14095                                         return ret;
14096                                 }
14097
14098                                 insn->imm = ret + 1;
14099                                 continue;
14100                         }
14101
14102                         if (!bpf_map_ptr_unpriv(aux))
14103                                 continue;
14104
14105                         /* instead of changing every JIT dealing with tail_call
14106                          * emit two extra insns:
14107                          * if (index >= max_entries) goto out;
14108                          * index &= array->index_mask;
14109                          * to avoid out-of-bounds cpu speculation
14110                          */
14111                         if (bpf_map_ptr_poisoned(aux)) {
14112                                 verbose(env, "tail_call abusing map_ptr\n");
14113                                 return -EINVAL;
14114                         }
14115
14116                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14117                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
14118                                                   map_ptr->max_entries, 2);
14119                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
14120                                                     container_of(map_ptr,
14121                                                                  struct bpf_array,
14122                                                                  map)->index_mask);
14123                         insn_buf[2] = *insn;
14124                         cnt = 3;
14125                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14126                         if (!new_prog)
14127                                 return -ENOMEM;
14128
14129                         delta    += cnt - 1;
14130                         env->prog = prog = new_prog;
14131                         insn      = new_prog->insnsi + i + delta;
14132                         continue;
14133                 }
14134
14135                 if (insn->imm == BPF_FUNC_timer_set_callback) {
14136                         /* The verifier will process callback_fn as many times as necessary
14137                          * with different maps and the register states prepared by
14138                          * set_timer_callback_state will be accurate.
14139                          *
14140                          * The following use case is valid:
14141                          *   map1 is shared by prog1, prog2, prog3.
14142                          *   prog1 calls bpf_timer_init for some map1 elements
14143                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
14144                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
14145                          *   prog3 calls bpf_timer_start for some map1 elements.
14146                          *     Those that were not both bpf_timer_init-ed and
14147                          *     bpf_timer_set_callback-ed will return -EINVAL.
14148                          */
14149                         struct bpf_insn ld_addrs[2] = {
14150                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
14151                         };
14152
14153                         insn_buf[0] = ld_addrs[0];
14154                         insn_buf[1] = ld_addrs[1];
14155                         insn_buf[2] = *insn;
14156                         cnt = 3;
14157
14158                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14159                         if (!new_prog)
14160                                 return -ENOMEM;
14161
14162                         delta    += cnt - 1;
14163                         env->prog = prog = new_prog;
14164                         insn      = new_prog->insnsi + i + delta;
14165                         goto patch_call_imm;
14166                 }
14167
14168                 if (insn->imm == BPF_FUNC_task_storage_get ||
14169                     insn->imm == BPF_FUNC_sk_storage_get ||
14170                     insn->imm == BPF_FUNC_inode_storage_get) {
14171                         if (env->prog->aux->sleepable)
14172                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
14173                         else
14174                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
14175                         insn_buf[1] = *insn;
14176                         cnt = 2;
14177
14178                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14179                         if (!new_prog)
14180                                 return -ENOMEM;
14181
14182                         delta += cnt - 1;
14183                         env->prog = prog = new_prog;
14184                         insn = new_prog->insnsi + i + delta;
14185                         goto patch_call_imm;
14186                 }
14187
14188                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
14189                  * and other inlining handlers are currently limited to 64 bit
14190                  * only.
14191                  */
14192                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14193                     (insn->imm == BPF_FUNC_map_lookup_elem ||
14194                      insn->imm == BPF_FUNC_map_update_elem ||
14195                      insn->imm == BPF_FUNC_map_delete_elem ||
14196                      insn->imm == BPF_FUNC_map_push_elem   ||
14197                      insn->imm == BPF_FUNC_map_pop_elem    ||
14198                      insn->imm == BPF_FUNC_map_peek_elem   ||
14199                      insn->imm == BPF_FUNC_redirect_map    ||
14200                      insn->imm == BPF_FUNC_for_each_map_elem ||
14201                      insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
14202                         aux = &env->insn_aux_data[i + delta];
14203                         if (bpf_map_ptr_poisoned(aux))
14204                                 goto patch_call_imm;
14205
14206                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14207                         ops = map_ptr->ops;
14208                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
14209                             ops->map_gen_lookup) {
14210                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
14211                                 if (cnt == -EOPNOTSUPP)
14212                                         goto patch_map_ops_generic;
14213                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14214                                         verbose(env, "bpf verifier is misconfigured\n");
14215                                         return -EINVAL;
14216                                 }
14217
14218                                 new_prog = bpf_patch_insn_data(env, i + delta,
14219                                                                insn_buf, cnt);
14220                                 if (!new_prog)
14221                                         return -ENOMEM;
14222
14223                                 delta    += cnt - 1;
14224                                 env->prog = prog = new_prog;
14225                                 insn      = new_prog->insnsi + i + delta;
14226                                 continue;
14227                         }
14228
14229                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
14230                                      (void *(*)(struct bpf_map *map, void *key))NULL));
14231                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
14232                                      (int (*)(struct bpf_map *map, void *key))NULL));
14233                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
14234                                      (int (*)(struct bpf_map *map, void *key, void *value,
14235                                               u64 flags))NULL));
14236                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
14237                                      (int (*)(struct bpf_map *map, void *value,
14238                                               u64 flags))NULL));
14239                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
14240                                      (int (*)(struct bpf_map *map, void *value))NULL));
14241                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
14242                                      (int (*)(struct bpf_map *map, void *value))NULL));
14243                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
14244                                      (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
14245                         BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
14246                                      (int (*)(struct bpf_map *map,
14247                                               bpf_callback_t callback_fn,
14248                                               void *callback_ctx,
14249                                               u64 flags))NULL));
14250                         BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
14251                                      (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
14252
14253 patch_map_ops_generic:
14254                         switch (insn->imm) {
14255                         case BPF_FUNC_map_lookup_elem:
14256                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
14257                                 continue;
14258                         case BPF_FUNC_map_update_elem:
14259                                 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
14260                                 continue;
14261                         case BPF_FUNC_map_delete_elem:
14262                                 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
14263                                 continue;
14264                         case BPF_FUNC_map_push_elem:
14265                                 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
14266                                 continue;
14267                         case BPF_FUNC_map_pop_elem:
14268                                 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
14269                                 continue;
14270                         case BPF_FUNC_map_peek_elem:
14271                                 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
14272                                 continue;
14273                         case BPF_FUNC_redirect_map:
14274                                 insn->imm = BPF_CALL_IMM(ops->map_redirect);
14275                                 continue;
14276                         case BPF_FUNC_for_each_map_elem:
14277                                 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
14278                                 continue;
14279                         case BPF_FUNC_map_lookup_percpu_elem:
14280                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
14281                                 continue;
14282                         }
14283
14284                         goto patch_call_imm;
14285                 }
14286
14287                 /* Implement bpf_jiffies64 inline. */
14288                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14289                     insn->imm == BPF_FUNC_jiffies64) {
14290                         struct bpf_insn ld_jiffies_addr[2] = {
14291                                 BPF_LD_IMM64(BPF_REG_0,
14292                                              (unsigned long)&jiffies),
14293                         };
14294
14295                         insn_buf[0] = ld_jiffies_addr[0];
14296                         insn_buf[1] = ld_jiffies_addr[1];
14297                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
14298                                                   BPF_REG_0, 0);
14299                         cnt = 3;
14300
14301                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
14302                                                        cnt);
14303                         if (!new_prog)
14304                                 return -ENOMEM;
14305
14306                         delta    += cnt - 1;
14307                         env->prog = prog = new_prog;
14308                         insn      = new_prog->insnsi + i + delta;
14309                         continue;
14310                 }
14311
14312                 /* Implement bpf_get_func_arg inline. */
14313                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14314                     insn->imm == BPF_FUNC_get_func_arg) {
14315                         /* Load nr_args from ctx - 8 */
14316                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14317                         insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
14318                         insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
14319                         insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
14320                         insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
14321                         insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14322                         insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
14323                         insn_buf[7] = BPF_JMP_A(1);
14324                         insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
14325                         cnt = 9;
14326
14327                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14328                         if (!new_prog)
14329                                 return -ENOMEM;
14330
14331                         delta    += cnt - 1;
14332                         env->prog = prog = new_prog;
14333                         insn      = new_prog->insnsi + i + delta;
14334                         continue;
14335                 }
14336
14337                 /* Implement bpf_get_func_ret inline. */
14338                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14339                     insn->imm == BPF_FUNC_get_func_ret) {
14340                         if (eatype == BPF_TRACE_FEXIT ||
14341                             eatype == BPF_MODIFY_RETURN) {
14342                                 /* Load nr_args from ctx - 8 */
14343                                 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14344                                 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
14345                                 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
14346                                 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14347                                 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
14348                                 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
14349                                 cnt = 6;
14350                         } else {
14351                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
14352                                 cnt = 1;
14353                         }
14354
14355                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14356                         if (!new_prog)
14357                                 return -ENOMEM;
14358
14359                         delta    += cnt - 1;
14360                         env->prog = prog = new_prog;
14361                         insn      = new_prog->insnsi + i + delta;
14362                         continue;
14363                 }
14364
14365                 /* Implement get_func_arg_cnt inline. */
14366                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14367                     insn->imm == BPF_FUNC_get_func_arg_cnt) {
14368                         /* Load nr_args from ctx - 8 */
14369                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14370
14371                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14372                         if (!new_prog)
14373                                 return -ENOMEM;
14374
14375                         env->prog = prog = new_prog;
14376                         insn      = new_prog->insnsi + i + delta;
14377                         continue;
14378                 }
14379
14380                 /* Implement bpf_get_func_ip inline. */
14381                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14382                     insn->imm == BPF_FUNC_get_func_ip) {
14383                         /* Load IP address from ctx - 16 */
14384                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
14385
14386                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14387                         if (!new_prog)
14388                                 return -ENOMEM;
14389
14390                         env->prog = prog = new_prog;
14391                         insn      = new_prog->insnsi + i + delta;
14392                         continue;
14393                 }
14394
14395 patch_call_imm:
14396                 fn = env->ops->get_func_proto(insn->imm, env->prog);
14397                 /* all functions that have prototype and verifier allowed
14398                  * programs to call them, must be real in-kernel functions
14399                  */
14400                 if (!fn->func) {
14401                         verbose(env,
14402                                 "kernel subsystem misconfigured func %s#%d\n",
14403                                 func_id_name(insn->imm), insn->imm);
14404                         return -EFAULT;
14405                 }
14406                 insn->imm = fn->func - __bpf_call_base;
14407         }
14408
14409         /* Since poke tab is now finalized, publish aux to tracker. */
14410         for (i = 0; i < prog->aux->size_poke_tab; i++) {
14411                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
14412                 if (!map_ptr->ops->map_poke_track ||
14413                     !map_ptr->ops->map_poke_untrack ||
14414                     !map_ptr->ops->map_poke_run) {
14415                         verbose(env, "bpf verifier is misconfigured\n");
14416                         return -EINVAL;
14417                 }
14418
14419                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
14420                 if (ret < 0) {
14421                         verbose(env, "tracking tail call prog failed\n");
14422                         return ret;
14423                 }
14424         }
14425
14426         sort_kfunc_descs_by_imm(env->prog);
14427
14428         return 0;
14429 }
14430
14431 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
14432                                         int position,
14433                                         s32 stack_base,
14434                                         u32 callback_subprogno,
14435                                         u32 *cnt)
14436 {
14437         s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
14438         s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
14439         s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
14440         int reg_loop_max = BPF_REG_6;
14441         int reg_loop_cnt = BPF_REG_7;
14442         int reg_loop_ctx = BPF_REG_8;
14443
14444         struct bpf_prog *new_prog;
14445         u32 callback_start;
14446         u32 call_insn_offset;
14447         s32 callback_offset;
14448
14449         /* This represents an inlined version of bpf_iter.c:bpf_loop,
14450          * be careful to modify this code in sync.
14451          */
14452         struct bpf_insn insn_buf[] = {
14453                 /* Return error and jump to the end of the patch if
14454                  * expected number of iterations is too big.
14455                  */
14456                 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
14457                 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
14458                 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
14459                 /* spill R6, R7, R8 to use these as loop vars */
14460                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
14461                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
14462                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
14463                 /* initialize loop vars */
14464                 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
14465                 BPF_MOV32_IMM(reg_loop_cnt, 0),
14466                 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
14467                 /* loop header,
14468                  * if reg_loop_cnt >= reg_loop_max skip the loop body
14469                  */
14470                 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
14471                 /* callback call,
14472                  * correct callback offset would be set after patching
14473                  */
14474                 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
14475                 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
14476                 BPF_CALL_REL(0),
14477                 /* increment loop counter */
14478                 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
14479                 /* jump to loop header if callback returned 0 */
14480                 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
14481                 /* return value of bpf_loop,
14482                  * set R0 to the number of iterations
14483                  */
14484                 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
14485                 /* restore original values of R6, R7, R8 */
14486                 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
14487                 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
14488                 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
14489         };
14490
14491         *cnt = ARRAY_SIZE(insn_buf);
14492         new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
14493         if (!new_prog)
14494                 return new_prog;
14495
14496         /* callback start is known only after patching */
14497         callback_start = env->subprog_info[callback_subprogno].start;
14498         /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
14499         call_insn_offset = position + 12;
14500         callback_offset = callback_start - call_insn_offset - 1;
14501         new_prog->insnsi[call_insn_offset].imm = callback_offset;
14502
14503         return new_prog;
14504 }
14505
14506 static bool is_bpf_loop_call(struct bpf_insn *insn)
14507 {
14508         return insn->code == (BPF_JMP | BPF_CALL) &&
14509                 insn->src_reg == 0 &&
14510                 insn->imm == BPF_FUNC_loop;
14511 }
14512
14513 /* For all sub-programs in the program (including main) check
14514  * insn_aux_data to see if there are bpf_loop calls that require
14515  * inlining. If such calls are found the calls are replaced with a
14516  * sequence of instructions produced by `inline_bpf_loop` function and
14517  * subprog stack_depth is increased by the size of 3 registers.
14518  * This stack space is used to spill values of the R6, R7, R8.  These
14519  * registers are used to store the loop bound, counter and context
14520  * variables.
14521  */
14522 static int optimize_bpf_loop(struct bpf_verifier_env *env)
14523 {
14524         struct bpf_subprog_info *subprogs = env->subprog_info;
14525         int i, cur_subprog = 0, cnt, delta = 0;
14526         struct bpf_insn *insn = env->prog->insnsi;
14527         int insn_cnt = env->prog->len;
14528         u16 stack_depth = subprogs[cur_subprog].stack_depth;
14529         u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14530         u16 stack_depth_extra = 0;
14531
14532         for (i = 0; i < insn_cnt; i++, insn++) {
14533                 struct bpf_loop_inline_state *inline_state =
14534                         &env->insn_aux_data[i + delta].loop_inline_state;
14535
14536                 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
14537                         struct bpf_prog *new_prog;
14538
14539                         stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
14540                         new_prog = inline_bpf_loop(env,
14541                                                    i + delta,
14542                                                    -(stack_depth + stack_depth_extra),
14543                                                    inline_state->callback_subprogno,
14544                                                    &cnt);
14545                         if (!new_prog)
14546                                 return -ENOMEM;
14547
14548                         delta     += cnt - 1;
14549                         env->prog  = new_prog;
14550                         insn       = new_prog->insnsi + i + delta;
14551                 }
14552
14553                 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
14554                         subprogs[cur_subprog].stack_depth += stack_depth_extra;
14555                         cur_subprog++;
14556                         stack_depth = subprogs[cur_subprog].stack_depth;
14557                         stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14558                         stack_depth_extra = 0;
14559                 }
14560         }
14561
14562         env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14563
14564         return 0;
14565 }
14566
14567 static void free_states(struct bpf_verifier_env *env)
14568 {
14569         struct bpf_verifier_state_list *sl, *sln;
14570         int i;
14571
14572         sl = env->free_list;
14573         while (sl) {
14574                 sln = sl->next;
14575                 free_verifier_state(&sl->state, false);
14576                 kfree(sl);
14577                 sl = sln;
14578         }
14579         env->free_list = NULL;
14580
14581         if (!env->explored_states)
14582                 return;
14583
14584         for (i = 0; i < state_htab_size(env); i++) {
14585                 sl = env->explored_states[i];
14586
14587                 while (sl) {
14588                         sln = sl->next;
14589                         free_verifier_state(&sl->state, false);
14590                         kfree(sl);
14591                         sl = sln;
14592                 }
14593                 env->explored_states[i] = NULL;
14594         }
14595 }
14596
14597 static int do_check_common(struct bpf_verifier_env *env, int subprog)
14598 {
14599         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14600         struct bpf_verifier_state *state;
14601         struct bpf_reg_state *regs;
14602         int ret, i;
14603
14604         env->prev_linfo = NULL;
14605         env->pass_cnt++;
14606
14607         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
14608         if (!state)
14609                 return -ENOMEM;
14610         state->curframe = 0;
14611         state->speculative = false;
14612         state->branches = 1;
14613         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
14614         if (!state->frame[0]) {
14615                 kfree(state);
14616                 return -ENOMEM;
14617         }
14618         env->cur_state = state;
14619         init_func_state(env, state->frame[0],
14620                         BPF_MAIN_FUNC /* callsite */,
14621                         0 /* frameno */,
14622                         subprog);
14623
14624         regs = state->frame[state->curframe]->regs;
14625         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
14626                 ret = btf_prepare_func_args(env, subprog, regs);
14627                 if (ret)
14628                         goto out;
14629                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
14630                         if (regs[i].type == PTR_TO_CTX)
14631                                 mark_reg_known_zero(env, regs, i);
14632                         else if (regs[i].type == SCALAR_VALUE)
14633                                 mark_reg_unknown(env, regs, i);
14634                         else if (base_type(regs[i].type) == PTR_TO_MEM) {
14635                                 const u32 mem_size = regs[i].mem_size;
14636
14637                                 mark_reg_known_zero(env, regs, i);
14638                                 regs[i].mem_size = mem_size;
14639                                 regs[i].id = ++env->id_gen;
14640                         }
14641                 }
14642         } else {
14643                 /* 1st arg to a function */
14644                 regs[BPF_REG_1].type = PTR_TO_CTX;
14645                 mark_reg_known_zero(env, regs, BPF_REG_1);
14646                 ret = btf_check_subprog_arg_match(env, subprog, regs);
14647                 if (ret == -EFAULT)
14648                         /* unlikely verifier bug. abort.
14649                          * ret == 0 and ret < 0 are sadly acceptable for
14650                          * main() function due to backward compatibility.
14651                          * Like socket filter program may be written as:
14652                          * int bpf_prog(struct pt_regs *ctx)
14653                          * and never dereference that ctx in the program.
14654                          * 'struct pt_regs' is a type mismatch for socket
14655                          * filter that should be using 'struct __sk_buff'.
14656                          */
14657                         goto out;
14658         }
14659
14660         ret = do_check(env);
14661 out:
14662         /* check for NULL is necessary, since cur_state can be freed inside
14663          * do_check() under memory pressure.
14664          */
14665         if (env->cur_state) {
14666                 free_verifier_state(env->cur_state, true);
14667                 env->cur_state = NULL;
14668         }
14669         while (!pop_stack(env, NULL, NULL, false));
14670         if (!ret && pop_log)
14671                 bpf_vlog_reset(&env->log, 0);
14672         free_states(env);
14673         return ret;
14674 }
14675
14676 /* Verify all global functions in a BPF program one by one based on their BTF.
14677  * All global functions must pass verification. Otherwise the whole program is rejected.
14678  * Consider:
14679  * int bar(int);
14680  * int foo(int f)
14681  * {
14682  *    return bar(f);
14683  * }
14684  * int bar(int b)
14685  * {
14686  *    ...
14687  * }
14688  * foo() will be verified first for R1=any_scalar_value. During verification it
14689  * will be assumed that bar() already verified successfully and call to bar()
14690  * from foo() will be checked for type match only. Later bar() will be verified
14691  * independently to check that it's safe for R1=any_scalar_value.
14692  */
14693 static int do_check_subprogs(struct bpf_verifier_env *env)
14694 {
14695         struct bpf_prog_aux *aux = env->prog->aux;
14696         int i, ret;
14697
14698         if (!aux->func_info)
14699                 return 0;
14700
14701         for (i = 1; i < env->subprog_cnt; i++) {
14702                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
14703                         continue;
14704                 env->insn_idx = env->subprog_info[i].start;
14705                 WARN_ON_ONCE(env->insn_idx == 0);
14706                 ret = do_check_common(env, i);
14707                 if (ret) {
14708                         return ret;
14709                 } else if (env->log.level & BPF_LOG_LEVEL) {
14710                         verbose(env,
14711                                 "Func#%d is safe for any args that match its prototype\n",
14712                                 i);
14713                 }
14714         }
14715         return 0;
14716 }
14717
14718 static int do_check_main(struct bpf_verifier_env *env)
14719 {
14720         int ret;
14721
14722         env->insn_idx = 0;
14723         ret = do_check_common(env, 0);
14724         if (!ret)
14725                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14726         return ret;
14727 }
14728
14729
14730 static void print_verification_stats(struct bpf_verifier_env *env)
14731 {
14732         int i;
14733
14734         if (env->log.level & BPF_LOG_STATS) {
14735                 verbose(env, "verification time %lld usec\n",
14736                         div_u64(env->verification_time, 1000));
14737                 verbose(env, "stack depth ");
14738                 for (i = 0; i < env->subprog_cnt; i++) {
14739                         u32 depth = env->subprog_info[i].stack_depth;
14740
14741                         verbose(env, "%d", depth);
14742                         if (i + 1 < env->subprog_cnt)
14743                                 verbose(env, "+");
14744                 }
14745                 verbose(env, "\n");
14746         }
14747         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
14748                 "total_states %d peak_states %d mark_read %d\n",
14749                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
14750                 env->max_states_per_insn, env->total_states,
14751                 env->peak_states, env->longest_mark_read_walk);
14752 }
14753
14754 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
14755 {
14756         const struct btf_type *t, *func_proto;
14757         const struct bpf_struct_ops *st_ops;
14758         const struct btf_member *member;
14759         struct bpf_prog *prog = env->prog;
14760         u32 btf_id, member_idx;
14761         const char *mname;
14762
14763         if (!prog->gpl_compatible) {
14764                 verbose(env, "struct ops programs must have a GPL compatible license\n");
14765                 return -EINVAL;
14766         }
14767
14768         btf_id = prog->aux->attach_btf_id;
14769         st_ops = bpf_struct_ops_find(btf_id);
14770         if (!st_ops) {
14771                 verbose(env, "attach_btf_id %u is not a supported struct\n",
14772                         btf_id);
14773                 return -ENOTSUPP;
14774         }
14775
14776         t = st_ops->type;
14777         member_idx = prog->expected_attach_type;
14778         if (member_idx >= btf_type_vlen(t)) {
14779                 verbose(env, "attach to invalid member idx %u of struct %s\n",
14780                         member_idx, st_ops->name);
14781                 return -EINVAL;
14782         }
14783
14784         member = &btf_type_member(t)[member_idx];
14785         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
14786         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
14787                                                NULL);
14788         if (!func_proto) {
14789                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
14790                         mname, member_idx, st_ops->name);
14791                 return -EINVAL;
14792         }
14793
14794         if (st_ops->check_member) {
14795                 int err = st_ops->check_member(t, member);
14796
14797                 if (err) {
14798                         verbose(env, "attach to unsupported member %s of struct %s\n",
14799                                 mname, st_ops->name);
14800                         return err;
14801                 }
14802         }
14803
14804         prog->aux->attach_func_proto = func_proto;
14805         prog->aux->attach_func_name = mname;
14806         env->ops = st_ops->verifier_ops;
14807
14808         return 0;
14809 }
14810 #define SECURITY_PREFIX "security_"
14811
14812 static int check_attach_modify_return(unsigned long addr, const char *func_name)
14813 {
14814         if (within_error_injection_list(addr) ||
14815             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
14816                 return 0;
14817
14818         return -EINVAL;
14819 }
14820
14821 /* list of non-sleepable functions that are otherwise on
14822  * ALLOW_ERROR_INJECTION list
14823  */
14824 BTF_SET_START(btf_non_sleepable_error_inject)
14825 /* Three functions below can be called from sleepable and non-sleepable context.
14826  * Assume non-sleepable from bpf safety point of view.
14827  */
14828 BTF_ID(func, __filemap_add_folio)
14829 BTF_ID(func, should_fail_alloc_page)
14830 BTF_ID(func, should_failslab)
14831 BTF_SET_END(btf_non_sleepable_error_inject)
14832
14833 static int check_non_sleepable_error_inject(u32 btf_id)
14834 {
14835         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14836 }
14837
14838 int bpf_check_attach_target(struct bpf_verifier_log *log,
14839                             const struct bpf_prog *prog,
14840                             const struct bpf_prog *tgt_prog,
14841                             u32 btf_id,
14842                             struct bpf_attach_target_info *tgt_info)
14843 {
14844         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
14845         const char prefix[] = "btf_trace_";
14846         int ret = 0, subprog = -1, i;
14847         const struct btf_type *t;
14848         bool conservative = true;
14849         const char *tname;
14850         struct btf *btf;
14851         long addr = 0;
14852
14853         if (!btf_id) {
14854                 bpf_log(log, "Tracing programs must provide btf_id\n");
14855                 return -EINVAL;
14856         }
14857         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
14858         if (!btf) {
14859                 bpf_log(log,
14860                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
14861                 return -EINVAL;
14862         }
14863         t = btf_type_by_id(btf, btf_id);
14864         if (!t) {
14865                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
14866                 return -EINVAL;
14867         }
14868         tname = btf_name_by_offset(btf, t->name_off);
14869         if (!tname) {
14870                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
14871                 return -EINVAL;
14872         }
14873         if (tgt_prog) {
14874                 struct bpf_prog_aux *aux = tgt_prog->aux;
14875
14876                 for (i = 0; i < aux->func_info_cnt; i++)
14877                         if (aux->func_info[i].type_id == btf_id) {
14878                                 subprog = i;
14879                                 break;
14880                         }
14881                 if (subprog == -1) {
14882                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
14883                         return -EINVAL;
14884                 }
14885                 conservative = aux->func_info_aux[subprog].unreliable;
14886                 if (prog_extension) {
14887                         if (conservative) {
14888                                 bpf_log(log,
14889                                         "Cannot replace static functions\n");
14890                                 return -EINVAL;
14891                         }
14892                         if (!prog->jit_requested) {
14893                                 bpf_log(log,
14894                                         "Extension programs should be JITed\n");
14895                                 return -EINVAL;
14896                         }
14897                 }
14898                 if (!tgt_prog->jited) {
14899                         bpf_log(log, "Can attach to only JITed progs\n");
14900                         return -EINVAL;
14901                 }
14902                 if (tgt_prog->type == prog->type) {
14903                         /* Cannot fentry/fexit another fentry/fexit program.
14904                          * Cannot attach program extension to another extension.
14905                          * It's ok to attach fentry/fexit to extension program.
14906                          */
14907                         bpf_log(log, "Cannot recursively attach\n");
14908                         return -EINVAL;
14909                 }
14910                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
14911                     prog_extension &&
14912                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
14913                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
14914                         /* Program extensions can extend all program types
14915                          * except fentry/fexit. The reason is the following.
14916                          * The fentry/fexit programs are used for performance
14917                          * analysis, stats and can be attached to any program
14918                          * type except themselves. When extension program is
14919                          * replacing XDP function it is necessary to allow
14920                          * performance analysis of all functions. Both original
14921                          * XDP program and its program extension. Hence
14922                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
14923                          * allowed. If extending of fentry/fexit was allowed it
14924                          * would be possible to create long call chain
14925                          * fentry->extension->fentry->extension beyond
14926                          * reasonable stack size. Hence extending fentry is not
14927                          * allowed.
14928                          */
14929                         bpf_log(log, "Cannot extend fentry/fexit\n");
14930                         return -EINVAL;
14931                 }
14932         } else {
14933                 if (prog_extension) {
14934                         bpf_log(log, "Cannot replace kernel functions\n");
14935                         return -EINVAL;
14936                 }
14937         }
14938
14939         switch (prog->expected_attach_type) {
14940         case BPF_TRACE_RAW_TP:
14941                 if (tgt_prog) {
14942                         bpf_log(log,
14943                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
14944                         return -EINVAL;
14945                 }
14946                 if (!btf_type_is_typedef(t)) {
14947                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
14948                                 btf_id);
14949                         return -EINVAL;
14950                 }
14951                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
14952                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
14953                                 btf_id, tname);
14954                         return -EINVAL;
14955                 }
14956                 tname += sizeof(prefix) - 1;
14957                 t = btf_type_by_id(btf, t->type);
14958                 if (!btf_type_is_ptr(t))
14959                         /* should never happen in valid vmlinux build */
14960                         return -EINVAL;
14961                 t = btf_type_by_id(btf, t->type);
14962                 if (!btf_type_is_func_proto(t))
14963                         /* should never happen in valid vmlinux build */
14964                         return -EINVAL;
14965
14966                 break;
14967         case BPF_TRACE_ITER:
14968                 if (!btf_type_is_func(t)) {
14969                         bpf_log(log, "attach_btf_id %u is not a function\n",
14970                                 btf_id);
14971                         return -EINVAL;
14972                 }
14973                 t = btf_type_by_id(btf, t->type);
14974                 if (!btf_type_is_func_proto(t))
14975                         return -EINVAL;
14976                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
14977                 if (ret)
14978                         return ret;
14979                 break;
14980         default:
14981                 if (!prog_extension)
14982                         return -EINVAL;
14983                 fallthrough;
14984         case BPF_MODIFY_RETURN:
14985         case BPF_LSM_MAC:
14986         case BPF_LSM_CGROUP:
14987         case BPF_TRACE_FENTRY:
14988         case BPF_TRACE_FEXIT:
14989                 if (!btf_type_is_func(t)) {
14990                         bpf_log(log, "attach_btf_id %u is not a function\n",
14991                                 btf_id);
14992                         return -EINVAL;
14993                 }
14994                 if (prog_extension &&
14995                     btf_check_type_match(log, prog, btf, t))
14996                         return -EINVAL;
14997                 t = btf_type_by_id(btf, t->type);
14998                 if (!btf_type_is_func_proto(t))
14999                         return -EINVAL;
15000
15001                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
15002                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
15003                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
15004                         return -EINVAL;
15005
15006                 if (tgt_prog && conservative)
15007                         t = NULL;
15008
15009                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15010                 if (ret < 0)
15011                         return ret;
15012
15013                 if (tgt_prog) {
15014                         if (subprog == 0)
15015                                 addr = (long) tgt_prog->bpf_func;
15016                         else
15017                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
15018                 } else {
15019                         addr = kallsyms_lookup_name(tname);
15020                         if (!addr) {
15021                                 bpf_log(log,
15022                                         "The address of function %s cannot be found\n",
15023                                         tname);
15024                                 return -ENOENT;
15025                         }
15026                 }
15027
15028                 if (prog->aux->sleepable) {
15029                         ret = -EINVAL;
15030                         switch (prog->type) {
15031                         case BPF_PROG_TYPE_TRACING:
15032                                 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
15033                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
15034                                  */
15035                                 if (!check_non_sleepable_error_inject(btf_id) &&
15036                                     within_error_injection_list(addr))
15037                                         ret = 0;
15038                                 break;
15039                         case BPF_PROG_TYPE_LSM:
15040                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
15041                                  * Only some of them are sleepable.
15042                                  */
15043                                 if (bpf_lsm_is_sleepable_hook(btf_id))
15044                                         ret = 0;
15045                                 break;
15046                         default:
15047                                 break;
15048                         }
15049                         if (ret) {
15050                                 bpf_log(log, "%s is not sleepable\n", tname);
15051                                 return ret;
15052                         }
15053                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
15054                         if (tgt_prog) {
15055                                 bpf_log(log, "can't modify return codes of BPF programs\n");
15056                                 return -EINVAL;
15057                         }
15058                         ret = check_attach_modify_return(addr, tname);
15059                         if (ret) {
15060                                 bpf_log(log, "%s() is not modifiable\n", tname);
15061                                 return ret;
15062                         }
15063                 }
15064
15065                 break;
15066         }
15067         tgt_info->tgt_addr = addr;
15068         tgt_info->tgt_name = tname;
15069         tgt_info->tgt_type = t;
15070         return 0;
15071 }
15072
15073 BTF_SET_START(btf_id_deny)
15074 BTF_ID_UNUSED
15075 #ifdef CONFIG_SMP
15076 BTF_ID(func, migrate_disable)
15077 BTF_ID(func, migrate_enable)
15078 #endif
15079 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
15080 BTF_ID(func, rcu_read_unlock_strict)
15081 #endif
15082 BTF_SET_END(btf_id_deny)
15083
15084 static int check_attach_btf_id(struct bpf_verifier_env *env)
15085 {
15086         struct bpf_prog *prog = env->prog;
15087         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
15088         struct bpf_attach_target_info tgt_info = {};
15089         u32 btf_id = prog->aux->attach_btf_id;
15090         struct bpf_trampoline *tr;
15091         int ret;
15092         u64 key;
15093
15094         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
15095                 if (prog->aux->sleepable)
15096                         /* attach_btf_id checked to be zero already */
15097                         return 0;
15098                 verbose(env, "Syscall programs can only be sleepable\n");
15099                 return -EINVAL;
15100         }
15101
15102         if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
15103             prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
15104                 verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
15105                 return -EINVAL;
15106         }
15107
15108         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
15109                 return check_struct_ops_btf_id(env);
15110
15111         if (prog->type != BPF_PROG_TYPE_TRACING &&
15112             prog->type != BPF_PROG_TYPE_LSM &&
15113             prog->type != BPF_PROG_TYPE_EXT)
15114                 return 0;
15115
15116         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
15117         if (ret)
15118                 return ret;
15119
15120         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
15121                 /* to make freplace equivalent to their targets, they need to
15122                  * inherit env->ops and expected_attach_type for the rest of the
15123                  * verification
15124                  */
15125                 env->ops = bpf_verifier_ops[tgt_prog->type];
15126                 prog->expected_attach_type = tgt_prog->expected_attach_type;
15127         }
15128
15129         /* store info about the attachment target that will be used later */
15130         prog->aux->attach_func_proto = tgt_info.tgt_type;
15131         prog->aux->attach_func_name = tgt_info.tgt_name;
15132
15133         if (tgt_prog) {
15134                 prog->aux->saved_dst_prog_type = tgt_prog->type;
15135                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
15136         }
15137
15138         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
15139                 prog->aux->attach_btf_trace = true;
15140                 return 0;
15141         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
15142                 if (!bpf_iter_prog_supported(prog))
15143                         return -EINVAL;
15144                 return 0;
15145         }
15146
15147         if (prog->type == BPF_PROG_TYPE_LSM) {
15148                 ret = bpf_lsm_verify_prog(&env->log, prog);
15149                 if (ret < 0)
15150                         return ret;
15151         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
15152                    btf_id_set_contains(&btf_id_deny, btf_id)) {
15153                 return -EINVAL;
15154         }
15155
15156         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
15157         tr = bpf_trampoline_get(key, &tgt_info);
15158         if (!tr)
15159                 return -ENOMEM;
15160
15161         prog->aux->dst_trampoline = tr;
15162         return 0;
15163 }
15164
15165 struct btf *bpf_get_btf_vmlinux(void)
15166 {
15167         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
15168                 mutex_lock(&bpf_verifier_lock);
15169                 if (!btf_vmlinux)
15170                         btf_vmlinux = btf_parse_vmlinux();
15171                 mutex_unlock(&bpf_verifier_lock);
15172         }
15173         return btf_vmlinux;
15174 }
15175
15176 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
15177 {
15178         u64 start_time = ktime_get_ns();
15179         struct bpf_verifier_env *env;
15180         struct bpf_verifier_log *log;
15181         int i, len, ret = -EINVAL;
15182         bool is_priv;
15183
15184         /* no program is valid */
15185         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
15186                 return -EINVAL;
15187
15188         /* 'struct bpf_verifier_env' can be global, but since it's not small,
15189          * allocate/free it every time bpf_check() is called
15190          */
15191         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
15192         if (!env)
15193                 return -ENOMEM;
15194         log = &env->log;
15195
15196         len = (*prog)->len;
15197         env->insn_aux_data =
15198                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
15199         ret = -ENOMEM;
15200         if (!env->insn_aux_data)
15201                 goto err_free_env;
15202         for (i = 0; i < len; i++)
15203                 env->insn_aux_data[i].orig_idx = i;
15204         env->prog = *prog;
15205         env->ops = bpf_verifier_ops[env->prog->type];
15206         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
15207         is_priv = bpf_capable();
15208
15209         bpf_get_btf_vmlinux();
15210
15211         /* grab the mutex to protect few globals used by verifier */
15212         if (!is_priv)
15213                 mutex_lock(&bpf_verifier_lock);
15214
15215         if (attr->log_level || attr->log_buf || attr->log_size) {
15216                 /* user requested verbose verifier output
15217                  * and supplied buffer to store the verification trace
15218                  */
15219                 log->level = attr->log_level;
15220                 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
15221                 log->len_total = attr->log_size;
15222
15223                 /* log attributes have to be sane */
15224                 if (!bpf_verifier_log_attr_valid(log)) {
15225                         ret = -EINVAL;
15226                         goto err_unlock;
15227                 }
15228         }
15229
15230         mark_verifier_state_clean(env);
15231
15232         if (IS_ERR(btf_vmlinux)) {
15233                 /* Either gcc or pahole or kernel are broken. */
15234                 verbose(env, "in-kernel BTF is malformed\n");
15235                 ret = PTR_ERR(btf_vmlinux);
15236                 goto skip_full_check;
15237         }
15238
15239         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
15240         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
15241                 env->strict_alignment = true;
15242         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
15243                 env->strict_alignment = false;
15244
15245         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
15246         env->allow_uninit_stack = bpf_allow_uninit_stack();
15247         env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
15248         env->bypass_spec_v1 = bpf_bypass_spec_v1();
15249         env->bypass_spec_v4 = bpf_bypass_spec_v4();
15250         env->bpf_capable = bpf_capable();
15251
15252         if (is_priv)
15253                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
15254
15255         env->explored_states = kvcalloc(state_htab_size(env),
15256                                        sizeof(struct bpf_verifier_state_list *),
15257                                        GFP_USER);
15258         ret = -ENOMEM;
15259         if (!env->explored_states)
15260                 goto skip_full_check;
15261
15262         ret = add_subprog_and_kfunc(env);
15263         if (ret < 0)
15264                 goto skip_full_check;
15265
15266         ret = check_subprogs(env);
15267         if (ret < 0)
15268                 goto skip_full_check;
15269
15270         ret = check_btf_info(env, attr, uattr);
15271         if (ret < 0)
15272                 goto skip_full_check;
15273
15274         ret = check_attach_btf_id(env);
15275         if (ret)
15276                 goto skip_full_check;
15277
15278         ret = resolve_pseudo_ldimm64(env);
15279         if (ret < 0)
15280                 goto skip_full_check;
15281
15282         if (bpf_prog_is_dev_bound(env->prog->aux)) {
15283                 ret = bpf_prog_offload_verifier_prep(env->prog);
15284                 if (ret)
15285                         goto skip_full_check;
15286         }
15287
15288         ret = check_cfg(env);
15289         if (ret < 0)
15290                 goto skip_full_check;
15291
15292         ret = do_check_subprogs(env);
15293         ret = ret ?: do_check_main(env);
15294
15295         if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
15296                 ret = bpf_prog_offload_finalize(env);
15297
15298 skip_full_check:
15299         kvfree(env->explored_states);
15300
15301         if (ret == 0)
15302                 ret = check_max_stack_depth(env);
15303
15304         /* instruction rewrites happen after this point */
15305         if (ret == 0)
15306                 ret = optimize_bpf_loop(env);
15307
15308         if (is_priv) {
15309                 if (ret == 0)
15310                         opt_hard_wire_dead_code_branches(env);
15311                 if (ret == 0)
15312                         ret = opt_remove_dead_code(env);
15313                 if (ret == 0)
15314                         ret = opt_remove_nops(env);
15315         } else {
15316                 if (ret == 0)
15317                         sanitize_dead_code(env);
15318         }
15319
15320         if (ret == 0)
15321                 /* program is valid, convert *(u32*)(ctx + off) accesses */
15322                 ret = convert_ctx_accesses(env);
15323
15324         if (ret == 0)
15325                 ret = do_misc_fixups(env);
15326
15327         /* do 32-bit optimization after insn patching has done so those patched
15328          * insns could be handled correctly.
15329          */
15330         if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
15331                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
15332                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
15333                                                                      : false;
15334         }
15335
15336         if (ret == 0)
15337                 ret = fixup_call_args(env);
15338
15339         env->verification_time = ktime_get_ns() - start_time;
15340         print_verification_stats(env);
15341         env->prog->aux->verified_insns = env->insn_processed;
15342
15343         if (log->level && bpf_verifier_log_full(log))
15344                 ret = -ENOSPC;
15345         if (log->level && !log->ubuf) {
15346                 ret = -EFAULT;
15347                 goto err_release_maps;
15348         }
15349
15350         if (ret)
15351                 goto err_release_maps;
15352
15353         if (env->used_map_cnt) {
15354                 /* if program passed verifier, update used_maps in bpf_prog_info */
15355                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
15356                                                           sizeof(env->used_maps[0]),
15357                                                           GFP_KERNEL);
15358
15359                 if (!env->prog->aux->used_maps) {
15360                         ret = -ENOMEM;
15361                         goto err_release_maps;
15362                 }
15363
15364                 memcpy(env->prog->aux->used_maps, env->used_maps,
15365                        sizeof(env->used_maps[0]) * env->used_map_cnt);
15366                 env->prog->aux->used_map_cnt = env->used_map_cnt;
15367         }
15368         if (env->used_btf_cnt) {
15369                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
15370                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
15371                                                           sizeof(env->used_btfs[0]),
15372                                                           GFP_KERNEL);
15373                 if (!env->prog->aux->used_btfs) {
15374                         ret = -ENOMEM;
15375                         goto err_release_maps;
15376                 }
15377
15378                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
15379                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
15380                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
15381         }
15382         if (env->used_map_cnt || env->used_btf_cnt) {
15383                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
15384                  * bpf_ld_imm64 instructions
15385                  */
15386                 convert_pseudo_ld_imm64(env);
15387         }
15388
15389         adjust_btf_func(env);
15390
15391 err_release_maps:
15392         if (!env->prog->aux->used_maps)
15393                 /* if we didn't copy map pointers into bpf_prog_info, release
15394                  * them now. Otherwise free_used_maps() will release them.
15395                  */
15396                 release_maps(env);
15397         if (!env->prog->aux->used_btfs)
15398                 release_btfs(env);
15399
15400         /* extension progs temporarily inherit the attach_type of their targets
15401            for verification purposes, so set it back to zero before returning
15402          */
15403         if (env->prog->type == BPF_PROG_TYPE_EXT)
15404                 env->prog->expected_attach_type = 0;
15405
15406         *prog = env->prog;
15407 err_unlock:
15408         if (!is_priv)
15409                 mutex_unlock(&bpf_verifier_lock);
15410         vfree(env->insn_aux_data);
15411 err_free_env:
15412         kfree(env);
15413         return ret;
15414 }