Merge https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next
[linux-2.6-microblaze.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
27 #include "disasm.h"
28
29 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
30 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
31         [_id] = & _name ## _verifier_ops,
32 #define BPF_MAP_TYPE(_id, _ops)
33 #define BPF_LINK_TYPE(_id, _name)
34 #include <linux/bpf_types.h>
35 #undef BPF_PROG_TYPE
36 #undef BPF_MAP_TYPE
37 #undef BPF_LINK_TYPE
38 };
39
40 /* bpf_check() is a static code analyzer that walks eBPF program
41  * instruction by instruction and updates register/stack state.
42  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
43  *
44  * The first pass is depth-first-search to check that the program is a DAG.
45  * It rejects the following programs:
46  * - larger than BPF_MAXINSNS insns
47  * - if loop is present (detected via back-edge)
48  * - unreachable insns exist (shouldn't be a forest. program = one function)
49  * - out of bounds or malformed jumps
50  * The second pass is all possible path descent from the 1st insn.
51  * Since it's analyzing all paths through the program, the length of the
52  * analysis is limited to 64k insn, which may be hit even if total number of
53  * insn is less then 4K, but there are too many branches that change stack/regs.
54  * Number of 'branches to be analyzed' is limited to 1k
55  *
56  * On entry to each instruction, each register has a type, and the instruction
57  * changes the types of the registers depending on instruction semantics.
58  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
59  * copied to R1.
60  *
61  * All registers are 64-bit.
62  * R0 - return register
63  * R1-R5 argument passing registers
64  * R6-R9 callee saved registers
65  * R10 - frame pointer read-only
66  *
67  * At the start of BPF program the register R1 contains a pointer to bpf_context
68  * and has type PTR_TO_CTX.
69  *
70  * Verifier tracks arithmetic operations on pointers in case:
71  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
72  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
73  * 1st insn copies R10 (which has FRAME_PTR) type into R1
74  * and 2nd arithmetic instruction is pattern matched to recognize
75  * that it wants to construct a pointer to some element within stack.
76  * So after 2nd insn, the register R1 has type PTR_TO_STACK
77  * (and -20 constant is saved for further stack bounds checking).
78  * Meaning that this reg is a pointer to stack plus known immediate constant.
79  *
80  * Most of the time the registers have SCALAR_VALUE type, which
81  * means the register has some value, but it's not a valid pointer.
82  * (like pointer plus pointer becomes SCALAR_VALUE type)
83  *
84  * When verifier sees load or store instructions the type of base register
85  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
86  * four pointer types recognized by check_mem_access() function.
87  *
88  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
89  * and the range of [ptr, ptr + map's value_size) is accessible.
90  *
91  * registers used to pass values to function calls are checked against
92  * function argument constraints.
93  *
94  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
95  * It means that the register type passed to this function must be
96  * PTR_TO_STACK and it will be used inside the function as
97  * 'pointer to map element key'
98  *
99  * For example the argument constraints for bpf_map_lookup_elem():
100  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
101  *   .arg1_type = ARG_CONST_MAP_PTR,
102  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
103  *
104  * ret_type says that this function returns 'pointer to map elem value or null'
105  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
106  * 2nd argument should be a pointer to stack, which will be used inside
107  * the helper function as a pointer to map element key.
108  *
109  * On the kernel side the helper function looks like:
110  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
111  * {
112  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
113  *    void *key = (void *) (unsigned long) r2;
114  *    void *value;
115  *
116  *    here kernel can access 'key' and 'map' pointers safely, knowing that
117  *    [key, key + map->key_size) bytes are valid and were initialized on
118  *    the stack of eBPF program.
119  * }
120  *
121  * Corresponding eBPF program may look like:
122  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
123  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
124  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
125  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
126  * here verifier looks at prototype of map_lookup_elem() and sees:
127  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
128  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
129  *
130  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
131  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
132  * and were initialized prior to this call.
133  * If it's ok, then verifier allows this BPF_CALL insn and looks at
134  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
135  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
136  * returns either pointer to map value or NULL.
137  *
138  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
139  * insn, the register holding that pointer in the true branch changes state to
140  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
141  * branch. See check_cond_jmp_op().
142  *
143  * After the call R0 is set to return type of the function and registers R1-R5
144  * are set to NOT_INIT to indicate that they are no longer readable.
145  *
146  * The following reference types represent a potential reference to a kernel
147  * resource which, after first being allocated, must be checked and freed by
148  * the BPF program:
149  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
150  *
151  * When the verifier sees a helper call return a reference type, it allocates a
152  * pointer id for the reference and stores it in the current function state.
153  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
154  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
155  * passes through a NULL-check conditional. For the branch wherein the state is
156  * changed to CONST_IMM, the verifier releases the reference.
157  *
158  * For each helper function that allocates a reference, such as
159  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
160  * bpf_sk_release(). When a reference type passes into the release function,
161  * the verifier also releases the reference. If any unchecked or unreleased
162  * reference remains at the end of the program, the verifier rejects it.
163  */
164
165 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
166 struct bpf_verifier_stack_elem {
167         /* verifer state is 'st'
168          * before processing instruction 'insn_idx'
169          * and after processing instruction 'prev_insn_idx'
170          */
171         struct bpf_verifier_state st;
172         int insn_idx;
173         int prev_insn_idx;
174         struct bpf_verifier_stack_elem *next;
175         /* length of verifier log at the time this state was pushed on stack */
176         u32 log_pos;
177 };
178
179 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ    8192
180 #define BPF_COMPLEXITY_LIMIT_STATES     64
181
182 #define BPF_MAP_KEY_POISON      (1ULL << 63)
183 #define BPF_MAP_KEY_SEEN        (1ULL << 62)
184
185 #define BPF_MAP_PTR_UNPRIV      1UL
186 #define BPF_MAP_PTR_POISON      ((void *)((0xeB9FUL << 1) +     \
187                                           POISON_POINTER_DELTA))
188 #define BPF_MAP_PTR(X)          ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
189
190 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
191 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
192
193 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
194 {
195         return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
196 }
197
198 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
199 {
200         return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
201 }
202
203 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
204                               const struct bpf_map *map, bool unpriv)
205 {
206         BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
207         unpriv |= bpf_map_ptr_unpriv(aux);
208         aux->map_ptr_state = (unsigned long)map |
209                              (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
210 }
211
212 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
213 {
214         return aux->map_key_state & BPF_MAP_KEY_POISON;
215 }
216
217 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
218 {
219         return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
220 }
221
222 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
223 {
224         return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
225 }
226
227 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
228 {
229         bool poisoned = bpf_map_key_poisoned(aux);
230
231         aux->map_key_state = state | BPF_MAP_KEY_SEEN |
232                              (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
233 }
234
235 static bool bpf_pseudo_call(const struct bpf_insn *insn)
236 {
237         return insn->code == (BPF_JMP | BPF_CALL) &&
238                insn->src_reg == BPF_PSEUDO_CALL;
239 }
240
241 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
242 {
243         return insn->code == (BPF_JMP | BPF_CALL) &&
244                insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
245 }
246
247 struct bpf_call_arg_meta {
248         struct bpf_map *map_ptr;
249         bool raw_mode;
250         bool pkt_access;
251         u8 release_regno;
252         int regno;
253         int access_size;
254         int mem_size;
255         u64 msize_max_value;
256         int ref_obj_id;
257         int map_uid;
258         int func_id;
259         struct btf *btf;
260         u32 btf_id;
261         struct btf *ret_btf;
262         u32 ret_btf_id;
263         u32 subprogno;
264         struct bpf_map_value_off_desc *kptr_off_desc;
265         u8 uninit_dynptr_regno;
266 };
267
268 struct btf *btf_vmlinux;
269
270 static DEFINE_MUTEX(bpf_verifier_lock);
271
272 static const struct bpf_line_info *
273 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
274 {
275         const struct bpf_line_info *linfo;
276         const struct bpf_prog *prog;
277         u32 i, nr_linfo;
278
279         prog = env->prog;
280         nr_linfo = prog->aux->nr_linfo;
281
282         if (!nr_linfo || insn_off >= prog->len)
283                 return NULL;
284
285         linfo = prog->aux->linfo;
286         for (i = 1; i < nr_linfo; i++)
287                 if (insn_off < linfo[i].insn_off)
288                         break;
289
290         return &linfo[i - 1];
291 }
292
293 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
294                        va_list args)
295 {
296         unsigned int n;
297
298         n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
299
300         WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
301                   "verifier log line truncated - local buffer too short\n");
302
303         if (log->level == BPF_LOG_KERNEL) {
304                 bool newline = n > 0 && log->kbuf[n - 1] == '\n';
305
306                 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
307                 return;
308         }
309
310         n = min(log->len_total - log->len_used - 1, n);
311         log->kbuf[n] = '\0';
312         if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
313                 log->len_used += n;
314         else
315                 log->ubuf = NULL;
316 }
317
318 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
319 {
320         char zero = 0;
321
322         if (!bpf_verifier_log_needed(log))
323                 return;
324
325         log->len_used = new_pos;
326         if (put_user(zero, log->ubuf + new_pos))
327                 log->ubuf = NULL;
328 }
329
330 /* log_level controls verbosity level of eBPF verifier.
331  * bpf_verifier_log_write() is used to dump the verification trace to the log,
332  * so the user can figure out what's wrong with the program
333  */
334 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
335                                            const char *fmt, ...)
336 {
337         va_list args;
338
339         if (!bpf_verifier_log_needed(&env->log))
340                 return;
341
342         va_start(args, fmt);
343         bpf_verifier_vlog(&env->log, fmt, args);
344         va_end(args);
345 }
346 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
347
348 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
349 {
350         struct bpf_verifier_env *env = private_data;
351         va_list args;
352
353         if (!bpf_verifier_log_needed(&env->log))
354                 return;
355
356         va_start(args, fmt);
357         bpf_verifier_vlog(&env->log, fmt, args);
358         va_end(args);
359 }
360
361 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
362                             const char *fmt, ...)
363 {
364         va_list args;
365
366         if (!bpf_verifier_log_needed(log))
367                 return;
368
369         va_start(args, fmt);
370         bpf_verifier_vlog(log, fmt, args);
371         va_end(args);
372 }
373
374 static const char *ltrim(const char *s)
375 {
376         while (isspace(*s))
377                 s++;
378
379         return s;
380 }
381
382 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
383                                          u32 insn_off,
384                                          const char *prefix_fmt, ...)
385 {
386         const struct bpf_line_info *linfo;
387
388         if (!bpf_verifier_log_needed(&env->log))
389                 return;
390
391         linfo = find_linfo(env, insn_off);
392         if (!linfo || linfo == env->prev_linfo)
393                 return;
394
395         if (prefix_fmt) {
396                 va_list args;
397
398                 va_start(args, prefix_fmt);
399                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
400                 va_end(args);
401         }
402
403         verbose(env, "%s\n",
404                 ltrim(btf_name_by_offset(env->prog->aux->btf,
405                                          linfo->line_off)));
406
407         env->prev_linfo = linfo;
408 }
409
410 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
411                                    struct bpf_reg_state *reg,
412                                    struct tnum *range, const char *ctx,
413                                    const char *reg_name)
414 {
415         char tn_buf[48];
416
417         verbose(env, "At %s the register %s ", ctx, reg_name);
418         if (!tnum_is_unknown(reg->var_off)) {
419                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
420                 verbose(env, "has value %s", tn_buf);
421         } else {
422                 verbose(env, "has unknown scalar value");
423         }
424         tnum_strn(tn_buf, sizeof(tn_buf), *range);
425         verbose(env, " should have been in %s\n", tn_buf);
426 }
427
428 static bool type_is_pkt_pointer(enum bpf_reg_type type)
429 {
430         return type == PTR_TO_PACKET ||
431                type == PTR_TO_PACKET_META;
432 }
433
434 static bool type_is_sk_pointer(enum bpf_reg_type type)
435 {
436         return type == PTR_TO_SOCKET ||
437                 type == PTR_TO_SOCK_COMMON ||
438                 type == PTR_TO_TCP_SOCK ||
439                 type == PTR_TO_XDP_SOCK;
440 }
441
442 static bool reg_type_not_null(enum bpf_reg_type type)
443 {
444         return type == PTR_TO_SOCKET ||
445                 type == PTR_TO_TCP_SOCK ||
446                 type == PTR_TO_MAP_VALUE ||
447                 type == PTR_TO_MAP_KEY ||
448                 type == PTR_TO_SOCK_COMMON;
449 }
450
451 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
452 {
453         return reg->type == PTR_TO_MAP_VALUE &&
454                 map_value_has_spin_lock(reg->map_ptr);
455 }
456
457 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
458 {
459         return base_type(type) == PTR_TO_SOCKET ||
460                 base_type(type) == PTR_TO_TCP_SOCK ||
461                 base_type(type) == PTR_TO_MEM ||
462                 base_type(type) == PTR_TO_BTF_ID;
463 }
464
465 static bool type_is_rdonly_mem(u32 type)
466 {
467         return type & MEM_RDONLY;
468 }
469
470 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
471 {
472         return type == ARG_PTR_TO_SOCK_COMMON;
473 }
474
475 static bool type_may_be_null(u32 type)
476 {
477         return type & PTR_MAYBE_NULL;
478 }
479
480 static bool may_be_acquire_function(enum bpf_func_id func_id)
481 {
482         return 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_map_lookup_elem ||
486                 func_id == BPF_FUNC_ringbuf_reserve;
487 }
488
489 static bool is_acquire_function(enum bpf_func_id func_id,
490                                 const struct bpf_map *map)
491 {
492         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
493
494         if (func_id == BPF_FUNC_sk_lookup_tcp ||
495             func_id == BPF_FUNC_sk_lookup_udp ||
496             func_id == BPF_FUNC_skc_lookup_tcp ||
497             func_id == BPF_FUNC_ringbuf_reserve ||
498             func_id == BPF_FUNC_kptr_xchg)
499                 return true;
500
501         if (func_id == BPF_FUNC_map_lookup_elem &&
502             (map_type == BPF_MAP_TYPE_SOCKMAP ||
503              map_type == BPF_MAP_TYPE_SOCKHASH))
504                 return true;
505
506         return false;
507 }
508
509 static bool is_ptr_cast_function(enum bpf_func_id func_id)
510 {
511         return func_id == BPF_FUNC_tcp_sock ||
512                 func_id == BPF_FUNC_sk_fullsock ||
513                 func_id == BPF_FUNC_skc_to_tcp_sock ||
514                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
515                 func_id == BPF_FUNC_skc_to_udp6_sock ||
516                 func_id == BPF_FUNC_skc_to_mptcp_sock ||
517                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
518                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
519 }
520
521 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
522 {
523         return BPF_CLASS(insn->code) == BPF_STX &&
524                BPF_MODE(insn->code) == BPF_ATOMIC &&
525                insn->imm == BPF_CMPXCHG;
526 }
527
528 /* string representation of 'enum bpf_reg_type'
529  *
530  * Note that reg_type_str() can not appear more than once in a single verbose()
531  * statement.
532  */
533 static const char *reg_type_str(struct bpf_verifier_env *env,
534                                 enum bpf_reg_type type)
535 {
536         char postfix[16] = {0}, prefix[32] = {0};
537         static const char * const str[] = {
538                 [NOT_INIT]              = "?",
539                 [SCALAR_VALUE]          = "scalar",
540                 [PTR_TO_CTX]            = "ctx",
541                 [CONST_PTR_TO_MAP]      = "map_ptr",
542                 [PTR_TO_MAP_VALUE]      = "map_value",
543                 [PTR_TO_STACK]          = "fp",
544                 [PTR_TO_PACKET]         = "pkt",
545                 [PTR_TO_PACKET_META]    = "pkt_meta",
546                 [PTR_TO_PACKET_END]     = "pkt_end",
547                 [PTR_TO_FLOW_KEYS]      = "flow_keys",
548                 [PTR_TO_SOCKET]         = "sock",
549                 [PTR_TO_SOCK_COMMON]    = "sock_common",
550                 [PTR_TO_TCP_SOCK]       = "tcp_sock",
551                 [PTR_TO_TP_BUFFER]      = "tp_buffer",
552                 [PTR_TO_XDP_SOCK]       = "xdp_sock",
553                 [PTR_TO_BTF_ID]         = "ptr_",
554                 [PTR_TO_MEM]            = "mem",
555                 [PTR_TO_BUF]            = "buf",
556                 [PTR_TO_FUNC]           = "func",
557                 [PTR_TO_MAP_KEY]        = "map_key",
558         };
559
560         if (type & PTR_MAYBE_NULL) {
561                 if (base_type(type) == PTR_TO_BTF_ID)
562                         strncpy(postfix, "or_null_", 16);
563                 else
564                         strncpy(postfix, "_or_null", 16);
565         }
566
567         if (type & MEM_RDONLY)
568                 strncpy(prefix, "rdonly_", 32);
569         if (type & MEM_ALLOC)
570                 strncpy(prefix, "alloc_", 32);
571         if (type & MEM_USER)
572                 strncpy(prefix, "user_", 32);
573         if (type & MEM_PERCPU)
574                 strncpy(prefix, "percpu_", 32);
575         if (type & PTR_UNTRUSTED)
576                 strncpy(prefix, "untrusted_", 32);
577
578         snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
579                  prefix, str[base_type(type)], postfix);
580         return env->type_str_buf;
581 }
582
583 static char slot_type_char[] = {
584         [STACK_INVALID] = '?',
585         [STACK_SPILL]   = 'r',
586         [STACK_MISC]    = 'm',
587         [STACK_ZERO]    = '0',
588         [STACK_DYNPTR]  = 'd',
589 };
590
591 static void print_liveness(struct bpf_verifier_env *env,
592                            enum bpf_reg_liveness live)
593 {
594         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
595             verbose(env, "_");
596         if (live & REG_LIVE_READ)
597                 verbose(env, "r");
598         if (live & REG_LIVE_WRITTEN)
599                 verbose(env, "w");
600         if (live & REG_LIVE_DONE)
601                 verbose(env, "D");
602 }
603
604 static int get_spi(s32 off)
605 {
606         return (-off - 1) / BPF_REG_SIZE;
607 }
608
609 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
610 {
611         int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
612
613         /* We need to check that slots between [spi - nr_slots + 1, spi] are
614          * within [0, allocated_stack).
615          *
616          * Please note that the spi grows downwards. For example, a dynptr
617          * takes the size of two stack slots; the first slot will be at
618          * spi and the second slot will be at spi - 1.
619          */
620         return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
621 }
622
623 static struct bpf_func_state *func(struct bpf_verifier_env *env,
624                                    const struct bpf_reg_state *reg)
625 {
626         struct bpf_verifier_state *cur = env->cur_state;
627
628         return cur->frame[reg->frameno];
629 }
630
631 static const char *kernel_type_name(const struct btf* btf, u32 id)
632 {
633         return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
634 }
635
636 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
637 {
638         env->scratched_regs |= 1U << regno;
639 }
640
641 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
642 {
643         env->scratched_stack_slots |= 1ULL << spi;
644 }
645
646 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
647 {
648         return (env->scratched_regs >> regno) & 1;
649 }
650
651 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
652 {
653         return (env->scratched_stack_slots >> regno) & 1;
654 }
655
656 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
657 {
658         return env->scratched_regs || env->scratched_stack_slots;
659 }
660
661 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
662 {
663         env->scratched_regs = 0U;
664         env->scratched_stack_slots = 0ULL;
665 }
666
667 /* Used for printing the entire verifier state. */
668 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
669 {
670         env->scratched_regs = ~0U;
671         env->scratched_stack_slots = ~0ULL;
672 }
673
674 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
675 {
676         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
677         case DYNPTR_TYPE_LOCAL:
678                 return BPF_DYNPTR_TYPE_LOCAL;
679         case DYNPTR_TYPE_RINGBUF:
680                 return BPF_DYNPTR_TYPE_RINGBUF;
681         default:
682                 return BPF_DYNPTR_TYPE_INVALID;
683         }
684 }
685
686 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
687 {
688         return type == BPF_DYNPTR_TYPE_RINGBUF;
689 }
690
691 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
692                                    enum bpf_arg_type arg_type, int insn_idx)
693 {
694         struct bpf_func_state *state = func(env, reg);
695         enum bpf_dynptr_type type;
696         int spi, i, id;
697
698         spi = get_spi(reg->off);
699
700         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
701                 return -EINVAL;
702
703         for (i = 0; i < BPF_REG_SIZE; i++) {
704                 state->stack[spi].slot_type[i] = STACK_DYNPTR;
705                 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
706         }
707
708         type = arg_to_dynptr_type(arg_type);
709         if (type == BPF_DYNPTR_TYPE_INVALID)
710                 return -EINVAL;
711
712         state->stack[spi].spilled_ptr.dynptr.first_slot = true;
713         state->stack[spi].spilled_ptr.dynptr.type = type;
714         state->stack[spi - 1].spilled_ptr.dynptr.type = type;
715
716         if (dynptr_type_refcounted(type)) {
717                 /* The id is used to track proper releasing */
718                 id = acquire_reference_state(env, insn_idx);
719                 if (id < 0)
720                         return id;
721
722                 state->stack[spi].spilled_ptr.id = id;
723                 state->stack[spi - 1].spilled_ptr.id = id;
724         }
725
726         return 0;
727 }
728
729 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
730 {
731         struct bpf_func_state *state = func(env, reg);
732         int spi, i;
733
734         spi = get_spi(reg->off);
735
736         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
737                 return -EINVAL;
738
739         for (i = 0; i < BPF_REG_SIZE; i++) {
740                 state->stack[spi].slot_type[i] = STACK_INVALID;
741                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
742         }
743
744         /* Invalidate any slices associated with this dynptr */
745         if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
746                 release_reference(env, state->stack[spi].spilled_ptr.id);
747                 state->stack[spi].spilled_ptr.id = 0;
748                 state->stack[spi - 1].spilled_ptr.id = 0;
749         }
750
751         state->stack[spi].spilled_ptr.dynptr.first_slot = false;
752         state->stack[spi].spilled_ptr.dynptr.type = 0;
753         state->stack[spi - 1].spilled_ptr.dynptr.type = 0;
754
755         return 0;
756 }
757
758 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
759 {
760         struct bpf_func_state *state = func(env, reg);
761         int spi = get_spi(reg->off);
762         int i;
763
764         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
765                 return true;
766
767         for (i = 0; i < BPF_REG_SIZE; i++) {
768                 if (state->stack[spi].slot_type[i] == STACK_DYNPTR ||
769                     state->stack[spi - 1].slot_type[i] == STACK_DYNPTR)
770                         return false;
771         }
772
773         return true;
774 }
775
776 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
777                                      enum bpf_arg_type arg_type)
778 {
779         struct bpf_func_state *state = func(env, reg);
780         int spi = get_spi(reg->off);
781         int i;
782
783         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
784             !state->stack[spi].spilled_ptr.dynptr.first_slot)
785                 return false;
786
787         for (i = 0; i < BPF_REG_SIZE; i++) {
788                 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
789                     state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
790                         return false;
791         }
792
793         /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
794         if (arg_type == ARG_PTR_TO_DYNPTR)
795                 return true;
796
797         return state->stack[spi].spilled_ptr.dynptr.type == arg_to_dynptr_type(arg_type);
798 }
799
800 /* The reg state of a pointer or a bounded scalar was saved when
801  * it was spilled to the stack.
802  */
803 static bool is_spilled_reg(const struct bpf_stack_state *stack)
804 {
805         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
806 }
807
808 static void scrub_spilled_slot(u8 *stype)
809 {
810         if (*stype != STACK_INVALID)
811                 *stype = STACK_MISC;
812 }
813
814 static void print_verifier_state(struct bpf_verifier_env *env,
815                                  const struct bpf_func_state *state,
816                                  bool print_all)
817 {
818         const struct bpf_reg_state *reg;
819         enum bpf_reg_type t;
820         int i;
821
822         if (state->frameno)
823                 verbose(env, " frame%d:", state->frameno);
824         for (i = 0; i < MAX_BPF_REG; i++) {
825                 reg = &state->regs[i];
826                 t = reg->type;
827                 if (t == NOT_INIT)
828                         continue;
829                 if (!print_all && !reg_scratched(env, i))
830                         continue;
831                 verbose(env, " R%d", i);
832                 print_liveness(env, reg->live);
833                 verbose(env, "=");
834                 if (t == SCALAR_VALUE && reg->precise)
835                         verbose(env, "P");
836                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
837                     tnum_is_const(reg->var_off)) {
838                         /* reg->off should be 0 for SCALAR_VALUE */
839                         verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
840                         verbose(env, "%lld", reg->var_off.value + reg->off);
841                 } else {
842                         const char *sep = "";
843
844                         verbose(env, "%s", reg_type_str(env, t));
845                         if (base_type(t) == PTR_TO_BTF_ID)
846                                 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
847                         verbose(env, "(");
848 /*
849  * _a stands for append, was shortened to avoid multiline statements below.
850  * This macro is used to output a comma separated list of attributes.
851  */
852 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
853
854                         if (reg->id)
855                                 verbose_a("id=%d", reg->id);
856                         if (reg_type_may_be_refcounted_or_null(t) && reg->ref_obj_id)
857                                 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
858                         if (t != SCALAR_VALUE)
859                                 verbose_a("off=%d", reg->off);
860                         if (type_is_pkt_pointer(t))
861                                 verbose_a("r=%d", reg->range);
862                         else if (base_type(t) == CONST_PTR_TO_MAP ||
863                                  base_type(t) == PTR_TO_MAP_KEY ||
864                                  base_type(t) == PTR_TO_MAP_VALUE)
865                                 verbose_a("ks=%d,vs=%d",
866                                           reg->map_ptr->key_size,
867                                           reg->map_ptr->value_size);
868                         if (tnum_is_const(reg->var_off)) {
869                                 /* Typically an immediate SCALAR_VALUE, but
870                                  * could be a pointer whose offset is too big
871                                  * for reg->off
872                                  */
873                                 verbose_a("imm=%llx", reg->var_off.value);
874                         } else {
875                                 if (reg->smin_value != reg->umin_value &&
876                                     reg->smin_value != S64_MIN)
877                                         verbose_a("smin=%lld", (long long)reg->smin_value);
878                                 if (reg->smax_value != reg->umax_value &&
879                                     reg->smax_value != S64_MAX)
880                                         verbose_a("smax=%lld", (long long)reg->smax_value);
881                                 if (reg->umin_value != 0)
882                                         verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
883                                 if (reg->umax_value != U64_MAX)
884                                         verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
885                                 if (!tnum_is_unknown(reg->var_off)) {
886                                         char tn_buf[48];
887
888                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
889                                         verbose_a("var_off=%s", tn_buf);
890                                 }
891                                 if (reg->s32_min_value != reg->smin_value &&
892                                     reg->s32_min_value != S32_MIN)
893                                         verbose_a("s32_min=%d", (int)(reg->s32_min_value));
894                                 if (reg->s32_max_value != reg->smax_value &&
895                                     reg->s32_max_value != S32_MAX)
896                                         verbose_a("s32_max=%d", (int)(reg->s32_max_value));
897                                 if (reg->u32_min_value != reg->umin_value &&
898                                     reg->u32_min_value != U32_MIN)
899                                         verbose_a("u32_min=%d", (int)(reg->u32_min_value));
900                                 if (reg->u32_max_value != reg->umax_value &&
901                                     reg->u32_max_value != U32_MAX)
902                                         verbose_a("u32_max=%d", (int)(reg->u32_max_value));
903                         }
904 #undef verbose_a
905
906                         verbose(env, ")");
907                 }
908         }
909         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
910                 char types_buf[BPF_REG_SIZE + 1];
911                 bool valid = false;
912                 int j;
913
914                 for (j = 0; j < BPF_REG_SIZE; j++) {
915                         if (state->stack[i].slot_type[j] != STACK_INVALID)
916                                 valid = true;
917                         types_buf[j] = slot_type_char[
918                                         state->stack[i].slot_type[j]];
919                 }
920                 types_buf[BPF_REG_SIZE] = 0;
921                 if (!valid)
922                         continue;
923                 if (!print_all && !stack_slot_scratched(env, i))
924                         continue;
925                 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
926                 print_liveness(env, state->stack[i].spilled_ptr.live);
927                 if (is_spilled_reg(&state->stack[i])) {
928                         reg = &state->stack[i].spilled_ptr;
929                         t = reg->type;
930                         verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
931                         if (t == SCALAR_VALUE && reg->precise)
932                                 verbose(env, "P");
933                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
934                                 verbose(env, "%lld", reg->var_off.value + reg->off);
935                 } else {
936                         verbose(env, "=%s", types_buf);
937                 }
938         }
939         if (state->acquired_refs && state->refs[0].id) {
940                 verbose(env, " refs=%d", state->refs[0].id);
941                 for (i = 1; i < state->acquired_refs; i++)
942                         if (state->refs[i].id)
943                                 verbose(env, ",%d", state->refs[i].id);
944         }
945         if (state->in_callback_fn)
946                 verbose(env, " cb");
947         if (state->in_async_callback_fn)
948                 verbose(env, " async_cb");
949         verbose(env, "\n");
950         mark_verifier_state_clean(env);
951 }
952
953 static inline u32 vlog_alignment(u32 pos)
954 {
955         return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
956                         BPF_LOG_MIN_ALIGNMENT) - pos - 1;
957 }
958
959 static void print_insn_state(struct bpf_verifier_env *env,
960                              const struct bpf_func_state *state)
961 {
962         if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
963                 /* remove new line character */
964                 bpf_vlog_reset(&env->log, env->prev_log_len - 1);
965                 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
966         } else {
967                 verbose(env, "%d:", env->insn_idx);
968         }
969         print_verifier_state(env, state, false);
970 }
971
972 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
973  * small to hold src. This is different from krealloc since we don't want to preserve
974  * the contents of dst.
975  *
976  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
977  * not be allocated.
978  */
979 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
980 {
981         size_t bytes;
982
983         if (ZERO_OR_NULL_PTR(src))
984                 goto out;
985
986         if (unlikely(check_mul_overflow(n, size, &bytes)))
987                 return NULL;
988
989         if (ksize(dst) < bytes) {
990                 kfree(dst);
991                 dst = kmalloc_track_caller(bytes, flags);
992                 if (!dst)
993                         return NULL;
994         }
995
996         memcpy(dst, src, bytes);
997 out:
998         return dst ? dst : ZERO_SIZE_PTR;
999 }
1000
1001 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1002  * small to hold new_n items. new items are zeroed out if the array grows.
1003  *
1004  * Contrary to krealloc_array, does not free arr if new_n is zero.
1005  */
1006 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1007 {
1008         if (!new_n || old_n == new_n)
1009                 goto out;
1010
1011         arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
1012         if (!arr)
1013                 return NULL;
1014
1015         if (new_n > old_n)
1016                 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1017
1018 out:
1019         return arr ? arr : ZERO_SIZE_PTR;
1020 }
1021
1022 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1023 {
1024         dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1025                                sizeof(struct bpf_reference_state), GFP_KERNEL);
1026         if (!dst->refs)
1027                 return -ENOMEM;
1028
1029         dst->acquired_refs = src->acquired_refs;
1030         return 0;
1031 }
1032
1033 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1034 {
1035         size_t n = src->allocated_stack / BPF_REG_SIZE;
1036
1037         dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1038                                 GFP_KERNEL);
1039         if (!dst->stack)
1040                 return -ENOMEM;
1041
1042         dst->allocated_stack = src->allocated_stack;
1043         return 0;
1044 }
1045
1046 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1047 {
1048         state->refs = realloc_array(state->refs, state->acquired_refs, n,
1049                                     sizeof(struct bpf_reference_state));
1050         if (!state->refs)
1051                 return -ENOMEM;
1052
1053         state->acquired_refs = n;
1054         return 0;
1055 }
1056
1057 static int grow_stack_state(struct bpf_func_state *state, int size)
1058 {
1059         size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1060
1061         if (old_n >= n)
1062                 return 0;
1063
1064         state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1065         if (!state->stack)
1066                 return -ENOMEM;
1067
1068         state->allocated_stack = size;
1069         return 0;
1070 }
1071
1072 /* Acquire a pointer id from the env and update the state->refs to include
1073  * this new pointer reference.
1074  * On success, returns a valid pointer id to associate with the register
1075  * On failure, returns a negative errno.
1076  */
1077 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1078 {
1079         struct bpf_func_state *state = cur_func(env);
1080         int new_ofs = state->acquired_refs;
1081         int id, err;
1082
1083         err = resize_reference_state(state, state->acquired_refs + 1);
1084         if (err)
1085                 return err;
1086         id = ++env->id_gen;
1087         state->refs[new_ofs].id = id;
1088         state->refs[new_ofs].insn_idx = insn_idx;
1089
1090         return id;
1091 }
1092
1093 /* release function corresponding to acquire_reference_state(). Idempotent. */
1094 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1095 {
1096         int i, last_idx;
1097
1098         last_idx = state->acquired_refs - 1;
1099         for (i = 0; i < state->acquired_refs; i++) {
1100                 if (state->refs[i].id == ptr_id) {
1101                         if (last_idx && i != last_idx)
1102                                 memcpy(&state->refs[i], &state->refs[last_idx],
1103                                        sizeof(*state->refs));
1104                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1105                         state->acquired_refs--;
1106                         return 0;
1107                 }
1108         }
1109         return -EINVAL;
1110 }
1111
1112 static void free_func_state(struct bpf_func_state *state)
1113 {
1114         if (!state)
1115                 return;
1116         kfree(state->refs);
1117         kfree(state->stack);
1118         kfree(state);
1119 }
1120
1121 static void clear_jmp_history(struct bpf_verifier_state *state)
1122 {
1123         kfree(state->jmp_history);
1124         state->jmp_history = NULL;
1125         state->jmp_history_cnt = 0;
1126 }
1127
1128 static void free_verifier_state(struct bpf_verifier_state *state,
1129                                 bool free_self)
1130 {
1131         int i;
1132
1133         for (i = 0; i <= state->curframe; i++) {
1134                 free_func_state(state->frame[i]);
1135                 state->frame[i] = NULL;
1136         }
1137         clear_jmp_history(state);
1138         if (free_self)
1139                 kfree(state);
1140 }
1141
1142 /* copy verifier state from src to dst growing dst stack space
1143  * when necessary to accommodate larger src stack
1144  */
1145 static int copy_func_state(struct bpf_func_state *dst,
1146                            const struct bpf_func_state *src)
1147 {
1148         int err;
1149
1150         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1151         err = copy_reference_state(dst, src);
1152         if (err)
1153                 return err;
1154         return copy_stack_state(dst, src);
1155 }
1156
1157 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1158                                const struct bpf_verifier_state *src)
1159 {
1160         struct bpf_func_state *dst;
1161         int i, err;
1162
1163         dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1164                                             src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1165                                             GFP_USER);
1166         if (!dst_state->jmp_history)
1167                 return -ENOMEM;
1168         dst_state->jmp_history_cnt = src->jmp_history_cnt;
1169
1170         /* if dst has more stack frames then src frame, free them */
1171         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1172                 free_func_state(dst_state->frame[i]);
1173                 dst_state->frame[i] = NULL;
1174         }
1175         dst_state->speculative = src->speculative;
1176         dst_state->curframe = src->curframe;
1177         dst_state->active_spin_lock = src->active_spin_lock;
1178         dst_state->branches = src->branches;
1179         dst_state->parent = src->parent;
1180         dst_state->first_insn_idx = src->first_insn_idx;
1181         dst_state->last_insn_idx = src->last_insn_idx;
1182         for (i = 0; i <= src->curframe; i++) {
1183                 dst = dst_state->frame[i];
1184                 if (!dst) {
1185                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1186                         if (!dst)
1187                                 return -ENOMEM;
1188                         dst_state->frame[i] = dst;
1189                 }
1190                 err = copy_func_state(dst, src->frame[i]);
1191                 if (err)
1192                         return err;
1193         }
1194         return 0;
1195 }
1196
1197 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1198 {
1199         while (st) {
1200                 u32 br = --st->branches;
1201
1202                 /* WARN_ON(br > 1) technically makes sense here,
1203                  * but see comment in push_stack(), hence:
1204                  */
1205                 WARN_ONCE((int)br < 0,
1206                           "BUG update_branch_counts:branches_to_explore=%d\n",
1207                           br);
1208                 if (br)
1209                         break;
1210                 st = st->parent;
1211         }
1212 }
1213
1214 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1215                      int *insn_idx, bool pop_log)
1216 {
1217         struct bpf_verifier_state *cur = env->cur_state;
1218         struct bpf_verifier_stack_elem *elem, *head = env->head;
1219         int err;
1220
1221         if (env->head == NULL)
1222                 return -ENOENT;
1223
1224         if (cur) {
1225                 err = copy_verifier_state(cur, &head->st);
1226                 if (err)
1227                         return err;
1228         }
1229         if (pop_log)
1230                 bpf_vlog_reset(&env->log, head->log_pos);
1231         if (insn_idx)
1232                 *insn_idx = head->insn_idx;
1233         if (prev_insn_idx)
1234                 *prev_insn_idx = head->prev_insn_idx;
1235         elem = head->next;
1236         free_verifier_state(&head->st, false);
1237         kfree(head);
1238         env->head = elem;
1239         env->stack_size--;
1240         return 0;
1241 }
1242
1243 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1244                                              int insn_idx, int prev_insn_idx,
1245                                              bool speculative)
1246 {
1247         struct bpf_verifier_state *cur = env->cur_state;
1248         struct bpf_verifier_stack_elem *elem;
1249         int err;
1250
1251         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1252         if (!elem)
1253                 goto err;
1254
1255         elem->insn_idx = insn_idx;
1256         elem->prev_insn_idx = prev_insn_idx;
1257         elem->next = env->head;
1258         elem->log_pos = env->log.len_used;
1259         env->head = elem;
1260         env->stack_size++;
1261         err = copy_verifier_state(&elem->st, cur);
1262         if (err)
1263                 goto err;
1264         elem->st.speculative |= speculative;
1265         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1266                 verbose(env, "The sequence of %d jumps is too complex.\n",
1267                         env->stack_size);
1268                 goto err;
1269         }
1270         if (elem->st.parent) {
1271                 ++elem->st.parent->branches;
1272                 /* WARN_ON(branches > 2) technically makes sense here,
1273                  * but
1274                  * 1. speculative states will bump 'branches' for non-branch
1275                  * instructions
1276                  * 2. is_state_visited() heuristics may decide not to create
1277                  * a new state for a sequence of branches and all such current
1278                  * and cloned states will be pointing to a single parent state
1279                  * which might have large 'branches' count.
1280                  */
1281         }
1282         return &elem->st;
1283 err:
1284         free_verifier_state(env->cur_state, true);
1285         env->cur_state = NULL;
1286         /* pop all elements and return */
1287         while (!pop_stack(env, NULL, NULL, false));
1288         return NULL;
1289 }
1290
1291 #define CALLER_SAVED_REGS 6
1292 static const int caller_saved[CALLER_SAVED_REGS] = {
1293         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1294 };
1295
1296 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1297                                 struct bpf_reg_state *reg);
1298
1299 /* This helper doesn't clear reg->id */
1300 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1301 {
1302         reg->var_off = tnum_const(imm);
1303         reg->smin_value = (s64)imm;
1304         reg->smax_value = (s64)imm;
1305         reg->umin_value = imm;
1306         reg->umax_value = imm;
1307
1308         reg->s32_min_value = (s32)imm;
1309         reg->s32_max_value = (s32)imm;
1310         reg->u32_min_value = (u32)imm;
1311         reg->u32_max_value = (u32)imm;
1312 }
1313
1314 /* Mark the unknown part of a register (variable offset or scalar value) as
1315  * known to have the value @imm.
1316  */
1317 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1318 {
1319         /* Clear id, off, and union(map_ptr, range) */
1320         memset(((u8 *)reg) + sizeof(reg->type), 0,
1321                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1322         ___mark_reg_known(reg, imm);
1323 }
1324
1325 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1326 {
1327         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1328         reg->s32_min_value = (s32)imm;
1329         reg->s32_max_value = (s32)imm;
1330         reg->u32_min_value = (u32)imm;
1331         reg->u32_max_value = (u32)imm;
1332 }
1333
1334 /* Mark the 'variable offset' part of a register as zero.  This should be
1335  * used only on registers holding a pointer type.
1336  */
1337 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1338 {
1339         __mark_reg_known(reg, 0);
1340 }
1341
1342 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1343 {
1344         __mark_reg_known(reg, 0);
1345         reg->type = SCALAR_VALUE;
1346 }
1347
1348 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1349                                 struct bpf_reg_state *regs, u32 regno)
1350 {
1351         if (WARN_ON(regno >= MAX_BPF_REG)) {
1352                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1353                 /* Something bad happened, let's kill all regs */
1354                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1355                         __mark_reg_not_init(env, regs + regno);
1356                 return;
1357         }
1358         __mark_reg_known_zero(regs + regno);
1359 }
1360
1361 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1362 {
1363         if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1364                 const struct bpf_map *map = reg->map_ptr;
1365
1366                 if (map->inner_map_meta) {
1367                         reg->type = CONST_PTR_TO_MAP;
1368                         reg->map_ptr = map->inner_map_meta;
1369                         /* transfer reg's id which is unique for every map_lookup_elem
1370                          * as UID of the inner map.
1371                          */
1372                         if (map_value_has_timer(map->inner_map_meta))
1373                                 reg->map_uid = reg->id;
1374                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1375                         reg->type = PTR_TO_XDP_SOCK;
1376                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1377                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1378                         reg->type = PTR_TO_SOCKET;
1379                 } else {
1380                         reg->type = PTR_TO_MAP_VALUE;
1381                 }
1382                 return;
1383         }
1384
1385         reg->type &= ~PTR_MAYBE_NULL;
1386 }
1387
1388 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1389 {
1390         return type_is_pkt_pointer(reg->type);
1391 }
1392
1393 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1394 {
1395         return reg_is_pkt_pointer(reg) ||
1396                reg->type == PTR_TO_PACKET_END;
1397 }
1398
1399 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1400 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1401                                     enum bpf_reg_type which)
1402 {
1403         /* The register can already have a range from prior markings.
1404          * This is fine as long as it hasn't been advanced from its
1405          * origin.
1406          */
1407         return reg->type == which &&
1408                reg->id == 0 &&
1409                reg->off == 0 &&
1410                tnum_equals_const(reg->var_off, 0);
1411 }
1412
1413 /* Reset the min/max bounds of a register */
1414 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1415 {
1416         reg->smin_value = S64_MIN;
1417         reg->smax_value = S64_MAX;
1418         reg->umin_value = 0;
1419         reg->umax_value = U64_MAX;
1420
1421         reg->s32_min_value = S32_MIN;
1422         reg->s32_max_value = S32_MAX;
1423         reg->u32_min_value = 0;
1424         reg->u32_max_value = U32_MAX;
1425 }
1426
1427 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1428 {
1429         reg->smin_value = S64_MIN;
1430         reg->smax_value = S64_MAX;
1431         reg->umin_value = 0;
1432         reg->umax_value = U64_MAX;
1433 }
1434
1435 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1436 {
1437         reg->s32_min_value = S32_MIN;
1438         reg->s32_max_value = S32_MAX;
1439         reg->u32_min_value = 0;
1440         reg->u32_max_value = U32_MAX;
1441 }
1442
1443 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1444 {
1445         struct tnum var32_off = tnum_subreg(reg->var_off);
1446
1447         /* min signed is max(sign bit) | min(other bits) */
1448         reg->s32_min_value = max_t(s32, reg->s32_min_value,
1449                         var32_off.value | (var32_off.mask & S32_MIN));
1450         /* max signed is min(sign bit) | max(other bits) */
1451         reg->s32_max_value = min_t(s32, reg->s32_max_value,
1452                         var32_off.value | (var32_off.mask & S32_MAX));
1453         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1454         reg->u32_max_value = min(reg->u32_max_value,
1455                                  (u32)(var32_off.value | var32_off.mask));
1456 }
1457
1458 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1459 {
1460         /* min signed is max(sign bit) | min(other bits) */
1461         reg->smin_value = max_t(s64, reg->smin_value,
1462                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1463         /* max signed is min(sign bit) | max(other bits) */
1464         reg->smax_value = min_t(s64, reg->smax_value,
1465                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1466         reg->umin_value = max(reg->umin_value, reg->var_off.value);
1467         reg->umax_value = min(reg->umax_value,
1468                               reg->var_off.value | reg->var_off.mask);
1469 }
1470
1471 static void __update_reg_bounds(struct bpf_reg_state *reg)
1472 {
1473         __update_reg32_bounds(reg);
1474         __update_reg64_bounds(reg);
1475 }
1476
1477 /* Uses signed min/max values to inform unsigned, and vice-versa */
1478 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1479 {
1480         /* Learn sign from signed bounds.
1481          * If we cannot cross the sign boundary, then signed and unsigned bounds
1482          * are the same, so combine.  This works even in the negative case, e.g.
1483          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1484          */
1485         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1486                 reg->s32_min_value = reg->u32_min_value =
1487                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1488                 reg->s32_max_value = reg->u32_max_value =
1489                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1490                 return;
1491         }
1492         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1493          * boundary, so we must be careful.
1494          */
1495         if ((s32)reg->u32_max_value >= 0) {
1496                 /* Positive.  We can't learn anything from the smin, but smax
1497                  * is positive, hence safe.
1498                  */
1499                 reg->s32_min_value = reg->u32_min_value;
1500                 reg->s32_max_value = reg->u32_max_value =
1501                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1502         } else if ((s32)reg->u32_min_value < 0) {
1503                 /* Negative.  We can't learn anything from the smax, but smin
1504                  * is negative, hence safe.
1505                  */
1506                 reg->s32_min_value = reg->u32_min_value =
1507                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1508                 reg->s32_max_value = reg->u32_max_value;
1509         }
1510 }
1511
1512 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1513 {
1514         /* Learn sign from signed bounds.
1515          * If we cannot cross the sign boundary, then signed and unsigned bounds
1516          * are the same, so combine.  This works even in the negative case, e.g.
1517          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1518          */
1519         if (reg->smin_value >= 0 || reg->smax_value < 0) {
1520                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1521                                                           reg->umin_value);
1522                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1523                                                           reg->umax_value);
1524                 return;
1525         }
1526         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1527          * boundary, so we must be careful.
1528          */
1529         if ((s64)reg->umax_value >= 0) {
1530                 /* Positive.  We can't learn anything from the smin, but smax
1531                  * is positive, hence safe.
1532                  */
1533                 reg->smin_value = reg->umin_value;
1534                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1535                                                           reg->umax_value);
1536         } else if ((s64)reg->umin_value < 0) {
1537                 /* Negative.  We can't learn anything from the smax, but smin
1538                  * is negative, hence safe.
1539                  */
1540                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1541                                                           reg->umin_value);
1542                 reg->smax_value = reg->umax_value;
1543         }
1544 }
1545
1546 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1547 {
1548         __reg32_deduce_bounds(reg);
1549         __reg64_deduce_bounds(reg);
1550 }
1551
1552 /* Attempts to improve var_off based on unsigned min/max information */
1553 static void __reg_bound_offset(struct bpf_reg_state *reg)
1554 {
1555         struct tnum var64_off = tnum_intersect(reg->var_off,
1556                                                tnum_range(reg->umin_value,
1557                                                           reg->umax_value));
1558         struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1559                                                 tnum_range(reg->u32_min_value,
1560                                                            reg->u32_max_value));
1561
1562         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1563 }
1564
1565 static void reg_bounds_sync(struct bpf_reg_state *reg)
1566 {
1567         /* We might have learned new bounds from the var_off. */
1568         __update_reg_bounds(reg);
1569         /* We might have learned something about the sign bit. */
1570         __reg_deduce_bounds(reg);
1571         /* We might have learned some bits from the bounds. */
1572         __reg_bound_offset(reg);
1573         /* Intersecting with the old var_off might have improved our bounds
1574          * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1575          * then new var_off is (0; 0x7f...fc) which improves our umax.
1576          */
1577         __update_reg_bounds(reg);
1578 }
1579
1580 static bool __reg32_bound_s64(s32 a)
1581 {
1582         return a >= 0 && a <= S32_MAX;
1583 }
1584
1585 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1586 {
1587         reg->umin_value = reg->u32_min_value;
1588         reg->umax_value = reg->u32_max_value;
1589
1590         /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1591          * be positive otherwise set to worse case bounds and refine later
1592          * from tnum.
1593          */
1594         if (__reg32_bound_s64(reg->s32_min_value) &&
1595             __reg32_bound_s64(reg->s32_max_value)) {
1596                 reg->smin_value = reg->s32_min_value;
1597                 reg->smax_value = reg->s32_max_value;
1598         } else {
1599                 reg->smin_value = 0;
1600                 reg->smax_value = U32_MAX;
1601         }
1602 }
1603
1604 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1605 {
1606         /* special case when 64-bit register has upper 32-bit register
1607          * zeroed. Typically happens after zext or <<32, >>32 sequence
1608          * allowing us to use 32-bit bounds directly,
1609          */
1610         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1611                 __reg_assign_32_into_64(reg);
1612         } else {
1613                 /* Otherwise the best we can do is push lower 32bit known and
1614                  * unknown bits into register (var_off set from jmp logic)
1615                  * then learn as much as possible from the 64-bit tnum
1616                  * known and unknown bits. The previous smin/smax bounds are
1617                  * invalid here because of jmp32 compare so mark them unknown
1618                  * so they do not impact tnum bounds calculation.
1619                  */
1620                 __mark_reg64_unbounded(reg);
1621         }
1622         reg_bounds_sync(reg);
1623 }
1624
1625 static bool __reg64_bound_s32(s64 a)
1626 {
1627         return a >= S32_MIN && a <= S32_MAX;
1628 }
1629
1630 static bool __reg64_bound_u32(u64 a)
1631 {
1632         return a >= U32_MIN && a <= U32_MAX;
1633 }
1634
1635 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1636 {
1637         __mark_reg32_unbounded(reg);
1638         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1639                 reg->s32_min_value = (s32)reg->smin_value;
1640                 reg->s32_max_value = (s32)reg->smax_value;
1641         }
1642         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1643                 reg->u32_min_value = (u32)reg->umin_value;
1644                 reg->u32_max_value = (u32)reg->umax_value;
1645         }
1646         reg_bounds_sync(reg);
1647 }
1648
1649 /* Mark a register as having a completely unknown (scalar) value. */
1650 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1651                                struct bpf_reg_state *reg)
1652 {
1653         /*
1654          * Clear type, id, off, and union(map_ptr, range) and
1655          * padding between 'type' and union
1656          */
1657         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1658         reg->type = SCALAR_VALUE;
1659         reg->var_off = tnum_unknown;
1660         reg->frameno = 0;
1661         reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1662         __mark_reg_unbounded(reg);
1663 }
1664
1665 static void mark_reg_unknown(struct bpf_verifier_env *env,
1666                              struct bpf_reg_state *regs, u32 regno)
1667 {
1668         if (WARN_ON(regno >= MAX_BPF_REG)) {
1669                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1670                 /* Something bad happened, let's kill all regs except FP */
1671                 for (regno = 0; regno < BPF_REG_FP; regno++)
1672                         __mark_reg_not_init(env, regs + regno);
1673                 return;
1674         }
1675         __mark_reg_unknown(env, regs + regno);
1676 }
1677
1678 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1679                                 struct bpf_reg_state *reg)
1680 {
1681         __mark_reg_unknown(env, reg);
1682         reg->type = NOT_INIT;
1683 }
1684
1685 static void mark_reg_not_init(struct bpf_verifier_env *env,
1686                               struct bpf_reg_state *regs, u32 regno)
1687 {
1688         if (WARN_ON(regno >= MAX_BPF_REG)) {
1689                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1690                 /* Something bad happened, let's kill all regs except FP */
1691                 for (regno = 0; regno < BPF_REG_FP; regno++)
1692                         __mark_reg_not_init(env, regs + regno);
1693                 return;
1694         }
1695         __mark_reg_not_init(env, regs + regno);
1696 }
1697
1698 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1699                             struct bpf_reg_state *regs, u32 regno,
1700                             enum bpf_reg_type reg_type,
1701                             struct btf *btf, u32 btf_id,
1702                             enum bpf_type_flag flag)
1703 {
1704         if (reg_type == SCALAR_VALUE) {
1705                 mark_reg_unknown(env, regs, regno);
1706                 return;
1707         }
1708         mark_reg_known_zero(env, regs, regno);
1709         regs[regno].type = PTR_TO_BTF_ID | flag;
1710         regs[regno].btf = btf;
1711         regs[regno].btf_id = btf_id;
1712 }
1713
1714 #define DEF_NOT_SUBREG  (0)
1715 static void init_reg_state(struct bpf_verifier_env *env,
1716                            struct bpf_func_state *state)
1717 {
1718         struct bpf_reg_state *regs = state->regs;
1719         int i;
1720
1721         for (i = 0; i < MAX_BPF_REG; i++) {
1722                 mark_reg_not_init(env, regs, i);
1723                 regs[i].live = REG_LIVE_NONE;
1724                 regs[i].parent = NULL;
1725                 regs[i].subreg_def = DEF_NOT_SUBREG;
1726         }
1727
1728         /* frame pointer */
1729         regs[BPF_REG_FP].type = PTR_TO_STACK;
1730         mark_reg_known_zero(env, regs, BPF_REG_FP);
1731         regs[BPF_REG_FP].frameno = state->frameno;
1732 }
1733
1734 #define BPF_MAIN_FUNC (-1)
1735 static void init_func_state(struct bpf_verifier_env *env,
1736                             struct bpf_func_state *state,
1737                             int callsite, int frameno, int subprogno)
1738 {
1739         state->callsite = callsite;
1740         state->frameno = frameno;
1741         state->subprogno = subprogno;
1742         init_reg_state(env, state);
1743         mark_verifier_state_scratched(env);
1744 }
1745
1746 /* Similar to push_stack(), but for async callbacks */
1747 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1748                                                 int insn_idx, int prev_insn_idx,
1749                                                 int subprog)
1750 {
1751         struct bpf_verifier_stack_elem *elem;
1752         struct bpf_func_state *frame;
1753
1754         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1755         if (!elem)
1756                 goto err;
1757
1758         elem->insn_idx = insn_idx;
1759         elem->prev_insn_idx = prev_insn_idx;
1760         elem->next = env->head;
1761         elem->log_pos = env->log.len_used;
1762         env->head = elem;
1763         env->stack_size++;
1764         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1765                 verbose(env,
1766                         "The sequence of %d jumps is too complex for async cb.\n",
1767                         env->stack_size);
1768                 goto err;
1769         }
1770         /* Unlike push_stack() do not copy_verifier_state().
1771          * The caller state doesn't matter.
1772          * This is async callback. It starts in a fresh stack.
1773          * Initialize it similar to do_check_common().
1774          */
1775         elem->st.branches = 1;
1776         frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1777         if (!frame)
1778                 goto err;
1779         init_func_state(env, frame,
1780                         BPF_MAIN_FUNC /* callsite */,
1781                         0 /* frameno within this callchain */,
1782                         subprog /* subprog number within this prog */);
1783         elem->st.frame[0] = frame;
1784         return &elem->st;
1785 err:
1786         free_verifier_state(env->cur_state, true);
1787         env->cur_state = NULL;
1788         /* pop all elements and return */
1789         while (!pop_stack(env, NULL, NULL, false));
1790         return NULL;
1791 }
1792
1793
1794 enum reg_arg_type {
1795         SRC_OP,         /* register is used as source operand */
1796         DST_OP,         /* register is used as destination operand */
1797         DST_OP_NO_MARK  /* same as above, check only, don't mark */
1798 };
1799
1800 static int cmp_subprogs(const void *a, const void *b)
1801 {
1802         return ((struct bpf_subprog_info *)a)->start -
1803                ((struct bpf_subprog_info *)b)->start;
1804 }
1805
1806 static int find_subprog(struct bpf_verifier_env *env, int off)
1807 {
1808         struct bpf_subprog_info *p;
1809
1810         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1811                     sizeof(env->subprog_info[0]), cmp_subprogs);
1812         if (!p)
1813                 return -ENOENT;
1814         return p - env->subprog_info;
1815
1816 }
1817
1818 static int add_subprog(struct bpf_verifier_env *env, int off)
1819 {
1820         int insn_cnt = env->prog->len;
1821         int ret;
1822
1823         if (off >= insn_cnt || off < 0) {
1824                 verbose(env, "call to invalid destination\n");
1825                 return -EINVAL;
1826         }
1827         ret = find_subprog(env, off);
1828         if (ret >= 0)
1829                 return ret;
1830         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1831                 verbose(env, "too many subprograms\n");
1832                 return -E2BIG;
1833         }
1834         /* determine subprog starts. The end is one before the next starts */
1835         env->subprog_info[env->subprog_cnt++].start = off;
1836         sort(env->subprog_info, env->subprog_cnt,
1837              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1838         return env->subprog_cnt - 1;
1839 }
1840
1841 #define MAX_KFUNC_DESCS 256
1842 #define MAX_KFUNC_BTFS  256
1843
1844 struct bpf_kfunc_desc {
1845         struct btf_func_model func_model;
1846         u32 func_id;
1847         s32 imm;
1848         u16 offset;
1849 };
1850
1851 struct bpf_kfunc_btf {
1852         struct btf *btf;
1853         struct module *module;
1854         u16 offset;
1855 };
1856
1857 struct bpf_kfunc_desc_tab {
1858         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1859         u32 nr_descs;
1860 };
1861
1862 struct bpf_kfunc_btf_tab {
1863         struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1864         u32 nr_descs;
1865 };
1866
1867 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1868 {
1869         const struct bpf_kfunc_desc *d0 = a;
1870         const struct bpf_kfunc_desc *d1 = b;
1871
1872         /* func_id is not greater than BTF_MAX_TYPE */
1873         return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1874 }
1875
1876 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1877 {
1878         const struct bpf_kfunc_btf *d0 = a;
1879         const struct bpf_kfunc_btf *d1 = b;
1880
1881         return d0->offset - d1->offset;
1882 }
1883
1884 static const struct bpf_kfunc_desc *
1885 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1886 {
1887         struct bpf_kfunc_desc desc = {
1888                 .func_id = func_id,
1889                 .offset = offset,
1890         };
1891         struct bpf_kfunc_desc_tab *tab;
1892
1893         tab = prog->aux->kfunc_tab;
1894         return bsearch(&desc, tab->descs, tab->nr_descs,
1895                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1896 }
1897
1898 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1899                                          s16 offset)
1900 {
1901         struct bpf_kfunc_btf kf_btf = { .offset = offset };
1902         struct bpf_kfunc_btf_tab *tab;
1903         struct bpf_kfunc_btf *b;
1904         struct module *mod;
1905         struct btf *btf;
1906         int btf_fd;
1907
1908         tab = env->prog->aux->kfunc_btf_tab;
1909         b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1910                     sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1911         if (!b) {
1912                 if (tab->nr_descs == MAX_KFUNC_BTFS) {
1913                         verbose(env, "too many different module BTFs\n");
1914                         return ERR_PTR(-E2BIG);
1915                 }
1916
1917                 if (bpfptr_is_null(env->fd_array)) {
1918                         verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1919                         return ERR_PTR(-EPROTO);
1920                 }
1921
1922                 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1923                                             offset * sizeof(btf_fd),
1924                                             sizeof(btf_fd)))
1925                         return ERR_PTR(-EFAULT);
1926
1927                 btf = btf_get_by_fd(btf_fd);
1928                 if (IS_ERR(btf)) {
1929                         verbose(env, "invalid module BTF fd specified\n");
1930                         return btf;
1931                 }
1932
1933                 if (!btf_is_module(btf)) {
1934                         verbose(env, "BTF fd for kfunc is not a module BTF\n");
1935                         btf_put(btf);
1936                         return ERR_PTR(-EINVAL);
1937                 }
1938
1939                 mod = btf_try_get_module(btf);
1940                 if (!mod) {
1941                         btf_put(btf);
1942                         return ERR_PTR(-ENXIO);
1943                 }
1944
1945                 b = &tab->descs[tab->nr_descs++];
1946                 b->btf = btf;
1947                 b->module = mod;
1948                 b->offset = offset;
1949
1950                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1951                      kfunc_btf_cmp_by_off, NULL);
1952         }
1953         return b->btf;
1954 }
1955
1956 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1957 {
1958         if (!tab)
1959                 return;
1960
1961         while (tab->nr_descs--) {
1962                 module_put(tab->descs[tab->nr_descs].module);
1963                 btf_put(tab->descs[tab->nr_descs].btf);
1964         }
1965         kfree(tab);
1966 }
1967
1968 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
1969 {
1970         if (offset) {
1971                 if (offset < 0) {
1972                         /* In the future, this can be allowed to increase limit
1973                          * of fd index into fd_array, interpreted as u16.
1974                          */
1975                         verbose(env, "negative offset disallowed for kernel module function call\n");
1976                         return ERR_PTR(-EINVAL);
1977                 }
1978
1979                 return __find_kfunc_desc_btf(env, offset);
1980         }
1981         return btf_vmlinux ?: ERR_PTR(-ENOENT);
1982 }
1983
1984 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
1985 {
1986         const struct btf_type *func, *func_proto;
1987         struct bpf_kfunc_btf_tab *btf_tab;
1988         struct bpf_kfunc_desc_tab *tab;
1989         struct bpf_prog_aux *prog_aux;
1990         struct bpf_kfunc_desc *desc;
1991         const char *func_name;
1992         struct btf *desc_btf;
1993         unsigned long call_imm;
1994         unsigned long addr;
1995         int err;
1996
1997         prog_aux = env->prog->aux;
1998         tab = prog_aux->kfunc_tab;
1999         btf_tab = prog_aux->kfunc_btf_tab;
2000         if (!tab) {
2001                 if (!btf_vmlinux) {
2002                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2003                         return -ENOTSUPP;
2004                 }
2005
2006                 if (!env->prog->jit_requested) {
2007                         verbose(env, "JIT is required for calling kernel function\n");
2008                         return -ENOTSUPP;
2009                 }
2010
2011                 if (!bpf_jit_supports_kfunc_call()) {
2012                         verbose(env, "JIT does not support calling kernel function\n");
2013                         return -ENOTSUPP;
2014                 }
2015
2016                 if (!env->prog->gpl_compatible) {
2017                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2018                         return -EINVAL;
2019                 }
2020
2021                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2022                 if (!tab)
2023                         return -ENOMEM;
2024                 prog_aux->kfunc_tab = tab;
2025         }
2026
2027         /* func_id == 0 is always invalid, but instead of returning an error, be
2028          * conservative and wait until the code elimination pass before returning
2029          * error, so that invalid calls that get pruned out can be in BPF programs
2030          * loaded from userspace.  It is also required that offset be untouched
2031          * for such calls.
2032          */
2033         if (!func_id && !offset)
2034                 return 0;
2035
2036         if (!btf_tab && offset) {
2037                 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2038                 if (!btf_tab)
2039                         return -ENOMEM;
2040                 prog_aux->kfunc_btf_tab = btf_tab;
2041         }
2042
2043         desc_btf = find_kfunc_desc_btf(env, offset);
2044         if (IS_ERR(desc_btf)) {
2045                 verbose(env, "failed to find BTF for kernel function\n");
2046                 return PTR_ERR(desc_btf);
2047         }
2048
2049         if (find_kfunc_desc(env->prog, func_id, offset))
2050                 return 0;
2051
2052         if (tab->nr_descs == MAX_KFUNC_DESCS) {
2053                 verbose(env, "too many different kernel function calls\n");
2054                 return -E2BIG;
2055         }
2056
2057         func = btf_type_by_id(desc_btf, func_id);
2058         if (!func || !btf_type_is_func(func)) {
2059                 verbose(env, "kernel btf_id %u is not a function\n",
2060                         func_id);
2061                 return -EINVAL;
2062         }
2063         func_proto = btf_type_by_id(desc_btf, func->type);
2064         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2065                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2066                         func_id);
2067                 return -EINVAL;
2068         }
2069
2070         func_name = btf_name_by_offset(desc_btf, func->name_off);
2071         addr = kallsyms_lookup_name(func_name);
2072         if (!addr) {
2073                 verbose(env, "cannot find address for kernel function %s\n",
2074                         func_name);
2075                 return -EINVAL;
2076         }
2077
2078         call_imm = BPF_CALL_IMM(addr);
2079         /* Check whether or not the relative offset overflows desc->imm */
2080         if ((unsigned long)(s32)call_imm != call_imm) {
2081                 verbose(env, "address of kernel function %s is out of range\n",
2082                         func_name);
2083                 return -EINVAL;
2084         }
2085
2086         desc = &tab->descs[tab->nr_descs++];
2087         desc->func_id = func_id;
2088         desc->imm = call_imm;
2089         desc->offset = offset;
2090         err = btf_distill_func_proto(&env->log, desc_btf,
2091                                      func_proto, func_name,
2092                                      &desc->func_model);
2093         if (!err)
2094                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2095                      kfunc_desc_cmp_by_id_off, NULL);
2096         return err;
2097 }
2098
2099 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2100 {
2101         const struct bpf_kfunc_desc *d0 = a;
2102         const struct bpf_kfunc_desc *d1 = b;
2103
2104         if (d0->imm > d1->imm)
2105                 return 1;
2106         else if (d0->imm < d1->imm)
2107                 return -1;
2108         return 0;
2109 }
2110
2111 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2112 {
2113         struct bpf_kfunc_desc_tab *tab;
2114
2115         tab = prog->aux->kfunc_tab;
2116         if (!tab)
2117                 return;
2118
2119         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2120              kfunc_desc_cmp_by_imm, NULL);
2121 }
2122
2123 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2124 {
2125         return !!prog->aux->kfunc_tab;
2126 }
2127
2128 const struct btf_func_model *
2129 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2130                          const struct bpf_insn *insn)
2131 {
2132         const struct bpf_kfunc_desc desc = {
2133                 .imm = insn->imm,
2134         };
2135         const struct bpf_kfunc_desc *res;
2136         struct bpf_kfunc_desc_tab *tab;
2137
2138         tab = prog->aux->kfunc_tab;
2139         res = bsearch(&desc, tab->descs, tab->nr_descs,
2140                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2141
2142         return res ? &res->func_model : NULL;
2143 }
2144
2145 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2146 {
2147         struct bpf_subprog_info *subprog = env->subprog_info;
2148         struct bpf_insn *insn = env->prog->insnsi;
2149         int i, ret, insn_cnt = env->prog->len;
2150
2151         /* Add entry function. */
2152         ret = add_subprog(env, 0);
2153         if (ret)
2154                 return ret;
2155
2156         for (i = 0; i < insn_cnt; i++, insn++) {
2157                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2158                     !bpf_pseudo_kfunc_call(insn))
2159                         continue;
2160
2161                 if (!env->bpf_capable) {
2162                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2163                         return -EPERM;
2164                 }
2165
2166                 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2167                         ret = add_subprog(env, i + insn->imm + 1);
2168                 else
2169                         ret = add_kfunc_call(env, insn->imm, insn->off);
2170
2171                 if (ret < 0)
2172                         return ret;
2173         }
2174
2175         /* Add a fake 'exit' subprog which could simplify subprog iteration
2176          * logic. 'subprog_cnt' should not be increased.
2177          */
2178         subprog[env->subprog_cnt].start = insn_cnt;
2179
2180         if (env->log.level & BPF_LOG_LEVEL2)
2181                 for (i = 0; i < env->subprog_cnt; i++)
2182                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
2183
2184         return 0;
2185 }
2186
2187 static int check_subprogs(struct bpf_verifier_env *env)
2188 {
2189         int i, subprog_start, subprog_end, off, cur_subprog = 0;
2190         struct bpf_subprog_info *subprog = env->subprog_info;
2191         struct bpf_insn *insn = env->prog->insnsi;
2192         int insn_cnt = env->prog->len;
2193
2194         /* now check that all jumps are within the same subprog */
2195         subprog_start = subprog[cur_subprog].start;
2196         subprog_end = subprog[cur_subprog + 1].start;
2197         for (i = 0; i < insn_cnt; i++) {
2198                 u8 code = insn[i].code;
2199
2200                 if (code == (BPF_JMP | BPF_CALL) &&
2201                     insn[i].imm == BPF_FUNC_tail_call &&
2202                     insn[i].src_reg != BPF_PSEUDO_CALL)
2203                         subprog[cur_subprog].has_tail_call = true;
2204                 if (BPF_CLASS(code) == BPF_LD &&
2205                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2206                         subprog[cur_subprog].has_ld_abs = true;
2207                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2208                         goto next;
2209                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2210                         goto next;
2211                 off = i + insn[i].off + 1;
2212                 if (off < subprog_start || off >= subprog_end) {
2213                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
2214                         return -EINVAL;
2215                 }
2216 next:
2217                 if (i == subprog_end - 1) {
2218                         /* to avoid fall-through from one subprog into another
2219                          * the last insn of the subprog should be either exit
2220                          * or unconditional jump back
2221                          */
2222                         if (code != (BPF_JMP | BPF_EXIT) &&
2223                             code != (BPF_JMP | BPF_JA)) {
2224                                 verbose(env, "last insn is not an exit or jmp\n");
2225                                 return -EINVAL;
2226                         }
2227                         subprog_start = subprog_end;
2228                         cur_subprog++;
2229                         if (cur_subprog < env->subprog_cnt)
2230                                 subprog_end = subprog[cur_subprog + 1].start;
2231                 }
2232         }
2233         return 0;
2234 }
2235
2236 /* Parentage chain of this register (or stack slot) should take care of all
2237  * issues like callee-saved registers, stack slot allocation time, etc.
2238  */
2239 static int mark_reg_read(struct bpf_verifier_env *env,
2240                          const struct bpf_reg_state *state,
2241                          struct bpf_reg_state *parent, u8 flag)
2242 {
2243         bool writes = parent == state->parent; /* Observe write marks */
2244         int cnt = 0;
2245
2246         while (parent) {
2247                 /* if read wasn't screened by an earlier write ... */
2248                 if (writes && state->live & REG_LIVE_WRITTEN)
2249                         break;
2250                 if (parent->live & REG_LIVE_DONE) {
2251                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2252                                 reg_type_str(env, parent->type),
2253                                 parent->var_off.value, parent->off);
2254                         return -EFAULT;
2255                 }
2256                 /* The first condition is more likely to be true than the
2257                  * second, checked it first.
2258                  */
2259                 if ((parent->live & REG_LIVE_READ) == flag ||
2260                     parent->live & REG_LIVE_READ64)
2261                         /* The parentage chain never changes and
2262                          * this parent was already marked as LIVE_READ.
2263                          * There is no need to keep walking the chain again and
2264                          * keep re-marking all parents as LIVE_READ.
2265                          * This case happens when the same register is read
2266                          * multiple times without writes into it in-between.
2267                          * Also, if parent has the stronger REG_LIVE_READ64 set,
2268                          * then no need to set the weak REG_LIVE_READ32.
2269                          */
2270                         break;
2271                 /* ... then we depend on parent's value */
2272                 parent->live |= flag;
2273                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2274                 if (flag == REG_LIVE_READ64)
2275                         parent->live &= ~REG_LIVE_READ32;
2276                 state = parent;
2277                 parent = state->parent;
2278                 writes = true;
2279                 cnt++;
2280         }
2281
2282         if (env->longest_mark_read_walk < cnt)
2283                 env->longest_mark_read_walk = cnt;
2284         return 0;
2285 }
2286
2287 /* This function is supposed to be used by the following 32-bit optimization
2288  * code only. It returns TRUE if the source or destination register operates
2289  * on 64-bit, otherwise return FALSE.
2290  */
2291 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2292                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2293 {
2294         u8 code, class, op;
2295
2296         code = insn->code;
2297         class = BPF_CLASS(code);
2298         op = BPF_OP(code);
2299         if (class == BPF_JMP) {
2300                 /* BPF_EXIT for "main" will reach here. Return TRUE
2301                  * conservatively.
2302                  */
2303                 if (op == BPF_EXIT)
2304                         return true;
2305                 if (op == BPF_CALL) {
2306                         /* BPF to BPF call will reach here because of marking
2307                          * caller saved clobber with DST_OP_NO_MARK for which we
2308                          * don't care the register def because they are anyway
2309                          * marked as NOT_INIT already.
2310                          */
2311                         if (insn->src_reg == BPF_PSEUDO_CALL)
2312                                 return false;
2313                         /* Helper call will reach here because of arg type
2314                          * check, conservatively return TRUE.
2315                          */
2316                         if (t == SRC_OP)
2317                                 return true;
2318
2319                         return false;
2320                 }
2321         }
2322
2323         if (class == BPF_ALU64 || class == BPF_JMP ||
2324             /* BPF_END always use BPF_ALU class. */
2325             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2326                 return true;
2327
2328         if (class == BPF_ALU || class == BPF_JMP32)
2329                 return false;
2330
2331         if (class == BPF_LDX) {
2332                 if (t != SRC_OP)
2333                         return BPF_SIZE(code) == BPF_DW;
2334                 /* LDX source must be ptr. */
2335                 return true;
2336         }
2337
2338         if (class == BPF_STX) {
2339                 /* BPF_STX (including atomic variants) has multiple source
2340                  * operands, one of which is a ptr. Check whether the caller is
2341                  * asking about it.
2342                  */
2343                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2344                         return true;
2345                 return BPF_SIZE(code) == BPF_DW;
2346         }
2347
2348         if (class == BPF_LD) {
2349                 u8 mode = BPF_MODE(code);
2350
2351                 /* LD_IMM64 */
2352                 if (mode == BPF_IMM)
2353                         return true;
2354
2355                 /* Both LD_IND and LD_ABS return 32-bit data. */
2356                 if (t != SRC_OP)
2357                         return  false;
2358
2359                 /* Implicit ctx ptr. */
2360                 if (regno == BPF_REG_6)
2361                         return true;
2362
2363                 /* Explicit source could be any width. */
2364                 return true;
2365         }
2366
2367         if (class == BPF_ST)
2368                 /* The only source register for BPF_ST is a ptr. */
2369                 return true;
2370
2371         /* Conservatively return true at default. */
2372         return true;
2373 }
2374
2375 /* Return the regno defined by the insn, or -1. */
2376 static int insn_def_regno(const struct bpf_insn *insn)
2377 {
2378         switch (BPF_CLASS(insn->code)) {
2379         case BPF_JMP:
2380         case BPF_JMP32:
2381         case BPF_ST:
2382                 return -1;
2383         case BPF_STX:
2384                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2385                     (insn->imm & BPF_FETCH)) {
2386                         if (insn->imm == BPF_CMPXCHG)
2387                                 return BPF_REG_0;
2388                         else
2389                                 return insn->src_reg;
2390                 } else {
2391                         return -1;
2392                 }
2393         default:
2394                 return insn->dst_reg;
2395         }
2396 }
2397
2398 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2399 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2400 {
2401         int dst_reg = insn_def_regno(insn);
2402
2403         if (dst_reg == -1)
2404                 return false;
2405
2406         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2407 }
2408
2409 static void mark_insn_zext(struct bpf_verifier_env *env,
2410                            struct bpf_reg_state *reg)
2411 {
2412         s32 def_idx = reg->subreg_def;
2413
2414         if (def_idx == DEF_NOT_SUBREG)
2415                 return;
2416
2417         env->insn_aux_data[def_idx - 1].zext_dst = true;
2418         /* The dst will be zero extended, so won't be sub-register anymore. */
2419         reg->subreg_def = DEF_NOT_SUBREG;
2420 }
2421
2422 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2423                          enum reg_arg_type t)
2424 {
2425         struct bpf_verifier_state *vstate = env->cur_state;
2426         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2427         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2428         struct bpf_reg_state *reg, *regs = state->regs;
2429         bool rw64;
2430
2431         if (regno >= MAX_BPF_REG) {
2432                 verbose(env, "R%d is invalid\n", regno);
2433                 return -EINVAL;
2434         }
2435
2436         mark_reg_scratched(env, regno);
2437
2438         reg = &regs[regno];
2439         rw64 = is_reg64(env, insn, regno, reg, t);
2440         if (t == SRC_OP) {
2441                 /* check whether register used as source operand can be read */
2442                 if (reg->type == NOT_INIT) {
2443                         verbose(env, "R%d !read_ok\n", regno);
2444                         return -EACCES;
2445                 }
2446                 /* We don't need to worry about FP liveness because it's read-only */
2447                 if (regno == BPF_REG_FP)
2448                         return 0;
2449
2450                 if (rw64)
2451                         mark_insn_zext(env, reg);
2452
2453                 return mark_reg_read(env, reg, reg->parent,
2454                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2455         } else {
2456                 /* check whether register used as dest operand can be written to */
2457                 if (regno == BPF_REG_FP) {
2458                         verbose(env, "frame pointer is read only\n");
2459                         return -EACCES;
2460                 }
2461                 reg->live |= REG_LIVE_WRITTEN;
2462                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2463                 if (t == DST_OP)
2464                         mark_reg_unknown(env, regs, regno);
2465         }
2466         return 0;
2467 }
2468
2469 /* for any branch, call, exit record the history of jmps in the given state */
2470 static int push_jmp_history(struct bpf_verifier_env *env,
2471                             struct bpf_verifier_state *cur)
2472 {
2473         u32 cnt = cur->jmp_history_cnt;
2474         struct bpf_idx_pair *p;
2475
2476         cnt++;
2477         p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2478         if (!p)
2479                 return -ENOMEM;
2480         p[cnt - 1].idx = env->insn_idx;
2481         p[cnt - 1].prev_idx = env->prev_insn_idx;
2482         cur->jmp_history = p;
2483         cur->jmp_history_cnt = cnt;
2484         return 0;
2485 }
2486
2487 /* Backtrack one insn at a time. If idx is not at the top of recorded
2488  * history then previous instruction came from straight line execution.
2489  */
2490 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2491                              u32 *history)
2492 {
2493         u32 cnt = *history;
2494
2495         if (cnt && st->jmp_history[cnt - 1].idx == i) {
2496                 i = st->jmp_history[cnt - 1].prev_idx;
2497                 (*history)--;
2498         } else {
2499                 i--;
2500         }
2501         return i;
2502 }
2503
2504 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2505 {
2506         const struct btf_type *func;
2507         struct btf *desc_btf;
2508
2509         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2510                 return NULL;
2511
2512         desc_btf = find_kfunc_desc_btf(data, insn->off);
2513         if (IS_ERR(desc_btf))
2514                 return "<error>";
2515
2516         func = btf_type_by_id(desc_btf, insn->imm);
2517         return btf_name_by_offset(desc_btf, func->name_off);
2518 }
2519
2520 /* For given verifier state backtrack_insn() is called from the last insn to
2521  * the first insn. Its purpose is to compute a bitmask of registers and
2522  * stack slots that needs precision in the parent verifier state.
2523  */
2524 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2525                           u32 *reg_mask, u64 *stack_mask)
2526 {
2527         const struct bpf_insn_cbs cbs = {
2528                 .cb_call        = disasm_kfunc_name,
2529                 .cb_print       = verbose,
2530                 .private_data   = env,
2531         };
2532         struct bpf_insn *insn = env->prog->insnsi + idx;
2533         u8 class = BPF_CLASS(insn->code);
2534         u8 opcode = BPF_OP(insn->code);
2535         u8 mode = BPF_MODE(insn->code);
2536         u32 dreg = 1u << insn->dst_reg;
2537         u32 sreg = 1u << insn->src_reg;
2538         u32 spi;
2539
2540         if (insn->code == 0)
2541                 return 0;
2542         if (env->log.level & BPF_LOG_LEVEL2) {
2543                 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2544                 verbose(env, "%d: ", idx);
2545                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2546         }
2547
2548         if (class == BPF_ALU || class == BPF_ALU64) {
2549                 if (!(*reg_mask & dreg))
2550                         return 0;
2551                 if (opcode == BPF_MOV) {
2552                         if (BPF_SRC(insn->code) == BPF_X) {
2553                                 /* dreg = sreg
2554                                  * dreg needs precision after this insn
2555                                  * sreg needs precision before this insn
2556                                  */
2557                                 *reg_mask &= ~dreg;
2558                                 *reg_mask |= sreg;
2559                         } else {
2560                                 /* dreg = K
2561                                  * dreg needs precision after this insn.
2562                                  * Corresponding register is already marked
2563                                  * as precise=true in this verifier state.
2564                                  * No further markings in parent are necessary
2565                                  */
2566                                 *reg_mask &= ~dreg;
2567                         }
2568                 } else {
2569                         if (BPF_SRC(insn->code) == BPF_X) {
2570                                 /* dreg += sreg
2571                                  * both dreg and sreg need precision
2572                                  * before this insn
2573                                  */
2574                                 *reg_mask |= sreg;
2575                         } /* else dreg += K
2576                            * dreg still needs precision before this insn
2577                            */
2578                 }
2579         } else if (class == BPF_LDX) {
2580                 if (!(*reg_mask & dreg))
2581                         return 0;
2582                 *reg_mask &= ~dreg;
2583
2584                 /* scalars can only be spilled into stack w/o losing precision.
2585                  * Load from any other memory can be zero extended.
2586                  * The desire to keep that precision is already indicated
2587                  * by 'precise' mark in corresponding register of this state.
2588                  * No further tracking necessary.
2589                  */
2590                 if (insn->src_reg != BPF_REG_FP)
2591                         return 0;
2592
2593                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2594                  * that [fp - off] slot contains scalar that needs to be
2595                  * tracked with precision
2596                  */
2597                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2598                 if (spi >= 64) {
2599                         verbose(env, "BUG spi %d\n", spi);
2600                         WARN_ONCE(1, "verifier backtracking bug");
2601                         return -EFAULT;
2602                 }
2603                 *stack_mask |= 1ull << spi;
2604         } else if (class == BPF_STX || class == BPF_ST) {
2605                 if (*reg_mask & dreg)
2606                         /* stx & st shouldn't be using _scalar_ dst_reg
2607                          * to access memory. It means backtracking
2608                          * encountered a case of pointer subtraction.
2609                          */
2610                         return -ENOTSUPP;
2611                 /* scalars can only be spilled into stack */
2612                 if (insn->dst_reg != BPF_REG_FP)
2613                         return 0;
2614                 spi = (-insn->off - 1) / BPF_REG_SIZE;
2615                 if (spi >= 64) {
2616                         verbose(env, "BUG spi %d\n", spi);
2617                         WARN_ONCE(1, "verifier backtracking bug");
2618                         return -EFAULT;
2619                 }
2620                 if (!(*stack_mask & (1ull << spi)))
2621                         return 0;
2622                 *stack_mask &= ~(1ull << spi);
2623                 if (class == BPF_STX)
2624                         *reg_mask |= sreg;
2625         } else if (class == BPF_JMP || class == BPF_JMP32) {
2626                 if (opcode == BPF_CALL) {
2627                         if (insn->src_reg == BPF_PSEUDO_CALL)
2628                                 return -ENOTSUPP;
2629                         /* regular helper call sets R0 */
2630                         *reg_mask &= ~1;
2631                         if (*reg_mask & 0x3f) {
2632                                 /* if backtracing was looking for registers R1-R5
2633                                  * they should have been found already.
2634                                  */
2635                                 verbose(env, "BUG regs %x\n", *reg_mask);
2636                                 WARN_ONCE(1, "verifier backtracking bug");
2637                                 return -EFAULT;
2638                         }
2639                 } else if (opcode == BPF_EXIT) {
2640                         return -ENOTSUPP;
2641                 }
2642         } else if (class == BPF_LD) {
2643                 if (!(*reg_mask & dreg))
2644                         return 0;
2645                 *reg_mask &= ~dreg;
2646                 /* It's ld_imm64 or ld_abs or ld_ind.
2647                  * For ld_imm64 no further tracking of precision
2648                  * into parent is necessary
2649                  */
2650                 if (mode == BPF_IND || mode == BPF_ABS)
2651                         /* to be analyzed */
2652                         return -ENOTSUPP;
2653         }
2654         return 0;
2655 }
2656
2657 /* the scalar precision tracking algorithm:
2658  * . at the start all registers have precise=false.
2659  * . scalar ranges are tracked as normal through alu and jmp insns.
2660  * . once precise value of the scalar register is used in:
2661  *   .  ptr + scalar alu
2662  *   . if (scalar cond K|scalar)
2663  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
2664  *   backtrack through the verifier states and mark all registers and
2665  *   stack slots with spilled constants that these scalar regisers
2666  *   should be precise.
2667  * . during state pruning two registers (or spilled stack slots)
2668  *   are equivalent if both are not precise.
2669  *
2670  * Note the verifier cannot simply walk register parentage chain,
2671  * since many different registers and stack slots could have been
2672  * used to compute single precise scalar.
2673  *
2674  * The approach of starting with precise=true for all registers and then
2675  * backtrack to mark a register as not precise when the verifier detects
2676  * that program doesn't care about specific value (e.g., when helper
2677  * takes register as ARG_ANYTHING parameter) is not safe.
2678  *
2679  * It's ok to walk single parentage chain of the verifier states.
2680  * It's possible that this backtracking will go all the way till 1st insn.
2681  * All other branches will be explored for needing precision later.
2682  *
2683  * The backtracking needs to deal with cases like:
2684  *   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)
2685  * r9 -= r8
2686  * r5 = r9
2687  * if r5 > 0x79f goto pc+7
2688  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2689  * r5 += 1
2690  * ...
2691  * call bpf_perf_event_output#25
2692  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2693  *
2694  * and this case:
2695  * r6 = 1
2696  * call foo // uses callee's r6 inside to compute r0
2697  * r0 += r6
2698  * if r0 == 0 goto
2699  *
2700  * to track above reg_mask/stack_mask needs to be independent for each frame.
2701  *
2702  * Also if parent's curframe > frame where backtracking started,
2703  * the verifier need to mark registers in both frames, otherwise callees
2704  * may incorrectly prune callers. This is similar to
2705  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2706  *
2707  * For now backtracking falls back into conservative marking.
2708  */
2709 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2710                                      struct bpf_verifier_state *st)
2711 {
2712         struct bpf_func_state *func;
2713         struct bpf_reg_state *reg;
2714         int i, j;
2715
2716         /* big hammer: mark all scalars precise in this path.
2717          * pop_stack may still get !precise scalars.
2718          */
2719         for (; st; st = st->parent)
2720                 for (i = 0; i <= st->curframe; i++) {
2721                         func = st->frame[i];
2722                         for (j = 0; j < BPF_REG_FP; j++) {
2723                                 reg = &func->regs[j];
2724                                 if (reg->type != SCALAR_VALUE)
2725                                         continue;
2726                                 reg->precise = true;
2727                         }
2728                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2729                                 if (!is_spilled_reg(&func->stack[j]))
2730                                         continue;
2731                                 reg = &func->stack[j].spilled_ptr;
2732                                 if (reg->type != SCALAR_VALUE)
2733                                         continue;
2734                                 reg->precise = true;
2735                         }
2736                 }
2737 }
2738
2739 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2740                                   int spi)
2741 {
2742         struct bpf_verifier_state *st = env->cur_state;
2743         int first_idx = st->first_insn_idx;
2744         int last_idx = env->insn_idx;
2745         struct bpf_func_state *func;
2746         struct bpf_reg_state *reg;
2747         u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2748         u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2749         bool skip_first = true;
2750         bool new_marks = false;
2751         int i, err;
2752
2753         if (!env->bpf_capable)
2754                 return 0;
2755
2756         func = st->frame[st->curframe];
2757         if (regno >= 0) {
2758                 reg = &func->regs[regno];
2759                 if (reg->type != SCALAR_VALUE) {
2760                         WARN_ONCE(1, "backtracing misuse");
2761                         return -EFAULT;
2762                 }
2763                 if (!reg->precise)
2764                         new_marks = true;
2765                 else
2766                         reg_mask = 0;
2767                 reg->precise = true;
2768         }
2769
2770         while (spi >= 0) {
2771                 if (!is_spilled_reg(&func->stack[spi])) {
2772                         stack_mask = 0;
2773                         break;
2774                 }
2775                 reg = &func->stack[spi].spilled_ptr;
2776                 if (reg->type != SCALAR_VALUE) {
2777                         stack_mask = 0;
2778                         break;
2779                 }
2780                 if (!reg->precise)
2781                         new_marks = true;
2782                 else
2783                         stack_mask = 0;
2784                 reg->precise = true;
2785                 break;
2786         }
2787
2788         if (!new_marks)
2789                 return 0;
2790         if (!reg_mask && !stack_mask)
2791                 return 0;
2792         for (;;) {
2793                 DECLARE_BITMAP(mask, 64);
2794                 u32 history = st->jmp_history_cnt;
2795
2796                 if (env->log.level & BPF_LOG_LEVEL2)
2797                         verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2798                 for (i = last_idx;;) {
2799                         if (skip_first) {
2800                                 err = 0;
2801                                 skip_first = false;
2802                         } else {
2803                                 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2804                         }
2805                         if (err == -ENOTSUPP) {
2806                                 mark_all_scalars_precise(env, st);
2807                                 return 0;
2808                         } else if (err) {
2809                                 return err;
2810                         }
2811                         if (!reg_mask && !stack_mask)
2812                                 /* Found assignment(s) into tracked register in this state.
2813                                  * Since this state is already marked, just return.
2814                                  * Nothing to be tracked further in the parent state.
2815                                  */
2816                                 return 0;
2817                         if (i == first_idx)
2818                                 break;
2819                         i = get_prev_insn_idx(st, i, &history);
2820                         if (i >= env->prog->len) {
2821                                 /* This can happen if backtracking reached insn 0
2822                                  * and there are still reg_mask or stack_mask
2823                                  * to backtrack.
2824                                  * It means the backtracking missed the spot where
2825                                  * particular register was initialized with a constant.
2826                                  */
2827                                 verbose(env, "BUG backtracking idx %d\n", i);
2828                                 WARN_ONCE(1, "verifier backtracking bug");
2829                                 return -EFAULT;
2830                         }
2831                 }
2832                 st = st->parent;
2833                 if (!st)
2834                         break;
2835
2836                 new_marks = false;
2837                 func = st->frame[st->curframe];
2838                 bitmap_from_u64(mask, reg_mask);
2839                 for_each_set_bit(i, mask, 32) {
2840                         reg = &func->regs[i];
2841                         if (reg->type != SCALAR_VALUE) {
2842                                 reg_mask &= ~(1u << i);
2843                                 continue;
2844                         }
2845                         if (!reg->precise)
2846                                 new_marks = true;
2847                         reg->precise = true;
2848                 }
2849
2850                 bitmap_from_u64(mask, stack_mask);
2851                 for_each_set_bit(i, mask, 64) {
2852                         if (i >= func->allocated_stack / BPF_REG_SIZE) {
2853                                 /* the sequence of instructions:
2854                                  * 2: (bf) r3 = r10
2855                                  * 3: (7b) *(u64 *)(r3 -8) = r0
2856                                  * 4: (79) r4 = *(u64 *)(r10 -8)
2857                                  * doesn't contain jmps. It's backtracked
2858                                  * as a single block.
2859                                  * During backtracking insn 3 is not recognized as
2860                                  * stack access, so at the end of backtracking
2861                                  * stack slot fp-8 is still marked in stack_mask.
2862                                  * However the parent state may not have accessed
2863                                  * fp-8 and it's "unallocated" stack space.
2864                                  * In such case fallback to conservative.
2865                                  */
2866                                 mark_all_scalars_precise(env, st);
2867                                 return 0;
2868                         }
2869
2870                         if (!is_spilled_reg(&func->stack[i])) {
2871                                 stack_mask &= ~(1ull << i);
2872                                 continue;
2873                         }
2874                         reg = &func->stack[i].spilled_ptr;
2875                         if (reg->type != SCALAR_VALUE) {
2876                                 stack_mask &= ~(1ull << i);
2877                                 continue;
2878                         }
2879                         if (!reg->precise)
2880                                 new_marks = true;
2881                         reg->precise = true;
2882                 }
2883                 if (env->log.level & BPF_LOG_LEVEL2) {
2884                         verbose(env, "parent %s regs=%x stack=%llx marks:",
2885                                 new_marks ? "didn't have" : "already had",
2886                                 reg_mask, stack_mask);
2887                         print_verifier_state(env, func, true);
2888                 }
2889
2890                 if (!reg_mask && !stack_mask)
2891                         break;
2892                 if (!new_marks)
2893                         break;
2894
2895                 last_idx = st->last_insn_idx;
2896                 first_idx = st->first_insn_idx;
2897         }
2898         return 0;
2899 }
2900
2901 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2902 {
2903         return __mark_chain_precision(env, regno, -1);
2904 }
2905
2906 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2907 {
2908         return __mark_chain_precision(env, -1, spi);
2909 }
2910
2911 static bool is_spillable_regtype(enum bpf_reg_type type)
2912 {
2913         switch (base_type(type)) {
2914         case PTR_TO_MAP_VALUE:
2915         case PTR_TO_STACK:
2916         case PTR_TO_CTX:
2917         case PTR_TO_PACKET:
2918         case PTR_TO_PACKET_META:
2919         case PTR_TO_PACKET_END:
2920         case PTR_TO_FLOW_KEYS:
2921         case CONST_PTR_TO_MAP:
2922         case PTR_TO_SOCKET:
2923         case PTR_TO_SOCK_COMMON:
2924         case PTR_TO_TCP_SOCK:
2925         case PTR_TO_XDP_SOCK:
2926         case PTR_TO_BTF_ID:
2927         case PTR_TO_BUF:
2928         case PTR_TO_MEM:
2929         case PTR_TO_FUNC:
2930         case PTR_TO_MAP_KEY:
2931                 return true;
2932         default:
2933                 return false;
2934         }
2935 }
2936
2937 /* Does this register contain a constant zero? */
2938 static bool register_is_null(struct bpf_reg_state *reg)
2939 {
2940         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2941 }
2942
2943 static bool register_is_const(struct bpf_reg_state *reg)
2944 {
2945         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2946 }
2947
2948 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2949 {
2950         return tnum_is_unknown(reg->var_off) &&
2951                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2952                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2953                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2954                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2955 }
2956
2957 static bool register_is_bounded(struct bpf_reg_state *reg)
2958 {
2959         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2960 }
2961
2962 static bool __is_pointer_value(bool allow_ptr_leaks,
2963                                const struct bpf_reg_state *reg)
2964 {
2965         if (allow_ptr_leaks)
2966                 return false;
2967
2968         return reg->type != SCALAR_VALUE;
2969 }
2970
2971 static void save_register_state(struct bpf_func_state *state,
2972                                 int spi, struct bpf_reg_state *reg,
2973                                 int size)
2974 {
2975         int i;
2976
2977         state->stack[spi].spilled_ptr = *reg;
2978         if (size == BPF_REG_SIZE)
2979                 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2980
2981         for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
2982                 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
2983
2984         /* size < 8 bytes spill */
2985         for (; i; i--)
2986                 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
2987 }
2988
2989 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2990  * stack boundary and alignment are checked in check_mem_access()
2991  */
2992 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2993                                        /* stack frame we're writing to */
2994                                        struct bpf_func_state *state,
2995                                        int off, int size, int value_regno,
2996                                        int insn_idx)
2997 {
2998         struct bpf_func_state *cur; /* state of the current function */
2999         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3000         u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
3001         struct bpf_reg_state *reg = NULL;
3002
3003         err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3004         if (err)
3005                 return err;
3006         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3007          * so it's aligned access and [off, off + size) are within stack limits
3008          */
3009         if (!env->allow_ptr_leaks &&
3010             state->stack[spi].slot_type[0] == STACK_SPILL &&
3011             size != BPF_REG_SIZE) {
3012                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3013                 return -EACCES;
3014         }
3015
3016         cur = env->cur_state->frame[env->cur_state->curframe];
3017         if (value_regno >= 0)
3018                 reg = &cur->regs[value_regno];
3019         if (!env->bypass_spec_v4) {
3020                 bool sanitize = reg && is_spillable_regtype(reg->type);
3021
3022                 for (i = 0; i < size; i++) {
3023                         if (state->stack[spi].slot_type[i] == STACK_INVALID) {
3024                                 sanitize = true;
3025                                 break;
3026                         }
3027                 }
3028
3029                 if (sanitize)
3030                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3031         }
3032
3033         mark_stack_slot_scratched(env, spi);
3034         if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3035             !register_is_null(reg) && env->bpf_capable) {
3036                 if (dst_reg != BPF_REG_FP) {
3037                         /* The backtracking logic can only recognize explicit
3038                          * stack slot address like [fp - 8]. Other spill of
3039                          * scalar via different register has to be conservative.
3040                          * Backtrack from here and mark all registers as precise
3041                          * that contributed into 'reg' being a constant.
3042                          */
3043                         err = mark_chain_precision(env, value_regno);
3044                         if (err)
3045                                 return err;
3046                 }
3047                 save_register_state(state, spi, reg, size);
3048         } else if (reg && is_spillable_regtype(reg->type)) {
3049                 /* register containing pointer is being spilled into stack */
3050                 if (size != BPF_REG_SIZE) {
3051                         verbose_linfo(env, insn_idx, "; ");
3052                         verbose(env, "invalid size of register spill\n");
3053                         return -EACCES;
3054                 }
3055                 if (state != cur && reg->type == PTR_TO_STACK) {
3056                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3057                         return -EINVAL;
3058                 }
3059                 save_register_state(state, spi, reg, size);
3060         } else {
3061                 u8 type = STACK_MISC;
3062
3063                 /* regular write of data into stack destroys any spilled ptr */
3064                 state->stack[spi].spilled_ptr.type = NOT_INIT;
3065                 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3066                 if (is_spilled_reg(&state->stack[spi]))
3067                         for (i = 0; i < BPF_REG_SIZE; i++)
3068                                 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3069
3070                 /* only mark the slot as written if all 8 bytes were written
3071                  * otherwise read propagation may incorrectly stop too soon
3072                  * when stack slots are partially written.
3073                  * This heuristic means that read propagation will be
3074                  * conservative, since it will add reg_live_read marks
3075                  * to stack slots all the way to first state when programs
3076                  * writes+reads less than 8 bytes
3077                  */
3078                 if (size == BPF_REG_SIZE)
3079                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3080
3081                 /* when we zero initialize stack slots mark them as such */
3082                 if (reg && register_is_null(reg)) {
3083                         /* backtracking doesn't work for STACK_ZERO yet. */
3084                         err = mark_chain_precision(env, value_regno);
3085                         if (err)
3086                                 return err;
3087                         type = STACK_ZERO;
3088                 }
3089
3090                 /* Mark slots affected by this stack write. */
3091                 for (i = 0; i < size; i++)
3092                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3093                                 type;
3094         }
3095         return 0;
3096 }
3097
3098 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3099  * known to contain a variable offset.
3100  * This function checks whether the write is permitted and conservatively
3101  * tracks the effects of the write, considering that each stack slot in the
3102  * dynamic range is potentially written to.
3103  *
3104  * 'off' includes 'regno->off'.
3105  * 'value_regno' can be -1, meaning that an unknown value is being written to
3106  * the stack.
3107  *
3108  * Spilled pointers in range are not marked as written because we don't know
3109  * what's going to be actually written. This means that read propagation for
3110  * future reads cannot be terminated by this write.
3111  *
3112  * For privileged programs, uninitialized stack slots are considered
3113  * initialized by this write (even though we don't know exactly what offsets
3114  * are going to be written to). The idea is that we don't want the verifier to
3115  * reject future reads that access slots written to through variable offsets.
3116  */
3117 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3118                                      /* func where register points to */
3119                                      struct bpf_func_state *state,
3120                                      int ptr_regno, int off, int size,
3121                                      int value_regno, int insn_idx)
3122 {
3123         struct bpf_func_state *cur; /* state of the current function */
3124         int min_off, max_off;
3125         int i, err;
3126         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3127         bool writing_zero = false;
3128         /* set if the fact that we're writing a zero is used to let any
3129          * stack slots remain STACK_ZERO
3130          */
3131         bool zero_used = false;
3132
3133         cur = env->cur_state->frame[env->cur_state->curframe];
3134         ptr_reg = &cur->regs[ptr_regno];
3135         min_off = ptr_reg->smin_value + off;
3136         max_off = ptr_reg->smax_value + off + size;
3137         if (value_regno >= 0)
3138                 value_reg = &cur->regs[value_regno];
3139         if (value_reg && register_is_null(value_reg))
3140                 writing_zero = true;
3141
3142         err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3143         if (err)
3144                 return err;
3145
3146
3147         /* Variable offset writes destroy any spilled pointers in range. */
3148         for (i = min_off; i < max_off; i++) {
3149                 u8 new_type, *stype;
3150                 int slot, spi;
3151
3152                 slot = -i - 1;
3153                 spi = slot / BPF_REG_SIZE;
3154                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3155                 mark_stack_slot_scratched(env, spi);
3156
3157                 if (!env->allow_ptr_leaks
3158                                 && *stype != NOT_INIT
3159                                 && *stype != SCALAR_VALUE) {
3160                         /* Reject the write if there's are spilled pointers in
3161                          * range. If we didn't reject here, the ptr status
3162                          * would be erased below (even though not all slots are
3163                          * actually overwritten), possibly opening the door to
3164                          * leaks.
3165                          */
3166                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3167                                 insn_idx, i);
3168                         return -EINVAL;
3169                 }
3170
3171                 /* Erase all spilled pointers. */
3172                 state->stack[spi].spilled_ptr.type = NOT_INIT;
3173
3174                 /* Update the slot type. */
3175                 new_type = STACK_MISC;
3176                 if (writing_zero && *stype == STACK_ZERO) {
3177                         new_type = STACK_ZERO;
3178                         zero_used = true;
3179                 }
3180                 /* If the slot is STACK_INVALID, we check whether it's OK to
3181                  * pretend that it will be initialized by this write. The slot
3182                  * might not actually be written to, and so if we mark it as
3183                  * initialized future reads might leak uninitialized memory.
3184                  * For privileged programs, we will accept such reads to slots
3185                  * that may or may not be written because, if we're reject
3186                  * them, the error would be too confusing.
3187                  */
3188                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3189                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3190                                         insn_idx, i);
3191                         return -EINVAL;
3192                 }
3193                 *stype = new_type;
3194         }
3195         if (zero_used) {
3196                 /* backtracking doesn't work for STACK_ZERO yet. */
3197                 err = mark_chain_precision(env, value_regno);
3198                 if (err)
3199                         return err;
3200         }
3201         return 0;
3202 }
3203
3204 /* When register 'dst_regno' is assigned some values from stack[min_off,
3205  * max_off), we set the register's type according to the types of the
3206  * respective stack slots. If all the stack values are known to be zeros, then
3207  * so is the destination reg. Otherwise, the register is considered to be
3208  * SCALAR. This function does not deal with register filling; the caller must
3209  * ensure that all spilled registers in the stack range have been marked as
3210  * read.
3211  */
3212 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3213                                 /* func where src register points to */
3214                                 struct bpf_func_state *ptr_state,
3215                                 int min_off, int max_off, int dst_regno)
3216 {
3217         struct bpf_verifier_state *vstate = env->cur_state;
3218         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3219         int i, slot, spi;
3220         u8 *stype;
3221         int zeros = 0;
3222
3223         for (i = min_off; i < max_off; i++) {
3224                 slot = -i - 1;
3225                 spi = slot / BPF_REG_SIZE;
3226                 stype = ptr_state->stack[spi].slot_type;
3227                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3228                         break;
3229                 zeros++;
3230         }
3231         if (zeros == max_off - min_off) {
3232                 /* any access_size read into register is zero extended,
3233                  * so the whole register == const_zero
3234                  */
3235                 __mark_reg_const_zero(&state->regs[dst_regno]);
3236                 /* backtracking doesn't support STACK_ZERO yet,
3237                  * so mark it precise here, so that later
3238                  * backtracking can stop here.
3239                  * Backtracking may not need this if this register
3240                  * doesn't participate in pointer adjustment.
3241                  * Forward propagation of precise flag is not
3242                  * necessary either. This mark is only to stop
3243                  * backtracking. Any register that contributed
3244                  * to const 0 was marked precise before spill.
3245                  */
3246                 state->regs[dst_regno].precise = true;
3247         } else {
3248                 /* have read misc data from the stack */
3249                 mark_reg_unknown(env, state->regs, dst_regno);
3250         }
3251         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3252 }
3253
3254 /* Read the stack at 'off' and put the results into the register indicated by
3255  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3256  * spilled reg.
3257  *
3258  * 'dst_regno' can be -1, meaning that the read value is not going to a
3259  * register.
3260  *
3261  * The access is assumed to be within the current stack bounds.
3262  */
3263 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3264                                       /* func where src register points to */
3265                                       struct bpf_func_state *reg_state,
3266                                       int off, int size, int dst_regno)
3267 {
3268         struct bpf_verifier_state *vstate = env->cur_state;
3269         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3270         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3271         struct bpf_reg_state *reg;
3272         u8 *stype, type;
3273
3274         stype = reg_state->stack[spi].slot_type;
3275         reg = &reg_state->stack[spi].spilled_ptr;
3276
3277         if (is_spilled_reg(&reg_state->stack[spi])) {
3278                 u8 spill_size = 1;
3279
3280                 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3281                         spill_size++;
3282
3283                 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3284                         if (reg->type != SCALAR_VALUE) {
3285                                 verbose_linfo(env, env->insn_idx, "; ");
3286                                 verbose(env, "invalid size of register fill\n");
3287                                 return -EACCES;
3288                         }
3289
3290                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3291                         if (dst_regno < 0)
3292                                 return 0;
3293
3294                         if (!(off % BPF_REG_SIZE) && size == spill_size) {
3295                                 /* The earlier check_reg_arg() has decided the
3296                                  * subreg_def for this insn.  Save it first.
3297                                  */
3298                                 s32 subreg_def = state->regs[dst_regno].subreg_def;
3299
3300                                 state->regs[dst_regno] = *reg;
3301                                 state->regs[dst_regno].subreg_def = subreg_def;
3302                         } else {
3303                                 for (i = 0; i < size; i++) {
3304                                         type = stype[(slot - i) % BPF_REG_SIZE];
3305                                         if (type == STACK_SPILL)
3306                                                 continue;
3307                                         if (type == STACK_MISC)
3308                                                 continue;
3309                                         verbose(env, "invalid read from stack off %d+%d size %d\n",
3310                                                 off, i, size);
3311                                         return -EACCES;
3312                                 }
3313                                 mark_reg_unknown(env, state->regs, dst_regno);
3314                         }
3315                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3316                         return 0;
3317                 }
3318
3319                 if (dst_regno >= 0) {
3320                         /* restore register state from stack */
3321                         state->regs[dst_regno] = *reg;
3322                         /* mark reg as written since spilled pointer state likely
3323                          * has its liveness marks cleared by is_state_visited()
3324                          * which resets stack/reg liveness for state transitions
3325                          */
3326                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3327                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3328                         /* If dst_regno==-1, the caller is asking us whether
3329                          * it is acceptable to use this value as a SCALAR_VALUE
3330                          * (e.g. for XADD).
3331                          * We must not allow unprivileged callers to do that
3332                          * with spilled pointers.
3333                          */
3334                         verbose(env, "leaking pointer from stack off %d\n",
3335                                 off);
3336                         return -EACCES;
3337                 }
3338                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3339         } else {
3340                 for (i = 0; i < size; i++) {
3341                         type = stype[(slot - i) % BPF_REG_SIZE];
3342                         if (type == STACK_MISC)
3343                                 continue;
3344                         if (type == STACK_ZERO)
3345                                 continue;
3346                         verbose(env, "invalid read from stack off %d+%d size %d\n",
3347                                 off, i, size);
3348                         return -EACCES;
3349                 }
3350                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3351                 if (dst_regno >= 0)
3352                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3353         }
3354         return 0;
3355 }
3356
3357 enum bpf_access_src {
3358         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
3359         ACCESS_HELPER = 2,  /* the access is performed by a helper */
3360 };
3361
3362 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3363                                          int regno, int off, int access_size,
3364                                          bool zero_size_allowed,
3365                                          enum bpf_access_src type,
3366                                          struct bpf_call_arg_meta *meta);
3367
3368 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3369 {
3370         return cur_regs(env) + regno;
3371 }
3372
3373 /* Read the stack at 'ptr_regno + off' and put the result into the register
3374  * 'dst_regno'.
3375  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3376  * but not its variable offset.
3377  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3378  *
3379  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3380  * filling registers (i.e. reads of spilled register cannot be detected when
3381  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3382  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3383  * offset; for a fixed offset check_stack_read_fixed_off should be used
3384  * instead.
3385  */
3386 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3387                                     int ptr_regno, int off, int size, int dst_regno)
3388 {
3389         /* The state of the source register. */
3390         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3391         struct bpf_func_state *ptr_state = func(env, reg);
3392         int err;
3393         int min_off, max_off;
3394
3395         /* Note that we pass a NULL meta, so raw access will not be permitted.
3396          */
3397         err = check_stack_range_initialized(env, ptr_regno, off, size,
3398                                             false, ACCESS_DIRECT, NULL);
3399         if (err)
3400                 return err;
3401
3402         min_off = reg->smin_value + off;
3403         max_off = reg->smax_value + off;
3404         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3405         return 0;
3406 }
3407
3408 /* check_stack_read dispatches to check_stack_read_fixed_off or
3409  * check_stack_read_var_off.
3410  *
3411  * The caller must ensure that the offset falls within the allocated stack
3412  * bounds.
3413  *
3414  * 'dst_regno' is a register which will receive the value from the stack. It
3415  * can be -1, meaning that the read value is not going to a register.
3416  */
3417 static int check_stack_read(struct bpf_verifier_env *env,
3418                             int ptr_regno, int off, int size,
3419                             int dst_regno)
3420 {
3421         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3422         struct bpf_func_state *state = func(env, reg);
3423         int err;
3424         /* Some accesses are only permitted with a static offset. */
3425         bool var_off = !tnum_is_const(reg->var_off);
3426
3427         /* The offset is required to be static when reads don't go to a
3428          * register, in order to not leak pointers (see
3429          * check_stack_read_fixed_off).
3430          */
3431         if (dst_regno < 0 && var_off) {
3432                 char tn_buf[48];
3433
3434                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3435                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3436                         tn_buf, off, size);
3437                 return -EACCES;
3438         }
3439         /* Variable offset is prohibited for unprivileged mode for simplicity
3440          * since it requires corresponding support in Spectre masking for stack
3441          * ALU. See also retrieve_ptr_limit().
3442          */
3443         if (!env->bypass_spec_v1 && var_off) {
3444                 char tn_buf[48];
3445
3446                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3447                 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3448                                 ptr_regno, tn_buf);
3449                 return -EACCES;
3450         }
3451
3452         if (!var_off) {
3453                 off += reg->var_off.value;
3454                 err = check_stack_read_fixed_off(env, state, off, size,
3455                                                  dst_regno);
3456         } else {
3457                 /* Variable offset stack reads need more conservative handling
3458                  * than fixed offset ones. Note that dst_regno >= 0 on this
3459                  * branch.
3460                  */
3461                 err = check_stack_read_var_off(env, ptr_regno, off, size,
3462                                                dst_regno);
3463         }
3464         return err;
3465 }
3466
3467
3468 /* check_stack_write dispatches to check_stack_write_fixed_off or
3469  * check_stack_write_var_off.
3470  *
3471  * 'ptr_regno' is the register used as a pointer into the stack.
3472  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3473  * 'value_regno' is the register whose value we're writing to the stack. It can
3474  * be -1, meaning that we're not writing from a register.
3475  *
3476  * The caller must ensure that the offset falls within the maximum stack size.
3477  */
3478 static int check_stack_write(struct bpf_verifier_env *env,
3479                              int ptr_regno, int off, int size,
3480                              int value_regno, int insn_idx)
3481 {
3482         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3483         struct bpf_func_state *state = func(env, reg);
3484         int err;
3485
3486         if (tnum_is_const(reg->var_off)) {
3487                 off += reg->var_off.value;
3488                 err = check_stack_write_fixed_off(env, state, off, size,
3489                                                   value_regno, insn_idx);
3490         } else {
3491                 /* Variable offset stack reads need more conservative handling
3492                  * than fixed offset ones.
3493                  */
3494                 err = check_stack_write_var_off(env, state,
3495                                                 ptr_regno, off, size,
3496                                                 value_regno, insn_idx);
3497         }
3498         return err;
3499 }
3500
3501 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3502                                  int off, int size, enum bpf_access_type type)
3503 {
3504         struct bpf_reg_state *regs = cur_regs(env);
3505         struct bpf_map *map = regs[regno].map_ptr;
3506         u32 cap = bpf_map_flags_to_cap(map);
3507
3508         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3509                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3510                         map->value_size, off, size);
3511                 return -EACCES;
3512         }
3513
3514         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3515                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3516                         map->value_size, off, size);
3517                 return -EACCES;
3518         }
3519
3520         return 0;
3521 }
3522
3523 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3524 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3525                               int off, int size, u32 mem_size,
3526                               bool zero_size_allowed)
3527 {
3528         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3529         struct bpf_reg_state *reg;
3530
3531         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3532                 return 0;
3533
3534         reg = &cur_regs(env)[regno];
3535         switch (reg->type) {
3536         case PTR_TO_MAP_KEY:
3537                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3538                         mem_size, off, size);
3539                 break;
3540         case PTR_TO_MAP_VALUE:
3541                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3542                         mem_size, off, size);
3543                 break;
3544         case PTR_TO_PACKET:
3545         case PTR_TO_PACKET_META:
3546         case PTR_TO_PACKET_END:
3547                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3548                         off, size, regno, reg->id, off, mem_size);
3549                 break;
3550         case PTR_TO_MEM:
3551         default:
3552                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3553                         mem_size, off, size);
3554         }
3555
3556         return -EACCES;
3557 }
3558
3559 /* check read/write into a memory region with possible variable offset */
3560 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3561                                    int off, int size, u32 mem_size,
3562                                    bool zero_size_allowed)
3563 {
3564         struct bpf_verifier_state *vstate = env->cur_state;
3565         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3566         struct bpf_reg_state *reg = &state->regs[regno];
3567         int err;
3568
3569         /* We may have adjusted the register pointing to memory region, so we
3570          * need to try adding each of min_value and max_value to off
3571          * to make sure our theoretical access will be safe.
3572          *
3573          * The minimum value is only important with signed
3574          * comparisons where we can't assume the floor of a
3575          * value is 0.  If we are using signed variables for our
3576          * index'es we need to make sure that whatever we use
3577          * will have a set floor within our range.
3578          */
3579         if (reg->smin_value < 0 &&
3580             (reg->smin_value == S64_MIN ||
3581              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3582               reg->smin_value + off < 0)) {
3583                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3584                         regno);
3585                 return -EACCES;
3586         }
3587         err = __check_mem_access(env, regno, reg->smin_value + off, size,
3588                                  mem_size, zero_size_allowed);
3589         if (err) {
3590                 verbose(env, "R%d min value is outside of the allowed memory range\n",
3591                         regno);
3592                 return err;
3593         }
3594
3595         /* If we haven't set a max value then we need to bail since we can't be
3596          * sure we won't do bad things.
3597          * If reg->umax_value + off could overflow, treat that as unbounded too.
3598          */
3599         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3600                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3601                         regno);
3602                 return -EACCES;
3603         }
3604         err = __check_mem_access(env, regno, reg->umax_value + off, size,
3605                                  mem_size, zero_size_allowed);
3606         if (err) {
3607                 verbose(env, "R%d max value is outside of the allowed memory range\n",
3608                         regno);
3609                 return err;
3610         }
3611
3612         return 0;
3613 }
3614
3615 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3616                                const struct bpf_reg_state *reg, int regno,
3617                                bool fixed_off_ok)
3618 {
3619         /* Access to this pointer-typed register or passing it to a helper
3620          * is only allowed in its original, unmodified form.
3621          */
3622
3623         if (reg->off < 0) {
3624                 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3625                         reg_type_str(env, reg->type), regno, reg->off);
3626                 return -EACCES;
3627         }
3628
3629         if (!fixed_off_ok && reg->off) {
3630                 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3631                         reg_type_str(env, reg->type), regno, reg->off);
3632                 return -EACCES;
3633         }
3634
3635         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3636                 char tn_buf[48];
3637
3638                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3639                 verbose(env, "variable %s access var_off=%s disallowed\n",
3640                         reg_type_str(env, reg->type), tn_buf);
3641                 return -EACCES;
3642         }
3643
3644         return 0;
3645 }
3646
3647 int check_ptr_off_reg(struct bpf_verifier_env *env,
3648                       const struct bpf_reg_state *reg, int regno)
3649 {
3650         return __check_ptr_off_reg(env, reg, regno, false);
3651 }
3652
3653 static int map_kptr_match_type(struct bpf_verifier_env *env,
3654                                struct bpf_map_value_off_desc *off_desc,
3655                                struct bpf_reg_state *reg, u32 regno)
3656 {
3657         const char *targ_name = kernel_type_name(off_desc->kptr.btf, off_desc->kptr.btf_id);
3658         int perm_flags = PTR_MAYBE_NULL;
3659         const char *reg_name = "";
3660
3661         /* Only unreferenced case accepts untrusted pointers */
3662         if (off_desc->type == BPF_KPTR_UNREF)
3663                 perm_flags |= PTR_UNTRUSTED;
3664
3665         if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3666                 goto bad_type;
3667
3668         if (!btf_is_kernel(reg->btf)) {
3669                 verbose(env, "R%d must point to kernel BTF\n", regno);
3670                 return -EINVAL;
3671         }
3672         /* We need to verify reg->type and reg->btf, before accessing reg->btf */
3673         reg_name = kernel_type_name(reg->btf, reg->btf_id);
3674
3675         /* For ref_ptr case, release function check should ensure we get one
3676          * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3677          * normal store of unreferenced kptr, we must ensure var_off is zero.
3678          * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3679          * reg->off and reg->ref_obj_id are not needed here.
3680          */
3681         if (__check_ptr_off_reg(env, reg, regno, true))
3682                 return -EACCES;
3683
3684         /* A full type match is needed, as BTF can be vmlinux or module BTF, and
3685          * we also need to take into account the reg->off.
3686          *
3687          * We want to support cases like:
3688          *
3689          * struct foo {
3690          *         struct bar br;
3691          *         struct baz bz;
3692          * };
3693          *
3694          * struct foo *v;
3695          * v = func();        // PTR_TO_BTF_ID
3696          * val->foo = v;      // reg->off is zero, btf and btf_id match type
3697          * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3698          *                    // first member type of struct after comparison fails
3699          * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3700          *                    // to match type
3701          *
3702          * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3703          * is zero. We must also ensure that btf_struct_ids_match does not walk
3704          * the struct to match type against first member of struct, i.e. reject
3705          * second case from above. Hence, when type is BPF_KPTR_REF, we set
3706          * strict mode to true for type match.
3707          */
3708         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3709                                   off_desc->kptr.btf, off_desc->kptr.btf_id,
3710                                   off_desc->type == BPF_KPTR_REF))
3711                 goto bad_type;
3712         return 0;
3713 bad_type:
3714         verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3715                 reg_type_str(env, reg->type), reg_name);
3716         verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3717         if (off_desc->type == BPF_KPTR_UNREF)
3718                 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3719                         targ_name);
3720         else
3721                 verbose(env, "\n");
3722         return -EINVAL;
3723 }
3724
3725 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3726                                  int value_regno, int insn_idx,
3727                                  struct bpf_map_value_off_desc *off_desc)
3728 {
3729         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3730         int class = BPF_CLASS(insn->code);
3731         struct bpf_reg_state *val_reg;
3732
3733         /* Things we already checked for in check_map_access and caller:
3734          *  - Reject cases where variable offset may touch kptr
3735          *  - size of access (must be BPF_DW)
3736          *  - tnum_is_const(reg->var_off)
3737          *  - off_desc->offset == off + reg->var_off.value
3738          */
3739         /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
3740         if (BPF_MODE(insn->code) != BPF_MEM) {
3741                 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
3742                 return -EACCES;
3743         }
3744
3745         /* We only allow loading referenced kptr, since it will be marked as
3746          * untrusted, similar to unreferenced kptr.
3747          */
3748         if (class != BPF_LDX && off_desc->type == BPF_KPTR_REF) {
3749                 verbose(env, "store to referenced kptr disallowed\n");
3750                 return -EACCES;
3751         }
3752
3753         if (class == BPF_LDX) {
3754                 val_reg = reg_state(env, value_regno);
3755                 /* We can simply mark the value_regno receiving the pointer
3756                  * value from map as PTR_TO_BTF_ID, with the correct type.
3757                  */
3758                 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, off_desc->kptr.btf,
3759                                 off_desc->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
3760                 /* For mark_ptr_or_null_reg */
3761                 val_reg->id = ++env->id_gen;
3762         } else if (class == BPF_STX) {
3763                 val_reg = reg_state(env, value_regno);
3764                 if (!register_is_null(val_reg) &&
3765                     map_kptr_match_type(env, off_desc, val_reg, value_regno))
3766                         return -EACCES;
3767         } else if (class == BPF_ST) {
3768                 if (insn->imm) {
3769                         verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
3770                                 off_desc->offset);
3771                         return -EACCES;
3772                 }
3773         } else {
3774                 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
3775                 return -EACCES;
3776         }
3777         return 0;
3778 }
3779
3780 /* check read/write into a map element with possible variable offset */
3781 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3782                             int off, int size, bool zero_size_allowed,
3783                             enum bpf_access_src src)
3784 {
3785         struct bpf_verifier_state *vstate = env->cur_state;
3786         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3787         struct bpf_reg_state *reg = &state->regs[regno];
3788         struct bpf_map *map = reg->map_ptr;
3789         int err;
3790
3791         err = check_mem_region_access(env, regno, off, size, map->value_size,
3792                                       zero_size_allowed);
3793         if (err)
3794                 return err;
3795
3796         if (map_value_has_spin_lock(map)) {
3797                 u32 lock = map->spin_lock_off;
3798
3799                 /* if any part of struct bpf_spin_lock can be touched by
3800                  * load/store reject this program.
3801                  * To check that [x1, x2) overlaps with [y1, y2)
3802                  * it is sufficient to check x1 < y2 && y1 < x2.
3803                  */
3804                 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3805                      lock < reg->umax_value + off + size) {
3806                         verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3807                         return -EACCES;
3808                 }
3809         }
3810         if (map_value_has_timer(map)) {
3811                 u32 t = map->timer_off;
3812
3813                 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3814                      t < reg->umax_value + off + size) {
3815                         verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3816                         return -EACCES;
3817                 }
3818         }
3819         if (map_value_has_kptrs(map)) {
3820                 struct bpf_map_value_off *tab = map->kptr_off_tab;
3821                 int i;
3822
3823                 for (i = 0; i < tab->nr_off; i++) {
3824                         u32 p = tab->off[i].offset;
3825
3826                         if (reg->smin_value + off < p + sizeof(u64) &&
3827                             p < reg->umax_value + off + size) {
3828                                 if (src != ACCESS_DIRECT) {
3829                                         verbose(env, "kptr cannot be accessed indirectly by helper\n");
3830                                         return -EACCES;
3831                                 }
3832                                 if (!tnum_is_const(reg->var_off)) {
3833                                         verbose(env, "kptr access cannot have variable offset\n");
3834                                         return -EACCES;
3835                                 }
3836                                 if (p != off + reg->var_off.value) {
3837                                         verbose(env, "kptr access misaligned expected=%u off=%llu\n",
3838                                                 p, off + reg->var_off.value);
3839                                         return -EACCES;
3840                                 }
3841                                 if (size != bpf_size_to_bytes(BPF_DW)) {
3842                                         verbose(env, "kptr access size must be BPF_DW\n");
3843                                         return -EACCES;
3844                                 }
3845                                 break;
3846                         }
3847                 }
3848         }
3849         return err;
3850 }
3851
3852 #define MAX_PACKET_OFF 0xffff
3853
3854 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3855                                        const struct bpf_call_arg_meta *meta,
3856                                        enum bpf_access_type t)
3857 {
3858         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3859
3860         switch (prog_type) {
3861         /* Program types only with direct read access go here! */
3862         case BPF_PROG_TYPE_LWT_IN:
3863         case BPF_PROG_TYPE_LWT_OUT:
3864         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3865         case BPF_PROG_TYPE_SK_REUSEPORT:
3866         case BPF_PROG_TYPE_FLOW_DISSECTOR:
3867         case BPF_PROG_TYPE_CGROUP_SKB:
3868                 if (t == BPF_WRITE)
3869                         return false;
3870                 fallthrough;
3871
3872         /* Program types with direct read + write access go here! */
3873         case BPF_PROG_TYPE_SCHED_CLS:
3874         case BPF_PROG_TYPE_SCHED_ACT:
3875         case BPF_PROG_TYPE_XDP:
3876         case BPF_PROG_TYPE_LWT_XMIT:
3877         case BPF_PROG_TYPE_SK_SKB:
3878         case BPF_PROG_TYPE_SK_MSG:
3879                 if (meta)
3880                         return meta->pkt_access;
3881
3882                 env->seen_direct_write = true;
3883                 return true;
3884
3885         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3886                 if (t == BPF_WRITE)
3887                         env->seen_direct_write = true;
3888
3889                 return true;
3890
3891         default:
3892                 return false;
3893         }
3894 }
3895
3896 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3897                                int size, bool zero_size_allowed)
3898 {
3899         struct bpf_reg_state *regs = cur_regs(env);
3900         struct bpf_reg_state *reg = &regs[regno];
3901         int err;
3902
3903         /* We may have added a variable offset to the packet pointer; but any
3904          * reg->range we have comes after that.  We are only checking the fixed
3905          * offset.
3906          */
3907
3908         /* We don't allow negative numbers, because we aren't tracking enough
3909          * detail to prove they're safe.
3910          */
3911         if (reg->smin_value < 0) {
3912                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3913                         regno);
3914                 return -EACCES;
3915         }
3916
3917         err = reg->range < 0 ? -EINVAL :
3918               __check_mem_access(env, regno, off, size, reg->range,
3919                                  zero_size_allowed);
3920         if (err) {
3921                 verbose(env, "R%d offset is outside of the packet\n", regno);
3922                 return err;
3923         }
3924
3925         /* __check_mem_access has made sure "off + size - 1" is within u16.
3926          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3927          * otherwise find_good_pkt_pointers would have refused to set range info
3928          * that __check_mem_access would have rejected this pkt access.
3929          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3930          */
3931         env->prog->aux->max_pkt_offset =
3932                 max_t(u32, env->prog->aux->max_pkt_offset,
3933                       off + reg->umax_value + size - 1);
3934
3935         return err;
3936 }
3937
3938 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
3939 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3940                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
3941                             struct btf **btf, u32 *btf_id)
3942 {
3943         struct bpf_insn_access_aux info = {
3944                 .reg_type = *reg_type,
3945                 .log = &env->log,
3946         };
3947
3948         if (env->ops->is_valid_access &&
3949             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3950                 /* A non zero info.ctx_field_size indicates that this field is a
3951                  * candidate for later verifier transformation to load the whole
3952                  * field and then apply a mask when accessed with a narrower
3953                  * access than actual ctx access size. A zero info.ctx_field_size
3954                  * will only allow for whole field access and rejects any other
3955                  * type of narrower access.
3956                  */
3957                 *reg_type = info.reg_type;
3958
3959                 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
3960                         *btf = info.btf;
3961                         *btf_id = info.btf_id;
3962                 } else {
3963                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3964                 }
3965                 /* remember the offset of last byte accessed in ctx */
3966                 if (env->prog->aux->max_ctx_offset < off + size)
3967                         env->prog->aux->max_ctx_offset = off + size;
3968                 return 0;
3969         }
3970
3971         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3972         return -EACCES;
3973 }
3974
3975 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3976                                   int size)
3977 {
3978         if (size < 0 || off < 0 ||
3979             (u64)off + size > sizeof(struct bpf_flow_keys)) {
3980                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3981                         off, size);
3982                 return -EACCES;
3983         }
3984         return 0;
3985 }
3986
3987 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3988                              u32 regno, int off, int size,
3989                              enum bpf_access_type t)
3990 {
3991         struct bpf_reg_state *regs = cur_regs(env);
3992         struct bpf_reg_state *reg = &regs[regno];
3993         struct bpf_insn_access_aux info = {};
3994         bool valid;
3995
3996         if (reg->smin_value < 0) {
3997                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3998                         regno);
3999                 return -EACCES;
4000         }
4001
4002         switch (reg->type) {
4003         case PTR_TO_SOCK_COMMON:
4004                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4005                 break;
4006         case PTR_TO_SOCKET:
4007                 valid = bpf_sock_is_valid_access(off, size, t, &info);
4008                 break;
4009         case PTR_TO_TCP_SOCK:
4010                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4011                 break;
4012         case PTR_TO_XDP_SOCK:
4013                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4014                 break;
4015         default:
4016                 valid = false;
4017         }
4018
4019
4020         if (valid) {
4021                 env->insn_aux_data[insn_idx].ctx_field_size =
4022                         info.ctx_field_size;
4023                 return 0;
4024         }
4025
4026         verbose(env, "R%d invalid %s access off=%d size=%d\n",
4027                 regno, reg_type_str(env, reg->type), off, size);
4028
4029         return -EACCES;
4030 }
4031
4032 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4033 {
4034         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4035 }
4036
4037 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4038 {
4039         const struct bpf_reg_state *reg = reg_state(env, regno);
4040
4041         return reg->type == PTR_TO_CTX;
4042 }
4043
4044 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4045 {
4046         const struct bpf_reg_state *reg = reg_state(env, regno);
4047
4048         return type_is_sk_pointer(reg->type);
4049 }
4050
4051 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4052 {
4053         const struct bpf_reg_state *reg = reg_state(env, regno);
4054
4055         return type_is_pkt_pointer(reg->type);
4056 }
4057
4058 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4059 {
4060         const struct bpf_reg_state *reg = reg_state(env, regno);
4061
4062         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4063         return reg->type == PTR_TO_FLOW_KEYS;
4064 }
4065
4066 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4067                                    const struct bpf_reg_state *reg,
4068                                    int off, int size, bool strict)
4069 {
4070         struct tnum reg_off;
4071         int ip_align;
4072
4073         /* Byte size accesses are always allowed. */
4074         if (!strict || size == 1)
4075                 return 0;
4076
4077         /* For platforms that do not have a Kconfig enabling
4078          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4079          * NET_IP_ALIGN is universally set to '2'.  And on platforms
4080          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4081          * to this code only in strict mode where we want to emulate
4082          * the NET_IP_ALIGN==2 checking.  Therefore use an
4083          * unconditional IP align value of '2'.
4084          */
4085         ip_align = 2;
4086
4087         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4088         if (!tnum_is_aligned(reg_off, size)) {
4089                 char tn_buf[48];
4090
4091                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4092                 verbose(env,
4093                         "misaligned packet access off %d+%s+%d+%d size %d\n",
4094                         ip_align, tn_buf, reg->off, off, size);
4095                 return -EACCES;
4096         }
4097
4098         return 0;
4099 }
4100
4101 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4102                                        const struct bpf_reg_state *reg,
4103                                        const char *pointer_desc,
4104                                        int off, int size, bool strict)
4105 {
4106         struct tnum reg_off;
4107
4108         /* Byte size accesses are always allowed. */
4109         if (!strict || size == 1)
4110                 return 0;
4111
4112         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4113         if (!tnum_is_aligned(reg_off, size)) {
4114                 char tn_buf[48];
4115
4116                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4117                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4118                         pointer_desc, tn_buf, reg->off, off, size);
4119                 return -EACCES;
4120         }
4121
4122         return 0;
4123 }
4124
4125 static int check_ptr_alignment(struct bpf_verifier_env *env,
4126                                const struct bpf_reg_state *reg, int off,
4127                                int size, bool strict_alignment_once)
4128 {
4129         bool strict = env->strict_alignment || strict_alignment_once;
4130         const char *pointer_desc = "";
4131
4132         switch (reg->type) {
4133         case PTR_TO_PACKET:
4134         case PTR_TO_PACKET_META:
4135                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4136                  * right in front, treat it the very same way.
4137                  */
4138                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
4139         case PTR_TO_FLOW_KEYS:
4140                 pointer_desc = "flow keys ";
4141                 break;
4142         case PTR_TO_MAP_KEY:
4143                 pointer_desc = "key ";
4144                 break;
4145         case PTR_TO_MAP_VALUE:
4146                 pointer_desc = "value ";
4147                 break;
4148         case PTR_TO_CTX:
4149                 pointer_desc = "context ";
4150                 break;
4151         case PTR_TO_STACK:
4152                 pointer_desc = "stack ";
4153                 /* The stack spill tracking logic in check_stack_write_fixed_off()
4154                  * and check_stack_read_fixed_off() relies on stack accesses being
4155                  * aligned.
4156                  */
4157                 strict = true;
4158                 break;
4159         case PTR_TO_SOCKET:
4160                 pointer_desc = "sock ";
4161                 break;
4162         case PTR_TO_SOCK_COMMON:
4163                 pointer_desc = "sock_common ";
4164                 break;
4165         case PTR_TO_TCP_SOCK:
4166                 pointer_desc = "tcp_sock ";
4167                 break;
4168         case PTR_TO_XDP_SOCK:
4169                 pointer_desc = "xdp_sock ";
4170                 break;
4171         default:
4172                 break;
4173         }
4174         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4175                                            strict);
4176 }
4177
4178 static int update_stack_depth(struct bpf_verifier_env *env,
4179                               const struct bpf_func_state *func,
4180                               int off)
4181 {
4182         u16 stack = env->subprog_info[func->subprogno].stack_depth;
4183
4184         if (stack >= -off)
4185                 return 0;
4186
4187         /* update known max for given subprogram */
4188         env->subprog_info[func->subprogno].stack_depth = -off;
4189         return 0;
4190 }
4191
4192 /* starting from main bpf function walk all instructions of the function
4193  * and recursively walk all callees that given function can call.
4194  * Ignore jump and exit insns.
4195  * Since recursion is prevented by check_cfg() this algorithm
4196  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4197  */
4198 static int check_max_stack_depth(struct bpf_verifier_env *env)
4199 {
4200         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
4201         struct bpf_subprog_info *subprog = env->subprog_info;
4202         struct bpf_insn *insn = env->prog->insnsi;
4203         bool tail_call_reachable = false;
4204         int ret_insn[MAX_CALL_FRAMES];
4205         int ret_prog[MAX_CALL_FRAMES];
4206         int j;
4207
4208 process_func:
4209         /* protect against potential stack overflow that might happen when
4210          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4211          * depth for such case down to 256 so that the worst case scenario
4212          * would result in 8k stack size (32 which is tailcall limit * 256 =
4213          * 8k).
4214          *
4215          * To get the idea what might happen, see an example:
4216          * func1 -> sub rsp, 128
4217          *  subfunc1 -> sub rsp, 256
4218          *  tailcall1 -> add rsp, 256
4219          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4220          *   subfunc2 -> sub rsp, 64
4221          *   subfunc22 -> sub rsp, 128
4222          *   tailcall2 -> add rsp, 128
4223          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4224          *
4225          * tailcall will unwind the current stack frame but it will not get rid
4226          * of caller's stack as shown on the example above.
4227          */
4228         if (idx && subprog[idx].has_tail_call && depth >= 256) {
4229                 verbose(env,
4230                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4231                         depth);
4232                 return -EACCES;
4233         }
4234         /* round up to 32-bytes, since this is granularity
4235          * of interpreter stack size
4236          */
4237         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4238         if (depth > MAX_BPF_STACK) {
4239                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
4240                         frame + 1, depth);
4241                 return -EACCES;
4242         }
4243 continue_func:
4244         subprog_end = subprog[idx + 1].start;
4245         for (; i < subprog_end; i++) {
4246                 int next_insn;
4247
4248                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4249                         continue;
4250                 /* remember insn and function to return to */
4251                 ret_insn[frame] = i + 1;
4252                 ret_prog[frame] = idx;
4253
4254                 /* find the callee */
4255                 next_insn = i + insn[i].imm + 1;
4256                 idx = find_subprog(env, next_insn);
4257                 if (idx < 0) {
4258                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4259                                   next_insn);
4260                         return -EFAULT;
4261                 }
4262                 if (subprog[idx].is_async_cb) {
4263                         if (subprog[idx].has_tail_call) {
4264                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4265                                 return -EFAULT;
4266                         }
4267                          /* async callbacks don't increase bpf prog stack size */
4268                         continue;
4269                 }
4270                 i = next_insn;
4271
4272                 if (subprog[idx].has_tail_call)
4273                         tail_call_reachable = true;
4274
4275                 frame++;
4276                 if (frame >= MAX_CALL_FRAMES) {
4277                         verbose(env, "the call stack of %d frames is too deep !\n",
4278                                 frame);
4279                         return -E2BIG;
4280                 }
4281                 goto process_func;
4282         }
4283         /* if tail call got detected across bpf2bpf calls then mark each of the
4284          * currently present subprog frames as tail call reachable subprogs;
4285          * this info will be utilized by JIT so that we will be preserving the
4286          * tail call counter throughout bpf2bpf calls combined with tailcalls
4287          */
4288         if (tail_call_reachable)
4289                 for (j = 0; j < frame; j++)
4290                         subprog[ret_prog[j]].tail_call_reachable = true;
4291         if (subprog[0].tail_call_reachable)
4292                 env->prog->aux->tail_call_reachable = true;
4293
4294         /* end of for() loop means the last insn of the 'subprog'
4295          * was reached. Doesn't matter whether it was JA or EXIT
4296          */
4297         if (frame == 0)
4298                 return 0;
4299         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4300         frame--;
4301         i = ret_insn[frame];
4302         idx = ret_prog[frame];
4303         goto continue_func;
4304 }
4305
4306 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
4307 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4308                                   const struct bpf_insn *insn, int idx)
4309 {
4310         int start = idx + insn->imm + 1, subprog;
4311
4312         subprog = find_subprog(env, start);
4313         if (subprog < 0) {
4314                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4315                           start);
4316                 return -EFAULT;
4317         }
4318         return env->subprog_info[subprog].stack_depth;
4319 }
4320 #endif
4321
4322 static int __check_buffer_access(struct bpf_verifier_env *env,
4323                                  const char *buf_info,
4324                                  const struct bpf_reg_state *reg,
4325                                  int regno, int off, int size)
4326 {
4327         if (off < 0) {
4328                 verbose(env,
4329                         "R%d invalid %s buffer access: off=%d, size=%d\n",
4330                         regno, buf_info, off, size);
4331                 return -EACCES;
4332         }
4333         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4334                 char tn_buf[48];
4335
4336                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4337                 verbose(env,
4338                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4339                         regno, off, tn_buf);
4340                 return -EACCES;
4341         }
4342
4343         return 0;
4344 }
4345
4346 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4347                                   const struct bpf_reg_state *reg,
4348                                   int regno, int off, int size)
4349 {
4350         int err;
4351
4352         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4353         if (err)
4354                 return err;
4355
4356         if (off + size > env->prog->aux->max_tp_access)
4357                 env->prog->aux->max_tp_access = off + size;
4358
4359         return 0;
4360 }
4361
4362 static int check_buffer_access(struct bpf_verifier_env *env,
4363                                const struct bpf_reg_state *reg,
4364                                int regno, int off, int size,
4365                                bool zero_size_allowed,
4366                                u32 *max_access)
4367 {
4368         const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4369         int err;
4370
4371         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4372         if (err)
4373                 return err;
4374
4375         if (off + size > *max_access)
4376                 *max_access = off + size;
4377
4378         return 0;
4379 }
4380
4381 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
4382 static void zext_32_to_64(struct bpf_reg_state *reg)
4383 {
4384         reg->var_off = tnum_subreg(reg->var_off);
4385         __reg_assign_32_into_64(reg);
4386 }
4387
4388 /* truncate register to smaller size (in bytes)
4389  * must be called with size < BPF_REG_SIZE
4390  */
4391 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4392 {
4393         u64 mask;
4394
4395         /* clear high bits in bit representation */
4396         reg->var_off = tnum_cast(reg->var_off, size);
4397
4398         /* fix arithmetic bounds */
4399         mask = ((u64)1 << (size * 8)) - 1;
4400         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4401                 reg->umin_value &= mask;
4402                 reg->umax_value &= mask;
4403         } else {
4404                 reg->umin_value = 0;
4405                 reg->umax_value = mask;
4406         }
4407         reg->smin_value = reg->umin_value;
4408         reg->smax_value = reg->umax_value;
4409
4410         /* If size is smaller than 32bit register the 32bit register
4411          * values are also truncated so we push 64-bit bounds into
4412          * 32-bit bounds. Above were truncated < 32-bits already.
4413          */
4414         if (size >= 4)
4415                 return;
4416         __reg_combine_64_into_32(reg);
4417 }
4418
4419 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4420 {
4421         /* A map is considered read-only if the following condition are true:
4422          *
4423          * 1) BPF program side cannot change any of the map content. The
4424          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4425          *    and was set at map creation time.
4426          * 2) The map value(s) have been initialized from user space by a
4427          *    loader and then "frozen", such that no new map update/delete
4428          *    operations from syscall side are possible for the rest of
4429          *    the map's lifetime from that point onwards.
4430          * 3) Any parallel/pending map update/delete operations from syscall
4431          *    side have been completed. Only after that point, it's safe to
4432          *    assume that map value(s) are immutable.
4433          */
4434         return (map->map_flags & BPF_F_RDONLY_PROG) &&
4435                READ_ONCE(map->frozen) &&
4436                !bpf_map_write_active(map);
4437 }
4438
4439 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4440 {
4441         void *ptr;
4442         u64 addr;
4443         int err;
4444
4445         err = map->ops->map_direct_value_addr(map, &addr, off);
4446         if (err)
4447                 return err;
4448         ptr = (void *)(long)addr + off;
4449
4450         switch (size) {
4451         case sizeof(u8):
4452                 *val = (u64)*(u8 *)ptr;
4453                 break;
4454         case sizeof(u16):
4455                 *val = (u64)*(u16 *)ptr;
4456                 break;
4457         case sizeof(u32):
4458                 *val = (u64)*(u32 *)ptr;
4459                 break;
4460         case sizeof(u64):
4461                 *val = *(u64 *)ptr;
4462                 break;
4463         default:
4464                 return -EINVAL;
4465         }
4466         return 0;
4467 }
4468
4469 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4470                                    struct bpf_reg_state *regs,
4471                                    int regno, int off, int size,
4472                                    enum bpf_access_type atype,
4473                                    int value_regno)
4474 {
4475         struct bpf_reg_state *reg = regs + regno;
4476         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4477         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4478         enum bpf_type_flag flag = 0;
4479         u32 btf_id;
4480         int ret;
4481
4482         if (off < 0) {
4483                 verbose(env,
4484                         "R%d is ptr_%s invalid negative access: off=%d\n",
4485                         regno, tname, off);
4486                 return -EACCES;
4487         }
4488         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4489                 char tn_buf[48];
4490
4491                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4492                 verbose(env,
4493                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4494                         regno, tname, off, tn_buf);
4495                 return -EACCES;
4496         }
4497
4498         if (reg->type & MEM_USER) {
4499                 verbose(env,
4500                         "R%d is ptr_%s access user memory: off=%d\n",
4501                         regno, tname, off);
4502                 return -EACCES;
4503         }
4504
4505         if (reg->type & MEM_PERCPU) {
4506                 verbose(env,
4507                         "R%d is ptr_%s access percpu memory: off=%d\n",
4508                         regno, tname, off);
4509                 return -EACCES;
4510         }
4511
4512         if (env->ops->btf_struct_access) {
4513                 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4514                                                   off, size, atype, &btf_id, &flag);
4515         } else {
4516                 if (atype != BPF_READ) {
4517                         verbose(env, "only read is supported\n");
4518                         return -EACCES;
4519                 }
4520
4521                 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4522                                         atype, &btf_id, &flag);
4523         }
4524
4525         if (ret < 0)
4526                 return ret;
4527
4528         /* If this is an untrusted pointer, all pointers formed by walking it
4529          * also inherit the untrusted flag.
4530          */
4531         if (type_flag(reg->type) & PTR_UNTRUSTED)
4532                 flag |= PTR_UNTRUSTED;
4533
4534         if (atype == BPF_READ && value_regno >= 0)
4535                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4536
4537         return 0;
4538 }
4539
4540 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4541                                    struct bpf_reg_state *regs,
4542                                    int regno, int off, int size,
4543                                    enum bpf_access_type atype,
4544                                    int value_regno)
4545 {
4546         struct bpf_reg_state *reg = regs + regno;
4547         struct bpf_map *map = reg->map_ptr;
4548         enum bpf_type_flag flag = 0;
4549         const struct btf_type *t;
4550         const char *tname;
4551         u32 btf_id;
4552         int ret;
4553
4554         if (!btf_vmlinux) {
4555                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4556                 return -ENOTSUPP;
4557         }
4558
4559         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4560                 verbose(env, "map_ptr access not supported for map type %d\n",
4561                         map->map_type);
4562                 return -ENOTSUPP;
4563         }
4564
4565         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4566         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4567
4568         if (!env->allow_ptr_to_map_access) {
4569                 verbose(env,
4570                         "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4571                         tname);
4572                 return -EPERM;
4573         }
4574
4575         if (off < 0) {
4576                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4577                         regno, tname, off);
4578                 return -EACCES;
4579         }
4580
4581         if (atype != BPF_READ) {
4582                 verbose(env, "only read from %s is supported\n", tname);
4583                 return -EACCES;
4584         }
4585
4586         ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag);
4587         if (ret < 0)
4588                 return ret;
4589
4590         if (value_regno >= 0)
4591                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4592
4593         return 0;
4594 }
4595
4596 /* Check that the stack access at the given offset is within bounds. The
4597  * maximum valid offset is -1.
4598  *
4599  * The minimum valid offset is -MAX_BPF_STACK for writes, and
4600  * -state->allocated_stack for reads.
4601  */
4602 static int check_stack_slot_within_bounds(int off,
4603                                           struct bpf_func_state *state,
4604                                           enum bpf_access_type t)
4605 {
4606         int min_valid_off;
4607
4608         if (t == BPF_WRITE)
4609                 min_valid_off = -MAX_BPF_STACK;
4610         else
4611                 min_valid_off = -state->allocated_stack;
4612
4613         if (off < min_valid_off || off > -1)
4614                 return -EACCES;
4615         return 0;
4616 }
4617
4618 /* Check that the stack access at 'regno + off' falls within the maximum stack
4619  * bounds.
4620  *
4621  * 'off' includes `regno->offset`, but not its dynamic part (if any).
4622  */
4623 static int check_stack_access_within_bounds(
4624                 struct bpf_verifier_env *env,
4625                 int regno, int off, int access_size,
4626                 enum bpf_access_src src, enum bpf_access_type type)
4627 {
4628         struct bpf_reg_state *regs = cur_regs(env);
4629         struct bpf_reg_state *reg = regs + regno;
4630         struct bpf_func_state *state = func(env, reg);
4631         int min_off, max_off;
4632         int err;
4633         char *err_extra;
4634
4635         if (src == ACCESS_HELPER)
4636                 /* We don't know if helpers are reading or writing (or both). */
4637                 err_extra = " indirect access to";
4638         else if (type == BPF_READ)
4639                 err_extra = " read from";
4640         else
4641                 err_extra = " write to";
4642
4643         if (tnum_is_const(reg->var_off)) {
4644                 min_off = reg->var_off.value + off;
4645                 if (access_size > 0)
4646                         max_off = min_off + access_size - 1;
4647                 else
4648                         max_off = min_off;
4649         } else {
4650                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4651                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
4652                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4653                                 err_extra, regno);
4654                         return -EACCES;
4655                 }
4656                 min_off = reg->smin_value + off;
4657                 if (access_size > 0)
4658                         max_off = reg->smax_value + off + access_size - 1;
4659                 else
4660                         max_off = min_off;
4661         }
4662
4663         err = check_stack_slot_within_bounds(min_off, state, type);
4664         if (!err)
4665                 err = check_stack_slot_within_bounds(max_off, state, type);
4666
4667         if (err) {
4668                 if (tnum_is_const(reg->var_off)) {
4669                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4670                                 err_extra, regno, off, access_size);
4671                 } else {
4672                         char tn_buf[48];
4673
4674                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4675                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4676                                 err_extra, regno, tn_buf, access_size);
4677                 }
4678         }
4679         return err;
4680 }
4681
4682 /* check whether memory at (regno + off) is accessible for t = (read | write)
4683  * if t==write, value_regno is a register which value is stored into memory
4684  * if t==read, value_regno is a register which will receive the value from memory
4685  * if t==write && value_regno==-1, some unknown value is stored into memory
4686  * if t==read && value_regno==-1, don't care what we read from memory
4687  */
4688 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4689                             int off, int bpf_size, enum bpf_access_type t,
4690                             int value_regno, bool strict_alignment_once)
4691 {
4692         struct bpf_reg_state *regs = cur_regs(env);
4693         struct bpf_reg_state *reg = regs + regno;
4694         struct bpf_func_state *state;
4695         int size, err = 0;
4696
4697         size = bpf_size_to_bytes(bpf_size);
4698         if (size < 0)
4699                 return size;
4700
4701         /* alignment checks will add in reg->off themselves */
4702         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4703         if (err)
4704                 return err;
4705
4706         /* for access checks, reg->off is just part of off */
4707         off += reg->off;
4708
4709         if (reg->type == PTR_TO_MAP_KEY) {
4710                 if (t == BPF_WRITE) {
4711                         verbose(env, "write to change key R%d not allowed\n", regno);
4712                         return -EACCES;
4713                 }
4714
4715                 err = check_mem_region_access(env, regno, off, size,
4716                                               reg->map_ptr->key_size, false);
4717                 if (err)
4718                         return err;
4719                 if (value_regno >= 0)
4720                         mark_reg_unknown(env, regs, value_regno);
4721         } else if (reg->type == PTR_TO_MAP_VALUE) {
4722                 struct bpf_map_value_off_desc *kptr_off_desc = NULL;
4723
4724                 if (t == BPF_WRITE && value_regno >= 0 &&
4725                     is_pointer_value(env, value_regno)) {
4726                         verbose(env, "R%d leaks addr into map\n", value_regno);
4727                         return -EACCES;
4728                 }
4729                 err = check_map_access_type(env, regno, off, size, t);
4730                 if (err)
4731                         return err;
4732                 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
4733                 if (err)
4734                         return err;
4735                 if (tnum_is_const(reg->var_off))
4736                         kptr_off_desc = bpf_map_kptr_off_contains(reg->map_ptr,
4737                                                                   off + reg->var_off.value);
4738                 if (kptr_off_desc) {
4739                         err = check_map_kptr_access(env, regno, value_regno, insn_idx,
4740                                                     kptr_off_desc);
4741                 } else if (t == BPF_READ && value_regno >= 0) {
4742                         struct bpf_map *map = reg->map_ptr;
4743
4744                         /* if map is read-only, track its contents as scalars */
4745                         if (tnum_is_const(reg->var_off) &&
4746                             bpf_map_is_rdonly(map) &&
4747                             map->ops->map_direct_value_addr) {
4748                                 int map_off = off + reg->var_off.value;
4749                                 u64 val = 0;
4750
4751                                 err = bpf_map_direct_read(map, map_off, size,
4752                                                           &val);
4753                                 if (err)
4754                                         return err;
4755
4756                                 regs[value_regno].type = SCALAR_VALUE;
4757                                 __mark_reg_known(&regs[value_regno], val);
4758                         } else {
4759                                 mark_reg_unknown(env, regs, value_regno);
4760                         }
4761                 }
4762         } else if (base_type(reg->type) == PTR_TO_MEM) {
4763                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4764
4765                 if (type_may_be_null(reg->type)) {
4766                         verbose(env, "R%d invalid mem access '%s'\n", regno,
4767                                 reg_type_str(env, reg->type));
4768                         return -EACCES;
4769                 }
4770
4771                 if (t == BPF_WRITE && rdonly_mem) {
4772                         verbose(env, "R%d cannot write into %s\n",
4773                                 regno, reg_type_str(env, reg->type));
4774                         return -EACCES;
4775                 }
4776
4777                 if (t == BPF_WRITE && value_regno >= 0 &&
4778                     is_pointer_value(env, value_regno)) {
4779                         verbose(env, "R%d leaks addr into mem\n", value_regno);
4780                         return -EACCES;
4781                 }
4782
4783                 err = check_mem_region_access(env, regno, off, size,
4784                                               reg->mem_size, false);
4785                 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
4786                         mark_reg_unknown(env, regs, value_regno);
4787         } else if (reg->type == PTR_TO_CTX) {
4788                 enum bpf_reg_type reg_type = SCALAR_VALUE;
4789                 struct btf *btf = NULL;
4790                 u32 btf_id = 0;
4791
4792                 if (t == BPF_WRITE && value_regno >= 0 &&
4793                     is_pointer_value(env, value_regno)) {
4794                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
4795                         return -EACCES;
4796                 }
4797
4798                 err = check_ptr_off_reg(env, reg, regno);
4799                 if (err < 0)
4800                         return err;
4801
4802                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
4803                                        &btf_id);
4804                 if (err)
4805                         verbose_linfo(env, insn_idx, "; ");
4806                 if (!err && t == BPF_READ && value_regno >= 0) {
4807                         /* ctx access returns either a scalar, or a
4808                          * PTR_TO_PACKET[_META,_END]. In the latter
4809                          * case, we know the offset is zero.
4810                          */
4811                         if (reg_type == SCALAR_VALUE) {
4812                                 mark_reg_unknown(env, regs, value_regno);
4813                         } else {
4814                                 mark_reg_known_zero(env, regs,
4815                                                     value_regno);
4816                                 if (type_may_be_null(reg_type))
4817                                         regs[value_regno].id = ++env->id_gen;
4818                                 /* A load of ctx field could have different
4819                                  * actual load size with the one encoded in the
4820                                  * insn. When the dst is PTR, it is for sure not
4821                                  * a sub-register.
4822                                  */
4823                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4824                                 if (base_type(reg_type) == PTR_TO_BTF_ID) {
4825                                         regs[value_regno].btf = btf;
4826                                         regs[value_regno].btf_id = btf_id;
4827                                 }
4828                         }
4829                         regs[value_regno].type = reg_type;
4830                 }
4831
4832         } else if (reg->type == PTR_TO_STACK) {
4833                 /* Basic bounds checks. */
4834                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4835                 if (err)
4836                         return err;
4837
4838                 state = func(env, reg);
4839                 err = update_stack_depth(env, state, off);
4840                 if (err)
4841                         return err;
4842
4843                 if (t == BPF_READ)
4844                         err = check_stack_read(env, regno, off, size,
4845                                                value_regno);
4846                 else
4847                         err = check_stack_write(env, regno, off, size,
4848                                                 value_regno, insn_idx);
4849         } else if (reg_is_pkt_pointer(reg)) {
4850                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4851                         verbose(env, "cannot write into packet\n");
4852                         return -EACCES;
4853                 }
4854                 if (t == BPF_WRITE && value_regno >= 0 &&
4855                     is_pointer_value(env, value_regno)) {
4856                         verbose(env, "R%d leaks addr into packet\n",
4857                                 value_regno);
4858                         return -EACCES;
4859                 }
4860                 err = check_packet_access(env, regno, off, size, false);
4861                 if (!err && t == BPF_READ && value_regno >= 0)
4862                         mark_reg_unknown(env, regs, value_regno);
4863         } else if (reg->type == PTR_TO_FLOW_KEYS) {
4864                 if (t == BPF_WRITE && value_regno >= 0 &&
4865                     is_pointer_value(env, value_regno)) {
4866                         verbose(env, "R%d leaks addr into flow keys\n",
4867                                 value_regno);
4868                         return -EACCES;
4869                 }
4870
4871                 err = check_flow_keys_access(env, off, size);
4872                 if (!err && t == BPF_READ && value_regno >= 0)
4873                         mark_reg_unknown(env, regs, value_regno);
4874         } else if (type_is_sk_pointer(reg->type)) {
4875                 if (t == BPF_WRITE) {
4876                         verbose(env, "R%d cannot write into %s\n",
4877                                 regno, reg_type_str(env, reg->type));
4878                         return -EACCES;
4879                 }
4880                 err = check_sock_access(env, insn_idx, regno, off, size, t);
4881                 if (!err && value_regno >= 0)
4882                         mark_reg_unknown(env, regs, value_regno);
4883         } else if (reg->type == PTR_TO_TP_BUFFER) {
4884                 err = check_tp_buffer_access(env, reg, regno, off, size);
4885                 if (!err && t == BPF_READ && value_regno >= 0)
4886                         mark_reg_unknown(env, regs, value_regno);
4887         } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
4888                    !type_may_be_null(reg->type)) {
4889                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4890                                               value_regno);
4891         } else if (reg->type == CONST_PTR_TO_MAP) {
4892                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4893                                               value_regno);
4894         } else if (base_type(reg->type) == PTR_TO_BUF) {
4895                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
4896                 u32 *max_access;
4897
4898                 if (rdonly_mem) {
4899                         if (t == BPF_WRITE) {
4900                                 verbose(env, "R%d cannot write into %s\n",
4901                                         regno, reg_type_str(env, reg->type));
4902                                 return -EACCES;
4903                         }
4904                         max_access = &env->prog->aux->max_rdonly_access;
4905                 } else {
4906                         max_access = &env->prog->aux->max_rdwr_access;
4907                 }
4908
4909                 err = check_buffer_access(env, reg, regno, off, size, false,
4910                                           max_access);
4911
4912                 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
4913                         mark_reg_unknown(env, regs, value_regno);
4914         } else {
4915                 verbose(env, "R%d invalid mem access '%s'\n", regno,
4916                         reg_type_str(env, reg->type));
4917                 return -EACCES;
4918         }
4919
4920         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4921             regs[value_regno].type == SCALAR_VALUE) {
4922                 /* b/h/w load zero-extends, mark upper bits as known 0 */
4923                 coerce_reg_to_size(&regs[value_regno], size);
4924         }
4925         return err;
4926 }
4927
4928 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4929 {
4930         int load_reg;
4931         int err;
4932
4933         switch (insn->imm) {
4934         case BPF_ADD:
4935         case BPF_ADD | BPF_FETCH:
4936         case BPF_AND:
4937         case BPF_AND | BPF_FETCH:
4938         case BPF_OR:
4939         case BPF_OR | BPF_FETCH:
4940         case BPF_XOR:
4941         case BPF_XOR | BPF_FETCH:
4942         case BPF_XCHG:
4943         case BPF_CMPXCHG:
4944                 break;
4945         default:
4946                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4947                 return -EINVAL;
4948         }
4949
4950         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4951                 verbose(env, "invalid atomic operand size\n");
4952                 return -EINVAL;
4953         }
4954
4955         /* check src1 operand */
4956         err = check_reg_arg(env, insn->src_reg, SRC_OP);
4957         if (err)
4958                 return err;
4959
4960         /* check src2 operand */
4961         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4962         if (err)
4963                 return err;
4964
4965         if (insn->imm == BPF_CMPXCHG) {
4966                 /* Check comparison of R0 with memory location */
4967                 const u32 aux_reg = BPF_REG_0;
4968
4969                 err = check_reg_arg(env, aux_reg, SRC_OP);
4970                 if (err)
4971                         return err;
4972
4973                 if (is_pointer_value(env, aux_reg)) {
4974                         verbose(env, "R%d leaks addr into mem\n", aux_reg);
4975                         return -EACCES;
4976                 }
4977         }
4978
4979         if (is_pointer_value(env, insn->src_reg)) {
4980                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4981                 return -EACCES;
4982         }
4983
4984         if (is_ctx_reg(env, insn->dst_reg) ||
4985             is_pkt_reg(env, insn->dst_reg) ||
4986             is_flow_key_reg(env, insn->dst_reg) ||
4987             is_sk_reg(env, insn->dst_reg)) {
4988                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4989                         insn->dst_reg,
4990                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
4991                 return -EACCES;
4992         }
4993
4994         if (insn->imm & BPF_FETCH) {
4995                 if (insn->imm == BPF_CMPXCHG)
4996                         load_reg = BPF_REG_0;
4997                 else
4998                         load_reg = insn->src_reg;
4999
5000                 /* check and record load of old value */
5001                 err = check_reg_arg(env, load_reg, DST_OP);
5002                 if (err)
5003                         return err;
5004         } else {
5005                 /* This instruction accesses a memory location but doesn't
5006                  * actually load it into a register.
5007                  */
5008                 load_reg = -1;
5009         }
5010
5011         /* Check whether we can read the memory, with second call for fetch
5012          * case to simulate the register fill.
5013          */
5014         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5015                                BPF_SIZE(insn->code), BPF_READ, -1, true);
5016         if (!err && load_reg >= 0)
5017                 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5018                                        BPF_SIZE(insn->code), BPF_READ, load_reg,
5019                                        true);
5020         if (err)
5021                 return err;
5022
5023         /* Check whether we can write into the same memory. */
5024         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5025                                BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5026         if (err)
5027                 return err;
5028
5029         return 0;
5030 }
5031
5032 /* When register 'regno' is used to read the stack (either directly or through
5033  * a helper function) make sure that it's within stack boundary and, depending
5034  * on the access type, that all elements of the stack are initialized.
5035  *
5036  * 'off' includes 'regno->off', but not its dynamic part (if any).
5037  *
5038  * All registers that have been spilled on the stack in the slots within the
5039  * read offsets are marked as read.
5040  */
5041 static int check_stack_range_initialized(
5042                 struct bpf_verifier_env *env, int regno, int off,
5043                 int access_size, bool zero_size_allowed,
5044                 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5045 {
5046         struct bpf_reg_state *reg = reg_state(env, regno);
5047         struct bpf_func_state *state = func(env, reg);
5048         int err, min_off, max_off, i, j, slot, spi;
5049         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5050         enum bpf_access_type bounds_check_type;
5051         /* Some accesses can write anything into the stack, others are
5052          * read-only.
5053          */
5054         bool clobber = false;
5055
5056         if (access_size == 0 && !zero_size_allowed) {
5057                 verbose(env, "invalid zero-sized read\n");
5058                 return -EACCES;
5059         }
5060
5061         if (type == ACCESS_HELPER) {
5062                 /* The bounds checks for writes are more permissive than for
5063                  * reads. However, if raw_mode is not set, we'll do extra
5064                  * checks below.
5065                  */
5066                 bounds_check_type = BPF_WRITE;
5067                 clobber = true;
5068         } else {
5069                 bounds_check_type = BPF_READ;
5070         }
5071         err = check_stack_access_within_bounds(env, regno, off, access_size,
5072                                                type, bounds_check_type);
5073         if (err)
5074                 return err;
5075
5076
5077         if (tnum_is_const(reg->var_off)) {
5078                 min_off = max_off = reg->var_off.value + off;
5079         } else {
5080                 /* Variable offset is prohibited for unprivileged mode for
5081                  * simplicity since it requires corresponding support in
5082                  * Spectre masking for stack ALU.
5083                  * See also retrieve_ptr_limit().
5084                  */
5085                 if (!env->bypass_spec_v1) {
5086                         char tn_buf[48];
5087
5088                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5089                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5090                                 regno, err_extra, tn_buf);
5091                         return -EACCES;
5092                 }
5093                 /* Only initialized buffer on stack is allowed to be accessed
5094                  * with variable offset. With uninitialized buffer it's hard to
5095                  * guarantee that whole memory is marked as initialized on
5096                  * helper return since specific bounds are unknown what may
5097                  * cause uninitialized stack leaking.
5098                  */
5099                 if (meta && meta->raw_mode)
5100                         meta = NULL;
5101
5102                 min_off = reg->smin_value + off;
5103                 max_off = reg->smax_value + off;
5104         }
5105
5106         if (meta && meta->raw_mode) {
5107                 meta->access_size = access_size;
5108                 meta->regno = regno;
5109                 return 0;
5110         }
5111
5112         for (i = min_off; i < max_off + access_size; i++) {
5113                 u8 *stype;
5114
5115                 slot = -i - 1;
5116                 spi = slot / BPF_REG_SIZE;
5117                 if (state->allocated_stack <= slot)
5118                         goto err;
5119                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5120                 if (*stype == STACK_MISC)
5121                         goto mark;
5122                 if (*stype == STACK_ZERO) {
5123                         if (clobber) {
5124                                 /* helper can write anything into the stack */
5125                                 *stype = STACK_MISC;
5126                         }
5127                         goto mark;
5128                 }
5129
5130                 if (is_spilled_reg(&state->stack[spi]) &&
5131                     base_type(state->stack[spi].spilled_ptr.type) == PTR_TO_BTF_ID)
5132                         goto mark;
5133
5134                 if (is_spilled_reg(&state->stack[spi]) &&
5135                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5136                      env->allow_ptr_leaks)) {
5137                         if (clobber) {
5138                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5139                                 for (j = 0; j < BPF_REG_SIZE; j++)
5140                                         scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5141                         }
5142                         goto mark;
5143                 }
5144
5145 err:
5146                 if (tnum_is_const(reg->var_off)) {
5147                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5148                                 err_extra, regno, min_off, i - min_off, access_size);
5149                 } else {
5150                         char tn_buf[48];
5151
5152                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5153                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5154                                 err_extra, regno, tn_buf, i - min_off, access_size);
5155                 }
5156                 return -EACCES;
5157 mark:
5158                 /* reading any byte out of 8-byte 'spill_slot' will cause
5159                  * the whole slot to be marked as 'read'
5160                  */
5161                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5162                               state->stack[spi].spilled_ptr.parent,
5163                               REG_LIVE_READ64);
5164         }
5165         return update_stack_depth(env, state, min_off);
5166 }
5167
5168 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5169                                    int access_size, bool zero_size_allowed,
5170                                    struct bpf_call_arg_meta *meta)
5171 {
5172         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5173         u32 *max_access;
5174
5175         switch (base_type(reg->type)) {
5176         case PTR_TO_PACKET:
5177         case PTR_TO_PACKET_META:
5178                 return check_packet_access(env, regno, reg->off, access_size,
5179                                            zero_size_allowed);
5180         case PTR_TO_MAP_KEY:
5181                 if (meta && meta->raw_mode) {
5182                         verbose(env, "R%d cannot write into %s\n", regno,
5183                                 reg_type_str(env, reg->type));
5184                         return -EACCES;
5185                 }
5186                 return check_mem_region_access(env, regno, reg->off, access_size,
5187                                                reg->map_ptr->key_size, false);
5188         case PTR_TO_MAP_VALUE:
5189                 if (check_map_access_type(env, regno, reg->off, access_size,
5190                                           meta && meta->raw_mode ? BPF_WRITE :
5191                                           BPF_READ))
5192                         return -EACCES;
5193                 return check_map_access(env, regno, reg->off, access_size,
5194                                         zero_size_allowed, ACCESS_HELPER);
5195         case PTR_TO_MEM:
5196                 if (type_is_rdonly_mem(reg->type)) {
5197                         if (meta && meta->raw_mode) {
5198                                 verbose(env, "R%d cannot write into %s\n", regno,
5199                                         reg_type_str(env, reg->type));
5200                                 return -EACCES;
5201                         }
5202                 }
5203                 return check_mem_region_access(env, regno, reg->off,
5204                                                access_size, reg->mem_size,
5205                                                zero_size_allowed);
5206         case PTR_TO_BUF:
5207                 if (type_is_rdonly_mem(reg->type)) {
5208                         if (meta && meta->raw_mode) {
5209                                 verbose(env, "R%d cannot write into %s\n", regno,
5210                                         reg_type_str(env, reg->type));
5211                                 return -EACCES;
5212                         }
5213
5214                         max_access = &env->prog->aux->max_rdonly_access;
5215                 } else {
5216                         max_access = &env->prog->aux->max_rdwr_access;
5217                 }
5218                 return check_buffer_access(env, reg, regno, reg->off,
5219                                            access_size, zero_size_allowed,
5220                                            max_access);
5221         case PTR_TO_STACK:
5222                 return check_stack_range_initialized(
5223                                 env,
5224                                 regno, reg->off, access_size,
5225                                 zero_size_allowed, ACCESS_HELPER, meta);
5226         default: /* scalar_value or invalid ptr */
5227                 /* Allow zero-byte read from NULL, regardless of pointer type */
5228                 if (zero_size_allowed && access_size == 0 &&
5229                     register_is_null(reg))
5230                         return 0;
5231
5232                 verbose(env, "R%d type=%s ", regno,
5233                         reg_type_str(env, reg->type));
5234                 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5235                 return -EACCES;
5236         }
5237 }
5238
5239 static int check_mem_size_reg(struct bpf_verifier_env *env,
5240                               struct bpf_reg_state *reg, u32 regno,
5241                               bool zero_size_allowed,
5242                               struct bpf_call_arg_meta *meta)
5243 {
5244         int err;
5245
5246         /* This is used to refine r0 return value bounds for helpers
5247          * that enforce this value as an upper bound on return values.
5248          * See do_refine_retval_range() for helpers that can refine
5249          * the return value. C type of helper is u32 so we pull register
5250          * bound from umax_value however, if negative verifier errors
5251          * out. Only upper bounds can be learned because retval is an
5252          * int type and negative retvals are allowed.
5253          */
5254         meta->msize_max_value = reg->umax_value;
5255
5256         /* The register is SCALAR_VALUE; the access check
5257          * happens using its boundaries.
5258          */
5259         if (!tnum_is_const(reg->var_off))
5260                 /* For unprivileged variable accesses, disable raw
5261                  * mode so that the program is required to
5262                  * initialize all the memory that the helper could
5263                  * just partially fill up.
5264                  */
5265                 meta = NULL;
5266
5267         if (reg->smin_value < 0) {
5268                 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5269                         regno);
5270                 return -EACCES;
5271         }
5272
5273         if (reg->umin_value == 0) {
5274                 err = check_helper_mem_access(env, regno - 1, 0,
5275                                               zero_size_allowed,
5276                                               meta);
5277                 if (err)
5278                         return err;
5279         }
5280
5281         if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5282                 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5283                         regno);
5284                 return -EACCES;
5285         }
5286         err = check_helper_mem_access(env, regno - 1,
5287                                       reg->umax_value,
5288                                       zero_size_allowed, meta);
5289         if (!err)
5290                 err = mark_chain_precision(env, regno);
5291         return err;
5292 }
5293
5294 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5295                    u32 regno, u32 mem_size)
5296 {
5297         bool may_be_null = type_may_be_null(reg->type);
5298         struct bpf_reg_state saved_reg;
5299         struct bpf_call_arg_meta meta;
5300         int err;
5301
5302         if (register_is_null(reg))
5303                 return 0;
5304
5305         memset(&meta, 0, sizeof(meta));
5306         /* Assuming that the register contains a value check if the memory
5307          * access is safe. Temporarily save and restore the register's state as
5308          * the conversion shouldn't be visible to a caller.
5309          */
5310         if (may_be_null) {
5311                 saved_reg = *reg;
5312                 mark_ptr_not_null_reg(reg);
5313         }
5314
5315         err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5316         /* Check access for BPF_WRITE */
5317         meta.raw_mode = true;
5318         err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5319
5320         if (may_be_null)
5321                 *reg = saved_reg;
5322
5323         return err;
5324 }
5325
5326 int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5327                              u32 regno)
5328 {
5329         struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5330         bool may_be_null = type_may_be_null(mem_reg->type);
5331         struct bpf_reg_state saved_reg;
5332         struct bpf_call_arg_meta meta;
5333         int err;
5334
5335         WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5336
5337         memset(&meta, 0, sizeof(meta));
5338
5339         if (may_be_null) {
5340                 saved_reg = *mem_reg;
5341                 mark_ptr_not_null_reg(mem_reg);
5342         }
5343
5344         err = check_mem_size_reg(env, reg, regno, true, &meta);
5345         /* Check access for BPF_WRITE */
5346         meta.raw_mode = true;
5347         err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5348
5349         if (may_be_null)
5350                 *mem_reg = saved_reg;
5351         return err;
5352 }
5353
5354 /* Implementation details:
5355  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
5356  * Two bpf_map_lookups (even with the same key) will have different reg->id.
5357  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
5358  * value_or_null->value transition, since the verifier only cares about
5359  * the range of access to valid map value pointer and doesn't care about actual
5360  * address of the map element.
5361  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5362  * reg->id > 0 after value_or_null->value transition. By doing so
5363  * two bpf_map_lookups will be considered two different pointers that
5364  * point to different bpf_spin_locks.
5365  * The verifier allows taking only one bpf_spin_lock at a time to avoid
5366  * dead-locks.
5367  * Since only one bpf_spin_lock is allowed the checks are simpler than
5368  * reg_is_refcounted() logic. The verifier needs to remember only
5369  * one spin_lock instead of array of acquired_refs.
5370  * cur_state->active_spin_lock remembers which map value element got locked
5371  * and clears it after bpf_spin_unlock.
5372  */
5373 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5374                              bool is_lock)
5375 {
5376         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5377         struct bpf_verifier_state *cur = env->cur_state;
5378         bool is_const = tnum_is_const(reg->var_off);
5379         struct bpf_map *map = reg->map_ptr;
5380         u64 val = reg->var_off.value;
5381
5382         if (!is_const) {
5383                 verbose(env,
5384                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5385                         regno);
5386                 return -EINVAL;
5387         }
5388         if (!map->btf) {
5389                 verbose(env,
5390                         "map '%s' has to have BTF in order to use bpf_spin_lock\n",
5391                         map->name);
5392                 return -EINVAL;
5393         }
5394         if (!map_value_has_spin_lock(map)) {
5395                 if (map->spin_lock_off == -E2BIG)
5396                         verbose(env,
5397                                 "map '%s' has more than one 'struct bpf_spin_lock'\n",
5398                                 map->name);
5399                 else if (map->spin_lock_off == -ENOENT)
5400                         verbose(env,
5401                                 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
5402                                 map->name);
5403                 else
5404                         verbose(env,
5405                                 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
5406                                 map->name);
5407                 return -EINVAL;
5408         }
5409         if (map->spin_lock_off != val + reg->off) {
5410                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
5411                         val + reg->off);
5412                 return -EINVAL;
5413         }
5414         if (is_lock) {
5415                 if (cur->active_spin_lock) {
5416                         verbose(env,
5417                                 "Locking two bpf_spin_locks are not allowed\n");
5418                         return -EINVAL;
5419                 }
5420                 cur->active_spin_lock = reg->id;
5421         } else {
5422                 if (!cur->active_spin_lock) {
5423                         verbose(env, "bpf_spin_unlock without taking a lock\n");
5424                         return -EINVAL;
5425                 }
5426                 if (cur->active_spin_lock != reg->id) {
5427                         verbose(env, "bpf_spin_unlock of different lock\n");
5428                         return -EINVAL;
5429                 }
5430                 cur->active_spin_lock = 0;
5431         }
5432         return 0;
5433 }
5434
5435 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5436                               struct bpf_call_arg_meta *meta)
5437 {
5438         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5439         bool is_const = tnum_is_const(reg->var_off);
5440         struct bpf_map *map = reg->map_ptr;
5441         u64 val = reg->var_off.value;
5442
5443         if (!is_const) {
5444                 verbose(env,
5445                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5446                         regno);
5447                 return -EINVAL;
5448         }
5449         if (!map->btf) {
5450                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5451                         map->name);
5452                 return -EINVAL;
5453         }
5454         if (!map_value_has_timer(map)) {
5455                 if (map->timer_off == -E2BIG)
5456                         verbose(env,
5457                                 "map '%s' has more than one 'struct bpf_timer'\n",
5458                                 map->name);
5459                 else if (map->timer_off == -ENOENT)
5460                         verbose(env,
5461                                 "map '%s' doesn't have 'struct bpf_timer'\n",
5462                                 map->name);
5463                 else
5464                         verbose(env,
5465                                 "map '%s' is not a struct type or bpf_timer is mangled\n",
5466                                 map->name);
5467                 return -EINVAL;
5468         }
5469         if (map->timer_off != val + reg->off) {
5470                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5471                         val + reg->off, map->timer_off);
5472                 return -EINVAL;
5473         }
5474         if (meta->map_ptr) {
5475                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5476                 return -EFAULT;
5477         }
5478         meta->map_uid = reg->map_uid;
5479         meta->map_ptr = map;
5480         return 0;
5481 }
5482
5483 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5484                              struct bpf_call_arg_meta *meta)
5485 {
5486         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5487         struct bpf_map_value_off_desc *off_desc;
5488         struct bpf_map *map_ptr = reg->map_ptr;
5489         u32 kptr_off;
5490         int ret;
5491
5492         if (!tnum_is_const(reg->var_off)) {
5493                 verbose(env,
5494                         "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5495                         regno);
5496                 return -EINVAL;
5497         }
5498         if (!map_ptr->btf) {
5499                 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5500                         map_ptr->name);
5501                 return -EINVAL;
5502         }
5503         if (!map_value_has_kptrs(map_ptr)) {
5504                 ret = PTR_ERR_OR_ZERO(map_ptr->kptr_off_tab);
5505                 if (ret == -E2BIG)
5506                         verbose(env, "map '%s' has more than %d kptr\n", map_ptr->name,
5507                                 BPF_MAP_VALUE_OFF_MAX);
5508                 else if (ret == -EEXIST)
5509                         verbose(env, "map '%s' has repeating kptr BTF tags\n", map_ptr->name);
5510                 else
5511                         verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5512                 return -EINVAL;
5513         }
5514
5515         meta->map_ptr = map_ptr;
5516         kptr_off = reg->off + reg->var_off.value;
5517         off_desc = bpf_map_kptr_off_contains(map_ptr, kptr_off);
5518         if (!off_desc) {
5519                 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5520                 return -EACCES;
5521         }
5522         if (off_desc->type != BPF_KPTR_REF) {
5523                 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5524                 return -EACCES;
5525         }
5526         meta->kptr_off_desc = off_desc;
5527         return 0;
5528 }
5529
5530 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5531 {
5532         return type == ARG_CONST_SIZE ||
5533                type == ARG_CONST_SIZE_OR_ZERO;
5534 }
5535
5536 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
5537 {
5538         return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
5539 }
5540
5541 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
5542 {
5543         return type == ARG_PTR_TO_INT ||
5544                type == ARG_PTR_TO_LONG;
5545 }
5546
5547 static bool arg_type_is_release(enum bpf_arg_type type)
5548 {
5549         return type & OBJ_RELEASE;
5550 }
5551
5552 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5553 {
5554         return base_type(type) == ARG_PTR_TO_DYNPTR;
5555 }
5556
5557 static int int_ptr_type_to_size(enum bpf_arg_type type)
5558 {
5559         if (type == ARG_PTR_TO_INT)
5560                 return sizeof(u32);
5561         else if (type == ARG_PTR_TO_LONG)
5562                 return sizeof(u64);
5563
5564         return -EINVAL;
5565 }
5566
5567 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5568                                  const struct bpf_call_arg_meta *meta,
5569                                  enum bpf_arg_type *arg_type)
5570 {
5571         if (!meta->map_ptr) {
5572                 /* kernel subsystem misconfigured verifier */
5573                 verbose(env, "invalid map_ptr to access map->type\n");
5574                 return -EACCES;
5575         }
5576
5577         switch (meta->map_ptr->map_type) {
5578         case BPF_MAP_TYPE_SOCKMAP:
5579         case BPF_MAP_TYPE_SOCKHASH:
5580                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5581                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5582                 } else {
5583                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
5584                         return -EINVAL;
5585                 }
5586                 break;
5587         case BPF_MAP_TYPE_BLOOM_FILTER:
5588                 if (meta->func_id == BPF_FUNC_map_peek_elem)
5589                         *arg_type = ARG_PTR_TO_MAP_VALUE;
5590                 break;
5591         default:
5592                 break;
5593         }
5594         return 0;
5595 }
5596
5597 struct bpf_reg_types {
5598         const enum bpf_reg_type types[10];
5599         u32 *btf_id;
5600 };
5601
5602 static const struct bpf_reg_types map_key_value_types = {
5603         .types = {
5604                 PTR_TO_STACK,
5605                 PTR_TO_PACKET,
5606                 PTR_TO_PACKET_META,
5607                 PTR_TO_MAP_KEY,
5608                 PTR_TO_MAP_VALUE,
5609         },
5610 };
5611
5612 static const struct bpf_reg_types sock_types = {
5613         .types = {
5614                 PTR_TO_SOCK_COMMON,
5615                 PTR_TO_SOCKET,
5616                 PTR_TO_TCP_SOCK,
5617                 PTR_TO_XDP_SOCK,
5618         },
5619 };
5620
5621 #ifdef CONFIG_NET
5622 static const struct bpf_reg_types btf_id_sock_common_types = {
5623         .types = {
5624                 PTR_TO_SOCK_COMMON,
5625                 PTR_TO_SOCKET,
5626                 PTR_TO_TCP_SOCK,
5627                 PTR_TO_XDP_SOCK,
5628                 PTR_TO_BTF_ID,
5629         },
5630         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5631 };
5632 #endif
5633
5634 static const struct bpf_reg_types mem_types = {
5635         .types = {
5636                 PTR_TO_STACK,
5637                 PTR_TO_PACKET,
5638                 PTR_TO_PACKET_META,
5639                 PTR_TO_MAP_KEY,
5640                 PTR_TO_MAP_VALUE,
5641                 PTR_TO_MEM,
5642                 PTR_TO_MEM | MEM_ALLOC,
5643                 PTR_TO_BUF,
5644         },
5645 };
5646
5647 static const struct bpf_reg_types int_ptr_types = {
5648         .types = {
5649                 PTR_TO_STACK,
5650                 PTR_TO_PACKET,
5651                 PTR_TO_PACKET_META,
5652                 PTR_TO_MAP_KEY,
5653                 PTR_TO_MAP_VALUE,
5654         },
5655 };
5656
5657 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5658 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5659 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5660 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
5661 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5662 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5663 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5664 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_BTF_ID | MEM_PERCPU } };
5665 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5666 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5667 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5668 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5669 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5670
5671 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5672         [ARG_PTR_TO_MAP_KEY]            = &map_key_value_types,
5673         [ARG_PTR_TO_MAP_VALUE]          = &map_key_value_types,
5674         [ARG_CONST_SIZE]                = &scalar_types,
5675         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
5676         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
5677         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
5678         [ARG_PTR_TO_CTX]                = &context_types,
5679         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
5680 #ifdef CONFIG_NET
5681         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
5682 #endif
5683         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
5684         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
5685         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
5686         [ARG_PTR_TO_MEM]                = &mem_types,
5687         [ARG_PTR_TO_ALLOC_MEM]          = &alloc_mem_types,
5688         [ARG_PTR_TO_INT]                = &int_ptr_types,
5689         [ARG_PTR_TO_LONG]               = &int_ptr_types,
5690         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
5691         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
5692         [ARG_PTR_TO_STACK]              = &stack_ptr_types,
5693         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
5694         [ARG_PTR_TO_TIMER]              = &timer_types,
5695         [ARG_PTR_TO_KPTR]               = &kptr_types,
5696         [ARG_PTR_TO_DYNPTR]             = &stack_ptr_types,
5697 };
5698
5699 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
5700                           enum bpf_arg_type arg_type,
5701                           const u32 *arg_btf_id,
5702                           struct bpf_call_arg_meta *meta)
5703 {
5704         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5705         enum bpf_reg_type expected, type = reg->type;
5706         const struct bpf_reg_types *compatible;
5707         int i, j;
5708
5709         compatible = compatible_reg_types[base_type(arg_type)];
5710         if (!compatible) {
5711                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5712                 return -EFAULT;
5713         }
5714
5715         /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
5716          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
5717          *
5718          * Same for MAYBE_NULL:
5719          *
5720          * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
5721          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
5722          *
5723          * Therefore we fold these flags depending on the arg_type before comparison.
5724          */
5725         if (arg_type & MEM_RDONLY)
5726                 type &= ~MEM_RDONLY;
5727         if (arg_type & PTR_MAYBE_NULL)
5728                 type &= ~PTR_MAYBE_NULL;
5729
5730         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5731                 expected = compatible->types[i];
5732                 if (expected == NOT_INIT)
5733                         break;
5734
5735                 if (type == expected)
5736                         goto found;
5737         }
5738
5739         verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
5740         for (j = 0; j + 1 < i; j++)
5741                 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
5742         verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
5743         return -EACCES;
5744
5745 found:
5746         if (reg->type == PTR_TO_BTF_ID) {
5747                 /* For bpf_sk_release, it needs to match against first member
5748                  * 'struct sock_common', hence make an exception for it. This
5749                  * allows bpf_sk_release to work for multiple socket types.
5750                  */
5751                 bool strict_type_match = arg_type_is_release(arg_type) &&
5752                                          meta->func_id != BPF_FUNC_sk_release;
5753
5754                 if (!arg_btf_id) {
5755                         if (!compatible->btf_id) {
5756                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5757                                 return -EFAULT;
5758                         }
5759                         arg_btf_id = compatible->btf_id;
5760                 }
5761
5762                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
5763                         if (map_kptr_match_type(env, meta->kptr_off_desc, reg, regno))
5764                                 return -EACCES;
5765                 } else if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5766                                                  btf_vmlinux, *arg_btf_id,
5767                                                  strict_type_match)) {
5768                         verbose(env, "R%d is of type %s but %s is expected\n",
5769                                 regno, kernel_type_name(reg->btf, reg->btf_id),
5770                                 kernel_type_name(btf_vmlinux, *arg_btf_id));
5771                         return -EACCES;
5772                 }
5773         }
5774
5775         return 0;
5776 }
5777
5778 int check_func_arg_reg_off(struct bpf_verifier_env *env,
5779                            const struct bpf_reg_state *reg, int regno,
5780                            enum bpf_arg_type arg_type)
5781 {
5782         enum bpf_reg_type type = reg->type;
5783         bool fixed_off_ok = false;
5784
5785         switch ((u32)type) {
5786         /* Pointer types where reg offset is explicitly allowed: */
5787         case PTR_TO_STACK:
5788                 if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
5789                         verbose(env, "cannot pass in dynptr at an offset\n");
5790                         return -EINVAL;
5791                 }
5792                 fallthrough;
5793         case PTR_TO_PACKET:
5794         case PTR_TO_PACKET_META:
5795         case PTR_TO_MAP_KEY:
5796         case PTR_TO_MAP_VALUE:
5797         case PTR_TO_MEM:
5798         case PTR_TO_MEM | MEM_RDONLY:
5799         case PTR_TO_MEM | MEM_ALLOC:
5800         case PTR_TO_BUF:
5801         case PTR_TO_BUF | MEM_RDONLY:
5802         case SCALAR_VALUE:
5803                 /* Some of the argument types nevertheless require a
5804                  * zero register offset.
5805                  */
5806                 if (base_type(arg_type) != ARG_PTR_TO_ALLOC_MEM)
5807                         return 0;
5808                 break;
5809         /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
5810          * fixed offset.
5811          */
5812         case PTR_TO_BTF_ID:
5813                 /* When referenced PTR_TO_BTF_ID is passed to release function,
5814                  * it's fixed offset must be 0. In the other cases, fixed offset
5815                  * can be non-zero.
5816                  */
5817                 if (arg_type_is_release(arg_type) && reg->off) {
5818                         verbose(env, "R%d must have zero offset when passed to release func\n",
5819                                 regno);
5820                         return -EINVAL;
5821                 }
5822                 /* For arg is release pointer, fixed_off_ok must be false, but
5823                  * we already checked and rejected reg->off != 0 above, so set
5824                  * to true to allow fixed offset for all other cases.
5825                  */
5826                 fixed_off_ok = true;
5827                 break;
5828         default:
5829                 break;
5830         }
5831         return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
5832 }
5833
5834 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
5835 {
5836         struct bpf_func_state *state = func(env, reg);
5837         int spi = get_spi(reg->off);
5838
5839         return state->stack[spi].spilled_ptr.id;
5840 }
5841
5842 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5843                           struct bpf_call_arg_meta *meta,
5844                           const struct bpf_func_proto *fn)
5845 {
5846         u32 regno = BPF_REG_1 + arg;
5847         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5848         enum bpf_arg_type arg_type = fn->arg_type[arg];
5849         enum bpf_reg_type type = reg->type;
5850         u32 *arg_btf_id = NULL;
5851         int err = 0;
5852
5853         if (arg_type == ARG_DONTCARE)
5854                 return 0;
5855
5856         err = check_reg_arg(env, regno, SRC_OP);
5857         if (err)
5858                 return err;
5859
5860         if (arg_type == ARG_ANYTHING) {
5861                 if (is_pointer_value(env, regno)) {
5862                         verbose(env, "R%d leaks addr into helper function\n",
5863                                 regno);
5864                         return -EACCES;
5865                 }
5866                 return 0;
5867         }
5868
5869         if (type_is_pkt_pointer(type) &&
5870             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5871                 verbose(env, "helper access to the packet is not allowed\n");
5872                 return -EACCES;
5873         }
5874
5875         if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
5876                 err = resolve_map_arg_type(env, meta, &arg_type);
5877                 if (err)
5878                         return err;
5879         }
5880
5881         if (register_is_null(reg) && type_may_be_null(arg_type))
5882                 /* A NULL register has a SCALAR_VALUE type, so skip
5883                  * type checking.
5884                  */
5885                 goto skip_type_check;
5886
5887         /* arg_btf_id and arg_size are in a union. */
5888         if (base_type(arg_type) == ARG_PTR_TO_BTF_ID)
5889                 arg_btf_id = fn->arg_btf_id[arg];
5890
5891         err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
5892         if (err)
5893                 return err;
5894
5895         err = check_func_arg_reg_off(env, reg, regno, arg_type);
5896         if (err)
5897                 return err;
5898
5899 skip_type_check:
5900         if (arg_type_is_release(arg_type)) {
5901                 if (arg_type_is_dynptr(arg_type)) {
5902                         struct bpf_func_state *state = func(env, reg);
5903                         int spi = get_spi(reg->off);
5904
5905                         if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
5906                             !state->stack[spi].spilled_ptr.id) {
5907                                 verbose(env, "arg %d is an unacquired reference\n", regno);
5908                                 return -EINVAL;
5909                         }
5910                 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
5911                         verbose(env, "R%d must be referenced when passed to release function\n",
5912                                 regno);
5913                         return -EINVAL;
5914                 }
5915                 if (meta->release_regno) {
5916                         verbose(env, "verifier internal error: more than one release argument\n");
5917                         return -EFAULT;
5918                 }
5919                 meta->release_regno = regno;
5920         }
5921
5922         if (reg->ref_obj_id) {
5923                 if (meta->ref_obj_id) {
5924                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5925                                 regno, reg->ref_obj_id,
5926                                 meta->ref_obj_id);
5927                         return -EFAULT;
5928                 }
5929                 meta->ref_obj_id = reg->ref_obj_id;
5930         }
5931
5932         if (arg_type == ARG_CONST_MAP_PTR) {
5933                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
5934                 if (meta->map_ptr) {
5935                         /* Use map_uid (which is unique id of inner map) to reject:
5936                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5937                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5938                          * if (inner_map1 && inner_map2) {
5939                          *     timer = bpf_map_lookup_elem(inner_map1);
5940                          *     if (timer)
5941                          *         // mismatch would have been allowed
5942                          *         bpf_timer_init(timer, inner_map2);
5943                          * }
5944                          *
5945                          * Comparing map_ptr is enough to distinguish normal and outer maps.
5946                          */
5947                         if (meta->map_ptr != reg->map_ptr ||
5948                             meta->map_uid != reg->map_uid) {
5949                                 verbose(env,
5950                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
5951                                         meta->map_uid, reg->map_uid);
5952                                 return -EINVAL;
5953                         }
5954                 }
5955                 meta->map_ptr = reg->map_ptr;
5956                 meta->map_uid = reg->map_uid;
5957         } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
5958                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
5959                  * check that [key, key + map->key_size) are within
5960                  * stack limits and initialized
5961                  */
5962                 if (!meta->map_ptr) {
5963                         /* in function declaration map_ptr must come before
5964                          * map_key, so that it's verified and known before
5965                          * we have to check map_key here. Otherwise it means
5966                          * that kernel subsystem misconfigured verifier
5967                          */
5968                         verbose(env, "invalid map_ptr to access map->key\n");
5969                         return -EACCES;
5970                 }
5971                 err = check_helper_mem_access(env, regno,
5972                                               meta->map_ptr->key_size, false,
5973                                               NULL);
5974         } else if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
5975                 if (type_may_be_null(arg_type) && register_is_null(reg))
5976                         return 0;
5977
5978                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
5979                  * check [value, value + map->value_size) validity
5980                  */
5981                 if (!meta->map_ptr) {
5982                         /* kernel subsystem misconfigured verifier */
5983                         verbose(env, "invalid map_ptr to access map->value\n");
5984                         return -EACCES;
5985                 }
5986                 meta->raw_mode = arg_type & MEM_UNINIT;
5987                 err = check_helper_mem_access(env, regno,
5988                                               meta->map_ptr->value_size, false,
5989                                               meta);
5990         } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
5991                 if (!reg->btf_id) {
5992                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
5993                         return -EACCES;
5994                 }
5995                 meta->ret_btf = reg->btf;
5996                 meta->ret_btf_id = reg->btf_id;
5997         } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
5998                 if (meta->func_id == BPF_FUNC_spin_lock) {
5999                         if (process_spin_lock(env, regno, true))
6000                                 return -EACCES;
6001                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
6002                         if (process_spin_lock(env, regno, false))
6003                                 return -EACCES;
6004                 } else {
6005                         verbose(env, "verifier internal error\n");
6006                         return -EFAULT;
6007                 }
6008         } else if (arg_type == ARG_PTR_TO_TIMER) {
6009                 if (process_timer_func(env, regno, meta))
6010                         return -EACCES;
6011         } else if (arg_type == ARG_PTR_TO_FUNC) {
6012                 meta->subprogno = reg->subprogno;
6013         } else if (base_type(arg_type) == ARG_PTR_TO_MEM) {
6014                 /* The access to this pointer is only checked when we hit the
6015                  * next is_mem_size argument below.
6016                  */
6017                 meta->raw_mode = arg_type & MEM_UNINIT;
6018                 if (arg_type & MEM_FIXED_SIZE) {
6019                         err = check_helper_mem_access(env, regno,
6020                                                       fn->arg_size[arg], false,
6021                                                       meta);
6022                 }
6023         } else if (arg_type_is_mem_size(arg_type)) {
6024                 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
6025
6026                 err = check_mem_size_reg(env, reg, regno, zero_size_allowed, meta);
6027         } else if (arg_type_is_dynptr(arg_type)) {
6028                 if (arg_type & MEM_UNINIT) {
6029                         if (!is_dynptr_reg_valid_uninit(env, reg)) {
6030                                 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6031                                 return -EINVAL;
6032                         }
6033
6034                         /* We only support one dynptr being uninitialized at the moment,
6035                          * which is sufficient for the helper functions we have right now.
6036                          */
6037                         if (meta->uninit_dynptr_regno) {
6038                                 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6039                                 return -EFAULT;
6040                         }
6041
6042                         meta->uninit_dynptr_regno = regno;
6043                 } else if (!is_dynptr_reg_valid_init(env, reg, arg_type)) {
6044                         const char *err_extra = "";
6045
6046                         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6047                         case DYNPTR_TYPE_LOCAL:
6048                                 err_extra = "local ";
6049                                 break;
6050                         case DYNPTR_TYPE_RINGBUF:
6051                                 err_extra = "ringbuf ";
6052                                 break;
6053                         default:
6054                                 break;
6055                         }
6056
6057                         verbose(env, "Expected an initialized %sdynptr as arg #%d\n",
6058                                 err_extra, arg + 1);
6059                         return -EINVAL;
6060                 }
6061         } else if (arg_type_is_alloc_size(arg_type)) {
6062                 if (!tnum_is_const(reg->var_off)) {
6063                         verbose(env, "R%d is not a known constant'\n",
6064                                 regno);
6065                         return -EACCES;
6066                 }
6067                 meta->mem_size = reg->var_off.value;
6068         } else if (arg_type_is_int_ptr(arg_type)) {
6069                 int size = int_ptr_type_to_size(arg_type);
6070
6071                 err = check_helper_mem_access(env, regno, size, false, meta);
6072                 if (err)
6073                         return err;
6074                 err = check_ptr_alignment(env, reg, 0, size, true);
6075         } else if (arg_type == ARG_PTR_TO_CONST_STR) {
6076                 struct bpf_map *map = reg->map_ptr;
6077                 int map_off;
6078                 u64 map_addr;
6079                 char *str_ptr;
6080
6081                 if (!bpf_map_is_rdonly(map)) {
6082                         verbose(env, "R%d does not point to a readonly map'\n", regno);
6083                         return -EACCES;
6084                 }
6085
6086                 if (!tnum_is_const(reg->var_off)) {
6087                         verbose(env, "R%d is not a constant address'\n", regno);
6088                         return -EACCES;
6089                 }
6090
6091                 if (!map->ops->map_direct_value_addr) {
6092                         verbose(env, "no direct value access support for this map type\n");
6093                         return -EACCES;
6094                 }
6095
6096                 err = check_map_access(env, regno, reg->off,
6097                                        map->value_size - reg->off, false,
6098                                        ACCESS_HELPER);
6099                 if (err)
6100                         return err;
6101
6102                 map_off = reg->off + reg->var_off.value;
6103                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6104                 if (err) {
6105                         verbose(env, "direct value access on string failed\n");
6106                         return err;
6107                 }
6108
6109                 str_ptr = (char *)(long)(map_addr);
6110                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6111                         verbose(env, "string is not zero-terminated\n");
6112                         return -EINVAL;
6113                 }
6114         } else if (arg_type == ARG_PTR_TO_KPTR) {
6115                 if (process_kptr_func(env, regno, meta))
6116                         return -EACCES;
6117         }
6118
6119         return err;
6120 }
6121
6122 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6123 {
6124         enum bpf_attach_type eatype = env->prog->expected_attach_type;
6125         enum bpf_prog_type type = resolve_prog_type(env->prog);
6126
6127         if (func_id != BPF_FUNC_map_update_elem)
6128                 return false;
6129
6130         /* It's not possible to get access to a locked struct sock in these
6131          * contexts, so updating is safe.
6132          */
6133         switch (type) {
6134         case BPF_PROG_TYPE_TRACING:
6135                 if (eatype == BPF_TRACE_ITER)
6136                         return true;
6137                 break;
6138         case BPF_PROG_TYPE_SOCKET_FILTER:
6139         case BPF_PROG_TYPE_SCHED_CLS:
6140         case BPF_PROG_TYPE_SCHED_ACT:
6141         case BPF_PROG_TYPE_XDP:
6142         case BPF_PROG_TYPE_SK_REUSEPORT:
6143         case BPF_PROG_TYPE_FLOW_DISSECTOR:
6144         case BPF_PROG_TYPE_SK_LOOKUP:
6145                 return true;
6146         default:
6147                 break;
6148         }
6149
6150         verbose(env, "cannot update sockmap in this context\n");
6151         return false;
6152 }
6153
6154 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6155 {
6156         return env->prog->jit_requested &&
6157                bpf_jit_supports_subprog_tailcalls();
6158 }
6159
6160 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6161                                         struct bpf_map *map, int func_id)
6162 {
6163         if (!map)
6164                 return 0;
6165
6166         /* We need a two way check, first is from map perspective ... */
6167         switch (map->map_type) {
6168         case BPF_MAP_TYPE_PROG_ARRAY:
6169                 if (func_id != BPF_FUNC_tail_call)
6170                         goto error;
6171                 break;
6172         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6173                 if (func_id != BPF_FUNC_perf_event_read &&
6174                     func_id != BPF_FUNC_perf_event_output &&
6175                     func_id != BPF_FUNC_skb_output &&
6176                     func_id != BPF_FUNC_perf_event_read_value &&
6177                     func_id != BPF_FUNC_xdp_output)
6178                         goto error;
6179                 break;
6180         case BPF_MAP_TYPE_RINGBUF:
6181                 if (func_id != BPF_FUNC_ringbuf_output &&
6182                     func_id != BPF_FUNC_ringbuf_reserve &&
6183                     func_id != BPF_FUNC_ringbuf_query &&
6184                     func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6185                     func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6186                     func_id != BPF_FUNC_ringbuf_discard_dynptr)
6187                         goto error;
6188                 break;
6189         case BPF_MAP_TYPE_STACK_TRACE:
6190                 if (func_id != BPF_FUNC_get_stackid)
6191                         goto error;
6192                 break;
6193         case BPF_MAP_TYPE_CGROUP_ARRAY:
6194                 if (func_id != BPF_FUNC_skb_under_cgroup &&
6195                     func_id != BPF_FUNC_current_task_under_cgroup)
6196                         goto error;
6197                 break;
6198         case BPF_MAP_TYPE_CGROUP_STORAGE:
6199         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6200                 if (func_id != BPF_FUNC_get_local_storage)
6201                         goto error;
6202                 break;
6203         case BPF_MAP_TYPE_DEVMAP:
6204         case BPF_MAP_TYPE_DEVMAP_HASH:
6205                 if (func_id != BPF_FUNC_redirect_map &&
6206                     func_id != BPF_FUNC_map_lookup_elem)
6207                         goto error;
6208                 break;
6209         /* Restrict bpf side of cpumap and xskmap, open when use-cases
6210          * appear.
6211          */
6212         case BPF_MAP_TYPE_CPUMAP:
6213                 if (func_id != BPF_FUNC_redirect_map)
6214                         goto error;
6215                 break;
6216         case BPF_MAP_TYPE_XSKMAP:
6217                 if (func_id != BPF_FUNC_redirect_map &&
6218                     func_id != BPF_FUNC_map_lookup_elem)
6219                         goto error;
6220                 break;
6221         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6222         case BPF_MAP_TYPE_HASH_OF_MAPS:
6223                 if (func_id != BPF_FUNC_map_lookup_elem)
6224                         goto error;
6225                 break;
6226         case BPF_MAP_TYPE_SOCKMAP:
6227                 if (func_id != BPF_FUNC_sk_redirect_map &&
6228                     func_id != BPF_FUNC_sock_map_update &&
6229                     func_id != BPF_FUNC_map_delete_elem &&
6230                     func_id != BPF_FUNC_msg_redirect_map &&
6231                     func_id != BPF_FUNC_sk_select_reuseport &&
6232                     func_id != BPF_FUNC_map_lookup_elem &&
6233                     !may_update_sockmap(env, func_id))
6234                         goto error;
6235                 break;
6236         case BPF_MAP_TYPE_SOCKHASH:
6237                 if (func_id != BPF_FUNC_sk_redirect_hash &&
6238                     func_id != BPF_FUNC_sock_hash_update &&
6239                     func_id != BPF_FUNC_map_delete_elem &&
6240                     func_id != BPF_FUNC_msg_redirect_hash &&
6241                     func_id != BPF_FUNC_sk_select_reuseport &&
6242                     func_id != BPF_FUNC_map_lookup_elem &&
6243                     !may_update_sockmap(env, func_id))
6244                         goto error;
6245                 break;
6246         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6247                 if (func_id != BPF_FUNC_sk_select_reuseport)
6248                         goto error;
6249                 break;
6250         case BPF_MAP_TYPE_QUEUE:
6251         case BPF_MAP_TYPE_STACK:
6252                 if (func_id != BPF_FUNC_map_peek_elem &&
6253                     func_id != BPF_FUNC_map_pop_elem &&
6254                     func_id != BPF_FUNC_map_push_elem)
6255                         goto error;
6256                 break;
6257         case BPF_MAP_TYPE_SK_STORAGE:
6258                 if (func_id != BPF_FUNC_sk_storage_get &&
6259                     func_id != BPF_FUNC_sk_storage_delete)
6260                         goto error;
6261                 break;
6262         case BPF_MAP_TYPE_INODE_STORAGE:
6263                 if (func_id != BPF_FUNC_inode_storage_get &&
6264                     func_id != BPF_FUNC_inode_storage_delete)
6265                         goto error;
6266                 break;
6267         case BPF_MAP_TYPE_TASK_STORAGE:
6268                 if (func_id != BPF_FUNC_task_storage_get &&
6269                     func_id != BPF_FUNC_task_storage_delete)
6270                         goto error;
6271                 break;
6272         case BPF_MAP_TYPE_BLOOM_FILTER:
6273                 if (func_id != BPF_FUNC_map_peek_elem &&
6274                     func_id != BPF_FUNC_map_push_elem)
6275                         goto error;
6276                 break;
6277         default:
6278                 break;
6279         }
6280
6281         /* ... and second from the function itself. */
6282         switch (func_id) {
6283         case BPF_FUNC_tail_call:
6284                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6285                         goto error;
6286                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6287                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6288                         return -EINVAL;
6289                 }
6290                 break;
6291         case BPF_FUNC_perf_event_read:
6292         case BPF_FUNC_perf_event_output:
6293         case BPF_FUNC_perf_event_read_value:
6294         case BPF_FUNC_skb_output:
6295         case BPF_FUNC_xdp_output:
6296                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6297                         goto error;
6298                 break;
6299         case BPF_FUNC_ringbuf_output:
6300         case BPF_FUNC_ringbuf_reserve:
6301         case BPF_FUNC_ringbuf_query:
6302         case BPF_FUNC_ringbuf_reserve_dynptr:
6303         case BPF_FUNC_ringbuf_submit_dynptr:
6304         case BPF_FUNC_ringbuf_discard_dynptr:
6305                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6306                         goto error;
6307                 break;
6308         case BPF_FUNC_get_stackid:
6309                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6310                         goto error;
6311                 break;
6312         case BPF_FUNC_current_task_under_cgroup:
6313         case BPF_FUNC_skb_under_cgroup:
6314                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6315                         goto error;
6316                 break;
6317         case BPF_FUNC_redirect_map:
6318                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6319                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6320                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
6321                     map->map_type != BPF_MAP_TYPE_XSKMAP)
6322                         goto error;
6323                 break;
6324         case BPF_FUNC_sk_redirect_map:
6325         case BPF_FUNC_msg_redirect_map:
6326         case BPF_FUNC_sock_map_update:
6327                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6328                         goto error;
6329                 break;
6330         case BPF_FUNC_sk_redirect_hash:
6331         case BPF_FUNC_msg_redirect_hash:
6332         case BPF_FUNC_sock_hash_update:
6333                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6334                         goto error;
6335                 break;
6336         case BPF_FUNC_get_local_storage:
6337                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6338                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6339                         goto error;
6340                 break;
6341         case BPF_FUNC_sk_select_reuseport:
6342                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6343                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6344                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
6345                         goto error;
6346                 break;
6347         case BPF_FUNC_map_pop_elem:
6348                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6349                     map->map_type != BPF_MAP_TYPE_STACK)
6350                         goto error;
6351                 break;
6352         case BPF_FUNC_map_peek_elem:
6353         case BPF_FUNC_map_push_elem:
6354                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6355                     map->map_type != BPF_MAP_TYPE_STACK &&
6356                     map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6357                         goto error;
6358                 break;
6359         case BPF_FUNC_map_lookup_percpu_elem:
6360                 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6361                     map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6362                     map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6363                         goto error;
6364                 break;
6365         case BPF_FUNC_sk_storage_get:
6366         case BPF_FUNC_sk_storage_delete:
6367                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6368                         goto error;
6369                 break;
6370         case BPF_FUNC_inode_storage_get:
6371         case BPF_FUNC_inode_storage_delete:
6372                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6373                         goto error;
6374                 break;
6375         case BPF_FUNC_task_storage_get:
6376         case BPF_FUNC_task_storage_delete:
6377                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6378                         goto error;
6379                 break;
6380         default:
6381                 break;
6382         }
6383
6384         return 0;
6385 error:
6386         verbose(env, "cannot pass map_type %d into func %s#%d\n",
6387                 map->map_type, func_id_name(func_id), func_id);
6388         return -EINVAL;
6389 }
6390
6391 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6392 {
6393         int count = 0;
6394
6395         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6396                 count++;
6397         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6398                 count++;
6399         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6400                 count++;
6401         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6402                 count++;
6403         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6404                 count++;
6405
6406         /* We only support one arg being in raw mode at the moment,
6407          * which is sufficient for the helper functions we have
6408          * right now.
6409          */
6410         return count <= 1;
6411 }
6412
6413 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6414 {
6415         bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6416         bool has_size = fn->arg_size[arg] != 0;
6417         bool is_next_size = false;
6418
6419         if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6420                 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6421
6422         if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6423                 return is_next_size;
6424
6425         return has_size == is_next_size || is_next_size == is_fixed;
6426 }
6427
6428 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6429 {
6430         /* bpf_xxx(..., buf, len) call will access 'len'
6431          * bytes from memory 'buf'. Both arg types need
6432          * to be paired, so make sure there's no buggy
6433          * helper function specification.
6434          */
6435         if (arg_type_is_mem_size(fn->arg1_type) ||
6436             check_args_pair_invalid(fn, 0) ||
6437             check_args_pair_invalid(fn, 1) ||
6438             check_args_pair_invalid(fn, 2) ||
6439             check_args_pair_invalid(fn, 3) ||
6440             check_args_pair_invalid(fn, 4))
6441                 return false;
6442
6443         return true;
6444 }
6445
6446 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
6447 {
6448         int count = 0;
6449
6450         if (arg_type_may_be_refcounted(fn->arg1_type))
6451                 count++;
6452         if (arg_type_may_be_refcounted(fn->arg2_type))
6453                 count++;
6454         if (arg_type_may_be_refcounted(fn->arg3_type))
6455                 count++;
6456         if (arg_type_may_be_refcounted(fn->arg4_type))
6457                 count++;
6458         if (arg_type_may_be_refcounted(fn->arg5_type))
6459                 count++;
6460
6461         /* A reference acquiring function cannot acquire
6462          * another refcounted ptr.
6463          */
6464         if (may_be_acquire_function(func_id) && count)
6465                 return false;
6466
6467         /* We only support one arg being unreferenced at the moment,
6468          * which is sufficient for the helper functions we have right now.
6469          */
6470         return count <= 1;
6471 }
6472
6473 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6474 {
6475         int i;
6476
6477         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6478                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
6479                         return false;
6480
6481                 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6482                     /* arg_btf_id and arg_size are in a union. */
6483                     (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6484                      !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6485                         return false;
6486         }
6487
6488         return true;
6489 }
6490
6491 static int check_func_proto(const struct bpf_func_proto *fn, int func_id,
6492                             struct bpf_call_arg_meta *meta)
6493 {
6494         return check_raw_mode_ok(fn) &&
6495                check_arg_pair_ok(fn) &&
6496                check_btf_id_ok(fn) &&
6497                check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
6498 }
6499
6500 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6501  * are now invalid, so turn them into unknown SCALAR_VALUE.
6502  */
6503 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
6504                                      struct bpf_func_state *state)
6505 {
6506         struct bpf_reg_state *regs = state->regs, *reg;
6507         int i;
6508
6509         for (i = 0; i < MAX_BPF_REG; i++)
6510                 if (reg_is_pkt_pointer_any(&regs[i]))
6511                         mark_reg_unknown(env, regs, i);
6512
6513         bpf_for_each_spilled_reg(i, state, reg) {
6514                 if (!reg)
6515                         continue;
6516                 if (reg_is_pkt_pointer_any(reg))
6517                         __mark_reg_unknown(env, reg);
6518         }
6519 }
6520
6521 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6522 {
6523         struct bpf_verifier_state *vstate = env->cur_state;
6524         int i;
6525
6526         for (i = 0; i <= vstate->curframe; i++)
6527                 __clear_all_pkt_pointers(env, vstate->frame[i]);
6528 }
6529
6530 enum {
6531         AT_PKT_END = -1,
6532         BEYOND_PKT_END = -2,
6533 };
6534
6535 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6536 {
6537         struct bpf_func_state *state = vstate->frame[vstate->curframe];
6538         struct bpf_reg_state *reg = &state->regs[regn];
6539
6540         if (reg->type != PTR_TO_PACKET)
6541                 /* PTR_TO_PACKET_META is not supported yet */
6542                 return;
6543
6544         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6545          * How far beyond pkt_end it goes is unknown.
6546          * if (!range_open) it's the case of pkt >= pkt_end
6547          * if (range_open) it's the case of pkt > pkt_end
6548          * hence this pointer is at least 1 byte bigger than pkt_end
6549          */
6550         if (range_open)
6551                 reg->range = BEYOND_PKT_END;
6552         else
6553                 reg->range = AT_PKT_END;
6554 }
6555
6556 static void release_reg_references(struct bpf_verifier_env *env,
6557                                    struct bpf_func_state *state,
6558                                    int ref_obj_id)
6559 {
6560         struct bpf_reg_state *regs = state->regs, *reg;
6561         int i;
6562
6563         for (i = 0; i < MAX_BPF_REG; i++)
6564                 if (regs[i].ref_obj_id == ref_obj_id)
6565                         mark_reg_unknown(env, regs, i);
6566
6567         bpf_for_each_spilled_reg(i, state, reg) {
6568                 if (!reg)
6569                         continue;
6570                 if (reg->ref_obj_id == ref_obj_id)
6571                         __mark_reg_unknown(env, reg);
6572         }
6573 }
6574
6575 /* The pointer with the specified id has released its reference to kernel
6576  * resources. Identify all copies of the same pointer and clear the reference.
6577  */
6578 static int release_reference(struct bpf_verifier_env *env,
6579                              int ref_obj_id)
6580 {
6581         struct bpf_verifier_state *vstate = env->cur_state;
6582         int err;
6583         int i;
6584
6585         err = release_reference_state(cur_func(env), ref_obj_id);
6586         if (err)
6587                 return err;
6588
6589         for (i = 0; i <= vstate->curframe; i++)
6590                 release_reg_references(env, vstate->frame[i], ref_obj_id);
6591
6592         return 0;
6593 }
6594
6595 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6596                                     struct bpf_reg_state *regs)
6597 {
6598         int i;
6599
6600         /* after the call registers r0 - r5 were scratched */
6601         for (i = 0; i < CALLER_SAVED_REGS; i++) {
6602                 mark_reg_not_init(env, regs, caller_saved[i]);
6603                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6604         }
6605 }
6606
6607 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6608                                    struct bpf_func_state *caller,
6609                                    struct bpf_func_state *callee,
6610                                    int insn_idx);
6611
6612 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6613                              int *insn_idx, int subprog,
6614                              set_callee_state_fn set_callee_state_cb)
6615 {
6616         struct bpf_verifier_state *state = env->cur_state;
6617         struct bpf_func_info_aux *func_info_aux;
6618         struct bpf_func_state *caller, *callee;
6619         int err;
6620         bool is_global = false;
6621
6622         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6623                 verbose(env, "the call stack of %d frames is too deep\n",
6624                         state->curframe + 2);
6625                 return -E2BIG;
6626         }
6627
6628         caller = state->frame[state->curframe];
6629         if (state->frame[state->curframe + 1]) {
6630                 verbose(env, "verifier bug. Frame %d already allocated\n",
6631                         state->curframe + 1);
6632                 return -EFAULT;
6633         }
6634
6635         func_info_aux = env->prog->aux->func_info_aux;
6636         if (func_info_aux)
6637                 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6638         err = btf_check_subprog_arg_match(env, subprog, caller->regs);
6639         if (err == -EFAULT)
6640                 return err;
6641         if (is_global) {
6642                 if (err) {
6643                         verbose(env, "Caller passes invalid args into func#%d\n",
6644                                 subprog);
6645                         return err;
6646                 } else {
6647                         if (env->log.level & BPF_LOG_LEVEL)
6648                                 verbose(env,
6649                                         "Func#%d is global and valid. Skipping.\n",
6650                                         subprog);
6651                         clear_caller_saved_regs(env, caller->regs);
6652
6653                         /* All global functions return a 64-bit SCALAR_VALUE */
6654                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
6655                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6656
6657                         /* continue with next insn after call */
6658                         return 0;
6659                 }
6660         }
6661
6662         if (insn->code == (BPF_JMP | BPF_CALL) &&
6663             insn->src_reg == 0 &&
6664             insn->imm == BPF_FUNC_timer_set_callback) {
6665                 struct bpf_verifier_state *async_cb;
6666
6667                 /* there is no real recursion here. timer callbacks are async */
6668                 env->subprog_info[subprog].is_async_cb = true;
6669                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6670                                          *insn_idx, subprog);
6671                 if (!async_cb)
6672                         return -EFAULT;
6673                 callee = async_cb->frame[0];
6674                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
6675
6676                 /* Convert bpf_timer_set_callback() args into timer callback args */
6677                 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6678                 if (err)
6679                         return err;
6680
6681                 clear_caller_saved_regs(env, caller->regs);
6682                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6683                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6684                 /* continue with next insn after call */
6685                 return 0;
6686         }
6687
6688         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6689         if (!callee)
6690                 return -ENOMEM;
6691         state->frame[state->curframe + 1] = callee;
6692
6693         /* callee cannot access r0, r6 - r9 for reading and has to write
6694          * into its own stack before reading from it.
6695          * callee can read/write into caller's stack
6696          */
6697         init_func_state(env, callee,
6698                         /* remember the callsite, it will be used by bpf_exit */
6699                         *insn_idx /* callsite */,
6700                         state->curframe + 1 /* frameno within this callchain */,
6701                         subprog /* subprog number within this prog */);
6702
6703         /* Transfer references to the callee */
6704         err = copy_reference_state(callee, caller);
6705         if (err)
6706                 return err;
6707
6708         err = set_callee_state_cb(env, caller, callee, *insn_idx);
6709         if (err)
6710                 return err;
6711
6712         clear_caller_saved_regs(env, caller->regs);
6713
6714         /* only increment it after check_reg_arg() finished */
6715         state->curframe++;
6716
6717         /* and go analyze first insn of the callee */
6718         *insn_idx = env->subprog_info[subprog].start - 1;
6719
6720         if (env->log.level & BPF_LOG_LEVEL) {
6721                 verbose(env, "caller:\n");
6722                 print_verifier_state(env, caller, true);
6723                 verbose(env, "callee:\n");
6724                 print_verifier_state(env, callee, true);
6725         }
6726         return 0;
6727 }
6728
6729 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6730                                    struct bpf_func_state *caller,
6731                                    struct bpf_func_state *callee)
6732 {
6733         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6734          *      void *callback_ctx, u64 flags);
6735          * callback_fn(struct bpf_map *map, void *key, void *value,
6736          *      void *callback_ctx);
6737          */
6738         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6739
6740         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6741         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6742         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6743
6744         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6745         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6746         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6747
6748         /* pointer to stack or null */
6749         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6750
6751         /* unused */
6752         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6753         return 0;
6754 }
6755
6756 static int set_callee_state(struct bpf_verifier_env *env,
6757                             struct bpf_func_state *caller,
6758                             struct bpf_func_state *callee, int insn_idx)
6759 {
6760         int i;
6761
6762         /* copy r1 - r5 args that callee can access.  The copy includes parent
6763          * pointers, which connects us up to the liveness chain
6764          */
6765         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6766                 callee->regs[i] = caller->regs[i];
6767         return 0;
6768 }
6769
6770 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6771                            int *insn_idx)
6772 {
6773         int subprog, target_insn;
6774
6775         target_insn = *insn_idx + insn->imm + 1;
6776         subprog = find_subprog(env, target_insn);
6777         if (subprog < 0) {
6778                 verbose(env, "verifier bug. No program starts at insn %d\n",
6779                         target_insn);
6780                 return -EFAULT;
6781         }
6782
6783         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6784 }
6785
6786 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6787                                        struct bpf_func_state *caller,
6788                                        struct bpf_func_state *callee,
6789                                        int insn_idx)
6790 {
6791         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6792         struct bpf_map *map;
6793         int err;
6794
6795         if (bpf_map_ptr_poisoned(insn_aux)) {
6796                 verbose(env, "tail_call abusing map_ptr\n");
6797                 return -EINVAL;
6798         }
6799
6800         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6801         if (!map->ops->map_set_for_each_callback_args ||
6802             !map->ops->map_for_each_callback) {
6803                 verbose(env, "callback function not allowed for map\n");
6804                 return -ENOTSUPP;
6805         }
6806
6807         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6808         if (err)
6809                 return err;
6810
6811         callee->in_callback_fn = true;
6812         return 0;
6813 }
6814
6815 static int set_loop_callback_state(struct bpf_verifier_env *env,
6816                                    struct bpf_func_state *caller,
6817                                    struct bpf_func_state *callee,
6818                                    int insn_idx)
6819 {
6820         /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6821          *          u64 flags);
6822          * callback_fn(u32 index, void *callback_ctx);
6823          */
6824         callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6825         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6826
6827         /* unused */
6828         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6829         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6830         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6831
6832         callee->in_callback_fn = true;
6833         return 0;
6834 }
6835
6836 static int set_timer_callback_state(struct bpf_verifier_env *env,
6837                                     struct bpf_func_state *caller,
6838                                     struct bpf_func_state *callee,
6839                                     int insn_idx)
6840 {
6841         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6842
6843         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6844          * callback_fn(struct bpf_map *map, void *key, void *value);
6845          */
6846         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6847         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6848         callee->regs[BPF_REG_1].map_ptr = map_ptr;
6849
6850         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6851         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6852         callee->regs[BPF_REG_2].map_ptr = map_ptr;
6853
6854         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6855         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6856         callee->regs[BPF_REG_3].map_ptr = map_ptr;
6857
6858         /* unused */
6859         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6860         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6861         callee->in_async_callback_fn = true;
6862         return 0;
6863 }
6864
6865 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6866                                        struct bpf_func_state *caller,
6867                                        struct bpf_func_state *callee,
6868                                        int insn_idx)
6869 {
6870         /* bpf_find_vma(struct task_struct *task, u64 addr,
6871          *               void *callback_fn, void *callback_ctx, u64 flags)
6872          * (callback_fn)(struct task_struct *task,
6873          *               struct vm_area_struct *vma, void *callback_ctx);
6874          */
6875         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6876
6877         callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6878         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6879         callee->regs[BPF_REG_2].btf =  btf_vmlinux;
6880         callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
6881
6882         /* pointer to stack or null */
6883         callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6884
6885         /* unused */
6886         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6887         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6888         callee->in_callback_fn = true;
6889         return 0;
6890 }
6891
6892 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
6893 {
6894         struct bpf_verifier_state *state = env->cur_state;
6895         struct bpf_func_state *caller, *callee;
6896         struct bpf_reg_state *r0;
6897         int err;
6898
6899         callee = state->frame[state->curframe];
6900         r0 = &callee->regs[BPF_REG_0];
6901         if (r0->type == PTR_TO_STACK) {
6902                 /* technically it's ok to return caller's stack pointer
6903                  * (or caller's caller's pointer) back to the caller,
6904                  * since these pointers are valid. Only current stack
6905                  * pointer will be invalid as soon as function exits,
6906                  * but let's be conservative
6907                  */
6908                 verbose(env, "cannot return stack pointer to the caller\n");
6909                 return -EINVAL;
6910         }
6911
6912         state->curframe--;
6913         caller = state->frame[state->curframe];
6914         if (callee->in_callback_fn) {
6915                 /* enforce R0 return value range [0, 1]. */
6916                 struct tnum range = tnum_range(0, 1);
6917
6918                 if (r0->type != SCALAR_VALUE) {
6919                         verbose(env, "R0 not a scalar value\n");
6920                         return -EACCES;
6921                 }
6922                 if (!tnum_in(range, r0->var_off)) {
6923                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
6924                         return -EINVAL;
6925                 }
6926         } else {
6927                 /* return to the caller whatever r0 had in the callee */
6928                 caller->regs[BPF_REG_0] = *r0;
6929         }
6930
6931         /* Transfer references to the caller */
6932         err = copy_reference_state(caller, callee);
6933         if (err)
6934                 return err;
6935
6936         *insn_idx = callee->callsite + 1;
6937         if (env->log.level & BPF_LOG_LEVEL) {
6938                 verbose(env, "returning from callee:\n");
6939                 print_verifier_state(env, callee, true);
6940                 verbose(env, "to caller at %d:\n", *insn_idx);
6941                 print_verifier_state(env, caller, true);
6942         }
6943         /* clear everything in the callee */
6944         free_func_state(callee);
6945         state->frame[state->curframe + 1] = NULL;
6946         return 0;
6947 }
6948
6949 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
6950                                    int func_id,
6951                                    struct bpf_call_arg_meta *meta)
6952 {
6953         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
6954
6955         if (ret_type != RET_INTEGER ||
6956             (func_id != BPF_FUNC_get_stack &&
6957              func_id != BPF_FUNC_get_task_stack &&
6958              func_id != BPF_FUNC_probe_read_str &&
6959              func_id != BPF_FUNC_probe_read_kernel_str &&
6960              func_id != BPF_FUNC_probe_read_user_str))
6961                 return;
6962
6963         ret_reg->smax_value = meta->msize_max_value;
6964         ret_reg->s32_max_value = meta->msize_max_value;
6965         ret_reg->smin_value = -MAX_ERRNO;
6966         ret_reg->s32_min_value = -MAX_ERRNO;
6967         reg_bounds_sync(ret_reg);
6968 }
6969
6970 static int
6971 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6972                 int func_id, int insn_idx)
6973 {
6974         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6975         struct bpf_map *map = meta->map_ptr;
6976
6977         if (func_id != BPF_FUNC_tail_call &&
6978             func_id != BPF_FUNC_map_lookup_elem &&
6979             func_id != BPF_FUNC_map_update_elem &&
6980             func_id != BPF_FUNC_map_delete_elem &&
6981             func_id != BPF_FUNC_map_push_elem &&
6982             func_id != BPF_FUNC_map_pop_elem &&
6983             func_id != BPF_FUNC_map_peek_elem &&
6984             func_id != BPF_FUNC_for_each_map_elem &&
6985             func_id != BPF_FUNC_redirect_map &&
6986             func_id != BPF_FUNC_map_lookup_percpu_elem)
6987                 return 0;
6988
6989         if (map == NULL) {
6990                 verbose(env, "kernel subsystem misconfigured verifier\n");
6991                 return -EINVAL;
6992         }
6993
6994         /* In case of read-only, some additional restrictions
6995          * need to be applied in order to prevent altering the
6996          * state of the map from program side.
6997          */
6998         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
6999             (func_id == BPF_FUNC_map_delete_elem ||
7000              func_id == BPF_FUNC_map_update_elem ||
7001              func_id == BPF_FUNC_map_push_elem ||
7002              func_id == BPF_FUNC_map_pop_elem)) {
7003                 verbose(env, "write into map forbidden\n");
7004                 return -EACCES;
7005         }
7006
7007         if (!BPF_MAP_PTR(aux->map_ptr_state))
7008                 bpf_map_ptr_store(aux, meta->map_ptr,
7009                                   !meta->map_ptr->bypass_spec_v1);
7010         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7011                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7012                                   !meta->map_ptr->bypass_spec_v1);
7013         return 0;
7014 }
7015
7016 static int
7017 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7018                 int func_id, int insn_idx)
7019 {
7020         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7021         struct bpf_reg_state *regs = cur_regs(env), *reg;
7022         struct bpf_map *map = meta->map_ptr;
7023         struct tnum range;
7024         u64 val;
7025         int err;
7026
7027         if (func_id != BPF_FUNC_tail_call)
7028                 return 0;
7029         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7030                 verbose(env, "kernel subsystem misconfigured verifier\n");
7031                 return -EINVAL;
7032         }
7033
7034         range = tnum_range(0, map->max_entries - 1);
7035         reg = &regs[BPF_REG_3];
7036
7037         if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
7038                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7039                 return 0;
7040         }
7041
7042         err = mark_chain_precision(env, BPF_REG_3);
7043         if (err)
7044                 return err;
7045
7046         val = reg->var_off.value;
7047         if (bpf_map_key_unseen(aux))
7048                 bpf_map_key_store(aux, val);
7049         else if (!bpf_map_key_poisoned(aux) &&
7050                   bpf_map_key_immediate(aux) != val)
7051                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7052         return 0;
7053 }
7054
7055 static int check_reference_leak(struct bpf_verifier_env *env)
7056 {
7057         struct bpf_func_state *state = cur_func(env);
7058         int i;
7059
7060         for (i = 0; i < state->acquired_refs; i++) {
7061                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7062                         state->refs[i].id, state->refs[i].insn_idx);
7063         }
7064         return state->acquired_refs ? -EINVAL : 0;
7065 }
7066
7067 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7068                                    struct bpf_reg_state *regs)
7069 {
7070         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
7071         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
7072         struct bpf_map *fmt_map = fmt_reg->map_ptr;
7073         int err, fmt_map_off, num_args;
7074         u64 fmt_addr;
7075         char *fmt;
7076
7077         /* data must be an array of u64 */
7078         if (data_len_reg->var_off.value % 8)
7079                 return -EINVAL;
7080         num_args = data_len_reg->var_off.value / 8;
7081
7082         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7083          * and map_direct_value_addr is set.
7084          */
7085         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7086         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7087                                                   fmt_map_off);
7088         if (err) {
7089                 verbose(env, "verifier bug\n");
7090                 return -EFAULT;
7091         }
7092         fmt = (char *)(long)fmt_addr + fmt_map_off;
7093
7094         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7095          * can focus on validating the format specifiers.
7096          */
7097         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7098         if (err < 0)
7099                 verbose(env, "Invalid format string\n");
7100
7101         return err;
7102 }
7103
7104 static int check_get_func_ip(struct bpf_verifier_env *env)
7105 {
7106         enum bpf_prog_type type = resolve_prog_type(env->prog);
7107         int func_id = BPF_FUNC_get_func_ip;
7108
7109         if (type == BPF_PROG_TYPE_TRACING) {
7110                 if (!bpf_prog_has_trampoline(env->prog)) {
7111                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7112                                 func_id_name(func_id), func_id);
7113                         return -ENOTSUPP;
7114                 }
7115                 return 0;
7116         } else if (type == BPF_PROG_TYPE_KPROBE) {
7117                 return 0;
7118         }
7119
7120         verbose(env, "func %s#%d not supported for program type %d\n",
7121                 func_id_name(func_id), func_id, type);
7122         return -ENOTSUPP;
7123 }
7124
7125 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7126 {
7127         return &env->insn_aux_data[env->insn_idx];
7128 }
7129
7130 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7131 {
7132         struct bpf_reg_state *regs = cur_regs(env);
7133         struct bpf_reg_state *reg = &regs[BPF_REG_4];
7134         bool reg_is_null = register_is_null(reg);
7135
7136         if (reg_is_null)
7137                 mark_chain_precision(env, BPF_REG_4);
7138
7139         return reg_is_null;
7140 }
7141
7142 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7143 {
7144         struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7145
7146         if (!state->initialized) {
7147                 state->initialized = 1;
7148                 state->fit_for_inline = loop_flag_is_zero(env);
7149                 state->callback_subprogno = subprogno;
7150                 return;
7151         }
7152
7153         if (!state->fit_for_inline)
7154                 return;
7155
7156         state->fit_for_inline = (loop_flag_is_zero(env) &&
7157                                  state->callback_subprogno == subprogno);
7158 }
7159
7160 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7161                              int *insn_idx_p)
7162 {
7163         const struct bpf_func_proto *fn = NULL;
7164         enum bpf_return_type ret_type;
7165         enum bpf_type_flag ret_flag;
7166         struct bpf_reg_state *regs;
7167         struct bpf_call_arg_meta meta;
7168         int insn_idx = *insn_idx_p;
7169         bool changes_data;
7170         int i, err, func_id;
7171
7172         /* find function prototype */
7173         func_id = insn->imm;
7174         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7175                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7176                         func_id);
7177                 return -EINVAL;
7178         }
7179
7180         if (env->ops->get_func_proto)
7181                 fn = env->ops->get_func_proto(func_id, env->prog);
7182         if (!fn) {
7183                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7184                         func_id);
7185                 return -EINVAL;
7186         }
7187
7188         /* eBPF programs must be GPL compatible to use GPL-ed functions */
7189         if (!env->prog->gpl_compatible && fn->gpl_only) {
7190                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7191                 return -EINVAL;
7192         }
7193
7194         if (fn->allowed && !fn->allowed(env->prog)) {
7195                 verbose(env, "helper call is not allowed in probe\n");
7196                 return -EINVAL;
7197         }
7198
7199         /* With LD_ABS/IND some JITs save/restore skb from r1. */
7200         changes_data = bpf_helper_changes_pkt_data(fn->func);
7201         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7202                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7203                         func_id_name(func_id), func_id);
7204                 return -EINVAL;
7205         }
7206
7207         memset(&meta, 0, sizeof(meta));
7208         meta.pkt_access = fn->pkt_access;
7209
7210         err = check_func_proto(fn, func_id, &meta);
7211         if (err) {
7212                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7213                         func_id_name(func_id), func_id);
7214                 return err;
7215         }
7216
7217         meta.func_id = func_id;
7218         /* check args */
7219         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7220                 err = check_func_arg(env, i, &meta, fn);
7221                 if (err)
7222                         return err;
7223         }
7224
7225         err = record_func_map(env, &meta, func_id, insn_idx);
7226         if (err)
7227                 return err;
7228
7229         err = record_func_key(env, &meta, func_id, insn_idx);
7230         if (err)
7231                 return err;
7232
7233         /* Mark slots with STACK_MISC in case of raw mode, stack offset
7234          * is inferred from register state.
7235          */
7236         for (i = 0; i < meta.access_size; i++) {
7237                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7238                                        BPF_WRITE, -1, false);
7239                 if (err)
7240                         return err;
7241         }
7242
7243         regs = cur_regs(env);
7244
7245         if (meta.uninit_dynptr_regno) {
7246                 /* we write BPF_DW bits (8 bytes) at a time */
7247                 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7248                         err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7249                                                i, BPF_DW, BPF_WRITE, -1, false);
7250                         if (err)
7251                                 return err;
7252                 }
7253
7254                 err = mark_stack_slots_dynptr(env, &regs[meta.uninit_dynptr_regno],
7255                                               fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7256                                               insn_idx);
7257                 if (err)
7258                         return err;
7259         }
7260
7261         if (meta.release_regno) {
7262                 err = -EINVAL;
7263                 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7264                         err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
7265                 else if (meta.ref_obj_id)
7266                         err = release_reference(env, meta.ref_obj_id);
7267                 /* meta.ref_obj_id can only be 0 if register that is meant to be
7268                  * released is NULL, which must be > R0.
7269                  */
7270                 else if (register_is_null(&regs[meta.release_regno]))
7271                         err = 0;
7272                 if (err) {
7273                         verbose(env, "func %s#%d reference has not been acquired before\n",
7274                                 func_id_name(func_id), func_id);
7275                         return err;
7276                 }
7277         }
7278
7279         switch (func_id) {
7280         case BPF_FUNC_tail_call:
7281                 err = check_reference_leak(env);
7282                 if (err) {
7283                         verbose(env, "tail_call would lead to reference leak\n");
7284                         return err;
7285                 }
7286                 break;
7287         case BPF_FUNC_get_local_storage:
7288                 /* check that flags argument in get_local_storage(map, flags) is 0,
7289                  * this is required because get_local_storage() can't return an error.
7290                  */
7291                 if (!register_is_null(&regs[BPF_REG_2])) {
7292                         verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7293                         return -EINVAL;
7294                 }
7295                 break;
7296         case BPF_FUNC_for_each_map_elem:
7297                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7298                                         set_map_elem_callback_state);
7299                 break;
7300         case BPF_FUNC_timer_set_callback:
7301                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7302                                         set_timer_callback_state);
7303                 break;
7304         case BPF_FUNC_find_vma:
7305                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7306                                         set_find_vma_callback_state);
7307                 break;
7308         case BPF_FUNC_snprintf:
7309                 err = check_bpf_snprintf_call(env, regs);
7310                 break;
7311         case BPF_FUNC_loop:
7312                 update_loop_inline_state(env, meta.subprogno);
7313                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7314                                         set_loop_callback_state);
7315                 break;
7316         case BPF_FUNC_dynptr_from_mem:
7317                 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7318                         verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7319                                 reg_type_str(env, regs[BPF_REG_1].type));
7320                         return -EACCES;
7321                 }
7322                 break;
7323         case BPF_FUNC_set_retval:
7324                 if (env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7325                         if (!env->prog->aux->attach_func_proto->type) {
7326                                 /* Make sure programs that attach to void
7327                                  * hooks don't try to modify return value.
7328                                  */
7329                                 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7330                                 return -EINVAL;
7331                         }
7332                 }
7333                 break;
7334         }
7335
7336         if (err)
7337                 return err;
7338
7339         /* reset caller saved regs */
7340         for (i = 0; i < CALLER_SAVED_REGS; i++) {
7341                 mark_reg_not_init(env, regs, caller_saved[i]);
7342                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7343         }
7344
7345         /* helper call returns 64-bit value. */
7346         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7347
7348         /* update return register (already marked as written above) */
7349         ret_type = fn->ret_type;
7350         ret_flag = type_flag(fn->ret_type);
7351         if (ret_type == RET_INTEGER) {
7352                 /* sets type to SCALAR_VALUE */
7353                 mark_reg_unknown(env, regs, BPF_REG_0);
7354         } else if (ret_type == RET_VOID) {
7355                 regs[BPF_REG_0].type = NOT_INIT;
7356         } else if (base_type(ret_type) == RET_PTR_TO_MAP_VALUE) {
7357                 /* There is no offset yet applied, variable or fixed */
7358                 mark_reg_known_zero(env, regs, BPF_REG_0);
7359                 /* remember map_ptr, so that check_map_access()
7360                  * can check 'value_size' boundary of memory access
7361                  * to map element returned from bpf_map_lookup_elem()
7362                  */
7363                 if (meta.map_ptr == NULL) {
7364                         verbose(env,
7365                                 "kernel subsystem misconfigured verifier\n");
7366                         return -EINVAL;
7367                 }
7368                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
7369                 regs[BPF_REG_0].map_uid = meta.map_uid;
7370                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7371                 if (!type_may_be_null(ret_type) &&
7372                     map_value_has_spin_lock(meta.map_ptr)) {
7373                         regs[BPF_REG_0].id = ++env->id_gen;
7374                 }
7375         } else if (base_type(ret_type) == RET_PTR_TO_SOCKET) {
7376                 mark_reg_known_zero(env, regs, BPF_REG_0);
7377                 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7378         } else if (base_type(ret_type) == RET_PTR_TO_SOCK_COMMON) {
7379                 mark_reg_known_zero(env, regs, BPF_REG_0);
7380                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7381         } else if (base_type(ret_type) == RET_PTR_TO_TCP_SOCK) {
7382                 mark_reg_known_zero(env, regs, BPF_REG_0);
7383                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7384         } else if (base_type(ret_type) == RET_PTR_TO_ALLOC_MEM) {
7385                 mark_reg_known_zero(env, regs, BPF_REG_0);
7386                 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7387                 regs[BPF_REG_0].mem_size = meta.mem_size;
7388         } else if (base_type(ret_type) == RET_PTR_TO_MEM_OR_BTF_ID) {
7389                 const struct btf_type *t;
7390
7391                 mark_reg_known_zero(env, regs, BPF_REG_0);
7392                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7393                 if (!btf_type_is_struct(t)) {
7394                         u32 tsize;
7395                         const struct btf_type *ret;
7396                         const char *tname;
7397
7398                         /* resolve the type size of ksym. */
7399                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7400                         if (IS_ERR(ret)) {
7401                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7402                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
7403                                         tname, PTR_ERR(ret));
7404                                 return -EINVAL;
7405                         }
7406                         regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7407                         regs[BPF_REG_0].mem_size = tsize;
7408                 } else {
7409                         /* MEM_RDONLY may be carried from ret_flag, but it
7410                          * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7411                          * it will confuse the check of PTR_TO_BTF_ID in
7412                          * check_mem_access().
7413                          */
7414                         ret_flag &= ~MEM_RDONLY;
7415
7416                         regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7417                         regs[BPF_REG_0].btf = meta.ret_btf;
7418                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7419                 }
7420         } else if (base_type(ret_type) == RET_PTR_TO_BTF_ID) {
7421                 struct btf *ret_btf;
7422                 int ret_btf_id;
7423
7424                 mark_reg_known_zero(env, regs, BPF_REG_0);
7425                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7426                 if (func_id == BPF_FUNC_kptr_xchg) {
7427                         ret_btf = meta.kptr_off_desc->kptr.btf;
7428                         ret_btf_id = meta.kptr_off_desc->kptr.btf_id;
7429                 } else {
7430                         ret_btf = btf_vmlinux;
7431                         ret_btf_id = *fn->ret_btf_id;
7432                 }
7433                 if (ret_btf_id == 0) {
7434                         verbose(env, "invalid return type %u of func %s#%d\n",
7435                                 base_type(ret_type), func_id_name(func_id),
7436                                 func_id);
7437                         return -EINVAL;
7438                 }
7439                 regs[BPF_REG_0].btf = ret_btf;
7440                 regs[BPF_REG_0].btf_id = ret_btf_id;
7441         } else {
7442                 verbose(env, "unknown return type %u of func %s#%d\n",
7443                         base_type(ret_type), func_id_name(func_id), func_id);
7444                 return -EINVAL;
7445         }
7446
7447         if (type_may_be_null(regs[BPF_REG_0].type))
7448                 regs[BPF_REG_0].id = ++env->id_gen;
7449
7450         if (is_ptr_cast_function(func_id)) {
7451                 /* For release_reference() */
7452                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7453         } else if (is_acquire_function(func_id, meta.map_ptr)) {
7454                 int id = acquire_reference_state(env, insn_idx);
7455
7456                 if (id < 0)
7457                         return id;
7458                 /* For mark_ptr_or_null_reg() */
7459                 regs[BPF_REG_0].id = id;
7460                 /* For release_reference() */
7461                 regs[BPF_REG_0].ref_obj_id = id;
7462         } else if (func_id == BPF_FUNC_dynptr_data) {
7463                 int dynptr_id = 0, i;
7464
7465                 /* Find the id of the dynptr we're acquiring a reference to */
7466                 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7467                         if (arg_type_is_dynptr(fn->arg_type[i])) {
7468                                 if (dynptr_id) {
7469                                         verbose(env, "verifier internal error: multiple dynptr args in func\n");
7470                                         return -EFAULT;
7471                                 }
7472                                 dynptr_id = stack_slot_get_id(env, &regs[BPF_REG_1 + i]);
7473                         }
7474                 }
7475                 /* For release_reference() */
7476                 regs[BPF_REG_0].ref_obj_id = dynptr_id;
7477         }
7478
7479         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7480
7481         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7482         if (err)
7483                 return err;
7484
7485         if ((func_id == BPF_FUNC_get_stack ||
7486              func_id == BPF_FUNC_get_task_stack) &&
7487             !env->prog->has_callchain_buf) {
7488                 const char *err_str;
7489
7490 #ifdef CONFIG_PERF_EVENTS
7491                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
7492                 err_str = "cannot get callchain buffer for func %s#%d\n";
7493 #else
7494                 err = -ENOTSUPP;
7495                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7496 #endif
7497                 if (err) {
7498                         verbose(env, err_str, func_id_name(func_id), func_id);
7499                         return err;
7500                 }
7501
7502                 env->prog->has_callchain_buf = true;
7503         }
7504
7505         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7506                 env->prog->call_get_stack = true;
7507
7508         if (func_id == BPF_FUNC_get_func_ip) {
7509                 if (check_get_func_ip(env))
7510                         return -ENOTSUPP;
7511                 env->prog->call_get_func_ip = true;
7512         }
7513
7514         if (changes_data)
7515                 clear_all_pkt_pointers(env);
7516         return 0;
7517 }
7518
7519 /* mark_btf_func_reg_size() is used when the reg size is determined by
7520  * the BTF func_proto's return value size and argument.
7521  */
7522 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7523                                    size_t reg_size)
7524 {
7525         struct bpf_reg_state *reg = &cur_regs(env)[regno];
7526
7527         if (regno == BPF_REG_0) {
7528                 /* Function return value */
7529                 reg->live |= REG_LIVE_WRITTEN;
7530                 reg->subreg_def = reg_size == sizeof(u64) ?
7531                         DEF_NOT_SUBREG : env->insn_idx + 1;
7532         } else {
7533                 /* Function argument */
7534                 if (reg_size == sizeof(u64)) {
7535                         mark_insn_zext(env, reg);
7536                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7537                 } else {
7538                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7539                 }
7540         }
7541 }
7542
7543 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7544                             int *insn_idx_p)
7545 {
7546         const struct btf_type *t, *func, *func_proto, *ptr_type;
7547         struct bpf_reg_state *regs = cur_regs(env);
7548         const char *func_name, *ptr_type_name;
7549         u32 i, nargs, func_id, ptr_type_id;
7550         int err, insn_idx = *insn_idx_p;
7551         const struct btf_param *args;
7552         struct btf *desc_btf;
7553         bool acq;
7554
7555         /* skip for now, but return error when we find this in fixup_kfunc_call */
7556         if (!insn->imm)
7557                 return 0;
7558
7559         desc_btf = find_kfunc_desc_btf(env, insn->off);
7560         if (IS_ERR(desc_btf))
7561                 return PTR_ERR(desc_btf);
7562
7563         func_id = insn->imm;
7564         func = btf_type_by_id(desc_btf, func_id);
7565         func_name = btf_name_by_offset(desc_btf, func->name_off);
7566         func_proto = btf_type_by_id(desc_btf, func->type);
7567
7568         if (!btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog),
7569                                       BTF_KFUNC_TYPE_CHECK, func_id)) {
7570                 verbose(env, "calling kernel function %s is not allowed\n",
7571                         func_name);
7572                 return -EACCES;
7573         }
7574
7575         acq = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog),
7576                                         BTF_KFUNC_TYPE_ACQUIRE, func_id);
7577
7578         /* Check the arguments */
7579         err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs);
7580         if (err < 0)
7581                 return err;
7582         /* In case of release function, we get register number of refcounted
7583          * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
7584          */
7585         if (err) {
7586                 err = release_reference(env, regs[err].ref_obj_id);
7587                 if (err) {
7588                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
7589                                 func_name, func_id);
7590                         return err;
7591                 }
7592         }
7593
7594         for (i = 0; i < CALLER_SAVED_REGS; i++)
7595                 mark_reg_not_init(env, regs, caller_saved[i]);
7596
7597         /* Check return type */
7598         t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
7599
7600         if (acq && !btf_type_is_ptr(t)) {
7601                 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
7602                 return -EINVAL;
7603         }
7604
7605         if (btf_type_is_scalar(t)) {
7606                 mark_reg_unknown(env, regs, BPF_REG_0);
7607                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
7608         } else if (btf_type_is_ptr(t)) {
7609                 ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
7610                                                    &ptr_type_id);
7611                 if (!btf_type_is_struct(ptr_type)) {
7612                         ptr_type_name = btf_name_by_offset(desc_btf,
7613                                                            ptr_type->name_off);
7614                         verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
7615                                 func_name, btf_type_str(ptr_type),
7616                                 ptr_type_name);
7617                         return -EINVAL;
7618                 }
7619                 mark_reg_known_zero(env, regs, BPF_REG_0);
7620                 regs[BPF_REG_0].btf = desc_btf;
7621                 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
7622                 regs[BPF_REG_0].btf_id = ptr_type_id;
7623                 if (btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog),
7624                                               BTF_KFUNC_TYPE_RET_NULL, func_id)) {
7625                         regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
7626                         /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
7627                         regs[BPF_REG_0].id = ++env->id_gen;
7628                 }
7629                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
7630                 if (acq) {
7631                         int id = acquire_reference_state(env, insn_idx);
7632
7633                         if (id < 0)
7634                                 return id;
7635                         regs[BPF_REG_0].id = id;
7636                         regs[BPF_REG_0].ref_obj_id = id;
7637                 }
7638         } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
7639
7640         nargs = btf_type_vlen(func_proto);
7641         args = (const struct btf_param *)(func_proto + 1);
7642         for (i = 0; i < nargs; i++) {
7643                 u32 regno = i + 1;
7644
7645                 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
7646                 if (btf_type_is_ptr(t))
7647                         mark_btf_func_reg_size(env, regno, sizeof(void *));
7648                 else
7649                         /* scalar. ensured by btf_check_kfunc_arg_match() */
7650                         mark_btf_func_reg_size(env, regno, t->size);
7651         }
7652
7653         return 0;
7654 }
7655
7656 static bool signed_add_overflows(s64 a, s64 b)
7657 {
7658         /* Do the add in u64, where overflow is well-defined */
7659         s64 res = (s64)((u64)a + (u64)b);
7660
7661         if (b < 0)
7662                 return res > a;
7663         return res < a;
7664 }
7665
7666 static bool signed_add32_overflows(s32 a, s32 b)
7667 {
7668         /* Do the add in u32, where overflow is well-defined */
7669         s32 res = (s32)((u32)a + (u32)b);
7670
7671         if (b < 0)
7672                 return res > a;
7673         return res < a;
7674 }
7675
7676 static bool signed_sub_overflows(s64 a, s64 b)
7677 {
7678         /* Do the sub in u64, where overflow is well-defined */
7679         s64 res = (s64)((u64)a - (u64)b);
7680
7681         if (b < 0)
7682                 return res < a;
7683         return res > a;
7684 }
7685
7686 static bool signed_sub32_overflows(s32 a, s32 b)
7687 {
7688         /* Do the sub in u32, where overflow is well-defined */
7689         s32 res = (s32)((u32)a - (u32)b);
7690
7691         if (b < 0)
7692                 return res < a;
7693         return res > a;
7694 }
7695
7696 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
7697                                   const struct bpf_reg_state *reg,
7698                                   enum bpf_reg_type type)
7699 {
7700         bool known = tnum_is_const(reg->var_off);
7701         s64 val = reg->var_off.value;
7702         s64 smin = reg->smin_value;
7703
7704         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
7705                 verbose(env, "math between %s pointer and %lld is not allowed\n",
7706                         reg_type_str(env, type), val);
7707                 return false;
7708         }
7709
7710         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
7711                 verbose(env, "%s pointer offset %d is not allowed\n",
7712                         reg_type_str(env, type), reg->off);
7713                 return false;
7714         }
7715
7716         if (smin == S64_MIN) {
7717                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
7718                         reg_type_str(env, type));
7719                 return false;
7720         }
7721
7722         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
7723                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
7724                         smin, reg_type_str(env, type));
7725                 return false;
7726         }
7727
7728         return true;
7729 }
7730
7731 enum {
7732         REASON_BOUNDS   = -1,
7733         REASON_TYPE     = -2,
7734         REASON_PATHS    = -3,
7735         REASON_LIMIT    = -4,
7736         REASON_STACK    = -5,
7737 };
7738
7739 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
7740                               u32 *alu_limit, bool mask_to_left)
7741 {
7742         u32 max = 0, ptr_limit = 0;
7743
7744         switch (ptr_reg->type) {
7745         case PTR_TO_STACK:
7746                 /* Offset 0 is out-of-bounds, but acceptable start for the
7747                  * left direction, see BPF_REG_FP. Also, unknown scalar
7748                  * offset where we would need to deal with min/max bounds is
7749                  * currently prohibited for unprivileged.
7750                  */
7751                 max = MAX_BPF_STACK + mask_to_left;
7752                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
7753                 break;
7754         case PTR_TO_MAP_VALUE:
7755                 max = ptr_reg->map_ptr->value_size;
7756                 ptr_limit = (mask_to_left ?
7757                              ptr_reg->smin_value :
7758                              ptr_reg->umax_value) + ptr_reg->off;
7759                 break;
7760         default:
7761                 return REASON_TYPE;
7762         }
7763
7764         if (ptr_limit >= max)
7765                 return REASON_LIMIT;
7766         *alu_limit = ptr_limit;
7767         return 0;
7768 }
7769
7770 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7771                                     const struct bpf_insn *insn)
7772 {
7773         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
7774 }
7775
7776 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7777                                        u32 alu_state, u32 alu_limit)
7778 {
7779         /* If we arrived here from different branches with different
7780          * state or limits to sanitize, then this won't work.
7781          */
7782         if (aux->alu_state &&
7783             (aux->alu_state != alu_state ||
7784              aux->alu_limit != alu_limit))
7785                 return REASON_PATHS;
7786
7787         /* Corresponding fixup done in do_misc_fixups(). */
7788         aux->alu_state = alu_state;
7789         aux->alu_limit = alu_limit;
7790         return 0;
7791 }
7792
7793 static int sanitize_val_alu(struct bpf_verifier_env *env,
7794                             struct bpf_insn *insn)
7795 {
7796         struct bpf_insn_aux_data *aux = cur_aux(env);
7797
7798         if (can_skip_alu_sanitation(env, insn))
7799                 return 0;
7800
7801         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
7802 }
7803
7804 static bool sanitize_needed(u8 opcode)
7805 {
7806         return opcode == BPF_ADD || opcode == BPF_SUB;
7807 }
7808
7809 struct bpf_sanitize_info {
7810         struct bpf_insn_aux_data aux;
7811         bool mask_to_left;
7812 };
7813
7814 static struct bpf_verifier_state *
7815 sanitize_speculative_path(struct bpf_verifier_env *env,
7816                           const struct bpf_insn *insn,
7817                           u32 next_idx, u32 curr_idx)
7818 {
7819         struct bpf_verifier_state *branch;
7820         struct bpf_reg_state *regs;
7821
7822         branch = push_stack(env, next_idx, curr_idx, true);
7823         if (branch && insn) {
7824                 regs = branch->frame[branch->curframe]->regs;
7825                 if (BPF_SRC(insn->code) == BPF_K) {
7826                         mark_reg_unknown(env, regs, insn->dst_reg);
7827                 } else if (BPF_SRC(insn->code) == BPF_X) {
7828                         mark_reg_unknown(env, regs, insn->dst_reg);
7829                         mark_reg_unknown(env, regs, insn->src_reg);
7830                 }
7831         }
7832         return branch;
7833 }
7834
7835 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
7836                             struct bpf_insn *insn,
7837                             const struct bpf_reg_state *ptr_reg,
7838                             const struct bpf_reg_state *off_reg,
7839                             struct bpf_reg_state *dst_reg,
7840                             struct bpf_sanitize_info *info,
7841                             const bool commit_window)
7842 {
7843         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
7844         struct bpf_verifier_state *vstate = env->cur_state;
7845         bool off_is_imm = tnum_is_const(off_reg->var_off);
7846         bool off_is_neg = off_reg->smin_value < 0;
7847         bool ptr_is_dst_reg = ptr_reg == dst_reg;
7848         u8 opcode = BPF_OP(insn->code);
7849         u32 alu_state, alu_limit;
7850         struct bpf_reg_state tmp;
7851         bool ret;
7852         int err;
7853
7854         if (can_skip_alu_sanitation(env, insn))
7855                 return 0;
7856
7857         /* We already marked aux for masking from non-speculative
7858          * paths, thus we got here in the first place. We only care
7859          * to explore bad access from here.
7860          */
7861         if (vstate->speculative)
7862                 goto do_sim;
7863
7864         if (!commit_window) {
7865                 if (!tnum_is_const(off_reg->var_off) &&
7866                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
7867                         return REASON_BOUNDS;
7868
7869                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
7870                                      (opcode == BPF_SUB && !off_is_neg);
7871         }
7872
7873         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
7874         if (err < 0)
7875                 return err;
7876
7877         if (commit_window) {
7878                 /* In commit phase we narrow the masking window based on
7879                  * the observed pointer move after the simulated operation.
7880                  */
7881                 alu_state = info->aux.alu_state;
7882                 alu_limit = abs(info->aux.alu_limit - alu_limit);
7883         } else {
7884                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
7885                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
7886                 alu_state |= ptr_is_dst_reg ?
7887                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
7888
7889                 /* Limit pruning on unknown scalars to enable deep search for
7890                  * potential masking differences from other program paths.
7891                  */
7892                 if (!off_is_imm)
7893                         env->explore_alu_limits = true;
7894         }
7895
7896         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
7897         if (err < 0)
7898                 return err;
7899 do_sim:
7900         /* If we're in commit phase, we're done here given we already
7901          * pushed the truncated dst_reg into the speculative verification
7902          * stack.
7903          *
7904          * Also, when register is a known constant, we rewrite register-based
7905          * operation to immediate-based, and thus do not need masking (and as
7906          * a consequence, do not need to simulate the zero-truncation either).
7907          */
7908         if (commit_window || off_is_imm)
7909                 return 0;
7910
7911         /* Simulate and find potential out-of-bounds access under
7912          * speculative execution from truncation as a result of
7913          * masking when off was not within expected range. If off
7914          * sits in dst, then we temporarily need to move ptr there
7915          * to simulate dst (== 0) +/-= ptr. Needed, for example,
7916          * for cases where we use K-based arithmetic in one direction
7917          * and truncated reg-based in the other in order to explore
7918          * bad access.
7919          */
7920         if (!ptr_is_dst_reg) {
7921                 tmp = *dst_reg;
7922                 *dst_reg = *ptr_reg;
7923         }
7924         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
7925                                         env->insn_idx);
7926         if (!ptr_is_dst_reg && ret)
7927                 *dst_reg = tmp;
7928         return !ret ? REASON_STACK : 0;
7929 }
7930
7931 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
7932 {
7933         struct bpf_verifier_state *vstate = env->cur_state;
7934
7935         /* If we simulate paths under speculation, we don't update the
7936          * insn as 'seen' such that when we verify unreachable paths in
7937          * the non-speculative domain, sanitize_dead_code() can still
7938          * rewrite/sanitize them.
7939          */
7940         if (!vstate->speculative)
7941                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
7942 }
7943
7944 static int sanitize_err(struct bpf_verifier_env *env,
7945                         const struct bpf_insn *insn, int reason,
7946                         const struct bpf_reg_state *off_reg,
7947                         const struct bpf_reg_state *dst_reg)
7948 {
7949         static const char *err = "pointer arithmetic with it prohibited for !root";
7950         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
7951         u32 dst = insn->dst_reg, src = insn->src_reg;
7952
7953         switch (reason) {
7954         case REASON_BOUNDS:
7955                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
7956                         off_reg == dst_reg ? dst : src, err);
7957                 break;
7958         case REASON_TYPE:
7959                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
7960                         off_reg == dst_reg ? src : dst, err);
7961                 break;
7962         case REASON_PATHS:
7963                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
7964                         dst, op, err);
7965                 break;
7966         case REASON_LIMIT:
7967                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
7968                         dst, op, err);
7969                 break;
7970         case REASON_STACK:
7971                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
7972                         dst, err);
7973                 break;
7974         default:
7975                 verbose(env, "verifier internal error: unknown reason (%d)\n",
7976                         reason);
7977                 break;
7978         }
7979
7980         return -EACCES;
7981 }
7982
7983 /* check that stack access falls within stack limits and that 'reg' doesn't
7984  * have a variable offset.
7985  *
7986  * Variable offset is prohibited for unprivileged mode for simplicity since it
7987  * requires corresponding support in Spectre masking for stack ALU.  See also
7988  * retrieve_ptr_limit().
7989  *
7990  *
7991  * 'off' includes 'reg->off'.
7992  */
7993 static int check_stack_access_for_ptr_arithmetic(
7994                                 struct bpf_verifier_env *env,
7995                                 int regno,
7996                                 const struct bpf_reg_state *reg,
7997                                 int off)
7998 {
7999         if (!tnum_is_const(reg->var_off)) {
8000                 char tn_buf[48];
8001
8002                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8003                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
8004                         regno, tn_buf, off);
8005                 return -EACCES;
8006         }
8007
8008         if (off >= 0 || off < -MAX_BPF_STACK) {
8009                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
8010                         "prohibited for !root; off=%d\n", regno, off);
8011                 return -EACCES;
8012         }
8013
8014         return 0;
8015 }
8016
8017 static int sanitize_check_bounds(struct bpf_verifier_env *env,
8018                                  const struct bpf_insn *insn,
8019                                  const struct bpf_reg_state *dst_reg)
8020 {
8021         u32 dst = insn->dst_reg;
8022
8023         /* For unprivileged we require that resulting offset must be in bounds
8024          * in order to be able to sanitize access later on.
8025          */
8026         if (env->bypass_spec_v1)
8027                 return 0;
8028
8029         switch (dst_reg->type) {
8030         case PTR_TO_STACK:
8031                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
8032                                         dst_reg->off + dst_reg->var_off.value))
8033                         return -EACCES;
8034                 break;
8035         case PTR_TO_MAP_VALUE:
8036                 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
8037                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
8038                                 "prohibited for !root\n", dst);
8039                         return -EACCES;
8040                 }
8041                 break;
8042         default:
8043                 break;
8044         }
8045
8046         return 0;
8047 }
8048
8049 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
8050  * Caller should also handle BPF_MOV case separately.
8051  * If we return -EACCES, caller may want to try again treating pointer as a
8052  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
8053  */
8054 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
8055                                    struct bpf_insn *insn,
8056                                    const struct bpf_reg_state *ptr_reg,
8057                                    const struct bpf_reg_state *off_reg)
8058 {
8059         struct bpf_verifier_state *vstate = env->cur_state;
8060         struct bpf_func_state *state = vstate->frame[vstate->curframe];
8061         struct bpf_reg_state *regs = state->regs, *dst_reg;
8062         bool known = tnum_is_const(off_reg->var_off);
8063         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
8064             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
8065         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
8066             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
8067         struct bpf_sanitize_info info = {};
8068         u8 opcode = BPF_OP(insn->code);
8069         u32 dst = insn->dst_reg;
8070         int ret;
8071
8072         dst_reg = &regs[dst];
8073
8074         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
8075             smin_val > smax_val || umin_val > umax_val) {
8076                 /* Taint dst register if offset had invalid bounds derived from
8077                  * e.g. dead branches.
8078                  */
8079                 __mark_reg_unknown(env, dst_reg);
8080                 return 0;
8081         }
8082
8083         if (BPF_CLASS(insn->code) != BPF_ALU64) {
8084                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
8085                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8086                         __mark_reg_unknown(env, dst_reg);
8087                         return 0;
8088                 }
8089
8090                 verbose(env,
8091                         "R%d 32-bit pointer arithmetic prohibited\n",
8092                         dst);
8093                 return -EACCES;
8094         }
8095
8096         if (ptr_reg->type & PTR_MAYBE_NULL) {
8097                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
8098                         dst, reg_type_str(env, ptr_reg->type));
8099                 return -EACCES;
8100         }
8101
8102         switch (base_type(ptr_reg->type)) {
8103         case CONST_PTR_TO_MAP:
8104                 /* smin_val represents the known value */
8105                 if (known && smin_val == 0 && opcode == BPF_ADD)
8106                         break;
8107                 fallthrough;
8108         case PTR_TO_PACKET_END:
8109         case PTR_TO_SOCKET:
8110         case PTR_TO_SOCK_COMMON:
8111         case PTR_TO_TCP_SOCK:
8112         case PTR_TO_XDP_SOCK:
8113                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
8114                         dst, reg_type_str(env, ptr_reg->type));
8115                 return -EACCES;
8116         default:
8117                 break;
8118         }
8119
8120         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
8121          * The id may be overwritten later if we create a new variable offset.
8122          */
8123         dst_reg->type = ptr_reg->type;
8124         dst_reg->id = ptr_reg->id;
8125
8126         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
8127             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
8128                 return -EINVAL;
8129
8130         /* pointer types do not carry 32-bit bounds at the moment. */
8131         __mark_reg32_unbounded(dst_reg);
8132
8133         if (sanitize_needed(opcode)) {
8134                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
8135                                        &info, false);
8136                 if (ret < 0)
8137                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
8138         }
8139
8140         switch (opcode) {
8141         case BPF_ADD:
8142                 /* We can take a fixed offset as long as it doesn't overflow
8143                  * the s32 'off' field
8144                  */
8145                 if (known && (ptr_reg->off + smin_val ==
8146                               (s64)(s32)(ptr_reg->off + smin_val))) {
8147                         /* pointer += K.  Accumulate it into fixed offset */
8148                         dst_reg->smin_value = smin_ptr;
8149                         dst_reg->smax_value = smax_ptr;
8150                         dst_reg->umin_value = umin_ptr;
8151                         dst_reg->umax_value = umax_ptr;
8152                         dst_reg->var_off = ptr_reg->var_off;
8153                         dst_reg->off = ptr_reg->off + smin_val;
8154                         dst_reg->raw = ptr_reg->raw;
8155                         break;
8156                 }
8157                 /* A new variable offset is created.  Note that off_reg->off
8158                  * == 0, since it's a scalar.
8159                  * dst_reg gets the pointer type and since some positive
8160                  * integer value was added to the pointer, give it a new 'id'
8161                  * if it's a PTR_TO_PACKET.
8162                  * this creates a new 'base' pointer, off_reg (variable) gets
8163                  * added into the variable offset, and we copy the fixed offset
8164                  * from ptr_reg.
8165                  */
8166                 if (signed_add_overflows(smin_ptr, smin_val) ||
8167                     signed_add_overflows(smax_ptr, smax_val)) {
8168                         dst_reg->smin_value = S64_MIN;
8169                         dst_reg->smax_value = S64_MAX;
8170                 } else {
8171                         dst_reg->smin_value = smin_ptr + smin_val;
8172                         dst_reg->smax_value = smax_ptr + smax_val;
8173                 }
8174                 if (umin_ptr + umin_val < umin_ptr ||
8175                     umax_ptr + umax_val < umax_ptr) {
8176                         dst_reg->umin_value = 0;
8177                         dst_reg->umax_value = U64_MAX;
8178                 } else {
8179                         dst_reg->umin_value = umin_ptr + umin_val;
8180                         dst_reg->umax_value = umax_ptr + umax_val;
8181                 }
8182                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
8183                 dst_reg->off = ptr_reg->off;
8184                 dst_reg->raw = ptr_reg->raw;
8185                 if (reg_is_pkt_pointer(ptr_reg)) {
8186                         dst_reg->id = ++env->id_gen;
8187                         /* something was added to pkt_ptr, set range to zero */
8188                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8189                 }
8190                 break;
8191         case BPF_SUB:
8192                 if (dst_reg == off_reg) {
8193                         /* scalar -= pointer.  Creates an unknown scalar */
8194                         verbose(env, "R%d tried to subtract pointer from scalar\n",
8195                                 dst);
8196                         return -EACCES;
8197                 }
8198                 /* We don't allow subtraction from FP, because (according to
8199                  * test_verifier.c test "invalid fp arithmetic", JITs might not
8200                  * be able to deal with it.
8201                  */
8202                 if (ptr_reg->type == PTR_TO_STACK) {
8203                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
8204                                 dst);
8205                         return -EACCES;
8206                 }
8207                 if (known && (ptr_reg->off - smin_val ==
8208                               (s64)(s32)(ptr_reg->off - smin_val))) {
8209                         /* pointer -= K.  Subtract it from fixed offset */
8210                         dst_reg->smin_value = smin_ptr;
8211                         dst_reg->smax_value = smax_ptr;
8212                         dst_reg->umin_value = umin_ptr;
8213                         dst_reg->umax_value = umax_ptr;
8214                         dst_reg->var_off = ptr_reg->var_off;
8215                         dst_reg->id = ptr_reg->id;
8216                         dst_reg->off = ptr_reg->off - smin_val;
8217                         dst_reg->raw = ptr_reg->raw;
8218                         break;
8219                 }
8220                 /* A new variable offset is created.  If the subtrahend is known
8221                  * nonnegative, then any reg->range we had before is still good.
8222                  */
8223                 if (signed_sub_overflows(smin_ptr, smax_val) ||
8224                     signed_sub_overflows(smax_ptr, smin_val)) {
8225                         /* Overflow possible, we know nothing */
8226                         dst_reg->smin_value = S64_MIN;
8227                         dst_reg->smax_value = S64_MAX;
8228                 } else {
8229                         dst_reg->smin_value = smin_ptr - smax_val;
8230                         dst_reg->smax_value = smax_ptr - smin_val;
8231                 }
8232                 if (umin_ptr < umax_val) {
8233                         /* Overflow possible, we know nothing */
8234                         dst_reg->umin_value = 0;
8235                         dst_reg->umax_value = U64_MAX;
8236                 } else {
8237                         /* Cannot overflow (as long as bounds are consistent) */
8238                         dst_reg->umin_value = umin_ptr - umax_val;
8239                         dst_reg->umax_value = umax_ptr - umin_val;
8240                 }
8241                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
8242                 dst_reg->off = ptr_reg->off;
8243                 dst_reg->raw = ptr_reg->raw;
8244                 if (reg_is_pkt_pointer(ptr_reg)) {
8245                         dst_reg->id = ++env->id_gen;
8246                         /* something was added to pkt_ptr, set range to zero */
8247                         if (smin_val < 0)
8248                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8249                 }
8250                 break;
8251         case BPF_AND:
8252         case BPF_OR:
8253         case BPF_XOR:
8254                 /* bitwise ops on pointers are troublesome, prohibit. */
8255                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
8256                         dst, bpf_alu_string[opcode >> 4]);
8257                 return -EACCES;
8258         default:
8259                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
8260                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
8261                         dst, bpf_alu_string[opcode >> 4]);
8262                 return -EACCES;
8263         }
8264
8265         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
8266                 return -EINVAL;
8267         reg_bounds_sync(dst_reg);
8268         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
8269                 return -EACCES;
8270         if (sanitize_needed(opcode)) {
8271                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
8272                                        &info, true);
8273                 if (ret < 0)
8274                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
8275         }
8276
8277         return 0;
8278 }
8279
8280 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
8281                                  struct bpf_reg_state *src_reg)
8282 {
8283         s32 smin_val = src_reg->s32_min_value;
8284         s32 smax_val = src_reg->s32_max_value;
8285         u32 umin_val = src_reg->u32_min_value;
8286         u32 umax_val = src_reg->u32_max_value;
8287
8288         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
8289             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
8290                 dst_reg->s32_min_value = S32_MIN;
8291                 dst_reg->s32_max_value = S32_MAX;
8292         } else {
8293                 dst_reg->s32_min_value += smin_val;
8294                 dst_reg->s32_max_value += smax_val;
8295         }
8296         if (dst_reg->u32_min_value + umin_val < umin_val ||
8297             dst_reg->u32_max_value + umax_val < umax_val) {
8298                 dst_reg->u32_min_value = 0;
8299                 dst_reg->u32_max_value = U32_MAX;
8300         } else {
8301                 dst_reg->u32_min_value += umin_val;
8302                 dst_reg->u32_max_value += umax_val;
8303         }
8304 }
8305
8306 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
8307                                struct bpf_reg_state *src_reg)
8308 {
8309         s64 smin_val = src_reg->smin_value;
8310         s64 smax_val = src_reg->smax_value;
8311         u64 umin_val = src_reg->umin_value;
8312         u64 umax_val = src_reg->umax_value;
8313
8314         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
8315             signed_add_overflows(dst_reg->smax_value, smax_val)) {
8316                 dst_reg->smin_value = S64_MIN;
8317                 dst_reg->smax_value = S64_MAX;
8318         } else {
8319                 dst_reg->smin_value += smin_val;
8320                 dst_reg->smax_value += smax_val;
8321         }
8322         if (dst_reg->umin_value + umin_val < umin_val ||
8323             dst_reg->umax_value + umax_val < umax_val) {
8324                 dst_reg->umin_value = 0;
8325                 dst_reg->umax_value = U64_MAX;
8326         } else {
8327                 dst_reg->umin_value += umin_val;
8328                 dst_reg->umax_value += umax_val;
8329         }
8330 }
8331
8332 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
8333                                  struct bpf_reg_state *src_reg)
8334 {
8335         s32 smin_val = src_reg->s32_min_value;
8336         s32 smax_val = src_reg->s32_max_value;
8337         u32 umin_val = src_reg->u32_min_value;
8338         u32 umax_val = src_reg->u32_max_value;
8339
8340         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
8341             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
8342                 /* Overflow possible, we know nothing */
8343                 dst_reg->s32_min_value = S32_MIN;
8344                 dst_reg->s32_max_value = S32_MAX;
8345         } else {
8346                 dst_reg->s32_min_value -= smax_val;
8347                 dst_reg->s32_max_value -= smin_val;
8348         }
8349         if (dst_reg->u32_min_value < umax_val) {
8350                 /* Overflow possible, we know nothing */
8351                 dst_reg->u32_min_value = 0;
8352                 dst_reg->u32_max_value = U32_MAX;
8353         } else {
8354                 /* Cannot overflow (as long as bounds are consistent) */
8355                 dst_reg->u32_min_value -= umax_val;
8356                 dst_reg->u32_max_value -= umin_val;
8357         }
8358 }
8359
8360 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
8361                                struct bpf_reg_state *src_reg)
8362 {
8363         s64 smin_val = src_reg->smin_value;
8364         s64 smax_val = src_reg->smax_value;
8365         u64 umin_val = src_reg->umin_value;
8366         u64 umax_val = src_reg->umax_value;
8367
8368         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
8369             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
8370                 /* Overflow possible, we know nothing */
8371                 dst_reg->smin_value = S64_MIN;
8372                 dst_reg->smax_value = S64_MAX;
8373         } else {
8374                 dst_reg->smin_value -= smax_val;
8375                 dst_reg->smax_value -= smin_val;
8376         }
8377         if (dst_reg->umin_value < umax_val) {
8378                 /* Overflow possible, we know nothing */
8379                 dst_reg->umin_value = 0;
8380                 dst_reg->umax_value = U64_MAX;
8381         } else {
8382                 /* Cannot overflow (as long as bounds are consistent) */
8383                 dst_reg->umin_value -= umax_val;
8384                 dst_reg->umax_value -= umin_val;
8385         }
8386 }
8387
8388 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
8389                                  struct bpf_reg_state *src_reg)
8390 {
8391         s32 smin_val = src_reg->s32_min_value;
8392         u32 umin_val = src_reg->u32_min_value;
8393         u32 umax_val = src_reg->u32_max_value;
8394
8395         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
8396                 /* Ain't nobody got time to multiply that sign */
8397                 __mark_reg32_unbounded(dst_reg);
8398                 return;
8399         }
8400         /* Both values are positive, so we can work with unsigned and
8401          * copy the result to signed (unless it exceeds S32_MAX).
8402          */
8403         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
8404                 /* Potential overflow, we know nothing */
8405                 __mark_reg32_unbounded(dst_reg);
8406                 return;
8407         }
8408         dst_reg->u32_min_value *= umin_val;
8409         dst_reg->u32_max_value *= umax_val;
8410         if (dst_reg->u32_max_value > S32_MAX) {
8411                 /* Overflow possible, we know nothing */
8412                 dst_reg->s32_min_value = S32_MIN;
8413                 dst_reg->s32_max_value = S32_MAX;
8414         } else {
8415                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8416                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8417         }
8418 }
8419
8420 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
8421                                struct bpf_reg_state *src_reg)
8422 {
8423         s64 smin_val = src_reg->smin_value;
8424         u64 umin_val = src_reg->umin_value;
8425         u64 umax_val = src_reg->umax_value;
8426
8427         if (smin_val < 0 || dst_reg->smin_value < 0) {
8428                 /* Ain't nobody got time to multiply that sign */
8429                 __mark_reg64_unbounded(dst_reg);
8430                 return;
8431         }
8432         /* Both values are positive, so we can work with unsigned and
8433          * copy the result to signed (unless it exceeds S64_MAX).
8434          */
8435         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
8436                 /* Potential overflow, we know nothing */
8437                 __mark_reg64_unbounded(dst_reg);
8438                 return;
8439         }
8440         dst_reg->umin_value *= umin_val;
8441         dst_reg->umax_value *= umax_val;
8442         if (dst_reg->umax_value > S64_MAX) {
8443                 /* Overflow possible, we know nothing */
8444                 dst_reg->smin_value = S64_MIN;
8445                 dst_reg->smax_value = S64_MAX;
8446         } else {
8447                 dst_reg->smin_value = dst_reg->umin_value;
8448                 dst_reg->smax_value = dst_reg->umax_value;
8449         }
8450 }
8451
8452 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
8453                                  struct bpf_reg_state *src_reg)
8454 {
8455         bool src_known = tnum_subreg_is_const(src_reg->var_off);
8456         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8457         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8458         s32 smin_val = src_reg->s32_min_value;
8459         u32 umax_val = src_reg->u32_max_value;
8460
8461         if (src_known && dst_known) {
8462                 __mark_reg32_known(dst_reg, var32_off.value);
8463                 return;
8464         }
8465
8466         /* We get our minimum from the var_off, since that's inherently
8467          * bitwise.  Our maximum is the minimum of the operands' maxima.
8468          */
8469         dst_reg->u32_min_value = var32_off.value;
8470         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
8471         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8472                 /* Lose signed bounds when ANDing negative numbers,
8473                  * ain't nobody got time for that.
8474                  */
8475                 dst_reg->s32_min_value = S32_MIN;
8476                 dst_reg->s32_max_value = S32_MAX;
8477         } else {
8478                 /* ANDing two positives gives a positive, so safe to
8479                  * cast result into s64.
8480                  */
8481                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8482                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8483         }
8484 }
8485
8486 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
8487                                struct bpf_reg_state *src_reg)
8488 {
8489         bool src_known = tnum_is_const(src_reg->var_off);
8490         bool dst_known = tnum_is_const(dst_reg->var_off);
8491         s64 smin_val = src_reg->smin_value;
8492         u64 umax_val = src_reg->umax_value;
8493
8494         if (src_known && dst_known) {
8495                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8496                 return;
8497         }
8498
8499         /* We get our minimum from the var_off, since that's inherently
8500          * bitwise.  Our maximum is the minimum of the operands' maxima.
8501          */
8502         dst_reg->umin_value = dst_reg->var_off.value;
8503         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
8504         if (dst_reg->smin_value < 0 || smin_val < 0) {
8505                 /* Lose signed bounds when ANDing negative numbers,
8506                  * ain't nobody got time for that.
8507                  */
8508                 dst_reg->smin_value = S64_MIN;
8509                 dst_reg->smax_value = S64_MAX;
8510         } else {
8511                 /* ANDing two positives gives a positive, so safe to
8512                  * cast result into s64.
8513                  */
8514                 dst_reg->smin_value = dst_reg->umin_value;
8515                 dst_reg->smax_value = dst_reg->umax_value;
8516         }
8517         /* We may learn something more from the var_off */
8518         __update_reg_bounds(dst_reg);
8519 }
8520
8521 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
8522                                 struct bpf_reg_state *src_reg)
8523 {
8524         bool src_known = tnum_subreg_is_const(src_reg->var_off);
8525         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8526         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8527         s32 smin_val = src_reg->s32_min_value;
8528         u32 umin_val = src_reg->u32_min_value;
8529
8530         if (src_known && dst_known) {
8531                 __mark_reg32_known(dst_reg, var32_off.value);
8532                 return;
8533         }
8534
8535         /* We get our maximum from the var_off, and our minimum is the
8536          * maximum of the operands' minima
8537          */
8538         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
8539         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8540         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8541                 /* Lose signed bounds when ORing negative numbers,
8542                  * ain't nobody got time for that.
8543                  */
8544                 dst_reg->s32_min_value = S32_MIN;
8545                 dst_reg->s32_max_value = S32_MAX;
8546         } else {
8547                 /* ORing two positives gives a positive, so safe to
8548                  * cast result into s64.
8549                  */
8550                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8551                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8552         }
8553 }
8554
8555 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
8556                               struct bpf_reg_state *src_reg)
8557 {
8558         bool src_known = tnum_is_const(src_reg->var_off);
8559         bool dst_known = tnum_is_const(dst_reg->var_off);
8560         s64 smin_val = src_reg->smin_value;
8561         u64 umin_val = src_reg->umin_value;
8562
8563         if (src_known && dst_known) {
8564                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8565                 return;
8566         }
8567
8568         /* We get our maximum from the var_off, and our minimum is the
8569          * maximum of the operands' minima
8570          */
8571         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
8572         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8573         if (dst_reg->smin_value < 0 || smin_val < 0) {
8574                 /* Lose signed bounds when ORing negative numbers,
8575                  * ain't nobody got time for that.
8576                  */
8577                 dst_reg->smin_value = S64_MIN;
8578                 dst_reg->smax_value = S64_MAX;
8579         } else {
8580                 /* ORing two positives gives a positive, so safe to
8581                  * cast result into s64.
8582                  */
8583                 dst_reg->smin_value = dst_reg->umin_value;
8584                 dst_reg->smax_value = dst_reg->umax_value;
8585         }
8586         /* We may learn something more from the var_off */
8587         __update_reg_bounds(dst_reg);
8588 }
8589
8590 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
8591                                  struct bpf_reg_state *src_reg)
8592 {
8593         bool src_known = tnum_subreg_is_const(src_reg->var_off);
8594         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8595         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8596         s32 smin_val = src_reg->s32_min_value;
8597
8598         if (src_known && dst_known) {
8599                 __mark_reg32_known(dst_reg, var32_off.value);
8600                 return;
8601         }
8602
8603         /* We get both minimum and maximum from the var32_off. */
8604         dst_reg->u32_min_value = var32_off.value;
8605         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8606
8607         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
8608                 /* XORing two positive sign numbers gives a positive,
8609                  * so safe to cast u32 result into s32.
8610                  */
8611                 dst_reg->s32_min_value = dst_reg->u32_min_value;
8612                 dst_reg->s32_max_value = dst_reg->u32_max_value;
8613         } else {
8614                 dst_reg->s32_min_value = S32_MIN;
8615                 dst_reg->s32_max_value = S32_MAX;
8616         }
8617 }
8618
8619 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
8620                                struct bpf_reg_state *src_reg)
8621 {
8622         bool src_known = tnum_is_const(src_reg->var_off);
8623         bool dst_known = tnum_is_const(dst_reg->var_off);
8624         s64 smin_val = src_reg->smin_value;
8625
8626         if (src_known && dst_known) {
8627                 /* dst_reg->var_off.value has been updated earlier */
8628                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8629                 return;
8630         }
8631
8632         /* We get both minimum and maximum from the var_off. */
8633         dst_reg->umin_value = dst_reg->var_off.value;
8634         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
8635
8636         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
8637                 /* XORing two positive sign numbers gives a positive,
8638                  * so safe to cast u64 result into s64.
8639                  */
8640                 dst_reg->smin_value = dst_reg->umin_value;
8641                 dst_reg->smax_value = dst_reg->umax_value;
8642         } else {
8643                 dst_reg->smin_value = S64_MIN;
8644                 dst_reg->smax_value = S64_MAX;
8645         }
8646
8647         __update_reg_bounds(dst_reg);
8648 }
8649
8650 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8651                                    u64 umin_val, u64 umax_val)
8652 {
8653         /* We lose all sign bit information (except what we can pick
8654          * up from var_off)
8655          */
8656         dst_reg->s32_min_value = S32_MIN;
8657         dst_reg->s32_max_value = S32_MAX;
8658         /* If we might shift our top bit out, then we know nothing */
8659         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
8660                 dst_reg->u32_min_value = 0;
8661                 dst_reg->u32_max_value = U32_MAX;
8662         } else {
8663                 dst_reg->u32_min_value <<= umin_val;
8664                 dst_reg->u32_max_value <<= umax_val;
8665         }
8666 }
8667
8668 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
8669                                  struct bpf_reg_state *src_reg)
8670 {
8671         u32 umax_val = src_reg->u32_max_value;
8672         u32 umin_val = src_reg->u32_min_value;
8673         /* u32 alu operation will zext upper bits */
8674         struct tnum subreg = tnum_subreg(dst_reg->var_off);
8675
8676         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8677         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
8678         /* Not required but being careful mark reg64 bounds as unknown so
8679          * that we are forced to pick them up from tnum and zext later and
8680          * if some path skips this step we are still safe.
8681          */
8682         __mark_reg64_unbounded(dst_reg);
8683         __update_reg32_bounds(dst_reg);
8684 }
8685
8686 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
8687                                    u64 umin_val, u64 umax_val)
8688 {
8689         /* Special case <<32 because it is a common compiler pattern to sign
8690          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
8691          * positive we know this shift will also be positive so we can track
8692          * bounds correctly. Otherwise we lose all sign bit information except
8693          * what we can pick up from var_off. Perhaps we can generalize this
8694          * later to shifts of any length.
8695          */
8696         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
8697                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
8698         else
8699                 dst_reg->smax_value = S64_MAX;
8700
8701         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
8702                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
8703         else
8704                 dst_reg->smin_value = S64_MIN;
8705
8706         /* If we might shift our top bit out, then we know nothing */
8707         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
8708                 dst_reg->umin_value = 0;
8709                 dst_reg->umax_value = U64_MAX;
8710         } else {
8711                 dst_reg->umin_value <<= umin_val;
8712                 dst_reg->umax_value <<= umax_val;
8713         }
8714 }
8715
8716 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
8717                                struct bpf_reg_state *src_reg)
8718 {
8719         u64 umax_val = src_reg->umax_value;
8720         u64 umin_val = src_reg->umin_value;
8721
8722         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
8723         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
8724         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
8725
8726         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
8727         /* We may learn something more from the var_off */
8728         __update_reg_bounds(dst_reg);
8729 }
8730
8731 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
8732                                  struct bpf_reg_state *src_reg)
8733 {
8734         struct tnum subreg = tnum_subreg(dst_reg->var_off);
8735         u32 umax_val = src_reg->u32_max_value;
8736         u32 umin_val = src_reg->u32_min_value;
8737
8738         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8739          * be negative, then either:
8740          * 1) src_reg might be zero, so the sign bit of the result is
8741          *    unknown, so we lose our signed bounds
8742          * 2) it's known negative, thus the unsigned bounds capture the
8743          *    signed bounds
8744          * 3) the signed bounds cross zero, so they tell us nothing
8745          *    about the result
8746          * If the value in dst_reg is known nonnegative, then again the
8747          * unsigned bounds capture the signed bounds.
8748          * Thus, in all cases it suffices to blow away our signed bounds
8749          * and rely on inferring new ones from the unsigned bounds and
8750          * var_off of the result.
8751          */
8752         dst_reg->s32_min_value = S32_MIN;
8753         dst_reg->s32_max_value = S32_MAX;
8754
8755         dst_reg->var_off = tnum_rshift(subreg, umin_val);
8756         dst_reg->u32_min_value >>= umax_val;
8757         dst_reg->u32_max_value >>= umin_val;
8758
8759         __mark_reg64_unbounded(dst_reg);
8760         __update_reg32_bounds(dst_reg);
8761 }
8762
8763 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
8764                                struct bpf_reg_state *src_reg)
8765 {
8766         u64 umax_val = src_reg->umax_value;
8767         u64 umin_val = src_reg->umin_value;
8768
8769         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
8770          * be negative, then either:
8771          * 1) src_reg might be zero, so the sign bit of the result is
8772          *    unknown, so we lose our signed bounds
8773          * 2) it's known negative, thus the unsigned bounds capture the
8774          *    signed bounds
8775          * 3) the signed bounds cross zero, so they tell us nothing
8776          *    about the result
8777          * If the value in dst_reg is known nonnegative, then again the
8778          * unsigned bounds capture the signed bounds.
8779          * Thus, in all cases it suffices to blow away our signed bounds
8780          * and rely on inferring new ones from the unsigned bounds and
8781          * var_off of the result.
8782          */
8783         dst_reg->smin_value = S64_MIN;
8784         dst_reg->smax_value = S64_MAX;
8785         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8786         dst_reg->umin_value >>= umax_val;
8787         dst_reg->umax_value >>= umin_val;
8788
8789         /* Its not easy to operate on alu32 bounds here because it depends
8790          * on bits being shifted in. Take easy way out and mark unbounded
8791          * so we can recalculate later from tnum.
8792          */
8793         __mark_reg32_unbounded(dst_reg);
8794         __update_reg_bounds(dst_reg);
8795 }
8796
8797 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
8798                                   struct bpf_reg_state *src_reg)
8799 {
8800         u64 umin_val = src_reg->u32_min_value;
8801
8802         /* Upon reaching here, src_known is true and
8803          * umax_val is equal to umin_val.
8804          */
8805         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
8806         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
8807
8808         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
8809
8810         /* blow away the dst_reg umin_value/umax_value and rely on
8811          * dst_reg var_off to refine the result.
8812          */
8813         dst_reg->u32_min_value = 0;
8814         dst_reg->u32_max_value = U32_MAX;
8815
8816         __mark_reg64_unbounded(dst_reg);
8817         __update_reg32_bounds(dst_reg);
8818 }
8819
8820 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
8821                                 struct bpf_reg_state *src_reg)
8822 {
8823         u64 umin_val = src_reg->umin_value;
8824
8825         /* Upon reaching here, src_known is true and umax_val is equal
8826          * to umin_val.
8827          */
8828         dst_reg->smin_value >>= umin_val;
8829         dst_reg->smax_value >>= umin_val;
8830
8831         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
8832
8833         /* blow away the dst_reg umin_value/umax_value and rely on
8834          * dst_reg var_off to refine the result.
8835          */
8836         dst_reg->umin_value = 0;
8837         dst_reg->umax_value = U64_MAX;
8838
8839         /* Its not easy to operate on alu32 bounds here because it depends
8840          * on bits being shifted in from upper 32-bits. Take easy way out
8841          * and mark unbounded so we can recalculate later from tnum.
8842          */
8843         __mark_reg32_unbounded(dst_reg);
8844         __update_reg_bounds(dst_reg);
8845 }
8846
8847 /* WARNING: This function does calculations on 64-bit values, but the actual
8848  * execution may occur on 32-bit values. Therefore, things like bitshifts
8849  * need extra checks in the 32-bit case.
8850  */
8851 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
8852                                       struct bpf_insn *insn,
8853                                       struct bpf_reg_state *dst_reg,
8854                                       struct bpf_reg_state src_reg)
8855 {
8856         struct bpf_reg_state *regs = cur_regs(env);
8857         u8 opcode = BPF_OP(insn->code);
8858         bool src_known;
8859         s64 smin_val, smax_val;
8860         u64 umin_val, umax_val;
8861         s32 s32_min_val, s32_max_val;
8862         u32 u32_min_val, u32_max_val;
8863         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
8864         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
8865         int ret;
8866
8867         smin_val = src_reg.smin_value;
8868         smax_val = src_reg.smax_value;
8869         umin_val = src_reg.umin_value;
8870         umax_val = src_reg.umax_value;
8871
8872         s32_min_val = src_reg.s32_min_value;
8873         s32_max_val = src_reg.s32_max_value;
8874         u32_min_val = src_reg.u32_min_value;
8875         u32_max_val = src_reg.u32_max_value;
8876
8877         if (alu32) {
8878                 src_known = tnum_subreg_is_const(src_reg.var_off);
8879                 if ((src_known &&
8880                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
8881                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
8882                         /* Taint dst register if offset had invalid bounds
8883                          * derived from e.g. dead branches.
8884                          */
8885                         __mark_reg_unknown(env, dst_reg);
8886                         return 0;
8887                 }
8888         } else {
8889                 src_known = tnum_is_const(src_reg.var_off);
8890                 if ((src_known &&
8891                      (smin_val != smax_val || umin_val != umax_val)) ||
8892                     smin_val > smax_val || umin_val > umax_val) {
8893                         /* Taint dst register if offset had invalid bounds
8894                          * derived from e.g. dead branches.
8895                          */
8896                         __mark_reg_unknown(env, dst_reg);
8897                         return 0;
8898                 }
8899         }
8900
8901         if (!src_known &&
8902             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
8903                 __mark_reg_unknown(env, dst_reg);
8904                 return 0;
8905         }
8906
8907         if (sanitize_needed(opcode)) {
8908                 ret = sanitize_val_alu(env, insn);
8909                 if (ret < 0)
8910                         return sanitize_err(env, insn, ret, NULL, NULL);
8911         }
8912
8913         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
8914          * There are two classes of instructions: The first class we track both
8915          * alu32 and alu64 sign/unsigned bounds independently this provides the
8916          * greatest amount of precision when alu operations are mixed with jmp32
8917          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
8918          * and BPF_OR. This is possible because these ops have fairly easy to
8919          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
8920          * See alu32 verifier tests for examples. The second class of
8921          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
8922          * with regards to tracking sign/unsigned bounds because the bits may
8923          * cross subreg boundaries in the alu64 case. When this happens we mark
8924          * the reg unbounded in the subreg bound space and use the resulting
8925          * tnum to calculate an approximation of the sign/unsigned bounds.
8926          */
8927         switch (opcode) {
8928         case BPF_ADD:
8929                 scalar32_min_max_add(dst_reg, &src_reg);
8930                 scalar_min_max_add(dst_reg, &src_reg);
8931                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
8932                 break;
8933         case BPF_SUB:
8934                 scalar32_min_max_sub(dst_reg, &src_reg);
8935                 scalar_min_max_sub(dst_reg, &src_reg);
8936                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
8937                 break;
8938         case BPF_MUL:
8939                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
8940                 scalar32_min_max_mul(dst_reg, &src_reg);
8941                 scalar_min_max_mul(dst_reg, &src_reg);
8942                 break;
8943         case BPF_AND:
8944                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
8945                 scalar32_min_max_and(dst_reg, &src_reg);
8946                 scalar_min_max_and(dst_reg, &src_reg);
8947                 break;
8948         case BPF_OR:
8949                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
8950                 scalar32_min_max_or(dst_reg, &src_reg);
8951                 scalar_min_max_or(dst_reg, &src_reg);
8952                 break;
8953         case BPF_XOR:
8954                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
8955                 scalar32_min_max_xor(dst_reg, &src_reg);
8956                 scalar_min_max_xor(dst_reg, &src_reg);
8957                 break;
8958         case BPF_LSH:
8959                 if (umax_val >= insn_bitness) {
8960                         /* Shifts greater than 31 or 63 are undefined.
8961                          * This includes shifts by a negative number.
8962                          */
8963                         mark_reg_unknown(env, regs, insn->dst_reg);
8964                         break;
8965                 }
8966                 if (alu32)
8967                         scalar32_min_max_lsh(dst_reg, &src_reg);
8968                 else
8969                         scalar_min_max_lsh(dst_reg, &src_reg);
8970                 break;
8971         case BPF_RSH:
8972                 if (umax_val >= insn_bitness) {
8973                         /* Shifts greater than 31 or 63 are undefined.
8974                          * This includes shifts by a negative number.
8975                          */
8976                         mark_reg_unknown(env, regs, insn->dst_reg);
8977                         break;
8978                 }
8979                 if (alu32)
8980                         scalar32_min_max_rsh(dst_reg, &src_reg);
8981                 else
8982                         scalar_min_max_rsh(dst_reg, &src_reg);
8983                 break;
8984         case BPF_ARSH:
8985                 if (umax_val >= insn_bitness) {
8986                         /* Shifts greater than 31 or 63 are undefined.
8987                          * This includes shifts by a negative number.
8988                          */
8989                         mark_reg_unknown(env, regs, insn->dst_reg);
8990                         break;
8991                 }
8992                 if (alu32)
8993                         scalar32_min_max_arsh(dst_reg, &src_reg);
8994                 else
8995                         scalar_min_max_arsh(dst_reg, &src_reg);
8996                 break;
8997         default:
8998                 mark_reg_unknown(env, regs, insn->dst_reg);
8999                 break;
9000         }
9001
9002         /* ALU32 ops are zero extended into 64bit register */
9003         if (alu32)
9004                 zext_32_to_64(dst_reg);
9005         reg_bounds_sync(dst_reg);
9006         return 0;
9007 }
9008
9009 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
9010  * and var_off.
9011  */
9012 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
9013                                    struct bpf_insn *insn)
9014 {
9015         struct bpf_verifier_state *vstate = env->cur_state;
9016         struct bpf_func_state *state = vstate->frame[vstate->curframe];
9017         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
9018         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
9019         u8 opcode = BPF_OP(insn->code);
9020         int err;
9021
9022         dst_reg = &regs[insn->dst_reg];
9023         src_reg = NULL;
9024         if (dst_reg->type != SCALAR_VALUE)
9025                 ptr_reg = dst_reg;
9026         else
9027                 /* Make sure ID is cleared otherwise dst_reg min/max could be
9028                  * incorrectly propagated into other registers by find_equal_scalars()
9029                  */
9030                 dst_reg->id = 0;
9031         if (BPF_SRC(insn->code) == BPF_X) {
9032                 src_reg = &regs[insn->src_reg];
9033                 if (src_reg->type != SCALAR_VALUE) {
9034                         if (dst_reg->type != SCALAR_VALUE) {
9035                                 /* Combining two pointers by any ALU op yields
9036                                  * an arbitrary scalar. Disallow all math except
9037                                  * pointer subtraction
9038                                  */
9039                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9040                                         mark_reg_unknown(env, regs, insn->dst_reg);
9041                                         return 0;
9042                                 }
9043                                 verbose(env, "R%d pointer %s pointer prohibited\n",
9044                                         insn->dst_reg,
9045                                         bpf_alu_string[opcode >> 4]);
9046                                 return -EACCES;
9047                         } else {
9048                                 /* scalar += pointer
9049                                  * This is legal, but we have to reverse our
9050                                  * src/dest handling in computing the range
9051                                  */
9052                                 err = mark_chain_precision(env, insn->dst_reg);
9053                                 if (err)
9054                                         return err;
9055                                 return adjust_ptr_min_max_vals(env, insn,
9056                                                                src_reg, dst_reg);
9057                         }
9058                 } else if (ptr_reg) {
9059                         /* pointer += scalar */
9060                         err = mark_chain_precision(env, insn->src_reg);
9061                         if (err)
9062                                 return err;
9063                         return adjust_ptr_min_max_vals(env, insn,
9064                                                        dst_reg, src_reg);
9065                 }
9066         } else {
9067                 /* Pretend the src is a reg with a known value, since we only
9068                  * need to be able to read from this state.
9069                  */
9070                 off_reg.type = SCALAR_VALUE;
9071                 __mark_reg_known(&off_reg, insn->imm);
9072                 src_reg = &off_reg;
9073                 if (ptr_reg) /* pointer += K */
9074                         return adjust_ptr_min_max_vals(env, insn,
9075                                                        ptr_reg, src_reg);
9076         }
9077
9078         /* Got here implies adding two SCALAR_VALUEs */
9079         if (WARN_ON_ONCE(ptr_reg)) {
9080                 print_verifier_state(env, state, true);
9081                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
9082                 return -EINVAL;
9083         }
9084         if (WARN_ON(!src_reg)) {
9085                 print_verifier_state(env, state, true);
9086                 verbose(env, "verifier internal error: no src_reg\n");
9087                 return -EINVAL;
9088         }
9089         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
9090 }
9091
9092 /* check validity of 32-bit and 64-bit arithmetic operations */
9093 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
9094 {
9095         struct bpf_reg_state *regs = cur_regs(env);
9096         u8 opcode = BPF_OP(insn->code);
9097         int err;
9098
9099         if (opcode == BPF_END || opcode == BPF_NEG) {
9100                 if (opcode == BPF_NEG) {
9101                         if (BPF_SRC(insn->code) != BPF_K ||
9102                             insn->src_reg != BPF_REG_0 ||
9103                             insn->off != 0 || insn->imm != 0) {
9104                                 verbose(env, "BPF_NEG uses reserved fields\n");
9105                                 return -EINVAL;
9106                         }
9107                 } else {
9108                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
9109                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
9110                             BPF_CLASS(insn->code) == BPF_ALU64) {
9111                                 verbose(env, "BPF_END uses reserved fields\n");
9112                                 return -EINVAL;
9113                         }
9114                 }
9115
9116                 /* check src operand */
9117                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9118                 if (err)
9119                         return err;
9120
9121                 if (is_pointer_value(env, insn->dst_reg)) {
9122                         verbose(env, "R%d pointer arithmetic prohibited\n",
9123                                 insn->dst_reg);
9124                         return -EACCES;
9125                 }
9126
9127                 /* check dest operand */
9128                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
9129                 if (err)
9130                         return err;
9131
9132         } else if (opcode == BPF_MOV) {
9133
9134                 if (BPF_SRC(insn->code) == BPF_X) {
9135                         if (insn->imm != 0 || insn->off != 0) {
9136                                 verbose(env, "BPF_MOV uses reserved fields\n");
9137                                 return -EINVAL;
9138                         }
9139
9140                         /* check src operand */
9141                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
9142                         if (err)
9143                                 return err;
9144                 } else {
9145                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9146                                 verbose(env, "BPF_MOV uses reserved fields\n");
9147                                 return -EINVAL;
9148                         }
9149                 }
9150
9151                 /* check dest operand, mark as required later */
9152                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9153                 if (err)
9154                         return err;
9155
9156                 if (BPF_SRC(insn->code) == BPF_X) {
9157                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
9158                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
9159
9160                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
9161                                 /* case: R1 = R2
9162                                  * copy register state to dest reg
9163                                  */
9164                                 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
9165                                         /* Assign src and dst registers the same ID
9166                                          * that will be used by find_equal_scalars()
9167                                          * to propagate min/max range.
9168                                          */
9169                                         src_reg->id = ++env->id_gen;
9170                                 *dst_reg = *src_reg;
9171                                 dst_reg->live |= REG_LIVE_WRITTEN;
9172                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
9173                         } else {
9174                                 /* R1 = (u32) R2 */
9175                                 if (is_pointer_value(env, insn->src_reg)) {
9176                                         verbose(env,
9177                                                 "R%d partial copy of pointer\n",
9178                                                 insn->src_reg);
9179                                         return -EACCES;
9180                                 } else if (src_reg->type == SCALAR_VALUE) {
9181                                         *dst_reg = *src_reg;
9182                                         /* Make sure ID is cleared otherwise
9183                                          * dst_reg min/max could be incorrectly
9184                                          * propagated into src_reg by find_equal_scalars()
9185                                          */
9186                                         dst_reg->id = 0;
9187                                         dst_reg->live |= REG_LIVE_WRITTEN;
9188                                         dst_reg->subreg_def = env->insn_idx + 1;
9189                                 } else {
9190                                         mark_reg_unknown(env, regs,
9191                                                          insn->dst_reg);
9192                                 }
9193                                 zext_32_to_64(dst_reg);
9194                                 reg_bounds_sync(dst_reg);
9195                         }
9196                 } else {
9197                         /* case: R = imm
9198                          * remember the value we stored into this reg
9199                          */
9200                         /* clear any state __mark_reg_known doesn't set */
9201                         mark_reg_unknown(env, regs, insn->dst_reg);
9202                         regs[insn->dst_reg].type = SCALAR_VALUE;
9203                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
9204                                 __mark_reg_known(regs + insn->dst_reg,
9205                                                  insn->imm);
9206                         } else {
9207                                 __mark_reg_known(regs + insn->dst_reg,
9208                                                  (u32)insn->imm);
9209                         }
9210                 }
9211
9212         } else if (opcode > BPF_END) {
9213                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
9214                 return -EINVAL;
9215
9216         } else {        /* all other ALU ops: and, sub, xor, add, ... */
9217
9218                 if (BPF_SRC(insn->code) == BPF_X) {
9219                         if (insn->imm != 0 || insn->off != 0) {
9220                                 verbose(env, "BPF_ALU uses reserved fields\n");
9221                                 return -EINVAL;
9222                         }
9223                         /* check src1 operand */
9224                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
9225                         if (err)
9226                                 return err;
9227                 } else {
9228                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9229                                 verbose(env, "BPF_ALU uses reserved fields\n");
9230                                 return -EINVAL;
9231                         }
9232                 }
9233
9234                 /* check src2 operand */
9235                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9236                 if (err)
9237                         return err;
9238
9239                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
9240                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
9241                         verbose(env, "div by zero\n");
9242                         return -EINVAL;
9243                 }
9244
9245                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
9246                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
9247                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
9248
9249                         if (insn->imm < 0 || insn->imm >= size) {
9250                                 verbose(env, "invalid shift %d\n", insn->imm);
9251                                 return -EINVAL;
9252                         }
9253                 }
9254
9255                 /* check dest operand */
9256                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9257                 if (err)
9258                         return err;
9259
9260                 return adjust_reg_min_max_vals(env, insn);
9261         }
9262
9263         return 0;
9264 }
9265
9266 static void __find_good_pkt_pointers(struct bpf_func_state *state,
9267                                      struct bpf_reg_state *dst_reg,
9268                                      enum bpf_reg_type type, int new_range)
9269 {
9270         struct bpf_reg_state *reg;
9271         int i;
9272
9273         for (i = 0; i < MAX_BPF_REG; i++) {
9274                 reg = &state->regs[i];
9275                 if (reg->type == type && reg->id == dst_reg->id)
9276                         /* keep the maximum range already checked */
9277                         reg->range = max(reg->range, new_range);
9278         }
9279
9280         bpf_for_each_spilled_reg(i, state, reg) {
9281                 if (!reg)
9282                         continue;
9283                 if (reg->type == type && reg->id == dst_reg->id)
9284                         reg->range = max(reg->range, new_range);
9285         }
9286 }
9287
9288 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
9289                                    struct bpf_reg_state *dst_reg,
9290                                    enum bpf_reg_type type,
9291                                    bool range_right_open)
9292 {
9293         int new_range, i;
9294
9295         if (dst_reg->off < 0 ||
9296             (dst_reg->off == 0 && range_right_open))
9297                 /* This doesn't give us any range */
9298                 return;
9299
9300         if (dst_reg->umax_value > MAX_PACKET_OFF ||
9301             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
9302                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
9303                  * than pkt_end, but that's because it's also less than pkt.
9304                  */
9305                 return;
9306
9307         new_range = dst_reg->off;
9308         if (range_right_open)
9309                 new_range++;
9310
9311         /* Examples for register markings:
9312          *
9313          * pkt_data in dst register:
9314          *
9315          *   r2 = r3;
9316          *   r2 += 8;
9317          *   if (r2 > pkt_end) goto <handle exception>
9318          *   <access okay>
9319          *
9320          *   r2 = r3;
9321          *   r2 += 8;
9322          *   if (r2 < pkt_end) goto <access okay>
9323          *   <handle exception>
9324          *
9325          *   Where:
9326          *     r2 == dst_reg, pkt_end == src_reg
9327          *     r2=pkt(id=n,off=8,r=0)
9328          *     r3=pkt(id=n,off=0,r=0)
9329          *
9330          * pkt_data in src register:
9331          *
9332          *   r2 = r3;
9333          *   r2 += 8;
9334          *   if (pkt_end >= r2) goto <access okay>
9335          *   <handle exception>
9336          *
9337          *   r2 = r3;
9338          *   r2 += 8;
9339          *   if (pkt_end <= r2) goto <handle exception>
9340          *   <access okay>
9341          *
9342          *   Where:
9343          *     pkt_end == dst_reg, r2 == src_reg
9344          *     r2=pkt(id=n,off=8,r=0)
9345          *     r3=pkt(id=n,off=0,r=0)
9346          *
9347          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
9348          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
9349          * and [r3, r3 + 8-1) respectively is safe to access depending on
9350          * the check.
9351          */
9352
9353         /* If our ids match, then we must have the same max_value.  And we
9354          * don't care about the other reg's fixed offset, since if it's too big
9355          * the range won't allow anything.
9356          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
9357          */
9358         for (i = 0; i <= vstate->curframe; i++)
9359                 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
9360                                          new_range);
9361 }
9362
9363 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
9364 {
9365         struct tnum subreg = tnum_subreg(reg->var_off);
9366         s32 sval = (s32)val;
9367
9368         switch (opcode) {
9369         case BPF_JEQ:
9370                 if (tnum_is_const(subreg))
9371                         return !!tnum_equals_const(subreg, val);
9372                 break;
9373         case BPF_JNE:
9374                 if (tnum_is_const(subreg))
9375                         return !tnum_equals_const(subreg, val);
9376                 break;
9377         case BPF_JSET:
9378                 if ((~subreg.mask & subreg.value) & val)
9379                         return 1;
9380                 if (!((subreg.mask | subreg.value) & val))
9381                         return 0;
9382                 break;
9383         case BPF_JGT:
9384                 if (reg->u32_min_value > val)
9385                         return 1;
9386                 else if (reg->u32_max_value <= val)
9387                         return 0;
9388                 break;
9389         case BPF_JSGT:
9390                 if (reg->s32_min_value > sval)
9391                         return 1;
9392                 else if (reg->s32_max_value <= sval)
9393                         return 0;
9394                 break;
9395         case BPF_JLT:
9396                 if (reg->u32_max_value < val)
9397                         return 1;
9398                 else if (reg->u32_min_value >= val)
9399                         return 0;
9400                 break;
9401         case BPF_JSLT:
9402                 if (reg->s32_max_value < sval)
9403                         return 1;
9404                 else if (reg->s32_min_value >= sval)
9405                         return 0;
9406                 break;
9407         case BPF_JGE:
9408                 if (reg->u32_min_value >= val)
9409                         return 1;
9410                 else if (reg->u32_max_value < val)
9411                         return 0;
9412                 break;
9413         case BPF_JSGE:
9414                 if (reg->s32_min_value >= sval)
9415                         return 1;
9416                 else if (reg->s32_max_value < sval)
9417                         return 0;
9418                 break;
9419         case BPF_JLE:
9420                 if (reg->u32_max_value <= val)
9421                         return 1;
9422                 else if (reg->u32_min_value > val)
9423                         return 0;
9424                 break;
9425         case BPF_JSLE:
9426                 if (reg->s32_max_value <= sval)
9427                         return 1;
9428                 else if (reg->s32_min_value > sval)
9429                         return 0;
9430                 break;
9431         }
9432
9433         return -1;
9434 }
9435
9436
9437 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
9438 {
9439         s64 sval = (s64)val;
9440
9441         switch (opcode) {
9442         case BPF_JEQ:
9443                 if (tnum_is_const(reg->var_off))
9444                         return !!tnum_equals_const(reg->var_off, val);
9445                 break;
9446         case BPF_JNE:
9447                 if (tnum_is_const(reg->var_off))
9448                         return !tnum_equals_const(reg->var_off, val);
9449                 break;
9450         case BPF_JSET:
9451                 if ((~reg->var_off.mask & reg->var_off.value) & val)
9452                         return 1;
9453                 if (!((reg->var_off.mask | reg->var_off.value) & val))
9454                         return 0;
9455                 break;
9456         case BPF_JGT:
9457                 if (reg->umin_value > val)
9458                         return 1;
9459                 else if (reg->umax_value <= val)
9460                         return 0;
9461                 break;
9462         case BPF_JSGT:
9463                 if (reg->smin_value > sval)
9464                         return 1;
9465                 else if (reg->smax_value <= sval)
9466                         return 0;
9467                 break;
9468         case BPF_JLT:
9469                 if (reg->umax_value < val)
9470                         return 1;
9471                 else if (reg->umin_value >= val)
9472                         return 0;
9473                 break;
9474         case BPF_JSLT:
9475                 if (reg->smax_value < sval)
9476                         return 1;
9477                 else if (reg->smin_value >= sval)
9478                         return 0;
9479                 break;
9480         case BPF_JGE:
9481                 if (reg->umin_value >= val)
9482                         return 1;
9483                 else if (reg->umax_value < val)
9484                         return 0;
9485                 break;
9486         case BPF_JSGE:
9487                 if (reg->smin_value >= sval)
9488                         return 1;
9489                 else if (reg->smax_value < sval)
9490                         return 0;
9491                 break;
9492         case BPF_JLE:
9493                 if (reg->umax_value <= val)
9494                         return 1;
9495                 else if (reg->umin_value > val)
9496                         return 0;
9497                 break;
9498         case BPF_JSLE:
9499                 if (reg->smax_value <= sval)
9500                         return 1;
9501                 else if (reg->smin_value > sval)
9502                         return 0;
9503                 break;
9504         }
9505
9506         return -1;
9507 }
9508
9509 /* compute branch direction of the expression "if (reg opcode val) goto target;"
9510  * and return:
9511  *  1 - branch will be taken and "goto target" will be executed
9512  *  0 - branch will not be taken and fall-through to next insn
9513  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
9514  *      range [0,10]
9515  */
9516 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
9517                            bool is_jmp32)
9518 {
9519         if (__is_pointer_value(false, reg)) {
9520                 if (!reg_type_not_null(reg->type))
9521                         return -1;
9522
9523                 /* If pointer is valid tests against zero will fail so we can
9524                  * use this to direct branch taken.
9525                  */
9526                 if (val != 0)
9527                         return -1;
9528
9529                 switch (opcode) {
9530                 case BPF_JEQ:
9531                         return 0;
9532                 case BPF_JNE:
9533                         return 1;
9534                 default:
9535                         return -1;
9536                 }
9537         }
9538
9539         if (is_jmp32)
9540                 return is_branch32_taken(reg, val, opcode);
9541         return is_branch64_taken(reg, val, opcode);
9542 }
9543
9544 static int flip_opcode(u32 opcode)
9545 {
9546         /* How can we transform "a <op> b" into "b <op> a"? */
9547         static const u8 opcode_flip[16] = {
9548                 /* these stay the same */
9549                 [BPF_JEQ  >> 4] = BPF_JEQ,
9550                 [BPF_JNE  >> 4] = BPF_JNE,
9551                 [BPF_JSET >> 4] = BPF_JSET,
9552                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
9553                 [BPF_JGE  >> 4] = BPF_JLE,
9554                 [BPF_JGT  >> 4] = BPF_JLT,
9555                 [BPF_JLE  >> 4] = BPF_JGE,
9556                 [BPF_JLT  >> 4] = BPF_JGT,
9557                 [BPF_JSGE >> 4] = BPF_JSLE,
9558                 [BPF_JSGT >> 4] = BPF_JSLT,
9559                 [BPF_JSLE >> 4] = BPF_JSGE,
9560                 [BPF_JSLT >> 4] = BPF_JSGT
9561         };
9562         return opcode_flip[opcode >> 4];
9563 }
9564
9565 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
9566                                    struct bpf_reg_state *src_reg,
9567                                    u8 opcode)
9568 {
9569         struct bpf_reg_state *pkt;
9570
9571         if (src_reg->type == PTR_TO_PACKET_END) {
9572                 pkt = dst_reg;
9573         } else if (dst_reg->type == PTR_TO_PACKET_END) {
9574                 pkt = src_reg;
9575                 opcode = flip_opcode(opcode);
9576         } else {
9577                 return -1;
9578         }
9579
9580         if (pkt->range >= 0)
9581                 return -1;
9582
9583         switch (opcode) {
9584         case BPF_JLE:
9585                 /* pkt <= pkt_end */
9586                 fallthrough;
9587         case BPF_JGT:
9588                 /* pkt > pkt_end */
9589                 if (pkt->range == BEYOND_PKT_END)
9590                         /* pkt has at last one extra byte beyond pkt_end */
9591                         return opcode == BPF_JGT;
9592                 break;
9593         case BPF_JLT:
9594                 /* pkt < pkt_end */
9595                 fallthrough;
9596         case BPF_JGE:
9597                 /* pkt >= pkt_end */
9598                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
9599                         return opcode == BPF_JGE;
9600                 break;
9601         }
9602         return -1;
9603 }
9604
9605 /* Adjusts the register min/max values in the case that the dst_reg is the
9606  * variable register that we are working on, and src_reg is a constant or we're
9607  * simply doing a BPF_K check.
9608  * In JEQ/JNE cases we also adjust the var_off values.
9609  */
9610 static void reg_set_min_max(struct bpf_reg_state *true_reg,
9611                             struct bpf_reg_state *false_reg,
9612                             u64 val, u32 val32,
9613                             u8 opcode, bool is_jmp32)
9614 {
9615         struct tnum false_32off = tnum_subreg(false_reg->var_off);
9616         struct tnum false_64off = false_reg->var_off;
9617         struct tnum true_32off = tnum_subreg(true_reg->var_off);
9618         struct tnum true_64off = true_reg->var_off;
9619         s64 sval = (s64)val;
9620         s32 sval32 = (s32)val32;
9621
9622         /* If the dst_reg is a pointer, we can't learn anything about its
9623          * variable offset from the compare (unless src_reg were a pointer into
9624          * the same object, but we don't bother with that.
9625          * Since false_reg and true_reg have the same type by construction, we
9626          * only need to check one of them for pointerness.
9627          */
9628         if (__is_pointer_value(false, false_reg))
9629                 return;
9630
9631         switch (opcode) {
9632         /* JEQ/JNE comparison doesn't change the register equivalence.
9633          *
9634          * r1 = r2;
9635          * if (r1 == 42) goto label;
9636          * ...
9637          * label: // here both r1 and r2 are known to be 42.
9638          *
9639          * Hence when marking register as known preserve it's ID.
9640          */
9641         case BPF_JEQ:
9642                 if (is_jmp32) {
9643                         __mark_reg32_known(true_reg, val32);
9644                         true_32off = tnum_subreg(true_reg->var_off);
9645                 } else {
9646                         ___mark_reg_known(true_reg, val);
9647                         true_64off = true_reg->var_off;
9648                 }
9649                 break;
9650         case BPF_JNE:
9651                 if (is_jmp32) {
9652                         __mark_reg32_known(false_reg, val32);
9653                         false_32off = tnum_subreg(false_reg->var_off);
9654                 } else {
9655                         ___mark_reg_known(false_reg, val);
9656                         false_64off = false_reg->var_off;
9657                 }
9658                 break;
9659         case BPF_JSET:
9660                 if (is_jmp32) {
9661                         false_32off = tnum_and(false_32off, tnum_const(~val32));
9662                         if (is_power_of_2(val32))
9663                                 true_32off = tnum_or(true_32off,
9664                                                      tnum_const(val32));
9665                 } else {
9666                         false_64off = tnum_and(false_64off, tnum_const(~val));
9667                         if (is_power_of_2(val))
9668                                 true_64off = tnum_or(true_64off,
9669                                                      tnum_const(val));
9670                 }
9671                 break;
9672         case BPF_JGE:
9673         case BPF_JGT:
9674         {
9675                 if (is_jmp32) {
9676                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
9677                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
9678
9679                         false_reg->u32_max_value = min(false_reg->u32_max_value,
9680                                                        false_umax);
9681                         true_reg->u32_min_value = max(true_reg->u32_min_value,
9682                                                       true_umin);
9683                 } else {
9684                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
9685                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
9686
9687                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
9688                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
9689                 }
9690                 break;
9691         }
9692         case BPF_JSGE:
9693         case BPF_JSGT:
9694         {
9695                 if (is_jmp32) {
9696                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
9697                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
9698
9699                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
9700                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
9701                 } else {
9702                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
9703                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
9704
9705                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
9706                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
9707                 }
9708                 break;
9709         }
9710         case BPF_JLE:
9711         case BPF_JLT:
9712         {
9713                 if (is_jmp32) {
9714                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
9715                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
9716
9717                         false_reg->u32_min_value = max(false_reg->u32_min_value,
9718                                                        false_umin);
9719                         true_reg->u32_max_value = min(true_reg->u32_max_value,
9720                                                       true_umax);
9721                 } else {
9722                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
9723                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
9724
9725                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
9726                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
9727                 }
9728                 break;
9729         }
9730         case BPF_JSLE:
9731         case BPF_JSLT:
9732         {
9733                 if (is_jmp32) {
9734                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
9735                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
9736
9737                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
9738                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
9739                 } else {
9740                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
9741                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
9742
9743                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
9744                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
9745                 }
9746                 break;
9747         }
9748         default:
9749                 return;
9750         }
9751
9752         if (is_jmp32) {
9753                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
9754                                              tnum_subreg(false_32off));
9755                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
9756                                             tnum_subreg(true_32off));
9757                 __reg_combine_32_into_64(false_reg);
9758                 __reg_combine_32_into_64(true_reg);
9759         } else {
9760                 false_reg->var_off = false_64off;
9761                 true_reg->var_off = true_64off;
9762                 __reg_combine_64_into_32(false_reg);
9763                 __reg_combine_64_into_32(true_reg);
9764         }
9765 }
9766
9767 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
9768  * the variable reg.
9769  */
9770 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
9771                                 struct bpf_reg_state *false_reg,
9772                                 u64 val, u32 val32,
9773                                 u8 opcode, bool is_jmp32)
9774 {
9775         opcode = flip_opcode(opcode);
9776         /* This uses zero as "not present in table"; luckily the zero opcode,
9777          * BPF_JA, can't get here.
9778          */
9779         if (opcode)
9780                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
9781 }
9782
9783 /* Regs are known to be equal, so intersect their min/max/var_off */
9784 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9785                                   struct bpf_reg_state *dst_reg)
9786 {
9787         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9788                                                         dst_reg->umin_value);
9789         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9790                                                         dst_reg->umax_value);
9791         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9792                                                         dst_reg->smin_value);
9793         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9794                                                         dst_reg->smax_value);
9795         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9796                                                              dst_reg->var_off);
9797         reg_bounds_sync(src_reg);
9798         reg_bounds_sync(dst_reg);
9799 }
9800
9801 static void reg_combine_min_max(struct bpf_reg_state *true_src,
9802                                 struct bpf_reg_state *true_dst,
9803                                 struct bpf_reg_state *false_src,
9804                                 struct bpf_reg_state *false_dst,
9805                                 u8 opcode)
9806 {
9807         switch (opcode) {
9808         case BPF_JEQ:
9809                 __reg_combine_min_max(true_src, true_dst);
9810                 break;
9811         case BPF_JNE:
9812                 __reg_combine_min_max(false_src, false_dst);
9813                 break;
9814         }
9815 }
9816
9817 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
9818                                  struct bpf_reg_state *reg, u32 id,
9819                                  bool is_null)
9820 {
9821         if (type_may_be_null(reg->type) && reg->id == id &&
9822             !WARN_ON_ONCE(!reg->id)) {
9823                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
9824                                  !tnum_equals_const(reg->var_off, 0) ||
9825                                  reg->off)) {
9826                         /* Old offset (both fixed and variable parts) should
9827                          * have been known-zero, because we don't allow pointer
9828                          * arithmetic on pointers that might be NULL. If we
9829                          * see this happening, don't convert the register.
9830                          */
9831                         return;
9832                 }
9833                 if (is_null) {
9834                         reg->type = SCALAR_VALUE;
9835                         /* We don't need id and ref_obj_id from this point
9836                          * onwards anymore, thus we should better reset it,
9837                          * so that state pruning has chances to take effect.
9838                          */
9839                         reg->id = 0;
9840                         reg->ref_obj_id = 0;
9841
9842                         return;
9843                 }
9844
9845                 mark_ptr_not_null_reg(reg);
9846
9847                 if (!reg_may_point_to_spin_lock(reg)) {
9848                         /* For not-NULL ptr, reg->ref_obj_id will be reset
9849                          * in release_reg_references().
9850                          *
9851                          * reg->id is still used by spin_lock ptr. Other
9852                          * than spin_lock ptr type, reg->id can be reset.
9853                          */
9854                         reg->id = 0;
9855                 }
9856         }
9857 }
9858
9859 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
9860                                     bool is_null)
9861 {
9862         struct bpf_reg_state *reg;
9863         int i;
9864
9865         for (i = 0; i < MAX_BPF_REG; i++)
9866                 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
9867
9868         bpf_for_each_spilled_reg(i, state, reg) {
9869                 if (!reg)
9870                         continue;
9871                 mark_ptr_or_null_reg(state, reg, id, is_null);
9872         }
9873 }
9874
9875 /* The logic is similar to find_good_pkt_pointers(), both could eventually
9876  * be folded together at some point.
9877  */
9878 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
9879                                   bool is_null)
9880 {
9881         struct bpf_func_state *state = vstate->frame[vstate->curframe];
9882         struct bpf_reg_state *regs = state->regs;
9883         u32 ref_obj_id = regs[regno].ref_obj_id;
9884         u32 id = regs[regno].id;
9885         int i;
9886
9887         if (ref_obj_id && ref_obj_id == id && is_null)
9888                 /* regs[regno] is in the " == NULL" branch.
9889                  * No one could have freed the reference state before
9890                  * doing the NULL check.
9891                  */
9892                 WARN_ON_ONCE(release_reference_state(state, id));
9893
9894         for (i = 0; i <= vstate->curframe; i++)
9895                 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
9896 }
9897
9898 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
9899                                    struct bpf_reg_state *dst_reg,
9900                                    struct bpf_reg_state *src_reg,
9901                                    struct bpf_verifier_state *this_branch,
9902                                    struct bpf_verifier_state *other_branch)
9903 {
9904         if (BPF_SRC(insn->code) != BPF_X)
9905                 return false;
9906
9907         /* Pointers are always 64-bit. */
9908         if (BPF_CLASS(insn->code) == BPF_JMP32)
9909                 return false;
9910
9911         switch (BPF_OP(insn->code)) {
9912         case BPF_JGT:
9913                 if ((dst_reg->type == PTR_TO_PACKET &&
9914                      src_reg->type == PTR_TO_PACKET_END) ||
9915                     (dst_reg->type == PTR_TO_PACKET_META &&
9916                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9917                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
9918                         find_good_pkt_pointers(this_branch, dst_reg,
9919                                                dst_reg->type, false);
9920                         mark_pkt_end(other_branch, insn->dst_reg, true);
9921                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
9922                             src_reg->type == PTR_TO_PACKET) ||
9923                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9924                             src_reg->type == PTR_TO_PACKET_META)) {
9925                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
9926                         find_good_pkt_pointers(other_branch, src_reg,
9927                                                src_reg->type, true);
9928                         mark_pkt_end(this_branch, insn->src_reg, false);
9929                 } else {
9930                         return false;
9931                 }
9932                 break;
9933         case BPF_JLT:
9934                 if ((dst_reg->type == PTR_TO_PACKET &&
9935                      src_reg->type == PTR_TO_PACKET_END) ||
9936                     (dst_reg->type == PTR_TO_PACKET_META &&
9937                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9938                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
9939                         find_good_pkt_pointers(other_branch, dst_reg,
9940                                                dst_reg->type, true);
9941                         mark_pkt_end(this_branch, insn->dst_reg, false);
9942                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
9943                             src_reg->type == PTR_TO_PACKET) ||
9944                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9945                             src_reg->type == PTR_TO_PACKET_META)) {
9946                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
9947                         find_good_pkt_pointers(this_branch, src_reg,
9948                                                src_reg->type, false);
9949                         mark_pkt_end(other_branch, insn->src_reg, true);
9950                 } else {
9951                         return false;
9952                 }
9953                 break;
9954         case BPF_JGE:
9955                 if ((dst_reg->type == PTR_TO_PACKET &&
9956                      src_reg->type == PTR_TO_PACKET_END) ||
9957                     (dst_reg->type == PTR_TO_PACKET_META &&
9958                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9959                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
9960                         find_good_pkt_pointers(this_branch, dst_reg,
9961                                                dst_reg->type, true);
9962                         mark_pkt_end(other_branch, insn->dst_reg, false);
9963                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
9964                             src_reg->type == PTR_TO_PACKET) ||
9965                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9966                             src_reg->type == PTR_TO_PACKET_META)) {
9967                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
9968                         find_good_pkt_pointers(other_branch, src_reg,
9969                                                src_reg->type, false);
9970                         mark_pkt_end(this_branch, insn->src_reg, true);
9971                 } else {
9972                         return false;
9973                 }
9974                 break;
9975         case BPF_JLE:
9976                 if ((dst_reg->type == PTR_TO_PACKET &&
9977                      src_reg->type == PTR_TO_PACKET_END) ||
9978                     (dst_reg->type == PTR_TO_PACKET_META &&
9979                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9980                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
9981                         find_good_pkt_pointers(other_branch, dst_reg,
9982                                                dst_reg->type, false);
9983                         mark_pkt_end(this_branch, insn->dst_reg, true);
9984                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
9985                             src_reg->type == PTR_TO_PACKET) ||
9986                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9987                             src_reg->type == PTR_TO_PACKET_META)) {
9988                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
9989                         find_good_pkt_pointers(this_branch, src_reg,
9990                                                src_reg->type, true);
9991                         mark_pkt_end(other_branch, insn->src_reg, false);
9992                 } else {
9993                         return false;
9994                 }
9995                 break;
9996         default:
9997                 return false;
9998         }
9999
10000         return true;
10001 }
10002
10003 static void find_equal_scalars(struct bpf_verifier_state *vstate,
10004                                struct bpf_reg_state *known_reg)
10005 {
10006         struct bpf_func_state *state;
10007         struct bpf_reg_state *reg;
10008         int i, j;
10009
10010         for (i = 0; i <= vstate->curframe; i++) {
10011                 state = vstate->frame[i];
10012                 for (j = 0; j < MAX_BPF_REG; j++) {
10013                         reg = &state->regs[j];
10014                         if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10015                                 *reg = *known_reg;
10016                 }
10017
10018                 bpf_for_each_spilled_reg(j, state, reg) {
10019                         if (!reg)
10020                                 continue;
10021                         if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10022                                 *reg = *known_reg;
10023                 }
10024         }
10025 }
10026
10027 static int check_cond_jmp_op(struct bpf_verifier_env *env,
10028                              struct bpf_insn *insn, int *insn_idx)
10029 {
10030         struct bpf_verifier_state *this_branch = env->cur_state;
10031         struct bpf_verifier_state *other_branch;
10032         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
10033         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
10034         u8 opcode = BPF_OP(insn->code);
10035         bool is_jmp32;
10036         int pred = -1;
10037         int err;
10038
10039         /* Only conditional jumps are expected to reach here. */
10040         if (opcode == BPF_JA || opcode > BPF_JSLE) {
10041                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
10042                 return -EINVAL;
10043         }
10044
10045         if (BPF_SRC(insn->code) == BPF_X) {
10046                 if (insn->imm != 0) {
10047                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10048                         return -EINVAL;
10049                 }
10050
10051                 /* check src1 operand */
10052                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10053                 if (err)
10054                         return err;
10055
10056                 if (is_pointer_value(env, insn->src_reg)) {
10057                         verbose(env, "R%d pointer comparison prohibited\n",
10058                                 insn->src_reg);
10059                         return -EACCES;
10060                 }
10061                 src_reg = &regs[insn->src_reg];
10062         } else {
10063                 if (insn->src_reg != BPF_REG_0) {
10064                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10065                         return -EINVAL;
10066                 }
10067         }
10068
10069         /* check src2 operand */
10070         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10071         if (err)
10072                 return err;
10073
10074         dst_reg = &regs[insn->dst_reg];
10075         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
10076
10077         if (BPF_SRC(insn->code) == BPF_K) {
10078                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
10079         } else if (src_reg->type == SCALAR_VALUE &&
10080                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
10081                 pred = is_branch_taken(dst_reg,
10082                                        tnum_subreg(src_reg->var_off).value,
10083                                        opcode,
10084                                        is_jmp32);
10085         } else if (src_reg->type == SCALAR_VALUE &&
10086                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
10087                 pred = is_branch_taken(dst_reg,
10088                                        src_reg->var_off.value,
10089                                        opcode,
10090                                        is_jmp32);
10091         } else if (reg_is_pkt_pointer_any(dst_reg) &&
10092                    reg_is_pkt_pointer_any(src_reg) &&
10093                    !is_jmp32) {
10094                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
10095         }
10096
10097         if (pred >= 0) {
10098                 /* If we get here with a dst_reg pointer type it is because
10099                  * above is_branch_taken() special cased the 0 comparison.
10100                  */
10101                 if (!__is_pointer_value(false, dst_reg))
10102                         err = mark_chain_precision(env, insn->dst_reg);
10103                 if (BPF_SRC(insn->code) == BPF_X && !err &&
10104                     !__is_pointer_value(false, src_reg))
10105                         err = mark_chain_precision(env, insn->src_reg);
10106                 if (err)
10107                         return err;
10108         }
10109
10110         if (pred == 1) {
10111                 /* Only follow the goto, ignore fall-through. If needed, push
10112                  * the fall-through branch for simulation under speculative
10113                  * execution.
10114                  */
10115                 if (!env->bypass_spec_v1 &&
10116                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
10117                                                *insn_idx))
10118                         return -EFAULT;
10119                 *insn_idx += insn->off;
10120                 return 0;
10121         } else if (pred == 0) {
10122                 /* Only follow the fall-through branch, since that's where the
10123                  * program will go. If needed, push the goto branch for
10124                  * simulation under speculative execution.
10125                  */
10126                 if (!env->bypass_spec_v1 &&
10127                     !sanitize_speculative_path(env, insn,
10128                                                *insn_idx + insn->off + 1,
10129                                                *insn_idx))
10130                         return -EFAULT;
10131                 return 0;
10132         }
10133
10134         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
10135                                   false);
10136         if (!other_branch)
10137                 return -EFAULT;
10138         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
10139
10140         /* detect if we are comparing against a constant value so we can adjust
10141          * our min/max values for our dst register.
10142          * this is only legit if both are scalars (or pointers to the same
10143          * object, I suppose, but we don't support that right now), because
10144          * otherwise the different base pointers mean the offsets aren't
10145          * comparable.
10146          */
10147         if (BPF_SRC(insn->code) == BPF_X) {
10148                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
10149
10150                 if (dst_reg->type == SCALAR_VALUE &&
10151                     src_reg->type == SCALAR_VALUE) {
10152                         if (tnum_is_const(src_reg->var_off) ||
10153                             (is_jmp32 &&
10154                              tnum_is_const(tnum_subreg(src_reg->var_off))))
10155                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10156                                                 dst_reg,
10157                                                 src_reg->var_off.value,
10158                                                 tnum_subreg(src_reg->var_off).value,
10159                                                 opcode, is_jmp32);
10160                         else if (tnum_is_const(dst_reg->var_off) ||
10161                                  (is_jmp32 &&
10162                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
10163                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
10164                                                     src_reg,
10165                                                     dst_reg->var_off.value,
10166                                                     tnum_subreg(dst_reg->var_off).value,
10167                                                     opcode, is_jmp32);
10168                         else if (!is_jmp32 &&
10169                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
10170                                 /* Comparing for equality, we can combine knowledge */
10171                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
10172                                                     &other_branch_regs[insn->dst_reg],
10173                                                     src_reg, dst_reg, opcode);
10174                         if (src_reg->id &&
10175                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
10176                                 find_equal_scalars(this_branch, src_reg);
10177                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
10178                         }
10179
10180                 }
10181         } else if (dst_reg->type == SCALAR_VALUE) {
10182                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10183                                         dst_reg, insn->imm, (u32)insn->imm,
10184                                         opcode, is_jmp32);
10185         }
10186
10187         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
10188             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
10189                 find_equal_scalars(this_branch, dst_reg);
10190                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
10191         }
10192
10193         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
10194          * NOTE: these optimizations below are related with pointer comparison
10195          *       which will never be JMP32.
10196          */
10197         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
10198             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
10199             type_may_be_null(dst_reg->type)) {
10200                 /* Mark all identical registers in each branch as either
10201                  * safe or unknown depending R == 0 or R != 0 conditional.
10202                  */
10203                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
10204                                       opcode == BPF_JNE);
10205                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
10206                                       opcode == BPF_JEQ);
10207         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
10208                                            this_branch, other_branch) &&
10209                    is_pointer_value(env, insn->dst_reg)) {
10210                 verbose(env, "R%d pointer comparison prohibited\n",
10211                         insn->dst_reg);
10212                 return -EACCES;
10213         }
10214         if (env->log.level & BPF_LOG_LEVEL)
10215                 print_insn_state(env, this_branch->frame[this_branch->curframe]);
10216         return 0;
10217 }
10218
10219 /* verify BPF_LD_IMM64 instruction */
10220 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
10221 {
10222         struct bpf_insn_aux_data *aux = cur_aux(env);
10223         struct bpf_reg_state *regs = cur_regs(env);
10224         struct bpf_reg_state *dst_reg;
10225         struct bpf_map *map;
10226         int err;
10227
10228         if (BPF_SIZE(insn->code) != BPF_DW) {
10229                 verbose(env, "invalid BPF_LD_IMM insn\n");
10230                 return -EINVAL;
10231         }
10232         if (insn->off != 0) {
10233                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
10234                 return -EINVAL;
10235         }
10236
10237         err = check_reg_arg(env, insn->dst_reg, DST_OP);
10238         if (err)
10239                 return err;
10240
10241         dst_reg = &regs[insn->dst_reg];
10242         if (insn->src_reg == 0) {
10243                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
10244
10245                 dst_reg->type = SCALAR_VALUE;
10246                 __mark_reg_known(&regs[insn->dst_reg], imm);
10247                 return 0;
10248         }
10249
10250         /* All special src_reg cases are listed below. From this point onwards
10251          * we either succeed and assign a corresponding dst_reg->type after
10252          * zeroing the offset, or fail and reject the program.
10253          */
10254         mark_reg_known_zero(env, regs, insn->dst_reg);
10255
10256         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
10257                 dst_reg->type = aux->btf_var.reg_type;
10258                 switch (base_type(dst_reg->type)) {
10259                 case PTR_TO_MEM:
10260                         dst_reg->mem_size = aux->btf_var.mem_size;
10261                         break;
10262                 case PTR_TO_BTF_ID:
10263                         dst_reg->btf = aux->btf_var.btf;
10264                         dst_reg->btf_id = aux->btf_var.btf_id;
10265                         break;
10266                 default:
10267                         verbose(env, "bpf verifier is misconfigured\n");
10268                         return -EFAULT;
10269                 }
10270                 return 0;
10271         }
10272
10273         if (insn->src_reg == BPF_PSEUDO_FUNC) {
10274                 struct bpf_prog_aux *aux = env->prog->aux;
10275                 u32 subprogno = find_subprog(env,
10276                                              env->insn_idx + insn->imm + 1);
10277
10278                 if (!aux->func_info) {
10279                         verbose(env, "missing btf func_info\n");
10280                         return -EINVAL;
10281                 }
10282                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
10283                         verbose(env, "callback function not static\n");
10284                         return -EINVAL;
10285                 }
10286
10287                 dst_reg->type = PTR_TO_FUNC;
10288                 dst_reg->subprogno = subprogno;
10289                 return 0;
10290         }
10291
10292         map = env->used_maps[aux->map_index];
10293         dst_reg->map_ptr = map;
10294
10295         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
10296             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
10297                 dst_reg->type = PTR_TO_MAP_VALUE;
10298                 dst_reg->off = aux->map_off;
10299                 if (map_value_has_spin_lock(map))
10300                         dst_reg->id = ++env->id_gen;
10301         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
10302                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
10303                 dst_reg->type = CONST_PTR_TO_MAP;
10304         } else {
10305                 verbose(env, "bpf verifier is misconfigured\n");
10306                 return -EINVAL;
10307         }
10308
10309         return 0;
10310 }
10311
10312 static bool may_access_skb(enum bpf_prog_type type)
10313 {
10314         switch (type) {
10315         case BPF_PROG_TYPE_SOCKET_FILTER:
10316         case BPF_PROG_TYPE_SCHED_CLS:
10317         case BPF_PROG_TYPE_SCHED_ACT:
10318                 return true;
10319         default:
10320                 return false;
10321         }
10322 }
10323
10324 /* verify safety of LD_ABS|LD_IND instructions:
10325  * - they can only appear in the programs where ctx == skb
10326  * - since they are wrappers of function calls, they scratch R1-R5 registers,
10327  *   preserve R6-R9, and store return value into R0
10328  *
10329  * Implicit input:
10330  *   ctx == skb == R6 == CTX
10331  *
10332  * Explicit input:
10333  *   SRC == any register
10334  *   IMM == 32-bit immediate
10335  *
10336  * Output:
10337  *   R0 - 8/16/32-bit skb data converted to cpu endianness
10338  */
10339 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
10340 {
10341         struct bpf_reg_state *regs = cur_regs(env);
10342         static const int ctx_reg = BPF_REG_6;
10343         u8 mode = BPF_MODE(insn->code);
10344         int i, err;
10345
10346         if (!may_access_skb(resolve_prog_type(env->prog))) {
10347                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
10348                 return -EINVAL;
10349         }
10350
10351         if (!env->ops->gen_ld_abs) {
10352                 verbose(env, "bpf verifier is misconfigured\n");
10353                 return -EINVAL;
10354         }
10355
10356         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
10357             BPF_SIZE(insn->code) == BPF_DW ||
10358             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
10359                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
10360                 return -EINVAL;
10361         }
10362
10363         /* check whether implicit source operand (register R6) is readable */
10364         err = check_reg_arg(env, ctx_reg, SRC_OP);
10365         if (err)
10366                 return err;
10367
10368         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
10369          * gen_ld_abs() may terminate the program at runtime, leading to
10370          * reference leak.
10371          */
10372         err = check_reference_leak(env);
10373         if (err) {
10374                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
10375                 return err;
10376         }
10377
10378         if (env->cur_state->active_spin_lock) {
10379                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
10380                 return -EINVAL;
10381         }
10382
10383         if (regs[ctx_reg].type != PTR_TO_CTX) {
10384                 verbose(env,
10385                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
10386                 return -EINVAL;
10387         }
10388
10389         if (mode == BPF_IND) {
10390                 /* check explicit source operand */
10391                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10392                 if (err)
10393                         return err;
10394         }
10395
10396         err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
10397         if (err < 0)
10398                 return err;
10399
10400         /* reset caller saved regs to unreadable */
10401         for (i = 0; i < CALLER_SAVED_REGS; i++) {
10402                 mark_reg_not_init(env, regs, caller_saved[i]);
10403                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10404         }
10405
10406         /* mark destination R0 register as readable, since it contains
10407          * the value fetched from the packet.
10408          * Already marked as written above.
10409          */
10410         mark_reg_unknown(env, regs, BPF_REG_0);
10411         /* ld_abs load up to 32-bit skb data. */
10412         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
10413         return 0;
10414 }
10415
10416 static int check_return_code(struct bpf_verifier_env *env)
10417 {
10418         struct tnum enforce_attach_type_range = tnum_unknown;
10419         const struct bpf_prog *prog = env->prog;
10420         struct bpf_reg_state *reg;
10421         struct tnum range = tnum_range(0, 1);
10422         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10423         int err;
10424         struct bpf_func_state *frame = env->cur_state->frame[0];
10425         const bool is_subprog = frame->subprogno;
10426
10427         /* LSM and struct_ops func-ptr's return type could be "void" */
10428         if (!is_subprog) {
10429                 switch (prog_type) {
10430                 case BPF_PROG_TYPE_LSM:
10431                         if (prog->expected_attach_type == BPF_LSM_CGROUP)
10432                                 /* See below, can be 0 or 0-1 depending on hook. */
10433                                 break;
10434                         fallthrough;
10435                 case BPF_PROG_TYPE_STRUCT_OPS:
10436                         if (!prog->aux->attach_func_proto->type)
10437                                 return 0;
10438                         break;
10439                 default:
10440                         break;
10441                 }
10442         }
10443
10444         /* eBPF calling convention is such that R0 is used
10445          * to return the value from eBPF program.
10446          * Make sure that it's readable at this time
10447          * of bpf_exit, which means that program wrote
10448          * something into it earlier
10449          */
10450         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
10451         if (err)
10452                 return err;
10453
10454         if (is_pointer_value(env, BPF_REG_0)) {
10455                 verbose(env, "R0 leaks addr as return value\n");
10456                 return -EACCES;
10457         }
10458
10459         reg = cur_regs(env) + BPF_REG_0;
10460
10461         if (frame->in_async_callback_fn) {
10462                 /* enforce return zero from async callbacks like timer */
10463                 if (reg->type != SCALAR_VALUE) {
10464                         verbose(env, "In async callback the register R0 is not a known value (%s)\n",
10465                                 reg_type_str(env, reg->type));
10466                         return -EINVAL;
10467                 }
10468
10469                 if (!tnum_in(tnum_const(0), reg->var_off)) {
10470                         verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
10471                         return -EINVAL;
10472                 }
10473                 return 0;
10474         }
10475
10476         if (is_subprog) {
10477                 if (reg->type != SCALAR_VALUE) {
10478                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
10479                                 reg_type_str(env, reg->type));
10480                         return -EINVAL;
10481                 }
10482                 return 0;
10483         }
10484
10485         switch (prog_type) {
10486         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10487                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
10488                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
10489                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
10490                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
10491                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
10492                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
10493                         range = tnum_range(1, 1);
10494                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
10495                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
10496                         range = tnum_range(0, 3);
10497                 break;
10498         case BPF_PROG_TYPE_CGROUP_SKB:
10499                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
10500                         range = tnum_range(0, 3);
10501                         enforce_attach_type_range = tnum_range(2, 3);
10502                 }
10503                 break;
10504         case BPF_PROG_TYPE_CGROUP_SOCK:
10505         case BPF_PROG_TYPE_SOCK_OPS:
10506         case BPF_PROG_TYPE_CGROUP_DEVICE:
10507         case BPF_PROG_TYPE_CGROUP_SYSCTL:
10508         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10509                 break;
10510         case BPF_PROG_TYPE_RAW_TRACEPOINT:
10511                 if (!env->prog->aux->attach_btf_id)
10512                         return 0;
10513                 range = tnum_const(0);
10514                 break;
10515         case BPF_PROG_TYPE_TRACING:
10516                 switch (env->prog->expected_attach_type) {
10517                 case BPF_TRACE_FENTRY:
10518                 case BPF_TRACE_FEXIT:
10519                         range = tnum_const(0);
10520                         break;
10521                 case BPF_TRACE_RAW_TP:
10522                 case BPF_MODIFY_RETURN:
10523                         return 0;
10524                 case BPF_TRACE_ITER:
10525                         break;
10526                 default:
10527                         return -ENOTSUPP;
10528                 }
10529                 break;
10530         case BPF_PROG_TYPE_SK_LOOKUP:
10531                 range = tnum_range(SK_DROP, SK_PASS);
10532                 break;
10533
10534         case BPF_PROG_TYPE_LSM:
10535                 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
10536                         /* Regular BPF_PROG_TYPE_LSM programs can return
10537                          * any value.
10538                          */
10539                         return 0;
10540                 }
10541                 if (!env->prog->aux->attach_func_proto->type) {
10542                         /* Make sure programs that attach to void
10543                          * hooks don't try to modify return value.
10544                          */
10545                         range = tnum_range(1, 1);
10546                 }
10547                 break;
10548
10549         case BPF_PROG_TYPE_EXT:
10550                 /* freplace program can return anything as its return value
10551                  * depends on the to-be-replaced kernel func or bpf program.
10552                  */
10553         default:
10554                 return 0;
10555         }
10556
10557         if (reg->type != SCALAR_VALUE) {
10558                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
10559                         reg_type_str(env, reg->type));
10560                 return -EINVAL;
10561         }
10562
10563         if (!tnum_in(range, reg->var_off)) {
10564                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
10565                 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
10566                     prog_type == BPF_PROG_TYPE_LSM &&
10567                     !prog->aux->attach_func_proto->type)
10568                         verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10569                 return -EINVAL;
10570         }
10571
10572         if (!tnum_is_unknown(enforce_attach_type_range) &&
10573             tnum_in(enforce_attach_type_range, reg->var_off))
10574                 env->prog->enforce_expected_attach_type = 1;
10575         return 0;
10576 }
10577
10578 /* non-recursive DFS pseudo code
10579  * 1  procedure DFS-iterative(G,v):
10580  * 2      label v as discovered
10581  * 3      let S be a stack
10582  * 4      S.push(v)
10583  * 5      while S is not empty
10584  * 6            t <- S.pop()
10585  * 7            if t is what we're looking for:
10586  * 8                return t
10587  * 9            for all edges e in G.adjacentEdges(t) do
10588  * 10               if edge e is already labelled
10589  * 11                   continue with the next edge
10590  * 12               w <- G.adjacentVertex(t,e)
10591  * 13               if vertex w is not discovered and not explored
10592  * 14                   label e as tree-edge
10593  * 15                   label w as discovered
10594  * 16                   S.push(w)
10595  * 17                   continue at 5
10596  * 18               else if vertex w is discovered
10597  * 19                   label e as back-edge
10598  * 20               else
10599  * 21                   // vertex w is explored
10600  * 22                   label e as forward- or cross-edge
10601  * 23           label t as explored
10602  * 24           S.pop()
10603  *
10604  * convention:
10605  * 0x10 - discovered
10606  * 0x11 - discovered and fall-through edge labelled
10607  * 0x12 - discovered and fall-through and branch edges labelled
10608  * 0x20 - explored
10609  */
10610
10611 enum {
10612         DISCOVERED = 0x10,
10613         EXPLORED = 0x20,
10614         FALLTHROUGH = 1,
10615         BRANCH = 2,
10616 };
10617
10618 static u32 state_htab_size(struct bpf_verifier_env *env)
10619 {
10620         return env->prog->len;
10621 }
10622
10623 static struct bpf_verifier_state_list **explored_state(
10624                                         struct bpf_verifier_env *env,
10625                                         int idx)
10626 {
10627         struct bpf_verifier_state *cur = env->cur_state;
10628         struct bpf_func_state *state = cur->frame[cur->curframe];
10629
10630         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
10631 }
10632
10633 static void init_explored_state(struct bpf_verifier_env *env, int idx)
10634 {
10635         env->insn_aux_data[idx].prune_point = true;
10636 }
10637
10638 enum {
10639         DONE_EXPLORING = 0,
10640         KEEP_EXPLORING = 1,
10641 };
10642
10643 /* t, w, e - match pseudo-code above:
10644  * t - index of current instruction
10645  * w - next instruction
10646  * e - edge
10647  */
10648 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
10649                      bool loop_ok)
10650 {
10651         int *insn_stack = env->cfg.insn_stack;
10652         int *insn_state = env->cfg.insn_state;
10653
10654         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
10655                 return DONE_EXPLORING;
10656
10657         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
10658                 return DONE_EXPLORING;
10659
10660         if (w < 0 || w >= env->prog->len) {
10661                 verbose_linfo(env, t, "%d: ", t);
10662                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
10663                 return -EINVAL;
10664         }
10665
10666         if (e == BRANCH)
10667                 /* mark branch target for state pruning */
10668                 init_explored_state(env, w);
10669
10670         if (insn_state[w] == 0) {
10671                 /* tree-edge */
10672                 insn_state[t] = DISCOVERED | e;
10673                 insn_state[w] = DISCOVERED;
10674                 if (env->cfg.cur_stack >= env->prog->len)
10675                         return -E2BIG;
10676                 insn_stack[env->cfg.cur_stack++] = w;
10677                 return KEEP_EXPLORING;
10678         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
10679                 if (loop_ok && env->bpf_capable)
10680                         return DONE_EXPLORING;
10681                 verbose_linfo(env, t, "%d: ", t);
10682                 verbose_linfo(env, w, "%d: ", w);
10683                 verbose(env, "back-edge from insn %d to %d\n", t, w);
10684                 return -EINVAL;
10685         } else if (insn_state[w] == EXPLORED) {
10686                 /* forward- or cross-edge */
10687                 insn_state[t] = DISCOVERED | e;
10688         } else {
10689                 verbose(env, "insn state internal bug\n");
10690                 return -EFAULT;
10691         }
10692         return DONE_EXPLORING;
10693 }
10694
10695 static int visit_func_call_insn(int t, int insn_cnt,
10696                                 struct bpf_insn *insns,
10697                                 struct bpf_verifier_env *env,
10698                                 bool visit_callee)
10699 {
10700         int ret;
10701
10702         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
10703         if (ret)
10704                 return ret;
10705
10706         if (t + 1 < insn_cnt)
10707                 init_explored_state(env, t + 1);
10708         if (visit_callee) {
10709                 init_explored_state(env, t);
10710                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
10711                                 /* It's ok to allow recursion from CFG point of
10712                                  * view. __check_func_call() will do the actual
10713                                  * check.
10714                                  */
10715                                 bpf_pseudo_func(insns + t));
10716         }
10717         return ret;
10718 }
10719
10720 /* Visits the instruction at index t and returns one of the following:
10721  *  < 0 - an error occurred
10722  *  DONE_EXPLORING - the instruction was fully explored
10723  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
10724  */
10725 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
10726 {
10727         struct bpf_insn *insns = env->prog->insnsi;
10728         int ret;
10729
10730         if (bpf_pseudo_func(insns + t))
10731                 return visit_func_call_insn(t, insn_cnt, insns, env, true);
10732
10733         /* All non-branch instructions have a single fall-through edge. */
10734         if (BPF_CLASS(insns[t].code) != BPF_JMP &&
10735             BPF_CLASS(insns[t].code) != BPF_JMP32)
10736                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
10737
10738         switch (BPF_OP(insns[t].code)) {
10739         case BPF_EXIT:
10740                 return DONE_EXPLORING;
10741
10742         case BPF_CALL:
10743                 if (insns[t].imm == BPF_FUNC_timer_set_callback)
10744                         /* Mark this call insn to trigger is_state_visited() check
10745                          * before call itself is processed by __check_func_call().
10746                          * Otherwise new async state will be pushed for further
10747                          * exploration.
10748                          */
10749                         init_explored_state(env, t);
10750                 return visit_func_call_insn(t, insn_cnt, insns, env,
10751                                             insns[t].src_reg == BPF_PSEUDO_CALL);
10752
10753         case BPF_JA:
10754                 if (BPF_SRC(insns[t].code) != BPF_K)
10755                         return -EINVAL;
10756
10757                 /* unconditional jump with single edge */
10758                 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
10759                                 true);
10760                 if (ret)
10761                         return ret;
10762
10763                 /* unconditional jmp is not a good pruning point,
10764                  * but it's marked, since backtracking needs
10765                  * to record jmp history in is_state_visited().
10766                  */
10767                 init_explored_state(env, t + insns[t].off + 1);
10768                 /* tell verifier to check for equivalent states
10769                  * after every call and jump
10770                  */
10771                 if (t + 1 < insn_cnt)
10772                         init_explored_state(env, t + 1);
10773
10774                 return ret;
10775
10776         default:
10777                 /* conditional jump with two edges */
10778                 init_explored_state(env, t);
10779                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
10780                 if (ret)
10781                         return ret;
10782
10783                 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
10784         }
10785 }
10786
10787 /* non-recursive depth-first-search to detect loops in BPF program
10788  * loop == back-edge in directed graph
10789  */
10790 static int check_cfg(struct bpf_verifier_env *env)
10791 {
10792         int insn_cnt = env->prog->len;
10793         int *insn_stack, *insn_state;
10794         int ret = 0;
10795         int i;
10796
10797         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10798         if (!insn_state)
10799                 return -ENOMEM;
10800
10801         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
10802         if (!insn_stack) {
10803                 kvfree(insn_state);
10804                 return -ENOMEM;
10805         }
10806
10807         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10808         insn_stack[0] = 0; /* 0 is the first instruction */
10809         env->cfg.cur_stack = 1;
10810
10811         while (env->cfg.cur_stack > 0) {
10812                 int t = insn_stack[env->cfg.cur_stack - 1];
10813
10814                 ret = visit_insn(t, insn_cnt, env);
10815                 switch (ret) {
10816                 case DONE_EXPLORING:
10817                         insn_state[t] = EXPLORED;
10818                         env->cfg.cur_stack--;
10819                         break;
10820                 case KEEP_EXPLORING:
10821                         break;
10822                 default:
10823                         if (ret > 0) {
10824                                 verbose(env, "visit_insn internal bug\n");
10825                                 ret = -EFAULT;
10826                         }
10827                         goto err_free;
10828                 }
10829         }
10830
10831         if (env->cfg.cur_stack < 0) {
10832                 verbose(env, "pop stack internal bug\n");
10833                 ret = -EFAULT;
10834                 goto err_free;
10835         }
10836
10837         for (i = 0; i < insn_cnt; i++) {
10838                 if (insn_state[i] != EXPLORED) {
10839                         verbose(env, "unreachable insn %d\n", i);
10840                         ret = -EINVAL;
10841                         goto err_free;
10842                 }
10843         }
10844         ret = 0; /* cfg looks good */
10845
10846 err_free:
10847         kvfree(insn_state);
10848         kvfree(insn_stack);
10849         env->cfg.insn_state = env->cfg.insn_stack = NULL;
10850         return ret;
10851 }
10852
10853 static int check_abnormal_return(struct bpf_verifier_env *env)
10854 {
10855         int i;
10856
10857         for (i = 1; i < env->subprog_cnt; i++) {
10858                 if (env->subprog_info[i].has_ld_abs) {
10859                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
10860                         return -EINVAL;
10861                 }
10862                 if (env->subprog_info[i].has_tail_call) {
10863                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
10864                         return -EINVAL;
10865                 }
10866         }
10867         return 0;
10868 }
10869
10870 /* The minimum supported BTF func info size */
10871 #define MIN_BPF_FUNCINFO_SIZE   8
10872 #define MAX_FUNCINFO_REC_SIZE   252
10873
10874 static int check_btf_func(struct bpf_verifier_env *env,
10875                           const union bpf_attr *attr,
10876                           bpfptr_t uattr)
10877 {
10878         const struct btf_type *type, *func_proto, *ret_type;
10879         u32 i, nfuncs, urec_size, min_size;
10880         u32 krec_size = sizeof(struct bpf_func_info);
10881         struct bpf_func_info *krecord;
10882         struct bpf_func_info_aux *info_aux = NULL;
10883         struct bpf_prog *prog;
10884         const struct btf *btf;
10885         bpfptr_t urecord;
10886         u32 prev_offset = 0;
10887         bool scalar_return;
10888         int ret = -ENOMEM;
10889
10890         nfuncs = attr->func_info_cnt;
10891         if (!nfuncs) {
10892                 if (check_abnormal_return(env))
10893                         return -EINVAL;
10894                 return 0;
10895         }
10896
10897         if (nfuncs != env->subprog_cnt) {
10898                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
10899                 return -EINVAL;
10900         }
10901
10902         urec_size = attr->func_info_rec_size;
10903         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
10904             urec_size > MAX_FUNCINFO_REC_SIZE ||
10905             urec_size % sizeof(u32)) {
10906                 verbose(env, "invalid func info rec size %u\n", urec_size);
10907                 return -EINVAL;
10908         }
10909
10910         prog = env->prog;
10911         btf = prog->aux->btf;
10912
10913         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
10914         min_size = min_t(u32, krec_size, urec_size);
10915
10916         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
10917         if (!krecord)
10918                 return -ENOMEM;
10919         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
10920         if (!info_aux)
10921                 goto err_free;
10922
10923         for (i = 0; i < nfuncs; i++) {
10924                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
10925                 if (ret) {
10926                         if (ret == -E2BIG) {
10927                                 verbose(env, "nonzero tailing record in func info");
10928                                 /* set the size kernel expects so loader can zero
10929                                  * out the rest of the record.
10930                                  */
10931                                 if (copy_to_bpfptr_offset(uattr,
10932                                                           offsetof(union bpf_attr, func_info_rec_size),
10933                                                           &min_size, sizeof(min_size)))
10934                                         ret = -EFAULT;
10935                         }
10936                         goto err_free;
10937                 }
10938
10939                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
10940                         ret = -EFAULT;
10941                         goto err_free;
10942                 }
10943
10944                 /* check insn_off */
10945                 ret = -EINVAL;
10946                 if (i == 0) {
10947                         if (krecord[i].insn_off) {
10948                                 verbose(env,
10949                                         "nonzero insn_off %u for the first func info record",
10950                                         krecord[i].insn_off);
10951                                 goto err_free;
10952                         }
10953                 } else if (krecord[i].insn_off <= prev_offset) {
10954                         verbose(env,
10955                                 "same or smaller insn offset (%u) than previous func info record (%u)",
10956                                 krecord[i].insn_off, prev_offset);
10957                         goto err_free;
10958                 }
10959
10960                 if (env->subprog_info[i].start != krecord[i].insn_off) {
10961                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
10962                         goto err_free;
10963                 }
10964
10965                 /* check type_id */
10966                 type = btf_type_by_id(btf, krecord[i].type_id);
10967                 if (!type || !btf_type_is_func(type)) {
10968                         verbose(env, "invalid type id %d in func info",
10969                                 krecord[i].type_id);
10970                         goto err_free;
10971                 }
10972                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
10973
10974                 func_proto = btf_type_by_id(btf, type->type);
10975                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
10976                         /* btf_func_check() already verified it during BTF load */
10977                         goto err_free;
10978                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
10979                 scalar_return =
10980                         btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
10981                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
10982                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
10983                         goto err_free;
10984                 }
10985                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
10986                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
10987                         goto err_free;
10988                 }
10989
10990                 prev_offset = krecord[i].insn_off;
10991                 bpfptr_add(&urecord, urec_size);
10992         }
10993
10994         prog->aux->func_info = krecord;
10995         prog->aux->func_info_cnt = nfuncs;
10996         prog->aux->func_info_aux = info_aux;
10997         return 0;
10998
10999 err_free:
11000         kvfree(krecord);
11001         kfree(info_aux);
11002         return ret;
11003 }
11004
11005 static void adjust_btf_func(struct bpf_verifier_env *env)
11006 {
11007         struct bpf_prog_aux *aux = env->prog->aux;
11008         int i;
11009
11010         if (!aux->func_info)
11011                 return;
11012
11013         for (i = 0; i < env->subprog_cnt; i++)
11014                 aux->func_info[i].insn_off = env->subprog_info[i].start;
11015 }
11016
11017 #define MIN_BPF_LINEINFO_SIZE   offsetofend(struct bpf_line_info, line_col)
11018 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
11019
11020 static int check_btf_line(struct bpf_verifier_env *env,
11021                           const union bpf_attr *attr,
11022                           bpfptr_t uattr)
11023 {
11024         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
11025         struct bpf_subprog_info *sub;
11026         struct bpf_line_info *linfo;
11027         struct bpf_prog *prog;
11028         const struct btf *btf;
11029         bpfptr_t ulinfo;
11030         int err;
11031
11032         nr_linfo = attr->line_info_cnt;
11033         if (!nr_linfo)
11034                 return 0;
11035         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
11036                 return -EINVAL;
11037
11038         rec_size = attr->line_info_rec_size;
11039         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
11040             rec_size > MAX_LINEINFO_REC_SIZE ||
11041             rec_size & (sizeof(u32) - 1))
11042                 return -EINVAL;
11043
11044         /* Need to zero it in case the userspace may
11045          * pass in a smaller bpf_line_info object.
11046          */
11047         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
11048                          GFP_KERNEL | __GFP_NOWARN);
11049         if (!linfo)
11050                 return -ENOMEM;
11051
11052         prog = env->prog;
11053         btf = prog->aux->btf;
11054
11055         s = 0;
11056         sub = env->subprog_info;
11057         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
11058         expected_size = sizeof(struct bpf_line_info);
11059         ncopy = min_t(u32, expected_size, rec_size);
11060         for (i = 0; i < nr_linfo; i++) {
11061                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
11062                 if (err) {
11063                         if (err == -E2BIG) {
11064                                 verbose(env, "nonzero tailing record in line_info");
11065                                 if (copy_to_bpfptr_offset(uattr,
11066                                                           offsetof(union bpf_attr, line_info_rec_size),
11067                                                           &expected_size, sizeof(expected_size)))
11068                                         err = -EFAULT;
11069                         }
11070                         goto err_free;
11071                 }
11072
11073                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
11074                         err = -EFAULT;
11075                         goto err_free;
11076                 }
11077
11078                 /*
11079                  * Check insn_off to ensure
11080                  * 1) strictly increasing AND
11081                  * 2) bounded by prog->len
11082                  *
11083                  * The linfo[0].insn_off == 0 check logically falls into
11084                  * the later "missing bpf_line_info for func..." case
11085                  * because the first linfo[0].insn_off must be the
11086                  * first sub also and the first sub must have
11087                  * subprog_info[0].start == 0.
11088                  */
11089                 if ((i && linfo[i].insn_off <= prev_offset) ||
11090                     linfo[i].insn_off >= prog->len) {
11091                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
11092                                 i, linfo[i].insn_off, prev_offset,
11093                                 prog->len);
11094                         err = -EINVAL;
11095                         goto err_free;
11096                 }
11097
11098                 if (!prog->insnsi[linfo[i].insn_off].code) {
11099                         verbose(env,
11100                                 "Invalid insn code at line_info[%u].insn_off\n",
11101                                 i);
11102                         err = -EINVAL;
11103                         goto err_free;
11104                 }
11105
11106                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
11107                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
11108                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
11109                         err = -EINVAL;
11110                         goto err_free;
11111                 }
11112
11113                 if (s != env->subprog_cnt) {
11114                         if (linfo[i].insn_off == sub[s].start) {
11115                                 sub[s].linfo_idx = i;
11116                                 s++;
11117                         } else if (sub[s].start < linfo[i].insn_off) {
11118                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
11119                                 err = -EINVAL;
11120                                 goto err_free;
11121                         }
11122                 }
11123
11124                 prev_offset = linfo[i].insn_off;
11125                 bpfptr_add(&ulinfo, rec_size);
11126         }
11127
11128         if (s != env->subprog_cnt) {
11129                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
11130                         env->subprog_cnt - s, s);
11131                 err = -EINVAL;
11132                 goto err_free;
11133         }
11134
11135         prog->aux->linfo = linfo;
11136         prog->aux->nr_linfo = nr_linfo;
11137
11138         return 0;
11139
11140 err_free:
11141         kvfree(linfo);
11142         return err;
11143 }
11144
11145 #define MIN_CORE_RELO_SIZE      sizeof(struct bpf_core_relo)
11146 #define MAX_CORE_RELO_SIZE      MAX_FUNCINFO_REC_SIZE
11147
11148 static int check_core_relo(struct bpf_verifier_env *env,
11149                            const union bpf_attr *attr,
11150                            bpfptr_t uattr)
11151 {
11152         u32 i, nr_core_relo, ncopy, expected_size, rec_size;
11153         struct bpf_core_relo core_relo = {};
11154         struct bpf_prog *prog = env->prog;
11155         const struct btf *btf = prog->aux->btf;
11156         struct bpf_core_ctx ctx = {
11157                 .log = &env->log,
11158                 .btf = btf,
11159         };
11160         bpfptr_t u_core_relo;
11161         int err;
11162
11163         nr_core_relo = attr->core_relo_cnt;
11164         if (!nr_core_relo)
11165                 return 0;
11166         if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
11167                 return -EINVAL;
11168
11169         rec_size = attr->core_relo_rec_size;
11170         if (rec_size < MIN_CORE_RELO_SIZE ||
11171             rec_size > MAX_CORE_RELO_SIZE ||
11172             rec_size % sizeof(u32))
11173                 return -EINVAL;
11174
11175         u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
11176         expected_size = sizeof(struct bpf_core_relo);
11177         ncopy = min_t(u32, expected_size, rec_size);
11178
11179         /* Unlike func_info and line_info, copy and apply each CO-RE
11180          * relocation record one at a time.
11181          */
11182         for (i = 0; i < nr_core_relo; i++) {
11183                 /* future proofing when sizeof(bpf_core_relo) changes */
11184                 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
11185                 if (err) {
11186                         if (err == -E2BIG) {
11187                                 verbose(env, "nonzero tailing record in core_relo");
11188                                 if (copy_to_bpfptr_offset(uattr,
11189                                                           offsetof(union bpf_attr, core_relo_rec_size),
11190                                                           &expected_size, sizeof(expected_size)))
11191                                         err = -EFAULT;
11192                         }
11193                         break;
11194                 }
11195
11196                 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
11197                         err = -EFAULT;
11198                         break;
11199                 }
11200
11201                 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
11202                         verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
11203                                 i, core_relo.insn_off, prog->len);
11204                         err = -EINVAL;
11205                         break;
11206                 }
11207
11208                 err = bpf_core_apply(&ctx, &core_relo, i,
11209                                      &prog->insnsi[core_relo.insn_off / 8]);
11210                 if (err)
11211                         break;
11212                 bpfptr_add(&u_core_relo, rec_size);
11213         }
11214         return err;
11215 }
11216
11217 static int check_btf_info(struct bpf_verifier_env *env,
11218                           const union bpf_attr *attr,
11219                           bpfptr_t uattr)
11220 {
11221         struct btf *btf;
11222         int err;
11223
11224         if (!attr->func_info_cnt && !attr->line_info_cnt) {
11225                 if (check_abnormal_return(env))
11226                         return -EINVAL;
11227                 return 0;
11228         }
11229
11230         btf = btf_get_by_fd(attr->prog_btf_fd);
11231         if (IS_ERR(btf))
11232                 return PTR_ERR(btf);
11233         if (btf_is_kernel(btf)) {
11234                 btf_put(btf);
11235                 return -EACCES;
11236         }
11237         env->prog->aux->btf = btf;
11238
11239         err = check_btf_func(env, attr, uattr);
11240         if (err)
11241                 return err;
11242
11243         err = check_btf_line(env, attr, uattr);
11244         if (err)
11245                 return err;
11246
11247         err = check_core_relo(env, attr, uattr);
11248         if (err)
11249                 return err;
11250
11251         return 0;
11252 }
11253
11254 /* check %cur's range satisfies %old's */
11255 static bool range_within(struct bpf_reg_state *old,
11256                          struct bpf_reg_state *cur)
11257 {
11258         return old->umin_value <= cur->umin_value &&
11259                old->umax_value >= cur->umax_value &&
11260                old->smin_value <= cur->smin_value &&
11261                old->smax_value >= cur->smax_value &&
11262                old->u32_min_value <= cur->u32_min_value &&
11263                old->u32_max_value >= cur->u32_max_value &&
11264                old->s32_min_value <= cur->s32_min_value &&
11265                old->s32_max_value >= cur->s32_max_value;
11266 }
11267
11268 /* If in the old state two registers had the same id, then they need to have
11269  * the same id in the new state as well.  But that id could be different from
11270  * the old state, so we need to track the mapping from old to new ids.
11271  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
11272  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
11273  * regs with a different old id could still have new id 9, we don't care about
11274  * that.
11275  * So we look through our idmap to see if this old id has been seen before.  If
11276  * so, we require the new id to match; otherwise, we add the id pair to the map.
11277  */
11278 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
11279 {
11280         unsigned int i;
11281
11282         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
11283                 if (!idmap[i].old) {
11284                         /* Reached an empty slot; haven't seen this id before */
11285                         idmap[i].old = old_id;
11286                         idmap[i].cur = cur_id;
11287                         return true;
11288                 }
11289                 if (idmap[i].old == old_id)
11290                         return idmap[i].cur == cur_id;
11291         }
11292         /* We ran out of idmap slots, which should be impossible */
11293         WARN_ON_ONCE(1);
11294         return false;
11295 }
11296
11297 static void clean_func_state(struct bpf_verifier_env *env,
11298                              struct bpf_func_state *st)
11299 {
11300         enum bpf_reg_liveness live;
11301         int i, j;
11302
11303         for (i = 0; i < BPF_REG_FP; i++) {
11304                 live = st->regs[i].live;
11305                 /* liveness must not touch this register anymore */
11306                 st->regs[i].live |= REG_LIVE_DONE;
11307                 if (!(live & REG_LIVE_READ))
11308                         /* since the register is unused, clear its state
11309                          * to make further comparison simpler
11310                          */
11311                         __mark_reg_not_init(env, &st->regs[i]);
11312         }
11313
11314         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
11315                 live = st->stack[i].spilled_ptr.live;
11316                 /* liveness must not touch this stack slot anymore */
11317                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
11318                 if (!(live & REG_LIVE_READ)) {
11319                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
11320                         for (j = 0; j < BPF_REG_SIZE; j++)
11321                                 st->stack[i].slot_type[j] = STACK_INVALID;
11322                 }
11323         }
11324 }
11325
11326 static void clean_verifier_state(struct bpf_verifier_env *env,
11327                                  struct bpf_verifier_state *st)
11328 {
11329         int i;
11330
11331         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
11332                 /* all regs in this state in all frames were already marked */
11333                 return;
11334
11335         for (i = 0; i <= st->curframe; i++)
11336                 clean_func_state(env, st->frame[i]);
11337 }
11338
11339 /* the parentage chains form a tree.
11340  * the verifier states are added to state lists at given insn and
11341  * pushed into state stack for future exploration.
11342  * when the verifier reaches bpf_exit insn some of the verifer states
11343  * stored in the state lists have their final liveness state already,
11344  * but a lot of states will get revised from liveness point of view when
11345  * the verifier explores other branches.
11346  * Example:
11347  * 1: r0 = 1
11348  * 2: if r1 == 100 goto pc+1
11349  * 3: r0 = 2
11350  * 4: exit
11351  * when the verifier reaches exit insn the register r0 in the state list of
11352  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
11353  * of insn 2 and goes exploring further. At the insn 4 it will walk the
11354  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
11355  *
11356  * Since the verifier pushes the branch states as it sees them while exploring
11357  * the program the condition of walking the branch instruction for the second
11358  * time means that all states below this branch were already explored and
11359  * their final liveness marks are already propagated.
11360  * Hence when the verifier completes the search of state list in is_state_visited()
11361  * we can call this clean_live_states() function to mark all liveness states
11362  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
11363  * will not be used.
11364  * This function also clears the registers and stack for states that !READ
11365  * to simplify state merging.
11366  *
11367  * Important note here that walking the same branch instruction in the callee
11368  * doesn't meant that the states are DONE. The verifier has to compare
11369  * the callsites
11370  */
11371 static void clean_live_states(struct bpf_verifier_env *env, int insn,
11372                               struct bpf_verifier_state *cur)
11373 {
11374         struct bpf_verifier_state_list *sl;
11375         int i;
11376
11377         sl = *explored_state(env, insn);
11378         while (sl) {
11379                 if (sl->state.branches)
11380                         goto next;
11381                 if (sl->state.insn_idx != insn ||
11382                     sl->state.curframe != cur->curframe)
11383                         goto next;
11384                 for (i = 0; i <= cur->curframe; i++)
11385                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
11386                                 goto next;
11387                 clean_verifier_state(env, &sl->state);
11388 next:
11389                 sl = sl->next;
11390         }
11391 }
11392
11393 /* Returns true if (rold safe implies rcur safe) */
11394 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
11395                     struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
11396 {
11397         bool equal;
11398
11399         if (!(rold->live & REG_LIVE_READ))
11400                 /* explored state didn't use this */
11401                 return true;
11402
11403         equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
11404
11405         if (rold->type == PTR_TO_STACK)
11406                 /* two stack pointers are equal only if they're pointing to
11407                  * the same stack frame, since fp-8 in foo != fp-8 in bar
11408                  */
11409                 return equal && rold->frameno == rcur->frameno;
11410
11411         if (equal)
11412                 return true;
11413
11414         if (rold->type == NOT_INIT)
11415                 /* explored state can't have used this */
11416                 return true;
11417         if (rcur->type == NOT_INIT)
11418                 return false;
11419         switch (base_type(rold->type)) {
11420         case SCALAR_VALUE:
11421                 if (env->explore_alu_limits)
11422                         return false;
11423                 if (rcur->type == SCALAR_VALUE) {
11424                         if (!rold->precise && !rcur->precise)
11425                                 return true;
11426                         /* new val must satisfy old val knowledge */
11427                         return range_within(rold, rcur) &&
11428                                tnum_in(rold->var_off, rcur->var_off);
11429                 } else {
11430                         /* We're trying to use a pointer in place of a scalar.
11431                          * Even if the scalar was unbounded, this could lead to
11432                          * pointer leaks because scalars are allowed to leak
11433                          * while pointers are not. We could make this safe in
11434                          * special cases if root is calling us, but it's
11435                          * probably not worth the hassle.
11436                          */
11437                         return false;
11438                 }
11439         case PTR_TO_MAP_KEY:
11440         case PTR_TO_MAP_VALUE:
11441                 /* a PTR_TO_MAP_VALUE could be safe to use as a
11442                  * PTR_TO_MAP_VALUE_OR_NULL into the same map.
11443                  * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
11444                  * checked, doing so could have affected others with the same
11445                  * id, and we can't check for that because we lost the id when
11446                  * we converted to a PTR_TO_MAP_VALUE.
11447                  */
11448                 if (type_may_be_null(rold->type)) {
11449                         if (!type_may_be_null(rcur->type))
11450                                 return false;
11451                         if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
11452                                 return false;
11453                         /* Check our ids match any regs they're supposed to */
11454                         return check_ids(rold->id, rcur->id, idmap);
11455                 }
11456
11457                 /* If the new min/max/var_off satisfy the old ones and
11458                  * everything else matches, we are OK.
11459                  * 'id' is not compared, since it's only used for maps with
11460                  * bpf_spin_lock inside map element and in such cases if
11461                  * the rest of the prog is valid for one map element then
11462                  * it's valid for all map elements regardless of the key
11463                  * used in bpf_map_lookup()
11464                  */
11465                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
11466                        range_within(rold, rcur) &&
11467                        tnum_in(rold->var_off, rcur->var_off);
11468         case PTR_TO_PACKET_META:
11469         case PTR_TO_PACKET:
11470                 if (rcur->type != rold->type)
11471                         return false;
11472                 /* We must have at least as much range as the old ptr
11473                  * did, so that any accesses which were safe before are
11474                  * still safe.  This is true even if old range < old off,
11475                  * since someone could have accessed through (ptr - k), or
11476                  * even done ptr -= k in a register, to get a safe access.
11477                  */
11478                 if (rold->range > rcur->range)
11479                         return false;
11480                 /* If the offsets don't match, we can't trust our alignment;
11481                  * nor can we be sure that we won't fall out of range.
11482                  */
11483                 if (rold->off != rcur->off)
11484                         return false;
11485                 /* id relations must be preserved */
11486                 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
11487                         return false;
11488                 /* new val must satisfy old val knowledge */
11489                 return range_within(rold, rcur) &&
11490                        tnum_in(rold->var_off, rcur->var_off);
11491         case PTR_TO_CTX:
11492         case CONST_PTR_TO_MAP:
11493         case PTR_TO_PACKET_END:
11494         case PTR_TO_FLOW_KEYS:
11495         case PTR_TO_SOCKET:
11496         case PTR_TO_SOCK_COMMON:
11497         case PTR_TO_TCP_SOCK:
11498         case PTR_TO_XDP_SOCK:
11499                 /* Only valid matches are exact, which memcmp() above
11500                  * would have accepted
11501                  */
11502         default:
11503                 /* Don't know what's going on, just say it's not safe */
11504                 return false;
11505         }
11506
11507         /* Shouldn't get here; if we do, say it's not safe */
11508         WARN_ON_ONCE(1);
11509         return false;
11510 }
11511
11512 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
11513                       struct bpf_func_state *cur, struct bpf_id_pair *idmap)
11514 {
11515         int i, spi;
11516
11517         /* walk slots of the explored stack and ignore any additional
11518          * slots in the current stack, since explored(safe) state
11519          * didn't use them
11520          */
11521         for (i = 0; i < old->allocated_stack; i++) {
11522                 spi = i / BPF_REG_SIZE;
11523
11524                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
11525                         i += BPF_REG_SIZE - 1;
11526                         /* explored state didn't use this */
11527                         continue;
11528                 }
11529
11530                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
11531                         continue;
11532
11533                 /* explored stack has more populated slots than current stack
11534                  * and these slots were used
11535                  */
11536                 if (i >= cur->allocated_stack)
11537                         return false;
11538
11539                 /* if old state was safe with misc data in the stack
11540                  * it will be safe with zero-initialized stack.
11541                  * The opposite is not true
11542                  */
11543                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
11544                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
11545                         continue;
11546                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
11547                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
11548                         /* Ex: old explored (safe) state has STACK_SPILL in
11549                          * this stack slot, but current has STACK_MISC ->
11550                          * this verifier states are not equivalent,
11551                          * return false to continue verification of this path
11552                          */
11553                         return false;
11554                 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
11555                         continue;
11556                 if (!is_spilled_reg(&old->stack[spi]))
11557                         continue;
11558                 if (!regsafe(env, &old->stack[spi].spilled_ptr,
11559                              &cur->stack[spi].spilled_ptr, idmap))
11560                         /* when explored and current stack slot are both storing
11561                          * spilled registers, check that stored pointers types
11562                          * are the same as well.
11563                          * Ex: explored safe path could have stored
11564                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
11565                          * but current path has stored:
11566                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
11567                          * such verifier states are not equivalent.
11568                          * return false to continue verification of this path
11569                          */
11570                         return false;
11571         }
11572         return true;
11573 }
11574
11575 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
11576 {
11577         if (old->acquired_refs != cur->acquired_refs)
11578                 return false;
11579         return !memcmp(old->refs, cur->refs,
11580                        sizeof(*old->refs) * old->acquired_refs);
11581 }
11582
11583 /* compare two verifier states
11584  *
11585  * all states stored in state_list are known to be valid, since
11586  * verifier reached 'bpf_exit' instruction through them
11587  *
11588  * this function is called when verifier exploring different branches of
11589  * execution popped from the state stack. If it sees an old state that has
11590  * more strict register state and more strict stack state then this execution
11591  * branch doesn't need to be explored further, since verifier already
11592  * concluded that more strict state leads to valid finish.
11593  *
11594  * Therefore two states are equivalent if register state is more conservative
11595  * and explored stack state is more conservative than the current one.
11596  * Example:
11597  *       explored                   current
11598  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
11599  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
11600  *
11601  * In other words if current stack state (one being explored) has more
11602  * valid slots than old one that already passed validation, it means
11603  * the verifier can stop exploring and conclude that current state is valid too
11604  *
11605  * Similarly with registers. If explored state has register type as invalid
11606  * whereas register type in current state is meaningful, it means that
11607  * the current state will reach 'bpf_exit' instruction safely
11608  */
11609 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
11610                               struct bpf_func_state *cur)
11611 {
11612         int i;
11613
11614         memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
11615         for (i = 0; i < MAX_BPF_REG; i++)
11616                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
11617                              env->idmap_scratch))
11618                         return false;
11619
11620         if (!stacksafe(env, old, cur, env->idmap_scratch))
11621                 return false;
11622
11623         if (!refsafe(old, cur))
11624                 return false;
11625
11626         return true;
11627 }
11628
11629 static bool states_equal(struct bpf_verifier_env *env,
11630                          struct bpf_verifier_state *old,
11631                          struct bpf_verifier_state *cur)
11632 {
11633         int i;
11634
11635         if (old->curframe != cur->curframe)
11636                 return false;
11637
11638         /* Verification state from speculative execution simulation
11639          * must never prune a non-speculative execution one.
11640          */
11641         if (old->speculative && !cur->speculative)
11642                 return false;
11643
11644         if (old->active_spin_lock != cur->active_spin_lock)
11645                 return false;
11646
11647         /* for states to be equal callsites have to be the same
11648          * and all frame states need to be equivalent
11649          */
11650         for (i = 0; i <= old->curframe; i++) {
11651                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
11652                         return false;
11653                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
11654                         return false;
11655         }
11656         return true;
11657 }
11658
11659 /* Return 0 if no propagation happened. Return negative error code if error
11660  * happened. Otherwise, return the propagated bit.
11661  */
11662 static int propagate_liveness_reg(struct bpf_verifier_env *env,
11663                                   struct bpf_reg_state *reg,
11664                                   struct bpf_reg_state *parent_reg)
11665 {
11666         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
11667         u8 flag = reg->live & REG_LIVE_READ;
11668         int err;
11669
11670         /* When comes here, read flags of PARENT_REG or REG could be any of
11671          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
11672          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
11673          */
11674         if (parent_flag == REG_LIVE_READ64 ||
11675             /* Or if there is no read flag from REG. */
11676             !flag ||
11677             /* Or if the read flag from REG is the same as PARENT_REG. */
11678             parent_flag == flag)
11679                 return 0;
11680
11681         err = mark_reg_read(env, reg, parent_reg, flag);
11682         if (err)
11683                 return err;
11684
11685         return flag;
11686 }
11687
11688 /* A write screens off any subsequent reads; but write marks come from the
11689  * straight-line code between a state and its parent.  When we arrive at an
11690  * equivalent state (jump target or such) we didn't arrive by the straight-line
11691  * code, so read marks in the state must propagate to the parent regardless
11692  * of the state's write marks. That's what 'parent == state->parent' comparison
11693  * in mark_reg_read() is for.
11694  */
11695 static int propagate_liveness(struct bpf_verifier_env *env,
11696                               const struct bpf_verifier_state *vstate,
11697                               struct bpf_verifier_state *vparent)
11698 {
11699         struct bpf_reg_state *state_reg, *parent_reg;
11700         struct bpf_func_state *state, *parent;
11701         int i, frame, err = 0;
11702
11703         if (vparent->curframe != vstate->curframe) {
11704                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
11705                      vparent->curframe, vstate->curframe);
11706                 return -EFAULT;
11707         }
11708         /* Propagate read liveness of registers... */
11709         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
11710         for (frame = 0; frame <= vstate->curframe; frame++) {
11711                 parent = vparent->frame[frame];
11712                 state = vstate->frame[frame];
11713                 parent_reg = parent->regs;
11714                 state_reg = state->regs;
11715                 /* We don't need to worry about FP liveness, it's read-only */
11716                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
11717                         err = propagate_liveness_reg(env, &state_reg[i],
11718                                                      &parent_reg[i]);
11719                         if (err < 0)
11720                                 return err;
11721                         if (err == REG_LIVE_READ64)
11722                                 mark_insn_zext(env, &parent_reg[i]);
11723                 }
11724
11725                 /* Propagate stack slots. */
11726                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
11727                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
11728                         parent_reg = &parent->stack[i].spilled_ptr;
11729                         state_reg = &state->stack[i].spilled_ptr;
11730                         err = propagate_liveness_reg(env, state_reg,
11731                                                      parent_reg);
11732                         if (err < 0)
11733                                 return err;
11734                 }
11735         }
11736         return 0;
11737 }
11738
11739 /* find precise scalars in the previous equivalent state and
11740  * propagate them into the current state
11741  */
11742 static int propagate_precision(struct bpf_verifier_env *env,
11743                                const struct bpf_verifier_state *old)
11744 {
11745         struct bpf_reg_state *state_reg;
11746         struct bpf_func_state *state;
11747         int i, err = 0;
11748
11749         state = old->frame[old->curframe];
11750         state_reg = state->regs;
11751         for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
11752                 if (state_reg->type != SCALAR_VALUE ||
11753                     !state_reg->precise)
11754                         continue;
11755                 if (env->log.level & BPF_LOG_LEVEL2)
11756                         verbose(env, "propagating r%d\n", i);
11757                 err = mark_chain_precision(env, i);
11758                 if (err < 0)
11759                         return err;
11760         }
11761
11762         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
11763                 if (!is_spilled_reg(&state->stack[i]))
11764                         continue;
11765                 state_reg = &state->stack[i].spilled_ptr;
11766                 if (state_reg->type != SCALAR_VALUE ||
11767                     !state_reg->precise)
11768                         continue;
11769                 if (env->log.level & BPF_LOG_LEVEL2)
11770                         verbose(env, "propagating fp%d\n",
11771                                 (-i - 1) * BPF_REG_SIZE);
11772                 err = mark_chain_precision_stack(env, i);
11773                 if (err < 0)
11774                         return err;
11775         }
11776         return 0;
11777 }
11778
11779 static bool states_maybe_looping(struct bpf_verifier_state *old,
11780                                  struct bpf_verifier_state *cur)
11781 {
11782         struct bpf_func_state *fold, *fcur;
11783         int i, fr = cur->curframe;
11784
11785         if (old->curframe != fr)
11786                 return false;
11787
11788         fold = old->frame[fr];
11789         fcur = cur->frame[fr];
11790         for (i = 0; i < MAX_BPF_REG; i++)
11791                 if (memcmp(&fold->regs[i], &fcur->regs[i],
11792                            offsetof(struct bpf_reg_state, parent)))
11793                         return false;
11794         return true;
11795 }
11796
11797
11798 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
11799 {
11800         struct bpf_verifier_state_list *new_sl;
11801         struct bpf_verifier_state_list *sl, **pprev;
11802         struct bpf_verifier_state *cur = env->cur_state, *new;
11803         int i, j, err, states_cnt = 0;
11804         bool add_new_state = env->test_state_freq ? true : false;
11805
11806         cur->last_insn_idx = env->prev_insn_idx;
11807         if (!env->insn_aux_data[insn_idx].prune_point)
11808                 /* this 'insn_idx' instruction wasn't marked, so we will not
11809                  * be doing state search here
11810                  */
11811                 return 0;
11812
11813         /* bpf progs typically have pruning point every 4 instructions
11814          * http://vger.kernel.org/bpfconf2019.html#session-1
11815          * Do not add new state for future pruning if the verifier hasn't seen
11816          * at least 2 jumps and at least 8 instructions.
11817          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11818          * In tests that amounts to up to 50% reduction into total verifier
11819          * memory consumption and 20% verifier time speedup.
11820          */
11821         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11822             env->insn_processed - env->prev_insn_processed >= 8)
11823                 add_new_state = true;
11824
11825         pprev = explored_state(env, insn_idx);
11826         sl = *pprev;
11827
11828         clean_live_states(env, insn_idx, cur);
11829
11830         while (sl) {
11831                 states_cnt++;
11832                 if (sl->state.insn_idx != insn_idx)
11833                         goto next;
11834
11835                 if (sl->state.branches) {
11836                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
11837
11838                         if (frame->in_async_callback_fn &&
11839                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
11840                                 /* Different async_entry_cnt means that the verifier is
11841                                  * processing another entry into async callback.
11842                                  * Seeing the same state is not an indication of infinite
11843                                  * loop or infinite recursion.
11844                                  * But finding the same state doesn't mean that it's safe
11845                                  * to stop processing the current state. The previous state
11846                                  * hasn't yet reached bpf_exit, since state.branches > 0.
11847                                  * Checking in_async_callback_fn alone is not enough either.
11848                                  * Since the verifier still needs to catch infinite loops
11849                                  * inside async callbacks.
11850                                  */
11851                         } else if (states_maybe_looping(&sl->state, cur) &&
11852                                    states_equal(env, &sl->state, cur)) {
11853                                 verbose_linfo(env, insn_idx, "; ");
11854                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
11855                                 return -EINVAL;
11856                         }
11857                         /* if the verifier is processing a loop, avoid adding new state
11858                          * too often, since different loop iterations have distinct
11859                          * states and may not help future pruning.
11860                          * This threshold shouldn't be too low to make sure that
11861                          * a loop with large bound will be rejected quickly.
11862                          * The most abusive loop will be:
11863                          * r1 += 1
11864                          * if r1 < 1000000 goto pc-2
11865                          * 1M insn_procssed limit / 100 == 10k peak states.
11866                          * This threshold shouldn't be too high either, since states
11867                          * at the end of the loop are likely to be useful in pruning.
11868                          */
11869                         if (env->jmps_processed - env->prev_jmps_processed < 20 &&
11870                             env->insn_processed - env->prev_insn_processed < 100)
11871                                 add_new_state = false;
11872                         goto miss;
11873                 }
11874                 if (states_equal(env, &sl->state, cur)) {
11875                         sl->hit_cnt++;
11876                         /* reached equivalent register/stack state,
11877                          * prune the search.
11878                          * Registers read by the continuation are read by us.
11879                          * If we have any write marks in env->cur_state, they
11880                          * will prevent corresponding reads in the continuation
11881                          * from reaching our parent (an explored_state).  Our
11882                          * own state will get the read marks recorded, but
11883                          * they'll be immediately forgotten as we're pruning
11884                          * this state and will pop a new one.
11885                          */
11886                         err = propagate_liveness(env, &sl->state, cur);
11887
11888                         /* if previous state reached the exit with precision and
11889                          * current state is equivalent to it (except precsion marks)
11890                          * the precision needs to be propagated back in
11891                          * the current state.
11892                          */
11893                         err = err ? : push_jmp_history(env, cur);
11894                         err = err ? : propagate_precision(env, &sl->state);
11895                         if (err)
11896                                 return err;
11897                         return 1;
11898                 }
11899 miss:
11900                 /* when new state is not going to be added do not increase miss count.
11901                  * Otherwise several loop iterations will remove the state
11902                  * recorded earlier. The goal of these heuristics is to have
11903                  * states from some iterations of the loop (some in the beginning
11904                  * and some at the end) to help pruning.
11905                  */
11906                 if (add_new_state)
11907                         sl->miss_cnt++;
11908                 /* heuristic to determine whether this state is beneficial
11909                  * to keep checking from state equivalence point of view.
11910                  * Higher numbers increase max_states_per_insn and verification time,
11911                  * but do not meaningfully decrease insn_processed.
11912                  */
11913                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
11914                         /* the state is unlikely to be useful. Remove it to
11915                          * speed up verification
11916                          */
11917                         *pprev = sl->next;
11918                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
11919                                 u32 br = sl->state.branches;
11920
11921                                 WARN_ONCE(br,
11922                                           "BUG live_done but branches_to_explore %d\n",
11923                                           br);
11924                                 free_verifier_state(&sl->state, false);
11925                                 kfree(sl);
11926                                 env->peak_states--;
11927                         } else {
11928                                 /* cannot free this state, since parentage chain may
11929                                  * walk it later. Add it for free_list instead to
11930                                  * be freed at the end of verification
11931                                  */
11932                                 sl->next = env->free_list;
11933                                 env->free_list = sl;
11934                         }
11935                         sl = *pprev;
11936                         continue;
11937                 }
11938 next:
11939                 pprev = &sl->next;
11940                 sl = *pprev;
11941         }
11942
11943         if (env->max_states_per_insn < states_cnt)
11944                 env->max_states_per_insn = states_cnt;
11945
11946         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
11947                 return push_jmp_history(env, cur);
11948
11949         if (!add_new_state)
11950                 return push_jmp_history(env, cur);
11951
11952         /* There were no equivalent states, remember the current one.
11953          * Technically the current state is not proven to be safe yet,
11954          * but it will either reach outer most bpf_exit (which means it's safe)
11955          * or it will be rejected. When there are no loops the verifier won't be
11956          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
11957          * again on the way to bpf_exit.
11958          * When looping the sl->state.branches will be > 0 and this state
11959          * will not be considered for equivalence until branches == 0.
11960          */
11961         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
11962         if (!new_sl)
11963                 return -ENOMEM;
11964         env->total_states++;
11965         env->peak_states++;
11966         env->prev_jmps_processed = env->jmps_processed;
11967         env->prev_insn_processed = env->insn_processed;
11968
11969         /* add new state to the head of linked list */
11970         new = &new_sl->state;
11971         err = copy_verifier_state(new, cur);
11972         if (err) {
11973                 free_verifier_state(new, false);
11974                 kfree(new_sl);
11975                 return err;
11976         }
11977         new->insn_idx = insn_idx;
11978         WARN_ONCE(new->branches != 1,
11979                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
11980
11981         cur->parent = new;
11982         cur->first_insn_idx = insn_idx;
11983         clear_jmp_history(cur);
11984         new_sl->next = *explored_state(env, insn_idx);
11985         *explored_state(env, insn_idx) = new_sl;
11986         /* connect new state to parentage chain. Current frame needs all
11987          * registers connected. Only r6 - r9 of the callers are alive (pushed
11988          * to the stack implicitly by JITs) so in callers' frames connect just
11989          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
11990          * the state of the call instruction (with WRITTEN set), and r0 comes
11991          * from callee with its full parentage chain, anyway.
11992          */
11993         /* clear write marks in current state: the writes we did are not writes
11994          * our child did, so they don't screen off its reads from us.
11995          * (There are no read marks in current state, because reads always mark
11996          * their parent and current state never has children yet.  Only
11997          * explored_states can get read marks.)
11998          */
11999         for (j = 0; j <= cur->curframe; j++) {
12000                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
12001                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
12002                 for (i = 0; i < BPF_REG_FP; i++)
12003                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
12004         }
12005
12006         /* all stack frames are accessible from callee, clear them all */
12007         for (j = 0; j <= cur->curframe; j++) {
12008                 struct bpf_func_state *frame = cur->frame[j];
12009                 struct bpf_func_state *newframe = new->frame[j];
12010
12011                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
12012                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
12013                         frame->stack[i].spilled_ptr.parent =
12014                                                 &newframe->stack[i].spilled_ptr;
12015                 }
12016         }
12017         return 0;
12018 }
12019
12020 /* Return true if it's OK to have the same insn return a different type. */
12021 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
12022 {
12023         switch (base_type(type)) {
12024         case PTR_TO_CTX:
12025         case PTR_TO_SOCKET:
12026         case PTR_TO_SOCK_COMMON:
12027         case PTR_TO_TCP_SOCK:
12028         case PTR_TO_XDP_SOCK:
12029         case PTR_TO_BTF_ID:
12030                 return false;
12031         default:
12032                 return true;
12033         }
12034 }
12035
12036 /* If an instruction was previously used with particular pointer types, then we
12037  * need to be careful to avoid cases such as the below, where it may be ok
12038  * for one branch accessing the pointer, but not ok for the other branch:
12039  *
12040  * R1 = sock_ptr
12041  * goto X;
12042  * ...
12043  * R1 = some_other_valid_ptr;
12044  * goto X;
12045  * ...
12046  * R2 = *(u32 *)(R1 + 0);
12047  */
12048 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
12049 {
12050         return src != prev && (!reg_type_mismatch_ok(src) ||
12051                                !reg_type_mismatch_ok(prev));
12052 }
12053
12054 static int do_check(struct bpf_verifier_env *env)
12055 {
12056         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12057         struct bpf_verifier_state *state = env->cur_state;
12058         struct bpf_insn *insns = env->prog->insnsi;
12059         struct bpf_reg_state *regs;
12060         int insn_cnt = env->prog->len;
12061         bool do_print_state = false;
12062         int prev_insn_idx = -1;
12063
12064         for (;;) {
12065                 struct bpf_insn *insn;
12066                 u8 class;
12067                 int err;
12068
12069                 env->prev_insn_idx = prev_insn_idx;
12070                 if (env->insn_idx >= insn_cnt) {
12071                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
12072                                 env->insn_idx, insn_cnt);
12073                         return -EFAULT;
12074                 }
12075
12076                 insn = &insns[env->insn_idx];
12077                 class = BPF_CLASS(insn->code);
12078
12079                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
12080                         verbose(env,
12081                                 "BPF program is too large. Processed %d insn\n",
12082                                 env->insn_processed);
12083                         return -E2BIG;
12084                 }
12085
12086                 err = is_state_visited(env, env->insn_idx);
12087                 if (err < 0)
12088                         return err;
12089                 if (err == 1) {
12090                         /* found equivalent state, can prune the search */
12091                         if (env->log.level & BPF_LOG_LEVEL) {
12092                                 if (do_print_state)
12093                                         verbose(env, "\nfrom %d to %d%s: safe\n",
12094                                                 env->prev_insn_idx, env->insn_idx,
12095                                                 env->cur_state->speculative ?
12096                                                 " (speculative execution)" : "");
12097                                 else
12098                                         verbose(env, "%d: safe\n", env->insn_idx);
12099                         }
12100                         goto process_bpf_exit;
12101                 }
12102
12103                 if (signal_pending(current))
12104                         return -EAGAIN;
12105
12106                 if (need_resched())
12107                         cond_resched();
12108
12109                 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
12110                         verbose(env, "\nfrom %d to %d%s:",
12111                                 env->prev_insn_idx, env->insn_idx,
12112                                 env->cur_state->speculative ?
12113                                 " (speculative execution)" : "");
12114                         print_verifier_state(env, state->frame[state->curframe], true);
12115                         do_print_state = false;
12116                 }
12117
12118                 if (env->log.level & BPF_LOG_LEVEL) {
12119                         const struct bpf_insn_cbs cbs = {
12120                                 .cb_call        = disasm_kfunc_name,
12121                                 .cb_print       = verbose,
12122                                 .private_data   = env,
12123                         };
12124
12125                         if (verifier_state_scratched(env))
12126                                 print_insn_state(env, state->frame[state->curframe]);
12127
12128                         verbose_linfo(env, env->insn_idx, "; ");
12129                         env->prev_log_len = env->log.len_used;
12130                         verbose(env, "%d: ", env->insn_idx);
12131                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12132                         env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
12133                         env->prev_log_len = env->log.len_used;
12134                 }
12135
12136                 if (bpf_prog_is_dev_bound(env->prog->aux)) {
12137                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
12138                                                            env->prev_insn_idx);
12139                         if (err)
12140                                 return err;
12141                 }
12142
12143                 regs = cur_regs(env);
12144                 sanitize_mark_insn_seen(env);
12145                 prev_insn_idx = env->insn_idx;
12146
12147                 if (class == BPF_ALU || class == BPF_ALU64) {
12148                         err = check_alu_op(env, insn);
12149                         if (err)
12150                                 return err;
12151
12152                 } else if (class == BPF_LDX) {
12153                         enum bpf_reg_type *prev_src_type, src_reg_type;
12154
12155                         /* check for reserved fields is already done */
12156
12157                         /* check src operand */
12158                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
12159                         if (err)
12160                                 return err;
12161
12162                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12163                         if (err)
12164                                 return err;
12165
12166                         src_reg_type = regs[insn->src_reg].type;
12167
12168                         /* check that memory (src_reg + off) is readable,
12169                          * the state of dst_reg will be updated by this func
12170                          */
12171                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
12172                                                insn->off, BPF_SIZE(insn->code),
12173                                                BPF_READ, insn->dst_reg, false);
12174                         if (err)
12175                                 return err;
12176
12177                         prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12178
12179                         if (*prev_src_type == NOT_INIT) {
12180                                 /* saw a valid insn
12181                                  * dst_reg = *(u32 *)(src_reg + off)
12182                                  * save type to validate intersecting paths
12183                                  */
12184                                 *prev_src_type = src_reg_type;
12185
12186                         } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
12187                                 /* ABuser program is trying to use the same insn
12188                                  * dst_reg = *(u32*) (src_reg + off)
12189                                  * with different pointer types:
12190                                  * src_reg == ctx in one branch and
12191                                  * src_reg == stack|map in some other branch.
12192                                  * Reject it.
12193                                  */
12194                                 verbose(env, "same insn cannot be used with different pointers\n");
12195                                 return -EINVAL;
12196                         }
12197
12198                 } else if (class == BPF_STX) {
12199                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
12200
12201                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
12202                                 err = check_atomic(env, env->insn_idx, insn);
12203                                 if (err)
12204                                         return err;
12205                                 env->insn_idx++;
12206                                 continue;
12207                         }
12208
12209                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
12210                                 verbose(env, "BPF_STX uses reserved fields\n");
12211                                 return -EINVAL;
12212                         }
12213
12214                         /* check src1 operand */
12215                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
12216                         if (err)
12217                                 return err;
12218                         /* check src2 operand */
12219                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12220                         if (err)
12221                                 return err;
12222
12223                         dst_reg_type = regs[insn->dst_reg].type;
12224
12225                         /* check that memory (dst_reg + off) is writeable */
12226                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12227                                                insn->off, BPF_SIZE(insn->code),
12228                                                BPF_WRITE, insn->src_reg, false);
12229                         if (err)
12230                                 return err;
12231
12232                         prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12233
12234                         if (*prev_dst_type == NOT_INIT) {
12235                                 *prev_dst_type = dst_reg_type;
12236                         } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
12237                                 verbose(env, "same insn cannot be used with different pointers\n");
12238                                 return -EINVAL;
12239                         }
12240
12241                 } else if (class == BPF_ST) {
12242                         if (BPF_MODE(insn->code) != BPF_MEM ||
12243                             insn->src_reg != BPF_REG_0) {
12244                                 verbose(env, "BPF_ST uses reserved fields\n");
12245                                 return -EINVAL;
12246                         }
12247                         /* check src operand */
12248                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12249                         if (err)
12250                                 return err;
12251
12252                         if (is_ctx_reg(env, insn->dst_reg)) {
12253                                 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
12254                                         insn->dst_reg,
12255                                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
12256                                 return -EACCES;
12257                         }
12258
12259                         /* check that memory (dst_reg + off) is writeable */
12260                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12261                                                insn->off, BPF_SIZE(insn->code),
12262                                                BPF_WRITE, -1, false);
12263                         if (err)
12264                                 return err;
12265
12266                 } else if (class == BPF_JMP || class == BPF_JMP32) {
12267                         u8 opcode = BPF_OP(insn->code);
12268
12269                         env->jmps_processed++;
12270                         if (opcode == BPF_CALL) {
12271                                 if (BPF_SRC(insn->code) != BPF_K ||
12272                                     (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
12273                                      && insn->off != 0) ||
12274                                     (insn->src_reg != BPF_REG_0 &&
12275                                      insn->src_reg != BPF_PSEUDO_CALL &&
12276                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
12277                                     insn->dst_reg != BPF_REG_0 ||
12278                                     class == BPF_JMP32) {
12279                                         verbose(env, "BPF_CALL uses reserved fields\n");
12280                                         return -EINVAL;
12281                                 }
12282
12283                                 if (env->cur_state->active_spin_lock &&
12284                                     (insn->src_reg == BPF_PSEUDO_CALL ||
12285                                      insn->imm != BPF_FUNC_spin_unlock)) {
12286                                         verbose(env, "function calls are not allowed while holding a lock\n");
12287                                         return -EINVAL;
12288                                 }
12289                                 if (insn->src_reg == BPF_PSEUDO_CALL)
12290                                         err = check_func_call(env, insn, &env->insn_idx);
12291                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
12292                                         err = check_kfunc_call(env, insn, &env->insn_idx);
12293                                 else
12294                                         err = check_helper_call(env, insn, &env->insn_idx);
12295                                 if (err)
12296                                         return err;
12297                         } else if (opcode == BPF_JA) {
12298                                 if (BPF_SRC(insn->code) != BPF_K ||
12299                                     insn->imm != 0 ||
12300                                     insn->src_reg != BPF_REG_0 ||
12301                                     insn->dst_reg != BPF_REG_0 ||
12302                                     class == BPF_JMP32) {
12303                                         verbose(env, "BPF_JA uses reserved fields\n");
12304                                         return -EINVAL;
12305                                 }
12306
12307                                 env->insn_idx += insn->off + 1;
12308                                 continue;
12309
12310                         } else if (opcode == BPF_EXIT) {
12311                                 if (BPF_SRC(insn->code) != BPF_K ||
12312                                     insn->imm != 0 ||
12313                                     insn->src_reg != BPF_REG_0 ||
12314                                     insn->dst_reg != BPF_REG_0 ||
12315                                     class == BPF_JMP32) {
12316                                         verbose(env, "BPF_EXIT uses reserved fields\n");
12317                                         return -EINVAL;
12318                                 }
12319
12320                                 if (env->cur_state->active_spin_lock) {
12321                                         verbose(env, "bpf_spin_unlock is missing\n");
12322                                         return -EINVAL;
12323                                 }
12324
12325                                 if (state->curframe) {
12326                                         /* exit from nested function */
12327                                         err = prepare_func_exit(env, &env->insn_idx);
12328                                         if (err)
12329                                                 return err;
12330                                         do_print_state = true;
12331                                         continue;
12332                                 }
12333
12334                                 err = check_reference_leak(env);
12335                                 if (err)
12336                                         return err;
12337
12338                                 err = check_return_code(env);
12339                                 if (err)
12340                                         return err;
12341 process_bpf_exit:
12342                                 mark_verifier_state_scratched(env);
12343                                 update_branch_counts(env, env->cur_state);
12344                                 err = pop_stack(env, &prev_insn_idx,
12345                                                 &env->insn_idx, pop_log);
12346                                 if (err < 0) {
12347                                         if (err != -ENOENT)
12348                                                 return err;
12349                                         break;
12350                                 } else {
12351                                         do_print_state = true;
12352                                         continue;
12353                                 }
12354                         } else {
12355                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
12356                                 if (err)
12357                                         return err;
12358                         }
12359                 } else if (class == BPF_LD) {
12360                         u8 mode = BPF_MODE(insn->code);
12361
12362                         if (mode == BPF_ABS || mode == BPF_IND) {
12363                                 err = check_ld_abs(env, insn);
12364                                 if (err)
12365                                         return err;
12366
12367                         } else if (mode == BPF_IMM) {
12368                                 err = check_ld_imm(env, insn);
12369                                 if (err)
12370                                         return err;
12371
12372                                 env->insn_idx++;
12373                                 sanitize_mark_insn_seen(env);
12374                         } else {
12375                                 verbose(env, "invalid BPF_LD mode\n");
12376                                 return -EINVAL;
12377                         }
12378                 } else {
12379                         verbose(env, "unknown insn class %d\n", class);
12380                         return -EINVAL;
12381                 }
12382
12383                 env->insn_idx++;
12384         }
12385
12386         return 0;
12387 }
12388
12389 static int find_btf_percpu_datasec(struct btf *btf)
12390 {
12391         const struct btf_type *t;
12392         const char *tname;
12393         int i, n;
12394
12395         /*
12396          * Both vmlinux and module each have their own ".data..percpu"
12397          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
12398          * types to look at only module's own BTF types.
12399          */
12400         n = btf_nr_types(btf);
12401         if (btf_is_module(btf))
12402                 i = btf_nr_types(btf_vmlinux);
12403         else
12404                 i = 1;
12405
12406         for(; i < n; i++) {
12407                 t = btf_type_by_id(btf, i);
12408                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
12409                         continue;
12410
12411                 tname = btf_name_by_offset(btf, t->name_off);
12412                 if (!strcmp(tname, ".data..percpu"))
12413                         return i;
12414         }
12415
12416         return -ENOENT;
12417 }
12418
12419 /* replace pseudo btf_id with kernel symbol address */
12420 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
12421                                struct bpf_insn *insn,
12422                                struct bpf_insn_aux_data *aux)
12423 {
12424         const struct btf_var_secinfo *vsi;
12425         const struct btf_type *datasec;
12426         struct btf_mod_pair *btf_mod;
12427         const struct btf_type *t;
12428         const char *sym_name;
12429         bool percpu = false;
12430         u32 type, id = insn->imm;
12431         struct btf *btf;
12432         s32 datasec_id;
12433         u64 addr;
12434         int i, btf_fd, err;
12435
12436         btf_fd = insn[1].imm;
12437         if (btf_fd) {
12438                 btf = btf_get_by_fd(btf_fd);
12439                 if (IS_ERR(btf)) {
12440                         verbose(env, "invalid module BTF object FD specified.\n");
12441                         return -EINVAL;
12442                 }
12443         } else {
12444                 if (!btf_vmlinux) {
12445                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
12446                         return -EINVAL;
12447                 }
12448                 btf = btf_vmlinux;
12449                 btf_get(btf);
12450         }
12451
12452         t = btf_type_by_id(btf, id);
12453         if (!t) {
12454                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
12455                 err = -ENOENT;
12456                 goto err_put;
12457         }
12458
12459         if (!btf_type_is_var(t)) {
12460                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
12461                 err = -EINVAL;
12462                 goto err_put;
12463         }
12464
12465         sym_name = btf_name_by_offset(btf, t->name_off);
12466         addr = kallsyms_lookup_name(sym_name);
12467         if (!addr) {
12468                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
12469                         sym_name);
12470                 err = -ENOENT;
12471                 goto err_put;
12472         }
12473
12474         datasec_id = find_btf_percpu_datasec(btf);
12475         if (datasec_id > 0) {
12476                 datasec = btf_type_by_id(btf, datasec_id);
12477                 for_each_vsi(i, datasec, vsi) {
12478                         if (vsi->type == id) {
12479                                 percpu = true;
12480                                 break;
12481                         }
12482                 }
12483         }
12484
12485         insn[0].imm = (u32)addr;
12486         insn[1].imm = addr >> 32;
12487
12488         type = t->type;
12489         t = btf_type_skip_modifiers(btf, type, NULL);
12490         if (percpu) {
12491                 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
12492                 aux->btf_var.btf = btf;
12493                 aux->btf_var.btf_id = type;
12494         } else if (!btf_type_is_struct(t)) {
12495                 const struct btf_type *ret;
12496                 const char *tname;
12497                 u32 tsize;
12498
12499                 /* resolve the type size of ksym. */
12500                 ret = btf_resolve_size(btf, t, &tsize);
12501                 if (IS_ERR(ret)) {
12502                         tname = btf_name_by_offset(btf, t->name_off);
12503                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
12504                                 tname, PTR_ERR(ret));
12505                         err = -EINVAL;
12506                         goto err_put;
12507                 }
12508                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
12509                 aux->btf_var.mem_size = tsize;
12510         } else {
12511                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
12512                 aux->btf_var.btf = btf;
12513                 aux->btf_var.btf_id = type;
12514         }
12515
12516         /* check whether we recorded this BTF (and maybe module) already */
12517         for (i = 0; i < env->used_btf_cnt; i++) {
12518                 if (env->used_btfs[i].btf == btf) {
12519                         btf_put(btf);
12520                         return 0;
12521                 }
12522         }
12523
12524         if (env->used_btf_cnt >= MAX_USED_BTFS) {
12525                 err = -E2BIG;
12526                 goto err_put;
12527         }
12528
12529         btf_mod = &env->used_btfs[env->used_btf_cnt];
12530         btf_mod->btf = btf;
12531         btf_mod->module = NULL;
12532
12533         /* if we reference variables from kernel module, bump its refcount */
12534         if (btf_is_module(btf)) {
12535                 btf_mod->module = btf_try_get_module(btf);
12536                 if (!btf_mod->module) {
12537                         err = -ENXIO;
12538                         goto err_put;
12539                 }
12540         }
12541
12542         env->used_btf_cnt++;
12543
12544         return 0;
12545 err_put:
12546         btf_put(btf);
12547         return err;
12548 }
12549
12550 static int check_map_prealloc(struct bpf_map *map)
12551 {
12552         return (map->map_type != BPF_MAP_TYPE_HASH &&
12553                 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
12554                 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
12555                 !(map->map_flags & BPF_F_NO_PREALLOC);
12556 }
12557
12558 static bool is_tracing_prog_type(enum bpf_prog_type type)
12559 {
12560         switch (type) {
12561         case BPF_PROG_TYPE_KPROBE:
12562         case BPF_PROG_TYPE_TRACEPOINT:
12563         case BPF_PROG_TYPE_PERF_EVENT:
12564         case BPF_PROG_TYPE_RAW_TRACEPOINT:
12565                 return true;
12566         default:
12567                 return false;
12568         }
12569 }
12570
12571 static bool is_preallocated_map(struct bpf_map *map)
12572 {
12573         if (!check_map_prealloc(map))
12574                 return false;
12575         if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
12576                 return false;
12577         return true;
12578 }
12579
12580 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
12581                                         struct bpf_map *map,
12582                                         struct bpf_prog *prog)
12583
12584 {
12585         enum bpf_prog_type prog_type = resolve_prog_type(prog);
12586         /*
12587          * Validate that trace type programs use preallocated hash maps.
12588          *
12589          * For programs attached to PERF events this is mandatory as the
12590          * perf NMI can hit any arbitrary code sequence.
12591          *
12592          * All other trace types using preallocated hash maps are unsafe as
12593          * well because tracepoint or kprobes can be inside locked regions
12594          * of the memory allocator or at a place where a recursion into the
12595          * memory allocator would see inconsistent state.
12596          *
12597          * On RT enabled kernels run-time allocation of all trace type
12598          * programs is strictly prohibited due to lock type constraints. On
12599          * !RT kernels it is allowed for backwards compatibility reasons for
12600          * now, but warnings are emitted so developers are made aware of
12601          * the unsafety and can fix their programs before this is enforced.
12602          */
12603         if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
12604                 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
12605                         verbose(env, "perf_event programs can only use preallocated hash map\n");
12606                         return -EINVAL;
12607                 }
12608                 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
12609                         verbose(env, "trace type programs can only use preallocated hash map\n");
12610                         return -EINVAL;
12611                 }
12612                 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
12613                 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
12614         }
12615
12616         if (map_value_has_spin_lock(map)) {
12617                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12618                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12619                         return -EINVAL;
12620                 }
12621
12622                 if (is_tracing_prog_type(prog_type)) {
12623                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12624                         return -EINVAL;
12625                 }
12626
12627                 if (prog->aux->sleepable) {
12628                         verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12629                         return -EINVAL;
12630                 }
12631         }
12632
12633         if (map_value_has_timer(map)) {
12634                 if (is_tracing_prog_type(prog_type)) {
12635                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
12636                         return -EINVAL;
12637                 }
12638         }
12639
12640         if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
12641             !bpf_offload_prog_map_match(prog, map)) {
12642                 verbose(env, "offload device mismatch between prog and map\n");
12643                 return -EINVAL;
12644         }
12645
12646         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
12647                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
12648                 return -EINVAL;
12649         }
12650
12651         if (prog->aux->sleepable)
12652                 switch (map->map_type) {
12653                 case BPF_MAP_TYPE_HASH:
12654                 case BPF_MAP_TYPE_LRU_HASH:
12655                 case BPF_MAP_TYPE_ARRAY:
12656                 case BPF_MAP_TYPE_PERCPU_HASH:
12657                 case BPF_MAP_TYPE_PERCPU_ARRAY:
12658                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12659                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
12660                 case BPF_MAP_TYPE_HASH_OF_MAPS:
12661                         if (!is_preallocated_map(map)) {
12662                                 verbose(env,
12663                                         "Sleepable programs can only use preallocated maps\n");
12664                                 return -EINVAL;
12665                         }
12666                         break;
12667                 case BPF_MAP_TYPE_RINGBUF:
12668                 case BPF_MAP_TYPE_INODE_STORAGE:
12669                 case BPF_MAP_TYPE_SK_STORAGE:
12670                 case BPF_MAP_TYPE_TASK_STORAGE:
12671                         break;
12672                 default:
12673                         verbose(env,
12674                                 "Sleepable programs can only use array, hash, and ringbuf maps\n");
12675                         return -EINVAL;
12676                 }
12677
12678         return 0;
12679 }
12680
12681 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
12682 {
12683         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
12684                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
12685 }
12686
12687 /* find and rewrite pseudo imm in ld_imm64 instructions:
12688  *
12689  * 1. if it accesses map FD, replace it with actual map pointer.
12690  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
12691  *
12692  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
12693  */
12694 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
12695 {
12696         struct bpf_insn *insn = env->prog->insnsi;
12697         int insn_cnt = env->prog->len;
12698         int i, j, err;
12699
12700         err = bpf_prog_calc_tag(env->prog);
12701         if (err)
12702                 return err;
12703
12704         for (i = 0; i < insn_cnt; i++, insn++) {
12705                 if (BPF_CLASS(insn->code) == BPF_LDX &&
12706                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
12707                         verbose(env, "BPF_LDX uses reserved fields\n");
12708                         return -EINVAL;
12709                 }
12710
12711                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
12712                         struct bpf_insn_aux_data *aux;
12713                         struct bpf_map *map;
12714                         struct fd f;
12715                         u64 addr;
12716                         u32 fd;
12717
12718                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
12719                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
12720                             insn[1].off != 0) {
12721                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
12722                                 return -EINVAL;
12723                         }
12724
12725                         if (insn[0].src_reg == 0)
12726                                 /* valid generic load 64-bit imm */
12727                                 goto next_insn;
12728
12729                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
12730                                 aux = &env->insn_aux_data[i];
12731                                 err = check_pseudo_btf_id(env, insn, aux);
12732                                 if (err)
12733                                         return err;
12734                                 goto next_insn;
12735                         }
12736
12737                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
12738                                 aux = &env->insn_aux_data[i];
12739                                 aux->ptr_type = PTR_TO_FUNC;
12740                                 goto next_insn;
12741                         }
12742
12743                         /* In final convert_pseudo_ld_imm64() step, this is
12744                          * converted into regular 64-bit imm load insn.
12745                          */
12746                         switch (insn[0].src_reg) {
12747                         case BPF_PSEUDO_MAP_VALUE:
12748                         case BPF_PSEUDO_MAP_IDX_VALUE:
12749                                 break;
12750                         case BPF_PSEUDO_MAP_FD:
12751                         case BPF_PSEUDO_MAP_IDX:
12752                                 if (insn[1].imm == 0)
12753                                         break;
12754                                 fallthrough;
12755                         default:
12756                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
12757                                 return -EINVAL;
12758                         }
12759
12760                         switch (insn[0].src_reg) {
12761                         case BPF_PSEUDO_MAP_IDX_VALUE:
12762                         case BPF_PSEUDO_MAP_IDX:
12763                                 if (bpfptr_is_null(env->fd_array)) {
12764                                         verbose(env, "fd_idx without fd_array is invalid\n");
12765                                         return -EPROTO;
12766                                 }
12767                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
12768                                                             insn[0].imm * sizeof(fd),
12769                                                             sizeof(fd)))
12770                                         return -EFAULT;
12771                                 break;
12772                         default:
12773                                 fd = insn[0].imm;
12774                                 break;
12775                         }
12776
12777                         f = fdget(fd);
12778                         map = __bpf_map_get(f);
12779                         if (IS_ERR(map)) {
12780                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
12781                                         insn[0].imm);
12782                                 return PTR_ERR(map);
12783                         }
12784
12785                         err = check_map_prog_compatibility(env, map, env->prog);
12786                         if (err) {
12787                                 fdput(f);
12788                                 return err;
12789                         }
12790
12791                         aux = &env->insn_aux_data[i];
12792                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12793                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
12794                                 addr = (unsigned long)map;
12795                         } else {
12796                                 u32 off = insn[1].imm;
12797
12798                                 if (off >= BPF_MAX_VAR_OFF) {
12799                                         verbose(env, "direct value offset of %u is not allowed\n", off);
12800                                         fdput(f);
12801                                         return -EINVAL;
12802                                 }
12803
12804                                 if (!map->ops->map_direct_value_addr) {
12805                                         verbose(env, "no direct value access support for this map type\n");
12806                                         fdput(f);
12807                                         return -EINVAL;
12808                                 }
12809
12810                                 err = map->ops->map_direct_value_addr(map, &addr, off);
12811                                 if (err) {
12812                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12813                                                 map->value_size, off);
12814                                         fdput(f);
12815                                         return err;
12816                                 }
12817
12818                                 aux->map_off = off;
12819                                 addr += off;
12820                         }
12821
12822                         insn[0].imm = (u32)addr;
12823                         insn[1].imm = addr >> 32;
12824
12825                         /* check whether we recorded this map already */
12826                         for (j = 0; j < env->used_map_cnt; j++) {
12827                                 if (env->used_maps[j] == map) {
12828                                         aux->map_index = j;
12829                                         fdput(f);
12830                                         goto next_insn;
12831                                 }
12832                         }
12833
12834                         if (env->used_map_cnt >= MAX_USED_MAPS) {
12835                                 fdput(f);
12836                                 return -E2BIG;
12837                         }
12838
12839                         /* hold the map. If the program is rejected by verifier,
12840                          * the map will be released by release_maps() or it
12841                          * will be used by the valid program until it's unloaded
12842                          * and all maps are released in free_used_maps()
12843                          */
12844                         bpf_map_inc(map);
12845
12846                         aux->map_index = env->used_map_cnt;
12847                         env->used_maps[env->used_map_cnt++] = map;
12848
12849                         if (bpf_map_is_cgroup_storage(map) &&
12850                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
12851                                 verbose(env, "only one cgroup storage of each type is allowed\n");
12852                                 fdput(f);
12853                                 return -EBUSY;
12854                         }
12855
12856                         fdput(f);
12857 next_insn:
12858                         insn++;
12859                         i++;
12860                         continue;
12861                 }
12862
12863                 /* Basic sanity check before we invest more work here. */
12864                 if (!bpf_opcode_in_insntable(insn->code)) {
12865                         verbose(env, "unknown opcode %02x\n", insn->code);
12866                         return -EINVAL;
12867                 }
12868         }
12869
12870         /* now all pseudo BPF_LD_IMM64 instructions load valid
12871          * 'struct bpf_map *' into a register instead of user map_fd.
12872          * These pointers will be used later by verifier to validate map access.
12873          */
12874         return 0;
12875 }
12876
12877 /* drop refcnt of maps used by the rejected program */
12878 static void release_maps(struct bpf_verifier_env *env)
12879 {
12880         __bpf_free_used_maps(env->prog->aux, env->used_maps,
12881                              env->used_map_cnt);
12882 }
12883
12884 /* drop refcnt of maps used by the rejected program */
12885 static void release_btfs(struct bpf_verifier_env *env)
12886 {
12887         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
12888                              env->used_btf_cnt);
12889 }
12890
12891 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
12892 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
12893 {
12894         struct bpf_insn *insn = env->prog->insnsi;
12895         int insn_cnt = env->prog->len;
12896         int i;
12897
12898         for (i = 0; i < insn_cnt; i++, insn++) {
12899                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
12900                         continue;
12901                 if (insn->src_reg == BPF_PSEUDO_FUNC)
12902                         continue;
12903                 insn->src_reg = 0;
12904         }
12905 }
12906
12907 /* single env->prog->insni[off] instruction was replaced with the range
12908  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
12909  * [0, off) and [off, end) to new locations, so the patched range stays zero
12910  */
12911 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
12912                                  struct bpf_insn_aux_data *new_data,
12913                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
12914 {
12915         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
12916         struct bpf_insn *insn = new_prog->insnsi;
12917         u32 old_seen = old_data[off].seen;
12918         u32 prog_len;
12919         int i;
12920
12921         /* aux info at OFF always needs adjustment, no matter fast path
12922          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
12923          * original insn at old prog.
12924          */
12925         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
12926
12927         if (cnt == 1)
12928                 return;
12929         prog_len = new_prog->len;
12930
12931         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
12932         memcpy(new_data + off + cnt - 1, old_data + off,
12933                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
12934         for (i = off; i < off + cnt - 1; i++) {
12935                 /* Expand insni[off]'s seen count to the patched range. */
12936                 new_data[i].seen = old_seen;
12937                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
12938         }
12939         env->insn_aux_data = new_data;
12940         vfree(old_data);
12941 }
12942
12943 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
12944 {
12945         int i;
12946
12947         if (len == 1)
12948                 return;
12949         /* NOTE: fake 'exit' subprog should be updated as well. */
12950         for (i = 0; i <= env->subprog_cnt; i++) {
12951                 if (env->subprog_info[i].start <= off)
12952                         continue;
12953                 env->subprog_info[i].start += len - 1;
12954         }
12955 }
12956
12957 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
12958 {
12959         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
12960         int i, sz = prog->aux->size_poke_tab;
12961         struct bpf_jit_poke_descriptor *desc;
12962
12963         for (i = 0; i < sz; i++) {
12964                 desc = &tab[i];
12965                 if (desc->insn_idx <= off)
12966                         continue;
12967                 desc->insn_idx += len - 1;
12968         }
12969 }
12970
12971 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
12972                                             const struct bpf_insn *patch, u32 len)
12973 {
12974         struct bpf_prog *new_prog;
12975         struct bpf_insn_aux_data *new_data = NULL;
12976
12977         if (len > 1) {
12978                 new_data = vzalloc(array_size(env->prog->len + len - 1,
12979                                               sizeof(struct bpf_insn_aux_data)));
12980                 if (!new_data)
12981                         return NULL;
12982         }
12983
12984         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
12985         if (IS_ERR(new_prog)) {
12986                 if (PTR_ERR(new_prog) == -ERANGE)
12987                         verbose(env,
12988                                 "insn %d cannot be patched due to 16-bit range\n",
12989                                 env->insn_aux_data[off].orig_idx);
12990                 vfree(new_data);
12991                 return NULL;
12992         }
12993         adjust_insn_aux_data(env, new_data, new_prog, off, len);
12994         adjust_subprog_starts(env, off, len);
12995         adjust_poke_descs(new_prog, off, len);
12996         return new_prog;
12997 }
12998
12999 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
13000                                               u32 off, u32 cnt)
13001 {
13002         int i, j;
13003
13004         /* find first prog starting at or after off (first to remove) */
13005         for (i = 0; i < env->subprog_cnt; i++)
13006                 if (env->subprog_info[i].start >= off)
13007                         break;
13008         /* find first prog starting at or after off + cnt (first to stay) */
13009         for (j = i; j < env->subprog_cnt; j++)
13010                 if (env->subprog_info[j].start >= off + cnt)
13011                         break;
13012         /* if j doesn't start exactly at off + cnt, we are just removing
13013          * the front of previous prog
13014          */
13015         if (env->subprog_info[j].start != off + cnt)
13016                 j--;
13017
13018         if (j > i) {
13019                 struct bpf_prog_aux *aux = env->prog->aux;
13020                 int move;
13021
13022                 /* move fake 'exit' subprog as well */
13023                 move = env->subprog_cnt + 1 - j;
13024
13025                 memmove(env->subprog_info + i,
13026                         env->subprog_info + j,
13027                         sizeof(*env->subprog_info) * move);
13028                 env->subprog_cnt -= j - i;
13029
13030                 /* remove func_info */
13031                 if (aux->func_info) {
13032                         move = aux->func_info_cnt - j;
13033
13034                         memmove(aux->func_info + i,
13035                                 aux->func_info + j,
13036                                 sizeof(*aux->func_info) * move);
13037                         aux->func_info_cnt -= j - i;
13038                         /* func_info->insn_off is set after all code rewrites,
13039                          * in adjust_btf_func() - no need to adjust
13040                          */
13041                 }
13042         } else {
13043                 /* convert i from "first prog to remove" to "first to adjust" */
13044                 if (env->subprog_info[i].start == off)
13045                         i++;
13046         }
13047
13048         /* update fake 'exit' subprog as well */
13049         for (; i <= env->subprog_cnt; i++)
13050                 env->subprog_info[i].start -= cnt;
13051
13052         return 0;
13053 }
13054
13055 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
13056                                       u32 cnt)
13057 {
13058         struct bpf_prog *prog = env->prog;
13059         u32 i, l_off, l_cnt, nr_linfo;
13060         struct bpf_line_info *linfo;
13061
13062         nr_linfo = prog->aux->nr_linfo;
13063         if (!nr_linfo)
13064                 return 0;
13065
13066         linfo = prog->aux->linfo;
13067
13068         /* find first line info to remove, count lines to be removed */
13069         for (i = 0; i < nr_linfo; i++)
13070                 if (linfo[i].insn_off >= off)
13071                         break;
13072
13073         l_off = i;
13074         l_cnt = 0;
13075         for (; i < nr_linfo; i++)
13076                 if (linfo[i].insn_off < off + cnt)
13077                         l_cnt++;
13078                 else
13079                         break;
13080
13081         /* First live insn doesn't match first live linfo, it needs to "inherit"
13082          * last removed linfo.  prog is already modified, so prog->len == off
13083          * means no live instructions after (tail of the program was removed).
13084          */
13085         if (prog->len != off && l_cnt &&
13086             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
13087                 l_cnt--;
13088                 linfo[--i].insn_off = off + cnt;
13089         }
13090
13091         /* remove the line info which refer to the removed instructions */
13092         if (l_cnt) {
13093                 memmove(linfo + l_off, linfo + i,
13094                         sizeof(*linfo) * (nr_linfo - i));
13095
13096                 prog->aux->nr_linfo -= l_cnt;
13097                 nr_linfo = prog->aux->nr_linfo;
13098         }
13099
13100         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
13101         for (i = l_off; i < nr_linfo; i++)
13102                 linfo[i].insn_off -= cnt;
13103
13104         /* fix up all subprogs (incl. 'exit') which start >= off */
13105         for (i = 0; i <= env->subprog_cnt; i++)
13106                 if (env->subprog_info[i].linfo_idx > l_off) {
13107                         /* program may have started in the removed region but
13108                          * may not be fully removed
13109                          */
13110                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
13111                                 env->subprog_info[i].linfo_idx -= l_cnt;
13112                         else
13113                                 env->subprog_info[i].linfo_idx = l_off;
13114                 }
13115
13116         return 0;
13117 }
13118
13119 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
13120 {
13121         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13122         unsigned int orig_prog_len = env->prog->len;
13123         int err;
13124
13125         if (bpf_prog_is_dev_bound(env->prog->aux))
13126                 bpf_prog_offload_remove_insns(env, off, cnt);
13127
13128         err = bpf_remove_insns(env->prog, off, cnt);
13129         if (err)
13130                 return err;
13131
13132         err = adjust_subprog_starts_after_remove(env, off, cnt);
13133         if (err)
13134                 return err;
13135
13136         err = bpf_adj_linfo_after_remove(env, off, cnt);
13137         if (err)
13138                 return err;
13139
13140         memmove(aux_data + off, aux_data + off + cnt,
13141                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
13142
13143         return 0;
13144 }
13145
13146 /* The verifier does more data flow analysis than llvm and will not
13147  * explore branches that are dead at run time. Malicious programs can
13148  * have dead code too. Therefore replace all dead at-run-time code
13149  * with 'ja -1'.
13150  *
13151  * Just nops are not optimal, e.g. if they would sit at the end of the
13152  * program and through another bug we would manage to jump there, then
13153  * we'd execute beyond program memory otherwise. Returning exception
13154  * code also wouldn't work since we can have subprogs where the dead
13155  * code could be located.
13156  */
13157 static void sanitize_dead_code(struct bpf_verifier_env *env)
13158 {
13159         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13160         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
13161         struct bpf_insn *insn = env->prog->insnsi;
13162         const int insn_cnt = env->prog->len;
13163         int i;
13164
13165         for (i = 0; i < insn_cnt; i++) {
13166                 if (aux_data[i].seen)
13167                         continue;
13168                 memcpy(insn + i, &trap, sizeof(trap));
13169                 aux_data[i].zext_dst = false;
13170         }
13171 }
13172
13173 static bool insn_is_cond_jump(u8 code)
13174 {
13175         u8 op;
13176
13177         if (BPF_CLASS(code) == BPF_JMP32)
13178                 return true;
13179
13180         if (BPF_CLASS(code) != BPF_JMP)
13181                 return false;
13182
13183         op = BPF_OP(code);
13184         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
13185 }
13186
13187 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
13188 {
13189         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13190         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13191         struct bpf_insn *insn = env->prog->insnsi;
13192         const int insn_cnt = env->prog->len;
13193         int i;
13194
13195         for (i = 0; i < insn_cnt; i++, insn++) {
13196                 if (!insn_is_cond_jump(insn->code))
13197                         continue;
13198
13199                 if (!aux_data[i + 1].seen)
13200                         ja.off = insn->off;
13201                 else if (!aux_data[i + 1 + insn->off].seen)
13202                         ja.off = 0;
13203                 else
13204                         continue;
13205
13206                 if (bpf_prog_is_dev_bound(env->prog->aux))
13207                         bpf_prog_offload_replace_insn(env, i, &ja);
13208
13209                 memcpy(insn, &ja, sizeof(ja));
13210         }
13211 }
13212
13213 static int opt_remove_dead_code(struct bpf_verifier_env *env)
13214 {
13215         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13216         int insn_cnt = env->prog->len;
13217         int i, err;
13218
13219         for (i = 0; i < insn_cnt; i++) {
13220                 int j;
13221
13222                 j = 0;
13223                 while (i + j < insn_cnt && !aux_data[i + j].seen)
13224                         j++;
13225                 if (!j)
13226                         continue;
13227
13228                 err = verifier_remove_insns(env, i, j);
13229                 if (err)
13230                         return err;
13231                 insn_cnt = env->prog->len;
13232         }
13233
13234         return 0;
13235 }
13236
13237 static int opt_remove_nops(struct bpf_verifier_env *env)
13238 {
13239         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13240         struct bpf_insn *insn = env->prog->insnsi;
13241         int insn_cnt = env->prog->len;
13242         int i, err;
13243
13244         for (i = 0; i < insn_cnt; i++) {
13245                 if (memcmp(&insn[i], &ja, sizeof(ja)))
13246                         continue;
13247
13248                 err = verifier_remove_insns(env, i, 1);
13249                 if (err)
13250                         return err;
13251                 insn_cnt--;
13252                 i--;
13253         }
13254
13255         return 0;
13256 }
13257
13258 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
13259                                          const union bpf_attr *attr)
13260 {
13261         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
13262         struct bpf_insn_aux_data *aux = env->insn_aux_data;
13263         int i, patch_len, delta = 0, len = env->prog->len;
13264         struct bpf_insn *insns = env->prog->insnsi;
13265         struct bpf_prog *new_prog;
13266         bool rnd_hi32;
13267
13268         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
13269         zext_patch[1] = BPF_ZEXT_REG(0);
13270         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
13271         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
13272         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
13273         for (i = 0; i < len; i++) {
13274                 int adj_idx = i + delta;
13275                 struct bpf_insn insn;
13276                 int load_reg;
13277
13278                 insn = insns[adj_idx];
13279                 load_reg = insn_def_regno(&insn);
13280                 if (!aux[adj_idx].zext_dst) {
13281                         u8 code, class;
13282                         u32 imm_rnd;
13283
13284                         if (!rnd_hi32)
13285                                 continue;
13286
13287                         code = insn.code;
13288                         class = BPF_CLASS(code);
13289                         if (load_reg == -1)
13290                                 continue;
13291
13292                         /* NOTE: arg "reg" (the fourth one) is only used for
13293                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
13294                          *       here.
13295                          */
13296                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
13297                                 if (class == BPF_LD &&
13298                                     BPF_MODE(code) == BPF_IMM)
13299                                         i++;
13300                                 continue;
13301                         }
13302
13303                         /* ctx load could be transformed into wider load. */
13304                         if (class == BPF_LDX &&
13305                             aux[adj_idx].ptr_type == PTR_TO_CTX)
13306                                 continue;
13307
13308                         imm_rnd = get_random_int();
13309                         rnd_hi32_patch[0] = insn;
13310                         rnd_hi32_patch[1].imm = imm_rnd;
13311                         rnd_hi32_patch[3].dst_reg = load_reg;
13312                         patch = rnd_hi32_patch;
13313                         patch_len = 4;
13314                         goto apply_patch_buffer;
13315                 }
13316
13317                 /* Add in an zero-extend instruction if a) the JIT has requested
13318                  * it or b) it's a CMPXCHG.
13319                  *
13320                  * The latter is because: BPF_CMPXCHG always loads a value into
13321                  * R0, therefore always zero-extends. However some archs'
13322                  * equivalent instruction only does this load when the
13323                  * comparison is successful. This detail of CMPXCHG is
13324                  * orthogonal to the general zero-extension behaviour of the
13325                  * CPU, so it's treated independently of bpf_jit_needs_zext.
13326                  */
13327                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
13328                         continue;
13329
13330                 if (WARN_ON(load_reg == -1)) {
13331                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
13332                         return -EFAULT;
13333                 }
13334
13335                 zext_patch[0] = insn;
13336                 zext_patch[1].dst_reg = load_reg;
13337                 zext_patch[1].src_reg = load_reg;
13338                 patch = zext_patch;
13339                 patch_len = 2;
13340 apply_patch_buffer:
13341                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
13342                 if (!new_prog)
13343                         return -ENOMEM;
13344                 env->prog = new_prog;
13345                 insns = new_prog->insnsi;
13346                 aux = env->insn_aux_data;
13347                 delta += patch_len - 1;
13348         }
13349
13350         return 0;
13351 }
13352
13353 /* convert load instructions that access fields of a context type into a
13354  * sequence of instructions that access fields of the underlying structure:
13355  *     struct __sk_buff    -> struct sk_buff
13356  *     struct bpf_sock_ops -> struct sock
13357  */
13358 static int convert_ctx_accesses(struct bpf_verifier_env *env)
13359 {
13360         const struct bpf_verifier_ops *ops = env->ops;
13361         int i, cnt, size, ctx_field_size, delta = 0;
13362         const int insn_cnt = env->prog->len;
13363         struct bpf_insn insn_buf[16], *insn;
13364         u32 target_size, size_default, off;
13365         struct bpf_prog *new_prog;
13366         enum bpf_access_type type;
13367         bool is_narrower_load;
13368
13369         if (ops->gen_prologue || env->seen_direct_write) {
13370                 if (!ops->gen_prologue) {
13371                         verbose(env, "bpf verifier is misconfigured\n");
13372                         return -EINVAL;
13373                 }
13374                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
13375                                         env->prog);
13376                 if (cnt >= ARRAY_SIZE(insn_buf)) {
13377                         verbose(env, "bpf verifier is misconfigured\n");
13378                         return -EINVAL;
13379                 } else if (cnt) {
13380                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
13381                         if (!new_prog)
13382                                 return -ENOMEM;
13383
13384                         env->prog = new_prog;
13385                         delta += cnt - 1;
13386                 }
13387         }
13388
13389         if (bpf_prog_is_dev_bound(env->prog->aux))
13390                 return 0;
13391
13392         insn = env->prog->insnsi + delta;
13393
13394         for (i = 0; i < insn_cnt; i++, insn++) {
13395                 bpf_convert_ctx_access_t convert_ctx_access;
13396                 bool ctx_access;
13397
13398                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
13399                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
13400                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
13401                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
13402                         type = BPF_READ;
13403                         ctx_access = true;
13404                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
13405                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
13406                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
13407                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
13408                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
13409                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
13410                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
13411                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
13412                         type = BPF_WRITE;
13413                         ctx_access = BPF_CLASS(insn->code) == BPF_STX;
13414                 } else {
13415                         continue;
13416                 }
13417
13418                 if (type == BPF_WRITE &&
13419                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
13420                         struct bpf_insn patch[] = {
13421                                 *insn,
13422                                 BPF_ST_NOSPEC(),
13423                         };
13424
13425                         cnt = ARRAY_SIZE(patch);
13426                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
13427                         if (!new_prog)
13428                                 return -ENOMEM;
13429
13430                         delta    += cnt - 1;
13431                         env->prog = new_prog;
13432                         insn      = new_prog->insnsi + i + delta;
13433                         continue;
13434                 }
13435
13436                 if (!ctx_access)
13437                         continue;
13438
13439                 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
13440                 case PTR_TO_CTX:
13441                         if (!ops->convert_ctx_access)
13442                                 continue;
13443                         convert_ctx_access = ops->convert_ctx_access;
13444                         break;
13445                 case PTR_TO_SOCKET:
13446                 case PTR_TO_SOCK_COMMON:
13447                         convert_ctx_access = bpf_sock_convert_ctx_access;
13448                         break;
13449                 case PTR_TO_TCP_SOCK:
13450                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
13451                         break;
13452                 case PTR_TO_XDP_SOCK:
13453                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
13454                         break;
13455                 case PTR_TO_BTF_ID:
13456                 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
13457                         if (type == BPF_READ) {
13458                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
13459                                         BPF_SIZE((insn)->code);
13460                                 env->prog->aux->num_exentries++;
13461                         } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
13462                                 verbose(env, "Writes through BTF pointers are not allowed\n");
13463                                 return -EINVAL;
13464                         }
13465                         continue;
13466                 default:
13467                         continue;
13468                 }
13469
13470                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
13471                 size = BPF_LDST_BYTES(insn);
13472
13473                 /* If the read access is a narrower load of the field,
13474                  * convert to a 4/8-byte load, to minimum program type specific
13475                  * convert_ctx_access changes. If conversion is successful,
13476                  * we will apply proper mask to the result.
13477                  */
13478                 is_narrower_load = size < ctx_field_size;
13479                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
13480                 off = insn->off;
13481                 if (is_narrower_load) {
13482                         u8 size_code;
13483
13484                         if (type == BPF_WRITE) {
13485                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
13486                                 return -EINVAL;
13487                         }
13488
13489                         size_code = BPF_H;
13490                         if (ctx_field_size == 4)
13491                                 size_code = BPF_W;
13492                         else if (ctx_field_size == 8)
13493                                 size_code = BPF_DW;
13494
13495                         insn->off = off & ~(size_default - 1);
13496                         insn->code = BPF_LDX | BPF_MEM | size_code;
13497                 }
13498
13499                 target_size = 0;
13500                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
13501                                          &target_size);
13502                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
13503                     (ctx_field_size && !target_size)) {
13504                         verbose(env, "bpf verifier is misconfigured\n");
13505                         return -EINVAL;
13506                 }
13507
13508                 if (is_narrower_load && size < target_size) {
13509                         u8 shift = bpf_ctx_narrow_access_offset(
13510                                 off, size, size_default) * 8;
13511                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
13512                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
13513                                 return -EINVAL;
13514                         }
13515                         if (ctx_field_size <= 4) {
13516                                 if (shift)
13517                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
13518                                                                         insn->dst_reg,
13519                                                                         shift);
13520                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13521                                                                 (1 << size * 8) - 1);
13522                         } else {
13523                                 if (shift)
13524                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
13525                                                                         insn->dst_reg,
13526                                                                         shift);
13527                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
13528                                                                 (1ULL << size * 8) - 1);
13529                         }
13530                 }
13531
13532                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13533                 if (!new_prog)
13534                         return -ENOMEM;
13535
13536                 delta += cnt - 1;
13537
13538                 /* keep walking new program and skip insns we just inserted */
13539                 env->prog = new_prog;
13540                 insn      = new_prog->insnsi + i + delta;
13541         }
13542
13543         return 0;
13544 }
13545
13546 static int jit_subprogs(struct bpf_verifier_env *env)
13547 {
13548         struct bpf_prog *prog = env->prog, **func, *tmp;
13549         int i, j, subprog_start, subprog_end = 0, len, subprog;
13550         struct bpf_map *map_ptr;
13551         struct bpf_insn *insn;
13552         void *old_bpf_func;
13553         int err, num_exentries;
13554
13555         if (env->subprog_cnt <= 1)
13556                 return 0;
13557
13558         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13559                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
13560                         continue;
13561
13562                 /* Upon error here we cannot fall back to interpreter but
13563                  * need a hard reject of the program. Thus -EFAULT is
13564                  * propagated in any case.
13565                  */
13566                 subprog = find_subprog(env, i + insn->imm + 1);
13567                 if (subprog < 0) {
13568                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
13569                                   i + insn->imm + 1);
13570                         return -EFAULT;
13571                 }
13572                 /* temporarily remember subprog id inside insn instead of
13573                  * aux_data, since next loop will split up all insns into funcs
13574                  */
13575                 insn->off = subprog;
13576                 /* remember original imm in case JIT fails and fallback
13577                  * to interpreter will be needed
13578                  */
13579                 env->insn_aux_data[i].call_imm = insn->imm;
13580                 /* point imm to __bpf_call_base+1 from JITs point of view */
13581                 insn->imm = 1;
13582                 if (bpf_pseudo_func(insn))
13583                         /* jit (e.g. x86_64) may emit fewer instructions
13584                          * if it learns a u32 imm is the same as a u64 imm.
13585                          * Force a non zero here.
13586                          */
13587                         insn[1].imm = 1;
13588         }
13589
13590         err = bpf_prog_alloc_jited_linfo(prog);
13591         if (err)
13592                 goto out_undo_insn;
13593
13594         err = -ENOMEM;
13595         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
13596         if (!func)
13597                 goto out_undo_insn;
13598
13599         for (i = 0; i < env->subprog_cnt; i++) {
13600                 subprog_start = subprog_end;
13601                 subprog_end = env->subprog_info[i + 1].start;
13602
13603                 len = subprog_end - subprog_start;
13604                 /* bpf_prog_run() doesn't call subprogs directly,
13605                  * hence main prog stats include the runtime of subprogs.
13606                  * subprogs don't have IDs and not reachable via prog_get_next_id
13607                  * func[i]->stats will never be accessed and stays NULL
13608                  */
13609                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
13610                 if (!func[i])
13611                         goto out_free;
13612                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
13613                        len * sizeof(struct bpf_insn));
13614                 func[i]->type = prog->type;
13615                 func[i]->len = len;
13616                 if (bpf_prog_calc_tag(func[i]))
13617                         goto out_free;
13618                 func[i]->is_func = 1;
13619                 func[i]->aux->func_idx = i;
13620                 /* Below members will be freed only at prog->aux */
13621                 func[i]->aux->btf = prog->aux->btf;
13622                 func[i]->aux->func_info = prog->aux->func_info;
13623                 func[i]->aux->poke_tab = prog->aux->poke_tab;
13624                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13625
13626                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
13627                         struct bpf_jit_poke_descriptor *poke;
13628
13629                         poke = &prog->aux->poke_tab[j];
13630                         if (poke->insn_idx < subprog_end &&
13631                             poke->insn_idx >= subprog_start)
13632                                 poke->aux = func[i]->aux;
13633                 }
13634
13635                 /* Use bpf_prog_F_tag to indicate functions in stack traces.
13636                  * Long term would need debug info to populate names
13637                  */
13638                 func[i]->aux->name[0] = 'F';
13639                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13640                 func[i]->jit_requested = 1;
13641                 func[i]->blinding_requested = prog->blinding_requested;
13642                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13643                 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
13644                 func[i]->aux->linfo = prog->aux->linfo;
13645                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
13646                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
13647                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
13648                 num_exentries = 0;
13649                 insn = func[i]->insnsi;
13650                 for (j = 0; j < func[i]->len; j++, insn++) {
13651                         if (BPF_CLASS(insn->code) == BPF_LDX &&
13652                             BPF_MODE(insn->code) == BPF_PROBE_MEM)
13653                                 num_exentries++;
13654                 }
13655                 func[i]->aux->num_exentries = num_exentries;
13656                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
13657                 func[i] = bpf_int_jit_compile(func[i]);
13658                 if (!func[i]->jited) {
13659                         err = -ENOTSUPP;
13660                         goto out_free;
13661                 }
13662                 cond_resched();
13663         }
13664
13665         /* at this point all bpf functions were successfully JITed
13666          * now populate all bpf_calls with correct addresses and
13667          * run last pass of JIT
13668          */
13669         for (i = 0; i < env->subprog_cnt; i++) {
13670                 insn = func[i]->insnsi;
13671                 for (j = 0; j < func[i]->len; j++, insn++) {
13672                         if (bpf_pseudo_func(insn)) {
13673                                 subprog = insn->off;
13674                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
13675                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
13676                                 continue;
13677                         }
13678                         if (!bpf_pseudo_call(insn))
13679                                 continue;
13680                         subprog = insn->off;
13681                         insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
13682                 }
13683
13684                 /* we use the aux data to keep a list of the start addresses
13685                  * of the JITed images for each function in the program
13686                  *
13687                  * for some architectures, such as powerpc64, the imm field
13688                  * might not be large enough to hold the offset of the start
13689                  * address of the callee's JITed image from __bpf_call_base
13690                  *
13691                  * in such cases, we can lookup the start address of a callee
13692                  * by using its subprog id, available from the off field of
13693                  * the call instruction, as an index for this list
13694                  */
13695                 func[i]->aux->func = func;
13696                 func[i]->aux->func_cnt = env->subprog_cnt;
13697         }
13698         for (i = 0; i < env->subprog_cnt; i++) {
13699                 old_bpf_func = func[i]->bpf_func;
13700                 tmp = bpf_int_jit_compile(func[i]);
13701                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
13702                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
13703                         err = -ENOTSUPP;
13704                         goto out_free;
13705                 }
13706                 cond_resched();
13707         }
13708
13709         /* finally lock prog and jit images for all functions and
13710          * populate kallsysm
13711          */
13712         for (i = 0; i < env->subprog_cnt; i++) {
13713                 bpf_prog_lock_ro(func[i]);
13714                 bpf_prog_kallsyms_add(func[i]);
13715         }
13716
13717         /* Last step: make now unused interpreter insns from main
13718          * prog consistent for later dump requests, so they can
13719          * later look the same as if they were interpreted only.
13720          */
13721         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13722                 if (bpf_pseudo_func(insn)) {
13723                         insn[0].imm = env->insn_aux_data[i].call_imm;
13724                         insn[1].imm = insn->off;
13725                         insn->off = 0;
13726                         continue;
13727                 }
13728                 if (!bpf_pseudo_call(insn))
13729                         continue;
13730                 insn->off = env->insn_aux_data[i].call_imm;
13731                 subprog = find_subprog(env, i + insn->off + 1);
13732                 insn->imm = subprog;
13733         }
13734
13735         prog->jited = 1;
13736         prog->bpf_func = func[0]->bpf_func;
13737         prog->jited_len = func[0]->jited_len;
13738         prog->aux->func = func;
13739         prog->aux->func_cnt = env->subprog_cnt;
13740         bpf_prog_jit_attempt_done(prog);
13741         return 0;
13742 out_free:
13743         /* We failed JIT'ing, so at this point we need to unregister poke
13744          * descriptors from subprogs, so that kernel is not attempting to
13745          * patch it anymore as we're freeing the subprog JIT memory.
13746          */
13747         for (i = 0; i < prog->aux->size_poke_tab; i++) {
13748                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
13749                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
13750         }
13751         /* At this point we're guaranteed that poke descriptors are not
13752          * live anymore. We can just unlink its descriptor table as it's
13753          * released with the main prog.
13754          */
13755         for (i = 0; i < env->subprog_cnt; i++) {
13756                 if (!func[i])
13757                         continue;
13758                 func[i]->aux->poke_tab = NULL;
13759                 bpf_jit_free(func[i]);
13760         }
13761         kfree(func);
13762 out_undo_insn:
13763         /* cleanup main prog to be interpreted */
13764         prog->jit_requested = 0;
13765         prog->blinding_requested = 0;
13766         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13767                 if (!bpf_pseudo_call(insn))
13768                         continue;
13769                 insn->off = 0;
13770                 insn->imm = env->insn_aux_data[i].call_imm;
13771         }
13772         bpf_prog_jit_attempt_done(prog);
13773         return err;
13774 }
13775
13776 static int fixup_call_args(struct bpf_verifier_env *env)
13777 {
13778 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13779         struct bpf_prog *prog = env->prog;
13780         struct bpf_insn *insn = prog->insnsi;
13781         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
13782         int i, depth;
13783 #endif
13784         int err = 0;
13785
13786         if (env->prog->jit_requested &&
13787             !bpf_prog_is_dev_bound(env->prog->aux)) {
13788                 err = jit_subprogs(env);
13789                 if (err == 0)
13790                         return 0;
13791                 if (err == -EFAULT)
13792                         return err;
13793         }
13794 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
13795         if (has_kfunc_call) {
13796                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13797                 return -EINVAL;
13798         }
13799         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13800                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
13801                  * have to be rejected, since interpreter doesn't support them yet.
13802                  */
13803                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13804                 return -EINVAL;
13805         }
13806         for (i = 0; i < prog->len; i++, insn++) {
13807                 if (bpf_pseudo_func(insn)) {
13808                         /* When JIT fails the progs with callback calls
13809                          * have to be rejected, since interpreter doesn't support them yet.
13810                          */
13811                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
13812                         return -EINVAL;
13813                 }
13814
13815                 if (!bpf_pseudo_call(insn))
13816                         continue;
13817                 depth = get_callee_stack_depth(env, insn, i);
13818                 if (depth < 0)
13819                         return depth;
13820                 bpf_patch_call_args(insn, depth);
13821         }
13822         err = 0;
13823 #endif
13824         return err;
13825 }
13826
13827 static int fixup_kfunc_call(struct bpf_verifier_env *env,
13828                             struct bpf_insn *insn)
13829 {
13830         const struct bpf_kfunc_desc *desc;
13831
13832         if (!insn->imm) {
13833                 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13834                 return -EINVAL;
13835         }
13836
13837         /* insn->imm has the btf func_id. Replace it with
13838          * an address (relative to __bpf_base_call).
13839          */
13840         desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
13841         if (!desc) {
13842                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13843                         insn->imm);
13844                 return -EFAULT;
13845         }
13846
13847         insn->imm = desc->imm;
13848
13849         return 0;
13850 }
13851
13852 /* Do various post-verification rewrites in a single program pass.
13853  * These rewrites simplify JIT and interpreter implementations.
13854  */
13855 static int do_misc_fixups(struct bpf_verifier_env *env)
13856 {
13857         struct bpf_prog *prog = env->prog;
13858         enum bpf_attach_type eatype = prog->expected_attach_type;
13859         enum bpf_prog_type prog_type = resolve_prog_type(prog);
13860         struct bpf_insn *insn = prog->insnsi;
13861         const struct bpf_func_proto *fn;
13862         const int insn_cnt = prog->len;
13863         const struct bpf_map_ops *ops;
13864         struct bpf_insn_aux_data *aux;
13865         struct bpf_insn insn_buf[16];
13866         struct bpf_prog *new_prog;
13867         struct bpf_map *map_ptr;
13868         int i, ret, cnt, delta = 0;
13869
13870         for (i = 0; i < insn_cnt; i++, insn++) {
13871                 /* Make divide-by-zero exceptions impossible. */
13872                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
13873                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
13874                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
13875                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
13876                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
13877                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
13878                         struct bpf_insn *patchlet;
13879                         struct bpf_insn chk_and_div[] = {
13880                                 /* [R,W]x div 0 -> 0 */
13881                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13882                                              BPF_JNE | BPF_K, insn->src_reg,
13883                                              0, 2, 0),
13884                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
13885                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13886                                 *insn,
13887                         };
13888                         struct bpf_insn chk_and_mod[] = {
13889                                 /* [R,W]x mod 0 -> [R,W]x */
13890                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13891                                              BPF_JEQ | BPF_K, insn->src_reg,
13892                                              0, 1 + (is64 ? 0 : 1), 0),
13893                                 *insn,
13894                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13895                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
13896                         };
13897
13898                         patchlet = isdiv ? chk_and_div : chk_and_mod;
13899                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
13900                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
13901
13902                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
13903                         if (!new_prog)
13904                                 return -ENOMEM;
13905
13906                         delta    += cnt - 1;
13907                         env->prog = prog = new_prog;
13908                         insn      = new_prog->insnsi + i + delta;
13909                         continue;
13910                 }
13911
13912                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
13913                 if (BPF_CLASS(insn->code) == BPF_LD &&
13914                     (BPF_MODE(insn->code) == BPF_ABS ||
13915                      BPF_MODE(insn->code) == BPF_IND)) {
13916                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
13917                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13918                                 verbose(env, "bpf verifier is misconfigured\n");
13919                                 return -EINVAL;
13920                         }
13921
13922                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13923                         if (!new_prog)
13924                                 return -ENOMEM;
13925
13926                         delta    += cnt - 1;
13927                         env->prog = prog = new_prog;
13928                         insn      = new_prog->insnsi + i + delta;
13929                         continue;
13930                 }
13931
13932                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
13933                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
13934                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
13935                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
13936                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
13937                         struct bpf_insn *patch = &insn_buf[0];
13938                         bool issrc, isneg, isimm;
13939                         u32 off_reg;
13940
13941                         aux = &env->insn_aux_data[i + delta];
13942                         if (!aux->alu_state ||
13943                             aux->alu_state == BPF_ALU_NON_POINTER)
13944                                 continue;
13945
13946                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
13947                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
13948                                 BPF_ALU_SANITIZE_SRC;
13949                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
13950
13951                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
13952                         if (isimm) {
13953                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13954                         } else {
13955                                 if (isneg)
13956                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13957                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13958                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
13959                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
13960                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
13961                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
13962                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
13963                         }
13964                         if (!issrc)
13965                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
13966                         insn->src_reg = BPF_REG_AX;
13967                         if (isneg)
13968                                 insn->code = insn->code == code_add ?
13969                                              code_sub : code_add;
13970                         *patch++ = *insn;
13971                         if (issrc && isneg && !isimm)
13972                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13973                         cnt = patch - insn_buf;
13974
13975                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13976                         if (!new_prog)
13977                                 return -ENOMEM;
13978
13979                         delta    += cnt - 1;
13980                         env->prog = prog = new_prog;
13981                         insn      = new_prog->insnsi + i + delta;
13982                         continue;
13983                 }
13984
13985                 if (insn->code != (BPF_JMP | BPF_CALL))
13986                         continue;
13987                 if (insn->src_reg == BPF_PSEUDO_CALL)
13988                         continue;
13989                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
13990                         ret = fixup_kfunc_call(env, insn);
13991                         if (ret)
13992                                 return ret;
13993                         continue;
13994                 }
13995
13996                 if (insn->imm == BPF_FUNC_get_route_realm)
13997                         prog->dst_needed = 1;
13998                 if (insn->imm == BPF_FUNC_get_prandom_u32)
13999                         bpf_user_rnd_init_once();
14000                 if (insn->imm == BPF_FUNC_override_return)
14001                         prog->kprobe_override = 1;
14002                 if (insn->imm == BPF_FUNC_tail_call) {
14003                         /* If we tail call into other programs, we
14004                          * cannot make any assumptions since they can
14005                          * be replaced dynamically during runtime in
14006                          * the program array.
14007                          */
14008                         prog->cb_access = 1;
14009                         if (!allow_tail_call_in_subprogs(env))
14010                                 prog->aux->stack_depth = MAX_BPF_STACK;
14011                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
14012
14013                         /* mark bpf_tail_call as different opcode to avoid
14014                          * conditional branch in the interpreter for every normal
14015                          * call and to prevent accidental JITing by JIT compiler
14016                          * that doesn't support bpf_tail_call yet
14017                          */
14018                         insn->imm = 0;
14019                         insn->code = BPF_JMP | BPF_TAIL_CALL;
14020
14021                         aux = &env->insn_aux_data[i + delta];
14022                         if (env->bpf_capable && !prog->blinding_requested &&
14023                             prog->jit_requested &&
14024                             !bpf_map_key_poisoned(aux) &&
14025                             !bpf_map_ptr_poisoned(aux) &&
14026                             !bpf_map_ptr_unpriv(aux)) {
14027                                 struct bpf_jit_poke_descriptor desc = {
14028                                         .reason = BPF_POKE_REASON_TAIL_CALL,
14029                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
14030                                         .tail_call.key = bpf_map_key_immediate(aux),
14031                                         .insn_idx = i + delta,
14032                                 };
14033
14034                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
14035                                 if (ret < 0) {
14036                                         verbose(env, "adding tail call poke descriptor failed\n");
14037                                         return ret;
14038                                 }
14039
14040                                 insn->imm = ret + 1;
14041                                 continue;
14042                         }
14043
14044                         if (!bpf_map_ptr_unpriv(aux))
14045                                 continue;
14046
14047                         /* instead of changing every JIT dealing with tail_call
14048                          * emit two extra insns:
14049                          * if (index >= max_entries) goto out;
14050                          * index &= array->index_mask;
14051                          * to avoid out-of-bounds cpu speculation
14052                          */
14053                         if (bpf_map_ptr_poisoned(aux)) {
14054                                 verbose(env, "tail_call abusing map_ptr\n");
14055                                 return -EINVAL;
14056                         }
14057
14058                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14059                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
14060                                                   map_ptr->max_entries, 2);
14061                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
14062                                                     container_of(map_ptr,
14063                                                                  struct bpf_array,
14064                                                                  map)->index_mask);
14065                         insn_buf[2] = *insn;
14066                         cnt = 3;
14067                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14068                         if (!new_prog)
14069                                 return -ENOMEM;
14070
14071                         delta    += cnt - 1;
14072                         env->prog = prog = new_prog;
14073                         insn      = new_prog->insnsi + i + delta;
14074                         continue;
14075                 }
14076
14077                 if (insn->imm == BPF_FUNC_timer_set_callback) {
14078                         /* The verifier will process callback_fn as many times as necessary
14079                          * with different maps and the register states prepared by
14080                          * set_timer_callback_state will be accurate.
14081                          *
14082                          * The following use case is valid:
14083                          *   map1 is shared by prog1, prog2, prog3.
14084                          *   prog1 calls bpf_timer_init for some map1 elements
14085                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
14086                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
14087                          *   prog3 calls bpf_timer_start for some map1 elements.
14088                          *     Those that were not both bpf_timer_init-ed and
14089                          *     bpf_timer_set_callback-ed will return -EINVAL.
14090                          */
14091                         struct bpf_insn ld_addrs[2] = {
14092                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
14093                         };
14094
14095                         insn_buf[0] = ld_addrs[0];
14096                         insn_buf[1] = ld_addrs[1];
14097                         insn_buf[2] = *insn;
14098                         cnt = 3;
14099
14100                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14101                         if (!new_prog)
14102                                 return -ENOMEM;
14103
14104                         delta    += cnt - 1;
14105                         env->prog = prog = new_prog;
14106                         insn      = new_prog->insnsi + i + delta;
14107                         goto patch_call_imm;
14108                 }
14109
14110                 if (insn->imm == BPF_FUNC_task_storage_get ||
14111                     insn->imm == BPF_FUNC_sk_storage_get ||
14112                     insn->imm == BPF_FUNC_inode_storage_get) {
14113                         if (env->prog->aux->sleepable)
14114                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
14115                         else
14116                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
14117                         insn_buf[1] = *insn;
14118                         cnt = 2;
14119
14120                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14121                         if (!new_prog)
14122                                 return -ENOMEM;
14123
14124                         delta += cnt - 1;
14125                         env->prog = prog = new_prog;
14126                         insn = new_prog->insnsi + i + delta;
14127                         goto patch_call_imm;
14128                 }
14129
14130                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
14131                  * and other inlining handlers are currently limited to 64 bit
14132                  * only.
14133                  */
14134                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14135                     (insn->imm == BPF_FUNC_map_lookup_elem ||
14136                      insn->imm == BPF_FUNC_map_update_elem ||
14137                      insn->imm == BPF_FUNC_map_delete_elem ||
14138                      insn->imm == BPF_FUNC_map_push_elem   ||
14139                      insn->imm == BPF_FUNC_map_pop_elem    ||
14140                      insn->imm == BPF_FUNC_map_peek_elem   ||
14141                      insn->imm == BPF_FUNC_redirect_map    ||
14142                      insn->imm == BPF_FUNC_for_each_map_elem ||
14143                      insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
14144                         aux = &env->insn_aux_data[i + delta];
14145                         if (bpf_map_ptr_poisoned(aux))
14146                                 goto patch_call_imm;
14147
14148                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14149                         ops = map_ptr->ops;
14150                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
14151                             ops->map_gen_lookup) {
14152                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
14153                                 if (cnt == -EOPNOTSUPP)
14154                                         goto patch_map_ops_generic;
14155                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14156                                         verbose(env, "bpf verifier is misconfigured\n");
14157                                         return -EINVAL;
14158                                 }
14159
14160                                 new_prog = bpf_patch_insn_data(env, i + delta,
14161                                                                insn_buf, cnt);
14162                                 if (!new_prog)
14163                                         return -ENOMEM;
14164
14165                                 delta    += cnt - 1;
14166                                 env->prog = prog = new_prog;
14167                                 insn      = new_prog->insnsi + i + delta;
14168                                 continue;
14169                         }
14170
14171                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
14172                                      (void *(*)(struct bpf_map *map, void *key))NULL));
14173                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
14174                                      (int (*)(struct bpf_map *map, void *key))NULL));
14175                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
14176                                      (int (*)(struct bpf_map *map, void *key, void *value,
14177                                               u64 flags))NULL));
14178                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
14179                                      (int (*)(struct bpf_map *map, void *value,
14180                                               u64 flags))NULL));
14181                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
14182                                      (int (*)(struct bpf_map *map, void *value))NULL));
14183                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
14184                                      (int (*)(struct bpf_map *map, void *value))NULL));
14185                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
14186                                      (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
14187                         BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
14188                                      (int (*)(struct bpf_map *map,
14189                                               bpf_callback_t callback_fn,
14190                                               void *callback_ctx,
14191                                               u64 flags))NULL));
14192                         BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
14193                                      (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
14194
14195 patch_map_ops_generic:
14196                         switch (insn->imm) {
14197                         case BPF_FUNC_map_lookup_elem:
14198                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
14199                                 continue;
14200                         case BPF_FUNC_map_update_elem:
14201                                 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
14202                                 continue;
14203                         case BPF_FUNC_map_delete_elem:
14204                                 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
14205                                 continue;
14206                         case BPF_FUNC_map_push_elem:
14207                                 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
14208                                 continue;
14209                         case BPF_FUNC_map_pop_elem:
14210                                 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
14211                                 continue;
14212                         case BPF_FUNC_map_peek_elem:
14213                                 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
14214                                 continue;
14215                         case BPF_FUNC_redirect_map:
14216                                 insn->imm = BPF_CALL_IMM(ops->map_redirect);
14217                                 continue;
14218                         case BPF_FUNC_for_each_map_elem:
14219                                 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
14220                                 continue;
14221                         case BPF_FUNC_map_lookup_percpu_elem:
14222                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
14223                                 continue;
14224                         }
14225
14226                         goto patch_call_imm;
14227                 }
14228
14229                 /* Implement bpf_jiffies64 inline. */
14230                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14231                     insn->imm == BPF_FUNC_jiffies64) {
14232                         struct bpf_insn ld_jiffies_addr[2] = {
14233                                 BPF_LD_IMM64(BPF_REG_0,
14234                                              (unsigned long)&jiffies),
14235                         };
14236
14237                         insn_buf[0] = ld_jiffies_addr[0];
14238                         insn_buf[1] = ld_jiffies_addr[1];
14239                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
14240                                                   BPF_REG_0, 0);
14241                         cnt = 3;
14242
14243                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
14244                                                        cnt);
14245                         if (!new_prog)
14246                                 return -ENOMEM;
14247
14248                         delta    += cnt - 1;
14249                         env->prog = prog = new_prog;
14250                         insn      = new_prog->insnsi + i + delta;
14251                         continue;
14252                 }
14253
14254                 /* Implement bpf_get_func_arg inline. */
14255                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14256                     insn->imm == BPF_FUNC_get_func_arg) {
14257                         /* Load nr_args from ctx - 8 */
14258                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14259                         insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
14260                         insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
14261                         insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
14262                         insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
14263                         insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14264                         insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
14265                         insn_buf[7] = BPF_JMP_A(1);
14266                         insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
14267                         cnt = 9;
14268
14269                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14270                         if (!new_prog)
14271                                 return -ENOMEM;
14272
14273                         delta    += cnt - 1;
14274                         env->prog = prog = new_prog;
14275                         insn      = new_prog->insnsi + i + delta;
14276                         continue;
14277                 }
14278
14279                 /* Implement bpf_get_func_ret inline. */
14280                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14281                     insn->imm == BPF_FUNC_get_func_ret) {
14282                         if (eatype == BPF_TRACE_FEXIT ||
14283                             eatype == BPF_MODIFY_RETURN) {
14284                                 /* Load nr_args from ctx - 8 */
14285                                 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14286                                 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
14287                                 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
14288                                 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14289                                 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
14290                                 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
14291                                 cnt = 6;
14292                         } else {
14293                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
14294                                 cnt = 1;
14295                         }
14296
14297                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14298                         if (!new_prog)
14299                                 return -ENOMEM;
14300
14301                         delta    += cnt - 1;
14302                         env->prog = prog = new_prog;
14303                         insn      = new_prog->insnsi + i + delta;
14304                         continue;
14305                 }
14306
14307                 /* Implement get_func_arg_cnt inline. */
14308                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14309                     insn->imm == BPF_FUNC_get_func_arg_cnt) {
14310                         /* Load nr_args from ctx - 8 */
14311                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14312
14313                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14314                         if (!new_prog)
14315                                 return -ENOMEM;
14316
14317                         env->prog = prog = new_prog;
14318                         insn      = new_prog->insnsi + i + delta;
14319                         continue;
14320                 }
14321
14322                 /* Implement bpf_get_func_ip inline. */
14323                 if (prog_type == BPF_PROG_TYPE_TRACING &&
14324                     insn->imm == BPF_FUNC_get_func_ip) {
14325                         /* Load IP address from ctx - 16 */
14326                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
14327
14328                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14329                         if (!new_prog)
14330                                 return -ENOMEM;
14331
14332                         env->prog = prog = new_prog;
14333                         insn      = new_prog->insnsi + i + delta;
14334                         continue;
14335                 }
14336
14337 patch_call_imm:
14338                 fn = env->ops->get_func_proto(insn->imm, env->prog);
14339                 /* all functions that have prototype and verifier allowed
14340                  * programs to call them, must be real in-kernel functions
14341                  */
14342                 if (!fn->func) {
14343                         verbose(env,
14344                                 "kernel subsystem misconfigured func %s#%d\n",
14345                                 func_id_name(insn->imm), insn->imm);
14346                         return -EFAULT;
14347                 }
14348                 insn->imm = fn->func - __bpf_call_base;
14349         }
14350
14351         /* Since poke tab is now finalized, publish aux to tracker. */
14352         for (i = 0; i < prog->aux->size_poke_tab; i++) {
14353                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
14354                 if (!map_ptr->ops->map_poke_track ||
14355                     !map_ptr->ops->map_poke_untrack ||
14356                     !map_ptr->ops->map_poke_run) {
14357                         verbose(env, "bpf verifier is misconfigured\n");
14358                         return -EINVAL;
14359                 }
14360
14361                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
14362                 if (ret < 0) {
14363                         verbose(env, "tracking tail call prog failed\n");
14364                         return ret;
14365                 }
14366         }
14367
14368         sort_kfunc_descs_by_imm(env->prog);
14369
14370         return 0;
14371 }
14372
14373 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
14374                                         int position,
14375                                         s32 stack_base,
14376                                         u32 callback_subprogno,
14377                                         u32 *cnt)
14378 {
14379         s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
14380         s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
14381         s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
14382         int reg_loop_max = BPF_REG_6;
14383         int reg_loop_cnt = BPF_REG_7;
14384         int reg_loop_ctx = BPF_REG_8;
14385
14386         struct bpf_prog *new_prog;
14387         u32 callback_start;
14388         u32 call_insn_offset;
14389         s32 callback_offset;
14390
14391         /* This represents an inlined version of bpf_iter.c:bpf_loop,
14392          * be careful to modify this code in sync.
14393          */
14394         struct bpf_insn insn_buf[] = {
14395                 /* Return error and jump to the end of the patch if
14396                  * expected number of iterations is too big.
14397                  */
14398                 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
14399                 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
14400                 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
14401                 /* spill R6, R7, R8 to use these as loop vars */
14402                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
14403                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
14404                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
14405                 /* initialize loop vars */
14406                 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
14407                 BPF_MOV32_IMM(reg_loop_cnt, 0),
14408                 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
14409                 /* loop header,
14410                  * if reg_loop_cnt >= reg_loop_max skip the loop body
14411                  */
14412                 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
14413                 /* callback call,
14414                  * correct callback offset would be set after patching
14415                  */
14416                 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
14417                 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
14418                 BPF_CALL_REL(0),
14419                 /* increment loop counter */
14420                 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
14421                 /* jump to loop header if callback returned 0 */
14422                 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
14423                 /* return value of bpf_loop,
14424                  * set R0 to the number of iterations
14425                  */
14426                 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
14427                 /* restore original values of R6, R7, R8 */
14428                 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
14429                 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
14430                 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
14431         };
14432
14433         *cnt = ARRAY_SIZE(insn_buf);
14434         new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
14435         if (!new_prog)
14436                 return new_prog;
14437
14438         /* callback start is known only after patching */
14439         callback_start = env->subprog_info[callback_subprogno].start;
14440         /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
14441         call_insn_offset = position + 12;
14442         callback_offset = callback_start - call_insn_offset - 1;
14443         new_prog->insnsi[call_insn_offset].imm = callback_offset;
14444
14445         return new_prog;
14446 }
14447
14448 static bool is_bpf_loop_call(struct bpf_insn *insn)
14449 {
14450         return insn->code == (BPF_JMP | BPF_CALL) &&
14451                 insn->src_reg == 0 &&
14452                 insn->imm == BPF_FUNC_loop;
14453 }
14454
14455 /* For all sub-programs in the program (including main) check
14456  * insn_aux_data to see if there are bpf_loop calls that require
14457  * inlining. If such calls are found the calls are replaced with a
14458  * sequence of instructions produced by `inline_bpf_loop` function and
14459  * subprog stack_depth is increased by the size of 3 registers.
14460  * This stack space is used to spill values of the R6, R7, R8.  These
14461  * registers are used to store the loop bound, counter and context
14462  * variables.
14463  */
14464 static int optimize_bpf_loop(struct bpf_verifier_env *env)
14465 {
14466         struct bpf_subprog_info *subprogs = env->subprog_info;
14467         int i, cur_subprog = 0, cnt, delta = 0;
14468         struct bpf_insn *insn = env->prog->insnsi;
14469         int insn_cnt = env->prog->len;
14470         u16 stack_depth = subprogs[cur_subprog].stack_depth;
14471         u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14472         u16 stack_depth_extra = 0;
14473
14474         for (i = 0; i < insn_cnt; i++, insn++) {
14475                 struct bpf_loop_inline_state *inline_state =
14476                         &env->insn_aux_data[i + delta].loop_inline_state;
14477
14478                 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
14479                         struct bpf_prog *new_prog;
14480
14481                         stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
14482                         new_prog = inline_bpf_loop(env,
14483                                                    i + delta,
14484                                                    -(stack_depth + stack_depth_extra),
14485                                                    inline_state->callback_subprogno,
14486                                                    &cnt);
14487                         if (!new_prog)
14488                                 return -ENOMEM;
14489
14490                         delta     += cnt - 1;
14491                         env->prog  = new_prog;
14492                         insn       = new_prog->insnsi + i + delta;
14493                 }
14494
14495                 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
14496                         subprogs[cur_subprog].stack_depth += stack_depth_extra;
14497                         cur_subprog++;
14498                         stack_depth = subprogs[cur_subprog].stack_depth;
14499                         stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14500                         stack_depth_extra = 0;
14501                 }
14502         }
14503
14504         env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14505
14506         return 0;
14507 }
14508
14509 static void free_states(struct bpf_verifier_env *env)
14510 {
14511         struct bpf_verifier_state_list *sl, *sln;
14512         int i;
14513
14514         sl = env->free_list;
14515         while (sl) {
14516                 sln = sl->next;
14517                 free_verifier_state(&sl->state, false);
14518                 kfree(sl);
14519                 sl = sln;
14520         }
14521         env->free_list = NULL;
14522
14523         if (!env->explored_states)
14524                 return;
14525
14526         for (i = 0; i < state_htab_size(env); i++) {
14527                 sl = env->explored_states[i];
14528
14529                 while (sl) {
14530                         sln = sl->next;
14531                         free_verifier_state(&sl->state, false);
14532                         kfree(sl);
14533                         sl = sln;
14534                 }
14535                 env->explored_states[i] = NULL;
14536         }
14537 }
14538
14539 static int do_check_common(struct bpf_verifier_env *env, int subprog)
14540 {
14541         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14542         struct bpf_verifier_state *state;
14543         struct bpf_reg_state *regs;
14544         int ret, i;
14545
14546         env->prev_linfo = NULL;
14547         env->pass_cnt++;
14548
14549         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
14550         if (!state)
14551                 return -ENOMEM;
14552         state->curframe = 0;
14553         state->speculative = false;
14554         state->branches = 1;
14555         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
14556         if (!state->frame[0]) {
14557                 kfree(state);
14558                 return -ENOMEM;
14559         }
14560         env->cur_state = state;
14561         init_func_state(env, state->frame[0],
14562                         BPF_MAIN_FUNC /* callsite */,
14563                         0 /* frameno */,
14564                         subprog);
14565
14566         regs = state->frame[state->curframe]->regs;
14567         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
14568                 ret = btf_prepare_func_args(env, subprog, regs);
14569                 if (ret)
14570                         goto out;
14571                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
14572                         if (regs[i].type == PTR_TO_CTX)
14573                                 mark_reg_known_zero(env, regs, i);
14574                         else if (regs[i].type == SCALAR_VALUE)
14575                                 mark_reg_unknown(env, regs, i);
14576                         else if (base_type(regs[i].type) == PTR_TO_MEM) {
14577                                 const u32 mem_size = regs[i].mem_size;
14578
14579                                 mark_reg_known_zero(env, regs, i);
14580                                 regs[i].mem_size = mem_size;
14581                                 regs[i].id = ++env->id_gen;
14582                         }
14583                 }
14584         } else {
14585                 /* 1st arg to a function */
14586                 regs[BPF_REG_1].type = PTR_TO_CTX;
14587                 mark_reg_known_zero(env, regs, BPF_REG_1);
14588                 ret = btf_check_subprog_arg_match(env, subprog, regs);
14589                 if (ret == -EFAULT)
14590                         /* unlikely verifier bug. abort.
14591                          * ret == 0 and ret < 0 are sadly acceptable for
14592                          * main() function due to backward compatibility.
14593                          * Like socket filter program may be written as:
14594                          * int bpf_prog(struct pt_regs *ctx)
14595                          * and never dereference that ctx in the program.
14596                          * 'struct pt_regs' is a type mismatch for socket
14597                          * filter that should be using 'struct __sk_buff'.
14598                          */
14599                         goto out;
14600         }
14601
14602         ret = do_check(env);
14603 out:
14604         /* check for NULL is necessary, since cur_state can be freed inside
14605          * do_check() under memory pressure.
14606          */
14607         if (env->cur_state) {
14608                 free_verifier_state(env->cur_state, true);
14609                 env->cur_state = NULL;
14610         }
14611         while (!pop_stack(env, NULL, NULL, false));
14612         if (!ret && pop_log)
14613                 bpf_vlog_reset(&env->log, 0);
14614         free_states(env);
14615         return ret;
14616 }
14617
14618 /* Verify all global functions in a BPF program one by one based on their BTF.
14619  * All global functions must pass verification. Otherwise the whole program is rejected.
14620  * Consider:
14621  * int bar(int);
14622  * int foo(int f)
14623  * {
14624  *    return bar(f);
14625  * }
14626  * int bar(int b)
14627  * {
14628  *    ...
14629  * }
14630  * foo() will be verified first for R1=any_scalar_value. During verification it
14631  * will be assumed that bar() already verified successfully and call to bar()
14632  * from foo() will be checked for type match only. Later bar() will be verified
14633  * independently to check that it's safe for R1=any_scalar_value.
14634  */
14635 static int do_check_subprogs(struct bpf_verifier_env *env)
14636 {
14637         struct bpf_prog_aux *aux = env->prog->aux;
14638         int i, ret;
14639
14640         if (!aux->func_info)
14641                 return 0;
14642
14643         for (i = 1; i < env->subprog_cnt; i++) {
14644                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
14645                         continue;
14646                 env->insn_idx = env->subprog_info[i].start;
14647                 WARN_ON_ONCE(env->insn_idx == 0);
14648                 ret = do_check_common(env, i);
14649                 if (ret) {
14650                         return ret;
14651                 } else if (env->log.level & BPF_LOG_LEVEL) {
14652                         verbose(env,
14653                                 "Func#%d is safe for any args that match its prototype\n",
14654                                 i);
14655                 }
14656         }
14657         return 0;
14658 }
14659
14660 static int do_check_main(struct bpf_verifier_env *env)
14661 {
14662         int ret;
14663
14664         env->insn_idx = 0;
14665         ret = do_check_common(env, 0);
14666         if (!ret)
14667                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14668         return ret;
14669 }
14670
14671
14672 static void print_verification_stats(struct bpf_verifier_env *env)
14673 {
14674         int i;
14675
14676         if (env->log.level & BPF_LOG_STATS) {
14677                 verbose(env, "verification time %lld usec\n",
14678                         div_u64(env->verification_time, 1000));
14679                 verbose(env, "stack depth ");
14680                 for (i = 0; i < env->subprog_cnt; i++) {
14681                         u32 depth = env->subprog_info[i].stack_depth;
14682
14683                         verbose(env, "%d", depth);
14684                         if (i + 1 < env->subprog_cnt)
14685                                 verbose(env, "+");
14686                 }
14687                 verbose(env, "\n");
14688         }
14689         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
14690                 "total_states %d peak_states %d mark_read %d\n",
14691                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
14692                 env->max_states_per_insn, env->total_states,
14693                 env->peak_states, env->longest_mark_read_walk);
14694 }
14695
14696 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
14697 {
14698         const struct btf_type *t, *func_proto;
14699         const struct bpf_struct_ops *st_ops;
14700         const struct btf_member *member;
14701         struct bpf_prog *prog = env->prog;
14702         u32 btf_id, member_idx;
14703         const char *mname;
14704
14705         if (!prog->gpl_compatible) {
14706                 verbose(env, "struct ops programs must have a GPL compatible license\n");
14707                 return -EINVAL;
14708         }
14709
14710         btf_id = prog->aux->attach_btf_id;
14711         st_ops = bpf_struct_ops_find(btf_id);
14712         if (!st_ops) {
14713                 verbose(env, "attach_btf_id %u is not a supported struct\n",
14714                         btf_id);
14715                 return -ENOTSUPP;
14716         }
14717
14718         t = st_ops->type;
14719         member_idx = prog->expected_attach_type;
14720         if (member_idx >= btf_type_vlen(t)) {
14721                 verbose(env, "attach to invalid member idx %u of struct %s\n",
14722                         member_idx, st_ops->name);
14723                 return -EINVAL;
14724         }
14725
14726         member = &btf_type_member(t)[member_idx];
14727         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
14728         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
14729                                                NULL);
14730         if (!func_proto) {
14731                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
14732                         mname, member_idx, st_ops->name);
14733                 return -EINVAL;
14734         }
14735
14736         if (st_ops->check_member) {
14737                 int err = st_ops->check_member(t, member);
14738
14739                 if (err) {
14740                         verbose(env, "attach to unsupported member %s of struct %s\n",
14741                                 mname, st_ops->name);
14742                         return err;
14743                 }
14744         }
14745
14746         prog->aux->attach_func_proto = func_proto;
14747         prog->aux->attach_func_name = mname;
14748         env->ops = st_ops->verifier_ops;
14749
14750         return 0;
14751 }
14752 #define SECURITY_PREFIX "security_"
14753
14754 static int check_attach_modify_return(unsigned long addr, const char *func_name)
14755 {
14756         if (within_error_injection_list(addr) ||
14757             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
14758                 return 0;
14759
14760         return -EINVAL;
14761 }
14762
14763 /* list of non-sleepable functions that are otherwise on
14764  * ALLOW_ERROR_INJECTION list
14765  */
14766 BTF_SET_START(btf_non_sleepable_error_inject)
14767 /* Three functions below can be called from sleepable and non-sleepable context.
14768  * Assume non-sleepable from bpf safety point of view.
14769  */
14770 BTF_ID(func, __filemap_add_folio)
14771 BTF_ID(func, should_fail_alloc_page)
14772 BTF_ID(func, should_failslab)
14773 BTF_SET_END(btf_non_sleepable_error_inject)
14774
14775 static int check_non_sleepable_error_inject(u32 btf_id)
14776 {
14777         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
14778 }
14779
14780 int bpf_check_attach_target(struct bpf_verifier_log *log,
14781                             const struct bpf_prog *prog,
14782                             const struct bpf_prog *tgt_prog,
14783                             u32 btf_id,
14784                             struct bpf_attach_target_info *tgt_info)
14785 {
14786         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
14787         const char prefix[] = "btf_trace_";
14788         int ret = 0, subprog = -1, i;
14789         const struct btf_type *t;
14790         bool conservative = true;
14791         const char *tname;
14792         struct btf *btf;
14793         long addr = 0;
14794
14795         if (!btf_id) {
14796                 bpf_log(log, "Tracing programs must provide btf_id\n");
14797                 return -EINVAL;
14798         }
14799         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
14800         if (!btf) {
14801                 bpf_log(log,
14802                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
14803                 return -EINVAL;
14804         }
14805         t = btf_type_by_id(btf, btf_id);
14806         if (!t) {
14807                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
14808                 return -EINVAL;
14809         }
14810         tname = btf_name_by_offset(btf, t->name_off);
14811         if (!tname) {
14812                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
14813                 return -EINVAL;
14814         }
14815         if (tgt_prog) {
14816                 struct bpf_prog_aux *aux = tgt_prog->aux;
14817
14818                 for (i = 0; i < aux->func_info_cnt; i++)
14819                         if (aux->func_info[i].type_id == btf_id) {
14820                                 subprog = i;
14821                                 break;
14822                         }
14823                 if (subprog == -1) {
14824                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
14825                         return -EINVAL;
14826                 }
14827                 conservative = aux->func_info_aux[subprog].unreliable;
14828                 if (prog_extension) {
14829                         if (conservative) {
14830                                 bpf_log(log,
14831                                         "Cannot replace static functions\n");
14832                                 return -EINVAL;
14833                         }
14834                         if (!prog->jit_requested) {
14835                                 bpf_log(log,
14836                                         "Extension programs should be JITed\n");
14837                                 return -EINVAL;
14838                         }
14839                 }
14840                 if (!tgt_prog->jited) {
14841                         bpf_log(log, "Can attach to only JITed progs\n");
14842                         return -EINVAL;
14843                 }
14844                 if (tgt_prog->type == prog->type) {
14845                         /* Cannot fentry/fexit another fentry/fexit program.
14846                          * Cannot attach program extension to another extension.
14847                          * It's ok to attach fentry/fexit to extension program.
14848                          */
14849                         bpf_log(log, "Cannot recursively attach\n");
14850                         return -EINVAL;
14851                 }
14852                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
14853                     prog_extension &&
14854                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
14855                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
14856                         /* Program extensions can extend all program types
14857                          * except fentry/fexit. The reason is the following.
14858                          * The fentry/fexit programs are used for performance
14859                          * analysis, stats and can be attached to any program
14860                          * type except themselves. When extension program is
14861                          * replacing XDP function it is necessary to allow
14862                          * performance analysis of all functions. Both original
14863                          * XDP program and its program extension. Hence
14864                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
14865                          * allowed. If extending of fentry/fexit was allowed it
14866                          * would be possible to create long call chain
14867                          * fentry->extension->fentry->extension beyond
14868                          * reasonable stack size. Hence extending fentry is not
14869                          * allowed.
14870                          */
14871                         bpf_log(log, "Cannot extend fentry/fexit\n");
14872                         return -EINVAL;
14873                 }
14874         } else {
14875                 if (prog_extension) {
14876                         bpf_log(log, "Cannot replace kernel functions\n");
14877                         return -EINVAL;
14878                 }
14879         }
14880
14881         switch (prog->expected_attach_type) {
14882         case BPF_TRACE_RAW_TP:
14883                 if (tgt_prog) {
14884                         bpf_log(log,
14885                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
14886                         return -EINVAL;
14887                 }
14888                 if (!btf_type_is_typedef(t)) {
14889                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
14890                                 btf_id);
14891                         return -EINVAL;
14892                 }
14893                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
14894                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
14895                                 btf_id, tname);
14896                         return -EINVAL;
14897                 }
14898                 tname += sizeof(prefix) - 1;
14899                 t = btf_type_by_id(btf, t->type);
14900                 if (!btf_type_is_ptr(t))
14901                         /* should never happen in valid vmlinux build */
14902                         return -EINVAL;
14903                 t = btf_type_by_id(btf, t->type);
14904                 if (!btf_type_is_func_proto(t))
14905                         /* should never happen in valid vmlinux build */
14906                         return -EINVAL;
14907
14908                 break;
14909         case BPF_TRACE_ITER:
14910                 if (!btf_type_is_func(t)) {
14911                         bpf_log(log, "attach_btf_id %u is not a function\n",
14912                                 btf_id);
14913                         return -EINVAL;
14914                 }
14915                 t = btf_type_by_id(btf, t->type);
14916                 if (!btf_type_is_func_proto(t))
14917                         return -EINVAL;
14918                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
14919                 if (ret)
14920                         return ret;
14921                 break;
14922         default:
14923                 if (!prog_extension)
14924                         return -EINVAL;
14925                 fallthrough;
14926         case BPF_MODIFY_RETURN:
14927         case BPF_LSM_MAC:
14928         case BPF_LSM_CGROUP:
14929         case BPF_TRACE_FENTRY:
14930         case BPF_TRACE_FEXIT:
14931                 if (!btf_type_is_func(t)) {
14932                         bpf_log(log, "attach_btf_id %u is not a function\n",
14933                                 btf_id);
14934                         return -EINVAL;
14935                 }
14936                 if (prog_extension &&
14937                     btf_check_type_match(log, prog, btf, t))
14938                         return -EINVAL;
14939                 t = btf_type_by_id(btf, t->type);
14940                 if (!btf_type_is_func_proto(t))
14941                         return -EINVAL;
14942
14943                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
14944                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
14945                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
14946                         return -EINVAL;
14947
14948                 if (tgt_prog && conservative)
14949                         t = NULL;
14950
14951                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
14952                 if (ret < 0)
14953                         return ret;
14954
14955                 if (tgt_prog) {
14956                         if (subprog == 0)
14957                                 addr = (long) tgt_prog->bpf_func;
14958                         else
14959                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
14960                 } else {
14961                         addr = kallsyms_lookup_name(tname);
14962                         if (!addr) {
14963                                 bpf_log(log,
14964                                         "The address of function %s cannot be found\n",
14965                                         tname);
14966                                 return -ENOENT;
14967                         }
14968                 }
14969
14970                 if (prog->aux->sleepable) {
14971                         ret = -EINVAL;
14972                         switch (prog->type) {
14973                         case BPF_PROG_TYPE_TRACING:
14974                                 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
14975                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
14976                                  */
14977                                 if (!check_non_sleepable_error_inject(btf_id) &&
14978                                     within_error_injection_list(addr))
14979                                         ret = 0;
14980                                 break;
14981                         case BPF_PROG_TYPE_LSM:
14982                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
14983                                  * Only some of them are sleepable.
14984                                  */
14985                                 if (bpf_lsm_is_sleepable_hook(btf_id))
14986                                         ret = 0;
14987                                 break;
14988                         default:
14989                                 break;
14990                         }
14991                         if (ret) {
14992                                 bpf_log(log, "%s is not sleepable\n", tname);
14993                                 return ret;
14994                         }
14995                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
14996                         if (tgt_prog) {
14997                                 bpf_log(log, "can't modify return codes of BPF programs\n");
14998                                 return -EINVAL;
14999                         }
15000                         ret = check_attach_modify_return(addr, tname);
15001                         if (ret) {
15002                                 bpf_log(log, "%s() is not modifiable\n", tname);
15003                                 return ret;
15004                         }
15005                 }
15006
15007                 break;
15008         }
15009         tgt_info->tgt_addr = addr;
15010         tgt_info->tgt_name = tname;
15011         tgt_info->tgt_type = t;
15012         return 0;
15013 }
15014
15015 BTF_SET_START(btf_id_deny)
15016 BTF_ID_UNUSED
15017 #ifdef CONFIG_SMP
15018 BTF_ID(func, migrate_disable)
15019 BTF_ID(func, migrate_enable)
15020 #endif
15021 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
15022 BTF_ID(func, rcu_read_unlock_strict)
15023 #endif
15024 BTF_SET_END(btf_id_deny)
15025
15026 static int check_attach_btf_id(struct bpf_verifier_env *env)
15027 {
15028         struct bpf_prog *prog = env->prog;
15029         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
15030         struct bpf_attach_target_info tgt_info = {};
15031         u32 btf_id = prog->aux->attach_btf_id;
15032         struct bpf_trampoline *tr;
15033         int ret;
15034         u64 key;
15035
15036         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
15037                 if (prog->aux->sleepable)
15038                         /* attach_btf_id checked to be zero already */
15039                         return 0;
15040                 verbose(env, "Syscall programs can only be sleepable\n");
15041                 return -EINVAL;
15042         }
15043
15044         if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
15045             prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
15046                 verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
15047                 return -EINVAL;
15048         }
15049
15050         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
15051                 return check_struct_ops_btf_id(env);
15052
15053         if (prog->type != BPF_PROG_TYPE_TRACING &&
15054             prog->type != BPF_PROG_TYPE_LSM &&
15055             prog->type != BPF_PROG_TYPE_EXT)
15056                 return 0;
15057
15058         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
15059         if (ret)
15060                 return ret;
15061
15062         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
15063                 /* to make freplace equivalent to their targets, they need to
15064                  * inherit env->ops and expected_attach_type for the rest of the
15065                  * verification
15066                  */
15067                 env->ops = bpf_verifier_ops[tgt_prog->type];
15068                 prog->expected_attach_type = tgt_prog->expected_attach_type;
15069         }
15070
15071         /* store info about the attachment target that will be used later */
15072         prog->aux->attach_func_proto = tgt_info.tgt_type;
15073         prog->aux->attach_func_name = tgt_info.tgt_name;
15074
15075         if (tgt_prog) {
15076                 prog->aux->saved_dst_prog_type = tgt_prog->type;
15077                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
15078         }
15079
15080         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
15081                 prog->aux->attach_btf_trace = true;
15082                 return 0;
15083         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
15084                 if (!bpf_iter_prog_supported(prog))
15085                         return -EINVAL;
15086                 return 0;
15087         }
15088
15089         if (prog->type == BPF_PROG_TYPE_LSM) {
15090                 ret = bpf_lsm_verify_prog(&env->log, prog);
15091                 if (ret < 0)
15092                         return ret;
15093         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
15094                    btf_id_set_contains(&btf_id_deny, btf_id)) {
15095                 return -EINVAL;
15096         }
15097
15098         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
15099         tr = bpf_trampoline_get(key, &tgt_info);
15100         if (!tr)
15101                 return -ENOMEM;
15102
15103         prog->aux->dst_trampoline = tr;
15104         return 0;
15105 }
15106
15107 struct btf *bpf_get_btf_vmlinux(void)
15108 {
15109         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
15110                 mutex_lock(&bpf_verifier_lock);
15111                 if (!btf_vmlinux)
15112                         btf_vmlinux = btf_parse_vmlinux();
15113                 mutex_unlock(&bpf_verifier_lock);
15114         }
15115         return btf_vmlinux;
15116 }
15117
15118 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
15119 {
15120         u64 start_time = ktime_get_ns();
15121         struct bpf_verifier_env *env;
15122         struct bpf_verifier_log *log;
15123         int i, len, ret = -EINVAL;
15124         bool is_priv;
15125
15126         /* no program is valid */
15127         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
15128                 return -EINVAL;
15129
15130         /* 'struct bpf_verifier_env' can be global, but since it's not small,
15131          * allocate/free it every time bpf_check() is called
15132          */
15133         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
15134         if (!env)
15135                 return -ENOMEM;
15136         log = &env->log;
15137
15138         len = (*prog)->len;
15139         env->insn_aux_data =
15140                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
15141         ret = -ENOMEM;
15142         if (!env->insn_aux_data)
15143                 goto err_free_env;
15144         for (i = 0; i < len; i++)
15145                 env->insn_aux_data[i].orig_idx = i;
15146         env->prog = *prog;
15147         env->ops = bpf_verifier_ops[env->prog->type];
15148         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
15149         is_priv = bpf_capable();
15150
15151         bpf_get_btf_vmlinux();
15152
15153         /* grab the mutex to protect few globals used by verifier */
15154         if (!is_priv)
15155                 mutex_lock(&bpf_verifier_lock);
15156
15157         if (attr->log_level || attr->log_buf || attr->log_size) {
15158                 /* user requested verbose verifier output
15159                  * and supplied buffer to store the verification trace
15160                  */
15161                 log->level = attr->log_level;
15162                 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
15163                 log->len_total = attr->log_size;
15164
15165                 /* log attributes have to be sane */
15166                 if (!bpf_verifier_log_attr_valid(log)) {
15167                         ret = -EINVAL;
15168                         goto err_unlock;
15169                 }
15170         }
15171
15172         mark_verifier_state_clean(env);
15173
15174         if (IS_ERR(btf_vmlinux)) {
15175                 /* Either gcc or pahole or kernel are broken. */
15176                 verbose(env, "in-kernel BTF is malformed\n");
15177                 ret = PTR_ERR(btf_vmlinux);
15178                 goto skip_full_check;
15179         }
15180
15181         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
15182         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
15183                 env->strict_alignment = true;
15184         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
15185                 env->strict_alignment = false;
15186
15187         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
15188         env->allow_uninit_stack = bpf_allow_uninit_stack();
15189         env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
15190         env->bypass_spec_v1 = bpf_bypass_spec_v1();
15191         env->bypass_spec_v4 = bpf_bypass_spec_v4();
15192         env->bpf_capable = bpf_capable();
15193
15194         if (is_priv)
15195                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
15196
15197         env->explored_states = kvcalloc(state_htab_size(env),
15198                                        sizeof(struct bpf_verifier_state_list *),
15199                                        GFP_USER);
15200         ret = -ENOMEM;
15201         if (!env->explored_states)
15202                 goto skip_full_check;
15203
15204         ret = add_subprog_and_kfunc(env);
15205         if (ret < 0)
15206                 goto skip_full_check;
15207
15208         ret = check_subprogs(env);
15209         if (ret < 0)
15210                 goto skip_full_check;
15211
15212         ret = check_btf_info(env, attr, uattr);
15213         if (ret < 0)
15214                 goto skip_full_check;
15215
15216         ret = check_attach_btf_id(env);
15217         if (ret)
15218                 goto skip_full_check;
15219
15220         ret = resolve_pseudo_ldimm64(env);
15221         if (ret < 0)
15222                 goto skip_full_check;
15223
15224         if (bpf_prog_is_dev_bound(env->prog->aux)) {
15225                 ret = bpf_prog_offload_verifier_prep(env->prog);
15226                 if (ret)
15227                         goto skip_full_check;
15228         }
15229
15230         ret = check_cfg(env);
15231         if (ret < 0)
15232                 goto skip_full_check;
15233
15234         ret = do_check_subprogs(env);
15235         ret = ret ?: do_check_main(env);
15236
15237         if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
15238                 ret = bpf_prog_offload_finalize(env);
15239
15240 skip_full_check:
15241         kvfree(env->explored_states);
15242
15243         if (ret == 0)
15244                 ret = check_max_stack_depth(env);
15245
15246         /* instruction rewrites happen after this point */
15247         if (ret == 0)
15248                 ret = optimize_bpf_loop(env);
15249
15250         if (is_priv) {
15251                 if (ret == 0)
15252                         opt_hard_wire_dead_code_branches(env);
15253                 if (ret == 0)
15254                         ret = opt_remove_dead_code(env);
15255                 if (ret == 0)
15256                         ret = opt_remove_nops(env);
15257         } else {
15258                 if (ret == 0)
15259                         sanitize_dead_code(env);
15260         }
15261
15262         if (ret == 0)
15263                 /* program is valid, convert *(u32*)(ctx + off) accesses */
15264                 ret = convert_ctx_accesses(env);
15265
15266         if (ret == 0)
15267                 ret = do_misc_fixups(env);
15268
15269         /* do 32-bit optimization after insn patching has done so those patched
15270          * insns could be handled correctly.
15271          */
15272         if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
15273                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
15274                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
15275                                                                      : false;
15276         }
15277
15278         if (ret == 0)
15279                 ret = fixup_call_args(env);
15280
15281         env->verification_time = ktime_get_ns() - start_time;
15282         print_verification_stats(env);
15283         env->prog->aux->verified_insns = env->insn_processed;
15284
15285         if (log->level && bpf_verifier_log_full(log))
15286                 ret = -ENOSPC;
15287         if (log->level && !log->ubuf) {
15288                 ret = -EFAULT;
15289                 goto err_release_maps;
15290         }
15291
15292         if (ret)
15293                 goto err_release_maps;
15294
15295         if (env->used_map_cnt) {
15296                 /* if program passed verifier, update used_maps in bpf_prog_info */
15297                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
15298                                                           sizeof(env->used_maps[0]),
15299                                                           GFP_KERNEL);
15300
15301                 if (!env->prog->aux->used_maps) {
15302                         ret = -ENOMEM;
15303                         goto err_release_maps;
15304                 }
15305
15306                 memcpy(env->prog->aux->used_maps, env->used_maps,
15307                        sizeof(env->used_maps[0]) * env->used_map_cnt);
15308                 env->prog->aux->used_map_cnt = env->used_map_cnt;
15309         }
15310         if (env->used_btf_cnt) {
15311                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
15312                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
15313                                                           sizeof(env->used_btfs[0]),
15314                                                           GFP_KERNEL);
15315                 if (!env->prog->aux->used_btfs) {
15316                         ret = -ENOMEM;
15317                         goto err_release_maps;
15318                 }
15319
15320                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
15321                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
15322                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
15323         }
15324         if (env->used_map_cnt || env->used_btf_cnt) {
15325                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
15326                  * bpf_ld_imm64 instructions
15327                  */
15328                 convert_pseudo_ld_imm64(env);
15329         }
15330
15331         adjust_btf_func(env);
15332
15333 err_release_maps:
15334         if (!env->prog->aux->used_maps)
15335                 /* if we didn't copy map pointers into bpf_prog_info, release
15336                  * them now. Otherwise free_used_maps() will release them.
15337                  */
15338                 release_maps(env);
15339         if (!env->prog->aux->used_btfs)
15340                 release_btfs(env);
15341
15342         /* extension progs temporarily inherit the attach_type of their targets
15343            for verification purposes, so set it back to zero before returning
15344          */
15345         if (env->prog->type == BPF_PROG_TYPE_EXT)
15346                 env->prog->expected_attach_type = 0;
15347
15348         *prog = env->prog;
15349 err_unlock:
15350         if (!is_priv)
15351                 mutex_unlock(&bpf_verifier_lock);
15352         vfree(env->insn_aux_data);
15353 err_free_env:
15354         kfree(env);
15355         return ret;
15356 }