]> Git Repo - linux.git/blob - kernel/bpf/verifier.c
Merge git://git.kernel.org/pub/scm/linux/kernel/git/netdev/net
[linux.git] / kernel / bpf / verifier.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28
29 #include "disasm.h"
30
31 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
32 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
33         [_id] = & _name ## _verifier_ops,
34 #define BPF_MAP_TYPE(_id, _ops)
35 #define BPF_LINK_TYPE(_id, _name)
36 #include <linux/bpf_types.h>
37 #undef BPF_PROG_TYPE
38 #undef BPF_MAP_TYPE
39 #undef BPF_LINK_TYPE
40 };
41
42 /* bpf_check() is a static code analyzer that walks eBPF program
43  * instruction by instruction and updates register/stack state.
44  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
45  *
46  * The first pass is depth-first-search to check that the program is a DAG.
47  * It rejects the following programs:
48  * - larger than BPF_MAXINSNS insns
49  * - if loop is present (detected via back-edge)
50  * - unreachable insns exist (shouldn't be a forest. program = one function)
51  * - out of bounds or malformed jumps
52  * The second pass is all possible path descent from the 1st insn.
53  * Since it's analyzing all paths through the program, the length of the
54  * analysis is limited to 64k insn, which may be hit even if total number of
55  * insn is less then 4K, but there are too many branches that change stack/regs.
56  * Number of 'branches to be analyzed' is limited to 1k
57  *
58  * On entry to each instruction, each register has a type, and the instruction
59  * changes the types of the registers depending on instruction semantics.
60  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
61  * copied to R1.
62  *
63  * All registers are 64-bit.
64  * R0 - return register
65  * R1-R5 argument passing registers
66  * R6-R9 callee saved registers
67  * R10 - frame pointer read-only
68  *
69  * At the start of BPF program the register R1 contains a pointer to bpf_context
70  * and has type PTR_TO_CTX.
71  *
72  * Verifier tracks arithmetic operations on pointers in case:
73  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
74  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
75  * 1st insn copies R10 (which has FRAME_PTR) type into R1
76  * and 2nd arithmetic instruction is pattern matched to recognize
77  * that it wants to construct a pointer to some element within stack.
78  * So after 2nd insn, the register R1 has type PTR_TO_STACK
79  * (and -20 constant is saved for further stack bounds checking).
80  * Meaning that this reg is a pointer to stack plus known immediate constant.
81  *
82  * Most of the time the registers have SCALAR_VALUE type, which
83  * means the register has some value, but it's not a valid pointer.
84  * (like pointer plus pointer becomes SCALAR_VALUE type)
85  *
86  * When verifier sees load or store instructions the type of base register
87  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
88  * four pointer types recognized by check_mem_access() function.
89  *
90  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
91  * and the range of [ptr, ptr + map's value_size) is accessible.
92  *
93  * registers used to pass values to function calls are checked against
94  * function argument constraints.
95  *
96  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
97  * It means that the register type passed to this function must be
98  * PTR_TO_STACK and it will be used inside the function as
99  * 'pointer to map element key'
100  *
101  * For example the argument constraints for bpf_map_lookup_elem():
102  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
103  *   .arg1_type = ARG_CONST_MAP_PTR,
104  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
105  *
106  * ret_type says that this function returns 'pointer to map elem value or null'
107  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
108  * 2nd argument should be a pointer to stack, which will be used inside
109  * the helper function as a pointer to map element key.
110  *
111  * On the kernel side the helper function looks like:
112  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
113  * {
114  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
115  *    void *key = (void *) (unsigned long) r2;
116  *    void *value;
117  *
118  *    here kernel can access 'key' and 'map' pointers safely, knowing that
119  *    [key, key + map->key_size) bytes are valid and were initialized on
120  *    the stack of eBPF program.
121  * }
122  *
123  * Corresponding eBPF program may look like:
124  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
125  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
126  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
127  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
128  * here verifier looks at prototype of map_lookup_elem() and sees:
129  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
130  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
131  *
132  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
133  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
134  * and were initialized prior to this call.
135  * If it's ok, then verifier allows this BPF_CALL insn and looks at
136  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
137  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
138  * returns either pointer to map value or NULL.
139  *
140  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
141  * insn, the register holding that pointer in the true branch changes state to
142  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
143  * branch. See check_cond_jmp_op().
144  *
145  * After the call R0 is set to return type of the function and registers R1-R5
146  * are set to NOT_INIT to indicate that they are no longer readable.
147  *
148  * The following reference types represent a potential reference to a kernel
149  * resource which, after first being allocated, must be checked and freed by
150  * the BPF program:
151  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
152  *
153  * When the verifier sees a helper call return a reference type, it allocates a
154  * pointer id for the reference and stores it in the current function state.
155  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
156  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
157  * passes through a NULL-check conditional. For the branch wherein the state is
158  * changed to CONST_IMM, the verifier releases the reference.
159  *
160  * For each helper function that allocates a reference, such as
161  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
162  * bpf_sk_release(). When a reference type passes into the release function,
163  * the verifier also releases the reference. If any unchecked or unreleased
164  * reference remains at the end of the program, the verifier rejects it.
165  */
166
167 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
168 struct bpf_verifier_stack_elem {
169         /* verifer state is 'st'
170          * before processing instruction 'insn_idx'
171          * and after processing instruction 'prev_insn_idx'
172          */
173         struct bpf_verifier_state st;
174         int insn_idx;
175         int prev_insn_idx;
176         struct bpf_verifier_stack_elem *next;
177         /* length of verifier log at the time this state was pushed on stack */
178         u32 log_pos;
179 };
180
181 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ    8192
182 #define BPF_COMPLEXITY_LIMIT_STATES     64
183
184 #define BPF_MAP_KEY_POISON      (1ULL << 63)
185 #define BPF_MAP_KEY_SEEN        (1ULL << 62)
186
187 #define BPF_MAP_PTR_UNPRIV      1UL
188 #define BPF_MAP_PTR_POISON      ((void *)((0xeB9FUL << 1) +     \
189                                           POISON_POINTER_DELTA))
190 #define BPF_MAP_PTR(X)          ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
191
192 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
193 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
194 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
195 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
196 static int ref_set_non_owning(struct bpf_verifier_env *env,
197                               struct bpf_reg_state *reg);
198
199 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
200 {
201         return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
202 }
203
204 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
205 {
206         return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
207 }
208
209 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
210                               const struct bpf_map *map, bool unpriv)
211 {
212         BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
213         unpriv |= bpf_map_ptr_unpriv(aux);
214         aux->map_ptr_state = (unsigned long)map |
215                              (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
216 }
217
218 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
219 {
220         return aux->map_key_state & BPF_MAP_KEY_POISON;
221 }
222
223 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
224 {
225         return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
226 }
227
228 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
229 {
230         return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
231 }
232
233 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
234 {
235         bool poisoned = bpf_map_key_poisoned(aux);
236
237         aux->map_key_state = state | BPF_MAP_KEY_SEEN |
238                              (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
239 }
240
241 static bool bpf_pseudo_call(const struct bpf_insn *insn)
242 {
243         return insn->code == (BPF_JMP | BPF_CALL) &&
244                insn->src_reg == BPF_PSEUDO_CALL;
245 }
246
247 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
248 {
249         return insn->code == (BPF_JMP | BPF_CALL) &&
250                insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
251 }
252
253 struct bpf_call_arg_meta {
254         struct bpf_map *map_ptr;
255         bool raw_mode;
256         bool pkt_access;
257         u8 release_regno;
258         int regno;
259         int access_size;
260         int mem_size;
261         u64 msize_max_value;
262         int ref_obj_id;
263         int dynptr_id;
264         int map_uid;
265         int func_id;
266         struct btf *btf;
267         u32 btf_id;
268         struct btf *ret_btf;
269         u32 ret_btf_id;
270         u32 subprogno;
271         struct btf_field *kptr_field;
272 };
273
274 struct bpf_kfunc_call_arg_meta {
275         /* In parameters */
276         struct btf *btf;
277         u32 func_id;
278         u32 kfunc_flags;
279         const struct btf_type *func_proto;
280         const char *func_name;
281         /* Out parameters */
282         u32 ref_obj_id;
283         u8 release_regno;
284         bool r0_rdonly;
285         u32 ret_btf_id;
286         u64 r0_size;
287         u32 subprogno;
288         struct {
289                 u64 value;
290                 bool found;
291         } arg_constant;
292         struct {
293                 struct btf *btf;
294                 u32 btf_id;
295         } arg_obj_drop;
296         struct {
297                 struct btf_field *field;
298         } arg_list_head;
299         struct {
300                 struct btf_field *field;
301         } arg_rbtree_root;
302         struct {
303                 enum bpf_dynptr_type type;
304                 u32 id;
305         } initialized_dynptr;
306         struct {
307                 u8 spi;
308                 u8 frameno;
309         } iter;
310         u64 mem_size;
311 };
312
313 struct btf *btf_vmlinux;
314
315 static DEFINE_MUTEX(bpf_verifier_lock);
316
317 static const struct bpf_line_info *
318 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
319 {
320         const struct bpf_line_info *linfo;
321         const struct bpf_prog *prog;
322         u32 i, nr_linfo;
323
324         prog = env->prog;
325         nr_linfo = prog->aux->nr_linfo;
326
327         if (!nr_linfo || insn_off >= prog->len)
328                 return NULL;
329
330         linfo = prog->aux->linfo;
331         for (i = 1; i < nr_linfo; i++)
332                 if (insn_off < linfo[i].insn_off)
333                         break;
334
335         return &linfo[i - 1];
336 }
337
338 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
339 {
340         struct bpf_verifier_env *env = private_data;
341         va_list args;
342
343         if (!bpf_verifier_log_needed(&env->log))
344                 return;
345
346         va_start(args, fmt);
347         bpf_verifier_vlog(&env->log, fmt, args);
348         va_end(args);
349 }
350
351 static const char *ltrim(const char *s)
352 {
353         while (isspace(*s))
354                 s++;
355
356         return s;
357 }
358
359 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
360                                          u32 insn_off,
361                                          const char *prefix_fmt, ...)
362 {
363         const struct bpf_line_info *linfo;
364
365         if (!bpf_verifier_log_needed(&env->log))
366                 return;
367
368         linfo = find_linfo(env, insn_off);
369         if (!linfo || linfo == env->prev_linfo)
370                 return;
371
372         if (prefix_fmt) {
373                 va_list args;
374
375                 va_start(args, prefix_fmt);
376                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
377                 va_end(args);
378         }
379
380         verbose(env, "%s\n",
381                 ltrim(btf_name_by_offset(env->prog->aux->btf,
382                                          linfo->line_off)));
383
384         env->prev_linfo = linfo;
385 }
386
387 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
388                                    struct bpf_reg_state *reg,
389                                    struct tnum *range, const char *ctx,
390                                    const char *reg_name)
391 {
392         char tn_buf[48];
393
394         verbose(env, "At %s the register %s ", ctx, reg_name);
395         if (!tnum_is_unknown(reg->var_off)) {
396                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
397                 verbose(env, "has value %s", tn_buf);
398         } else {
399                 verbose(env, "has unknown scalar value");
400         }
401         tnum_strn(tn_buf, sizeof(tn_buf), *range);
402         verbose(env, " should have been in %s\n", tn_buf);
403 }
404
405 static bool type_is_pkt_pointer(enum bpf_reg_type type)
406 {
407         type = base_type(type);
408         return type == PTR_TO_PACKET ||
409                type == PTR_TO_PACKET_META;
410 }
411
412 static bool type_is_sk_pointer(enum bpf_reg_type type)
413 {
414         return type == PTR_TO_SOCKET ||
415                 type == PTR_TO_SOCK_COMMON ||
416                 type == PTR_TO_TCP_SOCK ||
417                 type == PTR_TO_XDP_SOCK;
418 }
419
420 static bool type_may_be_null(u32 type)
421 {
422         return type & PTR_MAYBE_NULL;
423 }
424
425 static bool reg_type_not_null(enum bpf_reg_type type)
426 {
427         if (type_may_be_null(type))
428                 return false;
429
430         type = base_type(type);
431         return type == PTR_TO_SOCKET ||
432                 type == PTR_TO_TCP_SOCK ||
433                 type == PTR_TO_MAP_VALUE ||
434                 type == PTR_TO_MAP_KEY ||
435                 type == PTR_TO_SOCK_COMMON ||
436                 type == PTR_TO_MEM;
437 }
438
439 static bool type_is_ptr_alloc_obj(u32 type)
440 {
441         return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
442 }
443
444 static bool type_is_non_owning_ref(u32 type)
445 {
446         return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
447 }
448
449 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
450 {
451         struct btf_record *rec = NULL;
452         struct btf_struct_meta *meta;
453
454         if (reg->type == PTR_TO_MAP_VALUE) {
455                 rec = reg->map_ptr->record;
456         } else if (type_is_ptr_alloc_obj(reg->type)) {
457                 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
458                 if (meta)
459                         rec = meta->record;
460         }
461         return rec;
462 }
463
464 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
465 {
466         return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
467 }
468
469 static bool type_is_rdonly_mem(u32 type)
470 {
471         return type & MEM_RDONLY;
472 }
473
474 static bool is_acquire_function(enum bpf_func_id func_id,
475                                 const struct bpf_map *map)
476 {
477         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
478
479         if (func_id == BPF_FUNC_sk_lookup_tcp ||
480             func_id == BPF_FUNC_sk_lookup_udp ||
481             func_id == BPF_FUNC_skc_lookup_tcp ||
482             func_id == BPF_FUNC_ringbuf_reserve ||
483             func_id == BPF_FUNC_kptr_xchg)
484                 return true;
485
486         if (func_id == BPF_FUNC_map_lookup_elem &&
487             (map_type == BPF_MAP_TYPE_SOCKMAP ||
488              map_type == BPF_MAP_TYPE_SOCKHASH))
489                 return true;
490
491         return false;
492 }
493
494 static bool is_ptr_cast_function(enum bpf_func_id func_id)
495 {
496         return func_id == BPF_FUNC_tcp_sock ||
497                 func_id == BPF_FUNC_sk_fullsock ||
498                 func_id == BPF_FUNC_skc_to_tcp_sock ||
499                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
500                 func_id == BPF_FUNC_skc_to_udp6_sock ||
501                 func_id == BPF_FUNC_skc_to_mptcp_sock ||
502                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
503                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
504 }
505
506 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
507 {
508         return func_id == BPF_FUNC_dynptr_data;
509 }
510
511 static bool is_callback_calling_function(enum bpf_func_id func_id)
512 {
513         return func_id == BPF_FUNC_for_each_map_elem ||
514                func_id == BPF_FUNC_timer_set_callback ||
515                func_id == BPF_FUNC_find_vma ||
516                func_id == BPF_FUNC_loop ||
517                func_id == BPF_FUNC_user_ringbuf_drain;
518 }
519
520 static bool is_storage_get_function(enum bpf_func_id func_id)
521 {
522         return func_id == BPF_FUNC_sk_storage_get ||
523                func_id == BPF_FUNC_inode_storage_get ||
524                func_id == BPF_FUNC_task_storage_get ||
525                func_id == BPF_FUNC_cgrp_storage_get;
526 }
527
528 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
529                                         const struct bpf_map *map)
530 {
531         int ref_obj_uses = 0;
532
533         if (is_ptr_cast_function(func_id))
534                 ref_obj_uses++;
535         if (is_acquire_function(func_id, map))
536                 ref_obj_uses++;
537         if (is_dynptr_ref_function(func_id))
538                 ref_obj_uses++;
539
540         return ref_obj_uses > 1;
541 }
542
543 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
544 {
545         return BPF_CLASS(insn->code) == BPF_STX &&
546                BPF_MODE(insn->code) == BPF_ATOMIC &&
547                insn->imm == BPF_CMPXCHG;
548 }
549
550 /* string representation of 'enum bpf_reg_type'
551  *
552  * Note that reg_type_str() can not appear more than once in a single verbose()
553  * statement.
554  */
555 static const char *reg_type_str(struct bpf_verifier_env *env,
556                                 enum bpf_reg_type type)
557 {
558         char postfix[16] = {0}, prefix[64] = {0};
559         static const char * const str[] = {
560                 [NOT_INIT]              = "?",
561                 [SCALAR_VALUE]          = "scalar",
562                 [PTR_TO_CTX]            = "ctx",
563                 [CONST_PTR_TO_MAP]      = "map_ptr",
564                 [PTR_TO_MAP_VALUE]      = "map_value",
565                 [PTR_TO_STACK]          = "fp",
566                 [PTR_TO_PACKET]         = "pkt",
567                 [PTR_TO_PACKET_META]    = "pkt_meta",
568                 [PTR_TO_PACKET_END]     = "pkt_end",
569                 [PTR_TO_FLOW_KEYS]      = "flow_keys",
570                 [PTR_TO_SOCKET]         = "sock",
571                 [PTR_TO_SOCK_COMMON]    = "sock_common",
572                 [PTR_TO_TCP_SOCK]       = "tcp_sock",
573                 [PTR_TO_TP_BUFFER]      = "tp_buffer",
574                 [PTR_TO_XDP_SOCK]       = "xdp_sock",
575                 [PTR_TO_BTF_ID]         = "ptr_",
576                 [PTR_TO_MEM]            = "mem",
577                 [PTR_TO_BUF]            = "buf",
578                 [PTR_TO_FUNC]           = "func",
579                 [PTR_TO_MAP_KEY]        = "map_key",
580                 [CONST_PTR_TO_DYNPTR]   = "dynptr_ptr",
581         };
582
583         if (type & PTR_MAYBE_NULL) {
584                 if (base_type(type) == PTR_TO_BTF_ID)
585                         strncpy(postfix, "or_null_", 16);
586                 else
587                         strncpy(postfix, "_or_null", 16);
588         }
589
590         snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
591                  type & MEM_RDONLY ? "rdonly_" : "",
592                  type & MEM_RINGBUF ? "ringbuf_" : "",
593                  type & MEM_USER ? "user_" : "",
594                  type & MEM_PERCPU ? "percpu_" : "",
595                  type & MEM_RCU ? "rcu_" : "",
596                  type & PTR_UNTRUSTED ? "untrusted_" : "",
597                  type & PTR_TRUSTED ? "trusted_" : ""
598         );
599
600         snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
601                  prefix, str[base_type(type)], postfix);
602         return env->type_str_buf;
603 }
604
605 static char slot_type_char[] = {
606         [STACK_INVALID] = '?',
607         [STACK_SPILL]   = 'r',
608         [STACK_MISC]    = 'm',
609         [STACK_ZERO]    = '0',
610         [STACK_DYNPTR]  = 'd',
611         [STACK_ITER]    = 'i',
612 };
613
614 static void print_liveness(struct bpf_verifier_env *env,
615                            enum bpf_reg_liveness live)
616 {
617         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
618             verbose(env, "_");
619         if (live & REG_LIVE_READ)
620                 verbose(env, "r");
621         if (live & REG_LIVE_WRITTEN)
622                 verbose(env, "w");
623         if (live & REG_LIVE_DONE)
624                 verbose(env, "D");
625 }
626
627 static int __get_spi(s32 off)
628 {
629         return (-off - 1) / BPF_REG_SIZE;
630 }
631
632 static struct bpf_func_state *func(struct bpf_verifier_env *env,
633                                    const struct bpf_reg_state *reg)
634 {
635         struct bpf_verifier_state *cur = env->cur_state;
636
637         return cur->frame[reg->frameno];
638 }
639
640 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
641 {
642        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
643
644        /* We need to check that slots between [spi - nr_slots + 1, spi] are
645         * within [0, allocated_stack).
646         *
647         * Please note that the spi grows downwards. For example, a dynptr
648         * takes the size of two stack slots; the first slot will be at
649         * spi and the second slot will be at spi - 1.
650         */
651        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
652 }
653
654 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
655                                   const char *obj_kind, int nr_slots)
656 {
657         int off, spi;
658
659         if (!tnum_is_const(reg->var_off)) {
660                 verbose(env, "%s has to be at a constant offset\n", obj_kind);
661                 return -EINVAL;
662         }
663
664         off = reg->off + reg->var_off.value;
665         if (off % BPF_REG_SIZE) {
666                 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
667                 return -EINVAL;
668         }
669
670         spi = __get_spi(off);
671         if (spi + 1 < nr_slots) {
672                 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
673                 return -EINVAL;
674         }
675
676         if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
677                 return -ERANGE;
678         return spi;
679 }
680
681 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
682 {
683         return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
684 }
685
686 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
687 {
688         return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
689 }
690
691 static const char *btf_type_name(const struct btf *btf, u32 id)
692 {
693         return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
694 }
695
696 static const char *dynptr_type_str(enum bpf_dynptr_type type)
697 {
698         switch (type) {
699         case BPF_DYNPTR_TYPE_LOCAL:
700                 return "local";
701         case BPF_DYNPTR_TYPE_RINGBUF:
702                 return "ringbuf";
703         case BPF_DYNPTR_TYPE_SKB:
704                 return "skb";
705         case BPF_DYNPTR_TYPE_XDP:
706                 return "xdp";
707         case BPF_DYNPTR_TYPE_INVALID:
708                 return "<invalid>";
709         default:
710                 WARN_ONCE(1, "unknown dynptr type %d\n", type);
711                 return "<unknown>";
712         }
713 }
714
715 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
716 {
717         if (!btf || btf_id == 0)
718                 return "<invalid>";
719
720         /* we already validated that type is valid and has conforming name */
721         return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
722 }
723
724 static const char *iter_state_str(enum bpf_iter_state state)
725 {
726         switch (state) {
727         case BPF_ITER_STATE_ACTIVE:
728                 return "active";
729         case BPF_ITER_STATE_DRAINED:
730                 return "drained";
731         case BPF_ITER_STATE_INVALID:
732                 return "<invalid>";
733         default:
734                 WARN_ONCE(1, "unknown iter state %d\n", state);
735                 return "<unknown>";
736         }
737 }
738
739 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
740 {
741         env->scratched_regs |= 1U << regno;
742 }
743
744 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
745 {
746         env->scratched_stack_slots |= 1ULL << spi;
747 }
748
749 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
750 {
751         return (env->scratched_regs >> regno) & 1;
752 }
753
754 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
755 {
756         return (env->scratched_stack_slots >> regno) & 1;
757 }
758
759 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
760 {
761         return env->scratched_regs || env->scratched_stack_slots;
762 }
763
764 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
765 {
766         env->scratched_regs = 0U;
767         env->scratched_stack_slots = 0ULL;
768 }
769
770 /* Used for printing the entire verifier state. */
771 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
772 {
773         env->scratched_regs = ~0U;
774         env->scratched_stack_slots = ~0ULL;
775 }
776
777 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
778 {
779         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
780         case DYNPTR_TYPE_LOCAL:
781                 return BPF_DYNPTR_TYPE_LOCAL;
782         case DYNPTR_TYPE_RINGBUF:
783                 return BPF_DYNPTR_TYPE_RINGBUF;
784         case DYNPTR_TYPE_SKB:
785                 return BPF_DYNPTR_TYPE_SKB;
786         case DYNPTR_TYPE_XDP:
787                 return BPF_DYNPTR_TYPE_XDP;
788         default:
789                 return BPF_DYNPTR_TYPE_INVALID;
790         }
791 }
792
793 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
794 {
795         switch (type) {
796         case BPF_DYNPTR_TYPE_LOCAL:
797                 return DYNPTR_TYPE_LOCAL;
798         case BPF_DYNPTR_TYPE_RINGBUF:
799                 return DYNPTR_TYPE_RINGBUF;
800         case BPF_DYNPTR_TYPE_SKB:
801                 return DYNPTR_TYPE_SKB;
802         case BPF_DYNPTR_TYPE_XDP:
803                 return DYNPTR_TYPE_XDP;
804         default:
805                 return 0;
806         }
807 }
808
809 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
810 {
811         return type == BPF_DYNPTR_TYPE_RINGBUF;
812 }
813
814 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
815                               enum bpf_dynptr_type type,
816                               bool first_slot, int dynptr_id);
817
818 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
819                                 struct bpf_reg_state *reg);
820
821 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
822                                    struct bpf_reg_state *sreg1,
823                                    struct bpf_reg_state *sreg2,
824                                    enum bpf_dynptr_type type)
825 {
826         int id = ++env->id_gen;
827
828         __mark_dynptr_reg(sreg1, type, true, id);
829         __mark_dynptr_reg(sreg2, type, false, id);
830 }
831
832 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
833                                struct bpf_reg_state *reg,
834                                enum bpf_dynptr_type type)
835 {
836         __mark_dynptr_reg(reg, type, true, ++env->id_gen);
837 }
838
839 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
840                                         struct bpf_func_state *state, int spi);
841
842 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
843                                    enum bpf_arg_type arg_type, int insn_idx)
844 {
845         struct bpf_func_state *state = func(env, reg);
846         enum bpf_dynptr_type type;
847         int spi, i, id, err;
848
849         spi = dynptr_get_spi(env, reg);
850         if (spi < 0)
851                 return spi;
852
853         /* We cannot assume both spi and spi - 1 belong to the same dynptr,
854          * hence we need to call destroy_if_dynptr_stack_slot twice for both,
855          * to ensure that for the following example:
856          *      [d1][d1][d2][d2]
857          * spi    3   2   1   0
858          * So marking spi = 2 should lead to destruction of both d1 and d2. In
859          * case they do belong to same dynptr, second call won't see slot_type
860          * as STACK_DYNPTR and will simply skip destruction.
861          */
862         err = destroy_if_dynptr_stack_slot(env, state, spi);
863         if (err)
864                 return err;
865         err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
866         if (err)
867                 return err;
868
869         for (i = 0; i < BPF_REG_SIZE; i++) {
870                 state->stack[spi].slot_type[i] = STACK_DYNPTR;
871                 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
872         }
873
874         type = arg_to_dynptr_type(arg_type);
875         if (type == BPF_DYNPTR_TYPE_INVALID)
876                 return -EINVAL;
877
878         mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
879                                &state->stack[spi - 1].spilled_ptr, type);
880
881         if (dynptr_type_refcounted(type)) {
882                 /* The id is used to track proper releasing */
883                 id = acquire_reference_state(env, insn_idx);
884                 if (id < 0)
885                         return id;
886
887                 state->stack[spi].spilled_ptr.ref_obj_id = id;
888                 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
889         }
890
891         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
892         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
893
894         return 0;
895 }
896
897 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
898 {
899         struct bpf_func_state *state = func(env, reg);
900         int spi, i;
901
902         spi = dynptr_get_spi(env, reg);
903         if (spi < 0)
904                 return spi;
905
906         for (i = 0; i < BPF_REG_SIZE; i++) {
907                 state->stack[spi].slot_type[i] = STACK_INVALID;
908                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
909         }
910
911         /* Invalidate any slices associated with this dynptr */
912         if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type))
913                 WARN_ON_ONCE(release_reference(env, state->stack[spi].spilled_ptr.ref_obj_id));
914
915         __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
916         __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
917
918         /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
919          *
920          * While we don't allow reading STACK_INVALID, it is still possible to
921          * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
922          * helpers or insns can do partial read of that part without failing,
923          * but check_stack_range_initialized, check_stack_read_var_off, and
924          * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
925          * the slot conservatively. Hence we need to prevent those liveness
926          * marking walks.
927          *
928          * This was not a problem before because STACK_INVALID is only set by
929          * default (where the default reg state has its reg->parent as NULL), or
930          * in clean_live_states after REG_LIVE_DONE (at which point
931          * mark_reg_read won't walk reg->parent chain), but not randomly during
932          * verifier state exploration (like we did above). Hence, for our case
933          * parentage chain will still be live (i.e. reg->parent may be
934          * non-NULL), while earlier reg->parent was NULL, so we need
935          * REG_LIVE_WRITTEN to screen off read marker propagation when it is
936          * done later on reads or by mark_dynptr_read as well to unnecessary
937          * mark registers in verifier state.
938          */
939         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
940         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
941
942         return 0;
943 }
944
945 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
946                                struct bpf_reg_state *reg);
947
948 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
949 {
950         if (!env->allow_ptr_leaks)
951                 __mark_reg_not_init(env, reg);
952         else
953                 __mark_reg_unknown(env, reg);
954 }
955
956 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
957                                         struct bpf_func_state *state, int spi)
958 {
959         struct bpf_func_state *fstate;
960         struct bpf_reg_state *dreg;
961         int i, dynptr_id;
962
963         /* We always ensure that STACK_DYNPTR is never set partially,
964          * hence just checking for slot_type[0] is enough. This is
965          * different for STACK_SPILL, where it may be only set for
966          * 1 byte, so code has to use is_spilled_reg.
967          */
968         if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
969                 return 0;
970
971         /* Reposition spi to first slot */
972         if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
973                 spi = spi + 1;
974
975         if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
976                 verbose(env, "cannot overwrite referenced dynptr\n");
977                 return -EINVAL;
978         }
979
980         mark_stack_slot_scratched(env, spi);
981         mark_stack_slot_scratched(env, spi - 1);
982
983         /* Writing partially to one dynptr stack slot destroys both. */
984         for (i = 0; i < BPF_REG_SIZE; i++) {
985                 state->stack[spi].slot_type[i] = STACK_INVALID;
986                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
987         }
988
989         dynptr_id = state->stack[spi].spilled_ptr.id;
990         /* Invalidate any slices associated with this dynptr */
991         bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
992                 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
993                 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
994                         continue;
995                 if (dreg->dynptr_id == dynptr_id)
996                         mark_reg_invalid(env, dreg);
997         }));
998
999         /* Do not release reference state, we are destroying dynptr on stack,
1000          * not using some helper to release it. Just reset register.
1001          */
1002         __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1003         __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1004
1005         /* Same reason as unmark_stack_slots_dynptr above */
1006         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1007         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1008
1009         return 0;
1010 }
1011
1012 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1013 {
1014         int spi;
1015
1016         if (reg->type == CONST_PTR_TO_DYNPTR)
1017                 return false;
1018
1019         spi = dynptr_get_spi(env, reg);
1020
1021         /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1022          * error because this just means the stack state hasn't been updated yet.
1023          * We will do check_mem_access to check and update stack bounds later.
1024          */
1025         if (spi < 0 && spi != -ERANGE)
1026                 return false;
1027
1028         /* We don't need to check if the stack slots are marked by previous
1029          * dynptr initializations because we allow overwriting existing unreferenced
1030          * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1031          * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1032          * touching are completely destructed before we reinitialize them for a new
1033          * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1034          * instead of delaying it until the end where the user will get "Unreleased
1035          * reference" error.
1036          */
1037         return true;
1038 }
1039
1040 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1041 {
1042         struct bpf_func_state *state = func(env, reg);
1043         int i, spi;
1044
1045         /* This already represents first slot of initialized bpf_dynptr.
1046          *
1047          * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1048          * check_func_arg_reg_off's logic, so we don't need to check its
1049          * offset and alignment.
1050          */
1051         if (reg->type == CONST_PTR_TO_DYNPTR)
1052                 return true;
1053
1054         spi = dynptr_get_spi(env, reg);
1055         if (spi < 0)
1056                 return false;
1057         if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1058                 return false;
1059
1060         for (i = 0; i < BPF_REG_SIZE; i++) {
1061                 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1062                     state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1063                         return false;
1064         }
1065
1066         return true;
1067 }
1068
1069 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1070                                     enum bpf_arg_type arg_type)
1071 {
1072         struct bpf_func_state *state = func(env, reg);
1073         enum bpf_dynptr_type dynptr_type;
1074         int spi;
1075
1076         /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1077         if (arg_type == ARG_PTR_TO_DYNPTR)
1078                 return true;
1079
1080         dynptr_type = arg_to_dynptr_type(arg_type);
1081         if (reg->type == CONST_PTR_TO_DYNPTR) {
1082                 return reg->dynptr.type == dynptr_type;
1083         } else {
1084                 spi = dynptr_get_spi(env, reg);
1085                 if (spi < 0)
1086                         return false;
1087                 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1088         }
1089 }
1090
1091 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1092
1093 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1094                                  struct bpf_reg_state *reg, int insn_idx,
1095                                  struct btf *btf, u32 btf_id, int nr_slots)
1096 {
1097         struct bpf_func_state *state = func(env, reg);
1098         int spi, i, j, id;
1099
1100         spi = iter_get_spi(env, reg, nr_slots);
1101         if (spi < 0)
1102                 return spi;
1103
1104         id = acquire_reference_state(env, insn_idx);
1105         if (id < 0)
1106                 return id;
1107
1108         for (i = 0; i < nr_slots; i++) {
1109                 struct bpf_stack_state *slot = &state->stack[spi - i];
1110                 struct bpf_reg_state *st = &slot->spilled_ptr;
1111
1112                 __mark_reg_known_zero(st);
1113                 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1114                 st->live |= REG_LIVE_WRITTEN;
1115                 st->ref_obj_id = i == 0 ? id : 0;
1116                 st->iter.btf = btf;
1117                 st->iter.btf_id = btf_id;
1118                 st->iter.state = BPF_ITER_STATE_ACTIVE;
1119                 st->iter.depth = 0;
1120
1121                 for (j = 0; j < BPF_REG_SIZE; j++)
1122                         slot->slot_type[j] = STACK_ITER;
1123
1124                 mark_stack_slot_scratched(env, spi - i);
1125         }
1126
1127         return 0;
1128 }
1129
1130 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1131                                    struct bpf_reg_state *reg, int nr_slots)
1132 {
1133         struct bpf_func_state *state = func(env, reg);
1134         int spi, i, j;
1135
1136         spi = iter_get_spi(env, reg, nr_slots);
1137         if (spi < 0)
1138                 return spi;
1139
1140         for (i = 0; i < nr_slots; i++) {
1141                 struct bpf_stack_state *slot = &state->stack[spi - i];
1142                 struct bpf_reg_state *st = &slot->spilled_ptr;
1143
1144                 if (i == 0)
1145                         WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1146
1147                 __mark_reg_not_init(env, st);
1148
1149                 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1150                 st->live |= REG_LIVE_WRITTEN;
1151
1152                 for (j = 0; j < BPF_REG_SIZE; j++)
1153                         slot->slot_type[j] = STACK_INVALID;
1154
1155                 mark_stack_slot_scratched(env, spi - i);
1156         }
1157
1158         return 0;
1159 }
1160
1161 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1162                                      struct bpf_reg_state *reg, int nr_slots)
1163 {
1164         struct bpf_func_state *state = func(env, reg);
1165         int spi, i, j;
1166
1167         /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1168          * will do check_mem_access to check and update stack bounds later, so
1169          * return true for that case.
1170          */
1171         spi = iter_get_spi(env, reg, nr_slots);
1172         if (spi == -ERANGE)
1173                 return true;
1174         if (spi < 0)
1175                 return false;
1176
1177         for (i = 0; i < nr_slots; i++) {
1178                 struct bpf_stack_state *slot = &state->stack[spi - i];
1179
1180                 for (j = 0; j < BPF_REG_SIZE; j++)
1181                         if (slot->slot_type[j] == STACK_ITER)
1182                                 return false;
1183         }
1184
1185         return true;
1186 }
1187
1188 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1189                                    struct btf *btf, u32 btf_id, int nr_slots)
1190 {
1191         struct bpf_func_state *state = func(env, reg);
1192         int spi, i, j;
1193
1194         spi = iter_get_spi(env, reg, nr_slots);
1195         if (spi < 0)
1196                 return false;
1197
1198         for (i = 0; i < nr_slots; i++) {
1199                 struct bpf_stack_state *slot = &state->stack[spi - i];
1200                 struct bpf_reg_state *st = &slot->spilled_ptr;
1201
1202                 /* only main (first) slot has ref_obj_id set */
1203                 if (i == 0 && !st->ref_obj_id)
1204                         return false;
1205                 if (i != 0 && st->ref_obj_id)
1206                         return false;
1207                 if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1208                         return false;
1209
1210                 for (j = 0; j < BPF_REG_SIZE; j++)
1211                         if (slot->slot_type[j] != STACK_ITER)
1212                                 return false;
1213         }
1214
1215         return true;
1216 }
1217
1218 /* Check if given stack slot is "special":
1219  *   - spilled register state (STACK_SPILL);
1220  *   - dynptr state (STACK_DYNPTR);
1221  *   - iter state (STACK_ITER).
1222  */
1223 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1224 {
1225         enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1226
1227         switch (type) {
1228         case STACK_SPILL:
1229         case STACK_DYNPTR:
1230         case STACK_ITER:
1231                 return true;
1232         case STACK_INVALID:
1233         case STACK_MISC:
1234         case STACK_ZERO:
1235                 return false;
1236         default:
1237                 WARN_ONCE(1, "unknown stack slot type %d\n", type);
1238                 return true;
1239         }
1240 }
1241
1242 /* The reg state of a pointer or a bounded scalar was saved when
1243  * it was spilled to the stack.
1244  */
1245 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1246 {
1247         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1248 }
1249
1250 static void scrub_spilled_slot(u8 *stype)
1251 {
1252         if (*stype != STACK_INVALID)
1253                 *stype = STACK_MISC;
1254 }
1255
1256 static void print_verifier_state(struct bpf_verifier_env *env,
1257                                  const struct bpf_func_state *state,
1258                                  bool print_all)
1259 {
1260         const struct bpf_reg_state *reg;
1261         enum bpf_reg_type t;
1262         int i;
1263
1264         if (state->frameno)
1265                 verbose(env, " frame%d:", state->frameno);
1266         for (i = 0; i < MAX_BPF_REG; i++) {
1267                 reg = &state->regs[i];
1268                 t = reg->type;
1269                 if (t == NOT_INIT)
1270                         continue;
1271                 if (!print_all && !reg_scratched(env, i))
1272                         continue;
1273                 verbose(env, " R%d", i);
1274                 print_liveness(env, reg->live);
1275                 verbose(env, "=");
1276                 if (t == SCALAR_VALUE && reg->precise)
1277                         verbose(env, "P");
1278                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1279                     tnum_is_const(reg->var_off)) {
1280                         /* reg->off should be 0 for SCALAR_VALUE */
1281                         verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1282                         verbose(env, "%lld", reg->var_off.value + reg->off);
1283                 } else {
1284                         const char *sep = "";
1285
1286                         verbose(env, "%s", reg_type_str(env, t));
1287                         if (base_type(t) == PTR_TO_BTF_ID)
1288                                 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1289                         verbose(env, "(");
1290 /*
1291  * _a stands for append, was shortened to avoid multiline statements below.
1292  * This macro is used to output a comma separated list of attributes.
1293  */
1294 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1295
1296                         if (reg->id)
1297                                 verbose_a("id=%d", reg->id);
1298                         if (reg->ref_obj_id)
1299                                 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1300                         if (type_is_non_owning_ref(reg->type))
1301                                 verbose_a("%s", "non_own_ref");
1302                         if (t != SCALAR_VALUE)
1303                                 verbose_a("off=%d", reg->off);
1304                         if (type_is_pkt_pointer(t))
1305                                 verbose_a("r=%d", reg->range);
1306                         else if (base_type(t) == CONST_PTR_TO_MAP ||
1307                                  base_type(t) == PTR_TO_MAP_KEY ||
1308                                  base_type(t) == PTR_TO_MAP_VALUE)
1309                                 verbose_a("ks=%d,vs=%d",
1310                                           reg->map_ptr->key_size,
1311                                           reg->map_ptr->value_size);
1312                         if (tnum_is_const(reg->var_off)) {
1313                                 /* Typically an immediate SCALAR_VALUE, but
1314                                  * could be a pointer whose offset is too big
1315                                  * for reg->off
1316                                  */
1317                                 verbose_a("imm=%llx", reg->var_off.value);
1318                         } else {
1319                                 if (reg->smin_value != reg->umin_value &&
1320                                     reg->smin_value != S64_MIN)
1321                                         verbose_a("smin=%lld", (long long)reg->smin_value);
1322                                 if (reg->smax_value != reg->umax_value &&
1323                                     reg->smax_value != S64_MAX)
1324                                         verbose_a("smax=%lld", (long long)reg->smax_value);
1325                                 if (reg->umin_value != 0)
1326                                         verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1327                                 if (reg->umax_value != U64_MAX)
1328                                         verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1329                                 if (!tnum_is_unknown(reg->var_off)) {
1330                                         char tn_buf[48];
1331
1332                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1333                                         verbose_a("var_off=%s", tn_buf);
1334                                 }
1335                                 if (reg->s32_min_value != reg->smin_value &&
1336                                     reg->s32_min_value != S32_MIN)
1337                                         verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1338                                 if (reg->s32_max_value != reg->smax_value &&
1339                                     reg->s32_max_value != S32_MAX)
1340                                         verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1341                                 if (reg->u32_min_value != reg->umin_value &&
1342                                     reg->u32_min_value != U32_MIN)
1343                                         verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1344                                 if (reg->u32_max_value != reg->umax_value &&
1345                                     reg->u32_max_value != U32_MAX)
1346                                         verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1347                         }
1348 #undef verbose_a
1349
1350                         verbose(env, ")");
1351                 }
1352         }
1353         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1354                 char types_buf[BPF_REG_SIZE + 1];
1355                 bool valid = false;
1356                 int j;
1357
1358                 for (j = 0; j < BPF_REG_SIZE; j++) {
1359                         if (state->stack[i].slot_type[j] != STACK_INVALID)
1360                                 valid = true;
1361                         types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1362                 }
1363                 types_buf[BPF_REG_SIZE] = 0;
1364                 if (!valid)
1365                         continue;
1366                 if (!print_all && !stack_slot_scratched(env, i))
1367                         continue;
1368                 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1369                 case STACK_SPILL:
1370                         reg = &state->stack[i].spilled_ptr;
1371                         t = reg->type;
1372
1373                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1374                         print_liveness(env, reg->live);
1375                         verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1376                         if (t == SCALAR_VALUE && reg->precise)
1377                                 verbose(env, "P");
1378                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1379                                 verbose(env, "%lld", reg->var_off.value + reg->off);
1380                         break;
1381                 case STACK_DYNPTR:
1382                         i += BPF_DYNPTR_NR_SLOTS - 1;
1383                         reg = &state->stack[i].spilled_ptr;
1384
1385                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1386                         print_liveness(env, reg->live);
1387                         verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1388                         if (reg->ref_obj_id)
1389                                 verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1390                         break;
1391                 case STACK_ITER:
1392                         /* only main slot has ref_obj_id set; skip others */
1393                         reg = &state->stack[i].spilled_ptr;
1394                         if (!reg->ref_obj_id)
1395                                 continue;
1396
1397                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1398                         print_liveness(env, reg->live);
1399                         verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1400                                 iter_type_str(reg->iter.btf, reg->iter.btf_id),
1401                                 reg->ref_obj_id, iter_state_str(reg->iter.state),
1402                                 reg->iter.depth);
1403                         break;
1404                 case STACK_MISC:
1405                 case STACK_ZERO:
1406                 default:
1407                         reg = &state->stack[i].spilled_ptr;
1408
1409                         for (j = 0; j < BPF_REG_SIZE; j++)
1410                                 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1411                         types_buf[BPF_REG_SIZE] = 0;
1412
1413                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1414                         print_liveness(env, reg->live);
1415                         verbose(env, "=%s", types_buf);
1416                         break;
1417                 }
1418         }
1419         if (state->acquired_refs && state->refs[0].id) {
1420                 verbose(env, " refs=%d", state->refs[0].id);
1421                 for (i = 1; i < state->acquired_refs; i++)
1422                         if (state->refs[i].id)
1423                                 verbose(env, ",%d", state->refs[i].id);
1424         }
1425         if (state->in_callback_fn)
1426                 verbose(env, " cb");
1427         if (state->in_async_callback_fn)
1428                 verbose(env, " async_cb");
1429         verbose(env, "\n");
1430         mark_verifier_state_clean(env);
1431 }
1432
1433 static inline u32 vlog_alignment(u32 pos)
1434 {
1435         return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1436                         BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1437 }
1438
1439 static void print_insn_state(struct bpf_verifier_env *env,
1440                              const struct bpf_func_state *state)
1441 {
1442         if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1443                 /* remove new line character */
1444                 bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1445                 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1446         } else {
1447                 verbose(env, "%d:", env->insn_idx);
1448         }
1449         print_verifier_state(env, state, false);
1450 }
1451
1452 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1453  * small to hold src. This is different from krealloc since we don't want to preserve
1454  * the contents of dst.
1455  *
1456  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1457  * not be allocated.
1458  */
1459 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1460 {
1461         size_t alloc_bytes;
1462         void *orig = dst;
1463         size_t bytes;
1464
1465         if (ZERO_OR_NULL_PTR(src))
1466                 goto out;
1467
1468         if (unlikely(check_mul_overflow(n, size, &bytes)))
1469                 return NULL;
1470
1471         alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1472         dst = krealloc(orig, alloc_bytes, flags);
1473         if (!dst) {
1474                 kfree(orig);
1475                 return NULL;
1476         }
1477
1478         memcpy(dst, src, bytes);
1479 out:
1480         return dst ? dst : ZERO_SIZE_PTR;
1481 }
1482
1483 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1484  * small to hold new_n items. new items are zeroed out if the array grows.
1485  *
1486  * Contrary to krealloc_array, does not free arr if new_n is zero.
1487  */
1488 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1489 {
1490         size_t alloc_size;
1491         void *new_arr;
1492
1493         if (!new_n || old_n == new_n)
1494                 goto out;
1495
1496         alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1497         new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1498         if (!new_arr) {
1499                 kfree(arr);
1500                 return NULL;
1501         }
1502         arr = new_arr;
1503
1504         if (new_n > old_n)
1505                 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1506
1507 out:
1508         return arr ? arr : ZERO_SIZE_PTR;
1509 }
1510
1511 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1512 {
1513         dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1514                                sizeof(struct bpf_reference_state), GFP_KERNEL);
1515         if (!dst->refs)
1516                 return -ENOMEM;
1517
1518         dst->acquired_refs = src->acquired_refs;
1519         return 0;
1520 }
1521
1522 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1523 {
1524         size_t n = src->allocated_stack / BPF_REG_SIZE;
1525
1526         dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1527                                 GFP_KERNEL);
1528         if (!dst->stack)
1529                 return -ENOMEM;
1530
1531         dst->allocated_stack = src->allocated_stack;
1532         return 0;
1533 }
1534
1535 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1536 {
1537         state->refs = realloc_array(state->refs, state->acquired_refs, n,
1538                                     sizeof(struct bpf_reference_state));
1539         if (!state->refs)
1540                 return -ENOMEM;
1541
1542         state->acquired_refs = n;
1543         return 0;
1544 }
1545
1546 static int grow_stack_state(struct bpf_func_state *state, int size)
1547 {
1548         size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1549
1550         if (old_n >= n)
1551                 return 0;
1552
1553         state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1554         if (!state->stack)
1555                 return -ENOMEM;
1556
1557         state->allocated_stack = size;
1558         return 0;
1559 }
1560
1561 /* Acquire a pointer id from the env and update the state->refs to include
1562  * this new pointer reference.
1563  * On success, returns a valid pointer id to associate with the register
1564  * On failure, returns a negative errno.
1565  */
1566 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1567 {
1568         struct bpf_func_state *state = cur_func(env);
1569         int new_ofs = state->acquired_refs;
1570         int id, err;
1571
1572         err = resize_reference_state(state, state->acquired_refs + 1);
1573         if (err)
1574                 return err;
1575         id = ++env->id_gen;
1576         state->refs[new_ofs].id = id;
1577         state->refs[new_ofs].insn_idx = insn_idx;
1578         state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1579
1580         return id;
1581 }
1582
1583 /* release function corresponding to acquire_reference_state(). Idempotent. */
1584 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1585 {
1586         int i, last_idx;
1587
1588         last_idx = state->acquired_refs - 1;
1589         for (i = 0; i < state->acquired_refs; i++) {
1590                 if (state->refs[i].id == ptr_id) {
1591                         /* Cannot release caller references in callbacks */
1592                         if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1593                                 return -EINVAL;
1594                         if (last_idx && i != last_idx)
1595                                 memcpy(&state->refs[i], &state->refs[last_idx],
1596                                        sizeof(*state->refs));
1597                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1598                         state->acquired_refs--;
1599                         return 0;
1600                 }
1601         }
1602         return -EINVAL;
1603 }
1604
1605 static void free_func_state(struct bpf_func_state *state)
1606 {
1607         if (!state)
1608                 return;
1609         kfree(state->refs);
1610         kfree(state->stack);
1611         kfree(state);
1612 }
1613
1614 static void clear_jmp_history(struct bpf_verifier_state *state)
1615 {
1616         kfree(state->jmp_history);
1617         state->jmp_history = NULL;
1618         state->jmp_history_cnt = 0;
1619 }
1620
1621 static void free_verifier_state(struct bpf_verifier_state *state,
1622                                 bool free_self)
1623 {
1624         int i;
1625
1626         for (i = 0; i <= state->curframe; i++) {
1627                 free_func_state(state->frame[i]);
1628                 state->frame[i] = NULL;
1629         }
1630         clear_jmp_history(state);
1631         if (free_self)
1632                 kfree(state);
1633 }
1634
1635 /* copy verifier state from src to dst growing dst stack space
1636  * when necessary to accommodate larger src stack
1637  */
1638 static int copy_func_state(struct bpf_func_state *dst,
1639                            const struct bpf_func_state *src)
1640 {
1641         int err;
1642
1643         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1644         err = copy_reference_state(dst, src);
1645         if (err)
1646                 return err;
1647         return copy_stack_state(dst, src);
1648 }
1649
1650 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1651                                const struct bpf_verifier_state *src)
1652 {
1653         struct bpf_func_state *dst;
1654         int i, err;
1655
1656         dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1657                                             src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1658                                             GFP_USER);
1659         if (!dst_state->jmp_history)
1660                 return -ENOMEM;
1661         dst_state->jmp_history_cnt = src->jmp_history_cnt;
1662
1663         /* if dst has more stack frames then src frame, free them */
1664         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1665                 free_func_state(dst_state->frame[i]);
1666                 dst_state->frame[i] = NULL;
1667         }
1668         dst_state->speculative = src->speculative;
1669         dst_state->active_rcu_lock = src->active_rcu_lock;
1670         dst_state->curframe = src->curframe;
1671         dst_state->active_lock.ptr = src->active_lock.ptr;
1672         dst_state->active_lock.id = src->active_lock.id;
1673         dst_state->branches = src->branches;
1674         dst_state->parent = src->parent;
1675         dst_state->first_insn_idx = src->first_insn_idx;
1676         dst_state->last_insn_idx = src->last_insn_idx;
1677         for (i = 0; i <= src->curframe; i++) {
1678                 dst = dst_state->frame[i];
1679                 if (!dst) {
1680                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1681                         if (!dst)
1682                                 return -ENOMEM;
1683                         dst_state->frame[i] = dst;
1684                 }
1685                 err = copy_func_state(dst, src->frame[i]);
1686                 if (err)
1687                         return err;
1688         }
1689         return 0;
1690 }
1691
1692 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1693 {
1694         while (st) {
1695                 u32 br = --st->branches;
1696
1697                 /* WARN_ON(br > 1) technically makes sense here,
1698                  * but see comment in push_stack(), hence:
1699                  */
1700                 WARN_ONCE((int)br < 0,
1701                           "BUG update_branch_counts:branches_to_explore=%d\n",
1702                           br);
1703                 if (br)
1704                         break;
1705                 st = st->parent;
1706         }
1707 }
1708
1709 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1710                      int *insn_idx, bool pop_log)
1711 {
1712         struct bpf_verifier_state *cur = env->cur_state;
1713         struct bpf_verifier_stack_elem *elem, *head = env->head;
1714         int err;
1715
1716         if (env->head == NULL)
1717                 return -ENOENT;
1718
1719         if (cur) {
1720                 err = copy_verifier_state(cur, &head->st);
1721                 if (err)
1722                         return err;
1723         }
1724         if (pop_log)
1725                 bpf_vlog_reset(&env->log, head->log_pos);
1726         if (insn_idx)
1727                 *insn_idx = head->insn_idx;
1728         if (prev_insn_idx)
1729                 *prev_insn_idx = head->prev_insn_idx;
1730         elem = head->next;
1731         free_verifier_state(&head->st, false);
1732         kfree(head);
1733         env->head = elem;
1734         env->stack_size--;
1735         return 0;
1736 }
1737
1738 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1739                                              int insn_idx, int prev_insn_idx,
1740                                              bool speculative)
1741 {
1742         struct bpf_verifier_state *cur = env->cur_state;
1743         struct bpf_verifier_stack_elem *elem;
1744         int err;
1745
1746         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1747         if (!elem)
1748                 goto err;
1749
1750         elem->insn_idx = insn_idx;
1751         elem->prev_insn_idx = prev_insn_idx;
1752         elem->next = env->head;
1753         elem->log_pos = env->log.end_pos;
1754         env->head = elem;
1755         env->stack_size++;
1756         err = copy_verifier_state(&elem->st, cur);
1757         if (err)
1758                 goto err;
1759         elem->st.speculative |= speculative;
1760         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1761                 verbose(env, "The sequence of %d jumps is too complex.\n",
1762                         env->stack_size);
1763                 goto err;
1764         }
1765         if (elem->st.parent) {
1766                 ++elem->st.parent->branches;
1767                 /* WARN_ON(branches > 2) technically makes sense here,
1768                  * but
1769                  * 1. speculative states will bump 'branches' for non-branch
1770                  * instructions
1771                  * 2. is_state_visited() heuristics may decide not to create
1772                  * a new state for a sequence of branches and all such current
1773                  * and cloned states will be pointing to a single parent state
1774                  * which might have large 'branches' count.
1775                  */
1776         }
1777         return &elem->st;
1778 err:
1779         free_verifier_state(env->cur_state, true);
1780         env->cur_state = NULL;
1781         /* pop all elements and return */
1782         while (!pop_stack(env, NULL, NULL, false));
1783         return NULL;
1784 }
1785
1786 #define CALLER_SAVED_REGS 6
1787 static const int caller_saved[CALLER_SAVED_REGS] = {
1788         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1789 };
1790
1791 /* This helper doesn't clear reg->id */
1792 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1793 {
1794         reg->var_off = tnum_const(imm);
1795         reg->smin_value = (s64)imm;
1796         reg->smax_value = (s64)imm;
1797         reg->umin_value = imm;
1798         reg->umax_value = imm;
1799
1800         reg->s32_min_value = (s32)imm;
1801         reg->s32_max_value = (s32)imm;
1802         reg->u32_min_value = (u32)imm;
1803         reg->u32_max_value = (u32)imm;
1804 }
1805
1806 /* Mark the unknown part of a register (variable offset or scalar value) as
1807  * known to have the value @imm.
1808  */
1809 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1810 {
1811         /* Clear off and union(map_ptr, range) */
1812         memset(((u8 *)reg) + sizeof(reg->type), 0,
1813                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1814         reg->id = 0;
1815         reg->ref_obj_id = 0;
1816         ___mark_reg_known(reg, imm);
1817 }
1818
1819 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1820 {
1821         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1822         reg->s32_min_value = (s32)imm;
1823         reg->s32_max_value = (s32)imm;
1824         reg->u32_min_value = (u32)imm;
1825         reg->u32_max_value = (u32)imm;
1826 }
1827
1828 /* Mark the 'variable offset' part of a register as zero.  This should be
1829  * used only on registers holding a pointer type.
1830  */
1831 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1832 {
1833         __mark_reg_known(reg, 0);
1834 }
1835
1836 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1837 {
1838         __mark_reg_known(reg, 0);
1839         reg->type = SCALAR_VALUE;
1840 }
1841
1842 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1843                                 struct bpf_reg_state *regs, u32 regno)
1844 {
1845         if (WARN_ON(regno >= MAX_BPF_REG)) {
1846                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1847                 /* Something bad happened, let's kill all regs */
1848                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1849                         __mark_reg_not_init(env, regs + regno);
1850                 return;
1851         }
1852         __mark_reg_known_zero(regs + regno);
1853 }
1854
1855 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1856                               bool first_slot, int dynptr_id)
1857 {
1858         /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1859          * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1860          * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1861          */
1862         __mark_reg_known_zero(reg);
1863         reg->type = CONST_PTR_TO_DYNPTR;
1864         /* Give each dynptr a unique id to uniquely associate slices to it. */
1865         reg->id = dynptr_id;
1866         reg->dynptr.type = type;
1867         reg->dynptr.first_slot = first_slot;
1868 }
1869
1870 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1871 {
1872         if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1873                 const struct bpf_map *map = reg->map_ptr;
1874
1875                 if (map->inner_map_meta) {
1876                         reg->type = CONST_PTR_TO_MAP;
1877                         reg->map_ptr = map->inner_map_meta;
1878                         /* transfer reg's id which is unique for every map_lookup_elem
1879                          * as UID of the inner map.
1880                          */
1881                         if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1882                                 reg->map_uid = reg->id;
1883                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1884                         reg->type = PTR_TO_XDP_SOCK;
1885                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1886                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1887                         reg->type = PTR_TO_SOCKET;
1888                 } else {
1889                         reg->type = PTR_TO_MAP_VALUE;
1890                 }
1891                 return;
1892         }
1893
1894         reg->type &= ~PTR_MAYBE_NULL;
1895 }
1896
1897 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1898                                 struct btf_field_graph_root *ds_head)
1899 {
1900         __mark_reg_known_zero(&regs[regno]);
1901         regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1902         regs[regno].btf = ds_head->btf;
1903         regs[regno].btf_id = ds_head->value_btf_id;
1904         regs[regno].off = ds_head->node_offset;
1905 }
1906
1907 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1908 {
1909         return type_is_pkt_pointer(reg->type);
1910 }
1911
1912 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1913 {
1914         return reg_is_pkt_pointer(reg) ||
1915                reg->type == PTR_TO_PACKET_END;
1916 }
1917
1918 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
1919 {
1920         return base_type(reg->type) == PTR_TO_MEM &&
1921                 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
1922 }
1923
1924 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1925 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1926                                     enum bpf_reg_type which)
1927 {
1928         /* The register can already have a range from prior markings.
1929          * This is fine as long as it hasn't been advanced from its
1930          * origin.
1931          */
1932         return reg->type == which &&
1933                reg->id == 0 &&
1934                reg->off == 0 &&
1935                tnum_equals_const(reg->var_off, 0);
1936 }
1937
1938 /* Reset the min/max bounds of a register */
1939 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1940 {
1941         reg->smin_value = S64_MIN;
1942         reg->smax_value = S64_MAX;
1943         reg->umin_value = 0;
1944         reg->umax_value = U64_MAX;
1945
1946         reg->s32_min_value = S32_MIN;
1947         reg->s32_max_value = S32_MAX;
1948         reg->u32_min_value = 0;
1949         reg->u32_max_value = U32_MAX;
1950 }
1951
1952 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1953 {
1954         reg->smin_value = S64_MIN;
1955         reg->smax_value = S64_MAX;
1956         reg->umin_value = 0;
1957         reg->umax_value = U64_MAX;
1958 }
1959
1960 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1961 {
1962         reg->s32_min_value = S32_MIN;
1963         reg->s32_max_value = S32_MAX;
1964         reg->u32_min_value = 0;
1965         reg->u32_max_value = U32_MAX;
1966 }
1967
1968 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1969 {
1970         struct tnum var32_off = tnum_subreg(reg->var_off);
1971
1972         /* min signed is max(sign bit) | min(other bits) */
1973         reg->s32_min_value = max_t(s32, reg->s32_min_value,
1974                         var32_off.value | (var32_off.mask & S32_MIN));
1975         /* max signed is min(sign bit) | max(other bits) */
1976         reg->s32_max_value = min_t(s32, reg->s32_max_value,
1977                         var32_off.value | (var32_off.mask & S32_MAX));
1978         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1979         reg->u32_max_value = min(reg->u32_max_value,
1980                                  (u32)(var32_off.value | var32_off.mask));
1981 }
1982
1983 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1984 {
1985         /* min signed is max(sign bit) | min(other bits) */
1986         reg->smin_value = max_t(s64, reg->smin_value,
1987                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1988         /* max signed is min(sign bit) | max(other bits) */
1989         reg->smax_value = min_t(s64, reg->smax_value,
1990                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1991         reg->umin_value = max(reg->umin_value, reg->var_off.value);
1992         reg->umax_value = min(reg->umax_value,
1993                               reg->var_off.value | reg->var_off.mask);
1994 }
1995
1996 static void __update_reg_bounds(struct bpf_reg_state *reg)
1997 {
1998         __update_reg32_bounds(reg);
1999         __update_reg64_bounds(reg);
2000 }
2001
2002 /* Uses signed min/max values to inform unsigned, and vice-versa */
2003 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2004 {
2005         /* Learn sign from signed bounds.
2006          * If we cannot cross the sign boundary, then signed and unsigned bounds
2007          * are the same, so combine.  This works even in the negative case, e.g.
2008          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2009          */
2010         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2011                 reg->s32_min_value = reg->u32_min_value =
2012                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
2013                 reg->s32_max_value = reg->u32_max_value =
2014                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
2015                 return;
2016         }
2017         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
2018          * boundary, so we must be careful.
2019          */
2020         if ((s32)reg->u32_max_value >= 0) {
2021                 /* Positive.  We can't learn anything from the smin, but smax
2022                  * is positive, hence safe.
2023                  */
2024                 reg->s32_min_value = reg->u32_min_value;
2025                 reg->s32_max_value = reg->u32_max_value =
2026                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
2027         } else if ((s32)reg->u32_min_value < 0) {
2028                 /* Negative.  We can't learn anything from the smax, but smin
2029                  * is negative, hence safe.
2030                  */
2031                 reg->s32_min_value = reg->u32_min_value =
2032                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
2033                 reg->s32_max_value = reg->u32_max_value;
2034         }
2035 }
2036
2037 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2038 {
2039         /* Learn sign from signed bounds.
2040          * If we cannot cross the sign boundary, then signed and unsigned bounds
2041          * are the same, so combine.  This works even in the negative case, e.g.
2042          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2043          */
2044         if (reg->smin_value >= 0 || reg->smax_value < 0) {
2045                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2046                                                           reg->umin_value);
2047                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2048                                                           reg->umax_value);
2049                 return;
2050         }
2051         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
2052          * boundary, so we must be careful.
2053          */
2054         if ((s64)reg->umax_value >= 0) {
2055                 /* Positive.  We can't learn anything from the smin, but smax
2056                  * is positive, hence safe.
2057                  */
2058                 reg->smin_value = reg->umin_value;
2059                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2060                                                           reg->umax_value);
2061         } else if ((s64)reg->umin_value < 0) {
2062                 /* Negative.  We can't learn anything from the smax, but smin
2063                  * is negative, hence safe.
2064                  */
2065                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2066                                                           reg->umin_value);
2067                 reg->smax_value = reg->umax_value;
2068         }
2069 }
2070
2071 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2072 {
2073         __reg32_deduce_bounds(reg);
2074         __reg64_deduce_bounds(reg);
2075 }
2076
2077 /* Attempts to improve var_off based on unsigned min/max information */
2078 static void __reg_bound_offset(struct bpf_reg_state *reg)
2079 {
2080         struct tnum var64_off = tnum_intersect(reg->var_off,
2081                                                tnum_range(reg->umin_value,
2082                                                           reg->umax_value));
2083         struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2084                                                tnum_range(reg->u32_min_value,
2085                                                           reg->u32_max_value));
2086
2087         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2088 }
2089
2090 static void reg_bounds_sync(struct bpf_reg_state *reg)
2091 {
2092         /* We might have learned new bounds from the var_off. */
2093         __update_reg_bounds(reg);
2094         /* We might have learned something about the sign bit. */
2095         __reg_deduce_bounds(reg);
2096         /* We might have learned some bits from the bounds. */
2097         __reg_bound_offset(reg);
2098         /* Intersecting with the old var_off might have improved our bounds
2099          * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2100          * then new var_off is (0; 0x7f...fc) which improves our umax.
2101          */
2102         __update_reg_bounds(reg);
2103 }
2104
2105 static bool __reg32_bound_s64(s32 a)
2106 {
2107         return a >= 0 && a <= S32_MAX;
2108 }
2109
2110 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2111 {
2112         reg->umin_value = reg->u32_min_value;
2113         reg->umax_value = reg->u32_max_value;
2114
2115         /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2116          * be positive otherwise set to worse case bounds and refine later
2117          * from tnum.
2118          */
2119         if (__reg32_bound_s64(reg->s32_min_value) &&
2120             __reg32_bound_s64(reg->s32_max_value)) {
2121                 reg->smin_value = reg->s32_min_value;
2122                 reg->smax_value = reg->s32_max_value;
2123         } else {
2124                 reg->smin_value = 0;
2125                 reg->smax_value = U32_MAX;
2126         }
2127 }
2128
2129 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2130 {
2131         /* special case when 64-bit register has upper 32-bit register
2132          * zeroed. Typically happens after zext or <<32, >>32 sequence
2133          * allowing us to use 32-bit bounds directly,
2134          */
2135         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2136                 __reg_assign_32_into_64(reg);
2137         } else {
2138                 /* Otherwise the best we can do is push lower 32bit known and
2139                  * unknown bits into register (var_off set from jmp logic)
2140                  * then learn as much as possible from the 64-bit tnum
2141                  * known and unknown bits. The previous smin/smax bounds are
2142                  * invalid here because of jmp32 compare so mark them unknown
2143                  * so they do not impact tnum bounds calculation.
2144                  */
2145                 __mark_reg64_unbounded(reg);
2146         }
2147         reg_bounds_sync(reg);
2148 }
2149
2150 static bool __reg64_bound_s32(s64 a)
2151 {
2152         return a >= S32_MIN && a <= S32_MAX;
2153 }
2154
2155 static bool __reg64_bound_u32(u64 a)
2156 {
2157         return a >= U32_MIN && a <= U32_MAX;
2158 }
2159
2160 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2161 {
2162         __mark_reg32_unbounded(reg);
2163         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2164                 reg->s32_min_value = (s32)reg->smin_value;
2165                 reg->s32_max_value = (s32)reg->smax_value;
2166         }
2167         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2168                 reg->u32_min_value = (u32)reg->umin_value;
2169                 reg->u32_max_value = (u32)reg->umax_value;
2170         }
2171         reg_bounds_sync(reg);
2172 }
2173
2174 /* Mark a register as having a completely unknown (scalar) value. */
2175 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2176                                struct bpf_reg_state *reg)
2177 {
2178         /*
2179          * Clear type, off, and union(map_ptr, range) and
2180          * padding between 'type' and union
2181          */
2182         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2183         reg->type = SCALAR_VALUE;
2184         reg->id = 0;
2185         reg->ref_obj_id = 0;
2186         reg->var_off = tnum_unknown;
2187         reg->frameno = 0;
2188         reg->precise = !env->bpf_capable;
2189         __mark_reg_unbounded(reg);
2190 }
2191
2192 static void mark_reg_unknown(struct bpf_verifier_env *env,
2193                              struct bpf_reg_state *regs, u32 regno)
2194 {
2195         if (WARN_ON(regno >= MAX_BPF_REG)) {
2196                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2197                 /* Something bad happened, let's kill all regs except FP */
2198                 for (regno = 0; regno < BPF_REG_FP; regno++)
2199                         __mark_reg_not_init(env, regs + regno);
2200                 return;
2201         }
2202         __mark_reg_unknown(env, regs + regno);
2203 }
2204
2205 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2206                                 struct bpf_reg_state *reg)
2207 {
2208         __mark_reg_unknown(env, reg);
2209         reg->type = NOT_INIT;
2210 }
2211
2212 static void mark_reg_not_init(struct bpf_verifier_env *env,
2213                               struct bpf_reg_state *regs, u32 regno)
2214 {
2215         if (WARN_ON(regno >= MAX_BPF_REG)) {
2216                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2217                 /* Something bad happened, let's kill all regs except FP */
2218                 for (regno = 0; regno < BPF_REG_FP; regno++)
2219                         __mark_reg_not_init(env, regs + regno);
2220                 return;
2221         }
2222         __mark_reg_not_init(env, regs + regno);
2223 }
2224
2225 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2226                             struct bpf_reg_state *regs, u32 regno,
2227                             enum bpf_reg_type reg_type,
2228                             struct btf *btf, u32 btf_id,
2229                             enum bpf_type_flag flag)
2230 {
2231         if (reg_type == SCALAR_VALUE) {
2232                 mark_reg_unknown(env, regs, regno);
2233                 return;
2234         }
2235         mark_reg_known_zero(env, regs, regno);
2236         regs[regno].type = PTR_TO_BTF_ID | flag;
2237         regs[regno].btf = btf;
2238         regs[regno].btf_id = btf_id;
2239 }
2240
2241 #define DEF_NOT_SUBREG  (0)
2242 static void init_reg_state(struct bpf_verifier_env *env,
2243                            struct bpf_func_state *state)
2244 {
2245         struct bpf_reg_state *regs = state->regs;
2246         int i;
2247
2248         for (i = 0; i < MAX_BPF_REG; i++) {
2249                 mark_reg_not_init(env, regs, i);
2250                 regs[i].live = REG_LIVE_NONE;
2251                 regs[i].parent = NULL;
2252                 regs[i].subreg_def = DEF_NOT_SUBREG;
2253         }
2254
2255         /* frame pointer */
2256         regs[BPF_REG_FP].type = PTR_TO_STACK;
2257         mark_reg_known_zero(env, regs, BPF_REG_FP);
2258         regs[BPF_REG_FP].frameno = state->frameno;
2259 }
2260
2261 #define BPF_MAIN_FUNC (-1)
2262 static void init_func_state(struct bpf_verifier_env *env,
2263                             struct bpf_func_state *state,
2264                             int callsite, int frameno, int subprogno)
2265 {
2266         state->callsite = callsite;
2267         state->frameno = frameno;
2268         state->subprogno = subprogno;
2269         state->callback_ret_range = tnum_range(0, 0);
2270         init_reg_state(env, state);
2271         mark_verifier_state_scratched(env);
2272 }
2273
2274 /* Similar to push_stack(), but for async callbacks */
2275 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2276                                                 int insn_idx, int prev_insn_idx,
2277                                                 int subprog)
2278 {
2279         struct bpf_verifier_stack_elem *elem;
2280         struct bpf_func_state *frame;
2281
2282         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2283         if (!elem)
2284                 goto err;
2285
2286         elem->insn_idx = insn_idx;
2287         elem->prev_insn_idx = prev_insn_idx;
2288         elem->next = env->head;
2289         elem->log_pos = env->log.end_pos;
2290         env->head = elem;
2291         env->stack_size++;
2292         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2293                 verbose(env,
2294                         "The sequence of %d jumps is too complex for async cb.\n",
2295                         env->stack_size);
2296                 goto err;
2297         }
2298         /* Unlike push_stack() do not copy_verifier_state().
2299          * The caller state doesn't matter.
2300          * This is async callback. It starts in a fresh stack.
2301          * Initialize it similar to do_check_common().
2302          */
2303         elem->st.branches = 1;
2304         frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2305         if (!frame)
2306                 goto err;
2307         init_func_state(env, frame,
2308                         BPF_MAIN_FUNC /* callsite */,
2309                         0 /* frameno within this callchain */,
2310                         subprog /* subprog number within this prog */);
2311         elem->st.frame[0] = frame;
2312         return &elem->st;
2313 err:
2314         free_verifier_state(env->cur_state, true);
2315         env->cur_state = NULL;
2316         /* pop all elements and return */
2317         while (!pop_stack(env, NULL, NULL, false));
2318         return NULL;
2319 }
2320
2321
2322 enum reg_arg_type {
2323         SRC_OP,         /* register is used as source operand */
2324         DST_OP,         /* register is used as destination operand */
2325         DST_OP_NO_MARK  /* same as above, check only, don't mark */
2326 };
2327
2328 static int cmp_subprogs(const void *a, const void *b)
2329 {
2330         return ((struct bpf_subprog_info *)a)->start -
2331                ((struct bpf_subprog_info *)b)->start;
2332 }
2333
2334 static int find_subprog(struct bpf_verifier_env *env, int off)
2335 {
2336         struct bpf_subprog_info *p;
2337
2338         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2339                     sizeof(env->subprog_info[0]), cmp_subprogs);
2340         if (!p)
2341                 return -ENOENT;
2342         return p - env->subprog_info;
2343
2344 }
2345
2346 static int add_subprog(struct bpf_verifier_env *env, int off)
2347 {
2348         int insn_cnt = env->prog->len;
2349         int ret;
2350
2351         if (off >= insn_cnt || off < 0) {
2352                 verbose(env, "call to invalid destination\n");
2353                 return -EINVAL;
2354         }
2355         ret = find_subprog(env, off);
2356         if (ret >= 0)
2357                 return ret;
2358         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2359                 verbose(env, "too many subprograms\n");
2360                 return -E2BIG;
2361         }
2362         /* determine subprog starts. The end is one before the next starts */
2363         env->subprog_info[env->subprog_cnt++].start = off;
2364         sort(env->subprog_info, env->subprog_cnt,
2365              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2366         return env->subprog_cnt - 1;
2367 }
2368
2369 #define MAX_KFUNC_DESCS 256
2370 #define MAX_KFUNC_BTFS  256
2371
2372 struct bpf_kfunc_desc {
2373         struct btf_func_model func_model;
2374         u32 func_id;
2375         s32 imm;
2376         u16 offset;
2377 };
2378
2379 struct bpf_kfunc_btf {
2380         struct btf *btf;
2381         struct module *module;
2382         u16 offset;
2383 };
2384
2385 struct bpf_kfunc_desc_tab {
2386         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2387         u32 nr_descs;
2388 };
2389
2390 struct bpf_kfunc_btf_tab {
2391         struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2392         u32 nr_descs;
2393 };
2394
2395 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2396 {
2397         const struct bpf_kfunc_desc *d0 = a;
2398         const struct bpf_kfunc_desc *d1 = b;
2399
2400         /* func_id is not greater than BTF_MAX_TYPE */
2401         return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2402 }
2403
2404 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2405 {
2406         const struct bpf_kfunc_btf *d0 = a;
2407         const struct bpf_kfunc_btf *d1 = b;
2408
2409         return d0->offset - d1->offset;
2410 }
2411
2412 static const struct bpf_kfunc_desc *
2413 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2414 {
2415         struct bpf_kfunc_desc desc = {
2416                 .func_id = func_id,
2417                 .offset = offset,
2418         };
2419         struct bpf_kfunc_desc_tab *tab;
2420
2421         tab = prog->aux->kfunc_tab;
2422         return bsearch(&desc, tab->descs, tab->nr_descs,
2423                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2424 }
2425
2426 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2427                                          s16 offset)
2428 {
2429         struct bpf_kfunc_btf kf_btf = { .offset = offset };
2430         struct bpf_kfunc_btf_tab *tab;
2431         struct bpf_kfunc_btf *b;
2432         struct module *mod;
2433         struct btf *btf;
2434         int btf_fd;
2435
2436         tab = env->prog->aux->kfunc_btf_tab;
2437         b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2438                     sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2439         if (!b) {
2440                 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2441                         verbose(env, "too many different module BTFs\n");
2442                         return ERR_PTR(-E2BIG);
2443                 }
2444
2445                 if (bpfptr_is_null(env->fd_array)) {
2446                         verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2447                         return ERR_PTR(-EPROTO);
2448                 }
2449
2450                 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2451                                             offset * sizeof(btf_fd),
2452                                             sizeof(btf_fd)))
2453                         return ERR_PTR(-EFAULT);
2454
2455                 btf = btf_get_by_fd(btf_fd);
2456                 if (IS_ERR(btf)) {
2457                         verbose(env, "invalid module BTF fd specified\n");
2458                         return btf;
2459                 }
2460
2461                 if (!btf_is_module(btf)) {
2462                         verbose(env, "BTF fd for kfunc is not a module BTF\n");
2463                         btf_put(btf);
2464                         return ERR_PTR(-EINVAL);
2465                 }
2466
2467                 mod = btf_try_get_module(btf);
2468                 if (!mod) {
2469                         btf_put(btf);
2470                         return ERR_PTR(-ENXIO);
2471                 }
2472
2473                 b = &tab->descs[tab->nr_descs++];
2474                 b->btf = btf;
2475                 b->module = mod;
2476                 b->offset = offset;
2477
2478                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2479                      kfunc_btf_cmp_by_off, NULL);
2480         }
2481         return b->btf;
2482 }
2483
2484 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2485 {
2486         if (!tab)
2487                 return;
2488
2489         while (tab->nr_descs--) {
2490                 module_put(tab->descs[tab->nr_descs].module);
2491                 btf_put(tab->descs[tab->nr_descs].btf);
2492         }
2493         kfree(tab);
2494 }
2495
2496 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2497 {
2498         if (offset) {
2499                 if (offset < 0) {
2500                         /* In the future, this can be allowed to increase limit
2501                          * of fd index into fd_array, interpreted as u16.
2502                          */
2503                         verbose(env, "negative offset disallowed for kernel module function call\n");
2504                         return ERR_PTR(-EINVAL);
2505                 }
2506
2507                 return __find_kfunc_desc_btf(env, offset);
2508         }
2509         return btf_vmlinux ?: ERR_PTR(-ENOENT);
2510 }
2511
2512 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2513 {
2514         const struct btf_type *func, *func_proto;
2515         struct bpf_kfunc_btf_tab *btf_tab;
2516         struct bpf_kfunc_desc_tab *tab;
2517         struct bpf_prog_aux *prog_aux;
2518         struct bpf_kfunc_desc *desc;
2519         const char *func_name;
2520         struct btf *desc_btf;
2521         unsigned long call_imm;
2522         unsigned long addr;
2523         int err;
2524
2525         prog_aux = env->prog->aux;
2526         tab = prog_aux->kfunc_tab;
2527         btf_tab = prog_aux->kfunc_btf_tab;
2528         if (!tab) {
2529                 if (!btf_vmlinux) {
2530                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2531                         return -ENOTSUPP;
2532                 }
2533
2534                 if (!env->prog->jit_requested) {
2535                         verbose(env, "JIT is required for calling kernel function\n");
2536                         return -ENOTSUPP;
2537                 }
2538
2539                 if (!bpf_jit_supports_kfunc_call()) {
2540                         verbose(env, "JIT does not support calling kernel function\n");
2541                         return -ENOTSUPP;
2542                 }
2543
2544                 if (!env->prog->gpl_compatible) {
2545                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2546                         return -EINVAL;
2547                 }
2548
2549                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2550                 if (!tab)
2551                         return -ENOMEM;
2552                 prog_aux->kfunc_tab = tab;
2553         }
2554
2555         /* func_id == 0 is always invalid, but instead of returning an error, be
2556          * conservative and wait until the code elimination pass before returning
2557          * error, so that invalid calls that get pruned out can be in BPF programs
2558          * loaded from userspace.  It is also required that offset be untouched
2559          * for such calls.
2560          */
2561         if (!func_id && !offset)
2562                 return 0;
2563
2564         if (!btf_tab && offset) {
2565                 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2566                 if (!btf_tab)
2567                         return -ENOMEM;
2568                 prog_aux->kfunc_btf_tab = btf_tab;
2569         }
2570
2571         desc_btf = find_kfunc_desc_btf(env, offset);
2572         if (IS_ERR(desc_btf)) {
2573                 verbose(env, "failed to find BTF for kernel function\n");
2574                 return PTR_ERR(desc_btf);
2575         }
2576
2577         if (find_kfunc_desc(env->prog, func_id, offset))
2578                 return 0;
2579
2580         if (tab->nr_descs == MAX_KFUNC_DESCS) {
2581                 verbose(env, "too many different kernel function calls\n");
2582                 return -E2BIG;
2583         }
2584
2585         func = btf_type_by_id(desc_btf, func_id);
2586         if (!func || !btf_type_is_func(func)) {
2587                 verbose(env, "kernel btf_id %u is not a function\n",
2588                         func_id);
2589                 return -EINVAL;
2590         }
2591         func_proto = btf_type_by_id(desc_btf, func->type);
2592         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2593                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2594                         func_id);
2595                 return -EINVAL;
2596         }
2597
2598         func_name = btf_name_by_offset(desc_btf, func->name_off);
2599         addr = kallsyms_lookup_name(func_name);
2600         if (!addr) {
2601                 verbose(env, "cannot find address for kernel function %s\n",
2602                         func_name);
2603                 return -EINVAL;
2604         }
2605
2606         call_imm = BPF_CALL_IMM(addr);
2607         /* Check whether or not the relative offset overflows desc->imm */
2608         if ((unsigned long)(s32)call_imm != call_imm) {
2609                 verbose(env, "address of kernel function %s is out of range\n",
2610                         func_name);
2611                 return -EINVAL;
2612         }
2613
2614         if (bpf_dev_bound_kfunc_id(func_id)) {
2615                 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2616                 if (err)
2617                         return err;
2618         }
2619
2620         desc = &tab->descs[tab->nr_descs++];
2621         desc->func_id = func_id;
2622         desc->imm = call_imm;
2623         desc->offset = offset;
2624         err = btf_distill_func_proto(&env->log, desc_btf,
2625                                      func_proto, func_name,
2626                                      &desc->func_model);
2627         if (!err)
2628                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2629                      kfunc_desc_cmp_by_id_off, NULL);
2630         return err;
2631 }
2632
2633 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2634 {
2635         const struct bpf_kfunc_desc *d0 = a;
2636         const struct bpf_kfunc_desc *d1 = b;
2637
2638         if (d0->imm > d1->imm)
2639                 return 1;
2640         else if (d0->imm < d1->imm)
2641                 return -1;
2642         return 0;
2643 }
2644
2645 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2646 {
2647         struct bpf_kfunc_desc_tab *tab;
2648
2649         tab = prog->aux->kfunc_tab;
2650         if (!tab)
2651                 return;
2652
2653         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2654              kfunc_desc_cmp_by_imm, NULL);
2655 }
2656
2657 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2658 {
2659         return !!prog->aux->kfunc_tab;
2660 }
2661
2662 const struct btf_func_model *
2663 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2664                          const struct bpf_insn *insn)
2665 {
2666         const struct bpf_kfunc_desc desc = {
2667                 .imm = insn->imm,
2668         };
2669         const struct bpf_kfunc_desc *res;
2670         struct bpf_kfunc_desc_tab *tab;
2671
2672         tab = prog->aux->kfunc_tab;
2673         res = bsearch(&desc, tab->descs, tab->nr_descs,
2674                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2675
2676         return res ? &res->func_model : NULL;
2677 }
2678
2679 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2680 {
2681         struct bpf_subprog_info *subprog = env->subprog_info;
2682         struct bpf_insn *insn = env->prog->insnsi;
2683         int i, ret, insn_cnt = env->prog->len;
2684
2685         /* Add entry function. */
2686         ret = add_subprog(env, 0);
2687         if (ret)
2688                 return ret;
2689
2690         for (i = 0; i < insn_cnt; i++, insn++) {
2691                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2692                     !bpf_pseudo_kfunc_call(insn))
2693                         continue;
2694
2695                 if (!env->bpf_capable) {
2696                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2697                         return -EPERM;
2698                 }
2699
2700                 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2701                         ret = add_subprog(env, i + insn->imm + 1);
2702                 else
2703                         ret = add_kfunc_call(env, insn->imm, insn->off);
2704
2705                 if (ret < 0)
2706                         return ret;
2707         }
2708
2709         /* Add a fake 'exit' subprog which could simplify subprog iteration
2710          * logic. 'subprog_cnt' should not be increased.
2711          */
2712         subprog[env->subprog_cnt].start = insn_cnt;
2713
2714         if (env->log.level & BPF_LOG_LEVEL2)
2715                 for (i = 0; i < env->subprog_cnt; i++)
2716                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
2717
2718         return 0;
2719 }
2720
2721 static int check_subprogs(struct bpf_verifier_env *env)
2722 {
2723         int i, subprog_start, subprog_end, off, cur_subprog = 0;
2724         struct bpf_subprog_info *subprog = env->subprog_info;
2725         struct bpf_insn *insn = env->prog->insnsi;
2726         int insn_cnt = env->prog->len;
2727
2728         /* now check that all jumps are within the same subprog */
2729         subprog_start = subprog[cur_subprog].start;
2730         subprog_end = subprog[cur_subprog + 1].start;
2731         for (i = 0; i < insn_cnt; i++) {
2732                 u8 code = insn[i].code;
2733
2734                 if (code == (BPF_JMP | BPF_CALL) &&
2735                     insn[i].src_reg == 0 &&
2736                     insn[i].imm == BPF_FUNC_tail_call)
2737                         subprog[cur_subprog].has_tail_call = true;
2738                 if (BPF_CLASS(code) == BPF_LD &&
2739                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2740                         subprog[cur_subprog].has_ld_abs = true;
2741                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2742                         goto next;
2743                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2744                         goto next;
2745                 off = i + insn[i].off + 1;
2746                 if (off < subprog_start || off >= subprog_end) {
2747                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
2748                         return -EINVAL;
2749                 }
2750 next:
2751                 if (i == subprog_end - 1) {
2752                         /* to avoid fall-through from one subprog into another
2753                          * the last insn of the subprog should be either exit
2754                          * or unconditional jump back
2755                          */
2756                         if (code != (BPF_JMP | BPF_EXIT) &&
2757                             code != (BPF_JMP | BPF_JA)) {
2758                                 verbose(env, "last insn is not an exit or jmp\n");
2759                                 return -EINVAL;
2760                         }
2761                         subprog_start = subprog_end;
2762                         cur_subprog++;
2763                         if (cur_subprog < env->subprog_cnt)
2764                                 subprog_end = subprog[cur_subprog + 1].start;
2765                 }
2766         }
2767         return 0;
2768 }
2769
2770 /* Parentage chain of this register (or stack slot) should take care of all
2771  * issues like callee-saved registers, stack slot allocation time, etc.
2772  */
2773 static int mark_reg_read(struct bpf_verifier_env *env,
2774                          const struct bpf_reg_state *state,
2775                          struct bpf_reg_state *parent, u8 flag)
2776 {
2777         bool writes = parent == state->parent; /* Observe write marks */
2778         int cnt = 0;
2779
2780         while (parent) {
2781                 /* if read wasn't screened by an earlier write ... */
2782                 if (writes && state->live & REG_LIVE_WRITTEN)
2783                         break;
2784                 if (parent->live & REG_LIVE_DONE) {
2785                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2786                                 reg_type_str(env, parent->type),
2787                                 parent->var_off.value, parent->off);
2788                         return -EFAULT;
2789                 }
2790                 /* The first condition is more likely to be true than the
2791                  * second, checked it first.
2792                  */
2793                 if ((parent->live & REG_LIVE_READ) == flag ||
2794                     parent->live & REG_LIVE_READ64)
2795                         /* The parentage chain never changes and
2796                          * this parent was already marked as LIVE_READ.
2797                          * There is no need to keep walking the chain again and
2798                          * keep re-marking all parents as LIVE_READ.
2799                          * This case happens when the same register is read
2800                          * multiple times without writes into it in-between.
2801                          * Also, if parent has the stronger REG_LIVE_READ64 set,
2802                          * then no need to set the weak REG_LIVE_READ32.
2803                          */
2804                         break;
2805                 /* ... then we depend on parent's value */
2806                 parent->live |= flag;
2807                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2808                 if (flag == REG_LIVE_READ64)
2809                         parent->live &= ~REG_LIVE_READ32;
2810                 state = parent;
2811                 parent = state->parent;
2812                 writes = true;
2813                 cnt++;
2814         }
2815
2816         if (env->longest_mark_read_walk < cnt)
2817                 env->longest_mark_read_walk = cnt;
2818         return 0;
2819 }
2820
2821 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2822 {
2823         struct bpf_func_state *state = func(env, reg);
2824         int spi, ret;
2825
2826         /* For CONST_PTR_TO_DYNPTR, it must have already been done by
2827          * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2828          * check_kfunc_call.
2829          */
2830         if (reg->type == CONST_PTR_TO_DYNPTR)
2831                 return 0;
2832         spi = dynptr_get_spi(env, reg);
2833         if (spi < 0)
2834                 return spi;
2835         /* Caller ensures dynptr is valid and initialized, which means spi is in
2836          * bounds and spi is the first dynptr slot. Simply mark stack slot as
2837          * read.
2838          */
2839         ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2840                             state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2841         if (ret)
2842                 return ret;
2843         return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2844                              state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2845 }
2846
2847 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
2848                           int spi, int nr_slots)
2849 {
2850         struct bpf_func_state *state = func(env, reg);
2851         int err, i;
2852
2853         for (i = 0; i < nr_slots; i++) {
2854                 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
2855
2856                 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
2857                 if (err)
2858                         return err;
2859
2860                 mark_stack_slot_scratched(env, spi - i);
2861         }
2862
2863         return 0;
2864 }
2865
2866 /* This function is supposed to be used by the following 32-bit optimization
2867  * code only. It returns TRUE if the source or destination register operates
2868  * on 64-bit, otherwise return FALSE.
2869  */
2870 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2871                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2872 {
2873         u8 code, class, op;
2874
2875         code = insn->code;
2876         class = BPF_CLASS(code);
2877         op = BPF_OP(code);
2878         if (class == BPF_JMP) {
2879                 /* BPF_EXIT for "main" will reach here. Return TRUE
2880                  * conservatively.
2881                  */
2882                 if (op == BPF_EXIT)
2883                         return true;
2884                 if (op == BPF_CALL) {
2885                         /* BPF to BPF call will reach here because of marking
2886                          * caller saved clobber with DST_OP_NO_MARK for which we
2887                          * don't care the register def because they are anyway
2888                          * marked as NOT_INIT already.
2889                          */
2890                         if (insn->src_reg == BPF_PSEUDO_CALL)
2891                                 return false;
2892                         /* Helper call will reach here because of arg type
2893                          * check, conservatively return TRUE.
2894                          */
2895                         if (t == SRC_OP)
2896                                 return true;
2897
2898                         return false;
2899                 }
2900         }
2901
2902         if (class == BPF_ALU64 || class == BPF_JMP ||
2903             /* BPF_END always use BPF_ALU class. */
2904             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2905                 return true;
2906
2907         if (class == BPF_ALU || class == BPF_JMP32)
2908                 return false;
2909
2910         if (class == BPF_LDX) {
2911                 if (t != SRC_OP)
2912                         return BPF_SIZE(code) == BPF_DW;
2913                 /* LDX source must be ptr. */
2914                 return true;
2915         }
2916
2917         if (class == BPF_STX) {
2918                 /* BPF_STX (including atomic variants) has multiple source
2919                  * operands, one of which is a ptr. Check whether the caller is
2920                  * asking about it.
2921                  */
2922                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2923                         return true;
2924                 return BPF_SIZE(code) == BPF_DW;
2925         }
2926
2927         if (class == BPF_LD) {
2928                 u8 mode = BPF_MODE(code);
2929
2930                 /* LD_IMM64 */
2931                 if (mode == BPF_IMM)
2932                         return true;
2933
2934                 /* Both LD_IND and LD_ABS return 32-bit data. */
2935                 if (t != SRC_OP)
2936                         return  false;
2937
2938                 /* Implicit ctx ptr. */
2939                 if (regno == BPF_REG_6)
2940                         return true;
2941
2942                 /* Explicit source could be any width. */
2943                 return true;
2944         }
2945
2946         if (class == BPF_ST)
2947                 /* The only source register for BPF_ST is a ptr. */
2948                 return true;
2949
2950         /* Conservatively return true at default. */
2951         return true;
2952 }
2953
2954 /* Return the regno defined by the insn, or -1. */
2955 static int insn_def_regno(const struct bpf_insn *insn)
2956 {
2957         switch (BPF_CLASS(insn->code)) {
2958         case BPF_JMP:
2959         case BPF_JMP32:
2960         case BPF_ST:
2961                 return -1;
2962         case BPF_STX:
2963                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2964                     (insn->imm & BPF_FETCH)) {
2965                         if (insn->imm == BPF_CMPXCHG)
2966                                 return BPF_REG_0;
2967                         else
2968                                 return insn->src_reg;
2969                 } else {
2970                         return -1;
2971                 }
2972         default:
2973                 return insn->dst_reg;
2974         }
2975 }
2976
2977 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2978 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2979 {
2980         int dst_reg = insn_def_regno(insn);
2981
2982         if (dst_reg == -1)
2983                 return false;
2984
2985         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2986 }
2987
2988 static void mark_insn_zext(struct bpf_verifier_env *env,
2989                            struct bpf_reg_state *reg)
2990 {
2991         s32 def_idx = reg->subreg_def;
2992
2993         if (def_idx == DEF_NOT_SUBREG)
2994                 return;
2995
2996         env->insn_aux_data[def_idx - 1].zext_dst = true;
2997         /* The dst will be zero extended, so won't be sub-register anymore. */
2998         reg->subreg_def = DEF_NOT_SUBREG;
2999 }
3000
3001 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3002                          enum reg_arg_type t)
3003 {
3004         struct bpf_verifier_state *vstate = env->cur_state;
3005         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3006         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3007         struct bpf_reg_state *reg, *regs = state->regs;
3008         bool rw64;
3009
3010         if (regno >= MAX_BPF_REG) {
3011                 verbose(env, "R%d is invalid\n", regno);
3012                 return -EINVAL;
3013         }
3014
3015         mark_reg_scratched(env, regno);
3016
3017         reg = &regs[regno];
3018         rw64 = is_reg64(env, insn, regno, reg, t);
3019         if (t == SRC_OP) {
3020                 /* check whether register used as source operand can be read */
3021                 if (reg->type == NOT_INIT) {
3022                         verbose(env, "R%d !read_ok\n", regno);
3023                         return -EACCES;
3024                 }
3025                 /* We don't need to worry about FP liveness because it's read-only */
3026                 if (regno == BPF_REG_FP)
3027                         return 0;
3028
3029                 if (rw64)
3030                         mark_insn_zext(env, reg);
3031
3032                 return mark_reg_read(env, reg, reg->parent,
3033                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3034         } else {
3035                 /* check whether register used as dest operand can be written to */
3036                 if (regno == BPF_REG_FP) {
3037                         verbose(env, "frame pointer is read only\n");
3038                         return -EACCES;
3039                 }
3040                 reg->live |= REG_LIVE_WRITTEN;
3041                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3042                 if (t == DST_OP)
3043                         mark_reg_unknown(env, regs, regno);
3044         }
3045         return 0;
3046 }
3047
3048 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3049 {
3050         env->insn_aux_data[idx].jmp_point = true;
3051 }
3052
3053 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3054 {
3055         return env->insn_aux_data[insn_idx].jmp_point;
3056 }
3057
3058 /* for any branch, call, exit record the history of jmps in the given state */
3059 static int push_jmp_history(struct bpf_verifier_env *env,
3060                             struct bpf_verifier_state *cur)
3061 {
3062         u32 cnt = cur->jmp_history_cnt;
3063         struct bpf_idx_pair *p;
3064         size_t alloc_size;
3065
3066         if (!is_jmp_point(env, env->insn_idx))
3067                 return 0;
3068
3069         cnt++;
3070         alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3071         p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3072         if (!p)
3073                 return -ENOMEM;
3074         p[cnt - 1].idx = env->insn_idx;
3075         p[cnt - 1].prev_idx = env->prev_insn_idx;
3076         cur->jmp_history = p;
3077         cur->jmp_history_cnt = cnt;
3078         return 0;
3079 }
3080
3081 /* Backtrack one insn at a time. If idx is not at the top of recorded
3082  * history then previous instruction came from straight line execution.
3083  */
3084 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3085                              u32 *history)
3086 {
3087         u32 cnt = *history;
3088
3089         if (cnt && st->jmp_history[cnt - 1].idx == i) {
3090                 i = st->jmp_history[cnt - 1].prev_idx;
3091                 (*history)--;
3092         } else {
3093                 i--;
3094         }
3095         return i;
3096 }
3097
3098 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3099 {
3100         const struct btf_type *func;
3101         struct btf *desc_btf;
3102
3103         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3104                 return NULL;
3105
3106         desc_btf = find_kfunc_desc_btf(data, insn->off);
3107         if (IS_ERR(desc_btf))
3108                 return "<error>";
3109
3110         func = btf_type_by_id(desc_btf, insn->imm);
3111         return btf_name_by_offset(desc_btf, func->name_off);
3112 }
3113
3114 /* For given verifier state backtrack_insn() is called from the last insn to
3115  * the first insn. Its purpose is to compute a bitmask of registers and
3116  * stack slots that needs precision in the parent verifier state.
3117  */
3118 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
3119                           u32 *reg_mask, u64 *stack_mask)
3120 {
3121         const struct bpf_insn_cbs cbs = {
3122                 .cb_call        = disasm_kfunc_name,
3123                 .cb_print       = verbose,
3124                 .private_data   = env,
3125         };
3126         struct bpf_insn *insn = env->prog->insnsi + idx;
3127         u8 class = BPF_CLASS(insn->code);
3128         u8 opcode = BPF_OP(insn->code);
3129         u8 mode = BPF_MODE(insn->code);
3130         u32 dreg = 1u << insn->dst_reg;
3131         u32 sreg = 1u << insn->src_reg;
3132         u32 spi;
3133
3134         if (insn->code == 0)
3135                 return 0;
3136         if (env->log.level & BPF_LOG_LEVEL2) {
3137                 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
3138                 verbose(env, "%d: ", idx);
3139                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3140         }
3141
3142         if (class == BPF_ALU || class == BPF_ALU64) {
3143                 if (!(*reg_mask & dreg))
3144                         return 0;
3145                 if (opcode == BPF_MOV) {
3146                         if (BPF_SRC(insn->code) == BPF_X) {
3147                                 /* dreg = sreg
3148                                  * dreg needs precision after this insn
3149                                  * sreg needs precision before this insn
3150                                  */
3151                                 *reg_mask &= ~dreg;
3152                                 *reg_mask |= sreg;
3153                         } else {
3154                                 /* dreg = K
3155                                  * dreg needs precision after this insn.
3156                                  * Corresponding register is already marked
3157                                  * as precise=true in this verifier state.
3158                                  * No further markings in parent are necessary
3159                                  */
3160                                 *reg_mask &= ~dreg;
3161                         }
3162                 } else {
3163                         if (BPF_SRC(insn->code) == BPF_X) {
3164                                 /* dreg += sreg
3165                                  * both dreg and sreg need precision
3166                                  * before this insn
3167                                  */
3168                                 *reg_mask |= sreg;
3169                         } /* else dreg += K
3170                            * dreg still needs precision before this insn
3171                            */
3172                 }
3173         } else if (class == BPF_LDX) {
3174                 if (!(*reg_mask & dreg))
3175                         return 0;
3176                 *reg_mask &= ~dreg;
3177
3178                 /* scalars can only be spilled into stack w/o losing precision.
3179                  * Load from any other memory can be zero extended.
3180                  * The desire to keep that precision is already indicated
3181                  * by 'precise' mark in corresponding register of this state.
3182                  * No further tracking necessary.
3183                  */
3184                 if (insn->src_reg != BPF_REG_FP)
3185                         return 0;
3186
3187                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3188                  * that [fp - off] slot contains scalar that needs to be
3189                  * tracked with precision
3190                  */
3191                 spi = (-insn->off - 1) / BPF_REG_SIZE;
3192                 if (spi >= 64) {
3193                         verbose(env, "BUG spi %d\n", spi);
3194                         WARN_ONCE(1, "verifier backtracking bug");
3195                         return -EFAULT;
3196                 }
3197                 *stack_mask |= 1ull << spi;
3198         } else if (class == BPF_STX || class == BPF_ST) {
3199                 if (*reg_mask & dreg)
3200                         /* stx & st shouldn't be using _scalar_ dst_reg
3201                          * to access memory. It means backtracking
3202                          * encountered a case of pointer subtraction.
3203                          */
3204                         return -ENOTSUPP;
3205                 /* scalars can only be spilled into stack */
3206                 if (insn->dst_reg != BPF_REG_FP)
3207                         return 0;
3208                 spi = (-insn->off - 1) / BPF_REG_SIZE;
3209                 if (spi >= 64) {
3210                         verbose(env, "BUG spi %d\n", spi);
3211                         WARN_ONCE(1, "verifier backtracking bug");
3212                         return -EFAULT;
3213                 }
3214                 if (!(*stack_mask & (1ull << spi)))
3215                         return 0;
3216                 *stack_mask &= ~(1ull << spi);
3217                 if (class == BPF_STX)
3218                         *reg_mask |= sreg;
3219         } else if (class == BPF_JMP || class == BPF_JMP32) {
3220                 if (opcode == BPF_CALL) {
3221                         if (insn->src_reg == BPF_PSEUDO_CALL)
3222                                 return -ENOTSUPP;
3223                         /* BPF helpers that invoke callback subprogs are
3224                          * equivalent to BPF_PSEUDO_CALL above
3225                          */
3226                         if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
3227                                 return -ENOTSUPP;
3228                         /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3229                          * catch this error later. Make backtracking conservative
3230                          * with ENOTSUPP.
3231                          */
3232                         if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3233                                 return -ENOTSUPP;
3234                         /* regular helper call sets R0 */
3235                         *reg_mask &= ~1;
3236                         if (*reg_mask & 0x3f) {
3237                                 /* if backtracing was looking for registers R1-R5
3238                                  * they should have been found already.
3239                                  */
3240                                 verbose(env, "BUG regs %x\n", *reg_mask);
3241                                 WARN_ONCE(1, "verifier backtracking bug");
3242                                 return -EFAULT;
3243                         }
3244                 } else if (opcode == BPF_EXIT) {
3245                         return -ENOTSUPP;
3246                 } else if (BPF_SRC(insn->code) == BPF_X) {
3247                         if (!(*reg_mask & (dreg | sreg)))
3248                                 return 0;
3249                         /* dreg <cond> sreg
3250                          * Both dreg and sreg need precision before
3251                          * this insn. If only sreg was marked precise
3252                          * before it would be equally necessary to
3253                          * propagate it to dreg.
3254                          */
3255                         *reg_mask |= (sreg | dreg);
3256                          /* else dreg <cond> K
3257                           * Only dreg still needs precision before
3258                           * this insn, so for the K-based conditional
3259                           * there is nothing new to be marked.
3260                           */
3261                 }
3262         } else if (class == BPF_LD) {
3263                 if (!(*reg_mask & dreg))
3264                         return 0;
3265                 *reg_mask &= ~dreg;
3266                 /* It's ld_imm64 or ld_abs or ld_ind.
3267                  * For ld_imm64 no further tracking of precision
3268                  * into parent is necessary
3269                  */
3270                 if (mode == BPF_IND || mode == BPF_ABS)
3271                         /* to be analyzed */
3272                         return -ENOTSUPP;
3273         }
3274         return 0;
3275 }
3276
3277 /* the scalar precision tracking algorithm:
3278  * . at the start all registers have precise=false.
3279  * . scalar ranges are tracked as normal through alu and jmp insns.
3280  * . once precise value of the scalar register is used in:
3281  *   .  ptr + scalar alu
3282  *   . if (scalar cond K|scalar)
3283  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3284  *   backtrack through the verifier states and mark all registers and
3285  *   stack slots with spilled constants that these scalar regisers
3286  *   should be precise.
3287  * . during state pruning two registers (or spilled stack slots)
3288  *   are equivalent if both are not precise.
3289  *
3290  * Note the verifier cannot simply walk register parentage chain,
3291  * since many different registers and stack slots could have been
3292  * used to compute single precise scalar.
3293  *
3294  * The approach of starting with precise=true for all registers and then
3295  * backtrack to mark a register as not precise when the verifier detects
3296  * that program doesn't care about specific value (e.g., when helper
3297  * takes register as ARG_ANYTHING parameter) is not safe.
3298  *
3299  * It's ok to walk single parentage chain of the verifier states.
3300  * It's possible that this backtracking will go all the way till 1st insn.
3301  * All other branches will be explored for needing precision later.
3302  *
3303  * The backtracking needs to deal with cases like:
3304  *   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)
3305  * r9 -= r8
3306  * r5 = r9
3307  * if r5 > 0x79f goto pc+7
3308  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3309  * r5 += 1
3310  * ...
3311  * call bpf_perf_event_output#25
3312  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3313  *
3314  * and this case:
3315  * r6 = 1
3316  * call foo // uses callee's r6 inside to compute r0
3317  * r0 += r6
3318  * if r0 == 0 goto
3319  *
3320  * to track above reg_mask/stack_mask needs to be independent for each frame.
3321  *
3322  * Also if parent's curframe > frame where backtracking started,
3323  * the verifier need to mark registers in both frames, otherwise callees
3324  * may incorrectly prune callers. This is similar to
3325  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3326  *
3327  * For now backtracking falls back into conservative marking.
3328  */
3329 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3330                                      struct bpf_verifier_state *st)
3331 {
3332         struct bpf_func_state *func;
3333         struct bpf_reg_state *reg;
3334         int i, j;
3335
3336         /* big hammer: mark all scalars precise in this path.
3337          * pop_stack may still get !precise scalars.
3338          * We also skip current state and go straight to first parent state,
3339          * because precision markings in current non-checkpointed state are
3340          * not needed. See why in the comment in __mark_chain_precision below.
3341          */
3342         for (st = st->parent; st; st = st->parent) {
3343                 for (i = 0; i <= st->curframe; i++) {
3344                         func = st->frame[i];
3345                         for (j = 0; j < BPF_REG_FP; j++) {
3346                                 reg = &func->regs[j];
3347                                 if (reg->type != SCALAR_VALUE)
3348                                         continue;
3349                                 reg->precise = true;
3350                         }
3351                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3352                                 if (!is_spilled_reg(&func->stack[j]))
3353                                         continue;
3354                                 reg = &func->stack[j].spilled_ptr;
3355                                 if (reg->type != SCALAR_VALUE)
3356                                         continue;
3357                                 reg->precise = true;
3358                         }
3359                 }
3360         }
3361 }
3362
3363 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3364 {
3365         struct bpf_func_state *func;
3366         struct bpf_reg_state *reg;
3367         int i, j;
3368
3369         for (i = 0; i <= st->curframe; i++) {
3370                 func = st->frame[i];
3371                 for (j = 0; j < BPF_REG_FP; j++) {
3372                         reg = &func->regs[j];
3373                         if (reg->type != SCALAR_VALUE)
3374                                 continue;
3375                         reg->precise = false;
3376                 }
3377                 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3378                         if (!is_spilled_reg(&func->stack[j]))
3379                                 continue;
3380                         reg = &func->stack[j].spilled_ptr;
3381                         if (reg->type != SCALAR_VALUE)
3382                                 continue;
3383                         reg->precise = false;
3384                 }
3385         }
3386 }
3387
3388 /*
3389  * __mark_chain_precision() backtracks BPF program instruction sequence and
3390  * chain of verifier states making sure that register *regno* (if regno >= 0)
3391  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3392  * SCALARS, as well as any other registers and slots that contribute to
3393  * a tracked state of given registers/stack slots, depending on specific BPF
3394  * assembly instructions (see backtrack_insns() for exact instruction handling
3395  * logic). This backtracking relies on recorded jmp_history and is able to
3396  * traverse entire chain of parent states. This process ends only when all the
3397  * necessary registers/slots and their transitive dependencies are marked as
3398  * precise.
3399  *
3400  * One important and subtle aspect is that precise marks *do not matter* in
3401  * the currently verified state (current state). It is important to understand
3402  * why this is the case.
3403  *
3404  * First, note that current state is the state that is not yet "checkpointed",
3405  * i.e., it is not yet put into env->explored_states, and it has no children
3406  * states as well. It's ephemeral, and can end up either a) being discarded if
3407  * compatible explored state is found at some point or BPF_EXIT instruction is
3408  * reached or b) checkpointed and put into env->explored_states, branching out
3409  * into one or more children states.
3410  *
3411  * In the former case, precise markings in current state are completely
3412  * ignored by state comparison code (see regsafe() for details). Only
3413  * checkpointed ("old") state precise markings are important, and if old
3414  * state's register/slot is precise, regsafe() assumes current state's
3415  * register/slot as precise and checks value ranges exactly and precisely. If
3416  * states turn out to be compatible, current state's necessary precise
3417  * markings and any required parent states' precise markings are enforced
3418  * after the fact with propagate_precision() logic, after the fact. But it's
3419  * important to realize that in this case, even after marking current state
3420  * registers/slots as precise, we immediately discard current state. So what
3421  * actually matters is any of the precise markings propagated into current
3422  * state's parent states, which are always checkpointed (due to b) case above).
3423  * As such, for scenario a) it doesn't matter if current state has precise
3424  * markings set or not.
3425  *
3426  * Now, for the scenario b), checkpointing and forking into child(ren)
3427  * state(s). Note that before current state gets to checkpointing step, any
3428  * processed instruction always assumes precise SCALAR register/slot
3429  * knowledge: if precise value or range is useful to prune jump branch, BPF
3430  * verifier takes this opportunity enthusiastically. Similarly, when
3431  * register's value is used to calculate offset or memory address, exact
3432  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3433  * what we mentioned above about state comparison ignoring precise markings
3434  * during state comparison, BPF verifier ignores and also assumes precise
3435  * markings *at will* during instruction verification process. But as verifier
3436  * assumes precision, it also propagates any precision dependencies across
3437  * parent states, which are not yet finalized, so can be further restricted
3438  * based on new knowledge gained from restrictions enforced by their children
3439  * states. This is so that once those parent states are finalized, i.e., when
3440  * they have no more active children state, state comparison logic in
3441  * is_state_visited() would enforce strict and precise SCALAR ranges, if
3442  * required for correctness.
3443  *
3444  * To build a bit more intuition, note also that once a state is checkpointed,
3445  * the path we took to get to that state is not important. This is crucial
3446  * property for state pruning. When state is checkpointed and finalized at
3447  * some instruction index, it can be correctly and safely used to "short
3448  * circuit" any *compatible* state that reaches exactly the same instruction
3449  * index. I.e., if we jumped to that instruction from a completely different
3450  * code path than original finalized state was derived from, it doesn't
3451  * matter, current state can be discarded because from that instruction
3452  * forward having a compatible state will ensure we will safely reach the
3453  * exit. States describe preconditions for further exploration, but completely
3454  * forget the history of how we got here.
3455  *
3456  * This also means that even if we needed precise SCALAR range to get to
3457  * finalized state, but from that point forward *that same* SCALAR register is
3458  * never used in a precise context (i.e., it's precise value is not needed for
3459  * correctness), it's correct and safe to mark such register as "imprecise"
3460  * (i.e., precise marking set to false). This is what we rely on when we do
3461  * not set precise marking in current state. If no child state requires
3462  * precision for any given SCALAR register, it's safe to dictate that it can
3463  * be imprecise. If any child state does require this register to be precise,
3464  * we'll mark it precise later retroactively during precise markings
3465  * propagation from child state to parent states.
3466  *
3467  * Skipping precise marking setting in current state is a mild version of
3468  * relying on the above observation. But we can utilize this property even
3469  * more aggressively by proactively forgetting any precise marking in the
3470  * current state (which we inherited from the parent state), right before we
3471  * checkpoint it and branch off into new child state. This is done by
3472  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3473  * finalized states which help in short circuiting more future states.
3474  */
3475 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
3476                                   int spi)
3477 {
3478         struct bpf_verifier_state *st = env->cur_state;
3479         int first_idx = st->first_insn_idx;
3480         int last_idx = env->insn_idx;
3481         struct bpf_func_state *func;
3482         struct bpf_reg_state *reg;
3483         u32 reg_mask = regno >= 0 ? 1u << regno : 0;
3484         u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
3485         bool skip_first = true;
3486         bool new_marks = false;
3487         int i, err;
3488
3489         if (!env->bpf_capable)
3490                 return 0;
3491
3492         /* Do sanity checks against current state of register and/or stack
3493          * slot, but don't set precise flag in current state, as precision
3494          * tracking in the current state is unnecessary.
3495          */
3496         func = st->frame[frame];
3497         if (regno >= 0) {
3498                 reg = &func->regs[regno];
3499                 if (reg->type != SCALAR_VALUE) {
3500                         WARN_ONCE(1, "backtracing misuse");
3501                         return -EFAULT;
3502                 }
3503                 new_marks = true;
3504         }
3505
3506         while (spi >= 0) {
3507                 if (!is_spilled_reg(&func->stack[spi])) {
3508                         stack_mask = 0;
3509                         break;
3510                 }
3511                 reg = &func->stack[spi].spilled_ptr;
3512                 if (reg->type != SCALAR_VALUE) {
3513                         stack_mask = 0;
3514                         break;
3515                 }
3516                 new_marks = true;
3517                 break;
3518         }
3519
3520         if (!new_marks)
3521                 return 0;
3522         if (!reg_mask && !stack_mask)
3523                 return 0;
3524
3525         for (;;) {
3526                 DECLARE_BITMAP(mask, 64);
3527                 u32 history = st->jmp_history_cnt;
3528
3529                 if (env->log.level & BPF_LOG_LEVEL2)
3530                         verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
3531
3532                 if (last_idx < 0) {
3533                         /* we are at the entry into subprog, which
3534                          * is expected for global funcs, but only if
3535                          * requested precise registers are R1-R5
3536                          * (which are global func's input arguments)
3537                          */
3538                         if (st->curframe == 0 &&
3539                             st->frame[0]->subprogno > 0 &&
3540                             st->frame[0]->callsite == BPF_MAIN_FUNC &&
3541                             stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
3542                                 bitmap_from_u64(mask, reg_mask);
3543                                 for_each_set_bit(i, mask, 32) {
3544                                         reg = &st->frame[0]->regs[i];
3545                                         if (reg->type != SCALAR_VALUE) {
3546                                                 reg_mask &= ~(1u << i);
3547                                                 continue;
3548                                         }
3549                                         reg->precise = true;
3550                                 }
3551                                 return 0;
3552                         }
3553
3554                         verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
3555                                 st->frame[0]->subprogno, reg_mask, stack_mask);
3556                         WARN_ONCE(1, "verifier backtracking bug");
3557                         return -EFAULT;
3558                 }
3559
3560                 for (i = last_idx;;) {
3561                         if (skip_first) {
3562                                 err = 0;
3563                                 skip_first = false;
3564                         } else {
3565                                 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
3566                         }
3567                         if (err == -ENOTSUPP) {
3568                                 mark_all_scalars_precise(env, st);
3569                                 return 0;
3570                         } else if (err) {
3571                                 return err;
3572                         }
3573                         if (!reg_mask && !stack_mask)
3574                                 /* Found assignment(s) into tracked register in this state.
3575                                  * Since this state is already marked, just return.
3576                                  * Nothing to be tracked further in the parent state.
3577                                  */
3578                                 return 0;
3579                         if (i == first_idx)
3580                                 break;
3581                         i = get_prev_insn_idx(st, i, &history);
3582                         if (i >= env->prog->len) {
3583                                 /* This can happen if backtracking reached insn 0
3584                                  * and there are still reg_mask or stack_mask
3585                                  * to backtrack.
3586                                  * It means the backtracking missed the spot where
3587                                  * particular register was initialized with a constant.
3588                                  */
3589                                 verbose(env, "BUG backtracking idx %d\n", i);
3590                                 WARN_ONCE(1, "verifier backtracking bug");
3591                                 return -EFAULT;
3592                         }
3593                 }
3594                 st = st->parent;
3595                 if (!st)
3596                         break;
3597
3598                 new_marks = false;
3599                 func = st->frame[frame];
3600                 bitmap_from_u64(mask, reg_mask);
3601                 for_each_set_bit(i, mask, 32) {
3602                         reg = &func->regs[i];
3603                         if (reg->type != SCALAR_VALUE) {
3604                                 reg_mask &= ~(1u << i);
3605                                 continue;
3606                         }
3607                         if (!reg->precise)
3608                                 new_marks = true;
3609                         reg->precise = true;
3610                 }
3611
3612                 bitmap_from_u64(mask, stack_mask);
3613                 for_each_set_bit(i, mask, 64) {
3614                         if (i >= func->allocated_stack / BPF_REG_SIZE) {
3615                                 /* the sequence of instructions:
3616                                  * 2: (bf) r3 = r10
3617                                  * 3: (7b) *(u64 *)(r3 -8) = r0
3618                                  * 4: (79) r4 = *(u64 *)(r10 -8)
3619                                  * doesn't contain jmps. It's backtracked
3620                                  * as a single block.
3621                                  * During backtracking insn 3 is not recognized as
3622                                  * stack access, so at the end of backtracking
3623                                  * stack slot fp-8 is still marked in stack_mask.
3624                                  * However the parent state may not have accessed
3625                                  * fp-8 and it's "unallocated" stack space.
3626                                  * In such case fallback to conservative.
3627                                  */
3628                                 mark_all_scalars_precise(env, st);
3629                                 return 0;
3630                         }
3631
3632                         if (!is_spilled_reg(&func->stack[i])) {
3633                                 stack_mask &= ~(1ull << i);
3634                                 continue;
3635                         }
3636                         reg = &func->stack[i].spilled_ptr;
3637                         if (reg->type != SCALAR_VALUE) {
3638                                 stack_mask &= ~(1ull << i);
3639                                 continue;
3640                         }
3641                         if (!reg->precise)
3642                                 new_marks = true;
3643                         reg->precise = true;
3644                 }
3645                 if (env->log.level & BPF_LOG_LEVEL2) {
3646                         verbose(env, "parent %s regs=%x stack=%llx marks:",
3647                                 new_marks ? "didn't have" : "already had",
3648                                 reg_mask, stack_mask);
3649                         print_verifier_state(env, func, true);
3650                 }
3651
3652                 if (!reg_mask && !stack_mask)
3653                         break;
3654                 if (!new_marks)
3655                         break;
3656
3657                 last_idx = st->last_insn_idx;
3658                 first_idx = st->first_insn_idx;
3659         }
3660         return 0;
3661 }
3662
3663 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3664 {
3665         return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
3666 }
3667
3668 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
3669 {
3670         return __mark_chain_precision(env, frame, regno, -1);
3671 }
3672
3673 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
3674 {
3675         return __mark_chain_precision(env, frame, -1, spi);
3676 }
3677
3678 static bool is_spillable_regtype(enum bpf_reg_type type)
3679 {
3680         switch (base_type(type)) {
3681         case PTR_TO_MAP_VALUE:
3682         case PTR_TO_STACK:
3683         case PTR_TO_CTX:
3684         case PTR_TO_PACKET:
3685         case PTR_TO_PACKET_META:
3686         case PTR_TO_PACKET_END:
3687         case PTR_TO_FLOW_KEYS:
3688         case CONST_PTR_TO_MAP:
3689         case PTR_TO_SOCKET:
3690         case PTR_TO_SOCK_COMMON:
3691         case PTR_TO_TCP_SOCK:
3692         case PTR_TO_XDP_SOCK:
3693         case PTR_TO_BTF_ID:
3694         case PTR_TO_BUF:
3695         case PTR_TO_MEM:
3696         case PTR_TO_FUNC:
3697         case PTR_TO_MAP_KEY:
3698                 return true;
3699         default:
3700                 return false;
3701         }
3702 }
3703
3704 /* Does this register contain a constant zero? */
3705 static bool register_is_null(struct bpf_reg_state *reg)
3706 {
3707         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3708 }
3709
3710 static bool register_is_const(struct bpf_reg_state *reg)
3711 {
3712         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3713 }
3714
3715 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3716 {
3717         return tnum_is_unknown(reg->var_off) &&
3718                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3719                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3720                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3721                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3722 }
3723
3724 static bool register_is_bounded(struct bpf_reg_state *reg)
3725 {
3726         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3727 }
3728
3729 static bool __is_pointer_value(bool allow_ptr_leaks,
3730                                const struct bpf_reg_state *reg)
3731 {
3732         if (allow_ptr_leaks)
3733                 return false;
3734
3735         return reg->type != SCALAR_VALUE;
3736 }
3737
3738 /* Copy src state preserving dst->parent and dst->live fields */
3739 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
3740 {
3741         struct bpf_reg_state *parent = dst->parent;
3742         enum bpf_reg_liveness live = dst->live;
3743
3744         *dst = *src;
3745         dst->parent = parent;
3746         dst->live = live;
3747 }
3748
3749 static void save_register_state(struct bpf_func_state *state,
3750                                 int spi, struct bpf_reg_state *reg,
3751                                 int size)
3752 {
3753         int i;
3754
3755         copy_register_state(&state->stack[spi].spilled_ptr, reg);
3756         if (size == BPF_REG_SIZE)
3757                 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3758
3759         for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3760                 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3761
3762         /* size < 8 bytes spill */
3763         for (; i; i--)
3764                 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3765 }
3766
3767 static bool is_bpf_st_mem(struct bpf_insn *insn)
3768 {
3769         return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
3770 }
3771
3772 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3773  * stack boundary and alignment are checked in check_mem_access()
3774  */
3775 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3776                                        /* stack frame we're writing to */
3777                                        struct bpf_func_state *state,
3778                                        int off, int size, int value_regno,
3779                                        int insn_idx)
3780 {
3781         struct bpf_func_state *cur; /* state of the current function */
3782         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3783         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3784         struct bpf_reg_state *reg = NULL;
3785         u32 dst_reg = insn->dst_reg;
3786
3787         err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3788         if (err)
3789                 return err;
3790         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3791          * so it's aligned access and [off, off + size) are within stack limits
3792          */
3793         if (!env->allow_ptr_leaks &&
3794             state->stack[spi].slot_type[0] == STACK_SPILL &&
3795             size != BPF_REG_SIZE) {
3796                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3797                 return -EACCES;
3798         }
3799
3800         cur = env->cur_state->frame[env->cur_state->curframe];
3801         if (value_regno >= 0)
3802                 reg = &cur->regs[value_regno];
3803         if (!env->bypass_spec_v4) {
3804                 bool sanitize = reg && is_spillable_regtype(reg->type);
3805
3806                 for (i = 0; i < size; i++) {
3807                         u8 type = state->stack[spi].slot_type[i];
3808
3809                         if (type != STACK_MISC && type != STACK_ZERO) {
3810                                 sanitize = true;
3811                                 break;
3812                         }
3813                 }
3814
3815                 if (sanitize)
3816                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3817         }
3818
3819         err = destroy_if_dynptr_stack_slot(env, state, spi);
3820         if (err)
3821                 return err;
3822
3823         mark_stack_slot_scratched(env, spi);
3824         if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3825             !register_is_null(reg) && env->bpf_capable) {
3826                 if (dst_reg != BPF_REG_FP) {
3827                         /* The backtracking logic can only recognize explicit
3828                          * stack slot address like [fp - 8]. Other spill of
3829                          * scalar via different register has to be conservative.
3830                          * Backtrack from here and mark all registers as precise
3831                          * that contributed into 'reg' being a constant.
3832                          */
3833                         err = mark_chain_precision(env, value_regno);
3834                         if (err)
3835                                 return err;
3836                 }
3837                 save_register_state(state, spi, reg, size);
3838         } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
3839                    insn->imm != 0 && env->bpf_capable) {
3840                 struct bpf_reg_state fake_reg = {};
3841
3842                 __mark_reg_known(&fake_reg, (u32)insn->imm);
3843                 fake_reg.type = SCALAR_VALUE;
3844                 save_register_state(state, spi, &fake_reg, size);
3845         } else if (reg && is_spillable_regtype(reg->type)) {
3846                 /* register containing pointer is being spilled into stack */
3847                 if (size != BPF_REG_SIZE) {
3848                         verbose_linfo(env, insn_idx, "; ");
3849                         verbose(env, "invalid size of register spill\n");
3850                         return -EACCES;
3851                 }
3852                 if (state != cur && reg->type == PTR_TO_STACK) {
3853                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3854                         return -EINVAL;
3855                 }
3856                 save_register_state(state, spi, reg, size);
3857         } else {
3858                 u8 type = STACK_MISC;
3859
3860                 /* regular write of data into stack destroys any spilled ptr */
3861                 state->stack[spi].spilled_ptr.type = NOT_INIT;
3862                 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
3863                 if (is_stack_slot_special(&state->stack[spi]))
3864                         for (i = 0; i < BPF_REG_SIZE; i++)
3865                                 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3866
3867                 /* only mark the slot as written if all 8 bytes were written
3868                  * otherwise read propagation may incorrectly stop too soon
3869                  * when stack slots are partially written.
3870                  * This heuristic means that read propagation will be
3871                  * conservative, since it will add reg_live_read marks
3872                  * to stack slots all the way to first state when programs
3873                  * writes+reads less than 8 bytes
3874                  */
3875                 if (size == BPF_REG_SIZE)
3876                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3877
3878                 /* when we zero initialize stack slots mark them as such */
3879                 if ((reg && register_is_null(reg)) ||
3880                     (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
3881                         /* backtracking doesn't work for STACK_ZERO yet. */
3882                         err = mark_chain_precision(env, value_regno);
3883                         if (err)
3884                                 return err;
3885                         type = STACK_ZERO;
3886                 }
3887
3888                 /* Mark slots affected by this stack write. */
3889                 for (i = 0; i < size; i++)
3890                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3891                                 type;
3892         }
3893         return 0;
3894 }
3895
3896 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3897  * known to contain a variable offset.
3898  * This function checks whether the write is permitted and conservatively
3899  * tracks the effects of the write, considering that each stack slot in the
3900  * dynamic range is potentially written to.
3901  *
3902  * 'off' includes 'regno->off'.
3903  * 'value_regno' can be -1, meaning that an unknown value is being written to
3904  * the stack.
3905  *
3906  * Spilled pointers in range are not marked as written because we don't know
3907  * what's going to be actually written. This means that read propagation for
3908  * future reads cannot be terminated by this write.
3909  *
3910  * For privileged programs, uninitialized stack slots are considered
3911  * initialized by this write (even though we don't know exactly what offsets
3912  * are going to be written to). The idea is that we don't want the verifier to
3913  * reject future reads that access slots written to through variable offsets.
3914  */
3915 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3916                                      /* func where register points to */
3917                                      struct bpf_func_state *state,
3918                                      int ptr_regno, int off, int size,
3919                                      int value_regno, int insn_idx)
3920 {
3921         struct bpf_func_state *cur; /* state of the current function */
3922         int min_off, max_off;
3923         int i, err;
3924         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3925         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3926         bool writing_zero = false;
3927         /* set if the fact that we're writing a zero is used to let any
3928          * stack slots remain STACK_ZERO
3929          */
3930         bool zero_used = false;
3931
3932         cur = env->cur_state->frame[env->cur_state->curframe];
3933         ptr_reg = &cur->regs[ptr_regno];
3934         min_off = ptr_reg->smin_value + off;
3935         max_off = ptr_reg->smax_value + off + size;
3936         if (value_regno >= 0)
3937                 value_reg = &cur->regs[value_regno];
3938         if ((value_reg && register_is_null(value_reg)) ||
3939             (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
3940                 writing_zero = true;
3941
3942         err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3943         if (err)
3944                 return err;
3945
3946         for (i = min_off; i < max_off; i++) {
3947                 int spi;
3948
3949                 spi = __get_spi(i);
3950                 err = destroy_if_dynptr_stack_slot(env, state, spi);
3951                 if (err)
3952                         return err;
3953         }
3954
3955         /* Variable offset writes destroy any spilled pointers in range. */
3956         for (i = min_off; i < max_off; i++) {
3957                 u8 new_type, *stype;
3958                 int slot, spi;
3959
3960                 slot = -i - 1;
3961                 spi = slot / BPF_REG_SIZE;
3962                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3963                 mark_stack_slot_scratched(env, spi);
3964
3965                 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3966                         /* Reject the write if range we may write to has not
3967                          * been initialized beforehand. If we didn't reject
3968                          * here, the ptr status would be erased below (even
3969                          * though not all slots are actually overwritten),
3970                          * possibly opening the door to leaks.
3971                          *
3972                          * We do however catch STACK_INVALID case below, and
3973                          * only allow reading possibly uninitialized memory
3974                          * later for CAP_PERFMON, as the write may not happen to
3975                          * that slot.
3976                          */
3977                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3978                                 insn_idx, i);
3979                         return -EINVAL;
3980                 }
3981
3982                 /* Erase all spilled pointers. */
3983                 state->stack[spi].spilled_ptr.type = NOT_INIT;
3984
3985                 /* Update the slot type. */
3986                 new_type = STACK_MISC;
3987                 if (writing_zero && *stype == STACK_ZERO) {
3988                         new_type = STACK_ZERO;
3989                         zero_used = true;
3990                 }
3991                 /* If the slot is STACK_INVALID, we check whether it's OK to
3992                  * pretend that it will be initialized by this write. The slot
3993                  * might not actually be written to, and so if we mark it as
3994                  * initialized future reads might leak uninitialized memory.
3995                  * For privileged programs, we will accept such reads to slots
3996                  * that may or may not be written because, if we're reject
3997                  * them, the error would be too confusing.
3998                  */
3999                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4000                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4001                                         insn_idx, i);
4002                         return -EINVAL;
4003                 }
4004                 *stype = new_type;
4005         }
4006         if (zero_used) {
4007                 /* backtracking doesn't work for STACK_ZERO yet. */
4008                 err = mark_chain_precision(env, value_regno);
4009                 if (err)
4010                         return err;
4011         }
4012         return 0;
4013 }
4014
4015 /* When register 'dst_regno' is assigned some values from stack[min_off,
4016  * max_off), we set the register's type according to the types of the
4017  * respective stack slots. If all the stack values are known to be zeros, then
4018  * so is the destination reg. Otherwise, the register is considered to be
4019  * SCALAR. This function does not deal with register filling; the caller must
4020  * ensure that all spilled registers in the stack range have been marked as
4021  * read.
4022  */
4023 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4024                                 /* func where src register points to */
4025                                 struct bpf_func_state *ptr_state,
4026                                 int min_off, int max_off, int dst_regno)
4027 {
4028         struct bpf_verifier_state *vstate = env->cur_state;
4029         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4030         int i, slot, spi;
4031         u8 *stype;
4032         int zeros = 0;
4033
4034         for (i = min_off; i < max_off; i++) {
4035                 slot = -i - 1;
4036                 spi = slot / BPF_REG_SIZE;
4037                 stype = ptr_state->stack[spi].slot_type;
4038                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4039                         break;
4040                 zeros++;
4041         }
4042         if (zeros == max_off - min_off) {
4043                 /* any access_size read into register is zero extended,
4044                  * so the whole register == const_zero
4045                  */
4046                 __mark_reg_const_zero(&state->regs[dst_regno]);
4047                 /* backtracking doesn't support STACK_ZERO yet,
4048                  * so mark it precise here, so that later
4049                  * backtracking can stop here.
4050                  * Backtracking may not need this if this register
4051                  * doesn't participate in pointer adjustment.
4052                  * Forward propagation of precise flag is not
4053                  * necessary either. This mark is only to stop
4054                  * backtracking. Any register that contributed
4055                  * to const 0 was marked precise before spill.
4056                  */
4057                 state->regs[dst_regno].precise = true;
4058         } else {
4059                 /* have read misc data from the stack */
4060                 mark_reg_unknown(env, state->regs, dst_regno);
4061         }
4062         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4063 }
4064
4065 /* Read the stack at 'off' and put the results into the register indicated by
4066  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4067  * spilled reg.
4068  *
4069  * 'dst_regno' can be -1, meaning that the read value is not going to a
4070  * register.
4071  *
4072  * The access is assumed to be within the current stack bounds.
4073  */
4074 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4075                                       /* func where src register points to */
4076                                       struct bpf_func_state *reg_state,
4077                                       int off, int size, int dst_regno)
4078 {
4079         struct bpf_verifier_state *vstate = env->cur_state;
4080         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4081         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4082         struct bpf_reg_state *reg;
4083         u8 *stype, type;
4084
4085         stype = reg_state->stack[spi].slot_type;
4086         reg = &reg_state->stack[spi].spilled_ptr;
4087
4088         if (is_spilled_reg(&reg_state->stack[spi])) {
4089                 u8 spill_size = 1;
4090
4091                 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4092                         spill_size++;
4093
4094                 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4095                         if (reg->type != SCALAR_VALUE) {
4096                                 verbose_linfo(env, env->insn_idx, "; ");
4097                                 verbose(env, "invalid size of register fill\n");
4098                                 return -EACCES;
4099                         }
4100
4101                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4102                         if (dst_regno < 0)
4103                                 return 0;
4104
4105                         if (!(off % BPF_REG_SIZE) && size == spill_size) {
4106                                 /* The earlier check_reg_arg() has decided the
4107                                  * subreg_def for this insn.  Save it first.
4108                                  */
4109                                 s32 subreg_def = state->regs[dst_regno].subreg_def;
4110
4111                                 copy_register_state(&state->regs[dst_regno], reg);
4112                                 state->regs[dst_regno].subreg_def = subreg_def;
4113                         } else {
4114                                 for (i = 0; i < size; i++) {
4115                                         type = stype[(slot - i) % BPF_REG_SIZE];
4116                                         if (type == STACK_SPILL)
4117                                                 continue;
4118                                         if (type == STACK_MISC)
4119                                                 continue;
4120                                         if (type == STACK_INVALID && env->allow_uninit_stack)
4121                                                 continue;
4122                                         verbose(env, "invalid read from stack off %d+%d size %d\n",
4123                                                 off, i, size);
4124                                         return -EACCES;
4125                                 }
4126                                 mark_reg_unknown(env, state->regs, dst_regno);
4127                         }
4128                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4129                         return 0;
4130                 }
4131
4132                 if (dst_regno >= 0) {
4133                         /* restore register state from stack */
4134                         copy_register_state(&state->regs[dst_regno], reg);
4135                         /* mark reg as written since spilled pointer state likely
4136                          * has its liveness marks cleared by is_state_visited()
4137                          * which resets stack/reg liveness for state transitions
4138                          */
4139                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4140                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4141                         /* If dst_regno==-1, the caller is asking us whether
4142                          * it is acceptable to use this value as a SCALAR_VALUE
4143                          * (e.g. for XADD).
4144                          * We must not allow unprivileged callers to do that
4145                          * with spilled pointers.
4146                          */
4147                         verbose(env, "leaking pointer from stack off %d\n",
4148                                 off);
4149                         return -EACCES;
4150                 }
4151                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4152         } else {
4153                 for (i = 0; i < size; i++) {
4154                         type = stype[(slot - i) % BPF_REG_SIZE];
4155                         if (type == STACK_MISC)
4156                                 continue;
4157                         if (type == STACK_ZERO)
4158                                 continue;
4159                         if (type == STACK_INVALID && env->allow_uninit_stack)
4160                                 continue;
4161                         verbose(env, "invalid read from stack off %d+%d size %d\n",
4162                                 off, i, size);
4163                         return -EACCES;
4164                 }
4165                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4166                 if (dst_regno >= 0)
4167                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4168         }
4169         return 0;
4170 }
4171
4172 enum bpf_access_src {
4173         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4174         ACCESS_HELPER = 2,  /* the access is performed by a helper */
4175 };
4176
4177 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4178                                          int regno, int off, int access_size,
4179                                          bool zero_size_allowed,
4180                                          enum bpf_access_src type,
4181                                          struct bpf_call_arg_meta *meta);
4182
4183 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4184 {
4185         return cur_regs(env) + regno;
4186 }
4187
4188 /* Read the stack at 'ptr_regno + off' and put the result into the register
4189  * 'dst_regno'.
4190  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4191  * but not its variable offset.
4192  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4193  *
4194  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4195  * filling registers (i.e. reads of spilled register cannot be detected when
4196  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4197  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4198  * offset; for a fixed offset check_stack_read_fixed_off should be used
4199  * instead.
4200  */
4201 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4202                                     int ptr_regno, int off, int size, int dst_regno)
4203 {
4204         /* The state of the source register. */
4205         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4206         struct bpf_func_state *ptr_state = func(env, reg);
4207         int err;
4208         int min_off, max_off;
4209
4210         /* Note that we pass a NULL meta, so raw access will not be permitted.
4211          */
4212         err = check_stack_range_initialized(env, ptr_regno, off, size,
4213                                             false, ACCESS_DIRECT, NULL);
4214         if (err)
4215                 return err;
4216
4217         min_off = reg->smin_value + off;
4218         max_off = reg->smax_value + off;
4219         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4220         return 0;
4221 }
4222
4223 /* check_stack_read dispatches to check_stack_read_fixed_off or
4224  * check_stack_read_var_off.
4225  *
4226  * The caller must ensure that the offset falls within the allocated stack
4227  * bounds.
4228  *
4229  * 'dst_regno' is a register which will receive the value from the stack. It
4230  * can be -1, meaning that the read value is not going to a register.
4231  */
4232 static int check_stack_read(struct bpf_verifier_env *env,
4233                             int ptr_regno, int off, int size,
4234                             int dst_regno)
4235 {
4236         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4237         struct bpf_func_state *state = func(env, reg);
4238         int err;
4239         /* Some accesses are only permitted with a static offset. */
4240         bool var_off = !tnum_is_const(reg->var_off);
4241
4242         /* The offset is required to be static when reads don't go to a
4243          * register, in order to not leak pointers (see
4244          * check_stack_read_fixed_off).
4245          */
4246         if (dst_regno < 0 && var_off) {
4247                 char tn_buf[48];
4248
4249                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4250                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4251                         tn_buf, off, size);
4252                 return -EACCES;
4253         }
4254         /* Variable offset is prohibited for unprivileged mode for simplicity
4255          * since it requires corresponding support in Spectre masking for stack
4256          * ALU. See also retrieve_ptr_limit(). The check in
4257          * check_stack_access_for_ptr_arithmetic() called by
4258          * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4259          * with variable offsets, therefore no check is required here. Further,
4260          * just checking it here would be insufficient as speculative stack
4261          * writes could still lead to unsafe speculative behaviour.
4262          */
4263         if (!var_off) {
4264                 off += reg->var_off.value;
4265                 err = check_stack_read_fixed_off(env, state, off, size,
4266                                                  dst_regno);
4267         } else {
4268                 /* Variable offset stack reads need more conservative handling
4269                  * than fixed offset ones. Note that dst_regno >= 0 on this
4270                  * branch.
4271                  */
4272                 err = check_stack_read_var_off(env, ptr_regno, off, size,
4273                                                dst_regno);
4274         }
4275         return err;
4276 }
4277
4278
4279 /* check_stack_write dispatches to check_stack_write_fixed_off or
4280  * check_stack_write_var_off.
4281  *
4282  * 'ptr_regno' is the register used as a pointer into the stack.
4283  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4284  * 'value_regno' is the register whose value we're writing to the stack. It can
4285  * be -1, meaning that we're not writing from a register.
4286  *
4287  * The caller must ensure that the offset falls within the maximum stack size.
4288  */
4289 static int check_stack_write(struct bpf_verifier_env *env,
4290                              int ptr_regno, int off, int size,
4291                              int value_regno, int insn_idx)
4292 {
4293         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4294         struct bpf_func_state *state = func(env, reg);
4295         int err;
4296
4297         if (tnum_is_const(reg->var_off)) {
4298                 off += reg->var_off.value;
4299                 err = check_stack_write_fixed_off(env, state, off, size,
4300                                                   value_regno, insn_idx);
4301         } else {
4302                 /* Variable offset stack reads need more conservative handling
4303                  * than fixed offset ones.
4304                  */
4305                 err = check_stack_write_var_off(env, state,
4306                                                 ptr_regno, off, size,
4307                                                 value_regno, insn_idx);
4308         }
4309         return err;
4310 }
4311
4312 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4313                                  int off, int size, enum bpf_access_type type)
4314 {
4315         struct bpf_reg_state *regs = cur_regs(env);
4316         struct bpf_map *map = regs[regno].map_ptr;
4317         u32 cap = bpf_map_flags_to_cap(map);
4318
4319         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4320                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4321                         map->value_size, off, size);
4322                 return -EACCES;
4323         }
4324
4325         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4326                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4327                         map->value_size, off, size);
4328                 return -EACCES;
4329         }
4330
4331         return 0;
4332 }
4333
4334 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4335 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4336                               int off, int size, u32 mem_size,
4337                               bool zero_size_allowed)
4338 {
4339         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4340         struct bpf_reg_state *reg;
4341
4342         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4343                 return 0;
4344
4345         reg = &cur_regs(env)[regno];
4346         switch (reg->type) {
4347         case PTR_TO_MAP_KEY:
4348                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4349                         mem_size, off, size);
4350                 break;
4351         case PTR_TO_MAP_VALUE:
4352                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4353                         mem_size, off, size);
4354                 break;
4355         case PTR_TO_PACKET:
4356         case PTR_TO_PACKET_META:
4357         case PTR_TO_PACKET_END:
4358                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4359                         off, size, regno, reg->id, off, mem_size);
4360                 break;
4361         case PTR_TO_MEM:
4362         default:
4363                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4364                         mem_size, off, size);
4365         }
4366
4367         return -EACCES;
4368 }
4369
4370 /* check read/write into a memory region with possible variable offset */
4371 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4372                                    int off, int size, u32 mem_size,
4373                                    bool zero_size_allowed)
4374 {
4375         struct bpf_verifier_state *vstate = env->cur_state;
4376         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4377         struct bpf_reg_state *reg = &state->regs[regno];
4378         int err;
4379
4380         /* We may have adjusted the register pointing to memory region, so we
4381          * need to try adding each of min_value and max_value to off
4382          * to make sure our theoretical access will be safe.
4383          *
4384          * The minimum value is only important with signed
4385          * comparisons where we can't assume the floor of a
4386          * value is 0.  If we are using signed variables for our
4387          * index'es we need to make sure that whatever we use
4388          * will have a set floor within our range.
4389          */
4390         if (reg->smin_value < 0 &&
4391             (reg->smin_value == S64_MIN ||
4392              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4393               reg->smin_value + off < 0)) {
4394                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4395                         regno);
4396                 return -EACCES;
4397         }
4398         err = __check_mem_access(env, regno, reg->smin_value + off, size,
4399                                  mem_size, zero_size_allowed);
4400         if (err) {
4401                 verbose(env, "R%d min value is outside of the allowed memory range\n",
4402                         regno);
4403                 return err;
4404         }
4405
4406         /* If we haven't set a max value then we need to bail since we can't be
4407          * sure we won't do bad things.
4408          * If reg->umax_value + off could overflow, treat that as unbounded too.
4409          */
4410         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4411                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4412                         regno);
4413                 return -EACCES;
4414         }
4415         err = __check_mem_access(env, regno, reg->umax_value + off, size,
4416                                  mem_size, zero_size_allowed);
4417         if (err) {
4418                 verbose(env, "R%d max value is outside of the allowed memory range\n",
4419                         regno);
4420                 return err;
4421         }
4422
4423         return 0;
4424 }
4425
4426 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4427                                const struct bpf_reg_state *reg, int regno,
4428                                bool fixed_off_ok)
4429 {
4430         /* Access to this pointer-typed register or passing it to a helper
4431          * is only allowed in its original, unmodified form.
4432          */
4433
4434         if (reg->off < 0) {
4435                 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4436                         reg_type_str(env, reg->type), regno, reg->off);
4437                 return -EACCES;
4438         }
4439
4440         if (!fixed_off_ok && reg->off) {
4441                 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4442                         reg_type_str(env, reg->type), regno, reg->off);
4443                 return -EACCES;
4444         }
4445
4446         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4447                 char tn_buf[48];
4448
4449                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4450                 verbose(env, "variable %s access var_off=%s disallowed\n",
4451                         reg_type_str(env, reg->type), tn_buf);
4452                 return -EACCES;
4453         }
4454
4455         return 0;
4456 }
4457
4458 int check_ptr_off_reg(struct bpf_verifier_env *env,
4459                       const struct bpf_reg_state *reg, int regno)
4460 {
4461         return __check_ptr_off_reg(env, reg, regno, false);
4462 }
4463
4464 static int map_kptr_match_type(struct bpf_verifier_env *env,
4465                                struct btf_field *kptr_field,
4466                                struct bpf_reg_state *reg, u32 regno)
4467 {
4468         const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4469         int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4470         const char *reg_name = "";
4471
4472         /* Only unreferenced case accepts untrusted pointers */
4473         if (kptr_field->type == BPF_KPTR_UNREF)
4474                 perm_flags |= PTR_UNTRUSTED;
4475
4476         if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
4477                 goto bad_type;
4478
4479         if (!btf_is_kernel(reg->btf)) {
4480                 verbose(env, "R%d must point to kernel BTF\n", regno);
4481                 return -EINVAL;
4482         }
4483         /* We need to verify reg->type and reg->btf, before accessing reg->btf */
4484         reg_name = btf_type_name(reg->btf, reg->btf_id);
4485
4486         /* For ref_ptr case, release function check should ensure we get one
4487          * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
4488          * normal store of unreferenced kptr, we must ensure var_off is zero.
4489          * Since ref_ptr cannot be accessed directly by BPF insns, checks for
4490          * reg->off and reg->ref_obj_id are not needed here.
4491          */
4492         if (__check_ptr_off_reg(env, reg, regno, true))
4493                 return -EACCES;
4494
4495         /* A full type match is needed, as BTF can be vmlinux or module BTF, and
4496          * we also need to take into account the reg->off.
4497          *
4498          * We want to support cases like:
4499          *
4500          * struct foo {
4501          *         struct bar br;
4502          *         struct baz bz;
4503          * };
4504          *
4505          * struct foo *v;
4506          * v = func();        // PTR_TO_BTF_ID
4507          * val->foo = v;      // reg->off is zero, btf and btf_id match type
4508          * val->bar = &v->br; // reg->off is still zero, but we need to retry with
4509          *                    // first member type of struct after comparison fails
4510          * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
4511          *                    // to match type
4512          *
4513          * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
4514          * is zero. We must also ensure that btf_struct_ids_match does not walk
4515          * the struct to match type against first member of struct, i.e. reject
4516          * second case from above. Hence, when type is BPF_KPTR_REF, we set
4517          * strict mode to true for type match.
4518          */
4519         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4520                                   kptr_field->kptr.btf, kptr_field->kptr.btf_id,
4521                                   kptr_field->type == BPF_KPTR_REF))
4522                 goto bad_type;
4523         return 0;
4524 bad_type:
4525         verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
4526                 reg_type_str(env, reg->type), reg_name);
4527         verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
4528         if (kptr_field->type == BPF_KPTR_UNREF)
4529                 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
4530                         targ_name);
4531         else
4532                 verbose(env, "\n");
4533         return -EINVAL;
4534 }
4535
4536 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
4537  * can dereference RCU protected pointers and result is PTR_TRUSTED.
4538  */
4539 static bool in_rcu_cs(struct bpf_verifier_env *env)
4540 {
4541         return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
4542 }
4543
4544 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
4545 BTF_SET_START(rcu_protected_types)
4546 BTF_ID(struct, prog_test_ref_kfunc)
4547 BTF_ID(struct, cgroup)
4548 BTF_ID(struct, bpf_cpumask)
4549 BTF_ID(struct, task_struct)
4550 BTF_SET_END(rcu_protected_types)
4551
4552 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
4553 {
4554         if (!btf_is_kernel(btf))
4555                 return false;
4556         return btf_id_set_contains(&rcu_protected_types, btf_id);
4557 }
4558
4559 static bool rcu_safe_kptr(const struct btf_field *field)
4560 {
4561         const struct btf_field_kptr *kptr = &field->kptr;
4562
4563         return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
4564 }
4565
4566 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
4567                                  int value_regno, int insn_idx,
4568                                  struct btf_field *kptr_field)
4569 {
4570         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4571         int class = BPF_CLASS(insn->code);
4572         struct bpf_reg_state *val_reg;
4573
4574         /* Things we already checked for in check_map_access and caller:
4575          *  - Reject cases where variable offset may touch kptr
4576          *  - size of access (must be BPF_DW)
4577          *  - tnum_is_const(reg->var_off)
4578          *  - kptr_field->offset == off + reg->var_off.value
4579          */
4580         /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4581         if (BPF_MODE(insn->code) != BPF_MEM) {
4582                 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4583                 return -EACCES;
4584         }
4585
4586         /* We only allow loading referenced kptr, since it will be marked as
4587          * untrusted, similar to unreferenced kptr.
4588          */
4589         if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
4590                 verbose(env, "store to referenced kptr disallowed\n");
4591                 return -EACCES;
4592         }
4593
4594         if (class == BPF_LDX) {
4595                 val_reg = reg_state(env, value_regno);
4596                 /* We can simply mark the value_regno receiving the pointer
4597                  * value from map as PTR_TO_BTF_ID, with the correct type.
4598                  */
4599                 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
4600                                 kptr_field->kptr.btf_id,
4601                                 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
4602                                 PTR_MAYBE_NULL | MEM_RCU :
4603                                 PTR_MAYBE_NULL | PTR_UNTRUSTED);
4604                 /* For mark_ptr_or_null_reg */
4605                 val_reg->id = ++env->id_gen;
4606         } else if (class == BPF_STX) {
4607                 val_reg = reg_state(env, value_regno);
4608                 if (!register_is_null(val_reg) &&
4609                     map_kptr_match_type(env, kptr_field, val_reg, value_regno))
4610                         return -EACCES;
4611         } else if (class == BPF_ST) {
4612                 if (insn->imm) {
4613                         verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
4614                                 kptr_field->offset);
4615                         return -EACCES;
4616                 }
4617         } else {
4618                 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
4619                 return -EACCES;
4620         }
4621         return 0;
4622 }
4623
4624 /* check read/write into a map element with possible variable offset */
4625 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
4626                             int off, int size, bool zero_size_allowed,
4627                             enum bpf_access_src src)
4628 {
4629         struct bpf_verifier_state *vstate = env->cur_state;
4630         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4631         struct bpf_reg_state *reg = &state->regs[regno];
4632         struct bpf_map *map = reg->map_ptr;
4633         struct btf_record *rec;
4634         int err, i;
4635
4636         err = check_mem_region_access(env, regno, off, size, map->value_size,
4637                                       zero_size_allowed);
4638         if (err)
4639                 return err;
4640
4641         if (IS_ERR_OR_NULL(map->record))
4642                 return 0;
4643         rec = map->record;
4644         for (i = 0; i < rec->cnt; i++) {
4645                 struct btf_field *field = &rec->fields[i];
4646                 u32 p = field->offset;
4647
4648                 /* If any part of a field  can be touched by load/store, reject
4649                  * this program. To check that [x1, x2) overlaps with [y1, y2),
4650                  * it is sufficient to check x1 < y2 && y1 < x2.
4651                  */
4652                 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
4653                     p < reg->umax_value + off + size) {
4654                         switch (field->type) {
4655                         case BPF_KPTR_UNREF:
4656                         case BPF_KPTR_REF:
4657                                 if (src != ACCESS_DIRECT) {
4658                                         verbose(env, "kptr cannot be accessed indirectly by helper\n");
4659                                         return -EACCES;
4660                                 }
4661                                 if (!tnum_is_const(reg->var_off)) {
4662                                         verbose(env, "kptr access cannot have variable offset\n");
4663                                         return -EACCES;
4664                                 }
4665                                 if (p != off + reg->var_off.value) {
4666                                         verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4667                                                 p, off + reg->var_off.value);
4668                                         return -EACCES;
4669                                 }
4670                                 if (size != bpf_size_to_bytes(BPF_DW)) {
4671                                         verbose(env, "kptr access size must be BPF_DW\n");
4672                                         return -EACCES;
4673                                 }
4674                                 break;
4675                         default:
4676                                 verbose(env, "%s cannot be accessed directly by load/store\n",
4677                                         btf_field_type_name(field->type));
4678                                 return -EACCES;
4679                         }
4680                 }
4681         }
4682         return 0;
4683 }
4684
4685 #define MAX_PACKET_OFF 0xffff
4686
4687 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4688                                        const struct bpf_call_arg_meta *meta,
4689                                        enum bpf_access_type t)
4690 {
4691         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4692
4693         switch (prog_type) {
4694         /* Program types only with direct read access go here! */
4695         case BPF_PROG_TYPE_LWT_IN:
4696         case BPF_PROG_TYPE_LWT_OUT:
4697         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4698         case BPF_PROG_TYPE_SK_REUSEPORT:
4699         case BPF_PROG_TYPE_FLOW_DISSECTOR:
4700         case BPF_PROG_TYPE_CGROUP_SKB:
4701                 if (t == BPF_WRITE)
4702                         return false;
4703                 fallthrough;
4704
4705         /* Program types with direct read + write access go here! */
4706         case BPF_PROG_TYPE_SCHED_CLS:
4707         case BPF_PROG_TYPE_SCHED_ACT:
4708         case BPF_PROG_TYPE_XDP:
4709         case BPF_PROG_TYPE_LWT_XMIT:
4710         case BPF_PROG_TYPE_SK_SKB:
4711         case BPF_PROG_TYPE_SK_MSG:
4712                 if (meta)
4713                         return meta->pkt_access;
4714
4715                 env->seen_direct_write = true;
4716                 return true;
4717
4718         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4719                 if (t == BPF_WRITE)
4720                         env->seen_direct_write = true;
4721
4722                 return true;
4723
4724         default:
4725                 return false;
4726         }
4727 }
4728
4729 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
4730                                int size, bool zero_size_allowed)
4731 {
4732         struct bpf_reg_state *regs = cur_regs(env);
4733         struct bpf_reg_state *reg = &regs[regno];
4734         int err;
4735
4736         /* We may have added a variable offset to the packet pointer; but any
4737          * reg->range we have comes after that.  We are only checking the fixed
4738          * offset.
4739          */
4740
4741         /* We don't allow negative numbers, because we aren't tracking enough
4742          * detail to prove they're safe.
4743          */
4744         if (reg->smin_value < 0) {
4745                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4746                         regno);
4747                 return -EACCES;
4748         }
4749
4750         err = reg->range < 0 ? -EINVAL :
4751               __check_mem_access(env, regno, off, size, reg->range,
4752                                  zero_size_allowed);
4753         if (err) {
4754                 verbose(env, "R%d offset is outside of the packet\n", regno);
4755                 return err;
4756         }
4757
4758         /* __check_mem_access has made sure "off + size - 1" is within u16.
4759          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4760          * otherwise find_good_pkt_pointers would have refused to set range info
4761          * that __check_mem_access would have rejected this pkt access.
4762          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4763          */
4764         env->prog->aux->max_pkt_offset =
4765                 max_t(u32, env->prog->aux->max_pkt_offset,
4766                       off + reg->umax_value + size - 1);
4767
4768         return err;
4769 }
4770
4771 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
4772 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4773                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
4774                             struct btf **btf, u32 *btf_id)
4775 {
4776         struct bpf_insn_access_aux info = {
4777                 .reg_type = *reg_type,
4778                 .log = &env->log,
4779         };
4780
4781         if (env->ops->is_valid_access &&
4782             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4783                 /* A non zero info.ctx_field_size indicates that this field is a
4784                  * candidate for later verifier transformation to load the whole
4785                  * field and then apply a mask when accessed with a narrower
4786                  * access than actual ctx access size. A zero info.ctx_field_size
4787                  * will only allow for whole field access and rejects any other
4788                  * type of narrower access.
4789                  */
4790                 *reg_type = info.reg_type;
4791
4792                 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4793                         *btf = info.btf;
4794                         *btf_id = info.btf_id;
4795                 } else {
4796                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4797                 }
4798                 /* remember the offset of last byte accessed in ctx */
4799                 if (env->prog->aux->max_ctx_offset < off + size)
4800                         env->prog->aux->max_ctx_offset = off + size;
4801                 return 0;
4802         }
4803
4804         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4805         return -EACCES;
4806 }
4807
4808 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4809                                   int size)
4810 {
4811         if (size < 0 || off < 0 ||
4812             (u64)off + size > sizeof(struct bpf_flow_keys)) {
4813                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4814                         off, size);
4815                 return -EACCES;
4816         }
4817         return 0;
4818 }
4819
4820 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4821                              u32 regno, int off, int size,
4822                              enum bpf_access_type t)
4823 {
4824         struct bpf_reg_state *regs = cur_regs(env);
4825         struct bpf_reg_state *reg = &regs[regno];
4826         struct bpf_insn_access_aux info = {};
4827         bool valid;
4828
4829         if (reg->smin_value < 0) {
4830                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4831                         regno);
4832                 return -EACCES;
4833         }
4834
4835         switch (reg->type) {
4836         case PTR_TO_SOCK_COMMON:
4837                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4838                 break;
4839         case PTR_TO_SOCKET:
4840                 valid = bpf_sock_is_valid_access(off, size, t, &info);
4841                 break;
4842         case PTR_TO_TCP_SOCK:
4843                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4844                 break;
4845         case PTR_TO_XDP_SOCK:
4846                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4847                 break;
4848         default:
4849                 valid = false;
4850         }
4851
4852
4853         if (valid) {
4854                 env->insn_aux_data[insn_idx].ctx_field_size =
4855                         info.ctx_field_size;
4856                 return 0;
4857         }
4858
4859         verbose(env, "R%d invalid %s access off=%d size=%d\n",
4860                 regno, reg_type_str(env, reg->type), off, size);
4861
4862         return -EACCES;
4863 }
4864
4865 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4866 {
4867         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4868 }
4869
4870 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4871 {
4872         const struct bpf_reg_state *reg = reg_state(env, regno);
4873
4874         return reg->type == PTR_TO_CTX;
4875 }
4876
4877 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4878 {
4879         const struct bpf_reg_state *reg = reg_state(env, regno);
4880
4881         return type_is_sk_pointer(reg->type);
4882 }
4883
4884 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4885 {
4886         const struct bpf_reg_state *reg = reg_state(env, regno);
4887
4888         return type_is_pkt_pointer(reg->type);
4889 }
4890
4891 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4892 {
4893         const struct bpf_reg_state *reg = reg_state(env, regno);
4894
4895         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4896         return reg->type == PTR_TO_FLOW_KEYS;
4897 }
4898
4899 static bool is_trusted_reg(const struct bpf_reg_state *reg)
4900 {
4901         /* A referenced register is always trusted. */
4902         if (reg->ref_obj_id)
4903                 return true;
4904
4905         /* If a register is not referenced, it is trusted if it has the
4906          * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
4907          * other type modifiers may be safe, but we elect to take an opt-in
4908          * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
4909          * not.
4910          *
4911          * Eventually, we should make PTR_TRUSTED the single source of truth
4912          * for whether a register is trusted.
4913          */
4914         return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
4915                !bpf_type_has_unsafe_modifiers(reg->type);
4916 }
4917
4918 static bool is_rcu_reg(const struct bpf_reg_state *reg)
4919 {
4920         return reg->type & MEM_RCU;
4921 }
4922
4923 static void clear_trusted_flags(enum bpf_type_flag *flag)
4924 {
4925         *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
4926 }
4927
4928 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4929                                    const struct bpf_reg_state *reg,
4930                                    int off, int size, bool strict)
4931 {
4932         struct tnum reg_off;
4933         int ip_align;
4934
4935         /* Byte size accesses are always allowed. */
4936         if (!strict || size == 1)
4937                 return 0;
4938
4939         /* For platforms that do not have a Kconfig enabling
4940          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4941          * NET_IP_ALIGN is universally set to '2'.  And on platforms
4942          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4943          * to this code only in strict mode where we want to emulate
4944          * the NET_IP_ALIGN==2 checking.  Therefore use an
4945          * unconditional IP align value of '2'.
4946          */
4947         ip_align = 2;
4948
4949         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4950         if (!tnum_is_aligned(reg_off, size)) {
4951                 char tn_buf[48];
4952
4953                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4954                 verbose(env,
4955                         "misaligned packet access off %d+%s+%d+%d size %d\n",
4956                         ip_align, tn_buf, reg->off, off, size);
4957                 return -EACCES;
4958         }
4959
4960         return 0;
4961 }
4962
4963 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4964                                        const struct bpf_reg_state *reg,
4965                                        const char *pointer_desc,
4966                                        int off, int size, bool strict)
4967 {
4968         struct tnum reg_off;
4969
4970         /* Byte size accesses are always allowed. */
4971         if (!strict || size == 1)
4972                 return 0;
4973
4974         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4975         if (!tnum_is_aligned(reg_off, size)) {
4976                 char tn_buf[48];
4977
4978                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4979                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4980                         pointer_desc, tn_buf, reg->off, off, size);
4981                 return -EACCES;
4982         }
4983
4984         return 0;
4985 }
4986
4987 static int check_ptr_alignment(struct bpf_verifier_env *env,
4988                                const struct bpf_reg_state *reg, int off,
4989                                int size, bool strict_alignment_once)
4990 {
4991         bool strict = env->strict_alignment || strict_alignment_once;
4992         const char *pointer_desc = "";
4993
4994         switch (reg->type) {
4995         case PTR_TO_PACKET:
4996         case PTR_TO_PACKET_META:
4997                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4998                  * right in front, treat it the very same way.
4999                  */
5000                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5001         case PTR_TO_FLOW_KEYS:
5002                 pointer_desc = "flow keys ";
5003                 break;
5004         case PTR_TO_MAP_KEY:
5005                 pointer_desc = "key ";
5006                 break;
5007         case PTR_TO_MAP_VALUE:
5008                 pointer_desc = "value ";
5009                 break;
5010         case PTR_TO_CTX:
5011                 pointer_desc = "context ";
5012                 break;
5013         case PTR_TO_STACK:
5014                 pointer_desc = "stack ";
5015                 /* The stack spill tracking logic in check_stack_write_fixed_off()
5016                  * and check_stack_read_fixed_off() relies on stack accesses being
5017                  * aligned.
5018                  */
5019                 strict = true;
5020                 break;
5021         case PTR_TO_SOCKET:
5022                 pointer_desc = "sock ";
5023                 break;
5024         case PTR_TO_SOCK_COMMON:
5025                 pointer_desc = "sock_common ";
5026                 break;
5027         case PTR_TO_TCP_SOCK:
5028                 pointer_desc = "tcp_sock ";
5029                 break;
5030         case PTR_TO_XDP_SOCK:
5031                 pointer_desc = "xdp_sock ";
5032                 break;
5033         default:
5034                 break;
5035         }
5036         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5037                                            strict);
5038 }
5039
5040 static int update_stack_depth(struct bpf_verifier_env *env,
5041                               const struct bpf_func_state *func,
5042                               int off)
5043 {
5044         u16 stack = env->subprog_info[func->subprogno].stack_depth;
5045
5046         if (stack >= -off)
5047                 return 0;
5048
5049         /* update known max for given subprogram */
5050         env->subprog_info[func->subprogno].stack_depth = -off;
5051         return 0;
5052 }
5053
5054 /* starting from main bpf function walk all instructions of the function
5055  * and recursively walk all callees that given function can call.
5056  * Ignore jump and exit insns.
5057  * Since recursion is prevented by check_cfg() this algorithm
5058  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5059  */
5060 static int check_max_stack_depth(struct bpf_verifier_env *env)
5061 {
5062         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
5063         struct bpf_subprog_info *subprog = env->subprog_info;
5064         struct bpf_insn *insn = env->prog->insnsi;
5065         bool tail_call_reachable = false;
5066         int ret_insn[MAX_CALL_FRAMES];
5067         int ret_prog[MAX_CALL_FRAMES];
5068         int j;
5069
5070 process_func:
5071         /* protect against potential stack overflow that might happen when
5072          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5073          * depth for such case down to 256 so that the worst case scenario
5074          * would result in 8k stack size (32 which is tailcall limit * 256 =
5075          * 8k).
5076          *
5077          * To get the idea what might happen, see an example:
5078          * func1 -> sub rsp, 128
5079          *  subfunc1 -> sub rsp, 256
5080          *  tailcall1 -> add rsp, 256
5081          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5082          *   subfunc2 -> sub rsp, 64
5083          *   subfunc22 -> sub rsp, 128
5084          *   tailcall2 -> add rsp, 128
5085          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5086          *
5087          * tailcall will unwind the current stack frame but it will not get rid
5088          * of caller's stack as shown on the example above.
5089          */
5090         if (idx && subprog[idx].has_tail_call && depth >= 256) {
5091                 verbose(env,
5092                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5093                         depth);
5094                 return -EACCES;
5095         }
5096         /* round up to 32-bytes, since this is granularity
5097          * of interpreter stack size
5098          */
5099         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5100         if (depth > MAX_BPF_STACK) {
5101                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5102                         frame + 1, depth);
5103                 return -EACCES;
5104         }
5105 continue_func:
5106         subprog_end = subprog[idx + 1].start;
5107         for (; i < subprog_end; i++) {
5108                 int next_insn;
5109
5110                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5111                         continue;
5112                 /* remember insn and function to return to */
5113                 ret_insn[frame] = i + 1;
5114                 ret_prog[frame] = idx;
5115
5116                 /* find the callee */
5117                 next_insn = i + insn[i].imm + 1;
5118                 idx = find_subprog(env, next_insn);
5119                 if (idx < 0) {
5120                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5121                                   next_insn);
5122                         return -EFAULT;
5123                 }
5124                 if (subprog[idx].is_async_cb) {
5125                         if (subprog[idx].has_tail_call) {
5126                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5127                                 return -EFAULT;
5128                         }
5129                          /* async callbacks don't increase bpf prog stack size */
5130                         continue;
5131                 }
5132                 i = next_insn;
5133
5134                 if (subprog[idx].has_tail_call)
5135                         tail_call_reachable = true;
5136
5137                 frame++;
5138                 if (frame >= MAX_CALL_FRAMES) {
5139                         verbose(env, "the call stack of %d frames is too deep !\n",
5140                                 frame);
5141                         return -E2BIG;
5142                 }
5143                 goto process_func;
5144         }
5145         /* if tail call got detected across bpf2bpf calls then mark each of the
5146          * currently present subprog frames as tail call reachable subprogs;
5147          * this info will be utilized by JIT so that we will be preserving the
5148          * tail call counter throughout bpf2bpf calls combined with tailcalls
5149          */
5150         if (tail_call_reachable)
5151                 for (j = 0; j < frame; j++)
5152                         subprog[ret_prog[j]].tail_call_reachable = true;
5153         if (subprog[0].tail_call_reachable)
5154                 env->prog->aux->tail_call_reachable = true;
5155
5156         /* end of for() loop means the last insn of the 'subprog'
5157          * was reached. Doesn't matter whether it was JA or EXIT
5158          */
5159         if (frame == 0)
5160                 return 0;
5161         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5162         frame--;
5163         i = ret_insn[frame];
5164         idx = ret_prog[frame];
5165         goto continue_func;
5166 }
5167
5168 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5169 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5170                                   const struct bpf_insn *insn, int idx)
5171 {
5172         int start = idx + insn->imm + 1, subprog;
5173
5174         subprog = find_subprog(env, start);
5175         if (subprog < 0) {
5176                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5177                           start);
5178                 return -EFAULT;
5179         }
5180         return env->subprog_info[subprog].stack_depth;
5181 }
5182 #endif
5183
5184 static int __check_buffer_access(struct bpf_verifier_env *env,
5185                                  const char *buf_info,
5186                                  const struct bpf_reg_state *reg,
5187                                  int regno, int off, int size)
5188 {
5189         if (off < 0) {
5190                 verbose(env,
5191                         "R%d invalid %s buffer access: off=%d, size=%d\n",
5192                         regno, buf_info, off, size);
5193                 return -EACCES;
5194         }
5195         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5196                 char tn_buf[48];
5197
5198                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5199                 verbose(env,
5200                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5201                         regno, off, tn_buf);
5202                 return -EACCES;
5203         }
5204
5205         return 0;
5206 }
5207
5208 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5209                                   const struct bpf_reg_state *reg,
5210                                   int regno, int off, int size)
5211 {
5212         int err;
5213
5214         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5215         if (err)
5216                 return err;
5217
5218         if (off + size > env->prog->aux->max_tp_access)
5219                 env->prog->aux->max_tp_access = off + size;
5220
5221         return 0;
5222 }
5223
5224 static int check_buffer_access(struct bpf_verifier_env *env,
5225                                const struct bpf_reg_state *reg,
5226                                int regno, int off, int size,
5227                                bool zero_size_allowed,
5228                                u32 *max_access)
5229 {
5230         const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5231         int err;
5232
5233         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5234         if (err)
5235                 return err;
5236
5237         if (off + size > *max_access)
5238                 *max_access = off + size;
5239
5240         return 0;
5241 }
5242
5243 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5244 static void zext_32_to_64(struct bpf_reg_state *reg)
5245 {
5246         reg->var_off = tnum_subreg(reg->var_off);
5247         __reg_assign_32_into_64(reg);
5248 }
5249
5250 /* truncate register to smaller size (in bytes)
5251  * must be called with size < BPF_REG_SIZE
5252  */
5253 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5254 {
5255         u64 mask;
5256
5257         /* clear high bits in bit representation */
5258         reg->var_off = tnum_cast(reg->var_off, size);
5259
5260         /* fix arithmetic bounds */
5261         mask = ((u64)1 << (size * 8)) - 1;
5262         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5263                 reg->umin_value &= mask;
5264                 reg->umax_value &= mask;
5265         } else {
5266                 reg->umin_value = 0;
5267                 reg->umax_value = mask;
5268         }
5269         reg->smin_value = reg->umin_value;
5270         reg->smax_value = reg->umax_value;
5271
5272         /* If size is smaller than 32bit register the 32bit register
5273          * values are also truncated so we push 64-bit bounds into
5274          * 32-bit bounds. Above were truncated < 32-bits already.
5275          */
5276         if (size >= 4)
5277                 return;
5278         __reg_combine_64_into_32(reg);
5279 }
5280
5281 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5282 {
5283         /* A map is considered read-only if the following condition are true:
5284          *
5285          * 1) BPF program side cannot change any of the map content. The
5286          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5287          *    and was set at map creation time.
5288          * 2) The map value(s) have been initialized from user space by a
5289          *    loader and then "frozen", such that no new map update/delete
5290          *    operations from syscall side are possible for the rest of
5291          *    the map's lifetime from that point onwards.
5292          * 3) Any parallel/pending map update/delete operations from syscall
5293          *    side have been completed. Only after that point, it's safe to
5294          *    assume that map value(s) are immutable.
5295          */
5296         return (map->map_flags & BPF_F_RDONLY_PROG) &&
5297                READ_ONCE(map->frozen) &&
5298                !bpf_map_write_active(map);
5299 }
5300
5301 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
5302 {
5303         void *ptr;
5304         u64 addr;
5305         int err;
5306
5307         err = map->ops->map_direct_value_addr(map, &addr, off);
5308         if (err)
5309                 return err;
5310         ptr = (void *)(long)addr + off;
5311
5312         switch (size) {
5313         case sizeof(u8):
5314                 *val = (u64)*(u8 *)ptr;
5315                 break;
5316         case sizeof(u16):
5317                 *val = (u64)*(u16 *)ptr;
5318                 break;
5319         case sizeof(u32):
5320                 *val = (u64)*(u32 *)ptr;
5321                 break;
5322         case sizeof(u64):
5323                 *val = *(u64 *)ptr;
5324                 break;
5325         default:
5326                 return -EINVAL;
5327         }
5328         return 0;
5329 }
5330
5331 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
5332 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
5333 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
5334
5335 /*
5336  * Allow list few fields as RCU trusted or full trusted.
5337  * This logic doesn't allow mix tagging and will be removed once GCC supports
5338  * btf_type_tag.
5339  */
5340
5341 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
5342 BTF_TYPE_SAFE_RCU(struct task_struct) {
5343         const cpumask_t *cpus_ptr;
5344         struct css_set __rcu *cgroups;
5345         struct task_struct __rcu *real_parent;
5346         struct task_struct *group_leader;
5347 };
5348
5349 BTF_TYPE_SAFE_RCU(struct cgroup) {
5350         /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
5351         struct kernfs_node *kn;
5352 };
5353
5354 BTF_TYPE_SAFE_RCU(struct css_set) {
5355         struct cgroup *dfl_cgrp;
5356 };
5357
5358 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
5359 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
5360         struct file __rcu *exe_file;
5361 };
5362
5363 /* skb->sk, req->sk are not RCU protected, but we mark them as such
5364  * because bpf prog accessible sockets are SOCK_RCU_FREE.
5365  */
5366 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
5367         struct sock *sk;
5368 };
5369
5370 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
5371         struct sock *sk;
5372 };
5373
5374 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
5375 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
5376         struct seq_file *seq;
5377 };
5378
5379 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
5380         struct bpf_iter_meta *meta;
5381         struct task_struct *task;
5382 };
5383
5384 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
5385         struct file *file;
5386 };
5387
5388 BTF_TYPE_SAFE_TRUSTED(struct file) {
5389         struct inode *f_inode;
5390 };
5391
5392 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
5393         /* no negative dentry-s in places where bpf can see it */
5394         struct inode *d_inode;
5395 };
5396
5397 BTF_TYPE_SAFE_TRUSTED(struct socket) {
5398         struct sock *sk;
5399 };
5400
5401 static bool type_is_rcu(struct bpf_verifier_env *env,
5402                         struct bpf_reg_state *reg,
5403                         const char *field_name, u32 btf_id)
5404 {
5405         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
5406         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
5407         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
5408
5409         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
5410 }
5411
5412 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
5413                                 struct bpf_reg_state *reg,
5414                                 const char *field_name, u32 btf_id)
5415 {
5416         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
5417         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
5418         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
5419
5420         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
5421 }
5422
5423 static bool type_is_trusted(struct bpf_verifier_env *env,
5424                             struct bpf_reg_state *reg,
5425                             const char *field_name, u32 btf_id)
5426 {
5427         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
5428         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
5429         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
5430         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
5431         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
5432         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
5433
5434         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
5435 }
5436
5437 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
5438                                    struct bpf_reg_state *regs,
5439                                    int regno, int off, int size,
5440                                    enum bpf_access_type atype,
5441                                    int value_regno)
5442 {
5443         struct bpf_reg_state *reg = regs + regno;
5444         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
5445         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
5446         const char *field_name = NULL;
5447         enum bpf_type_flag flag = 0;
5448         u32 btf_id = 0;
5449         int ret;
5450
5451         if (!env->allow_ptr_leaks) {
5452                 verbose(env,
5453                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5454                         tname);
5455                 return -EPERM;
5456         }
5457         if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
5458                 verbose(env,
5459                         "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
5460                         tname);
5461                 return -EINVAL;
5462         }
5463         if (off < 0) {
5464                 verbose(env,
5465                         "R%d is ptr_%s invalid negative access: off=%d\n",
5466                         regno, tname, off);
5467                 return -EACCES;
5468         }
5469         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5470                 char tn_buf[48];
5471
5472                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5473                 verbose(env,
5474                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
5475                         regno, tname, off, tn_buf);
5476                 return -EACCES;
5477         }
5478
5479         if (reg->type & MEM_USER) {
5480                 verbose(env,
5481                         "R%d is ptr_%s access user memory: off=%d\n",
5482                         regno, tname, off);
5483                 return -EACCES;
5484         }
5485
5486         if (reg->type & MEM_PERCPU) {
5487                 verbose(env,
5488                         "R%d is ptr_%s access percpu memory: off=%d\n",
5489                         regno, tname, off);
5490                 return -EACCES;
5491         }
5492
5493         if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
5494                 if (!btf_is_kernel(reg->btf)) {
5495                         verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
5496                         return -EFAULT;
5497                 }
5498                 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
5499         } else {
5500                 /* Writes are permitted with default btf_struct_access for
5501                  * program allocated objects (which always have ref_obj_id > 0),
5502                  * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
5503                  */
5504                 if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
5505                         verbose(env, "only read is supported\n");
5506                         return -EACCES;
5507                 }
5508
5509                 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
5510                     !reg->ref_obj_id) {
5511                         verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
5512                         return -EFAULT;
5513                 }
5514
5515                 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
5516         }
5517
5518         if (ret < 0)
5519                 return ret;
5520
5521         if (ret != PTR_TO_BTF_ID) {
5522                 /* just mark; */
5523
5524         } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
5525                 /* If this is an untrusted pointer, all pointers formed by walking it
5526                  * also inherit the untrusted flag.
5527                  */
5528                 flag = PTR_UNTRUSTED;
5529
5530         } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
5531                 /* By default any pointer obtained from walking a trusted pointer is no
5532                  * longer trusted, unless the field being accessed has explicitly been
5533                  * marked as inheriting its parent's state of trust (either full or RCU).
5534                  * For example:
5535                  * 'cgroups' pointer is untrusted if task->cgroups dereference
5536                  * happened in a sleepable program outside of bpf_rcu_read_lock()
5537                  * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
5538                  * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
5539                  *
5540                  * A regular RCU-protected pointer with __rcu tag can also be deemed
5541                  * trusted if we are in an RCU CS. Such pointer can be NULL.
5542                  */
5543                 if (type_is_trusted(env, reg, field_name, btf_id)) {
5544                         flag |= PTR_TRUSTED;
5545                 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
5546                         if (type_is_rcu(env, reg, field_name, btf_id)) {
5547                                 /* ignore __rcu tag and mark it MEM_RCU */
5548                                 flag |= MEM_RCU;
5549                         } else if (flag & MEM_RCU ||
5550                                    type_is_rcu_or_null(env, reg, field_name, btf_id)) {
5551                                 /* __rcu tagged pointers can be NULL */
5552                                 flag |= MEM_RCU | PTR_MAYBE_NULL;
5553                         } else if (flag & (MEM_PERCPU | MEM_USER)) {
5554                                 /* keep as-is */
5555                         } else {
5556                                 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
5557                                 clear_trusted_flags(&flag);
5558                         }
5559                 } else {
5560                         /*
5561                          * If not in RCU CS or MEM_RCU pointer can be NULL then
5562                          * aggressively mark as untrusted otherwise such
5563                          * pointers will be plain PTR_TO_BTF_ID without flags
5564                          * and will be allowed to be passed into helpers for
5565                          * compat reasons.
5566                          */
5567                         flag = PTR_UNTRUSTED;
5568                 }
5569         } else {
5570                 /* Old compat. Deprecated */
5571                 clear_trusted_flags(&flag);
5572         }
5573
5574         if (atype == BPF_READ && value_regno >= 0)
5575                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
5576
5577         return 0;
5578 }
5579
5580 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
5581                                    struct bpf_reg_state *regs,
5582                                    int regno, int off, int size,
5583                                    enum bpf_access_type atype,
5584                                    int value_regno)
5585 {
5586         struct bpf_reg_state *reg = regs + regno;
5587         struct bpf_map *map = reg->map_ptr;
5588         struct bpf_reg_state map_reg;
5589         enum bpf_type_flag flag = 0;
5590         const struct btf_type *t;
5591         const char *tname;
5592         u32 btf_id;
5593         int ret;
5594
5595         if (!btf_vmlinux) {
5596                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
5597                 return -ENOTSUPP;
5598         }
5599
5600         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
5601                 verbose(env, "map_ptr access not supported for map type %d\n",
5602                         map->map_type);
5603                 return -ENOTSUPP;
5604         }
5605
5606         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
5607         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5608
5609         if (!env->allow_ptr_leaks) {
5610                 verbose(env,
5611                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
5612                         tname);
5613                 return -EPERM;
5614         }
5615
5616         if (off < 0) {
5617                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
5618                         regno, tname, off);
5619                 return -EACCES;
5620         }
5621
5622         if (atype != BPF_READ) {
5623                 verbose(env, "only read from %s is supported\n", tname);
5624                 return -EACCES;
5625         }
5626
5627         /* Simulate access to a PTR_TO_BTF_ID */
5628         memset(&map_reg, 0, sizeof(map_reg));
5629         mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
5630         ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
5631         if (ret < 0)
5632                 return ret;
5633
5634         if (value_regno >= 0)
5635                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
5636
5637         return 0;
5638 }
5639
5640 /* Check that the stack access at the given offset is within bounds. The
5641  * maximum valid offset is -1.
5642  *
5643  * The minimum valid offset is -MAX_BPF_STACK for writes, and
5644  * -state->allocated_stack for reads.
5645  */
5646 static int check_stack_slot_within_bounds(int off,
5647                                           struct bpf_func_state *state,
5648                                           enum bpf_access_type t)
5649 {
5650         int min_valid_off;
5651
5652         if (t == BPF_WRITE)
5653                 min_valid_off = -MAX_BPF_STACK;
5654         else
5655                 min_valid_off = -state->allocated_stack;
5656
5657         if (off < min_valid_off || off > -1)
5658                 return -EACCES;
5659         return 0;
5660 }
5661
5662 /* Check that the stack access at 'regno + off' falls within the maximum stack
5663  * bounds.
5664  *
5665  * 'off' includes `regno->offset`, but not its dynamic part (if any).
5666  */
5667 static int check_stack_access_within_bounds(
5668                 struct bpf_verifier_env *env,
5669                 int regno, int off, int access_size,
5670                 enum bpf_access_src src, enum bpf_access_type type)
5671 {
5672         struct bpf_reg_state *regs = cur_regs(env);
5673         struct bpf_reg_state *reg = regs + regno;
5674         struct bpf_func_state *state = func(env, reg);
5675         int min_off, max_off;
5676         int err;
5677         char *err_extra;
5678
5679         if (src == ACCESS_HELPER)
5680                 /* We don't know if helpers are reading or writing (or both). */
5681                 err_extra = " indirect access to";
5682         else if (type == BPF_READ)
5683                 err_extra = " read from";
5684         else
5685                 err_extra = " write to";
5686
5687         if (tnum_is_const(reg->var_off)) {
5688                 min_off = reg->var_off.value + off;
5689                 if (access_size > 0)
5690                         max_off = min_off + access_size - 1;
5691                 else
5692                         max_off = min_off;
5693         } else {
5694                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
5695                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
5696                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
5697                                 err_extra, regno);
5698                         return -EACCES;
5699                 }
5700                 min_off = reg->smin_value + off;
5701                 if (access_size > 0)
5702                         max_off = reg->smax_value + off + access_size - 1;
5703                 else
5704                         max_off = min_off;
5705         }
5706
5707         err = check_stack_slot_within_bounds(min_off, state, type);
5708         if (!err)
5709                 err = check_stack_slot_within_bounds(max_off, state, type);
5710
5711         if (err) {
5712                 if (tnum_is_const(reg->var_off)) {
5713                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
5714                                 err_extra, regno, off, access_size);
5715                 } else {
5716                         char tn_buf[48];
5717
5718                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5719                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
5720                                 err_extra, regno, tn_buf, access_size);
5721                 }
5722         }
5723         return err;
5724 }
5725
5726 /* check whether memory at (regno + off) is accessible for t = (read | write)
5727  * if t==write, value_regno is a register which value is stored into memory
5728  * if t==read, value_regno is a register which will receive the value from memory
5729  * if t==write && value_regno==-1, some unknown value is stored into memory
5730  * if t==read && value_regno==-1, don't care what we read from memory
5731  */
5732 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
5733                             int off, int bpf_size, enum bpf_access_type t,
5734                             int value_regno, bool strict_alignment_once)
5735 {
5736         struct bpf_reg_state *regs = cur_regs(env);
5737         struct bpf_reg_state *reg = regs + regno;
5738         struct bpf_func_state *state;
5739         int size, err = 0;
5740
5741         size = bpf_size_to_bytes(bpf_size);
5742         if (size < 0)
5743                 return size;
5744
5745         /* alignment checks will add in reg->off themselves */
5746         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
5747         if (err)
5748                 return err;
5749
5750         /* for access checks, reg->off is just part of off */
5751         off += reg->off;
5752
5753         if (reg->type == PTR_TO_MAP_KEY) {
5754                 if (t == BPF_WRITE) {
5755                         verbose(env, "write to change key R%d not allowed\n", regno);
5756                         return -EACCES;
5757                 }
5758
5759                 err = check_mem_region_access(env, regno, off, size,
5760                                               reg->map_ptr->key_size, false);
5761                 if (err)
5762                         return err;
5763                 if (value_regno >= 0)
5764                         mark_reg_unknown(env, regs, value_regno);
5765         } else if (reg->type == PTR_TO_MAP_VALUE) {
5766                 struct btf_field *kptr_field = NULL;
5767
5768                 if (t == BPF_WRITE && value_regno >= 0 &&
5769                     is_pointer_value(env, value_regno)) {
5770                         verbose(env, "R%d leaks addr into map\n", value_regno);
5771                         return -EACCES;
5772                 }
5773                 err = check_map_access_type(env, regno, off, size, t);
5774                 if (err)
5775                         return err;
5776                 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
5777                 if (err)
5778                         return err;
5779                 if (tnum_is_const(reg->var_off))
5780                         kptr_field = btf_record_find(reg->map_ptr->record,
5781                                                      off + reg->var_off.value, BPF_KPTR);
5782                 if (kptr_field) {
5783                         err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
5784                 } else if (t == BPF_READ && value_regno >= 0) {
5785                         struct bpf_map *map = reg->map_ptr;
5786
5787                         /* if map is read-only, track its contents as scalars */
5788                         if (tnum_is_const(reg->var_off) &&
5789                             bpf_map_is_rdonly(map) &&
5790                             map->ops->map_direct_value_addr) {
5791                                 int map_off = off + reg->var_off.value;
5792                                 u64 val = 0;
5793
5794                                 err = bpf_map_direct_read(map, map_off, size,
5795                                                           &val);
5796                                 if (err)
5797                                         return err;
5798
5799                                 regs[value_regno].type = SCALAR_VALUE;
5800                                 __mark_reg_known(&regs[value_regno], val);
5801                         } else {
5802                                 mark_reg_unknown(env, regs, value_regno);
5803                         }
5804                 }
5805         } else if (base_type(reg->type) == PTR_TO_MEM) {
5806                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
5807
5808                 if (type_may_be_null(reg->type)) {
5809                         verbose(env, "R%d invalid mem access '%s'\n", regno,
5810                                 reg_type_str(env, reg->type));
5811                         return -EACCES;
5812                 }
5813
5814                 if (t == BPF_WRITE && rdonly_mem) {
5815                         verbose(env, "R%d cannot write into %s\n",
5816                                 regno, reg_type_str(env, reg->type));
5817                         return -EACCES;
5818                 }
5819
5820                 if (t == BPF_WRITE && value_regno >= 0 &&
5821                     is_pointer_value(env, value_regno)) {
5822                         verbose(env, "R%d leaks addr into mem\n", value_regno);
5823                         return -EACCES;
5824                 }
5825
5826                 err = check_mem_region_access(env, regno, off, size,
5827                                               reg->mem_size, false);
5828                 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
5829                         mark_reg_unknown(env, regs, value_regno);
5830         } else if (reg->type == PTR_TO_CTX) {
5831                 enum bpf_reg_type reg_type = SCALAR_VALUE;
5832                 struct btf *btf = NULL;
5833                 u32 btf_id = 0;
5834
5835                 if (t == BPF_WRITE && value_regno >= 0 &&
5836                     is_pointer_value(env, value_regno)) {
5837                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
5838                         return -EACCES;
5839                 }
5840
5841                 err = check_ptr_off_reg(env, reg, regno);
5842                 if (err < 0)
5843                         return err;
5844
5845                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
5846                                        &btf_id);
5847                 if (err)
5848                         verbose_linfo(env, insn_idx, "; ");
5849                 if (!err && t == BPF_READ && value_regno >= 0) {
5850                         /* ctx access returns either a scalar, or a
5851                          * PTR_TO_PACKET[_META,_END]. In the latter
5852                          * case, we know the offset is zero.
5853                          */
5854                         if (reg_type == SCALAR_VALUE) {
5855                                 mark_reg_unknown(env, regs, value_regno);
5856                         } else {
5857                                 mark_reg_known_zero(env, regs,
5858                                                     value_regno);
5859                                 if (type_may_be_null(reg_type))
5860                                         regs[value_regno].id = ++env->id_gen;
5861                                 /* A load of ctx field could have different
5862                                  * actual load size with the one encoded in the
5863                                  * insn. When the dst is PTR, it is for sure not
5864                                  * a sub-register.
5865                                  */
5866                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
5867                                 if (base_type(reg_type) == PTR_TO_BTF_ID) {
5868                                         regs[value_regno].btf = btf;
5869                                         regs[value_regno].btf_id = btf_id;
5870                                 }
5871                         }
5872                         regs[value_regno].type = reg_type;
5873                 }
5874
5875         } else if (reg->type == PTR_TO_STACK) {
5876                 /* Basic bounds checks. */
5877                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
5878                 if (err)
5879                         return err;
5880
5881                 state = func(env, reg);
5882                 err = update_stack_depth(env, state, off);
5883                 if (err)
5884                         return err;
5885
5886                 if (t == BPF_READ)
5887                         err = check_stack_read(env, regno, off, size,
5888                                                value_regno);
5889                 else
5890                         err = check_stack_write(env, regno, off, size,
5891                                                 value_regno, insn_idx);
5892         } else if (reg_is_pkt_pointer(reg)) {
5893                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
5894                         verbose(env, "cannot write into packet\n");
5895                         return -EACCES;
5896                 }
5897                 if (t == BPF_WRITE && value_regno >= 0 &&
5898                     is_pointer_value(env, value_regno)) {
5899                         verbose(env, "R%d leaks addr into packet\n",
5900                                 value_regno);
5901                         return -EACCES;
5902                 }
5903                 err = check_packet_access(env, regno, off, size, false);
5904                 if (!err && t == BPF_READ && value_regno >= 0)
5905                         mark_reg_unknown(env, regs, value_regno);
5906         } else if (reg->type == PTR_TO_FLOW_KEYS) {
5907                 if (t == BPF_WRITE && value_regno >= 0 &&
5908                     is_pointer_value(env, value_regno)) {
5909                         verbose(env, "R%d leaks addr into flow keys\n",
5910                                 value_regno);
5911                         return -EACCES;
5912                 }
5913
5914                 err = check_flow_keys_access(env, off, size);
5915                 if (!err && t == BPF_READ && value_regno >= 0)
5916                         mark_reg_unknown(env, regs, value_regno);
5917         } else if (type_is_sk_pointer(reg->type)) {
5918                 if (t == BPF_WRITE) {
5919                         verbose(env, "R%d cannot write into %s\n",
5920                                 regno, reg_type_str(env, reg->type));
5921                         return -EACCES;
5922                 }
5923                 err = check_sock_access(env, insn_idx, regno, off, size, t);
5924                 if (!err && value_regno >= 0)
5925                         mark_reg_unknown(env, regs, value_regno);
5926         } else if (reg->type == PTR_TO_TP_BUFFER) {
5927                 err = check_tp_buffer_access(env, reg, regno, off, size);
5928                 if (!err && t == BPF_READ && value_regno >= 0)
5929                         mark_reg_unknown(env, regs, value_regno);
5930         } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5931                    !type_may_be_null(reg->type)) {
5932                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5933                                               value_regno);
5934         } else if (reg->type == CONST_PTR_TO_MAP) {
5935                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5936                                               value_regno);
5937         } else if (base_type(reg->type) == PTR_TO_BUF) {
5938                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
5939                 u32 *max_access;
5940
5941                 if (rdonly_mem) {
5942                         if (t == BPF_WRITE) {
5943                                 verbose(env, "R%d cannot write into %s\n",
5944                                         regno, reg_type_str(env, reg->type));
5945                                 return -EACCES;
5946                         }
5947                         max_access = &env->prog->aux->max_rdonly_access;
5948                 } else {
5949                         max_access = &env->prog->aux->max_rdwr_access;
5950                 }
5951
5952                 err = check_buffer_access(env, reg, regno, off, size, false,
5953                                           max_access);
5954
5955                 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5956                         mark_reg_unknown(env, regs, value_regno);
5957         } else {
5958                 verbose(env, "R%d invalid mem access '%s'\n", regno,
5959                         reg_type_str(env, reg->type));
5960                 return -EACCES;
5961         }
5962
5963         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5964             regs[value_regno].type == SCALAR_VALUE) {
5965                 /* b/h/w load zero-extends, mark upper bits as known 0 */
5966                 coerce_reg_to_size(&regs[value_regno], size);
5967         }
5968         return err;
5969 }
5970
5971 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5972 {
5973         int load_reg;
5974         int err;
5975
5976         switch (insn->imm) {
5977         case BPF_ADD:
5978         case BPF_ADD | BPF_FETCH:
5979         case BPF_AND:
5980         case BPF_AND | BPF_FETCH:
5981         case BPF_OR:
5982         case BPF_OR | BPF_FETCH:
5983         case BPF_XOR:
5984         case BPF_XOR | BPF_FETCH:
5985         case BPF_XCHG:
5986         case BPF_CMPXCHG:
5987                 break;
5988         default:
5989                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5990                 return -EINVAL;
5991         }
5992
5993         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5994                 verbose(env, "invalid atomic operand size\n");
5995                 return -EINVAL;
5996         }
5997
5998         /* check src1 operand */
5999         err = check_reg_arg(env, insn->src_reg, SRC_OP);
6000         if (err)
6001                 return err;
6002
6003         /* check src2 operand */
6004         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6005         if (err)
6006                 return err;
6007
6008         if (insn->imm == BPF_CMPXCHG) {
6009                 /* Check comparison of R0 with memory location */
6010                 const u32 aux_reg = BPF_REG_0;
6011
6012                 err = check_reg_arg(env, aux_reg, SRC_OP);
6013                 if (err)
6014                         return err;
6015
6016                 if (is_pointer_value(env, aux_reg)) {
6017                         verbose(env, "R%d leaks addr into mem\n", aux_reg);
6018                         return -EACCES;
6019                 }
6020         }
6021
6022         if (is_pointer_value(env, insn->src_reg)) {
6023                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6024                 return -EACCES;
6025         }
6026
6027         if (is_ctx_reg(env, insn->dst_reg) ||
6028             is_pkt_reg(env, insn->dst_reg) ||
6029             is_flow_key_reg(env, insn->dst_reg) ||
6030             is_sk_reg(env, insn->dst_reg)) {
6031                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6032                         insn->dst_reg,
6033                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6034                 return -EACCES;
6035         }
6036
6037         if (insn->imm & BPF_FETCH) {
6038                 if (insn->imm == BPF_CMPXCHG)
6039                         load_reg = BPF_REG_0;
6040                 else
6041                         load_reg = insn->src_reg;
6042
6043                 /* check and record load of old value */
6044                 err = check_reg_arg(env, load_reg, DST_OP);
6045                 if (err)
6046                         return err;
6047         } else {
6048                 /* This instruction accesses a memory location but doesn't
6049                  * actually load it into a register.
6050                  */
6051                 load_reg = -1;
6052         }
6053
6054         /* Check whether we can read the memory, with second call for fetch
6055          * case to simulate the register fill.
6056          */
6057         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6058                                BPF_SIZE(insn->code), BPF_READ, -1, true);
6059         if (!err && load_reg >= 0)
6060                 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6061                                        BPF_SIZE(insn->code), BPF_READ, load_reg,
6062                                        true);
6063         if (err)
6064                 return err;
6065
6066         /* Check whether we can write into the same memory. */
6067         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6068                                BPF_SIZE(insn->code), BPF_WRITE, -1, true);
6069         if (err)
6070                 return err;
6071
6072         return 0;
6073 }
6074
6075 /* When register 'regno' is used to read the stack (either directly or through
6076  * a helper function) make sure that it's within stack boundary and, depending
6077  * on the access type, that all elements of the stack are initialized.
6078  *
6079  * 'off' includes 'regno->off', but not its dynamic part (if any).
6080  *
6081  * All registers that have been spilled on the stack in the slots within the
6082  * read offsets are marked as read.
6083  */
6084 static int check_stack_range_initialized(
6085                 struct bpf_verifier_env *env, int regno, int off,
6086                 int access_size, bool zero_size_allowed,
6087                 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6088 {
6089         struct bpf_reg_state *reg = reg_state(env, regno);
6090         struct bpf_func_state *state = func(env, reg);
6091         int err, min_off, max_off, i, j, slot, spi;
6092         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6093         enum bpf_access_type bounds_check_type;
6094         /* Some accesses can write anything into the stack, others are
6095          * read-only.
6096          */
6097         bool clobber = false;
6098
6099         if (access_size == 0 && !zero_size_allowed) {
6100                 verbose(env, "invalid zero-sized read\n");
6101                 return -EACCES;
6102         }
6103
6104         if (type == ACCESS_HELPER) {
6105                 /* The bounds checks for writes are more permissive than for
6106                  * reads. However, if raw_mode is not set, we'll do extra
6107                  * checks below.
6108                  */
6109                 bounds_check_type = BPF_WRITE;
6110                 clobber = true;
6111         } else {
6112                 bounds_check_type = BPF_READ;
6113         }
6114         err = check_stack_access_within_bounds(env, regno, off, access_size,
6115                                                type, bounds_check_type);
6116         if (err)
6117                 return err;
6118
6119
6120         if (tnum_is_const(reg->var_off)) {
6121                 min_off = max_off = reg->var_off.value + off;
6122         } else {
6123                 /* Variable offset is prohibited for unprivileged mode for
6124                  * simplicity since it requires corresponding support in
6125                  * Spectre masking for stack ALU.
6126                  * See also retrieve_ptr_limit().
6127                  */
6128                 if (!env->bypass_spec_v1) {
6129                         char tn_buf[48];
6130
6131                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6132                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6133                                 regno, err_extra, tn_buf);
6134                         return -EACCES;
6135                 }
6136                 /* Only initialized buffer on stack is allowed to be accessed
6137                  * with variable offset. With uninitialized buffer it's hard to
6138                  * guarantee that whole memory is marked as initialized on
6139                  * helper return since specific bounds are unknown what may
6140                  * cause uninitialized stack leaking.
6141                  */
6142                 if (meta && meta->raw_mode)
6143                         meta = NULL;
6144
6145                 min_off = reg->smin_value + off;
6146                 max_off = reg->smax_value + off;
6147         }
6148
6149         if (meta && meta->raw_mode) {
6150                 /* Ensure we won't be overwriting dynptrs when simulating byte
6151                  * by byte access in check_helper_call using meta.access_size.
6152                  * This would be a problem if we have a helper in the future
6153                  * which takes:
6154                  *
6155                  *      helper(uninit_mem, len, dynptr)
6156                  *
6157                  * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6158                  * may end up writing to dynptr itself when touching memory from
6159                  * arg 1. This can be relaxed on a case by case basis for known
6160                  * safe cases, but reject due to the possibilitiy of aliasing by
6161                  * default.
6162                  */
6163                 for (i = min_off; i < max_off + access_size; i++) {
6164                         int stack_off = -i - 1;
6165
6166                         spi = __get_spi(i);
6167                         /* raw_mode may write past allocated_stack */
6168                         if (state->allocated_stack <= stack_off)
6169                                 continue;
6170                         if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6171                                 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6172                                 return -EACCES;
6173                         }
6174                 }
6175                 meta->access_size = access_size;
6176                 meta->regno = regno;
6177                 return 0;
6178         }
6179
6180         for (i = min_off; i < max_off + access_size; i++) {
6181                 u8 *stype;
6182
6183                 slot = -i - 1;
6184                 spi = slot / BPF_REG_SIZE;
6185                 if (state->allocated_stack <= slot)
6186                         goto err;
6187                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6188                 if (*stype == STACK_MISC)
6189                         goto mark;
6190                 if ((*stype == STACK_ZERO) ||
6191                     (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6192                         if (clobber) {
6193                                 /* helper can write anything into the stack */
6194                                 *stype = STACK_MISC;
6195                         }
6196                         goto mark;
6197                 }
6198
6199                 if (is_spilled_reg(&state->stack[spi]) &&
6200                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6201                      env->allow_ptr_leaks)) {
6202                         if (clobber) {
6203                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6204                                 for (j = 0; j < BPF_REG_SIZE; j++)
6205                                         scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6206                         }
6207                         goto mark;
6208                 }
6209
6210 err:
6211                 if (tnum_is_const(reg->var_off)) {
6212                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6213                                 err_extra, regno, min_off, i - min_off, access_size);
6214                 } else {
6215                         char tn_buf[48];
6216
6217                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6218                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6219                                 err_extra, regno, tn_buf, i - min_off, access_size);
6220                 }
6221                 return -EACCES;
6222 mark:
6223                 /* reading any byte out of 8-byte 'spill_slot' will cause
6224                  * the whole slot to be marked as 'read'
6225                  */
6226                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
6227                               state->stack[spi].spilled_ptr.parent,
6228                               REG_LIVE_READ64);
6229                 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6230                  * be sure that whether stack slot is written to or not. Hence,
6231                  * we must still conservatively propagate reads upwards even if
6232                  * helper may write to the entire memory range.
6233                  */
6234         }
6235         return update_stack_depth(env, state, min_off);
6236 }
6237
6238 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6239                                    int access_size, bool zero_size_allowed,
6240                                    struct bpf_call_arg_meta *meta)
6241 {
6242         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6243         u32 *max_access;
6244
6245         switch (base_type(reg->type)) {
6246         case PTR_TO_PACKET:
6247         case PTR_TO_PACKET_META:
6248                 return check_packet_access(env, regno, reg->off, access_size,
6249                                            zero_size_allowed);
6250         case PTR_TO_MAP_KEY:
6251                 if (meta && meta->raw_mode) {
6252                         verbose(env, "R%d cannot write into %s\n", regno,
6253                                 reg_type_str(env, reg->type));
6254                         return -EACCES;
6255                 }
6256                 return check_mem_region_access(env, regno, reg->off, access_size,
6257                                                reg->map_ptr->key_size, false);
6258         case PTR_TO_MAP_VALUE:
6259                 if (check_map_access_type(env, regno, reg->off, access_size,
6260                                           meta && meta->raw_mode ? BPF_WRITE :
6261                                           BPF_READ))
6262                         return -EACCES;
6263                 return check_map_access(env, regno, reg->off, access_size,
6264                                         zero_size_allowed, ACCESS_HELPER);
6265         case PTR_TO_MEM:
6266                 if (type_is_rdonly_mem(reg->type)) {
6267                         if (meta && meta->raw_mode) {
6268                                 verbose(env, "R%d cannot write into %s\n", regno,
6269                                         reg_type_str(env, reg->type));
6270                                 return -EACCES;
6271                         }
6272                 }
6273                 return check_mem_region_access(env, regno, reg->off,
6274                                                access_size, reg->mem_size,
6275                                                zero_size_allowed);
6276         case PTR_TO_BUF:
6277                 if (type_is_rdonly_mem(reg->type)) {
6278                         if (meta && meta->raw_mode) {
6279                                 verbose(env, "R%d cannot write into %s\n", regno,
6280                                         reg_type_str(env, reg->type));
6281                                 return -EACCES;
6282                         }
6283
6284                         max_access = &env->prog->aux->max_rdonly_access;
6285                 } else {
6286                         max_access = &env->prog->aux->max_rdwr_access;
6287                 }
6288                 return check_buffer_access(env, reg, regno, reg->off,
6289                                            access_size, zero_size_allowed,
6290                                            max_access);
6291         case PTR_TO_STACK:
6292                 return check_stack_range_initialized(
6293                                 env,
6294                                 regno, reg->off, access_size,
6295                                 zero_size_allowed, ACCESS_HELPER, meta);
6296         case PTR_TO_BTF_ID:
6297                 return check_ptr_to_btf_access(env, regs, regno, reg->off,
6298                                                access_size, BPF_READ, -1);
6299         case PTR_TO_CTX:
6300                 /* in case the function doesn't know how to access the context,
6301                  * (because we are in a program of type SYSCALL for example), we
6302                  * can not statically check its size.
6303                  * Dynamically check it now.
6304                  */
6305                 if (!env->ops->convert_ctx_access) {
6306                         enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
6307                         int offset = access_size - 1;
6308
6309                         /* Allow zero-byte read from PTR_TO_CTX */
6310                         if (access_size == 0)
6311                                 return zero_size_allowed ? 0 : -EACCES;
6312
6313                         return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
6314                                                 atype, -1, false);
6315                 }
6316
6317                 fallthrough;
6318         default: /* scalar_value or invalid ptr */
6319                 /* Allow zero-byte read from NULL, regardless of pointer type */
6320                 if (zero_size_allowed && access_size == 0 &&
6321                     register_is_null(reg))
6322                         return 0;
6323
6324                 verbose(env, "R%d type=%s ", regno,
6325                         reg_type_str(env, reg->type));
6326                 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
6327                 return -EACCES;
6328         }
6329 }
6330
6331 static int check_mem_size_reg(struct bpf_verifier_env *env,
6332                               struct bpf_reg_state *reg, u32 regno,
6333                               bool zero_size_allowed,
6334                               struct bpf_call_arg_meta *meta)
6335 {
6336         int err;
6337
6338         /* This is used to refine r0 return value bounds for helpers
6339          * that enforce this value as an upper bound on return values.
6340          * See do_refine_retval_range() for helpers that can refine
6341          * the return value. C type of helper is u32 so we pull register
6342          * bound from umax_value however, if negative verifier errors
6343          * out. Only upper bounds can be learned because retval is an
6344          * int type and negative retvals are allowed.
6345          */
6346         meta->msize_max_value = reg->umax_value;
6347
6348         /* The register is SCALAR_VALUE; the access check
6349          * happens using its boundaries.
6350          */
6351         if (!tnum_is_const(reg->var_off))
6352                 /* For unprivileged variable accesses, disable raw
6353                  * mode so that the program is required to
6354                  * initialize all the memory that the helper could
6355                  * just partially fill up.
6356                  */
6357                 meta = NULL;
6358
6359         if (reg->smin_value < 0) {
6360                 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
6361                         regno);
6362                 return -EACCES;
6363         }
6364
6365         if (reg->umin_value == 0) {
6366                 err = check_helper_mem_access(env, regno - 1, 0,
6367                                               zero_size_allowed,
6368                                               meta);
6369                 if (err)
6370                         return err;
6371         }
6372
6373         if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
6374                 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
6375                         regno);
6376                 return -EACCES;
6377         }
6378         err = check_helper_mem_access(env, regno - 1,
6379                                       reg->umax_value,
6380                                       zero_size_allowed, meta);
6381         if (!err)
6382                 err = mark_chain_precision(env, regno);
6383         return err;
6384 }
6385
6386 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6387                    u32 regno, u32 mem_size)
6388 {
6389         bool may_be_null = type_may_be_null(reg->type);
6390         struct bpf_reg_state saved_reg;
6391         struct bpf_call_arg_meta meta;
6392         int err;
6393
6394         if (register_is_null(reg))
6395                 return 0;
6396
6397         memset(&meta, 0, sizeof(meta));
6398         /* Assuming that the register contains a value check if the memory
6399          * access is safe. Temporarily save and restore the register's state as
6400          * the conversion shouldn't be visible to a caller.
6401          */
6402         if (may_be_null) {
6403                 saved_reg = *reg;
6404                 mark_ptr_not_null_reg(reg);
6405         }
6406
6407         err = check_helper_mem_access(env, regno, mem_size, true, &meta);
6408         /* Check access for BPF_WRITE */
6409         meta.raw_mode = true;
6410         err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
6411
6412         if (may_be_null)
6413                 *reg = saved_reg;
6414
6415         return err;
6416 }
6417
6418 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
6419                                     u32 regno)
6420 {
6421         struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
6422         bool may_be_null = type_may_be_null(mem_reg->type);
6423         struct bpf_reg_state saved_reg;
6424         struct bpf_call_arg_meta meta;
6425         int err;
6426
6427         WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
6428
6429         memset(&meta, 0, sizeof(meta));
6430
6431         if (may_be_null) {
6432                 saved_reg = *mem_reg;
6433                 mark_ptr_not_null_reg(mem_reg);
6434         }
6435
6436         err = check_mem_size_reg(env, reg, regno, true, &meta);
6437         /* Check access for BPF_WRITE */
6438         meta.raw_mode = true;
6439         err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
6440
6441         if (may_be_null)
6442                 *mem_reg = saved_reg;
6443         return err;
6444 }
6445
6446 /* Implementation details:
6447  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
6448  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
6449  * Two bpf_map_lookups (even with the same key) will have different reg->id.
6450  * Two separate bpf_obj_new will also have different reg->id.
6451  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
6452  * clears reg->id after value_or_null->value transition, since the verifier only
6453  * cares about the range of access to valid map value pointer and doesn't care
6454  * about actual address of the map element.
6455  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
6456  * reg->id > 0 after value_or_null->value transition. By doing so
6457  * two bpf_map_lookups will be considered two different pointers that
6458  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
6459  * returned from bpf_obj_new.
6460  * The verifier allows taking only one bpf_spin_lock at a time to avoid
6461  * dead-locks.
6462  * Since only one bpf_spin_lock is allowed the checks are simpler than
6463  * reg_is_refcounted() logic. The verifier needs to remember only
6464  * one spin_lock instead of array of acquired_refs.
6465  * cur_state->active_lock remembers which map value element or allocated
6466  * object got locked and clears it after bpf_spin_unlock.
6467  */
6468 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
6469                              bool is_lock)
6470 {
6471         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6472         struct bpf_verifier_state *cur = env->cur_state;
6473         bool is_const = tnum_is_const(reg->var_off);
6474         u64 val = reg->var_off.value;
6475         struct bpf_map *map = NULL;
6476         struct btf *btf = NULL;
6477         struct btf_record *rec;
6478
6479         if (!is_const) {
6480                 verbose(env,
6481                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
6482                         regno);
6483                 return -EINVAL;
6484         }
6485         if (reg->type == PTR_TO_MAP_VALUE) {
6486                 map = reg->map_ptr;
6487                 if (!map->btf) {
6488                         verbose(env,
6489                                 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
6490                                 map->name);
6491                         return -EINVAL;
6492                 }
6493         } else {
6494                 btf = reg->btf;
6495         }
6496
6497         rec = reg_btf_record(reg);
6498         if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
6499                 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
6500                         map ? map->name : "kptr");
6501                 return -EINVAL;
6502         }
6503         if (rec->spin_lock_off != val + reg->off) {
6504                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
6505                         val + reg->off, rec->spin_lock_off);
6506                 return -EINVAL;
6507         }
6508         if (is_lock) {
6509                 if (cur->active_lock.ptr) {
6510                         verbose(env,
6511                                 "Locking two bpf_spin_locks are not allowed\n");
6512                         return -EINVAL;
6513                 }
6514                 if (map)
6515                         cur->active_lock.ptr = map;
6516                 else
6517                         cur->active_lock.ptr = btf;
6518                 cur->active_lock.id = reg->id;
6519         } else {
6520                 void *ptr;
6521
6522                 if (map)
6523                         ptr = map;
6524                 else
6525                         ptr = btf;
6526
6527                 if (!cur->active_lock.ptr) {
6528                         verbose(env, "bpf_spin_unlock without taking a lock\n");
6529                         return -EINVAL;
6530                 }
6531                 if (cur->active_lock.ptr != ptr ||
6532                     cur->active_lock.id != reg->id) {
6533                         verbose(env, "bpf_spin_unlock of different lock\n");
6534                         return -EINVAL;
6535                 }
6536
6537                 invalidate_non_owning_refs(env);
6538
6539                 cur->active_lock.ptr = NULL;
6540                 cur->active_lock.id = 0;
6541         }
6542         return 0;
6543 }
6544
6545 static int process_timer_func(struct bpf_verifier_env *env, int regno,
6546                               struct bpf_call_arg_meta *meta)
6547 {
6548         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6549         bool is_const = tnum_is_const(reg->var_off);
6550         struct bpf_map *map = reg->map_ptr;
6551         u64 val = reg->var_off.value;
6552
6553         if (!is_const) {
6554                 verbose(env,
6555                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
6556                         regno);
6557                 return -EINVAL;
6558         }
6559         if (!map->btf) {
6560                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
6561                         map->name);
6562                 return -EINVAL;
6563         }
6564         if (!btf_record_has_field(map->record, BPF_TIMER)) {
6565                 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
6566                 return -EINVAL;
6567         }
6568         if (map->record->timer_off != val + reg->off) {
6569                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
6570                         val + reg->off, map->record->timer_off);
6571                 return -EINVAL;
6572         }
6573         if (meta->map_ptr) {
6574                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
6575                 return -EFAULT;
6576         }
6577         meta->map_uid = reg->map_uid;
6578         meta->map_ptr = map;
6579         return 0;
6580 }
6581
6582 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
6583                              struct bpf_call_arg_meta *meta)
6584 {
6585         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6586         struct bpf_map *map_ptr = reg->map_ptr;
6587         struct btf_field *kptr_field;
6588         u32 kptr_off;
6589
6590         if (!tnum_is_const(reg->var_off)) {
6591                 verbose(env,
6592                         "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
6593                         regno);
6594                 return -EINVAL;
6595         }
6596         if (!map_ptr->btf) {
6597                 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
6598                         map_ptr->name);
6599                 return -EINVAL;
6600         }
6601         if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
6602                 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
6603                 return -EINVAL;
6604         }
6605
6606         meta->map_ptr = map_ptr;
6607         kptr_off = reg->off + reg->var_off.value;
6608         kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
6609         if (!kptr_field) {
6610                 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
6611                 return -EACCES;
6612         }
6613         if (kptr_field->type != BPF_KPTR_REF) {
6614                 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
6615                 return -EACCES;
6616         }
6617         meta->kptr_field = kptr_field;
6618         return 0;
6619 }
6620
6621 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
6622  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
6623  *
6624  * In both cases we deal with the first 8 bytes, but need to mark the next 8
6625  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
6626  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
6627  *
6628  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
6629  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
6630  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
6631  * mutate the view of the dynptr and also possibly destroy it. In the latter
6632  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
6633  * memory that dynptr points to.
6634  *
6635  * The verifier will keep track both levels of mutation (bpf_dynptr's in
6636  * reg->type and the memory's in reg->dynptr.type), but there is no support for
6637  * readonly dynptr view yet, hence only the first case is tracked and checked.
6638  *
6639  * This is consistent with how C applies the const modifier to a struct object,
6640  * where the pointer itself inside bpf_dynptr becomes const but not what it
6641  * points to.
6642  *
6643  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
6644  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
6645  */
6646 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
6647                                enum bpf_arg_type arg_type)
6648 {
6649         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6650         int err;
6651
6652         /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
6653          * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
6654          */
6655         if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
6656                 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
6657                 return -EFAULT;
6658         }
6659
6660         /*  MEM_UNINIT - Points to memory that is an appropriate candidate for
6661          *               constructing a mutable bpf_dynptr object.
6662          *
6663          *               Currently, this is only possible with PTR_TO_STACK
6664          *               pointing to a region of at least 16 bytes which doesn't
6665          *               contain an existing bpf_dynptr.
6666          *
6667          *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
6668          *               mutated or destroyed. However, the memory it points to
6669          *               may be mutated.
6670          *
6671          *  None       - Points to a initialized dynptr that can be mutated and
6672          *               destroyed, including mutation of the memory it points
6673          *               to.
6674          */
6675         if (arg_type & MEM_UNINIT) {
6676                 int i;
6677
6678                 if (!is_dynptr_reg_valid_uninit(env, reg)) {
6679                         verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6680                         return -EINVAL;
6681                 }
6682
6683                 /* we write BPF_DW bits (8 bytes) at a time */
6684                 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
6685                         err = check_mem_access(env, insn_idx, regno,
6686                                                i, BPF_DW, BPF_WRITE, -1, false);
6687                         if (err)
6688                                 return err;
6689                 }
6690
6691                 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx);
6692         } else /* MEM_RDONLY and None case from above */ {
6693                 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
6694                 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
6695                         verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
6696                         return -EINVAL;
6697                 }
6698
6699                 if (!is_dynptr_reg_valid_init(env, reg)) {
6700                         verbose(env,
6701                                 "Expected an initialized dynptr as arg #%d\n",
6702                                 regno);
6703                         return -EINVAL;
6704                 }
6705
6706                 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
6707                 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
6708                         verbose(env,
6709                                 "Expected a dynptr of type %s as arg #%d\n",
6710                                 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
6711                         return -EINVAL;
6712                 }
6713
6714                 err = mark_dynptr_read(env, reg);
6715         }
6716         return err;
6717 }
6718
6719 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
6720 {
6721         struct bpf_func_state *state = func(env, reg);
6722
6723         return state->stack[spi].spilled_ptr.ref_obj_id;
6724 }
6725
6726 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
6727 {
6728         return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
6729 }
6730
6731 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
6732 {
6733         return meta->kfunc_flags & KF_ITER_NEW;
6734 }
6735
6736 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
6737 {
6738         return meta->kfunc_flags & KF_ITER_NEXT;
6739 }
6740
6741 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
6742 {
6743         return meta->kfunc_flags & KF_ITER_DESTROY;
6744 }
6745
6746 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
6747 {
6748         /* btf_check_iter_kfuncs() guarantees that first argument of any iter
6749          * kfunc is iter state pointer
6750          */
6751         return arg == 0 && is_iter_kfunc(meta);
6752 }
6753
6754 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
6755                             struct bpf_kfunc_call_arg_meta *meta)
6756 {
6757         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6758         const struct btf_type *t;
6759         const struct btf_param *arg;
6760         int spi, err, i, nr_slots;
6761         u32 btf_id;
6762
6763         /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
6764         arg = &btf_params(meta->func_proto)[0];
6765         t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);        /* PTR */
6766         t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);       /* STRUCT */
6767         nr_slots = t->size / BPF_REG_SIZE;
6768
6769         if (is_iter_new_kfunc(meta)) {
6770                 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
6771                 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
6772                         verbose(env, "expected uninitialized iter_%s as arg #%d\n",
6773                                 iter_type_str(meta->btf, btf_id), regno);
6774                         return -EINVAL;
6775                 }
6776
6777                 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
6778                         err = check_mem_access(env, insn_idx, regno,
6779                                                i, BPF_DW, BPF_WRITE, -1, false);
6780                         if (err)
6781                                 return err;
6782                 }
6783
6784                 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
6785                 if (err)
6786                         return err;
6787         } else {
6788                 /* iter_next() or iter_destroy() expect initialized iter state*/
6789                 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
6790                         verbose(env, "expected an initialized iter_%s as arg #%d\n",
6791                                 iter_type_str(meta->btf, btf_id), regno);
6792                         return -EINVAL;
6793                 }
6794
6795                 spi = iter_get_spi(env, reg, nr_slots);
6796                 if (spi < 0)
6797                         return spi;
6798
6799                 err = mark_iter_read(env, reg, spi, nr_slots);
6800                 if (err)
6801                         return err;
6802
6803                 /* remember meta->iter info for process_iter_next_call() */
6804                 meta->iter.spi = spi;
6805                 meta->iter.frameno = reg->frameno;
6806                 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
6807
6808                 if (is_iter_destroy_kfunc(meta)) {
6809                         err = unmark_stack_slots_iter(env, reg, nr_slots);
6810                         if (err)
6811                                 return err;
6812                 }
6813         }
6814
6815         return 0;
6816 }
6817
6818 /* process_iter_next_call() is called when verifier gets to iterator's next
6819  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
6820  * to it as just "iter_next()" in comments below.
6821  *
6822  * BPF verifier relies on a crucial contract for any iter_next()
6823  * implementation: it should *eventually* return NULL, and once that happens
6824  * it should keep returning NULL. That is, once iterator exhausts elements to
6825  * iterate, it should never reset or spuriously return new elements.
6826  *
6827  * With the assumption of such contract, process_iter_next_call() simulates
6828  * a fork in the verifier state to validate loop logic correctness and safety
6829  * without having to simulate infinite amount of iterations.
6830  *
6831  * In current state, we first assume that iter_next() returned NULL and
6832  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
6833  * conditions we should not form an infinite loop and should eventually reach
6834  * exit.
6835  *
6836  * Besides that, we also fork current state and enqueue it for later
6837  * verification. In a forked state we keep iterator state as ACTIVE
6838  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
6839  * also bump iteration depth to prevent erroneous infinite loop detection
6840  * later on (see iter_active_depths_differ() comment for details). In this
6841  * state we assume that we'll eventually loop back to another iter_next()
6842  * calls (it could be in exactly same location or in some other instruction,
6843  * it doesn't matter, we don't make any unnecessary assumptions about this,
6844  * everything revolves around iterator state in a stack slot, not which
6845  * instruction is calling iter_next()). When that happens, we either will come
6846  * to iter_next() with equivalent state and can conclude that next iteration
6847  * will proceed in exactly the same way as we just verified, so it's safe to
6848  * assume that loop converges. If not, we'll go on another iteration
6849  * simulation with a different input state, until all possible starting states
6850  * are validated or we reach maximum number of instructions limit.
6851  *
6852  * This way, we will either exhaustively discover all possible input states
6853  * that iterator loop can start with and eventually will converge, or we'll
6854  * effectively regress into bounded loop simulation logic and either reach
6855  * maximum number of instructions if loop is not provably convergent, or there
6856  * is some statically known limit on number of iterations (e.g., if there is
6857  * an explicit `if n > 100 then break;` statement somewhere in the loop).
6858  *
6859  * One very subtle but very important aspect is that we *always* simulate NULL
6860  * condition first (as the current state) before we simulate non-NULL case.
6861  * This has to do with intricacies of scalar precision tracking. By simulating
6862  * "exit condition" of iter_next() returning NULL first, we make sure all the
6863  * relevant precision marks *that will be set **after** we exit iterator loop*
6864  * are propagated backwards to common parent state of NULL and non-NULL
6865  * branches. Thanks to that, state equivalence checks done later in forked
6866  * state, when reaching iter_next() for ACTIVE iterator, can assume that
6867  * precision marks are finalized and won't change. Because simulating another
6868  * ACTIVE iterator iteration won't change them (because given same input
6869  * states we'll end up with exactly same output states which we are currently
6870  * comparing; and verification after the loop already propagated back what
6871  * needs to be **additionally** tracked as precise). It's subtle, grok
6872  * precision tracking for more intuitive understanding.
6873  */
6874 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
6875                                   struct bpf_kfunc_call_arg_meta *meta)
6876 {
6877         struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
6878         struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
6879         struct bpf_reg_state *cur_iter, *queued_iter;
6880         int iter_frameno = meta->iter.frameno;
6881         int iter_spi = meta->iter.spi;
6882
6883         BTF_TYPE_EMIT(struct bpf_iter);
6884
6885         cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
6886
6887         if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
6888             cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
6889                 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
6890                         cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
6891                 return -EFAULT;
6892         }
6893
6894         if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
6895                 /* branch out active iter state */
6896                 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
6897                 if (!queued_st)
6898                         return -ENOMEM;
6899
6900                 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
6901                 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
6902                 queued_iter->iter.depth++;
6903
6904                 queued_fr = queued_st->frame[queued_st->curframe];
6905                 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
6906         }
6907
6908         /* switch to DRAINED state, but keep the depth unchanged */
6909         /* mark current iter state as drained and assume returned NULL */
6910         cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
6911         __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
6912
6913         return 0;
6914 }
6915
6916 static bool arg_type_is_mem_size(enum bpf_arg_type type)
6917 {
6918         return type == ARG_CONST_SIZE ||
6919                type == ARG_CONST_SIZE_OR_ZERO;
6920 }
6921
6922 static bool arg_type_is_release(enum bpf_arg_type type)
6923 {
6924         return type & OBJ_RELEASE;
6925 }
6926
6927 static bool arg_type_is_dynptr(enum bpf_arg_type type)
6928 {
6929         return base_type(type) == ARG_PTR_TO_DYNPTR;
6930 }
6931
6932 static int int_ptr_type_to_size(enum bpf_arg_type type)
6933 {
6934         if (type == ARG_PTR_TO_INT)
6935                 return sizeof(u32);
6936         else if (type == ARG_PTR_TO_LONG)
6937                 return sizeof(u64);
6938
6939         return -EINVAL;
6940 }
6941
6942 static int resolve_map_arg_type(struct bpf_verifier_env *env,
6943                                  const struct bpf_call_arg_meta *meta,
6944                                  enum bpf_arg_type *arg_type)
6945 {
6946         if (!meta->map_ptr) {
6947                 /* kernel subsystem misconfigured verifier */
6948                 verbose(env, "invalid map_ptr to access map->type\n");
6949                 return -EACCES;
6950         }
6951
6952         switch (meta->map_ptr->map_type) {
6953         case BPF_MAP_TYPE_SOCKMAP:
6954         case BPF_MAP_TYPE_SOCKHASH:
6955                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6956                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
6957                 } else {
6958                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
6959                         return -EINVAL;
6960                 }
6961                 break;
6962         case BPF_MAP_TYPE_BLOOM_FILTER:
6963                 if (meta->func_id == BPF_FUNC_map_peek_elem)
6964                         *arg_type = ARG_PTR_TO_MAP_VALUE;
6965                 break;
6966         default:
6967                 break;
6968         }
6969         return 0;
6970 }
6971
6972 struct bpf_reg_types {
6973         const enum bpf_reg_type types[10];
6974         u32 *btf_id;
6975 };
6976
6977 static const struct bpf_reg_types sock_types = {
6978         .types = {
6979                 PTR_TO_SOCK_COMMON,
6980                 PTR_TO_SOCKET,
6981                 PTR_TO_TCP_SOCK,
6982                 PTR_TO_XDP_SOCK,
6983         },
6984 };
6985
6986 #ifdef CONFIG_NET
6987 static const struct bpf_reg_types btf_id_sock_common_types = {
6988         .types = {
6989                 PTR_TO_SOCK_COMMON,
6990                 PTR_TO_SOCKET,
6991                 PTR_TO_TCP_SOCK,
6992                 PTR_TO_XDP_SOCK,
6993                 PTR_TO_BTF_ID,
6994                 PTR_TO_BTF_ID | PTR_TRUSTED,
6995         },
6996         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6997 };
6998 #endif
6999
7000 static const struct bpf_reg_types mem_types = {
7001         .types = {
7002                 PTR_TO_STACK,
7003                 PTR_TO_PACKET,
7004                 PTR_TO_PACKET_META,
7005                 PTR_TO_MAP_KEY,
7006                 PTR_TO_MAP_VALUE,
7007                 PTR_TO_MEM,
7008                 PTR_TO_MEM | MEM_RINGBUF,
7009                 PTR_TO_BUF,
7010                 PTR_TO_BTF_ID | PTR_TRUSTED,
7011         },
7012 };
7013
7014 static const struct bpf_reg_types int_ptr_types = {
7015         .types = {
7016                 PTR_TO_STACK,
7017                 PTR_TO_PACKET,
7018                 PTR_TO_PACKET_META,
7019                 PTR_TO_MAP_KEY,
7020                 PTR_TO_MAP_VALUE,
7021         },
7022 };
7023
7024 static const struct bpf_reg_types spin_lock_types = {
7025         .types = {
7026                 PTR_TO_MAP_VALUE,
7027                 PTR_TO_BTF_ID | MEM_ALLOC,
7028         }
7029 };
7030
7031 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7032 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7033 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7034 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7035 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7036 static const struct bpf_reg_types btf_ptr_types = {
7037         .types = {
7038                 PTR_TO_BTF_ID,
7039                 PTR_TO_BTF_ID | PTR_TRUSTED,
7040                 PTR_TO_BTF_ID | MEM_RCU,
7041         },
7042 };
7043 static const struct bpf_reg_types percpu_btf_ptr_types = {
7044         .types = {
7045                 PTR_TO_BTF_ID | MEM_PERCPU,
7046                 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7047         }
7048 };
7049 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7050 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7051 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7052 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7053 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7054 static const struct bpf_reg_types dynptr_types = {
7055         .types = {
7056                 PTR_TO_STACK,
7057                 CONST_PTR_TO_DYNPTR,
7058         }
7059 };
7060
7061 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7062         [ARG_PTR_TO_MAP_KEY]            = &mem_types,
7063         [ARG_PTR_TO_MAP_VALUE]          = &mem_types,
7064         [ARG_CONST_SIZE]                = &scalar_types,
7065         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
7066         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
7067         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
7068         [ARG_PTR_TO_CTX]                = &context_types,
7069         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
7070 #ifdef CONFIG_NET
7071         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
7072 #endif
7073         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
7074         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
7075         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
7076         [ARG_PTR_TO_MEM]                = &mem_types,
7077         [ARG_PTR_TO_RINGBUF_MEM]        = &ringbuf_mem_types,
7078         [ARG_PTR_TO_INT]                = &int_ptr_types,
7079         [ARG_PTR_TO_LONG]               = &int_ptr_types,
7080         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
7081         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
7082         [ARG_PTR_TO_STACK]              = &stack_ptr_types,
7083         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
7084         [ARG_PTR_TO_TIMER]              = &timer_types,
7085         [ARG_PTR_TO_KPTR]               = &kptr_types,
7086         [ARG_PTR_TO_DYNPTR]             = &dynptr_types,
7087 };
7088
7089 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7090                           enum bpf_arg_type arg_type,
7091                           const u32 *arg_btf_id,
7092                           struct bpf_call_arg_meta *meta)
7093 {
7094         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7095         enum bpf_reg_type expected, type = reg->type;
7096         const struct bpf_reg_types *compatible;
7097         int i, j;
7098
7099         compatible = compatible_reg_types[base_type(arg_type)];
7100         if (!compatible) {
7101                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7102                 return -EFAULT;
7103         }
7104
7105         /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7106          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7107          *
7108          * Same for MAYBE_NULL:
7109          *
7110          * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7111          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7112          *
7113          * Therefore we fold these flags depending on the arg_type before comparison.
7114          */
7115         if (arg_type & MEM_RDONLY)
7116                 type &= ~MEM_RDONLY;
7117         if (arg_type & PTR_MAYBE_NULL)
7118                 type &= ~PTR_MAYBE_NULL;
7119
7120         if (meta->func_id == BPF_FUNC_kptr_xchg && type & MEM_ALLOC)
7121                 type &= ~MEM_ALLOC;
7122
7123         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7124                 expected = compatible->types[i];
7125                 if (expected == NOT_INIT)
7126                         break;
7127
7128                 if (type == expected)
7129                         goto found;
7130         }
7131
7132         verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7133         for (j = 0; j + 1 < i; j++)
7134                 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7135         verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7136         return -EACCES;
7137
7138 found:
7139         if (base_type(reg->type) != PTR_TO_BTF_ID)
7140                 return 0;
7141
7142         if (compatible == &mem_types) {
7143                 if (!(arg_type & MEM_RDONLY)) {
7144                         verbose(env,
7145                                 "%s() may write into memory pointed by R%d type=%s\n",
7146                                 func_id_name(meta->func_id),
7147                                 regno, reg_type_str(env, reg->type));
7148                         return -EACCES;
7149                 }
7150                 return 0;
7151         }
7152
7153         switch ((int)reg->type) {
7154         case PTR_TO_BTF_ID:
7155         case PTR_TO_BTF_ID | PTR_TRUSTED:
7156         case PTR_TO_BTF_ID | MEM_RCU:
7157         case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7158         case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7159         {
7160                 /* For bpf_sk_release, it needs to match against first member
7161                  * 'struct sock_common', hence make an exception for it. This
7162                  * allows bpf_sk_release to work for multiple socket types.
7163                  */
7164                 bool strict_type_match = arg_type_is_release(arg_type) &&
7165                                          meta->func_id != BPF_FUNC_sk_release;
7166
7167                 if (type_may_be_null(reg->type) &&
7168                     (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7169                         verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7170                         return -EACCES;
7171                 }
7172
7173                 if (!arg_btf_id) {
7174                         if (!compatible->btf_id) {
7175                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7176                                 return -EFAULT;
7177                         }
7178                         arg_btf_id = compatible->btf_id;
7179                 }
7180
7181                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
7182                         if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7183                                 return -EACCES;
7184                 } else {
7185                         if (arg_btf_id == BPF_PTR_POISON) {
7186                                 verbose(env, "verifier internal error:");
7187                                 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7188                                         regno);
7189                                 return -EACCES;
7190                         }
7191
7192                         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7193                                                   btf_vmlinux, *arg_btf_id,
7194                                                   strict_type_match)) {
7195                                 verbose(env, "R%d is of type %s but %s is expected\n",
7196                                         regno, btf_type_name(reg->btf, reg->btf_id),
7197                                         btf_type_name(btf_vmlinux, *arg_btf_id));
7198                                 return -EACCES;
7199                         }
7200                 }
7201                 break;
7202         }
7203         case PTR_TO_BTF_ID | MEM_ALLOC:
7204                 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7205                     meta->func_id != BPF_FUNC_kptr_xchg) {
7206                         verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7207                         return -EFAULT;
7208                 }
7209                 /* Handled by helper specific checks */
7210                 break;
7211         case PTR_TO_BTF_ID | MEM_PERCPU:
7212         case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7213                 /* Handled by helper specific checks */
7214                 break;
7215         default:
7216                 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7217                 return -EFAULT;
7218         }
7219         return 0;
7220 }
7221
7222 static struct btf_field *
7223 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7224 {
7225         struct btf_field *field;
7226         struct btf_record *rec;
7227
7228         rec = reg_btf_record(reg);
7229         if (!rec)
7230                 return NULL;
7231
7232         field = btf_record_find(rec, off, fields);
7233         if (!field)
7234                 return NULL;
7235
7236         return field;
7237 }
7238
7239 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7240                            const struct bpf_reg_state *reg, int regno,
7241                            enum bpf_arg_type arg_type)
7242 {
7243         u32 type = reg->type;
7244
7245         /* When referenced register is passed to release function, its fixed
7246          * offset must be 0.
7247          *
7248          * We will check arg_type_is_release reg has ref_obj_id when storing
7249          * meta->release_regno.
7250          */
7251         if (arg_type_is_release(arg_type)) {
7252                 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7253                  * may not directly point to the object being released, but to
7254                  * dynptr pointing to such object, which might be at some offset
7255                  * on the stack. In that case, we simply to fallback to the
7256                  * default handling.
7257                  */
7258                 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7259                         return 0;
7260
7261                 if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
7262                         if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
7263                                 return __check_ptr_off_reg(env, reg, regno, true);
7264
7265                         verbose(env, "R%d must have zero offset when passed to release func\n",
7266                                 regno);
7267                         verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
7268                                 btf_type_name(reg->btf, reg->btf_id), reg->off);
7269                         return -EINVAL;
7270                 }
7271
7272                 /* Doing check_ptr_off_reg check for the offset will catch this
7273                  * because fixed_off_ok is false, but checking here allows us
7274                  * to give the user a better error message.
7275                  */
7276                 if (reg->off) {
7277                         verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7278                                 regno);
7279                         return -EINVAL;
7280                 }
7281                 return __check_ptr_off_reg(env, reg, regno, false);
7282         }
7283
7284         switch (type) {
7285         /* Pointer types where both fixed and variable offset is explicitly allowed: */
7286         case PTR_TO_STACK:
7287         case PTR_TO_PACKET:
7288         case PTR_TO_PACKET_META:
7289         case PTR_TO_MAP_KEY:
7290         case PTR_TO_MAP_VALUE:
7291         case PTR_TO_MEM:
7292         case PTR_TO_MEM | MEM_RDONLY:
7293         case PTR_TO_MEM | MEM_RINGBUF:
7294         case PTR_TO_BUF:
7295         case PTR_TO_BUF | MEM_RDONLY:
7296         case SCALAR_VALUE:
7297                 return 0;
7298         /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
7299          * fixed offset.
7300          */
7301         case PTR_TO_BTF_ID:
7302         case PTR_TO_BTF_ID | MEM_ALLOC:
7303         case PTR_TO_BTF_ID | PTR_TRUSTED:
7304         case PTR_TO_BTF_ID | MEM_RCU:
7305         case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
7306                 /* When referenced PTR_TO_BTF_ID is passed to release function,
7307                  * its fixed offset must be 0. In the other cases, fixed offset
7308                  * can be non-zero. This was already checked above. So pass
7309                  * fixed_off_ok as true to allow fixed offset for all other
7310                  * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
7311                  * still need to do checks instead of returning.
7312                  */
7313                 return __check_ptr_off_reg(env, reg, regno, true);
7314         default:
7315                 return __check_ptr_off_reg(env, reg, regno, false);
7316         }
7317 }
7318
7319 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
7320                                                 const struct bpf_func_proto *fn,
7321                                                 struct bpf_reg_state *regs)
7322 {
7323         struct bpf_reg_state *state = NULL;
7324         int i;
7325
7326         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
7327                 if (arg_type_is_dynptr(fn->arg_type[i])) {
7328                         if (state) {
7329                                 verbose(env, "verifier internal error: multiple dynptr args\n");
7330                                 return NULL;
7331                         }
7332                         state = &regs[BPF_REG_1 + i];
7333                 }
7334
7335         if (!state)
7336                 verbose(env, "verifier internal error: no dynptr arg found\n");
7337
7338         return state;
7339 }
7340
7341 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7342 {
7343         struct bpf_func_state *state = func(env, reg);
7344         int spi;
7345
7346         if (reg->type == CONST_PTR_TO_DYNPTR)
7347                 return reg->id;
7348         spi = dynptr_get_spi(env, reg);
7349         if (spi < 0)
7350                 return spi;
7351         return state->stack[spi].spilled_ptr.id;
7352 }
7353
7354 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
7355 {
7356         struct bpf_func_state *state = func(env, reg);
7357         int spi;
7358
7359         if (reg->type == CONST_PTR_TO_DYNPTR)
7360                 return reg->ref_obj_id;
7361         spi = dynptr_get_spi(env, reg);
7362         if (spi < 0)
7363                 return spi;
7364         return state->stack[spi].spilled_ptr.ref_obj_id;
7365 }
7366
7367 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
7368                                             struct bpf_reg_state *reg)
7369 {
7370         struct bpf_func_state *state = func(env, reg);
7371         int spi;
7372
7373         if (reg->type == CONST_PTR_TO_DYNPTR)
7374                 return reg->dynptr.type;
7375
7376         spi = __get_spi(reg->off);
7377         if (spi < 0) {
7378                 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
7379                 return BPF_DYNPTR_TYPE_INVALID;
7380         }
7381
7382         return state->stack[spi].spilled_ptr.dynptr.type;
7383 }
7384
7385 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
7386                           struct bpf_call_arg_meta *meta,
7387                           const struct bpf_func_proto *fn,
7388                           int insn_idx)
7389 {
7390         u32 regno = BPF_REG_1 + arg;
7391         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7392         enum bpf_arg_type arg_type = fn->arg_type[arg];
7393         enum bpf_reg_type type = reg->type;
7394         u32 *arg_btf_id = NULL;
7395         int err = 0;
7396
7397         if (arg_type == ARG_DONTCARE)
7398                 return 0;
7399
7400         err = check_reg_arg(env, regno, SRC_OP);
7401         if (err)
7402                 return err;
7403
7404         if (arg_type == ARG_ANYTHING) {
7405                 if (is_pointer_value(env, regno)) {
7406                         verbose(env, "R%d leaks addr into helper function\n",
7407                                 regno);
7408                         return -EACCES;
7409                 }
7410                 return 0;
7411         }
7412
7413         if (type_is_pkt_pointer(type) &&
7414             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
7415                 verbose(env, "helper access to the packet is not allowed\n");
7416                 return -EACCES;
7417         }
7418
7419         if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
7420                 err = resolve_map_arg_type(env, meta, &arg_type);
7421                 if (err)
7422                         return err;
7423         }
7424
7425         if (register_is_null(reg) && type_may_be_null(arg_type))
7426                 /* A NULL register has a SCALAR_VALUE type, so skip
7427                  * type checking.
7428                  */
7429                 goto skip_type_check;
7430
7431         /* arg_btf_id and arg_size are in a union. */
7432         if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
7433             base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
7434                 arg_btf_id = fn->arg_btf_id[arg];
7435
7436         err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
7437         if (err)
7438                 return err;
7439
7440         err = check_func_arg_reg_off(env, reg, regno, arg_type);
7441         if (err)
7442                 return err;
7443
7444 skip_type_check:
7445         if (arg_type_is_release(arg_type)) {
7446                 if (arg_type_is_dynptr(arg_type)) {
7447                         struct bpf_func_state *state = func(env, reg);
7448                         int spi;
7449
7450                         /* Only dynptr created on stack can be released, thus
7451                          * the get_spi and stack state checks for spilled_ptr
7452                          * should only be done before process_dynptr_func for
7453                          * PTR_TO_STACK.
7454                          */
7455                         if (reg->type == PTR_TO_STACK) {
7456                                 spi = dynptr_get_spi(env, reg);
7457                                 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
7458                                         verbose(env, "arg %d is an unacquired reference\n", regno);
7459                                         return -EINVAL;
7460                                 }
7461                         } else {
7462                                 verbose(env, "cannot release unowned const bpf_dynptr\n");
7463                                 return -EINVAL;
7464                         }
7465                 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
7466                         verbose(env, "R%d must be referenced when passed to release function\n",
7467                                 regno);
7468                         return -EINVAL;
7469                 }
7470                 if (meta->release_regno) {
7471                         verbose(env, "verifier internal error: more than one release argument\n");
7472                         return -EFAULT;
7473                 }
7474                 meta->release_regno = regno;
7475         }
7476
7477         if (reg->ref_obj_id) {
7478                 if (meta->ref_obj_id) {
7479                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
7480                                 regno, reg->ref_obj_id,
7481                                 meta->ref_obj_id);
7482                         return -EFAULT;
7483                 }
7484                 meta->ref_obj_id = reg->ref_obj_id;
7485         }
7486
7487         switch (base_type(arg_type)) {
7488         case ARG_CONST_MAP_PTR:
7489                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
7490                 if (meta->map_ptr) {
7491                         /* Use map_uid (which is unique id of inner map) to reject:
7492                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
7493                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
7494                          * if (inner_map1 && inner_map2) {
7495                          *     timer = bpf_map_lookup_elem(inner_map1);
7496                          *     if (timer)
7497                          *         // mismatch would have been allowed
7498                          *         bpf_timer_init(timer, inner_map2);
7499                          * }
7500                          *
7501                          * Comparing map_ptr is enough to distinguish normal and outer maps.
7502                          */
7503                         if (meta->map_ptr != reg->map_ptr ||
7504                             meta->map_uid != reg->map_uid) {
7505                                 verbose(env,
7506                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
7507                                         meta->map_uid, reg->map_uid);
7508                                 return -EINVAL;
7509                         }
7510                 }
7511                 meta->map_ptr = reg->map_ptr;
7512                 meta->map_uid = reg->map_uid;
7513                 break;
7514         case ARG_PTR_TO_MAP_KEY:
7515                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
7516                  * check that [key, key + map->key_size) are within
7517                  * stack limits and initialized
7518                  */
7519                 if (!meta->map_ptr) {
7520                         /* in function declaration map_ptr must come before
7521                          * map_key, so that it's verified and known before
7522                          * we have to check map_key here. Otherwise it means
7523                          * that kernel subsystem misconfigured verifier
7524                          */
7525                         verbose(env, "invalid map_ptr to access map->key\n");
7526                         return -EACCES;
7527                 }
7528                 err = check_helper_mem_access(env, regno,
7529                                               meta->map_ptr->key_size, false,
7530                                               NULL);
7531                 break;
7532         case ARG_PTR_TO_MAP_VALUE:
7533                 if (type_may_be_null(arg_type) && register_is_null(reg))
7534                         return 0;
7535
7536                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
7537                  * check [value, value + map->value_size) validity
7538                  */
7539                 if (!meta->map_ptr) {
7540                         /* kernel subsystem misconfigured verifier */
7541                         verbose(env, "invalid map_ptr to access map->value\n");
7542                         return -EACCES;
7543                 }
7544                 meta->raw_mode = arg_type & MEM_UNINIT;
7545                 err = check_helper_mem_access(env, regno,
7546                                               meta->map_ptr->value_size, false,
7547                                               meta);
7548                 break;
7549         case ARG_PTR_TO_PERCPU_BTF_ID:
7550                 if (!reg->btf_id) {
7551                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
7552                         return -EACCES;
7553                 }
7554                 meta->ret_btf = reg->btf;
7555                 meta->ret_btf_id = reg->btf_id;
7556                 break;
7557         case ARG_PTR_TO_SPIN_LOCK:
7558                 if (in_rbtree_lock_required_cb(env)) {
7559                         verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
7560                         return -EACCES;
7561                 }
7562                 if (meta->func_id == BPF_FUNC_spin_lock) {
7563                         err = process_spin_lock(env, regno, true);
7564                         if (err)
7565                                 return err;
7566                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
7567                         err = process_spin_lock(env, regno, false);
7568                         if (err)
7569                                 return err;
7570                 } else {
7571                         verbose(env, "verifier internal error\n");
7572                         return -EFAULT;
7573                 }
7574                 break;
7575         case ARG_PTR_TO_TIMER:
7576                 err = process_timer_func(env, regno, meta);
7577                 if (err)
7578                         return err;
7579                 break;
7580         case ARG_PTR_TO_FUNC:
7581                 meta->subprogno = reg->subprogno;
7582                 break;
7583         case ARG_PTR_TO_MEM:
7584                 /* The access to this pointer is only checked when we hit the
7585                  * next is_mem_size argument below.
7586                  */
7587                 meta->raw_mode = arg_type & MEM_UNINIT;
7588                 if (arg_type & MEM_FIXED_SIZE) {
7589                         err = check_helper_mem_access(env, regno,
7590                                                       fn->arg_size[arg], false,
7591                                                       meta);
7592                 }
7593                 break;
7594         case ARG_CONST_SIZE:
7595                 err = check_mem_size_reg(env, reg, regno, false, meta);
7596                 break;
7597         case ARG_CONST_SIZE_OR_ZERO:
7598                 err = check_mem_size_reg(env, reg, regno, true, meta);
7599                 break;
7600         case ARG_PTR_TO_DYNPTR:
7601                 err = process_dynptr_func(env, regno, insn_idx, arg_type);
7602                 if (err)
7603                         return err;
7604                 break;
7605         case ARG_CONST_ALLOC_SIZE_OR_ZERO:
7606                 if (!tnum_is_const(reg->var_off)) {
7607                         verbose(env, "R%d is not a known constant'\n",
7608                                 regno);
7609                         return -EACCES;
7610                 }
7611                 meta->mem_size = reg->var_off.value;
7612                 err = mark_chain_precision(env, regno);
7613                 if (err)
7614                         return err;
7615                 break;
7616         case ARG_PTR_TO_INT:
7617         case ARG_PTR_TO_LONG:
7618         {
7619                 int size = int_ptr_type_to_size(arg_type);
7620
7621                 err = check_helper_mem_access(env, regno, size, false, meta);
7622                 if (err)
7623                         return err;
7624                 err = check_ptr_alignment(env, reg, 0, size, true);
7625                 break;
7626         }
7627         case ARG_PTR_TO_CONST_STR:
7628         {
7629                 struct bpf_map *map = reg->map_ptr;
7630                 int map_off;
7631                 u64 map_addr;
7632                 char *str_ptr;
7633
7634                 if (!bpf_map_is_rdonly(map)) {
7635                         verbose(env, "R%d does not point to a readonly map'\n", regno);
7636                         return -EACCES;
7637                 }
7638
7639                 if (!tnum_is_const(reg->var_off)) {
7640                         verbose(env, "R%d is not a constant address'\n", regno);
7641                         return -EACCES;
7642                 }
7643
7644                 if (!map->ops->map_direct_value_addr) {
7645                         verbose(env, "no direct value access support for this map type\n");
7646                         return -EACCES;
7647                 }
7648
7649                 err = check_map_access(env, regno, reg->off,
7650                                        map->value_size - reg->off, false,
7651                                        ACCESS_HELPER);
7652                 if (err)
7653                         return err;
7654
7655                 map_off = reg->off + reg->var_off.value;
7656                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
7657                 if (err) {
7658                         verbose(env, "direct value access on string failed\n");
7659                         return err;
7660                 }
7661
7662                 str_ptr = (char *)(long)(map_addr);
7663                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
7664                         verbose(env, "string is not zero-terminated\n");
7665                         return -EINVAL;
7666                 }
7667                 break;
7668         }
7669         case ARG_PTR_TO_KPTR:
7670                 err = process_kptr_func(env, regno, meta);
7671                 if (err)
7672                         return err;
7673                 break;
7674         }
7675
7676         return err;
7677 }
7678
7679 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
7680 {
7681         enum bpf_attach_type eatype = env->prog->expected_attach_type;
7682         enum bpf_prog_type type = resolve_prog_type(env->prog);
7683
7684         if (func_id != BPF_FUNC_map_update_elem)
7685                 return false;
7686
7687         /* It's not possible to get access to a locked struct sock in these
7688          * contexts, so updating is safe.
7689          */
7690         switch (type) {
7691         case BPF_PROG_TYPE_TRACING:
7692                 if (eatype == BPF_TRACE_ITER)
7693                         return true;
7694                 break;
7695         case BPF_PROG_TYPE_SOCKET_FILTER:
7696         case BPF_PROG_TYPE_SCHED_CLS:
7697         case BPF_PROG_TYPE_SCHED_ACT:
7698         case BPF_PROG_TYPE_XDP:
7699         case BPF_PROG_TYPE_SK_REUSEPORT:
7700         case BPF_PROG_TYPE_FLOW_DISSECTOR:
7701         case BPF_PROG_TYPE_SK_LOOKUP:
7702                 return true;
7703         default:
7704                 break;
7705         }
7706
7707         verbose(env, "cannot update sockmap in this context\n");
7708         return false;
7709 }
7710
7711 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
7712 {
7713         return env->prog->jit_requested &&
7714                bpf_jit_supports_subprog_tailcalls();
7715 }
7716
7717 static int check_map_func_compatibility(struct bpf_verifier_env *env,
7718                                         struct bpf_map *map, int func_id)
7719 {
7720         if (!map)
7721                 return 0;
7722
7723         /* We need a two way check, first is from map perspective ... */
7724         switch (map->map_type) {
7725         case BPF_MAP_TYPE_PROG_ARRAY:
7726                 if (func_id != BPF_FUNC_tail_call)
7727                         goto error;
7728                 break;
7729         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
7730                 if (func_id != BPF_FUNC_perf_event_read &&
7731                     func_id != BPF_FUNC_perf_event_output &&
7732                     func_id != BPF_FUNC_skb_output &&
7733                     func_id != BPF_FUNC_perf_event_read_value &&
7734                     func_id != BPF_FUNC_xdp_output)
7735                         goto error;
7736                 break;
7737         case BPF_MAP_TYPE_RINGBUF:
7738                 if (func_id != BPF_FUNC_ringbuf_output &&
7739                     func_id != BPF_FUNC_ringbuf_reserve &&
7740                     func_id != BPF_FUNC_ringbuf_query &&
7741                     func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
7742                     func_id != BPF_FUNC_ringbuf_submit_dynptr &&
7743                     func_id != BPF_FUNC_ringbuf_discard_dynptr)
7744                         goto error;
7745                 break;
7746         case BPF_MAP_TYPE_USER_RINGBUF:
7747                 if (func_id != BPF_FUNC_user_ringbuf_drain)
7748                         goto error;
7749                 break;
7750         case BPF_MAP_TYPE_STACK_TRACE:
7751                 if (func_id != BPF_FUNC_get_stackid)
7752                         goto error;
7753                 break;
7754         case BPF_MAP_TYPE_CGROUP_ARRAY:
7755                 if (func_id != BPF_FUNC_skb_under_cgroup &&
7756                     func_id != BPF_FUNC_current_task_under_cgroup)
7757                         goto error;
7758                 break;
7759         case BPF_MAP_TYPE_CGROUP_STORAGE:
7760         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
7761                 if (func_id != BPF_FUNC_get_local_storage)
7762                         goto error;
7763                 break;
7764         case BPF_MAP_TYPE_DEVMAP:
7765         case BPF_MAP_TYPE_DEVMAP_HASH:
7766                 if (func_id != BPF_FUNC_redirect_map &&
7767                     func_id != BPF_FUNC_map_lookup_elem)
7768                         goto error;
7769                 break;
7770         /* Restrict bpf side of cpumap and xskmap, open when use-cases
7771          * appear.
7772          */
7773         case BPF_MAP_TYPE_CPUMAP:
7774                 if (func_id != BPF_FUNC_redirect_map)
7775                         goto error;
7776                 break;
7777         case BPF_MAP_TYPE_XSKMAP:
7778                 if (func_id != BPF_FUNC_redirect_map &&
7779                     func_id != BPF_FUNC_map_lookup_elem)
7780                         goto error;
7781                 break;
7782         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
7783         case BPF_MAP_TYPE_HASH_OF_MAPS:
7784                 if (func_id != BPF_FUNC_map_lookup_elem)
7785                         goto error;
7786                 break;
7787         case BPF_MAP_TYPE_SOCKMAP:
7788                 if (func_id != BPF_FUNC_sk_redirect_map &&
7789                     func_id != BPF_FUNC_sock_map_update &&
7790                     func_id != BPF_FUNC_map_delete_elem &&
7791                     func_id != BPF_FUNC_msg_redirect_map &&
7792                     func_id != BPF_FUNC_sk_select_reuseport &&
7793                     func_id != BPF_FUNC_map_lookup_elem &&
7794                     !may_update_sockmap(env, func_id))
7795                         goto error;
7796                 break;
7797         case BPF_MAP_TYPE_SOCKHASH:
7798                 if (func_id != BPF_FUNC_sk_redirect_hash &&
7799                     func_id != BPF_FUNC_sock_hash_update &&
7800                     func_id != BPF_FUNC_map_delete_elem &&
7801                     func_id != BPF_FUNC_msg_redirect_hash &&
7802                     func_id != BPF_FUNC_sk_select_reuseport &&
7803                     func_id != BPF_FUNC_map_lookup_elem &&
7804                     !may_update_sockmap(env, func_id))
7805                         goto error;
7806                 break;
7807         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
7808                 if (func_id != BPF_FUNC_sk_select_reuseport)
7809                         goto error;
7810                 break;
7811         case BPF_MAP_TYPE_QUEUE:
7812         case BPF_MAP_TYPE_STACK:
7813                 if (func_id != BPF_FUNC_map_peek_elem &&
7814                     func_id != BPF_FUNC_map_pop_elem &&
7815                     func_id != BPF_FUNC_map_push_elem)
7816                         goto error;
7817                 break;
7818         case BPF_MAP_TYPE_SK_STORAGE:
7819                 if (func_id != BPF_FUNC_sk_storage_get &&
7820                     func_id != BPF_FUNC_sk_storage_delete &&
7821                     func_id != BPF_FUNC_kptr_xchg)
7822                         goto error;
7823                 break;
7824         case BPF_MAP_TYPE_INODE_STORAGE:
7825                 if (func_id != BPF_FUNC_inode_storage_get &&
7826                     func_id != BPF_FUNC_inode_storage_delete &&
7827                     func_id != BPF_FUNC_kptr_xchg)
7828                         goto error;
7829                 break;
7830         case BPF_MAP_TYPE_TASK_STORAGE:
7831                 if (func_id != BPF_FUNC_task_storage_get &&
7832                     func_id != BPF_FUNC_task_storage_delete &&
7833                     func_id != BPF_FUNC_kptr_xchg)
7834                         goto error;
7835                 break;
7836         case BPF_MAP_TYPE_CGRP_STORAGE:
7837                 if (func_id != BPF_FUNC_cgrp_storage_get &&
7838                     func_id != BPF_FUNC_cgrp_storage_delete &&
7839                     func_id != BPF_FUNC_kptr_xchg)
7840                         goto error;
7841                 break;
7842         case BPF_MAP_TYPE_BLOOM_FILTER:
7843                 if (func_id != BPF_FUNC_map_peek_elem &&
7844                     func_id != BPF_FUNC_map_push_elem)
7845                         goto error;
7846                 break;
7847         default:
7848                 break;
7849         }
7850
7851         /* ... and second from the function itself. */
7852         switch (func_id) {
7853         case BPF_FUNC_tail_call:
7854                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
7855                         goto error;
7856                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
7857                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
7858                         return -EINVAL;
7859                 }
7860                 break;
7861         case BPF_FUNC_perf_event_read:
7862         case BPF_FUNC_perf_event_output:
7863         case BPF_FUNC_perf_event_read_value:
7864         case BPF_FUNC_skb_output:
7865         case BPF_FUNC_xdp_output:
7866                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
7867                         goto error;
7868                 break;
7869         case BPF_FUNC_ringbuf_output:
7870         case BPF_FUNC_ringbuf_reserve:
7871         case BPF_FUNC_ringbuf_query:
7872         case BPF_FUNC_ringbuf_reserve_dynptr:
7873         case BPF_FUNC_ringbuf_submit_dynptr:
7874         case BPF_FUNC_ringbuf_discard_dynptr:
7875                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
7876                         goto error;
7877                 break;
7878         case BPF_FUNC_user_ringbuf_drain:
7879                 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
7880                         goto error;
7881                 break;
7882         case BPF_FUNC_get_stackid:
7883                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
7884                         goto error;
7885                 break;
7886         case BPF_FUNC_current_task_under_cgroup:
7887         case BPF_FUNC_skb_under_cgroup:
7888                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
7889                         goto error;
7890                 break;
7891         case BPF_FUNC_redirect_map:
7892                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
7893                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
7894                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
7895                     map->map_type != BPF_MAP_TYPE_XSKMAP)
7896                         goto error;
7897                 break;
7898         case BPF_FUNC_sk_redirect_map:
7899         case BPF_FUNC_msg_redirect_map:
7900         case BPF_FUNC_sock_map_update:
7901                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
7902                         goto error;
7903                 break;
7904         case BPF_FUNC_sk_redirect_hash:
7905         case BPF_FUNC_msg_redirect_hash:
7906         case BPF_FUNC_sock_hash_update:
7907                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
7908                         goto error;
7909                 break;
7910         case BPF_FUNC_get_local_storage:
7911                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
7912                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
7913                         goto error;
7914                 break;
7915         case BPF_FUNC_sk_select_reuseport:
7916                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
7917                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
7918                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
7919                         goto error;
7920                 break;
7921         case BPF_FUNC_map_pop_elem:
7922                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7923                     map->map_type != BPF_MAP_TYPE_STACK)
7924                         goto error;
7925                 break;
7926         case BPF_FUNC_map_peek_elem:
7927         case BPF_FUNC_map_push_elem:
7928                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
7929                     map->map_type != BPF_MAP_TYPE_STACK &&
7930                     map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
7931                         goto error;
7932                 break;
7933         case BPF_FUNC_map_lookup_percpu_elem:
7934                 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
7935                     map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
7936                     map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
7937                         goto error;
7938                 break;
7939         case BPF_FUNC_sk_storage_get:
7940         case BPF_FUNC_sk_storage_delete:
7941                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
7942                         goto error;
7943                 break;
7944         case BPF_FUNC_inode_storage_get:
7945         case BPF_FUNC_inode_storage_delete:
7946                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
7947                         goto error;
7948                 break;
7949         case BPF_FUNC_task_storage_get:
7950         case BPF_FUNC_task_storage_delete:
7951                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
7952                         goto error;
7953                 break;
7954         case BPF_FUNC_cgrp_storage_get:
7955         case BPF_FUNC_cgrp_storage_delete:
7956                 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
7957                         goto error;
7958                 break;
7959         default:
7960                 break;
7961         }
7962
7963         return 0;
7964 error:
7965         verbose(env, "cannot pass map_type %d into func %s#%d\n",
7966                 map->map_type, func_id_name(func_id), func_id);
7967         return -EINVAL;
7968 }
7969
7970 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
7971 {
7972         int count = 0;
7973
7974         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
7975                 count++;
7976         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
7977                 count++;
7978         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
7979                 count++;
7980         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
7981                 count++;
7982         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
7983                 count++;
7984
7985         /* We only support one arg being in raw mode at the moment,
7986          * which is sufficient for the helper functions we have
7987          * right now.
7988          */
7989         return count <= 1;
7990 }
7991
7992 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
7993 {
7994         bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
7995         bool has_size = fn->arg_size[arg] != 0;
7996         bool is_next_size = false;
7997
7998         if (arg + 1 < ARRAY_SIZE(fn->arg_type))
7999                 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8000
8001         if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8002                 return is_next_size;
8003
8004         return has_size == is_next_size || is_next_size == is_fixed;
8005 }
8006
8007 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8008 {
8009         /* bpf_xxx(..., buf, len) call will access 'len'
8010          * bytes from memory 'buf'. Both arg types need
8011          * to be paired, so make sure there's no buggy
8012          * helper function specification.
8013          */
8014         if (arg_type_is_mem_size(fn->arg1_type) ||
8015             check_args_pair_invalid(fn, 0) ||
8016             check_args_pair_invalid(fn, 1) ||
8017             check_args_pair_invalid(fn, 2) ||
8018             check_args_pair_invalid(fn, 3) ||
8019             check_args_pair_invalid(fn, 4))
8020                 return false;
8021
8022         return true;
8023 }
8024
8025 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8026 {
8027         int i;
8028
8029         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8030                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8031                         return !!fn->arg_btf_id[i];
8032                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8033                         return fn->arg_btf_id[i] == BPF_PTR_POISON;
8034                 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8035                     /* arg_btf_id and arg_size are in a union. */
8036                     (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8037                      !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8038                         return false;
8039         }
8040
8041         return true;
8042 }
8043
8044 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8045 {
8046         return check_raw_mode_ok(fn) &&
8047                check_arg_pair_ok(fn) &&
8048                check_btf_id_ok(fn) ? 0 : -EINVAL;
8049 }
8050
8051 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8052  * are now invalid, so turn them into unknown SCALAR_VALUE.
8053  *
8054  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8055  * since these slices point to packet data.
8056  */
8057 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8058 {
8059         struct bpf_func_state *state;
8060         struct bpf_reg_state *reg;
8061
8062         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8063                 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8064                         mark_reg_invalid(env, reg);
8065         }));
8066 }
8067
8068 enum {
8069         AT_PKT_END = -1,
8070         BEYOND_PKT_END = -2,
8071 };
8072
8073 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8074 {
8075         struct bpf_func_state *state = vstate->frame[vstate->curframe];
8076         struct bpf_reg_state *reg = &state->regs[regn];
8077
8078         if (reg->type != PTR_TO_PACKET)
8079                 /* PTR_TO_PACKET_META is not supported yet */
8080                 return;
8081
8082         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8083          * How far beyond pkt_end it goes is unknown.
8084          * if (!range_open) it's the case of pkt >= pkt_end
8085          * if (range_open) it's the case of pkt > pkt_end
8086          * hence this pointer is at least 1 byte bigger than pkt_end
8087          */
8088         if (range_open)
8089                 reg->range = BEYOND_PKT_END;
8090         else
8091                 reg->range = AT_PKT_END;
8092 }
8093
8094 /* The pointer with the specified id has released its reference to kernel
8095  * resources. Identify all copies of the same pointer and clear the reference.
8096  */
8097 static int release_reference(struct bpf_verifier_env *env,
8098                              int ref_obj_id)
8099 {
8100         struct bpf_func_state *state;
8101         struct bpf_reg_state *reg;
8102         int err;
8103
8104         err = release_reference_state(cur_func(env), ref_obj_id);
8105         if (err)
8106                 return err;
8107
8108         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8109                 if (reg->ref_obj_id == ref_obj_id)
8110                         mark_reg_invalid(env, reg);
8111         }));
8112
8113         return 0;
8114 }
8115
8116 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8117 {
8118         struct bpf_func_state *unused;
8119         struct bpf_reg_state *reg;
8120
8121         bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8122                 if (type_is_non_owning_ref(reg->type))
8123                         mark_reg_invalid(env, reg);
8124         }));
8125 }
8126
8127 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8128                                     struct bpf_reg_state *regs)
8129 {
8130         int i;
8131
8132         /* after the call registers r0 - r5 were scratched */
8133         for (i = 0; i < CALLER_SAVED_REGS; i++) {
8134                 mark_reg_not_init(env, regs, caller_saved[i]);
8135                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8136         }
8137 }
8138
8139 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8140                                    struct bpf_func_state *caller,
8141                                    struct bpf_func_state *callee,
8142                                    int insn_idx);
8143
8144 static int set_callee_state(struct bpf_verifier_env *env,
8145                             struct bpf_func_state *caller,
8146                             struct bpf_func_state *callee, int insn_idx);
8147
8148 static bool is_callback_calling_kfunc(u32 btf_id);
8149
8150 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8151                              int *insn_idx, int subprog,
8152                              set_callee_state_fn set_callee_state_cb)
8153 {
8154         struct bpf_verifier_state *state = env->cur_state;
8155         struct bpf_func_info_aux *func_info_aux;
8156         struct bpf_func_state *caller, *callee;
8157         int err;
8158         bool is_global = false;
8159
8160         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8161                 verbose(env, "the call stack of %d frames is too deep\n",
8162                         state->curframe + 2);
8163                 return -E2BIG;
8164         }
8165
8166         caller = state->frame[state->curframe];
8167         if (state->frame[state->curframe + 1]) {
8168                 verbose(env, "verifier bug. Frame %d already allocated\n",
8169                         state->curframe + 1);
8170                 return -EFAULT;
8171         }
8172
8173         func_info_aux = env->prog->aux->func_info_aux;
8174         if (func_info_aux)
8175                 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
8176         err = btf_check_subprog_call(env, subprog, caller->regs);
8177         if (err == -EFAULT)
8178                 return err;
8179         if (is_global) {
8180                 if (err) {
8181                         verbose(env, "Caller passes invalid args into func#%d\n",
8182                                 subprog);
8183                         return err;
8184                 } else {
8185                         if (env->log.level & BPF_LOG_LEVEL)
8186                                 verbose(env,
8187                                         "Func#%d is global and valid. Skipping.\n",
8188                                         subprog);
8189                         clear_caller_saved_regs(env, caller->regs);
8190
8191                         /* All global functions return a 64-bit SCALAR_VALUE */
8192                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
8193                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8194
8195                         /* continue with next insn after call */
8196                         return 0;
8197                 }
8198         }
8199
8200         /* set_callee_state is used for direct subprog calls, but we are
8201          * interested in validating only BPF helpers that can call subprogs as
8202          * callbacks
8203          */
8204         if (set_callee_state_cb != set_callee_state) {
8205                 if (bpf_pseudo_kfunc_call(insn) &&
8206                     !is_callback_calling_kfunc(insn->imm)) {
8207                         verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8208                                 func_id_name(insn->imm), insn->imm);
8209                         return -EFAULT;
8210                 } else if (!bpf_pseudo_kfunc_call(insn) &&
8211                            !is_callback_calling_function(insn->imm)) { /* helper */
8212                         verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8213                                 func_id_name(insn->imm), insn->imm);
8214                         return -EFAULT;
8215                 }
8216         }
8217
8218         if (insn->code == (BPF_JMP | BPF_CALL) &&
8219             insn->src_reg == 0 &&
8220             insn->imm == BPF_FUNC_timer_set_callback) {
8221                 struct bpf_verifier_state *async_cb;
8222
8223                 /* there is no real recursion here. timer callbacks are async */
8224                 env->subprog_info[subprog].is_async_cb = true;
8225                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8226                                          *insn_idx, subprog);
8227                 if (!async_cb)
8228                         return -EFAULT;
8229                 callee = async_cb->frame[0];
8230                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
8231
8232                 /* Convert bpf_timer_set_callback() args into timer callback args */
8233                 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8234                 if (err)
8235                         return err;
8236
8237                 clear_caller_saved_regs(env, caller->regs);
8238                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8239                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8240                 /* continue with next insn after call */
8241                 return 0;
8242         }
8243
8244         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8245         if (!callee)
8246                 return -ENOMEM;
8247         state->frame[state->curframe + 1] = callee;
8248
8249         /* callee cannot access r0, r6 - r9 for reading and has to write
8250          * into its own stack before reading from it.
8251          * callee can read/write into caller's stack
8252          */
8253         init_func_state(env, callee,
8254                         /* remember the callsite, it will be used by bpf_exit */
8255                         *insn_idx /* callsite */,
8256                         state->curframe + 1 /* frameno within this callchain */,
8257                         subprog /* subprog number within this prog */);
8258
8259         /* Transfer references to the callee */
8260         err = copy_reference_state(callee, caller);
8261         if (err)
8262                 goto err_out;
8263
8264         err = set_callee_state_cb(env, caller, callee, *insn_idx);
8265         if (err)
8266                 goto err_out;
8267
8268         clear_caller_saved_regs(env, caller->regs);
8269
8270         /* only increment it after check_reg_arg() finished */
8271         state->curframe++;
8272
8273         /* and go analyze first insn of the callee */
8274         *insn_idx = env->subprog_info[subprog].start - 1;
8275
8276         if (env->log.level & BPF_LOG_LEVEL) {
8277                 verbose(env, "caller:\n");
8278                 print_verifier_state(env, caller, true);
8279                 verbose(env, "callee:\n");
8280                 print_verifier_state(env, callee, true);
8281         }
8282         return 0;
8283
8284 err_out:
8285         free_func_state(callee);
8286         state->frame[state->curframe + 1] = NULL;
8287         return err;
8288 }
8289
8290 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
8291                                    struct bpf_func_state *caller,
8292                                    struct bpf_func_state *callee)
8293 {
8294         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
8295          *      void *callback_ctx, u64 flags);
8296          * callback_fn(struct bpf_map *map, void *key, void *value,
8297          *      void *callback_ctx);
8298          */
8299         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8300
8301         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8302         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8303         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8304
8305         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8306         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8307         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
8308
8309         /* pointer to stack or null */
8310         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
8311
8312         /* unused */
8313         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8314         return 0;
8315 }
8316
8317 static int set_callee_state(struct bpf_verifier_env *env,
8318                             struct bpf_func_state *caller,
8319                             struct bpf_func_state *callee, int insn_idx)
8320 {
8321         int i;
8322
8323         /* copy r1 - r5 args that callee can access.  The copy includes parent
8324          * pointers, which connects us up to the liveness chain
8325          */
8326         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
8327                 callee->regs[i] = caller->regs[i];
8328         return 0;
8329 }
8330
8331 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8332                            int *insn_idx)
8333 {
8334         int subprog, target_insn;
8335
8336         target_insn = *insn_idx + insn->imm + 1;
8337         subprog = find_subprog(env, target_insn);
8338         if (subprog < 0) {
8339                 verbose(env, "verifier bug. No program starts at insn %d\n",
8340                         target_insn);
8341                 return -EFAULT;
8342         }
8343
8344         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
8345 }
8346
8347 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
8348                                        struct bpf_func_state *caller,
8349                                        struct bpf_func_state *callee,
8350                                        int insn_idx)
8351 {
8352         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
8353         struct bpf_map *map;
8354         int err;
8355
8356         if (bpf_map_ptr_poisoned(insn_aux)) {
8357                 verbose(env, "tail_call abusing map_ptr\n");
8358                 return -EINVAL;
8359         }
8360
8361         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
8362         if (!map->ops->map_set_for_each_callback_args ||
8363             !map->ops->map_for_each_callback) {
8364                 verbose(env, "callback function not allowed for map\n");
8365                 return -ENOTSUPP;
8366         }
8367
8368         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
8369         if (err)
8370                 return err;
8371
8372         callee->in_callback_fn = true;
8373         callee->callback_ret_range = tnum_range(0, 1);
8374         return 0;
8375 }
8376
8377 static int set_loop_callback_state(struct bpf_verifier_env *env,
8378                                    struct bpf_func_state *caller,
8379                                    struct bpf_func_state *callee,
8380                                    int insn_idx)
8381 {
8382         /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
8383          *          u64 flags);
8384          * callback_fn(u32 index, void *callback_ctx);
8385          */
8386         callee->regs[BPF_REG_1].type = SCALAR_VALUE;
8387         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8388
8389         /* unused */
8390         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8391         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8392         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8393
8394         callee->in_callback_fn = true;
8395         callee->callback_ret_range = tnum_range(0, 1);
8396         return 0;
8397 }
8398
8399 static int set_timer_callback_state(struct bpf_verifier_env *env,
8400                                     struct bpf_func_state *caller,
8401                                     struct bpf_func_state *callee,
8402                                     int insn_idx)
8403 {
8404         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
8405
8406         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
8407          * callback_fn(struct bpf_map *map, void *key, void *value);
8408          */
8409         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
8410         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
8411         callee->regs[BPF_REG_1].map_ptr = map_ptr;
8412
8413         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8414         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8415         callee->regs[BPF_REG_2].map_ptr = map_ptr;
8416
8417         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
8418         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
8419         callee->regs[BPF_REG_3].map_ptr = map_ptr;
8420
8421         /* unused */
8422         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8423         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8424         callee->in_async_callback_fn = true;
8425         callee->callback_ret_range = tnum_range(0, 1);
8426         return 0;
8427 }
8428
8429 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
8430                                        struct bpf_func_state *caller,
8431                                        struct bpf_func_state *callee,
8432                                        int insn_idx)
8433 {
8434         /* bpf_find_vma(struct task_struct *task, u64 addr,
8435          *               void *callback_fn, void *callback_ctx, u64 flags)
8436          * (callback_fn)(struct task_struct *task,
8437          *               struct vm_area_struct *vma, void *callback_ctx);
8438          */
8439         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8440
8441         callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
8442         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8443         callee->regs[BPF_REG_2].btf =  btf_vmlinux;
8444         callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
8445
8446         /* pointer to stack or null */
8447         callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
8448
8449         /* unused */
8450         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8451         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8452         callee->in_callback_fn = true;
8453         callee->callback_ret_range = tnum_range(0, 1);
8454         return 0;
8455 }
8456
8457 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
8458                                            struct bpf_func_state *caller,
8459                                            struct bpf_func_state *callee,
8460                                            int insn_idx)
8461 {
8462         /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
8463          *                        callback_ctx, u64 flags);
8464          * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
8465          */
8466         __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
8467         mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
8468         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
8469
8470         /* unused */
8471         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8472         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8473         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8474
8475         callee->in_callback_fn = true;
8476         callee->callback_ret_range = tnum_range(0, 1);
8477         return 0;
8478 }
8479
8480 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
8481                                          struct bpf_func_state *caller,
8482                                          struct bpf_func_state *callee,
8483                                          int insn_idx)
8484 {
8485         /* void bpf_rbtree_add(struct bpf_rb_root *root, struct bpf_rb_node *node,
8486          *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
8487          *
8488          * 'struct bpf_rb_node *node' arg to bpf_rbtree_add is the same PTR_TO_BTF_ID w/ offset
8489          * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
8490          * by this point, so look at 'root'
8491          */
8492         struct btf_field *field;
8493
8494         field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
8495                                       BPF_RB_ROOT);
8496         if (!field || !field->graph_root.value_btf_id)
8497                 return -EFAULT;
8498
8499         mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
8500         ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
8501         mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
8502         ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
8503
8504         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
8505         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
8506         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
8507         callee->in_callback_fn = true;
8508         callee->callback_ret_range = tnum_range(0, 1);
8509         return 0;
8510 }
8511
8512 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
8513
8514 /* Are we currently verifying the callback for a rbtree helper that must
8515  * be called with lock held? If so, no need to complain about unreleased
8516  * lock
8517  */
8518 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
8519 {
8520         struct bpf_verifier_state *state = env->cur_state;
8521         struct bpf_insn *insn = env->prog->insnsi;
8522         struct bpf_func_state *callee;
8523         int kfunc_btf_id;
8524
8525         if (!state->curframe)
8526                 return false;
8527
8528         callee = state->frame[state->curframe];
8529
8530         if (!callee->in_callback_fn)
8531                 return false;
8532
8533         kfunc_btf_id = insn[callee->callsite].imm;
8534         return is_rbtree_lock_required_kfunc(kfunc_btf_id);
8535 }
8536
8537 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
8538 {
8539         struct bpf_verifier_state *state = env->cur_state;
8540         struct bpf_func_state *caller, *callee;
8541         struct bpf_reg_state *r0;
8542         int err;
8543
8544         callee = state->frame[state->curframe];
8545         r0 = &callee->regs[BPF_REG_0];
8546         if (r0->type == PTR_TO_STACK) {
8547                 /* technically it's ok to return caller's stack pointer
8548                  * (or caller's caller's pointer) back to the caller,
8549                  * since these pointers are valid. Only current stack
8550                  * pointer will be invalid as soon as function exits,
8551                  * but let's be conservative
8552                  */
8553                 verbose(env, "cannot return stack pointer to the caller\n");
8554                 return -EINVAL;
8555         }
8556
8557         caller = state->frame[state->curframe - 1];
8558         if (callee->in_callback_fn) {
8559                 /* enforce R0 return value range [0, 1]. */
8560                 struct tnum range = callee->callback_ret_range;
8561
8562                 if (r0->type != SCALAR_VALUE) {
8563                         verbose(env, "R0 not a scalar value\n");
8564                         return -EACCES;
8565                 }
8566                 if (!tnum_in(range, r0->var_off)) {
8567                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
8568                         return -EINVAL;
8569                 }
8570         } else {
8571                 /* return to the caller whatever r0 had in the callee */
8572                 caller->regs[BPF_REG_0] = *r0;
8573         }
8574
8575         /* callback_fn frame should have released its own additions to parent's
8576          * reference state at this point, or check_reference_leak would
8577          * complain, hence it must be the same as the caller. There is no need
8578          * to copy it back.
8579          */
8580         if (!callee->in_callback_fn) {
8581                 /* Transfer references to the caller */
8582                 err = copy_reference_state(caller, callee);
8583                 if (err)
8584                         return err;
8585         }
8586
8587         *insn_idx = callee->callsite + 1;
8588         if (env->log.level & BPF_LOG_LEVEL) {
8589                 verbose(env, "returning from callee:\n");
8590                 print_verifier_state(env, callee, true);
8591                 verbose(env, "to caller at %d:\n", *insn_idx);
8592                 print_verifier_state(env, caller, true);
8593         }
8594         /* clear everything in the callee */
8595         free_func_state(callee);
8596         state->frame[state->curframe--] = NULL;
8597         return 0;
8598 }
8599
8600 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
8601                                    int func_id,
8602                                    struct bpf_call_arg_meta *meta)
8603 {
8604         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
8605
8606         if (ret_type != RET_INTEGER ||
8607             (func_id != BPF_FUNC_get_stack &&
8608              func_id != BPF_FUNC_get_task_stack &&
8609              func_id != BPF_FUNC_probe_read_str &&
8610              func_id != BPF_FUNC_probe_read_kernel_str &&
8611              func_id != BPF_FUNC_probe_read_user_str))
8612                 return;
8613
8614         ret_reg->smax_value = meta->msize_max_value;
8615         ret_reg->s32_max_value = meta->msize_max_value;
8616         ret_reg->smin_value = -MAX_ERRNO;
8617         ret_reg->s32_min_value = -MAX_ERRNO;
8618         reg_bounds_sync(ret_reg);
8619 }
8620
8621 static int
8622 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
8623                 int func_id, int insn_idx)
8624 {
8625         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
8626         struct bpf_map *map = meta->map_ptr;
8627
8628         if (func_id != BPF_FUNC_tail_call &&
8629             func_id != BPF_FUNC_map_lookup_elem &&
8630             func_id != BPF_FUNC_map_update_elem &&
8631             func_id != BPF_FUNC_map_delete_elem &&
8632             func_id != BPF_FUNC_map_push_elem &&
8633             func_id != BPF_FUNC_map_pop_elem &&
8634             func_id != BPF_FUNC_map_peek_elem &&
8635             func_id != BPF_FUNC_for_each_map_elem &&
8636             func_id != BPF_FUNC_redirect_map &&
8637             func_id != BPF_FUNC_map_lookup_percpu_elem)
8638                 return 0;
8639
8640         if (map == NULL) {
8641                 verbose(env, "kernel subsystem misconfigured verifier\n");
8642                 return -EINVAL;
8643         }
8644
8645         /* In case of read-only, some additional restrictions
8646          * need to be applied in order to prevent altering the
8647          * state of the map from program side.
8648          */
8649         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
8650             (func_id == BPF_FUNC_map_delete_elem ||
8651              func_id == BPF_FUNC_map_update_elem ||
8652              func_id == BPF_FUNC_map_push_elem ||
8653              func_id == BPF_FUNC_map_pop_elem)) {
8654                 verbose(env, "write into map forbidden\n");
8655                 return -EACCES;
8656         }
8657
8658         if (!BPF_MAP_PTR(aux->map_ptr_state))
8659                 bpf_map_ptr_store(aux, meta->map_ptr,
8660                                   !meta->map_ptr->bypass_spec_v1);
8661         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
8662                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
8663                                   !meta->map_ptr->bypass_spec_v1);
8664         return 0;
8665 }
8666
8667 static int
8668 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
8669                 int func_id, int insn_idx)
8670 {
8671         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
8672         struct bpf_reg_state *regs = cur_regs(env), *reg;
8673         struct bpf_map *map = meta->map_ptr;
8674         u64 val, max;
8675         int err;
8676
8677         if (func_id != BPF_FUNC_tail_call)
8678                 return 0;
8679         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
8680                 verbose(env, "kernel subsystem misconfigured verifier\n");
8681                 return -EINVAL;
8682         }
8683
8684         reg = &regs[BPF_REG_3];
8685         val = reg->var_off.value;
8686         max = map->max_entries;
8687
8688         if (!(register_is_const(reg) && val < max)) {
8689                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
8690                 return 0;
8691         }
8692
8693         err = mark_chain_precision(env, BPF_REG_3);
8694         if (err)
8695                 return err;
8696         if (bpf_map_key_unseen(aux))
8697                 bpf_map_key_store(aux, val);
8698         else if (!bpf_map_key_poisoned(aux) &&
8699                   bpf_map_key_immediate(aux) != val)
8700                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
8701         return 0;
8702 }
8703
8704 static int check_reference_leak(struct bpf_verifier_env *env)
8705 {
8706         struct bpf_func_state *state = cur_func(env);
8707         bool refs_lingering = false;
8708         int i;
8709
8710         if (state->frameno && !state->in_callback_fn)
8711                 return 0;
8712
8713         for (i = 0; i < state->acquired_refs; i++) {
8714                 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
8715                         continue;
8716                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
8717                         state->refs[i].id, state->refs[i].insn_idx);
8718                 refs_lingering = true;
8719         }
8720         return refs_lingering ? -EINVAL : 0;
8721 }
8722
8723 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
8724                                    struct bpf_reg_state *regs)
8725 {
8726         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
8727         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
8728         struct bpf_map *fmt_map = fmt_reg->map_ptr;
8729         struct bpf_bprintf_data data = {};
8730         int err, fmt_map_off, num_args;
8731         u64 fmt_addr;
8732         char *fmt;
8733
8734         /* data must be an array of u64 */
8735         if (data_len_reg->var_off.value % 8)
8736                 return -EINVAL;
8737         num_args = data_len_reg->var_off.value / 8;
8738
8739         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
8740          * and map_direct_value_addr is set.
8741          */
8742         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
8743         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
8744                                                   fmt_map_off);
8745         if (err) {
8746                 verbose(env, "verifier bug\n");
8747                 return -EFAULT;
8748         }
8749         fmt = (char *)(long)fmt_addr + fmt_map_off;
8750
8751         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
8752          * can focus on validating the format specifiers.
8753          */
8754         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
8755         if (err < 0)
8756                 verbose(env, "Invalid format string\n");
8757
8758         return err;
8759 }
8760
8761 static int check_get_func_ip(struct bpf_verifier_env *env)
8762 {
8763         enum bpf_prog_type type = resolve_prog_type(env->prog);
8764         int func_id = BPF_FUNC_get_func_ip;
8765
8766         if (type == BPF_PROG_TYPE_TRACING) {
8767                 if (!bpf_prog_has_trampoline(env->prog)) {
8768                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
8769                                 func_id_name(func_id), func_id);
8770                         return -ENOTSUPP;
8771                 }
8772                 return 0;
8773         } else if (type == BPF_PROG_TYPE_KPROBE) {
8774                 return 0;
8775         }
8776
8777         verbose(env, "func %s#%d not supported for program type %d\n",
8778                 func_id_name(func_id), func_id, type);
8779         return -ENOTSUPP;
8780 }
8781
8782 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
8783 {
8784         return &env->insn_aux_data[env->insn_idx];
8785 }
8786
8787 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
8788 {
8789         struct bpf_reg_state *regs = cur_regs(env);
8790         struct bpf_reg_state *reg = &regs[BPF_REG_4];
8791         bool reg_is_null = register_is_null(reg);
8792
8793         if (reg_is_null)
8794                 mark_chain_precision(env, BPF_REG_4);
8795
8796         return reg_is_null;
8797 }
8798
8799 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
8800 {
8801         struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
8802
8803         if (!state->initialized) {
8804                 state->initialized = 1;
8805                 state->fit_for_inline = loop_flag_is_zero(env);
8806                 state->callback_subprogno = subprogno;
8807                 return;
8808         }
8809
8810         if (!state->fit_for_inline)
8811                 return;
8812
8813         state->fit_for_inline = (loop_flag_is_zero(env) &&
8814                                  state->callback_subprogno == subprogno);
8815 }
8816
8817 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8818                              int *insn_idx_p)
8819 {
8820         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8821         const struct bpf_func_proto *fn = NULL;
8822         enum bpf_return_type ret_type;
8823         enum bpf_type_flag ret_flag;
8824         struct bpf_reg_state *regs;
8825         struct bpf_call_arg_meta meta;
8826         int insn_idx = *insn_idx_p;
8827         bool changes_data;
8828         int i, err, func_id;
8829
8830         /* find function prototype */
8831         func_id = insn->imm;
8832         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
8833                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
8834                         func_id);
8835                 return -EINVAL;
8836         }
8837
8838         if (env->ops->get_func_proto)
8839                 fn = env->ops->get_func_proto(func_id, env->prog);
8840         if (!fn) {
8841                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
8842                         func_id);
8843                 return -EINVAL;
8844         }
8845
8846         /* eBPF programs must be GPL compatible to use GPL-ed functions */
8847         if (!env->prog->gpl_compatible && fn->gpl_only) {
8848                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
8849                 return -EINVAL;
8850         }
8851
8852         if (fn->allowed && !fn->allowed(env->prog)) {
8853                 verbose(env, "helper call is not allowed in probe\n");
8854                 return -EINVAL;
8855         }
8856
8857         if (!env->prog->aux->sleepable && fn->might_sleep) {
8858                 verbose(env, "helper call might sleep in a non-sleepable prog\n");
8859                 return -EINVAL;
8860         }
8861
8862         /* With LD_ABS/IND some JITs save/restore skb from r1. */
8863         changes_data = bpf_helper_changes_pkt_data(fn->func);
8864         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
8865                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
8866                         func_id_name(func_id), func_id);
8867                 return -EINVAL;
8868         }
8869
8870         memset(&meta, 0, sizeof(meta));
8871         meta.pkt_access = fn->pkt_access;
8872
8873         err = check_func_proto(fn, func_id);
8874         if (err) {
8875                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
8876                         func_id_name(func_id), func_id);
8877                 return err;
8878         }
8879
8880         if (env->cur_state->active_rcu_lock) {
8881                 if (fn->might_sleep) {
8882                         verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
8883                                 func_id_name(func_id), func_id);
8884                         return -EINVAL;
8885                 }
8886
8887                 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
8888                         env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
8889         }
8890
8891         meta.func_id = func_id;
8892         /* check args */
8893         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
8894                 err = check_func_arg(env, i, &meta, fn, insn_idx);
8895                 if (err)
8896                         return err;
8897         }
8898
8899         err = record_func_map(env, &meta, func_id, insn_idx);
8900         if (err)
8901                 return err;
8902
8903         err = record_func_key(env, &meta, func_id, insn_idx);
8904         if (err)
8905                 return err;
8906
8907         /* Mark slots with STACK_MISC in case of raw mode, stack offset
8908          * is inferred from register state.
8909          */
8910         for (i = 0; i < meta.access_size; i++) {
8911                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
8912                                        BPF_WRITE, -1, false);
8913                 if (err)
8914                         return err;
8915         }
8916
8917         regs = cur_regs(env);
8918
8919         if (meta.release_regno) {
8920                 err = -EINVAL;
8921                 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
8922                  * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
8923                  * is safe to do directly.
8924                  */
8925                 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
8926                         if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
8927                                 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
8928                                 return -EFAULT;
8929                         }
8930                         err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
8931                 } else if (meta.ref_obj_id) {
8932                         err = release_reference(env, meta.ref_obj_id);
8933                 } else if (register_is_null(&regs[meta.release_regno])) {
8934                         /* meta.ref_obj_id can only be 0 if register that is meant to be
8935                          * released is NULL, which must be > R0.
8936                          */
8937                         err = 0;
8938                 }
8939                 if (err) {
8940                         verbose(env, "func %s#%d reference has not been acquired before\n",
8941                                 func_id_name(func_id), func_id);
8942                         return err;
8943                 }
8944         }
8945
8946         switch (func_id) {
8947         case BPF_FUNC_tail_call:
8948                 err = check_reference_leak(env);
8949                 if (err) {
8950                         verbose(env, "tail_call would lead to reference leak\n");
8951                         return err;
8952                 }
8953                 break;
8954         case BPF_FUNC_get_local_storage:
8955                 /* check that flags argument in get_local_storage(map, flags) is 0,
8956                  * this is required because get_local_storage() can't return an error.
8957                  */
8958                 if (!register_is_null(&regs[BPF_REG_2])) {
8959                         verbose(env, "get_local_storage() doesn't support non-zero flags\n");
8960                         return -EINVAL;
8961                 }
8962                 break;
8963         case BPF_FUNC_for_each_map_elem:
8964                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8965                                         set_map_elem_callback_state);
8966                 break;
8967         case BPF_FUNC_timer_set_callback:
8968                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8969                                         set_timer_callback_state);
8970                 break;
8971         case BPF_FUNC_find_vma:
8972                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8973                                         set_find_vma_callback_state);
8974                 break;
8975         case BPF_FUNC_snprintf:
8976                 err = check_bpf_snprintf_call(env, regs);
8977                 break;
8978         case BPF_FUNC_loop:
8979                 update_loop_inline_state(env, meta.subprogno);
8980                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
8981                                         set_loop_callback_state);
8982                 break;
8983         case BPF_FUNC_dynptr_from_mem:
8984                 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
8985                         verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
8986                                 reg_type_str(env, regs[BPF_REG_1].type));
8987                         return -EACCES;
8988                 }
8989                 break;
8990         case BPF_FUNC_set_retval:
8991                 if (prog_type == BPF_PROG_TYPE_LSM &&
8992                     env->prog->expected_attach_type == BPF_LSM_CGROUP) {
8993                         if (!env->prog->aux->attach_func_proto->type) {
8994                                 /* Make sure programs that attach to void
8995                                  * hooks don't try to modify return value.
8996                                  */
8997                                 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
8998                                 return -EINVAL;
8999                         }
9000                 }
9001                 break;
9002         case BPF_FUNC_dynptr_data:
9003         {
9004                 struct bpf_reg_state *reg;
9005                 int id, ref_obj_id;
9006
9007                 reg = get_dynptr_arg_reg(env, fn, regs);
9008                 if (!reg)
9009                         return -EFAULT;
9010
9011
9012                 if (meta.dynptr_id) {
9013                         verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9014                         return -EFAULT;
9015                 }
9016                 if (meta.ref_obj_id) {
9017                         verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9018                         return -EFAULT;
9019                 }
9020
9021                 id = dynptr_id(env, reg);
9022                 if (id < 0) {
9023                         verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9024                         return id;
9025                 }
9026
9027                 ref_obj_id = dynptr_ref_obj_id(env, reg);
9028                 if (ref_obj_id < 0) {
9029                         verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9030                         return ref_obj_id;
9031                 }
9032
9033                 meta.dynptr_id = id;
9034                 meta.ref_obj_id = ref_obj_id;
9035
9036                 break;
9037         }
9038         case BPF_FUNC_dynptr_write:
9039         {
9040                 enum bpf_dynptr_type dynptr_type;
9041                 struct bpf_reg_state *reg;
9042
9043                 reg = get_dynptr_arg_reg(env, fn, regs);
9044                 if (!reg)
9045                         return -EFAULT;
9046
9047                 dynptr_type = dynptr_get_type(env, reg);
9048                 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9049                         return -EFAULT;
9050
9051                 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9052                         /* this will trigger clear_all_pkt_pointers(), which will
9053                          * invalidate all dynptr slices associated with the skb
9054                          */
9055                         changes_data = true;
9056
9057                 break;
9058         }
9059         case BPF_FUNC_user_ringbuf_drain:
9060                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9061                                         set_user_ringbuf_callback_state);
9062                 break;
9063         }
9064
9065         if (err)
9066                 return err;
9067
9068         /* reset caller saved regs */
9069         for (i = 0; i < CALLER_SAVED_REGS; i++) {
9070                 mark_reg_not_init(env, regs, caller_saved[i]);
9071                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9072         }
9073
9074         /* helper call returns 64-bit value. */
9075         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9076
9077         /* update return register (already marked as written above) */
9078         ret_type = fn->ret_type;
9079         ret_flag = type_flag(ret_type);
9080
9081         switch (base_type(ret_type)) {
9082         case RET_INTEGER:
9083                 /* sets type to SCALAR_VALUE */
9084                 mark_reg_unknown(env, regs, BPF_REG_0);
9085                 break;
9086         case RET_VOID:
9087                 regs[BPF_REG_0].type = NOT_INIT;
9088                 break;
9089         case RET_PTR_TO_MAP_VALUE:
9090                 /* There is no offset yet applied, variable or fixed */
9091                 mark_reg_known_zero(env, regs, BPF_REG_0);
9092                 /* remember map_ptr, so that check_map_access()
9093                  * can check 'value_size' boundary of memory access
9094                  * to map element returned from bpf_map_lookup_elem()
9095                  */
9096                 if (meta.map_ptr == NULL) {
9097                         verbose(env,
9098                                 "kernel subsystem misconfigured verifier\n");
9099                         return -EINVAL;
9100                 }
9101                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
9102                 regs[BPF_REG_0].map_uid = meta.map_uid;
9103                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9104                 if (!type_may_be_null(ret_type) &&
9105                     btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9106                         regs[BPF_REG_0].id = ++env->id_gen;
9107                 }
9108                 break;
9109         case RET_PTR_TO_SOCKET:
9110                 mark_reg_known_zero(env, regs, BPF_REG_0);
9111                 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9112                 break;
9113         case RET_PTR_TO_SOCK_COMMON:
9114                 mark_reg_known_zero(env, regs, BPF_REG_0);
9115                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9116                 break;
9117         case RET_PTR_TO_TCP_SOCK:
9118                 mark_reg_known_zero(env, regs, BPF_REG_0);
9119                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9120                 break;
9121         case RET_PTR_TO_MEM:
9122                 mark_reg_known_zero(env, regs, BPF_REG_0);
9123                 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9124                 regs[BPF_REG_0].mem_size = meta.mem_size;
9125                 break;
9126         case RET_PTR_TO_MEM_OR_BTF_ID:
9127         {
9128                 const struct btf_type *t;
9129
9130                 mark_reg_known_zero(env, regs, BPF_REG_0);
9131                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9132                 if (!btf_type_is_struct(t)) {
9133                         u32 tsize;
9134                         const struct btf_type *ret;
9135                         const char *tname;
9136
9137                         /* resolve the type size of ksym. */
9138                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9139                         if (IS_ERR(ret)) {
9140                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9141                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
9142                                         tname, PTR_ERR(ret));
9143                                 return -EINVAL;
9144                         }
9145                         regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9146                         regs[BPF_REG_0].mem_size = tsize;
9147                 } else {
9148                         /* MEM_RDONLY may be carried from ret_flag, but it
9149                          * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9150                          * it will confuse the check of PTR_TO_BTF_ID in
9151                          * check_mem_access().
9152                          */
9153                         ret_flag &= ~MEM_RDONLY;
9154
9155                         regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9156                         regs[BPF_REG_0].btf = meta.ret_btf;
9157                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9158                 }
9159                 break;
9160         }
9161         case RET_PTR_TO_BTF_ID:
9162         {
9163                 struct btf *ret_btf;
9164                 int ret_btf_id;
9165
9166                 mark_reg_known_zero(env, regs, BPF_REG_0);
9167                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9168                 if (func_id == BPF_FUNC_kptr_xchg) {
9169                         ret_btf = meta.kptr_field->kptr.btf;
9170                         ret_btf_id = meta.kptr_field->kptr.btf_id;
9171                         if (!btf_is_kernel(ret_btf))
9172                                 regs[BPF_REG_0].type |= MEM_ALLOC;
9173                 } else {
9174                         if (fn->ret_btf_id == BPF_PTR_POISON) {
9175                                 verbose(env, "verifier internal error:");
9176                                 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9177                                         func_id_name(func_id));
9178                                 return -EINVAL;
9179                         }
9180                         ret_btf = btf_vmlinux;
9181                         ret_btf_id = *fn->ret_btf_id;
9182                 }
9183                 if (ret_btf_id == 0) {
9184                         verbose(env, "invalid return type %u of func %s#%d\n",
9185                                 base_type(ret_type), func_id_name(func_id),
9186                                 func_id);
9187                         return -EINVAL;
9188                 }
9189                 regs[BPF_REG_0].btf = ret_btf;
9190                 regs[BPF_REG_0].btf_id = ret_btf_id;
9191                 break;
9192         }
9193         default:
9194                 verbose(env, "unknown return type %u of func %s#%d\n",
9195                         base_type(ret_type), func_id_name(func_id), func_id);
9196                 return -EINVAL;
9197         }
9198
9199         if (type_may_be_null(regs[BPF_REG_0].type))
9200                 regs[BPF_REG_0].id = ++env->id_gen;
9201
9202         if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9203                 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9204                         func_id_name(func_id), func_id);
9205                 return -EFAULT;
9206         }
9207
9208         if (is_dynptr_ref_function(func_id))
9209                 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9210
9211         if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9212                 /* For release_reference() */
9213                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9214         } else if (is_acquire_function(func_id, meta.map_ptr)) {
9215                 int id = acquire_reference_state(env, insn_idx);
9216
9217                 if (id < 0)
9218                         return id;
9219                 /* For mark_ptr_or_null_reg() */
9220                 regs[BPF_REG_0].id = id;
9221                 /* For release_reference() */
9222                 regs[BPF_REG_0].ref_obj_id = id;
9223         }
9224
9225         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9226
9227         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9228         if (err)
9229                 return err;
9230
9231         if ((func_id == BPF_FUNC_get_stack ||
9232              func_id == BPF_FUNC_get_task_stack) &&
9233             !env->prog->has_callchain_buf) {
9234                 const char *err_str;
9235
9236 #ifdef CONFIG_PERF_EVENTS
9237                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
9238                 err_str = "cannot get callchain buffer for func %s#%d\n";
9239 #else
9240                 err = -ENOTSUPP;
9241                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9242 #endif
9243                 if (err) {
9244                         verbose(env, err_str, func_id_name(func_id), func_id);
9245                         return err;
9246                 }
9247
9248                 env->prog->has_callchain_buf = true;
9249         }
9250
9251         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9252                 env->prog->call_get_stack = true;
9253
9254         if (func_id == BPF_FUNC_get_func_ip) {
9255                 if (check_get_func_ip(env))
9256                         return -ENOTSUPP;
9257                 env->prog->call_get_func_ip = true;
9258         }
9259
9260         if (changes_data)
9261                 clear_all_pkt_pointers(env);
9262         return 0;
9263 }
9264
9265 /* mark_btf_func_reg_size() is used when the reg size is determined by
9266  * the BTF func_proto's return value size and argument.
9267  */
9268 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9269                                    size_t reg_size)
9270 {
9271         struct bpf_reg_state *reg = &cur_regs(env)[regno];
9272
9273         if (regno == BPF_REG_0) {
9274                 /* Function return value */
9275                 reg->live |= REG_LIVE_WRITTEN;
9276                 reg->subreg_def = reg_size == sizeof(u64) ?
9277                         DEF_NOT_SUBREG : env->insn_idx + 1;
9278         } else {
9279                 /* Function argument */
9280                 if (reg_size == sizeof(u64)) {
9281                         mark_insn_zext(env, reg);
9282                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
9283                 } else {
9284                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
9285                 }
9286         }
9287 }
9288
9289 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
9290 {
9291         return meta->kfunc_flags & KF_ACQUIRE;
9292 }
9293
9294 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
9295 {
9296         return meta->kfunc_flags & KF_RET_NULL;
9297 }
9298
9299 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
9300 {
9301         return meta->kfunc_flags & KF_RELEASE;
9302 }
9303
9304 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
9305 {
9306         return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
9307 }
9308
9309 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
9310 {
9311         return meta->kfunc_flags & KF_SLEEPABLE;
9312 }
9313
9314 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
9315 {
9316         return meta->kfunc_flags & KF_DESTRUCTIVE;
9317 }
9318
9319 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
9320 {
9321         return meta->kfunc_flags & KF_RCU;
9322 }
9323
9324 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg)
9325 {
9326         return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET);
9327 }
9328
9329 static bool __kfunc_param_match_suffix(const struct btf *btf,
9330                                        const struct btf_param *arg,
9331                                        const char *suffix)
9332 {
9333         int suffix_len = strlen(suffix), len;
9334         const char *param_name;
9335
9336         /* In the future, this can be ported to use BTF tagging */
9337         param_name = btf_name_by_offset(btf, arg->name_off);
9338         if (str_is_empty(param_name))
9339                 return false;
9340         len = strlen(param_name);
9341         if (len < suffix_len)
9342                 return false;
9343         param_name += len - suffix_len;
9344         return !strncmp(param_name, suffix, suffix_len);
9345 }
9346
9347 static bool is_kfunc_arg_mem_size(const struct btf *btf,
9348                                   const struct btf_param *arg,
9349                                   const struct bpf_reg_state *reg)
9350 {
9351         const struct btf_type *t;
9352
9353         t = btf_type_skip_modifiers(btf, arg->type, NULL);
9354         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9355                 return false;
9356
9357         return __kfunc_param_match_suffix(btf, arg, "__sz");
9358 }
9359
9360 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
9361                                         const struct btf_param *arg,
9362                                         const struct bpf_reg_state *reg)
9363 {
9364         const struct btf_type *t;
9365
9366         t = btf_type_skip_modifiers(btf, arg->type, NULL);
9367         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
9368                 return false;
9369
9370         return __kfunc_param_match_suffix(btf, arg, "__szk");
9371 }
9372
9373 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
9374 {
9375         return __kfunc_param_match_suffix(btf, arg, "__k");
9376 }
9377
9378 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
9379 {
9380         return __kfunc_param_match_suffix(btf, arg, "__ign");
9381 }
9382
9383 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
9384 {
9385         return __kfunc_param_match_suffix(btf, arg, "__alloc");
9386 }
9387
9388 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
9389 {
9390         return __kfunc_param_match_suffix(btf, arg, "__uninit");
9391 }
9392
9393 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
9394                                           const struct btf_param *arg,
9395                                           const char *name)
9396 {
9397         int len, target_len = strlen(name);
9398         const char *param_name;
9399
9400         param_name = btf_name_by_offset(btf, arg->name_off);
9401         if (str_is_empty(param_name))
9402                 return false;
9403         len = strlen(param_name);
9404         if (len != target_len)
9405                 return false;
9406         if (strcmp(param_name, name))
9407                 return false;
9408
9409         return true;
9410 }
9411
9412 enum {
9413         KF_ARG_DYNPTR_ID,
9414         KF_ARG_LIST_HEAD_ID,
9415         KF_ARG_LIST_NODE_ID,
9416         KF_ARG_RB_ROOT_ID,
9417         KF_ARG_RB_NODE_ID,
9418 };
9419
9420 BTF_ID_LIST(kf_arg_btf_ids)
9421 BTF_ID(struct, bpf_dynptr_kern)
9422 BTF_ID(struct, bpf_list_head)
9423 BTF_ID(struct, bpf_list_node)
9424 BTF_ID(struct, bpf_rb_root)
9425 BTF_ID(struct, bpf_rb_node)
9426
9427 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
9428                                     const struct btf_param *arg, int type)
9429 {
9430         const struct btf_type *t;
9431         u32 res_id;
9432
9433         t = btf_type_skip_modifiers(btf, arg->type, NULL);
9434         if (!t)
9435                 return false;
9436         if (!btf_type_is_ptr(t))
9437                 return false;
9438         t = btf_type_skip_modifiers(btf, t->type, &res_id);
9439         if (!t)
9440                 return false;
9441         return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
9442 }
9443
9444 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
9445 {
9446         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
9447 }
9448
9449 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
9450 {
9451         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
9452 }
9453
9454 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
9455 {
9456         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
9457 }
9458
9459 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
9460 {
9461         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
9462 }
9463
9464 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
9465 {
9466         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
9467 }
9468
9469 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
9470                                   const struct btf_param *arg)
9471 {
9472         const struct btf_type *t;
9473
9474         t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
9475         if (!t)
9476                 return false;
9477
9478         return true;
9479 }
9480
9481 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
9482 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
9483                                         const struct btf *btf,
9484                                         const struct btf_type *t, int rec)
9485 {
9486         const struct btf_type *member_type;
9487         const struct btf_member *member;
9488         u32 i;
9489
9490         if (!btf_type_is_struct(t))
9491                 return false;
9492
9493         for_each_member(i, t, member) {
9494                 const struct btf_array *array;
9495
9496                 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
9497                 if (btf_type_is_struct(member_type)) {
9498                         if (rec >= 3) {
9499                                 verbose(env, "max struct nesting depth exceeded\n");
9500                                 return false;
9501                         }
9502                         if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
9503                                 return false;
9504                         continue;
9505                 }
9506                 if (btf_type_is_array(member_type)) {
9507                         array = btf_array(member_type);
9508                         if (!array->nelems)
9509                                 return false;
9510                         member_type = btf_type_skip_modifiers(btf, array->type, NULL);
9511                         if (!btf_type_is_scalar(member_type))
9512                                 return false;
9513                         continue;
9514                 }
9515                 if (!btf_type_is_scalar(member_type))
9516                         return false;
9517         }
9518         return true;
9519 }
9520
9521
9522 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
9523 #ifdef CONFIG_NET
9524         [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
9525         [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9526         [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
9527 #endif
9528 };
9529
9530 enum kfunc_ptr_arg_type {
9531         KF_ARG_PTR_TO_CTX,
9532         KF_ARG_PTR_TO_ALLOC_BTF_ID,  /* Allocated object */
9533         KF_ARG_PTR_TO_KPTR,          /* PTR_TO_KPTR but type specific */
9534         KF_ARG_PTR_TO_DYNPTR,
9535         KF_ARG_PTR_TO_ITER,
9536         KF_ARG_PTR_TO_LIST_HEAD,
9537         KF_ARG_PTR_TO_LIST_NODE,
9538         KF_ARG_PTR_TO_BTF_ID,        /* Also covers reg2btf_ids conversions */
9539         KF_ARG_PTR_TO_MEM,
9540         KF_ARG_PTR_TO_MEM_SIZE,      /* Size derived from next argument, skip it */
9541         KF_ARG_PTR_TO_CALLBACK,
9542         KF_ARG_PTR_TO_RB_ROOT,
9543         KF_ARG_PTR_TO_RB_NODE,
9544 };
9545
9546 enum special_kfunc_type {
9547         KF_bpf_obj_new_impl,
9548         KF_bpf_obj_drop_impl,
9549         KF_bpf_list_push_front,
9550         KF_bpf_list_push_back,
9551         KF_bpf_list_pop_front,
9552         KF_bpf_list_pop_back,
9553         KF_bpf_cast_to_kern_ctx,
9554         KF_bpf_rdonly_cast,
9555         KF_bpf_rcu_read_lock,
9556         KF_bpf_rcu_read_unlock,
9557         KF_bpf_rbtree_remove,
9558         KF_bpf_rbtree_add,
9559         KF_bpf_rbtree_first,
9560         KF_bpf_dynptr_from_skb,
9561         KF_bpf_dynptr_from_xdp,
9562         KF_bpf_dynptr_slice,
9563         KF_bpf_dynptr_slice_rdwr,
9564 };
9565
9566 BTF_SET_START(special_kfunc_set)
9567 BTF_ID(func, bpf_obj_new_impl)
9568 BTF_ID(func, bpf_obj_drop_impl)
9569 BTF_ID(func, bpf_list_push_front)
9570 BTF_ID(func, bpf_list_push_back)
9571 BTF_ID(func, bpf_list_pop_front)
9572 BTF_ID(func, bpf_list_pop_back)
9573 BTF_ID(func, bpf_cast_to_kern_ctx)
9574 BTF_ID(func, bpf_rdonly_cast)
9575 BTF_ID(func, bpf_rbtree_remove)
9576 BTF_ID(func, bpf_rbtree_add)
9577 BTF_ID(func, bpf_rbtree_first)
9578 BTF_ID(func, bpf_dynptr_from_skb)
9579 BTF_ID(func, bpf_dynptr_from_xdp)
9580 BTF_ID(func, bpf_dynptr_slice)
9581 BTF_ID(func, bpf_dynptr_slice_rdwr)
9582 BTF_SET_END(special_kfunc_set)
9583
9584 BTF_ID_LIST(special_kfunc_list)
9585 BTF_ID(func, bpf_obj_new_impl)
9586 BTF_ID(func, bpf_obj_drop_impl)
9587 BTF_ID(func, bpf_list_push_front)
9588 BTF_ID(func, bpf_list_push_back)
9589 BTF_ID(func, bpf_list_pop_front)
9590 BTF_ID(func, bpf_list_pop_back)
9591 BTF_ID(func, bpf_cast_to_kern_ctx)
9592 BTF_ID(func, bpf_rdonly_cast)
9593 BTF_ID(func, bpf_rcu_read_lock)
9594 BTF_ID(func, bpf_rcu_read_unlock)
9595 BTF_ID(func, bpf_rbtree_remove)
9596 BTF_ID(func, bpf_rbtree_add)
9597 BTF_ID(func, bpf_rbtree_first)
9598 BTF_ID(func, bpf_dynptr_from_skb)
9599 BTF_ID(func, bpf_dynptr_from_xdp)
9600 BTF_ID(func, bpf_dynptr_slice)
9601 BTF_ID(func, bpf_dynptr_slice_rdwr)
9602
9603 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
9604 {
9605         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
9606 }
9607
9608 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
9609 {
9610         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
9611 }
9612
9613 static enum kfunc_ptr_arg_type
9614 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
9615                        struct bpf_kfunc_call_arg_meta *meta,
9616                        const struct btf_type *t, const struct btf_type *ref_t,
9617                        const char *ref_tname, const struct btf_param *args,
9618                        int argno, int nargs)
9619 {
9620         u32 regno = argno + 1;
9621         struct bpf_reg_state *regs = cur_regs(env);
9622         struct bpf_reg_state *reg = &regs[regno];
9623         bool arg_mem_size = false;
9624
9625         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
9626                 return KF_ARG_PTR_TO_CTX;
9627
9628         /* In this function, we verify the kfunc's BTF as per the argument type,
9629          * leaving the rest of the verification with respect to the register
9630          * type to our caller. When a set of conditions hold in the BTF type of
9631          * arguments, we resolve it to a known kfunc_ptr_arg_type.
9632          */
9633         if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
9634                 return KF_ARG_PTR_TO_CTX;
9635
9636         if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
9637                 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
9638
9639         if (is_kfunc_arg_kptr_get(meta, argno)) {
9640                 if (!btf_type_is_ptr(ref_t)) {
9641                         verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n");
9642                         return -EINVAL;
9643                 }
9644                 ref_t = btf_type_by_id(meta->btf, ref_t->type);
9645                 ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off);
9646                 if (!btf_type_is_struct(ref_t)) {
9647                         verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n",
9648                                 meta->func_name, btf_type_str(ref_t), ref_tname);
9649                         return -EINVAL;
9650                 }
9651                 return KF_ARG_PTR_TO_KPTR;
9652         }
9653
9654         if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
9655                 return KF_ARG_PTR_TO_DYNPTR;
9656
9657         if (is_kfunc_arg_iter(meta, argno))
9658                 return KF_ARG_PTR_TO_ITER;
9659
9660         if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
9661                 return KF_ARG_PTR_TO_LIST_HEAD;
9662
9663         if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
9664                 return KF_ARG_PTR_TO_LIST_NODE;
9665
9666         if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
9667                 return KF_ARG_PTR_TO_RB_ROOT;
9668
9669         if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
9670                 return KF_ARG_PTR_TO_RB_NODE;
9671
9672         if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
9673                 if (!btf_type_is_struct(ref_t)) {
9674                         verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
9675                                 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
9676                         return -EINVAL;
9677                 }
9678                 return KF_ARG_PTR_TO_BTF_ID;
9679         }
9680
9681         if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
9682                 return KF_ARG_PTR_TO_CALLBACK;
9683
9684
9685         if (argno + 1 < nargs &&
9686             (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
9687              is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
9688                 arg_mem_size = true;
9689
9690         /* This is the catch all argument type of register types supported by
9691          * check_helper_mem_access. However, we only allow when argument type is
9692          * pointer to scalar, or struct composed (recursively) of scalars. When
9693          * arg_mem_size is true, the pointer can be void *.
9694          */
9695         if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
9696             (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
9697                 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
9698                         argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
9699                 return -EINVAL;
9700         }
9701         return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
9702 }
9703
9704 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
9705                                         struct bpf_reg_state *reg,
9706                                         const struct btf_type *ref_t,
9707                                         const char *ref_tname, u32 ref_id,
9708                                         struct bpf_kfunc_call_arg_meta *meta,
9709                                         int argno)
9710 {
9711         const struct btf_type *reg_ref_t;
9712         bool strict_type_match = false;
9713         const struct btf *reg_btf;
9714         const char *reg_ref_tname;
9715         u32 reg_ref_id;
9716
9717         if (base_type(reg->type) == PTR_TO_BTF_ID) {
9718                 reg_btf = reg->btf;
9719                 reg_ref_id = reg->btf_id;
9720         } else {
9721                 reg_btf = btf_vmlinux;
9722                 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
9723         }
9724
9725         /* Enforce strict type matching for calls to kfuncs that are acquiring
9726          * or releasing a reference, or are no-cast aliases. We do _not_
9727          * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
9728          * as we want to enable BPF programs to pass types that are bitwise
9729          * equivalent without forcing them to explicitly cast with something
9730          * like bpf_cast_to_kern_ctx().
9731          *
9732          * For example, say we had a type like the following:
9733          *
9734          * struct bpf_cpumask {
9735          *      cpumask_t cpumask;
9736          *      refcount_t usage;
9737          * };
9738          *
9739          * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
9740          * to a struct cpumask, so it would be safe to pass a struct
9741          * bpf_cpumask * to a kfunc expecting a struct cpumask *.
9742          *
9743          * The philosophy here is similar to how we allow scalars of different
9744          * types to be passed to kfuncs as long as the size is the same. The
9745          * only difference here is that we're simply allowing
9746          * btf_struct_ids_match() to walk the struct at the 0th offset, and
9747          * resolve types.
9748          */
9749         if (is_kfunc_acquire(meta) ||
9750             (is_kfunc_release(meta) && reg->ref_obj_id) ||
9751             btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
9752                 strict_type_match = true;
9753
9754         WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
9755
9756         reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
9757         reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
9758         if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
9759                 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
9760                         meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
9761                         btf_type_str(reg_ref_t), reg_ref_tname);
9762                 return -EINVAL;
9763         }
9764         return 0;
9765 }
9766
9767 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env,
9768                                       struct bpf_reg_state *reg,
9769                                       const struct btf_type *ref_t,
9770                                       const char *ref_tname,
9771                                       struct bpf_kfunc_call_arg_meta *meta,
9772                                       int argno)
9773 {
9774         struct btf_field *kptr_field;
9775
9776         /* check_func_arg_reg_off allows var_off for
9777          * PTR_TO_MAP_VALUE, but we need fixed offset to find
9778          * off_desc.
9779          */
9780         if (!tnum_is_const(reg->var_off)) {
9781                 verbose(env, "arg#0 must have constant offset\n");
9782                 return -EINVAL;
9783         }
9784
9785         kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR);
9786         if (!kptr_field || kptr_field->type != BPF_KPTR_REF) {
9787                 verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n",
9788                         reg->off + reg->var_off.value);
9789                 return -EINVAL;
9790         }
9791
9792         if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf,
9793                                   kptr_field->kptr.btf_id, true)) {
9794                 verbose(env, "kernel function %s args#%d expected pointer to %s %s\n",
9795                         meta->func_name, argno, btf_type_str(ref_t), ref_tname);
9796                 return -EINVAL;
9797         }
9798         return 0;
9799 }
9800
9801 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9802 {
9803         struct bpf_verifier_state *state = env->cur_state;
9804
9805         if (!state->active_lock.ptr) {
9806                 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
9807                 return -EFAULT;
9808         }
9809
9810         if (type_flag(reg->type) & NON_OWN_REF) {
9811                 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
9812                 return -EFAULT;
9813         }
9814
9815         reg->type |= NON_OWN_REF;
9816         return 0;
9817 }
9818
9819 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
9820 {
9821         struct bpf_func_state *state, *unused;
9822         struct bpf_reg_state *reg;
9823         int i;
9824
9825         state = cur_func(env);
9826
9827         if (!ref_obj_id) {
9828                 verbose(env, "verifier internal error: ref_obj_id is zero for "
9829                              "owning -> non-owning conversion\n");
9830                 return -EFAULT;
9831         }
9832
9833         for (i = 0; i < state->acquired_refs; i++) {
9834                 if (state->refs[i].id != ref_obj_id)
9835                         continue;
9836
9837                 /* Clear ref_obj_id here so release_reference doesn't clobber
9838                  * the whole reg
9839                  */
9840                 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9841                         if (reg->ref_obj_id == ref_obj_id) {
9842                                 reg->ref_obj_id = 0;
9843                                 ref_set_non_owning(env, reg);
9844                         }
9845                 }));
9846                 return 0;
9847         }
9848
9849         verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
9850         return -EFAULT;
9851 }
9852
9853 /* Implementation details:
9854  *
9855  * Each register points to some region of memory, which we define as an
9856  * allocation. Each allocation may embed a bpf_spin_lock which protects any
9857  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
9858  * allocation. The lock and the data it protects are colocated in the same
9859  * memory region.
9860  *
9861  * Hence, everytime a register holds a pointer value pointing to such
9862  * allocation, the verifier preserves a unique reg->id for it.
9863  *
9864  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
9865  * bpf_spin_lock is called.
9866  *
9867  * To enable this, lock state in the verifier captures two values:
9868  *      active_lock.ptr = Register's type specific pointer
9869  *      active_lock.id  = A unique ID for each register pointer value
9870  *
9871  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
9872  * supported register types.
9873  *
9874  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
9875  * allocated objects is the reg->btf pointer.
9876  *
9877  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
9878  * can establish the provenance of the map value statically for each distinct
9879  * lookup into such maps. They always contain a single map value hence unique
9880  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
9881  *
9882  * So, in case of global variables, they use array maps with max_entries = 1,
9883  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
9884  * into the same map value as max_entries is 1, as described above).
9885  *
9886  * In case of inner map lookups, the inner map pointer has same map_ptr as the
9887  * outer map pointer (in verifier context), but each lookup into an inner map
9888  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
9889  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
9890  * will get different reg->id assigned to each lookup, hence different
9891  * active_lock.id.
9892  *
9893  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
9894  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
9895  * returned from bpf_obj_new. Each allocation receives a new reg->id.
9896  */
9897 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9898 {
9899         void *ptr;
9900         u32 id;
9901
9902         switch ((int)reg->type) {
9903         case PTR_TO_MAP_VALUE:
9904                 ptr = reg->map_ptr;
9905                 break;
9906         case PTR_TO_BTF_ID | MEM_ALLOC:
9907                 ptr = reg->btf;
9908                 break;
9909         default:
9910                 verbose(env, "verifier internal error: unknown reg type for lock check\n");
9911                 return -EFAULT;
9912         }
9913         id = reg->id;
9914
9915         if (!env->cur_state->active_lock.ptr)
9916                 return -EINVAL;
9917         if (env->cur_state->active_lock.ptr != ptr ||
9918             env->cur_state->active_lock.id != id) {
9919                 verbose(env, "held lock and object are not in the same allocation\n");
9920                 return -EINVAL;
9921         }
9922         return 0;
9923 }
9924
9925 static bool is_bpf_list_api_kfunc(u32 btf_id)
9926 {
9927         return btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
9928                btf_id == special_kfunc_list[KF_bpf_list_push_back] ||
9929                btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
9930                btf_id == special_kfunc_list[KF_bpf_list_pop_back];
9931 }
9932
9933 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
9934 {
9935         return btf_id == special_kfunc_list[KF_bpf_rbtree_add] ||
9936                btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
9937                btf_id == special_kfunc_list[KF_bpf_rbtree_first];
9938 }
9939
9940 static bool is_bpf_graph_api_kfunc(u32 btf_id)
9941 {
9942         return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id);
9943 }
9944
9945 static bool is_callback_calling_kfunc(u32 btf_id)
9946 {
9947         return btf_id == special_kfunc_list[KF_bpf_rbtree_add];
9948 }
9949
9950 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
9951 {
9952         return is_bpf_rbtree_api_kfunc(btf_id);
9953 }
9954
9955 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
9956                                           enum btf_field_type head_field_type,
9957                                           u32 kfunc_btf_id)
9958 {
9959         bool ret;
9960
9961         switch (head_field_type) {
9962         case BPF_LIST_HEAD:
9963                 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
9964                 break;
9965         case BPF_RB_ROOT:
9966                 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
9967                 break;
9968         default:
9969                 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
9970                         btf_field_type_name(head_field_type));
9971                 return false;
9972         }
9973
9974         if (!ret)
9975                 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
9976                         btf_field_type_name(head_field_type));
9977         return ret;
9978 }
9979
9980 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
9981                                           enum btf_field_type node_field_type,
9982                                           u32 kfunc_btf_id)
9983 {
9984         bool ret;
9985
9986         switch (node_field_type) {
9987         case BPF_LIST_NODE:
9988                 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front] ||
9989                        kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back]);
9990                 break;
9991         case BPF_RB_NODE:
9992                 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
9993                        kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add]);
9994                 break;
9995         default:
9996                 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
9997                         btf_field_type_name(node_field_type));
9998                 return false;
9999         }
10000
10001         if (!ret)
10002                 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10003                         btf_field_type_name(node_field_type));
10004         return ret;
10005 }
10006
10007 static int
10008 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10009                                    struct bpf_reg_state *reg, u32 regno,
10010                                    struct bpf_kfunc_call_arg_meta *meta,
10011                                    enum btf_field_type head_field_type,
10012                                    struct btf_field **head_field)
10013 {
10014         const char *head_type_name;
10015         struct btf_field *field;
10016         struct btf_record *rec;
10017         u32 head_off;
10018
10019         if (meta->btf != btf_vmlinux) {
10020                 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10021                 return -EFAULT;
10022         }
10023
10024         if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10025                 return -EFAULT;
10026
10027         head_type_name = btf_field_type_name(head_field_type);
10028         if (!tnum_is_const(reg->var_off)) {
10029                 verbose(env,
10030                         "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10031                         regno, head_type_name);
10032                 return -EINVAL;
10033         }
10034
10035         rec = reg_btf_record(reg);
10036         head_off = reg->off + reg->var_off.value;
10037         field = btf_record_find(rec, head_off, head_field_type);
10038         if (!field) {
10039                 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10040                 return -EINVAL;
10041         }
10042
10043         /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10044         if (check_reg_allocation_locked(env, reg)) {
10045                 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10046                         rec->spin_lock_off, head_type_name);
10047                 return -EINVAL;
10048         }
10049
10050         if (*head_field) {
10051                 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10052                 return -EFAULT;
10053         }
10054         *head_field = field;
10055         return 0;
10056 }
10057
10058 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10059                                            struct bpf_reg_state *reg, u32 regno,
10060                                            struct bpf_kfunc_call_arg_meta *meta)
10061 {
10062         return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10063                                                           &meta->arg_list_head.field);
10064 }
10065
10066 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10067                                              struct bpf_reg_state *reg, u32 regno,
10068                                              struct bpf_kfunc_call_arg_meta *meta)
10069 {
10070         return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10071                                                           &meta->arg_rbtree_root.field);
10072 }
10073
10074 static int
10075 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10076                                    struct bpf_reg_state *reg, u32 regno,
10077                                    struct bpf_kfunc_call_arg_meta *meta,
10078                                    enum btf_field_type head_field_type,
10079                                    enum btf_field_type node_field_type,
10080                                    struct btf_field **node_field)
10081 {
10082         const char *node_type_name;
10083         const struct btf_type *et, *t;
10084         struct btf_field *field;
10085         u32 node_off;
10086
10087         if (meta->btf != btf_vmlinux) {
10088                 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10089                 return -EFAULT;
10090         }
10091
10092         if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10093                 return -EFAULT;
10094
10095         node_type_name = btf_field_type_name(node_field_type);
10096         if (!tnum_is_const(reg->var_off)) {
10097                 verbose(env,
10098                         "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10099                         regno, node_type_name);
10100                 return -EINVAL;
10101         }
10102
10103         node_off = reg->off + reg->var_off.value;
10104         field = reg_find_field_offset(reg, node_off, node_field_type);
10105         if (!field || field->offset != node_off) {
10106                 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10107                 return -EINVAL;
10108         }
10109
10110         field = *node_field;
10111
10112         et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10113         t = btf_type_by_id(reg->btf, reg->btf_id);
10114         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10115                                   field->graph_root.value_btf_id, true)) {
10116                 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10117                         "in struct %s, but arg is at offset=%d in struct %s\n",
10118                         btf_field_type_name(head_field_type),
10119                         btf_field_type_name(node_field_type),
10120                         field->graph_root.node_offset,
10121                         btf_name_by_offset(field->graph_root.btf, et->name_off),
10122                         node_off, btf_name_by_offset(reg->btf, t->name_off));
10123                 return -EINVAL;
10124         }
10125
10126         if (node_off != field->graph_root.node_offset) {
10127                 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10128                         node_off, btf_field_type_name(node_field_type),
10129                         field->graph_root.node_offset,
10130                         btf_name_by_offset(field->graph_root.btf, et->name_off));
10131                 return -EINVAL;
10132         }
10133
10134         return 0;
10135 }
10136
10137 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10138                                            struct bpf_reg_state *reg, u32 regno,
10139                                            struct bpf_kfunc_call_arg_meta *meta)
10140 {
10141         return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10142                                                   BPF_LIST_HEAD, BPF_LIST_NODE,
10143                                                   &meta->arg_list_head.field);
10144 }
10145
10146 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10147                                              struct bpf_reg_state *reg, u32 regno,
10148                                              struct bpf_kfunc_call_arg_meta *meta)
10149 {
10150         return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10151                                                   BPF_RB_ROOT, BPF_RB_NODE,
10152                                                   &meta->arg_rbtree_root.field);
10153 }
10154
10155 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10156                             int insn_idx)
10157 {
10158         const char *func_name = meta->func_name, *ref_tname;
10159         const struct btf *btf = meta->btf;
10160         const struct btf_param *args;
10161         u32 i, nargs;
10162         int ret;
10163
10164         args = (const struct btf_param *)(meta->func_proto + 1);
10165         nargs = btf_type_vlen(meta->func_proto);
10166         if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10167                 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10168                         MAX_BPF_FUNC_REG_ARGS);
10169                 return -EINVAL;
10170         }
10171
10172         /* Check that BTF function arguments match actual types that the
10173          * verifier sees.
10174          */
10175         for (i = 0; i < nargs; i++) {
10176                 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
10177                 const struct btf_type *t, *ref_t, *resolve_ret;
10178                 enum bpf_arg_type arg_type = ARG_DONTCARE;
10179                 u32 regno = i + 1, ref_id, type_size;
10180                 bool is_ret_buf_sz = false;
10181                 int kf_arg_type;
10182
10183                 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10184
10185                 if (is_kfunc_arg_ignore(btf, &args[i]))
10186                         continue;
10187
10188                 if (btf_type_is_scalar(t)) {
10189                         if (reg->type != SCALAR_VALUE) {
10190                                 verbose(env, "R%d is not a scalar\n", regno);
10191                                 return -EINVAL;
10192                         }
10193
10194                         if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10195                                 if (meta->arg_constant.found) {
10196                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
10197                                         return -EFAULT;
10198                                 }
10199                                 if (!tnum_is_const(reg->var_off)) {
10200                                         verbose(env, "R%d must be a known constant\n", regno);
10201                                         return -EINVAL;
10202                                 }
10203                                 ret = mark_chain_precision(env, regno);
10204                                 if (ret < 0)
10205                                         return ret;
10206                                 meta->arg_constant.found = true;
10207                                 meta->arg_constant.value = reg->var_off.value;
10208                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10209                                 meta->r0_rdonly = true;
10210                                 is_ret_buf_sz = true;
10211                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10212                                 is_ret_buf_sz = true;
10213                         }
10214
10215                         if (is_ret_buf_sz) {
10216                                 if (meta->r0_size) {
10217                                         verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10218                                         return -EINVAL;
10219                                 }
10220
10221                                 if (!tnum_is_const(reg->var_off)) {
10222                                         verbose(env, "R%d is not a const\n", regno);
10223                                         return -EINVAL;
10224                                 }
10225
10226                                 meta->r0_size = reg->var_off.value;
10227                                 ret = mark_chain_precision(env, regno);
10228                                 if (ret)
10229                                         return ret;
10230                         }
10231                         continue;
10232                 }
10233
10234                 if (!btf_type_is_ptr(t)) {
10235                         verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10236                         return -EINVAL;
10237                 }
10238
10239                 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10240                     (register_is_null(reg) || type_may_be_null(reg->type))) {
10241                         verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10242                         return -EACCES;
10243                 }
10244
10245                 if (reg->ref_obj_id) {
10246                         if (is_kfunc_release(meta) && meta->ref_obj_id) {
10247                                 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10248                                         regno, reg->ref_obj_id,
10249                                         meta->ref_obj_id);
10250                                 return -EFAULT;
10251                         }
10252                         meta->ref_obj_id = reg->ref_obj_id;
10253                         if (is_kfunc_release(meta))
10254                                 meta->release_regno = regno;
10255                 }
10256
10257                 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10258                 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10259
10260                 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10261                 if (kf_arg_type < 0)
10262                         return kf_arg_type;
10263
10264                 switch (kf_arg_type) {
10265                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10266                 case KF_ARG_PTR_TO_BTF_ID:
10267                         if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10268                                 break;
10269
10270                         if (!is_trusted_reg(reg)) {
10271                                 if (!is_kfunc_rcu(meta)) {
10272                                         verbose(env, "R%d must be referenced or trusted\n", regno);
10273                                         return -EINVAL;
10274                                 }
10275                                 if (!is_rcu_reg(reg)) {
10276                                         verbose(env, "R%d must be a rcu pointer\n", regno);
10277                                         return -EINVAL;
10278                                 }
10279                         }
10280
10281                         fallthrough;
10282                 case KF_ARG_PTR_TO_CTX:
10283                         /* Trusted arguments have the same offset checks as release arguments */
10284                         arg_type |= OBJ_RELEASE;
10285                         break;
10286                 case KF_ARG_PTR_TO_KPTR:
10287                 case KF_ARG_PTR_TO_DYNPTR:
10288                 case KF_ARG_PTR_TO_ITER:
10289                 case KF_ARG_PTR_TO_LIST_HEAD:
10290                 case KF_ARG_PTR_TO_LIST_NODE:
10291                 case KF_ARG_PTR_TO_RB_ROOT:
10292                 case KF_ARG_PTR_TO_RB_NODE:
10293                 case KF_ARG_PTR_TO_MEM:
10294                 case KF_ARG_PTR_TO_MEM_SIZE:
10295                 case KF_ARG_PTR_TO_CALLBACK:
10296                         /* Trusted by default */
10297                         break;
10298                 default:
10299                         WARN_ON_ONCE(1);
10300                         return -EFAULT;
10301                 }
10302
10303                 if (is_kfunc_release(meta) && reg->ref_obj_id)
10304                         arg_type |= OBJ_RELEASE;
10305                 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
10306                 if (ret < 0)
10307                         return ret;
10308
10309                 switch (kf_arg_type) {
10310                 case KF_ARG_PTR_TO_CTX:
10311                         if (reg->type != PTR_TO_CTX) {
10312                                 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
10313                                 return -EINVAL;
10314                         }
10315
10316                         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10317                                 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
10318                                 if (ret < 0)
10319                                         return -EINVAL;
10320                                 meta->ret_btf_id  = ret;
10321                         }
10322                         break;
10323                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10324                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10325                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
10326                                 return -EINVAL;
10327                         }
10328                         if (!reg->ref_obj_id) {
10329                                 verbose(env, "allocated object must be referenced\n");
10330                                 return -EINVAL;
10331                         }
10332                         if (meta->btf == btf_vmlinux &&
10333                             meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
10334                                 meta->arg_obj_drop.btf = reg->btf;
10335                                 meta->arg_obj_drop.btf_id = reg->btf_id;
10336                         }
10337                         break;
10338                 case KF_ARG_PTR_TO_KPTR:
10339                         if (reg->type != PTR_TO_MAP_VALUE) {
10340                                 verbose(env, "arg#0 expected pointer to map value\n");
10341                                 return -EINVAL;
10342                         }
10343                         ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i);
10344                         if (ret < 0)
10345                                 return ret;
10346                         break;
10347                 case KF_ARG_PTR_TO_DYNPTR:
10348                 {
10349                         enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
10350
10351                         if (reg->type != PTR_TO_STACK &&
10352                             reg->type != CONST_PTR_TO_DYNPTR) {
10353                                 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
10354                                 return -EINVAL;
10355                         }
10356
10357                         if (reg->type == CONST_PTR_TO_DYNPTR)
10358                                 dynptr_arg_type |= MEM_RDONLY;
10359
10360                         if (is_kfunc_arg_uninit(btf, &args[i]))
10361                                 dynptr_arg_type |= MEM_UNINIT;
10362
10363                         if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb])
10364                                 dynptr_arg_type |= DYNPTR_TYPE_SKB;
10365                         else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp])
10366                                 dynptr_arg_type |= DYNPTR_TYPE_XDP;
10367
10368                         ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type);
10369                         if (ret < 0)
10370                                 return ret;
10371
10372                         if (!(dynptr_arg_type & MEM_UNINIT)) {
10373                                 int id = dynptr_id(env, reg);
10374
10375                                 if (id < 0) {
10376                                         verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10377                                         return id;
10378                                 }
10379                                 meta->initialized_dynptr.id = id;
10380                                 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
10381                         }
10382
10383                         break;
10384                 }
10385                 case KF_ARG_PTR_TO_ITER:
10386                         ret = process_iter_arg(env, regno, insn_idx, meta);
10387                         if (ret < 0)
10388                                 return ret;
10389                         break;
10390                 case KF_ARG_PTR_TO_LIST_HEAD:
10391                         if (reg->type != PTR_TO_MAP_VALUE &&
10392                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10393                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10394                                 return -EINVAL;
10395                         }
10396                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10397                                 verbose(env, "allocated object must be referenced\n");
10398                                 return -EINVAL;
10399                         }
10400                         ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
10401                         if (ret < 0)
10402                                 return ret;
10403                         break;
10404                 case KF_ARG_PTR_TO_RB_ROOT:
10405                         if (reg->type != PTR_TO_MAP_VALUE &&
10406                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10407                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
10408                                 return -EINVAL;
10409                         }
10410                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
10411                                 verbose(env, "allocated object must be referenced\n");
10412                                 return -EINVAL;
10413                         }
10414                         ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
10415                         if (ret < 0)
10416                                 return ret;
10417                         break;
10418                 case KF_ARG_PTR_TO_LIST_NODE:
10419                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10420                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
10421                                 return -EINVAL;
10422                         }
10423                         if (!reg->ref_obj_id) {
10424                                 verbose(env, "allocated object must be referenced\n");
10425                                 return -EINVAL;
10426                         }
10427                         ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
10428                         if (ret < 0)
10429                                 return ret;
10430                         break;
10431                 case KF_ARG_PTR_TO_RB_NODE:
10432                         if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
10433                                 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
10434                                         verbose(env, "rbtree_remove node input must be non-owning ref\n");
10435                                         return -EINVAL;
10436                                 }
10437                                 if (in_rbtree_lock_required_cb(env)) {
10438                                         verbose(env, "rbtree_remove not allowed in rbtree cb\n");
10439                                         return -EINVAL;
10440                                 }
10441                         } else {
10442                                 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
10443                                         verbose(env, "arg#%d expected pointer to allocated object\n", i);
10444                                         return -EINVAL;
10445                                 }
10446                                 if (!reg->ref_obj_id) {
10447                                         verbose(env, "allocated object must be referenced\n");
10448                                         return -EINVAL;
10449                                 }
10450                         }
10451
10452                         ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
10453                         if (ret < 0)
10454                                 return ret;
10455                         break;
10456                 case KF_ARG_PTR_TO_BTF_ID:
10457                         /* Only base_type is checked, further checks are done here */
10458                         if ((base_type(reg->type) != PTR_TO_BTF_ID ||
10459                              (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
10460                             !reg2btf_ids[base_type(reg->type)]) {
10461                                 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
10462                                 verbose(env, "expected %s or socket\n",
10463                                         reg_type_str(env, base_type(reg->type) |
10464                                                           (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
10465                                 return -EINVAL;
10466                         }
10467                         ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
10468                         if (ret < 0)
10469                                 return ret;
10470                         break;
10471                 case KF_ARG_PTR_TO_MEM:
10472                         resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
10473                         if (IS_ERR(resolve_ret)) {
10474                                 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
10475                                         i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
10476                                 return -EINVAL;
10477                         }
10478                         ret = check_mem_reg(env, reg, regno, type_size);
10479                         if (ret < 0)
10480                                 return ret;
10481                         break;
10482                 case KF_ARG_PTR_TO_MEM_SIZE:
10483                 {
10484                         struct bpf_reg_state *size_reg = &regs[regno + 1];
10485                         const struct btf_param *size_arg = &args[i + 1];
10486
10487                         ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
10488                         if (ret < 0) {
10489                                 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
10490                                 return ret;
10491                         }
10492
10493                         if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
10494                                 if (meta->arg_constant.found) {
10495                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
10496                                         return -EFAULT;
10497                                 }
10498                                 if (!tnum_is_const(size_reg->var_off)) {
10499                                         verbose(env, "R%d must be a known constant\n", regno + 1);
10500                                         return -EINVAL;
10501                                 }
10502                                 meta->arg_constant.found = true;
10503                                 meta->arg_constant.value = size_reg->var_off.value;
10504                         }
10505
10506                         /* Skip next '__sz' or '__szk' argument */
10507                         i++;
10508                         break;
10509                 }
10510                 case KF_ARG_PTR_TO_CALLBACK:
10511                         meta->subprogno = reg->subprogno;
10512                         break;
10513                 }
10514         }
10515
10516         if (is_kfunc_release(meta) && !meta->release_regno) {
10517                 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
10518                         func_name);
10519                 return -EINVAL;
10520         }
10521
10522         return 0;
10523 }
10524
10525 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
10526                             struct bpf_insn *insn,
10527                             struct bpf_kfunc_call_arg_meta *meta,
10528                             const char **kfunc_name)
10529 {
10530         const struct btf_type *func, *func_proto;
10531         u32 func_id, *kfunc_flags;
10532         const char *func_name;
10533         struct btf *desc_btf;
10534
10535         if (kfunc_name)
10536                 *kfunc_name = NULL;
10537
10538         if (!insn->imm)
10539                 return -EINVAL;
10540
10541         desc_btf = find_kfunc_desc_btf(env, insn->off);
10542         if (IS_ERR(desc_btf))
10543                 return PTR_ERR(desc_btf);
10544
10545         func_id = insn->imm;
10546         func = btf_type_by_id(desc_btf, func_id);
10547         func_name = btf_name_by_offset(desc_btf, func->name_off);
10548         if (kfunc_name)
10549                 *kfunc_name = func_name;
10550         func_proto = btf_type_by_id(desc_btf, func->type);
10551
10552         kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
10553         if (!kfunc_flags) {
10554                 return -EACCES;
10555         }
10556
10557         memset(meta, 0, sizeof(*meta));
10558         meta->btf = desc_btf;
10559         meta->func_id = func_id;
10560         meta->kfunc_flags = *kfunc_flags;
10561         meta->func_proto = func_proto;
10562         meta->func_name = func_name;
10563
10564         return 0;
10565 }
10566
10567 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10568                             int *insn_idx_p)
10569 {
10570         const struct btf_type *t, *ptr_type;
10571         u32 i, nargs, ptr_type_id, release_ref_obj_id;
10572         struct bpf_reg_state *regs = cur_regs(env);
10573         const char *func_name, *ptr_type_name;
10574         bool sleepable, rcu_lock, rcu_unlock;
10575         struct bpf_kfunc_call_arg_meta meta;
10576         struct bpf_insn_aux_data *insn_aux;
10577         int err, insn_idx = *insn_idx_p;
10578         const struct btf_param *args;
10579         const struct btf_type *ret_t;
10580         struct btf *desc_btf;
10581
10582         /* skip for now, but return error when we find this in fixup_kfunc_call */
10583         if (!insn->imm)
10584                 return 0;
10585
10586         err = fetch_kfunc_meta(env, insn, &meta, &func_name);
10587         if (err == -EACCES && func_name)
10588                 verbose(env, "calling kernel function %s is not allowed\n", func_name);
10589         if (err)
10590                 return err;
10591         desc_btf = meta.btf;
10592         insn_aux = &env->insn_aux_data[insn_idx];
10593
10594         insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
10595
10596         if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
10597                 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
10598                 return -EACCES;
10599         }
10600
10601         sleepable = is_kfunc_sleepable(&meta);
10602         if (sleepable && !env->prog->aux->sleepable) {
10603                 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
10604                 return -EACCES;
10605         }
10606
10607         rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
10608         rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
10609
10610         if (env->cur_state->active_rcu_lock) {
10611                 struct bpf_func_state *state;
10612                 struct bpf_reg_state *reg;
10613
10614                 if (rcu_lock) {
10615                         verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
10616                         return -EINVAL;
10617                 } else if (rcu_unlock) {
10618                         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10619                                 if (reg->type & MEM_RCU) {
10620                                         reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
10621                                         reg->type |= PTR_UNTRUSTED;
10622                                 }
10623                         }));
10624                         env->cur_state->active_rcu_lock = false;
10625                 } else if (sleepable) {
10626                         verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
10627                         return -EACCES;
10628                 }
10629         } else if (rcu_lock) {
10630                 env->cur_state->active_rcu_lock = true;
10631         } else if (rcu_unlock) {
10632                 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
10633                 return -EINVAL;
10634         }
10635
10636         /* Check the arguments */
10637         err = check_kfunc_args(env, &meta, insn_idx);
10638         if (err < 0)
10639                 return err;
10640         /* In case of release function, we get register number of refcounted
10641          * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
10642          */
10643         if (meta.release_regno) {
10644                 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
10645                 if (err) {
10646                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
10647                                 func_name, meta.func_id);
10648                         return err;
10649                 }
10650         }
10651
10652         if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front] ||
10653             meta.func_id == special_kfunc_list[KF_bpf_list_push_back] ||
10654             meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) {
10655                 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
10656                 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
10657                 if (err) {
10658                         verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
10659                                 func_name, meta.func_id);
10660                         return err;
10661                 }
10662
10663                 err = release_reference(env, release_ref_obj_id);
10664                 if (err) {
10665                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
10666                                 func_name, meta.func_id);
10667                         return err;
10668                 }
10669         }
10670
10671         if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) {
10672                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
10673                                         set_rbtree_add_callback_state);
10674                 if (err) {
10675                         verbose(env, "kfunc %s#%d failed callback verification\n",
10676                                 func_name, meta.func_id);
10677                         return err;
10678                 }
10679         }
10680
10681         for (i = 0; i < CALLER_SAVED_REGS; i++)
10682                 mark_reg_not_init(env, regs, caller_saved[i]);
10683
10684         /* Check return type */
10685         t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
10686
10687         if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
10688                 /* Only exception is bpf_obj_new_impl */
10689                 if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) {
10690                         verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
10691                         return -EINVAL;
10692                 }
10693         }
10694
10695         if (btf_type_is_scalar(t)) {
10696                 mark_reg_unknown(env, regs, BPF_REG_0);
10697                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
10698         } else if (btf_type_is_ptr(t)) {
10699                 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
10700
10701                 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
10702                         if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
10703                                 struct btf *ret_btf;
10704                                 u32 ret_btf_id;
10705
10706                                 if (unlikely(!bpf_global_ma_set))
10707                                         return -ENOMEM;
10708
10709                                 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
10710                                         verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
10711                                         return -EINVAL;
10712                                 }
10713
10714                                 ret_btf = env->prog->aux->btf;
10715                                 ret_btf_id = meta.arg_constant.value;
10716
10717                                 /* This may be NULL due to user not supplying a BTF */
10718                                 if (!ret_btf) {
10719                                         verbose(env, "bpf_obj_new requires prog BTF\n");
10720                                         return -EINVAL;
10721                                 }
10722
10723                                 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
10724                                 if (!ret_t || !__btf_type_is_struct(ret_t)) {
10725                                         verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
10726                                         return -EINVAL;
10727                                 }
10728
10729                                 mark_reg_known_zero(env, regs, BPF_REG_0);
10730                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
10731                                 regs[BPF_REG_0].btf = ret_btf;
10732                                 regs[BPF_REG_0].btf_id = ret_btf_id;
10733
10734                                 insn_aux->obj_new_size = ret_t->size;
10735                                 insn_aux->kptr_struct_meta =
10736                                         btf_find_struct_meta(ret_btf, ret_btf_id);
10737                         } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10738                                    meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
10739                                 struct btf_field *field = meta.arg_list_head.field;
10740
10741                                 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
10742                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10743                                    meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
10744                                 struct btf_field *field = meta.arg_rbtree_root.field;
10745
10746                                 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
10747                         } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10748                                 mark_reg_known_zero(env, regs, BPF_REG_0);
10749                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
10750                                 regs[BPF_REG_0].btf = desc_btf;
10751                                 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10752                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
10753                                 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
10754                                 if (!ret_t || !btf_type_is_struct(ret_t)) {
10755                                         verbose(env,
10756                                                 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
10757                                         return -EINVAL;
10758                                 }
10759
10760                                 mark_reg_known_zero(env, regs, BPF_REG_0);
10761                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
10762                                 regs[BPF_REG_0].btf = desc_btf;
10763                                 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
10764                         } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
10765                                    meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
10766                                 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
10767
10768                                 mark_reg_known_zero(env, regs, BPF_REG_0);
10769
10770                                 if (!meta.arg_constant.found) {
10771                                         verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
10772                                         return -EFAULT;
10773                                 }
10774
10775                                 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
10776
10777                                 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
10778                                 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
10779
10780                                 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
10781                                         regs[BPF_REG_0].type |= MEM_RDONLY;
10782                                 } else {
10783                                         /* this will set env->seen_direct_write to true */
10784                                         if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
10785                                                 verbose(env, "the prog does not allow writes to packet data\n");
10786                                                 return -EINVAL;
10787                                         }
10788                                 }
10789
10790                                 if (!meta.initialized_dynptr.id) {
10791                                         verbose(env, "verifier internal error: no dynptr id\n");
10792                                         return -EFAULT;
10793                                 }
10794                                 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
10795
10796                                 /* we don't need to set BPF_REG_0's ref obj id
10797                                  * because packet slices are not refcounted (see
10798                                  * dynptr_type_refcounted)
10799                                  */
10800                         } else {
10801                                 verbose(env, "kernel function %s unhandled dynamic return type\n",
10802                                         meta.func_name);
10803                                 return -EFAULT;
10804                         }
10805                 } else if (!__btf_type_is_struct(ptr_type)) {
10806                         if (!meta.r0_size) {
10807                                 __u32 sz;
10808
10809                                 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
10810                                         meta.r0_size = sz;
10811                                         meta.r0_rdonly = true;
10812                                 }
10813                         }
10814                         if (!meta.r0_size) {
10815                                 ptr_type_name = btf_name_by_offset(desc_btf,
10816                                                                    ptr_type->name_off);
10817                                 verbose(env,
10818                                         "kernel function %s returns pointer type %s %s is not supported\n",
10819                                         func_name,
10820                                         btf_type_str(ptr_type),
10821                                         ptr_type_name);
10822                                 return -EINVAL;
10823                         }
10824
10825                         mark_reg_known_zero(env, regs, BPF_REG_0);
10826                         regs[BPF_REG_0].type = PTR_TO_MEM;
10827                         regs[BPF_REG_0].mem_size = meta.r0_size;
10828
10829                         if (meta.r0_rdonly)
10830                                 regs[BPF_REG_0].type |= MEM_RDONLY;
10831
10832                         /* Ensures we don't access the memory after a release_reference() */
10833                         if (meta.ref_obj_id)
10834                                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10835                 } else {
10836                         mark_reg_known_zero(env, regs, BPF_REG_0);
10837                         regs[BPF_REG_0].btf = desc_btf;
10838                         regs[BPF_REG_0].type = PTR_TO_BTF_ID;
10839                         regs[BPF_REG_0].btf_id = ptr_type_id;
10840                 }
10841
10842                 if (is_kfunc_ret_null(&meta)) {
10843                         regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
10844                         /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
10845                         regs[BPF_REG_0].id = ++env->id_gen;
10846                 }
10847                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
10848                 if (is_kfunc_acquire(&meta)) {
10849                         int id = acquire_reference_state(env, insn_idx);
10850
10851                         if (id < 0)
10852                                 return id;
10853                         if (is_kfunc_ret_null(&meta))
10854                                 regs[BPF_REG_0].id = id;
10855                         regs[BPF_REG_0].ref_obj_id = id;
10856                 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
10857                         ref_set_non_owning(env, &regs[BPF_REG_0]);
10858                 }
10859
10860                 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove])
10861                         invalidate_non_owning_refs(env);
10862
10863                 if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
10864                         regs[BPF_REG_0].id = ++env->id_gen;
10865         } else if (btf_type_is_void(t)) {
10866                 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
10867                         if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
10868                                 insn_aux->kptr_struct_meta =
10869                                         btf_find_struct_meta(meta.arg_obj_drop.btf,
10870                                                              meta.arg_obj_drop.btf_id);
10871                         }
10872                 }
10873         }
10874
10875         nargs = btf_type_vlen(meta.func_proto);
10876         args = (const struct btf_param *)(meta.func_proto + 1);
10877         for (i = 0; i < nargs; i++) {
10878                 u32 regno = i + 1;
10879
10880                 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
10881                 if (btf_type_is_ptr(t))
10882                         mark_btf_func_reg_size(env, regno, sizeof(void *));
10883                 else
10884                         /* scalar. ensured by btf_check_kfunc_arg_match() */
10885                         mark_btf_func_reg_size(env, regno, t->size);
10886         }
10887
10888         if (is_iter_next_kfunc(&meta)) {
10889                 err = process_iter_next_call(env, insn_idx, &meta);
10890                 if (err)
10891                         return err;
10892         }
10893
10894         return 0;
10895 }
10896
10897 static bool signed_add_overflows(s64 a, s64 b)
10898 {
10899         /* Do the add in u64, where overflow is well-defined */
10900         s64 res = (s64)((u64)a + (u64)b);
10901
10902         if (b < 0)
10903                 return res > a;
10904         return res < a;
10905 }
10906
10907 static bool signed_add32_overflows(s32 a, s32 b)
10908 {
10909         /* Do the add in u32, where overflow is well-defined */
10910         s32 res = (s32)((u32)a + (u32)b);
10911
10912         if (b < 0)
10913                 return res > a;
10914         return res < a;
10915 }
10916
10917 static bool signed_sub_overflows(s64 a, s64 b)
10918 {
10919         /* Do the sub in u64, where overflow is well-defined */
10920         s64 res = (s64)((u64)a - (u64)b);
10921
10922         if (b < 0)
10923                 return res < a;
10924         return res > a;
10925 }
10926
10927 static bool signed_sub32_overflows(s32 a, s32 b)
10928 {
10929         /* Do the sub in u32, where overflow is well-defined */
10930         s32 res = (s32)((u32)a - (u32)b);
10931
10932         if (b < 0)
10933                 return res < a;
10934         return res > a;
10935 }
10936
10937 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
10938                                   const struct bpf_reg_state *reg,
10939                                   enum bpf_reg_type type)
10940 {
10941         bool known = tnum_is_const(reg->var_off);
10942         s64 val = reg->var_off.value;
10943         s64 smin = reg->smin_value;
10944
10945         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
10946                 verbose(env, "math between %s pointer and %lld is not allowed\n",
10947                         reg_type_str(env, type), val);
10948                 return false;
10949         }
10950
10951         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
10952                 verbose(env, "%s pointer offset %d is not allowed\n",
10953                         reg_type_str(env, type), reg->off);
10954                 return false;
10955         }
10956
10957         if (smin == S64_MIN) {
10958                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
10959                         reg_type_str(env, type));
10960                 return false;
10961         }
10962
10963         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
10964                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
10965                         smin, reg_type_str(env, type));
10966                 return false;
10967         }
10968
10969         return true;
10970 }
10971
10972 enum {
10973         REASON_BOUNDS   = -1,
10974         REASON_TYPE     = -2,
10975         REASON_PATHS    = -3,
10976         REASON_LIMIT    = -4,
10977         REASON_STACK    = -5,
10978 };
10979
10980 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
10981                               u32 *alu_limit, bool mask_to_left)
10982 {
10983         u32 max = 0, ptr_limit = 0;
10984
10985         switch (ptr_reg->type) {
10986         case PTR_TO_STACK:
10987                 /* Offset 0 is out-of-bounds, but acceptable start for the
10988                  * left direction, see BPF_REG_FP. Also, unknown scalar
10989                  * offset where we would need to deal with min/max bounds is
10990                  * currently prohibited for unprivileged.
10991                  */
10992                 max = MAX_BPF_STACK + mask_to_left;
10993                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
10994                 break;
10995         case PTR_TO_MAP_VALUE:
10996                 max = ptr_reg->map_ptr->value_size;
10997                 ptr_limit = (mask_to_left ?
10998                              ptr_reg->smin_value :
10999                              ptr_reg->umax_value) + ptr_reg->off;
11000                 break;
11001         default:
11002                 return REASON_TYPE;
11003         }
11004
11005         if (ptr_limit >= max)
11006                 return REASON_LIMIT;
11007         *alu_limit = ptr_limit;
11008         return 0;
11009 }
11010
11011 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11012                                     const struct bpf_insn *insn)
11013 {
11014         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11015 }
11016
11017 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11018                                        u32 alu_state, u32 alu_limit)
11019 {
11020         /* If we arrived here from different branches with different
11021          * state or limits to sanitize, then this won't work.
11022          */
11023         if (aux->alu_state &&
11024             (aux->alu_state != alu_state ||
11025              aux->alu_limit != alu_limit))
11026                 return REASON_PATHS;
11027
11028         /* Corresponding fixup done in do_misc_fixups(). */
11029         aux->alu_state = alu_state;
11030         aux->alu_limit = alu_limit;
11031         return 0;
11032 }
11033
11034 static int sanitize_val_alu(struct bpf_verifier_env *env,
11035                             struct bpf_insn *insn)
11036 {
11037         struct bpf_insn_aux_data *aux = cur_aux(env);
11038
11039         if (can_skip_alu_sanitation(env, insn))
11040                 return 0;
11041
11042         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11043 }
11044
11045 static bool sanitize_needed(u8 opcode)
11046 {
11047         return opcode == BPF_ADD || opcode == BPF_SUB;
11048 }
11049
11050 struct bpf_sanitize_info {
11051         struct bpf_insn_aux_data aux;
11052         bool mask_to_left;
11053 };
11054
11055 static struct bpf_verifier_state *
11056 sanitize_speculative_path(struct bpf_verifier_env *env,
11057                           const struct bpf_insn *insn,
11058                           u32 next_idx, u32 curr_idx)
11059 {
11060         struct bpf_verifier_state *branch;
11061         struct bpf_reg_state *regs;
11062
11063         branch = push_stack(env, next_idx, curr_idx, true);
11064         if (branch && insn) {
11065                 regs = branch->frame[branch->curframe]->regs;
11066                 if (BPF_SRC(insn->code) == BPF_K) {
11067                         mark_reg_unknown(env, regs, insn->dst_reg);
11068                 } else if (BPF_SRC(insn->code) == BPF_X) {
11069                         mark_reg_unknown(env, regs, insn->dst_reg);
11070                         mark_reg_unknown(env, regs, insn->src_reg);
11071                 }
11072         }
11073         return branch;
11074 }
11075
11076 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11077                             struct bpf_insn *insn,
11078                             const struct bpf_reg_state *ptr_reg,
11079                             const struct bpf_reg_state *off_reg,
11080                             struct bpf_reg_state *dst_reg,
11081                             struct bpf_sanitize_info *info,
11082                             const bool commit_window)
11083 {
11084         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11085         struct bpf_verifier_state *vstate = env->cur_state;
11086         bool off_is_imm = tnum_is_const(off_reg->var_off);
11087         bool off_is_neg = off_reg->smin_value < 0;
11088         bool ptr_is_dst_reg = ptr_reg == dst_reg;
11089         u8 opcode = BPF_OP(insn->code);
11090         u32 alu_state, alu_limit;
11091         struct bpf_reg_state tmp;
11092         bool ret;
11093         int err;
11094
11095         if (can_skip_alu_sanitation(env, insn))
11096                 return 0;
11097
11098         /* We already marked aux for masking from non-speculative
11099          * paths, thus we got here in the first place. We only care
11100          * to explore bad access from here.
11101          */
11102         if (vstate->speculative)
11103                 goto do_sim;
11104
11105         if (!commit_window) {
11106                 if (!tnum_is_const(off_reg->var_off) &&
11107                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11108                         return REASON_BOUNDS;
11109
11110                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
11111                                      (opcode == BPF_SUB && !off_is_neg);
11112         }
11113
11114         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11115         if (err < 0)
11116                 return err;
11117
11118         if (commit_window) {
11119                 /* In commit phase we narrow the masking window based on
11120                  * the observed pointer move after the simulated operation.
11121                  */
11122                 alu_state = info->aux.alu_state;
11123                 alu_limit = abs(info->aux.alu_limit - alu_limit);
11124         } else {
11125                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11126                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11127                 alu_state |= ptr_is_dst_reg ?
11128                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11129
11130                 /* Limit pruning on unknown scalars to enable deep search for
11131                  * potential masking differences from other program paths.
11132                  */
11133                 if (!off_is_imm)
11134                         env->explore_alu_limits = true;
11135         }
11136
11137         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11138         if (err < 0)
11139                 return err;
11140 do_sim:
11141         /* If we're in commit phase, we're done here given we already
11142          * pushed the truncated dst_reg into the speculative verification
11143          * stack.
11144          *
11145          * Also, when register is a known constant, we rewrite register-based
11146          * operation to immediate-based, and thus do not need masking (and as
11147          * a consequence, do not need to simulate the zero-truncation either).
11148          */
11149         if (commit_window || off_is_imm)
11150                 return 0;
11151
11152         /* Simulate and find potential out-of-bounds access under
11153          * speculative execution from truncation as a result of
11154          * masking when off was not within expected range. If off
11155          * sits in dst, then we temporarily need to move ptr there
11156          * to simulate dst (== 0) +/-= ptr. Needed, for example,
11157          * for cases where we use K-based arithmetic in one direction
11158          * and truncated reg-based in the other in order to explore
11159          * bad access.
11160          */
11161         if (!ptr_is_dst_reg) {
11162                 tmp = *dst_reg;
11163                 copy_register_state(dst_reg, ptr_reg);
11164         }
11165         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11166                                         env->insn_idx);
11167         if (!ptr_is_dst_reg && ret)
11168                 *dst_reg = tmp;
11169         return !ret ? REASON_STACK : 0;
11170 }
11171
11172 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11173 {
11174         struct bpf_verifier_state *vstate = env->cur_state;
11175
11176         /* If we simulate paths under speculation, we don't update the
11177          * insn as 'seen' such that when we verify unreachable paths in
11178          * the non-speculative domain, sanitize_dead_code() can still
11179          * rewrite/sanitize them.
11180          */
11181         if (!vstate->speculative)
11182                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11183 }
11184
11185 static int sanitize_err(struct bpf_verifier_env *env,
11186                         const struct bpf_insn *insn, int reason,
11187                         const struct bpf_reg_state *off_reg,
11188                         const struct bpf_reg_state *dst_reg)
11189 {
11190         static const char *err = "pointer arithmetic with it prohibited for !root";
11191         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11192         u32 dst = insn->dst_reg, src = insn->src_reg;
11193
11194         switch (reason) {
11195         case REASON_BOUNDS:
11196                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11197                         off_reg == dst_reg ? dst : src, err);
11198                 break;
11199         case REASON_TYPE:
11200                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11201                         off_reg == dst_reg ? src : dst, err);
11202                 break;
11203         case REASON_PATHS:
11204                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11205                         dst, op, err);
11206                 break;
11207         case REASON_LIMIT:
11208                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11209                         dst, op, err);
11210                 break;
11211         case REASON_STACK:
11212                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11213                         dst, err);
11214                 break;
11215         default:
11216                 verbose(env, "verifier internal error: unknown reason (%d)\n",
11217                         reason);
11218                 break;
11219         }
11220
11221         return -EACCES;
11222 }
11223
11224 /* check that stack access falls within stack limits and that 'reg' doesn't
11225  * have a variable offset.
11226  *
11227  * Variable offset is prohibited for unprivileged mode for simplicity since it
11228  * requires corresponding support in Spectre masking for stack ALU.  See also
11229  * retrieve_ptr_limit().
11230  *
11231  *
11232  * 'off' includes 'reg->off'.
11233  */
11234 static int check_stack_access_for_ptr_arithmetic(
11235                                 struct bpf_verifier_env *env,
11236                                 int regno,
11237                                 const struct bpf_reg_state *reg,
11238                                 int off)
11239 {
11240         if (!tnum_is_const(reg->var_off)) {
11241                 char tn_buf[48];
11242
11243                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11244                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11245                         regno, tn_buf, off);
11246                 return -EACCES;
11247         }
11248
11249         if (off >= 0 || off < -MAX_BPF_STACK) {
11250                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
11251                         "prohibited for !root; off=%d\n", regno, off);
11252                 return -EACCES;
11253         }
11254
11255         return 0;
11256 }
11257
11258 static int sanitize_check_bounds(struct bpf_verifier_env *env,
11259                                  const struct bpf_insn *insn,
11260                                  const struct bpf_reg_state *dst_reg)
11261 {
11262         u32 dst = insn->dst_reg;
11263
11264         /* For unprivileged we require that resulting offset must be in bounds
11265          * in order to be able to sanitize access later on.
11266          */
11267         if (env->bypass_spec_v1)
11268                 return 0;
11269
11270         switch (dst_reg->type) {
11271         case PTR_TO_STACK:
11272                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
11273                                         dst_reg->off + dst_reg->var_off.value))
11274                         return -EACCES;
11275                 break;
11276         case PTR_TO_MAP_VALUE:
11277                 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
11278                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
11279                                 "prohibited for !root\n", dst);
11280                         return -EACCES;
11281                 }
11282                 break;
11283         default:
11284                 break;
11285         }
11286
11287         return 0;
11288 }
11289
11290 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
11291  * Caller should also handle BPF_MOV case separately.
11292  * If we return -EACCES, caller may want to try again treating pointer as a
11293  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
11294  */
11295 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
11296                                    struct bpf_insn *insn,
11297                                    const struct bpf_reg_state *ptr_reg,
11298                                    const struct bpf_reg_state *off_reg)
11299 {
11300         struct bpf_verifier_state *vstate = env->cur_state;
11301         struct bpf_func_state *state = vstate->frame[vstate->curframe];
11302         struct bpf_reg_state *regs = state->regs, *dst_reg;
11303         bool known = tnum_is_const(off_reg->var_off);
11304         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
11305             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
11306         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
11307             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
11308         struct bpf_sanitize_info info = {};
11309         u8 opcode = BPF_OP(insn->code);
11310         u32 dst = insn->dst_reg;
11311         int ret;
11312
11313         dst_reg = &regs[dst];
11314
11315         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
11316             smin_val > smax_val || umin_val > umax_val) {
11317                 /* Taint dst register if offset had invalid bounds derived from
11318                  * e.g. dead branches.
11319                  */
11320                 __mark_reg_unknown(env, dst_reg);
11321                 return 0;
11322         }
11323
11324         if (BPF_CLASS(insn->code) != BPF_ALU64) {
11325                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
11326                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
11327                         __mark_reg_unknown(env, dst_reg);
11328                         return 0;
11329                 }
11330
11331                 verbose(env,
11332                         "R%d 32-bit pointer arithmetic prohibited\n",
11333                         dst);
11334                 return -EACCES;
11335         }
11336
11337         if (ptr_reg->type & PTR_MAYBE_NULL) {
11338                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
11339                         dst, reg_type_str(env, ptr_reg->type));
11340                 return -EACCES;
11341         }
11342
11343         switch (base_type(ptr_reg->type)) {
11344         case CONST_PTR_TO_MAP:
11345                 /* smin_val represents the known value */
11346                 if (known && smin_val == 0 && opcode == BPF_ADD)
11347                         break;
11348                 fallthrough;
11349         case PTR_TO_PACKET_END:
11350         case PTR_TO_SOCKET:
11351         case PTR_TO_SOCK_COMMON:
11352         case PTR_TO_TCP_SOCK:
11353         case PTR_TO_XDP_SOCK:
11354                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
11355                         dst, reg_type_str(env, ptr_reg->type));
11356                 return -EACCES;
11357         default:
11358                 break;
11359         }
11360
11361         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
11362          * The id may be overwritten later if we create a new variable offset.
11363          */
11364         dst_reg->type = ptr_reg->type;
11365         dst_reg->id = ptr_reg->id;
11366
11367         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
11368             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
11369                 return -EINVAL;
11370
11371         /* pointer types do not carry 32-bit bounds at the moment. */
11372         __mark_reg32_unbounded(dst_reg);
11373
11374         if (sanitize_needed(opcode)) {
11375                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
11376                                        &info, false);
11377                 if (ret < 0)
11378                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
11379         }
11380
11381         switch (opcode) {
11382         case BPF_ADD:
11383                 /* We can take a fixed offset as long as it doesn't overflow
11384                  * the s32 'off' field
11385                  */
11386                 if (known && (ptr_reg->off + smin_val ==
11387                               (s64)(s32)(ptr_reg->off + smin_val))) {
11388                         /* pointer += K.  Accumulate it into fixed offset */
11389                         dst_reg->smin_value = smin_ptr;
11390                         dst_reg->smax_value = smax_ptr;
11391                         dst_reg->umin_value = umin_ptr;
11392                         dst_reg->umax_value = umax_ptr;
11393                         dst_reg->var_off = ptr_reg->var_off;
11394                         dst_reg->off = ptr_reg->off + smin_val;
11395                         dst_reg->raw = ptr_reg->raw;
11396                         break;
11397                 }
11398                 /* A new variable offset is created.  Note that off_reg->off
11399                  * == 0, since it's a scalar.
11400                  * dst_reg gets the pointer type and since some positive
11401                  * integer value was added to the pointer, give it a new 'id'
11402                  * if it's a PTR_TO_PACKET.
11403                  * this creates a new 'base' pointer, off_reg (variable) gets
11404                  * added into the variable offset, and we copy the fixed offset
11405                  * from ptr_reg.
11406                  */
11407                 if (signed_add_overflows(smin_ptr, smin_val) ||
11408                     signed_add_overflows(smax_ptr, smax_val)) {
11409                         dst_reg->smin_value = S64_MIN;
11410                         dst_reg->smax_value = S64_MAX;
11411                 } else {
11412                         dst_reg->smin_value = smin_ptr + smin_val;
11413                         dst_reg->smax_value = smax_ptr + smax_val;
11414                 }
11415                 if (umin_ptr + umin_val < umin_ptr ||
11416                     umax_ptr + umax_val < umax_ptr) {
11417                         dst_reg->umin_value = 0;
11418                         dst_reg->umax_value = U64_MAX;
11419                 } else {
11420                         dst_reg->umin_value = umin_ptr + umin_val;
11421                         dst_reg->umax_value = umax_ptr + umax_val;
11422                 }
11423                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
11424                 dst_reg->off = ptr_reg->off;
11425                 dst_reg->raw = ptr_reg->raw;
11426                 if (reg_is_pkt_pointer(ptr_reg)) {
11427                         dst_reg->id = ++env->id_gen;
11428                         /* something was added to pkt_ptr, set range to zero */
11429                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
11430                 }
11431                 break;
11432         case BPF_SUB:
11433                 if (dst_reg == off_reg) {
11434                         /* scalar -= pointer.  Creates an unknown scalar */
11435                         verbose(env, "R%d tried to subtract pointer from scalar\n",
11436                                 dst);
11437                         return -EACCES;
11438                 }
11439                 /* We don't allow subtraction from FP, because (according to
11440                  * test_verifier.c test "invalid fp arithmetic", JITs might not
11441                  * be able to deal with it.
11442                  */
11443                 if (ptr_reg->type == PTR_TO_STACK) {
11444                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
11445                                 dst);
11446                         return -EACCES;
11447                 }
11448                 if (known && (ptr_reg->off - smin_val ==
11449                               (s64)(s32)(ptr_reg->off - smin_val))) {
11450                         /* pointer -= K.  Subtract it from fixed offset */
11451                         dst_reg->smin_value = smin_ptr;
11452                         dst_reg->smax_value = smax_ptr;
11453                         dst_reg->umin_value = umin_ptr;
11454                         dst_reg->umax_value = umax_ptr;
11455                         dst_reg->var_off = ptr_reg->var_off;
11456                         dst_reg->id = ptr_reg->id;
11457                         dst_reg->off = ptr_reg->off - smin_val;
11458                         dst_reg->raw = ptr_reg->raw;
11459                         break;
11460                 }
11461                 /* A new variable offset is created.  If the subtrahend is known
11462                  * nonnegative, then any reg->range we had before is still good.
11463                  */
11464                 if (signed_sub_overflows(smin_ptr, smax_val) ||
11465                     signed_sub_overflows(smax_ptr, smin_val)) {
11466                         /* Overflow possible, we know nothing */
11467                         dst_reg->smin_value = S64_MIN;
11468                         dst_reg->smax_value = S64_MAX;
11469                 } else {
11470                         dst_reg->smin_value = smin_ptr - smax_val;
11471                         dst_reg->smax_value = smax_ptr - smin_val;
11472                 }
11473                 if (umin_ptr < umax_val) {
11474                         /* Overflow possible, we know nothing */
11475                         dst_reg->umin_value = 0;
11476                         dst_reg->umax_value = U64_MAX;
11477                 } else {
11478                         /* Cannot overflow (as long as bounds are consistent) */
11479                         dst_reg->umin_value = umin_ptr - umax_val;
11480                         dst_reg->umax_value = umax_ptr - umin_val;
11481                 }
11482                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
11483                 dst_reg->off = ptr_reg->off;
11484                 dst_reg->raw = ptr_reg->raw;
11485                 if (reg_is_pkt_pointer(ptr_reg)) {
11486                         dst_reg->id = ++env->id_gen;
11487                         /* something was added to pkt_ptr, set range to zero */
11488                         if (smin_val < 0)
11489                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
11490                 }
11491                 break;
11492         case BPF_AND:
11493         case BPF_OR:
11494         case BPF_XOR:
11495                 /* bitwise ops on pointers are troublesome, prohibit. */
11496                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
11497                         dst, bpf_alu_string[opcode >> 4]);
11498                 return -EACCES;
11499         default:
11500                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
11501                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
11502                         dst, bpf_alu_string[opcode >> 4]);
11503                 return -EACCES;
11504         }
11505
11506         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
11507                 return -EINVAL;
11508         reg_bounds_sync(dst_reg);
11509         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
11510                 return -EACCES;
11511         if (sanitize_needed(opcode)) {
11512                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
11513                                        &info, true);
11514                 if (ret < 0)
11515                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
11516         }
11517
11518         return 0;
11519 }
11520
11521 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
11522                                  struct bpf_reg_state *src_reg)
11523 {
11524         s32 smin_val = src_reg->s32_min_value;
11525         s32 smax_val = src_reg->s32_max_value;
11526         u32 umin_val = src_reg->u32_min_value;
11527         u32 umax_val = src_reg->u32_max_value;
11528
11529         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
11530             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
11531                 dst_reg->s32_min_value = S32_MIN;
11532                 dst_reg->s32_max_value = S32_MAX;
11533         } else {
11534                 dst_reg->s32_min_value += smin_val;
11535                 dst_reg->s32_max_value += smax_val;
11536         }
11537         if (dst_reg->u32_min_value + umin_val < umin_val ||
11538             dst_reg->u32_max_value + umax_val < umax_val) {
11539                 dst_reg->u32_min_value = 0;
11540                 dst_reg->u32_max_value = U32_MAX;
11541         } else {
11542                 dst_reg->u32_min_value += umin_val;
11543                 dst_reg->u32_max_value += umax_val;
11544         }
11545 }
11546
11547 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
11548                                struct bpf_reg_state *src_reg)
11549 {
11550         s64 smin_val = src_reg->smin_value;
11551         s64 smax_val = src_reg->smax_value;
11552         u64 umin_val = src_reg->umin_value;
11553         u64 umax_val = src_reg->umax_value;
11554
11555         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
11556             signed_add_overflows(dst_reg->smax_value, smax_val)) {
11557                 dst_reg->smin_value = S64_MIN;
11558                 dst_reg->smax_value = S64_MAX;
11559         } else {
11560                 dst_reg->smin_value += smin_val;
11561                 dst_reg->smax_value += smax_val;
11562         }
11563         if (dst_reg->umin_value + umin_val < umin_val ||
11564             dst_reg->umax_value + umax_val < umax_val) {
11565                 dst_reg->umin_value = 0;
11566                 dst_reg->umax_value = U64_MAX;
11567         } else {
11568                 dst_reg->umin_value += umin_val;
11569                 dst_reg->umax_value += umax_val;
11570         }
11571 }
11572
11573 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
11574                                  struct bpf_reg_state *src_reg)
11575 {
11576         s32 smin_val = src_reg->s32_min_value;
11577         s32 smax_val = src_reg->s32_max_value;
11578         u32 umin_val = src_reg->u32_min_value;
11579         u32 umax_val = src_reg->u32_max_value;
11580
11581         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
11582             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
11583                 /* Overflow possible, we know nothing */
11584                 dst_reg->s32_min_value = S32_MIN;
11585                 dst_reg->s32_max_value = S32_MAX;
11586         } else {
11587                 dst_reg->s32_min_value -= smax_val;
11588                 dst_reg->s32_max_value -= smin_val;
11589         }
11590         if (dst_reg->u32_min_value < umax_val) {
11591                 /* Overflow possible, we know nothing */
11592                 dst_reg->u32_min_value = 0;
11593                 dst_reg->u32_max_value = U32_MAX;
11594         } else {
11595                 /* Cannot overflow (as long as bounds are consistent) */
11596                 dst_reg->u32_min_value -= umax_val;
11597                 dst_reg->u32_max_value -= umin_val;
11598         }
11599 }
11600
11601 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
11602                                struct bpf_reg_state *src_reg)
11603 {
11604         s64 smin_val = src_reg->smin_value;
11605         s64 smax_val = src_reg->smax_value;
11606         u64 umin_val = src_reg->umin_value;
11607         u64 umax_val = src_reg->umax_value;
11608
11609         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
11610             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
11611                 /* Overflow possible, we know nothing */
11612                 dst_reg->smin_value = S64_MIN;
11613                 dst_reg->smax_value = S64_MAX;
11614         } else {
11615                 dst_reg->smin_value -= smax_val;
11616                 dst_reg->smax_value -= smin_val;
11617         }
11618         if (dst_reg->umin_value < umax_val) {
11619                 /* Overflow possible, we know nothing */
11620                 dst_reg->umin_value = 0;
11621                 dst_reg->umax_value = U64_MAX;
11622         } else {
11623                 /* Cannot overflow (as long as bounds are consistent) */
11624                 dst_reg->umin_value -= umax_val;
11625                 dst_reg->umax_value -= umin_val;
11626         }
11627 }
11628
11629 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
11630                                  struct bpf_reg_state *src_reg)
11631 {
11632         s32 smin_val = src_reg->s32_min_value;
11633         u32 umin_val = src_reg->u32_min_value;
11634         u32 umax_val = src_reg->u32_max_value;
11635
11636         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
11637                 /* Ain't nobody got time to multiply that sign */
11638                 __mark_reg32_unbounded(dst_reg);
11639                 return;
11640         }
11641         /* Both values are positive, so we can work with unsigned and
11642          * copy the result to signed (unless it exceeds S32_MAX).
11643          */
11644         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
11645                 /* Potential overflow, we know nothing */
11646                 __mark_reg32_unbounded(dst_reg);
11647                 return;
11648         }
11649         dst_reg->u32_min_value *= umin_val;
11650         dst_reg->u32_max_value *= umax_val;
11651         if (dst_reg->u32_max_value > S32_MAX) {
11652                 /* Overflow possible, we know nothing */
11653                 dst_reg->s32_min_value = S32_MIN;
11654                 dst_reg->s32_max_value = S32_MAX;
11655         } else {
11656                 dst_reg->s32_min_value = dst_reg->u32_min_value;
11657                 dst_reg->s32_max_value = dst_reg->u32_max_value;
11658         }
11659 }
11660
11661 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
11662                                struct bpf_reg_state *src_reg)
11663 {
11664         s64 smin_val = src_reg->smin_value;
11665         u64 umin_val = src_reg->umin_value;
11666         u64 umax_val = src_reg->umax_value;
11667
11668         if (smin_val < 0 || dst_reg->smin_value < 0) {
11669                 /* Ain't nobody got time to multiply that sign */
11670                 __mark_reg64_unbounded(dst_reg);
11671                 return;
11672         }
11673         /* Both values are positive, so we can work with unsigned and
11674          * copy the result to signed (unless it exceeds S64_MAX).
11675          */
11676         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
11677                 /* Potential overflow, we know nothing */
11678                 __mark_reg64_unbounded(dst_reg);
11679                 return;
11680         }
11681         dst_reg->umin_value *= umin_val;
11682         dst_reg->umax_value *= umax_val;
11683         if (dst_reg->umax_value > S64_MAX) {
11684                 /* Overflow possible, we know nothing */
11685                 dst_reg->smin_value = S64_MIN;
11686                 dst_reg->smax_value = S64_MAX;
11687         } else {
11688                 dst_reg->smin_value = dst_reg->umin_value;
11689                 dst_reg->smax_value = dst_reg->umax_value;
11690         }
11691 }
11692
11693 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
11694                                  struct bpf_reg_state *src_reg)
11695 {
11696         bool src_known = tnum_subreg_is_const(src_reg->var_off);
11697         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11698         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11699         s32 smin_val = src_reg->s32_min_value;
11700         u32 umax_val = src_reg->u32_max_value;
11701
11702         if (src_known && dst_known) {
11703                 __mark_reg32_known(dst_reg, var32_off.value);
11704                 return;
11705         }
11706
11707         /* We get our minimum from the var_off, since that's inherently
11708          * bitwise.  Our maximum is the minimum of the operands' maxima.
11709          */
11710         dst_reg->u32_min_value = var32_off.value;
11711         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
11712         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
11713                 /* Lose signed bounds when ANDing negative numbers,
11714                  * ain't nobody got time for that.
11715                  */
11716                 dst_reg->s32_min_value = S32_MIN;
11717                 dst_reg->s32_max_value = S32_MAX;
11718         } else {
11719                 /* ANDing two positives gives a positive, so safe to
11720                  * cast result into s64.
11721                  */
11722                 dst_reg->s32_min_value = dst_reg->u32_min_value;
11723                 dst_reg->s32_max_value = dst_reg->u32_max_value;
11724         }
11725 }
11726
11727 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
11728                                struct bpf_reg_state *src_reg)
11729 {
11730         bool src_known = tnum_is_const(src_reg->var_off);
11731         bool dst_known = tnum_is_const(dst_reg->var_off);
11732         s64 smin_val = src_reg->smin_value;
11733         u64 umax_val = src_reg->umax_value;
11734
11735         if (src_known && dst_known) {
11736                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
11737                 return;
11738         }
11739
11740         /* We get our minimum from the var_off, since that's inherently
11741          * bitwise.  Our maximum is the minimum of the operands' maxima.
11742          */
11743         dst_reg->umin_value = dst_reg->var_off.value;
11744         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
11745         if (dst_reg->smin_value < 0 || smin_val < 0) {
11746                 /* Lose signed bounds when ANDing negative numbers,
11747                  * ain't nobody got time for that.
11748                  */
11749                 dst_reg->smin_value = S64_MIN;
11750                 dst_reg->smax_value = S64_MAX;
11751         } else {
11752                 /* ANDing two positives gives a positive, so safe to
11753                  * cast result into s64.
11754                  */
11755                 dst_reg->smin_value = dst_reg->umin_value;
11756                 dst_reg->smax_value = dst_reg->umax_value;
11757         }
11758         /* We may learn something more from the var_off */
11759         __update_reg_bounds(dst_reg);
11760 }
11761
11762 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
11763                                 struct bpf_reg_state *src_reg)
11764 {
11765         bool src_known = tnum_subreg_is_const(src_reg->var_off);
11766         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11767         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11768         s32 smin_val = src_reg->s32_min_value;
11769         u32 umin_val = src_reg->u32_min_value;
11770
11771         if (src_known && dst_known) {
11772                 __mark_reg32_known(dst_reg, var32_off.value);
11773                 return;
11774         }
11775
11776         /* We get our maximum from the var_off, and our minimum is the
11777          * maximum of the operands' minima
11778          */
11779         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
11780         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
11781         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
11782                 /* Lose signed bounds when ORing negative numbers,
11783                  * ain't nobody got time for that.
11784                  */
11785                 dst_reg->s32_min_value = S32_MIN;
11786                 dst_reg->s32_max_value = S32_MAX;
11787         } else {
11788                 /* ORing two positives gives a positive, so safe to
11789                  * cast result into s64.
11790                  */
11791                 dst_reg->s32_min_value = dst_reg->u32_min_value;
11792                 dst_reg->s32_max_value = dst_reg->u32_max_value;
11793         }
11794 }
11795
11796 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
11797                               struct bpf_reg_state *src_reg)
11798 {
11799         bool src_known = tnum_is_const(src_reg->var_off);
11800         bool dst_known = tnum_is_const(dst_reg->var_off);
11801         s64 smin_val = src_reg->smin_value;
11802         u64 umin_val = src_reg->umin_value;
11803
11804         if (src_known && dst_known) {
11805                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
11806                 return;
11807         }
11808
11809         /* We get our maximum from the var_off, and our minimum is the
11810          * maximum of the operands' minima
11811          */
11812         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
11813         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
11814         if (dst_reg->smin_value < 0 || smin_val < 0) {
11815                 /* Lose signed bounds when ORing negative numbers,
11816                  * ain't nobody got time for that.
11817                  */
11818                 dst_reg->smin_value = S64_MIN;
11819                 dst_reg->smax_value = S64_MAX;
11820         } else {
11821                 /* ORing two positives gives a positive, so safe to
11822                  * cast result into s64.
11823                  */
11824                 dst_reg->smin_value = dst_reg->umin_value;
11825                 dst_reg->smax_value = dst_reg->umax_value;
11826         }
11827         /* We may learn something more from the var_off */
11828         __update_reg_bounds(dst_reg);
11829 }
11830
11831 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
11832                                  struct bpf_reg_state *src_reg)
11833 {
11834         bool src_known = tnum_subreg_is_const(src_reg->var_off);
11835         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
11836         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
11837         s32 smin_val = src_reg->s32_min_value;
11838
11839         if (src_known && dst_known) {
11840                 __mark_reg32_known(dst_reg, var32_off.value);
11841                 return;
11842         }
11843
11844         /* We get both minimum and maximum from the var32_off. */
11845         dst_reg->u32_min_value = var32_off.value;
11846         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
11847
11848         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
11849                 /* XORing two positive sign numbers gives a positive,
11850                  * so safe to cast u32 result into s32.
11851                  */
11852                 dst_reg->s32_min_value = dst_reg->u32_min_value;
11853                 dst_reg->s32_max_value = dst_reg->u32_max_value;
11854         } else {
11855                 dst_reg->s32_min_value = S32_MIN;
11856                 dst_reg->s32_max_value = S32_MAX;
11857         }
11858 }
11859
11860 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
11861                                struct bpf_reg_state *src_reg)
11862 {
11863         bool src_known = tnum_is_const(src_reg->var_off);
11864         bool dst_known = tnum_is_const(dst_reg->var_off);
11865         s64 smin_val = src_reg->smin_value;
11866
11867         if (src_known && dst_known) {
11868                 /* dst_reg->var_off.value has been updated earlier */
11869                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
11870                 return;
11871         }
11872
11873         /* We get both minimum and maximum from the var_off. */
11874         dst_reg->umin_value = dst_reg->var_off.value;
11875         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
11876
11877         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
11878                 /* XORing two positive sign numbers gives a positive,
11879                  * so safe to cast u64 result into s64.
11880                  */
11881                 dst_reg->smin_value = dst_reg->umin_value;
11882                 dst_reg->smax_value = dst_reg->umax_value;
11883         } else {
11884                 dst_reg->smin_value = S64_MIN;
11885                 dst_reg->smax_value = S64_MAX;
11886         }
11887
11888         __update_reg_bounds(dst_reg);
11889 }
11890
11891 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
11892                                    u64 umin_val, u64 umax_val)
11893 {
11894         /* We lose all sign bit information (except what we can pick
11895          * up from var_off)
11896          */
11897         dst_reg->s32_min_value = S32_MIN;
11898         dst_reg->s32_max_value = S32_MAX;
11899         /* If we might shift our top bit out, then we know nothing */
11900         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
11901                 dst_reg->u32_min_value = 0;
11902                 dst_reg->u32_max_value = U32_MAX;
11903         } else {
11904                 dst_reg->u32_min_value <<= umin_val;
11905                 dst_reg->u32_max_value <<= umax_val;
11906         }
11907 }
11908
11909 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
11910                                  struct bpf_reg_state *src_reg)
11911 {
11912         u32 umax_val = src_reg->u32_max_value;
11913         u32 umin_val = src_reg->u32_min_value;
11914         /* u32 alu operation will zext upper bits */
11915         struct tnum subreg = tnum_subreg(dst_reg->var_off);
11916
11917         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
11918         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
11919         /* Not required but being careful mark reg64 bounds as unknown so
11920          * that we are forced to pick them up from tnum and zext later and
11921          * if some path skips this step we are still safe.
11922          */
11923         __mark_reg64_unbounded(dst_reg);
11924         __update_reg32_bounds(dst_reg);
11925 }
11926
11927 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
11928                                    u64 umin_val, u64 umax_val)
11929 {
11930         /* Special case <<32 because it is a common compiler pattern to sign
11931          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
11932          * positive we know this shift will also be positive so we can track
11933          * bounds correctly. Otherwise we lose all sign bit information except
11934          * what we can pick up from var_off. Perhaps we can generalize this
11935          * later to shifts of any length.
11936          */
11937         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
11938                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
11939         else
11940                 dst_reg->smax_value = S64_MAX;
11941
11942         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
11943                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
11944         else
11945                 dst_reg->smin_value = S64_MIN;
11946
11947         /* If we might shift our top bit out, then we know nothing */
11948         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
11949                 dst_reg->umin_value = 0;
11950                 dst_reg->umax_value = U64_MAX;
11951         } else {
11952                 dst_reg->umin_value <<= umin_val;
11953                 dst_reg->umax_value <<= umax_val;
11954         }
11955 }
11956
11957 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
11958                                struct bpf_reg_state *src_reg)
11959 {
11960         u64 umax_val = src_reg->umax_value;
11961         u64 umin_val = src_reg->umin_value;
11962
11963         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
11964         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
11965         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
11966
11967         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
11968         /* We may learn something more from the var_off */
11969         __update_reg_bounds(dst_reg);
11970 }
11971
11972 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
11973                                  struct bpf_reg_state *src_reg)
11974 {
11975         struct tnum subreg = tnum_subreg(dst_reg->var_off);
11976         u32 umax_val = src_reg->u32_max_value;
11977         u32 umin_val = src_reg->u32_min_value;
11978
11979         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
11980          * be negative, then either:
11981          * 1) src_reg might be zero, so the sign bit of the result is
11982          *    unknown, so we lose our signed bounds
11983          * 2) it's known negative, thus the unsigned bounds capture the
11984          *    signed bounds
11985          * 3) the signed bounds cross zero, so they tell us nothing
11986          *    about the result
11987          * If the value in dst_reg is known nonnegative, then again the
11988          * unsigned bounds capture the signed bounds.
11989          * Thus, in all cases it suffices to blow away our signed bounds
11990          * and rely on inferring new ones from the unsigned bounds and
11991          * var_off of the result.
11992          */
11993         dst_reg->s32_min_value = S32_MIN;
11994         dst_reg->s32_max_value = S32_MAX;
11995
11996         dst_reg->var_off = tnum_rshift(subreg, umin_val);
11997         dst_reg->u32_min_value >>= umax_val;
11998         dst_reg->u32_max_value >>= umin_val;
11999
12000         __mark_reg64_unbounded(dst_reg);
12001         __update_reg32_bounds(dst_reg);
12002 }
12003
12004 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12005                                struct bpf_reg_state *src_reg)
12006 {
12007         u64 umax_val = src_reg->umax_value;
12008         u64 umin_val = src_reg->umin_value;
12009
12010         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12011          * be negative, then either:
12012          * 1) src_reg might be zero, so the sign bit of the result is
12013          *    unknown, so we lose our signed bounds
12014          * 2) it's known negative, thus the unsigned bounds capture the
12015          *    signed bounds
12016          * 3) the signed bounds cross zero, so they tell us nothing
12017          *    about the result
12018          * If the value in dst_reg is known nonnegative, then again the
12019          * unsigned bounds capture the signed bounds.
12020          * Thus, in all cases it suffices to blow away our signed bounds
12021          * and rely on inferring new ones from the unsigned bounds and
12022          * var_off of the result.
12023          */
12024         dst_reg->smin_value = S64_MIN;
12025         dst_reg->smax_value = S64_MAX;
12026         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12027         dst_reg->umin_value >>= umax_val;
12028         dst_reg->umax_value >>= umin_val;
12029
12030         /* Its not easy to operate on alu32 bounds here because it depends
12031          * on bits being shifted in. Take easy way out and mark unbounded
12032          * so we can recalculate later from tnum.
12033          */
12034         __mark_reg32_unbounded(dst_reg);
12035         __update_reg_bounds(dst_reg);
12036 }
12037
12038 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12039                                   struct bpf_reg_state *src_reg)
12040 {
12041         u64 umin_val = src_reg->u32_min_value;
12042
12043         /* Upon reaching here, src_known is true and
12044          * umax_val is equal to umin_val.
12045          */
12046         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12047         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12048
12049         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12050
12051         /* blow away the dst_reg umin_value/umax_value and rely on
12052          * dst_reg var_off to refine the result.
12053          */
12054         dst_reg->u32_min_value = 0;
12055         dst_reg->u32_max_value = U32_MAX;
12056
12057         __mark_reg64_unbounded(dst_reg);
12058         __update_reg32_bounds(dst_reg);
12059 }
12060
12061 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12062                                 struct bpf_reg_state *src_reg)
12063 {
12064         u64 umin_val = src_reg->umin_value;
12065
12066         /* Upon reaching here, src_known is true and umax_val is equal
12067          * to umin_val.
12068          */
12069         dst_reg->smin_value >>= umin_val;
12070         dst_reg->smax_value >>= umin_val;
12071
12072         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12073
12074         /* blow away the dst_reg umin_value/umax_value and rely on
12075          * dst_reg var_off to refine the result.
12076          */
12077         dst_reg->umin_value = 0;
12078         dst_reg->umax_value = U64_MAX;
12079
12080         /* Its not easy to operate on alu32 bounds here because it depends
12081          * on bits being shifted in from upper 32-bits. Take easy way out
12082          * and mark unbounded so we can recalculate later from tnum.
12083          */
12084         __mark_reg32_unbounded(dst_reg);
12085         __update_reg_bounds(dst_reg);
12086 }
12087
12088 /* WARNING: This function does calculations on 64-bit values, but the actual
12089  * execution may occur on 32-bit values. Therefore, things like bitshifts
12090  * need extra checks in the 32-bit case.
12091  */
12092 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12093                                       struct bpf_insn *insn,
12094                                       struct bpf_reg_state *dst_reg,
12095                                       struct bpf_reg_state src_reg)
12096 {
12097         struct bpf_reg_state *regs = cur_regs(env);
12098         u8 opcode = BPF_OP(insn->code);
12099         bool src_known;
12100         s64 smin_val, smax_val;
12101         u64 umin_val, umax_val;
12102         s32 s32_min_val, s32_max_val;
12103         u32 u32_min_val, u32_max_val;
12104         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12105         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12106         int ret;
12107
12108         smin_val = src_reg.smin_value;
12109         smax_val = src_reg.smax_value;
12110         umin_val = src_reg.umin_value;
12111         umax_val = src_reg.umax_value;
12112
12113         s32_min_val = src_reg.s32_min_value;
12114         s32_max_val = src_reg.s32_max_value;
12115         u32_min_val = src_reg.u32_min_value;
12116         u32_max_val = src_reg.u32_max_value;
12117
12118         if (alu32) {
12119                 src_known = tnum_subreg_is_const(src_reg.var_off);
12120                 if ((src_known &&
12121                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12122                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12123                         /* Taint dst register if offset had invalid bounds
12124                          * derived from e.g. dead branches.
12125                          */
12126                         __mark_reg_unknown(env, dst_reg);
12127                         return 0;
12128                 }
12129         } else {
12130                 src_known = tnum_is_const(src_reg.var_off);
12131                 if ((src_known &&
12132                      (smin_val != smax_val || umin_val != umax_val)) ||
12133                     smin_val > smax_val || umin_val > umax_val) {
12134                         /* Taint dst register if offset had invalid bounds
12135                          * derived from e.g. dead branches.
12136                          */
12137                         __mark_reg_unknown(env, dst_reg);
12138                         return 0;
12139                 }
12140         }
12141
12142         if (!src_known &&
12143             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12144                 __mark_reg_unknown(env, dst_reg);
12145                 return 0;
12146         }
12147
12148         if (sanitize_needed(opcode)) {
12149                 ret = sanitize_val_alu(env, insn);
12150                 if (ret < 0)
12151                         return sanitize_err(env, insn, ret, NULL, NULL);
12152         }
12153
12154         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12155          * There are two classes of instructions: The first class we track both
12156          * alu32 and alu64 sign/unsigned bounds independently this provides the
12157          * greatest amount of precision when alu operations are mixed with jmp32
12158          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12159          * and BPF_OR. This is possible because these ops have fairly easy to
12160          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12161          * See alu32 verifier tests for examples. The second class of
12162          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12163          * with regards to tracking sign/unsigned bounds because the bits may
12164          * cross subreg boundaries in the alu64 case. When this happens we mark
12165          * the reg unbounded in the subreg bound space and use the resulting
12166          * tnum to calculate an approximation of the sign/unsigned bounds.
12167          */
12168         switch (opcode) {
12169         case BPF_ADD:
12170                 scalar32_min_max_add(dst_reg, &src_reg);
12171                 scalar_min_max_add(dst_reg, &src_reg);
12172                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12173                 break;
12174         case BPF_SUB:
12175                 scalar32_min_max_sub(dst_reg, &src_reg);
12176                 scalar_min_max_sub(dst_reg, &src_reg);
12177                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12178                 break;
12179         case BPF_MUL:
12180                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12181                 scalar32_min_max_mul(dst_reg, &src_reg);
12182                 scalar_min_max_mul(dst_reg, &src_reg);
12183                 break;
12184         case BPF_AND:
12185                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12186                 scalar32_min_max_and(dst_reg, &src_reg);
12187                 scalar_min_max_and(dst_reg, &src_reg);
12188                 break;
12189         case BPF_OR:
12190                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12191                 scalar32_min_max_or(dst_reg, &src_reg);
12192                 scalar_min_max_or(dst_reg, &src_reg);
12193                 break;
12194         case BPF_XOR:
12195                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12196                 scalar32_min_max_xor(dst_reg, &src_reg);
12197                 scalar_min_max_xor(dst_reg, &src_reg);
12198                 break;
12199         case BPF_LSH:
12200                 if (umax_val >= insn_bitness) {
12201                         /* Shifts greater than 31 or 63 are undefined.
12202                          * This includes shifts by a negative number.
12203                          */
12204                         mark_reg_unknown(env, regs, insn->dst_reg);
12205                         break;
12206                 }
12207                 if (alu32)
12208                         scalar32_min_max_lsh(dst_reg, &src_reg);
12209                 else
12210                         scalar_min_max_lsh(dst_reg, &src_reg);
12211                 break;
12212         case BPF_RSH:
12213                 if (umax_val >= insn_bitness) {
12214                         /* Shifts greater than 31 or 63 are undefined.
12215                          * This includes shifts by a negative number.
12216                          */
12217                         mark_reg_unknown(env, regs, insn->dst_reg);
12218                         break;
12219                 }
12220                 if (alu32)
12221                         scalar32_min_max_rsh(dst_reg, &src_reg);
12222                 else
12223                         scalar_min_max_rsh(dst_reg, &src_reg);
12224                 break;
12225         case BPF_ARSH:
12226                 if (umax_val >= insn_bitness) {
12227                         /* Shifts greater than 31 or 63 are undefined.
12228                          * This includes shifts by a negative number.
12229                          */
12230                         mark_reg_unknown(env, regs, insn->dst_reg);
12231                         break;
12232                 }
12233                 if (alu32)
12234                         scalar32_min_max_arsh(dst_reg, &src_reg);
12235                 else
12236                         scalar_min_max_arsh(dst_reg, &src_reg);
12237                 break;
12238         default:
12239                 mark_reg_unknown(env, regs, insn->dst_reg);
12240                 break;
12241         }
12242
12243         /* ALU32 ops are zero extended into 64bit register */
12244         if (alu32)
12245                 zext_32_to_64(dst_reg);
12246         reg_bounds_sync(dst_reg);
12247         return 0;
12248 }
12249
12250 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
12251  * and var_off.
12252  */
12253 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
12254                                    struct bpf_insn *insn)
12255 {
12256         struct bpf_verifier_state *vstate = env->cur_state;
12257         struct bpf_func_state *state = vstate->frame[vstate->curframe];
12258         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
12259         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
12260         u8 opcode = BPF_OP(insn->code);
12261         int err;
12262
12263         dst_reg = &regs[insn->dst_reg];
12264         src_reg = NULL;
12265         if (dst_reg->type != SCALAR_VALUE)
12266                 ptr_reg = dst_reg;
12267         else
12268                 /* Make sure ID is cleared otherwise dst_reg min/max could be
12269                  * incorrectly propagated into other registers by find_equal_scalars()
12270                  */
12271                 dst_reg->id = 0;
12272         if (BPF_SRC(insn->code) == BPF_X) {
12273                 src_reg = &regs[insn->src_reg];
12274                 if (src_reg->type != SCALAR_VALUE) {
12275                         if (dst_reg->type != SCALAR_VALUE) {
12276                                 /* Combining two pointers by any ALU op yields
12277                                  * an arbitrary scalar. Disallow all math except
12278                                  * pointer subtraction
12279                                  */
12280                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12281                                         mark_reg_unknown(env, regs, insn->dst_reg);
12282                                         return 0;
12283                                 }
12284                                 verbose(env, "R%d pointer %s pointer prohibited\n",
12285                                         insn->dst_reg,
12286                                         bpf_alu_string[opcode >> 4]);
12287                                 return -EACCES;
12288                         } else {
12289                                 /* scalar += pointer
12290                                  * This is legal, but we have to reverse our
12291                                  * src/dest handling in computing the range
12292                                  */
12293                                 err = mark_chain_precision(env, insn->dst_reg);
12294                                 if (err)
12295                                         return err;
12296                                 return adjust_ptr_min_max_vals(env, insn,
12297                                                                src_reg, dst_reg);
12298                         }
12299                 } else if (ptr_reg) {
12300                         /* pointer += scalar */
12301                         err = mark_chain_precision(env, insn->src_reg);
12302                         if (err)
12303                                 return err;
12304                         return adjust_ptr_min_max_vals(env, insn,
12305                                                        dst_reg, src_reg);
12306                 } else if (dst_reg->precise) {
12307                         /* if dst_reg is precise, src_reg should be precise as well */
12308                         err = mark_chain_precision(env, insn->src_reg);
12309                         if (err)
12310                                 return err;
12311                 }
12312         } else {
12313                 /* Pretend the src is a reg with a known value, since we only
12314                  * need to be able to read from this state.
12315                  */
12316                 off_reg.type = SCALAR_VALUE;
12317                 __mark_reg_known(&off_reg, insn->imm);
12318                 src_reg = &off_reg;
12319                 if (ptr_reg) /* pointer += K */
12320                         return adjust_ptr_min_max_vals(env, insn,
12321                                                        ptr_reg, src_reg);
12322         }
12323
12324         /* Got here implies adding two SCALAR_VALUEs */
12325         if (WARN_ON_ONCE(ptr_reg)) {
12326                 print_verifier_state(env, state, true);
12327                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
12328                 return -EINVAL;
12329         }
12330         if (WARN_ON(!src_reg)) {
12331                 print_verifier_state(env, state, true);
12332                 verbose(env, "verifier internal error: no src_reg\n");
12333                 return -EINVAL;
12334         }
12335         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
12336 }
12337
12338 /* check validity of 32-bit and 64-bit arithmetic operations */
12339 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
12340 {
12341         struct bpf_reg_state *regs = cur_regs(env);
12342         u8 opcode = BPF_OP(insn->code);
12343         int err;
12344
12345         if (opcode == BPF_END || opcode == BPF_NEG) {
12346                 if (opcode == BPF_NEG) {
12347                         if (BPF_SRC(insn->code) != BPF_K ||
12348                             insn->src_reg != BPF_REG_0 ||
12349                             insn->off != 0 || insn->imm != 0) {
12350                                 verbose(env, "BPF_NEG uses reserved fields\n");
12351                                 return -EINVAL;
12352                         }
12353                 } else {
12354                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
12355                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
12356                             BPF_CLASS(insn->code) == BPF_ALU64) {
12357                                 verbose(env, "BPF_END uses reserved fields\n");
12358                                 return -EINVAL;
12359                         }
12360                 }
12361
12362                 /* check src operand */
12363                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12364                 if (err)
12365                         return err;
12366
12367                 if (is_pointer_value(env, insn->dst_reg)) {
12368                         verbose(env, "R%d pointer arithmetic prohibited\n",
12369                                 insn->dst_reg);
12370                         return -EACCES;
12371                 }
12372
12373                 /* check dest operand */
12374                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
12375                 if (err)
12376                         return err;
12377
12378         } else if (opcode == BPF_MOV) {
12379
12380                 if (BPF_SRC(insn->code) == BPF_X) {
12381                         if (insn->imm != 0 || insn->off != 0) {
12382                                 verbose(env, "BPF_MOV uses reserved fields\n");
12383                                 return -EINVAL;
12384                         }
12385
12386                         /* check src operand */
12387                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
12388                         if (err)
12389                                 return err;
12390                 } else {
12391                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
12392                                 verbose(env, "BPF_MOV uses reserved fields\n");
12393                                 return -EINVAL;
12394                         }
12395                 }
12396
12397                 /* check dest operand, mark as required later */
12398                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12399                 if (err)
12400                         return err;
12401
12402                 if (BPF_SRC(insn->code) == BPF_X) {
12403                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
12404                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
12405
12406                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
12407                                 /* case: R1 = R2
12408                                  * copy register state to dest reg
12409                                  */
12410                                 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
12411                                         /* Assign src and dst registers the same ID
12412                                          * that will be used by find_equal_scalars()
12413                                          * to propagate min/max range.
12414                                          */
12415                                         src_reg->id = ++env->id_gen;
12416                                 copy_register_state(dst_reg, src_reg);
12417                                 dst_reg->live |= REG_LIVE_WRITTEN;
12418                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
12419                         } else {
12420                                 /* R1 = (u32) R2 */
12421                                 if (is_pointer_value(env, insn->src_reg)) {
12422                                         verbose(env,
12423                                                 "R%d partial copy of pointer\n",
12424                                                 insn->src_reg);
12425                                         return -EACCES;
12426                                 } else if (src_reg->type == SCALAR_VALUE) {
12427                                         copy_register_state(dst_reg, src_reg);
12428                                         /* Make sure ID is cleared otherwise
12429                                          * dst_reg min/max could be incorrectly
12430                                          * propagated into src_reg by find_equal_scalars()
12431                                          */
12432                                         dst_reg->id = 0;
12433                                         dst_reg->live |= REG_LIVE_WRITTEN;
12434                                         dst_reg->subreg_def = env->insn_idx + 1;
12435                                 } else {
12436                                         mark_reg_unknown(env, regs,
12437                                                          insn->dst_reg);
12438                                 }
12439                                 zext_32_to_64(dst_reg);
12440                                 reg_bounds_sync(dst_reg);
12441                         }
12442                 } else {
12443                         /* case: R = imm
12444                          * remember the value we stored into this reg
12445                          */
12446                         /* clear any state __mark_reg_known doesn't set */
12447                         mark_reg_unknown(env, regs, insn->dst_reg);
12448                         regs[insn->dst_reg].type = SCALAR_VALUE;
12449                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
12450                                 __mark_reg_known(regs + insn->dst_reg,
12451                                                  insn->imm);
12452                         } else {
12453                                 __mark_reg_known(regs + insn->dst_reg,
12454                                                  (u32)insn->imm);
12455                         }
12456                 }
12457
12458         } else if (opcode > BPF_END) {
12459                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
12460                 return -EINVAL;
12461
12462         } else {        /* all other ALU ops: and, sub, xor, add, ... */
12463
12464                 if (BPF_SRC(insn->code) == BPF_X) {
12465                         if (insn->imm != 0 || insn->off != 0) {
12466                                 verbose(env, "BPF_ALU uses reserved fields\n");
12467                                 return -EINVAL;
12468                         }
12469                         /* check src1 operand */
12470                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
12471                         if (err)
12472                                 return err;
12473                 } else {
12474                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
12475                                 verbose(env, "BPF_ALU uses reserved fields\n");
12476                                 return -EINVAL;
12477                         }
12478                 }
12479
12480                 /* check src2 operand */
12481                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12482                 if (err)
12483                         return err;
12484
12485                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
12486                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
12487                         verbose(env, "div by zero\n");
12488                         return -EINVAL;
12489                 }
12490
12491                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
12492                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
12493                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
12494
12495                         if (insn->imm < 0 || insn->imm >= size) {
12496                                 verbose(env, "invalid shift %d\n", insn->imm);
12497                                 return -EINVAL;
12498                         }
12499                 }
12500
12501                 /* check dest operand */
12502                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12503                 if (err)
12504                         return err;
12505
12506                 return adjust_reg_min_max_vals(env, insn);
12507         }
12508
12509         return 0;
12510 }
12511
12512 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
12513                                    struct bpf_reg_state *dst_reg,
12514                                    enum bpf_reg_type type,
12515                                    bool range_right_open)
12516 {
12517         struct bpf_func_state *state;
12518         struct bpf_reg_state *reg;
12519         int new_range;
12520
12521         if (dst_reg->off < 0 ||
12522             (dst_reg->off == 0 && range_right_open))
12523                 /* This doesn't give us any range */
12524                 return;
12525
12526         if (dst_reg->umax_value > MAX_PACKET_OFF ||
12527             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
12528                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
12529                  * than pkt_end, but that's because it's also less than pkt.
12530                  */
12531                 return;
12532
12533         new_range = dst_reg->off;
12534         if (range_right_open)
12535                 new_range++;
12536
12537         /* Examples for register markings:
12538          *
12539          * pkt_data in dst register:
12540          *
12541          *   r2 = r3;
12542          *   r2 += 8;
12543          *   if (r2 > pkt_end) goto <handle exception>
12544          *   <access okay>
12545          *
12546          *   r2 = r3;
12547          *   r2 += 8;
12548          *   if (r2 < pkt_end) goto <access okay>
12549          *   <handle exception>
12550          *
12551          *   Where:
12552          *     r2 == dst_reg, pkt_end == src_reg
12553          *     r2=pkt(id=n,off=8,r=0)
12554          *     r3=pkt(id=n,off=0,r=0)
12555          *
12556          * pkt_data in src register:
12557          *
12558          *   r2 = r3;
12559          *   r2 += 8;
12560          *   if (pkt_end >= r2) goto <access okay>
12561          *   <handle exception>
12562          *
12563          *   r2 = r3;
12564          *   r2 += 8;
12565          *   if (pkt_end <= r2) goto <handle exception>
12566          *   <access okay>
12567          *
12568          *   Where:
12569          *     pkt_end == dst_reg, r2 == src_reg
12570          *     r2=pkt(id=n,off=8,r=0)
12571          *     r3=pkt(id=n,off=0,r=0)
12572          *
12573          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
12574          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
12575          * and [r3, r3 + 8-1) respectively is safe to access depending on
12576          * the check.
12577          */
12578
12579         /* If our ids match, then we must have the same max_value.  And we
12580          * don't care about the other reg's fixed offset, since if it's too big
12581          * the range won't allow anything.
12582          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
12583          */
12584         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
12585                 if (reg->type == type && reg->id == dst_reg->id)
12586                         /* keep the maximum range already checked */
12587                         reg->range = max(reg->range, new_range);
12588         }));
12589 }
12590
12591 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
12592 {
12593         struct tnum subreg = tnum_subreg(reg->var_off);
12594         s32 sval = (s32)val;
12595
12596         switch (opcode) {
12597         case BPF_JEQ:
12598                 if (tnum_is_const(subreg))
12599                         return !!tnum_equals_const(subreg, val);
12600                 else if (val < reg->u32_min_value || val > reg->u32_max_value)
12601                         return 0;
12602                 break;
12603         case BPF_JNE:
12604                 if (tnum_is_const(subreg))
12605                         return !tnum_equals_const(subreg, val);
12606                 else if (val < reg->u32_min_value || val > reg->u32_max_value)
12607                         return 1;
12608                 break;
12609         case BPF_JSET:
12610                 if ((~subreg.mask & subreg.value) & val)
12611                         return 1;
12612                 if (!((subreg.mask | subreg.value) & val))
12613                         return 0;
12614                 break;
12615         case BPF_JGT:
12616                 if (reg->u32_min_value > val)
12617                         return 1;
12618                 else if (reg->u32_max_value <= val)
12619                         return 0;
12620                 break;
12621         case BPF_JSGT:
12622                 if (reg->s32_min_value > sval)
12623                         return 1;
12624                 else if (reg->s32_max_value <= sval)
12625                         return 0;
12626                 break;
12627         case BPF_JLT:
12628                 if (reg->u32_max_value < val)
12629                         return 1;
12630                 else if (reg->u32_min_value >= val)
12631                         return 0;
12632                 break;
12633         case BPF_JSLT:
12634                 if (reg->s32_max_value < sval)
12635                         return 1;
12636                 else if (reg->s32_min_value >= sval)
12637                         return 0;
12638                 break;
12639         case BPF_JGE:
12640                 if (reg->u32_min_value >= val)
12641                         return 1;
12642                 else if (reg->u32_max_value < val)
12643                         return 0;
12644                 break;
12645         case BPF_JSGE:
12646                 if (reg->s32_min_value >= sval)
12647                         return 1;
12648                 else if (reg->s32_max_value < sval)
12649                         return 0;
12650                 break;
12651         case BPF_JLE:
12652                 if (reg->u32_max_value <= val)
12653                         return 1;
12654                 else if (reg->u32_min_value > val)
12655                         return 0;
12656                 break;
12657         case BPF_JSLE:
12658                 if (reg->s32_max_value <= sval)
12659                         return 1;
12660                 else if (reg->s32_min_value > sval)
12661                         return 0;
12662                 break;
12663         }
12664
12665         return -1;
12666 }
12667
12668
12669 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
12670 {
12671         s64 sval = (s64)val;
12672
12673         switch (opcode) {
12674         case BPF_JEQ:
12675                 if (tnum_is_const(reg->var_off))
12676                         return !!tnum_equals_const(reg->var_off, val);
12677                 else if (val < reg->umin_value || val > reg->umax_value)
12678                         return 0;
12679                 break;
12680         case BPF_JNE:
12681                 if (tnum_is_const(reg->var_off))
12682                         return !tnum_equals_const(reg->var_off, val);
12683                 else if (val < reg->umin_value || val > reg->umax_value)
12684                         return 1;
12685                 break;
12686         case BPF_JSET:
12687                 if ((~reg->var_off.mask & reg->var_off.value) & val)
12688                         return 1;
12689                 if (!((reg->var_off.mask | reg->var_off.value) & val))
12690                         return 0;
12691                 break;
12692         case BPF_JGT:
12693                 if (reg->umin_value > val)
12694                         return 1;
12695                 else if (reg->umax_value <= val)
12696                         return 0;
12697                 break;
12698         case BPF_JSGT:
12699                 if (reg->smin_value > sval)
12700                         return 1;
12701                 else if (reg->smax_value <= sval)
12702                         return 0;
12703                 break;
12704         case BPF_JLT:
12705                 if (reg->umax_value < val)
12706                         return 1;
12707                 else if (reg->umin_value >= val)
12708                         return 0;
12709                 break;
12710         case BPF_JSLT:
12711                 if (reg->smax_value < sval)
12712                         return 1;
12713                 else if (reg->smin_value >= sval)
12714                         return 0;
12715                 break;
12716         case BPF_JGE:
12717                 if (reg->umin_value >= val)
12718                         return 1;
12719                 else if (reg->umax_value < val)
12720                         return 0;
12721                 break;
12722         case BPF_JSGE:
12723                 if (reg->smin_value >= sval)
12724                         return 1;
12725                 else if (reg->smax_value < sval)
12726                         return 0;
12727                 break;
12728         case BPF_JLE:
12729                 if (reg->umax_value <= val)
12730                         return 1;
12731                 else if (reg->umin_value > val)
12732                         return 0;
12733                 break;
12734         case BPF_JSLE:
12735                 if (reg->smax_value <= sval)
12736                         return 1;
12737                 else if (reg->smin_value > sval)
12738                         return 0;
12739                 break;
12740         }
12741
12742         return -1;
12743 }
12744
12745 /* compute branch direction of the expression "if (reg opcode val) goto target;"
12746  * and return:
12747  *  1 - branch will be taken and "goto target" will be executed
12748  *  0 - branch will not be taken and fall-through to next insn
12749  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
12750  *      range [0,10]
12751  */
12752 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
12753                            bool is_jmp32)
12754 {
12755         if (__is_pointer_value(false, reg)) {
12756                 if (!reg_type_not_null(reg->type))
12757                         return -1;
12758
12759                 /* If pointer is valid tests against zero will fail so we can
12760                  * use this to direct branch taken.
12761                  */
12762                 if (val != 0)
12763                         return -1;
12764
12765                 switch (opcode) {
12766                 case BPF_JEQ:
12767                         return 0;
12768                 case BPF_JNE:
12769                         return 1;
12770                 default:
12771                         return -1;
12772                 }
12773         }
12774
12775         if (is_jmp32)
12776                 return is_branch32_taken(reg, val, opcode);
12777         return is_branch64_taken(reg, val, opcode);
12778 }
12779
12780 static int flip_opcode(u32 opcode)
12781 {
12782         /* How can we transform "a <op> b" into "b <op> a"? */
12783         static const u8 opcode_flip[16] = {
12784                 /* these stay the same */
12785                 [BPF_JEQ  >> 4] = BPF_JEQ,
12786                 [BPF_JNE  >> 4] = BPF_JNE,
12787                 [BPF_JSET >> 4] = BPF_JSET,
12788                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
12789                 [BPF_JGE  >> 4] = BPF_JLE,
12790                 [BPF_JGT  >> 4] = BPF_JLT,
12791                 [BPF_JLE  >> 4] = BPF_JGE,
12792                 [BPF_JLT  >> 4] = BPF_JGT,
12793                 [BPF_JSGE >> 4] = BPF_JSLE,
12794                 [BPF_JSGT >> 4] = BPF_JSLT,
12795                 [BPF_JSLE >> 4] = BPF_JSGE,
12796                 [BPF_JSLT >> 4] = BPF_JSGT
12797         };
12798         return opcode_flip[opcode >> 4];
12799 }
12800
12801 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
12802                                    struct bpf_reg_state *src_reg,
12803                                    u8 opcode)
12804 {
12805         struct bpf_reg_state *pkt;
12806
12807         if (src_reg->type == PTR_TO_PACKET_END) {
12808                 pkt = dst_reg;
12809         } else if (dst_reg->type == PTR_TO_PACKET_END) {
12810                 pkt = src_reg;
12811                 opcode = flip_opcode(opcode);
12812         } else {
12813                 return -1;
12814         }
12815
12816         if (pkt->range >= 0)
12817                 return -1;
12818
12819         switch (opcode) {
12820         case BPF_JLE:
12821                 /* pkt <= pkt_end */
12822                 fallthrough;
12823         case BPF_JGT:
12824                 /* pkt > pkt_end */
12825                 if (pkt->range == BEYOND_PKT_END)
12826                         /* pkt has at last one extra byte beyond pkt_end */
12827                         return opcode == BPF_JGT;
12828                 break;
12829         case BPF_JLT:
12830                 /* pkt < pkt_end */
12831                 fallthrough;
12832         case BPF_JGE:
12833                 /* pkt >= pkt_end */
12834                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
12835                         return opcode == BPF_JGE;
12836                 break;
12837         }
12838         return -1;
12839 }
12840
12841 /* Adjusts the register min/max values in the case that the dst_reg is the
12842  * variable register that we are working on, and src_reg is a constant or we're
12843  * simply doing a BPF_K check.
12844  * In JEQ/JNE cases we also adjust the var_off values.
12845  */
12846 static void reg_set_min_max(struct bpf_reg_state *true_reg,
12847                             struct bpf_reg_state *false_reg,
12848                             u64 val, u32 val32,
12849                             u8 opcode, bool is_jmp32)
12850 {
12851         struct tnum false_32off = tnum_subreg(false_reg->var_off);
12852         struct tnum false_64off = false_reg->var_off;
12853         struct tnum true_32off = tnum_subreg(true_reg->var_off);
12854         struct tnum true_64off = true_reg->var_off;
12855         s64 sval = (s64)val;
12856         s32 sval32 = (s32)val32;
12857
12858         /* If the dst_reg is a pointer, we can't learn anything about its
12859          * variable offset from the compare (unless src_reg were a pointer into
12860          * the same object, but we don't bother with that.
12861          * Since false_reg and true_reg have the same type by construction, we
12862          * only need to check one of them for pointerness.
12863          */
12864         if (__is_pointer_value(false, false_reg))
12865                 return;
12866
12867         switch (opcode) {
12868         /* JEQ/JNE comparison doesn't change the register equivalence.
12869          *
12870          * r1 = r2;
12871          * if (r1 == 42) goto label;
12872          * ...
12873          * label: // here both r1 and r2 are known to be 42.
12874          *
12875          * Hence when marking register as known preserve it's ID.
12876          */
12877         case BPF_JEQ:
12878                 if (is_jmp32) {
12879                         __mark_reg32_known(true_reg, val32);
12880                         true_32off = tnum_subreg(true_reg->var_off);
12881                 } else {
12882                         ___mark_reg_known(true_reg, val);
12883                         true_64off = true_reg->var_off;
12884                 }
12885                 break;
12886         case BPF_JNE:
12887                 if (is_jmp32) {
12888                         __mark_reg32_known(false_reg, val32);
12889                         false_32off = tnum_subreg(false_reg->var_off);
12890                 } else {
12891                         ___mark_reg_known(false_reg, val);
12892                         false_64off = false_reg->var_off;
12893                 }
12894                 break;
12895         case BPF_JSET:
12896                 if (is_jmp32) {
12897                         false_32off = tnum_and(false_32off, tnum_const(~val32));
12898                         if (is_power_of_2(val32))
12899                                 true_32off = tnum_or(true_32off,
12900                                                      tnum_const(val32));
12901                 } else {
12902                         false_64off = tnum_and(false_64off, tnum_const(~val));
12903                         if (is_power_of_2(val))
12904                                 true_64off = tnum_or(true_64off,
12905                                                      tnum_const(val));
12906                 }
12907                 break;
12908         case BPF_JGE:
12909         case BPF_JGT:
12910         {
12911                 if (is_jmp32) {
12912                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
12913                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
12914
12915                         false_reg->u32_max_value = min(false_reg->u32_max_value,
12916                                                        false_umax);
12917                         true_reg->u32_min_value = max(true_reg->u32_min_value,
12918                                                       true_umin);
12919                 } else {
12920                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
12921                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
12922
12923                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
12924                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
12925                 }
12926                 break;
12927         }
12928         case BPF_JSGE:
12929         case BPF_JSGT:
12930         {
12931                 if (is_jmp32) {
12932                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
12933                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
12934
12935                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
12936                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
12937                 } else {
12938                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
12939                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
12940
12941                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
12942                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
12943                 }
12944                 break;
12945         }
12946         case BPF_JLE:
12947         case BPF_JLT:
12948         {
12949                 if (is_jmp32) {
12950                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
12951                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
12952
12953                         false_reg->u32_min_value = max(false_reg->u32_min_value,
12954                                                        false_umin);
12955                         true_reg->u32_max_value = min(true_reg->u32_max_value,
12956                                                       true_umax);
12957                 } else {
12958                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
12959                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
12960
12961                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
12962                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
12963                 }
12964                 break;
12965         }
12966         case BPF_JSLE:
12967         case BPF_JSLT:
12968         {
12969                 if (is_jmp32) {
12970                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
12971                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
12972
12973                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
12974                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
12975                 } else {
12976                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
12977                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
12978
12979                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
12980                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
12981                 }
12982                 break;
12983         }
12984         default:
12985                 return;
12986         }
12987
12988         if (is_jmp32) {
12989                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
12990                                              tnum_subreg(false_32off));
12991                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
12992                                             tnum_subreg(true_32off));
12993                 __reg_combine_32_into_64(false_reg);
12994                 __reg_combine_32_into_64(true_reg);
12995         } else {
12996                 false_reg->var_off = false_64off;
12997                 true_reg->var_off = true_64off;
12998                 __reg_combine_64_into_32(false_reg);
12999                 __reg_combine_64_into_32(true_reg);
13000         }
13001 }
13002
13003 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13004  * the variable reg.
13005  */
13006 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13007                                 struct bpf_reg_state *false_reg,
13008                                 u64 val, u32 val32,
13009                                 u8 opcode, bool is_jmp32)
13010 {
13011         opcode = flip_opcode(opcode);
13012         /* This uses zero as "not present in table"; luckily the zero opcode,
13013          * BPF_JA, can't get here.
13014          */
13015         if (opcode)
13016                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13017 }
13018
13019 /* Regs are known to be equal, so intersect their min/max/var_off */
13020 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13021                                   struct bpf_reg_state *dst_reg)
13022 {
13023         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13024                                                         dst_reg->umin_value);
13025         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13026                                                         dst_reg->umax_value);
13027         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13028                                                         dst_reg->smin_value);
13029         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13030                                                         dst_reg->smax_value);
13031         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13032                                                              dst_reg->var_off);
13033         reg_bounds_sync(src_reg);
13034         reg_bounds_sync(dst_reg);
13035 }
13036
13037 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13038                                 struct bpf_reg_state *true_dst,
13039                                 struct bpf_reg_state *false_src,
13040                                 struct bpf_reg_state *false_dst,
13041                                 u8 opcode)
13042 {
13043         switch (opcode) {
13044         case BPF_JEQ:
13045                 __reg_combine_min_max(true_src, true_dst);
13046                 break;
13047         case BPF_JNE:
13048                 __reg_combine_min_max(false_src, false_dst);
13049                 break;
13050         }
13051 }
13052
13053 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13054                                  struct bpf_reg_state *reg, u32 id,
13055                                  bool is_null)
13056 {
13057         if (type_may_be_null(reg->type) && reg->id == id &&
13058             (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13059                 /* Old offset (both fixed and variable parts) should have been
13060                  * known-zero, because we don't allow pointer arithmetic on
13061                  * pointers that might be NULL. If we see this happening, don't
13062                  * convert the register.
13063                  *
13064                  * But in some cases, some helpers that return local kptrs
13065                  * advance offset for the returned pointer. In those cases, it
13066                  * is fine to expect to see reg->off.
13067                  */
13068                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13069                         return;
13070                 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13071                     WARN_ON_ONCE(reg->off))
13072                         return;
13073
13074                 if (is_null) {
13075                         reg->type = SCALAR_VALUE;
13076                         /* We don't need id and ref_obj_id from this point
13077                          * onwards anymore, thus we should better reset it,
13078                          * so that state pruning has chances to take effect.
13079                          */
13080                         reg->id = 0;
13081                         reg->ref_obj_id = 0;
13082
13083                         return;
13084                 }
13085
13086                 mark_ptr_not_null_reg(reg);
13087
13088                 if (!reg_may_point_to_spin_lock(reg)) {
13089                         /* For not-NULL ptr, reg->ref_obj_id will be reset
13090                          * in release_reference().
13091                          *
13092                          * reg->id is still used by spin_lock ptr. Other
13093                          * than spin_lock ptr type, reg->id can be reset.
13094                          */
13095                         reg->id = 0;
13096                 }
13097         }
13098 }
13099
13100 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13101  * be folded together at some point.
13102  */
13103 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13104                                   bool is_null)
13105 {
13106         struct bpf_func_state *state = vstate->frame[vstate->curframe];
13107         struct bpf_reg_state *regs = state->regs, *reg;
13108         u32 ref_obj_id = regs[regno].ref_obj_id;
13109         u32 id = regs[regno].id;
13110
13111         if (ref_obj_id && ref_obj_id == id && is_null)
13112                 /* regs[regno] is in the " == NULL" branch.
13113                  * No one could have freed the reference state before
13114                  * doing the NULL check.
13115                  */
13116                 WARN_ON_ONCE(release_reference_state(state, id));
13117
13118         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13119                 mark_ptr_or_null_reg(state, reg, id, is_null);
13120         }));
13121 }
13122
13123 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13124                                    struct bpf_reg_state *dst_reg,
13125                                    struct bpf_reg_state *src_reg,
13126                                    struct bpf_verifier_state *this_branch,
13127                                    struct bpf_verifier_state *other_branch)
13128 {
13129         if (BPF_SRC(insn->code) != BPF_X)
13130                 return false;
13131
13132         /* Pointers are always 64-bit. */
13133         if (BPF_CLASS(insn->code) == BPF_JMP32)
13134                 return false;
13135
13136         switch (BPF_OP(insn->code)) {
13137         case BPF_JGT:
13138                 if ((dst_reg->type == PTR_TO_PACKET &&
13139                      src_reg->type == PTR_TO_PACKET_END) ||
13140                     (dst_reg->type == PTR_TO_PACKET_META &&
13141                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13142                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13143                         find_good_pkt_pointers(this_branch, dst_reg,
13144                                                dst_reg->type, false);
13145                         mark_pkt_end(other_branch, insn->dst_reg, true);
13146                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13147                             src_reg->type == PTR_TO_PACKET) ||
13148                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13149                             src_reg->type == PTR_TO_PACKET_META)) {
13150                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
13151                         find_good_pkt_pointers(other_branch, src_reg,
13152                                                src_reg->type, true);
13153                         mark_pkt_end(this_branch, insn->src_reg, false);
13154                 } else {
13155                         return false;
13156                 }
13157                 break;
13158         case BPF_JLT:
13159                 if ((dst_reg->type == PTR_TO_PACKET &&
13160                      src_reg->type == PTR_TO_PACKET_END) ||
13161                     (dst_reg->type == PTR_TO_PACKET_META &&
13162                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13163                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13164                         find_good_pkt_pointers(other_branch, dst_reg,
13165                                                dst_reg->type, true);
13166                         mark_pkt_end(this_branch, insn->dst_reg, false);
13167                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13168                             src_reg->type == PTR_TO_PACKET) ||
13169                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13170                             src_reg->type == PTR_TO_PACKET_META)) {
13171                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
13172                         find_good_pkt_pointers(this_branch, src_reg,
13173                                                src_reg->type, false);
13174                         mark_pkt_end(other_branch, insn->src_reg, true);
13175                 } else {
13176                         return false;
13177                 }
13178                 break;
13179         case BPF_JGE:
13180                 if ((dst_reg->type == PTR_TO_PACKET &&
13181                      src_reg->type == PTR_TO_PACKET_END) ||
13182                     (dst_reg->type == PTR_TO_PACKET_META &&
13183                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13184                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13185                         find_good_pkt_pointers(this_branch, dst_reg,
13186                                                dst_reg->type, true);
13187                         mark_pkt_end(other_branch, insn->dst_reg, false);
13188                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13189                             src_reg->type == PTR_TO_PACKET) ||
13190                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13191                             src_reg->type == PTR_TO_PACKET_META)) {
13192                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
13193                         find_good_pkt_pointers(other_branch, src_reg,
13194                                                src_reg->type, false);
13195                         mark_pkt_end(this_branch, insn->src_reg, true);
13196                 } else {
13197                         return false;
13198                 }
13199                 break;
13200         case BPF_JLE:
13201                 if ((dst_reg->type == PTR_TO_PACKET &&
13202                      src_reg->type == PTR_TO_PACKET_END) ||
13203                     (dst_reg->type == PTR_TO_PACKET_META &&
13204                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13205                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
13206                         find_good_pkt_pointers(other_branch, dst_reg,
13207                                                dst_reg->type, false);
13208                         mark_pkt_end(this_branch, insn->dst_reg, true);
13209                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13210                             src_reg->type == PTR_TO_PACKET) ||
13211                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13212                             src_reg->type == PTR_TO_PACKET_META)) {
13213                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
13214                         find_good_pkt_pointers(this_branch, src_reg,
13215                                                src_reg->type, true);
13216                         mark_pkt_end(other_branch, insn->src_reg, false);
13217                 } else {
13218                         return false;
13219                 }
13220                 break;
13221         default:
13222                 return false;
13223         }
13224
13225         return true;
13226 }
13227
13228 static void find_equal_scalars(struct bpf_verifier_state *vstate,
13229                                struct bpf_reg_state *known_reg)
13230 {
13231         struct bpf_func_state *state;
13232         struct bpf_reg_state *reg;
13233
13234         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13235                 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
13236                         copy_register_state(reg, known_reg);
13237         }));
13238 }
13239
13240 static int check_cond_jmp_op(struct bpf_verifier_env *env,
13241                              struct bpf_insn *insn, int *insn_idx)
13242 {
13243         struct bpf_verifier_state *this_branch = env->cur_state;
13244         struct bpf_verifier_state *other_branch;
13245         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
13246         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
13247         struct bpf_reg_state *eq_branch_regs;
13248         u8 opcode = BPF_OP(insn->code);
13249         bool is_jmp32;
13250         int pred = -1;
13251         int err;
13252
13253         /* Only conditional jumps are expected to reach here. */
13254         if (opcode == BPF_JA || opcode > BPF_JSLE) {
13255                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
13256                 return -EINVAL;
13257         }
13258
13259         if (BPF_SRC(insn->code) == BPF_X) {
13260                 if (insn->imm != 0) {
13261                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13262                         return -EINVAL;
13263                 }
13264
13265                 /* check src1 operand */
13266                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13267                 if (err)
13268                         return err;
13269
13270                 if (is_pointer_value(env, insn->src_reg)) {
13271                         verbose(env, "R%d pointer comparison prohibited\n",
13272                                 insn->src_reg);
13273                         return -EACCES;
13274                 }
13275                 src_reg = &regs[insn->src_reg];
13276         } else {
13277                 if (insn->src_reg != BPF_REG_0) {
13278                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
13279                         return -EINVAL;
13280                 }
13281         }
13282
13283         /* check src2 operand */
13284         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13285         if (err)
13286                 return err;
13287
13288         dst_reg = &regs[insn->dst_reg];
13289         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
13290
13291         if (BPF_SRC(insn->code) == BPF_K) {
13292                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
13293         } else if (src_reg->type == SCALAR_VALUE &&
13294                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
13295                 pred = is_branch_taken(dst_reg,
13296                                        tnum_subreg(src_reg->var_off).value,
13297                                        opcode,
13298                                        is_jmp32);
13299         } else if (src_reg->type == SCALAR_VALUE &&
13300                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
13301                 pred = is_branch_taken(dst_reg,
13302                                        src_reg->var_off.value,
13303                                        opcode,
13304                                        is_jmp32);
13305         } else if (dst_reg->type == SCALAR_VALUE &&
13306                    is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
13307                 pred = is_branch_taken(src_reg,
13308                                        tnum_subreg(dst_reg->var_off).value,
13309                                        flip_opcode(opcode),
13310                                        is_jmp32);
13311         } else if (dst_reg->type == SCALAR_VALUE &&
13312                    !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
13313                 pred = is_branch_taken(src_reg,
13314                                        dst_reg->var_off.value,
13315                                        flip_opcode(opcode),
13316                                        is_jmp32);
13317         } else if (reg_is_pkt_pointer_any(dst_reg) &&
13318                    reg_is_pkt_pointer_any(src_reg) &&
13319                    !is_jmp32) {
13320                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
13321         }
13322
13323         if (pred >= 0) {
13324                 /* If we get here with a dst_reg pointer type it is because
13325                  * above is_branch_taken() special cased the 0 comparison.
13326                  */
13327                 if (!__is_pointer_value(false, dst_reg))
13328                         err = mark_chain_precision(env, insn->dst_reg);
13329                 if (BPF_SRC(insn->code) == BPF_X && !err &&
13330                     !__is_pointer_value(false, src_reg))
13331                         err = mark_chain_precision(env, insn->src_reg);
13332                 if (err)
13333                         return err;
13334         }
13335
13336         if (pred == 1) {
13337                 /* Only follow the goto, ignore fall-through. If needed, push
13338                  * the fall-through branch for simulation under speculative
13339                  * execution.
13340                  */
13341                 if (!env->bypass_spec_v1 &&
13342                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
13343                                                *insn_idx))
13344                         return -EFAULT;
13345                 *insn_idx += insn->off;
13346                 return 0;
13347         } else if (pred == 0) {
13348                 /* Only follow the fall-through branch, since that's where the
13349                  * program will go. If needed, push the goto branch for
13350                  * simulation under speculative execution.
13351                  */
13352                 if (!env->bypass_spec_v1 &&
13353                     !sanitize_speculative_path(env, insn,
13354                                                *insn_idx + insn->off + 1,
13355                                                *insn_idx))
13356                         return -EFAULT;
13357                 return 0;
13358         }
13359
13360         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
13361                                   false);
13362         if (!other_branch)
13363                 return -EFAULT;
13364         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
13365
13366         /* detect if we are comparing against a constant value so we can adjust
13367          * our min/max values for our dst register.
13368          * this is only legit if both are scalars (or pointers to the same
13369          * object, I suppose, see the PTR_MAYBE_NULL related if block below),
13370          * because otherwise the different base pointers mean the offsets aren't
13371          * comparable.
13372          */
13373         if (BPF_SRC(insn->code) == BPF_X) {
13374                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
13375
13376                 if (dst_reg->type == SCALAR_VALUE &&
13377                     src_reg->type == SCALAR_VALUE) {
13378                         if (tnum_is_const(src_reg->var_off) ||
13379                             (is_jmp32 &&
13380                              tnum_is_const(tnum_subreg(src_reg->var_off))))
13381                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
13382                                                 dst_reg,
13383                                                 src_reg->var_off.value,
13384                                                 tnum_subreg(src_reg->var_off).value,
13385                                                 opcode, is_jmp32);
13386                         else if (tnum_is_const(dst_reg->var_off) ||
13387                                  (is_jmp32 &&
13388                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
13389                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
13390                                                     src_reg,
13391                                                     dst_reg->var_off.value,
13392                                                     tnum_subreg(dst_reg->var_off).value,
13393                                                     opcode, is_jmp32);
13394                         else if (!is_jmp32 &&
13395                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
13396                                 /* Comparing for equality, we can combine knowledge */
13397                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
13398                                                     &other_branch_regs[insn->dst_reg],
13399                                                     src_reg, dst_reg, opcode);
13400                         if (src_reg->id &&
13401                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
13402                                 find_equal_scalars(this_branch, src_reg);
13403                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
13404                         }
13405
13406                 }
13407         } else if (dst_reg->type == SCALAR_VALUE) {
13408                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
13409                                         dst_reg, insn->imm, (u32)insn->imm,
13410                                         opcode, is_jmp32);
13411         }
13412
13413         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
13414             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
13415                 find_equal_scalars(this_branch, dst_reg);
13416                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
13417         }
13418
13419         /* if one pointer register is compared to another pointer
13420          * register check if PTR_MAYBE_NULL could be lifted.
13421          * E.g. register A - maybe null
13422          *      register B - not null
13423          * for JNE A, B, ... - A is not null in the false branch;
13424          * for JEQ A, B, ... - A is not null in the true branch.
13425          *
13426          * Since PTR_TO_BTF_ID points to a kernel struct that does
13427          * not need to be null checked by the BPF program, i.e.,
13428          * could be null even without PTR_MAYBE_NULL marking, so
13429          * only propagate nullness when neither reg is that type.
13430          */
13431         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
13432             __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
13433             type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
13434             base_type(src_reg->type) != PTR_TO_BTF_ID &&
13435             base_type(dst_reg->type) != PTR_TO_BTF_ID) {
13436                 eq_branch_regs = NULL;
13437                 switch (opcode) {
13438                 case BPF_JEQ:
13439                         eq_branch_regs = other_branch_regs;
13440                         break;
13441                 case BPF_JNE:
13442                         eq_branch_regs = regs;
13443                         break;
13444                 default:
13445                         /* do nothing */
13446                         break;
13447                 }
13448                 if (eq_branch_regs) {
13449                         if (type_may_be_null(src_reg->type))
13450                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
13451                         else
13452                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
13453                 }
13454         }
13455
13456         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
13457          * NOTE: these optimizations below are related with pointer comparison
13458          *       which will never be JMP32.
13459          */
13460         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
13461             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
13462             type_may_be_null(dst_reg->type)) {
13463                 /* Mark all identical registers in each branch as either
13464                  * safe or unknown depending R == 0 or R != 0 conditional.
13465                  */
13466                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
13467                                       opcode == BPF_JNE);
13468                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
13469                                       opcode == BPF_JEQ);
13470         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
13471                                            this_branch, other_branch) &&
13472                    is_pointer_value(env, insn->dst_reg)) {
13473                 verbose(env, "R%d pointer comparison prohibited\n",
13474                         insn->dst_reg);
13475                 return -EACCES;
13476         }
13477         if (env->log.level & BPF_LOG_LEVEL)
13478                 print_insn_state(env, this_branch->frame[this_branch->curframe]);
13479         return 0;
13480 }
13481
13482 /* verify BPF_LD_IMM64 instruction */
13483 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
13484 {
13485         struct bpf_insn_aux_data *aux = cur_aux(env);
13486         struct bpf_reg_state *regs = cur_regs(env);
13487         struct bpf_reg_state *dst_reg;
13488         struct bpf_map *map;
13489         int err;
13490
13491         if (BPF_SIZE(insn->code) != BPF_DW) {
13492                 verbose(env, "invalid BPF_LD_IMM insn\n");
13493                 return -EINVAL;
13494         }
13495         if (insn->off != 0) {
13496                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
13497                 return -EINVAL;
13498         }
13499
13500         err = check_reg_arg(env, insn->dst_reg, DST_OP);
13501         if (err)
13502                 return err;
13503
13504         dst_reg = &regs[insn->dst_reg];
13505         if (insn->src_reg == 0) {
13506                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
13507
13508                 dst_reg->type = SCALAR_VALUE;
13509                 __mark_reg_known(&regs[insn->dst_reg], imm);
13510                 return 0;
13511         }
13512
13513         /* All special src_reg cases are listed below. From this point onwards
13514          * we either succeed and assign a corresponding dst_reg->type after
13515          * zeroing the offset, or fail and reject the program.
13516          */
13517         mark_reg_known_zero(env, regs, insn->dst_reg);
13518
13519         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
13520                 dst_reg->type = aux->btf_var.reg_type;
13521                 switch (base_type(dst_reg->type)) {
13522                 case PTR_TO_MEM:
13523                         dst_reg->mem_size = aux->btf_var.mem_size;
13524                         break;
13525                 case PTR_TO_BTF_ID:
13526                         dst_reg->btf = aux->btf_var.btf;
13527                         dst_reg->btf_id = aux->btf_var.btf_id;
13528                         break;
13529                 default:
13530                         verbose(env, "bpf verifier is misconfigured\n");
13531                         return -EFAULT;
13532                 }
13533                 return 0;
13534         }
13535
13536         if (insn->src_reg == BPF_PSEUDO_FUNC) {
13537                 struct bpf_prog_aux *aux = env->prog->aux;
13538                 u32 subprogno = find_subprog(env,
13539                                              env->insn_idx + insn->imm + 1);
13540
13541                 if (!aux->func_info) {
13542                         verbose(env, "missing btf func_info\n");
13543                         return -EINVAL;
13544                 }
13545                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
13546                         verbose(env, "callback function not static\n");
13547                         return -EINVAL;
13548                 }
13549
13550                 dst_reg->type = PTR_TO_FUNC;
13551                 dst_reg->subprogno = subprogno;
13552                 return 0;
13553         }
13554
13555         map = env->used_maps[aux->map_index];
13556         dst_reg->map_ptr = map;
13557
13558         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
13559             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
13560                 dst_reg->type = PTR_TO_MAP_VALUE;
13561                 dst_reg->off = aux->map_off;
13562                 WARN_ON_ONCE(map->max_entries != 1);
13563                 /* We want reg->id to be same (0) as map_value is not distinct */
13564         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
13565                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
13566                 dst_reg->type = CONST_PTR_TO_MAP;
13567         } else {
13568                 verbose(env, "bpf verifier is misconfigured\n");
13569                 return -EINVAL;
13570         }
13571
13572         return 0;
13573 }
13574
13575 static bool may_access_skb(enum bpf_prog_type type)
13576 {
13577         switch (type) {
13578         case BPF_PROG_TYPE_SOCKET_FILTER:
13579         case BPF_PROG_TYPE_SCHED_CLS:
13580         case BPF_PROG_TYPE_SCHED_ACT:
13581                 return true;
13582         default:
13583                 return false;
13584         }
13585 }
13586
13587 /* verify safety of LD_ABS|LD_IND instructions:
13588  * - they can only appear in the programs where ctx == skb
13589  * - since they are wrappers of function calls, they scratch R1-R5 registers,
13590  *   preserve R6-R9, and store return value into R0
13591  *
13592  * Implicit input:
13593  *   ctx == skb == R6 == CTX
13594  *
13595  * Explicit input:
13596  *   SRC == any register
13597  *   IMM == 32-bit immediate
13598  *
13599  * Output:
13600  *   R0 - 8/16/32-bit skb data converted to cpu endianness
13601  */
13602 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
13603 {
13604         struct bpf_reg_state *regs = cur_regs(env);
13605         static const int ctx_reg = BPF_REG_6;
13606         u8 mode = BPF_MODE(insn->code);
13607         int i, err;
13608
13609         if (!may_access_skb(resolve_prog_type(env->prog))) {
13610                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
13611                 return -EINVAL;
13612         }
13613
13614         if (!env->ops->gen_ld_abs) {
13615                 verbose(env, "bpf verifier is misconfigured\n");
13616                 return -EINVAL;
13617         }
13618
13619         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
13620             BPF_SIZE(insn->code) == BPF_DW ||
13621             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
13622                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
13623                 return -EINVAL;
13624         }
13625
13626         /* check whether implicit source operand (register R6) is readable */
13627         err = check_reg_arg(env, ctx_reg, SRC_OP);
13628         if (err)
13629                 return err;
13630
13631         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
13632          * gen_ld_abs() may terminate the program at runtime, leading to
13633          * reference leak.
13634          */
13635         err = check_reference_leak(env);
13636         if (err) {
13637                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
13638                 return err;
13639         }
13640
13641         if (env->cur_state->active_lock.ptr) {
13642                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
13643                 return -EINVAL;
13644         }
13645
13646         if (env->cur_state->active_rcu_lock) {
13647                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
13648                 return -EINVAL;
13649         }
13650
13651         if (regs[ctx_reg].type != PTR_TO_CTX) {
13652                 verbose(env,
13653                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
13654                 return -EINVAL;
13655         }
13656
13657         if (mode == BPF_IND) {
13658                 /* check explicit source operand */
13659                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13660                 if (err)
13661                         return err;
13662         }
13663
13664         err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
13665         if (err < 0)
13666                 return err;
13667
13668         /* reset caller saved regs to unreadable */
13669         for (i = 0; i < CALLER_SAVED_REGS; i++) {
13670                 mark_reg_not_init(env, regs, caller_saved[i]);
13671                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
13672         }
13673
13674         /* mark destination R0 register as readable, since it contains
13675          * the value fetched from the packet.
13676          * Already marked as written above.
13677          */
13678         mark_reg_unknown(env, regs, BPF_REG_0);
13679         /* ld_abs load up to 32-bit skb data. */
13680         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
13681         return 0;
13682 }
13683
13684 static int check_return_code(struct bpf_verifier_env *env)
13685 {
13686         struct tnum enforce_attach_type_range = tnum_unknown;
13687         const struct bpf_prog *prog = env->prog;
13688         struct bpf_reg_state *reg;
13689         struct tnum range = tnum_range(0, 1);
13690         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
13691         int err;
13692         struct bpf_func_state *frame = env->cur_state->frame[0];
13693         const bool is_subprog = frame->subprogno;
13694
13695         /* LSM and struct_ops func-ptr's return type could be "void" */
13696         if (!is_subprog) {
13697                 switch (prog_type) {
13698                 case BPF_PROG_TYPE_LSM:
13699                         if (prog->expected_attach_type == BPF_LSM_CGROUP)
13700                                 /* See below, can be 0 or 0-1 depending on hook. */
13701                                 break;
13702                         fallthrough;
13703                 case BPF_PROG_TYPE_STRUCT_OPS:
13704                         if (!prog->aux->attach_func_proto->type)
13705                                 return 0;
13706                         break;
13707                 default:
13708                         break;
13709                 }
13710         }
13711
13712         /* eBPF calling convention is such that R0 is used
13713          * to return the value from eBPF program.
13714          * Make sure that it's readable at this time
13715          * of bpf_exit, which means that program wrote
13716          * something into it earlier
13717          */
13718         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
13719         if (err)
13720                 return err;
13721
13722         if (is_pointer_value(env, BPF_REG_0)) {
13723                 verbose(env, "R0 leaks addr as return value\n");
13724                 return -EACCES;
13725         }
13726
13727         reg = cur_regs(env) + BPF_REG_0;
13728
13729         if (frame->in_async_callback_fn) {
13730                 /* enforce return zero from async callbacks like timer */
13731                 if (reg->type != SCALAR_VALUE) {
13732                         verbose(env, "In async callback the register R0 is not a known value (%s)\n",
13733                                 reg_type_str(env, reg->type));
13734                         return -EINVAL;
13735                 }
13736
13737                 if (!tnum_in(tnum_const(0), reg->var_off)) {
13738                         verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
13739                         return -EINVAL;
13740                 }
13741                 return 0;
13742         }
13743
13744         if (is_subprog) {
13745                 if (reg->type != SCALAR_VALUE) {
13746                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
13747                                 reg_type_str(env, reg->type));
13748                         return -EINVAL;
13749                 }
13750                 return 0;
13751         }
13752
13753         switch (prog_type) {
13754         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
13755                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
13756                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
13757                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
13758                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
13759                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
13760                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
13761                         range = tnum_range(1, 1);
13762                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
13763                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
13764                         range = tnum_range(0, 3);
13765                 break;
13766         case BPF_PROG_TYPE_CGROUP_SKB:
13767                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
13768                         range = tnum_range(0, 3);
13769                         enforce_attach_type_range = tnum_range(2, 3);
13770                 }
13771                 break;
13772         case BPF_PROG_TYPE_CGROUP_SOCK:
13773         case BPF_PROG_TYPE_SOCK_OPS:
13774         case BPF_PROG_TYPE_CGROUP_DEVICE:
13775         case BPF_PROG_TYPE_CGROUP_SYSCTL:
13776         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
13777                 break;
13778         case BPF_PROG_TYPE_RAW_TRACEPOINT:
13779                 if (!env->prog->aux->attach_btf_id)
13780                         return 0;
13781                 range = tnum_const(0);
13782                 break;
13783         case BPF_PROG_TYPE_TRACING:
13784                 switch (env->prog->expected_attach_type) {
13785                 case BPF_TRACE_FENTRY:
13786                 case BPF_TRACE_FEXIT:
13787                         range = tnum_const(0);
13788                         break;
13789                 case BPF_TRACE_RAW_TP:
13790                 case BPF_MODIFY_RETURN:
13791                         return 0;
13792                 case BPF_TRACE_ITER:
13793                         break;
13794                 default:
13795                         return -ENOTSUPP;
13796                 }
13797                 break;
13798         case BPF_PROG_TYPE_SK_LOOKUP:
13799                 range = tnum_range(SK_DROP, SK_PASS);
13800                 break;
13801
13802         case BPF_PROG_TYPE_LSM:
13803                 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
13804                         /* Regular BPF_PROG_TYPE_LSM programs can return
13805                          * any value.
13806                          */
13807                         return 0;
13808                 }
13809                 if (!env->prog->aux->attach_func_proto->type) {
13810                         /* Make sure programs that attach to void
13811                          * hooks don't try to modify return value.
13812                          */
13813                         range = tnum_range(1, 1);
13814                 }
13815                 break;
13816
13817         case BPF_PROG_TYPE_EXT:
13818                 /* freplace program can return anything as its return value
13819                  * depends on the to-be-replaced kernel func or bpf program.
13820                  */
13821         default:
13822                 return 0;
13823         }
13824
13825         if (reg->type != SCALAR_VALUE) {
13826                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
13827                         reg_type_str(env, reg->type));
13828                 return -EINVAL;
13829         }
13830
13831         if (!tnum_in(range, reg->var_off)) {
13832                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
13833                 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
13834                     prog_type == BPF_PROG_TYPE_LSM &&
13835                     !prog->aux->attach_func_proto->type)
13836                         verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
13837                 return -EINVAL;
13838         }
13839
13840         if (!tnum_is_unknown(enforce_attach_type_range) &&
13841             tnum_in(enforce_attach_type_range, reg->var_off))
13842                 env->prog->enforce_expected_attach_type = 1;
13843         return 0;
13844 }
13845
13846 /* non-recursive DFS pseudo code
13847  * 1  procedure DFS-iterative(G,v):
13848  * 2      label v as discovered
13849  * 3      let S be a stack
13850  * 4      S.push(v)
13851  * 5      while S is not empty
13852  * 6            t <- S.peek()
13853  * 7            if t is what we're looking for:
13854  * 8                return t
13855  * 9            for all edges e in G.adjacentEdges(t) do
13856  * 10               if edge e is already labelled
13857  * 11                   continue with the next edge
13858  * 12               w <- G.adjacentVertex(t,e)
13859  * 13               if vertex w is not discovered and not explored
13860  * 14                   label e as tree-edge
13861  * 15                   label w as discovered
13862  * 16                   S.push(w)
13863  * 17                   continue at 5
13864  * 18               else if vertex w is discovered
13865  * 19                   label e as back-edge
13866  * 20               else
13867  * 21                   // vertex w is explored
13868  * 22                   label e as forward- or cross-edge
13869  * 23           label t as explored
13870  * 24           S.pop()
13871  *
13872  * convention:
13873  * 0x10 - discovered
13874  * 0x11 - discovered and fall-through edge labelled
13875  * 0x12 - discovered and fall-through and branch edges labelled
13876  * 0x20 - explored
13877  */
13878
13879 enum {
13880         DISCOVERED = 0x10,
13881         EXPLORED = 0x20,
13882         FALLTHROUGH = 1,
13883         BRANCH = 2,
13884 };
13885
13886 static u32 state_htab_size(struct bpf_verifier_env *env)
13887 {
13888         return env->prog->len;
13889 }
13890
13891 static struct bpf_verifier_state_list **explored_state(
13892                                         struct bpf_verifier_env *env,
13893                                         int idx)
13894 {
13895         struct bpf_verifier_state *cur = env->cur_state;
13896         struct bpf_func_state *state = cur->frame[cur->curframe];
13897
13898         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
13899 }
13900
13901 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
13902 {
13903         env->insn_aux_data[idx].prune_point = true;
13904 }
13905
13906 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
13907 {
13908         return env->insn_aux_data[insn_idx].prune_point;
13909 }
13910
13911 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
13912 {
13913         env->insn_aux_data[idx].force_checkpoint = true;
13914 }
13915
13916 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
13917 {
13918         return env->insn_aux_data[insn_idx].force_checkpoint;
13919 }
13920
13921
13922 enum {
13923         DONE_EXPLORING = 0,
13924         KEEP_EXPLORING = 1,
13925 };
13926
13927 /* t, w, e - match pseudo-code above:
13928  * t - index of current instruction
13929  * w - next instruction
13930  * e - edge
13931  */
13932 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
13933                      bool loop_ok)
13934 {
13935         int *insn_stack = env->cfg.insn_stack;
13936         int *insn_state = env->cfg.insn_state;
13937
13938         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
13939                 return DONE_EXPLORING;
13940
13941         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
13942                 return DONE_EXPLORING;
13943
13944         if (w < 0 || w >= env->prog->len) {
13945                 verbose_linfo(env, t, "%d: ", t);
13946                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
13947                 return -EINVAL;
13948         }
13949
13950         if (e == BRANCH) {
13951                 /* mark branch target for state pruning */
13952                 mark_prune_point(env, w);
13953                 mark_jmp_point(env, w);
13954         }
13955
13956         if (insn_state[w] == 0) {
13957                 /* tree-edge */
13958                 insn_state[t] = DISCOVERED | e;
13959                 insn_state[w] = DISCOVERED;
13960                 if (env->cfg.cur_stack >= env->prog->len)
13961                         return -E2BIG;
13962                 insn_stack[env->cfg.cur_stack++] = w;
13963                 return KEEP_EXPLORING;
13964         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
13965                 if (loop_ok && env->bpf_capable)
13966                         return DONE_EXPLORING;
13967                 verbose_linfo(env, t, "%d: ", t);
13968                 verbose_linfo(env, w, "%d: ", w);
13969                 verbose(env, "back-edge from insn %d to %d\n", t, w);
13970                 return -EINVAL;
13971         } else if (insn_state[w] == EXPLORED) {
13972                 /* forward- or cross-edge */
13973                 insn_state[t] = DISCOVERED | e;
13974         } else {
13975                 verbose(env, "insn state internal bug\n");
13976                 return -EFAULT;
13977         }
13978         return DONE_EXPLORING;
13979 }
13980
13981 static int visit_func_call_insn(int t, struct bpf_insn *insns,
13982                                 struct bpf_verifier_env *env,
13983                                 bool visit_callee)
13984 {
13985         int ret;
13986
13987         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
13988         if (ret)
13989                 return ret;
13990
13991         mark_prune_point(env, t + 1);
13992         /* when we exit from subprog, we need to record non-linear history */
13993         mark_jmp_point(env, t + 1);
13994
13995         if (visit_callee) {
13996                 mark_prune_point(env, t);
13997                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
13998                                 /* It's ok to allow recursion from CFG point of
13999                                  * view. __check_func_call() will do the actual
14000                                  * check.
14001                                  */
14002                                 bpf_pseudo_func(insns + t));
14003         }
14004         return ret;
14005 }
14006
14007 /* Visits the instruction at index t and returns one of the following:
14008  *  < 0 - an error occurred
14009  *  DONE_EXPLORING - the instruction was fully explored
14010  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
14011  */
14012 static int visit_insn(int t, struct bpf_verifier_env *env)
14013 {
14014         struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14015         int ret;
14016
14017         if (bpf_pseudo_func(insn))
14018                 return visit_func_call_insn(t, insns, env, true);
14019
14020         /* All non-branch instructions have a single fall-through edge. */
14021         if (BPF_CLASS(insn->code) != BPF_JMP &&
14022             BPF_CLASS(insn->code) != BPF_JMP32)
14023                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
14024
14025         switch (BPF_OP(insn->code)) {
14026         case BPF_EXIT:
14027                 return DONE_EXPLORING;
14028
14029         case BPF_CALL:
14030                 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14031                         /* Mark this call insn as a prune point to trigger
14032                          * is_state_visited() check before call itself is
14033                          * processed by __check_func_call(). Otherwise new
14034                          * async state will be pushed for further exploration.
14035                          */
14036                         mark_prune_point(env, t);
14037                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14038                         struct bpf_kfunc_call_arg_meta meta;
14039
14040                         ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14041                         if (ret == 0 && is_iter_next_kfunc(&meta)) {
14042                                 mark_prune_point(env, t);
14043                                 /* Checking and saving state checkpoints at iter_next() call
14044                                  * is crucial for fast convergence of open-coded iterator loop
14045                                  * logic, so we need to force it. If we don't do that,
14046                                  * is_state_visited() might skip saving a checkpoint, causing
14047                                  * unnecessarily long sequence of not checkpointed
14048                                  * instructions and jumps, leading to exhaustion of jump
14049                                  * history buffer, and potentially other undesired outcomes.
14050                                  * It is expected that with correct open-coded iterators
14051                                  * convergence will happen quickly, so we don't run a risk of
14052                                  * exhausting memory.
14053                                  */
14054                                 mark_force_checkpoint(env, t);
14055                         }
14056                 }
14057                 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14058
14059         case BPF_JA:
14060                 if (BPF_SRC(insn->code) != BPF_K)
14061                         return -EINVAL;
14062
14063                 /* unconditional jump with single edge */
14064                 ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env,
14065                                 true);
14066                 if (ret)
14067                         return ret;
14068
14069                 mark_prune_point(env, t + insn->off + 1);
14070                 mark_jmp_point(env, t + insn->off + 1);
14071
14072                 return ret;
14073
14074         default:
14075                 /* conditional jump with two edges */
14076                 mark_prune_point(env, t);
14077
14078                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
14079                 if (ret)
14080                         return ret;
14081
14082                 return push_insn(t, t + insn->off + 1, BRANCH, env, true);
14083         }
14084 }
14085
14086 /* non-recursive depth-first-search to detect loops in BPF program
14087  * loop == back-edge in directed graph
14088  */
14089 static int check_cfg(struct bpf_verifier_env *env)
14090 {
14091         int insn_cnt = env->prog->len;
14092         int *insn_stack, *insn_state;
14093         int ret = 0;
14094         int i;
14095
14096         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14097         if (!insn_state)
14098                 return -ENOMEM;
14099
14100         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14101         if (!insn_stack) {
14102                 kvfree(insn_state);
14103                 return -ENOMEM;
14104         }
14105
14106         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14107         insn_stack[0] = 0; /* 0 is the first instruction */
14108         env->cfg.cur_stack = 1;
14109
14110         while (env->cfg.cur_stack > 0) {
14111                 int t = insn_stack[env->cfg.cur_stack - 1];
14112
14113                 ret = visit_insn(t, env);
14114                 switch (ret) {
14115                 case DONE_EXPLORING:
14116                         insn_state[t] = EXPLORED;
14117                         env->cfg.cur_stack--;
14118                         break;
14119                 case KEEP_EXPLORING:
14120                         break;
14121                 default:
14122                         if (ret > 0) {
14123                                 verbose(env, "visit_insn internal bug\n");
14124                                 ret = -EFAULT;
14125                         }
14126                         goto err_free;
14127                 }
14128         }
14129
14130         if (env->cfg.cur_stack < 0) {
14131                 verbose(env, "pop stack internal bug\n");
14132                 ret = -EFAULT;
14133                 goto err_free;
14134         }
14135
14136         for (i = 0; i < insn_cnt; i++) {
14137                 if (insn_state[i] != EXPLORED) {
14138                         verbose(env, "unreachable insn %d\n", i);
14139                         ret = -EINVAL;
14140                         goto err_free;
14141                 }
14142         }
14143         ret = 0; /* cfg looks good */
14144
14145 err_free:
14146         kvfree(insn_state);
14147         kvfree(insn_stack);
14148         env->cfg.insn_state = env->cfg.insn_stack = NULL;
14149         return ret;
14150 }
14151
14152 static int check_abnormal_return(struct bpf_verifier_env *env)
14153 {
14154         int i;
14155
14156         for (i = 1; i < env->subprog_cnt; i++) {
14157                 if (env->subprog_info[i].has_ld_abs) {
14158                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14159                         return -EINVAL;
14160                 }
14161                 if (env->subprog_info[i].has_tail_call) {
14162                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14163                         return -EINVAL;
14164                 }
14165         }
14166         return 0;
14167 }
14168
14169 /* The minimum supported BTF func info size */
14170 #define MIN_BPF_FUNCINFO_SIZE   8
14171 #define MAX_FUNCINFO_REC_SIZE   252
14172
14173 static int check_btf_func(struct bpf_verifier_env *env,
14174                           const union bpf_attr *attr,
14175                           bpfptr_t uattr)
14176 {
14177         const struct btf_type *type, *func_proto, *ret_type;
14178         u32 i, nfuncs, urec_size, min_size;
14179         u32 krec_size = sizeof(struct bpf_func_info);
14180         struct bpf_func_info *krecord;
14181         struct bpf_func_info_aux *info_aux = NULL;
14182         struct bpf_prog *prog;
14183         const struct btf *btf;
14184         bpfptr_t urecord;
14185         u32 prev_offset = 0;
14186         bool scalar_return;
14187         int ret = -ENOMEM;
14188
14189         nfuncs = attr->func_info_cnt;
14190         if (!nfuncs) {
14191                 if (check_abnormal_return(env))
14192                         return -EINVAL;
14193                 return 0;
14194         }
14195
14196         if (nfuncs != env->subprog_cnt) {
14197                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
14198                 return -EINVAL;
14199         }
14200
14201         urec_size = attr->func_info_rec_size;
14202         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
14203             urec_size > MAX_FUNCINFO_REC_SIZE ||
14204             urec_size % sizeof(u32)) {
14205                 verbose(env, "invalid func info rec size %u\n", urec_size);
14206                 return -EINVAL;
14207         }
14208
14209         prog = env->prog;
14210         btf = prog->aux->btf;
14211
14212         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
14213         min_size = min_t(u32, krec_size, urec_size);
14214
14215         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
14216         if (!krecord)
14217                 return -ENOMEM;
14218         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
14219         if (!info_aux)
14220                 goto err_free;
14221
14222         for (i = 0; i < nfuncs; i++) {
14223                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
14224                 if (ret) {
14225                         if (ret == -E2BIG) {
14226                                 verbose(env, "nonzero tailing record in func info");
14227                                 /* set the size kernel expects so loader can zero
14228                                  * out the rest of the record.
14229                                  */
14230                                 if (copy_to_bpfptr_offset(uattr,
14231                                                           offsetof(union bpf_attr, func_info_rec_size),
14232                                                           &min_size, sizeof(min_size)))
14233                                         ret = -EFAULT;
14234                         }
14235                         goto err_free;
14236                 }
14237
14238                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
14239                         ret = -EFAULT;
14240                         goto err_free;
14241                 }
14242
14243                 /* check insn_off */
14244                 ret = -EINVAL;
14245                 if (i == 0) {
14246                         if (krecord[i].insn_off) {
14247                                 verbose(env,
14248                                         "nonzero insn_off %u for the first func info record",
14249                                         krecord[i].insn_off);
14250                                 goto err_free;
14251                         }
14252                 } else if (krecord[i].insn_off <= prev_offset) {
14253                         verbose(env,
14254                                 "same or smaller insn offset (%u) than previous func info record (%u)",
14255                                 krecord[i].insn_off, prev_offset);
14256                         goto err_free;
14257                 }
14258
14259                 if (env->subprog_info[i].start != krecord[i].insn_off) {
14260                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
14261                         goto err_free;
14262                 }
14263
14264                 /* check type_id */
14265                 type = btf_type_by_id(btf, krecord[i].type_id);
14266                 if (!type || !btf_type_is_func(type)) {
14267                         verbose(env, "invalid type id %d in func info",
14268                                 krecord[i].type_id);
14269                         goto err_free;
14270                 }
14271                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
14272
14273                 func_proto = btf_type_by_id(btf, type->type);
14274                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
14275                         /* btf_func_check() already verified it during BTF load */
14276                         goto err_free;
14277                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
14278                 scalar_return =
14279                         btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
14280                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
14281                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
14282                         goto err_free;
14283                 }
14284                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
14285                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
14286                         goto err_free;
14287                 }
14288
14289                 prev_offset = krecord[i].insn_off;
14290                 bpfptr_add(&urecord, urec_size);
14291         }
14292
14293         prog->aux->func_info = krecord;
14294         prog->aux->func_info_cnt = nfuncs;
14295         prog->aux->func_info_aux = info_aux;
14296         return 0;
14297
14298 err_free:
14299         kvfree(krecord);
14300         kfree(info_aux);
14301         return ret;
14302 }
14303
14304 static void adjust_btf_func(struct bpf_verifier_env *env)
14305 {
14306         struct bpf_prog_aux *aux = env->prog->aux;
14307         int i;
14308
14309         if (!aux->func_info)
14310                 return;
14311
14312         for (i = 0; i < env->subprog_cnt; i++)
14313                 aux->func_info[i].insn_off = env->subprog_info[i].start;
14314 }
14315
14316 #define MIN_BPF_LINEINFO_SIZE   offsetofend(struct bpf_line_info, line_col)
14317 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
14318
14319 static int check_btf_line(struct bpf_verifier_env *env,
14320                           const union bpf_attr *attr,
14321                           bpfptr_t uattr)
14322 {
14323         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
14324         struct bpf_subprog_info *sub;
14325         struct bpf_line_info *linfo;
14326         struct bpf_prog *prog;
14327         const struct btf *btf;
14328         bpfptr_t ulinfo;
14329         int err;
14330
14331         nr_linfo = attr->line_info_cnt;
14332         if (!nr_linfo)
14333                 return 0;
14334         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
14335                 return -EINVAL;
14336
14337         rec_size = attr->line_info_rec_size;
14338         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
14339             rec_size > MAX_LINEINFO_REC_SIZE ||
14340             rec_size & (sizeof(u32) - 1))
14341                 return -EINVAL;
14342
14343         /* Need to zero it in case the userspace may
14344          * pass in a smaller bpf_line_info object.
14345          */
14346         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
14347                          GFP_KERNEL | __GFP_NOWARN);
14348         if (!linfo)
14349                 return -ENOMEM;
14350
14351         prog = env->prog;
14352         btf = prog->aux->btf;
14353
14354         s = 0;
14355         sub = env->subprog_info;
14356         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
14357         expected_size = sizeof(struct bpf_line_info);
14358         ncopy = min_t(u32, expected_size, rec_size);
14359         for (i = 0; i < nr_linfo; i++) {
14360                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
14361                 if (err) {
14362                         if (err == -E2BIG) {
14363                                 verbose(env, "nonzero tailing record in line_info");
14364                                 if (copy_to_bpfptr_offset(uattr,
14365                                                           offsetof(union bpf_attr, line_info_rec_size),
14366                                                           &expected_size, sizeof(expected_size)))
14367                                         err = -EFAULT;
14368                         }
14369                         goto err_free;
14370                 }
14371
14372                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
14373                         err = -EFAULT;
14374                         goto err_free;
14375                 }
14376
14377                 /*
14378                  * Check insn_off to ensure
14379                  * 1) strictly increasing AND
14380                  * 2) bounded by prog->len
14381                  *
14382                  * The linfo[0].insn_off == 0 check logically falls into
14383                  * the later "missing bpf_line_info for func..." case
14384                  * because the first linfo[0].insn_off must be the
14385                  * first sub also and the first sub must have
14386                  * subprog_info[0].start == 0.
14387                  */
14388                 if ((i && linfo[i].insn_off <= prev_offset) ||
14389                     linfo[i].insn_off >= prog->len) {
14390                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
14391                                 i, linfo[i].insn_off, prev_offset,
14392                                 prog->len);
14393                         err = -EINVAL;
14394                         goto err_free;
14395                 }
14396
14397                 if (!prog->insnsi[linfo[i].insn_off].code) {
14398                         verbose(env,
14399                                 "Invalid insn code at line_info[%u].insn_off\n",
14400                                 i);
14401                         err = -EINVAL;
14402                         goto err_free;
14403                 }
14404
14405                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
14406                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
14407                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
14408                         err = -EINVAL;
14409                         goto err_free;
14410                 }
14411
14412                 if (s != env->subprog_cnt) {
14413                         if (linfo[i].insn_off == sub[s].start) {
14414                                 sub[s].linfo_idx = i;
14415                                 s++;
14416                         } else if (sub[s].start < linfo[i].insn_off) {
14417                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
14418                                 err = -EINVAL;
14419                                 goto err_free;
14420                         }
14421                 }
14422
14423                 prev_offset = linfo[i].insn_off;
14424                 bpfptr_add(&ulinfo, rec_size);
14425         }
14426
14427         if (s != env->subprog_cnt) {
14428                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
14429                         env->subprog_cnt - s, s);
14430                 err = -EINVAL;
14431                 goto err_free;
14432         }
14433
14434         prog->aux->linfo = linfo;
14435         prog->aux->nr_linfo = nr_linfo;
14436
14437         return 0;
14438
14439 err_free:
14440         kvfree(linfo);
14441         return err;
14442 }
14443
14444 #define MIN_CORE_RELO_SIZE      sizeof(struct bpf_core_relo)
14445 #define MAX_CORE_RELO_SIZE      MAX_FUNCINFO_REC_SIZE
14446
14447 static int check_core_relo(struct bpf_verifier_env *env,
14448                            const union bpf_attr *attr,
14449                            bpfptr_t uattr)
14450 {
14451         u32 i, nr_core_relo, ncopy, expected_size, rec_size;
14452         struct bpf_core_relo core_relo = {};
14453         struct bpf_prog *prog = env->prog;
14454         const struct btf *btf = prog->aux->btf;
14455         struct bpf_core_ctx ctx = {
14456                 .log = &env->log,
14457                 .btf = btf,
14458         };
14459         bpfptr_t u_core_relo;
14460         int err;
14461
14462         nr_core_relo = attr->core_relo_cnt;
14463         if (!nr_core_relo)
14464                 return 0;
14465         if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
14466                 return -EINVAL;
14467
14468         rec_size = attr->core_relo_rec_size;
14469         if (rec_size < MIN_CORE_RELO_SIZE ||
14470             rec_size > MAX_CORE_RELO_SIZE ||
14471             rec_size % sizeof(u32))
14472                 return -EINVAL;
14473
14474         u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
14475         expected_size = sizeof(struct bpf_core_relo);
14476         ncopy = min_t(u32, expected_size, rec_size);
14477
14478         /* Unlike func_info and line_info, copy and apply each CO-RE
14479          * relocation record one at a time.
14480          */
14481         for (i = 0; i < nr_core_relo; i++) {
14482                 /* future proofing when sizeof(bpf_core_relo) changes */
14483                 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
14484                 if (err) {
14485                         if (err == -E2BIG) {
14486                                 verbose(env, "nonzero tailing record in core_relo");
14487                                 if (copy_to_bpfptr_offset(uattr,
14488                                                           offsetof(union bpf_attr, core_relo_rec_size),
14489                                                           &expected_size, sizeof(expected_size)))
14490                                         err = -EFAULT;
14491                         }
14492                         break;
14493                 }
14494
14495                 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
14496                         err = -EFAULT;
14497                         break;
14498                 }
14499
14500                 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
14501                         verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
14502                                 i, core_relo.insn_off, prog->len);
14503                         err = -EINVAL;
14504                         break;
14505                 }
14506
14507                 err = bpf_core_apply(&ctx, &core_relo, i,
14508                                      &prog->insnsi[core_relo.insn_off / 8]);
14509                 if (err)
14510                         break;
14511                 bpfptr_add(&u_core_relo, rec_size);
14512         }
14513         return err;
14514 }
14515
14516 static int check_btf_info(struct bpf_verifier_env *env,
14517                           const union bpf_attr *attr,
14518                           bpfptr_t uattr)
14519 {
14520         struct btf *btf;
14521         int err;
14522
14523         if (!attr->func_info_cnt && !attr->line_info_cnt) {
14524                 if (check_abnormal_return(env))
14525                         return -EINVAL;
14526                 return 0;
14527         }
14528
14529         btf = btf_get_by_fd(attr->prog_btf_fd);
14530         if (IS_ERR(btf))
14531                 return PTR_ERR(btf);
14532         if (btf_is_kernel(btf)) {
14533                 btf_put(btf);
14534                 return -EACCES;
14535         }
14536         env->prog->aux->btf = btf;
14537
14538         err = check_btf_func(env, attr, uattr);
14539         if (err)
14540                 return err;
14541
14542         err = check_btf_line(env, attr, uattr);
14543         if (err)
14544                 return err;
14545
14546         err = check_core_relo(env, attr, uattr);
14547         if (err)
14548                 return err;
14549
14550         return 0;
14551 }
14552
14553 /* check %cur's range satisfies %old's */
14554 static bool range_within(struct bpf_reg_state *old,
14555                          struct bpf_reg_state *cur)
14556 {
14557         return old->umin_value <= cur->umin_value &&
14558                old->umax_value >= cur->umax_value &&
14559                old->smin_value <= cur->smin_value &&
14560                old->smax_value >= cur->smax_value &&
14561                old->u32_min_value <= cur->u32_min_value &&
14562                old->u32_max_value >= cur->u32_max_value &&
14563                old->s32_min_value <= cur->s32_min_value &&
14564                old->s32_max_value >= cur->s32_max_value;
14565 }
14566
14567 /* If in the old state two registers had the same id, then they need to have
14568  * the same id in the new state as well.  But that id could be different from
14569  * the old state, so we need to track the mapping from old to new ids.
14570  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
14571  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
14572  * regs with a different old id could still have new id 9, we don't care about
14573  * that.
14574  * So we look through our idmap to see if this old id has been seen before.  If
14575  * so, we require the new id to match; otherwise, we add the id pair to the map.
14576  */
14577 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
14578 {
14579         unsigned int i;
14580
14581         /* either both IDs should be set or both should be zero */
14582         if (!!old_id != !!cur_id)
14583                 return false;
14584
14585         if (old_id == 0) /* cur_id == 0 as well */
14586                 return true;
14587
14588         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
14589                 if (!idmap[i].old) {
14590                         /* Reached an empty slot; haven't seen this id before */
14591                         idmap[i].old = old_id;
14592                         idmap[i].cur = cur_id;
14593                         return true;
14594                 }
14595                 if (idmap[i].old == old_id)
14596                         return idmap[i].cur == cur_id;
14597         }
14598         /* We ran out of idmap slots, which should be impossible */
14599         WARN_ON_ONCE(1);
14600         return false;
14601 }
14602
14603 static void clean_func_state(struct bpf_verifier_env *env,
14604                              struct bpf_func_state *st)
14605 {
14606         enum bpf_reg_liveness live;
14607         int i, j;
14608
14609         for (i = 0; i < BPF_REG_FP; i++) {
14610                 live = st->regs[i].live;
14611                 /* liveness must not touch this register anymore */
14612                 st->regs[i].live |= REG_LIVE_DONE;
14613                 if (!(live & REG_LIVE_READ))
14614                         /* since the register is unused, clear its state
14615                          * to make further comparison simpler
14616                          */
14617                         __mark_reg_not_init(env, &st->regs[i]);
14618         }
14619
14620         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
14621                 live = st->stack[i].spilled_ptr.live;
14622                 /* liveness must not touch this stack slot anymore */
14623                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
14624                 if (!(live & REG_LIVE_READ)) {
14625                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
14626                         for (j = 0; j < BPF_REG_SIZE; j++)
14627                                 st->stack[i].slot_type[j] = STACK_INVALID;
14628                 }
14629         }
14630 }
14631
14632 static void clean_verifier_state(struct bpf_verifier_env *env,
14633                                  struct bpf_verifier_state *st)
14634 {
14635         int i;
14636
14637         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
14638                 /* all regs in this state in all frames were already marked */
14639                 return;
14640
14641         for (i = 0; i <= st->curframe; i++)
14642                 clean_func_state(env, st->frame[i]);
14643 }
14644
14645 /* the parentage chains form a tree.
14646  * the verifier states are added to state lists at given insn and
14647  * pushed into state stack for future exploration.
14648  * when the verifier reaches bpf_exit insn some of the verifer states
14649  * stored in the state lists have their final liveness state already,
14650  * but a lot of states will get revised from liveness point of view when
14651  * the verifier explores other branches.
14652  * Example:
14653  * 1: r0 = 1
14654  * 2: if r1 == 100 goto pc+1
14655  * 3: r0 = 2
14656  * 4: exit
14657  * when the verifier reaches exit insn the register r0 in the state list of
14658  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
14659  * of insn 2 and goes exploring further. At the insn 4 it will walk the
14660  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
14661  *
14662  * Since the verifier pushes the branch states as it sees them while exploring
14663  * the program the condition of walking the branch instruction for the second
14664  * time means that all states below this branch were already explored and
14665  * their final liveness marks are already propagated.
14666  * Hence when the verifier completes the search of state list in is_state_visited()
14667  * we can call this clean_live_states() function to mark all liveness states
14668  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
14669  * will not be used.
14670  * This function also clears the registers and stack for states that !READ
14671  * to simplify state merging.
14672  *
14673  * Important note here that walking the same branch instruction in the callee
14674  * doesn't meant that the states are DONE. The verifier has to compare
14675  * the callsites
14676  */
14677 static void clean_live_states(struct bpf_verifier_env *env, int insn,
14678                               struct bpf_verifier_state *cur)
14679 {
14680         struct bpf_verifier_state_list *sl;
14681         int i;
14682
14683         sl = *explored_state(env, insn);
14684         while (sl) {
14685                 if (sl->state.branches)
14686                         goto next;
14687                 if (sl->state.insn_idx != insn ||
14688                     sl->state.curframe != cur->curframe)
14689                         goto next;
14690                 for (i = 0; i <= cur->curframe; i++)
14691                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
14692                                 goto next;
14693                 clean_verifier_state(env, &sl->state);
14694 next:
14695                 sl = sl->next;
14696         }
14697 }
14698
14699 static bool regs_exact(const struct bpf_reg_state *rold,
14700                        const struct bpf_reg_state *rcur,
14701                        struct bpf_id_pair *idmap)
14702 {
14703         return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 
14704                check_ids(rold->id, rcur->id, idmap) &&
14705                check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
14706 }
14707
14708 /* Returns true if (rold safe implies rcur safe) */
14709 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
14710                     struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
14711 {
14712         if (!(rold->live & REG_LIVE_READ))
14713                 /* explored state didn't use this */
14714                 return true;
14715         if (rold->type == NOT_INIT)
14716                 /* explored state can't have used this */
14717                 return true;
14718         if (rcur->type == NOT_INIT)
14719                 return false;
14720
14721         /* Enforce that register types have to match exactly, including their
14722          * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
14723          * rule.
14724          *
14725          * One can make a point that using a pointer register as unbounded
14726          * SCALAR would be technically acceptable, but this could lead to
14727          * pointer leaks because scalars are allowed to leak while pointers
14728          * are not. We could make this safe in special cases if root is
14729          * calling us, but it's probably not worth the hassle.
14730          *
14731          * Also, register types that are *not* MAYBE_NULL could technically be
14732          * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
14733          * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
14734          * to the same map).
14735          * However, if the old MAYBE_NULL register then got NULL checked,
14736          * doing so could have affected others with the same id, and we can't
14737          * check for that because we lost the id when we converted to
14738          * a non-MAYBE_NULL variant.
14739          * So, as a general rule we don't allow mixing MAYBE_NULL and
14740          * non-MAYBE_NULL registers as well.
14741          */
14742         if (rold->type != rcur->type)
14743                 return false;
14744
14745         switch (base_type(rold->type)) {
14746         case SCALAR_VALUE:
14747                 if (regs_exact(rold, rcur, idmap))
14748                         return true;
14749                 if (env->explore_alu_limits)
14750                         return false;
14751                 if (!rold->precise)
14752                         return true;
14753                 /* new val must satisfy old val knowledge */
14754                 return range_within(rold, rcur) &&
14755                        tnum_in(rold->var_off, rcur->var_off);
14756         case PTR_TO_MAP_KEY:
14757         case PTR_TO_MAP_VALUE:
14758         case PTR_TO_MEM:
14759         case PTR_TO_BUF:
14760         case PTR_TO_TP_BUFFER:
14761                 /* If the new min/max/var_off satisfy the old ones and
14762                  * everything else matches, we are OK.
14763                  */
14764                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
14765                        range_within(rold, rcur) &&
14766                        tnum_in(rold->var_off, rcur->var_off) &&
14767                        check_ids(rold->id, rcur->id, idmap) &&
14768                        check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
14769         case PTR_TO_PACKET_META:
14770         case PTR_TO_PACKET:
14771                 /* We must have at least as much range as the old ptr
14772                  * did, so that any accesses which were safe before are
14773                  * still safe.  This is true even if old range < old off,
14774                  * since someone could have accessed through (ptr - k), or
14775                  * even done ptr -= k in a register, to get a safe access.
14776                  */
14777                 if (rold->range > rcur->range)
14778                         return false;
14779                 /* If the offsets don't match, we can't trust our alignment;
14780                  * nor can we be sure that we won't fall out of range.
14781                  */
14782                 if (rold->off != rcur->off)
14783                         return false;
14784                 /* id relations must be preserved */
14785                 if (!check_ids(rold->id, rcur->id, idmap))
14786                         return false;
14787                 /* new val must satisfy old val knowledge */
14788                 return range_within(rold, rcur) &&
14789                        tnum_in(rold->var_off, rcur->var_off);
14790         case PTR_TO_STACK:
14791                 /* two stack pointers are equal only if they're pointing to
14792                  * the same stack frame, since fp-8 in foo != fp-8 in bar
14793                  */
14794                 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
14795         default:
14796                 return regs_exact(rold, rcur, idmap);
14797         }
14798 }
14799
14800 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
14801                       struct bpf_func_state *cur, struct bpf_id_pair *idmap)
14802 {
14803         int i, spi;
14804
14805         /* walk slots of the explored stack and ignore any additional
14806          * slots in the current stack, since explored(safe) state
14807          * didn't use them
14808          */
14809         for (i = 0; i < old->allocated_stack; i++) {
14810                 struct bpf_reg_state *old_reg, *cur_reg;
14811
14812                 spi = i / BPF_REG_SIZE;
14813
14814                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
14815                         i += BPF_REG_SIZE - 1;
14816                         /* explored state didn't use this */
14817                         continue;
14818                 }
14819
14820                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
14821                         continue;
14822
14823                 if (env->allow_uninit_stack &&
14824                     old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
14825                         continue;
14826
14827                 /* explored stack has more populated slots than current stack
14828                  * and these slots were used
14829                  */
14830                 if (i >= cur->allocated_stack)
14831                         return false;
14832
14833                 /* if old state was safe with misc data in the stack
14834                  * it will be safe with zero-initialized stack.
14835                  * The opposite is not true
14836                  */
14837                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
14838                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
14839                         continue;
14840                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
14841                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
14842                         /* Ex: old explored (safe) state has STACK_SPILL in
14843                          * this stack slot, but current has STACK_MISC ->
14844                          * this verifier states are not equivalent,
14845                          * return false to continue verification of this path
14846                          */
14847                         return false;
14848                 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
14849                         continue;
14850                 /* Both old and cur are having same slot_type */
14851                 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
14852                 case STACK_SPILL:
14853                         /* when explored and current stack slot are both storing
14854                          * spilled registers, check that stored pointers types
14855                          * are the same as well.
14856                          * Ex: explored safe path could have stored
14857                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
14858                          * but current path has stored:
14859                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
14860                          * such verifier states are not equivalent.
14861                          * return false to continue verification of this path
14862                          */
14863                         if (!regsafe(env, &old->stack[spi].spilled_ptr,
14864                                      &cur->stack[spi].spilled_ptr, idmap))
14865                                 return false;
14866                         break;
14867                 case STACK_DYNPTR:
14868                         old_reg = &old->stack[spi].spilled_ptr;
14869                         cur_reg = &cur->stack[spi].spilled_ptr;
14870                         if (old_reg->dynptr.type != cur_reg->dynptr.type ||
14871                             old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
14872                             !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
14873                                 return false;
14874                         break;
14875                 case STACK_ITER:
14876                         old_reg = &old->stack[spi].spilled_ptr;
14877                         cur_reg = &cur->stack[spi].spilled_ptr;
14878                         /* iter.depth is not compared between states as it
14879                          * doesn't matter for correctness and would otherwise
14880                          * prevent convergence; we maintain it only to prevent
14881                          * infinite loop check triggering, see
14882                          * iter_active_depths_differ()
14883                          */
14884                         if (old_reg->iter.btf != cur_reg->iter.btf ||
14885                             old_reg->iter.btf_id != cur_reg->iter.btf_id ||
14886                             old_reg->iter.state != cur_reg->iter.state ||
14887                             /* ignore {old_reg,cur_reg}->iter.depth, see above */
14888                             !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
14889                                 return false;
14890                         break;
14891                 case STACK_MISC:
14892                 case STACK_ZERO:
14893                 case STACK_INVALID:
14894                         continue;
14895                 /* Ensure that new unhandled slot types return false by default */
14896                 default:
14897                         return false;
14898                 }
14899         }
14900         return true;
14901 }
14902
14903 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
14904                     struct bpf_id_pair *idmap)
14905 {
14906         int i;
14907
14908         if (old->acquired_refs != cur->acquired_refs)
14909                 return false;
14910
14911         for (i = 0; i < old->acquired_refs; i++) {
14912                 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
14913                         return false;
14914         }
14915
14916         return true;
14917 }
14918
14919 /* compare two verifier states
14920  *
14921  * all states stored in state_list are known to be valid, since
14922  * verifier reached 'bpf_exit' instruction through them
14923  *
14924  * this function is called when verifier exploring different branches of
14925  * execution popped from the state stack. If it sees an old state that has
14926  * more strict register state and more strict stack state then this execution
14927  * branch doesn't need to be explored further, since verifier already
14928  * concluded that more strict state leads to valid finish.
14929  *
14930  * Therefore two states are equivalent if register state is more conservative
14931  * and explored stack state is more conservative than the current one.
14932  * Example:
14933  *       explored                   current
14934  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
14935  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
14936  *
14937  * In other words if current stack state (one being explored) has more
14938  * valid slots than old one that already passed validation, it means
14939  * the verifier can stop exploring and conclude that current state is valid too
14940  *
14941  * Similarly with registers. If explored state has register type as invalid
14942  * whereas register type in current state is meaningful, it means that
14943  * the current state will reach 'bpf_exit' instruction safely
14944  */
14945 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
14946                               struct bpf_func_state *cur)
14947 {
14948         int i;
14949
14950         for (i = 0; i < MAX_BPF_REG; i++)
14951                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
14952                              env->idmap_scratch))
14953                         return false;
14954
14955         if (!stacksafe(env, old, cur, env->idmap_scratch))
14956                 return false;
14957
14958         if (!refsafe(old, cur, env->idmap_scratch))
14959                 return false;
14960
14961         return true;
14962 }
14963
14964 static bool states_equal(struct bpf_verifier_env *env,
14965                          struct bpf_verifier_state *old,
14966                          struct bpf_verifier_state *cur)
14967 {
14968         int i;
14969
14970         if (old->curframe != cur->curframe)
14971                 return false;
14972
14973         memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
14974
14975         /* Verification state from speculative execution simulation
14976          * must never prune a non-speculative execution one.
14977          */
14978         if (old->speculative && !cur->speculative)
14979                 return false;
14980
14981         if (old->active_lock.ptr != cur->active_lock.ptr)
14982                 return false;
14983
14984         /* Old and cur active_lock's have to be either both present
14985          * or both absent.
14986          */
14987         if (!!old->active_lock.id != !!cur->active_lock.id)
14988                 return false;
14989
14990         if (old->active_lock.id &&
14991             !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch))
14992                 return false;
14993
14994         if (old->active_rcu_lock != cur->active_rcu_lock)
14995                 return false;
14996
14997         /* for states to be equal callsites have to be the same
14998          * and all frame states need to be equivalent
14999          */
15000         for (i = 0; i <= old->curframe; i++) {
15001                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
15002                         return false;
15003                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15004                         return false;
15005         }
15006         return true;
15007 }
15008
15009 /* Return 0 if no propagation happened. Return negative error code if error
15010  * happened. Otherwise, return the propagated bit.
15011  */
15012 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15013                                   struct bpf_reg_state *reg,
15014                                   struct bpf_reg_state *parent_reg)
15015 {
15016         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15017         u8 flag = reg->live & REG_LIVE_READ;
15018         int err;
15019
15020         /* When comes here, read flags of PARENT_REG or REG could be any of
15021          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15022          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15023          */
15024         if (parent_flag == REG_LIVE_READ64 ||
15025             /* Or if there is no read flag from REG. */
15026             !flag ||
15027             /* Or if the read flag from REG is the same as PARENT_REG. */
15028             parent_flag == flag)
15029                 return 0;
15030
15031         err = mark_reg_read(env, reg, parent_reg, flag);
15032         if (err)
15033                 return err;
15034
15035         return flag;
15036 }
15037
15038 /* A write screens off any subsequent reads; but write marks come from the
15039  * straight-line code between a state and its parent.  When we arrive at an
15040  * equivalent state (jump target or such) we didn't arrive by the straight-line
15041  * code, so read marks in the state must propagate to the parent regardless
15042  * of the state's write marks. That's what 'parent == state->parent' comparison
15043  * in mark_reg_read() is for.
15044  */
15045 static int propagate_liveness(struct bpf_verifier_env *env,
15046                               const struct bpf_verifier_state *vstate,
15047                               struct bpf_verifier_state *vparent)
15048 {
15049         struct bpf_reg_state *state_reg, *parent_reg;
15050         struct bpf_func_state *state, *parent;
15051         int i, frame, err = 0;
15052
15053         if (vparent->curframe != vstate->curframe) {
15054                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
15055                      vparent->curframe, vstate->curframe);
15056                 return -EFAULT;
15057         }
15058         /* Propagate read liveness of registers... */
15059         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15060         for (frame = 0; frame <= vstate->curframe; frame++) {
15061                 parent = vparent->frame[frame];
15062                 state = vstate->frame[frame];
15063                 parent_reg = parent->regs;
15064                 state_reg = state->regs;
15065                 /* We don't need to worry about FP liveness, it's read-only */
15066                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15067                         err = propagate_liveness_reg(env, &state_reg[i],
15068                                                      &parent_reg[i]);
15069                         if (err < 0)
15070                                 return err;
15071                         if (err == REG_LIVE_READ64)
15072                                 mark_insn_zext(env, &parent_reg[i]);
15073                 }
15074
15075                 /* Propagate stack slots. */
15076                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15077                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15078                         parent_reg = &parent->stack[i].spilled_ptr;
15079                         state_reg = &state->stack[i].spilled_ptr;
15080                         err = propagate_liveness_reg(env, state_reg,
15081                                                      parent_reg);
15082                         if (err < 0)
15083                                 return err;
15084                 }
15085         }
15086         return 0;
15087 }
15088
15089 /* find precise scalars in the previous equivalent state and
15090  * propagate them into the current state
15091  */
15092 static int propagate_precision(struct bpf_verifier_env *env,
15093                                const struct bpf_verifier_state *old)
15094 {
15095         struct bpf_reg_state *state_reg;
15096         struct bpf_func_state *state;
15097         int i, err = 0, fr;
15098
15099         for (fr = old->curframe; fr >= 0; fr--) {
15100                 state = old->frame[fr];
15101                 state_reg = state->regs;
15102                 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15103                         if (state_reg->type != SCALAR_VALUE ||
15104                             !state_reg->precise ||
15105                             !(state_reg->live & REG_LIVE_READ))
15106                                 continue;
15107                         if (env->log.level & BPF_LOG_LEVEL2)
15108                                 verbose(env, "frame %d: propagating r%d\n", fr, i);
15109                         err = mark_chain_precision_frame(env, fr, i);
15110                         if (err < 0)
15111                                 return err;
15112                 }
15113
15114                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15115                         if (!is_spilled_reg(&state->stack[i]))
15116                                 continue;
15117                         state_reg = &state->stack[i].spilled_ptr;
15118                         if (state_reg->type != SCALAR_VALUE ||
15119                             !state_reg->precise ||
15120                             !(state_reg->live & REG_LIVE_READ))
15121                                 continue;
15122                         if (env->log.level & BPF_LOG_LEVEL2)
15123                                 verbose(env, "frame %d: propagating fp%d\n",
15124                                         fr, (-i - 1) * BPF_REG_SIZE);
15125                         err = mark_chain_precision_stack_frame(env, fr, i);
15126                         if (err < 0)
15127                                 return err;
15128                 }
15129         }
15130         return 0;
15131 }
15132
15133 static bool states_maybe_looping(struct bpf_verifier_state *old,
15134                                  struct bpf_verifier_state *cur)
15135 {
15136         struct bpf_func_state *fold, *fcur;
15137         int i, fr = cur->curframe;
15138
15139         if (old->curframe != fr)
15140                 return false;
15141
15142         fold = old->frame[fr];
15143         fcur = cur->frame[fr];
15144         for (i = 0; i < MAX_BPF_REG; i++)
15145                 if (memcmp(&fold->regs[i], &fcur->regs[i],
15146                            offsetof(struct bpf_reg_state, parent)))
15147                         return false;
15148         return true;
15149 }
15150
15151 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
15152 {
15153         return env->insn_aux_data[insn_idx].is_iter_next;
15154 }
15155
15156 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
15157  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
15158  * states to match, which otherwise would look like an infinite loop. So while
15159  * iter_next() calls are taken care of, we still need to be careful and
15160  * prevent erroneous and too eager declaration of "ininite loop", when
15161  * iterators are involved.
15162  *
15163  * Here's a situation in pseudo-BPF assembly form:
15164  *
15165  *   0: again:                          ; set up iter_next() call args
15166  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
15167  *   2:   call bpf_iter_num_next        ; this is iter_next() call
15168  *   3:   if r0 == 0 goto done
15169  *   4:   ... something useful here ...
15170  *   5:   goto again                    ; another iteration
15171  *   6: done:
15172  *   7:   r1 = &it
15173  *   8:   call bpf_iter_num_destroy     ; clean up iter state
15174  *   9:   exit
15175  *
15176  * This is a typical loop. Let's assume that we have a prune point at 1:,
15177  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
15178  * again`, assuming other heuristics don't get in a way).
15179  *
15180  * When we first time come to 1:, let's say we have some state X. We proceed
15181  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
15182  * Now we come back to validate that forked ACTIVE state. We proceed through
15183  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
15184  * are converging. But the problem is that we don't know that yet, as this
15185  * convergence has to happen at iter_next() call site only. So if nothing is
15186  * done, at 1: verifier will use bounded loop logic and declare infinite
15187  * looping (and would be *technically* correct, if not for iterator's
15188  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
15189  * don't want that. So what we do in process_iter_next_call() when we go on
15190  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
15191  * a different iteration. So when we suspect an infinite loop, we additionally
15192  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
15193  * pretend we are not looping and wait for next iter_next() call.
15194  *
15195  * This only applies to ACTIVE state. In DRAINED state we don't expect to
15196  * loop, because that would actually mean infinite loop, as DRAINED state is
15197  * "sticky", and so we'll keep returning into the same instruction with the
15198  * same state (at least in one of possible code paths).
15199  *
15200  * This approach allows to keep infinite loop heuristic even in the face of
15201  * active iterator. E.g., C snippet below is and will be detected as
15202  * inifintely looping:
15203  *
15204  *   struct bpf_iter_num it;
15205  *   int *p, x;
15206  *
15207  *   bpf_iter_num_new(&it, 0, 10);
15208  *   while ((p = bpf_iter_num_next(&t))) {
15209  *       x = p;
15210  *       while (x--) {} // <<-- infinite loop here
15211  *   }
15212  *
15213  */
15214 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
15215 {
15216         struct bpf_reg_state *slot, *cur_slot;
15217         struct bpf_func_state *state;
15218         int i, fr;
15219
15220         for (fr = old->curframe; fr >= 0; fr--) {
15221                 state = old->frame[fr];
15222                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15223                         if (state->stack[i].slot_type[0] != STACK_ITER)
15224                                 continue;
15225
15226                         slot = &state->stack[i].spilled_ptr;
15227                         if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
15228                                 continue;
15229
15230                         cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
15231                         if (cur_slot->iter.depth != slot->iter.depth)
15232                                 return true;
15233                 }
15234         }
15235         return false;
15236 }
15237
15238 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
15239 {
15240         struct bpf_verifier_state_list *new_sl;
15241         struct bpf_verifier_state_list *sl, **pprev;
15242         struct bpf_verifier_state *cur = env->cur_state, *new;
15243         int i, j, err, states_cnt = 0;
15244         bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
15245         bool add_new_state = force_new_state;
15246
15247         /* bpf progs typically have pruning point every 4 instructions
15248          * http://vger.kernel.org/bpfconf2019.html#session-1
15249          * Do not add new state for future pruning if the verifier hasn't seen
15250          * at least 2 jumps and at least 8 instructions.
15251          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
15252          * In tests that amounts to up to 50% reduction into total verifier
15253          * memory consumption and 20% verifier time speedup.
15254          */
15255         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
15256             env->insn_processed - env->prev_insn_processed >= 8)
15257                 add_new_state = true;
15258
15259         pprev = explored_state(env, insn_idx);
15260         sl = *pprev;
15261
15262         clean_live_states(env, insn_idx, cur);
15263
15264         while (sl) {
15265                 states_cnt++;
15266                 if (sl->state.insn_idx != insn_idx)
15267                         goto next;
15268
15269                 if (sl->state.branches) {
15270                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
15271
15272                         if (frame->in_async_callback_fn &&
15273                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
15274                                 /* Different async_entry_cnt means that the verifier is
15275                                  * processing another entry into async callback.
15276                                  * Seeing the same state is not an indication of infinite
15277                                  * loop or infinite recursion.
15278                                  * But finding the same state doesn't mean that it's safe
15279                                  * to stop processing the current state. The previous state
15280                                  * hasn't yet reached bpf_exit, since state.branches > 0.
15281                                  * Checking in_async_callback_fn alone is not enough either.
15282                                  * Since the verifier still needs to catch infinite loops
15283                                  * inside async callbacks.
15284                                  */
15285                                 goto skip_inf_loop_check;
15286                         }
15287                         /* BPF open-coded iterators loop detection is special.
15288                          * states_maybe_looping() logic is too simplistic in detecting
15289                          * states that *might* be equivalent, because it doesn't know
15290                          * about ID remapping, so don't even perform it.
15291                          * See process_iter_next_call() and iter_active_depths_differ()
15292                          * for overview of the logic. When current and one of parent
15293                          * states are detected as equivalent, it's a good thing: we prove
15294                          * convergence and can stop simulating further iterations.
15295                          * It's safe to assume that iterator loop will finish, taking into
15296                          * account iter_next() contract of eventually returning
15297                          * sticky NULL result.
15298                          */
15299                         if (is_iter_next_insn(env, insn_idx)) {
15300                                 if (states_equal(env, &sl->state, cur)) {
15301                                         struct bpf_func_state *cur_frame;
15302                                         struct bpf_reg_state *iter_state, *iter_reg;
15303                                         int spi;
15304
15305                                         cur_frame = cur->frame[cur->curframe];
15306                                         /* btf_check_iter_kfuncs() enforces that
15307                                          * iter state pointer is always the first arg
15308                                          */
15309                                         iter_reg = &cur_frame->regs[BPF_REG_1];
15310                                         /* current state is valid due to states_equal(),
15311                                          * so we can assume valid iter and reg state,
15312                                          * no need for extra (re-)validations
15313                                          */
15314                                         spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
15315                                         iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
15316                                         if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
15317                                                 goto hit;
15318                                 }
15319                                 goto skip_inf_loop_check;
15320                         }
15321                         /* attempt to detect infinite loop to avoid unnecessary doomed work */
15322                         if (states_maybe_looping(&sl->state, cur) &&
15323                             states_equal(env, &sl->state, cur) &&
15324                             !iter_active_depths_differ(&sl->state, cur)) {
15325                                 verbose_linfo(env, insn_idx, "; ");
15326                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
15327                                 return -EINVAL;
15328                         }
15329                         /* if the verifier is processing a loop, avoid adding new state
15330                          * too often, since different loop iterations have distinct
15331                          * states and may not help future pruning.
15332                          * This threshold shouldn't be too low to make sure that
15333                          * a loop with large bound will be rejected quickly.
15334                          * The most abusive loop will be:
15335                          * r1 += 1
15336                          * if r1 < 1000000 goto pc-2
15337                          * 1M insn_procssed limit / 100 == 10k peak states.
15338                          * This threshold shouldn't be too high either, since states
15339                          * at the end of the loop are likely to be useful in pruning.
15340                          */
15341 skip_inf_loop_check:
15342                         if (!force_new_state &&
15343                             env->jmps_processed - env->prev_jmps_processed < 20 &&
15344                             env->insn_processed - env->prev_insn_processed < 100)
15345                                 add_new_state = false;
15346                         goto miss;
15347                 }
15348                 if (states_equal(env, &sl->state, cur)) {
15349 hit:
15350                         sl->hit_cnt++;
15351                         /* reached equivalent register/stack state,
15352                          * prune the search.
15353                          * Registers read by the continuation are read by us.
15354                          * If we have any write marks in env->cur_state, they
15355                          * will prevent corresponding reads in the continuation
15356                          * from reaching our parent (an explored_state).  Our
15357                          * own state will get the read marks recorded, but
15358                          * they'll be immediately forgotten as we're pruning
15359                          * this state and will pop a new one.
15360                          */
15361                         err = propagate_liveness(env, &sl->state, cur);
15362
15363                         /* if previous state reached the exit with precision and
15364                          * current state is equivalent to it (except precsion marks)
15365                          * the precision needs to be propagated back in
15366                          * the current state.
15367                          */
15368                         err = err ? : push_jmp_history(env, cur);
15369                         err = err ? : propagate_precision(env, &sl->state);
15370                         if (err)
15371                                 return err;
15372                         return 1;
15373                 }
15374 miss:
15375                 /* when new state is not going to be added do not increase miss count.
15376                  * Otherwise several loop iterations will remove the state
15377                  * recorded earlier. The goal of these heuristics is to have
15378                  * states from some iterations of the loop (some in the beginning
15379                  * and some at the end) to help pruning.
15380                  */
15381                 if (add_new_state)
15382                         sl->miss_cnt++;
15383                 /* heuristic to determine whether this state is beneficial
15384                  * to keep checking from state equivalence point of view.
15385                  * Higher numbers increase max_states_per_insn and verification time,
15386                  * but do not meaningfully decrease insn_processed.
15387                  */
15388                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
15389                         /* the state is unlikely to be useful. Remove it to
15390                          * speed up verification
15391                          */
15392                         *pprev = sl->next;
15393                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
15394                                 u32 br = sl->state.branches;
15395
15396                                 WARN_ONCE(br,
15397                                           "BUG live_done but branches_to_explore %d\n",
15398                                           br);
15399                                 free_verifier_state(&sl->state, false);
15400                                 kfree(sl);
15401                                 env->peak_states--;
15402                         } else {
15403                                 /* cannot free this state, since parentage chain may
15404                                  * walk it later. Add it for free_list instead to
15405                                  * be freed at the end of verification
15406                                  */
15407                                 sl->next = env->free_list;
15408                                 env->free_list = sl;
15409                         }
15410                         sl = *pprev;
15411                         continue;
15412                 }
15413 next:
15414                 pprev = &sl->next;
15415                 sl = *pprev;
15416         }
15417
15418         if (env->max_states_per_insn < states_cnt)
15419                 env->max_states_per_insn = states_cnt;
15420
15421         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
15422                 return 0;
15423
15424         if (!add_new_state)
15425                 return 0;
15426
15427         /* There were no equivalent states, remember the current one.
15428          * Technically the current state is not proven to be safe yet,
15429          * but it will either reach outer most bpf_exit (which means it's safe)
15430          * or it will be rejected. When there are no loops the verifier won't be
15431          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
15432          * again on the way to bpf_exit.
15433          * When looping the sl->state.branches will be > 0 and this state
15434          * will not be considered for equivalence until branches == 0.
15435          */
15436         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
15437         if (!new_sl)
15438                 return -ENOMEM;
15439         env->total_states++;
15440         env->peak_states++;
15441         env->prev_jmps_processed = env->jmps_processed;
15442         env->prev_insn_processed = env->insn_processed;
15443
15444         /* forget precise markings we inherited, see __mark_chain_precision */
15445         if (env->bpf_capable)
15446                 mark_all_scalars_imprecise(env, cur);
15447
15448         /* add new state to the head of linked list */
15449         new = &new_sl->state;
15450         err = copy_verifier_state(new, cur);
15451         if (err) {
15452                 free_verifier_state(new, false);
15453                 kfree(new_sl);
15454                 return err;
15455         }
15456         new->insn_idx = insn_idx;
15457         WARN_ONCE(new->branches != 1,
15458                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
15459
15460         cur->parent = new;
15461         cur->first_insn_idx = insn_idx;
15462         clear_jmp_history(cur);
15463         new_sl->next = *explored_state(env, insn_idx);
15464         *explored_state(env, insn_idx) = new_sl;
15465         /* connect new state to parentage chain. Current frame needs all
15466          * registers connected. Only r6 - r9 of the callers are alive (pushed
15467          * to the stack implicitly by JITs) so in callers' frames connect just
15468          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
15469          * the state of the call instruction (with WRITTEN set), and r0 comes
15470          * from callee with its full parentage chain, anyway.
15471          */
15472         /* clear write marks in current state: the writes we did are not writes
15473          * our child did, so they don't screen off its reads from us.
15474          * (There are no read marks in current state, because reads always mark
15475          * their parent and current state never has children yet.  Only
15476          * explored_states can get read marks.)
15477          */
15478         for (j = 0; j <= cur->curframe; j++) {
15479                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
15480                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
15481                 for (i = 0; i < BPF_REG_FP; i++)
15482                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
15483         }
15484
15485         /* all stack frames are accessible from callee, clear them all */
15486         for (j = 0; j <= cur->curframe; j++) {
15487                 struct bpf_func_state *frame = cur->frame[j];
15488                 struct bpf_func_state *newframe = new->frame[j];
15489
15490                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
15491                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
15492                         frame->stack[i].spilled_ptr.parent =
15493                                                 &newframe->stack[i].spilled_ptr;
15494                 }
15495         }
15496         return 0;
15497 }
15498
15499 /* Return true if it's OK to have the same insn return a different type. */
15500 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
15501 {
15502         switch (base_type(type)) {
15503         case PTR_TO_CTX:
15504         case PTR_TO_SOCKET:
15505         case PTR_TO_SOCK_COMMON:
15506         case PTR_TO_TCP_SOCK:
15507         case PTR_TO_XDP_SOCK:
15508         case PTR_TO_BTF_ID:
15509                 return false;
15510         default:
15511                 return true;
15512         }
15513 }
15514
15515 /* If an instruction was previously used with particular pointer types, then we
15516  * need to be careful to avoid cases such as the below, where it may be ok
15517  * for one branch accessing the pointer, but not ok for the other branch:
15518  *
15519  * R1 = sock_ptr
15520  * goto X;
15521  * ...
15522  * R1 = some_other_valid_ptr;
15523  * goto X;
15524  * ...
15525  * R2 = *(u32 *)(R1 + 0);
15526  */
15527 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
15528 {
15529         return src != prev && (!reg_type_mismatch_ok(src) ||
15530                                !reg_type_mismatch_ok(prev));
15531 }
15532
15533 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
15534                              bool allow_trust_missmatch)
15535 {
15536         enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
15537
15538         if (*prev_type == NOT_INIT) {
15539                 /* Saw a valid insn
15540                  * dst_reg = *(u32 *)(src_reg + off)
15541                  * save type to validate intersecting paths
15542                  */
15543                 *prev_type = type;
15544         } else if (reg_type_mismatch(type, *prev_type)) {
15545                 /* Abuser program is trying to use the same insn
15546                  * dst_reg = *(u32*) (src_reg + off)
15547                  * with different pointer types:
15548                  * src_reg == ctx in one branch and
15549                  * src_reg == stack|map in some other branch.
15550                  * Reject it.
15551                  */
15552                 if (allow_trust_missmatch &&
15553                     base_type(type) == PTR_TO_BTF_ID &&
15554                     base_type(*prev_type) == PTR_TO_BTF_ID) {
15555                         /*
15556                          * Have to support a use case when one path through
15557                          * the program yields TRUSTED pointer while another
15558                          * is UNTRUSTED. Fallback to UNTRUSTED to generate
15559                          * BPF_PROBE_MEM.
15560                          */
15561                         *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
15562                 } else {
15563                         verbose(env, "same insn cannot be used with different pointers\n");
15564                         return -EINVAL;
15565                 }
15566         }
15567
15568         return 0;
15569 }
15570
15571 static int do_check(struct bpf_verifier_env *env)
15572 {
15573         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
15574         struct bpf_verifier_state *state = env->cur_state;
15575         struct bpf_insn *insns = env->prog->insnsi;
15576         struct bpf_reg_state *regs;
15577         int insn_cnt = env->prog->len;
15578         bool do_print_state = false;
15579         int prev_insn_idx = -1;
15580
15581         for (;;) {
15582                 struct bpf_insn *insn;
15583                 u8 class;
15584                 int err;
15585
15586                 env->prev_insn_idx = prev_insn_idx;
15587                 if (env->insn_idx >= insn_cnt) {
15588                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
15589                                 env->insn_idx, insn_cnt);
15590                         return -EFAULT;
15591                 }
15592
15593                 insn = &insns[env->insn_idx];
15594                 class = BPF_CLASS(insn->code);
15595
15596                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
15597                         verbose(env,
15598                                 "BPF program is too large. Processed %d insn\n",
15599                                 env->insn_processed);
15600                         return -E2BIG;
15601                 }
15602
15603                 state->last_insn_idx = env->prev_insn_idx;
15604
15605                 if (is_prune_point(env, env->insn_idx)) {
15606                         err = is_state_visited(env, env->insn_idx);
15607                         if (err < 0)
15608                                 return err;
15609                         if (err == 1) {
15610                                 /* found equivalent state, can prune the search */
15611                                 if (env->log.level & BPF_LOG_LEVEL) {
15612                                         if (do_print_state)
15613                                                 verbose(env, "\nfrom %d to %d%s: safe\n",
15614                                                         env->prev_insn_idx, env->insn_idx,
15615                                                         env->cur_state->speculative ?
15616                                                         " (speculative execution)" : "");
15617                                         else
15618                                                 verbose(env, "%d: safe\n", env->insn_idx);
15619                                 }
15620                                 goto process_bpf_exit;
15621                         }
15622                 }
15623
15624                 if (is_jmp_point(env, env->insn_idx)) {
15625                         err = push_jmp_history(env, state);
15626                         if (err)
15627                                 return err;
15628                 }
15629
15630                 if (signal_pending(current))
15631                         return -EAGAIN;
15632
15633                 if (need_resched())
15634                         cond_resched();
15635
15636                 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
15637                         verbose(env, "\nfrom %d to %d%s:",
15638                                 env->prev_insn_idx, env->insn_idx,
15639                                 env->cur_state->speculative ?
15640                                 " (speculative execution)" : "");
15641                         print_verifier_state(env, state->frame[state->curframe], true);
15642                         do_print_state = false;
15643                 }
15644
15645                 if (env->log.level & BPF_LOG_LEVEL) {
15646                         const struct bpf_insn_cbs cbs = {
15647                                 .cb_call        = disasm_kfunc_name,
15648                                 .cb_print       = verbose,
15649                                 .private_data   = env,
15650                         };
15651
15652                         if (verifier_state_scratched(env))
15653                                 print_insn_state(env, state->frame[state->curframe]);
15654
15655                         verbose_linfo(env, env->insn_idx, "; ");
15656                         env->prev_log_pos = env->log.end_pos;
15657                         verbose(env, "%d: ", env->insn_idx);
15658                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
15659                         env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
15660                         env->prev_log_pos = env->log.end_pos;
15661                 }
15662
15663                 if (bpf_prog_is_offloaded(env->prog->aux)) {
15664                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
15665                                                            env->prev_insn_idx);
15666                         if (err)
15667                                 return err;
15668                 }
15669
15670                 regs = cur_regs(env);
15671                 sanitize_mark_insn_seen(env);
15672                 prev_insn_idx = env->insn_idx;
15673
15674                 if (class == BPF_ALU || class == BPF_ALU64) {
15675                         err = check_alu_op(env, insn);
15676                         if (err)
15677                                 return err;
15678
15679                 } else if (class == BPF_LDX) {
15680                         enum bpf_reg_type src_reg_type;
15681
15682                         /* check for reserved fields is already done */
15683
15684                         /* check src operand */
15685                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
15686                         if (err)
15687                                 return err;
15688
15689                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15690                         if (err)
15691                                 return err;
15692
15693                         src_reg_type = regs[insn->src_reg].type;
15694
15695                         /* check that memory (src_reg + off) is readable,
15696                          * the state of dst_reg will be updated by this func
15697                          */
15698                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
15699                                                insn->off, BPF_SIZE(insn->code),
15700                                                BPF_READ, insn->dst_reg, false);
15701                         if (err)
15702                                 return err;
15703
15704                         err = save_aux_ptr_type(env, src_reg_type, true);
15705                         if (err)
15706                                 return err;
15707                 } else if (class == BPF_STX) {
15708                         enum bpf_reg_type dst_reg_type;
15709
15710                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
15711                                 err = check_atomic(env, env->insn_idx, insn);
15712                                 if (err)
15713                                         return err;
15714                                 env->insn_idx++;
15715                                 continue;
15716                         }
15717
15718                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
15719                                 verbose(env, "BPF_STX uses reserved fields\n");
15720                                 return -EINVAL;
15721                         }
15722
15723                         /* check src1 operand */
15724                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
15725                         if (err)
15726                                 return err;
15727                         /* check src2 operand */
15728                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15729                         if (err)
15730                                 return err;
15731
15732                         dst_reg_type = regs[insn->dst_reg].type;
15733
15734                         /* check that memory (dst_reg + off) is writeable */
15735                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
15736                                                insn->off, BPF_SIZE(insn->code),
15737                                                BPF_WRITE, insn->src_reg, false);
15738                         if (err)
15739                                 return err;
15740
15741                         err = save_aux_ptr_type(env, dst_reg_type, false);
15742                         if (err)
15743                                 return err;
15744                 } else if (class == BPF_ST) {
15745                         enum bpf_reg_type dst_reg_type;
15746
15747                         if (BPF_MODE(insn->code) != BPF_MEM ||
15748                             insn->src_reg != BPF_REG_0) {
15749                                 verbose(env, "BPF_ST uses reserved fields\n");
15750                                 return -EINVAL;
15751                         }
15752                         /* check src operand */
15753                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15754                         if (err)
15755                                 return err;
15756
15757                         dst_reg_type = regs[insn->dst_reg].type;
15758
15759                         /* check that memory (dst_reg + off) is writeable */
15760                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
15761                                                insn->off, BPF_SIZE(insn->code),
15762                                                BPF_WRITE, -1, false);
15763                         if (err)
15764                                 return err;
15765
15766                         err = save_aux_ptr_type(env, dst_reg_type, false);
15767                         if (err)
15768                                 return err;
15769                 } else if (class == BPF_JMP || class == BPF_JMP32) {
15770                         u8 opcode = BPF_OP(insn->code);
15771
15772                         env->jmps_processed++;
15773                         if (opcode == BPF_CALL) {
15774                                 if (BPF_SRC(insn->code) != BPF_K ||
15775                                     (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
15776                                      && insn->off != 0) ||
15777                                     (insn->src_reg != BPF_REG_0 &&
15778                                      insn->src_reg != BPF_PSEUDO_CALL &&
15779                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
15780                                     insn->dst_reg != BPF_REG_0 ||
15781                                     class == BPF_JMP32) {
15782                                         verbose(env, "BPF_CALL uses reserved fields\n");
15783                                         return -EINVAL;
15784                                 }
15785
15786                                 if (env->cur_state->active_lock.ptr) {
15787                                         if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
15788                                             (insn->src_reg == BPF_PSEUDO_CALL) ||
15789                                             (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
15790                                              (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
15791                                                 verbose(env, "function calls are not allowed while holding a lock\n");
15792                                                 return -EINVAL;
15793                                         }
15794                                 }
15795                                 if (insn->src_reg == BPF_PSEUDO_CALL)
15796                                         err = check_func_call(env, insn, &env->insn_idx);
15797                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
15798                                         err = check_kfunc_call(env, insn, &env->insn_idx);
15799                                 else
15800                                         err = check_helper_call(env, insn, &env->insn_idx);
15801                                 if (err)
15802                                         return err;
15803
15804                                 mark_reg_scratched(env, BPF_REG_0);
15805                         } else if (opcode == BPF_JA) {
15806                                 if (BPF_SRC(insn->code) != BPF_K ||
15807                                     insn->imm != 0 ||
15808                                     insn->src_reg != BPF_REG_0 ||
15809                                     insn->dst_reg != BPF_REG_0 ||
15810                                     class == BPF_JMP32) {
15811                                         verbose(env, "BPF_JA uses reserved fields\n");
15812                                         return -EINVAL;
15813                                 }
15814
15815                                 env->insn_idx += insn->off + 1;
15816                                 continue;
15817
15818                         } else if (opcode == BPF_EXIT) {
15819                                 if (BPF_SRC(insn->code) != BPF_K ||
15820                                     insn->imm != 0 ||
15821                                     insn->src_reg != BPF_REG_0 ||
15822                                     insn->dst_reg != BPF_REG_0 ||
15823                                     class == BPF_JMP32) {
15824                                         verbose(env, "BPF_EXIT uses reserved fields\n");
15825                                         return -EINVAL;
15826                                 }
15827
15828                                 if (env->cur_state->active_lock.ptr &&
15829                                     !in_rbtree_lock_required_cb(env)) {
15830                                         verbose(env, "bpf_spin_unlock is missing\n");
15831                                         return -EINVAL;
15832                                 }
15833
15834                                 if (env->cur_state->active_rcu_lock) {
15835                                         verbose(env, "bpf_rcu_read_unlock is missing\n");
15836                                         return -EINVAL;
15837                                 }
15838
15839                                 /* We must do check_reference_leak here before
15840                                  * prepare_func_exit to handle the case when
15841                                  * state->curframe > 0, it may be a callback
15842                                  * function, for which reference_state must
15843                                  * match caller reference state when it exits.
15844                                  */
15845                                 err = check_reference_leak(env);
15846                                 if (err)
15847                                         return err;
15848
15849                                 if (state->curframe) {
15850                                         /* exit from nested function */
15851                                         err = prepare_func_exit(env, &env->insn_idx);
15852                                         if (err)
15853                                                 return err;
15854                                         do_print_state = true;
15855                                         continue;
15856                                 }
15857
15858                                 err = check_return_code(env);
15859                                 if (err)
15860                                         return err;
15861 process_bpf_exit:
15862                                 mark_verifier_state_scratched(env);
15863                                 update_branch_counts(env, env->cur_state);
15864                                 err = pop_stack(env, &prev_insn_idx,
15865                                                 &env->insn_idx, pop_log);
15866                                 if (err < 0) {
15867                                         if (err != -ENOENT)
15868                                                 return err;
15869                                         break;
15870                                 } else {
15871                                         do_print_state = true;
15872                                         continue;
15873                                 }
15874                         } else {
15875                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
15876                                 if (err)
15877                                         return err;
15878                         }
15879                 } else if (class == BPF_LD) {
15880                         u8 mode = BPF_MODE(insn->code);
15881
15882                         if (mode == BPF_ABS || mode == BPF_IND) {
15883                                 err = check_ld_abs(env, insn);
15884                                 if (err)
15885                                         return err;
15886
15887                         } else if (mode == BPF_IMM) {
15888                                 err = check_ld_imm(env, insn);
15889                                 if (err)
15890                                         return err;
15891
15892                                 env->insn_idx++;
15893                                 sanitize_mark_insn_seen(env);
15894                         } else {
15895                                 verbose(env, "invalid BPF_LD mode\n");
15896                                 return -EINVAL;
15897                         }
15898                 } else {
15899                         verbose(env, "unknown insn class %d\n", class);
15900                         return -EINVAL;
15901                 }
15902
15903                 env->insn_idx++;
15904         }
15905
15906         return 0;
15907 }
15908
15909 static int find_btf_percpu_datasec(struct btf *btf)
15910 {
15911         const struct btf_type *t;
15912         const char *tname;
15913         int i, n;
15914
15915         /*
15916          * Both vmlinux and module each have their own ".data..percpu"
15917          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
15918          * types to look at only module's own BTF types.
15919          */
15920         n = btf_nr_types(btf);
15921         if (btf_is_module(btf))
15922                 i = btf_nr_types(btf_vmlinux);
15923         else
15924                 i = 1;
15925
15926         for(; i < n; i++) {
15927                 t = btf_type_by_id(btf, i);
15928                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
15929                         continue;
15930
15931                 tname = btf_name_by_offset(btf, t->name_off);
15932                 if (!strcmp(tname, ".data..percpu"))
15933                         return i;
15934         }
15935
15936         return -ENOENT;
15937 }
15938
15939 /* replace pseudo btf_id with kernel symbol address */
15940 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
15941                                struct bpf_insn *insn,
15942                                struct bpf_insn_aux_data *aux)
15943 {
15944         const struct btf_var_secinfo *vsi;
15945         const struct btf_type *datasec;
15946         struct btf_mod_pair *btf_mod;
15947         const struct btf_type *t;
15948         const char *sym_name;
15949         bool percpu = false;
15950         u32 type, id = insn->imm;
15951         struct btf *btf;
15952         s32 datasec_id;
15953         u64 addr;
15954         int i, btf_fd, err;
15955
15956         btf_fd = insn[1].imm;
15957         if (btf_fd) {
15958                 btf = btf_get_by_fd(btf_fd);
15959                 if (IS_ERR(btf)) {
15960                         verbose(env, "invalid module BTF object FD specified.\n");
15961                         return -EINVAL;
15962                 }
15963         } else {
15964                 if (!btf_vmlinux) {
15965                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
15966                         return -EINVAL;
15967                 }
15968                 btf = btf_vmlinux;
15969                 btf_get(btf);
15970         }
15971
15972         t = btf_type_by_id(btf, id);
15973         if (!t) {
15974                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
15975                 err = -ENOENT;
15976                 goto err_put;
15977         }
15978
15979         if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
15980                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
15981                 err = -EINVAL;
15982                 goto err_put;
15983         }
15984
15985         sym_name = btf_name_by_offset(btf, t->name_off);
15986         addr = kallsyms_lookup_name(sym_name);
15987         if (!addr) {
15988                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
15989                         sym_name);
15990                 err = -ENOENT;
15991                 goto err_put;
15992         }
15993         insn[0].imm = (u32)addr;
15994         insn[1].imm = addr >> 32;
15995
15996         if (btf_type_is_func(t)) {
15997                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
15998                 aux->btf_var.mem_size = 0;
15999                 goto check_btf;
16000         }
16001
16002         datasec_id = find_btf_percpu_datasec(btf);
16003         if (datasec_id > 0) {
16004                 datasec = btf_type_by_id(btf, datasec_id);
16005                 for_each_vsi(i, datasec, vsi) {
16006                         if (vsi->type == id) {
16007                                 percpu = true;
16008                                 break;
16009                         }
16010                 }
16011         }
16012
16013         type = t->type;
16014         t = btf_type_skip_modifiers(btf, type, NULL);
16015         if (percpu) {
16016                 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16017                 aux->btf_var.btf = btf;
16018                 aux->btf_var.btf_id = type;
16019         } else if (!btf_type_is_struct(t)) {
16020                 const struct btf_type *ret;
16021                 const char *tname;
16022                 u32 tsize;
16023
16024                 /* resolve the type size of ksym. */
16025                 ret = btf_resolve_size(btf, t, &tsize);
16026                 if (IS_ERR(ret)) {
16027                         tname = btf_name_by_offset(btf, t->name_off);
16028                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16029                                 tname, PTR_ERR(ret));
16030                         err = -EINVAL;
16031                         goto err_put;
16032                 }
16033                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16034                 aux->btf_var.mem_size = tsize;
16035         } else {
16036                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
16037                 aux->btf_var.btf = btf;
16038                 aux->btf_var.btf_id = type;
16039         }
16040 check_btf:
16041         /* check whether we recorded this BTF (and maybe module) already */
16042         for (i = 0; i < env->used_btf_cnt; i++) {
16043                 if (env->used_btfs[i].btf == btf) {
16044                         btf_put(btf);
16045                         return 0;
16046                 }
16047         }
16048
16049         if (env->used_btf_cnt >= MAX_USED_BTFS) {
16050                 err = -E2BIG;
16051                 goto err_put;
16052         }
16053
16054         btf_mod = &env->used_btfs[env->used_btf_cnt];
16055         btf_mod->btf = btf;
16056         btf_mod->module = NULL;
16057
16058         /* if we reference variables from kernel module, bump its refcount */
16059         if (btf_is_module(btf)) {
16060                 btf_mod->module = btf_try_get_module(btf);
16061                 if (!btf_mod->module) {
16062                         err = -ENXIO;
16063                         goto err_put;
16064                 }
16065         }
16066
16067         env->used_btf_cnt++;
16068
16069         return 0;
16070 err_put:
16071         btf_put(btf);
16072         return err;
16073 }
16074
16075 static bool is_tracing_prog_type(enum bpf_prog_type type)
16076 {
16077         switch (type) {
16078         case BPF_PROG_TYPE_KPROBE:
16079         case BPF_PROG_TYPE_TRACEPOINT:
16080         case BPF_PROG_TYPE_PERF_EVENT:
16081         case BPF_PROG_TYPE_RAW_TRACEPOINT:
16082         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16083                 return true;
16084         default:
16085                 return false;
16086         }
16087 }
16088
16089 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16090                                         struct bpf_map *map,
16091                                         struct bpf_prog *prog)
16092
16093 {
16094         enum bpf_prog_type prog_type = resolve_prog_type(prog);
16095
16096         if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16097             btf_record_has_field(map->record, BPF_RB_ROOT)) {
16098                 if (is_tracing_prog_type(prog_type)) {
16099                         verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
16100                         return -EINVAL;
16101                 }
16102         }
16103
16104         if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
16105                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16106                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16107                         return -EINVAL;
16108                 }
16109
16110                 if (is_tracing_prog_type(prog_type)) {
16111                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
16112                         return -EINVAL;
16113                 }
16114
16115                 if (prog->aux->sleepable) {
16116                         verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
16117                         return -EINVAL;
16118                 }
16119         }
16120
16121         if (btf_record_has_field(map->record, BPF_TIMER)) {
16122                 if (is_tracing_prog_type(prog_type)) {
16123                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
16124                         return -EINVAL;
16125                 }
16126         }
16127
16128         if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
16129             !bpf_offload_prog_map_match(prog, map)) {
16130                 verbose(env, "offload device mismatch between prog and map\n");
16131                 return -EINVAL;
16132         }
16133
16134         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
16135                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
16136                 return -EINVAL;
16137         }
16138
16139         if (prog->aux->sleepable)
16140                 switch (map->map_type) {
16141                 case BPF_MAP_TYPE_HASH:
16142                 case BPF_MAP_TYPE_LRU_HASH:
16143                 case BPF_MAP_TYPE_ARRAY:
16144                 case BPF_MAP_TYPE_PERCPU_HASH:
16145                 case BPF_MAP_TYPE_PERCPU_ARRAY:
16146                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
16147                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
16148                 case BPF_MAP_TYPE_HASH_OF_MAPS:
16149                 case BPF_MAP_TYPE_RINGBUF:
16150                 case BPF_MAP_TYPE_USER_RINGBUF:
16151                 case BPF_MAP_TYPE_INODE_STORAGE:
16152                 case BPF_MAP_TYPE_SK_STORAGE:
16153                 case BPF_MAP_TYPE_TASK_STORAGE:
16154                 case BPF_MAP_TYPE_CGRP_STORAGE:
16155                         break;
16156                 default:
16157                         verbose(env,
16158                                 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
16159                         return -EINVAL;
16160                 }
16161
16162         return 0;
16163 }
16164
16165 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
16166 {
16167         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
16168                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
16169 }
16170
16171 /* find and rewrite pseudo imm in ld_imm64 instructions:
16172  *
16173  * 1. if it accesses map FD, replace it with actual map pointer.
16174  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
16175  *
16176  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
16177  */
16178 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
16179 {
16180         struct bpf_insn *insn = env->prog->insnsi;
16181         int insn_cnt = env->prog->len;
16182         int i, j, err;
16183
16184         err = bpf_prog_calc_tag(env->prog);
16185         if (err)
16186                 return err;
16187
16188         for (i = 0; i < insn_cnt; i++, insn++) {
16189                 if (BPF_CLASS(insn->code) == BPF_LDX &&
16190                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
16191                         verbose(env, "BPF_LDX uses reserved fields\n");
16192                         return -EINVAL;
16193                 }
16194
16195                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
16196                         struct bpf_insn_aux_data *aux;
16197                         struct bpf_map *map;
16198                         struct fd f;
16199                         u64 addr;
16200                         u32 fd;
16201
16202                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
16203                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
16204                             insn[1].off != 0) {
16205                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
16206                                 return -EINVAL;
16207                         }
16208
16209                         if (insn[0].src_reg == 0)
16210                                 /* valid generic load 64-bit imm */
16211                                 goto next_insn;
16212
16213                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
16214                                 aux = &env->insn_aux_data[i];
16215                                 err = check_pseudo_btf_id(env, insn, aux);
16216                                 if (err)
16217                                         return err;
16218                                 goto next_insn;
16219                         }
16220
16221                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
16222                                 aux = &env->insn_aux_data[i];
16223                                 aux->ptr_type = PTR_TO_FUNC;
16224                                 goto next_insn;
16225                         }
16226
16227                         /* In final convert_pseudo_ld_imm64() step, this is
16228                          * converted into regular 64-bit imm load insn.
16229                          */
16230                         switch (insn[0].src_reg) {
16231                         case BPF_PSEUDO_MAP_VALUE:
16232                         case BPF_PSEUDO_MAP_IDX_VALUE:
16233                                 break;
16234                         case BPF_PSEUDO_MAP_FD:
16235                         case BPF_PSEUDO_MAP_IDX:
16236                                 if (insn[1].imm == 0)
16237                                         break;
16238                                 fallthrough;
16239                         default:
16240                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
16241                                 return -EINVAL;
16242                         }
16243
16244                         switch (insn[0].src_reg) {
16245                         case BPF_PSEUDO_MAP_IDX_VALUE:
16246                         case BPF_PSEUDO_MAP_IDX:
16247                                 if (bpfptr_is_null(env->fd_array)) {
16248                                         verbose(env, "fd_idx without fd_array is invalid\n");
16249                                         return -EPROTO;
16250                                 }
16251                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
16252                                                             insn[0].imm * sizeof(fd),
16253                                                             sizeof(fd)))
16254                                         return -EFAULT;
16255                                 break;
16256                         default:
16257                                 fd = insn[0].imm;
16258                                 break;
16259                         }
16260
16261                         f = fdget(fd);
16262                         map = __bpf_map_get(f);
16263                         if (IS_ERR(map)) {
16264                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
16265                                         insn[0].imm);
16266                                 return PTR_ERR(map);
16267                         }
16268
16269                         err = check_map_prog_compatibility(env, map, env->prog);
16270                         if (err) {
16271                                 fdput(f);
16272                                 return err;
16273                         }
16274
16275                         aux = &env->insn_aux_data[i];
16276                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
16277                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
16278                                 addr = (unsigned long)map;
16279                         } else {
16280                                 u32 off = insn[1].imm;
16281
16282                                 if (off >= BPF_MAX_VAR_OFF) {
16283                                         verbose(env, "direct value offset of %u is not allowed\n", off);
16284                                         fdput(f);
16285                                         return -EINVAL;
16286                                 }
16287
16288                                 if (!map->ops->map_direct_value_addr) {
16289                                         verbose(env, "no direct value access support for this map type\n");
16290                                         fdput(f);
16291                                         return -EINVAL;
16292                                 }
16293
16294                                 err = map->ops->map_direct_value_addr(map, &addr, off);
16295                                 if (err) {
16296                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
16297                                                 map->value_size, off);
16298                                         fdput(f);
16299                                         return err;
16300                                 }
16301
16302                                 aux->map_off = off;
16303                                 addr += off;
16304                         }
16305
16306                         insn[0].imm = (u32)addr;
16307                         insn[1].imm = addr >> 32;
16308
16309                         /* check whether we recorded this map already */
16310                         for (j = 0; j < env->used_map_cnt; j++) {
16311                                 if (env->used_maps[j] == map) {
16312                                         aux->map_index = j;
16313                                         fdput(f);
16314                                         goto next_insn;
16315                                 }
16316                         }
16317
16318                         if (env->used_map_cnt >= MAX_USED_MAPS) {
16319                                 fdput(f);
16320                                 return -E2BIG;
16321                         }
16322
16323                         /* hold the map. If the program is rejected by verifier,
16324                          * the map will be released by release_maps() or it
16325                          * will be used by the valid program until it's unloaded
16326                          * and all maps are released in free_used_maps()
16327                          */
16328                         bpf_map_inc(map);
16329
16330                         aux->map_index = env->used_map_cnt;
16331                         env->used_maps[env->used_map_cnt++] = map;
16332
16333                         if (bpf_map_is_cgroup_storage(map) &&
16334                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
16335                                 verbose(env, "only one cgroup storage of each type is allowed\n");
16336                                 fdput(f);
16337                                 return -EBUSY;
16338                         }
16339
16340                         fdput(f);
16341 next_insn:
16342                         insn++;
16343                         i++;
16344                         continue;
16345                 }
16346
16347                 /* Basic sanity check before we invest more work here. */
16348                 if (!bpf_opcode_in_insntable(insn->code)) {
16349                         verbose(env, "unknown opcode %02x\n", insn->code);
16350                         return -EINVAL;
16351                 }
16352         }
16353
16354         /* now all pseudo BPF_LD_IMM64 instructions load valid
16355          * 'struct bpf_map *' into a register instead of user map_fd.
16356          * These pointers will be used later by verifier to validate map access.
16357          */
16358         return 0;
16359 }
16360
16361 /* drop refcnt of maps used by the rejected program */
16362 static void release_maps(struct bpf_verifier_env *env)
16363 {
16364         __bpf_free_used_maps(env->prog->aux, env->used_maps,
16365                              env->used_map_cnt);
16366 }
16367
16368 /* drop refcnt of maps used by the rejected program */
16369 static void release_btfs(struct bpf_verifier_env *env)
16370 {
16371         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
16372                              env->used_btf_cnt);
16373 }
16374
16375 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
16376 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
16377 {
16378         struct bpf_insn *insn = env->prog->insnsi;
16379         int insn_cnt = env->prog->len;
16380         int i;
16381
16382         for (i = 0; i < insn_cnt; i++, insn++) {
16383                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
16384                         continue;
16385                 if (insn->src_reg == BPF_PSEUDO_FUNC)
16386                         continue;
16387                 insn->src_reg = 0;
16388         }
16389 }
16390
16391 /* single env->prog->insni[off] instruction was replaced with the range
16392  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
16393  * [0, off) and [off, end) to new locations, so the patched range stays zero
16394  */
16395 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
16396                                  struct bpf_insn_aux_data *new_data,
16397                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
16398 {
16399         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
16400         struct bpf_insn *insn = new_prog->insnsi;
16401         u32 old_seen = old_data[off].seen;
16402         u32 prog_len;
16403         int i;
16404
16405         /* aux info at OFF always needs adjustment, no matter fast path
16406          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
16407          * original insn at old prog.
16408          */
16409         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
16410
16411         if (cnt == 1)
16412                 return;
16413         prog_len = new_prog->len;
16414
16415         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
16416         memcpy(new_data + off + cnt - 1, old_data + off,
16417                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
16418         for (i = off; i < off + cnt - 1; i++) {
16419                 /* Expand insni[off]'s seen count to the patched range. */
16420                 new_data[i].seen = old_seen;
16421                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
16422         }
16423         env->insn_aux_data = new_data;
16424         vfree(old_data);
16425 }
16426
16427 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
16428 {
16429         int i;
16430
16431         if (len == 1)
16432                 return;
16433         /* NOTE: fake 'exit' subprog should be updated as well. */
16434         for (i = 0; i <= env->subprog_cnt; i++) {
16435                 if (env->subprog_info[i].start <= off)
16436                         continue;
16437                 env->subprog_info[i].start += len - 1;
16438         }
16439 }
16440
16441 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
16442 {
16443         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
16444         int i, sz = prog->aux->size_poke_tab;
16445         struct bpf_jit_poke_descriptor *desc;
16446
16447         for (i = 0; i < sz; i++) {
16448                 desc = &tab[i];
16449                 if (desc->insn_idx <= off)
16450                         continue;
16451                 desc->insn_idx += len - 1;
16452         }
16453 }
16454
16455 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
16456                                             const struct bpf_insn *patch, u32 len)
16457 {
16458         struct bpf_prog *new_prog;
16459         struct bpf_insn_aux_data *new_data = NULL;
16460
16461         if (len > 1) {
16462                 new_data = vzalloc(array_size(env->prog->len + len - 1,
16463                                               sizeof(struct bpf_insn_aux_data)));
16464                 if (!new_data)
16465                         return NULL;
16466         }
16467
16468         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
16469         if (IS_ERR(new_prog)) {
16470                 if (PTR_ERR(new_prog) == -ERANGE)
16471                         verbose(env,
16472                                 "insn %d cannot be patched due to 16-bit range\n",
16473                                 env->insn_aux_data[off].orig_idx);
16474                 vfree(new_data);
16475                 return NULL;
16476         }
16477         adjust_insn_aux_data(env, new_data, new_prog, off, len);
16478         adjust_subprog_starts(env, off, len);
16479         adjust_poke_descs(new_prog, off, len);
16480         return new_prog;
16481 }
16482
16483 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
16484                                               u32 off, u32 cnt)
16485 {
16486         int i, j;
16487
16488         /* find first prog starting at or after off (first to remove) */
16489         for (i = 0; i < env->subprog_cnt; i++)
16490                 if (env->subprog_info[i].start >= off)
16491                         break;
16492         /* find first prog starting at or after off + cnt (first to stay) */
16493         for (j = i; j < env->subprog_cnt; j++)
16494                 if (env->subprog_info[j].start >= off + cnt)
16495                         break;
16496         /* if j doesn't start exactly at off + cnt, we are just removing
16497          * the front of previous prog
16498          */
16499         if (env->subprog_info[j].start != off + cnt)
16500                 j--;
16501
16502         if (j > i) {
16503                 struct bpf_prog_aux *aux = env->prog->aux;
16504                 int move;
16505
16506                 /* move fake 'exit' subprog as well */
16507                 move = env->subprog_cnt + 1 - j;
16508
16509                 memmove(env->subprog_info + i,
16510                         env->subprog_info + j,
16511                         sizeof(*env->subprog_info) * move);
16512                 env->subprog_cnt -= j - i;
16513
16514                 /* remove func_info */
16515                 if (aux->func_info) {
16516                         move = aux->func_info_cnt - j;
16517
16518                         memmove(aux->func_info + i,
16519                                 aux->func_info + j,
16520                                 sizeof(*aux->func_info) * move);
16521                         aux->func_info_cnt -= j - i;
16522                         /* func_info->insn_off is set after all code rewrites,
16523                          * in adjust_btf_func() - no need to adjust
16524                          */
16525                 }
16526         } else {
16527                 /* convert i from "first prog to remove" to "first to adjust" */
16528                 if (env->subprog_info[i].start == off)
16529                         i++;
16530         }
16531
16532         /* update fake 'exit' subprog as well */
16533         for (; i <= env->subprog_cnt; i++)
16534                 env->subprog_info[i].start -= cnt;
16535
16536         return 0;
16537 }
16538
16539 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
16540                                       u32 cnt)
16541 {
16542         struct bpf_prog *prog = env->prog;
16543         u32 i, l_off, l_cnt, nr_linfo;
16544         struct bpf_line_info *linfo;
16545
16546         nr_linfo = prog->aux->nr_linfo;
16547         if (!nr_linfo)
16548                 return 0;
16549
16550         linfo = prog->aux->linfo;
16551
16552         /* find first line info to remove, count lines to be removed */
16553         for (i = 0; i < nr_linfo; i++)
16554                 if (linfo[i].insn_off >= off)
16555                         break;
16556
16557         l_off = i;
16558         l_cnt = 0;
16559         for (; i < nr_linfo; i++)
16560                 if (linfo[i].insn_off < off + cnt)
16561                         l_cnt++;
16562                 else
16563                         break;
16564
16565         /* First live insn doesn't match first live linfo, it needs to "inherit"
16566          * last removed linfo.  prog is already modified, so prog->len == off
16567          * means no live instructions after (tail of the program was removed).
16568          */
16569         if (prog->len != off && l_cnt &&
16570             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
16571                 l_cnt--;
16572                 linfo[--i].insn_off = off + cnt;
16573         }
16574
16575         /* remove the line info which refer to the removed instructions */
16576         if (l_cnt) {
16577                 memmove(linfo + l_off, linfo + i,
16578                         sizeof(*linfo) * (nr_linfo - i));
16579
16580                 prog->aux->nr_linfo -= l_cnt;
16581                 nr_linfo = prog->aux->nr_linfo;
16582         }
16583
16584         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
16585         for (i = l_off; i < nr_linfo; i++)
16586                 linfo[i].insn_off -= cnt;
16587
16588         /* fix up all subprogs (incl. 'exit') which start >= off */
16589         for (i = 0; i <= env->subprog_cnt; i++)
16590                 if (env->subprog_info[i].linfo_idx > l_off) {
16591                         /* program may have started in the removed region but
16592                          * may not be fully removed
16593                          */
16594                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
16595                                 env->subprog_info[i].linfo_idx -= l_cnt;
16596                         else
16597                                 env->subprog_info[i].linfo_idx = l_off;
16598                 }
16599
16600         return 0;
16601 }
16602
16603 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
16604 {
16605         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16606         unsigned int orig_prog_len = env->prog->len;
16607         int err;
16608
16609         if (bpf_prog_is_offloaded(env->prog->aux))
16610                 bpf_prog_offload_remove_insns(env, off, cnt);
16611
16612         err = bpf_remove_insns(env->prog, off, cnt);
16613         if (err)
16614                 return err;
16615
16616         err = adjust_subprog_starts_after_remove(env, off, cnt);
16617         if (err)
16618                 return err;
16619
16620         err = bpf_adj_linfo_after_remove(env, off, cnt);
16621         if (err)
16622                 return err;
16623
16624         memmove(aux_data + off, aux_data + off + cnt,
16625                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
16626
16627         return 0;
16628 }
16629
16630 /* The verifier does more data flow analysis than llvm and will not
16631  * explore branches that are dead at run time. Malicious programs can
16632  * have dead code too. Therefore replace all dead at-run-time code
16633  * with 'ja -1'.
16634  *
16635  * Just nops are not optimal, e.g. if they would sit at the end of the
16636  * program and through another bug we would manage to jump there, then
16637  * we'd execute beyond program memory otherwise. Returning exception
16638  * code also wouldn't work since we can have subprogs where the dead
16639  * code could be located.
16640  */
16641 static void sanitize_dead_code(struct bpf_verifier_env *env)
16642 {
16643         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16644         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
16645         struct bpf_insn *insn = env->prog->insnsi;
16646         const int insn_cnt = env->prog->len;
16647         int i;
16648
16649         for (i = 0; i < insn_cnt; i++) {
16650                 if (aux_data[i].seen)
16651                         continue;
16652                 memcpy(insn + i, &trap, sizeof(trap));
16653                 aux_data[i].zext_dst = false;
16654         }
16655 }
16656
16657 static bool insn_is_cond_jump(u8 code)
16658 {
16659         u8 op;
16660
16661         if (BPF_CLASS(code) == BPF_JMP32)
16662                 return true;
16663
16664         if (BPF_CLASS(code) != BPF_JMP)
16665                 return false;
16666
16667         op = BPF_OP(code);
16668         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
16669 }
16670
16671 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
16672 {
16673         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16674         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
16675         struct bpf_insn *insn = env->prog->insnsi;
16676         const int insn_cnt = env->prog->len;
16677         int i;
16678
16679         for (i = 0; i < insn_cnt; i++, insn++) {
16680                 if (!insn_is_cond_jump(insn->code))
16681                         continue;
16682
16683                 if (!aux_data[i + 1].seen)
16684                         ja.off = insn->off;
16685                 else if (!aux_data[i + 1 + insn->off].seen)
16686                         ja.off = 0;
16687                 else
16688                         continue;
16689
16690                 if (bpf_prog_is_offloaded(env->prog->aux))
16691                         bpf_prog_offload_replace_insn(env, i, &ja);
16692
16693                 memcpy(insn, &ja, sizeof(ja));
16694         }
16695 }
16696
16697 static int opt_remove_dead_code(struct bpf_verifier_env *env)
16698 {
16699         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
16700         int insn_cnt = env->prog->len;
16701         int i, err;
16702
16703         for (i = 0; i < insn_cnt; i++) {
16704                 int j;
16705
16706                 j = 0;
16707                 while (i + j < insn_cnt && !aux_data[i + j].seen)
16708                         j++;
16709                 if (!j)
16710                         continue;
16711
16712                 err = verifier_remove_insns(env, i, j);
16713                 if (err)
16714                         return err;
16715                 insn_cnt = env->prog->len;
16716         }
16717
16718         return 0;
16719 }
16720
16721 static int opt_remove_nops(struct bpf_verifier_env *env)
16722 {
16723         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
16724         struct bpf_insn *insn = env->prog->insnsi;
16725         int insn_cnt = env->prog->len;
16726         int i, err;
16727
16728         for (i = 0; i < insn_cnt; i++) {
16729                 if (memcmp(&insn[i], &ja, sizeof(ja)))
16730                         continue;
16731
16732                 err = verifier_remove_insns(env, i, 1);
16733                 if (err)
16734                         return err;
16735                 insn_cnt--;
16736                 i--;
16737         }
16738
16739         return 0;
16740 }
16741
16742 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
16743                                          const union bpf_attr *attr)
16744 {
16745         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
16746         struct bpf_insn_aux_data *aux = env->insn_aux_data;
16747         int i, patch_len, delta = 0, len = env->prog->len;
16748         struct bpf_insn *insns = env->prog->insnsi;
16749         struct bpf_prog *new_prog;
16750         bool rnd_hi32;
16751
16752         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
16753         zext_patch[1] = BPF_ZEXT_REG(0);
16754         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
16755         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
16756         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
16757         for (i = 0; i < len; i++) {
16758                 int adj_idx = i + delta;
16759                 struct bpf_insn insn;
16760                 int load_reg;
16761
16762                 insn = insns[adj_idx];
16763                 load_reg = insn_def_regno(&insn);
16764                 if (!aux[adj_idx].zext_dst) {
16765                         u8 code, class;
16766                         u32 imm_rnd;
16767
16768                         if (!rnd_hi32)
16769                                 continue;
16770
16771                         code = insn.code;
16772                         class = BPF_CLASS(code);
16773                         if (load_reg == -1)
16774                                 continue;
16775
16776                         /* NOTE: arg "reg" (the fourth one) is only used for
16777                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
16778                          *       here.
16779                          */
16780                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
16781                                 if (class == BPF_LD &&
16782                                     BPF_MODE(code) == BPF_IMM)
16783                                         i++;
16784                                 continue;
16785                         }
16786
16787                         /* ctx load could be transformed into wider load. */
16788                         if (class == BPF_LDX &&
16789                             aux[adj_idx].ptr_type == PTR_TO_CTX)
16790                                 continue;
16791
16792                         imm_rnd = get_random_u32();
16793                         rnd_hi32_patch[0] = insn;
16794                         rnd_hi32_patch[1].imm = imm_rnd;
16795                         rnd_hi32_patch[3].dst_reg = load_reg;
16796                         patch = rnd_hi32_patch;
16797                         patch_len = 4;
16798                         goto apply_patch_buffer;
16799                 }
16800
16801                 /* Add in an zero-extend instruction if a) the JIT has requested
16802                  * it or b) it's a CMPXCHG.
16803                  *
16804                  * The latter is because: BPF_CMPXCHG always loads a value into
16805                  * R0, therefore always zero-extends. However some archs'
16806                  * equivalent instruction only does this load when the
16807                  * comparison is successful. This detail of CMPXCHG is
16808                  * orthogonal to the general zero-extension behaviour of the
16809                  * CPU, so it's treated independently of bpf_jit_needs_zext.
16810                  */
16811                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
16812                         continue;
16813
16814                 /* Zero-extension is done by the caller. */
16815                 if (bpf_pseudo_kfunc_call(&insn))
16816                         continue;
16817
16818                 if (WARN_ON(load_reg == -1)) {
16819                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
16820                         return -EFAULT;
16821                 }
16822
16823                 zext_patch[0] = insn;
16824                 zext_patch[1].dst_reg = load_reg;
16825                 zext_patch[1].src_reg = load_reg;
16826                 patch = zext_patch;
16827                 patch_len = 2;
16828 apply_patch_buffer:
16829                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
16830                 if (!new_prog)
16831                         return -ENOMEM;
16832                 env->prog = new_prog;
16833                 insns = new_prog->insnsi;
16834                 aux = env->insn_aux_data;
16835                 delta += patch_len - 1;
16836         }
16837
16838         return 0;
16839 }
16840
16841 /* convert load instructions that access fields of a context type into a
16842  * sequence of instructions that access fields of the underlying structure:
16843  *     struct __sk_buff    -> struct sk_buff
16844  *     struct bpf_sock_ops -> struct sock
16845  */
16846 static int convert_ctx_accesses(struct bpf_verifier_env *env)
16847 {
16848         const struct bpf_verifier_ops *ops = env->ops;
16849         int i, cnt, size, ctx_field_size, delta = 0;
16850         const int insn_cnt = env->prog->len;
16851         struct bpf_insn insn_buf[16], *insn;
16852         u32 target_size, size_default, off;
16853         struct bpf_prog *new_prog;
16854         enum bpf_access_type type;
16855         bool is_narrower_load;
16856
16857         if (ops->gen_prologue || env->seen_direct_write) {
16858                 if (!ops->gen_prologue) {
16859                         verbose(env, "bpf verifier is misconfigured\n");
16860                         return -EINVAL;
16861                 }
16862                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
16863                                         env->prog);
16864                 if (cnt >= ARRAY_SIZE(insn_buf)) {
16865                         verbose(env, "bpf verifier is misconfigured\n");
16866                         return -EINVAL;
16867                 } else if (cnt) {
16868                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
16869                         if (!new_prog)
16870                                 return -ENOMEM;
16871
16872                         env->prog = new_prog;
16873                         delta += cnt - 1;
16874                 }
16875         }
16876
16877         if (bpf_prog_is_offloaded(env->prog->aux))
16878                 return 0;
16879
16880         insn = env->prog->insnsi + delta;
16881
16882         for (i = 0; i < insn_cnt; i++, insn++) {
16883                 bpf_convert_ctx_access_t convert_ctx_access;
16884
16885                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
16886                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
16887                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
16888                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
16889                         type = BPF_READ;
16890                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
16891                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
16892                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
16893                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
16894                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
16895                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
16896                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
16897                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
16898                         type = BPF_WRITE;
16899                 } else {
16900                         continue;
16901                 }
16902
16903                 if (type == BPF_WRITE &&
16904                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
16905                         struct bpf_insn patch[] = {
16906                                 *insn,
16907                                 BPF_ST_NOSPEC(),
16908                         };
16909
16910                         cnt = ARRAY_SIZE(patch);
16911                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
16912                         if (!new_prog)
16913                                 return -ENOMEM;
16914
16915                         delta    += cnt - 1;
16916                         env->prog = new_prog;
16917                         insn      = new_prog->insnsi + i + delta;
16918                         continue;
16919                 }
16920
16921                 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
16922                 case PTR_TO_CTX:
16923                         if (!ops->convert_ctx_access)
16924                                 continue;
16925                         convert_ctx_access = ops->convert_ctx_access;
16926                         break;
16927                 case PTR_TO_SOCKET:
16928                 case PTR_TO_SOCK_COMMON:
16929                         convert_ctx_access = bpf_sock_convert_ctx_access;
16930                         break;
16931                 case PTR_TO_TCP_SOCK:
16932                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
16933                         break;
16934                 case PTR_TO_XDP_SOCK:
16935                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
16936                         break;
16937                 case PTR_TO_BTF_ID:
16938                 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
16939                 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
16940                  * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
16941                  * be said once it is marked PTR_UNTRUSTED, hence we must handle
16942                  * any faults for loads into such types. BPF_WRITE is disallowed
16943                  * for this case.
16944                  */
16945                 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
16946                         if (type == BPF_READ) {
16947                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
16948                                         BPF_SIZE((insn)->code);
16949                                 env->prog->aux->num_exentries++;
16950                         }
16951                         continue;
16952                 default:
16953                         continue;
16954                 }
16955
16956                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
16957                 size = BPF_LDST_BYTES(insn);
16958
16959                 /* If the read access is a narrower load of the field,
16960                  * convert to a 4/8-byte load, to minimum program type specific
16961                  * convert_ctx_access changes. If conversion is successful,
16962                  * we will apply proper mask to the result.
16963                  */
16964                 is_narrower_load = size < ctx_field_size;
16965                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
16966                 off = insn->off;
16967                 if (is_narrower_load) {
16968                         u8 size_code;
16969
16970                         if (type == BPF_WRITE) {
16971                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
16972                                 return -EINVAL;
16973                         }
16974
16975                         size_code = BPF_H;
16976                         if (ctx_field_size == 4)
16977                                 size_code = BPF_W;
16978                         else if (ctx_field_size == 8)
16979                                 size_code = BPF_DW;
16980
16981                         insn->off = off & ~(size_default - 1);
16982                         insn->code = BPF_LDX | BPF_MEM | size_code;
16983                 }
16984
16985                 target_size = 0;
16986                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
16987                                          &target_size);
16988                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
16989                     (ctx_field_size && !target_size)) {
16990                         verbose(env, "bpf verifier is misconfigured\n");
16991                         return -EINVAL;
16992                 }
16993
16994                 if (is_narrower_load && size < target_size) {
16995                         u8 shift = bpf_ctx_narrow_access_offset(
16996                                 off, size, size_default) * 8;
16997                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
16998                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
16999                                 return -EINVAL;
17000                         }
17001                         if (ctx_field_size <= 4) {
17002                                 if (shift)
17003                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17004                                                                         insn->dst_reg,
17005                                                                         shift);
17006                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17007                                                                 (1 << size * 8) - 1);
17008                         } else {
17009                                 if (shift)
17010                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17011                                                                         insn->dst_reg,
17012                                                                         shift);
17013                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
17014                                                                 (1ULL << size * 8) - 1);
17015                         }
17016                 }
17017
17018                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17019                 if (!new_prog)
17020                         return -ENOMEM;
17021
17022                 delta += cnt - 1;
17023
17024                 /* keep walking new program and skip insns we just inserted */
17025                 env->prog = new_prog;
17026                 insn      = new_prog->insnsi + i + delta;
17027         }
17028
17029         return 0;
17030 }
17031
17032 static int jit_subprogs(struct bpf_verifier_env *env)
17033 {
17034         struct bpf_prog *prog = env->prog, **func, *tmp;
17035         int i, j, subprog_start, subprog_end = 0, len, subprog;
17036         struct bpf_map *map_ptr;
17037         struct bpf_insn *insn;
17038         void *old_bpf_func;
17039         int err, num_exentries;
17040
17041         if (env->subprog_cnt <= 1)
17042                 return 0;
17043
17044         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17045                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17046                         continue;
17047
17048                 /* Upon error here we cannot fall back to interpreter but
17049                  * need a hard reject of the program. Thus -EFAULT is
17050                  * propagated in any case.
17051                  */
17052                 subprog = find_subprog(env, i + insn->imm + 1);
17053                 if (subprog < 0) {
17054                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17055                                   i + insn->imm + 1);
17056                         return -EFAULT;
17057                 }
17058                 /* temporarily remember subprog id inside insn instead of
17059                  * aux_data, since next loop will split up all insns into funcs
17060                  */
17061                 insn->off = subprog;
17062                 /* remember original imm in case JIT fails and fallback
17063                  * to interpreter will be needed
17064                  */
17065                 env->insn_aux_data[i].call_imm = insn->imm;
17066                 /* point imm to __bpf_call_base+1 from JITs point of view */
17067                 insn->imm = 1;
17068                 if (bpf_pseudo_func(insn))
17069                         /* jit (e.g. x86_64) may emit fewer instructions
17070                          * if it learns a u32 imm is the same as a u64 imm.
17071                          * Force a non zero here.
17072                          */
17073                         insn[1].imm = 1;
17074         }
17075
17076         err = bpf_prog_alloc_jited_linfo(prog);
17077         if (err)
17078                 goto out_undo_insn;
17079
17080         err = -ENOMEM;
17081         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17082         if (!func)
17083                 goto out_undo_insn;
17084
17085         for (i = 0; i < env->subprog_cnt; i++) {
17086                 subprog_start = subprog_end;
17087                 subprog_end = env->subprog_info[i + 1].start;
17088
17089                 len = subprog_end - subprog_start;
17090                 /* bpf_prog_run() doesn't call subprogs directly,
17091                  * hence main prog stats include the runtime of subprogs.
17092                  * subprogs don't have IDs and not reachable via prog_get_next_id
17093                  * func[i]->stats will never be accessed and stays NULL
17094                  */
17095                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
17096                 if (!func[i])
17097                         goto out_free;
17098                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17099                        len * sizeof(struct bpf_insn));
17100                 func[i]->type = prog->type;
17101                 func[i]->len = len;
17102                 if (bpf_prog_calc_tag(func[i]))
17103                         goto out_free;
17104                 func[i]->is_func = 1;
17105                 func[i]->aux->func_idx = i;
17106                 /* Below members will be freed only at prog->aux */
17107                 func[i]->aux->btf = prog->aux->btf;
17108                 func[i]->aux->func_info = prog->aux->func_info;
17109                 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
17110                 func[i]->aux->poke_tab = prog->aux->poke_tab;
17111                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
17112
17113                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
17114                         struct bpf_jit_poke_descriptor *poke;
17115
17116                         poke = &prog->aux->poke_tab[j];
17117                         if (poke->insn_idx < subprog_end &&
17118                             poke->insn_idx >= subprog_start)
17119                                 poke->aux = func[i]->aux;
17120                 }
17121
17122                 func[i]->aux->name[0] = 'F';
17123                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
17124                 func[i]->jit_requested = 1;
17125                 func[i]->blinding_requested = prog->blinding_requested;
17126                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
17127                 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
17128                 func[i]->aux->linfo = prog->aux->linfo;
17129                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
17130                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
17131                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
17132                 num_exentries = 0;
17133                 insn = func[i]->insnsi;
17134                 for (j = 0; j < func[i]->len; j++, insn++) {
17135                         if (BPF_CLASS(insn->code) == BPF_LDX &&
17136                             BPF_MODE(insn->code) == BPF_PROBE_MEM)
17137                                 num_exentries++;
17138                 }
17139                 func[i]->aux->num_exentries = num_exentries;
17140                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
17141                 func[i] = bpf_int_jit_compile(func[i]);
17142                 if (!func[i]->jited) {
17143                         err = -ENOTSUPP;
17144                         goto out_free;
17145                 }
17146                 cond_resched();
17147         }
17148
17149         /* at this point all bpf functions were successfully JITed
17150          * now populate all bpf_calls with correct addresses and
17151          * run last pass of JIT
17152          */
17153         for (i = 0; i < env->subprog_cnt; i++) {
17154                 insn = func[i]->insnsi;
17155                 for (j = 0; j < func[i]->len; j++, insn++) {
17156                         if (bpf_pseudo_func(insn)) {
17157                                 subprog = insn->off;
17158                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
17159                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
17160                                 continue;
17161                         }
17162                         if (!bpf_pseudo_call(insn))
17163                                 continue;
17164                         subprog = insn->off;
17165                         insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
17166                 }
17167
17168                 /* we use the aux data to keep a list of the start addresses
17169                  * of the JITed images for each function in the program
17170                  *
17171                  * for some architectures, such as powerpc64, the imm field
17172                  * might not be large enough to hold the offset of the start
17173                  * address of the callee's JITed image from __bpf_call_base
17174                  *
17175                  * in such cases, we can lookup the start address of a callee
17176                  * by using its subprog id, available from the off field of
17177                  * the call instruction, as an index for this list
17178                  */
17179                 func[i]->aux->func = func;
17180                 func[i]->aux->func_cnt = env->subprog_cnt;
17181         }
17182         for (i = 0; i < env->subprog_cnt; i++) {
17183                 old_bpf_func = func[i]->bpf_func;
17184                 tmp = bpf_int_jit_compile(func[i]);
17185                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
17186                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
17187                         err = -ENOTSUPP;
17188                         goto out_free;
17189                 }
17190                 cond_resched();
17191         }
17192
17193         /* finally lock prog and jit images for all functions and
17194          * populate kallsysm
17195          */
17196         for (i = 0; i < env->subprog_cnt; i++) {
17197                 bpf_prog_lock_ro(func[i]);
17198                 bpf_prog_kallsyms_add(func[i]);
17199         }
17200
17201         /* Last step: make now unused interpreter insns from main
17202          * prog consistent for later dump requests, so they can
17203          * later look the same as if they were interpreted only.
17204          */
17205         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17206                 if (bpf_pseudo_func(insn)) {
17207                         insn[0].imm = env->insn_aux_data[i].call_imm;
17208                         insn[1].imm = insn->off;
17209                         insn->off = 0;
17210                         continue;
17211                 }
17212                 if (!bpf_pseudo_call(insn))
17213                         continue;
17214                 insn->off = env->insn_aux_data[i].call_imm;
17215                 subprog = find_subprog(env, i + insn->off + 1);
17216                 insn->imm = subprog;
17217         }
17218
17219         prog->jited = 1;
17220         prog->bpf_func = func[0]->bpf_func;
17221         prog->jited_len = func[0]->jited_len;
17222         prog->aux->func = func;
17223         prog->aux->func_cnt = env->subprog_cnt;
17224         bpf_prog_jit_attempt_done(prog);
17225         return 0;
17226 out_free:
17227         /* We failed JIT'ing, so at this point we need to unregister poke
17228          * descriptors from subprogs, so that kernel is not attempting to
17229          * patch it anymore as we're freeing the subprog JIT memory.
17230          */
17231         for (i = 0; i < prog->aux->size_poke_tab; i++) {
17232                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
17233                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
17234         }
17235         /* At this point we're guaranteed that poke descriptors are not
17236          * live anymore. We can just unlink its descriptor table as it's
17237          * released with the main prog.
17238          */
17239         for (i = 0; i < env->subprog_cnt; i++) {
17240                 if (!func[i])
17241                         continue;
17242                 func[i]->aux->poke_tab = NULL;
17243                 bpf_jit_free(func[i]);
17244         }
17245         kfree(func);
17246 out_undo_insn:
17247         /* cleanup main prog to be interpreted */
17248         prog->jit_requested = 0;
17249         prog->blinding_requested = 0;
17250         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17251                 if (!bpf_pseudo_call(insn))
17252                         continue;
17253                 insn->off = 0;
17254                 insn->imm = env->insn_aux_data[i].call_imm;
17255         }
17256         bpf_prog_jit_attempt_done(prog);
17257         return err;
17258 }
17259
17260 static int fixup_call_args(struct bpf_verifier_env *env)
17261 {
17262 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17263         struct bpf_prog *prog = env->prog;
17264         struct bpf_insn *insn = prog->insnsi;
17265         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
17266         int i, depth;
17267 #endif
17268         int err = 0;
17269
17270         if (env->prog->jit_requested &&
17271             !bpf_prog_is_offloaded(env->prog->aux)) {
17272                 err = jit_subprogs(env);
17273                 if (err == 0)
17274                         return 0;
17275                 if (err == -EFAULT)
17276                         return err;
17277         }
17278 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
17279         if (has_kfunc_call) {
17280                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
17281                 return -EINVAL;
17282         }
17283         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
17284                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
17285                  * have to be rejected, since interpreter doesn't support them yet.
17286                  */
17287                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
17288                 return -EINVAL;
17289         }
17290         for (i = 0; i < prog->len; i++, insn++) {
17291                 if (bpf_pseudo_func(insn)) {
17292                         /* When JIT fails the progs with callback calls
17293                          * have to be rejected, since interpreter doesn't support them yet.
17294                          */
17295                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
17296                         return -EINVAL;
17297                 }
17298
17299                 if (!bpf_pseudo_call(insn))
17300                         continue;
17301                 depth = get_callee_stack_depth(env, insn, i);
17302                 if (depth < 0)
17303                         return depth;
17304                 bpf_patch_call_args(insn, depth);
17305         }
17306         err = 0;
17307 #endif
17308         return err;
17309 }
17310
17311 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
17312                             struct bpf_insn *insn_buf, int insn_idx, int *cnt)
17313 {
17314         const struct bpf_kfunc_desc *desc;
17315         void *xdp_kfunc;
17316
17317         if (!insn->imm) {
17318                 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
17319                 return -EINVAL;
17320         }
17321
17322         *cnt = 0;
17323
17324         if (bpf_dev_bound_kfunc_id(insn->imm)) {
17325                 xdp_kfunc = bpf_dev_bound_resolve_kfunc(env->prog, insn->imm);
17326                 if (xdp_kfunc) {
17327                         insn->imm = BPF_CALL_IMM(xdp_kfunc);
17328                         return 0;
17329                 }
17330
17331                 /* fallback to default kfunc when not supported by netdev */
17332         }
17333
17334         /* insn->imm has the btf func_id. Replace it with
17335          * an address (relative to __bpf_call_base).
17336          */
17337         desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
17338         if (!desc) {
17339                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
17340                         insn->imm);
17341                 return -EFAULT;
17342         }
17343
17344         insn->imm = desc->imm;
17345         if (insn->off)
17346                 return 0;
17347         if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
17348                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
17349                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
17350                 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
17351
17352                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
17353                 insn_buf[1] = addr[0];
17354                 insn_buf[2] = addr[1];
17355                 insn_buf[3] = *insn;
17356                 *cnt = 4;
17357         } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
17358                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
17359                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
17360
17361                 insn_buf[0] = addr[0];
17362                 insn_buf[1] = addr[1];
17363                 insn_buf[2] = *insn;
17364                 *cnt = 3;
17365         } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
17366                    desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
17367                 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
17368                 *cnt = 1;
17369         } else if (desc->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
17370                 bool seen_direct_write = env->seen_direct_write;
17371                 bool is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
17372
17373                 if (is_rdonly)
17374                         insn->imm = BPF_CALL_IMM(bpf_dynptr_from_skb_rdonly);
17375
17376                 /* restore env->seen_direct_write to its original value, since
17377                  * may_access_direct_pkt_data mutates it
17378                  */
17379                 env->seen_direct_write = seen_direct_write;
17380         }
17381         return 0;
17382 }
17383
17384 /* Do various post-verification rewrites in a single program pass.
17385  * These rewrites simplify JIT and interpreter implementations.
17386  */
17387 static int do_misc_fixups(struct bpf_verifier_env *env)
17388 {
17389         struct bpf_prog *prog = env->prog;
17390         enum bpf_attach_type eatype = prog->expected_attach_type;
17391         enum bpf_prog_type prog_type = resolve_prog_type(prog);
17392         struct bpf_insn *insn = prog->insnsi;
17393         const struct bpf_func_proto *fn;
17394         const int insn_cnt = prog->len;
17395         const struct bpf_map_ops *ops;
17396         struct bpf_insn_aux_data *aux;
17397         struct bpf_insn insn_buf[16];
17398         struct bpf_prog *new_prog;
17399         struct bpf_map *map_ptr;
17400         int i, ret, cnt, delta = 0;
17401
17402         for (i = 0; i < insn_cnt; i++, insn++) {
17403                 /* Make divide-by-zero exceptions impossible. */
17404                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
17405                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
17406                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
17407                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
17408                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
17409                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
17410                         struct bpf_insn *patchlet;
17411                         struct bpf_insn chk_and_div[] = {
17412                                 /* [R,W]x div 0 -> 0 */
17413                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
17414                                              BPF_JNE | BPF_K, insn->src_reg,
17415                                              0, 2, 0),
17416                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
17417                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
17418                                 *insn,
17419                         };
17420                         struct bpf_insn chk_and_mod[] = {
17421                                 /* [R,W]x mod 0 -> [R,W]x */
17422                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
17423                                              BPF_JEQ | BPF_K, insn->src_reg,
17424                                              0, 1 + (is64 ? 0 : 1), 0),
17425                                 *insn,
17426                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
17427                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
17428                         };
17429
17430                         patchlet = isdiv ? chk_and_div : chk_and_mod;
17431                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
17432                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
17433
17434                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
17435                         if (!new_prog)
17436                                 return -ENOMEM;
17437
17438                         delta    += cnt - 1;
17439                         env->prog = prog = new_prog;
17440                         insn      = new_prog->insnsi + i + delta;
17441                         continue;
17442                 }
17443
17444                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
17445                 if (BPF_CLASS(insn->code) == BPF_LD &&
17446                     (BPF_MODE(insn->code) == BPF_ABS ||
17447                      BPF_MODE(insn->code) == BPF_IND)) {
17448                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
17449                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
17450                                 verbose(env, "bpf verifier is misconfigured\n");
17451                                 return -EINVAL;
17452                         }
17453
17454                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17455                         if (!new_prog)
17456                                 return -ENOMEM;
17457
17458                         delta    += cnt - 1;
17459                         env->prog = prog = new_prog;
17460                         insn      = new_prog->insnsi + i + delta;
17461                         continue;
17462                 }
17463
17464                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
17465                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
17466                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
17467                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
17468                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
17469                         struct bpf_insn *patch = &insn_buf[0];
17470                         bool issrc, isneg, isimm;
17471                         u32 off_reg;
17472
17473                         aux = &env->insn_aux_data[i + delta];
17474                         if (!aux->alu_state ||
17475                             aux->alu_state == BPF_ALU_NON_POINTER)
17476                                 continue;
17477
17478                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
17479                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
17480                                 BPF_ALU_SANITIZE_SRC;
17481                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
17482
17483                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
17484                         if (isimm) {
17485                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
17486                         } else {
17487                                 if (isneg)
17488                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
17489                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
17490                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
17491                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
17492                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
17493                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
17494                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
17495                         }
17496                         if (!issrc)
17497                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
17498                         insn->src_reg = BPF_REG_AX;
17499                         if (isneg)
17500                                 insn->code = insn->code == code_add ?
17501                                              code_sub : code_add;
17502                         *patch++ = *insn;
17503                         if (issrc && isneg && !isimm)
17504                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
17505                         cnt = patch - insn_buf;
17506
17507                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17508                         if (!new_prog)
17509                                 return -ENOMEM;
17510
17511                         delta    += cnt - 1;
17512                         env->prog = prog = new_prog;
17513                         insn      = new_prog->insnsi + i + delta;
17514                         continue;
17515                 }
17516
17517                 if (insn->code != (BPF_JMP | BPF_CALL))
17518                         continue;
17519                 if (insn->src_reg == BPF_PSEUDO_CALL)
17520                         continue;
17521                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17522                         ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
17523                         if (ret)
17524                                 return ret;
17525                         if (cnt == 0)
17526                                 continue;
17527
17528                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17529                         if (!new_prog)
17530                                 return -ENOMEM;
17531
17532                         delta    += cnt - 1;
17533                         env->prog = prog = new_prog;
17534                         insn      = new_prog->insnsi + i + delta;
17535                         continue;
17536                 }
17537
17538                 if (insn->imm == BPF_FUNC_get_route_realm)
17539                         prog->dst_needed = 1;
17540                 if (insn->imm == BPF_FUNC_get_prandom_u32)
17541                         bpf_user_rnd_init_once();
17542                 if (insn->imm == BPF_FUNC_override_return)
17543                         prog->kprobe_override = 1;
17544                 if (insn->imm == BPF_FUNC_tail_call) {
17545                         /* If we tail call into other programs, we
17546                          * cannot make any assumptions since they can
17547                          * be replaced dynamically during runtime in
17548                          * the program array.
17549                          */
17550                         prog->cb_access = 1;
17551                         if (!allow_tail_call_in_subprogs(env))
17552                                 prog->aux->stack_depth = MAX_BPF_STACK;
17553                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
17554
17555                         /* mark bpf_tail_call as different opcode to avoid
17556                          * conditional branch in the interpreter for every normal
17557                          * call and to prevent accidental JITing by JIT compiler
17558                          * that doesn't support bpf_tail_call yet
17559                          */
17560                         insn->imm = 0;
17561                         insn->code = BPF_JMP | BPF_TAIL_CALL;
17562
17563                         aux = &env->insn_aux_data[i + delta];
17564                         if (env->bpf_capable && !prog->blinding_requested &&
17565                             prog->jit_requested &&
17566                             !bpf_map_key_poisoned(aux) &&
17567                             !bpf_map_ptr_poisoned(aux) &&
17568                             !bpf_map_ptr_unpriv(aux)) {
17569                                 struct bpf_jit_poke_descriptor desc = {
17570                                         .reason = BPF_POKE_REASON_TAIL_CALL,
17571                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
17572                                         .tail_call.key = bpf_map_key_immediate(aux),
17573                                         .insn_idx = i + delta,
17574                                 };
17575
17576                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
17577                                 if (ret < 0) {
17578                                         verbose(env, "adding tail call poke descriptor failed\n");
17579                                         return ret;
17580                                 }
17581
17582                                 insn->imm = ret + 1;
17583                                 continue;
17584                         }
17585
17586                         if (!bpf_map_ptr_unpriv(aux))
17587                                 continue;
17588
17589                         /* instead of changing every JIT dealing with tail_call
17590                          * emit two extra insns:
17591                          * if (index >= max_entries) goto out;
17592                          * index &= array->index_mask;
17593                          * to avoid out-of-bounds cpu speculation
17594                          */
17595                         if (bpf_map_ptr_poisoned(aux)) {
17596                                 verbose(env, "tail_call abusing map_ptr\n");
17597                                 return -EINVAL;
17598                         }
17599
17600                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
17601                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
17602                                                   map_ptr->max_entries, 2);
17603                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
17604                                                     container_of(map_ptr,
17605                                                                  struct bpf_array,
17606                                                                  map)->index_mask);
17607                         insn_buf[2] = *insn;
17608                         cnt = 3;
17609                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17610                         if (!new_prog)
17611                                 return -ENOMEM;
17612
17613                         delta    += cnt - 1;
17614                         env->prog = prog = new_prog;
17615                         insn      = new_prog->insnsi + i + delta;
17616                         continue;
17617                 }
17618
17619                 if (insn->imm == BPF_FUNC_timer_set_callback) {
17620                         /* The verifier will process callback_fn as many times as necessary
17621                          * with different maps and the register states prepared by
17622                          * set_timer_callback_state will be accurate.
17623                          *
17624                          * The following use case is valid:
17625                          *   map1 is shared by prog1, prog2, prog3.
17626                          *   prog1 calls bpf_timer_init for some map1 elements
17627                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
17628                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
17629                          *   prog3 calls bpf_timer_start for some map1 elements.
17630                          *     Those that were not both bpf_timer_init-ed and
17631                          *     bpf_timer_set_callback-ed will return -EINVAL.
17632                          */
17633                         struct bpf_insn ld_addrs[2] = {
17634                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
17635                         };
17636
17637                         insn_buf[0] = ld_addrs[0];
17638                         insn_buf[1] = ld_addrs[1];
17639                         insn_buf[2] = *insn;
17640                         cnt = 3;
17641
17642                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17643                         if (!new_prog)
17644                                 return -ENOMEM;
17645
17646                         delta    += cnt - 1;
17647                         env->prog = prog = new_prog;
17648                         insn      = new_prog->insnsi + i + delta;
17649                         goto patch_call_imm;
17650                 }
17651
17652                 if (is_storage_get_function(insn->imm)) {
17653                         if (!env->prog->aux->sleepable ||
17654                             env->insn_aux_data[i + delta].storage_get_func_atomic)
17655                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
17656                         else
17657                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
17658                         insn_buf[1] = *insn;
17659                         cnt = 2;
17660
17661                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17662                         if (!new_prog)
17663                                 return -ENOMEM;
17664
17665                         delta += cnt - 1;
17666                         env->prog = prog = new_prog;
17667                         insn = new_prog->insnsi + i + delta;
17668                         goto patch_call_imm;
17669                 }
17670
17671                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
17672                  * and other inlining handlers are currently limited to 64 bit
17673                  * only.
17674                  */
17675                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
17676                     (insn->imm == BPF_FUNC_map_lookup_elem ||
17677                      insn->imm == BPF_FUNC_map_update_elem ||
17678                      insn->imm == BPF_FUNC_map_delete_elem ||
17679                      insn->imm == BPF_FUNC_map_push_elem   ||
17680                      insn->imm == BPF_FUNC_map_pop_elem    ||
17681                      insn->imm == BPF_FUNC_map_peek_elem   ||
17682                      insn->imm == BPF_FUNC_redirect_map    ||
17683                      insn->imm == BPF_FUNC_for_each_map_elem ||
17684                      insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
17685                         aux = &env->insn_aux_data[i + delta];
17686                         if (bpf_map_ptr_poisoned(aux))
17687                                 goto patch_call_imm;
17688
17689                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
17690                         ops = map_ptr->ops;
17691                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
17692                             ops->map_gen_lookup) {
17693                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
17694                                 if (cnt == -EOPNOTSUPP)
17695                                         goto patch_map_ops_generic;
17696                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
17697                                         verbose(env, "bpf verifier is misconfigured\n");
17698                                         return -EINVAL;
17699                                 }
17700
17701                                 new_prog = bpf_patch_insn_data(env, i + delta,
17702                                                                insn_buf, cnt);
17703                                 if (!new_prog)
17704                                         return -ENOMEM;
17705
17706                                 delta    += cnt - 1;
17707                                 env->prog = prog = new_prog;
17708                                 insn      = new_prog->insnsi + i + delta;
17709                                 continue;
17710                         }
17711
17712                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
17713                                      (void *(*)(struct bpf_map *map, void *key))NULL));
17714                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
17715                                      (long (*)(struct bpf_map *map, void *key))NULL));
17716                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
17717                                      (long (*)(struct bpf_map *map, void *key, void *value,
17718                                               u64 flags))NULL));
17719                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
17720                                      (long (*)(struct bpf_map *map, void *value,
17721                                               u64 flags))NULL));
17722                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
17723                                      (long (*)(struct bpf_map *map, void *value))NULL));
17724                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
17725                                      (long (*)(struct bpf_map *map, void *value))NULL));
17726                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
17727                                      (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
17728                         BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
17729                                      (long (*)(struct bpf_map *map,
17730                                               bpf_callback_t callback_fn,
17731                                               void *callback_ctx,
17732                                               u64 flags))NULL));
17733                         BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
17734                                      (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
17735
17736 patch_map_ops_generic:
17737                         switch (insn->imm) {
17738                         case BPF_FUNC_map_lookup_elem:
17739                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
17740                                 continue;
17741                         case BPF_FUNC_map_update_elem:
17742                                 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
17743                                 continue;
17744                         case BPF_FUNC_map_delete_elem:
17745                                 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
17746                                 continue;
17747                         case BPF_FUNC_map_push_elem:
17748                                 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
17749                                 continue;
17750                         case BPF_FUNC_map_pop_elem:
17751                                 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
17752                                 continue;
17753                         case BPF_FUNC_map_peek_elem:
17754                                 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
17755                                 continue;
17756                         case BPF_FUNC_redirect_map:
17757                                 insn->imm = BPF_CALL_IMM(ops->map_redirect);
17758                                 continue;
17759                         case BPF_FUNC_for_each_map_elem:
17760                                 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
17761                                 continue;
17762                         case BPF_FUNC_map_lookup_percpu_elem:
17763                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
17764                                 continue;
17765                         }
17766
17767                         goto patch_call_imm;
17768                 }
17769
17770                 /* Implement bpf_jiffies64 inline. */
17771                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
17772                     insn->imm == BPF_FUNC_jiffies64) {
17773                         struct bpf_insn ld_jiffies_addr[2] = {
17774                                 BPF_LD_IMM64(BPF_REG_0,
17775                                              (unsigned long)&jiffies),
17776                         };
17777
17778                         insn_buf[0] = ld_jiffies_addr[0];
17779                         insn_buf[1] = ld_jiffies_addr[1];
17780                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
17781                                                   BPF_REG_0, 0);
17782                         cnt = 3;
17783
17784                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
17785                                                        cnt);
17786                         if (!new_prog)
17787                                 return -ENOMEM;
17788
17789                         delta    += cnt - 1;
17790                         env->prog = prog = new_prog;
17791                         insn      = new_prog->insnsi + i + delta;
17792                         continue;
17793                 }
17794
17795                 /* Implement bpf_get_func_arg inline. */
17796                 if (prog_type == BPF_PROG_TYPE_TRACING &&
17797                     insn->imm == BPF_FUNC_get_func_arg) {
17798                         /* Load nr_args from ctx - 8 */
17799                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
17800                         insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
17801                         insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
17802                         insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
17803                         insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
17804                         insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
17805                         insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
17806                         insn_buf[7] = BPF_JMP_A(1);
17807                         insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
17808                         cnt = 9;
17809
17810                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17811                         if (!new_prog)
17812                                 return -ENOMEM;
17813
17814                         delta    += cnt - 1;
17815                         env->prog = prog = new_prog;
17816                         insn      = new_prog->insnsi + i + delta;
17817                         continue;
17818                 }
17819
17820                 /* Implement bpf_get_func_ret inline. */
17821                 if (prog_type == BPF_PROG_TYPE_TRACING &&
17822                     insn->imm == BPF_FUNC_get_func_ret) {
17823                         if (eatype == BPF_TRACE_FEXIT ||
17824                             eatype == BPF_MODIFY_RETURN) {
17825                                 /* Load nr_args from ctx - 8 */
17826                                 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
17827                                 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
17828                                 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
17829                                 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
17830                                 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
17831                                 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
17832                                 cnt = 6;
17833                         } else {
17834                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
17835                                 cnt = 1;
17836                         }
17837
17838                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17839                         if (!new_prog)
17840                                 return -ENOMEM;
17841
17842                         delta    += cnt - 1;
17843                         env->prog = prog = new_prog;
17844                         insn      = new_prog->insnsi + i + delta;
17845                         continue;
17846                 }
17847
17848                 /* Implement get_func_arg_cnt inline. */
17849                 if (prog_type == BPF_PROG_TYPE_TRACING &&
17850                     insn->imm == BPF_FUNC_get_func_arg_cnt) {
17851                         /* Load nr_args from ctx - 8 */
17852                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
17853
17854                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
17855                         if (!new_prog)
17856                                 return -ENOMEM;
17857
17858                         env->prog = prog = new_prog;
17859                         insn      = new_prog->insnsi + i + delta;
17860                         continue;
17861                 }
17862
17863                 /* Implement bpf_get_func_ip inline. */
17864                 if (prog_type == BPF_PROG_TYPE_TRACING &&
17865                     insn->imm == BPF_FUNC_get_func_ip) {
17866                         /* Load IP address from ctx - 16 */
17867                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
17868
17869                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
17870                         if (!new_prog)
17871                                 return -ENOMEM;
17872
17873                         env->prog = prog = new_prog;
17874                         insn      = new_prog->insnsi + i + delta;
17875                         continue;
17876                 }
17877
17878 patch_call_imm:
17879                 fn = env->ops->get_func_proto(insn->imm, env->prog);
17880                 /* all functions that have prototype and verifier allowed
17881                  * programs to call them, must be real in-kernel functions
17882                  */
17883                 if (!fn->func) {
17884                         verbose(env,
17885                                 "kernel subsystem misconfigured func %s#%d\n",
17886                                 func_id_name(insn->imm), insn->imm);
17887                         return -EFAULT;
17888                 }
17889                 insn->imm = fn->func - __bpf_call_base;
17890         }
17891
17892         /* Since poke tab is now finalized, publish aux to tracker. */
17893         for (i = 0; i < prog->aux->size_poke_tab; i++) {
17894                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
17895                 if (!map_ptr->ops->map_poke_track ||
17896                     !map_ptr->ops->map_poke_untrack ||
17897                     !map_ptr->ops->map_poke_run) {
17898                         verbose(env, "bpf verifier is misconfigured\n");
17899                         return -EINVAL;
17900                 }
17901
17902                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
17903                 if (ret < 0) {
17904                         verbose(env, "tracking tail call prog failed\n");
17905                         return ret;
17906                 }
17907         }
17908
17909         sort_kfunc_descs_by_imm(env->prog);
17910
17911         return 0;
17912 }
17913
17914 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
17915                                         int position,
17916                                         s32 stack_base,
17917                                         u32 callback_subprogno,
17918                                         u32 *cnt)
17919 {
17920         s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
17921         s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
17922         s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
17923         int reg_loop_max = BPF_REG_6;
17924         int reg_loop_cnt = BPF_REG_7;
17925         int reg_loop_ctx = BPF_REG_8;
17926
17927         struct bpf_prog *new_prog;
17928         u32 callback_start;
17929         u32 call_insn_offset;
17930         s32 callback_offset;
17931
17932         /* This represents an inlined version of bpf_iter.c:bpf_loop,
17933          * be careful to modify this code in sync.
17934          */
17935         struct bpf_insn insn_buf[] = {
17936                 /* Return error and jump to the end of the patch if
17937                  * expected number of iterations is too big.
17938                  */
17939                 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
17940                 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
17941                 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
17942                 /* spill R6, R7, R8 to use these as loop vars */
17943                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
17944                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
17945                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
17946                 /* initialize loop vars */
17947                 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
17948                 BPF_MOV32_IMM(reg_loop_cnt, 0),
17949                 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
17950                 /* loop header,
17951                  * if reg_loop_cnt >= reg_loop_max skip the loop body
17952                  */
17953                 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
17954                 /* callback call,
17955                  * correct callback offset would be set after patching
17956                  */
17957                 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
17958                 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
17959                 BPF_CALL_REL(0),
17960                 /* increment loop counter */
17961                 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
17962                 /* jump to loop header if callback returned 0 */
17963                 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
17964                 /* return value of bpf_loop,
17965                  * set R0 to the number of iterations
17966                  */
17967                 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
17968                 /* restore original values of R6, R7, R8 */
17969                 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
17970                 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
17971                 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
17972         };
17973
17974         *cnt = ARRAY_SIZE(insn_buf);
17975         new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
17976         if (!new_prog)
17977                 return new_prog;
17978
17979         /* callback start is known only after patching */
17980         callback_start = env->subprog_info[callback_subprogno].start;
17981         /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
17982         call_insn_offset = position + 12;
17983         callback_offset = callback_start - call_insn_offset - 1;
17984         new_prog->insnsi[call_insn_offset].imm = callback_offset;
17985
17986         return new_prog;
17987 }
17988
17989 static bool is_bpf_loop_call(struct bpf_insn *insn)
17990 {
17991         return insn->code == (BPF_JMP | BPF_CALL) &&
17992                 insn->src_reg == 0 &&
17993                 insn->imm == BPF_FUNC_loop;
17994 }
17995
17996 /* For all sub-programs in the program (including main) check
17997  * insn_aux_data to see if there are bpf_loop calls that require
17998  * inlining. If such calls are found the calls are replaced with a
17999  * sequence of instructions produced by `inline_bpf_loop` function and
18000  * subprog stack_depth is increased by the size of 3 registers.
18001  * This stack space is used to spill values of the R6, R7, R8.  These
18002  * registers are used to store the loop bound, counter and context
18003  * variables.
18004  */
18005 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18006 {
18007         struct bpf_subprog_info *subprogs = env->subprog_info;
18008         int i, cur_subprog = 0, cnt, delta = 0;
18009         struct bpf_insn *insn = env->prog->insnsi;
18010         int insn_cnt = env->prog->len;
18011         u16 stack_depth = subprogs[cur_subprog].stack_depth;
18012         u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18013         u16 stack_depth_extra = 0;
18014
18015         for (i = 0; i < insn_cnt; i++, insn++) {
18016                 struct bpf_loop_inline_state *inline_state =
18017                         &env->insn_aux_data[i + delta].loop_inline_state;
18018
18019                 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18020                         struct bpf_prog *new_prog;
18021
18022                         stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18023                         new_prog = inline_bpf_loop(env,
18024                                                    i + delta,
18025                                                    -(stack_depth + stack_depth_extra),
18026                                                    inline_state->callback_subprogno,
18027                                                    &cnt);
18028                         if (!new_prog)
18029                                 return -ENOMEM;
18030
18031                         delta     += cnt - 1;
18032                         env->prog  = new_prog;
18033                         insn       = new_prog->insnsi + i + delta;
18034                 }
18035
18036                 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
18037                         subprogs[cur_subprog].stack_depth += stack_depth_extra;
18038                         cur_subprog++;
18039                         stack_depth = subprogs[cur_subprog].stack_depth;
18040                         stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18041                         stack_depth_extra = 0;
18042                 }
18043         }
18044
18045         env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18046
18047         return 0;
18048 }
18049
18050 static void free_states(struct bpf_verifier_env *env)
18051 {
18052         struct bpf_verifier_state_list *sl, *sln;
18053         int i;
18054
18055         sl = env->free_list;
18056         while (sl) {
18057                 sln = sl->next;
18058                 free_verifier_state(&sl->state, false);
18059                 kfree(sl);
18060                 sl = sln;
18061         }
18062         env->free_list = NULL;
18063
18064         if (!env->explored_states)
18065                 return;
18066
18067         for (i = 0; i < state_htab_size(env); i++) {
18068                 sl = env->explored_states[i];
18069
18070                 while (sl) {
18071                         sln = sl->next;
18072                         free_verifier_state(&sl->state, false);
18073                         kfree(sl);
18074                         sl = sln;
18075                 }
18076                 env->explored_states[i] = NULL;
18077         }
18078 }
18079
18080 static int do_check_common(struct bpf_verifier_env *env, int subprog)
18081 {
18082         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18083         struct bpf_verifier_state *state;
18084         struct bpf_reg_state *regs;
18085         int ret, i;
18086
18087         env->prev_linfo = NULL;
18088         env->pass_cnt++;
18089
18090         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
18091         if (!state)
18092                 return -ENOMEM;
18093         state->curframe = 0;
18094         state->speculative = false;
18095         state->branches = 1;
18096         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
18097         if (!state->frame[0]) {
18098                 kfree(state);
18099                 return -ENOMEM;
18100         }
18101         env->cur_state = state;
18102         init_func_state(env, state->frame[0],
18103                         BPF_MAIN_FUNC /* callsite */,
18104                         0 /* frameno */,
18105                         subprog);
18106         state->first_insn_idx = env->subprog_info[subprog].start;
18107         state->last_insn_idx = -1;
18108
18109         regs = state->frame[state->curframe]->regs;
18110         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
18111                 ret = btf_prepare_func_args(env, subprog, regs);
18112                 if (ret)
18113                         goto out;
18114                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
18115                         if (regs[i].type == PTR_TO_CTX)
18116                                 mark_reg_known_zero(env, regs, i);
18117                         else if (regs[i].type == SCALAR_VALUE)
18118                                 mark_reg_unknown(env, regs, i);
18119                         else if (base_type(regs[i].type) == PTR_TO_MEM) {
18120                                 const u32 mem_size = regs[i].mem_size;
18121
18122                                 mark_reg_known_zero(env, regs, i);
18123                                 regs[i].mem_size = mem_size;
18124                                 regs[i].id = ++env->id_gen;
18125                         }
18126                 }
18127         } else {
18128                 /* 1st arg to a function */
18129                 regs[BPF_REG_1].type = PTR_TO_CTX;
18130                 mark_reg_known_zero(env, regs, BPF_REG_1);
18131                 ret = btf_check_subprog_arg_match(env, subprog, regs);
18132                 if (ret == -EFAULT)
18133                         /* unlikely verifier bug. abort.
18134                          * ret == 0 and ret < 0 are sadly acceptable for
18135                          * main() function due to backward compatibility.
18136                          * Like socket filter program may be written as:
18137                          * int bpf_prog(struct pt_regs *ctx)
18138                          * and never dereference that ctx in the program.
18139                          * 'struct pt_regs' is a type mismatch for socket
18140                          * filter that should be using 'struct __sk_buff'.
18141                          */
18142                         goto out;
18143         }
18144
18145         ret = do_check(env);
18146 out:
18147         /* check for NULL is necessary, since cur_state can be freed inside
18148          * do_check() under memory pressure.
18149          */
18150         if (env->cur_state) {
18151                 free_verifier_state(env->cur_state, true);
18152                 env->cur_state = NULL;
18153         }
18154         while (!pop_stack(env, NULL, NULL, false));
18155         if (!ret && pop_log)
18156                 bpf_vlog_reset(&env->log, 0);
18157         free_states(env);
18158         return ret;
18159 }
18160
18161 /* Verify all global functions in a BPF program one by one based on their BTF.
18162  * All global functions must pass verification. Otherwise the whole program is rejected.
18163  * Consider:
18164  * int bar(int);
18165  * int foo(int f)
18166  * {
18167  *    return bar(f);
18168  * }
18169  * int bar(int b)
18170  * {
18171  *    ...
18172  * }
18173  * foo() will be verified first for R1=any_scalar_value. During verification it
18174  * will be assumed that bar() already verified successfully and call to bar()
18175  * from foo() will be checked for type match only. Later bar() will be verified
18176  * independently to check that it's safe for R1=any_scalar_value.
18177  */
18178 static int do_check_subprogs(struct bpf_verifier_env *env)
18179 {
18180         struct bpf_prog_aux *aux = env->prog->aux;
18181         int i, ret;
18182
18183         if (!aux->func_info)
18184                 return 0;
18185
18186         for (i = 1; i < env->subprog_cnt; i++) {
18187                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
18188                         continue;
18189                 env->insn_idx = env->subprog_info[i].start;
18190                 WARN_ON_ONCE(env->insn_idx == 0);
18191                 ret = do_check_common(env, i);
18192                 if (ret) {
18193                         return ret;
18194                 } else if (env->log.level & BPF_LOG_LEVEL) {
18195                         verbose(env,
18196                                 "Func#%d is safe for any args that match its prototype\n",
18197                                 i);
18198                 }
18199         }
18200         return 0;
18201 }
18202
18203 static int do_check_main(struct bpf_verifier_env *env)
18204 {
18205         int ret;
18206
18207         env->insn_idx = 0;
18208         ret = do_check_common(env, 0);
18209         if (!ret)
18210                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18211         return ret;
18212 }
18213
18214
18215 static void print_verification_stats(struct bpf_verifier_env *env)
18216 {
18217         int i;
18218
18219         if (env->log.level & BPF_LOG_STATS) {
18220                 verbose(env, "verification time %lld usec\n",
18221                         div_u64(env->verification_time, 1000));
18222                 verbose(env, "stack depth ");
18223                 for (i = 0; i < env->subprog_cnt; i++) {
18224                         u32 depth = env->subprog_info[i].stack_depth;
18225
18226                         verbose(env, "%d", depth);
18227                         if (i + 1 < env->subprog_cnt)
18228                                 verbose(env, "+");
18229                 }
18230                 verbose(env, "\n");
18231         }
18232         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
18233                 "total_states %d peak_states %d mark_read %d\n",
18234                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
18235                 env->max_states_per_insn, env->total_states,
18236                 env->peak_states, env->longest_mark_read_walk);
18237 }
18238
18239 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
18240 {
18241         const struct btf_type *t, *func_proto;
18242         const struct bpf_struct_ops *st_ops;
18243         const struct btf_member *member;
18244         struct bpf_prog *prog = env->prog;
18245         u32 btf_id, member_idx;
18246         const char *mname;
18247
18248         if (!prog->gpl_compatible) {
18249                 verbose(env, "struct ops programs must have a GPL compatible license\n");
18250                 return -EINVAL;
18251         }
18252
18253         btf_id = prog->aux->attach_btf_id;
18254         st_ops = bpf_struct_ops_find(btf_id);
18255         if (!st_ops) {
18256                 verbose(env, "attach_btf_id %u is not a supported struct\n",
18257                         btf_id);
18258                 return -ENOTSUPP;
18259         }
18260
18261         t = st_ops->type;
18262         member_idx = prog->expected_attach_type;
18263         if (member_idx >= btf_type_vlen(t)) {
18264                 verbose(env, "attach to invalid member idx %u of struct %s\n",
18265                         member_idx, st_ops->name);
18266                 return -EINVAL;
18267         }
18268
18269         member = &btf_type_member(t)[member_idx];
18270         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
18271         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
18272                                                NULL);
18273         if (!func_proto) {
18274                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
18275                         mname, member_idx, st_ops->name);
18276                 return -EINVAL;
18277         }
18278
18279         if (st_ops->check_member) {
18280                 int err = st_ops->check_member(t, member, prog);
18281
18282                 if (err) {
18283                         verbose(env, "attach to unsupported member %s of struct %s\n",
18284                                 mname, st_ops->name);
18285                         return err;
18286                 }
18287         }
18288
18289         prog->aux->attach_func_proto = func_proto;
18290         prog->aux->attach_func_name = mname;
18291         env->ops = st_ops->verifier_ops;
18292
18293         return 0;
18294 }
18295 #define SECURITY_PREFIX "security_"
18296
18297 static int check_attach_modify_return(unsigned long addr, const char *func_name)
18298 {
18299         if (within_error_injection_list(addr) ||
18300             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
18301                 return 0;
18302
18303         return -EINVAL;
18304 }
18305
18306 /* list of non-sleepable functions that are otherwise on
18307  * ALLOW_ERROR_INJECTION list
18308  */
18309 BTF_SET_START(btf_non_sleepable_error_inject)
18310 /* Three functions below can be called from sleepable and non-sleepable context.
18311  * Assume non-sleepable from bpf safety point of view.
18312  */
18313 BTF_ID(func, __filemap_add_folio)
18314 BTF_ID(func, should_fail_alloc_page)
18315 BTF_ID(func, should_failslab)
18316 BTF_SET_END(btf_non_sleepable_error_inject)
18317
18318 static int check_non_sleepable_error_inject(u32 btf_id)
18319 {
18320         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
18321 }
18322
18323 int bpf_check_attach_target(struct bpf_verifier_log *log,
18324                             const struct bpf_prog *prog,
18325                             const struct bpf_prog *tgt_prog,
18326                             u32 btf_id,
18327                             struct bpf_attach_target_info *tgt_info)
18328 {
18329         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
18330         const char prefix[] = "btf_trace_";
18331         int ret = 0, subprog = -1, i;
18332         const struct btf_type *t;
18333         bool conservative = true;
18334         const char *tname;
18335         struct btf *btf;
18336         long addr = 0;
18337         struct module *mod = NULL;
18338
18339         if (!btf_id) {
18340                 bpf_log(log, "Tracing programs must provide btf_id\n");
18341                 return -EINVAL;
18342         }
18343         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
18344         if (!btf) {
18345                 bpf_log(log,
18346                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
18347                 return -EINVAL;
18348         }
18349         t = btf_type_by_id(btf, btf_id);
18350         if (!t) {
18351                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
18352                 return -EINVAL;
18353         }
18354         tname = btf_name_by_offset(btf, t->name_off);
18355         if (!tname) {
18356                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
18357                 return -EINVAL;
18358         }
18359         if (tgt_prog) {
18360                 struct bpf_prog_aux *aux = tgt_prog->aux;
18361
18362                 if (bpf_prog_is_dev_bound(prog->aux) &&
18363                     !bpf_prog_dev_bound_match(prog, tgt_prog)) {
18364                         bpf_log(log, "Target program bound device mismatch");
18365                         return -EINVAL;
18366                 }
18367
18368                 for (i = 0; i < aux->func_info_cnt; i++)
18369                         if (aux->func_info[i].type_id == btf_id) {
18370                                 subprog = i;
18371                                 break;
18372                         }
18373                 if (subprog == -1) {
18374                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
18375                         return -EINVAL;
18376                 }
18377                 conservative = aux->func_info_aux[subprog].unreliable;
18378                 if (prog_extension) {
18379                         if (conservative) {
18380                                 bpf_log(log,
18381                                         "Cannot replace static functions\n");
18382                                 return -EINVAL;
18383                         }
18384                         if (!prog->jit_requested) {
18385                                 bpf_log(log,
18386                                         "Extension programs should be JITed\n");
18387                                 return -EINVAL;
18388                         }
18389                 }
18390                 if (!tgt_prog->jited) {
18391                         bpf_log(log, "Can attach to only JITed progs\n");
18392                         return -EINVAL;
18393                 }
18394                 if (tgt_prog->type == prog->type) {
18395                         /* Cannot fentry/fexit another fentry/fexit program.
18396                          * Cannot attach program extension to another extension.
18397                          * It's ok to attach fentry/fexit to extension program.
18398                          */
18399                         bpf_log(log, "Cannot recursively attach\n");
18400                         return -EINVAL;
18401                 }
18402                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
18403                     prog_extension &&
18404                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
18405                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
18406                         /* Program extensions can extend all program types
18407                          * except fentry/fexit. The reason is the following.
18408                          * The fentry/fexit programs are used for performance
18409                          * analysis, stats and can be attached to any program
18410                          * type except themselves. When extension program is
18411                          * replacing XDP function it is necessary to allow
18412                          * performance analysis of all functions. Both original
18413                          * XDP program and its program extension. Hence
18414                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
18415                          * allowed. If extending of fentry/fexit was allowed it
18416                          * would be possible to create long call chain
18417                          * fentry->extension->fentry->extension beyond
18418                          * reasonable stack size. Hence extending fentry is not
18419                          * allowed.
18420                          */
18421                         bpf_log(log, "Cannot extend fentry/fexit\n");
18422                         return -EINVAL;
18423                 }
18424         } else {
18425                 if (prog_extension) {
18426                         bpf_log(log, "Cannot replace kernel functions\n");
18427                         return -EINVAL;
18428                 }
18429         }
18430
18431         switch (prog->expected_attach_type) {
18432         case BPF_TRACE_RAW_TP:
18433                 if (tgt_prog) {
18434                         bpf_log(log,
18435                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
18436                         return -EINVAL;
18437                 }
18438                 if (!btf_type_is_typedef(t)) {
18439                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
18440                                 btf_id);
18441                         return -EINVAL;
18442                 }
18443                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
18444                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
18445                                 btf_id, tname);
18446                         return -EINVAL;
18447                 }
18448                 tname += sizeof(prefix) - 1;
18449                 t = btf_type_by_id(btf, t->type);
18450                 if (!btf_type_is_ptr(t))
18451                         /* should never happen in valid vmlinux build */
18452                         return -EINVAL;
18453                 t = btf_type_by_id(btf, t->type);
18454                 if (!btf_type_is_func_proto(t))
18455                         /* should never happen in valid vmlinux build */
18456                         return -EINVAL;
18457
18458                 break;
18459         case BPF_TRACE_ITER:
18460                 if (!btf_type_is_func(t)) {
18461                         bpf_log(log, "attach_btf_id %u is not a function\n",
18462                                 btf_id);
18463                         return -EINVAL;
18464                 }
18465                 t = btf_type_by_id(btf, t->type);
18466                 if (!btf_type_is_func_proto(t))
18467                         return -EINVAL;
18468                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
18469                 if (ret)
18470                         return ret;
18471                 break;
18472         default:
18473                 if (!prog_extension)
18474                         return -EINVAL;
18475                 fallthrough;
18476         case BPF_MODIFY_RETURN:
18477         case BPF_LSM_MAC:
18478         case BPF_LSM_CGROUP:
18479         case BPF_TRACE_FENTRY:
18480         case BPF_TRACE_FEXIT:
18481                 if (!btf_type_is_func(t)) {
18482                         bpf_log(log, "attach_btf_id %u is not a function\n",
18483                                 btf_id);
18484                         return -EINVAL;
18485                 }
18486                 if (prog_extension &&
18487                     btf_check_type_match(log, prog, btf, t))
18488                         return -EINVAL;
18489                 t = btf_type_by_id(btf, t->type);
18490                 if (!btf_type_is_func_proto(t))
18491                         return -EINVAL;
18492
18493                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
18494                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
18495                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
18496                         return -EINVAL;
18497
18498                 if (tgt_prog && conservative)
18499                         t = NULL;
18500
18501                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
18502                 if (ret < 0)
18503                         return ret;
18504
18505                 if (tgt_prog) {
18506                         if (subprog == 0)
18507                                 addr = (long) tgt_prog->bpf_func;
18508                         else
18509                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
18510                 } else {
18511                         if (btf_is_module(btf)) {
18512                                 mod = btf_try_get_module(btf);
18513                                 if (mod)
18514                                         addr = find_kallsyms_symbol_value(mod, tname);
18515                                 else
18516                                         addr = 0;
18517                         } else {
18518                                 addr = kallsyms_lookup_name(tname);
18519                         }
18520                         if (!addr) {
18521                                 module_put(mod);
18522                                 bpf_log(log,
18523                                         "The address of function %s cannot be found\n",
18524                                         tname);
18525                                 return -ENOENT;
18526                         }
18527                 }
18528
18529                 if (prog->aux->sleepable) {
18530                         ret = -EINVAL;
18531                         switch (prog->type) {
18532                         case BPF_PROG_TYPE_TRACING:
18533
18534                                 /* fentry/fexit/fmod_ret progs can be sleepable if they are
18535                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
18536                                  */
18537                                 if (!check_non_sleepable_error_inject(btf_id) &&
18538                                     within_error_injection_list(addr))
18539                                         ret = 0;
18540                                 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
18541                                  * in the fmodret id set with the KF_SLEEPABLE flag.
18542                                  */
18543                                 else {
18544                                         u32 *flags = btf_kfunc_is_modify_return(btf, btf_id);
18545
18546                                         if (flags && (*flags & KF_SLEEPABLE))
18547                                                 ret = 0;
18548                                 }
18549                                 break;
18550                         case BPF_PROG_TYPE_LSM:
18551                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
18552                                  * Only some of them are sleepable.
18553                                  */
18554                                 if (bpf_lsm_is_sleepable_hook(btf_id))
18555                                         ret = 0;
18556                                 break;
18557                         default:
18558                                 break;
18559                         }
18560                         if (ret) {
18561                                 module_put(mod);
18562                                 bpf_log(log, "%s is not sleepable\n", tname);
18563                                 return ret;
18564                         }
18565                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
18566                         if (tgt_prog) {
18567                                 module_put(mod);
18568                                 bpf_log(log, "can't modify return codes of BPF programs\n");
18569                                 return -EINVAL;
18570                         }
18571                         ret = -EINVAL;
18572                         if (btf_kfunc_is_modify_return(btf, btf_id) ||
18573                             !check_attach_modify_return(addr, tname))
18574                                 ret = 0;
18575                         if (ret) {
18576                                 module_put(mod);
18577                                 bpf_log(log, "%s() is not modifiable\n", tname);
18578                                 return ret;
18579                         }
18580                 }
18581
18582                 break;
18583         }
18584         tgt_info->tgt_addr = addr;
18585         tgt_info->tgt_name = tname;
18586         tgt_info->tgt_type = t;
18587         tgt_info->tgt_mod = mod;
18588         return 0;
18589 }
18590
18591 BTF_SET_START(btf_id_deny)
18592 BTF_ID_UNUSED
18593 #ifdef CONFIG_SMP
18594 BTF_ID(func, migrate_disable)
18595 BTF_ID(func, migrate_enable)
18596 #endif
18597 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
18598 BTF_ID(func, rcu_read_unlock_strict)
18599 #endif
18600 BTF_SET_END(btf_id_deny)
18601
18602 static bool can_be_sleepable(struct bpf_prog *prog)
18603 {
18604         if (prog->type == BPF_PROG_TYPE_TRACING) {
18605                 switch (prog->expected_attach_type) {
18606                 case BPF_TRACE_FENTRY:
18607                 case BPF_TRACE_FEXIT:
18608                 case BPF_MODIFY_RETURN:
18609                 case BPF_TRACE_ITER:
18610                         return true;
18611                 default:
18612                         return false;
18613                 }
18614         }
18615         return prog->type == BPF_PROG_TYPE_LSM ||
18616                prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
18617                prog->type == BPF_PROG_TYPE_STRUCT_OPS;
18618 }
18619
18620 static int check_attach_btf_id(struct bpf_verifier_env *env)
18621 {
18622         struct bpf_prog *prog = env->prog;
18623         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
18624         struct bpf_attach_target_info tgt_info = {};
18625         u32 btf_id = prog->aux->attach_btf_id;
18626         struct bpf_trampoline *tr;
18627         int ret;
18628         u64 key;
18629
18630         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
18631                 if (prog->aux->sleepable)
18632                         /* attach_btf_id checked to be zero already */
18633                         return 0;
18634                 verbose(env, "Syscall programs can only be sleepable\n");
18635                 return -EINVAL;
18636         }
18637
18638         if (prog->aux->sleepable && !can_be_sleepable(prog)) {
18639                 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
18640                 return -EINVAL;
18641         }
18642
18643         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
18644                 return check_struct_ops_btf_id(env);
18645
18646         if (prog->type != BPF_PROG_TYPE_TRACING &&
18647             prog->type != BPF_PROG_TYPE_LSM &&
18648             prog->type != BPF_PROG_TYPE_EXT)
18649                 return 0;
18650
18651         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
18652         if (ret)
18653                 return ret;
18654
18655         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
18656                 /* to make freplace equivalent to their targets, they need to
18657                  * inherit env->ops and expected_attach_type for the rest of the
18658                  * verification
18659                  */
18660                 env->ops = bpf_verifier_ops[tgt_prog->type];
18661                 prog->expected_attach_type = tgt_prog->expected_attach_type;
18662         }
18663
18664         /* store info about the attachment target that will be used later */
18665         prog->aux->attach_func_proto = tgt_info.tgt_type;
18666         prog->aux->attach_func_name = tgt_info.tgt_name;
18667         prog->aux->mod = tgt_info.tgt_mod;
18668
18669         if (tgt_prog) {
18670                 prog->aux->saved_dst_prog_type = tgt_prog->type;
18671                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
18672         }
18673
18674         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
18675                 prog->aux->attach_btf_trace = true;
18676                 return 0;
18677         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
18678                 if (!bpf_iter_prog_supported(prog))
18679                         return -EINVAL;
18680                 return 0;
18681         }
18682
18683         if (prog->type == BPF_PROG_TYPE_LSM) {
18684                 ret = bpf_lsm_verify_prog(&env->log, prog);
18685                 if (ret < 0)
18686                         return ret;
18687         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
18688                    btf_id_set_contains(&btf_id_deny, btf_id)) {
18689                 return -EINVAL;
18690         }
18691
18692         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
18693         tr = bpf_trampoline_get(key, &tgt_info);
18694         if (!tr)
18695                 return -ENOMEM;
18696
18697         prog->aux->dst_trampoline = tr;
18698         return 0;
18699 }
18700
18701 struct btf *bpf_get_btf_vmlinux(void)
18702 {
18703         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
18704                 mutex_lock(&bpf_verifier_lock);
18705                 if (!btf_vmlinux)
18706                         btf_vmlinux = btf_parse_vmlinux();
18707                 mutex_unlock(&bpf_verifier_lock);
18708         }
18709         return btf_vmlinux;
18710 }
18711
18712 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
18713 {
18714         u64 start_time = ktime_get_ns();
18715         struct bpf_verifier_env *env;
18716         int i, len, ret = -EINVAL, err;
18717         u32 log_true_size;
18718         bool is_priv;
18719
18720         /* no program is valid */
18721         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
18722                 return -EINVAL;
18723
18724         /* 'struct bpf_verifier_env' can be global, but since it's not small,
18725          * allocate/free it every time bpf_check() is called
18726          */
18727         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
18728         if (!env)
18729                 return -ENOMEM;
18730
18731         len = (*prog)->len;
18732         env->insn_aux_data =
18733                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
18734         ret = -ENOMEM;
18735         if (!env->insn_aux_data)
18736                 goto err_free_env;
18737         for (i = 0; i < len; i++)
18738                 env->insn_aux_data[i].orig_idx = i;
18739         env->prog = *prog;
18740         env->ops = bpf_verifier_ops[env->prog->type];
18741         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
18742         is_priv = bpf_capable();
18743
18744         bpf_get_btf_vmlinux();
18745
18746         /* grab the mutex to protect few globals used by verifier */
18747         if (!is_priv)
18748                 mutex_lock(&bpf_verifier_lock);
18749
18750         /* user could have requested verbose verifier output
18751          * and supplied buffer to store the verification trace
18752          */
18753         ret = bpf_vlog_init(&env->log, attr->log_level,
18754                             (char __user *) (unsigned long) attr->log_buf,
18755                             attr->log_size);
18756         if (ret)
18757                 goto err_unlock;
18758
18759         mark_verifier_state_clean(env);
18760
18761         if (IS_ERR(btf_vmlinux)) {
18762                 /* Either gcc or pahole or kernel are broken. */
18763                 verbose(env, "in-kernel BTF is malformed\n");
18764                 ret = PTR_ERR(btf_vmlinux);
18765                 goto skip_full_check;
18766         }
18767
18768         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
18769         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
18770                 env->strict_alignment = true;
18771         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
18772                 env->strict_alignment = false;
18773
18774         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
18775         env->allow_uninit_stack = bpf_allow_uninit_stack();
18776         env->bypass_spec_v1 = bpf_bypass_spec_v1();
18777         env->bypass_spec_v4 = bpf_bypass_spec_v4();
18778         env->bpf_capable = bpf_capable();
18779
18780         if (is_priv)
18781                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
18782
18783         env->explored_states = kvcalloc(state_htab_size(env),
18784                                        sizeof(struct bpf_verifier_state_list *),
18785                                        GFP_USER);
18786         ret = -ENOMEM;
18787         if (!env->explored_states)
18788                 goto skip_full_check;
18789
18790         ret = add_subprog_and_kfunc(env);
18791         if (ret < 0)
18792                 goto skip_full_check;
18793
18794         ret = check_subprogs(env);
18795         if (ret < 0)
18796                 goto skip_full_check;
18797
18798         ret = check_btf_info(env, attr, uattr);
18799         if (ret < 0)
18800                 goto skip_full_check;
18801
18802         ret = check_attach_btf_id(env);
18803         if (ret)
18804                 goto skip_full_check;
18805
18806         ret = resolve_pseudo_ldimm64(env);
18807         if (ret < 0)
18808                 goto skip_full_check;
18809
18810         if (bpf_prog_is_offloaded(env->prog->aux)) {
18811                 ret = bpf_prog_offload_verifier_prep(env->prog);
18812                 if (ret)
18813                         goto skip_full_check;
18814         }
18815
18816         ret = check_cfg(env);
18817         if (ret < 0)
18818                 goto skip_full_check;
18819
18820         ret = do_check_subprogs(env);
18821         ret = ret ?: do_check_main(env);
18822
18823         if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
18824                 ret = bpf_prog_offload_finalize(env);
18825
18826 skip_full_check:
18827         kvfree(env->explored_states);
18828
18829         if (ret == 0)
18830                 ret = check_max_stack_depth(env);
18831
18832         /* instruction rewrites happen after this point */
18833         if (ret == 0)
18834                 ret = optimize_bpf_loop(env);
18835
18836         if (is_priv) {
18837                 if (ret == 0)
18838                         opt_hard_wire_dead_code_branches(env);
18839                 if (ret == 0)
18840                         ret = opt_remove_dead_code(env);
18841                 if (ret == 0)
18842                         ret = opt_remove_nops(env);
18843         } else {
18844                 if (ret == 0)
18845                         sanitize_dead_code(env);
18846         }
18847
18848         if (ret == 0)
18849                 /* program is valid, convert *(u32*)(ctx + off) accesses */
18850                 ret = convert_ctx_accesses(env);
18851
18852         if (ret == 0)
18853                 ret = do_misc_fixups(env);
18854
18855         /* do 32-bit optimization after insn patching has done so those patched
18856          * insns could be handled correctly.
18857          */
18858         if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
18859                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
18860                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
18861                                                                      : false;
18862         }
18863
18864         if (ret == 0)
18865                 ret = fixup_call_args(env);
18866
18867         env->verification_time = ktime_get_ns() - start_time;
18868         print_verification_stats(env);
18869         env->prog->aux->verified_insns = env->insn_processed;
18870
18871         /* preserve original error even if log finalization is successful */
18872         err = bpf_vlog_finalize(&env->log, &log_true_size);
18873         if (err)
18874                 ret = err;
18875
18876         if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
18877             copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
18878                                   &log_true_size, sizeof(log_true_size))) {
18879                 ret = -EFAULT;
18880                 goto err_release_maps;
18881         }
18882
18883         if (ret)
18884                 goto err_release_maps;
18885
18886         if (env->used_map_cnt) {
18887                 /* if program passed verifier, update used_maps in bpf_prog_info */
18888                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
18889                                                           sizeof(env->used_maps[0]),
18890                                                           GFP_KERNEL);
18891
18892                 if (!env->prog->aux->used_maps) {
18893                         ret = -ENOMEM;
18894                         goto err_release_maps;
18895                 }
18896
18897                 memcpy(env->prog->aux->used_maps, env->used_maps,
18898                        sizeof(env->used_maps[0]) * env->used_map_cnt);
18899                 env->prog->aux->used_map_cnt = env->used_map_cnt;
18900         }
18901         if (env->used_btf_cnt) {
18902                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
18903                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
18904                                                           sizeof(env->used_btfs[0]),
18905                                                           GFP_KERNEL);
18906                 if (!env->prog->aux->used_btfs) {
18907                         ret = -ENOMEM;
18908                         goto err_release_maps;
18909                 }
18910
18911                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
18912                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
18913                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
18914         }
18915         if (env->used_map_cnt || env->used_btf_cnt) {
18916                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
18917                  * bpf_ld_imm64 instructions
18918                  */
18919                 convert_pseudo_ld_imm64(env);
18920         }
18921
18922         adjust_btf_func(env);
18923
18924 err_release_maps:
18925         if (!env->prog->aux->used_maps)
18926                 /* if we didn't copy map pointers into bpf_prog_info, release
18927                  * them now. Otherwise free_used_maps() will release them.
18928                  */
18929                 release_maps(env);
18930         if (!env->prog->aux->used_btfs)
18931                 release_btfs(env);
18932
18933         /* extension progs temporarily inherit the attach_type of their targets
18934            for verification purposes, so set it back to zero before returning
18935          */
18936         if (env->prog->type == BPF_PROG_TYPE_EXT)
18937                 env->prog->expected_attach_type = 0;
18938
18939         *prog = env->prog;
18940 err_unlock:
18941         if (!is_priv)
18942                 mutex_unlock(&bpf_verifier_lock);
18943         vfree(env->insn_aux_data);
18944 err_free_env:
18945         kfree(env);
18946         return ret;
18947 }
This page took 1.211574 seconds and 4 git commands to generate.