xref: /openbmc/linux/kernel/bpf/verifier.c (revision 9144f784f852f9a125cabe9927b986d909bfa439)
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  #include <linux/cpumask.h>
29  #include <net/xdp.h>
30  
31  #include "disasm.h"
32  
33  static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
34  #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
35  	[_id] = & _name ## _verifier_ops,
36  #define BPF_MAP_TYPE(_id, _ops)
37  #define BPF_LINK_TYPE(_id, _name)
38  #include <linux/bpf_types.h>
39  #undef BPF_PROG_TYPE
40  #undef BPF_MAP_TYPE
41  #undef BPF_LINK_TYPE
42  };
43  
44  /* bpf_check() is a static code analyzer that walks eBPF program
45   * instruction by instruction and updates register/stack state.
46   * All paths of conditional branches are analyzed until 'bpf_exit' insn.
47   *
48   * The first pass is depth-first-search to check that the program is a DAG.
49   * It rejects the following programs:
50   * - larger than BPF_MAXINSNS insns
51   * - if loop is present (detected via back-edge)
52   * - unreachable insns exist (shouldn't be a forest. program = one function)
53   * - out of bounds or malformed jumps
54   * The second pass is all possible path descent from the 1st insn.
55   * Since it's analyzing all paths through the program, the length of the
56   * analysis is limited to 64k insn, which may be hit even if total number of
57   * insn is less then 4K, but there are too many branches that change stack/regs.
58   * Number of 'branches to be analyzed' is limited to 1k
59   *
60   * On entry to each instruction, each register has a type, and the instruction
61   * changes the types of the registers depending on instruction semantics.
62   * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
63   * copied to R1.
64   *
65   * All registers are 64-bit.
66   * R0 - return register
67   * R1-R5 argument passing registers
68   * R6-R9 callee saved registers
69   * R10 - frame pointer read-only
70   *
71   * At the start of BPF program the register R1 contains a pointer to bpf_context
72   * and has type PTR_TO_CTX.
73   *
74   * Verifier tracks arithmetic operations on pointers in case:
75   *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
76   *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
77   * 1st insn copies R10 (which has FRAME_PTR) type into R1
78   * and 2nd arithmetic instruction is pattern matched to recognize
79   * that it wants to construct a pointer to some element within stack.
80   * So after 2nd insn, the register R1 has type PTR_TO_STACK
81   * (and -20 constant is saved for further stack bounds checking).
82   * Meaning that this reg is a pointer to stack plus known immediate constant.
83   *
84   * Most of the time the registers have SCALAR_VALUE type, which
85   * means the register has some value, but it's not a valid pointer.
86   * (like pointer plus pointer becomes SCALAR_VALUE type)
87   *
88   * When verifier sees load or store instructions the type of base register
89   * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
90   * four pointer types recognized by check_mem_access() function.
91   *
92   * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
93   * and the range of [ptr, ptr + map's value_size) is accessible.
94   *
95   * registers used to pass values to function calls are checked against
96   * function argument constraints.
97   *
98   * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
99   * It means that the register type passed to this function must be
100   * PTR_TO_STACK and it will be used inside the function as
101   * 'pointer to map element key'
102   *
103   * For example the argument constraints for bpf_map_lookup_elem():
104   *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
105   *   .arg1_type = ARG_CONST_MAP_PTR,
106   *   .arg2_type = ARG_PTR_TO_MAP_KEY,
107   *
108   * ret_type says that this function returns 'pointer to map elem value or null'
109   * function expects 1st argument to be a const pointer to 'struct bpf_map' and
110   * 2nd argument should be a pointer to stack, which will be used inside
111   * the helper function as a pointer to map element key.
112   *
113   * On the kernel side the helper function looks like:
114   * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
115   * {
116   *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
117   *    void *key = (void *) (unsigned long) r2;
118   *    void *value;
119   *
120   *    here kernel can access 'key' and 'map' pointers safely, knowing that
121   *    [key, key + map->key_size) bytes are valid and were initialized on
122   *    the stack of eBPF program.
123   * }
124   *
125   * Corresponding eBPF program may look like:
126   *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
127   *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
128   *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
129   *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
130   * here verifier looks at prototype of map_lookup_elem() and sees:
131   * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
132   * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
133   *
134   * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
135   * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
136   * and were initialized prior to this call.
137   * If it's ok, then verifier allows this BPF_CALL insn and looks at
138   * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
139   * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
140   * returns either pointer to map value or NULL.
141   *
142   * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
143   * insn, the register holding that pointer in the true branch changes state to
144   * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
145   * branch. See check_cond_jmp_op().
146   *
147   * After the call R0 is set to return type of the function and registers R1-R5
148   * are set to NOT_INIT to indicate that they are no longer readable.
149   *
150   * The following reference types represent a potential reference to a kernel
151   * resource which, after first being allocated, must be checked and freed by
152   * the BPF program:
153   * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
154   *
155   * When the verifier sees a helper call return a reference type, it allocates a
156   * pointer id for the reference and stores it in the current function state.
157   * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
158   * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
159   * passes through a NULL-check conditional. For the branch wherein the state is
160   * changed to CONST_IMM, the verifier releases the reference.
161   *
162   * For each helper function that allocates a reference, such as
163   * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
164   * bpf_sk_release(). When a reference type passes into the release function,
165   * the verifier also releases the reference. If any unchecked or unreleased
166   * reference remains at the end of the program, the verifier rejects it.
167   */
168  
169  /* verifier_state + insn_idx are pushed to stack when branch is encountered */
170  struct bpf_verifier_stack_elem {
171  	/* verifer state is 'st'
172  	 * before processing instruction 'insn_idx'
173  	 * and after processing instruction 'prev_insn_idx'
174  	 */
175  	struct bpf_verifier_state st;
176  	int insn_idx;
177  	int prev_insn_idx;
178  	struct bpf_verifier_stack_elem *next;
179  	/* length of verifier log at the time this state was pushed on stack */
180  	u32 log_pos;
181  };
182  
183  #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
184  #define BPF_COMPLEXITY_LIMIT_STATES	64
185  
186  #define BPF_MAP_KEY_POISON	(1ULL << 63)
187  #define BPF_MAP_KEY_SEEN	(1ULL << 62)
188  
189  #define BPF_MAP_PTR_UNPRIV	1UL
190  #define BPF_MAP_PTR_POISON	((void *)((0xeB9FUL << 1) +	\
191  					  POISON_POINTER_DELTA))
192  #define BPF_MAP_PTR(X)		((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
193  
194  static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
195  static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
196  static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
197  static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
198  static int ref_set_non_owning(struct bpf_verifier_env *env,
199  			      struct bpf_reg_state *reg);
200  static void specialize_kfunc(struct bpf_verifier_env *env,
201  			     u32 func_id, u16 offset, unsigned long *addr);
202  static bool is_trusted_reg(const struct bpf_reg_state *reg);
203  
bpf_map_ptr_poisoned(const struct bpf_insn_aux_data * aux)204  static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
205  {
206  	return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
207  }
208  
bpf_map_ptr_unpriv(const struct bpf_insn_aux_data * aux)209  static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
210  {
211  	return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
212  }
213  
bpf_map_ptr_store(struct bpf_insn_aux_data * aux,const struct bpf_map * map,bool unpriv)214  static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
215  			      const struct bpf_map *map, bool unpriv)
216  {
217  	BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
218  	unpriv |= bpf_map_ptr_unpriv(aux);
219  	aux->map_ptr_state = (unsigned long)map |
220  			     (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
221  }
222  
bpf_map_key_poisoned(const struct bpf_insn_aux_data * aux)223  static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
224  {
225  	return aux->map_key_state & BPF_MAP_KEY_POISON;
226  }
227  
bpf_map_key_unseen(const struct bpf_insn_aux_data * aux)228  static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
229  {
230  	return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
231  }
232  
bpf_map_key_immediate(const struct bpf_insn_aux_data * aux)233  static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
234  {
235  	return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
236  }
237  
bpf_map_key_store(struct bpf_insn_aux_data * aux,u64 state)238  static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
239  {
240  	bool poisoned = bpf_map_key_poisoned(aux);
241  
242  	aux->map_key_state = state | BPF_MAP_KEY_SEEN |
243  			     (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
244  }
245  
bpf_helper_call(const struct bpf_insn * insn)246  static bool bpf_helper_call(const struct bpf_insn *insn)
247  {
248  	return insn->code == (BPF_JMP | BPF_CALL) &&
249  	       insn->src_reg == 0;
250  }
251  
bpf_pseudo_call(const struct bpf_insn * insn)252  static bool bpf_pseudo_call(const struct bpf_insn *insn)
253  {
254  	return insn->code == (BPF_JMP | BPF_CALL) &&
255  	       insn->src_reg == BPF_PSEUDO_CALL;
256  }
257  
bpf_pseudo_kfunc_call(const struct bpf_insn * insn)258  static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
259  {
260  	return insn->code == (BPF_JMP | BPF_CALL) &&
261  	       insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
262  }
263  
264  struct bpf_call_arg_meta {
265  	struct bpf_map *map_ptr;
266  	bool raw_mode;
267  	bool pkt_access;
268  	u8 release_regno;
269  	int regno;
270  	int access_size;
271  	int mem_size;
272  	u64 msize_max_value;
273  	int ref_obj_id;
274  	int dynptr_id;
275  	int map_uid;
276  	int func_id;
277  	struct btf *btf;
278  	u32 btf_id;
279  	struct btf *ret_btf;
280  	u32 ret_btf_id;
281  	u32 subprogno;
282  	struct btf_field *kptr_field;
283  };
284  
285  struct bpf_kfunc_call_arg_meta {
286  	/* In parameters */
287  	struct btf *btf;
288  	u32 func_id;
289  	u32 kfunc_flags;
290  	const struct btf_type *func_proto;
291  	const char *func_name;
292  	/* Out parameters */
293  	u32 ref_obj_id;
294  	u8 release_regno;
295  	bool r0_rdonly;
296  	u32 ret_btf_id;
297  	u64 r0_size;
298  	u32 subprogno;
299  	struct {
300  		u64 value;
301  		bool found;
302  	} arg_constant;
303  
304  	/* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
305  	 * generally to pass info about user-defined local kptr types to later
306  	 * verification logic
307  	 *   bpf_obj_drop
308  	 *     Record the local kptr type to be drop'd
309  	 *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
310  	 *     Record the local kptr type to be refcount_incr'd and use
311  	 *     arg_owning_ref to determine whether refcount_acquire should be
312  	 *     fallible
313  	 */
314  	struct btf *arg_btf;
315  	u32 arg_btf_id;
316  	bool arg_owning_ref;
317  
318  	struct {
319  		struct btf_field *field;
320  	} arg_list_head;
321  	struct {
322  		struct btf_field *field;
323  	} arg_rbtree_root;
324  	struct {
325  		enum bpf_dynptr_type type;
326  		u32 id;
327  		u32 ref_obj_id;
328  	} initialized_dynptr;
329  	struct {
330  		u8 spi;
331  		u8 frameno;
332  	} iter;
333  	u64 mem_size;
334  };
335  
336  struct btf *btf_vmlinux;
337  
338  static DEFINE_MUTEX(bpf_verifier_lock);
339  
340  static const struct bpf_line_info *
find_linfo(const struct bpf_verifier_env * env,u32 insn_off)341  find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
342  {
343  	const struct bpf_line_info *linfo;
344  	const struct bpf_prog *prog;
345  	u32 i, nr_linfo;
346  
347  	prog = env->prog;
348  	nr_linfo = prog->aux->nr_linfo;
349  
350  	if (!nr_linfo || insn_off >= prog->len)
351  		return NULL;
352  
353  	linfo = prog->aux->linfo;
354  	for (i = 1; i < nr_linfo; i++)
355  		if (insn_off < linfo[i].insn_off)
356  			break;
357  
358  	return &linfo[i - 1];
359  }
360  
verbose(void * private_data,const char * fmt,...)361  __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
362  {
363  	struct bpf_verifier_env *env = private_data;
364  	va_list args;
365  
366  	if (!bpf_verifier_log_needed(&env->log))
367  		return;
368  
369  	va_start(args, fmt);
370  	bpf_verifier_vlog(&env->log, fmt, args);
371  	va_end(args);
372  }
373  
ltrim(const char * s)374  static const char *ltrim(const char *s)
375  {
376  	while (isspace(*s))
377  		s++;
378  
379  	return s;
380  }
381  
verbose_linfo(struct bpf_verifier_env * env,u32 insn_off,const char * prefix_fmt,...)382  __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
383  					 u32 insn_off,
384  					 const char *prefix_fmt, ...)
385  {
386  	const struct bpf_line_info *linfo;
387  
388  	if (!bpf_verifier_log_needed(&env->log))
389  		return;
390  
391  	linfo = find_linfo(env, insn_off);
392  	if (!linfo || linfo == env->prev_linfo)
393  		return;
394  
395  	if (prefix_fmt) {
396  		va_list args;
397  
398  		va_start(args, prefix_fmt);
399  		bpf_verifier_vlog(&env->log, prefix_fmt, args);
400  		va_end(args);
401  	}
402  
403  	verbose(env, "%s\n",
404  		ltrim(btf_name_by_offset(env->prog->aux->btf,
405  					 linfo->line_off)));
406  
407  	env->prev_linfo = linfo;
408  }
409  
verbose_invalid_scalar(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct tnum * range,const char * ctx,const char * reg_name)410  static void verbose_invalid_scalar(struct bpf_verifier_env *env,
411  				   struct bpf_reg_state *reg,
412  				   struct tnum *range, const char *ctx,
413  				   const char *reg_name)
414  {
415  	char tn_buf[48];
416  
417  	verbose(env, "At %s the register %s ", ctx, reg_name);
418  	if (!tnum_is_unknown(reg->var_off)) {
419  		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
420  		verbose(env, "has value %s", tn_buf);
421  	} else {
422  		verbose(env, "has unknown scalar value");
423  	}
424  	tnum_strn(tn_buf, sizeof(tn_buf), *range);
425  	verbose(env, " should have been in %s\n", tn_buf);
426  }
427  
type_is_pkt_pointer(enum bpf_reg_type type)428  static bool type_is_pkt_pointer(enum bpf_reg_type type)
429  {
430  	type = base_type(type);
431  	return type == PTR_TO_PACKET ||
432  	       type == PTR_TO_PACKET_META;
433  }
434  
type_is_sk_pointer(enum bpf_reg_type type)435  static bool type_is_sk_pointer(enum bpf_reg_type type)
436  {
437  	return type == PTR_TO_SOCKET ||
438  		type == PTR_TO_SOCK_COMMON ||
439  		type == PTR_TO_TCP_SOCK ||
440  		type == PTR_TO_XDP_SOCK;
441  }
442  
type_may_be_null(u32 type)443  static bool type_may_be_null(u32 type)
444  {
445  	return type & PTR_MAYBE_NULL;
446  }
447  
reg_not_null(const struct bpf_reg_state * reg)448  static bool reg_not_null(const struct bpf_reg_state *reg)
449  {
450  	enum bpf_reg_type type;
451  
452  	type = reg->type;
453  	if (type_may_be_null(type))
454  		return false;
455  
456  	type = base_type(type);
457  	return type == PTR_TO_SOCKET ||
458  		type == PTR_TO_TCP_SOCK ||
459  		type == PTR_TO_MAP_VALUE ||
460  		type == PTR_TO_MAP_KEY ||
461  		type == PTR_TO_SOCK_COMMON ||
462  		(type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
463  		type == PTR_TO_MEM;
464  }
465  
type_is_ptr_alloc_obj(u32 type)466  static bool type_is_ptr_alloc_obj(u32 type)
467  {
468  	return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
469  }
470  
type_is_non_owning_ref(u32 type)471  static bool type_is_non_owning_ref(u32 type)
472  {
473  	return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
474  }
475  
reg_btf_record(const struct bpf_reg_state * reg)476  static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
477  {
478  	struct btf_record *rec = NULL;
479  	struct btf_struct_meta *meta;
480  
481  	if (reg->type == PTR_TO_MAP_VALUE) {
482  		rec = reg->map_ptr->record;
483  	} else if (type_is_ptr_alloc_obj(reg->type)) {
484  		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
485  		if (meta)
486  			rec = meta->record;
487  	}
488  	return rec;
489  }
490  
subprog_is_global(const struct bpf_verifier_env * env,int subprog)491  static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
492  {
493  	struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
494  
495  	return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
496  }
497  
reg_may_point_to_spin_lock(const struct bpf_reg_state * reg)498  static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
499  {
500  	return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
501  }
502  
type_is_rdonly_mem(u32 type)503  static bool type_is_rdonly_mem(u32 type)
504  {
505  	return type & MEM_RDONLY;
506  }
507  
is_acquire_function(enum bpf_func_id func_id,const struct bpf_map * map)508  static bool is_acquire_function(enum bpf_func_id func_id,
509  				const struct bpf_map *map)
510  {
511  	enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
512  
513  	if (func_id == BPF_FUNC_sk_lookup_tcp ||
514  	    func_id == BPF_FUNC_sk_lookup_udp ||
515  	    func_id == BPF_FUNC_skc_lookup_tcp ||
516  	    func_id == BPF_FUNC_ringbuf_reserve ||
517  	    func_id == BPF_FUNC_kptr_xchg)
518  		return true;
519  
520  	if (func_id == BPF_FUNC_map_lookup_elem &&
521  	    (map_type == BPF_MAP_TYPE_SOCKMAP ||
522  	     map_type == BPF_MAP_TYPE_SOCKHASH))
523  		return true;
524  
525  	return false;
526  }
527  
is_ptr_cast_function(enum bpf_func_id func_id)528  static bool is_ptr_cast_function(enum bpf_func_id func_id)
529  {
530  	return func_id == BPF_FUNC_tcp_sock ||
531  		func_id == BPF_FUNC_sk_fullsock ||
532  		func_id == BPF_FUNC_skc_to_tcp_sock ||
533  		func_id == BPF_FUNC_skc_to_tcp6_sock ||
534  		func_id == BPF_FUNC_skc_to_udp6_sock ||
535  		func_id == BPF_FUNC_skc_to_mptcp_sock ||
536  		func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
537  		func_id == BPF_FUNC_skc_to_tcp_request_sock;
538  }
539  
is_dynptr_ref_function(enum bpf_func_id func_id)540  static bool is_dynptr_ref_function(enum bpf_func_id func_id)
541  {
542  	return func_id == BPF_FUNC_dynptr_data;
543  }
544  
545  static bool is_sync_callback_calling_kfunc(u32 btf_id);
546  
is_sync_callback_calling_function(enum bpf_func_id func_id)547  static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
548  {
549  	return func_id == BPF_FUNC_for_each_map_elem ||
550  	       func_id == BPF_FUNC_find_vma ||
551  	       func_id == BPF_FUNC_loop ||
552  	       func_id == BPF_FUNC_user_ringbuf_drain;
553  }
554  
is_async_callback_calling_function(enum bpf_func_id func_id)555  static bool is_async_callback_calling_function(enum bpf_func_id func_id)
556  {
557  	return func_id == BPF_FUNC_timer_set_callback;
558  }
559  
is_callback_calling_function(enum bpf_func_id func_id)560  static bool is_callback_calling_function(enum bpf_func_id func_id)
561  {
562  	return is_sync_callback_calling_function(func_id) ||
563  	       is_async_callback_calling_function(func_id);
564  }
565  
is_sync_callback_calling_insn(struct bpf_insn * insn)566  static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
567  {
568  	return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
569  	       (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
570  }
571  
is_storage_get_function(enum bpf_func_id func_id)572  static bool is_storage_get_function(enum bpf_func_id func_id)
573  {
574  	return func_id == BPF_FUNC_sk_storage_get ||
575  	       func_id == BPF_FUNC_inode_storage_get ||
576  	       func_id == BPF_FUNC_task_storage_get ||
577  	       func_id == BPF_FUNC_cgrp_storage_get;
578  }
579  
helper_multiple_ref_obj_use(enum bpf_func_id func_id,const struct bpf_map * map)580  static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
581  					const struct bpf_map *map)
582  {
583  	int ref_obj_uses = 0;
584  
585  	if (is_ptr_cast_function(func_id))
586  		ref_obj_uses++;
587  	if (is_acquire_function(func_id, map))
588  		ref_obj_uses++;
589  	if (is_dynptr_ref_function(func_id))
590  		ref_obj_uses++;
591  
592  	return ref_obj_uses > 1;
593  }
594  
is_cmpxchg_insn(const struct bpf_insn * insn)595  static bool is_cmpxchg_insn(const struct bpf_insn *insn)
596  {
597  	return BPF_CLASS(insn->code) == BPF_STX &&
598  	       BPF_MODE(insn->code) == BPF_ATOMIC &&
599  	       insn->imm == BPF_CMPXCHG;
600  }
601  
602  /* string representation of 'enum bpf_reg_type'
603   *
604   * Note that reg_type_str() can not appear more than once in a single verbose()
605   * statement.
606   */
reg_type_str(struct bpf_verifier_env * env,enum bpf_reg_type type)607  static const char *reg_type_str(struct bpf_verifier_env *env,
608  				enum bpf_reg_type type)
609  {
610  	char postfix[16] = {0}, prefix[64] = {0};
611  	static const char * const str[] = {
612  		[NOT_INIT]		= "?",
613  		[SCALAR_VALUE]		= "scalar",
614  		[PTR_TO_CTX]		= "ctx",
615  		[CONST_PTR_TO_MAP]	= "map_ptr",
616  		[PTR_TO_MAP_VALUE]	= "map_value",
617  		[PTR_TO_STACK]		= "fp",
618  		[PTR_TO_PACKET]		= "pkt",
619  		[PTR_TO_PACKET_META]	= "pkt_meta",
620  		[PTR_TO_PACKET_END]	= "pkt_end",
621  		[PTR_TO_FLOW_KEYS]	= "flow_keys",
622  		[PTR_TO_SOCKET]		= "sock",
623  		[PTR_TO_SOCK_COMMON]	= "sock_common",
624  		[PTR_TO_TCP_SOCK]	= "tcp_sock",
625  		[PTR_TO_TP_BUFFER]	= "tp_buffer",
626  		[PTR_TO_XDP_SOCK]	= "xdp_sock",
627  		[PTR_TO_BTF_ID]		= "ptr_",
628  		[PTR_TO_MEM]		= "mem",
629  		[PTR_TO_BUF]		= "buf",
630  		[PTR_TO_FUNC]		= "func",
631  		[PTR_TO_MAP_KEY]	= "map_key",
632  		[CONST_PTR_TO_DYNPTR]	= "dynptr_ptr",
633  	};
634  
635  	if (type & PTR_MAYBE_NULL) {
636  		if (base_type(type) == PTR_TO_BTF_ID)
637  			strncpy(postfix, "or_null_", 16);
638  		else
639  			strncpy(postfix, "_or_null", 16);
640  	}
641  
642  	snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
643  		 type & MEM_RDONLY ? "rdonly_" : "",
644  		 type & MEM_RINGBUF ? "ringbuf_" : "",
645  		 type & MEM_USER ? "user_" : "",
646  		 type & MEM_PERCPU ? "percpu_" : "",
647  		 type & MEM_RCU ? "rcu_" : "",
648  		 type & PTR_UNTRUSTED ? "untrusted_" : "",
649  		 type & PTR_TRUSTED ? "trusted_" : ""
650  	);
651  
652  	snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
653  		 prefix, str[base_type(type)], postfix);
654  	return env->tmp_str_buf;
655  }
656  
657  static char slot_type_char[] = {
658  	[STACK_INVALID]	= '?',
659  	[STACK_SPILL]	= 'r',
660  	[STACK_MISC]	= 'm',
661  	[STACK_ZERO]	= '0',
662  	[STACK_DYNPTR]	= 'd',
663  	[STACK_ITER]	= 'i',
664  };
665  
print_liveness(struct bpf_verifier_env * env,enum bpf_reg_liveness live)666  static void print_liveness(struct bpf_verifier_env *env,
667  			   enum bpf_reg_liveness live)
668  {
669  	if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
670  	    verbose(env, "_");
671  	if (live & REG_LIVE_READ)
672  		verbose(env, "r");
673  	if (live & REG_LIVE_WRITTEN)
674  		verbose(env, "w");
675  	if (live & REG_LIVE_DONE)
676  		verbose(env, "D");
677  }
678  
__get_spi(s32 off)679  static int __get_spi(s32 off)
680  {
681  	return (-off - 1) / BPF_REG_SIZE;
682  }
683  
func(struct bpf_verifier_env * env,const struct bpf_reg_state * reg)684  static struct bpf_func_state *func(struct bpf_verifier_env *env,
685  				   const struct bpf_reg_state *reg)
686  {
687  	struct bpf_verifier_state *cur = env->cur_state;
688  
689  	return cur->frame[reg->frameno];
690  }
691  
is_spi_bounds_valid(struct bpf_func_state * state,int spi,int nr_slots)692  static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
693  {
694         int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
695  
696         /* We need to check that slots between [spi - nr_slots + 1, spi] are
697  	* within [0, allocated_stack).
698  	*
699  	* Please note that the spi grows downwards. For example, a dynptr
700  	* takes the size of two stack slots; the first slot will be at
701  	* spi and the second slot will be at spi - 1.
702  	*/
703         return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
704  }
705  
stack_slot_obj_get_spi(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * obj_kind,int nr_slots)706  static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
707  			          const char *obj_kind, int nr_slots)
708  {
709  	int off, spi;
710  
711  	if (!tnum_is_const(reg->var_off)) {
712  		verbose(env, "%s has to be at a constant offset\n", obj_kind);
713  		return -EINVAL;
714  	}
715  
716  	off = reg->off + reg->var_off.value;
717  	if (off % BPF_REG_SIZE) {
718  		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
719  		return -EINVAL;
720  	}
721  
722  	spi = __get_spi(off);
723  	if (spi + 1 < nr_slots) {
724  		verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
725  		return -EINVAL;
726  	}
727  
728  	if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
729  		return -ERANGE;
730  	return spi;
731  }
732  
dynptr_get_spi(struct bpf_verifier_env * env,struct bpf_reg_state * reg)733  static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
734  {
735  	return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
736  }
737  
iter_get_spi(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int nr_slots)738  static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
739  {
740  	return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
741  }
742  
btf_type_name(const struct btf * btf,u32 id)743  static const char *btf_type_name(const struct btf *btf, u32 id)
744  {
745  	return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
746  }
747  
dynptr_type_str(enum bpf_dynptr_type type)748  static const char *dynptr_type_str(enum bpf_dynptr_type type)
749  {
750  	switch (type) {
751  	case BPF_DYNPTR_TYPE_LOCAL:
752  		return "local";
753  	case BPF_DYNPTR_TYPE_RINGBUF:
754  		return "ringbuf";
755  	case BPF_DYNPTR_TYPE_SKB:
756  		return "skb";
757  	case BPF_DYNPTR_TYPE_XDP:
758  		return "xdp";
759  	case BPF_DYNPTR_TYPE_INVALID:
760  		return "<invalid>";
761  	default:
762  		WARN_ONCE(1, "unknown dynptr type %d\n", type);
763  		return "<unknown>";
764  	}
765  }
766  
iter_type_str(const struct btf * btf,u32 btf_id)767  static const char *iter_type_str(const struct btf *btf, u32 btf_id)
768  {
769  	if (!btf || btf_id == 0)
770  		return "<invalid>";
771  
772  	/* we already validated that type is valid and has conforming name */
773  	return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
774  }
775  
iter_state_str(enum bpf_iter_state state)776  static const char *iter_state_str(enum bpf_iter_state state)
777  {
778  	switch (state) {
779  	case BPF_ITER_STATE_ACTIVE:
780  		return "active";
781  	case BPF_ITER_STATE_DRAINED:
782  		return "drained";
783  	case BPF_ITER_STATE_INVALID:
784  		return "<invalid>";
785  	default:
786  		WARN_ONCE(1, "unknown iter state %d\n", state);
787  		return "<unknown>";
788  	}
789  }
790  
mark_reg_scratched(struct bpf_verifier_env * env,u32 regno)791  static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
792  {
793  	env->scratched_regs |= 1U << regno;
794  }
795  
mark_stack_slot_scratched(struct bpf_verifier_env * env,u32 spi)796  static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
797  {
798  	env->scratched_stack_slots |= 1ULL << spi;
799  }
800  
reg_scratched(const struct bpf_verifier_env * env,u32 regno)801  static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
802  {
803  	return (env->scratched_regs >> regno) & 1;
804  }
805  
stack_slot_scratched(const struct bpf_verifier_env * env,u64 regno)806  static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
807  {
808  	return (env->scratched_stack_slots >> regno) & 1;
809  }
810  
verifier_state_scratched(const struct bpf_verifier_env * env)811  static bool verifier_state_scratched(const struct bpf_verifier_env *env)
812  {
813  	return env->scratched_regs || env->scratched_stack_slots;
814  }
815  
mark_verifier_state_clean(struct bpf_verifier_env * env)816  static void mark_verifier_state_clean(struct bpf_verifier_env *env)
817  {
818  	env->scratched_regs = 0U;
819  	env->scratched_stack_slots = 0ULL;
820  }
821  
822  /* Used for printing the entire verifier state. */
mark_verifier_state_scratched(struct bpf_verifier_env * env)823  static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
824  {
825  	env->scratched_regs = ~0U;
826  	env->scratched_stack_slots = ~0ULL;
827  }
828  
arg_to_dynptr_type(enum bpf_arg_type arg_type)829  static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
830  {
831  	switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
832  	case DYNPTR_TYPE_LOCAL:
833  		return BPF_DYNPTR_TYPE_LOCAL;
834  	case DYNPTR_TYPE_RINGBUF:
835  		return BPF_DYNPTR_TYPE_RINGBUF;
836  	case DYNPTR_TYPE_SKB:
837  		return BPF_DYNPTR_TYPE_SKB;
838  	case DYNPTR_TYPE_XDP:
839  		return BPF_DYNPTR_TYPE_XDP;
840  	default:
841  		return BPF_DYNPTR_TYPE_INVALID;
842  	}
843  }
844  
get_dynptr_type_flag(enum bpf_dynptr_type type)845  static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
846  {
847  	switch (type) {
848  	case BPF_DYNPTR_TYPE_LOCAL:
849  		return DYNPTR_TYPE_LOCAL;
850  	case BPF_DYNPTR_TYPE_RINGBUF:
851  		return DYNPTR_TYPE_RINGBUF;
852  	case BPF_DYNPTR_TYPE_SKB:
853  		return DYNPTR_TYPE_SKB;
854  	case BPF_DYNPTR_TYPE_XDP:
855  		return DYNPTR_TYPE_XDP;
856  	default:
857  		return 0;
858  	}
859  }
860  
dynptr_type_refcounted(enum bpf_dynptr_type type)861  static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
862  {
863  	return type == BPF_DYNPTR_TYPE_RINGBUF;
864  }
865  
866  static void __mark_dynptr_reg(struct bpf_reg_state *reg,
867  			      enum bpf_dynptr_type type,
868  			      bool first_slot, int dynptr_id);
869  
870  static void __mark_reg_not_init(const struct bpf_verifier_env *env,
871  				struct bpf_reg_state *reg);
872  
mark_dynptr_stack_regs(struct bpf_verifier_env * env,struct bpf_reg_state * sreg1,struct bpf_reg_state * sreg2,enum bpf_dynptr_type type)873  static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
874  				   struct bpf_reg_state *sreg1,
875  				   struct bpf_reg_state *sreg2,
876  				   enum bpf_dynptr_type type)
877  {
878  	int id = ++env->id_gen;
879  
880  	__mark_dynptr_reg(sreg1, type, true, id);
881  	__mark_dynptr_reg(sreg2, type, false, id);
882  }
883  
mark_dynptr_cb_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,enum bpf_dynptr_type type)884  static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
885  			       struct bpf_reg_state *reg,
886  			       enum bpf_dynptr_type type)
887  {
888  	__mark_dynptr_reg(reg, type, true, ++env->id_gen);
889  }
890  
891  static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
892  				        struct bpf_func_state *state, int spi);
893  
mark_stack_slots_dynptr(struct bpf_verifier_env * env,struct bpf_reg_state * reg,enum bpf_arg_type arg_type,int insn_idx,int clone_ref_obj_id)894  static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
895  				   enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
896  {
897  	struct bpf_func_state *state = func(env, reg);
898  	enum bpf_dynptr_type type;
899  	int spi, i, err;
900  
901  	spi = dynptr_get_spi(env, reg);
902  	if (spi < 0)
903  		return spi;
904  
905  	/* We cannot assume both spi and spi - 1 belong to the same dynptr,
906  	 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
907  	 * to ensure that for the following example:
908  	 *	[d1][d1][d2][d2]
909  	 * spi    3   2   1   0
910  	 * So marking spi = 2 should lead to destruction of both d1 and d2. In
911  	 * case they do belong to same dynptr, second call won't see slot_type
912  	 * as STACK_DYNPTR and will simply skip destruction.
913  	 */
914  	err = destroy_if_dynptr_stack_slot(env, state, spi);
915  	if (err)
916  		return err;
917  	err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
918  	if (err)
919  		return err;
920  
921  	for (i = 0; i < BPF_REG_SIZE; i++) {
922  		state->stack[spi].slot_type[i] = STACK_DYNPTR;
923  		state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
924  	}
925  
926  	type = arg_to_dynptr_type(arg_type);
927  	if (type == BPF_DYNPTR_TYPE_INVALID)
928  		return -EINVAL;
929  
930  	mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
931  			       &state->stack[spi - 1].spilled_ptr, type);
932  
933  	if (dynptr_type_refcounted(type)) {
934  		/* The id is used to track proper releasing */
935  		int id;
936  
937  		if (clone_ref_obj_id)
938  			id = clone_ref_obj_id;
939  		else
940  			id = acquire_reference_state(env, insn_idx);
941  
942  		if (id < 0)
943  			return id;
944  
945  		state->stack[spi].spilled_ptr.ref_obj_id = id;
946  		state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
947  	}
948  
949  	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
950  	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
951  
952  	return 0;
953  }
954  
invalidate_dynptr(struct bpf_verifier_env * env,struct bpf_func_state * state,int spi)955  static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
956  {
957  	int i;
958  
959  	for (i = 0; i < BPF_REG_SIZE; i++) {
960  		state->stack[spi].slot_type[i] = STACK_INVALID;
961  		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
962  	}
963  
964  	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
965  	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
966  
967  	/* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
968  	 *
969  	 * While we don't allow reading STACK_INVALID, it is still possible to
970  	 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
971  	 * helpers or insns can do partial read of that part without failing,
972  	 * but check_stack_range_initialized, check_stack_read_var_off, and
973  	 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
974  	 * the slot conservatively. Hence we need to prevent those liveness
975  	 * marking walks.
976  	 *
977  	 * This was not a problem before because STACK_INVALID is only set by
978  	 * default (where the default reg state has its reg->parent as NULL), or
979  	 * in clean_live_states after REG_LIVE_DONE (at which point
980  	 * mark_reg_read won't walk reg->parent chain), but not randomly during
981  	 * verifier state exploration (like we did above). Hence, for our case
982  	 * parentage chain will still be live (i.e. reg->parent may be
983  	 * non-NULL), while earlier reg->parent was NULL, so we need
984  	 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
985  	 * done later on reads or by mark_dynptr_read as well to unnecessary
986  	 * mark registers in verifier state.
987  	 */
988  	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
989  	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
990  }
991  
unmark_stack_slots_dynptr(struct bpf_verifier_env * env,struct bpf_reg_state * reg)992  static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
993  {
994  	struct bpf_func_state *state = func(env, reg);
995  	int spi, ref_obj_id, i;
996  
997  	spi = dynptr_get_spi(env, reg);
998  	if (spi < 0)
999  		return spi;
1000  
1001  	if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1002  		invalidate_dynptr(env, state, spi);
1003  		return 0;
1004  	}
1005  
1006  	ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
1007  
1008  	/* If the dynptr has a ref_obj_id, then we need to invalidate
1009  	 * two things:
1010  	 *
1011  	 * 1) Any dynptrs with a matching ref_obj_id (clones)
1012  	 * 2) Any slices derived from this dynptr.
1013  	 */
1014  
1015  	/* Invalidate any slices associated with this dynptr */
1016  	WARN_ON_ONCE(release_reference(env, ref_obj_id));
1017  
1018  	/* Invalidate any dynptr clones */
1019  	for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1020  		if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1021  			continue;
1022  
1023  		/* it should always be the case that if the ref obj id
1024  		 * matches then the stack slot also belongs to a
1025  		 * dynptr
1026  		 */
1027  		if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1028  			verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1029  			return -EFAULT;
1030  		}
1031  		if (state->stack[i].spilled_ptr.dynptr.first_slot)
1032  			invalidate_dynptr(env, state, i);
1033  	}
1034  
1035  	return 0;
1036  }
1037  
1038  static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1039  			       struct bpf_reg_state *reg);
1040  
mark_reg_invalid(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)1041  static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1042  {
1043  	if (!env->allow_ptr_leaks)
1044  		__mark_reg_not_init(env, reg);
1045  	else
1046  		__mark_reg_unknown(env, reg);
1047  }
1048  
destroy_if_dynptr_stack_slot(struct bpf_verifier_env * env,struct bpf_func_state * state,int spi)1049  static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1050  				        struct bpf_func_state *state, int spi)
1051  {
1052  	struct bpf_func_state *fstate;
1053  	struct bpf_reg_state *dreg;
1054  	int i, dynptr_id;
1055  
1056  	/* We always ensure that STACK_DYNPTR is never set partially,
1057  	 * hence just checking for slot_type[0] is enough. This is
1058  	 * different for STACK_SPILL, where it may be only set for
1059  	 * 1 byte, so code has to use is_spilled_reg.
1060  	 */
1061  	if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1062  		return 0;
1063  
1064  	/* Reposition spi to first slot */
1065  	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1066  		spi = spi + 1;
1067  
1068  	if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1069  		verbose(env, "cannot overwrite referenced dynptr\n");
1070  		return -EINVAL;
1071  	}
1072  
1073  	mark_stack_slot_scratched(env, spi);
1074  	mark_stack_slot_scratched(env, spi - 1);
1075  
1076  	/* Writing partially to one dynptr stack slot destroys both. */
1077  	for (i = 0; i < BPF_REG_SIZE; i++) {
1078  		state->stack[spi].slot_type[i] = STACK_INVALID;
1079  		state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1080  	}
1081  
1082  	dynptr_id = state->stack[spi].spilled_ptr.id;
1083  	/* Invalidate any slices associated with this dynptr */
1084  	bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1085  		/* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1086  		if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1087  			continue;
1088  		if (dreg->dynptr_id == dynptr_id)
1089  			mark_reg_invalid(env, dreg);
1090  	}));
1091  
1092  	/* Do not release reference state, we are destroying dynptr on stack,
1093  	 * not using some helper to release it. Just reset register.
1094  	 */
1095  	__mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1096  	__mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1097  
1098  	/* Same reason as unmark_stack_slots_dynptr above */
1099  	state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1100  	state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1101  
1102  	return 0;
1103  }
1104  
is_dynptr_reg_valid_uninit(struct bpf_verifier_env * env,struct bpf_reg_state * reg)1105  static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1106  {
1107  	int spi;
1108  
1109  	if (reg->type == CONST_PTR_TO_DYNPTR)
1110  		return false;
1111  
1112  	spi = dynptr_get_spi(env, reg);
1113  
1114  	/* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1115  	 * error because this just means the stack state hasn't been updated yet.
1116  	 * We will do check_mem_access to check and update stack bounds later.
1117  	 */
1118  	if (spi < 0 && spi != -ERANGE)
1119  		return false;
1120  
1121  	/* We don't need to check if the stack slots are marked by previous
1122  	 * dynptr initializations because we allow overwriting existing unreferenced
1123  	 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1124  	 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1125  	 * touching are completely destructed before we reinitialize them for a new
1126  	 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1127  	 * instead of delaying it until the end where the user will get "Unreleased
1128  	 * reference" error.
1129  	 */
1130  	return true;
1131  }
1132  
is_dynptr_reg_valid_init(struct bpf_verifier_env * env,struct bpf_reg_state * reg)1133  static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1134  {
1135  	struct bpf_func_state *state = func(env, reg);
1136  	int i, spi;
1137  
1138  	/* This already represents first slot of initialized bpf_dynptr.
1139  	 *
1140  	 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1141  	 * check_func_arg_reg_off's logic, so we don't need to check its
1142  	 * offset and alignment.
1143  	 */
1144  	if (reg->type == CONST_PTR_TO_DYNPTR)
1145  		return true;
1146  
1147  	spi = dynptr_get_spi(env, reg);
1148  	if (spi < 0)
1149  		return false;
1150  	if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1151  		return false;
1152  
1153  	for (i = 0; i < BPF_REG_SIZE; i++) {
1154  		if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1155  		    state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1156  			return false;
1157  	}
1158  
1159  	return true;
1160  }
1161  
is_dynptr_type_expected(struct bpf_verifier_env * env,struct bpf_reg_state * reg,enum bpf_arg_type arg_type)1162  static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1163  				    enum bpf_arg_type arg_type)
1164  {
1165  	struct bpf_func_state *state = func(env, reg);
1166  	enum bpf_dynptr_type dynptr_type;
1167  	int spi;
1168  
1169  	/* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1170  	if (arg_type == ARG_PTR_TO_DYNPTR)
1171  		return true;
1172  
1173  	dynptr_type = arg_to_dynptr_type(arg_type);
1174  	if (reg->type == CONST_PTR_TO_DYNPTR) {
1175  		return reg->dynptr.type == dynptr_type;
1176  	} else {
1177  		spi = dynptr_get_spi(env, reg);
1178  		if (spi < 0)
1179  			return false;
1180  		return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1181  	}
1182  }
1183  
1184  static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1185  
mark_stack_slots_iter(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int insn_idx,struct btf * btf,u32 btf_id,int nr_slots)1186  static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1187  				 struct bpf_reg_state *reg, int insn_idx,
1188  				 struct btf *btf, u32 btf_id, int nr_slots)
1189  {
1190  	struct bpf_func_state *state = func(env, reg);
1191  	int spi, i, j, id;
1192  
1193  	spi = iter_get_spi(env, reg, nr_slots);
1194  	if (spi < 0)
1195  		return spi;
1196  
1197  	id = acquire_reference_state(env, insn_idx);
1198  	if (id < 0)
1199  		return id;
1200  
1201  	for (i = 0; i < nr_slots; i++) {
1202  		struct bpf_stack_state *slot = &state->stack[spi - i];
1203  		struct bpf_reg_state *st = &slot->spilled_ptr;
1204  
1205  		__mark_reg_known_zero(st);
1206  		st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1207  		st->live |= REG_LIVE_WRITTEN;
1208  		st->ref_obj_id = i == 0 ? id : 0;
1209  		st->iter.btf = btf;
1210  		st->iter.btf_id = btf_id;
1211  		st->iter.state = BPF_ITER_STATE_ACTIVE;
1212  		st->iter.depth = 0;
1213  
1214  		for (j = 0; j < BPF_REG_SIZE; j++)
1215  			slot->slot_type[j] = STACK_ITER;
1216  
1217  		mark_stack_slot_scratched(env, spi - i);
1218  	}
1219  
1220  	return 0;
1221  }
1222  
unmark_stack_slots_iter(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int nr_slots)1223  static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1224  				   struct bpf_reg_state *reg, int nr_slots)
1225  {
1226  	struct bpf_func_state *state = func(env, reg);
1227  	int spi, i, j;
1228  
1229  	spi = iter_get_spi(env, reg, nr_slots);
1230  	if (spi < 0)
1231  		return spi;
1232  
1233  	for (i = 0; i < nr_slots; i++) {
1234  		struct bpf_stack_state *slot = &state->stack[spi - i];
1235  		struct bpf_reg_state *st = &slot->spilled_ptr;
1236  
1237  		if (i == 0)
1238  			WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1239  
1240  		__mark_reg_not_init(env, st);
1241  
1242  		/* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1243  		st->live |= REG_LIVE_WRITTEN;
1244  
1245  		for (j = 0; j < BPF_REG_SIZE; j++)
1246  			slot->slot_type[j] = STACK_INVALID;
1247  
1248  		mark_stack_slot_scratched(env, spi - i);
1249  	}
1250  
1251  	return 0;
1252  }
1253  
is_iter_reg_valid_uninit(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int nr_slots)1254  static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1255  				     struct bpf_reg_state *reg, int nr_slots)
1256  {
1257  	struct bpf_func_state *state = func(env, reg);
1258  	int spi, i, j;
1259  
1260  	/* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1261  	 * will do check_mem_access to check and update stack bounds later, so
1262  	 * return true for that case.
1263  	 */
1264  	spi = iter_get_spi(env, reg, nr_slots);
1265  	if (spi == -ERANGE)
1266  		return true;
1267  	if (spi < 0)
1268  		return false;
1269  
1270  	for (i = 0; i < nr_slots; i++) {
1271  		struct bpf_stack_state *slot = &state->stack[spi - i];
1272  
1273  		for (j = 0; j < BPF_REG_SIZE; j++)
1274  			if (slot->slot_type[j] == STACK_ITER)
1275  				return false;
1276  	}
1277  
1278  	return true;
1279  }
1280  
is_iter_reg_valid_init(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct btf * btf,u32 btf_id,int nr_slots)1281  static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1282  				   struct btf *btf, u32 btf_id, int nr_slots)
1283  {
1284  	struct bpf_func_state *state = func(env, reg);
1285  	int spi, i, j;
1286  
1287  	spi = iter_get_spi(env, reg, nr_slots);
1288  	if (spi < 0)
1289  		return false;
1290  
1291  	for (i = 0; i < nr_slots; i++) {
1292  		struct bpf_stack_state *slot = &state->stack[spi - i];
1293  		struct bpf_reg_state *st = &slot->spilled_ptr;
1294  
1295  		/* only main (first) slot has ref_obj_id set */
1296  		if (i == 0 && !st->ref_obj_id)
1297  			return false;
1298  		if (i != 0 && st->ref_obj_id)
1299  			return false;
1300  		if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1301  			return false;
1302  
1303  		for (j = 0; j < BPF_REG_SIZE; j++)
1304  			if (slot->slot_type[j] != STACK_ITER)
1305  				return false;
1306  	}
1307  
1308  	return true;
1309  }
1310  
1311  /* Check if given stack slot is "special":
1312   *   - spilled register state (STACK_SPILL);
1313   *   - dynptr state (STACK_DYNPTR);
1314   *   - iter state (STACK_ITER).
1315   */
is_stack_slot_special(const struct bpf_stack_state * stack)1316  static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1317  {
1318  	enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1319  
1320  	switch (type) {
1321  	case STACK_SPILL:
1322  	case STACK_DYNPTR:
1323  	case STACK_ITER:
1324  		return true;
1325  	case STACK_INVALID:
1326  	case STACK_MISC:
1327  	case STACK_ZERO:
1328  		return false;
1329  	default:
1330  		WARN_ONCE(1, "unknown stack slot type %d\n", type);
1331  		return true;
1332  	}
1333  }
1334  
1335  /* The reg state of a pointer or a bounded scalar was saved when
1336   * it was spilled to the stack.
1337   */
is_spilled_reg(const struct bpf_stack_state * stack)1338  static bool is_spilled_reg(const struct bpf_stack_state *stack)
1339  {
1340  	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1341  }
1342  
is_spilled_scalar_reg(const struct bpf_stack_state * stack)1343  static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1344  {
1345  	return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1346  	       stack->spilled_ptr.type == SCALAR_VALUE;
1347  }
1348  
scrub_spilled_slot(u8 * stype)1349  static void scrub_spilled_slot(u8 *stype)
1350  {
1351  	if (*stype != STACK_INVALID)
1352  		*stype = STACK_MISC;
1353  }
1354  
print_verifier_state(struct bpf_verifier_env * env,const struct bpf_func_state * state,bool print_all)1355  static void print_verifier_state(struct bpf_verifier_env *env,
1356  				 const struct bpf_func_state *state,
1357  				 bool print_all)
1358  {
1359  	const struct bpf_reg_state *reg;
1360  	enum bpf_reg_type t;
1361  	int i;
1362  
1363  	if (state->frameno)
1364  		verbose(env, " frame%d:", state->frameno);
1365  	for (i = 0; i < MAX_BPF_REG; i++) {
1366  		reg = &state->regs[i];
1367  		t = reg->type;
1368  		if (t == NOT_INIT)
1369  			continue;
1370  		if (!print_all && !reg_scratched(env, i))
1371  			continue;
1372  		verbose(env, " R%d", i);
1373  		print_liveness(env, reg->live);
1374  		verbose(env, "=");
1375  		if (t == SCALAR_VALUE && reg->precise)
1376  			verbose(env, "P");
1377  		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1378  		    tnum_is_const(reg->var_off)) {
1379  			/* reg->off should be 0 for SCALAR_VALUE */
1380  			verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1381  			verbose(env, "%lld", reg->var_off.value + reg->off);
1382  		} else {
1383  			const char *sep = "";
1384  
1385  			verbose(env, "%s", reg_type_str(env, t));
1386  			if (base_type(t) == PTR_TO_BTF_ID)
1387  				verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1388  			verbose(env, "(");
1389  /*
1390   * _a stands for append, was shortened to avoid multiline statements below.
1391   * This macro is used to output a comma separated list of attributes.
1392   */
1393  #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1394  
1395  			if (reg->id)
1396  				verbose_a("id=%d", reg->id);
1397  			if (reg->ref_obj_id)
1398  				verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1399  			if (type_is_non_owning_ref(reg->type))
1400  				verbose_a("%s", "non_own_ref");
1401  			if (t != SCALAR_VALUE)
1402  				verbose_a("off=%d", reg->off);
1403  			if (type_is_pkt_pointer(t))
1404  				verbose_a("r=%d", reg->range);
1405  			else if (base_type(t) == CONST_PTR_TO_MAP ||
1406  				 base_type(t) == PTR_TO_MAP_KEY ||
1407  				 base_type(t) == PTR_TO_MAP_VALUE)
1408  				verbose_a("ks=%d,vs=%d",
1409  					  reg->map_ptr->key_size,
1410  					  reg->map_ptr->value_size);
1411  			if (tnum_is_const(reg->var_off)) {
1412  				/* Typically an immediate SCALAR_VALUE, but
1413  				 * could be a pointer whose offset is too big
1414  				 * for reg->off
1415  				 */
1416  				verbose_a("imm=%llx", reg->var_off.value);
1417  			} else {
1418  				if (reg->smin_value != reg->umin_value &&
1419  				    reg->smin_value != S64_MIN)
1420  					verbose_a("smin=%lld", (long long)reg->smin_value);
1421  				if (reg->smax_value != reg->umax_value &&
1422  				    reg->smax_value != S64_MAX)
1423  					verbose_a("smax=%lld", (long long)reg->smax_value);
1424  				if (reg->umin_value != 0)
1425  					verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1426  				if (reg->umax_value != U64_MAX)
1427  					verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1428  				if (!tnum_is_unknown(reg->var_off)) {
1429  					char tn_buf[48];
1430  
1431  					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1432  					verbose_a("var_off=%s", tn_buf);
1433  				}
1434  				if (reg->s32_min_value != reg->smin_value &&
1435  				    reg->s32_min_value != S32_MIN)
1436  					verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1437  				if (reg->s32_max_value != reg->smax_value &&
1438  				    reg->s32_max_value != S32_MAX)
1439  					verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1440  				if (reg->u32_min_value != reg->umin_value &&
1441  				    reg->u32_min_value != U32_MIN)
1442  					verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1443  				if (reg->u32_max_value != reg->umax_value &&
1444  				    reg->u32_max_value != U32_MAX)
1445  					verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1446  			}
1447  #undef verbose_a
1448  
1449  			verbose(env, ")");
1450  		}
1451  	}
1452  	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1453  		char types_buf[BPF_REG_SIZE + 1];
1454  		bool valid = false;
1455  		int j;
1456  
1457  		for (j = 0; j < BPF_REG_SIZE; j++) {
1458  			if (state->stack[i].slot_type[j] != STACK_INVALID)
1459  				valid = true;
1460  			types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1461  		}
1462  		types_buf[BPF_REG_SIZE] = 0;
1463  		if (!valid)
1464  			continue;
1465  		if (!print_all && !stack_slot_scratched(env, i))
1466  			continue;
1467  		switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1468  		case STACK_SPILL:
1469  			reg = &state->stack[i].spilled_ptr;
1470  			t = reg->type;
1471  
1472  			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1473  			print_liveness(env, reg->live);
1474  			verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1475  			if (t == SCALAR_VALUE && reg->precise)
1476  				verbose(env, "P");
1477  			if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1478  				verbose(env, "%lld", reg->var_off.value + reg->off);
1479  			break;
1480  		case STACK_DYNPTR:
1481  			i += BPF_DYNPTR_NR_SLOTS - 1;
1482  			reg = &state->stack[i].spilled_ptr;
1483  
1484  			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1485  			print_liveness(env, reg->live);
1486  			verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1487  			if (reg->ref_obj_id)
1488  				verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1489  			break;
1490  		case STACK_ITER:
1491  			/* only main slot has ref_obj_id set; skip others */
1492  			reg = &state->stack[i].spilled_ptr;
1493  			if (!reg->ref_obj_id)
1494  				continue;
1495  
1496  			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1497  			print_liveness(env, reg->live);
1498  			verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1499  				iter_type_str(reg->iter.btf, reg->iter.btf_id),
1500  				reg->ref_obj_id, iter_state_str(reg->iter.state),
1501  				reg->iter.depth);
1502  			break;
1503  		case STACK_MISC:
1504  		case STACK_ZERO:
1505  		default:
1506  			reg = &state->stack[i].spilled_ptr;
1507  
1508  			for (j = 0; j < BPF_REG_SIZE; j++)
1509  				types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1510  			types_buf[BPF_REG_SIZE] = 0;
1511  
1512  			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1513  			print_liveness(env, reg->live);
1514  			verbose(env, "=%s", types_buf);
1515  			break;
1516  		}
1517  	}
1518  	if (state->acquired_refs && state->refs[0].id) {
1519  		verbose(env, " refs=%d", state->refs[0].id);
1520  		for (i = 1; i < state->acquired_refs; i++)
1521  			if (state->refs[i].id)
1522  				verbose(env, ",%d", state->refs[i].id);
1523  	}
1524  	if (state->in_callback_fn)
1525  		verbose(env, " cb");
1526  	if (state->in_async_callback_fn)
1527  		verbose(env, " async_cb");
1528  	verbose(env, "\n");
1529  	if (!print_all)
1530  		mark_verifier_state_clean(env);
1531  }
1532  
vlog_alignment(u32 pos)1533  static inline u32 vlog_alignment(u32 pos)
1534  {
1535  	return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1536  			BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1537  }
1538  
print_insn_state(struct bpf_verifier_env * env,const struct bpf_func_state * state)1539  static void print_insn_state(struct bpf_verifier_env *env,
1540  			     const struct bpf_func_state *state)
1541  {
1542  	if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1543  		/* remove new line character */
1544  		bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1545  		verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1546  	} else {
1547  		verbose(env, "%d:", env->insn_idx);
1548  	}
1549  	print_verifier_state(env, state, false);
1550  }
1551  
1552  /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1553   * small to hold src. This is different from krealloc since we don't want to preserve
1554   * the contents of dst.
1555   *
1556   * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1557   * not be allocated.
1558   */
copy_array(void * dst,const void * src,size_t n,size_t size,gfp_t flags)1559  static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1560  {
1561  	size_t alloc_bytes;
1562  	void *orig = dst;
1563  	size_t bytes;
1564  
1565  	if (ZERO_OR_NULL_PTR(src))
1566  		goto out;
1567  
1568  	if (unlikely(check_mul_overflow(n, size, &bytes)))
1569  		return NULL;
1570  
1571  	alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1572  	dst = krealloc(orig, alloc_bytes, flags);
1573  	if (!dst) {
1574  		kfree(orig);
1575  		return NULL;
1576  	}
1577  
1578  	memcpy(dst, src, bytes);
1579  out:
1580  	return dst ? dst : ZERO_SIZE_PTR;
1581  }
1582  
1583  /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1584   * small to hold new_n items. new items are zeroed out if the array grows.
1585   *
1586   * Contrary to krealloc_array, does not free arr if new_n is zero.
1587   */
realloc_array(void * arr,size_t old_n,size_t new_n,size_t size)1588  static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1589  {
1590  	size_t alloc_size;
1591  	void *new_arr;
1592  
1593  	if (!new_n || old_n == new_n)
1594  		goto out;
1595  
1596  	alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1597  	new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1598  	if (!new_arr) {
1599  		kfree(arr);
1600  		return NULL;
1601  	}
1602  	arr = new_arr;
1603  
1604  	if (new_n > old_n)
1605  		memset(arr + old_n * size, 0, (new_n - old_n) * size);
1606  
1607  out:
1608  	return arr ? arr : ZERO_SIZE_PTR;
1609  }
1610  
copy_reference_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1611  static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1612  {
1613  	dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1614  			       sizeof(struct bpf_reference_state), GFP_KERNEL);
1615  	if (!dst->refs)
1616  		return -ENOMEM;
1617  
1618  	dst->acquired_refs = src->acquired_refs;
1619  	return 0;
1620  }
1621  
copy_stack_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1622  static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1623  {
1624  	size_t n = src->allocated_stack / BPF_REG_SIZE;
1625  
1626  	dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1627  				GFP_KERNEL);
1628  	if (!dst->stack)
1629  		return -ENOMEM;
1630  
1631  	dst->allocated_stack = src->allocated_stack;
1632  	return 0;
1633  }
1634  
resize_reference_state(struct bpf_func_state * state,size_t n)1635  static int resize_reference_state(struct bpf_func_state *state, size_t n)
1636  {
1637  	state->refs = realloc_array(state->refs, state->acquired_refs, n,
1638  				    sizeof(struct bpf_reference_state));
1639  	if (!state->refs)
1640  		return -ENOMEM;
1641  
1642  	state->acquired_refs = n;
1643  	return 0;
1644  }
1645  
1646  /* Possibly update state->allocated_stack to be at least size bytes. Also
1647   * possibly update the function's high-water mark in its bpf_subprog_info.
1648   */
grow_stack_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int size)1649  static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1650  {
1651  	size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1652  
1653  	if (old_n >= n)
1654  		return 0;
1655  
1656  	state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1657  	if (!state->stack)
1658  		return -ENOMEM;
1659  
1660  	state->allocated_stack = size;
1661  
1662  	/* update known max for given subprogram */
1663  	if (env->subprog_info[state->subprogno].stack_depth < size)
1664  		env->subprog_info[state->subprogno].stack_depth = size;
1665  
1666  	return 0;
1667  }
1668  
1669  /* Acquire a pointer id from the env and update the state->refs to include
1670   * this new pointer reference.
1671   * On success, returns a valid pointer id to associate with the register
1672   * On failure, returns a negative errno.
1673   */
acquire_reference_state(struct bpf_verifier_env * env,int insn_idx)1674  static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1675  {
1676  	struct bpf_func_state *state = cur_func(env);
1677  	int new_ofs = state->acquired_refs;
1678  	int id, err;
1679  
1680  	err = resize_reference_state(state, state->acquired_refs + 1);
1681  	if (err)
1682  		return err;
1683  	id = ++env->id_gen;
1684  	state->refs[new_ofs].id = id;
1685  	state->refs[new_ofs].insn_idx = insn_idx;
1686  	state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1687  
1688  	return id;
1689  }
1690  
1691  /* release function corresponding to acquire_reference_state(). Idempotent. */
release_reference_state(struct bpf_func_state * state,int ptr_id)1692  static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1693  {
1694  	int i, last_idx;
1695  
1696  	last_idx = state->acquired_refs - 1;
1697  	for (i = 0; i < state->acquired_refs; i++) {
1698  		if (state->refs[i].id == ptr_id) {
1699  			/* Cannot release caller references in callbacks */
1700  			if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1701  				return -EINVAL;
1702  			if (last_idx && i != last_idx)
1703  				memcpy(&state->refs[i], &state->refs[last_idx],
1704  				       sizeof(*state->refs));
1705  			memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1706  			state->acquired_refs--;
1707  			return 0;
1708  		}
1709  	}
1710  	return -EINVAL;
1711  }
1712  
free_func_state(struct bpf_func_state * state)1713  static void free_func_state(struct bpf_func_state *state)
1714  {
1715  	if (!state)
1716  		return;
1717  	kfree(state->refs);
1718  	kfree(state->stack);
1719  	kfree(state);
1720  }
1721  
clear_jmp_history(struct bpf_verifier_state * state)1722  static void clear_jmp_history(struct bpf_verifier_state *state)
1723  {
1724  	kfree(state->jmp_history);
1725  	state->jmp_history = NULL;
1726  	state->jmp_history_cnt = 0;
1727  }
1728  
free_verifier_state(struct bpf_verifier_state * state,bool free_self)1729  static void free_verifier_state(struct bpf_verifier_state *state,
1730  				bool free_self)
1731  {
1732  	int i;
1733  
1734  	for (i = 0; i <= state->curframe; i++) {
1735  		free_func_state(state->frame[i]);
1736  		state->frame[i] = NULL;
1737  	}
1738  	clear_jmp_history(state);
1739  	if (free_self)
1740  		kfree(state);
1741  }
1742  
1743  /* copy verifier state from src to dst growing dst stack space
1744   * when necessary to accommodate larger src stack
1745   */
copy_func_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1746  static int copy_func_state(struct bpf_func_state *dst,
1747  			   const struct bpf_func_state *src)
1748  {
1749  	int err;
1750  
1751  	memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1752  	err = copy_reference_state(dst, src);
1753  	if (err)
1754  		return err;
1755  	return copy_stack_state(dst, src);
1756  }
1757  
copy_verifier_state(struct bpf_verifier_state * dst_state,const struct bpf_verifier_state * src)1758  static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1759  			       const struct bpf_verifier_state *src)
1760  {
1761  	struct bpf_func_state *dst;
1762  	int i, err;
1763  
1764  	dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1765  					    src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1766  					    GFP_USER);
1767  	if (!dst_state->jmp_history)
1768  		return -ENOMEM;
1769  	dst_state->jmp_history_cnt = src->jmp_history_cnt;
1770  
1771  	/* if dst has more stack frames then src frame, free them */
1772  	for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1773  		free_func_state(dst_state->frame[i]);
1774  		dst_state->frame[i] = NULL;
1775  	}
1776  	dst_state->speculative = src->speculative;
1777  	dst_state->active_rcu_lock = src->active_rcu_lock;
1778  	dst_state->curframe = src->curframe;
1779  	dst_state->active_lock.ptr = src->active_lock.ptr;
1780  	dst_state->active_lock.id = src->active_lock.id;
1781  	dst_state->branches = src->branches;
1782  	dst_state->parent = src->parent;
1783  	dst_state->first_insn_idx = src->first_insn_idx;
1784  	dst_state->last_insn_idx = src->last_insn_idx;
1785  	dst_state->dfs_depth = src->dfs_depth;
1786  	dst_state->callback_unroll_depth = src->callback_unroll_depth;
1787  	dst_state->used_as_loop_entry = src->used_as_loop_entry;
1788  	for (i = 0; i <= src->curframe; i++) {
1789  		dst = dst_state->frame[i];
1790  		if (!dst) {
1791  			dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1792  			if (!dst)
1793  				return -ENOMEM;
1794  			dst_state->frame[i] = dst;
1795  		}
1796  		err = copy_func_state(dst, src->frame[i]);
1797  		if (err)
1798  			return err;
1799  	}
1800  	return 0;
1801  }
1802  
state_htab_size(struct bpf_verifier_env * env)1803  static u32 state_htab_size(struct bpf_verifier_env *env)
1804  {
1805  	return env->prog->len;
1806  }
1807  
explored_state(struct bpf_verifier_env * env,int idx)1808  static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1809  {
1810  	struct bpf_verifier_state *cur = env->cur_state;
1811  	struct bpf_func_state *state = cur->frame[cur->curframe];
1812  
1813  	return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1814  }
1815  
same_callsites(struct bpf_verifier_state * a,struct bpf_verifier_state * b)1816  static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1817  {
1818  	int fr;
1819  
1820  	if (a->curframe != b->curframe)
1821  		return false;
1822  
1823  	for (fr = a->curframe; fr >= 0; fr--)
1824  		if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1825  			return false;
1826  
1827  	return true;
1828  }
1829  
1830  /* Open coded iterators allow back-edges in the state graph in order to
1831   * check unbounded loops that iterators.
1832   *
1833   * In is_state_visited() it is necessary to know if explored states are
1834   * part of some loops in order to decide whether non-exact states
1835   * comparison could be used:
1836   * - non-exact states comparison establishes sub-state relation and uses
1837   *   read and precision marks to do so, these marks are propagated from
1838   *   children states and thus are not guaranteed to be final in a loop;
1839   * - exact states comparison just checks if current and explored states
1840   *   are identical (and thus form a back-edge).
1841   *
1842   * Paper "A New Algorithm for Identifying Loops in Decompilation"
1843   * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1844   * algorithm for loop structure detection and gives an overview of
1845   * relevant terminology. It also has helpful illustrations.
1846   *
1847   * [1] https://api.semanticscholar.org/CorpusID:15784067
1848   *
1849   * We use a similar algorithm but because loop nested structure is
1850   * irrelevant for verifier ours is significantly simpler and resembles
1851   * strongly connected components algorithm from Sedgewick's textbook.
1852   *
1853   * Define topmost loop entry as a first node of the loop traversed in a
1854   * depth first search starting from initial state. The goal of the loop
1855   * tracking algorithm is to associate topmost loop entries with states
1856   * derived from these entries.
1857   *
1858   * For each step in the DFS states traversal algorithm needs to identify
1859   * the following situations:
1860   *
1861   *          initial                     initial                   initial
1862   *            |                           |                         |
1863   *            V                           V                         V
1864   *           ...                         ...           .---------> hdr
1865   *            |                           |            |            |
1866   *            V                           V            |            V
1867   *           cur                     .-> succ          |    .------...
1868   *            |                      |    |            |    |       |
1869   *            V                      |    V            |    V       V
1870   *           succ                    '-- cur           |   ...     ...
1871   *                                                     |    |       |
1872   *                                                     |    V       V
1873   *                                                     |   succ <- cur
1874   *                                                     |    |
1875   *                                                     |    V
1876   *                                                     |   ...
1877   *                                                     |    |
1878   *                                                     '----'
1879   *
1880   *  (A) successor state of cur   (B) successor state of cur or it's entry
1881   *      not yet traversed            are in current DFS path, thus cur and succ
1882   *                                   are members of the same outermost loop
1883   *
1884   *                      initial                  initial
1885   *                        |                        |
1886   *                        V                        V
1887   *                       ...                      ...
1888   *                        |                        |
1889   *                        V                        V
1890   *                .------...               .------...
1891   *                |       |                |       |
1892   *                V       V                V       V
1893   *           .-> hdr     ...              ...     ...
1894   *           |    |       |                |       |
1895   *           |    V       V                V       V
1896   *           |   succ <- cur              succ <- cur
1897   *           |    |                        |
1898   *           |    V                        V
1899   *           |   ...                      ...
1900   *           |    |                        |
1901   *           '----'                       exit
1902   *
1903   * (C) successor state of cur is a part of some loop but this loop
1904   *     does not include cur or successor state is not in a loop at all.
1905   *
1906   * Algorithm could be described as the following python code:
1907   *
1908   *     traversed = set()   # Set of traversed nodes
1909   *     entries = {}        # Mapping from node to loop entry
1910   *     depths = {}         # Depth level assigned to graph node
1911   *     path = set()        # Current DFS path
1912   *
1913   *     # Find outermost loop entry known for n
1914   *     def get_loop_entry(n):
1915   *         h = entries.get(n, None)
1916   *         while h in entries and entries[h] != h:
1917   *             h = entries[h]
1918   *         return h
1919   *
1920   *     # Update n's loop entry if h's outermost entry comes
1921   *     # before n's outermost entry in current DFS path.
1922   *     def update_loop_entry(n, h):
1923   *         n1 = get_loop_entry(n) or n
1924   *         h1 = get_loop_entry(h) or h
1925   *         if h1 in path and depths[h1] <= depths[n1]:
1926   *             entries[n] = h1
1927   *
1928   *     def dfs(n, depth):
1929   *         traversed.add(n)
1930   *         path.add(n)
1931   *         depths[n] = depth
1932   *         for succ in G.successors(n):
1933   *             if succ not in traversed:
1934   *                 # Case A: explore succ and update cur's loop entry
1935   *                 #         only if succ's entry is in current DFS path.
1936   *                 dfs(succ, depth + 1)
1937   *                 h = get_loop_entry(succ)
1938   *                 update_loop_entry(n, h)
1939   *             else:
1940   *                 # Case B or C depending on `h1 in path` check in update_loop_entry().
1941   *                 update_loop_entry(n, succ)
1942   *         path.remove(n)
1943   *
1944   * To adapt this algorithm for use with verifier:
1945   * - use st->branch == 0 as a signal that DFS of succ had been finished
1946   *   and cur's loop entry has to be updated (case A), handle this in
1947   *   update_branch_counts();
1948   * - use st->branch > 0 as a signal that st is in the current DFS path;
1949   * - handle cases B and C in is_state_visited();
1950   * - update topmost loop entry for intermediate states in get_loop_entry().
1951   */
get_loop_entry(struct bpf_verifier_state * st)1952  static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1953  {
1954  	struct bpf_verifier_state *topmost = st->loop_entry, *old;
1955  
1956  	while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1957  		topmost = topmost->loop_entry;
1958  	/* Update loop entries for intermediate states to avoid this
1959  	 * traversal in future get_loop_entry() calls.
1960  	 */
1961  	while (st && st->loop_entry != topmost) {
1962  		old = st->loop_entry;
1963  		st->loop_entry = topmost;
1964  		st = old;
1965  	}
1966  	return topmost;
1967  }
1968  
update_loop_entry(struct bpf_verifier_state * cur,struct bpf_verifier_state * hdr)1969  static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1970  {
1971  	struct bpf_verifier_state *cur1, *hdr1;
1972  
1973  	cur1 = get_loop_entry(cur) ?: cur;
1974  	hdr1 = get_loop_entry(hdr) ?: hdr;
1975  	/* The head1->branches check decides between cases B and C in
1976  	 * comment for get_loop_entry(). If hdr1->branches == 0 then
1977  	 * head's topmost loop entry is not in current DFS path,
1978  	 * hence 'cur' and 'hdr' are not in the same loop and there is
1979  	 * no need to update cur->loop_entry.
1980  	 */
1981  	if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1982  		cur->loop_entry = hdr;
1983  		hdr->used_as_loop_entry = true;
1984  	}
1985  }
1986  
update_branch_counts(struct bpf_verifier_env * env,struct bpf_verifier_state * st)1987  static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1988  {
1989  	while (st) {
1990  		u32 br = --st->branches;
1991  
1992  		/* br == 0 signals that DFS exploration for 'st' is finished,
1993  		 * thus it is necessary to update parent's loop entry if it
1994  		 * turned out that st is a part of some loop.
1995  		 * This is a part of 'case A' in get_loop_entry() comment.
1996  		 */
1997  		if (br == 0 && st->parent && st->loop_entry)
1998  			update_loop_entry(st->parent, st->loop_entry);
1999  
2000  		/* WARN_ON(br > 1) technically makes sense here,
2001  		 * but see comment in push_stack(), hence:
2002  		 */
2003  		WARN_ONCE((int)br < 0,
2004  			  "BUG update_branch_counts:branches_to_explore=%d\n",
2005  			  br);
2006  		if (br)
2007  			break;
2008  		st = st->parent;
2009  	}
2010  }
2011  
pop_stack(struct bpf_verifier_env * env,int * prev_insn_idx,int * insn_idx,bool pop_log)2012  static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
2013  		     int *insn_idx, bool pop_log)
2014  {
2015  	struct bpf_verifier_state *cur = env->cur_state;
2016  	struct bpf_verifier_stack_elem *elem, *head = env->head;
2017  	int err;
2018  
2019  	if (env->head == NULL)
2020  		return -ENOENT;
2021  
2022  	if (cur) {
2023  		err = copy_verifier_state(cur, &head->st);
2024  		if (err)
2025  			return err;
2026  	}
2027  	if (pop_log)
2028  		bpf_vlog_reset(&env->log, head->log_pos);
2029  	if (insn_idx)
2030  		*insn_idx = head->insn_idx;
2031  	if (prev_insn_idx)
2032  		*prev_insn_idx = head->prev_insn_idx;
2033  	elem = head->next;
2034  	free_verifier_state(&head->st, false);
2035  	kfree(head);
2036  	env->head = elem;
2037  	env->stack_size--;
2038  	return 0;
2039  }
2040  
push_stack(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,bool speculative)2041  static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
2042  					     int insn_idx, int prev_insn_idx,
2043  					     bool speculative)
2044  {
2045  	struct bpf_verifier_state *cur = env->cur_state;
2046  	struct bpf_verifier_stack_elem *elem;
2047  	int err;
2048  
2049  	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2050  	if (!elem)
2051  		goto err;
2052  
2053  	elem->insn_idx = insn_idx;
2054  	elem->prev_insn_idx = prev_insn_idx;
2055  	elem->next = env->head;
2056  	elem->log_pos = env->log.end_pos;
2057  	env->head = elem;
2058  	env->stack_size++;
2059  	err = copy_verifier_state(&elem->st, cur);
2060  	if (err)
2061  		goto err;
2062  	elem->st.speculative |= speculative;
2063  	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2064  		verbose(env, "The sequence of %d jumps is too complex.\n",
2065  			env->stack_size);
2066  		goto err;
2067  	}
2068  	if (elem->st.parent) {
2069  		++elem->st.parent->branches;
2070  		/* WARN_ON(branches > 2) technically makes sense here,
2071  		 * but
2072  		 * 1. speculative states will bump 'branches' for non-branch
2073  		 * instructions
2074  		 * 2. is_state_visited() heuristics may decide not to create
2075  		 * a new state for a sequence of branches and all such current
2076  		 * and cloned states will be pointing to a single parent state
2077  		 * which might have large 'branches' count.
2078  		 */
2079  	}
2080  	return &elem->st;
2081  err:
2082  	free_verifier_state(env->cur_state, true);
2083  	env->cur_state = NULL;
2084  	/* pop all elements and return */
2085  	while (!pop_stack(env, NULL, NULL, false));
2086  	return NULL;
2087  }
2088  
2089  #define CALLER_SAVED_REGS 6
2090  static const int caller_saved[CALLER_SAVED_REGS] = {
2091  	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2092  };
2093  
2094  /* This helper doesn't clear reg->id */
___mark_reg_known(struct bpf_reg_state * reg,u64 imm)2095  static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2096  {
2097  	reg->var_off = tnum_const(imm);
2098  	reg->smin_value = (s64)imm;
2099  	reg->smax_value = (s64)imm;
2100  	reg->umin_value = imm;
2101  	reg->umax_value = imm;
2102  
2103  	reg->s32_min_value = (s32)imm;
2104  	reg->s32_max_value = (s32)imm;
2105  	reg->u32_min_value = (u32)imm;
2106  	reg->u32_max_value = (u32)imm;
2107  }
2108  
2109  /* Mark the unknown part of a register (variable offset or scalar value) as
2110   * known to have the value @imm.
2111   */
__mark_reg_known(struct bpf_reg_state * reg,u64 imm)2112  static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2113  {
2114  	/* Clear off and union(map_ptr, range) */
2115  	memset(((u8 *)reg) + sizeof(reg->type), 0,
2116  	       offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2117  	reg->id = 0;
2118  	reg->ref_obj_id = 0;
2119  	___mark_reg_known(reg, imm);
2120  }
2121  
__mark_reg32_known(struct bpf_reg_state * reg,u64 imm)2122  static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2123  {
2124  	reg->var_off = tnum_const_subreg(reg->var_off, imm);
2125  	reg->s32_min_value = (s32)imm;
2126  	reg->s32_max_value = (s32)imm;
2127  	reg->u32_min_value = (u32)imm;
2128  	reg->u32_max_value = (u32)imm;
2129  }
2130  
2131  /* Mark the 'variable offset' part of a register as zero.  This should be
2132   * used only on registers holding a pointer type.
2133   */
__mark_reg_known_zero(struct bpf_reg_state * reg)2134  static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2135  {
2136  	__mark_reg_known(reg, 0);
2137  }
2138  
__mark_reg_const_zero(struct bpf_reg_state * reg)2139  static void __mark_reg_const_zero(struct bpf_reg_state *reg)
2140  {
2141  	__mark_reg_known(reg, 0);
2142  	reg->type = SCALAR_VALUE;
2143  }
2144  
mark_reg_known_zero(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)2145  static void mark_reg_known_zero(struct bpf_verifier_env *env,
2146  				struct bpf_reg_state *regs, u32 regno)
2147  {
2148  	if (WARN_ON(regno >= MAX_BPF_REG)) {
2149  		verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2150  		/* Something bad happened, let's kill all regs */
2151  		for (regno = 0; regno < MAX_BPF_REG; regno++)
2152  			__mark_reg_not_init(env, regs + regno);
2153  		return;
2154  	}
2155  	__mark_reg_known_zero(regs + regno);
2156  }
2157  
__mark_dynptr_reg(struct bpf_reg_state * reg,enum bpf_dynptr_type type,bool first_slot,int dynptr_id)2158  static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2159  			      bool first_slot, int dynptr_id)
2160  {
2161  	/* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2162  	 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2163  	 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2164  	 */
2165  	__mark_reg_known_zero(reg);
2166  	reg->type = CONST_PTR_TO_DYNPTR;
2167  	/* Give each dynptr a unique id to uniquely associate slices to it. */
2168  	reg->id = dynptr_id;
2169  	reg->dynptr.type = type;
2170  	reg->dynptr.first_slot = first_slot;
2171  }
2172  
mark_ptr_not_null_reg(struct bpf_reg_state * reg)2173  static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2174  {
2175  	if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2176  		const struct bpf_map *map = reg->map_ptr;
2177  
2178  		if (map->inner_map_meta) {
2179  			reg->type = CONST_PTR_TO_MAP;
2180  			reg->map_ptr = map->inner_map_meta;
2181  			/* transfer reg's id which is unique for every map_lookup_elem
2182  			 * as UID of the inner map.
2183  			 */
2184  			if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
2185  				reg->map_uid = reg->id;
2186  		} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2187  			reg->type = PTR_TO_XDP_SOCK;
2188  		} else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2189  			   map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2190  			reg->type = PTR_TO_SOCKET;
2191  		} else {
2192  			reg->type = PTR_TO_MAP_VALUE;
2193  		}
2194  		return;
2195  	}
2196  
2197  	reg->type &= ~PTR_MAYBE_NULL;
2198  }
2199  
mark_reg_graph_node(struct bpf_reg_state * regs,u32 regno,struct btf_field_graph_root * ds_head)2200  static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2201  				struct btf_field_graph_root *ds_head)
2202  {
2203  	__mark_reg_known_zero(&regs[regno]);
2204  	regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2205  	regs[regno].btf = ds_head->btf;
2206  	regs[regno].btf_id = ds_head->value_btf_id;
2207  	regs[regno].off = ds_head->node_offset;
2208  }
2209  
reg_is_pkt_pointer(const struct bpf_reg_state * reg)2210  static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2211  {
2212  	return type_is_pkt_pointer(reg->type);
2213  }
2214  
reg_is_pkt_pointer_any(const struct bpf_reg_state * reg)2215  static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2216  {
2217  	return reg_is_pkt_pointer(reg) ||
2218  	       reg->type == PTR_TO_PACKET_END;
2219  }
2220  
reg_is_dynptr_slice_pkt(const struct bpf_reg_state * reg)2221  static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2222  {
2223  	return base_type(reg->type) == PTR_TO_MEM &&
2224  		(reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2225  }
2226  
2227  /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
reg_is_init_pkt_pointer(const struct bpf_reg_state * reg,enum bpf_reg_type which)2228  static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2229  				    enum bpf_reg_type which)
2230  {
2231  	/* The register can already have a range from prior markings.
2232  	 * This is fine as long as it hasn't been advanced from its
2233  	 * origin.
2234  	 */
2235  	return reg->type == which &&
2236  	       reg->id == 0 &&
2237  	       reg->off == 0 &&
2238  	       tnum_equals_const(reg->var_off, 0);
2239  }
2240  
2241  /* Reset the min/max bounds of a register */
__mark_reg_unbounded(struct bpf_reg_state * reg)2242  static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2243  {
2244  	reg->smin_value = S64_MIN;
2245  	reg->smax_value = S64_MAX;
2246  	reg->umin_value = 0;
2247  	reg->umax_value = U64_MAX;
2248  
2249  	reg->s32_min_value = S32_MIN;
2250  	reg->s32_max_value = S32_MAX;
2251  	reg->u32_min_value = 0;
2252  	reg->u32_max_value = U32_MAX;
2253  }
2254  
__mark_reg64_unbounded(struct bpf_reg_state * reg)2255  static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2256  {
2257  	reg->smin_value = S64_MIN;
2258  	reg->smax_value = S64_MAX;
2259  	reg->umin_value = 0;
2260  	reg->umax_value = U64_MAX;
2261  }
2262  
__mark_reg32_unbounded(struct bpf_reg_state * reg)2263  static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2264  {
2265  	reg->s32_min_value = S32_MIN;
2266  	reg->s32_max_value = S32_MAX;
2267  	reg->u32_min_value = 0;
2268  	reg->u32_max_value = U32_MAX;
2269  }
2270  
__update_reg32_bounds(struct bpf_reg_state * reg)2271  static void __update_reg32_bounds(struct bpf_reg_state *reg)
2272  {
2273  	struct tnum var32_off = tnum_subreg(reg->var_off);
2274  
2275  	/* min signed is max(sign bit) | min(other bits) */
2276  	reg->s32_min_value = max_t(s32, reg->s32_min_value,
2277  			var32_off.value | (var32_off.mask & S32_MIN));
2278  	/* max signed is min(sign bit) | max(other bits) */
2279  	reg->s32_max_value = min_t(s32, reg->s32_max_value,
2280  			var32_off.value | (var32_off.mask & S32_MAX));
2281  	reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2282  	reg->u32_max_value = min(reg->u32_max_value,
2283  				 (u32)(var32_off.value | var32_off.mask));
2284  }
2285  
__update_reg64_bounds(struct bpf_reg_state * reg)2286  static void __update_reg64_bounds(struct bpf_reg_state *reg)
2287  {
2288  	/* min signed is max(sign bit) | min(other bits) */
2289  	reg->smin_value = max_t(s64, reg->smin_value,
2290  				reg->var_off.value | (reg->var_off.mask & S64_MIN));
2291  	/* max signed is min(sign bit) | max(other bits) */
2292  	reg->smax_value = min_t(s64, reg->smax_value,
2293  				reg->var_off.value | (reg->var_off.mask & S64_MAX));
2294  	reg->umin_value = max(reg->umin_value, reg->var_off.value);
2295  	reg->umax_value = min(reg->umax_value,
2296  			      reg->var_off.value | reg->var_off.mask);
2297  }
2298  
__update_reg_bounds(struct bpf_reg_state * reg)2299  static void __update_reg_bounds(struct bpf_reg_state *reg)
2300  {
2301  	__update_reg32_bounds(reg);
2302  	__update_reg64_bounds(reg);
2303  }
2304  
2305  /* Uses signed min/max values to inform unsigned, and vice-versa */
__reg32_deduce_bounds(struct bpf_reg_state * reg)2306  static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2307  {
2308  	/* Learn sign from signed bounds.
2309  	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2310  	 * are the same, so combine.  This works even in the negative case, e.g.
2311  	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2312  	 */
2313  	if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2314  		reg->s32_min_value = reg->u32_min_value =
2315  			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2316  		reg->s32_max_value = reg->u32_max_value =
2317  			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2318  		return;
2319  	}
2320  	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2321  	 * boundary, so we must be careful.
2322  	 */
2323  	if ((s32)reg->u32_max_value >= 0) {
2324  		/* Positive.  We can't learn anything from the smin, but smax
2325  		 * is positive, hence safe.
2326  		 */
2327  		reg->s32_min_value = reg->u32_min_value;
2328  		reg->s32_max_value = reg->u32_max_value =
2329  			min_t(u32, reg->s32_max_value, reg->u32_max_value);
2330  	} else if ((s32)reg->u32_min_value < 0) {
2331  		/* Negative.  We can't learn anything from the smax, but smin
2332  		 * is negative, hence safe.
2333  		 */
2334  		reg->s32_min_value = reg->u32_min_value =
2335  			max_t(u32, reg->s32_min_value, reg->u32_min_value);
2336  		reg->s32_max_value = reg->u32_max_value;
2337  	}
2338  }
2339  
__reg64_deduce_bounds(struct bpf_reg_state * reg)2340  static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2341  {
2342  	/* Learn sign from signed bounds.
2343  	 * If we cannot cross the sign boundary, then signed and unsigned bounds
2344  	 * are the same, so combine.  This works even in the negative case, e.g.
2345  	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2346  	 */
2347  	if (reg->smin_value >= 0 || reg->smax_value < 0) {
2348  		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2349  							  reg->umin_value);
2350  		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2351  							  reg->umax_value);
2352  		return;
2353  	}
2354  	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
2355  	 * boundary, so we must be careful.
2356  	 */
2357  	if ((s64)reg->umax_value >= 0) {
2358  		/* Positive.  We can't learn anything from the smin, but smax
2359  		 * is positive, hence safe.
2360  		 */
2361  		reg->smin_value = reg->umin_value;
2362  		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2363  							  reg->umax_value);
2364  	} else if ((s64)reg->umin_value < 0) {
2365  		/* Negative.  We can't learn anything from the smax, but smin
2366  		 * is negative, hence safe.
2367  		 */
2368  		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2369  							  reg->umin_value);
2370  		reg->smax_value = reg->umax_value;
2371  	}
2372  }
2373  
__reg_deduce_bounds(struct bpf_reg_state * reg)2374  static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2375  {
2376  	__reg32_deduce_bounds(reg);
2377  	__reg64_deduce_bounds(reg);
2378  }
2379  
2380  /* Attempts to improve var_off based on unsigned min/max information */
__reg_bound_offset(struct bpf_reg_state * reg)2381  static void __reg_bound_offset(struct bpf_reg_state *reg)
2382  {
2383  	struct tnum var64_off = tnum_intersect(reg->var_off,
2384  					       tnum_range(reg->umin_value,
2385  							  reg->umax_value));
2386  	struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2387  					       tnum_range(reg->u32_min_value,
2388  							  reg->u32_max_value));
2389  
2390  	reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2391  }
2392  
reg_bounds_sync(struct bpf_reg_state * reg)2393  static void reg_bounds_sync(struct bpf_reg_state *reg)
2394  {
2395  	/* We might have learned new bounds from the var_off. */
2396  	__update_reg_bounds(reg);
2397  	/* We might have learned something about the sign bit. */
2398  	__reg_deduce_bounds(reg);
2399  	/* We might have learned some bits from the bounds. */
2400  	__reg_bound_offset(reg);
2401  	/* Intersecting with the old var_off might have improved our bounds
2402  	 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2403  	 * then new var_off is (0; 0x7f...fc) which improves our umax.
2404  	 */
2405  	__update_reg_bounds(reg);
2406  }
2407  
__reg32_bound_s64(s32 a)2408  static bool __reg32_bound_s64(s32 a)
2409  {
2410  	return a >= 0 && a <= S32_MAX;
2411  }
2412  
__reg_assign_32_into_64(struct bpf_reg_state * reg)2413  static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2414  {
2415  	reg->umin_value = reg->u32_min_value;
2416  	reg->umax_value = reg->u32_max_value;
2417  
2418  	/* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2419  	 * be positive otherwise set to worse case bounds and refine later
2420  	 * from tnum.
2421  	 */
2422  	if (__reg32_bound_s64(reg->s32_min_value) &&
2423  	    __reg32_bound_s64(reg->s32_max_value)) {
2424  		reg->smin_value = reg->s32_min_value;
2425  		reg->smax_value = reg->s32_max_value;
2426  	} else {
2427  		reg->smin_value = 0;
2428  		reg->smax_value = U32_MAX;
2429  	}
2430  }
2431  
__reg_combine_32_into_64(struct bpf_reg_state * reg)2432  static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2433  {
2434  	/* special case when 64-bit register has upper 32-bit register
2435  	 * zeroed. Typically happens after zext or <<32, >>32 sequence
2436  	 * allowing us to use 32-bit bounds directly,
2437  	 */
2438  	if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2439  		__reg_assign_32_into_64(reg);
2440  	} else {
2441  		/* Otherwise the best we can do is push lower 32bit known and
2442  		 * unknown bits into register (var_off set from jmp logic)
2443  		 * then learn as much as possible from the 64-bit tnum
2444  		 * known and unknown bits. The previous smin/smax bounds are
2445  		 * invalid here because of jmp32 compare so mark them unknown
2446  		 * so they do not impact tnum bounds calculation.
2447  		 */
2448  		__mark_reg64_unbounded(reg);
2449  	}
2450  	reg_bounds_sync(reg);
2451  }
2452  
__reg64_bound_s32(s64 a)2453  static bool __reg64_bound_s32(s64 a)
2454  {
2455  	return a >= S32_MIN && a <= S32_MAX;
2456  }
2457  
__reg64_bound_u32(u64 a)2458  static bool __reg64_bound_u32(u64 a)
2459  {
2460  	return a >= U32_MIN && a <= U32_MAX;
2461  }
2462  
__reg_combine_64_into_32(struct bpf_reg_state * reg)2463  static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2464  {
2465  	__mark_reg32_unbounded(reg);
2466  	if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2467  		reg->s32_min_value = (s32)reg->smin_value;
2468  		reg->s32_max_value = (s32)reg->smax_value;
2469  	}
2470  	if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2471  		reg->u32_min_value = (u32)reg->umin_value;
2472  		reg->u32_max_value = (u32)reg->umax_value;
2473  	}
2474  	reg_bounds_sync(reg);
2475  }
2476  
2477  /* Mark a register as having a completely unknown (scalar) value. */
__mark_reg_unknown(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)2478  static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2479  			       struct bpf_reg_state *reg)
2480  {
2481  	/*
2482  	 * Clear type, off, and union(map_ptr, range) and
2483  	 * padding between 'type' and union
2484  	 */
2485  	memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2486  	reg->type = SCALAR_VALUE;
2487  	reg->id = 0;
2488  	reg->ref_obj_id = 0;
2489  	reg->var_off = tnum_unknown;
2490  	reg->frameno = 0;
2491  	reg->precise = !env->bpf_capable;
2492  	__mark_reg_unbounded(reg);
2493  }
2494  
mark_reg_unknown(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)2495  static void mark_reg_unknown(struct bpf_verifier_env *env,
2496  			     struct bpf_reg_state *regs, u32 regno)
2497  {
2498  	if (WARN_ON(regno >= MAX_BPF_REG)) {
2499  		verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2500  		/* Something bad happened, let's kill all regs except FP */
2501  		for (regno = 0; regno < BPF_REG_FP; regno++)
2502  			__mark_reg_not_init(env, regs + regno);
2503  		return;
2504  	}
2505  	__mark_reg_unknown(env, regs + regno);
2506  }
2507  
__mark_reg_not_init(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)2508  static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2509  				struct bpf_reg_state *reg)
2510  {
2511  	__mark_reg_unknown(env, reg);
2512  	reg->type = NOT_INIT;
2513  }
2514  
mark_reg_not_init(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)2515  static void mark_reg_not_init(struct bpf_verifier_env *env,
2516  			      struct bpf_reg_state *regs, u32 regno)
2517  {
2518  	if (WARN_ON(regno >= MAX_BPF_REG)) {
2519  		verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2520  		/* Something bad happened, let's kill all regs except FP */
2521  		for (regno = 0; regno < BPF_REG_FP; regno++)
2522  			__mark_reg_not_init(env, regs + regno);
2523  		return;
2524  	}
2525  	__mark_reg_not_init(env, regs + regno);
2526  }
2527  
mark_btf_ld_reg(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno,enum bpf_reg_type reg_type,struct btf * btf,u32 btf_id,enum bpf_type_flag flag)2528  static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2529  			    struct bpf_reg_state *regs, u32 regno,
2530  			    enum bpf_reg_type reg_type,
2531  			    struct btf *btf, u32 btf_id,
2532  			    enum bpf_type_flag flag)
2533  {
2534  	if (reg_type == SCALAR_VALUE) {
2535  		mark_reg_unknown(env, regs, regno);
2536  		return;
2537  	}
2538  	mark_reg_known_zero(env, regs, regno);
2539  	regs[regno].type = PTR_TO_BTF_ID | flag;
2540  	regs[regno].btf = btf;
2541  	regs[regno].btf_id = btf_id;
2542  	if (type_may_be_null(flag))
2543  		regs[regno].id = ++env->id_gen;
2544  }
2545  
2546  #define DEF_NOT_SUBREG	(0)
init_reg_state(struct bpf_verifier_env * env,struct bpf_func_state * state)2547  static void init_reg_state(struct bpf_verifier_env *env,
2548  			   struct bpf_func_state *state)
2549  {
2550  	struct bpf_reg_state *regs = state->regs;
2551  	int i;
2552  
2553  	for (i = 0; i < MAX_BPF_REG; i++) {
2554  		mark_reg_not_init(env, regs, i);
2555  		regs[i].live = REG_LIVE_NONE;
2556  		regs[i].parent = NULL;
2557  		regs[i].subreg_def = DEF_NOT_SUBREG;
2558  	}
2559  
2560  	/* frame pointer */
2561  	regs[BPF_REG_FP].type = PTR_TO_STACK;
2562  	mark_reg_known_zero(env, regs, BPF_REG_FP);
2563  	regs[BPF_REG_FP].frameno = state->frameno;
2564  }
2565  
2566  #define BPF_MAIN_FUNC (-1)
init_func_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int callsite,int frameno,int subprogno)2567  static void init_func_state(struct bpf_verifier_env *env,
2568  			    struct bpf_func_state *state,
2569  			    int callsite, int frameno, int subprogno)
2570  {
2571  	state->callsite = callsite;
2572  	state->frameno = frameno;
2573  	state->subprogno = subprogno;
2574  	state->callback_ret_range = tnum_range(0, 0);
2575  	init_reg_state(env, state);
2576  	mark_verifier_state_scratched(env);
2577  }
2578  
2579  /* Similar to push_stack(), but for async callbacks */
push_async_cb(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,int subprog)2580  static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2581  						int insn_idx, int prev_insn_idx,
2582  						int subprog)
2583  {
2584  	struct bpf_verifier_stack_elem *elem;
2585  	struct bpf_func_state *frame;
2586  
2587  	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2588  	if (!elem)
2589  		goto err;
2590  
2591  	elem->insn_idx = insn_idx;
2592  	elem->prev_insn_idx = prev_insn_idx;
2593  	elem->next = env->head;
2594  	elem->log_pos = env->log.end_pos;
2595  	env->head = elem;
2596  	env->stack_size++;
2597  	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2598  		verbose(env,
2599  			"The sequence of %d jumps is too complex for async cb.\n",
2600  			env->stack_size);
2601  		goto err;
2602  	}
2603  	/* Unlike push_stack() do not copy_verifier_state().
2604  	 * The caller state doesn't matter.
2605  	 * This is async callback. It starts in a fresh stack.
2606  	 * Initialize it similar to do_check_common().
2607  	 */
2608  	elem->st.branches = 1;
2609  	frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2610  	if (!frame)
2611  		goto err;
2612  	init_func_state(env, frame,
2613  			BPF_MAIN_FUNC /* callsite */,
2614  			0 /* frameno within this callchain */,
2615  			subprog /* subprog number within this prog */);
2616  	elem->st.frame[0] = frame;
2617  	return &elem->st;
2618  err:
2619  	free_verifier_state(env->cur_state, true);
2620  	env->cur_state = NULL;
2621  	/* pop all elements and return */
2622  	while (!pop_stack(env, NULL, NULL, false));
2623  	return NULL;
2624  }
2625  
2626  
2627  enum reg_arg_type {
2628  	SRC_OP,		/* register is used as source operand */
2629  	DST_OP,		/* register is used as destination operand */
2630  	DST_OP_NO_MARK	/* same as above, check only, don't mark */
2631  };
2632  
cmp_subprogs(const void * a,const void * b)2633  static int cmp_subprogs(const void *a, const void *b)
2634  {
2635  	return ((struct bpf_subprog_info *)a)->start -
2636  	       ((struct bpf_subprog_info *)b)->start;
2637  }
2638  
find_subprog(struct bpf_verifier_env * env,int off)2639  static int find_subprog(struct bpf_verifier_env *env, int off)
2640  {
2641  	struct bpf_subprog_info *p;
2642  
2643  	p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2644  		    sizeof(env->subprog_info[0]), cmp_subprogs);
2645  	if (!p)
2646  		return -ENOENT;
2647  	return p - env->subprog_info;
2648  
2649  }
2650  
add_subprog(struct bpf_verifier_env * env,int off)2651  static int add_subprog(struct bpf_verifier_env *env, int off)
2652  {
2653  	int insn_cnt = env->prog->len;
2654  	int ret;
2655  
2656  	if (off >= insn_cnt || off < 0) {
2657  		verbose(env, "call to invalid destination\n");
2658  		return -EINVAL;
2659  	}
2660  	ret = find_subprog(env, off);
2661  	if (ret >= 0)
2662  		return ret;
2663  	if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2664  		verbose(env, "too many subprograms\n");
2665  		return -E2BIG;
2666  	}
2667  	/* determine subprog starts. The end is one before the next starts */
2668  	env->subprog_info[env->subprog_cnt++].start = off;
2669  	sort(env->subprog_info, env->subprog_cnt,
2670  	     sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2671  	return env->subprog_cnt - 1;
2672  }
2673  
2674  #define MAX_KFUNC_DESCS 256
2675  #define MAX_KFUNC_BTFS	256
2676  
2677  struct bpf_kfunc_desc {
2678  	struct btf_func_model func_model;
2679  	u32 func_id;
2680  	s32 imm;
2681  	u16 offset;
2682  	unsigned long addr;
2683  };
2684  
2685  struct bpf_kfunc_btf {
2686  	struct btf *btf;
2687  	struct module *module;
2688  	u16 offset;
2689  };
2690  
2691  struct bpf_kfunc_desc_tab {
2692  	/* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2693  	 * verification. JITs do lookups by bpf_insn, where func_id may not be
2694  	 * available, therefore at the end of verification do_misc_fixups()
2695  	 * sorts this by imm and offset.
2696  	 */
2697  	struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2698  	u32 nr_descs;
2699  };
2700  
2701  struct bpf_kfunc_btf_tab {
2702  	struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2703  	u32 nr_descs;
2704  };
2705  
kfunc_desc_cmp_by_id_off(const void * a,const void * b)2706  static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2707  {
2708  	const struct bpf_kfunc_desc *d0 = a;
2709  	const struct bpf_kfunc_desc *d1 = b;
2710  
2711  	/* func_id is not greater than BTF_MAX_TYPE */
2712  	return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2713  }
2714  
kfunc_btf_cmp_by_off(const void * a,const void * b)2715  static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2716  {
2717  	const struct bpf_kfunc_btf *d0 = a;
2718  	const struct bpf_kfunc_btf *d1 = b;
2719  
2720  	return d0->offset - d1->offset;
2721  }
2722  
2723  static const struct bpf_kfunc_desc *
find_kfunc_desc(const struct bpf_prog * prog,u32 func_id,u16 offset)2724  find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2725  {
2726  	struct bpf_kfunc_desc desc = {
2727  		.func_id = func_id,
2728  		.offset = offset,
2729  	};
2730  	struct bpf_kfunc_desc_tab *tab;
2731  
2732  	tab = prog->aux->kfunc_tab;
2733  	return bsearch(&desc, tab->descs, tab->nr_descs,
2734  		       sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2735  }
2736  
bpf_get_kfunc_addr(const struct bpf_prog * prog,u32 func_id,u16 btf_fd_idx,u8 ** func_addr)2737  int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2738  		       u16 btf_fd_idx, u8 **func_addr)
2739  {
2740  	const struct bpf_kfunc_desc *desc;
2741  
2742  	desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2743  	if (!desc)
2744  		return -EFAULT;
2745  
2746  	*func_addr = (u8 *)desc->addr;
2747  	return 0;
2748  }
2749  
__find_kfunc_desc_btf(struct bpf_verifier_env * env,s16 offset)2750  static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2751  					 s16 offset)
2752  {
2753  	struct bpf_kfunc_btf kf_btf = { .offset = offset };
2754  	struct bpf_kfunc_btf_tab *tab;
2755  	struct bpf_kfunc_btf *b;
2756  	struct module *mod;
2757  	struct btf *btf;
2758  	int btf_fd;
2759  
2760  	tab = env->prog->aux->kfunc_btf_tab;
2761  	b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2762  		    sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2763  	if (!b) {
2764  		if (tab->nr_descs == MAX_KFUNC_BTFS) {
2765  			verbose(env, "too many different module BTFs\n");
2766  			return ERR_PTR(-E2BIG);
2767  		}
2768  
2769  		if (bpfptr_is_null(env->fd_array)) {
2770  			verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2771  			return ERR_PTR(-EPROTO);
2772  		}
2773  
2774  		if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2775  					    offset * sizeof(btf_fd),
2776  					    sizeof(btf_fd)))
2777  			return ERR_PTR(-EFAULT);
2778  
2779  		btf = btf_get_by_fd(btf_fd);
2780  		if (IS_ERR(btf)) {
2781  			verbose(env, "invalid module BTF fd specified\n");
2782  			return btf;
2783  		}
2784  
2785  		if (!btf_is_module(btf)) {
2786  			verbose(env, "BTF fd for kfunc is not a module BTF\n");
2787  			btf_put(btf);
2788  			return ERR_PTR(-EINVAL);
2789  		}
2790  
2791  		mod = btf_try_get_module(btf);
2792  		if (!mod) {
2793  			btf_put(btf);
2794  			return ERR_PTR(-ENXIO);
2795  		}
2796  
2797  		b = &tab->descs[tab->nr_descs++];
2798  		b->btf = btf;
2799  		b->module = mod;
2800  		b->offset = offset;
2801  
2802  		/* sort() reorders entries by value, so b may no longer point
2803  		 * to the right entry after this
2804  		 */
2805  		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2806  		     kfunc_btf_cmp_by_off, NULL);
2807  	} else {
2808  		btf = b->btf;
2809  	}
2810  
2811  	return btf;
2812  }
2813  
bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab * tab)2814  void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2815  {
2816  	if (!tab)
2817  		return;
2818  
2819  	while (tab->nr_descs--) {
2820  		module_put(tab->descs[tab->nr_descs].module);
2821  		btf_put(tab->descs[tab->nr_descs].btf);
2822  	}
2823  	kfree(tab);
2824  }
2825  
find_kfunc_desc_btf(struct bpf_verifier_env * env,s16 offset)2826  static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2827  {
2828  	if (offset) {
2829  		if (offset < 0) {
2830  			/* In the future, this can be allowed to increase limit
2831  			 * of fd index into fd_array, interpreted as u16.
2832  			 */
2833  			verbose(env, "negative offset disallowed for kernel module function call\n");
2834  			return ERR_PTR(-EINVAL);
2835  		}
2836  
2837  		return __find_kfunc_desc_btf(env, offset);
2838  	}
2839  	return btf_vmlinux ?: ERR_PTR(-ENOENT);
2840  }
2841  
add_kfunc_call(struct bpf_verifier_env * env,u32 func_id,s16 offset)2842  static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2843  {
2844  	const struct btf_type *func, *func_proto;
2845  	struct bpf_kfunc_btf_tab *btf_tab;
2846  	struct bpf_kfunc_desc_tab *tab;
2847  	struct bpf_prog_aux *prog_aux;
2848  	struct bpf_kfunc_desc *desc;
2849  	const char *func_name;
2850  	struct btf *desc_btf;
2851  	unsigned long call_imm;
2852  	unsigned long addr;
2853  	int err;
2854  
2855  	prog_aux = env->prog->aux;
2856  	tab = prog_aux->kfunc_tab;
2857  	btf_tab = prog_aux->kfunc_btf_tab;
2858  	if (!tab) {
2859  		if (!btf_vmlinux) {
2860  			verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2861  			return -ENOTSUPP;
2862  		}
2863  
2864  		if (!env->prog->jit_requested) {
2865  			verbose(env, "JIT is required for calling kernel function\n");
2866  			return -ENOTSUPP;
2867  		}
2868  
2869  		if (!bpf_jit_supports_kfunc_call()) {
2870  			verbose(env, "JIT does not support calling kernel function\n");
2871  			return -ENOTSUPP;
2872  		}
2873  
2874  		if (!env->prog->gpl_compatible) {
2875  			verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2876  			return -EINVAL;
2877  		}
2878  
2879  		tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2880  		if (!tab)
2881  			return -ENOMEM;
2882  		prog_aux->kfunc_tab = tab;
2883  	}
2884  
2885  	/* func_id == 0 is always invalid, but instead of returning an error, be
2886  	 * conservative and wait until the code elimination pass before returning
2887  	 * error, so that invalid calls that get pruned out can be in BPF programs
2888  	 * loaded from userspace.  It is also required that offset be untouched
2889  	 * for such calls.
2890  	 */
2891  	if (!func_id && !offset)
2892  		return 0;
2893  
2894  	if (!btf_tab && offset) {
2895  		btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2896  		if (!btf_tab)
2897  			return -ENOMEM;
2898  		prog_aux->kfunc_btf_tab = btf_tab;
2899  	}
2900  
2901  	desc_btf = find_kfunc_desc_btf(env, offset);
2902  	if (IS_ERR(desc_btf)) {
2903  		verbose(env, "failed to find BTF for kernel function\n");
2904  		return PTR_ERR(desc_btf);
2905  	}
2906  
2907  	if (find_kfunc_desc(env->prog, func_id, offset))
2908  		return 0;
2909  
2910  	if (tab->nr_descs == MAX_KFUNC_DESCS) {
2911  		verbose(env, "too many different kernel function calls\n");
2912  		return -E2BIG;
2913  	}
2914  
2915  	func = btf_type_by_id(desc_btf, func_id);
2916  	if (!func || !btf_type_is_func(func)) {
2917  		verbose(env, "kernel btf_id %u is not a function\n",
2918  			func_id);
2919  		return -EINVAL;
2920  	}
2921  	func_proto = btf_type_by_id(desc_btf, func->type);
2922  	if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2923  		verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2924  			func_id);
2925  		return -EINVAL;
2926  	}
2927  
2928  	func_name = btf_name_by_offset(desc_btf, func->name_off);
2929  	addr = kallsyms_lookup_name(func_name);
2930  	if (!addr) {
2931  		verbose(env, "cannot find address for kernel function %s\n",
2932  			func_name);
2933  		return -EINVAL;
2934  	}
2935  	specialize_kfunc(env, func_id, offset, &addr);
2936  
2937  	if (bpf_jit_supports_far_kfunc_call()) {
2938  		call_imm = func_id;
2939  	} else {
2940  		call_imm = BPF_CALL_IMM(addr);
2941  		/* Check whether the relative offset overflows desc->imm */
2942  		if ((unsigned long)(s32)call_imm != call_imm) {
2943  			verbose(env, "address of kernel function %s is out of range\n",
2944  				func_name);
2945  			return -EINVAL;
2946  		}
2947  	}
2948  
2949  	if (bpf_dev_bound_kfunc_id(func_id)) {
2950  		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2951  		if (err)
2952  			return err;
2953  	}
2954  
2955  	desc = &tab->descs[tab->nr_descs++];
2956  	desc->func_id = func_id;
2957  	desc->imm = call_imm;
2958  	desc->offset = offset;
2959  	desc->addr = addr;
2960  	err = btf_distill_func_proto(&env->log, desc_btf,
2961  				     func_proto, func_name,
2962  				     &desc->func_model);
2963  	if (!err)
2964  		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2965  		     kfunc_desc_cmp_by_id_off, NULL);
2966  	return err;
2967  }
2968  
kfunc_desc_cmp_by_imm_off(const void * a,const void * b)2969  static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2970  {
2971  	const struct bpf_kfunc_desc *d0 = a;
2972  	const struct bpf_kfunc_desc *d1 = b;
2973  
2974  	if (d0->imm != d1->imm)
2975  		return d0->imm < d1->imm ? -1 : 1;
2976  	if (d0->offset != d1->offset)
2977  		return d0->offset < d1->offset ? -1 : 1;
2978  	return 0;
2979  }
2980  
sort_kfunc_descs_by_imm_off(struct bpf_prog * prog)2981  static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2982  {
2983  	struct bpf_kfunc_desc_tab *tab;
2984  
2985  	tab = prog->aux->kfunc_tab;
2986  	if (!tab)
2987  		return;
2988  
2989  	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2990  	     kfunc_desc_cmp_by_imm_off, NULL);
2991  }
2992  
bpf_prog_has_kfunc_call(const struct bpf_prog * prog)2993  bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2994  {
2995  	return !!prog->aux->kfunc_tab;
2996  }
2997  
2998  const struct btf_func_model *
bpf_jit_find_kfunc_model(const struct bpf_prog * prog,const struct bpf_insn * insn)2999  bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3000  			 const struct bpf_insn *insn)
3001  {
3002  	const struct bpf_kfunc_desc desc = {
3003  		.imm = insn->imm,
3004  		.offset = insn->off,
3005  	};
3006  	const struct bpf_kfunc_desc *res;
3007  	struct bpf_kfunc_desc_tab *tab;
3008  
3009  	tab = prog->aux->kfunc_tab;
3010  	res = bsearch(&desc, tab->descs, tab->nr_descs,
3011  		      sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3012  
3013  	return res ? &res->func_model : NULL;
3014  }
3015  
add_subprog_and_kfunc(struct bpf_verifier_env * env)3016  static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3017  {
3018  	struct bpf_subprog_info *subprog = env->subprog_info;
3019  	struct bpf_insn *insn = env->prog->insnsi;
3020  	int i, ret, insn_cnt = env->prog->len;
3021  
3022  	/* Add entry function. */
3023  	ret = add_subprog(env, 0);
3024  	if (ret)
3025  		return ret;
3026  
3027  	for (i = 0; i < insn_cnt; i++, insn++) {
3028  		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3029  		    !bpf_pseudo_kfunc_call(insn))
3030  			continue;
3031  
3032  		if (!env->bpf_capable) {
3033  			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3034  			return -EPERM;
3035  		}
3036  
3037  		if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3038  			ret = add_subprog(env, i + insn->imm + 1);
3039  		else
3040  			ret = add_kfunc_call(env, insn->imm, insn->off);
3041  
3042  		if (ret < 0)
3043  			return ret;
3044  	}
3045  
3046  	/* Add a fake 'exit' subprog which could simplify subprog iteration
3047  	 * logic. 'subprog_cnt' should not be increased.
3048  	 */
3049  	subprog[env->subprog_cnt].start = insn_cnt;
3050  
3051  	if (env->log.level & BPF_LOG_LEVEL2)
3052  		for (i = 0; i < env->subprog_cnt; i++)
3053  			verbose(env, "func#%d @%d\n", i, subprog[i].start);
3054  
3055  	return 0;
3056  }
3057  
check_subprogs(struct bpf_verifier_env * env)3058  static int check_subprogs(struct bpf_verifier_env *env)
3059  {
3060  	int i, subprog_start, subprog_end, off, cur_subprog = 0;
3061  	struct bpf_subprog_info *subprog = env->subprog_info;
3062  	struct bpf_insn *insn = env->prog->insnsi;
3063  	int insn_cnt = env->prog->len;
3064  
3065  	/* now check that all jumps are within the same subprog */
3066  	subprog_start = subprog[cur_subprog].start;
3067  	subprog_end = subprog[cur_subprog + 1].start;
3068  	for (i = 0; i < insn_cnt; i++) {
3069  		u8 code = insn[i].code;
3070  
3071  		if (code == (BPF_JMP | BPF_CALL) &&
3072  		    insn[i].src_reg == 0 &&
3073  		    insn[i].imm == BPF_FUNC_tail_call) {
3074  			subprog[cur_subprog].has_tail_call = true;
3075  			subprog[cur_subprog].tail_call_reachable = true;
3076  		}
3077  		if (BPF_CLASS(code) == BPF_LD &&
3078  		    (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3079  			subprog[cur_subprog].has_ld_abs = true;
3080  		if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3081  			goto next;
3082  		if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3083  			goto next;
3084  		if (code == (BPF_JMP32 | BPF_JA))
3085  			off = i + insn[i].imm + 1;
3086  		else
3087  			off = i + insn[i].off + 1;
3088  		if (off < subprog_start || off >= subprog_end) {
3089  			verbose(env, "jump out of range from insn %d to %d\n", i, off);
3090  			return -EINVAL;
3091  		}
3092  next:
3093  		if (i == subprog_end - 1) {
3094  			/* to avoid fall-through from one subprog into another
3095  			 * the last insn of the subprog should be either exit
3096  			 * or unconditional jump back
3097  			 */
3098  			if (code != (BPF_JMP | BPF_EXIT) &&
3099  			    code != (BPF_JMP32 | BPF_JA) &&
3100  			    code != (BPF_JMP | BPF_JA)) {
3101  				verbose(env, "last insn is not an exit or jmp\n");
3102  				return -EINVAL;
3103  			}
3104  			subprog_start = subprog_end;
3105  			cur_subprog++;
3106  			if (cur_subprog < env->subprog_cnt)
3107  				subprog_end = subprog[cur_subprog + 1].start;
3108  		}
3109  	}
3110  	return 0;
3111  }
3112  
3113  /* Parentage chain of this register (or stack slot) should take care of all
3114   * issues like callee-saved registers, stack slot allocation time, etc.
3115   */
mark_reg_read(struct bpf_verifier_env * env,const struct bpf_reg_state * state,struct bpf_reg_state * parent,u8 flag)3116  static int mark_reg_read(struct bpf_verifier_env *env,
3117  			 const struct bpf_reg_state *state,
3118  			 struct bpf_reg_state *parent, u8 flag)
3119  {
3120  	bool writes = parent == state->parent; /* Observe write marks */
3121  	int cnt = 0;
3122  
3123  	while (parent) {
3124  		/* if read wasn't screened by an earlier write ... */
3125  		if (writes && state->live & REG_LIVE_WRITTEN)
3126  			break;
3127  		if (parent->live & REG_LIVE_DONE) {
3128  			verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3129  				reg_type_str(env, parent->type),
3130  				parent->var_off.value, parent->off);
3131  			return -EFAULT;
3132  		}
3133  		/* The first condition is more likely to be true than the
3134  		 * second, checked it first.
3135  		 */
3136  		if ((parent->live & REG_LIVE_READ) == flag ||
3137  		    parent->live & REG_LIVE_READ64)
3138  			/* The parentage chain never changes and
3139  			 * this parent was already marked as LIVE_READ.
3140  			 * There is no need to keep walking the chain again and
3141  			 * keep re-marking all parents as LIVE_READ.
3142  			 * This case happens when the same register is read
3143  			 * multiple times without writes into it in-between.
3144  			 * Also, if parent has the stronger REG_LIVE_READ64 set,
3145  			 * then no need to set the weak REG_LIVE_READ32.
3146  			 */
3147  			break;
3148  		/* ... then we depend on parent's value */
3149  		parent->live |= flag;
3150  		/* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3151  		if (flag == REG_LIVE_READ64)
3152  			parent->live &= ~REG_LIVE_READ32;
3153  		state = parent;
3154  		parent = state->parent;
3155  		writes = true;
3156  		cnt++;
3157  	}
3158  
3159  	if (env->longest_mark_read_walk < cnt)
3160  		env->longest_mark_read_walk = cnt;
3161  	return 0;
3162  }
3163  
mark_dynptr_read(struct bpf_verifier_env * env,struct bpf_reg_state * reg)3164  static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3165  {
3166  	struct bpf_func_state *state = func(env, reg);
3167  	int spi, ret;
3168  
3169  	/* For CONST_PTR_TO_DYNPTR, it must have already been done by
3170  	 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3171  	 * check_kfunc_call.
3172  	 */
3173  	if (reg->type == CONST_PTR_TO_DYNPTR)
3174  		return 0;
3175  	spi = dynptr_get_spi(env, reg);
3176  	if (spi < 0)
3177  		return spi;
3178  	/* Caller ensures dynptr is valid and initialized, which means spi is in
3179  	 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3180  	 * read.
3181  	 */
3182  	ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3183  			    state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3184  	if (ret)
3185  		return ret;
3186  	return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3187  			     state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3188  }
3189  
mark_iter_read(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int spi,int nr_slots)3190  static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3191  			  int spi, int nr_slots)
3192  {
3193  	struct bpf_func_state *state = func(env, reg);
3194  	int err, i;
3195  
3196  	for (i = 0; i < nr_slots; i++) {
3197  		struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3198  
3199  		err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3200  		if (err)
3201  			return err;
3202  
3203  		mark_stack_slot_scratched(env, spi - i);
3204  	}
3205  
3206  	return 0;
3207  }
3208  
3209  /* This function is supposed to be used by the following 32-bit optimization
3210   * code only. It returns TRUE if the source or destination register operates
3211   * on 64-bit, otherwise return FALSE.
3212   */
is_reg64(struct bpf_verifier_env * env,struct bpf_insn * insn,u32 regno,struct bpf_reg_state * reg,enum reg_arg_type t)3213  static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3214  		     u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3215  {
3216  	u8 code, class, op;
3217  
3218  	code = insn->code;
3219  	class = BPF_CLASS(code);
3220  	op = BPF_OP(code);
3221  	if (class == BPF_JMP) {
3222  		/* BPF_EXIT for "main" will reach here. Return TRUE
3223  		 * conservatively.
3224  		 */
3225  		if (op == BPF_EXIT)
3226  			return true;
3227  		if (op == BPF_CALL) {
3228  			/* BPF to BPF call will reach here because of marking
3229  			 * caller saved clobber with DST_OP_NO_MARK for which we
3230  			 * don't care the register def because they are anyway
3231  			 * marked as NOT_INIT already.
3232  			 */
3233  			if (insn->src_reg == BPF_PSEUDO_CALL)
3234  				return false;
3235  			/* Helper call will reach here because of arg type
3236  			 * check, conservatively return TRUE.
3237  			 */
3238  			if (t == SRC_OP)
3239  				return true;
3240  
3241  			return false;
3242  		}
3243  	}
3244  
3245  	if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3246  		return false;
3247  
3248  	if (class == BPF_ALU64 || class == BPF_JMP ||
3249  	    (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3250  		return true;
3251  
3252  	if (class == BPF_ALU || class == BPF_JMP32)
3253  		return false;
3254  
3255  	if (class == BPF_LDX) {
3256  		if (t != SRC_OP)
3257  			return BPF_SIZE(code) == BPF_DW;
3258  		/* LDX source must be ptr. */
3259  		return true;
3260  	}
3261  
3262  	if (class == BPF_STX) {
3263  		/* BPF_STX (including atomic variants) has multiple source
3264  		 * operands, one of which is a ptr. Check whether the caller is
3265  		 * asking about it.
3266  		 */
3267  		if (t == SRC_OP && reg->type != SCALAR_VALUE)
3268  			return true;
3269  		return BPF_SIZE(code) == BPF_DW;
3270  	}
3271  
3272  	if (class == BPF_LD) {
3273  		u8 mode = BPF_MODE(code);
3274  
3275  		/* LD_IMM64 */
3276  		if (mode == BPF_IMM)
3277  			return true;
3278  
3279  		/* Both LD_IND and LD_ABS return 32-bit data. */
3280  		if (t != SRC_OP)
3281  			return  false;
3282  
3283  		/* Implicit ctx ptr. */
3284  		if (regno == BPF_REG_6)
3285  			return true;
3286  
3287  		/* Explicit source could be any width. */
3288  		return true;
3289  	}
3290  
3291  	if (class == BPF_ST)
3292  		/* The only source register for BPF_ST is a ptr. */
3293  		return true;
3294  
3295  	/* Conservatively return true at default. */
3296  	return true;
3297  }
3298  
3299  /* Return the regno defined by the insn, or -1. */
insn_def_regno(const struct bpf_insn * insn)3300  static int insn_def_regno(const struct bpf_insn *insn)
3301  {
3302  	switch (BPF_CLASS(insn->code)) {
3303  	case BPF_JMP:
3304  	case BPF_JMP32:
3305  	case BPF_ST:
3306  		return -1;
3307  	case BPF_STX:
3308  		if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3309  		    (insn->imm & BPF_FETCH)) {
3310  			if (insn->imm == BPF_CMPXCHG)
3311  				return BPF_REG_0;
3312  			else
3313  				return insn->src_reg;
3314  		} else {
3315  			return -1;
3316  		}
3317  	default:
3318  		return insn->dst_reg;
3319  	}
3320  }
3321  
3322  /* Return TRUE if INSN has defined any 32-bit value explicitly. */
insn_has_def32(struct bpf_verifier_env * env,struct bpf_insn * insn)3323  static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3324  {
3325  	int dst_reg = insn_def_regno(insn);
3326  
3327  	if (dst_reg == -1)
3328  		return false;
3329  
3330  	return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3331  }
3332  
mark_insn_zext(struct bpf_verifier_env * env,struct bpf_reg_state * reg)3333  static void mark_insn_zext(struct bpf_verifier_env *env,
3334  			   struct bpf_reg_state *reg)
3335  {
3336  	s32 def_idx = reg->subreg_def;
3337  
3338  	if (def_idx == DEF_NOT_SUBREG)
3339  		return;
3340  
3341  	env->insn_aux_data[def_idx - 1].zext_dst = true;
3342  	/* The dst will be zero extended, so won't be sub-register anymore. */
3343  	reg->subreg_def = DEF_NOT_SUBREG;
3344  }
3345  
__check_reg_arg(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno,enum reg_arg_type t)3346  static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3347  			   enum reg_arg_type t)
3348  {
3349  	struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3350  	struct bpf_reg_state *reg;
3351  	bool rw64;
3352  
3353  	if (regno >= MAX_BPF_REG) {
3354  		verbose(env, "R%d is invalid\n", regno);
3355  		return -EINVAL;
3356  	}
3357  
3358  	mark_reg_scratched(env, regno);
3359  
3360  	reg = &regs[regno];
3361  	rw64 = is_reg64(env, insn, regno, reg, t);
3362  	if (t == SRC_OP) {
3363  		/* check whether register used as source operand can be read */
3364  		if (reg->type == NOT_INIT) {
3365  			verbose(env, "R%d !read_ok\n", regno);
3366  			return -EACCES;
3367  		}
3368  		/* We don't need to worry about FP liveness because it's read-only */
3369  		if (regno == BPF_REG_FP)
3370  			return 0;
3371  
3372  		if (rw64)
3373  			mark_insn_zext(env, reg);
3374  
3375  		return mark_reg_read(env, reg, reg->parent,
3376  				     rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3377  	} else {
3378  		/* check whether register used as dest operand can be written to */
3379  		if (regno == BPF_REG_FP) {
3380  			verbose(env, "frame pointer is read only\n");
3381  			return -EACCES;
3382  		}
3383  		reg->live |= REG_LIVE_WRITTEN;
3384  		reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3385  		if (t == DST_OP)
3386  			mark_reg_unknown(env, regs, regno);
3387  	}
3388  	return 0;
3389  }
3390  
check_reg_arg(struct bpf_verifier_env * env,u32 regno,enum reg_arg_type t)3391  static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3392  			 enum reg_arg_type t)
3393  {
3394  	struct bpf_verifier_state *vstate = env->cur_state;
3395  	struct bpf_func_state *state = vstate->frame[vstate->curframe];
3396  
3397  	return __check_reg_arg(env, state->regs, regno, t);
3398  }
3399  
mark_jmp_point(struct bpf_verifier_env * env,int idx)3400  static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3401  {
3402  	env->insn_aux_data[idx].jmp_point = true;
3403  }
3404  
is_jmp_point(struct bpf_verifier_env * env,int insn_idx)3405  static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3406  {
3407  	return env->insn_aux_data[insn_idx].jmp_point;
3408  }
3409  
3410  /* for any branch, call, exit record the history of jmps in the given state */
push_jmp_history(struct bpf_verifier_env * env,struct bpf_verifier_state * cur)3411  static int push_jmp_history(struct bpf_verifier_env *env,
3412  			    struct bpf_verifier_state *cur)
3413  {
3414  	u32 cnt = cur->jmp_history_cnt;
3415  	struct bpf_idx_pair *p;
3416  	size_t alloc_size;
3417  
3418  	if (!is_jmp_point(env, env->insn_idx))
3419  		return 0;
3420  
3421  	cnt++;
3422  	alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3423  	p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3424  	if (!p)
3425  		return -ENOMEM;
3426  	p[cnt - 1].idx = env->insn_idx;
3427  	p[cnt - 1].prev_idx = env->prev_insn_idx;
3428  	cur->jmp_history = p;
3429  	cur->jmp_history_cnt = cnt;
3430  	return 0;
3431  }
3432  
3433  /* Backtrack one insn at a time. If idx is not at the top of recorded
3434   * history then previous instruction came from straight line execution.
3435   * Return -ENOENT if we exhausted all instructions within given state.
3436   *
3437   * It's legal to have a bit of a looping with the same starting and ending
3438   * insn index within the same state, e.g.: 3->4->5->3, so just because current
3439   * instruction index is the same as state's first_idx doesn't mean we are
3440   * done. If there is still some jump history left, we should keep going. We
3441   * need to take into account that we might have a jump history between given
3442   * state's parent and itself, due to checkpointing. In this case, we'll have
3443   * history entry recording a jump from last instruction of parent state and
3444   * first instruction of given state.
3445   */
get_prev_insn_idx(struct bpf_verifier_state * st,int i,u32 * history)3446  static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3447  			     u32 *history)
3448  {
3449  	u32 cnt = *history;
3450  
3451  	if (i == st->first_insn_idx) {
3452  		if (cnt == 0)
3453  			return -ENOENT;
3454  		if (cnt == 1 && st->jmp_history[0].idx == i)
3455  			return -ENOENT;
3456  	}
3457  
3458  	if (cnt && st->jmp_history[cnt - 1].idx == i) {
3459  		i = st->jmp_history[cnt - 1].prev_idx;
3460  		(*history)--;
3461  	} else {
3462  		i--;
3463  	}
3464  	return i;
3465  }
3466  
disasm_kfunc_name(void * data,const struct bpf_insn * insn)3467  static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3468  {
3469  	const struct btf_type *func;
3470  	struct btf *desc_btf;
3471  
3472  	if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3473  		return NULL;
3474  
3475  	desc_btf = find_kfunc_desc_btf(data, insn->off);
3476  	if (IS_ERR(desc_btf))
3477  		return "<error>";
3478  
3479  	func = btf_type_by_id(desc_btf, insn->imm);
3480  	return btf_name_by_offset(desc_btf, func->name_off);
3481  }
3482  
bt_init(struct backtrack_state * bt,u32 frame)3483  static inline void bt_init(struct backtrack_state *bt, u32 frame)
3484  {
3485  	bt->frame = frame;
3486  }
3487  
bt_reset(struct backtrack_state * bt)3488  static inline void bt_reset(struct backtrack_state *bt)
3489  {
3490  	struct bpf_verifier_env *env = bt->env;
3491  
3492  	memset(bt, 0, sizeof(*bt));
3493  	bt->env = env;
3494  }
3495  
bt_empty(struct backtrack_state * bt)3496  static inline u32 bt_empty(struct backtrack_state *bt)
3497  {
3498  	u64 mask = 0;
3499  	int i;
3500  
3501  	for (i = 0; i <= bt->frame; i++)
3502  		mask |= bt->reg_masks[i] | bt->stack_masks[i];
3503  
3504  	return mask == 0;
3505  }
3506  
bt_subprog_enter(struct backtrack_state * bt)3507  static inline int bt_subprog_enter(struct backtrack_state *bt)
3508  {
3509  	if (bt->frame == MAX_CALL_FRAMES - 1) {
3510  		verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3511  		WARN_ONCE(1, "verifier backtracking bug");
3512  		return -EFAULT;
3513  	}
3514  	bt->frame++;
3515  	return 0;
3516  }
3517  
bt_subprog_exit(struct backtrack_state * bt)3518  static inline int bt_subprog_exit(struct backtrack_state *bt)
3519  {
3520  	if (bt->frame == 0) {
3521  		verbose(bt->env, "BUG subprog exit from frame 0\n");
3522  		WARN_ONCE(1, "verifier backtracking bug");
3523  		return -EFAULT;
3524  	}
3525  	bt->frame--;
3526  	return 0;
3527  }
3528  
bt_set_frame_reg(struct backtrack_state * bt,u32 frame,u32 reg)3529  static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3530  {
3531  	bt->reg_masks[frame] |= 1 << reg;
3532  }
3533  
bt_clear_frame_reg(struct backtrack_state * bt,u32 frame,u32 reg)3534  static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3535  {
3536  	bt->reg_masks[frame] &= ~(1 << reg);
3537  }
3538  
bt_set_reg(struct backtrack_state * bt,u32 reg)3539  static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3540  {
3541  	bt_set_frame_reg(bt, bt->frame, reg);
3542  }
3543  
bt_clear_reg(struct backtrack_state * bt,u32 reg)3544  static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3545  {
3546  	bt_clear_frame_reg(bt, bt->frame, reg);
3547  }
3548  
bt_set_frame_slot(struct backtrack_state * bt,u32 frame,u32 slot)3549  static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3550  {
3551  	bt->stack_masks[frame] |= 1ull << slot;
3552  }
3553  
bt_clear_frame_slot(struct backtrack_state * bt,u32 frame,u32 slot)3554  static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3555  {
3556  	bt->stack_masks[frame] &= ~(1ull << slot);
3557  }
3558  
bt_set_slot(struct backtrack_state * bt,u32 slot)3559  static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3560  {
3561  	bt_set_frame_slot(bt, bt->frame, slot);
3562  }
3563  
bt_clear_slot(struct backtrack_state * bt,u32 slot)3564  static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3565  {
3566  	bt_clear_frame_slot(bt, bt->frame, slot);
3567  }
3568  
bt_frame_reg_mask(struct backtrack_state * bt,u32 frame)3569  static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3570  {
3571  	return bt->reg_masks[frame];
3572  }
3573  
bt_reg_mask(struct backtrack_state * bt)3574  static inline u32 bt_reg_mask(struct backtrack_state *bt)
3575  {
3576  	return bt->reg_masks[bt->frame];
3577  }
3578  
bt_frame_stack_mask(struct backtrack_state * bt,u32 frame)3579  static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3580  {
3581  	return bt->stack_masks[frame];
3582  }
3583  
bt_stack_mask(struct backtrack_state * bt)3584  static inline u64 bt_stack_mask(struct backtrack_state *bt)
3585  {
3586  	return bt->stack_masks[bt->frame];
3587  }
3588  
bt_is_reg_set(struct backtrack_state * bt,u32 reg)3589  static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3590  {
3591  	return bt->reg_masks[bt->frame] & (1 << reg);
3592  }
3593  
bt_is_slot_set(struct backtrack_state * bt,u32 slot)3594  static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3595  {
3596  	return bt->stack_masks[bt->frame] & (1ull << slot);
3597  }
3598  
3599  /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
fmt_reg_mask(char * buf,ssize_t buf_sz,u32 reg_mask)3600  static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3601  {
3602  	DECLARE_BITMAP(mask, 64);
3603  	bool first = true;
3604  	int i, n;
3605  
3606  	buf[0] = '\0';
3607  
3608  	bitmap_from_u64(mask, reg_mask);
3609  	for_each_set_bit(i, mask, 32) {
3610  		n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3611  		first = false;
3612  		buf += n;
3613  		buf_sz -= n;
3614  		if (buf_sz < 0)
3615  			break;
3616  	}
3617  }
3618  /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
fmt_stack_mask(char * buf,ssize_t buf_sz,u64 stack_mask)3619  static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3620  {
3621  	DECLARE_BITMAP(mask, 64);
3622  	bool first = true;
3623  	int i, n;
3624  
3625  	buf[0] = '\0';
3626  
3627  	bitmap_from_u64(mask, stack_mask);
3628  	for_each_set_bit(i, mask, 64) {
3629  		n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3630  		first = false;
3631  		buf += n;
3632  		buf_sz -= n;
3633  		if (buf_sz < 0)
3634  			break;
3635  	}
3636  }
3637  
3638  static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3639  
3640  /* For given verifier state backtrack_insn() is called from the last insn to
3641   * the first insn. Its purpose is to compute a bitmask of registers and
3642   * stack slots that needs precision in the parent verifier state.
3643   *
3644   * @idx is an index of the instruction we are currently processing;
3645   * @subseq_idx is an index of the subsequent instruction that:
3646   *   - *would be* executed next, if jump history is viewed in forward order;
3647   *   - *was* processed previously during backtracking.
3648   */
backtrack_insn(struct bpf_verifier_env * env,int idx,int subseq_idx,struct backtrack_state * bt)3649  static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3650  			  struct backtrack_state *bt)
3651  {
3652  	const struct bpf_insn_cbs cbs = {
3653  		.cb_call	= disasm_kfunc_name,
3654  		.cb_print	= verbose,
3655  		.private_data	= env,
3656  	};
3657  	struct bpf_insn *insn = env->prog->insnsi + idx;
3658  	u8 class = BPF_CLASS(insn->code);
3659  	u8 opcode = BPF_OP(insn->code);
3660  	u8 mode = BPF_MODE(insn->code);
3661  	u32 dreg = insn->dst_reg;
3662  	u32 sreg = insn->src_reg;
3663  	u32 spi, i;
3664  
3665  	if (insn->code == 0)
3666  		return 0;
3667  	if (env->log.level & BPF_LOG_LEVEL2) {
3668  		fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3669  		verbose(env, "mark_precise: frame%d: regs=%s ",
3670  			bt->frame, env->tmp_str_buf);
3671  		fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3672  		verbose(env, "stack=%s before ", env->tmp_str_buf);
3673  		verbose(env, "%d: ", idx);
3674  		print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3675  	}
3676  
3677  	if (class == BPF_ALU || class == BPF_ALU64) {
3678  		if (!bt_is_reg_set(bt, dreg))
3679  			return 0;
3680  		if (opcode == BPF_END || opcode == BPF_NEG) {
3681  			/* sreg is reserved and unused
3682  			 * dreg still need precision before this insn
3683  			 */
3684  			return 0;
3685  		} else if (opcode == BPF_MOV) {
3686  			if (BPF_SRC(insn->code) == BPF_X) {
3687  				/* dreg = sreg or dreg = (s8, s16, s32)sreg
3688  				 * dreg needs precision after this insn
3689  				 * sreg needs precision before this insn
3690  				 */
3691  				bt_clear_reg(bt, dreg);
3692  				if (sreg != BPF_REG_FP)
3693  					bt_set_reg(bt, sreg);
3694  			} else {
3695  				/* dreg = K
3696  				 * dreg needs precision after this insn.
3697  				 * Corresponding register is already marked
3698  				 * as precise=true in this verifier state.
3699  				 * No further markings in parent are necessary
3700  				 */
3701  				bt_clear_reg(bt, dreg);
3702  			}
3703  		} else {
3704  			if (BPF_SRC(insn->code) == BPF_X) {
3705  				/* dreg += sreg
3706  				 * both dreg and sreg need precision
3707  				 * before this insn
3708  				 */
3709  				if (sreg != BPF_REG_FP)
3710  					bt_set_reg(bt, sreg);
3711  			} /* else dreg += K
3712  			   * dreg still needs precision before this insn
3713  			   */
3714  		}
3715  	} else if (class == BPF_LDX) {
3716  		if (!bt_is_reg_set(bt, dreg))
3717  			return 0;
3718  		bt_clear_reg(bt, dreg);
3719  
3720  		/* scalars can only be spilled into stack w/o losing precision.
3721  		 * Load from any other memory can be zero extended.
3722  		 * The desire to keep that precision is already indicated
3723  		 * by 'precise' mark in corresponding register of this state.
3724  		 * No further tracking necessary.
3725  		 */
3726  		if (insn->src_reg != BPF_REG_FP)
3727  			return 0;
3728  
3729  		/* dreg = *(u64 *)[fp - off] was a fill from the stack.
3730  		 * that [fp - off] slot contains scalar that needs to be
3731  		 * tracked with precision
3732  		 */
3733  		spi = (-insn->off - 1) / BPF_REG_SIZE;
3734  		if (spi >= 64) {
3735  			verbose(env, "BUG spi %d\n", spi);
3736  			WARN_ONCE(1, "verifier backtracking bug");
3737  			return -EFAULT;
3738  		}
3739  		bt_set_slot(bt, spi);
3740  	} else if (class == BPF_STX || class == BPF_ST) {
3741  		if (bt_is_reg_set(bt, dreg))
3742  			/* stx & st shouldn't be using _scalar_ dst_reg
3743  			 * to access memory. It means backtracking
3744  			 * encountered a case of pointer subtraction.
3745  			 */
3746  			return -ENOTSUPP;
3747  		/* scalars can only be spilled into stack */
3748  		if (insn->dst_reg != BPF_REG_FP)
3749  			return 0;
3750  		spi = (-insn->off - 1) / BPF_REG_SIZE;
3751  		if (spi >= 64) {
3752  			verbose(env, "BUG spi %d\n", spi);
3753  			WARN_ONCE(1, "verifier backtracking bug");
3754  			return -EFAULT;
3755  		}
3756  		if (!bt_is_slot_set(bt, spi))
3757  			return 0;
3758  		bt_clear_slot(bt, spi);
3759  		if (class == BPF_STX)
3760  			bt_set_reg(bt, sreg);
3761  	} else if (class == BPF_JMP || class == BPF_JMP32) {
3762  		if (bpf_pseudo_call(insn)) {
3763  			int subprog_insn_idx, subprog;
3764  
3765  			subprog_insn_idx = idx + insn->imm + 1;
3766  			subprog = find_subprog(env, subprog_insn_idx);
3767  			if (subprog < 0)
3768  				return -EFAULT;
3769  
3770  			if (subprog_is_global(env, subprog)) {
3771  				/* check that jump history doesn't have any
3772  				 * extra instructions from subprog; the next
3773  				 * instruction after call to global subprog
3774  				 * should be literally next instruction in
3775  				 * caller program
3776  				 */
3777  				WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3778  				/* r1-r5 are invalidated after subprog call,
3779  				 * so for global func call it shouldn't be set
3780  				 * anymore
3781  				 */
3782  				if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3783  					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3784  					WARN_ONCE(1, "verifier backtracking bug");
3785  					return -EFAULT;
3786  				}
3787  				/* global subprog always sets R0 */
3788  				bt_clear_reg(bt, BPF_REG_0);
3789  				return 0;
3790  			} else {
3791  				/* static subprog call instruction, which
3792  				 * means that we are exiting current subprog,
3793  				 * so only r1-r5 could be still requested as
3794  				 * precise, r0 and r6-r10 or any stack slot in
3795  				 * the current frame should be zero by now
3796  				 */
3797  				if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3798  					verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3799  					WARN_ONCE(1, "verifier backtracking bug");
3800  					return -EFAULT;
3801  				}
3802  				/* we don't track register spills perfectly,
3803  				 * so fallback to force-precise instead of failing */
3804  				if (bt_stack_mask(bt) != 0)
3805  					return -ENOTSUPP;
3806  				/* propagate r1-r5 to the caller */
3807  				for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3808  					if (bt_is_reg_set(bt, i)) {
3809  						bt_clear_reg(bt, i);
3810  						bt_set_frame_reg(bt, bt->frame - 1, i);
3811  					}
3812  				}
3813  				if (bt_subprog_exit(bt))
3814  					return -EFAULT;
3815  				return 0;
3816  			}
3817  		} else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3818  			/* exit from callback subprog to callback-calling helper or
3819  			 * kfunc call. Use idx/subseq_idx check to discern it from
3820  			 * straight line code backtracking.
3821  			 * Unlike the subprog call handling above, we shouldn't
3822  			 * propagate precision of r1-r5 (if any requested), as they are
3823  			 * not actually arguments passed directly to callback subprogs
3824  			 */
3825  			if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3826  				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3827  				WARN_ONCE(1, "verifier backtracking bug");
3828  				return -EFAULT;
3829  			}
3830  			if (bt_stack_mask(bt) != 0)
3831  				return -ENOTSUPP;
3832  			/* clear r1-r5 in callback subprog's mask */
3833  			for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3834  				bt_clear_reg(bt, i);
3835  			if (bt_subprog_exit(bt))
3836  				return -EFAULT;
3837  			return 0;
3838  		} else if (opcode == BPF_CALL) {
3839  			/* kfunc with imm==0 is invalid and fixup_kfunc_call will
3840  			 * catch this error later. Make backtracking conservative
3841  			 * with ENOTSUPP.
3842  			 */
3843  			if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3844  				return -ENOTSUPP;
3845  			/* regular helper call sets R0 */
3846  			bt_clear_reg(bt, BPF_REG_0);
3847  			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3848  				/* if backtracing was looking for registers R1-R5
3849  				 * they should have been found already.
3850  				 */
3851  				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3852  				WARN_ONCE(1, "verifier backtracking bug");
3853  				return -EFAULT;
3854  			}
3855  		} else if (opcode == BPF_EXIT) {
3856  			bool r0_precise;
3857  
3858  			/* Backtracking to a nested function call, 'idx' is a part of
3859  			 * the inner frame 'subseq_idx' is a part of the outer frame.
3860  			 * In case of a regular function call, instructions giving
3861  			 * precision to registers R1-R5 should have been found already.
3862  			 * In case of a callback, it is ok to have R1-R5 marked for
3863  			 * backtracking, as these registers are set by the function
3864  			 * invoking callback.
3865  			 */
3866  			if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3867  				for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3868  					bt_clear_reg(bt, i);
3869  			if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3870  				verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3871  				WARN_ONCE(1, "verifier backtracking bug");
3872  				return -EFAULT;
3873  			}
3874  
3875  			/* BPF_EXIT in subprog or callback always returns
3876  			 * right after the call instruction, so by checking
3877  			 * whether the instruction at subseq_idx-1 is subprog
3878  			 * call or not we can distinguish actual exit from
3879  			 * *subprog* from exit from *callback*. In the former
3880  			 * case, we need to propagate r0 precision, if
3881  			 * necessary. In the former we never do that.
3882  			 */
3883  			r0_precise = subseq_idx - 1 >= 0 &&
3884  				     bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3885  				     bt_is_reg_set(bt, BPF_REG_0);
3886  
3887  			bt_clear_reg(bt, BPF_REG_0);
3888  			if (bt_subprog_enter(bt))
3889  				return -EFAULT;
3890  
3891  			if (r0_precise)
3892  				bt_set_reg(bt, BPF_REG_0);
3893  			/* r6-r9 and stack slots will stay set in caller frame
3894  			 * bitmasks until we return back from callee(s)
3895  			 */
3896  			return 0;
3897  		} else if (BPF_SRC(insn->code) == BPF_X) {
3898  			if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3899  				return 0;
3900  			/* dreg <cond> sreg
3901  			 * Both dreg and sreg need precision before
3902  			 * this insn. If only sreg was marked precise
3903  			 * before it would be equally necessary to
3904  			 * propagate it to dreg.
3905  			 */
3906  			bt_set_reg(bt, dreg);
3907  			bt_set_reg(bt, sreg);
3908  			 /* else dreg <cond> K
3909  			  * Only dreg still needs precision before
3910  			  * this insn, so for the K-based conditional
3911  			  * there is nothing new to be marked.
3912  			  */
3913  		}
3914  	} else if (class == BPF_LD) {
3915  		if (!bt_is_reg_set(bt, dreg))
3916  			return 0;
3917  		bt_clear_reg(bt, dreg);
3918  		/* It's ld_imm64 or ld_abs or ld_ind.
3919  		 * For ld_imm64 no further tracking of precision
3920  		 * into parent is necessary
3921  		 */
3922  		if (mode == BPF_IND || mode == BPF_ABS)
3923  			/* to be analyzed */
3924  			return -ENOTSUPP;
3925  	}
3926  	return 0;
3927  }
3928  
3929  /* the scalar precision tracking algorithm:
3930   * . at the start all registers have precise=false.
3931   * . scalar ranges are tracked as normal through alu and jmp insns.
3932   * . once precise value of the scalar register is used in:
3933   *   .  ptr + scalar alu
3934   *   . if (scalar cond K|scalar)
3935   *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3936   *   backtrack through the verifier states and mark all registers and
3937   *   stack slots with spilled constants that these scalar regisers
3938   *   should be precise.
3939   * . during state pruning two registers (or spilled stack slots)
3940   *   are equivalent if both are not precise.
3941   *
3942   * Note the verifier cannot simply walk register parentage chain,
3943   * since many different registers and stack slots could have been
3944   * used to compute single precise scalar.
3945   *
3946   * The approach of starting with precise=true for all registers and then
3947   * backtrack to mark a register as not precise when the verifier detects
3948   * that program doesn't care about specific value (e.g., when helper
3949   * takes register as ARG_ANYTHING parameter) is not safe.
3950   *
3951   * It's ok to walk single parentage chain of the verifier states.
3952   * It's possible that this backtracking will go all the way till 1st insn.
3953   * All other branches will be explored for needing precision later.
3954   *
3955   * The backtracking needs to deal with cases like:
3956   *   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)
3957   * r9 -= r8
3958   * r5 = r9
3959   * if r5 > 0x79f goto pc+7
3960   *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3961   * r5 += 1
3962   * ...
3963   * call bpf_perf_event_output#25
3964   *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3965   *
3966   * and this case:
3967   * r6 = 1
3968   * call foo // uses callee's r6 inside to compute r0
3969   * r0 += r6
3970   * if r0 == 0 goto
3971   *
3972   * to track above reg_mask/stack_mask needs to be independent for each frame.
3973   *
3974   * Also if parent's curframe > frame where backtracking started,
3975   * the verifier need to mark registers in both frames, otherwise callees
3976   * may incorrectly prune callers. This is similar to
3977   * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3978   *
3979   * For now backtracking falls back into conservative marking.
3980   */
mark_all_scalars_precise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)3981  static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3982  				     struct bpf_verifier_state *st)
3983  {
3984  	struct bpf_func_state *func;
3985  	struct bpf_reg_state *reg;
3986  	int i, j;
3987  
3988  	if (env->log.level & BPF_LOG_LEVEL2) {
3989  		verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3990  			st->curframe);
3991  	}
3992  
3993  	/* big hammer: mark all scalars precise in this path.
3994  	 * pop_stack may still get !precise scalars.
3995  	 * We also skip current state and go straight to first parent state,
3996  	 * because precision markings in current non-checkpointed state are
3997  	 * not needed. See why in the comment in __mark_chain_precision below.
3998  	 */
3999  	for (st = st->parent; st; st = st->parent) {
4000  		for (i = 0; i <= st->curframe; i++) {
4001  			func = st->frame[i];
4002  			for (j = 0; j < BPF_REG_FP; j++) {
4003  				reg = &func->regs[j];
4004  				if (reg->type != SCALAR_VALUE || reg->precise)
4005  					continue;
4006  				reg->precise = true;
4007  				if (env->log.level & BPF_LOG_LEVEL2) {
4008  					verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4009  						i, j);
4010  				}
4011  			}
4012  			for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4013  				if (!is_spilled_reg(&func->stack[j]))
4014  					continue;
4015  				reg = &func->stack[j].spilled_ptr;
4016  				if (reg->type != SCALAR_VALUE || reg->precise)
4017  					continue;
4018  				reg->precise = true;
4019  				if (env->log.level & BPF_LOG_LEVEL2) {
4020  					verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4021  						i, -(j + 1) * 8);
4022  				}
4023  			}
4024  		}
4025  	}
4026  }
4027  
mark_all_scalars_imprecise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)4028  static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4029  {
4030  	struct bpf_func_state *func;
4031  	struct bpf_reg_state *reg;
4032  	int i, j;
4033  
4034  	for (i = 0; i <= st->curframe; i++) {
4035  		func = st->frame[i];
4036  		for (j = 0; j < BPF_REG_FP; j++) {
4037  			reg = &func->regs[j];
4038  			if (reg->type != SCALAR_VALUE)
4039  				continue;
4040  			reg->precise = false;
4041  		}
4042  		for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4043  			if (!is_spilled_reg(&func->stack[j]))
4044  				continue;
4045  			reg = &func->stack[j].spilled_ptr;
4046  			if (reg->type != SCALAR_VALUE)
4047  				continue;
4048  			reg->precise = false;
4049  		}
4050  	}
4051  }
4052  
idset_contains(struct bpf_idset * s,u32 id)4053  static bool idset_contains(struct bpf_idset *s, u32 id)
4054  {
4055  	u32 i;
4056  
4057  	for (i = 0; i < s->count; ++i)
4058  		if (s->ids[i] == id)
4059  			return true;
4060  
4061  	return false;
4062  }
4063  
idset_push(struct bpf_idset * s,u32 id)4064  static int idset_push(struct bpf_idset *s, u32 id)
4065  {
4066  	if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
4067  		return -EFAULT;
4068  	s->ids[s->count++] = id;
4069  	return 0;
4070  }
4071  
idset_reset(struct bpf_idset * s)4072  static void idset_reset(struct bpf_idset *s)
4073  {
4074  	s->count = 0;
4075  }
4076  
4077  /* Collect a set of IDs for all registers currently marked as precise in env->bt.
4078   * Mark all registers with these IDs as precise.
4079   */
mark_precise_scalar_ids(struct bpf_verifier_env * env,struct bpf_verifier_state * st)4080  static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4081  {
4082  	struct bpf_idset *precise_ids = &env->idset_scratch;
4083  	struct backtrack_state *bt = &env->bt;
4084  	struct bpf_func_state *func;
4085  	struct bpf_reg_state *reg;
4086  	DECLARE_BITMAP(mask, 64);
4087  	int i, fr;
4088  
4089  	idset_reset(precise_ids);
4090  
4091  	for (fr = bt->frame; fr >= 0; fr--) {
4092  		func = st->frame[fr];
4093  
4094  		bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4095  		for_each_set_bit(i, mask, 32) {
4096  			reg = &func->regs[i];
4097  			if (!reg->id || reg->type != SCALAR_VALUE)
4098  				continue;
4099  			if (idset_push(precise_ids, reg->id))
4100  				return -EFAULT;
4101  		}
4102  
4103  		bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4104  		for_each_set_bit(i, mask, 64) {
4105  			if (i >= func->allocated_stack / BPF_REG_SIZE)
4106  				break;
4107  			if (!is_spilled_scalar_reg(&func->stack[i]))
4108  				continue;
4109  			reg = &func->stack[i].spilled_ptr;
4110  			if (!reg->id)
4111  				continue;
4112  			if (idset_push(precise_ids, reg->id))
4113  				return -EFAULT;
4114  		}
4115  	}
4116  
4117  	for (fr = 0; fr <= st->curframe; ++fr) {
4118  		func = st->frame[fr];
4119  
4120  		for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4121  			reg = &func->regs[i];
4122  			if (!reg->id)
4123  				continue;
4124  			if (!idset_contains(precise_ids, reg->id))
4125  				continue;
4126  			bt_set_frame_reg(bt, fr, i);
4127  		}
4128  		for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4129  			if (!is_spilled_scalar_reg(&func->stack[i]))
4130  				continue;
4131  			reg = &func->stack[i].spilled_ptr;
4132  			if (!reg->id)
4133  				continue;
4134  			if (!idset_contains(precise_ids, reg->id))
4135  				continue;
4136  			bt_set_frame_slot(bt, fr, i);
4137  		}
4138  	}
4139  
4140  	return 0;
4141  }
4142  
4143  /*
4144   * __mark_chain_precision() backtracks BPF program instruction sequence and
4145   * chain of verifier states making sure that register *regno* (if regno >= 0)
4146   * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4147   * SCALARS, as well as any other registers and slots that contribute to
4148   * a tracked state of given registers/stack slots, depending on specific BPF
4149   * assembly instructions (see backtrack_insns() for exact instruction handling
4150   * logic). This backtracking relies on recorded jmp_history and is able to
4151   * traverse entire chain of parent states. This process ends only when all the
4152   * necessary registers/slots and their transitive dependencies are marked as
4153   * precise.
4154   *
4155   * One important and subtle aspect is that precise marks *do not matter* in
4156   * the currently verified state (current state). It is important to understand
4157   * why this is the case.
4158   *
4159   * First, note that current state is the state that is not yet "checkpointed",
4160   * i.e., it is not yet put into env->explored_states, and it has no children
4161   * states as well. It's ephemeral, and can end up either a) being discarded if
4162   * compatible explored state is found at some point or BPF_EXIT instruction is
4163   * reached or b) checkpointed and put into env->explored_states, branching out
4164   * into one or more children states.
4165   *
4166   * In the former case, precise markings in current state are completely
4167   * ignored by state comparison code (see regsafe() for details). Only
4168   * checkpointed ("old") state precise markings are important, and if old
4169   * state's register/slot is precise, regsafe() assumes current state's
4170   * register/slot as precise and checks value ranges exactly and precisely. If
4171   * states turn out to be compatible, current state's necessary precise
4172   * markings and any required parent states' precise markings are enforced
4173   * after the fact with propagate_precision() logic, after the fact. But it's
4174   * important to realize that in this case, even after marking current state
4175   * registers/slots as precise, we immediately discard current state. So what
4176   * actually matters is any of the precise markings propagated into current
4177   * state's parent states, which are always checkpointed (due to b) case above).
4178   * As such, for scenario a) it doesn't matter if current state has precise
4179   * markings set or not.
4180   *
4181   * Now, for the scenario b), checkpointing and forking into child(ren)
4182   * state(s). Note that before current state gets to checkpointing step, any
4183   * processed instruction always assumes precise SCALAR register/slot
4184   * knowledge: if precise value or range is useful to prune jump branch, BPF
4185   * verifier takes this opportunity enthusiastically. Similarly, when
4186   * register's value is used to calculate offset or memory address, exact
4187   * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4188   * what we mentioned above about state comparison ignoring precise markings
4189   * during state comparison, BPF verifier ignores and also assumes precise
4190   * markings *at will* during instruction verification process. But as verifier
4191   * assumes precision, it also propagates any precision dependencies across
4192   * parent states, which are not yet finalized, so can be further restricted
4193   * based on new knowledge gained from restrictions enforced by their children
4194   * states. This is so that once those parent states are finalized, i.e., when
4195   * they have no more active children state, state comparison logic in
4196   * is_state_visited() would enforce strict and precise SCALAR ranges, if
4197   * required for correctness.
4198   *
4199   * To build a bit more intuition, note also that once a state is checkpointed,
4200   * the path we took to get to that state is not important. This is crucial
4201   * property for state pruning. When state is checkpointed and finalized at
4202   * some instruction index, it can be correctly and safely used to "short
4203   * circuit" any *compatible* state that reaches exactly the same instruction
4204   * index. I.e., if we jumped to that instruction from a completely different
4205   * code path than original finalized state was derived from, it doesn't
4206   * matter, current state can be discarded because from that instruction
4207   * forward having a compatible state will ensure we will safely reach the
4208   * exit. States describe preconditions for further exploration, but completely
4209   * forget the history of how we got here.
4210   *
4211   * This also means that even if we needed precise SCALAR range to get to
4212   * finalized state, but from that point forward *that same* SCALAR register is
4213   * never used in a precise context (i.e., it's precise value is not needed for
4214   * correctness), it's correct and safe to mark such register as "imprecise"
4215   * (i.e., precise marking set to false). This is what we rely on when we do
4216   * not set precise marking in current state. If no child state requires
4217   * precision for any given SCALAR register, it's safe to dictate that it can
4218   * be imprecise. If any child state does require this register to be precise,
4219   * we'll mark it precise later retroactively during precise markings
4220   * propagation from child state to parent states.
4221   *
4222   * Skipping precise marking setting in current state is a mild version of
4223   * relying on the above observation. But we can utilize this property even
4224   * more aggressively by proactively forgetting any precise marking in the
4225   * current state (which we inherited from the parent state), right before we
4226   * checkpoint it and branch off into new child state. This is done by
4227   * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4228   * finalized states which help in short circuiting more future states.
4229   */
__mark_chain_precision(struct bpf_verifier_env * env,int regno)4230  static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4231  {
4232  	struct backtrack_state *bt = &env->bt;
4233  	struct bpf_verifier_state *st = env->cur_state;
4234  	int first_idx = st->first_insn_idx;
4235  	int last_idx = env->insn_idx;
4236  	int subseq_idx = -1;
4237  	struct bpf_func_state *func;
4238  	struct bpf_reg_state *reg;
4239  	bool skip_first = true;
4240  	int i, fr, err;
4241  
4242  	if (!env->bpf_capable)
4243  		return 0;
4244  
4245  	/* set frame number from which we are starting to backtrack */
4246  	bt_init(bt, env->cur_state->curframe);
4247  
4248  	/* Do sanity checks against current state of register and/or stack
4249  	 * slot, but don't set precise flag in current state, as precision
4250  	 * tracking in the current state is unnecessary.
4251  	 */
4252  	func = st->frame[bt->frame];
4253  	if (regno >= 0) {
4254  		reg = &func->regs[regno];
4255  		if (reg->type != SCALAR_VALUE) {
4256  			WARN_ONCE(1, "backtracing misuse");
4257  			return -EFAULT;
4258  		}
4259  		bt_set_reg(bt, regno);
4260  	}
4261  
4262  	if (bt_empty(bt))
4263  		return 0;
4264  
4265  	for (;;) {
4266  		DECLARE_BITMAP(mask, 64);
4267  		u32 history = st->jmp_history_cnt;
4268  
4269  		if (env->log.level & BPF_LOG_LEVEL2) {
4270  			verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4271  				bt->frame, last_idx, first_idx, subseq_idx);
4272  		}
4273  
4274  		/* If some register with scalar ID is marked as precise,
4275  		 * make sure that all registers sharing this ID are also precise.
4276  		 * This is needed to estimate effect of find_equal_scalars().
4277  		 * Do this at the last instruction of each state,
4278  		 * bpf_reg_state::id fields are valid for these instructions.
4279  		 *
4280  		 * Allows to track precision in situation like below:
4281  		 *
4282  		 *     r2 = unknown value
4283  		 *     ...
4284  		 *   --- state #0 ---
4285  		 *     ...
4286  		 *     r1 = r2                 // r1 and r2 now share the same ID
4287  		 *     ...
4288  		 *   --- state #1 {r1.id = A, r2.id = A} ---
4289  		 *     ...
4290  		 *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4291  		 *     ...
4292  		 *   --- state #2 {r1.id = A, r2.id = A} ---
4293  		 *     r3 = r10
4294  		 *     r3 += r1                // need to mark both r1 and r2
4295  		 */
4296  		if (mark_precise_scalar_ids(env, st))
4297  			return -EFAULT;
4298  
4299  		if (last_idx < 0) {
4300  			/* we are at the entry into subprog, which
4301  			 * is expected for global funcs, but only if
4302  			 * requested precise registers are R1-R5
4303  			 * (which are global func's input arguments)
4304  			 */
4305  			if (st->curframe == 0 &&
4306  			    st->frame[0]->subprogno > 0 &&
4307  			    st->frame[0]->callsite == BPF_MAIN_FUNC &&
4308  			    bt_stack_mask(bt) == 0 &&
4309  			    (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4310  				bitmap_from_u64(mask, bt_reg_mask(bt));
4311  				for_each_set_bit(i, mask, 32) {
4312  					reg = &st->frame[0]->regs[i];
4313  					bt_clear_reg(bt, i);
4314  					if (reg->type == SCALAR_VALUE)
4315  						reg->precise = true;
4316  				}
4317  				return 0;
4318  			}
4319  
4320  			verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4321  				st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4322  			WARN_ONCE(1, "verifier backtracking bug");
4323  			return -EFAULT;
4324  		}
4325  
4326  		for (i = last_idx;;) {
4327  			if (skip_first) {
4328  				err = 0;
4329  				skip_first = false;
4330  			} else {
4331  				err = backtrack_insn(env, i, subseq_idx, bt);
4332  			}
4333  			if (err == -ENOTSUPP) {
4334  				mark_all_scalars_precise(env, env->cur_state);
4335  				bt_reset(bt);
4336  				return 0;
4337  			} else if (err) {
4338  				return err;
4339  			}
4340  			if (bt_empty(bt))
4341  				/* Found assignment(s) into tracked register in this state.
4342  				 * Since this state is already marked, just return.
4343  				 * Nothing to be tracked further in the parent state.
4344  				 */
4345  				return 0;
4346  			subseq_idx = i;
4347  			i = get_prev_insn_idx(st, i, &history);
4348  			if (i == -ENOENT)
4349  				break;
4350  			if (i >= env->prog->len) {
4351  				/* This can happen if backtracking reached insn 0
4352  				 * and there are still reg_mask or stack_mask
4353  				 * to backtrack.
4354  				 * It means the backtracking missed the spot where
4355  				 * particular register was initialized with a constant.
4356  				 */
4357  				verbose(env, "BUG backtracking idx %d\n", i);
4358  				WARN_ONCE(1, "verifier backtracking bug");
4359  				return -EFAULT;
4360  			}
4361  		}
4362  		st = st->parent;
4363  		if (!st)
4364  			break;
4365  
4366  		for (fr = bt->frame; fr >= 0; fr--) {
4367  			func = st->frame[fr];
4368  			bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4369  			for_each_set_bit(i, mask, 32) {
4370  				reg = &func->regs[i];
4371  				if (reg->type != SCALAR_VALUE) {
4372  					bt_clear_frame_reg(bt, fr, i);
4373  					continue;
4374  				}
4375  				if (reg->precise)
4376  					bt_clear_frame_reg(bt, fr, i);
4377  				else
4378  					reg->precise = true;
4379  			}
4380  
4381  			bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4382  			for_each_set_bit(i, mask, 64) {
4383  				if (i >= func->allocated_stack / BPF_REG_SIZE) {
4384  					/* the sequence of instructions:
4385  					 * 2: (bf) r3 = r10
4386  					 * 3: (7b) *(u64 *)(r3 -8) = r0
4387  					 * 4: (79) r4 = *(u64 *)(r10 -8)
4388  					 * doesn't contain jmps. It's backtracked
4389  					 * as a single block.
4390  					 * During backtracking insn 3 is not recognized as
4391  					 * stack access, so at the end of backtracking
4392  					 * stack slot fp-8 is still marked in stack_mask.
4393  					 * However the parent state may not have accessed
4394  					 * fp-8 and it's "unallocated" stack space.
4395  					 * In such case fallback to conservative.
4396  					 */
4397  					mark_all_scalars_precise(env, env->cur_state);
4398  					bt_reset(bt);
4399  					return 0;
4400  				}
4401  
4402  				if (!is_spilled_scalar_reg(&func->stack[i])) {
4403  					bt_clear_frame_slot(bt, fr, i);
4404  					continue;
4405  				}
4406  				reg = &func->stack[i].spilled_ptr;
4407  				if (reg->precise)
4408  					bt_clear_frame_slot(bt, fr, i);
4409  				else
4410  					reg->precise = true;
4411  			}
4412  			if (env->log.level & BPF_LOG_LEVEL2) {
4413  				fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4414  					     bt_frame_reg_mask(bt, fr));
4415  				verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4416  					fr, env->tmp_str_buf);
4417  				fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4418  					       bt_frame_stack_mask(bt, fr));
4419  				verbose(env, "stack=%s: ", env->tmp_str_buf);
4420  				print_verifier_state(env, func, true);
4421  			}
4422  		}
4423  
4424  		if (bt_empty(bt))
4425  			return 0;
4426  
4427  		subseq_idx = first_idx;
4428  		last_idx = st->last_insn_idx;
4429  		first_idx = st->first_insn_idx;
4430  	}
4431  
4432  	/* if we still have requested precise regs or slots, we missed
4433  	 * something (e.g., stack access through non-r10 register), so
4434  	 * fallback to marking all precise
4435  	 */
4436  	if (!bt_empty(bt)) {
4437  		mark_all_scalars_precise(env, env->cur_state);
4438  		bt_reset(bt);
4439  	}
4440  
4441  	return 0;
4442  }
4443  
mark_chain_precision(struct bpf_verifier_env * env,int regno)4444  int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4445  {
4446  	return __mark_chain_precision(env, regno);
4447  }
4448  
4449  /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4450   * desired reg and stack masks across all relevant frames
4451   */
mark_chain_precision_batch(struct bpf_verifier_env * env)4452  static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4453  {
4454  	return __mark_chain_precision(env, -1);
4455  }
4456  
is_spillable_regtype(enum bpf_reg_type type)4457  static bool is_spillable_regtype(enum bpf_reg_type type)
4458  {
4459  	switch (base_type(type)) {
4460  	case PTR_TO_MAP_VALUE:
4461  	case PTR_TO_STACK:
4462  	case PTR_TO_CTX:
4463  	case PTR_TO_PACKET:
4464  	case PTR_TO_PACKET_META:
4465  	case PTR_TO_PACKET_END:
4466  	case PTR_TO_FLOW_KEYS:
4467  	case CONST_PTR_TO_MAP:
4468  	case PTR_TO_SOCKET:
4469  	case PTR_TO_SOCK_COMMON:
4470  	case PTR_TO_TCP_SOCK:
4471  	case PTR_TO_XDP_SOCK:
4472  	case PTR_TO_BTF_ID:
4473  	case PTR_TO_BUF:
4474  	case PTR_TO_MEM:
4475  	case PTR_TO_FUNC:
4476  	case PTR_TO_MAP_KEY:
4477  		return true;
4478  	default:
4479  		return false;
4480  	}
4481  }
4482  
4483  /* Does this register contain a constant zero? */
register_is_null(struct bpf_reg_state * reg)4484  static bool register_is_null(struct bpf_reg_state *reg)
4485  {
4486  	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4487  }
4488  
register_is_const(struct bpf_reg_state * reg)4489  static bool register_is_const(struct bpf_reg_state *reg)
4490  {
4491  	return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4492  }
4493  
__is_scalar_unbounded(struct bpf_reg_state * reg)4494  static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4495  {
4496  	return tnum_is_unknown(reg->var_off) &&
4497  	       reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4498  	       reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4499  	       reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4500  	       reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4501  }
4502  
register_is_bounded(struct bpf_reg_state * reg)4503  static bool register_is_bounded(struct bpf_reg_state *reg)
4504  {
4505  	return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4506  }
4507  
__is_pointer_value(bool allow_ptr_leaks,const struct bpf_reg_state * reg)4508  static bool __is_pointer_value(bool allow_ptr_leaks,
4509  			       const struct bpf_reg_state *reg)
4510  {
4511  	if (allow_ptr_leaks)
4512  		return false;
4513  
4514  	return reg->type != SCALAR_VALUE;
4515  }
4516  
4517  /* Copy src state preserving dst->parent and dst->live fields */
copy_register_state(struct bpf_reg_state * dst,const struct bpf_reg_state * src)4518  static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4519  {
4520  	struct bpf_reg_state *parent = dst->parent;
4521  	enum bpf_reg_liveness live = dst->live;
4522  
4523  	*dst = *src;
4524  	dst->parent = parent;
4525  	dst->live = live;
4526  }
4527  
save_register_state(struct bpf_func_state * state,int spi,struct bpf_reg_state * reg,int size)4528  static void save_register_state(struct bpf_func_state *state,
4529  				int spi, struct bpf_reg_state *reg,
4530  				int size)
4531  {
4532  	int i;
4533  
4534  	copy_register_state(&state->stack[spi].spilled_ptr, reg);
4535  	if (size == BPF_REG_SIZE)
4536  		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4537  
4538  	for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4539  		state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4540  
4541  	/* size < 8 bytes spill */
4542  	for (; i; i--)
4543  		scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4544  }
4545  
is_bpf_st_mem(struct bpf_insn * insn)4546  static bool is_bpf_st_mem(struct bpf_insn *insn)
4547  {
4548  	return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4549  }
4550  
4551  /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4552   * stack boundary and alignment are checked in check_mem_access()
4553   */
check_stack_write_fixed_off(struct bpf_verifier_env * env,struct bpf_func_state * state,int off,int size,int value_regno,int insn_idx)4554  static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4555  				       /* stack frame we're writing to */
4556  				       struct bpf_func_state *state,
4557  				       int off, int size, int value_regno,
4558  				       int insn_idx)
4559  {
4560  	struct bpf_func_state *cur; /* state of the current function */
4561  	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4562  	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4563  	struct bpf_reg_state *reg = NULL;
4564  	u32 dst_reg = insn->dst_reg;
4565  
4566  	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4567  	 * so it's aligned access and [off, off + size) are within stack limits
4568  	 */
4569  	if (!env->allow_ptr_leaks &&
4570  	    is_spilled_reg(&state->stack[spi]) &&
4571  	    !is_spilled_scalar_reg(&state->stack[spi]) &&
4572  	    size != BPF_REG_SIZE) {
4573  		verbose(env, "attempt to corrupt spilled pointer on stack\n");
4574  		return -EACCES;
4575  	}
4576  
4577  	cur = env->cur_state->frame[env->cur_state->curframe];
4578  	if (value_regno >= 0)
4579  		reg = &cur->regs[value_regno];
4580  	if (!env->bypass_spec_v4) {
4581  		bool sanitize = reg && is_spillable_regtype(reg->type);
4582  
4583  		for (i = 0; i < size; i++) {
4584  			u8 type = state->stack[spi].slot_type[i];
4585  
4586  			if (type != STACK_MISC && type != STACK_ZERO) {
4587  				sanitize = true;
4588  				break;
4589  			}
4590  		}
4591  
4592  		if (sanitize)
4593  			env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4594  	}
4595  
4596  	err = destroy_if_dynptr_stack_slot(env, state, spi);
4597  	if (err)
4598  		return err;
4599  
4600  	mark_stack_slot_scratched(env, spi);
4601  	if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4602  	    !register_is_null(reg) && env->bpf_capable) {
4603  		if (dst_reg != BPF_REG_FP) {
4604  			/* The backtracking logic can only recognize explicit
4605  			 * stack slot address like [fp - 8]. Other spill of
4606  			 * scalar via different register has to be conservative.
4607  			 * Backtrack from here and mark all registers as precise
4608  			 * that contributed into 'reg' being a constant.
4609  			 */
4610  			err = mark_chain_precision(env, value_regno);
4611  			if (err)
4612  				return err;
4613  		}
4614  		save_register_state(state, spi, reg, size);
4615  		/* Break the relation on a narrowing spill. */
4616  		if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4617  			state->stack[spi].spilled_ptr.id = 0;
4618  	} else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4619  		   insn->imm != 0 && env->bpf_capable) {
4620  		struct bpf_reg_state fake_reg = {};
4621  
4622  		__mark_reg_known(&fake_reg, insn->imm);
4623  		fake_reg.type = SCALAR_VALUE;
4624  		save_register_state(state, spi, &fake_reg, size);
4625  	} else if (reg && is_spillable_regtype(reg->type)) {
4626  		/* register containing pointer is being spilled into stack */
4627  		if (size != BPF_REG_SIZE) {
4628  			verbose_linfo(env, insn_idx, "; ");
4629  			verbose(env, "invalid size of register spill\n");
4630  			return -EACCES;
4631  		}
4632  		if (state != cur && reg->type == PTR_TO_STACK) {
4633  			verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4634  			return -EINVAL;
4635  		}
4636  		save_register_state(state, spi, reg, size);
4637  	} else {
4638  		u8 type = STACK_MISC;
4639  
4640  		/* regular write of data into stack destroys any spilled ptr */
4641  		state->stack[spi].spilled_ptr.type = NOT_INIT;
4642  		/* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4643  		if (is_stack_slot_special(&state->stack[spi]))
4644  			for (i = 0; i < BPF_REG_SIZE; i++)
4645  				scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4646  
4647  		/* only mark the slot as written if all 8 bytes were written
4648  		 * otherwise read propagation may incorrectly stop too soon
4649  		 * when stack slots are partially written.
4650  		 * This heuristic means that read propagation will be
4651  		 * conservative, since it will add reg_live_read marks
4652  		 * to stack slots all the way to first state when programs
4653  		 * writes+reads less than 8 bytes
4654  		 */
4655  		if (size == BPF_REG_SIZE)
4656  			state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4657  
4658  		/* when we zero initialize stack slots mark them as such */
4659  		if ((reg && register_is_null(reg)) ||
4660  		    (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4661  			/* backtracking doesn't work for STACK_ZERO yet. */
4662  			err = mark_chain_precision(env, value_regno);
4663  			if (err)
4664  				return err;
4665  			type = STACK_ZERO;
4666  		}
4667  
4668  		/* Mark slots affected by this stack write. */
4669  		for (i = 0; i < size; i++)
4670  			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4671  				type;
4672  	}
4673  	return 0;
4674  }
4675  
4676  /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4677   * known to contain a variable offset.
4678   * This function checks whether the write is permitted and conservatively
4679   * tracks the effects of the write, considering that each stack slot in the
4680   * dynamic range is potentially written to.
4681   *
4682   * 'off' includes 'regno->off'.
4683   * 'value_regno' can be -1, meaning that an unknown value is being written to
4684   * the stack.
4685   *
4686   * Spilled pointers in range are not marked as written because we don't know
4687   * what's going to be actually written. This means that read propagation for
4688   * future reads cannot be terminated by this write.
4689   *
4690   * For privileged programs, uninitialized stack slots are considered
4691   * initialized by this write (even though we don't know exactly what offsets
4692   * are going to be written to). The idea is that we don't want the verifier to
4693   * reject future reads that access slots written to through variable offsets.
4694   */
check_stack_write_var_off(struct bpf_verifier_env * env,struct bpf_func_state * state,int ptr_regno,int off,int size,int value_regno,int insn_idx)4695  static int check_stack_write_var_off(struct bpf_verifier_env *env,
4696  				     /* func where register points to */
4697  				     struct bpf_func_state *state,
4698  				     int ptr_regno, int off, int size,
4699  				     int value_regno, int insn_idx)
4700  {
4701  	struct bpf_func_state *cur; /* state of the current function */
4702  	int min_off, max_off;
4703  	int i, err;
4704  	struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4705  	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4706  	bool writing_zero = false;
4707  	/* set if the fact that we're writing a zero is used to let any
4708  	 * stack slots remain STACK_ZERO
4709  	 */
4710  	bool zero_used = false;
4711  
4712  	cur = env->cur_state->frame[env->cur_state->curframe];
4713  	ptr_reg = &cur->regs[ptr_regno];
4714  	min_off = ptr_reg->smin_value + off;
4715  	max_off = ptr_reg->smax_value + off + size;
4716  	if (value_regno >= 0)
4717  		value_reg = &cur->regs[value_regno];
4718  	if ((value_reg && register_is_null(value_reg)) ||
4719  	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4720  		writing_zero = true;
4721  
4722  	for (i = min_off; i < max_off; i++) {
4723  		int spi;
4724  
4725  		spi = __get_spi(i);
4726  		err = destroy_if_dynptr_stack_slot(env, state, spi);
4727  		if (err)
4728  			return err;
4729  	}
4730  
4731  	/* Variable offset writes destroy any spilled pointers in range. */
4732  	for (i = min_off; i < max_off; i++) {
4733  		u8 new_type, *stype;
4734  		int slot, spi;
4735  
4736  		slot = -i - 1;
4737  		spi = slot / BPF_REG_SIZE;
4738  		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4739  		mark_stack_slot_scratched(env, spi);
4740  
4741  		if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4742  			/* Reject the write if range we may write to has not
4743  			 * been initialized beforehand. If we didn't reject
4744  			 * here, the ptr status would be erased below (even
4745  			 * though not all slots are actually overwritten),
4746  			 * possibly opening the door to leaks.
4747  			 *
4748  			 * We do however catch STACK_INVALID case below, and
4749  			 * only allow reading possibly uninitialized memory
4750  			 * later for CAP_PERFMON, as the write may not happen to
4751  			 * that slot.
4752  			 */
4753  			verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4754  				insn_idx, i);
4755  			return -EINVAL;
4756  		}
4757  
4758  		/* Erase all spilled pointers. */
4759  		state->stack[spi].spilled_ptr.type = NOT_INIT;
4760  
4761  		/* Update the slot type. */
4762  		new_type = STACK_MISC;
4763  		if (writing_zero && *stype == STACK_ZERO) {
4764  			new_type = STACK_ZERO;
4765  			zero_used = true;
4766  		}
4767  		/* If the slot is STACK_INVALID, we check whether it's OK to
4768  		 * pretend that it will be initialized by this write. The slot
4769  		 * might not actually be written to, and so if we mark it as
4770  		 * initialized future reads might leak uninitialized memory.
4771  		 * For privileged programs, we will accept such reads to slots
4772  		 * that may or may not be written because, if we're reject
4773  		 * them, the error would be too confusing.
4774  		 */
4775  		if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4776  			verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4777  					insn_idx, i);
4778  			return -EINVAL;
4779  		}
4780  		*stype = new_type;
4781  	}
4782  	if (zero_used) {
4783  		/* backtracking doesn't work for STACK_ZERO yet. */
4784  		err = mark_chain_precision(env, value_regno);
4785  		if (err)
4786  			return err;
4787  	}
4788  	return 0;
4789  }
4790  
4791  /* When register 'dst_regno' is assigned some values from stack[min_off,
4792   * max_off), we set the register's type according to the types of the
4793   * respective stack slots. If all the stack values are known to be zeros, then
4794   * so is the destination reg. Otherwise, the register is considered to be
4795   * SCALAR. This function does not deal with register filling; the caller must
4796   * ensure that all spilled registers in the stack range have been marked as
4797   * read.
4798   */
mark_reg_stack_read(struct bpf_verifier_env * env,struct bpf_func_state * ptr_state,int min_off,int max_off,int dst_regno)4799  static void mark_reg_stack_read(struct bpf_verifier_env *env,
4800  				/* func where src register points to */
4801  				struct bpf_func_state *ptr_state,
4802  				int min_off, int max_off, int dst_regno)
4803  {
4804  	struct bpf_verifier_state *vstate = env->cur_state;
4805  	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4806  	int i, slot, spi;
4807  	u8 *stype;
4808  	int zeros = 0;
4809  
4810  	for (i = min_off; i < max_off; i++) {
4811  		slot = -i - 1;
4812  		spi = slot / BPF_REG_SIZE;
4813  		mark_stack_slot_scratched(env, spi);
4814  		stype = ptr_state->stack[spi].slot_type;
4815  		if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4816  			break;
4817  		zeros++;
4818  	}
4819  	if (zeros == max_off - min_off) {
4820  		/* any access_size read into register is zero extended,
4821  		 * so the whole register == const_zero
4822  		 */
4823  		__mark_reg_const_zero(&state->regs[dst_regno]);
4824  		/* backtracking doesn't support STACK_ZERO yet,
4825  		 * so mark it precise here, so that later
4826  		 * backtracking can stop here.
4827  		 * Backtracking may not need this if this register
4828  		 * doesn't participate in pointer adjustment.
4829  		 * Forward propagation of precise flag is not
4830  		 * necessary either. This mark is only to stop
4831  		 * backtracking. Any register that contributed
4832  		 * to const 0 was marked precise before spill.
4833  		 */
4834  		state->regs[dst_regno].precise = true;
4835  	} else {
4836  		/* have read misc data from the stack */
4837  		mark_reg_unknown(env, state->regs, dst_regno);
4838  	}
4839  	state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4840  }
4841  
4842  /* Read the stack at 'off' and put the results into the register indicated by
4843   * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4844   * spilled reg.
4845   *
4846   * 'dst_regno' can be -1, meaning that the read value is not going to a
4847   * register.
4848   *
4849   * The access is assumed to be within the current stack bounds.
4850   */
check_stack_read_fixed_off(struct bpf_verifier_env * env,struct bpf_func_state * reg_state,int off,int size,int dst_regno)4851  static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4852  				      /* func where src register points to */
4853  				      struct bpf_func_state *reg_state,
4854  				      int off, int size, int dst_regno)
4855  {
4856  	struct bpf_verifier_state *vstate = env->cur_state;
4857  	struct bpf_func_state *state = vstate->frame[vstate->curframe];
4858  	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4859  	struct bpf_reg_state *reg;
4860  	u8 *stype, type;
4861  
4862  	stype = reg_state->stack[spi].slot_type;
4863  	reg = &reg_state->stack[spi].spilled_ptr;
4864  
4865  	mark_stack_slot_scratched(env, spi);
4866  
4867  	if (is_spilled_reg(&reg_state->stack[spi])) {
4868  		u8 spill_size = 1;
4869  
4870  		for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4871  			spill_size++;
4872  
4873  		if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4874  			if (reg->type != SCALAR_VALUE) {
4875  				verbose_linfo(env, env->insn_idx, "; ");
4876  				verbose(env, "invalid size of register fill\n");
4877  				return -EACCES;
4878  			}
4879  
4880  			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4881  			if (dst_regno < 0)
4882  				return 0;
4883  
4884  			if (!(off % BPF_REG_SIZE) && size == spill_size) {
4885  				/* The earlier check_reg_arg() has decided the
4886  				 * subreg_def for this insn.  Save it first.
4887  				 */
4888  				s32 subreg_def = state->regs[dst_regno].subreg_def;
4889  
4890  				copy_register_state(&state->regs[dst_regno], reg);
4891  				state->regs[dst_regno].subreg_def = subreg_def;
4892  			} else {
4893  				for (i = 0; i < size; i++) {
4894  					type = stype[(slot - i) % BPF_REG_SIZE];
4895  					if (type == STACK_SPILL)
4896  						continue;
4897  					if (type == STACK_MISC)
4898  						continue;
4899  					if (type == STACK_INVALID && env->allow_uninit_stack)
4900  						continue;
4901  					verbose(env, "invalid read from stack off %d+%d size %d\n",
4902  						off, i, size);
4903  					return -EACCES;
4904  				}
4905  				mark_reg_unknown(env, state->regs, dst_regno);
4906  			}
4907  			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4908  			return 0;
4909  		}
4910  
4911  		if (dst_regno >= 0) {
4912  			/* restore register state from stack */
4913  			copy_register_state(&state->regs[dst_regno], reg);
4914  			/* mark reg as written since spilled pointer state likely
4915  			 * has its liveness marks cleared by is_state_visited()
4916  			 * which resets stack/reg liveness for state transitions
4917  			 */
4918  			state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4919  		} else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4920  			/* If dst_regno==-1, the caller is asking us whether
4921  			 * it is acceptable to use this value as a SCALAR_VALUE
4922  			 * (e.g. for XADD).
4923  			 * We must not allow unprivileged callers to do that
4924  			 * with spilled pointers.
4925  			 */
4926  			verbose(env, "leaking pointer from stack off %d\n",
4927  				off);
4928  			return -EACCES;
4929  		}
4930  		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4931  	} else {
4932  		for (i = 0; i < size; i++) {
4933  			type = stype[(slot - i) % BPF_REG_SIZE];
4934  			if (type == STACK_MISC)
4935  				continue;
4936  			if (type == STACK_ZERO)
4937  				continue;
4938  			if (type == STACK_INVALID && env->allow_uninit_stack)
4939  				continue;
4940  			verbose(env, "invalid read from stack off %d+%d size %d\n",
4941  				off, i, size);
4942  			return -EACCES;
4943  		}
4944  		mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4945  		if (dst_regno >= 0)
4946  			mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4947  	}
4948  	return 0;
4949  }
4950  
4951  enum bpf_access_src {
4952  	ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4953  	ACCESS_HELPER = 2,  /* the access is performed by a helper */
4954  };
4955  
4956  static int check_stack_range_initialized(struct bpf_verifier_env *env,
4957  					 int regno, int off, int access_size,
4958  					 bool zero_size_allowed,
4959  					 enum bpf_access_src type,
4960  					 struct bpf_call_arg_meta *meta);
4961  
reg_state(struct bpf_verifier_env * env,int regno)4962  static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4963  {
4964  	return cur_regs(env) + regno;
4965  }
4966  
4967  /* Read the stack at 'ptr_regno + off' and put the result into the register
4968   * 'dst_regno'.
4969   * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4970   * but not its variable offset.
4971   * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4972   *
4973   * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4974   * filling registers (i.e. reads of spilled register cannot be detected when
4975   * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4976   * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4977   * offset; for a fixed offset check_stack_read_fixed_off should be used
4978   * instead.
4979   */
check_stack_read_var_off(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)4980  static int check_stack_read_var_off(struct bpf_verifier_env *env,
4981  				    int ptr_regno, int off, int size, int dst_regno)
4982  {
4983  	/* The state of the source register. */
4984  	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4985  	struct bpf_func_state *ptr_state = func(env, reg);
4986  	int err;
4987  	int min_off, max_off;
4988  
4989  	/* Note that we pass a NULL meta, so raw access will not be permitted.
4990  	 */
4991  	err = check_stack_range_initialized(env, ptr_regno, off, size,
4992  					    false, ACCESS_DIRECT, NULL);
4993  	if (err)
4994  		return err;
4995  
4996  	min_off = reg->smin_value + off;
4997  	max_off = reg->smax_value + off;
4998  	mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4999  	return 0;
5000  }
5001  
5002  /* check_stack_read dispatches to check_stack_read_fixed_off or
5003   * check_stack_read_var_off.
5004   *
5005   * The caller must ensure that the offset falls within the allocated stack
5006   * bounds.
5007   *
5008   * 'dst_regno' is a register which will receive the value from the stack. It
5009   * can be -1, meaning that the read value is not going to a register.
5010   */
check_stack_read(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)5011  static int check_stack_read(struct bpf_verifier_env *env,
5012  			    int ptr_regno, int off, int size,
5013  			    int dst_regno)
5014  {
5015  	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5016  	struct bpf_func_state *state = func(env, reg);
5017  	int err;
5018  	/* Some accesses are only permitted with a static offset. */
5019  	bool var_off = !tnum_is_const(reg->var_off);
5020  
5021  	/* The offset is required to be static when reads don't go to a
5022  	 * register, in order to not leak pointers (see
5023  	 * check_stack_read_fixed_off).
5024  	 */
5025  	if (dst_regno < 0 && var_off) {
5026  		char tn_buf[48];
5027  
5028  		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5029  		verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5030  			tn_buf, off, size);
5031  		return -EACCES;
5032  	}
5033  	/* Variable offset is prohibited for unprivileged mode for simplicity
5034  	 * since it requires corresponding support in Spectre masking for stack
5035  	 * ALU. See also retrieve_ptr_limit(). The check in
5036  	 * check_stack_access_for_ptr_arithmetic() called by
5037  	 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5038  	 * with variable offsets, therefore no check is required here. Further,
5039  	 * just checking it here would be insufficient as speculative stack
5040  	 * writes could still lead to unsafe speculative behaviour.
5041  	 */
5042  	if (!var_off) {
5043  		off += reg->var_off.value;
5044  		err = check_stack_read_fixed_off(env, state, off, size,
5045  						 dst_regno);
5046  	} else {
5047  		/* Variable offset stack reads need more conservative handling
5048  		 * than fixed offset ones. Note that dst_regno >= 0 on this
5049  		 * branch.
5050  		 */
5051  		err = check_stack_read_var_off(env, ptr_regno, off, size,
5052  					       dst_regno);
5053  	}
5054  	return err;
5055  }
5056  
5057  
5058  /* check_stack_write dispatches to check_stack_write_fixed_off or
5059   * check_stack_write_var_off.
5060   *
5061   * 'ptr_regno' is the register used as a pointer into the stack.
5062   * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5063   * 'value_regno' is the register whose value we're writing to the stack. It can
5064   * be -1, meaning that we're not writing from a register.
5065   *
5066   * The caller must ensure that the offset falls within the maximum stack size.
5067   */
check_stack_write(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int value_regno,int insn_idx)5068  static int check_stack_write(struct bpf_verifier_env *env,
5069  			     int ptr_regno, int off, int size,
5070  			     int value_regno, int insn_idx)
5071  {
5072  	struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5073  	struct bpf_func_state *state = func(env, reg);
5074  	int err;
5075  
5076  	if (tnum_is_const(reg->var_off)) {
5077  		off += reg->var_off.value;
5078  		err = check_stack_write_fixed_off(env, state, off, size,
5079  						  value_regno, insn_idx);
5080  	} else {
5081  		/* Variable offset stack reads need more conservative handling
5082  		 * than fixed offset ones.
5083  		 */
5084  		err = check_stack_write_var_off(env, state,
5085  						ptr_regno, off, size,
5086  						value_regno, insn_idx);
5087  	}
5088  	return err;
5089  }
5090  
check_map_access_type(struct bpf_verifier_env * env,u32 regno,int off,int size,enum bpf_access_type type)5091  static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5092  				 int off, int size, enum bpf_access_type type)
5093  {
5094  	struct bpf_reg_state *regs = cur_regs(env);
5095  	struct bpf_map *map = regs[regno].map_ptr;
5096  	u32 cap = bpf_map_flags_to_cap(map);
5097  
5098  	if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5099  		verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5100  			map->value_size, off, size);
5101  		return -EACCES;
5102  	}
5103  
5104  	if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5105  		verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5106  			map->value_size, off, size);
5107  		return -EACCES;
5108  	}
5109  
5110  	return 0;
5111  }
5112  
5113  /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
__check_mem_access(struct bpf_verifier_env * env,int regno,int off,int size,u32 mem_size,bool zero_size_allowed)5114  static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5115  			      int off, int size, u32 mem_size,
5116  			      bool zero_size_allowed)
5117  {
5118  	bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5119  	struct bpf_reg_state *reg;
5120  
5121  	if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5122  		return 0;
5123  
5124  	reg = &cur_regs(env)[regno];
5125  	switch (reg->type) {
5126  	case PTR_TO_MAP_KEY:
5127  		verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5128  			mem_size, off, size);
5129  		break;
5130  	case PTR_TO_MAP_VALUE:
5131  		verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5132  			mem_size, off, size);
5133  		break;
5134  	case PTR_TO_PACKET:
5135  	case PTR_TO_PACKET_META:
5136  	case PTR_TO_PACKET_END:
5137  		verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5138  			off, size, regno, reg->id, off, mem_size);
5139  		break;
5140  	case PTR_TO_MEM:
5141  	default:
5142  		verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5143  			mem_size, off, size);
5144  	}
5145  
5146  	return -EACCES;
5147  }
5148  
5149  /* check read/write into a memory region with possible variable offset */
check_mem_region_access(struct bpf_verifier_env * env,u32 regno,int off,int size,u32 mem_size,bool zero_size_allowed)5150  static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5151  				   int off, int size, u32 mem_size,
5152  				   bool zero_size_allowed)
5153  {
5154  	struct bpf_verifier_state *vstate = env->cur_state;
5155  	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5156  	struct bpf_reg_state *reg = &state->regs[regno];
5157  	int err;
5158  
5159  	/* We may have adjusted the register pointing to memory region, so we
5160  	 * need to try adding each of min_value and max_value to off
5161  	 * to make sure our theoretical access will be safe.
5162  	 *
5163  	 * The minimum value is only important with signed
5164  	 * comparisons where we can't assume the floor of a
5165  	 * value is 0.  If we are using signed variables for our
5166  	 * index'es we need to make sure that whatever we use
5167  	 * will have a set floor within our range.
5168  	 */
5169  	if (reg->smin_value < 0 &&
5170  	    (reg->smin_value == S64_MIN ||
5171  	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5172  	      reg->smin_value + off < 0)) {
5173  		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5174  			regno);
5175  		return -EACCES;
5176  	}
5177  	err = __check_mem_access(env, regno, reg->smin_value + off, size,
5178  				 mem_size, zero_size_allowed);
5179  	if (err) {
5180  		verbose(env, "R%d min value is outside of the allowed memory range\n",
5181  			regno);
5182  		return err;
5183  	}
5184  
5185  	/* If we haven't set a max value then we need to bail since we can't be
5186  	 * sure we won't do bad things.
5187  	 * If reg->umax_value + off could overflow, treat that as unbounded too.
5188  	 */
5189  	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5190  		verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5191  			regno);
5192  		return -EACCES;
5193  	}
5194  	err = __check_mem_access(env, regno, reg->umax_value + off, size,
5195  				 mem_size, zero_size_allowed);
5196  	if (err) {
5197  		verbose(env, "R%d max value is outside of the allowed memory range\n",
5198  			regno);
5199  		return err;
5200  	}
5201  
5202  	return 0;
5203  }
5204  
__check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,bool fixed_off_ok)5205  static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5206  			       const struct bpf_reg_state *reg, int regno,
5207  			       bool fixed_off_ok)
5208  {
5209  	/* Access to this pointer-typed register or passing it to a helper
5210  	 * is only allowed in its original, unmodified form.
5211  	 */
5212  
5213  	if (reg->off < 0) {
5214  		verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5215  			reg_type_str(env, reg->type), regno, reg->off);
5216  		return -EACCES;
5217  	}
5218  
5219  	if (!fixed_off_ok && reg->off) {
5220  		verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5221  			reg_type_str(env, reg->type), regno, reg->off);
5222  		return -EACCES;
5223  	}
5224  
5225  	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5226  		char tn_buf[48];
5227  
5228  		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5229  		verbose(env, "variable %s access var_off=%s disallowed\n",
5230  			reg_type_str(env, reg->type), tn_buf);
5231  		return -EACCES;
5232  	}
5233  
5234  	return 0;
5235  }
5236  
check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno)5237  int check_ptr_off_reg(struct bpf_verifier_env *env,
5238  		      const struct bpf_reg_state *reg, int regno)
5239  {
5240  	return __check_ptr_off_reg(env, reg, regno, false);
5241  }
5242  
map_kptr_match_type(struct bpf_verifier_env * env,struct btf_field * kptr_field,struct bpf_reg_state * reg,u32 regno)5243  static int map_kptr_match_type(struct bpf_verifier_env *env,
5244  			       struct btf_field *kptr_field,
5245  			       struct bpf_reg_state *reg, u32 regno)
5246  {
5247  	const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5248  	int perm_flags;
5249  	const char *reg_name = "";
5250  
5251  	if (btf_is_kernel(reg->btf)) {
5252  		perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5253  
5254  		/* Only unreferenced case accepts untrusted pointers */
5255  		if (kptr_field->type == BPF_KPTR_UNREF)
5256  			perm_flags |= PTR_UNTRUSTED;
5257  	} else {
5258  		perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5259  	}
5260  
5261  	if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5262  		goto bad_type;
5263  
5264  	/* We need to verify reg->type and reg->btf, before accessing reg->btf */
5265  	reg_name = btf_type_name(reg->btf, reg->btf_id);
5266  
5267  	/* For ref_ptr case, release function check should ensure we get one
5268  	 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5269  	 * normal store of unreferenced kptr, we must ensure var_off is zero.
5270  	 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5271  	 * reg->off and reg->ref_obj_id are not needed here.
5272  	 */
5273  	if (__check_ptr_off_reg(env, reg, regno, true))
5274  		return -EACCES;
5275  
5276  	/* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5277  	 * we also need to take into account the reg->off.
5278  	 *
5279  	 * We want to support cases like:
5280  	 *
5281  	 * struct foo {
5282  	 *         struct bar br;
5283  	 *         struct baz bz;
5284  	 * };
5285  	 *
5286  	 * struct foo *v;
5287  	 * v = func();	      // PTR_TO_BTF_ID
5288  	 * val->foo = v;      // reg->off is zero, btf and btf_id match type
5289  	 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5290  	 *                    // first member type of struct after comparison fails
5291  	 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5292  	 *                    // to match type
5293  	 *
5294  	 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5295  	 * is zero. We must also ensure that btf_struct_ids_match does not walk
5296  	 * the struct to match type against first member of struct, i.e. reject
5297  	 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5298  	 * strict mode to true for type match.
5299  	 */
5300  	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5301  				  kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5302  				  kptr_field->type == BPF_KPTR_REF))
5303  		goto bad_type;
5304  	return 0;
5305  bad_type:
5306  	verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5307  		reg_type_str(env, reg->type), reg_name);
5308  	verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5309  	if (kptr_field->type == BPF_KPTR_UNREF)
5310  		verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5311  			targ_name);
5312  	else
5313  		verbose(env, "\n");
5314  	return -EINVAL;
5315  }
5316  
5317  /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5318   * can dereference RCU protected pointers and result is PTR_TRUSTED.
5319   */
in_rcu_cs(struct bpf_verifier_env * env)5320  static bool in_rcu_cs(struct bpf_verifier_env *env)
5321  {
5322  	return env->cur_state->active_rcu_lock ||
5323  	       env->cur_state->active_lock.ptr ||
5324  	       !env->prog->aux->sleepable;
5325  }
5326  
5327  /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5328  BTF_SET_START(rcu_protected_types)
BTF_ID(struct,prog_test_ref_kfunc)5329  BTF_ID(struct, prog_test_ref_kfunc)
5330  BTF_ID(struct, cgroup)
5331  BTF_ID(struct, bpf_cpumask)
5332  BTF_ID(struct, task_struct)
5333  BTF_SET_END(rcu_protected_types)
5334  
5335  static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5336  {
5337  	if (!btf_is_kernel(btf))
5338  		return false;
5339  	return btf_id_set_contains(&rcu_protected_types, btf_id);
5340  }
5341  
rcu_safe_kptr(const struct btf_field * field)5342  static bool rcu_safe_kptr(const struct btf_field *field)
5343  {
5344  	const struct btf_field_kptr *kptr = &field->kptr;
5345  
5346  	return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5347  }
5348  
check_map_kptr_access(struct bpf_verifier_env * env,u32 regno,int value_regno,int insn_idx,struct btf_field * kptr_field)5349  static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5350  				 int value_regno, int insn_idx,
5351  				 struct btf_field *kptr_field)
5352  {
5353  	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5354  	int class = BPF_CLASS(insn->code);
5355  	struct bpf_reg_state *val_reg;
5356  
5357  	/* Things we already checked for in check_map_access and caller:
5358  	 *  - Reject cases where variable offset may touch kptr
5359  	 *  - size of access (must be BPF_DW)
5360  	 *  - tnum_is_const(reg->var_off)
5361  	 *  - kptr_field->offset == off + reg->var_off.value
5362  	 */
5363  	/* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5364  	if (BPF_MODE(insn->code) != BPF_MEM) {
5365  		verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5366  		return -EACCES;
5367  	}
5368  
5369  	/* We only allow loading referenced kptr, since it will be marked as
5370  	 * untrusted, similar to unreferenced kptr.
5371  	 */
5372  	if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5373  		verbose(env, "store to referenced kptr disallowed\n");
5374  		return -EACCES;
5375  	}
5376  
5377  	if (class == BPF_LDX) {
5378  		val_reg = reg_state(env, value_regno);
5379  		/* We can simply mark the value_regno receiving the pointer
5380  		 * value from map as PTR_TO_BTF_ID, with the correct type.
5381  		 */
5382  		mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5383  				kptr_field->kptr.btf_id,
5384  				rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5385  				PTR_MAYBE_NULL | MEM_RCU :
5386  				PTR_MAYBE_NULL | PTR_UNTRUSTED);
5387  	} else if (class == BPF_STX) {
5388  		val_reg = reg_state(env, value_regno);
5389  		if (!register_is_null(val_reg) &&
5390  		    map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5391  			return -EACCES;
5392  	} else if (class == BPF_ST) {
5393  		if (insn->imm) {
5394  			verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5395  				kptr_field->offset);
5396  			return -EACCES;
5397  		}
5398  	} else {
5399  		verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5400  		return -EACCES;
5401  	}
5402  	return 0;
5403  }
5404  
5405  /* check read/write into a map element with possible variable offset */
check_map_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed,enum bpf_access_src src)5406  static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5407  			    int off, int size, bool zero_size_allowed,
5408  			    enum bpf_access_src src)
5409  {
5410  	struct bpf_verifier_state *vstate = env->cur_state;
5411  	struct bpf_func_state *state = vstate->frame[vstate->curframe];
5412  	struct bpf_reg_state *reg = &state->regs[regno];
5413  	struct bpf_map *map = reg->map_ptr;
5414  	struct btf_record *rec;
5415  	int err, i;
5416  
5417  	err = check_mem_region_access(env, regno, off, size, map->value_size,
5418  				      zero_size_allowed);
5419  	if (err)
5420  		return err;
5421  
5422  	if (IS_ERR_OR_NULL(map->record))
5423  		return 0;
5424  	rec = map->record;
5425  	for (i = 0; i < rec->cnt; i++) {
5426  		struct btf_field *field = &rec->fields[i];
5427  		u32 p = field->offset;
5428  
5429  		/* If any part of a field  can be touched by load/store, reject
5430  		 * this program. To check that [x1, x2) overlaps with [y1, y2),
5431  		 * it is sufficient to check x1 < y2 && y1 < x2.
5432  		 */
5433  		if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5434  		    p < reg->umax_value + off + size) {
5435  			switch (field->type) {
5436  			case BPF_KPTR_UNREF:
5437  			case BPF_KPTR_REF:
5438  				if (src != ACCESS_DIRECT) {
5439  					verbose(env, "kptr cannot be accessed indirectly by helper\n");
5440  					return -EACCES;
5441  				}
5442  				if (!tnum_is_const(reg->var_off)) {
5443  					verbose(env, "kptr access cannot have variable offset\n");
5444  					return -EACCES;
5445  				}
5446  				if (p != off + reg->var_off.value) {
5447  					verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5448  						p, off + reg->var_off.value);
5449  					return -EACCES;
5450  				}
5451  				if (size != bpf_size_to_bytes(BPF_DW)) {
5452  					verbose(env, "kptr access size must be BPF_DW\n");
5453  					return -EACCES;
5454  				}
5455  				break;
5456  			default:
5457  				verbose(env, "%s cannot be accessed directly by load/store\n",
5458  					btf_field_type_name(field->type));
5459  				return -EACCES;
5460  			}
5461  		}
5462  	}
5463  	return 0;
5464  }
5465  
5466  #define MAX_PACKET_OFF 0xffff
5467  
may_access_direct_pkt_data(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_access_type t)5468  static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5469  				       const struct bpf_call_arg_meta *meta,
5470  				       enum bpf_access_type t)
5471  {
5472  	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5473  
5474  	switch (prog_type) {
5475  	/* Program types only with direct read access go here! */
5476  	case BPF_PROG_TYPE_LWT_IN:
5477  	case BPF_PROG_TYPE_LWT_OUT:
5478  	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5479  	case BPF_PROG_TYPE_SK_REUSEPORT:
5480  	case BPF_PROG_TYPE_FLOW_DISSECTOR:
5481  	case BPF_PROG_TYPE_CGROUP_SKB:
5482  		if (t == BPF_WRITE)
5483  			return false;
5484  		fallthrough;
5485  
5486  	/* Program types with direct read + write access go here! */
5487  	case BPF_PROG_TYPE_SCHED_CLS:
5488  	case BPF_PROG_TYPE_SCHED_ACT:
5489  	case BPF_PROG_TYPE_XDP:
5490  	case BPF_PROG_TYPE_LWT_XMIT:
5491  	case BPF_PROG_TYPE_SK_SKB:
5492  	case BPF_PROG_TYPE_SK_MSG:
5493  		if (meta)
5494  			return meta->pkt_access;
5495  
5496  		env->seen_direct_write = true;
5497  		return true;
5498  
5499  	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5500  		if (t == BPF_WRITE)
5501  			env->seen_direct_write = true;
5502  
5503  		return true;
5504  
5505  	default:
5506  		return false;
5507  	}
5508  }
5509  
check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)5510  static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5511  			       int size, bool zero_size_allowed)
5512  {
5513  	struct bpf_reg_state *regs = cur_regs(env);
5514  	struct bpf_reg_state *reg = &regs[regno];
5515  	int err;
5516  
5517  	/* We may have added a variable offset to the packet pointer; but any
5518  	 * reg->range we have comes after that.  We are only checking the fixed
5519  	 * offset.
5520  	 */
5521  
5522  	/* We don't allow negative numbers, because we aren't tracking enough
5523  	 * detail to prove they're safe.
5524  	 */
5525  	if (reg->smin_value < 0) {
5526  		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5527  			regno);
5528  		return -EACCES;
5529  	}
5530  
5531  	err = reg->range < 0 ? -EINVAL :
5532  	      __check_mem_access(env, regno, off, size, reg->range,
5533  				 zero_size_allowed);
5534  	if (err) {
5535  		verbose(env, "R%d offset is outside of the packet\n", regno);
5536  		return err;
5537  	}
5538  
5539  	/* __check_mem_access has made sure "off + size - 1" is within u16.
5540  	 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5541  	 * otherwise find_good_pkt_pointers would have refused to set range info
5542  	 * that __check_mem_access would have rejected this pkt access.
5543  	 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5544  	 */
5545  	env->prog->aux->max_pkt_offset =
5546  		max_t(u32, env->prog->aux->max_pkt_offset,
5547  		      off + reg->umax_value + size - 1);
5548  
5549  	return err;
5550  }
5551  
5552  /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
check_ctx_access(struct bpf_verifier_env * env,int insn_idx,int off,int size,enum bpf_access_type t,enum bpf_reg_type * reg_type,struct btf ** btf,u32 * btf_id)5553  static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5554  			    enum bpf_access_type t, enum bpf_reg_type *reg_type,
5555  			    struct btf **btf, u32 *btf_id)
5556  {
5557  	struct bpf_insn_access_aux info = {
5558  		.reg_type = *reg_type,
5559  		.log = &env->log,
5560  	};
5561  
5562  	if (env->ops->is_valid_access &&
5563  	    env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5564  		/* A non zero info.ctx_field_size indicates that this field is a
5565  		 * candidate for later verifier transformation to load the whole
5566  		 * field and then apply a mask when accessed with a narrower
5567  		 * access than actual ctx access size. A zero info.ctx_field_size
5568  		 * will only allow for whole field access and rejects any other
5569  		 * type of narrower access.
5570  		 */
5571  		*reg_type = info.reg_type;
5572  
5573  		if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5574  			*btf = info.btf;
5575  			*btf_id = info.btf_id;
5576  		} else {
5577  			env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5578  		}
5579  		/* remember the offset of last byte accessed in ctx */
5580  		if (env->prog->aux->max_ctx_offset < off + size)
5581  			env->prog->aux->max_ctx_offset = off + size;
5582  		return 0;
5583  	}
5584  
5585  	verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5586  	return -EACCES;
5587  }
5588  
check_flow_keys_access(struct bpf_verifier_env * env,int off,int size)5589  static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5590  				  int size)
5591  {
5592  	if (size < 0 || off < 0 ||
5593  	    (u64)off + size > sizeof(struct bpf_flow_keys)) {
5594  		verbose(env, "invalid access to flow keys off=%d size=%d\n",
5595  			off, size);
5596  		return -EACCES;
5597  	}
5598  	return 0;
5599  }
5600  
check_sock_access(struct bpf_verifier_env * env,int insn_idx,u32 regno,int off,int size,enum bpf_access_type t)5601  static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5602  			     u32 regno, int off, int size,
5603  			     enum bpf_access_type t)
5604  {
5605  	struct bpf_reg_state *regs = cur_regs(env);
5606  	struct bpf_reg_state *reg = &regs[regno];
5607  	struct bpf_insn_access_aux info = {};
5608  	bool valid;
5609  
5610  	if (reg->smin_value < 0) {
5611  		verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5612  			regno);
5613  		return -EACCES;
5614  	}
5615  
5616  	switch (reg->type) {
5617  	case PTR_TO_SOCK_COMMON:
5618  		valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5619  		break;
5620  	case PTR_TO_SOCKET:
5621  		valid = bpf_sock_is_valid_access(off, size, t, &info);
5622  		break;
5623  	case PTR_TO_TCP_SOCK:
5624  		valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5625  		break;
5626  	case PTR_TO_XDP_SOCK:
5627  		valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5628  		break;
5629  	default:
5630  		valid = false;
5631  	}
5632  
5633  
5634  	if (valid) {
5635  		env->insn_aux_data[insn_idx].ctx_field_size =
5636  			info.ctx_field_size;
5637  		return 0;
5638  	}
5639  
5640  	verbose(env, "R%d invalid %s access off=%d size=%d\n",
5641  		regno, reg_type_str(env, reg->type), off, size);
5642  
5643  	return -EACCES;
5644  }
5645  
is_pointer_value(struct bpf_verifier_env * env,int regno)5646  static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5647  {
5648  	return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5649  }
5650  
is_ctx_reg(struct bpf_verifier_env * env,int regno)5651  static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5652  {
5653  	const struct bpf_reg_state *reg = reg_state(env, regno);
5654  
5655  	return reg->type == PTR_TO_CTX;
5656  }
5657  
is_sk_reg(struct bpf_verifier_env * env,int regno)5658  static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5659  {
5660  	const struct bpf_reg_state *reg = reg_state(env, regno);
5661  
5662  	return type_is_sk_pointer(reg->type);
5663  }
5664  
is_pkt_reg(struct bpf_verifier_env * env,int regno)5665  static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5666  {
5667  	const struct bpf_reg_state *reg = reg_state(env, regno);
5668  
5669  	return type_is_pkt_pointer(reg->type);
5670  }
5671  
is_flow_key_reg(struct bpf_verifier_env * env,int regno)5672  static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5673  {
5674  	const struct bpf_reg_state *reg = reg_state(env, regno);
5675  
5676  	/* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5677  	return reg->type == PTR_TO_FLOW_KEYS;
5678  }
5679  
5680  static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5681  #ifdef CONFIG_NET
5682  	[PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5683  	[PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5684  	[PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5685  #endif
5686  	[CONST_PTR_TO_MAP] = btf_bpf_map_id,
5687  };
5688  
is_trusted_reg(const struct bpf_reg_state * reg)5689  static bool is_trusted_reg(const struct bpf_reg_state *reg)
5690  {
5691  	/* A referenced register is always trusted. */
5692  	if (reg->ref_obj_id)
5693  		return true;
5694  
5695  	/* Types listed in the reg2btf_ids are always trusted */
5696  	if (reg2btf_ids[base_type(reg->type)] &&
5697  	    !bpf_type_has_unsafe_modifiers(reg->type))
5698  		return true;
5699  
5700  	/* If a register is not referenced, it is trusted if it has the
5701  	 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5702  	 * other type modifiers may be safe, but we elect to take an opt-in
5703  	 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5704  	 * not.
5705  	 *
5706  	 * Eventually, we should make PTR_TRUSTED the single source of truth
5707  	 * for whether a register is trusted.
5708  	 */
5709  	return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5710  	       !bpf_type_has_unsafe_modifiers(reg->type);
5711  }
5712  
is_rcu_reg(const struct bpf_reg_state * reg)5713  static bool is_rcu_reg(const struct bpf_reg_state *reg)
5714  {
5715  	return reg->type & MEM_RCU;
5716  }
5717  
clear_trusted_flags(enum bpf_type_flag * flag)5718  static void clear_trusted_flags(enum bpf_type_flag *flag)
5719  {
5720  	*flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5721  }
5722  
check_pkt_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict)5723  static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5724  				   const struct bpf_reg_state *reg,
5725  				   int off, int size, bool strict)
5726  {
5727  	struct tnum reg_off;
5728  	int ip_align;
5729  
5730  	/* Byte size accesses are always allowed. */
5731  	if (!strict || size == 1)
5732  		return 0;
5733  
5734  	/* For platforms that do not have a Kconfig enabling
5735  	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5736  	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
5737  	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5738  	 * to this code only in strict mode where we want to emulate
5739  	 * the NET_IP_ALIGN==2 checking.  Therefore use an
5740  	 * unconditional IP align value of '2'.
5741  	 */
5742  	ip_align = 2;
5743  
5744  	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5745  	if (!tnum_is_aligned(reg_off, size)) {
5746  		char tn_buf[48];
5747  
5748  		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5749  		verbose(env,
5750  			"misaligned packet access off %d+%s+%d+%d size %d\n",
5751  			ip_align, tn_buf, reg->off, off, size);
5752  		return -EACCES;
5753  	}
5754  
5755  	return 0;
5756  }
5757  
check_generic_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,const char * pointer_desc,int off,int size,bool strict)5758  static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5759  				       const struct bpf_reg_state *reg,
5760  				       const char *pointer_desc,
5761  				       int off, int size, bool strict)
5762  {
5763  	struct tnum reg_off;
5764  
5765  	/* Byte size accesses are always allowed. */
5766  	if (!strict || size == 1)
5767  		return 0;
5768  
5769  	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5770  	if (!tnum_is_aligned(reg_off, size)) {
5771  		char tn_buf[48];
5772  
5773  		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5774  		verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5775  			pointer_desc, tn_buf, reg->off, off, size);
5776  		return -EACCES;
5777  	}
5778  
5779  	return 0;
5780  }
5781  
check_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict_alignment_once)5782  static int check_ptr_alignment(struct bpf_verifier_env *env,
5783  			       const struct bpf_reg_state *reg, int off,
5784  			       int size, bool strict_alignment_once)
5785  {
5786  	bool strict = env->strict_alignment || strict_alignment_once;
5787  	const char *pointer_desc = "";
5788  
5789  	switch (reg->type) {
5790  	case PTR_TO_PACKET:
5791  	case PTR_TO_PACKET_META:
5792  		/* Special case, because of NET_IP_ALIGN. Given metadata sits
5793  		 * right in front, treat it the very same way.
5794  		 */
5795  		return check_pkt_ptr_alignment(env, reg, off, size, strict);
5796  	case PTR_TO_FLOW_KEYS:
5797  		pointer_desc = "flow keys ";
5798  		break;
5799  	case PTR_TO_MAP_KEY:
5800  		pointer_desc = "key ";
5801  		break;
5802  	case PTR_TO_MAP_VALUE:
5803  		pointer_desc = "value ";
5804  		break;
5805  	case PTR_TO_CTX:
5806  		pointer_desc = "context ";
5807  		break;
5808  	case PTR_TO_STACK:
5809  		pointer_desc = "stack ";
5810  		/* The stack spill tracking logic in check_stack_write_fixed_off()
5811  		 * and check_stack_read_fixed_off() relies on stack accesses being
5812  		 * aligned.
5813  		 */
5814  		strict = true;
5815  		break;
5816  	case PTR_TO_SOCKET:
5817  		pointer_desc = "sock ";
5818  		break;
5819  	case PTR_TO_SOCK_COMMON:
5820  		pointer_desc = "sock_common ";
5821  		break;
5822  	case PTR_TO_TCP_SOCK:
5823  		pointer_desc = "tcp_sock ";
5824  		break;
5825  	case PTR_TO_XDP_SOCK:
5826  		pointer_desc = "xdp_sock ";
5827  		break;
5828  	default:
5829  		break;
5830  	}
5831  	return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5832  					   strict);
5833  }
5834  
5835  /* starting from main bpf function walk all instructions of the function
5836   * and recursively walk all callees that given function can call.
5837   * Ignore jump and exit insns.
5838   * Since recursion is prevented by check_cfg() this algorithm
5839   * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5840   */
check_max_stack_depth_subprog(struct bpf_verifier_env * env,int idx)5841  static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5842  {
5843  	struct bpf_subprog_info *subprog = env->subprog_info;
5844  	struct bpf_insn *insn = env->prog->insnsi;
5845  	int depth = 0, frame = 0, i, subprog_end;
5846  	bool tail_call_reachable = false;
5847  	int ret_insn[MAX_CALL_FRAMES];
5848  	int ret_prog[MAX_CALL_FRAMES];
5849  	int j;
5850  
5851  	i = subprog[idx].start;
5852  process_func:
5853  	/* protect against potential stack overflow that might happen when
5854  	 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5855  	 * depth for such case down to 256 so that the worst case scenario
5856  	 * would result in 8k stack size (32 which is tailcall limit * 256 =
5857  	 * 8k).
5858  	 *
5859  	 * To get the idea what might happen, see an example:
5860  	 * func1 -> sub rsp, 128
5861  	 *  subfunc1 -> sub rsp, 256
5862  	 *  tailcall1 -> add rsp, 256
5863  	 *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5864  	 *   subfunc2 -> sub rsp, 64
5865  	 *   subfunc22 -> sub rsp, 128
5866  	 *   tailcall2 -> add rsp, 128
5867  	 *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5868  	 *
5869  	 * tailcall will unwind the current stack frame but it will not get rid
5870  	 * of caller's stack as shown on the example above.
5871  	 */
5872  	if (idx && subprog[idx].has_tail_call && depth >= 256) {
5873  		verbose(env,
5874  			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5875  			depth);
5876  		return -EACCES;
5877  	}
5878  	/* round up to 32-bytes, since this is granularity
5879  	 * of interpreter stack size
5880  	 */
5881  	depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5882  	if (depth > MAX_BPF_STACK) {
5883  		verbose(env, "combined stack size of %d calls is %d. Too large\n",
5884  			frame + 1, depth);
5885  		return -EACCES;
5886  	}
5887  continue_func:
5888  	subprog_end = subprog[idx + 1].start;
5889  	for (; i < subprog_end; i++) {
5890  		int next_insn, sidx;
5891  
5892  		if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5893  			continue;
5894  		/* remember insn and function to return to */
5895  		ret_insn[frame] = i + 1;
5896  		ret_prog[frame] = idx;
5897  
5898  		/* find the callee */
5899  		next_insn = i + insn[i].imm + 1;
5900  		sidx = find_subprog(env, next_insn);
5901  		if (sidx < 0) {
5902  			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5903  				  next_insn);
5904  			return -EFAULT;
5905  		}
5906  		if (subprog[sidx].is_async_cb) {
5907  			if (subprog[sidx].has_tail_call) {
5908  				verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5909  				return -EFAULT;
5910  			}
5911  			/* async callbacks don't increase bpf prog stack size unless called directly */
5912  			if (!bpf_pseudo_call(insn + i))
5913  				continue;
5914  		}
5915  		i = next_insn;
5916  		idx = sidx;
5917  
5918  		if (subprog[idx].has_tail_call)
5919  			tail_call_reachable = true;
5920  
5921  		frame++;
5922  		if (frame >= MAX_CALL_FRAMES) {
5923  			verbose(env, "the call stack of %d frames is too deep !\n",
5924  				frame);
5925  			return -E2BIG;
5926  		}
5927  		goto process_func;
5928  	}
5929  	/* if tail call got detected across bpf2bpf calls then mark each of the
5930  	 * currently present subprog frames as tail call reachable subprogs;
5931  	 * this info will be utilized by JIT so that we will be preserving the
5932  	 * tail call counter throughout bpf2bpf calls combined with tailcalls
5933  	 */
5934  	if (tail_call_reachable)
5935  		for (j = 0; j < frame; j++)
5936  			subprog[ret_prog[j]].tail_call_reachable = true;
5937  	if (subprog[0].tail_call_reachable)
5938  		env->prog->aux->tail_call_reachable = true;
5939  
5940  	/* end of for() loop means the last insn of the 'subprog'
5941  	 * was reached. Doesn't matter whether it was JA or EXIT
5942  	 */
5943  	if (frame == 0)
5944  		return 0;
5945  	depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5946  	frame--;
5947  	i = ret_insn[frame];
5948  	idx = ret_prog[frame];
5949  	goto continue_func;
5950  }
5951  
check_max_stack_depth(struct bpf_verifier_env * env)5952  static int check_max_stack_depth(struct bpf_verifier_env *env)
5953  {
5954  	struct bpf_subprog_info *si = env->subprog_info;
5955  	int ret;
5956  
5957  	for (int i = 0; i < env->subprog_cnt; i++) {
5958  		if (!i || si[i].is_async_cb) {
5959  			ret = check_max_stack_depth_subprog(env, i);
5960  			if (ret < 0)
5961  				return ret;
5962  		}
5963  		continue;
5964  	}
5965  	return 0;
5966  }
5967  
5968  #ifndef CONFIG_BPF_JIT_ALWAYS_ON
get_callee_stack_depth(struct bpf_verifier_env * env,const struct bpf_insn * insn,int idx)5969  static int get_callee_stack_depth(struct bpf_verifier_env *env,
5970  				  const struct bpf_insn *insn, int idx)
5971  {
5972  	int start = idx + insn->imm + 1, subprog;
5973  
5974  	subprog = find_subprog(env, start);
5975  	if (subprog < 0) {
5976  		WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5977  			  start);
5978  		return -EFAULT;
5979  	}
5980  	return env->subprog_info[subprog].stack_depth;
5981  }
5982  #endif
5983  
__check_buffer_access(struct bpf_verifier_env * env,const char * buf_info,const struct bpf_reg_state * reg,int regno,int off,int size)5984  static int __check_buffer_access(struct bpf_verifier_env *env,
5985  				 const char *buf_info,
5986  				 const struct bpf_reg_state *reg,
5987  				 int regno, int off, int size)
5988  {
5989  	if (off < 0) {
5990  		verbose(env,
5991  			"R%d invalid %s buffer access: off=%d, size=%d\n",
5992  			regno, buf_info, off, size);
5993  		return -EACCES;
5994  	}
5995  	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5996  		char tn_buf[48];
5997  
5998  		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5999  		verbose(env,
6000  			"R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6001  			regno, off, tn_buf);
6002  		return -EACCES;
6003  	}
6004  
6005  	return 0;
6006  }
6007  
check_tp_buffer_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,int off,int size)6008  static int check_tp_buffer_access(struct bpf_verifier_env *env,
6009  				  const struct bpf_reg_state *reg,
6010  				  int regno, int off, int size)
6011  {
6012  	int err;
6013  
6014  	err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6015  	if (err)
6016  		return err;
6017  
6018  	if (off + size > env->prog->aux->max_tp_access)
6019  		env->prog->aux->max_tp_access = off + size;
6020  
6021  	return 0;
6022  }
6023  
check_buffer_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,int off,int size,bool zero_size_allowed,u32 * max_access)6024  static int check_buffer_access(struct bpf_verifier_env *env,
6025  			       const struct bpf_reg_state *reg,
6026  			       int regno, int off, int size,
6027  			       bool zero_size_allowed,
6028  			       u32 *max_access)
6029  {
6030  	const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6031  	int err;
6032  
6033  	err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6034  	if (err)
6035  		return err;
6036  
6037  	if (off + size > *max_access)
6038  		*max_access = off + size;
6039  
6040  	return 0;
6041  }
6042  
6043  /* BPF architecture zero extends alu32 ops into 64-bit registesr */
zext_32_to_64(struct bpf_reg_state * reg)6044  static void zext_32_to_64(struct bpf_reg_state *reg)
6045  {
6046  	reg->var_off = tnum_subreg(reg->var_off);
6047  	__reg_assign_32_into_64(reg);
6048  }
6049  
6050  /* truncate register to smaller size (in bytes)
6051   * must be called with size < BPF_REG_SIZE
6052   */
coerce_reg_to_size(struct bpf_reg_state * reg,int size)6053  static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6054  {
6055  	u64 mask;
6056  
6057  	/* clear high bits in bit representation */
6058  	reg->var_off = tnum_cast(reg->var_off, size);
6059  
6060  	/* fix arithmetic bounds */
6061  	mask = ((u64)1 << (size * 8)) - 1;
6062  	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6063  		reg->umin_value &= mask;
6064  		reg->umax_value &= mask;
6065  	} else {
6066  		reg->umin_value = 0;
6067  		reg->umax_value = mask;
6068  	}
6069  	reg->smin_value = reg->umin_value;
6070  	reg->smax_value = reg->umax_value;
6071  
6072  	/* If size is smaller than 32bit register the 32bit register
6073  	 * values are also truncated so we push 64-bit bounds into
6074  	 * 32-bit bounds. Above were truncated < 32-bits already.
6075  	 */
6076  	if (size >= 4)
6077  		return;
6078  	__reg_combine_64_into_32(reg);
6079  }
6080  
set_sext64_default_val(struct bpf_reg_state * reg,int size)6081  static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6082  {
6083  	if (size == 1) {
6084  		reg->smin_value = reg->s32_min_value = S8_MIN;
6085  		reg->smax_value = reg->s32_max_value = S8_MAX;
6086  	} else if (size == 2) {
6087  		reg->smin_value = reg->s32_min_value = S16_MIN;
6088  		reg->smax_value = reg->s32_max_value = S16_MAX;
6089  	} else {
6090  		/* size == 4 */
6091  		reg->smin_value = reg->s32_min_value = S32_MIN;
6092  		reg->smax_value = reg->s32_max_value = S32_MAX;
6093  	}
6094  	reg->umin_value = reg->u32_min_value = 0;
6095  	reg->umax_value = U64_MAX;
6096  	reg->u32_max_value = U32_MAX;
6097  	reg->var_off = tnum_unknown;
6098  }
6099  
coerce_reg_to_size_sx(struct bpf_reg_state * reg,int size)6100  static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6101  {
6102  	s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6103  	u64 top_smax_value, top_smin_value;
6104  	u64 num_bits = size * 8;
6105  
6106  	if (tnum_is_const(reg->var_off)) {
6107  		u64_cval = reg->var_off.value;
6108  		if (size == 1)
6109  			reg->var_off = tnum_const((s8)u64_cval);
6110  		else if (size == 2)
6111  			reg->var_off = tnum_const((s16)u64_cval);
6112  		else
6113  			/* size == 4 */
6114  			reg->var_off = tnum_const((s32)u64_cval);
6115  
6116  		u64_cval = reg->var_off.value;
6117  		reg->smax_value = reg->smin_value = u64_cval;
6118  		reg->umax_value = reg->umin_value = u64_cval;
6119  		reg->s32_max_value = reg->s32_min_value = u64_cval;
6120  		reg->u32_max_value = reg->u32_min_value = u64_cval;
6121  		return;
6122  	}
6123  
6124  	top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6125  	top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6126  
6127  	if (top_smax_value != top_smin_value)
6128  		goto out;
6129  
6130  	/* find the s64_min and s64_min after sign extension */
6131  	if (size == 1) {
6132  		init_s64_max = (s8)reg->smax_value;
6133  		init_s64_min = (s8)reg->smin_value;
6134  	} else if (size == 2) {
6135  		init_s64_max = (s16)reg->smax_value;
6136  		init_s64_min = (s16)reg->smin_value;
6137  	} else {
6138  		init_s64_max = (s32)reg->smax_value;
6139  		init_s64_min = (s32)reg->smin_value;
6140  	}
6141  
6142  	s64_max = max(init_s64_max, init_s64_min);
6143  	s64_min = min(init_s64_max, init_s64_min);
6144  
6145  	/* both of s64_max/s64_min positive or negative */
6146  	if ((s64_max >= 0) == (s64_min >= 0)) {
6147  		reg->s32_min_value = reg->smin_value = s64_min;
6148  		reg->s32_max_value = reg->smax_value = s64_max;
6149  		reg->u32_min_value = reg->umin_value = s64_min;
6150  		reg->u32_max_value = reg->umax_value = s64_max;
6151  		reg->var_off = tnum_range(s64_min, s64_max);
6152  		return;
6153  	}
6154  
6155  out:
6156  	set_sext64_default_val(reg, size);
6157  }
6158  
set_sext32_default_val(struct bpf_reg_state * reg,int size)6159  static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6160  {
6161  	if (size == 1) {
6162  		reg->s32_min_value = S8_MIN;
6163  		reg->s32_max_value = S8_MAX;
6164  	} else {
6165  		/* size == 2 */
6166  		reg->s32_min_value = S16_MIN;
6167  		reg->s32_max_value = S16_MAX;
6168  	}
6169  	reg->u32_min_value = 0;
6170  	reg->u32_max_value = U32_MAX;
6171  	reg->var_off = tnum_subreg(tnum_unknown);
6172  }
6173  
coerce_subreg_to_size_sx(struct bpf_reg_state * reg,int size)6174  static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6175  {
6176  	s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6177  	u32 top_smax_value, top_smin_value;
6178  	u32 num_bits = size * 8;
6179  
6180  	if (tnum_is_const(reg->var_off)) {
6181  		u32_val = reg->var_off.value;
6182  		if (size == 1)
6183  			reg->var_off = tnum_const((s8)u32_val);
6184  		else
6185  			reg->var_off = tnum_const((s16)u32_val);
6186  
6187  		u32_val = reg->var_off.value;
6188  		reg->s32_min_value = reg->s32_max_value = u32_val;
6189  		reg->u32_min_value = reg->u32_max_value = u32_val;
6190  		return;
6191  	}
6192  
6193  	top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6194  	top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6195  
6196  	if (top_smax_value != top_smin_value)
6197  		goto out;
6198  
6199  	/* find the s32_min and s32_min after sign extension */
6200  	if (size == 1) {
6201  		init_s32_max = (s8)reg->s32_max_value;
6202  		init_s32_min = (s8)reg->s32_min_value;
6203  	} else {
6204  		/* size == 2 */
6205  		init_s32_max = (s16)reg->s32_max_value;
6206  		init_s32_min = (s16)reg->s32_min_value;
6207  	}
6208  	s32_max = max(init_s32_max, init_s32_min);
6209  	s32_min = min(init_s32_max, init_s32_min);
6210  
6211  	if ((s32_min >= 0) == (s32_max >= 0)) {
6212  		reg->s32_min_value = s32_min;
6213  		reg->s32_max_value = s32_max;
6214  		reg->u32_min_value = (u32)s32_min;
6215  		reg->u32_max_value = (u32)s32_max;
6216  		reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
6217  		return;
6218  	}
6219  
6220  out:
6221  	set_sext32_default_val(reg, size);
6222  }
6223  
bpf_map_is_rdonly(const struct bpf_map * map)6224  static bool bpf_map_is_rdonly(const struct bpf_map *map)
6225  {
6226  	/* A map is considered read-only if the following condition are true:
6227  	 *
6228  	 * 1) BPF program side cannot change any of the map content. The
6229  	 *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6230  	 *    and was set at map creation time.
6231  	 * 2) The map value(s) have been initialized from user space by a
6232  	 *    loader and then "frozen", such that no new map update/delete
6233  	 *    operations from syscall side are possible for the rest of
6234  	 *    the map's lifetime from that point onwards.
6235  	 * 3) Any parallel/pending map update/delete operations from syscall
6236  	 *    side have been completed. Only after that point, it's safe to
6237  	 *    assume that map value(s) are immutable.
6238  	 */
6239  	return (map->map_flags & BPF_F_RDONLY_PROG) &&
6240  	       READ_ONCE(map->frozen) &&
6241  	       !bpf_map_write_active(map);
6242  }
6243  
bpf_map_direct_read(struct bpf_map * map,int off,int size,u64 * val,bool is_ldsx)6244  static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6245  			       bool is_ldsx)
6246  {
6247  	void *ptr;
6248  	u64 addr;
6249  	int err;
6250  
6251  	err = map->ops->map_direct_value_addr(map, &addr, off);
6252  	if (err)
6253  		return err;
6254  	ptr = (void *)(long)addr + off;
6255  
6256  	switch (size) {
6257  	case sizeof(u8):
6258  		*val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6259  		break;
6260  	case sizeof(u16):
6261  		*val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6262  		break;
6263  	case sizeof(u32):
6264  		*val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6265  		break;
6266  	case sizeof(u64):
6267  		*val = *(u64 *)ptr;
6268  		break;
6269  	default:
6270  		return -EINVAL;
6271  	}
6272  	return 0;
6273  }
6274  
6275  #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6276  #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6277  #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6278  #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type)  __PASTE(__type, __safe_trusted_or_null)
6279  
6280  /*
6281   * Allow list few fields as RCU trusted or full trusted.
6282   * This logic doesn't allow mix tagging and will be removed once GCC supports
6283   * btf_type_tag.
6284   */
6285  
6286  /* RCU trusted: these fields are trusted in RCU CS and never NULL */
BTF_TYPE_SAFE_RCU(struct task_struct)6287  BTF_TYPE_SAFE_RCU(struct task_struct) {
6288  	const cpumask_t *cpus_ptr;
6289  	struct css_set __rcu *cgroups;
6290  	struct task_struct __rcu *real_parent;
6291  	struct task_struct *group_leader;
6292  };
6293  
BTF_TYPE_SAFE_RCU(struct cgroup)6294  BTF_TYPE_SAFE_RCU(struct cgroup) {
6295  	/* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6296  	struct kernfs_node *kn;
6297  };
6298  
BTF_TYPE_SAFE_RCU(struct css_set)6299  BTF_TYPE_SAFE_RCU(struct css_set) {
6300  	struct cgroup *dfl_cgrp;
6301  };
6302  
6303  /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)6304  BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6305  	struct file __rcu *exe_file;
6306  };
6307  
6308  /* skb->sk, req->sk are not RCU protected, but we mark them as such
6309   * because bpf prog accessible sockets are SOCK_RCU_FREE.
6310   */
BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)6311  BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6312  	struct sock *sk;
6313  };
6314  
BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)6315  BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6316  	struct sock *sk;
6317  };
6318  
6319  /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)6320  BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6321  	struct seq_file *seq;
6322  };
6323  
BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)6324  BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6325  	struct bpf_iter_meta *meta;
6326  	struct task_struct *task;
6327  };
6328  
BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)6329  BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6330  	struct file *file;
6331  };
6332  
BTF_TYPE_SAFE_TRUSTED(struct file)6333  BTF_TYPE_SAFE_TRUSTED(struct file) {
6334  	struct inode *f_inode;
6335  };
6336  
BTF_TYPE_SAFE_TRUSTED(struct dentry)6337  BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6338  	/* no negative dentry-s in places where bpf can see it */
6339  	struct inode *d_inode;
6340  };
6341  
BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)6342  BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
6343  	struct sock *sk;
6344  };
6345  
type_is_rcu(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)6346  static bool type_is_rcu(struct bpf_verifier_env *env,
6347  			struct bpf_reg_state *reg,
6348  			const char *field_name, u32 btf_id)
6349  {
6350  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6351  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6352  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6353  
6354  	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6355  }
6356  
type_is_rcu_or_null(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)6357  static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6358  				struct bpf_reg_state *reg,
6359  				const char *field_name, u32 btf_id)
6360  {
6361  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6362  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6363  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6364  
6365  	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6366  }
6367  
type_is_trusted(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)6368  static bool type_is_trusted(struct bpf_verifier_env *env,
6369  			    struct bpf_reg_state *reg,
6370  			    const char *field_name, u32 btf_id)
6371  {
6372  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6373  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6374  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6375  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6376  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6377  
6378  	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6379  }
6380  
type_is_trusted_or_null(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)6381  static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
6382  				    struct bpf_reg_state *reg,
6383  				    const char *field_name, u32 btf_id)
6384  {
6385  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
6386  
6387  	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
6388  					  "__safe_trusted_or_null");
6389  }
6390  
check_ptr_to_btf_access(struct bpf_verifier_env * env,struct bpf_reg_state * regs,int regno,int off,int size,enum bpf_access_type atype,int value_regno)6391  static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6392  				   struct bpf_reg_state *regs,
6393  				   int regno, int off, int size,
6394  				   enum bpf_access_type atype,
6395  				   int value_regno)
6396  {
6397  	struct bpf_reg_state *reg = regs + regno;
6398  	const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6399  	const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6400  	const char *field_name = NULL;
6401  	enum bpf_type_flag flag = 0;
6402  	u32 btf_id = 0;
6403  	int ret;
6404  
6405  	if (!env->allow_ptr_leaks) {
6406  		verbose(env,
6407  			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6408  			tname);
6409  		return -EPERM;
6410  	}
6411  	if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6412  		verbose(env,
6413  			"Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6414  			tname);
6415  		return -EINVAL;
6416  	}
6417  	if (off < 0) {
6418  		verbose(env,
6419  			"R%d is ptr_%s invalid negative access: off=%d\n",
6420  			regno, tname, off);
6421  		return -EACCES;
6422  	}
6423  	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6424  		char tn_buf[48];
6425  
6426  		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6427  		verbose(env,
6428  			"R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6429  			regno, tname, off, tn_buf);
6430  		return -EACCES;
6431  	}
6432  
6433  	if (reg->type & MEM_USER) {
6434  		verbose(env,
6435  			"R%d is ptr_%s access user memory: off=%d\n",
6436  			regno, tname, off);
6437  		return -EACCES;
6438  	}
6439  
6440  	if (reg->type & MEM_PERCPU) {
6441  		verbose(env,
6442  			"R%d is ptr_%s access percpu memory: off=%d\n",
6443  			regno, tname, off);
6444  		return -EACCES;
6445  	}
6446  
6447  	if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6448  		if (!btf_is_kernel(reg->btf)) {
6449  			verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6450  			return -EFAULT;
6451  		}
6452  		ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6453  	} else {
6454  		/* Writes are permitted with default btf_struct_access for
6455  		 * program allocated objects (which always have ref_obj_id > 0),
6456  		 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6457  		 */
6458  		if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6459  			verbose(env, "only read is supported\n");
6460  			return -EACCES;
6461  		}
6462  
6463  		if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6464  		    !reg->ref_obj_id) {
6465  			verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6466  			return -EFAULT;
6467  		}
6468  
6469  		ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6470  	}
6471  
6472  	if (ret < 0)
6473  		return ret;
6474  
6475  	if (ret != PTR_TO_BTF_ID) {
6476  		/* just mark; */
6477  
6478  	} else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6479  		/* If this is an untrusted pointer, all pointers formed by walking it
6480  		 * also inherit the untrusted flag.
6481  		 */
6482  		flag = PTR_UNTRUSTED;
6483  
6484  	} else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6485  		/* By default any pointer obtained from walking a trusted pointer is no
6486  		 * longer trusted, unless the field being accessed has explicitly been
6487  		 * marked as inheriting its parent's state of trust (either full or RCU).
6488  		 * For example:
6489  		 * 'cgroups' pointer is untrusted if task->cgroups dereference
6490  		 * happened in a sleepable program outside of bpf_rcu_read_lock()
6491  		 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6492  		 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6493  		 *
6494  		 * A regular RCU-protected pointer with __rcu tag can also be deemed
6495  		 * trusted if we are in an RCU CS. Such pointer can be NULL.
6496  		 */
6497  		if (type_is_trusted(env, reg, field_name, btf_id)) {
6498  			flag |= PTR_TRUSTED;
6499  		} else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
6500  			flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
6501  		} else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6502  			if (type_is_rcu(env, reg, field_name, btf_id)) {
6503  				/* ignore __rcu tag and mark it MEM_RCU */
6504  				flag |= MEM_RCU;
6505  			} else if (flag & MEM_RCU ||
6506  				   type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6507  				/* __rcu tagged pointers can be NULL */
6508  				flag |= MEM_RCU | PTR_MAYBE_NULL;
6509  
6510  				/* We always trust them */
6511  				if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6512  				    flag & PTR_UNTRUSTED)
6513  					flag &= ~PTR_UNTRUSTED;
6514  			} else if (flag & (MEM_PERCPU | MEM_USER)) {
6515  				/* keep as-is */
6516  			} else {
6517  				/* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6518  				clear_trusted_flags(&flag);
6519  			}
6520  		} else {
6521  			/*
6522  			 * If not in RCU CS or MEM_RCU pointer can be NULL then
6523  			 * aggressively mark as untrusted otherwise such
6524  			 * pointers will be plain PTR_TO_BTF_ID without flags
6525  			 * and will be allowed to be passed into helpers for
6526  			 * compat reasons.
6527  			 */
6528  			flag = PTR_UNTRUSTED;
6529  		}
6530  	} else {
6531  		/* Old compat. Deprecated */
6532  		clear_trusted_flags(&flag);
6533  	}
6534  
6535  	if (atype == BPF_READ && value_regno >= 0)
6536  		mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6537  
6538  	return 0;
6539  }
6540  
check_ptr_to_map_access(struct bpf_verifier_env * env,struct bpf_reg_state * regs,int regno,int off,int size,enum bpf_access_type atype,int value_regno)6541  static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6542  				   struct bpf_reg_state *regs,
6543  				   int regno, int off, int size,
6544  				   enum bpf_access_type atype,
6545  				   int value_regno)
6546  {
6547  	struct bpf_reg_state *reg = regs + regno;
6548  	struct bpf_map *map = reg->map_ptr;
6549  	struct bpf_reg_state map_reg;
6550  	enum bpf_type_flag flag = 0;
6551  	const struct btf_type *t;
6552  	const char *tname;
6553  	u32 btf_id;
6554  	int ret;
6555  
6556  	if (!btf_vmlinux) {
6557  		verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6558  		return -ENOTSUPP;
6559  	}
6560  
6561  	if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6562  		verbose(env, "map_ptr access not supported for map type %d\n",
6563  			map->map_type);
6564  		return -ENOTSUPP;
6565  	}
6566  
6567  	t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6568  	tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6569  
6570  	if (!env->allow_ptr_leaks) {
6571  		verbose(env,
6572  			"'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6573  			tname);
6574  		return -EPERM;
6575  	}
6576  
6577  	if (off < 0) {
6578  		verbose(env, "R%d is %s invalid negative access: off=%d\n",
6579  			regno, tname, off);
6580  		return -EACCES;
6581  	}
6582  
6583  	if (atype != BPF_READ) {
6584  		verbose(env, "only read from %s is supported\n", tname);
6585  		return -EACCES;
6586  	}
6587  
6588  	/* Simulate access to a PTR_TO_BTF_ID */
6589  	memset(&map_reg, 0, sizeof(map_reg));
6590  	mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6591  	ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6592  	if (ret < 0)
6593  		return ret;
6594  
6595  	if (value_regno >= 0)
6596  		mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6597  
6598  	return 0;
6599  }
6600  
6601  /* Check that the stack access at the given offset is within bounds. The
6602   * maximum valid offset is -1.
6603   *
6604   * The minimum valid offset is -MAX_BPF_STACK for writes, and
6605   * -state->allocated_stack for reads.
6606   */
check_stack_slot_within_bounds(struct bpf_verifier_env * env,s64 off,struct bpf_func_state * state,enum bpf_access_type t)6607  static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6608                                            s64 off,
6609                                            struct bpf_func_state *state,
6610                                            enum bpf_access_type t)
6611  {
6612  	int min_valid_off;
6613  
6614  	if (t == BPF_WRITE || env->allow_uninit_stack)
6615  		min_valid_off = -MAX_BPF_STACK;
6616  	else
6617  		min_valid_off = -state->allocated_stack;
6618  
6619  	if (off < min_valid_off || off > -1)
6620  		return -EACCES;
6621  	return 0;
6622  }
6623  
6624  /* Check that the stack access at 'regno + off' falls within the maximum stack
6625   * bounds.
6626   *
6627   * 'off' includes `regno->offset`, but not its dynamic part (if any).
6628   */
check_stack_access_within_bounds(struct bpf_verifier_env * env,int regno,int off,int access_size,enum bpf_access_src src,enum bpf_access_type type)6629  static int check_stack_access_within_bounds(
6630  		struct bpf_verifier_env *env,
6631  		int regno, int off, int access_size,
6632  		enum bpf_access_src src, enum bpf_access_type type)
6633  {
6634  	struct bpf_reg_state *regs = cur_regs(env);
6635  	struct bpf_reg_state *reg = regs + regno;
6636  	struct bpf_func_state *state = func(env, reg);
6637  	s64 min_off, max_off;
6638  	int err;
6639  	char *err_extra;
6640  
6641  	if (src == ACCESS_HELPER)
6642  		/* We don't know if helpers are reading or writing (or both). */
6643  		err_extra = " indirect access to";
6644  	else if (type == BPF_READ)
6645  		err_extra = " read from";
6646  	else
6647  		err_extra = " write to";
6648  
6649  	if (tnum_is_const(reg->var_off)) {
6650  		min_off = (s64)reg->var_off.value + off;
6651  		max_off = min_off + access_size;
6652  	} else {
6653  		if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6654  		    reg->smin_value <= -BPF_MAX_VAR_OFF) {
6655  			verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6656  				err_extra, regno);
6657  			return -EACCES;
6658  		}
6659  		min_off = reg->smin_value + off;
6660  		max_off = reg->smax_value + off + access_size;
6661  	}
6662  
6663  	err = check_stack_slot_within_bounds(env, min_off, state, type);
6664  	if (!err && max_off > 0)
6665  		err = -EINVAL; /* out of stack access into non-negative offsets */
6666  	if (!err && access_size < 0)
6667  		/* access_size should not be negative (or overflow an int); others checks
6668  		 * along the way should have prevented such an access.
6669  		 */
6670  		err = -EFAULT; /* invalid negative access size; integer overflow? */
6671  
6672  	if (err) {
6673  		if (tnum_is_const(reg->var_off)) {
6674  			verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6675  				err_extra, regno, off, access_size);
6676  		} else {
6677  			char tn_buf[48];
6678  
6679  			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6680  			verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6681  				err_extra, regno, tn_buf, access_size);
6682  		}
6683  		return err;
6684  	}
6685  
6686  	return grow_stack_state(env, state, round_up(-min_off, BPF_REG_SIZE));
6687  }
6688  
6689  /* check whether memory at (regno + off) is accessible for t = (read | write)
6690   * if t==write, value_regno is a register which value is stored into memory
6691   * if t==read, value_regno is a register which will receive the value from memory
6692   * if t==write && value_regno==-1, some unknown value is stored into memory
6693   * if t==read && value_regno==-1, don't care what we read from memory
6694   */
check_mem_access(struct bpf_verifier_env * env,int insn_idx,u32 regno,int off,int bpf_size,enum bpf_access_type t,int value_regno,bool strict_alignment_once,bool is_ldsx)6695  static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6696  			    int off, int bpf_size, enum bpf_access_type t,
6697  			    int value_regno, bool strict_alignment_once, bool is_ldsx)
6698  {
6699  	struct bpf_reg_state *regs = cur_regs(env);
6700  	struct bpf_reg_state *reg = regs + regno;
6701  	int size, err = 0;
6702  
6703  	size = bpf_size_to_bytes(bpf_size);
6704  	if (size < 0)
6705  		return size;
6706  
6707  	/* alignment checks will add in reg->off themselves */
6708  	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6709  	if (err)
6710  		return err;
6711  
6712  	/* for access checks, reg->off is just part of off */
6713  	off += reg->off;
6714  
6715  	if (reg->type == PTR_TO_MAP_KEY) {
6716  		if (t == BPF_WRITE) {
6717  			verbose(env, "write to change key R%d not allowed\n", regno);
6718  			return -EACCES;
6719  		}
6720  
6721  		err = check_mem_region_access(env, regno, off, size,
6722  					      reg->map_ptr->key_size, false);
6723  		if (err)
6724  			return err;
6725  		if (value_regno >= 0)
6726  			mark_reg_unknown(env, regs, value_regno);
6727  	} else if (reg->type == PTR_TO_MAP_VALUE) {
6728  		struct btf_field *kptr_field = NULL;
6729  
6730  		if (t == BPF_WRITE && value_regno >= 0 &&
6731  		    is_pointer_value(env, value_regno)) {
6732  			verbose(env, "R%d leaks addr into map\n", value_regno);
6733  			return -EACCES;
6734  		}
6735  		err = check_map_access_type(env, regno, off, size, t);
6736  		if (err)
6737  			return err;
6738  		err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6739  		if (err)
6740  			return err;
6741  		if (tnum_is_const(reg->var_off))
6742  			kptr_field = btf_record_find(reg->map_ptr->record,
6743  						     off + reg->var_off.value, BPF_KPTR);
6744  		if (kptr_field) {
6745  			err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6746  		} else if (t == BPF_READ && value_regno >= 0) {
6747  			struct bpf_map *map = reg->map_ptr;
6748  
6749  			/* if map is read-only, track its contents as scalars */
6750  			if (tnum_is_const(reg->var_off) &&
6751  			    bpf_map_is_rdonly(map) &&
6752  			    map->ops->map_direct_value_addr) {
6753  				int map_off = off + reg->var_off.value;
6754  				u64 val = 0;
6755  
6756  				err = bpf_map_direct_read(map, map_off, size,
6757  							  &val, is_ldsx);
6758  				if (err)
6759  					return err;
6760  
6761  				regs[value_regno].type = SCALAR_VALUE;
6762  				__mark_reg_known(&regs[value_regno], val);
6763  			} else {
6764  				mark_reg_unknown(env, regs, value_regno);
6765  			}
6766  		}
6767  	} else if (base_type(reg->type) == PTR_TO_MEM) {
6768  		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6769  
6770  		if (type_may_be_null(reg->type)) {
6771  			verbose(env, "R%d invalid mem access '%s'\n", regno,
6772  				reg_type_str(env, reg->type));
6773  			return -EACCES;
6774  		}
6775  
6776  		if (t == BPF_WRITE && rdonly_mem) {
6777  			verbose(env, "R%d cannot write into %s\n",
6778  				regno, reg_type_str(env, reg->type));
6779  			return -EACCES;
6780  		}
6781  
6782  		if (t == BPF_WRITE && value_regno >= 0 &&
6783  		    is_pointer_value(env, value_regno)) {
6784  			verbose(env, "R%d leaks addr into mem\n", value_regno);
6785  			return -EACCES;
6786  		}
6787  
6788  		err = check_mem_region_access(env, regno, off, size,
6789  					      reg->mem_size, false);
6790  		if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6791  			mark_reg_unknown(env, regs, value_regno);
6792  	} else if (reg->type == PTR_TO_CTX) {
6793  		enum bpf_reg_type reg_type = SCALAR_VALUE;
6794  		struct btf *btf = NULL;
6795  		u32 btf_id = 0;
6796  
6797  		if (t == BPF_WRITE && value_regno >= 0 &&
6798  		    is_pointer_value(env, value_regno)) {
6799  			verbose(env, "R%d leaks addr into ctx\n", value_regno);
6800  			return -EACCES;
6801  		}
6802  
6803  		err = check_ptr_off_reg(env, reg, regno);
6804  		if (err < 0)
6805  			return err;
6806  
6807  		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6808  				       &btf_id);
6809  		if (err)
6810  			verbose_linfo(env, insn_idx, "; ");
6811  		if (!err && t == BPF_READ && value_regno >= 0) {
6812  			/* ctx access returns either a scalar, or a
6813  			 * PTR_TO_PACKET[_META,_END]. In the latter
6814  			 * case, we know the offset is zero.
6815  			 */
6816  			if (reg_type == SCALAR_VALUE) {
6817  				mark_reg_unknown(env, regs, value_regno);
6818  			} else {
6819  				mark_reg_known_zero(env, regs,
6820  						    value_regno);
6821  				if (type_may_be_null(reg_type))
6822  					regs[value_regno].id = ++env->id_gen;
6823  				/* A load of ctx field could have different
6824  				 * actual load size with the one encoded in the
6825  				 * insn. When the dst is PTR, it is for sure not
6826  				 * a sub-register.
6827  				 */
6828  				regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6829  				if (base_type(reg_type) == PTR_TO_BTF_ID) {
6830  					regs[value_regno].btf = btf;
6831  					regs[value_regno].btf_id = btf_id;
6832  				}
6833  			}
6834  			regs[value_regno].type = reg_type;
6835  		}
6836  
6837  	} else if (reg->type == PTR_TO_STACK) {
6838  		/* Basic bounds checks. */
6839  		err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6840  		if (err)
6841  			return err;
6842  
6843  		if (t == BPF_READ)
6844  			err = check_stack_read(env, regno, off, size,
6845  					       value_regno);
6846  		else
6847  			err = check_stack_write(env, regno, off, size,
6848  						value_regno, insn_idx);
6849  	} else if (reg_is_pkt_pointer(reg)) {
6850  		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6851  			verbose(env, "cannot write into packet\n");
6852  			return -EACCES;
6853  		}
6854  		if (t == BPF_WRITE && value_regno >= 0 &&
6855  		    is_pointer_value(env, value_regno)) {
6856  			verbose(env, "R%d leaks addr into packet\n",
6857  				value_regno);
6858  			return -EACCES;
6859  		}
6860  		err = check_packet_access(env, regno, off, size, false);
6861  		if (!err && t == BPF_READ && value_regno >= 0)
6862  			mark_reg_unknown(env, regs, value_regno);
6863  	} else if (reg->type == PTR_TO_FLOW_KEYS) {
6864  		if (t == BPF_WRITE && value_regno >= 0 &&
6865  		    is_pointer_value(env, value_regno)) {
6866  			verbose(env, "R%d leaks addr into flow keys\n",
6867  				value_regno);
6868  			return -EACCES;
6869  		}
6870  
6871  		err = check_flow_keys_access(env, off, size);
6872  		if (!err && t == BPF_READ && value_regno >= 0)
6873  			mark_reg_unknown(env, regs, value_regno);
6874  	} else if (type_is_sk_pointer(reg->type)) {
6875  		if (t == BPF_WRITE) {
6876  			verbose(env, "R%d cannot write into %s\n",
6877  				regno, reg_type_str(env, reg->type));
6878  			return -EACCES;
6879  		}
6880  		err = check_sock_access(env, insn_idx, regno, off, size, t);
6881  		if (!err && value_regno >= 0)
6882  			mark_reg_unknown(env, regs, value_regno);
6883  	} else if (reg->type == PTR_TO_TP_BUFFER) {
6884  		err = check_tp_buffer_access(env, reg, regno, off, size);
6885  		if (!err && t == BPF_READ && value_regno >= 0)
6886  			mark_reg_unknown(env, regs, value_regno);
6887  	} else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6888  		   !type_may_be_null(reg->type)) {
6889  		err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6890  					      value_regno);
6891  	} else if (reg->type == CONST_PTR_TO_MAP) {
6892  		err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6893  					      value_regno);
6894  	} else if (base_type(reg->type) == PTR_TO_BUF) {
6895  		bool rdonly_mem = type_is_rdonly_mem(reg->type);
6896  		u32 *max_access;
6897  
6898  		if (rdonly_mem) {
6899  			if (t == BPF_WRITE) {
6900  				verbose(env, "R%d cannot write into %s\n",
6901  					regno, reg_type_str(env, reg->type));
6902  				return -EACCES;
6903  			}
6904  			max_access = &env->prog->aux->max_rdonly_access;
6905  		} else {
6906  			max_access = &env->prog->aux->max_rdwr_access;
6907  		}
6908  
6909  		err = check_buffer_access(env, reg, regno, off, size, false,
6910  					  max_access);
6911  
6912  		if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6913  			mark_reg_unknown(env, regs, value_regno);
6914  	} else {
6915  		verbose(env, "R%d invalid mem access '%s'\n", regno,
6916  			reg_type_str(env, reg->type));
6917  		return -EACCES;
6918  	}
6919  
6920  	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6921  	    regs[value_regno].type == SCALAR_VALUE) {
6922  		if (!is_ldsx)
6923  			/* b/h/w load zero-extends, mark upper bits as known 0 */
6924  			coerce_reg_to_size(&regs[value_regno], size);
6925  		else
6926  			coerce_reg_to_size_sx(&regs[value_regno], size);
6927  	}
6928  	return err;
6929  }
6930  
check_atomic(struct bpf_verifier_env * env,int insn_idx,struct bpf_insn * insn)6931  static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6932  {
6933  	int load_reg;
6934  	int err;
6935  
6936  	switch (insn->imm) {
6937  	case BPF_ADD:
6938  	case BPF_ADD | BPF_FETCH:
6939  	case BPF_AND:
6940  	case BPF_AND | BPF_FETCH:
6941  	case BPF_OR:
6942  	case BPF_OR | BPF_FETCH:
6943  	case BPF_XOR:
6944  	case BPF_XOR | BPF_FETCH:
6945  	case BPF_XCHG:
6946  	case BPF_CMPXCHG:
6947  		break;
6948  	default:
6949  		verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6950  		return -EINVAL;
6951  	}
6952  
6953  	if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6954  		verbose(env, "invalid atomic operand size\n");
6955  		return -EINVAL;
6956  	}
6957  
6958  	/* check src1 operand */
6959  	err = check_reg_arg(env, insn->src_reg, SRC_OP);
6960  	if (err)
6961  		return err;
6962  
6963  	/* check src2 operand */
6964  	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6965  	if (err)
6966  		return err;
6967  
6968  	if (insn->imm == BPF_CMPXCHG) {
6969  		/* Check comparison of R0 with memory location */
6970  		const u32 aux_reg = BPF_REG_0;
6971  
6972  		err = check_reg_arg(env, aux_reg, SRC_OP);
6973  		if (err)
6974  			return err;
6975  
6976  		if (is_pointer_value(env, aux_reg)) {
6977  			verbose(env, "R%d leaks addr into mem\n", aux_reg);
6978  			return -EACCES;
6979  		}
6980  	}
6981  
6982  	if (is_pointer_value(env, insn->src_reg)) {
6983  		verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6984  		return -EACCES;
6985  	}
6986  
6987  	if (is_ctx_reg(env, insn->dst_reg) ||
6988  	    is_pkt_reg(env, insn->dst_reg) ||
6989  	    is_flow_key_reg(env, insn->dst_reg) ||
6990  	    is_sk_reg(env, insn->dst_reg)) {
6991  		verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6992  			insn->dst_reg,
6993  			reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6994  		return -EACCES;
6995  	}
6996  
6997  	if (insn->imm & BPF_FETCH) {
6998  		if (insn->imm == BPF_CMPXCHG)
6999  			load_reg = BPF_REG_0;
7000  		else
7001  			load_reg = insn->src_reg;
7002  
7003  		/* check and record load of old value */
7004  		err = check_reg_arg(env, load_reg, DST_OP);
7005  		if (err)
7006  			return err;
7007  	} else {
7008  		/* This instruction accesses a memory location but doesn't
7009  		 * actually load it into a register.
7010  		 */
7011  		load_reg = -1;
7012  	}
7013  
7014  	/* Check whether we can read the memory, with second call for fetch
7015  	 * case to simulate the register fill.
7016  	 */
7017  	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7018  			       BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7019  	if (!err && load_reg >= 0)
7020  		err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7021  				       BPF_SIZE(insn->code), BPF_READ, load_reg,
7022  				       true, false);
7023  	if (err)
7024  		return err;
7025  
7026  	/* Check whether we can write into the same memory. */
7027  	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7028  			       BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7029  	if (err)
7030  		return err;
7031  
7032  	return 0;
7033  }
7034  
7035  /* When register 'regno' is used to read the stack (either directly or through
7036   * a helper function) make sure that it's within stack boundary and, depending
7037   * on the access type and privileges, that all elements of the stack are
7038   * initialized.
7039   *
7040   * 'off' includes 'regno->off', but not its dynamic part (if any).
7041   *
7042   * All registers that have been spilled on the stack in the slots within the
7043   * read offsets are marked as read.
7044   */
check_stack_range_initialized(struct bpf_verifier_env * env,int regno,int off,int access_size,bool zero_size_allowed,enum bpf_access_src type,struct bpf_call_arg_meta * meta)7045  static int check_stack_range_initialized(
7046  		struct bpf_verifier_env *env, int regno, int off,
7047  		int access_size, bool zero_size_allowed,
7048  		enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7049  {
7050  	struct bpf_reg_state *reg = reg_state(env, regno);
7051  	struct bpf_func_state *state = func(env, reg);
7052  	int err, min_off, max_off, i, j, slot, spi;
7053  	char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7054  	enum bpf_access_type bounds_check_type;
7055  	/* Some accesses can write anything into the stack, others are
7056  	 * read-only.
7057  	 */
7058  	bool clobber = false;
7059  
7060  	if (access_size == 0 && !zero_size_allowed) {
7061  		verbose(env, "invalid zero-sized read\n");
7062  		return -EACCES;
7063  	}
7064  
7065  	if (type == ACCESS_HELPER) {
7066  		/* The bounds checks for writes are more permissive than for
7067  		 * reads. However, if raw_mode is not set, we'll do extra
7068  		 * checks below.
7069  		 */
7070  		bounds_check_type = BPF_WRITE;
7071  		clobber = true;
7072  	} else {
7073  		bounds_check_type = BPF_READ;
7074  	}
7075  	err = check_stack_access_within_bounds(env, regno, off, access_size,
7076  					       type, bounds_check_type);
7077  	if (err)
7078  		return err;
7079  
7080  
7081  	if (tnum_is_const(reg->var_off)) {
7082  		min_off = max_off = reg->var_off.value + off;
7083  	} else {
7084  		/* Variable offset is prohibited for unprivileged mode for
7085  		 * simplicity since it requires corresponding support in
7086  		 * Spectre masking for stack ALU.
7087  		 * See also retrieve_ptr_limit().
7088  		 */
7089  		if (!env->bypass_spec_v1) {
7090  			char tn_buf[48];
7091  
7092  			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7093  			verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7094  				regno, err_extra, tn_buf);
7095  			return -EACCES;
7096  		}
7097  		/* Only initialized buffer on stack is allowed to be accessed
7098  		 * with variable offset. With uninitialized buffer it's hard to
7099  		 * guarantee that whole memory is marked as initialized on
7100  		 * helper return since specific bounds are unknown what may
7101  		 * cause uninitialized stack leaking.
7102  		 */
7103  		if (meta && meta->raw_mode)
7104  			meta = NULL;
7105  
7106  		min_off = reg->smin_value + off;
7107  		max_off = reg->smax_value + off;
7108  	}
7109  
7110  	if (meta && meta->raw_mode) {
7111  		/* Ensure we won't be overwriting dynptrs when simulating byte
7112  		 * by byte access in check_helper_call using meta.access_size.
7113  		 * This would be a problem if we have a helper in the future
7114  		 * which takes:
7115  		 *
7116  		 *	helper(uninit_mem, len, dynptr)
7117  		 *
7118  		 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7119  		 * may end up writing to dynptr itself when touching memory from
7120  		 * arg 1. This can be relaxed on a case by case basis for known
7121  		 * safe cases, but reject due to the possibilitiy of aliasing by
7122  		 * default.
7123  		 */
7124  		for (i = min_off; i < max_off + access_size; i++) {
7125  			int stack_off = -i - 1;
7126  
7127  			spi = __get_spi(i);
7128  			/* raw_mode may write past allocated_stack */
7129  			if (state->allocated_stack <= stack_off)
7130  				continue;
7131  			if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7132  				verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7133  				return -EACCES;
7134  			}
7135  		}
7136  		meta->access_size = access_size;
7137  		meta->regno = regno;
7138  		return 0;
7139  	}
7140  
7141  	for (i = min_off; i < max_off + access_size; i++) {
7142  		u8 *stype;
7143  
7144  		slot = -i - 1;
7145  		spi = slot / BPF_REG_SIZE;
7146  		if (state->allocated_stack <= slot) {
7147  			verbose(env, "verifier bug: allocated_stack too small");
7148  			return -EFAULT;
7149  		}
7150  
7151  		stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7152  		if (*stype == STACK_MISC)
7153  			goto mark;
7154  		if ((*stype == STACK_ZERO) ||
7155  		    (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7156  			if (clobber) {
7157  				/* helper can write anything into the stack */
7158  				*stype = STACK_MISC;
7159  			}
7160  			goto mark;
7161  		}
7162  
7163  		if (is_spilled_reg(&state->stack[spi]) &&
7164  		    (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7165  		     env->allow_ptr_leaks)) {
7166  			if (clobber) {
7167  				__mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7168  				for (j = 0; j < BPF_REG_SIZE; j++)
7169  					scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7170  			}
7171  			goto mark;
7172  		}
7173  
7174  		if (tnum_is_const(reg->var_off)) {
7175  			verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7176  				err_extra, regno, min_off, i - min_off, access_size);
7177  		} else {
7178  			char tn_buf[48];
7179  
7180  			tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7181  			verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7182  				err_extra, regno, tn_buf, i - min_off, access_size);
7183  		}
7184  		return -EACCES;
7185  mark:
7186  		/* reading any byte out of 8-byte 'spill_slot' will cause
7187  		 * the whole slot to be marked as 'read'
7188  		 */
7189  		mark_reg_read(env, &state->stack[spi].spilled_ptr,
7190  			      state->stack[spi].spilled_ptr.parent,
7191  			      REG_LIVE_READ64);
7192  		/* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7193  		 * be sure that whether stack slot is written to or not. Hence,
7194  		 * we must still conservatively propagate reads upwards even if
7195  		 * helper may write to the entire memory range.
7196  		 */
7197  	}
7198  	return 0;
7199  }
7200  
check_helper_mem_access(struct bpf_verifier_env * env,int regno,int access_size,enum bpf_access_type access_type,bool zero_size_allowed,struct bpf_call_arg_meta * meta)7201  static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7202  				   int access_size, enum bpf_access_type access_type,
7203  				   bool zero_size_allowed,
7204  				   struct bpf_call_arg_meta *meta)
7205  {
7206  	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7207  	u32 *max_access;
7208  
7209  	switch (base_type(reg->type)) {
7210  	case PTR_TO_PACKET:
7211  	case PTR_TO_PACKET_META:
7212  		return check_packet_access(env, regno, reg->off, access_size,
7213  					   zero_size_allowed);
7214  	case PTR_TO_MAP_KEY:
7215  		if (access_type == BPF_WRITE) {
7216  			verbose(env, "R%d cannot write into %s\n", regno,
7217  				reg_type_str(env, reg->type));
7218  			return -EACCES;
7219  		}
7220  		return check_mem_region_access(env, regno, reg->off, access_size,
7221  					       reg->map_ptr->key_size, false);
7222  	case PTR_TO_MAP_VALUE:
7223  		if (check_map_access_type(env, regno, reg->off, access_size, access_type))
7224  			return -EACCES;
7225  		return check_map_access(env, regno, reg->off, access_size,
7226  					zero_size_allowed, ACCESS_HELPER);
7227  	case PTR_TO_MEM:
7228  		if (type_is_rdonly_mem(reg->type)) {
7229  			if (access_type == BPF_WRITE) {
7230  				verbose(env, "R%d cannot write into %s\n", regno,
7231  					reg_type_str(env, reg->type));
7232  				return -EACCES;
7233  			}
7234  		}
7235  		return check_mem_region_access(env, regno, reg->off,
7236  					       access_size, reg->mem_size,
7237  					       zero_size_allowed);
7238  	case PTR_TO_BUF:
7239  		if (type_is_rdonly_mem(reg->type)) {
7240  			if (access_type == BPF_WRITE) {
7241  				verbose(env, "R%d cannot write into %s\n", regno,
7242  					reg_type_str(env, reg->type));
7243  				return -EACCES;
7244  			}
7245  
7246  			max_access = &env->prog->aux->max_rdonly_access;
7247  		} else {
7248  			max_access = &env->prog->aux->max_rdwr_access;
7249  		}
7250  		return check_buffer_access(env, reg, regno, reg->off,
7251  					   access_size, zero_size_allowed,
7252  					   max_access);
7253  	case PTR_TO_STACK:
7254  		return check_stack_range_initialized(
7255  				env,
7256  				regno, reg->off, access_size,
7257  				zero_size_allowed, ACCESS_HELPER, meta);
7258  	case PTR_TO_BTF_ID:
7259  		return check_ptr_to_btf_access(env, regs, regno, reg->off,
7260  					       access_size, BPF_READ, -1);
7261  	case PTR_TO_CTX:
7262  		/* in case the function doesn't know how to access the context,
7263  		 * (because we are in a program of type SYSCALL for example), we
7264  		 * can not statically check its size.
7265  		 * Dynamically check it now.
7266  		 */
7267  		if (!env->ops->convert_ctx_access) {
7268  			int offset = access_size - 1;
7269  
7270  			/* Allow zero-byte read from PTR_TO_CTX */
7271  			if (access_size == 0)
7272  				return zero_size_allowed ? 0 : -EACCES;
7273  
7274  			return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7275  						access_type, -1, false, false);
7276  		}
7277  
7278  		fallthrough;
7279  	default: /* scalar_value or invalid ptr */
7280  		/* Allow zero-byte read from NULL, regardless of pointer type */
7281  		if (zero_size_allowed && access_size == 0 &&
7282  		    register_is_null(reg))
7283  			return 0;
7284  
7285  		verbose(env, "R%d type=%s ", regno,
7286  			reg_type_str(env, reg->type));
7287  		verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7288  		return -EACCES;
7289  	}
7290  }
7291  
check_mem_size_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,enum bpf_access_type access_type,bool zero_size_allowed,struct bpf_call_arg_meta * meta)7292  static int check_mem_size_reg(struct bpf_verifier_env *env,
7293  			      struct bpf_reg_state *reg, u32 regno,
7294  			      enum bpf_access_type access_type,
7295  			      bool zero_size_allowed,
7296  			      struct bpf_call_arg_meta *meta)
7297  {
7298  	int err;
7299  
7300  	/* This is used to refine r0 return value bounds for helpers
7301  	 * that enforce this value as an upper bound on return values.
7302  	 * See do_refine_retval_range() for helpers that can refine
7303  	 * the return value. C type of helper is u32 so we pull register
7304  	 * bound from umax_value however, if negative verifier errors
7305  	 * out. Only upper bounds can be learned because retval is an
7306  	 * int type and negative retvals are allowed.
7307  	 */
7308  	meta->msize_max_value = reg->umax_value;
7309  
7310  	/* The register is SCALAR_VALUE; the access check happens using
7311  	 * its boundaries. For unprivileged variable accesses, disable
7312  	 * raw mode so that the program is required to initialize all
7313  	 * the memory that the helper could just partially fill up.
7314  	 */
7315  	if (!tnum_is_const(reg->var_off))
7316  		meta = NULL;
7317  
7318  	if (reg->smin_value < 0) {
7319  		verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7320  			regno);
7321  		return -EACCES;
7322  	}
7323  
7324  	if (reg->umin_value == 0 && !zero_size_allowed) {
7325  		verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
7326  			regno, reg->umin_value, reg->umax_value);
7327  		return -EACCES;
7328  	}
7329  
7330  	if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7331  		verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7332  			regno);
7333  		return -EACCES;
7334  	}
7335  	err = check_helper_mem_access(env, regno - 1, reg->umax_value,
7336  				      access_type, zero_size_allowed, meta);
7337  	if (!err)
7338  		err = mark_chain_precision(env, regno);
7339  	return err;
7340  }
7341  
check_mem_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,u32 mem_size)7342  int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7343  		   u32 regno, u32 mem_size)
7344  {
7345  	bool may_be_null = type_may_be_null(reg->type);
7346  	struct bpf_reg_state saved_reg;
7347  	int err;
7348  
7349  	if (register_is_null(reg))
7350  		return 0;
7351  
7352  	/* Assuming that the register contains a value check if the memory
7353  	 * access is safe. Temporarily save and restore the register's state as
7354  	 * the conversion shouldn't be visible to a caller.
7355  	 */
7356  	if (may_be_null) {
7357  		saved_reg = *reg;
7358  		mark_ptr_not_null_reg(reg);
7359  	}
7360  
7361  	err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL);
7362  	err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL);
7363  
7364  	if (may_be_null)
7365  		*reg = saved_reg;
7366  
7367  	return err;
7368  }
7369  
check_kfunc_mem_size_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno)7370  static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7371  				    u32 regno)
7372  {
7373  	struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7374  	bool may_be_null = type_may_be_null(mem_reg->type);
7375  	struct bpf_reg_state saved_reg;
7376  	struct bpf_call_arg_meta meta;
7377  	int err;
7378  
7379  	WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7380  
7381  	memset(&meta, 0, sizeof(meta));
7382  
7383  	if (may_be_null) {
7384  		saved_reg = *mem_reg;
7385  		mark_ptr_not_null_reg(mem_reg);
7386  	}
7387  
7388  	err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta);
7389  	err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta);
7390  
7391  	if (may_be_null)
7392  		*mem_reg = saved_reg;
7393  
7394  	return err;
7395  }
7396  
7397  /* Implementation details:
7398   * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7399   * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7400   * Two bpf_map_lookups (even with the same key) will have different reg->id.
7401   * Two separate bpf_obj_new will also have different reg->id.
7402   * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7403   * clears reg->id after value_or_null->value transition, since the verifier only
7404   * cares about the range of access to valid map value pointer and doesn't care
7405   * about actual address of the map element.
7406   * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7407   * reg->id > 0 after value_or_null->value transition. By doing so
7408   * two bpf_map_lookups will be considered two different pointers that
7409   * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7410   * returned from bpf_obj_new.
7411   * The verifier allows taking only one bpf_spin_lock at a time to avoid
7412   * dead-locks.
7413   * Since only one bpf_spin_lock is allowed the checks are simpler than
7414   * reg_is_refcounted() logic. The verifier needs to remember only
7415   * one spin_lock instead of array of acquired_refs.
7416   * cur_state->active_lock remembers which map value element or allocated
7417   * object got locked and clears it after bpf_spin_unlock.
7418   */
process_spin_lock(struct bpf_verifier_env * env,int regno,bool is_lock)7419  static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7420  			     bool is_lock)
7421  {
7422  	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7423  	struct bpf_verifier_state *cur = env->cur_state;
7424  	bool is_const = tnum_is_const(reg->var_off);
7425  	u64 val = reg->var_off.value;
7426  	struct bpf_map *map = NULL;
7427  	struct btf *btf = NULL;
7428  	struct btf_record *rec;
7429  
7430  	if (!is_const) {
7431  		verbose(env,
7432  			"R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7433  			regno);
7434  		return -EINVAL;
7435  	}
7436  	if (reg->type == PTR_TO_MAP_VALUE) {
7437  		map = reg->map_ptr;
7438  		if (!map->btf) {
7439  			verbose(env,
7440  				"map '%s' has to have BTF in order to use bpf_spin_lock\n",
7441  				map->name);
7442  			return -EINVAL;
7443  		}
7444  	} else {
7445  		btf = reg->btf;
7446  	}
7447  
7448  	rec = reg_btf_record(reg);
7449  	if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7450  		verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7451  			map ? map->name : "kptr");
7452  		return -EINVAL;
7453  	}
7454  	if (rec->spin_lock_off != val + reg->off) {
7455  		verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7456  			val + reg->off, rec->spin_lock_off);
7457  		return -EINVAL;
7458  	}
7459  	if (is_lock) {
7460  		if (cur->active_lock.ptr) {
7461  			verbose(env,
7462  				"Locking two bpf_spin_locks are not allowed\n");
7463  			return -EINVAL;
7464  		}
7465  		if (map)
7466  			cur->active_lock.ptr = map;
7467  		else
7468  			cur->active_lock.ptr = btf;
7469  		cur->active_lock.id = reg->id;
7470  	} else {
7471  		void *ptr;
7472  
7473  		if (map)
7474  			ptr = map;
7475  		else
7476  			ptr = btf;
7477  
7478  		if (!cur->active_lock.ptr) {
7479  			verbose(env, "bpf_spin_unlock without taking a lock\n");
7480  			return -EINVAL;
7481  		}
7482  		if (cur->active_lock.ptr != ptr ||
7483  		    cur->active_lock.id != reg->id) {
7484  			verbose(env, "bpf_spin_unlock of different lock\n");
7485  			return -EINVAL;
7486  		}
7487  
7488  		invalidate_non_owning_refs(env);
7489  
7490  		cur->active_lock.ptr = NULL;
7491  		cur->active_lock.id = 0;
7492  	}
7493  	return 0;
7494  }
7495  
process_timer_func(struct bpf_verifier_env * env,int regno,struct bpf_call_arg_meta * meta)7496  static int process_timer_func(struct bpf_verifier_env *env, int regno,
7497  			      struct bpf_call_arg_meta *meta)
7498  {
7499  	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7500  	bool is_const = tnum_is_const(reg->var_off);
7501  	struct bpf_map *map = reg->map_ptr;
7502  	u64 val = reg->var_off.value;
7503  
7504  	if (!is_const) {
7505  		verbose(env,
7506  			"R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7507  			regno);
7508  		return -EINVAL;
7509  	}
7510  	if (!map->btf) {
7511  		verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7512  			map->name);
7513  		return -EINVAL;
7514  	}
7515  	if (!btf_record_has_field(map->record, BPF_TIMER)) {
7516  		verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7517  		return -EINVAL;
7518  	}
7519  	if (map->record->timer_off != val + reg->off) {
7520  		verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7521  			val + reg->off, map->record->timer_off);
7522  		return -EINVAL;
7523  	}
7524  	if (meta->map_ptr) {
7525  		verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7526  		return -EFAULT;
7527  	}
7528  	meta->map_uid = reg->map_uid;
7529  	meta->map_ptr = map;
7530  	return 0;
7531  }
7532  
process_kptr_func(struct bpf_verifier_env * env,int regno,struct bpf_call_arg_meta * meta)7533  static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7534  			     struct bpf_call_arg_meta *meta)
7535  {
7536  	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7537  	struct bpf_map *map_ptr = reg->map_ptr;
7538  	struct btf_field *kptr_field;
7539  	u32 kptr_off;
7540  
7541  	if (!tnum_is_const(reg->var_off)) {
7542  		verbose(env,
7543  			"R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7544  			regno);
7545  		return -EINVAL;
7546  	}
7547  	if (!map_ptr->btf) {
7548  		verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7549  			map_ptr->name);
7550  		return -EINVAL;
7551  	}
7552  	if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7553  		verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7554  		return -EINVAL;
7555  	}
7556  
7557  	meta->map_ptr = map_ptr;
7558  	kptr_off = reg->off + reg->var_off.value;
7559  	kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7560  	if (!kptr_field) {
7561  		verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7562  		return -EACCES;
7563  	}
7564  	if (kptr_field->type != BPF_KPTR_REF) {
7565  		verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7566  		return -EACCES;
7567  	}
7568  	meta->kptr_field = kptr_field;
7569  	return 0;
7570  }
7571  
7572  /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7573   * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7574   *
7575   * In both cases we deal with the first 8 bytes, but need to mark the next 8
7576   * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7577   * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7578   *
7579   * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7580   * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7581   * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7582   * mutate the view of the dynptr and also possibly destroy it. In the latter
7583   * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7584   * memory that dynptr points to.
7585   *
7586   * The verifier will keep track both levels of mutation (bpf_dynptr's in
7587   * reg->type and the memory's in reg->dynptr.type), but there is no support for
7588   * readonly dynptr view yet, hence only the first case is tracked and checked.
7589   *
7590   * This is consistent with how C applies the const modifier to a struct object,
7591   * where the pointer itself inside bpf_dynptr becomes const but not what it
7592   * points to.
7593   *
7594   * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7595   * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7596   */
process_dynptr_func(struct bpf_verifier_env * env,int regno,int insn_idx,enum bpf_arg_type arg_type,int clone_ref_obj_id)7597  static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7598  			       enum bpf_arg_type arg_type, int clone_ref_obj_id)
7599  {
7600  	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7601  	int err;
7602  
7603  	/* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7604  	 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7605  	 */
7606  	if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7607  		verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7608  		return -EFAULT;
7609  	}
7610  
7611  	/*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7612  	 *		 constructing a mutable bpf_dynptr object.
7613  	 *
7614  	 *		 Currently, this is only possible with PTR_TO_STACK
7615  	 *		 pointing to a region of at least 16 bytes which doesn't
7616  	 *		 contain an existing bpf_dynptr.
7617  	 *
7618  	 *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7619  	 *		 mutated or destroyed. However, the memory it points to
7620  	 *		 may be mutated.
7621  	 *
7622  	 *  None       - Points to a initialized dynptr that can be mutated and
7623  	 *		 destroyed, including mutation of the memory it points
7624  	 *		 to.
7625  	 */
7626  	if (arg_type & MEM_UNINIT) {
7627  		int i;
7628  
7629  		if (!is_dynptr_reg_valid_uninit(env, reg)) {
7630  			verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7631  			return -EINVAL;
7632  		}
7633  
7634  		/* we write BPF_DW bits (8 bytes) at a time */
7635  		for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7636  			err = check_mem_access(env, insn_idx, regno,
7637  					       i, BPF_DW, BPF_WRITE, -1, false, false);
7638  			if (err)
7639  				return err;
7640  		}
7641  
7642  		err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7643  	} else /* MEM_RDONLY and None case from above */ {
7644  		/* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7645  		if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7646  			verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7647  			return -EINVAL;
7648  		}
7649  
7650  		if (!is_dynptr_reg_valid_init(env, reg)) {
7651  			verbose(env,
7652  				"Expected an initialized dynptr as arg #%d\n",
7653  				regno);
7654  			return -EINVAL;
7655  		}
7656  
7657  		/* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7658  		if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7659  			verbose(env,
7660  				"Expected a dynptr of type %s as arg #%d\n",
7661  				dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7662  			return -EINVAL;
7663  		}
7664  
7665  		err = mark_dynptr_read(env, reg);
7666  	}
7667  	return err;
7668  }
7669  
iter_ref_obj_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int spi)7670  static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7671  {
7672  	struct bpf_func_state *state = func(env, reg);
7673  
7674  	return state->stack[spi].spilled_ptr.ref_obj_id;
7675  }
7676  
is_iter_kfunc(struct bpf_kfunc_call_arg_meta * meta)7677  static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7678  {
7679  	return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7680  }
7681  
is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta * meta)7682  static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7683  {
7684  	return meta->kfunc_flags & KF_ITER_NEW;
7685  }
7686  
is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta * meta)7687  static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7688  {
7689  	return meta->kfunc_flags & KF_ITER_NEXT;
7690  }
7691  
is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta * meta)7692  static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7693  {
7694  	return meta->kfunc_flags & KF_ITER_DESTROY;
7695  }
7696  
is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta * meta,int arg)7697  static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7698  {
7699  	/* btf_check_iter_kfuncs() guarantees that first argument of any iter
7700  	 * kfunc is iter state pointer
7701  	 */
7702  	return arg == 0 && is_iter_kfunc(meta);
7703  }
7704  
process_iter_arg(struct bpf_verifier_env * env,int regno,int insn_idx,struct bpf_kfunc_call_arg_meta * meta)7705  static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7706  			    struct bpf_kfunc_call_arg_meta *meta)
7707  {
7708  	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7709  	const struct btf_type *t;
7710  	const struct btf_param *arg;
7711  	int spi, err, i, nr_slots;
7712  	u32 btf_id;
7713  
7714  	/* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7715  	arg = &btf_params(meta->func_proto)[0];
7716  	t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);	/* PTR */
7717  	t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);	/* STRUCT */
7718  	nr_slots = t->size / BPF_REG_SIZE;
7719  
7720  	if (is_iter_new_kfunc(meta)) {
7721  		/* bpf_iter_<type>_new() expects pointer to uninit iter state */
7722  		if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7723  			verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7724  				iter_type_str(meta->btf, btf_id), regno);
7725  			return -EINVAL;
7726  		}
7727  
7728  		for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7729  			err = check_mem_access(env, insn_idx, regno,
7730  					       i, BPF_DW, BPF_WRITE, -1, false, false);
7731  			if (err)
7732  				return err;
7733  		}
7734  
7735  		err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7736  		if (err)
7737  			return err;
7738  	} else {
7739  		/* iter_next() or iter_destroy() expect initialized iter state*/
7740  		if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7741  			verbose(env, "expected an initialized iter_%s as arg #%d\n",
7742  				iter_type_str(meta->btf, btf_id), regno);
7743  			return -EINVAL;
7744  		}
7745  
7746  		spi = iter_get_spi(env, reg, nr_slots);
7747  		if (spi < 0)
7748  			return spi;
7749  
7750  		err = mark_iter_read(env, reg, spi, nr_slots);
7751  		if (err)
7752  			return err;
7753  
7754  		/* remember meta->iter info for process_iter_next_call() */
7755  		meta->iter.spi = spi;
7756  		meta->iter.frameno = reg->frameno;
7757  		meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7758  
7759  		if (is_iter_destroy_kfunc(meta)) {
7760  			err = unmark_stack_slots_iter(env, reg, nr_slots);
7761  			if (err)
7762  				return err;
7763  		}
7764  	}
7765  
7766  	return 0;
7767  }
7768  
7769  /* Look for a previous loop entry at insn_idx: nearest parent state
7770   * stopped at insn_idx with callsites matching those in cur->frame.
7771   */
find_prev_entry(struct bpf_verifier_env * env,struct bpf_verifier_state * cur,int insn_idx)7772  static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7773  						  struct bpf_verifier_state *cur,
7774  						  int insn_idx)
7775  {
7776  	struct bpf_verifier_state_list *sl;
7777  	struct bpf_verifier_state *st;
7778  
7779  	/* Explored states are pushed in stack order, most recent states come first */
7780  	sl = *explored_state(env, insn_idx);
7781  	for (; sl; sl = sl->next) {
7782  		/* If st->branches != 0 state is a part of current DFS verification path,
7783  		 * hence cur & st for a loop.
7784  		 */
7785  		st = &sl->state;
7786  		if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7787  		    st->dfs_depth < cur->dfs_depth)
7788  			return st;
7789  	}
7790  
7791  	return NULL;
7792  }
7793  
7794  static void reset_idmap_scratch(struct bpf_verifier_env *env);
7795  static bool regs_exact(const struct bpf_reg_state *rold,
7796  		       const struct bpf_reg_state *rcur,
7797  		       struct bpf_idmap *idmap);
7798  
maybe_widen_reg(struct bpf_verifier_env * env,struct bpf_reg_state * rold,struct bpf_reg_state * rcur,struct bpf_idmap * idmap)7799  static void maybe_widen_reg(struct bpf_verifier_env *env,
7800  			    struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7801  			    struct bpf_idmap *idmap)
7802  {
7803  	if (rold->type != SCALAR_VALUE)
7804  		return;
7805  	if (rold->type != rcur->type)
7806  		return;
7807  	if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7808  		return;
7809  	__mark_reg_unknown(env, rcur);
7810  }
7811  
widen_imprecise_scalars(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur)7812  static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7813  				   struct bpf_verifier_state *old,
7814  				   struct bpf_verifier_state *cur)
7815  {
7816  	struct bpf_func_state *fold, *fcur;
7817  	int i, fr;
7818  
7819  	reset_idmap_scratch(env);
7820  	for (fr = old->curframe; fr >= 0; fr--) {
7821  		fold = old->frame[fr];
7822  		fcur = cur->frame[fr];
7823  
7824  		for (i = 0; i < MAX_BPF_REG; i++)
7825  			maybe_widen_reg(env,
7826  					&fold->regs[i],
7827  					&fcur->regs[i],
7828  					&env->idmap_scratch);
7829  
7830  		for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7831  			if (!is_spilled_reg(&fold->stack[i]) ||
7832  			    !is_spilled_reg(&fcur->stack[i]))
7833  				continue;
7834  
7835  			maybe_widen_reg(env,
7836  					&fold->stack[i].spilled_ptr,
7837  					&fcur->stack[i].spilled_ptr,
7838  					&env->idmap_scratch);
7839  		}
7840  	}
7841  	return 0;
7842  }
7843  
get_iter_from_state(struct bpf_verifier_state * cur_st,struct bpf_kfunc_call_arg_meta * meta)7844  static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
7845  						 struct bpf_kfunc_call_arg_meta *meta)
7846  {
7847  	int iter_frameno = meta->iter.frameno;
7848  	int iter_spi = meta->iter.spi;
7849  
7850  	return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7851  }
7852  
7853  /* process_iter_next_call() is called when verifier gets to iterator's next
7854   * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7855   * to it as just "iter_next()" in comments below.
7856   *
7857   * BPF verifier relies on a crucial contract for any iter_next()
7858   * implementation: it should *eventually* return NULL, and once that happens
7859   * it should keep returning NULL. That is, once iterator exhausts elements to
7860   * iterate, it should never reset or spuriously return new elements.
7861   *
7862   * With the assumption of such contract, process_iter_next_call() simulates
7863   * a fork in the verifier state to validate loop logic correctness and safety
7864   * without having to simulate infinite amount of iterations.
7865   *
7866   * In current state, we first assume that iter_next() returned NULL and
7867   * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7868   * conditions we should not form an infinite loop and should eventually reach
7869   * exit.
7870   *
7871   * Besides that, we also fork current state and enqueue it for later
7872   * verification. In a forked state we keep iterator state as ACTIVE
7873   * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7874   * also bump iteration depth to prevent erroneous infinite loop detection
7875   * later on (see iter_active_depths_differ() comment for details). In this
7876   * state we assume that we'll eventually loop back to another iter_next()
7877   * calls (it could be in exactly same location or in some other instruction,
7878   * it doesn't matter, we don't make any unnecessary assumptions about this,
7879   * everything revolves around iterator state in a stack slot, not which
7880   * instruction is calling iter_next()). When that happens, we either will come
7881   * to iter_next() with equivalent state and can conclude that next iteration
7882   * will proceed in exactly the same way as we just verified, so it's safe to
7883   * assume that loop converges. If not, we'll go on another iteration
7884   * simulation with a different input state, until all possible starting states
7885   * are validated or we reach maximum number of instructions limit.
7886   *
7887   * This way, we will either exhaustively discover all possible input states
7888   * that iterator loop can start with and eventually will converge, or we'll
7889   * effectively regress into bounded loop simulation logic and either reach
7890   * maximum number of instructions if loop is not provably convergent, or there
7891   * is some statically known limit on number of iterations (e.g., if there is
7892   * an explicit `if n > 100 then break;` statement somewhere in the loop).
7893   *
7894   * Iteration convergence logic in is_state_visited() relies on exact
7895   * states comparison, which ignores read and precision marks.
7896   * This is necessary because read and precision marks are not finalized
7897   * while in the loop. Exact comparison might preclude convergence for
7898   * simple programs like below:
7899   *
7900   *     i = 0;
7901   *     while(iter_next(&it))
7902   *       i++;
7903   *
7904   * At each iteration step i++ would produce a new distinct state and
7905   * eventually instruction processing limit would be reached.
7906   *
7907   * To avoid such behavior speculatively forget (widen) range for
7908   * imprecise scalar registers, if those registers were not precise at the
7909   * end of the previous iteration and do not match exactly.
7910   *
7911   * This is a conservative heuristic that allows to verify wide range of programs,
7912   * however it precludes verification of programs that conjure an
7913   * imprecise value on the first loop iteration and use it as precise on a second.
7914   * For example, the following safe program would fail to verify:
7915   *
7916   *     struct bpf_num_iter it;
7917   *     int arr[10];
7918   *     int i = 0, a = 0;
7919   *     bpf_iter_num_new(&it, 0, 10);
7920   *     while (bpf_iter_num_next(&it)) {
7921   *       if (a == 0) {
7922   *         a = 1;
7923   *         i = 7; // Because i changed verifier would forget
7924   *                // it's range on second loop entry.
7925   *       } else {
7926   *         arr[i] = 42; // This would fail to verify.
7927   *       }
7928   *     }
7929   *     bpf_iter_num_destroy(&it);
7930   */
process_iter_next_call(struct bpf_verifier_env * env,int insn_idx,struct bpf_kfunc_call_arg_meta * meta)7931  static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7932  				  struct bpf_kfunc_call_arg_meta *meta)
7933  {
7934  	struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7935  	struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7936  	struct bpf_reg_state *cur_iter, *queued_iter;
7937  
7938  	BTF_TYPE_EMIT(struct bpf_iter);
7939  
7940  	cur_iter = get_iter_from_state(cur_st, meta);
7941  
7942  	if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7943  	    cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7944  		verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7945  			cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7946  		return -EFAULT;
7947  	}
7948  
7949  	if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7950  		/* Because iter_next() call is a checkpoint is_state_visitied()
7951  		 * should guarantee parent state with same call sites and insn_idx.
7952  		 */
7953  		if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
7954  		    !same_callsites(cur_st->parent, cur_st)) {
7955  			verbose(env, "bug: bad parent state for iter next call");
7956  			return -EFAULT;
7957  		}
7958  		/* Note cur_st->parent in the call below, it is necessary to skip
7959  		 * checkpoint created for cur_st by is_state_visited()
7960  		 * right at this instruction.
7961  		 */
7962  		prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
7963  		/* branch out active iter state */
7964  		queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7965  		if (!queued_st)
7966  			return -ENOMEM;
7967  
7968  		queued_iter = get_iter_from_state(queued_st, meta);
7969  		queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7970  		queued_iter->iter.depth++;
7971  		if (prev_st)
7972  			widen_imprecise_scalars(env, prev_st, queued_st);
7973  
7974  		queued_fr = queued_st->frame[queued_st->curframe];
7975  		mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7976  	}
7977  
7978  	/* switch to DRAINED state, but keep the depth unchanged */
7979  	/* mark current iter state as drained and assume returned NULL */
7980  	cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7981  	__mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7982  
7983  	return 0;
7984  }
7985  
arg_type_is_mem_size(enum bpf_arg_type type)7986  static bool arg_type_is_mem_size(enum bpf_arg_type type)
7987  {
7988  	return type == ARG_CONST_SIZE ||
7989  	       type == ARG_CONST_SIZE_OR_ZERO;
7990  }
7991  
arg_type_is_raw_mem(enum bpf_arg_type type)7992  static bool arg_type_is_raw_mem(enum bpf_arg_type type)
7993  {
7994  	return base_type(type) == ARG_PTR_TO_MEM &&
7995  	       type & MEM_UNINIT;
7996  }
7997  
arg_type_is_release(enum bpf_arg_type type)7998  static bool arg_type_is_release(enum bpf_arg_type type)
7999  {
8000  	return type & OBJ_RELEASE;
8001  }
8002  
arg_type_is_dynptr(enum bpf_arg_type type)8003  static bool arg_type_is_dynptr(enum bpf_arg_type type)
8004  {
8005  	return base_type(type) == ARG_PTR_TO_DYNPTR;
8006  }
8007  
resolve_map_arg_type(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_arg_type * arg_type)8008  static int resolve_map_arg_type(struct bpf_verifier_env *env,
8009  				 const struct bpf_call_arg_meta *meta,
8010  				 enum bpf_arg_type *arg_type)
8011  {
8012  	if (!meta->map_ptr) {
8013  		/* kernel subsystem misconfigured verifier */
8014  		verbose(env, "invalid map_ptr to access map->type\n");
8015  		return -EACCES;
8016  	}
8017  
8018  	switch (meta->map_ptr->map_type) {
8019  	case BPF_MAP_TYPE_SOCKMAP:
8020  	case BPF_MAP_TYPE_SOCKHASH:
8021  		if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8022  			*arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8023  		} else {
8024  			verbose(env, "invalid arg_type for sockmap/sockhash\n");
8025  			return -EINVAL;
8026  		}
8027  		break;
8028  	case BPF_MAP_TYPE_BLOOM_FILTER:
8029  		if (meta->func_id == BPF_FUNC_map_peek_elem)
8030  			*arg_type = ARG_PTR_TO_MAP_VALUE;
8031  		break;
8032  	default:
8033  		break;
8034  	}
8035  	return 0;
8036  }
8037  
8038  struct bpf_reg_types {
8039  	const enum bpf_reg_type types[10];
8040  	u32 *btf_id;
8041  };
8042  
8043  static const struct bpf_reg_types sock_types = {
8044  	.types = {
8045  		PTR_TO_SOCK_COMMON,
8046  		PTR_TO_SOCKET,
8047  		PTR_TO_TCP_SOCK,
8048  		PTR_TO_XDP_SOCK,
8049  	},
8050  };
8051  
8052  #ifdef CONFIG_NET
8053  static const struct bpf_reg_types btf_id_sock_common_types = {
8054  	.types = {
8055  		PTR_TO_SOCK_COMMON,
8056  		PTR_TO_SOCKET,
8057  		PTR_TO_TCP_SOCK,
8058  		PTR_TO_XDP_SOCK,
8059  		PTR_TO_BTF_ID,
8060  		PTR_TO_BTF_ID | PTR_TRUSTED,
8061  	},
8062  	.btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8063  };
8064  #endif
8065  
8066  static const struct bpf_reg_types mem_types = {
8067  	.types = {
8068  		PTR_TO_STACK,
8069  		PTR_TO_PACKET,
8070  		PTR_TO_PACKET_META,
8071  		PTR_TO_MAP_KEY,
8072  		PTR_TO_MAP_VALUE,
8073  		PTR_TO_MEM,
8074  		PTR_TO_MEM | MEM_RINGBUF,
8075  		PTR_TO_BUF,
8076  		PTR_TO_BTF_ID | PTR_TRUSTED,
8077  	},
8078  };
8079  
8080  static const struct bpf_reg_types spin_lock_types = {
8081  	.types = {
8082  		PTR_TO_MAP_VALUE,
8083  		PTR_TO_BTF_ID | MEM_ALLOC,
8084  	}
8085  };
8086  
8087  static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8088  static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8089  static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8090  static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8091  static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8092  static const struct bpf_reg_types btf_ptr_types = {
8093  	.types = {
8094  		PTR_TO_BTF_ID,
8095  		PTR_TO_BTF_ID | PTR_TRUSTED,
8096  		PTR_TO_BTF_ID | MEM_RCU,
8097  	},
8098  };
8099  static const struct bpf_reg_types percpu_btf_ptr_types = {
8100  	.types = {
8101  		PTR_TO_BTF_ID | MEM_PERCPU,
8102  		PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8103  	}
8104  };
8105  static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8106  static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8107  static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8108  static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8109  static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8110  static const struct bpf_reg_types dynptr_types = {
8111  	.types = {
8112  		PTR_TO_STACK,
8113  		CONST_PTR_TO_DYNPTR,
8114  	}
8115  };
8116  
8117  static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8118  	[ARG_PTR_TO_MAP_KEY]		= &mem_types,
8119  	[ARG_PTR_TO_MAP_VALUE]		= &mem_types,
8120  	[ARG_CONST_SIZE]		= &scalar_types,
8121  	[ARG_CONST_SIZE_OR_ZERO]	= &scalar_types,
8122  	[ARG_CONST_ALLOC_SIZE_OR_ZERO]	= &scalar_types,
8123  	[ARG_CONST_MAP_PTR]		= &const_map_ptr_types,
8124  	[ARG_PTR_TO_CTX]		= &context_types,
8125  	[ARG_PTR_TO_SOCK_COMMON]	= &sock_types,
8126  #ifdef CONFIG_NET
8127  	[ARG_PTR_TO_BTF_ID_SOCK_COMMON]	= &btf_id_sock_common_types,
8128  #endif
8129  	[ARG_PTR_TO_SOCKET]		= &fullsock_types,
8130  	[ARG_PTR_TO_BTF_ID]		= &btf_ptr_types,
8131  	[ARG_PTR_TO_SPIN_LOCK]		= &spin_lock_types,
8132  	[ARG_PTR_TO_MEM]		= &mem_types,
8133  	[ARG_PTR_TO_RINGBUF_MEM]	= &ringbuf_mem_types,
8134  	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
8135  	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
8136  	[ARG_PTR_TO_STACK]		= &stack_ptr_types,
8137  	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
8138  	[ARG_PTR_TO_TIMER]		= &timer_types,
8139  	[ARG_PTR_TO_KPTR]		= &kptr_types,
8140  	[ARG_PTR_TO_DYNPTR]		= &dynptr_types,
8141  };
8142  
check_reg_type(struct bpf_verifier_env * env,u32 regno,enum bpf_arg_type arg_type,const u32 * arg_btf_id,struct bpf_call_arg_meta * meta)8143  static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8144  			  enum bpf_arg_type arg_type,
8145  			  const u32 *arg_btf_id,
8146  			  struct bpf_call_arg_meta *meta)
8147  {
8148  	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8149  	enum bpf_reg_type expected, type = reg->type;
8150  	const struct bpf_reg_types *compatible;
8151  	int i, j;
8152  
8153  	compatible = compatible_reg_types[base_type(arg_type)];
8154  	if (!compatible) {
8155  		verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8156  		return -EFAULT;
8157  	}
8158  
8159  	/* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8160  	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8161  	 *
8162  	 * Same for MAYBE_NULL:
8163  	 *
8164  	 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8165  	 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8166  	 *
8167  	 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8168  	 *
8169  	 * Therefore we fold these flags depending on the arg_type before comparison.
8170  	 */
8171  	if (arg_type & MEM_RDONLY)
8172  		type &= ~MEM_RDONLY;
8173  	if (arg_type & PTR_MAYBE_NULL)
8174  		type &= ~PTR_MAYBE_NULL;
8175  	if (base_type(arg_type) == ARG_PTR_TO_MEM)
8176  		type &= ~DYNPTR_TYPE_FLAG_MASK;
8177  
8178  	if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
8179  		type &= ~MEM_ALLOC;
8180  
8181  	for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8182  		expected = compatible->types[i];
8183  		if (expected == NOT_INIT)
8184  			break;
8185  
8186  		if (type == expected)
8187  			goto found;
8188  	}
8189  
8190  	verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8191  	for (j = 0; j + 1 < i; j++)
8192  		verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8193  	verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8194  	return -EACCES;
8195  
8196  found:
8197  	if (base_type(reg->type) != PTR_TO_BTF_ID)
8198  		return 0;
8199  
8200  	if (compatible == &mem_types) {
8201  		if (!(arg_type & MEM_RDONLY)) {
8202  			verbose(env,
8203  				"%s() may write into memory pointed by R%d type=%s\n",
8204  				func_id_name(meta->func_id),
8205  				regno, reg_type_str(env, reg->type));
8206  			return -EACCES;
8207  		}
8208  		return 0;
8209  	}
8210  
8211  	switch ((int)reg->type) {
8212  	case PTR_TO_BTF_ID:
8213  	case PTR_TO_BTF_ID | PTR_TRUSTED:
8214  	case PTR_TO_BTF_ID | MEM_RCU:
8215  	case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8216  	case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8217  	{
8218  		/* For bpf_sk_release, it needs to match against first member
8219  		 * 'struct sock_common', hence make an exception for it. This
8220  		 * allows bpf_sk_release to work for multiple socket types.
8221  		 */
8222  		bool strict_type_match = arg_type_is_release(arg_type) &&
8223  					 meta->func_id != BPF_FUNC_sk_release;
8224  
8225  		if (type_may_be_null(reg->type) &&
8226  		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8227  			verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8228  			return -EACCES;
8229  		}
8230  
8231  		if (!arg_btf_id) {
8232  			if (!compatible->btf_id) {
8233  				verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8234  				return -EFAULT;
8235  			}
8236  			arg_btf_id = compatible->btf_id;
8237  		}
8238  
8239  		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8240  			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8241  				return -EACCES;
8242  		} else {
8243  			if (arg_btf_id == BPF_PTR_POISON) {
8244  				verbose(env, "verifier internal error:");
8245  				verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8246  					regno);
8247  				return -EACCES;
8248  			}
8249  
8250  			if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8251  						  btf_vmlinux, *arg_btf_id,
8252  						  strict_type_match)) {
8253  				verbose(env, "R%d is of type %s but %s is expected\n",
8254  					regno, btf_type_name(reg->btf, reg->btf_id),
8255  					btf_type_name(btf_vmlinux, *arg_btf_id));
8256  				return -EACCES;
8257  			}
8258  		}
8259  		break;
8260  	}
8261  	case PTR_TO_BTF_ID | MEM_ALLOC:
8262  		if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8263  		    meta->func_id != BPF_FUNC_kptr_xchg) {
8264  			verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8265  			return -EFAULT;
8266  		}
8267  		if (meta->func_id == BPF_FUNC_kptr_xchg) {
8268  			if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8269  				return -EACCES;
8270  		}
8271  		break;
8272  	case PTR_TO_BTF_ID | MEM_PERCPU:
8273  	case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8274  		/* Handled by helper specific checks */
8275  		break;
8276  	default:
8277  		verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8278  		return -EFAULT;
8279  	}
8280  	return 0;
8281  }
8282  
8283  static struct btf_field *
reg_find_field_offset(const struct bpf_reg_state * reg,s32 off,u32 fields)8284  reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8285  {
8286  	struct btf_field *field;
8287  	struct btf_record *rec;
8288  
8289  	rec = reg_btf_record(reg);
8290  	if (!rec)
8291  		return NULL;
8292  
8293  	field = btf_record_find(rec, off, fields);
8294  	if (!field)
8295  		return NULL;
8296  
8297  	return field;
8298  }
8299  
check_func_arg_reg_off(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,enum bpf_arg_type arg_type)8300  int check_func_arg_reg_off(struct bpf_verifier_env *env,
8301  			   const struct bpf_reg_state *reg, int regno,
8302  			   enum bpf_arg_type arg_type)
8303  {
8304  	u32 type = reg->type;
8305  
8306  	/* When referenced register is passed to release function, its fixed
8307  	 * offset must be 0.
8308  	 *
8309  	 * We will check arg_type_is_release reg has ref_obj_id when storing
8310  	 * meta->release_regno.
8311  	 */
8312  	if (arg_type_is_release(arg_type)) {
8313  		/* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8314  		 * may not directly point to the object being released, but to
8315  		 * dynptr pointing to such object, which might be at some offset
8316  		 * on the stack. In that case, we simply to fallback to the
8317  		 * default handling.
8318  		 */
8319  		if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8320  			return 0;
8321  
8322  		/* Doing check_ptr_off_reg check for the offset will catch this
8323  		 * because fixed_off_ok is false, but checking here allows us
8324  		 * to give the user a better error message.
8325  		 */
8326  		if (reg->off) {
8327  			verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8328  				regno);
8329  			return -EINVAL;
8330  		}
8331  		return __check_ptr_off_reg(env, reg, regno, false);
8332  	}
8333  
8334  	switch (type) {
8335  	/* Pointer types where both fixed and variable offset is explicitly allowed: */
8336  	case PTR_TO_STACK:
8337  	case PTR_TO_PACKET:
8338  	case PTR_TO_PACKET_META:
8339  	case PTR_TO_MAP_KEY:
8340  	case PTR_TO_MAP_VALUE:
8341  	case PTR_TO_MEM:
8342  	case PTR_TO_MEM | MEM_RDONLY:
8343  	case PTR_TO_MEM | MEM_RINGBUF:
8344  	case PTR_TO_BUF:
8345  	case PTR_TO_BUF | MEM_RDONLY:
8346  	case SCALAR_VALUE:
8347  		return 0;
8348  	/* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8349  	 * fixed offset.
8350  	 */
8351  	case PTR_TO_BTF_ID:
8352  	case PTR_TO_BTF_ID | MEM_ALLOC:
8353  	case PTR_TO_BTF_ID | PTR_TRUSTED:
8354  	case PTR_TO_BTF_ID | MEM_RCU:
8355  	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8356  	case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8357  		/* When referenced PTR_TO_BTF_ID is passed to release function,
8358  		 * its fixed offset must be 0. In the other cases, fixed offset
8359  		 * can be non-zero. This was already checked above. So pass
8360  		 * fixed_off_ok as true to allow fixed offset for all other
8361  		 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8362  		 * still need to do checks instead of returning.
8363  		 */
8364  		return __check_ptr_off_reg(env, reg, regno, true);
8365  	default:
8366  		return __check_ptr_off_reg(env, reg, regno, false);
8367  	}
8368  }
8369  
get_dynptr_arg_reg(struct bpf_verifier_env * env,const struct bpf_func_proto * fn,struct bpf_reg_state * regs)8370  static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8371  						const struct bpf_func_proto *fn,
8372  						struct bpf_reg_state *regs)
8373  {
8374  	struct bpf_reg_state *state = NULL;
8375  	int i;
8376  
8377  	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8378  		if (arg_type_is_dynptr(fn->arg_type[i])) {
8379  			if (state) {
8380  				verbose(env, "verifier internal error: multiple dynptr args\n");
8381  				return NULL;
8382  			}
8383  			state = &regs[BPF_REG_1 + i];
8384  		}
8385  
8386  	if (!state)
8387  		verbose(env, "verifier internal error: no dynptr arg found\n");
8388  
8389  	return state;
8390  }
8391  
dynptr_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg)8392  static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8393  {
8394  	struct bpf_func_state *state = func(env, reg);
8395  	int spi;
8396  
8397  	if (reg->type == CONST_PTR_TO_DYNPTR)
8398  		return reg->id;
8399  	spi = dynptr_get_spi(env, reg);
8400  	if (spi < 0)
8401  		return spi;
8402  	return state->stack[spi].spilled_ptr.id;
8403  }
8404  
dynptr_ref_obj_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg)8405  static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8406  {
8407  	struct bpf_func_state *state = func(env, reg);
8408  	int spi;
8409  
8410  	if (reg->type == CONST_PTR_TO_DYNPTR)
8411  		return reg->ref_obj_id;
8412  	spi = dynptr_get_spi(env, reg);
8413  	if (spi < 0)
8414  		return spi;
8415  	return state->stack[spi].spilled_ptr.ref_obj_id;
8416  }
8417  
dynptr_get_type(struct bpf_verifier_env * env,struct bpf_reg_state * reg)8418  static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8419  					    struct bpf_reg_state *reg)
8420  {
8421  	struct bpf_func_state *state = func(env, reg);
8422  	int spi;
8423  
8424  	if (reg->type == CONST_PTR_TO_DYNPTR)
8425  		return reg->dynptr.type;
8426  
8427  	spi = __get_spi(reg->off);
8428  	if (spi < 0) {
8429  		verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8430  		return BPF_DYNPTR_TYPE_INVALID;
8431  	}
8432  
8433  	return state->stack[spi].spilled_ptr.dynptr.type;
8434  }
8435  
check_func_arg(struct bpf_verifier_env * env,u32 arg,struct bpf_call_arg_meta * meta,const struct bpf_func_proto * fn,int insn_idx)8436  static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8437  			  struct bpf_call_arg_meta *meta,
8438  			  const struct bpf_func_proto *fn,
8439  			  int insn_idx)
8440  {
8441  	u32 regno = BPF_REG_1 + arg;
8442  	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8443  	enum bpf_arg_type arg_type = fn->arg_type[arg];
8444  	enum bpf_reg_type type = reg->type;
8445  	u32 *arg_btf_id = NULL;
8446  	int err = 0;
8447  
8448  	if (arg_type == ARG_DONTCARE)
8449  		return 0;
8450  
8451  	err = check_reg_arg(env, regno, SRC_OP);
8452  	if (err)
8453  		return err;
8454  
8455  	if (arg_type == ARG_ANYTHING) {
8456  		if (is_pointer_value(env, regno)) {
8457  			verbose(env, "R%d leaks addr into helper function\n",
8458  				regno);
8459  			return -EACCES;
8460  		}
8461  		return 0;
8462  	}
8463  
8464  	if (type_is_pkt_pointer(type) &&
8465  	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8466  		verbose(env, "helper access to the packet is not allowed\n");
8467  		return -EACCES;
8468  	}
8469  
8470  	if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8471  		err = resolve_map_arg_type(env, meta, &arg_type);
8472  		if (err)
8473  			return err;
8474  	}
8475  
8476  	if (register_is_null(reg) && type_may_be_null(arg_type))
8477  		/* A NULL register has a SCALAR_VALUE type, so skip
8478  		 * type checking.
8479  		 */
8480  		goto skip_type_check;
8481  
8482  	/* arg_btf_id and arg_size are in a union. */
8483  	if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8484  	    base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8485  		arg_btf_id = fn->arg_btf_id[arg];
8486  
8487  	err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8488  	if (err)
8489  		return err;
8490  
8491  	err = check_func_arg_reg_off(env, reg, regno, arg_type);
8492  	if (err)
8493  		return err;
8494  
8495  skip_type_check:
8496  	if (arg_type_is_release(arg_type)) {
8497  		if (arg_type_is_dynptr(arg_type)) {
8498  			struct bpf_func_state *state = func(env, reg);
8499  			int spi;
8500  
8501  			/* Only dynptr created on stack can be released, thus
8502  			 * the get_spi and stack state checks for spilled_ptr
8503  			 * should only be done before process_dynptr_func for
8504  			 * PTR_TO_STACK.
8505  			 */
8506  			if (reg->type == PTR_TO_STACK) {
8507  				spi = dynptr_get_spi(env, reg);
8508  				if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8509  					verbose(env, "arg %d is an unacquired reference\n", regno);
8510  					return -EINVAL;
8511  				}
8512  			} else {
8513  				verbose(env, "cannot release unowned const bpf_dynptr\n");
8514  				return -EINVAL;
8515  			}
8516  		} else if (!reg->ref_obj_id && !register_is_null(reg)) {
8517  			verbose(env, "R%d must be referenced when passed to release function\n",
8518  				regno);
8519  			return -EINVAL;
8520  		}
8521  		if (meta->release_regno) {
8522  			verbose(env, "verifier internal error: more than one release argument\n");
8523  			return -EFAULT;
8524  		}
8525  		meta->release_regno = regno;
8526  	}
8527  
8528  	if (reg->ref_obj_id) {
8529  		if (meta->ref_obj_id) {
8530  			verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8531  				regno, reg->ref_obj_id,
8532  				meta->ref_obj_id);
8533  			return -EFAULT;
8534  		}
8535  		meta->ref_obj_id = reg->ref_obj_id;
8536  	}
8537  
8538  	switch (base_type(arg_type)) {
8539  	case ARG_CONST_MAP_PTR:
8540  		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8541  		if (meta->map_ptr) {
8542  			/* Use map_uid (which is unique id of inner map) to reject:
8543  			 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8544  			 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8545  			 * if (inner_map1 && inner_map2) {
8546  			 *     timer = bpf_map_lookup_elem(inner_map1);
8547  			 *     if (timer)
8548  			 *         // mismatch would have been allowed
8549  			 *         bpf_timer_init(timer, inner_map2);
8550  			 * }
8551  			 *
8552  			 * Comparing map_ptr is enough to distinguish normal and outer maps.
8553  			 */
8554  			if (meta->map_ptr != reg->map_ptr ||
8555  			    meta->map_uid != reg->map_uid) {
8556  				verbose(env,
8557  					"timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8558  					meta->map_uid, reg->map_uid);
8559  				return -EINVAL;
8560  			}
8561  		}
8562  		meta->map_ptr = reg->map_ptr;
8563  		meta->map_uid = reg->map_uid;
8564  		break;
8565  	case ARG_PTR_TO_MAP_KEY:
8566  		/* bpf_map_xxx(..., map_ptr, ..., key) call:
8567  		 * check that [key, key + map->key_size) are within
8568  		 * stack limits and initialized
8569  		 */
8570  		if (!meta->map_ptr) {
8571  			/* in function declaration map_ptr must come before
8572  			 * map_key, so that it's verified and known before
8573  			 * we have to check map_key here. Otherwise it means
8574  			 * that kernel subsystem misconfigured verifier
8575  			 */
8576  			verbose(env, "invalid map_ptr to access map->key\n");
8577  			return -EACCES;
8578  		}
8579  		err = check_helper_mem_access(env, regno, meta->map_ptr->key_size,
8580  					      BPF_READ, false, NULL);
8581  		break;
8582  	case ARG_PTR_TO_MAP_VALUE:
8583  		if (type_may_be_null(arg_type) && register_is_null(reg))
8584  			return 0;
8585  
8586  		/* bpf_map_xxx(..., map_ptr, ..., value) call:
8587  		 * check [value, value + map->value_size) validity
8588  		 */
8589  		if (!meta->map_ptr) {
8590  			/* kernel subsystem misconfigured verifier */
8591  			verbose(env, "invalid map_ptr to access map->value\n");
8592  			return -EACCES;
8593  		}
8594  		meta->raw_mode = arg_type & MEM_UNINIT;
8595  		err = check_helper_mem_access(env, regno, meta->map_ptr->value_size,
8596  					      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
8597  					      false, meta);
8598  		break;
8599  	case ARG_PTR_TO_PERCPU_BTF_ID:
8600  		if (!reg->btf_id) {
8601  			verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8602  			return -EACCES;
8603  		}
8604  		meta->ret_btf = reg->btf;
8605  		meta->ret_btf_id = reg->btf_id;
8606  		break;
8607  	case ARG_PTR_TO_SPIN_LOCK:
8608  		if (in_rbtree_lock_required_cb(env)) {
8609  			verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8610  			return -EACCES;
8611  		}
8612  		if (meta->func_id == BPF_FUNC_spin_lock) {
8613  			err = process_spin_lock(env, regno, true);
8614  			if (err)
8615  				return err;
8616  		} else if (meta->func_id == BPF_FUNC_spin_unlock) {
8617  			err = process_spin_lock(env, regno, false);
8618  			if (err)
8619  				return err;
8620  		} else {
8621  			verbose(env, "verifier internal error\n");
8622  			return -EFAULT;
8623  		}
8624  		break;
8625  	case ARG_PTR_TO_TIMER:
8626  		err = process_timer_func(env, regno, meta);
8627  		if (err)
8628  			return err;
8629  		break;
8630  	case ARG_PTR_TO_FUNC:
8631  		meta->subprogno = reg->subprogno;
8632  		break;
8633  	case ARG_PTR_TO_MEM:
8634  		/* The access to this pointer is only checked when we hit the
8635  		 * next is_mem_size argument below.
8636  		 */
8637  		meta->raw_mode = arg_type & MEM_UNINIT;
8638  		if (arg_type & MEM_FIXED_SIZE) {
8639  			err = check_helper_mem_access(env, regno, fn->arg_size[arg],
8640  						      arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
8641  						      false, meta);
8642  			if (err)
8643  				return err;
8644  			if (arg_type & MEM_ALIGNED)
8645  				err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
8646  		}
8647  		break;
8648  	case ARG_CONST_SIZE:
8649  		err = check_mem_size_reg(env, reg, regno,
8650  					 fn->arg_type[arg - 1] & MEM_WRITE ?
8651  					 BPF_WRITE : BPF_READ,
8652  					 false, meta);
8653  		break;
8654  	case ARG_CONST_SIZE_OR_ZERO:
8655  		err = check_mem_size_reg(env, reg, regno,
8656  					 fn->arg_type[arg - 1] & MEM_WRITE ?
8657  					 BPF_WRITE : BPF_READ,
8658  					 true, meta);
8659  		break;
8660  	case ARG_PTR_TO_DYNPTR:
8661  		err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8662  		if (err)
8663  			return err;
8664  		break;
8665  	case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8666  		if (!tnum_is_const(reg->var_off)) {
8667  			verbose(env, "R%d is not a known constant'\n",
8668  				regno);
8669  			return -EACCES;
8670  		}
8671  		meta->mem_size = reg->var_off.value;
8672  		err = mark_chain_precision(env, regno);
8673  		if (err)
8674  			return err;
8675  		break;
8676  	case ARG_PTR_TO_CONST_STR:
8677  	{
8678  		struct bpf_map *map = reg->map_ptr;
8679  		int map_off;
8680  		u64 map_addr;
8681  		char *str_ptr;
8682  
8683  		if (!bpf_map_is_rdonly(map)) {
8684  			verbose(env, "R%d does not point to a readonly map'\n", regno);
8685  			return -EACCES;
8686  		}
8687  
8688  		if (!tnum_is_const(reg->var_off)) {
8689  			verbose(env, "R%d is not a constant address'\n", regno);
8690  			return -EACCES;
8691  		}
8692  
8693  		if (!map->ops->map_direct_value_addr) {
8694  			verbose(env, "no direct value access support for this map type\n");
8695  			return -EACCES;
8696  		}
8697  
8698  		err = check_map_access(env, regno, reg->off,
8699  				       map->value_size - reg->off, false,
8700  				       ACCESS_HELPER);
8701  		if (err)
8702  			return err;
8703  
8704  		map_off = reg->off + reg->var_off.value;
8705  		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8706  		if (err) {
8707  			verbose(env, "direct value access on string failed\n");
8708  			return err;
8709  		}
8710  
8711  		str_ptr = (char *)(long)(map_addr);
8712  		if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8713  			verbose(env, "string is not zero-terminated\n");
8714  			return -EINVAL;
8715  		}
8716  		break;
8717  	}
8718  	case ARG_PTR_TO_KPTR:
8719  		err = process_kptr_func(env, regno, meta);
8720  		if (err)
8721  			return err;
8722  		break;
8723  	}
8724  
8725  	return err;
8726  }
8727  
may_update_sockmap(struct bpf_verifier_env * env,int func_id)8728  static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8729  {
8730  	enum bpf_attach_type eatype = env->prog->expected_attach_type;
8731  	enum bpf_prog_type type = resolve_prog_type(env->prog);
8732  
8733  	if (func_id != BPF_FUNC_map_update_elem &&
8734  	    func_id != BPF_FUNC_map_delete_elem)
8735  		return false;
8736  
8737  	/* It's not possible to get access to a locked struct sock in these
8738  	 * contexts, so updating is safe.
8739  	 */
8740  	switch (type) {
8741  	case BPF_PROG_TYPE_TRACING:
8742  		if (eatype == BPF_TRACE_ITER)
8743  			return true;
8744  		break;
8745  	case BPF_PROG_TYPE_SOCK_OPS:
8746  		/* map_update allowed only via dedicated helpers with event type checks */
8747  		if (func_id == BPF_FUNC_map_delete_elem)
8748  			return true;
8749  		break;
8750  	case BPF_PROG_TYPE_SOCKET_FILTER:
8751  	case BPF_PROG_TYPE_SCHED_CLS:
8752  	case BPF_PROG_TYPE_SCHED_ACT:
8753  	case BPF_PROG_TYPE_XDP:
8754  	case BPF_PROG_TYPE_SK_REUSEPORT:
8755  	case BPF_PROG_TYPE_FLOW_DISSECTOR:
8756  	case BPF_PROG_TYPE_SK_LOOKUP:
8757  		return true;
8758  	default:
8759  		break;
8760  	}
8761  
8762  	verbose(env, "cannot update sockmap in this context\n");
8763  	return false;
8764  }
8765  
allow_tail_call_in_subprogs(struct bpf_verifier_env * env)8766  static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8767  {
8768  	return env->prog->jit_requested &&
8769  	       bpf_jit_supports_subprog_tailcalls();
8770  }
8771  
check_map_func_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,int func_id)8772  static int check_map_func_compatibility(struct bpf_verifier_env *env,
8773  					struct bpf_map *map, int func_id)
8774  {
8775  	if (!map)
8776  		return 0;
8777  
8778  	/* We need a two way check, first is from map perspective ... */
8779  	switch (map->map_type) {
8780  	case BPF_MAP_TYPE_PROG_ARRAY:
8781  		if (func_id != BPF_FUNC_tail_call)
8782  			goto error;
8783  		break;
8784  	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8785  		if (func_id != BPF_FUNC_perf_event_read &&
8786  		    func_id != BPF_FUNC_perf_event_output &&
8787  		    func_id != BPF_FUNC_skb_output &&
8788  		    func_id != BPF_FUNC_perf_event_read_value &&
8789  		    func_id != BPF_FUNC_xdp_output)
8790  			goto error;
8791  		break;
8792  	case BPF_MAP_TYPE_RINGBUF:
8793  		if (func_id != BPF_FUNC_ringbuf_output &&
8794  		    func_id != BPF_FUNC_ringbuf_reserve &&
8795  		    func_id != BPF_FUNC_ringbuf_query &&
8796  		    func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8797  		    func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8798  		    func_id != BPF_FUNC_ringbuf_discard_dynptr)
8799  			goto error;
8800  		break;
8801  	case BPF_MAP_TYPE_USER_RINGBUF:
8802  		if (func_id != BPF_FUNC_user_ringbuf_drain)
8803  			goto error;
8804  		break;
8805  	case BPF_MAP_TYPE_STACK_TRACE:
8806  		if (func_id != BPF_FUNC_get_stackid)
8807  			goto error;
8808  		break;
8809  	case BPF_MAP_TYPE_CGROUP_ARRAY:
8810  		if (func_id != BPF_FUNC_skb_under_cgroup &&
8811  		    func_id != BPF_FUNC_current_task_under_cgroup)
8812  			goto error;
8813  		break;
8814  	case BPF_MAP_TYPE_CGROUP_STORAGE:
8815  	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8816  		if (func_id != BPF_FUNC_get_local_storage)
8817  			goto error;
8818  		break;
8819  	case BPF_MAP_TYPE_DEVMAP:
8820  	case BPF_MAP_TYPE_DEVMAP_HASH:
8821  		if (func_id != BPF_FUNC_redirect_map &&
8822  		    func_id != BPF_FUNC_map_lookup_elem)
8823  			goto error;
8824  		break;
8825  	/* Restrict bpf side of cpumap and xskmap, open when use-cases
8826  	 * appear.
8827  	 */
8828  	case BPF_MAP_TYPE_CPUMAP:
8829  		if (func_id != BPF_FUNC_redirect_map)
8830  			goto error;
8831  		break;
8832  	case BPF_MAP_TYPE_XSKMAP:
8833  		if (func_id != BPF_FUNC_redirect_map &&
8834  		    func_id != BPF_FUNC_map_lookup_elem)
8835  			goto error;
8836  		break;
8837  	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8838  	case BPF_MAP_TYPE_HASH_OF_MAPS:
8839  		if (func_id != BPF_FUNC_map_lookup_elem)
8840  			goto error;
8841  		break;
8842  	case BPF_MAP_TYPE_SOCKMAP:
8843  		if (func_id != BPF_FUNC_sk_redirect_map &&
8844  		    func_id != BPF_FUNC_sock_map_update &&
8845  		    func_id != BPF_FUNC_msg_redirect_map &&
8846  		    func_id != BPF_FUNC_sk_select_reuseport &&
8847  		    func_id != BPF_FUNC_map_lookup_elem &&
8848  		    !may_update_sockmap(env, func_id))
8849  			goto error;
8850  		break;
8851  	case BPF_MAP_TYPE_SOCKHASH:
8852  		if (func_id != BPF_FUNC_sk_redirect_hash &&
8853  		    func_id != BPF_FUNC_sock_hash_update &&
8854  		    func_id != BPF_FUNC_msg_redirect_hash &&
8855  		    func_id != BPF_FUNC_sk_select_reuseport &&
8856  		    func_id != BPF_FUNC_map_lookup_elem &&
8857  		    !may_update_sockmap(env, func_id))
8858  			goto error;
8859  		break;
8860  	case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8861  		if (func_id != BPF_FUNC_sk_select_reuseport)
8862  			goto error;
8863  		break;
8864  	case BPF_MAP_TYPE_QUEUE:
8865  	case BPF_MAP_TYPE_STACK:
8866  		if (func_id != BPF_FUNC_map_peek_elem &&
8867  		    func_id != BPF_FUNC_map_pop_elem &&
8868  		    func_id != BPF_FUNC_map_push_elem)
8869  			goto error;
8870  		break;
8871  	case BPF_MAP_TYPE_SK_STORAGE:
8872  		if (func_id != BPF_FUNC_sk_storage_get &&
8873  		    func_id != BPF_FUNC_sk_storage_delete &&
8874  		    func_id != BPF_FUNC_kptr_xchg)
8875  			goto error;
8876  		break;
8877  	case BPF_MAP_TYPE_INODE_STORAGE:
8878  		if (func_id != BPF_FUNC_inode_storage_get &&
8879  		    func_id != BPF_FUNC_inode_storage_delete &&
8880  		    func_id != BPF_FUNC_kptr_xchg)
8881  			goto error;
8882  		break;
8883  	case BPF_MAP_TYPE_TASK_STORAGE:
8884  		if (func_id != BPF_FUNC_task_storage_get &&
8885  		    func_id != BPF_FUNC_task_storage_delete &&
8886  		    func_id != BPF_FUNC_kptr_xchg)
8887  			goto error;
8888  		break;
8889  	case BPF_MAP_TYPE_CGRP_STORAGE:
8890  		if (func_id != BPF_FUNC_cgrp_storage_get &&
8891  		    func_id != BPF_FUNC_cgrp_storage_delete &&
8892  		    func_id != BPF_FUNC_kptr_xchg)
8893  			goto error;
8894  		break;
8895  	case BPF_MAP_TYPE_BLOOM_FILTER:
8896  		if (func_id != BPF_FUNC_map_peek_elem &&
8897  		    func_id != BPF_FUNC_map_push_elem)
8898  			goto error;
8899  		break;
8900  	default:
8901  		break;
8902  	}
8903  
8904  	/* ... and second from the function itself. */
8905  	switch (func_id) {
8906  	case BPF_FUNC_tail_call:
8907  		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8908  			goto error;
8909  		if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8910  			verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8911  			return -EINVAL;
8912  		}
8913  		break;
8914  	case BPF_FUNC_perf_event_read:
8915  	case BPF_FUNC_perf_event_output:
8916  	case BPF_FUNC_perf_event_read_value:
8917  	case BPF_FUNC_skb_output:
8918  	case BPF_FUNC_xdp_output:
8919  		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8920  			goto error;
8921  		break;
8922  	case BPF_FUNC_ringbuf_output:
8923  	case BPF_FUNC_ringbuf_reserve:
8924  	case BPF_FUNC_ringbuf_query:
8925  	case BPF_FUNC_ringbuf_reserve_dynptr:
8926  	case BPF_FUNC_ringbuf_submit_dynptr:
8927  	case BPF_FUNC_ringbuf_discard_dynptr:
8928  		if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8929  			goto error;
8930  		break;
8931  	case BPF_FUNC_user_ringbuf_drain:
8932  		if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8933  			goto error;
8934  		break;
8935  	case BPF_FUNC_get_stackid:
8936  		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8937  			goto error;
8938  		break;
8939  	case BPF_FUNC_current_task_under_cgroup:
8940  	case BPF_FUNC_skb_under_cgroup:
8941  		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8942  			goto error;
8943  		break;
8944  	case BPF_FUNC_redirect_map:
8945  		if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8946  		    map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8947  		    map->map_type != BPF_MAP_TYPE_CPUMAP &&
8948  		    map->map_type != BPF_MAP_TYPE_XSKMAP)
8949  			goto error;
8950  		break;
8951  	case BPF_FUNC_sk_redirect_map:
8952  	case BPF_FUNC_msg_redirect_map:
8953  	case BPF_FUNC_sock_map_update:
8954  		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8955  			goto error;
8956  		break;
8957  	case BPF_FUNC_sk_redirect_hash:
8958  	case BPF_FUNC_msg_redirect_hash:
8959  	case BPF_FUNC_sock_hash_update:
8960  		if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8961  			goto error;
8962  		break;
8963  	case BPF_FUNC_get_local_storage:
8964  		if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8965  		    map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8966  			goto error;
8967  		break;
8968  	case BPF_FUNC_sk_select_reuseport:
8969  		if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8970  		    map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8971  		    map->map_type != BPF_MAP_TYPE_SOCKHASH)
8972  			goto error;
8973  		break;
8974  	case BPF_FUNC_map_pop_elem:
8975  		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8976  		    map->map_type != BPF_MAP_TYPE_STACK)
8977  			goto error;
8978  		break;
8979  	case BPF_FUNC_map_peek_elem:
8980  	case BPF_FUNC_map_push_elem:
8981  		if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8982  		    map->map_type != BPF_MAP_TYPE_STACK &&
8983  		    map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8984  			goto error;
8985  		break;
8986  	case BPF_FUNC_map_lookup_percpu_elem:
8987  		if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8988  		    map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8989  		    map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8990  			goto error;
8991  		break;
8992  	case BPF_FUNC_sk_storage_get:
8993  	case BPF_FUNC_sk_storage_delete:
8994  		if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8995  			goto error;
8996  		break;
8997  	case BPF_FUNC_inode_storage_get:
8998  	case BPF_FUNC_inode_storage_delete:
8999  		if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9000  			goto error;
9001  		break;
9002  	case BPF_FUNC_task_storage_get:
9003  	case BPF_FUNC_task_storage_delete:
9004  		if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9005  			goto error;
9006  		break;
9007  	case BPF_FUNC_cgrp_storage_get:
9008  	case BPF_FUNC_cgrp_storage_delete:
9009  		if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9010  			goto error;
9011  		break;
9012  	default:
9013  		break;
9014  	}
9015  
9016  	return 0;
9017  error:
9018  	verbose(env, "cannot pass map_type %d into func %s#%d\n",
9019  		map->map_type, func_id_name(func_id), func_id);
9020  	return -EINVAL;
9021  }
9022  
check_raw_mode_ok(const struct bpf_func_proto * fn)9023  static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9024  {
9025  	int count = 0;
9026  
9027  	if (arg_type_is_raw_mem(fn->arg1_type))
9028  		count++;
9029  	if (arg_type_is_raw_mem(fn->arg2_type))
9030  		count++;
9031  	if (arg_type_is_raw_mem(fn->arg3_type))
9032  		count++;
9033  	if (arg_type_is_raw_mem(fn->arg4_type))
9034  		count++;
9035  	if (arg_type_is_raw_mem(fn->arg5_type))
9036  		count++;
9037  
9038  	/* We only support one arg being in raw mode at the moment,
9039  	 * which is sufficient for the helper functions we have
9040  	 * right now.
9041  	 */
9042  	return count <= 1;
9043  }
9044  
check_args_pair_invalid(const struct bpf_func_proto * fn,int arg)9045  static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9046  {
9047  	bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9048  	bool has_size = fn->arg_size[arg] != 0;
9049  	bool is_next_size = false;
9050  
9051  	if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9052  		is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9053  
9054  	if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9055  		return is_next_size;
9056  
9057  	return has_size == is_next_size || is_next_size == is_fixed;
9058  }
9059  
check_arg_pair_ok(const struct bpf_func_proto * fn)9060  static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9061  {
9062  	/* bpf_xxx(..., buf, len) call will access 'len'
9063  	 * bytes from memory 'buf'. Both arg types need
9064  	 * to be paired, so make sure there's no buggy
9065  	 * helper function specification.
9066  	 */
9067  	if (arg_type_is_mem_size(fn->arg1_type) ||
9068  	    check_args_pair_invalid(fn, 0) ||
9069  	    check_args_pair_invalid(fn, 1) ||
9070  	    check_args_pair_invalid(fn, 2) ||
9071  	    check_args_pair_invalid(fn, 3) ||
9072  	    check_args_pair_invalid(fn, 4))
9073  		return false;
9074  
9075  	return true;
9076  }
9077  
check_btf_id_ok(const struct bpf_func_proto * fn)9078  static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9079  {
9080  	int i;
9081  
9082  	for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9083  		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9084  			return !!fn->arg_btf_id[i];
9085  		if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9086  			return fn->arg_btf_id[i] == BPF_PTR_POISON;
9087  		if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9088  		    /* arg_btf_id and arg_size are in a union. */
9089  		    (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9090  		     !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9091  			return false;
9092  	}
9093  
9094  	return true;
9095  }
9096  
check_func_proto(const struct bpf_func_proto * fn,int func_id)9097  static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9098  {
9099  	return check_raw_mode_ok(fn) &&
9100  	       check_arg_pair_ok(fn) &&
9101  	       check_btf_id_ok(fn) ? 0 : -EINVAL;
9102  }
9103  
9104  /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9105   * are now invalid, so turn them into unknown SCALAR_VALUE.
9106   *
9107   * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9108   * since these slices point to packet data.
9109   */
clear_all_pkt_pointers(struct bpf_verifier_env * env)9110  static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9111  {
9112  	struct bpf_func_state *state;
9113  	struct bpf_reg_state *reg;
9114  
9115  	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9116  		if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9117  			mark_reg_invalid(env, reg);
9118  	}));
9119  }
9120  
9121  enum {
9122  	AT_PKT_END = -1,
9123  	BEYOND_PKT_END = -2,
9124  };
9125  
mark_pkt_end(struct bpf_verifier_state * vstate,int regn,bool range_open)9126  static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9127  {
9128  	struct bpf_func_state *state = vstate->frame[vstate->curframe];
9129  	struct bpf_reg_state *reg = &state->regs[regn];
9130  
9131  	if (reg->type != PTR_TO_PACKET)
9132  		/* PTR_TO_PACKET_META is not supported yet */
9133  		return;
9134  
9135  	/* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9136  	 * How far beyond pkt_end it goes is unknown.
9137  	 * if (!range_open) it's the case of pkt >= pkt_end
9138  	 * if (range_open) it's the case of pkt > pkt_end
9139  	 * hence this pointer is at least 1 byte bigger than pkt_end
9140  	 */
9141  	if (range_open)
9142  		reg->range = BEYOND_PKT_END;
9143  	else
9144  		reg->range = AT_PKT_END;
9145  }
9146  
9147  /* The pointer with the specified id has released its reference to kernel
9148   * resources. Identify all copies of the same pointer and clear the reference.
9149   */
release_reference(struct bpf_verifier_env * env,int ref_obj_id)9150  static int release_reference(struct bpf_verifier_env *env,
9151  			     int ref_obj_id)
9152  {
9153  	struct bpf_func_state *state;
9154  	struct bpf_reg_state *reg;
9155  	int err;
9156  
9157  	err = release_reference_state(cur_func(env), ref_obj_id);
9158  	if (err)
9159  		return err;
9160  
9161  	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9162  		if (reg->ref_obj_id == ref_obj_id)
9163  			mark_reg_invalid(env, reg);
9164  	}));
9165  
9166  	return 0;
9167  }
9168  
invalidate_non_owning_refs(struct bpf_verifier_env * env)9169  static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9170  {
9171  	struct bpf_func_state *unused;
9172  	struct bpf_reg_state *reg;
9173  
9174  	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9175  		if (type_is_non_owning_ref(reg->type))
9176  			mark_reg_invalid(env, reg);
9177  	}));
9178  }
9179  
clear_caller_saved_regs(struct bpf_verifier_env * env,struct bpf_reg_state * regs)9180  static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9181  				    struct bpf_reg_state *regs)
9182  {
9183  	int i;
9184  
9185  	/* after the call registers r0 - r5 were scratched */
9186  	for (i = 0; i < CALLER_SAVED_REGS; i++) {
9187  		mark_reg_not_init(env, regs, caller_saved[i]);
9188  		__check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9189  	}
9190  }
9191  
9192  typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9193  				   struct bpf_func_state *caller,
9194  				   struct bpf_func_state *callee,
9195  				   int insn_idx);
9196  
9197  static int set_callee_state(struct bpf_verifier_env *env,
9198  			    struct bpf_func_state *caller,
9199  			    struct bpf_func_state *callee, int insn_idx);
9200  
setup_func_entry(struct bpf_verifier_env * env,int subprog,int callsite,set_callee_state_fn set_callee_state_cb,struct bpf_verifier_state * state)9201  static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9202  			    set_callee_state_fn set_callee_state_cb,
9203  			    struct bpf_verifier_state *state)
9204  {
9205  	struct bpf_func_state *caller, *callee;
9206  	int err;
9207  
9208  	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9209  		verbose(env, "the call stack of %d frames is too deep\n",
9210  			state->curframe + 2);
9211  		return -E2BIG;
9212  	}
9213  
9214  	if (state->frame[state->curframe + 1]) {
9215  		verbose(env, "verifier bug. Frame %d already allocated\n",
9216  			state->curframe + 1);
9217  		return -EFAULT;
9218  	}
9219  
9220  	caller = state->frame[state->curframe];
9221  	callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9222  	if (!callee)
9223  		return -ENOMEM;
9224  	state->frame[state->curframe + 1] = callee;
9225  
9226  	/* callee cannot access r0, r6 - r9 for reading and has to write
9227  	 * into its own stack before reading from it.
9228  	 * callee can read/write into caller's stack
9229  	 */
9230  	init_func_state(env, callee,
9231  			/* remember the callsite, it will be used by bpf_exit */
9232  			callsite,
9233  			state->curframe + 1 /* frameno within this callchain */,
9234  			subprog /* subprog number within this prog */);
9235  	/* Transfer references to the callee */
9236  	err = copy_reference_state(callee, caller);
9237  	err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9238  	if (err)
9239  		goto err_out;
9240  
9241  	/* only increment it after check_reg_arg() finished */
9242  	state->curframe++;
9243  
9244  	return 0;
9245  
9246  err_out:
9247  	free_func_state(callee);
9248  	state->frame[state->curframe + 1] = NULL;
9249  	return err;
9250  }
9251  
push_callback_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int insn_idx,int subprog,set_callee_state_fn set_callee_state_cb)9252  static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9253  			      int insn_idx, int subprog,
9254  			      set_callee_state_fn set_callee_state_cb)
9255  {
9256  	struct bpf_verifier_state *state = env->cur_state, *callback_state;
9257  	struct bpf_func_state *caller, *callee;
9258  	int err;
9259  
9260  	caller = state->frame[state->curframe];
9261  	err = btf_check_subprog_call(env, subprog, caller->regs);
9262  	if (err == -EFAULT)
9263  		return err;
9264  
9265  	/* set_callee_state is used for direct subprog calls, but we are
9266  	 * interested in validating only BPF helpers that can call subprogs as
9267  	 * callbacks
9268  	 */
9269  	if (bpf_pseudo_kfunc_call(insn) &&
9270  	    !is_sync_callback_calling_kfunc(insn->imm)) {
9271  		verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9272  			func_id_name(insn->imm), insn->imm);
9273  		return -EFAULT;
9274  	} else if (!bpf_pseudo_kfunc_call(insn) &&
9275  		   !is_callback_calling_function(insn->imm)) { /* helper */
9276  		verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9277  			func_id_name(insn->imm), insn->imm);
9278  		return -EFAULT;
9279  	}
9280  
9281  	if (insn->code == (BPF_JMP | BPF_CALL) &&
9282  	    insn->src_reg == 0 &&
9283  	    insn->imm == BPF_FUNC_timer_set_callback) {
9284  		struct bpf_verifier_state *async_cb;
9285  
9286  		/* there is no real recursion here. timer callbacks are async */
9287  		env->subprog_info[subprog].is_async_cb = true;
9288  		async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9289  					 insn_idx, subprog);
9290  		if (!async_cb)
9291  			return -EFAULT;
9292  		callee = async_cb->frame[0];
9293  		callee->async_entry_cnt = caller->async_entry_cnt + 1;
9294  
9295  		/* Convert bpf_timer_set_callback() args into timer callback args */
9296  		err = set_callee_state_cb(env, caller, callee, insn_idx);
9297  		if (err)
9298  			return err;
9299  
9300  		return 0;
9301  	}
9302  
9303  	/* for callback functions enqueue entry to callback and
9304  	 * proceed with next instruction within current frame.
9305  	 */
9306  	callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9307  	if (!callback_state)
9308  		return -ENOMEM;
9309  
9310  	err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9311  			       callback_state);
9312  	if (err)
9313  		return err;
9314  
9315  	callback_state->callback_unroll_depth++;
9316  	callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9317  	caller->callback_depth = 0;
9318  	return 0;
9319  }
9320  
check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)9321  static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9322  			   int *insn_idx)
9323  {
9324  	struct bpf_verifier_state *state = env->cur_state;
9325  	struct bpf_func_state *caller;
9326  	int err, subprog, target_insn;
9327  
9328  	target_insn = *insn_idx + insn->imm + 1;
9329  	subprog = find_subprog(env, target_insn);
9330  	if (subprog < 0) {
9331  		verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9332  		return -EFAULT;
9333  	}
9334  
9335  	caller = state->frame[state->curframe];
9336  	err = btf_check_subprog_call(env, subprog, caller->regs);
9337  	if (err == -EFAULT)
9338  		return err;
9339  	if (subprog_is_global(env, subprog)) {
9340  		if (err) {
9341  			verbose(env, "Caller passes invalid args into func#%d\n", subprog);
9342  			return err;
9343  		}
9344  
9345  		if (env->log.level & BPF_LOG_LEVEL)
9346  			verbose(env, "Func#%d is global and valid. Skipping.\n", subprog);
9347  		clear_caller_saved_regs(env, caller->regs);
9348  
9349  		/* All global functions return a 64-bit SCALAR_VALUE */
9350  		mark_reg_unknown(env, caller->regs, BPF_REG_0);
9351  		caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9352  
9353  		/* continue with next insn after call */
9354  		return 0;
9355  	}
9356  
9357  	/* for regular function entry setup new frame and continue
9358  	 * from that frame.
9359  	 */
9360  	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9361  	if (err)
9362  		return err;
9363  
9364  	clear_caller_saved_regs(env, caller->regs);
9365  
9366  	/* and go analyze first insn of the callee */
9367  	*insn_idx = env->subprog_info[subprog].start - 1;
9368  
9369  	if (env->log.level & BPF_LOG_LEVEL) {
9370  		verbose(env, "caller:\n");
9371  		print_verifier_state(env, caller, true);
9372  		verbose(env, "callee:\n");
9373  		print_verifier_state(env, state->frame[state->curframe], true);
9374  	}
9375  
9376  	return 0;
9377  }
9378  
map_set_for_each_callback_args(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee)9379  int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9380  				   struct bpf_func_state *caller,
9381  				   struct bpf_func_state *callee)
9382  {
9383  	/* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9384  	 *      void *callback_ctx, u64 flags);
9385  	 * callback_fn(struct bpf_map *map, void *key, void *value,
9386  	 *      void *callback_ctx);
9387  	 */
9388  	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9389  
9390  	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9391  	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9392  	callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9393  
9394  	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9395  	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9396  	callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9397  
9398  	/* pointer to stack or null */
9399  	callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9400  
9401  	/* unused */
9402  	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9403  	return 0;
9404  }
9405  
set_callee_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9406  static int set_callee_state(struct bpf_verifier_env *env,
9407  			    struct bpf_func_state *caller,
9408  			    struct bpf_func_state *callee, int insn_idx)
9409  {
9410  	int i;
9411  
9412  	/* copy r1 - r5 args that callee can access.  The copy includes parent
9413  	 * pointers, which connects us up to the liveness chain
9414  	 */
9415  	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9416  		callee->regs[i] = caller->regs[i];
9417  	return 0;
9418  }
9419  
set_map_elem_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9420  static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9421  				       struct bpf_func_state *caller,
9422  				       struct bpf_func_state *callee,
9423  				       int insn_idx)
9424  {
9425  	struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9426  	struct bpf_map *map;
9427  	int err;
9428  
9429  	if (bpf_map_ptr_poisoned(insn_aux)) {
9430  		verbose(env, "tail_call abusing map_ptr\n");
9431  		return -EINVAL;
9432  	}
9433  
9434  	map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9435  	if (!map->ops->map_set_for_each_callback_args ||
9436  	    !map->ops->map_for_each_callback) {
9437  		verbose(env, "callback function not allowed for map\n");
9438  		return -ENOTSUPP;
9439  	}
9440  
9441  	err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9442  	if (err)
9443  		return err;
9444  
9445  	callee->in_callback_fn = true;
9446  	callee->callback_ret_range = tnum_range(0, 1);
9447  	return 0;
9448  }
9449  
set_loop_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9450  static int set_loop_callback_state(struct bpf_verifier_env *env,
9451  				   struct bpf_func_state *caller,
9452  				   struct bpf_func_state *callee,
9453  				   int insn_idx)
9454  {
9455  	/* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9456  	 *	    u64 flags);
9457  	 * callback_fn(u32 index, void *callback_ctx);
9458  	 */
9459  	callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9460  	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9461  
9462  	/* unused */
9463  	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9464  	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9465  	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9466  
9467  	callee->in_callback_fn = true;
9468  	callee->callback_ret_range = tnum_range(0, 1);
9469  	return 0;
9470  }
9471  
set_timer_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9472  static int set_timer_callback_state(struct bpf_verifier_env *env,
9473  				    struct bpf_func_state *caller,
9474  				    struct bpf_func_state *callee,
9475  				    int insn_idx)
9476  {
9477  	struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9478  
9479  	/* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9480  	 * callback_fn(struct bpf_map *map, void *key, void *value);
9481  	 */
9482  	callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9483  	__mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9484  	callee->regs[BPF_REG_1].map_ptr = map_ptr;
9485  
9486  	callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9487  	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9488  	callee->regs[BPF_REG_2].map_ptr = map_ptr;
9489  
9490  	callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9491  	__mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9492  	callee->regs[BPF_REG_3].map_ptr = map_ptr;
9493  
9494  	/* unused */
9495  	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9496  	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9497  	callee->in_async_callback_fn = true;
9498  	callee->callback_ret_range = tnum_range(0, 1);
9499  	return 0;
9500  }
9501  
set_find_vma_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9502  static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9503  				       struct bpf_func_state *caller,
9504  				       struct bpf_func_state *callee,
9505  				       int insn_idx)
9506  {
9507  	/* bpf_find_vma(struct task_struct *task, u64 addr,
9508  	 *               void *callback_fn, void *callback_ctx, u64 flags)
9509  	 * (callback_fn)(struct task_struct *task,
9510  	 *               struct vm_area_struct *vma, void *callback_ctx);
9511  	 */
9512  	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9513  
9514  	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9515  	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9516  	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9517  	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9518  
9519  	/* pointer to stack or null */
9520  	callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9521  
9522  	/* unused */
9523  	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9524  	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9525  	callee->in_callback_fn = true;
9526  	callee->callback_ret_range = tnum_range(0, 1);
9527  	return 0;
9528  }
9529  
set_user_ringbuf_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9530  static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9531  					   struct bpf_func_state *caller,
9532  					   struct bpf_func_state *callee,
9533  					   int insn_idx)
9534  {
9535  	/* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9536  	 *			  callback_ctx, u64 flags);
9537  	 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9538  	 */
9539  	__mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9540  	mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9541  	callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9542  
9543  	/* unused */
9544  	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9545  	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9546  	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9547  
9548  	callee->in_callback_fn = true;
9549  	callee->callback_ret_range = tnum_range(0, 1);
9550  	return 0;
9551  }
9552  
set_rbtree_add_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9553  static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9554  					 struct bpf_func_state *caller,
9555  					 struct bpf_func_state *callee,
9556  					 int insn_idx)
9557  {
9558  	/* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9559  	 *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9560  	 *
9561  	 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9562  	 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9563  	 * by this point, so look at 'root'
9564  	 */
9565  	struct btf_field *field;
9566  
9567  	field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9568  				      BPF_RB_ROOT);
9569  	if (!field || !field->graph_root.value_btf_id)
9570  		return -EFAULT;
9571  
9572  	mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9573  	ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9574  	mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9575  	ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9576  
9577  	__mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9578  	__mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9579  	__mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9580  	callee->in_callback_fn = true;
9581  	callee->callback_ret_range = tnum_range(0, 1);
9582  	return 0;
9583  }
9584  
9585  static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9586  
9587  /* Are we currently verifying the callback for a rbtree helper that must
9588   * be called with lock held? If so, no need to complain about unreleased
9589   * lock
9590   */
in_rbtree_lock_required_cb(struct bpf_verifier_env * env)9591  static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9592  {
9593  	struct bpf_verifier_state *state = env->cur_state;
9594  	struct bpf_insn *insn = env->prog->insnsi;
9595  	struct bpf_func_state *callee;
9596  	int kfunc_btf_id;
9597  
9598  	if (!state->curframe)
9599  		return false;
9600  
9601  	callee = state->frame[state->curframe];
9602  
9603  	if (!callee->in_callback_fn)
9604  		return false;
9605  
9606  	kfunc_btf_id = insn[callee->callsite].imm;
9607  	return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9608  }
9609  
prepare_func_exit(struct bpf_verifier_env * env,int * insn_idx)9610  static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9611  {
9612  	struct bpf_verifier_state *state = env->cur_state, *prev_st;
9613  	struct bpf_func_state *caller, *callee;
9614  	struct bpf_reg_state *r0;
9615  	bool in_callback_fn;
9616  	int err;
9617  
9618  	callee = state->frame[state->curframe];
9619  	r0 = &callee->regs[BPF_REG_0];
9620  	if (r0->type == PTR_TO_STACK) {
9621  		/* technically it's ok to return caller's stack pointer
9622  		 * (or caller's caller's pointer) back to the caller,
9623  		 * since these pointers are valid. Only current stack
9624  		 * pointer will be invalid as soon as function exits,
9625  		 * but let's be conservative
9626  		 */
9627  		verbose(env, "cannot return stack pointer to the caller\n");
9628  		return -EINVAL;
9629  	}
9630  
9631  	caller = state->frame[state->curframe - 1];
9632  	if (callee->in_callback_fn) {
9633  		/* enforce R0 return value range [0, 1]. */
9634  		struct tnum range = callee->callback_ret_range;
9635  
9636  		if (r0->type != SCALAR_VALUE) {
9637  			verbose(env, "R0 not a scalar value\n");
9638  			return -EACCES;
9639  		}
9640  
9641  		/* we are going to rely on register's precise value */
9642  		err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9643  		err = err ?: mark_chain_precision(env, BPF_REG_0);
9644  		if (err)
9645  			return err;
9646  
9647  		if (!tnum_in(range, r0->var_off)) {
9648  			verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9649  			return -EINVAL;
9650  		}
9651  		if (!calls_callback(env, callee->callsite)) {
9652  			verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9653  				*insn_idx, callee->callsite);
9654  			return -EFAULT;
9655  		}
9656  	} else {
9657  		/* return to the caller whatever r0 had in the callee */
9658  		caller->regs[BPF_REG_0] = *r0;
9659  	}
9660  
9661  	/* callback_fn frame should have released its own additions to parent's
9662  	 * reference state at this point, or check_reference_leak would
9663  	 * complain, hence it must be the same as the caller. There is no need
9664  	 * to copy it back.
9665  	 */
9666  	if (!callee->in_callback_fn) {
9667  		/* Transfer references to the caller */
9668  		err = copy_reference_state(caller, callee);
9669  		if (err)
9670  			return err;
9671  	}
9672  
9673  	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9674  	 * there function call logic would reschedule callback visit. If iteration
9675  	 * converges is_state_visited() would prune that visit eventually.
9676  	 */
9677  	in_callback_fn = callee->in_callback_fn;
9678  	if (in_callback_fn)
9679  		*insn_idx = callee->callsite;
9680  	else
9681  		*insn_idx = callee->callsite + 1;
9682  
9683  	if (env->log.level & BPF_LOG_LEVEL) {
9684  		verbose(env, "returning from callee:\n");
9685  		print_verifier_state(env, callee, true);
9686  		verbose(env, "to caller at %d:\n", *insn_idx);
9687  		print_verifier_state(env, caller, true);
9688  	}
9689  	/* clear everything in the callee */
9690  	free_func_state(callee);
9691  	state->frame[state->curframe--] = NULL;
9692  
9693  	/* for callbacks widen imprecise scalars to make programs like below verify:
9694  	 *
9695  	 *   struct ctx { int i; }
9696  	 *   void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9697  	 *   ...
9698  	 *   struct ctx = { .i = 0; }
9699  	 *   bpf_loop(100, cb, &ctx, 0);
9700  	 *
9701  	 * This is similar to what is done in process_iter_next_call() for open
9702  	 * coded iterators.
9703  	 */
9704  	prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9705  	if (prev_st) {
9706  		err = widen_imprecise_scalars(env, prev_st, state);
9707  		if (err)
9708  			return err;
9709  	}
9710  	return 0;
9711  }
9712  
do_refine_retval_range(struct bpf_reg_state * regs,int ret_type,int func_id,struct bpf_call_arg_meta * meta)9713  static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9714  				   int func_id,
9715  				   struct bpf_call_arg_meta *meta)
9716  {
9717  	struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9718  
9719  	if (ret_type != RET_INTEGER)
9720  		return;
9721  
9722  	switch (func_id) {
9723  	case BPF_FUNC_get_stack:
9724  	case BPF_FUNC_get_task_stack:
9725  	case BPF_FUNC_probe_read_str:
9726  	case BPF_FUNC_probe_read_kernel_str:
9727  	case BPF_FUNC_probe_read_user_str:
9728  		ret_reg->smax_value = meta->msize_max_value;
9729  		ret_reg->s32_max_value = meta->msize_max_value;
9730  		ret_reg->smin_value = -MAX_ERRNO;
9731  		ret_reg->s32_min_value = -MAX_ERRNO;
9732  		reg_bounds_sync(ret_reg);
9733  		break;
9734  	case BPF_FUNC_get_smp_processor_id:
9735  		ret_reg->umax_value = nr_cpu_ids - 1;
9736  		ret_reg->u32_max_value = nr_cpu_ids - 1;
9737  		ret_reg->smax_value = nr_cpu_ids - 1;
9738  		ret_reg->s32_max_value = nr_cpu_ids - 1;
9739  		ret_reg->umin_value = 0;
9740  		ret_reg->u32_min_value = 0;
9741  		ret_reg->smin_value = 0;
9742  		ret_reg->s32_min_value = 0;
9743  		reg_bounds_sync(ret_reg);
9744  		break;
9745  	}
9746  }
9747  
9748  static int
record_func_map(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)9749  record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9750  		int func_id, int insn_idx)
9751  {
9752  	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9753  	struct bpf_map *map = meta->map_ptr;
9754  
9755  	if (func_id != BPF_FUNC_tail_call &&
9756  	    func_id != BPF_FUNC_map_lookup_elem &&
9757  	    func_id != BPF_FUNC_map_update_elem &&
9758  	    func_id != BPF_FUNC_map_delete_elem &&
9759  	    func_id != BPF_FUNC_map_push_elem &&
9760  	    func_id != BPF_FUNC_map_pop_elem &&
9761  	    func_id != BPF_FUNC_map_peek_elem &&
9762  	    func_id != BPF_FUNC_for_each_map_elem &&
9763  	    func_id != BPF_FUNC_redirect_map &&
9764  	    func_id != BPF_FUNC_map_lookup_percpu_elem)
9765  		return 0;
9766  
9767  	if (map == NULL) {
9768  		verbose(env, "kernel subsystem misconfigured verifier\n");
9769  		return -EINVAL;
9770  	}
9771  
9772  	/* In case of read-only, some additional restrictions
9773  	 * need to be applied in order to prevent altering the
9774  	 * state of the map from program side.
9775  	 */
9776  	if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9777  	    (func_id == BPF_FUNC_map_delete_elem ||
9778  	     func_id == BPF_FUNC_map_update_elem ||
9779  	     func_id == BPF_FUNC_map_push_elem ||
9780  	     func_id == BPF_FUNC_map_pop_elem)) {
9781  		verbose(env, "write into map forbidden\n");
9782  		return -EACCES;
9783  	}
9784  
9785  	if (!BPF_MAP_PTR(aux->map_ptr_state))
9786  		bpf_map_ptr_store(aux, meta->map_ptr,
9787  				  !meta->map_ptr->bypass_spec_v1);
9788  	else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9789  		bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9790  				  !meta->map_ptr->bypass_spec_v1);
9791  	return 0;
9792  }
9793  
9794  static int
record_func_key(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)9795  record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9796  		int func_id, int insn_idx)
9797  {
9798  	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9799  	struct bpf_reg_state *regs = cur_regs(env), *reg;
9800  	struct bpf_map *map = meta->map_ptr;
9801  	u64 val, max;
9802  	int err;
9803  
9804  	if (func_id != BPF_FUNC_tail_call)
9805  		return 0;
9806  	if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9807  		verbose(env, "kernel subsystem misconfigured verifier\n");
9808  		return -EINVAL;
9809  	}
9810  
9811  	reg = &regs[BPF_REG_3];
9812  	val = reg->var_off.value;
9813  	max = map->max_entries;
9814  
9815  	if (!(register_is_const(reg) && val < max)) {
9816  		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9817  		return 0;
9818  	}
9819  
9820  	err = mark_chain_precision(env, BPF_REG_3);
9821  	if (err)
9822  		return err;
9823  	if (bpf_map_key_unseen(aux))
9824  		bpf_map_key_store(aux, val);
9825  	else if (!bpf_map_key_poisoned(aux) &&
9826  		  bpf_map_key_immediate(aux) != val)
9827  		bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9828  	return 0;
9829  }
9830  
check_reference_leak(struct bpf_verifier_env * env)9831  static int check_reference_leak(struct bpf_verifier_env *env)
9832  {
9833  	struct bpf_func_state *state = cur_func(env);
9834  	bool refs_lingering = false;
9835  	int i;
9836  
9837  	if (state->frameno && !state->in_callback_fn)
9838  		return 0;
9839  
9840  	for (i = 0; i < state->acquired_refs; i++) {
9841  		if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9842  			continue;
9843  		verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9844  			state->refs[i].id, state->refs[i].insn_idx);
9845  		refs_lingering = true;
9846  	}
9847  	return refs_lingering ? -EINVAL : 0;
9848  }
9849  
check_bpf_snprintf_call(struct bpf_verifier_env * env,struct bpf_reg_state * regs)9850  static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9851  				   struct bpf_reg_state *regs)
9852  {
9853  	struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9854  	struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9855  	struct bpf_map *fmt_map = fmt_reg->map_ptr;
9856  	struct bpf_bprintf_data data = {};
9857  	int err, fmt_map_off, num_args;
9858  	u64 fmt_addr;
9859  	char *fmt;
9860  
9861  	/* data must be an array of u64 */
9862  	if (data_len_reg->var_off.value % 8)
9863  		return -EINVAL;
9864  	num_args = data_len_reg->var_off.value / 8;
9865  
9866  	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9867  	 * and map_direct_value_addr is set.
9868  	 */
9869  	fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9870  	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9871  						  fmt_map_off);
9872  	if (err) {
9873  		verbose(env, "verifier bug\n");
9874  		return -EFAULT;
9875  	}
9876  	fmt = (char *)(long)fmt_addr + fmt_map_off;
9877  
9878  	/* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9879  	 * can focus on validating the format specifiers.
9880  	 */
9881  	err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9882  	if (err < 0)
9883  		verbose(env, "Invalid format string\n");
9884  
9885  	return err;
9886  }
9887  
check_get_func_ip(struct bpf_verifier_env * env)9888  static int check_get_func_ip(struct bpf_verifier_env *env)
9889  {
9890  	enum bpf_prog_type type = resolve_prog_type(env->prog);
9891  	int func_id = BPF_FUNC_get_func_ip;
9892  
9893  	if (type == BPF_PROG_TYPE_TRACING) {
9894  		if (!bpf_prog_has_trampoline(env->prog)) {
9895  			verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9896  				func_id_name(func_id), func_id);
9897  			return -ENOTSUPP;
9898  		}
9899  		return 0;
9900  	} else if (type == BPF_PROG_TYPE_KPROBE) {
9901  		return 0;
9902  	}
9903  
9904  	verbose(env, "func %s#%d not supported for program type %d\n",
9905  		func_id_name(func_id), func_id, type);
9906  	return -ENOTSUPP;
9907  }
9908  
cur_aux(struct bpf_verifier_env * env)9909  static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9910  {
9911  	return &env->insn_aux_data[env->insn_idx];
9912  }
9913  
loop_flag_is_zero(struct bpf_verifier_env * env)9914  static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9915  {
9916  	struct bpf_reg_state *regs = cur_regs(env);
9917  	struct bpf_reg_state *reg = &regs[BPF_REG_4];
9918  	bool reg_is_null = register_is_null(reg);
9919  
9920  	if (reg_is_null)
9921  		mark_chain_precision(env, BPF_REG_4);
9922  
9923  	return reg_is_null;
9924  }
9925  
update_loop_inline_state(struct bpf_verifier_env * env,u32 subprogno)9926  static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9927  {
9928  	struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9929  
9930  	if (!state->initialized) {
9931  		state->initialized = 1;
9932  		state->fit_for_inline = loop_flag_is_zero(env);
9933  		state->callback_subprogno = subprogno;
9934  		return;
9935  	}
9936  
9937  	if (!state->fit_for_inline)
9938  		return;
9939  
9940  	state->fit_for_inline = (loop_flag_is_zero(env) &&
9941  				 state->callback_subprogno == subprogno);
9942  }
9943  
check_helper_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)9944  static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9945  			     int *insn_idx_p)
9946  {
9947  	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9948  	const struct bpf_func_proto *fn = NULL;
9949  	enum bpf_return_type ret_type;
9950  	enum bpf_type_flag ret_flag;
9951  	struct bpf_reg_state *regs;
9952  	struct bpf_call_arg_meta meta;
9953  	int insn_idx = *insn_idx_p;
9954  	bool changes_data;
9955  	int i, err, func_id;
9956  
9957  	/* find function prototype */
9958  	func_id = insn->imm;
9959  	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9960  		verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9961  			func_id);
9962  		return -EINVAL;
9963  	}
9964  
9965  	if (env->ops->get_func_proto)
9966  		fn = env->ops->get_func_proto(func_id, env->prog);
9967  	if (!fn) {
9968  		verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9969  			func_id);
9970  		return -EINVAL;
9971  	}
9972  
9973  	/* eBPF programs must be GPL compatible to use GPL-ed functions */
9974  	if (!env->prog->gpl_compatible && fn->gpl_only) {
9975  		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9976  		return -EINVAL;
9977  	}
9978  
9979  	if (fn->allowed && !fn->allowed(env->prog)) {
9980  		verbose(env, "helper call is not allowed in probe\n");
9981  		return -EINVAL;
9982  	}
9983  
9984  	if (!env->prog->aux->sleepable && fn->might_sleep) {
9985  		verbose(env, "helper call might sleep in a non-sleepable prog\n");
9986  		return -EINVAL;
9987  	}
9988  
9989  	/* With LD_ABS/IND some JITs save/restore skb from r1. */
9990  	changes_data = bpf_helper_changes_pkt_data(fn->func);
9991  	if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9992  		verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9993  			func_id_name(func_id), func_id);
9994  		return -EINVAL;
9995  	}
9996  
9997  	memset(&meta, 0, sizeof(meta));
9998  	meta.pkt_access = fn->pkt_access;
9999  
10000  	err = check_func_proto(fn, func_id);
10001  	if (err) {
10002  		verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10003  			func_id_name(func_id), func_id);
10004  		return err;
10005  	}
10006  
10007  	if (env->cur_state->active_rcu_lock) {
10008  		if (fn->might_sleep) {
10009  			verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10010  				func_id_name(func_id), func_id);
10011  			return -EINVAL;
10012  		}
10013  
10014  		if (env->prog->aux->sleepable && is_storage_get_function(func_id))
10015  			env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10016  	}
10017  
10018  	meta.func_id = func_id;
10019  	/* check args */
10020  	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10021  		err = check_func_arg(env, i, &meta, fn, insn_idx);
10022  		if (err)
10023  			return err;
10024  	}
10025  
10026  	err = record_func_map(env, &meta, func_id, insn_idx);
10027  	if (err)
10028  		return err;
10029  
10030  	err = record_func_key(env, &meta, func_id, insn_idx);
10031  	if (err)
10032  		return err;
10033  
10034  	/* Mark slots with STACK_MISC in case of raw mode, stack offset
10035  	 * is inferred from register state.
10036  	 */
10037  	for (i = 0; i < meta.access_size; i++) {
10038  		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10039  				       BPF_WRITE, -1, false, false);
10040  		if (err)
10041  			return err;
10042  	}
10043  
10044  	regs = cur_regs(env);
10045  
10046  	if (meta.release_regno) {
10047  		err = -EINVAL;
10048  		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10049  		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10050  		 * is safe to do directly.
10051  		 */
10052  		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10053  			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10054  				verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10055  				return -EFAULT;
10056  			}
10057  			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10058  		} else if (meta.ref_obj_id) {
10059  			err = release_reference(env, meta.ref_obj_id);
10060  		} else if (register_is_null(&regs[meta.release_regno])) {
10061  			/* meta.ref_obj_id can only be 0 if register that is meant to be
10062  			 * released is NULL, which must be > R0.
10063  			 */
10064  			err = 0;
10065  		}
10066  		if (err) {
10067  			verbose(env, "func %s#%d reference has not been acquired before\n",
10068  				func_id_name(func_id), func_id);
10069  			return err;
10070  		}
10071  	}
10072  
10073  	switch (func_id) {
10074  	case BPF_FUNC_tail_call:
10075  		err = check_reference_leak(env);
10076  		if (err) {
10077  			verbose(env, "tail_call would lead to reference leak\n");
10078  			return err;
10079  		}
10080  		break;
10081  	case BPF_FUNC_get_local_storage:
10082  		/* check that flags argument in get_local_storage(map, flags) is 0,
10083  		 * this is required because get_local_storage() can't return an error.
10084  		 */
10085  		if (!register_is_null(&regs[BPF_REG_2])) {
10086  			verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10087  			return -EINVAL;
10088  		}
10089  		break;
10090  	case BPF_FUNC_for_each_map_elem:
10091  		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10092  					 set_map_elem_callback_state);
10093  		break;
10094  	case BPF_FUNC_timer_set_callback:
10095  		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10096  					 set_timer_callback_state);
10097  		break;
10098  	case BPF_FUNC_find_vma:
10099  		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10100  					 set_find_vma_callback_state);
10101  		break;
10102  	case BPF_FUNC_snprintf:
10103  		err = check_bpf_snprintf_call(env, regs);
10104  		break;
10105  	case BPF_FUNC_loop:
10106  		update_loop_inline_state(env, meta.subprogno);
10107  		/* Verifier relies on R1 value to determine if bpf_loop() iteration
10108  		 * is finished, thus mark it precise.
10109  		 */
10110  		err = mark_chain_precision(env, BPF_REG_1);
10111  		if (err)
10112  			return err;
10113  		if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10114  			err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10115  						 set_loop_callback_state);
10116  		} else {
10117  			cur_func(env)->callback_depth = 0;
10118  			if (env->log.level & BPF_LOG_LEVEL2)
10119  				verbose(env, "frame%d bpf_loop iteration limit reached\n",
10120  					env->cur_state->curframe);
10121  		}
10122  		break;
10123  	case BPF_FUNC_dynptr_from_mem:
10124  		if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10125  			verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10126  				reg_type_str(env, regs[BPF_REG_1].type));
10127  			return -EACCES;
10128  		}
10129  		break;
10130  	case BPF_FUNC_set_retval:
10131  		if (prog_type == BPF_PROG_TYPE_LSM &&
10132  		    env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10133  			if (!env->prog->aux->attach_func_proto->type) {
10134  				/* Make sure programs that attach to void
10135  				 * hooks don't try to modify return value.
10136  				 */
10137  				verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10138  				return -EINVAL;
10139  			}
10140  		}
10141  		break;
10142  	case BPF_FUNC_dynptr_data:
10143  	{
10144  		struct bpf_reg_state *reg;
10145  		int id, ref_obj_id;
10146  
10147  		reg = get_dynptr_arg_reg(env, fn, regs);
10148  		if (!reg)
10149  			return -EFAULT;
10150  
10151  
10152  		if (meta.dynptr_id) {
10153  			verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10154  			return -EFAULT;
10155  		}
10156  		if (meta.ref_obj_id) {
10157  			verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10158  			return -EFAULT;
10159  		}
10160  
10161  		id = dynptr_id(env, reg);
10162  		if (id < 0) {
10163  			verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10164  			return id;
10165  		}
10166  
10167  		ref_obj_id = dynptr_ref_obj_id(env, reg);
10168  		if (ref_obj_id < 0) {
10169  			verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10170  			return ref_obj_id;
10171  		}
10172  
10173  		meta.dynptr_id = id;
10174  		meta.ref_obj_id = ref_obj_id;
10175  
10176  		break;
10177  	}
10178  	case BPF_FUNC_dynptr_write:
10179  	{
10180  		enum bpf_dynptr_type dynptr_type;
10181  		struct bpf_reg_state *reg;
10182  
10183  		reg = get_dynptr_arg_reg(env, fn, regs);
10184  		if (!reg)
10185  			return -EFAULT;
10186  
10187  		dynptr_type = dynptr_get_type(env, reg);
10188  		if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10189  			return -EFAULT;
10190  
10191  		if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10192  			/* this will trigger clear_all_pkt_pointers(), which will
10193  			 * invalidate all dynptr slices associated with the skb
10194  			 */
10195  			changes_data = true;
10196  
10197  		break;
10198  	}
10199  	case BPF_FUNC_user_ringbuf_drain:
10200  		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10201  					 set_user_ringbuf_callback_state);
10202  		break;
10203  	}
10204  
10205  	if (err)
10206  		return err;
10207  
10208  	/* reset caller saved regs */
10209  	for (i = 0; i < CALLER_SAVED_REGS; i++) {
10210  		mark_reg_not_init(env, regs, caller_saved[i]);
10211  		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10212  	}
10213  
10214  	/* helper call returns 64-bit value. */
10215  	regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10216  
10217  	/* update return register (already marked as written above) */
10218  	ret_type = fn->ret_type;
10219  	ret_flag = type_flag(ret_type);
10220  
10221  	switch (base_type(ret_type)) {
10222  	case RET_INTEGER:
10223  		/* sets type to SCALAR_VALUE */
10224  		mark_reg_unknown(env, regs, BPF_REG_0);
10225  		break;
10226  	case RET_VOID:
10227  		regs[BPF_REG_0].type = NOT_INIT;
10228  		break;
10229  	case RET_PTR_TO_MAP_VALUE:
10230  		/* There is no offset yet applied, variable or fixed */
10231  		mark_reg_known_zero(env, regs, BPF_REG_0);
10232  		/* remember map_ptr, so that check_map_access()
10233  		 * can check 'value_size' boundary of memory access
10234  		 * to map element returned from bpf_map_lookup_elem()
10235  		 */
10236  		if (meta.map_ptr == NULL) {
10237  			verbose(env,
10238  				"kernel subsystem misconfigured verifier\n");
10239  			return -EINVAL;
10240  		}
10241  		regs[BPF_REG_0].map_ptr = meta.map_ptr;
10242  		regs[BPF_REG_0].map_uid = meta.map_uid;
10243  		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10244  		if (!type_may_be_null(ret_type) &&
10245  		    btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10246  			regs[BPF_REG_0].id = ++env->id_gen;
10247  		}
10248  		break;
10249  	case RET_PTR_TO_SOCKET:
10250  		mark_reg_known_zero(env, regs, BPF_REG_0);
10251  		regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10252  		break;
10253  	case RET_PTR_TO_SOCK_COMMON:
10254  		mark_reg_known_zero(env, regs, BPF_REG_0);
10255  		regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10256  		break;
10257  	case RET_PTR_TO_TCP_SOCK:
10258  		mark_reg_known_zero(env, regs, BPF_REG_0);
10259  		regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10260  		break;
10261  	case RET_PTR_TO_MEM:
10262  		mark_reg_known_zero(env, regs, BPF_REG_0);
10263  		regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10264  		regs[BPF_REG_0].mem_size = meta.mem_size;
10265  		break;
10266  	case RET_PTR_TO_MEM_OR_BTF_ID:
10267  	{
10268  		const struct btf_type *t;
10269  
10270  		mark_reg_known_zero(env, regs, BPF_REG_0);
10271  		t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10272  		if (!btf_type_is_struct(t)) {
10273  			u32 tsize;
10274  			const struct btf_type *ret;
10275  			const char *tname;
10276  
10277  			/* resolve the type size of ksym. */
10278  			ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10279  			if (IS_ERR(ret)) {
10280  				tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10281  				verbose(env, "unable to resolve the size of type '%s': %ld\n",
10282  					tname, PTR_ERR(ret));
10283  				return -EINVAL;
10284  			}
10285  			regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10286  			regs[BPF_REG_0].mem_size = tsize;
10287  		} else {
10288  			/* MEM_RDONLY may be carried from ret_flag, but it
10289  			 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10290  			 * it will confuse the check of PTR_TO_BTF_ID in
10291  			 * check_mem_access().
10292  			 */
10293  			ret_flag &= ~MEM_RDONLY;
10294  
10295  			regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10296  			regs[BPF_REG_0].btf = meta.ret_btf;
10297  			regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10298  		}
10299  		break;
10300  	}
10301  	case RET_PTR_TO_BTF_ID:
10302  	{
10303  		struct btf *ret_btf;
10304  		int ret_btf_id;
10305  
10306  		mark_reg_known_zero(env, regs, BPF_REG_0);
10307  		regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10308  		if (func_id == BPF_FUNC_kptr_xchg) {
10309  			ret_btf = meta.kptr_field->kptr.btf;
10310  			ret_btf_id = meta.kptr_field->kptr.btf_id;
10311  			if (!btf_is_kernel(ret_btf))
10312  				regs[BPF_REG_0].type |= MEM_ALLOC;
10313  		} else {
10314  			if (fn->ret_btf_id == BPF_PTR_POISON) {
10315  				verbose(env, "verifier internal error:");
10316  				verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10317  					func_id_name(func_id));
10318  				return -EINVAL;
10319  			}
10320  			ret_btf = btf_vmlinux;
10321  			ret_btf_id = *fn->ret_btf_id;
10322  		}
10323  		if (ret_btf_id == 0) {
10324  			verbose(env, "invalid return type %u of func %s#%d\n",
10325  				base_type(ret_type), func_id_name(func_id),
10326  				func_id);
10327  			return -EINVAL;
10328  		}
10329  		regs[BPF_REG_0].btf = ret_btf;
10330  		regs[BPF_REG_0].btf_id = ret_btf_id;
10331  		break;
10332  	}
10333  	default:
10334  		verbose(env, "unknown return type %u of func %s#%d\n",
10335  			base_type(ret_type), func_id_name(func_id), func_id);
10336  		return -EINVAL;
10337  	}
10338  
10339  	if (type_may_be_null(regs[BPF_REG_0].type))
10340  		regs[BPF_REG_0].id = ++env->id_gen;
10341  
10342  	if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10343  		verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10344  			func_id_name(func_id), func_id);
10345  		return -EFAULT;
10346  	}
10347  
10348  	if (is_dynptr_ref_function(func_id))
10349  		regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10350  
10351  	if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10352  		/* For release_reference() */
10353  		regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10354  	} else if (is_acquire_function(func_id, meta.map_ptr)) {
10355  		int id = acquire_reference_state(env, insn_idx);
10356  
10357  		if (id < 0)
10358  			return id;
10359  		/* For mark_ptr_or_null_reg() */
10360  		regs[BPF_REG_0].id = id;
10361  		/* For release_reference() */
10362  		regs[BPF_REG_0].ref_obj_id = id;
10363  	}
10364  
10365  	do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
10366  
10367  	err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10368  	if (err)
10369  		return err;
10370  
10371  	if ((func_id == BPF_FUNC_get_stack ||
10372  	     func_id == BPF_FUNC_get_task_stack) &&
10373  	    !env->prog->has_callchain_buf) {
10374  		const char *err_str;
10375  
10376  #ifdef CONFIG_PERF_EVENTS
10377  		err = get_callchain_buffers(sysctl_perf_event_max_stack);
10378  		err_str = "cannot get callchain buffer for func %s#%d\n";
10379  #else
10380  		err = -ENOTSUPP;
10381  		err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10382  #endif
10383  		if (err) {
10384  			verbose(env, err_str, func_id_name(func_id), func_id);
10385  			return err;
10386  		}
10387  
10388  		env->prog->has_callchain_buf = true;
10389  	}
10390  
10391  	if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10392  		env->prog->call_get_stack = true;
10393  
10394  	if (func_id == BPF_FUNC_get_func_ip) {
10395  		if (check_get_func_ip(env))
10396  			return -ENOTSUPP;
10397  		env->prog->call_get_func_ip = true;
10398  	}
10399  
10400  	if (changes_data)
10401  		clear_all_pkt_pointers(env);
10402  	return 0;
10403  }
10404  
10405  /* mark_btf_func_reg_size() is used when the reg size is determined by
10406   * the BTF func_proto's return value size and argument.
10407   */
mark_btf_func_reg_size(struct bpf_verifier_env * env,u32 regno,size_t reg_size)10408  static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10409  				   size_t reg_size)
10410  {
10411  	struct bpf_reg_state *reg = &cur_regs(env)[regno];
10412  
10413  	if (regno == BPF_REG_0) {
10414  		/* Function return value */
10415  		reg->live |= REG_LIVE_WRITTEN;
10416  		reg->subreg_def = reg_size == sizeof(u64) ?
10417  			DEF_NOT_SUBREG : env->insn_idx + 1;
10418  	} else {
10419  		/* Function argument */
10420  		if (reg_size == sizeof(u64)) {
10421  			mark_insn_zext(env, reg);
10422  			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10423  		} else {
10424  			mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10425  		}
10426  	}
10427  }
10428  
is_kfunc_acquire(struct bpf_kfunc_call_arg_meta * meta)10429  static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10430  {
10431  	return meta->kfunc_flags & KF_ACQUIRE;
10432  }
10433  
is_kfunc_release(struct bpf_kfunc_call_arg_meta * meta)10434  static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10435  {
10436  	return meta->kfunc_flags & KF_RELEASE;
10437  }
10438  
is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta * meta)10439  static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10440  {
10441  	return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10442  }
10443  
is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta * meta)10444  static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10445  {
10446  	return meta->kfunc_flags & KF_SLEEPABLE;
10447  }
10448  
is_kfunc_destructive(struct bpf_kfunc_call_arg_meta * meta)10449  static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10450  {
10451  	return meta->kfunc_flags & KF_DESTRUCTIVE;
10452  }
10453  
is_kfunc_rcu(struct bpf_kfunc_call_arg_meta * meta)10454  static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10455  {
10456  	return meta->kfunc_flags & KF_RCU;
10457  }
10458  
__kfunc_param_match_suffix(const struct btf * btf,const struct btf_param * arg,const char * suffix)10459  static bool __kfunc_param_match_suffix(const struct btf *btf,
10460  				       const struct btf_param *arg,
10461  				       const char *suffix)
10462  {
10463  	int suffix_len = strlen(suffix), len;
10464  	const char *param_name;
10465  
10466  	/* In the future, this can be ported to use BTF tagging */
10467  	param_name = btf_name_by_offset(btf, arg->name_off);
10468  	if (str_is_empty(param_name))
10469  		return false;
10470  	len = strlen(param_name);
10471  	if (len < suffix_len)
10472  		return false;
10473  	param_name += len - suffix_len;
10474  	return !strncmp(param_name, suffix, suffix_len);
10475  }
10476  
is_kfunc_arg_mem_size(const struct btf * btf,const struct btf_param * arg,const struct bpf_reg_state * reg)10477  static bool is_kfunc_arg_mem_size(const struct btf *btf,
10478  				  const struct btf_param *arg,
10479  				  const struct bpf_reg_state *reg)
10480  {
10481  	const struct btf_type *t;
10482  
10483  	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10484  	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10485  		return false;
10486  
10487  	return __kfunc_param_match_suffix(btf, arg, "__sz");
10488  }
10489  
is_kfunc_arg_const_mem_size(const struct btf * btf,const struct btf_param * arg,const struct bpf_reg_state * reg)10490  static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10491  					const struct btf_param *arg,
10492  					const struct bpf_reg_state *reg)
10493  {
10494  	const struct btf_type *t;
10495  
10496  	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10497  	if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10498  		return false;
10499  
10500  	return __kfunc_param_match_suffix(btf, arg, "__szk");
10501  }
10502  
is_kfunc_arg_optional(const struct btf * btf,const struct btf_param * arg)10503  static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10504  {
10505  	return __kfunc_param_match_suffix(btf, arg, "__opt");
10506  }
10507  
is_kfunc_arg_constant(const struct btf * btf,const struct btf_param * arg)10508  static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10509  {
10510  	return __kfunc_param_match_suffix(btf, arg, "__k");
10511  }
10512  
is_kfunc_arg_ignore(const struct btf * btf,const struct btf_param * arg)10513  static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10514  {
10515  	return __kfunc_param_match_suffix(btf, arg, "__ign");
10516  }
10517  
is_kfunc_arg_alloc_obj(const struct btf * btf,const struct btf_param * arg)10518  static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10519  {
10520  	return __kfunc_param_match_suffix(btf, arg, "__alloc");
10521  }
10522  
is_kfunc_arg_uninit(const struct btf * btf,const struct btf_param * arg)10523  static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10524  {
10525  	return __kfunc_param_match_suffix(btf, arg, "__uninit");
10526  }
10527  
is_kfunc_arg_refcounted_kptr(const struct btf * btf,const struct btf_param * arg)10528  static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10529  {
10530  	return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10531  }
10532  
is_kfunc_arg_scalar_with_name(const struct btf * btf,const struct btf_param * arg,const char * name)10533  static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10534  					  const struct btf_param *arg,
10535  					  const char *name)
10536  {
10537  	int len, target_len = strlen(name);
10538  	const char *param_name;
10539  
10540  	param_name = btf_name_by_offset(btf, arg->name_off);
10541  	if (str_is_empty(param_name))
10542  		return false;
10543  	len = strlen(param_name);
10544  	if (len != target_len)
10545  		return false;
10546  	if (strcmp(param_name, name))
10547  		return false;
10548  
10549  	return true;
10550  }
10551  
10552  enum {
10553  	KF_ARG_DYNPTR_ID,
10554  	KF_ARG_LIST_HEAD_ID,
10555  	KF_ARG_LIST_NODE_ID,
10556  	KF_ARG_RB_ROOT_ID,
10557  	KF_ARG_RB_NODE_ID,
10558  };
10559  
10560  BTF_ID_LIST(kf_arg_btf_ids)
BTF_ID(struct,bpf_dynptr_kern)10561  BTF_ID(struct, bpf_dynptr_kern)
10562  BTF_ID(struct, bpf_list_head)
10563  BTF_ID(struct, bpf_list_node)
10564  BTF_ID(struct, bpf_rb_root)
10565  BTF_ID(struct, bpf_rb_node)
10566  
10567  static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10568  				    const struct btf_param *arg, int type)
10569  {
10570  	const struct btf_type *t;
10571  	u32 res_id;
10572  
10573  	t = btf_type_skip_modifiers(btf, arg->type, NULL);
10574  	if (!t)
10575  		return false;
10576  	if (!btf_type_is_ptr(t))
10577  		return false;
10578  	t = btf_type_skip_modifiers(btf, t->type, &res_id);
10579  	if (!t)
10580  		return false;
10581  	return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10582  }
10583  
is_kfunc_arg_dynptr(const struct btf * btf,const struct btf_param * arg)10584  static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10585  {
10586  	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10587  }
10588  
is_kfunc_arg_list_head(const struct btf * btf,const struct btf_param * arg)10589  static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10590  {
10591  	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10592  }
10593  
is_kfunc_arg_list_node(const struct btf * btf,const struct btf_param * arg)10594  static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10595  {
10596  	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10597  }
10598  
is_kfunc_arg_rbtree_root(const struct btf * btf,const struct btf_param * arg)10599  static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10600  {
10601  	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10602  }
10603  
is_kfunc_arg_rbtree_node(const struct btf * btf,const struct btf_param * arg)10604  static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10605  {
10606  	return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10607  }
10608  
is_kfunc_arg_callback(struct bpf_verifier_env * env,const struct btf * btf,const struct btf_param * arg)10609  static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10610  				  const struct btf_param *arg)
10611  {
10612  	const struct btf_type *t;
10613  
10614  	t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10615  	if (!t)
10616  		return false;
10617  
10618  	return true;
10619  }
10620  
10621  /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
__btf_type_is_scalar_struct(struct bpf_verifier_env * env,const struct btf * btf,const struct btf_type * t,int rec)10622  static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10623  					const struct btf *btf,
10624  					const struct btf_type *t, int rec)
10625  {
10626  	const struct btf_type *member_type;
10627  	const struct btf_member *member;
10628  	u32 i;
10629  
10630  	if (!btf_type_is_struct(t))
10631  		return false;
10632  
10633  	for_each_member(i, t, member) {
10634  		const struct btf_array *array;
10635  
10636  		member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10637  		if (btf_type_is_struct(member_type)) {
10638  			if (rec >= 3) {
10639  				verbose(env, "max struct nesting depth exceeded\n");
10640  				return false;
10641  			}
10642  			if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10643  				return false;
10644  			continue;
10645  		}
10646  		if (btf_type_is_array(member_type)) {
10647  			array = btf_array(member_type);
10648  			if (!array->nelems)
10649  				return false;
10650  			member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10651  			if (!btf_type_is_scalar(member_type))
10652  				return false;
10653  			continue;
10654  		}
10655  		if (!btf_type_is_scalar(member_type))
10656  			return false;
10657  	}
10658  	return true;
10659  }
10660  
10661  enum kfunc_ptr_arg_type {
10662  	KF_ARG_PTR_TO_CTX,
10663  	KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10664  	KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10665  	KF_ARG_PTR_TO_DYNPTR,
10666  	KF_ARG_PTR_TO_ITER,
10667  	KF_ARG_PTR_TO_LIST_HEAD,
10668  	KF_ARG_PTR_TO_LIST_NODE,
10669  	KF_ARG_PTR_TO_BTF_ID,	       /* Also covers reg2btf_ids conversions */
10670  	KF_ARG_PTR_TO_MEM,
10671  	KF_ARG_PTR_TO_MEM_SIZE,	       /* Size derived from next argument, skip it */
10672  	KF_ARG_PTR_TO_CALLBACK,
10673  	KF_ARG_PTR_TO_RB_ROOT,
10674  	KF_ARG_PTR_TO_RB_NODE,
10675  };
10676  
10677  enum special_kfunc_type {
10678  	KF_bpf_obj_new_impl,
10679  	KF_bpf_obj_drop_impl,
10680  	KF_bpf_refcount_acquire_impl,
10681  	KF_bpf_list_push_front_impl,
10682  	KF_bpf_list_push_back_impl,
10683  	KF_bpf_list_pop_front,
10684  	KF_bpf_list_pop_back,
10685  	KF_bpf_cast_to_kern_ctx,
10686  	KF_bpf_rdonly_cast,
10687  	KF_bpf_rcu_read_lock,
10688  	KF_bpf_rcu_read_unlock,
10689  	KF_bpf_rbtree_remove,
10690  	KF_bpf_rbtree_add_impl,
10691  	KF_bpf_rbtree_first,
10692  	KF_bpf_dynptr_from_skb,
10693  	KF_bpf_dynptr_from_xdp,
10694  	KF_bpf_dynptr_slice,
10695  	KF_bpf_dynptr_slice_rdwr,
10696  	KF_bpf_dynptr_clone,
10697  };
10698  
10699  BTF_SET_START(special_kfunc_set)
BTF_ID(func,bpf_obj_new_impl)10700  BTF_ID(func, bpf_obj_new_impl)
10701  BTF_ID(func, bpf_obj_drop_impl)
10702  BTF_ID(func, bpf_refcount_acquire_impl)
10703  BTF_ID(func, bpf_list_push_front_impl)
10704  BTF_ID(func, bpf_list_push_back_impl)
10705  BTF_ID(func, bpf_list_pop_front)
10706  BTF_ID(func, bpf_list_pop_back)
10707  BTF_ID(func, bpf_cast_to_kern_ctx)
10708  BTF_ID(func, bpf_rdonly_cast)
10709  BTF_ID(func, bpf_rbtree_remove)
10710  BTF_ID(func, bpf_rbtree_add_impl)
10711  BTF_ID(func, bpf_rbtree_first)
10712  BTF_ID(func, bpf_dynptr_from_skb)
10713  BTF_ID(func, bpf_dynptr_from_xdp)
10714  BTF_ID(func, bpf_dynptr_slice)
10715  BTF_ID(func, bpf_dynptr_slice_rdwr)
10716  BTF_ID(func, bpf_dynptr_clone)
10717  BTF_SET_END(special_kfunc_set)
10718  
10719  BTF_ID_LIST(special_kfunc_list)
10720  BTF_ID(func, bpf_obj_new_impl)
10721  BTF_ID(func, bpf_obj_drop_impl)
10722  BTF_ID(func, bpf_refcount_acquire_impl)
10723  BTF_ID(func, bpf_list_push_front_impl)
10724  BTF_ID(func, bpf_list_push_back_impl)
10725  BTF_ID(func, bpf_list_pop_front)
10726  BTF_ID(func, bpf_list_pop_back)
10727  BTF_ID(func, bpf_cast_to_kern_ctx)
10728  BTF_ID(func, bpf_rdonly_cast)
10729  BTF_ID(func, bpf_rcu_read_lock)
10730  BTF_ID(func, bpf_rcu_read_unlock)
10731  BTF_ID(func, bpf_rbtree_remove)
10732  BTF_ID(func, bpf_rbtree_add_impl)
10733  BTF_ID(func, bpf_rbtree_first)
10734  BTF_ID(func, bpf_dynptr_from_skb)
10735  BTF_ID(func, bpf_dynptr_from_xdp)
10736  BTF_ID(func, bpf_dynptr_slice)
10737  BTF_ID(func, bpf_dynptr_slice_rdwr)
10738  BTF_ID(func, bpf_dynptr_clone)
10739  
10740  static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10741  {
10742  	if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10743  	    meta->arg_owning_ref) {
10744  		return false;
10745  	}
10746  
10747  	return meta->kfunc_flags & KF_RET_NULL;
10748  }
10749  
is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta * meta)10750  static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10751  {
10752  	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10753  }
10754  
is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta * meta)10755  static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10756  {
10757  	return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10758  }
10759  
10760  static enum kfunc_ptr_arg_type
get_kfunc_ptr_arg_type(struct bpf_verifier_env * env,struct bpf_kfunc_call_arg_meta * meta,const struct btf_type * t,const struct btf_type * ref_t,const char * ref_tname,const struct btf_param * args,int argno,int nargs)10761  get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10762  		       struct bpf_kfunc_call_arg_meta *meta,
10763  		       const struct btf_type *t, const struct btf_type *ref_t,
10764  		       const char *ref_tname, const struct btf_param *args,
10765  		       int argno, int nargs)
10766  {
10767  	u32 regno = argno + 1;
10768  	struct bpf_reg_state *regs = cur_regs(env);
10769  	struct bpf_reg_state *reg = &regs[regno];
10770  	bool arg_mem_size = false;
10771  
10772  	if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10773  		return KF_ARG_PTR_TO_CTX;
10774  
10775  	/* In this function, we verify the kfunc's BTF as per the argument type,
10776  	 * leaving the rest of the verification with respect to the register
10777  	 * type to our caller. When a set of conditions hold in the BTF type of
10778  	 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10779  	 */
10780  	if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10781  		return KF_ARG_PTR_TO_CTX;
10782  
10783  	if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10784  		return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10785  
10786  	if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10787  		return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10788  
10789  	if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10790  		return KF_ARG_PTR_TO_DYNPTR;
10791  
10792  	if (is_kfunc_arg_iter(meta, argno))
10793  		return KF_ARG_PTR_TO_ITER;
10794  
10795  	if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10796  		return KF_ARG_PTR_TO_LIST_HEAD;
10797  
10798  	if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10799  		return KF_ARG_PTR_TO_LIST_NODE;
10800  
10801  	if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10802  		return KF_ARG_PTR_TO_RB_ROOT;
10803  
10804  	if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10805  		return KF_ARG_PTR_TO_RB_NODE;
10806  
10807  	if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10808  		if (!btf_type_is_struct(ref_t)) {
10809  			verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10810  				meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10811  			return -EINVAL;
10812  		}
10813  		return KF_ARG_PTR_TO_BTF_ID;
10814  	}
10815  
10816  	if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10817  		return KF_ARG_PTR_TO_CALLBACK;
10818  
10819  
10820  	if (argno + 1 < nargs &&
10821  	    (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10822  	     is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10823  		arg_mem_size = true;
10824  
10825  	/* This is the catch all argument type of register types supported by
10826  	 * check_helper_mem_access. However, we only allow when argument type is
10827  	 * pointer to scalar, or struct composed (recursively) of scalars. When
10828  	 * arg_mem_size is true, the pointer can be void *.
10829  	 */
10830  	if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10831  	    (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10832  		verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10833  			argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10834  		return -EINVAL;
10835  	}
10836  	return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10837  }
10838  
process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const struct btf_type * ref_t,const char * ref_tname,u32 ref_id,struct bpf_kfunc_call_arg_meta * meta,int argno)10839  static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10840  					struct bpf_reg_state *reg,
10841  					const struct btf_type *ref_t,
10842  					const char *ref_tname, u32 ref_id,
10843  					struct bpf_kfunc_call_arg_meta *meta,
10844  					int argno)
10845  {
10846  	const struct btf_type *reg_ref_t;
10847  	bool strict_type_match = false;
10848  	const struct btf *reg_btf;
10849  	const char *reg_ref_tname;
10850  	u32 reg_ref_id;
10851  
10852  	if (base_type(reg->type) == PTR_TO_BTF_ID) {
10853  		reg_btf = reg->btf;
10854  		reg_ref_id = reg->btf_id;
10855  	} else {
10856  		reg_btf = btf_vmlinux;
10857  		reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10858  	}
10859  
10860  	/* Enforce strict type matching for calls to kfuncs that are acquiring
10861  	 * or releasing a reference, or are no-cast aliases. We do _not_
10862  	 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10863  	 * as we want to enable BPF programs to pass types that are bitwise
10864  	 * equivalent without forcing them to explicitly cast with something
10865  	 * like bpf_cast_to_kern_ctx().
10866  	 *
10867  	 * For example, say we had a type like the following:
10868  	 *
10869  	 * struct bpf_cpumask {
10870  	 *	cpumask_t cpumask;
10871  	 *	refcount_t usage;
10872  	 * };
10873  	 *
10874  	 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10875  	 * to a struct cpumask, so it would be safe to pass a struct
10876  	 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10877  	 *
10878  	 * The philosophy here is similar to how we allow scalars of different
10879  	 * types to be passed to kfuncs as long as the size is the same. The
10880  	 * only difference here is that we're simply allowing
10881  	 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10882  	 * resolve types.
10883  	 */
10884  	if (is_kfunc_acquire(meta) ||
10885  	    (is_kfunc_release(meta) && reg->ref_obj_id) ||
10886  	    btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10887  		strict_type_match = true;
10888  
10889  	WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10890  
10891  	reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10892  	reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10893  	if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10894  		verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10895  			meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10896  			btf_type_str(reg_ref_t), reg_ref_tname);
10897  		return -EINVAL;
10898  	}
10899  	return 0;
10900  }
10901  
ref_set_non_owning(struct bpf_verifier_env * env,struct bpf_reg_state * reg)10902  static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10903  {
10904  	struct bpf_verifier_state *state = env->cur_state;
10905  	struct btf_record *rec = reg_btf_record(reg);
10906  
10907  	if (!state->active_lock.ptr) {
10908  		verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10909  		return -EFAULT;
10910  	}
10911  
10912  	if (type_flag(reg->type) & NON_OWN_REF) {
10913  		verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10914  		return -EFAULT;
10915  	}
10916  
10917  	reg->type |= NON_OWN_REF;
10918  	if (rec->refcount_off >= 0)
10919  		reg->type |= MEM_RCU;
10920  
10921  	return 0;
10922  }
10923  
ref_convert_owning_non_owning(struct bpf_verifier_env * env,u32 ref_obj_id)10924  static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10925  {
10926  	struct bpf_func_state *state, *unused;
10927  	struct bpf_reg_state *reg;
10928  	int i;
10929  
10930  	state = cur_func(env);
10931  
10932  	if (!ref_obj_id) {
10933  		verbose(env, "verifier internal error: ref_obj_id is zero for "
10934  			     "owning -> non-owning conversion\n");
10935  		return -EFAULT;
10936  	}
10937  
10938  	for (i = 0; i < state->acquired_refs; i++) {
10939  		if (state->refs[i].id != ref_obj_id)
10940  			continue;
10941  
10942  		/* Clear ref_obj_id here so release_reference doesn't clobber
10943  		 * the whole reg
10944  		 */
10945  		bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10946  			if (reg->ref_obj_id == ref_obj_id) {
10947  				reg->ref_obj_id = 0;
10948  				ref_set_non_owning(env, reg);
10949  			}
10950  		}));
10951  		return 0;
10952  	}
10953  
10954  	verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10955  	return -EFAULT;
10956  }
10957  
10958  /* Implementation details:
10959   *
10960   * Each register points to some region of memory, which we define as an
10961   * allocation. Each allocation may embed a bpf_spin_lock which protects any
10962   * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10963   * allocation. The lock and the data it protects are colocated in the same
10964   * memory region.
10965   *
10966   * Hence, everytime a register holds a pointer value pointing to such
10967   * allocation, the verifier preserves a unique reg->id for it.
10968   *
10969   * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10970   * bpf_spin_lock is called.
10971   *
10972   * To enable this, lock state in the verifier captures two values:
10973   *	active_lock.ptr = Register's type specific pointer
10974   *	active_lock.id  = A unique ID for each register pointer value
10975   *
10976   * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10977   * supported register types.
10978   *
10979   * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10980   * allocated objects is the reg->btf pointer.
10981   *
10982   * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10983   * can establish the provenance of the map value statically for each distinct
10984   * lookup into such maps. They always contain a single map value hence unique
10985   * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10986   *
10987   * So, in case of global variables, they use array maps with max_entries = 1,
10988   * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10989   * into the same map value as max_entries is 1, as described above).
10990   *
10991   * In case of inner map lookups, the inner map pointer has same map_ptr as the
10992   * outer map pointer (in verifier context), but each lookup into an inner map
10993   * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10994   * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10995   * will get different reg->id assigned to each lookup, hence different
10996   * active_lock.id.
10997   *
10998   * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10999   * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11000   * returned from bpf_obj_new. Each allocation receives a new reg->id.
11001   */
check_reg_allocation_locked(struct bpf_verifier_env * env,struct bpf_reg_state * reg)11002  static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11003  {
11004  	void *ptr;
11005  	u32 id;
11006  
11007  	switch ((int)reg->type) {
11008  	case PTR_TO_MAP_VALUE:
11009  		ptr = reg->map_ptr;
11010  		break;
11011  	case PTR_TO_BTF_ID | MEM_ALLOC:
11012  		ptr = reg->btf;
11013  		break;
11014  	default:
11015  		verbose(env, "verifier internal error: unknown reg type for lock check\n");
11016  		return -EFAULT;
11017  	}
11018  	id = reg->id;
11019  
11020  	if (!env->cur_state->active_lock.ptr)
11021  		return -EINVAL;
11022  	if (env->cur_state->active_lock.ptr != ptr ||
11023  	    env->cur_state->active_lock.id != id) {
11024  		verbose(env, "held lock and object are not in the same allocation\n");
11025  		return -EINVAL;
11026  	}
11027  	return 0;
11028  }
11029  
is_bpf_list_api_kfunc(u32 btf_id)11030  static bool is_bpf_list_api_kfunc(u32 btf_id)
11031  {
11032  	return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11033  	       btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11034  	       btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11035  	       btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11036  }
11037  
is_bpf_rbtree_api_kfunc(u32 btf_id)11038  static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11039  {
11040  	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11041  	       btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11042  	       btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11043  }
11044  
is_bpf_graph_api_kfunc(u32 btf_id)11045  static bool is_bpf_graph_api_kfunc(u32 btf_id)
11046  {
11047  	return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11048  	       btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11049  }
11050  
is_sync_callback_calling_kfunc(u32 btf_id)11051  static bool is_sync_callback_calling_kfunc(u32 btf_id)
11052  {
11053  	return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11054  }
11055  
is_rbtree_lock_required_kfunc(u32 btf_id)11056  static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11057  {
11058  	return is_bpf_rbtree_api_kfunc(btf_id);
11059  }
11060  
check_kfunc_is_graph_root_api(struct bpf_verifier_env * env,enum btf_field_type head_field_type,u32 kfunc_btf_id)11061  static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11062  					  enum btf_field_type head_field_type,
11063  					  u32 kfunc_btf_id)
11064  {
11065  	bool ret;
11066  
11067  	switch (head_field_type) {
11068  	case BPF_LIST_HEAD:
11069  		ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11070  		break;
11071  	case BPF_RB_ROOT:
11072  		ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11073  		break;
11074  	default:
11075  		verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11076  			btf_field_type_name(head_field_type));
11077  		return false;
11078  	}
11079  
11080  	if (!ret)
11081  		verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11082  			btf_field_type_name(head_field_type));
11083  	return ret;
11084  }
11085  
check_kfunc_is_graph_node_api(struct bpf_verifier_env * env,enum btf_field_type node_field_type,u32 kfunc_btf_id)11086  static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11087  					  enum btf_field_type node_field_type,
11088  					  u32 kfunc_btf_id)
11089  {
11090  	bool ret;
11091  
11092  	switch (node_field_type) {
11093  	case BPF_LIST_NODE:
11094  		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11095  		       kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11096  		break;
11097  	case BPF_RB_NODE:
11098  		ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11099  		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11100  		break;
11101  	default:
11102  		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11103  			btf_field_type_name(node_field_type));
11104  		return false;
11105  	}
11106  
11107  	if (!ret)
11108  		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11109  			btf_field_type_name(node_field_type));
11110  	return ret;
11111  }
11112  
11113  static int
__process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,struct bpf_kfunc_call_arg_meta * meta,enum btf_field_type head_field_type,struct btf_field ** head_field)11114  __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11115  				   struct bpf_reg_state *reg, u32 regno,
11116  				   struct bpf_kfunc_call_arg_meta *meta,
11117  				   enum btf_field_type head_field_type,
11118  				   struct btf_field **head_field)
11119  {
11120  	const char *head_type_name;
11121  	struct btf_field *field;
11122  	struct btf_record *rec;
11123  	u32 head_off;
11124  
11125  	if (meta->btf != btf_vmlinux) {
11126  		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11127  		return -EFAULT;
11128  	}
11129  
11130  	if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11131  		return -EFAULT;
11132  
11133  	head_type_name = btf_field_type_name(head_field_type);
11134  	if (!tnum_is_const(reg->var_off)) {
11135  		verbose(env,
11136  			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11137  			regno, head_type_name);
11138  		return -EINVAL;
11139  	}
11140  
11141  	rec = reg_btf_record(reg);
11142  	head_off = reg->off + reg->var_off.value;
11143  	field = btf_record_find(rec, head_off, head_field_type);
11144  	if (!field) {
11145  		verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11146  		return -EINVAL;
11147  	}
11148  
11149  	/* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11150  	if (check_reg_allocation_locked(env, reg)) {
11151  		verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11152  			rec->spin_lock_off, head_type_name);
11153  		return -EINVAL;
11154  	}
11155  
11156  	if (*head_field) {
11157  		verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11158  		return -EFAULT;
11159  	}
11160  	*head_field = field;
11161  	return 0;
11162  }
11163  
process_kf_arg_ptr_to_list_head(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,struct bpf_kfunc_call_arg_meta * meta)11164  static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11165  					   struct bpf_reg_state *reg, u32 regno,
11166  					   struct bpf_kfunc_call_arg_meta *meta)
11167  {
11168  	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11169  							  &meta->arg_list_head.field);
11170  }
11171  
process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,struct bpf_kfunc_call_arg_meta * meta)11172  static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11173  					     struct bpf_reg_state *reg, u32 regno,
11174  					     struct bpf_kfunc_call_arg_meta *meta)
11175  {
11176  	return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11177  							  &meta->arg_rbtree_root.field);
11178  }
11179  
11180  static int
__process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,struct bpf_kfunc_call_arg_meta * meta,enum btf_field_type head_field_type,enum btf_field_type node_field_type,struct btf_field ** node_field)11181  __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11182  				   struct bpf_reg_state *reg, u32 regno,
11183  				   struct bpf_kfunc_call_arg_meta *meta,
11184  				   enum btf_field_type head_field_type,
11185  				   enum btf_field_type node_field_type,
11186  				   struct btf_field **node_field)
11187  {
11188  	const char *node_type_name;
11189  	const struct btf_type *et, *t;
11190  	struct btf_field *field;
11191  	u32 node_off;
11192  
11193  	if (meta->btf != btf_vmlinux) {
11194  		verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11195  		return -EFAULT;
11196  	}
11197  
11198  	if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11199  		return -EFAULT;
11200  
11201  	node_type_name = btf_field_type_name(node_field_type);
11202  	if (!tnum_is_const(reg->var_off)) {
11203  		verbose(env,
11204  			"R%d doesn't have constant offset. %s has to be at the constant offset\n",
11205  			regno, node_type_name);
11206  		return -EINVAL;
11207  	}
11208  
11209  	node_off = reg->off + reg->var_off.value;
11210  	field = reg_find_field_offset(reg, node_off, node_field_type);
11211  	if (!field || field->offset != node_off) {
11212  		verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11213  		return -EINVAL;
11214  	}
11215  
11216  	field = *node_field;
11217  
11218  	et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11219  	t = btf_type_by_id(reg->btf, reg->btf_id);
11220  	if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11221  				  field->graph_root.value_btf_id, true)) {
11222  		verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11223  			"in struct %s, but arg is at offset=%d in struct %s\n",
11224  			btf_field_type_name(head_field_type),
11225  			btf_field_type_name(node_field_type),
11226  			field->graph_root.node_offset,
11227  			btf_name_by_offset(field->graph_root.btf, et->name_off),
11228  			node_off, btf_name_by_offset(reg->btf, t->name_off));
11229  		return -EINVAL;
11230  	}
11231  	meta->arg_btf = reg->btf;
11232  	meta->arg_btf_id = reg->btf_id;
11233  
11234  	if (node_off != field->graph_root.node_offset) {
11235  		verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11236  			node_off, btf_field_type_name(node_field_type),
11237  			field->graph_root.node_offset,
11238  			btf_name_by_offset(field->graph_root.btf, et->name_off));
11239  		return -EINVAL;
11240  	}
11241  
11242  	return 0;
11243  }
11244  
process_kf_arg_ptr_to_list_node(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,struct bpf_kfunc_call_arg_meta * meta)11245  static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11246  					   struct bpf_reg_state *reg, u32 regno,
11247  					   struct bpf_kfunc_call_arg_meta *meta)
11248  {
11249  	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11250  						  BPF_LIST_HEAD, BPF_LIST_NODE,
11251  						  &meta->arg_list_head.field);
11252  }
11253  
process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,struct bpf_kfunc_call_arg_meta * meta)11254  static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11255  					     struct bpf_reg_state *reg, u32 regno,
11256  					     struct bpf_kfunc_call_arg_meta *meta)
11257  {
11258  	return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11259  						  BPF_RB_ROOT, BPF_RB_NODE,
11260  						  &meta->arg_rbtree_root.field);
11261  }
11262  
check_kfunc_args(struct bpf_verifier_env * env,struct bpf_kfunc_call_arg_meta * meta,int insn_idx)11263  static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11264  			    int insn_idx)
11265  {
11266  	const char *func_name = meta->func_name, *ref_tname;
11267  	const struct btf *btf = meta->btf;
11268  	const struct btf_param *args;
11269  	struct btf_record *rec;
11270  	u32 i, nargs;
11271  	int ret;
11272  
11273  	args = (const struct btf_param *)(meta->func_proto + 1);
11274  	nargs = btf_type_vlen(meta->func_proto);
11275  	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11276  		verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11277  			MAX_BPF_FUNC_REG_ARGS);
11278  		return -EINVAL;
11279  	}
11280  
11281  	/* Check that BTF function arguments match actual types that the
11282  	 * verifier sees.
11283  	 */
11284  	for (i = 0; i < nargs; i++) {
11285  		struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11286  		const struct btf_type *t, *ref_t, *resolve_ret;
11287  		enum bpf_arg_type arg_type = ARG_DONTCARE;
11288  		u32 regno = i + 1, ref_id, type_size;
11289  		bool is_ret_buf_sz = false;
11290  		int kf_arg_type;
11291  
11292  		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11293  
11294  		if (is_kfunc_arg_ignore(btf, &args[i]))
11295  			continue;
11296  
11297  		if (btf_type_is_scalar(t)) {
11298  			if (reg->type != SCALAR_VALUE) {
11299  				verbose(env, "R%d is not a scalar\n", regno);
11300  				return -EINVAL;
11301  			}
11302  
11303  			if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11304  				if (meta->arg_constant.found) {
11305  					verbose(env, "verifier internal error: only one constant argument permitted\n");
11306  					return -EFAULT;
11307  				}
11308  				if (!tnum_is_const(reg->var_off)) {
11309  					verbose(env, "R%d must be a known constant\n", regno);
11310  					return -EINVAL;
11311  				}
11312  				ret = mark_chain_precision(env, regno);
11313  				if (ret < 0)
11314  					return ret;
11315  				meta->arg_constant.found = true;
11316  				meta->arg_constant.value = reg->var_off.value;
11317  			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11318  				meta->r0_rdonly = true;
11319  				is_ret_buf_sz = true;
11320  			} else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11321  				is_ret_buf_sz = true;
11322  			}
11323  
11324  			if (is_ret_buf_sz) {
11325  				if (meta->r0_size) {
11326  					verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11327  					return -EINVAL;
11328  				}
11329  
11330  				if (!tnum_is_const(reg->var_off)) {
11331  					verbose(env, "R%d is not a const\n", regno);
11332  					return -EINVAL;
11333  				}
11334  
11335  				meta->r0_size = reg->var_off.value;
11336  				ret = mark_chain_precision(env, regno);
11337  				if (ret)
11338  					return ret;
11339  			}
11340  			continue;
11341  		}
11342  
11343  		if (!btf_type_is_ptr(t)) {
11344  			verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11345  			return -EINVAL;
11346  		}
11347  
11348  		if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11349  		    (register_is_null(reg) || type_may_be_null(reg->type))) {
11350  			verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11351  			return -EACCES;
11352  		}
11353  
11354  		if (reg->ref_obj_id) {
11355  			if (is_kfunc_release(meta) && meta->ref_obj_id) {
11356  				verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11357  					regno, reg->ref_obj_id,
11358  					meta->ref_obj_id);
11359  				return -EFAULT;
11360  			}
11361  			meta->ref_obj_id = reg->ref_obj_id;
11362  			if (is_kfunc_release(meta))
11363  				meta->release_regno = regno;
11364  		}
11365  
11366  		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11367  		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11368  
11369  		kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11370  		if (kf_arg_type < 0)
11371  			return kf_arg_type;
11372  
11373  		switch (kf_arg_type) {
11374  		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11375  		case KF_ARG_PTR_TO_BTF_ID:
11376  			if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11377  				break;
11378  
11379  			if (!is_trusted_reg(reg)) {
11380  				if (!is_kfunc_rcu(meta)) {
11381  					verbose(env, "R%d must be referenced or trusted\n", regno);
11382  					return -EINVAL;
11383  				}
11384  				if (!is_rcu_reg(reg)) {
11385  					verbose(env, "R%d must be a rcu pointer\n", regno);
11386  					return -EINVAL;
11387  				}
11388  			}
11389  
11390  			fallthrough;
11391  		case KF_ARG_PTR_TO_CTX:
11392  			/* Trusted arguments have the same offset checks as release arguments */
11393  			arg_type |= OBJ_RELEASE;
11394  			break;
11395  		case KF_ARG_PTR_TO_DYNPTR:
11396  		case KF_ARG_PTR_TO_ITER:
11397  		case KF_ARG_PTR_TO_LIST_HEAD:
11398  		case KF_ARG_PTR_TO_LIST_NODE:
11399  		case KF_ARG_PTR_TO_RB_ROOT:
11400  		case KF_ARG_PTR_TO_RB_NODE:
11401  		case KF_ARG_PTR_TO_MEM:
11402  		case KF_ARG_PTR_TO_MEM_SIZE:
11403  		case KF_ARG_PTR_TO_CALLBACK:
11404  		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11405  			/* Trusted by default */
11406  			break;
11407  		default:
11408  			WARN_ON_ONCE(1);
11409  			return -EFAULT;
11410  		}
11411  
11412  		if (is_kfunc_release(meta) && reg->ref_obj_id)
11413  			arg_type |= OBJ_RELEASE;
11414  		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11415  		if (ret < 0)
11416  			return ret;
11417  
11418  		switch (kf_arg_type) {
11419  		case KF_ARG_PTR_TO_CTX:
11420  			if (reg->type != PTR_TO_CTX) {
11421  				verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11422  				return -EINVAL;
11423  			}
11424  
11425  			if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11426  				ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11427  				if (ret < 0)
11428  					return -EINVAL;
11429  				meta->ret_btf_id  = ret;
11430  			}
11431  			break;
11432  		case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11433  			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11434  				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11435  				return -EINVAL;
11436  			}
11437  			if (!reg->ref_obj_id) {
11438  				verbose(env, "allocated object must be referenced\n");
11439  				return -EINVAL;
11440  			}
11441  			if (meta->btf == btf_vmlinux &&
11442  			    meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11443  				meta->arg_btf = reg->btf;
11444  				meta->arg_btf_id = reg->btf_id;
11445  			}
11446  			break;
11447  		case KF_ARG_PTR_TO_DYNPTR:
11448  		{
11449  			enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11450  			int clone_ref_obj_id = 0;
11451  
11452  			if (reg->type != PTR_TO_STACK &&
11453  			    reg->type != CONST_PTR_TO_DYNPTR) {
11454  				verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11455  				return -EINVAL;
11456  			}
11457  
11458  			if (reg->type == CONST_PTR_TO_DYNPTR)
11459  				dynptr_arg_type |= MEM_RDONLY;
11460  
11461  			if (is_kfunc_arg_uninit(btf, &args[i]))
11462  				dynptr_arg_type |= MEM_UNINIT;
11463  
11464  			if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11465  				dynptr_arg_type |= DYNPTR_TYPE_SKB;
11466  			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11467  				dynptr_arg_type |= DYNPTR_TYPE_XDP;
11468  			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11469  				   (dynptr_arg_type & MEM_UNINIT)) {
11470  				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11471  
11472  				if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11473  					verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11474  					return -EFAULT;
11475  				}
11476  
11477  				dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11478  				clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11479  				if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11480  					verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11481  					return -EFAULT;
11482  				}
11483  			}
11484  
11485  			ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11486  			if (ret < 0)
11487  				return ret;
11488  
11489  			if (!(dynptr_arg_type & MEM_UNINIT)) {
11490  				int id = dynptr_id(env, reg);
11491  
11492  				if (id < 0) {
11493  					verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11494  					return id;
11495  				}
11496  				meta->initialized_dynptr.id = id;
11497  				meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11498  				meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11499  			}
11500  
11501  			break;
11502  		}
11503  		case KF_ARG_PTR_TO_ITER:
11504  			ret = process_iter_arg(env, regno, insn_idx, meta);
11505  			if (ret < 0)
11506  				return ret;
11507  			break;
11508  		case KF_ARG_PTR_TO_LIST_HEAD:
11509  			if (reg->type != PTR_TO_MAP_VALUE &&
11510  			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11511  				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11512  				return -EINVAL;
11513  			}
11514  			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11515  				verbose(env, "allocated object must be referenced\n");
11516  				return -EINVAL;
11517  			}
11518  			ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11519  			if (ret < 0)
11520  				return ret;
11521  			break;
11522  		case KF_ARG_PTR_TO_RB_ROOT:
11523  			if (reg->type != PTR_TO_MAP_VALUE &&
11524  			    reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11525  				verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11526  				return -EINVAL;
11527  			}
11528  			if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11529  				verbose(env, "allocated object must be referenced\n");
11530  				return -EINVAL;
11531  			}
11532  			ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11533  			if (ret < 0)
11534  				return ret;
11535  			break;
11536  		case KF_ARG_PTR_TO_LIST_NODE:
11537  			if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11538  				verbose(env, "arg#%d expected pointer to allocated object\n", i);
11539  				return -EINVAL;
11540  			}
11541  			if (!reg->ref_obj_id) {
11542  				verbose(env, "allocated object must be referenced\n");
11543  				return -EINVAL;
11544  			}
11545  			ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11546  			if (ret < 0)
11547  				return ret;
11548  			break;
11549  		case KF_ARG_PTR_TO_RB_NODE:
11550  			if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11551  				if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11552  					verbose(env, "rbtree_remove node input must be non-owning ref\n");
11553  					return -EINVAL;
11554  				}
11555  				if (in_rbtree_lock_required_cb(env)) {
11556  					verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11557  					return -EINVAL;
11558  				}
11559  			} else {
11560  				if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11561  					verbose(env, "arg#%d expected pointer to allocated object\n", i);
11562  					return -EINVAL;
11563  				}
11564  				if (!reg->ref_obj_id) {
11565  					verbose(env, "allocated object must be referenced\n");
11566  					return -EINVAL;
11567  				}
11568  			}
11569  
11570  			ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11571  			if (ret < 0)
11572  				return ret;
11573  			break;
11574  		case KF_ARG_PTR_TO_BTF_ID:
11575  			/* Only base_type is checked, further checks are done here */
11576  			if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11577  			     (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11578  			    !reg2btf_ids[base_type(reg->type)]) {
11579  				verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11580  				verbose(env, "expected %s or socket\n",
11581  					reg_type_str(env, base_type(reg->type) |
11582  							  (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11583  				return -EINVAL;
11584  			}
11585  			ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11586  			if (ret < 0)
11587  				return ret;
11588  			break;
11589  		case KF_ARG_PTR_TO_MEM:
11590  			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11591  			if (IS_ERR(resolve_ret)) {
11592  				verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11593  					i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11594  				return -EINVAL;
11595  			}
11596  			ret = check_mem_reg(env, reg, regno, type_size);
11597  			if (ret < 0)
11598  				return ret;
11599  			break;
11600  		case KF_ARG_PTR_TO_MEM_SIZE:
11601  		{
11602  			struct bpf_reg_state *buff_reg = &regs[regno];
11603  			const struct btf_param *buff_arg = &args[i];
11604  			struct bpf_reg_state *size_reg = &regs[regno + 1];
11605  			const struct btf_param *size_arg = &args[i + 1];
11606  
11607  			if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11608  				ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11609  				if (ret < 0) {
11610  					verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11611  					return ret;
11612  				}
11613  			}
11614  
11615  			if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11616  				if (meta->arg_constant.found) {
11617  					verbose(env, "verifier internal error: only one constant argument permitted\n");
11618  					return -EFAULT;
11619  				}
11620  				if (!tnum_is_const(size_reg->var_off)) {
11621  					verbose(env, "R%d must be a known constant\n", regno + 1);
11622  					return -EINVAL;
11623  				}
11624  				meta->arg_constant.found = true;
11625  				meta->arg_constant.value = size_reg->var_off.value;
11626  			}
11627  
11628  			/* Skip next '__sz' or '__szk' argument */
11629  			i++;
11630  			break;
11631  		}
11632  		case KF_ARG_PTR_TO_CALLBACK:
11633  			if (reg->type != PTR_TO_FUNC) {
11634  				verbose(env, "arg%d expected pointer to func\n", i);
11635  				return -EINVAL;
11636  			}
11637  			meta->subprogno = reg->subprogno;
11638  			break;
11639  		case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11640  			if (!type_is_ptr_alloc_obj(reg->type)) {
11641  				verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11642  				return -EINVAL;
11643  			}
11644  			if (!type_is_non_owning_ref(reg->type))
11645  				meta->arg_owning_ref = true;
11646  
11647  			rec = reg_btf_record(reg);
11648  			if (!rec) {
11649  				verbose(env, "verifier internal error: Couldn't find btf_record\n");
11650  				return -EFAULT;
11651  			}
11652  
11653  			if (rec->refcount_off < 0) {
11654  				verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11655  				return -EINVAL;
11656  			}
11657  
11658  			meta->arg_btf = reg->btf;
11659  			meta->arg_btf_id = reg->btf_id;
11660  			break;
11661  		}
11662  	}
11663  
11664  	if (is_kfunc_release(meta) && !meta->release_regno) {
11665  		verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11666  			func_name);
11667  		return -EINVAL;
11668  	}
11669  
11670  	return 0;
11671  }
11672  
fetch_kfunc_meta(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_kfunc_call_arg_meta * meta,const char ** kfunc_name)11673  static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11674  			    struct bpf_insn *insn,
11675  			    struct bpf_kfunc_call_arg_meta *meta,
11676  			    const char **kfunc_name)
11677  {
11678  	const struct btf_type *func, *func_proto;
11679  	u32 func_id, *kfunc_flags;
11680  	const char *func_name;
11681  	struct btf *desc_btf;
11682  
11683  	if (kfunc_name)
11684  		*kfunc_name = NULL;
11685  
11686  	if (!insn->imm)
11687  		return -EINVAL;
11688  
11689  	desc_btf = find_kfunc_desc_btf(env, insn->off);
11690  	if (IS_ERR(desc_btf))
11691  		return PTR_ERR(desc_btf);
11692  
11693  	func_id = insn->imm;
11694  	func = btf_type_by_id(desc_btf, func_id);
11695  	func_name = btf_name_by_offset(desc_btf, func->name_off);
11696  	if (kfunc_name)
11697  		*kfunc_name = func_name;
11698  	func_proto = btf_type_by_id(desc_btf, func->type);
11699  
11700  	kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11701  	if (!kfunc_flags) {
11702  		return -EACCES;
11703  	}
11704  
11705  	memset(meta, 0, sizeof(*meta));
11706  	meta->btf = desc_btf;
11707  	meta->func_id = func_id;
11708  	meta->kfunc_flags = *kfunc_flags;
11709  	meta->func_proto = func_proto;
11710  	meta->func_name = func_name;
11711  
11712  	return 0;
11713  }
11714  
check_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)11715  static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11716  			    int *insn_idx_p)
11717  {
11718  	const struct btf_type *t, *ptr_type;
11719  	u32 i, nargs, ptr_type_id, release_ref_obj_id;
11720  	struct bpf_reg_state *regs = cur_regs(env);
11721  	const char *func_name, *ptr_type_name;
11722  	bool sleepable, rcu_lock, rcu_unlock;
11723  	struct bpf_kfunc_call_arg_meta meta;
11724  	struct bpf_insn_aux_data *insn_aux;
11725  	int err, insn_idx = *insn_idx_p;
11726  	const struct btf_param *args;
11727  	const struct btf_type *ret_t;
11728  	struct btf *desc_btf;
11729  
11730  	/* skip for now, but return error when we find this in fixup_kfunc_call */
11731  	if (!insn->imm)
11732  		return 0;
11733  
11734  	err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11735  	if (err == -EACCES && func_name)
11736  		verbose(env, "calling kernel function %s is not allowed\n", func_name);
11737  	if (err)
11738  		return err;
11739  	desc_btf = meta.btf;
11740  	insn_aux = &env->insn_aux_data[insn_idx];
11741  
11742  	insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11743  
11744  	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11745  		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11746  		return -EACCES;
11747  	}
11748  
11749  	sleepable = is_kfunc_sleepable(&meta);
11750  	if (sleepable && !env->prog->aux->sleepable) {
11751  		verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11752  		return -EACCES;
11753  	}
11754  
11755  	/* Check the arguments */
11756  	err = check_kfunc_args(env, &meta, insn_idx);
11757  	if (err < 0)
11758  		return err;
11759  
11760  	if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11761  		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11762  					 set_rbtree_add_callback_state);
11763  		if (err) {
11764  			verbose(env, "kfunc %s#%d failed callback verification\n",
11765  				func_name, meta.func_id);
11766  			return err;
11767  		}
11768  	}
11769  
11770  	rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11771  	rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11772  
11773  	if (env->cur_state->active_rcu_lock) {
11774  		struct bpf_func_state *state;
11775  		struct bpf_reg_state *reg;
11776  
11777  		if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
11778  			verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
11779  			return -EACCES;
11780  		}
11781  
11782  		if (rcu_lock) {
11783  			verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11784  			return -EINVAL;
11785  		} else if (rcu_unlock) {
11786  			bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11787  				if (reg->type & MEM_RCU) {
11788  					reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11789  					reg->type |= PTR_UNTRUSTED;
11790  				}
11791  			}));
11792  			env->cur_state->active_rcu_lock = false;
11793  		} else if (sleepable) {
11794  			verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11795  			return -EACCES;
11796  		}
11797  	} else if (rcu_lock) {
11798  		env->cur_state->active_rcu_lock = true;
11799  	} else if (rcu_unlock) {
11800  		verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11801  		return -EINVAL;
11802  	}
11803  
11804  	/* In case of release function, we get register number of refcounted
11805  	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11806  	 */
11807  	if (meta.release_regno) {
11808  		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11809  		if (err) {
11810  			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11811  				func_name, meta.func_id);
11812  			return err;
11813  		}
11814  	}
11815  
11816  	if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11817  	    meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11818  	    meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11819  		release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11820  		insn_aux->insert_off = regs[BPF_REG_2].off;
11821  		insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11822  		err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11823  		if (err) {
11824  			verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11825  				func_name, meta.func_id);
11826  			return err;
11827  		}
11828  
11829  		err = release_reference(env, release_ref_obj_id);
11830  		if (err) {
11831  			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11832  				func_name, meta.func_id);
11833  			return err;
11834  		}
11835  	}
11836  
11837  	for (i = 0; i < CALLER_SAVED_REGS; i++)
11838  		mark_reg_not_init(env, regs, caller_saved[i]);
11839  
11840  	/* Check return type */
11841  	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11842  
11843  	if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11844  		/* Only exception is bpf_obj_new_impl */
11845  		if (meta.btf != btf_vmlinux ||
11846  		    (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11847  		     meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11848  			verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11849  			return -EINVAL;
11850  		}
11851  	}
11852  
11853  	if (btf_type_is_scalar(t)) {
11854  		mark_reg_unknown(env, regs, BPF_REG_0);
11855  		mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11856  	} else if (btf_type_is_ptr(t)) {
11857  		ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11858  
11859  		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11860  			if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11861  				struct btf *ret_btf;
11862  				u32 ret_btf_id;
11863  
11864  				if (unlikely(!bpf_global_ma_set))
11865  					return -ENOMEM;
11866  
11867  				if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11868  					verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11869  					return -EINVAL;
11870  				}
11871  
11872  				ret_btf = env->prog->aux->btf;
11873  				ret_btf_id = meta.arg_constant.value;
11874  
11875  				/* This may be NULL due to user not supplying a BTF */
11876  				if (!ret_btf) {
11877  					verbose(env, "bpf_obj_new requires prog BTF\n");
11878  					return -EINVAL;
11879  				}
11880  
11881  				ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11882  				if (!ret_t || !__btf_type_is_struct(ret_t)) {
11883  					verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11884  					return -EINVAL;
11885  				}
11886  
11887  				mark_reg_known_zero(env, regs, BPF_REG_0);
11888  				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11889  				regs[BPF_REG_0].btf = ret_btf;
11890  				regs[BPF_REG_0].btf_id = ret_btf_id;
11891  
11892  				insn_aux->obj_new_size = ret_t->size;
11893  				insn_aux->kptr_struct_meta =
11894  					btf_find_struct_meta(ret_btf, ret_btf_id);
11895  			} else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11896  				mark_reg_known_zero(env, regs, BPF_REG_0);
11897  				regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11898  				regs[BPF_REG_0].btf = meta.arg_btf;
11899  				regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11900  
11901  				insn_aux->kptr_struct_meta =
11902  					btf_find_struct_meta(meta.arg_btf,
11903  							     meta.arg_btf_id);
11904  			} else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11905  				   meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11906  				struct btf_field *field = meta.arg_list_head.field;
11907  
11908  				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11909  			} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11910  				   meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11911  				struct btf_field *field = meta.arg_rbtree_root.field;
11912  
11913  				mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11914  			} else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11915  				mark_reg_known_zero(env, regs, BPF_REG_0);
11916  				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11917  				regs[BPF_REG_0].btf = desc_btf;
11918  				regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11919  			} else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11920  				ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11921  				if (!ret_t || !btf_type_is_struct(ret_t)) {
11922  					verbose(env,
11923  						"kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11924  					return -EINVAL;
11925  				}
11926  
11927  				mark_reg_known_zero(env, regs, BPF_REG_0);
11928  				regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11929  				regs[BPF_REG_0].btf = desc_btf;
11930  				regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11931  			} else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11932  				   meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11933  				enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11934  
11935  				mark_reg_known_zero(env, regs, BPF_REG_0);
11936  
11937  				if (!meta.arg_constant.found) {
11938  					verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11939  					return -EFAULT;
11940  				}
11941  
11942  				regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11943  
11944  				/* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11945  				regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11946  
11947  				if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11948  					regs[BPF_REG_0].type |= MEM_RDONLY;
11949  				} else {
11950  					/* this will set env->seen_direct_write to true */
11951  					if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11952  						verbose(env, "the prog does not allow writes to packet data\n");
11953  						return -EINVAL;
11954  					}
11955  				}
11956  
11957  				if (!meta.initialized_dynptr.id) {
11958  					verbose(env, "verifier internal error: no dynptr id\n");
11959  					return -EFAULT;
11960  				}
11961  				regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11962  
11963  				/* we don't need to set BPF_REG_0's ref obj id
11964  				 * because packet slices are not refcounted (see
11965  				 * dynptr_type_refcounted)
11966  				 */
11967  			} else {
11968  				verbose(env, "kernel function %s unhandled dynamic return type\n",
11969  					meta.func_name);
11970  				return -EFAULT;
11971  			}
11972  		} else if (!__btf_type_is_struct(ptr_type)) {
11973  			if (!meta.r0_size) {
11974  				__u32 sz;
11975  
11976  				if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11977  					meta.r0_size = sz;
11978  					meta.r0_rdonly = true;
11979  				}
11980  			}
11981  			if (!meta.r0_size) {
11982  				ptr_type_name = btf_name_by_offset(desc_btf,
11983  								   ptr_type->name_off);
11984  				verbose(env,
11985  					"kernel function %s returns pointer type %s %s is not supported\n",
11986  					func_name,
11987  					btf_type_str(ptr_type),
11988  					ptr_type_name);
11989  				return -EINVAL;
11990  			}
11991  
11992  			mark_reg_known_zero(env, regs, BPF_REG_0);
11993  			regs[BPF_REG_0].type = PTR_TO_MEM;
11994  			regs[BPF_REG_0].mem_size = meta.r0_size;
11995  
11996  			if (meta.r0_rdonly)
11997  				regs[BPF_REG_0].type |= MEM_RDONLY;
11998  
11999  			/* Ensures we don't access the memory after a release_reference() */
12000  			if (meta.ref_obj_id)
12001  				regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12002  		} else {
12003  			mark_reg_known_zero(env, regs, BPF_REG_0);
12004  			regs[BPF_REG_0].btf = desc_btf;
12005  			regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12006  			regs[BPF_REG_0].btf_id = ptr_type_id;
12007  
12008  			if (is_iter_next_kfunc(&meta)) {
12009  				struct bpf_reg_state *cur_iter;
12010  
12011  				cur_iter = get_iter_from_state(env->cur_state, &meta);
12012  
12013  				if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */
12014  					regs[BPF_REG_0].type |= MEM_RCU;
12015  				else
12016  					regs[BPF_REG_0].type |= PTR_TRUSTED;
12017  			}
12018  		}
12019  
12020  		if (is_kfunc_ret_null(&meta)) {
12021  			regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12022  			/* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12023  			regs[BPF_REG_0].id = ++env->id_gen;
12024  		}
12025  		mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12026  		if (is_kfunc_acquire(&meta)) {
12027  			int id = acquire_reference_state(env, insn_idx);
12028  
12029  			if (id < 0)
12030  				return id;
12031  			if (is_kfunc_ret_null(&meta))
12032  				regs[BPF_REG_0].id = id;
12033  			regs[BPF_REG_0].ref_obj_id = id;
12034  		} else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12035  			ref_set_non_owning(env, &regs[BPF_REG_0]);
12036  		}
12037  
12038  		if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12039  			regs[BPF_REG_0].id = ++env->id_gen;
12040  	} else if (btf_type_is_void(t)) {
12041  		if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12042  			if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
12043  				insn_aux->kptr_struct_meta =
12044  					btf_find_struct_meta(meta.arg_btf,
12045  							     meta.arg_btf_id);
12046  			}
12047  		}
12048  	}
12049  
12050  	nargs = btf_type_vlen(meta.func_proto);
12051  	args = (const struct btf_param *)(meta.func_proto + 1);
12052  	for (i = 0; i < nargs; i++) {
12053  		u32 regno = i + 1;
12054  
12055  		t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12056  		if (btf_type_is_ptr(t))
12057  			mark_btf_func_reg_size(env, regno, sizeof(void *));
12058  		else
12059  			/* scalar. ensured by btf_check_kfunc_arg_match() */
12060  			mark_btf_func_reg_size(env, regno, t->size);
12061  	}
12062  
12063  	if (is_iter_next_kfunc(&meta)) {
12064  		err = process_iter_next_call(env, insn_idx, &meta);
12065  		if (err)
12066  			return err;
12067  	}
12068  
12069  	return 0;
12070  }
12071  
signed_add_overflows(s64 a,s64 b)12072  static bool signed_add_overflows(s64 a, s64 b)
12073  {
12074  	/* Do the add in u64, where overflow is well-defined */
12075  	s64 res = (s64)((u64)a + (u64)b);
12076  
12077  	if (b < 0)
12078  		return res > a;
12079  	return res < a;
12080  }
12081  
signed_add32_overflows(s32 a,s32 b)12082  static bool signed_add32_overflows(s32 a, s32 b)
12083  {
12084  	/* Do the add in u32, where overflow is well-defined */
12085  	s32 res = (s32)((u32)a + (u32)b);
12086  
12087  	if (b < 0)
12088  		return res > a;
12089  	return res < a;
12090  }
12091  
signed_sub_overflows(s64 a,s64 b)12092  static bool signed_sub_overflows(s64 a, s64 b)
12093  {
12094  	/* Do the sub in u64, where overflow is well-defined */
12095  	s64 res = (s64)((u64)a - (u64)b);
12096  
12097  	if (b < 0)
12098  		return res < a;
12099  	return res > a;
12100  }
12101  
signed_sub32_overflows(s32 a,s32 b)12102  static bool signed_sub32_overflows(s32 a, s32 b)
12103  {
12104  	/* Do the sub in u32, where overflow is well-defined */
12105  	s32 res = (s32)((u32)a - (u32)b);
12106  
12107  	if (b < 0)
12108  		return res < a;
12109  	return res > a;
12110  }
12111  
check_reg_sane_offset(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,enum bpf_reg_type type)12112  static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12113  				  const struct bpf_reg_state *reg,
12114  				  enum bpf_reg_type type)
12115  {
12116  	bool known = tnum_is_const(reg->var_off);
12117  	s64 val = reg->var_off.value;
12118  	s64 smin = reg->smin_value;
12119  
12120  	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12121  		verbose(env, "math between %s pointer and %lld is not allowed\n",
12122  			reg_type_str(env, type), val);
12123  		return false;
12124  	}
12125  
12126  	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12127  		verbose(env, "%s pointer offset %d is not allowed\n",
12128  			reg_type_str(env, type), reg->off);
12129  		return false;
12130  	}
12131  
12132  	if (smin == S64_MIN) {
12133  		verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12134  			reg_type_str(env, type));
12135  		return false;
12136  	}
12137  
12138  	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12139  		verbose(env, "value %lld makes %s pointer be out of bounds\n",
12140  			smin, reg_type_str(env, type));
12141  		return false;
12142  	}
12143  
12144  	return true;
12145  }
12146  
12147  enum {
12148  	REASON_BOUNDS	= -1,
12149  	REASON_TYPE	= -2,
12150  	REASON_PATHS	= -3,
12151  	REASON_LIMIT	= -4,
12152  	REASON_STACK	= -5,
12153  };
12154  
retrieve_ptr_limit(const struct bpf_reg_state * ptr_reg,u32 * alu_limit,bool mask_to_left)12155  static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12156  			      u32 *alu_limit, bool mask_to_left)
12157  {
12158  	u32 max = 0, ptr_limit = 0;
12159  
12160  	switch (ptr_reg->type) {
12161  	case PTR_TO_STACK:
12162  		/* Offset 0 is out-of-bounds, but acceptable start for the
12163  		 * left direction, see BPF_REG_FP. Also, unknown scalar
12164  		 * offset where we would need to deal with min/max bounds is
12165  		 * currently prohibited for unprivileged.
12166  		 */
12167  		max = MAX_BPF_STACK + mask_to_left;
12168  		ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12169  		break;
12170  	case PTR_TO_MAP_VALUE:
12171  		max = ptr_reg->map_ptr->value_size;
12172  		ptr_limit = (mask_to_left ?
12173  			     ptr_reg->smin_value :
12174  			     ptr_reg->umax_value) + ptr_reg->off;
12175  		break;
12176  	default:
12177  		return REASON_TYPE;
12178  	}
12179  
12180  	if (ptr_limit >= max)
12181  		return REASON_LIMIT;
12182  	*alu_limit = ptr_limit;
12183  	return 0;
12184  }
12185  
can_skip_alu_sanitation(const struct bpf_verifier_env * env,const struct bpf_insn * insn)12186  static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12187  				    const struct bpf_insn *insn)
12188  {
12189  	return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12190  }
12191  
update_alu_sanitation_state(struct bpf_insn_aux_data * aux,u32 alu_state,u32 alu_limit)12192  static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12193  				       u32 alu_state, u32 alu_limit)
12194  {
12195  	/* If we arrived here from different branches with different
12196  	 * state or limits to sanitize, then this won't work.
12197  	 */
12198  	if (aux->alu_state &&
12199  	    (aux->alu_state != alu_state ||
12200  	     aux->alu_limit != alu_limit))
12201  		return REASON_PATHS;
12202  
12203  	/* Corresponding fixup done in do_misc_fixups(). */
12204  	aux->alu_state = alu_state;
12205  	aux->alu_limit = alu_limit;
12206  	return 0;
12207  }
12208  
sanitize_val_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)12209  static int sanitize_val_alu(struct bpf_verifier_env *env,
12210  			    struct bpf_insn *insn)
12211  {
12212  	struct bpf_insn_aux_data *aux = cur_aux(env);
12213  
12214  	if (can_skip_alu_sanitation(env, insn))
12215  		return 0;
12216  
12217  	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12218  }
12219  
sanitize_needed(u8 opcode)12220  static bool sanitize_needed(u8 opcode)
12221  {
12222  	return opcode == BPF_ADD || opcode == BPF_SUB;
12223  }
12224  
12225  struct bpf_sanitize_info {
12226  	struct bpf_insn_aux_data aux;
12227  	bool mask_to_left;
12228  };
12229  
12230  static struct bpf_verifier_state *
sanitize_speculative_path(struct bpf_verifier_env * env,const struct bpf_insn * insn,u32 next_idx,u32 curr_idx)12231  sanitize_speculative_path(struct bpf_verifier_env *env,
12232  			  const struct bpf_insn *insn,
12233  			  u32 next_idx, u32 curr_idx)
12234  {
12235  	struct bpf_verifier_state *branch;
12236  	struct bpf_reg_state *regs;
12237  
12238  	branch = push_stack(env, next_idx, curr_idx, true);
12239  	if (branch && insn) {
12240  		regs = branch->frame[branch->curframe]->regs;
12241  		if (BPF_SRC(insn->code) == BPF_K) {
12242  			mark_reg_unknown(env, regs, insn->dst_reg);
12243  		} else if (BPF_SRC(insn->code) == BPF_X) {
12244  			mark_reg_unknown(env, regs, insn->dst_reg);
12245  			mark_reg_unknown(env, regs, insn->src_reg);
12246  		}
12247  	}
12248  	return branch;
12249  }
12250  
sanitize_ptr_alu(struct bpf_verifier_env * env,struct bpf_insn * insn,const struct bpf_reg_state * ptr_reg,const struct bpf_reg_state * off_reg,struct bpf_reg_state * dst_reg,struct bpf_sanitize_info * info,const bool commit_window)12251  static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12252  			    struct bpf_insn *insn,
12253  			    const struct bpf_reg_state *ptr_reg,
12254  			    const struct bpf_reg_state *off_reg,
12255  			    struct bpf_reg_state *dst_reg,
12256  			    struct bpf_sanitize_info *info,
12257  			    const bool commit_window)
12258  {
12259  	struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12260  	struct bpf_verifier_state *vstate = env->cur_state;
12261  	bool off_is_imm = tnum_is_const(off_reg->var_off);
12262  	bool off_is_neg = off_reg->smin_value < 0;
12263  	bool ptr_is_dst_reg = ptr_reg == dst_reg;
12264  	u8 opcode = BPF_OP(insn->code);
12265  	u32 alu_state, alu_limit;
12266  	struct bpf_reg_state tmp;
12267  	bool ret;
12268  	int err;
12269  
12270  	if (can_skip_alu_sanitation(env, insn))
12271  		return 0;
12272  
12273  	/* We already marked aux for masking from non-speculative
12274  	 * paths, thus we got here in the first place. We only care
12275  	 * to explore bad access from here.
12276  	 */
12277  	if (vstate->speculative)
12278  		goto do_sim;
12279  
12280  	if (!commit_window) {
12281  		if (!tnum_is_const(off_reg->var_off) &&
12282  		    (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12283  			return REASON_BOUNDS;
12284  
12285  		info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
12286  				     (opcode == BPF_SUB && !off_is_neg);
12287  	}
12288  
12289  	err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12290  	if (err < 0)
12291  		return err;
12292  
12293  	if (commit_window) {
12294  		/* In commit phase we narrow the masking window based on
12295  		 * the observed pointer move after the simulated operation.
12296  		 */
12297  		alu_state = info->aux.alu_state;
12298  		alu_limit = abs(info->aux.alu_limit - alu_limit);
12299  	} else {
12300  		alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12301  		alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12302  		alu_state |= ptr_is_dst_reg ?
12303  			     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12304  
12305  		/* Limit pruning on unknown scalars to enable deep search for
12306  		 * potential masking differences from other program paths.
12307  		 */
12308  		if (!off_is_imm)
12309  			env->explore_alu_limits = true;
12310  	}
12311  
12312  	err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12313  	if (err < 0)
12314  		return err;
12315  do_sim:
12316  	/* If we're in commit phase, we're done here given we already
12317  	 * pushed the truncated dst_reg into the speculative verification
12318  	 * stack.
12319  	 *
12320  	 * Also, when register is a known constant, we rewrite register-based
12321  	 * operation to immediate-based, and thus do not need masking (and as
12322  	 * a consequence, do not need to simulate the zero-truncation either).
12323  	 */
12324  	if (commit_window || off_is_imm)
12325  		return 0;
12326  
12327  	/* Simulate and find potential out-of-bounds access under
12328  	 * speculative execution from truncation as a result of
12329  	 * masking when off was not within expected range. If off
12330  	 * sits in dst, then we temporarily need to move ptr there
12331  	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12332  	 * for cases where we use K-based arithmetic in one direction
12333  	 * and truncated reg-based in the other in order to explore
12334  	 * bad access.
12335  	 */
12336  	if (!ptr_is_dst_reg) {
12337  		tmp = *dst_reg;
12338  		copy_register_state(dst_reg, ptr_reg);
12339  	}
12340  	ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12341  					env->insn_idx);
12342  	if (!ptr_is_dst_reg && ret)
12343  		*dst_reg = tmp;
12344  	return !ret ? REASON_STACK : 0;
12345  }
12346  
sanitize_mark_insn_seen(struct bpf_verifier_env * env)12347  static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12348  {
12349  	struct bpf_verifier_state *vstate = env->cur_state;
12350  
12351  	/* If we simulate paths under speculation, we don't update the
12352  	 * insn as 'seen' such that when we verify unreachable paths in
12353  	 * the non-speculative domain, sanitize_dead_code() can still
12354  	 * rewrite/sanitize them.
12355  	 */
12356  	if (!vstate->speculative)
12357  		env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12358  }
12359  
sanitize_err(struct bpf_verifier_env * env,const struct bpf_insn * insn,int reason,const struct bpf_reg_state * off_reg,const struct bpf_reg_state * dst_reg)12360  static int sanitize_err(struct bpf_verifier_env *env,
12361  			const struct bpf_insn *insn, int reason,
12362  			const struct bpf_reg_state *off_reg,
12363  			const struct bpf_reg_state *dst_reg)
12364  {
12365  	static const char *err = "pointer arithmetic with it prohibited for !root";
12366  	const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12367  	u32 dst = insn->dst_reg, src = insn->src_reg;
12368  
12369  	switch (reason) {
12370  	case REASON_BOUNDS:
12371  		verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12372  			off_reg == dst_reg ? dst : src, err);
12373  		break;
12374  	case REASON_TYPE:
12375  		verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12376  			off_reg == dst_reg ? src : dst, err);
12377  		break;
12378  	case REASON_PATHS:
12379  		verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12380  			dst, op, err);
12381  		break;
12382  	case REASON_LIMIT:
12383  		verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12384  			dst, op, err);
12385  		break;
12386  	case REASON_STACK:
12387  		verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12388  			dst, err);
12389  		break;
12390  	default:
12391  		verbose(env, "verifier internal error: unknown reason (%d)\n",
12392  			reason);
12393  		break;
12394  	}
12395  
12396  	return -EACCES;
12397  }
12398  
12399  /* check that stack access falls within stack limits and that 'reg' doesn't
12400   * have a variable offset.
12401   *
12402   * Variable offset is prohibited for unprivileged mode for simplicity since it
12403   * requires corresponding support in Spectre masking for stack ALU.  See also
12404   * retrieve_ptr_limit().
12405   *
12406   *
12407   * 'off' includes 'reg->off'.
12408   */
check_stack_access_for_ptr_arithmetic(struct bpf_verifier_env * env,int regno,const struct bpf_reg_state * reg,int off)12409  static int check_stack_access_for_ptr_arithmetic(
12410  				struct bpf_verifier_env *env,
12411  				int regno,
12412  				const struct bpf_reg_state *reg,
12413  				int off)
12414  {
12415  	if (!tnum_is_const(reg->var_off)) {
12416  		char tn_buf[48];
12417  
12418  		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12419  		verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12420  			regno, tn_buf, off);
12421  		return -EACCES;
12422  	}
12423  
12424  	if (off >= 0 || off < -MAX_BPF_STACK) {
12425  		verbose(env, "R%d stack pointer arithmetic goes out of range, "
12426  			"prohibited for !root; off=%d\n", regno, off);
12427  		return -EACCES;
12428  	}
12429  
12430  	return 0;
12431  }
12432  
sanitize_check_bounds(struct bpf_verifier_env * env,const struct bpf_insn * insn,const struct bpf_reg_state * dst_reg)12433  static int sanitize_check_bounds(struct bpf_verifier_env *env,
12434  				 const struct bpf_insn *insn,
12435  				 const struct bpf_reg_state *dst_reg)
12436  {
12437  	u32 dst = insn->dst_reg;
12438  
12439  	/* For unprivileged we require that resulting offset must be in bounds
12440  	 * in order to be able to sanitize access later on.
12441  	 */
12442  	if (env->bypass_spec_v1)
12443  		return 0;
12444  
12445  	switch (dst_reg->type) {
12446  	case PTR_TO_STACK:
12447  		if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12448  					dst_reg->off + dst_reg->var_off.value))
12449  			return -EACCES;
12450  		break;
12451  	case PTR_TO_MAP_VALUE:
12452  		if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12453  			verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12454  				"prohibited for !root\n", dst);
12455  			return -EACCES;
12456  		}
12457  		break;
12458  	default:
12459  		break;
12460  	}
12461  
12462  	return 0;
12463  }
12464  
12465  /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12466   * Caller should also handle BPF_MOV case separately.
12467   * If we return -EACCES, caller may want to try again treating pointer as a
12468   * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12469   */
adjust_ptr_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn,const struct bpf_reg_state * ptr_reg,const struct bpf_reg_state * off_reg)12470  static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12471  				   struct bpf_insn *insn,
12472  				   const struct bpf_reg_state *ptr_reg,
12473  				   const struct bpf_reg_state *off_reg)
12474  {
12475  	struct bpf_verifier_state *vstate = env->cur_state;
12476  	struct bpf_func_state *state = vstate->frame[vstate->curframe];
12477  	struct bpf_reg_state *regs = state->regs, *dst_reg;
12478  	bool known = tnum_is_const(off_reg->var_off);
12479  	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12480  	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12481  	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12482  	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12483  	struct bpf_sanitize_info info = {};
12484  	u8 opcode = BPF_OP(insn->code);
12485  	u32 dst = insn->dst_reg;
12486  	int ret;
12487  
12488  	dst_reg = &regs[dst];
12489  
12490  	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12491  	    smin_val > smax_val || umin_val > umax_val) {
12492  		/* Taint dst register if offset had invalid bounds derived from
12493  		 * e.g. dead branches.
12494  		 */
12495  		__mark_reg_unknown(env, dst_reg);
12496  		return 0;
12497  	}
12498  
12499  	if (BPF_CLASS(insn->code) != BPF_ALU64) {
12500  		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
12501  		if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12502  			__mark_reg_unknown(env, dst_reg);
12503  			return 0;
12504  		}
12505  
12506  		verbose(env,
12507  			"R%d 32-bit pointer arithmetic prohibited\n",
12508  			dst);
12509  		return -EACCES;
12510  	}
12511  
12512  	if (ptr_reg->type & PTR_MAYBE_NULL) {
12513  		verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12514  			dst, reg_type_str(env, ptr_reg->type));
12515  		return -EACCES;
12516  	}
12517  
12518  	switch (base_type(ptr_reg->type)) {
12519  	case PTR_TO_FLOW_KEYS:
12520  		if (known)
12521  			break;
12522  		fallthrough;
12523  	case CONST_PTR_TO_MAP:
12524  		/* smin_val represents the known value */
12525  		if (known && smin_val == 0 && opcode == BPF_ADD)
12526  			break;
12527  		fallthrough;
12528  	case PTR_TO_PACKET_END:
12529  	case PTR_TO_SOCKET:
12530  	case PTR_TO_SOCK_COMMON:
12531  	case PTR_TO_TCP_SOCK:
12532  	case PTR_TO_XDP_SOCK:
12533  		verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12534  			dst, reg_type_str(env, ptr_reg->type));
12535  		return -EACCES;
12536  	default:
12537  		break;
12538  	}
12539  
12540  	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12541  	 * The id may be overwritten later if we create a new variable offset.
12542  	 */
12543  	dst_reg->type = ptr_reg->type;
12544  	dst_reg->id = ptr_reg->id;
12545  
12546  	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12547  	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12548  		return -EINVAL;
12549  
12550  	/* pointer types do not carry 32-bit bounds at the moment. */
12551  	__mark_reg32_unbounded(dst_reg);
12552  
12553  	if (sanitize_needed(opcode)) {
12554  		ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12555  				       &info, false);
12556  		if (ret < 0)
12557  			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12558  	}
12559  
12560  	switch (opcode) {
12561  	case BPF_ADD:
12562  		/* We can take a fixed offset as long as it doesn't overflow
12563  		 * the s32 'off' field
12564  		 */
12565  		if (known && (ptr_reg->off + smin_val ==
12566  			      (s64)(s32)(ptr_reg->off + smin_val))) {
12567  			/* pointer += K.  Accumulate it into fixed offset */
12568  			dst_reg->smin_value = smin_ptr;
12569  			dst_reg->smax_value = smax_ptr;
12570  			dst_reg->umin_value = umin_ptr;
12571  			dst_reg->umax_value = umax_ptr;
12572  			dst_reg->var_off = ptr_reg->var_off;
12573  			dst_reg->off = ptr_reg->off + smin_val;
12574  			dst_reg->raw = ptr_reg->raw;
12575  			break;
12576  		}
12577  		/* A new variable offset is created.  Note that off_reg->off
12578  		 * == 0, since it's a scalar.
12579  		 * dst_reg gets the pointer type and since some positive
12580  		 * integer value was added to the pointer, give it a new 'id'
12581  		 * if it's a PTR_TO_PACKET.
12582  		 * this creates a new 'base' pointer, off_reg (variable) gets
12583  		 * added into the variable offset, and we copy the fixed offset
12584  		 * from ptr_reg.
12585  		 */
12586  		if (signed_add_overflows(smin_ptr, smin_val) ||
12587  		    signed_add_overflows(smax_ptr, smax_val)) {
12588  			dst_reg->smin_value = S64_MIN;
12589  			dst_reg->smax_value = S64_MAX;
12590  		} else {
12591  			dst_reg->smin_value = smin_ptr + smin_val;
12592  			dst_reg->smax_value = smax_ptr + smax_val;
12593  		}
12594  		if (umin_ptr + umin_val < umin_ptr ||
12595  		    umax_ptr + umax_val < umax_ptr) {
12596  			dst_reg->umin_value = 0;
12597  			dst_reg->umax_value = U64_MAX;
12598  		} else {
12599  			dst_reg->umin_value = umin_ptr + umin_val;
12600  			dst_reg->umax_value = umax_ptr + umax_val;
12601  		}
12602  		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12603  		dst_reg->off = ptr_reg->off;
12604  		dst_reg->raw = ptr_reg->raw;
12605  		if (reg_is_pkt_pointer(ptr_reg)) {
12606  			dst_reg->id = ++env->id_gen;
12607  			/* something was added to pkt_ptr, set range to zero */
12608  			memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12609  		}
12610  		break;
12611  	case BPF_SUB:
12612  		if (dst_reg == off_reg) {
12613  			/* scalar -= pointer.  Creates an unknown scalar */
12614  			verbose(env, "R%d tried to subtract pointer from scalar\n",
12615  				dst);
12616  			return -EACCES;
12617  		}
12618  		/* We don't allow subtraction from FP, because (according to
12619  		 * test_verifier.c test "invalid fp arithmetic", JITs might not
12620  		 * be able to deal with it.
12621  		 */
12622  		if (ptr_reg->type == PTR_TO_STACK) {
12623  			verbose(env, "R%d subtraction from stack pointer prohibited\n",
12624  				dst);
12625  			return -EACCES;
12626  		}
12627  		if (known && (ptr_reg->off - smin_val ==
12628  			      (s64)(s32)(ptr_reg->off - smin_val))) {
12629  			/* pointer -= K.  Subtract it from fixed offset */
12630  			dst_reg->smin_value = smin_ptr;
12631  			dst_reg->smax_value = smax_ptr;
12632  			dst_reg->umin_value = umin_ptr;
12633  			dst_reg->umax_value = umax_ptr;
12634  			dst_reg->var_off = ptr_reg->var_off;
12635  			dst_reg->id = ptr_reg->id;
12636  			dst_reg->off = ptr_reg->off - smin_val;
12637  			dst_reg->raw = ptr_reg->raw;
12638  			break;
12639  		}
12640  		/* A new variable offset is created.  If the subtrahend is known
12641  		 * nonnegative, then any reg->range we had before is still good.
12642  		 */
12643  		if (signed_sub_overflows(smin_ptr, smax_val) ||
12644  		    signed_sub_overflows(smax_ptr, smin_val)) {
12645  			/* Overflow possible, we know nothing */
12646  			dst_reg->smin_value = S64_MIN;
12647  			dst_reg->smax_value = S64_MAX;
12648  		} else {
12649  			dst_reg->smin_value = smin_ptr - smax_val;
12650  			dst_reg->smax_value = smax_ptr - smin_val;
12651  		}
12652  		if (umin_ptr < umax_val) {
12653  			/* Overflow possible, we know nothing */
12654  			dst_reg->umin_value = 0;
12655  			dst_reg->umax_value = U64_MAX;
12656  		} else {
12657  			/* Cannot overflow (as long as bounds are consistent) */
12658  			dst_reg->umin_value = umin_ptr - umax_val;
12659  			dst_reg->umax_value = umax_ptr - umin_val;
12660  		}
12661  		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12662  		dst_reg->off = ptr_reg->off;
12663  		dst_reg->raw = ptr_reg->raw;
12664  		if (reg_is_pkt_pointer(ptr_reg)) {
12665  			dst_reg->id = ++env->id_gen;
12666  			/* something was added to pkt_ptr, set range to zero */
12667  			if (smin_val < 0)
12668  				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12669  		}
12670  		break;
12671  	case BPF_AND:
12672  	case BPF_OR:
12673  	case BPF_XOR:
12674  		/* bitwise ops on pointers are troublesome, prohibit. */
12675  		verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12676  			dst, bpf_alu_string[opcode >> 4]);
12677  		return -EACCES;
12678  	default:
12679  		/* other operators (e.g. MUL,LSH) produce non-pointer results */
12680  		verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12681  			dst, bpf_alu_string[opcode >> 4]);
12682  		return -EACCES;
12683  	}
12684  
12685  	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12686  		return -EINVAL;
12687  	reg_bounds_sync(dst_reg);
12688  	if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12689  		return -EACCES;
12690  	if (sanitize_needed(opcode)) {
12691  		ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12692  				       &info, true);
12693  		if (ret < 0)
12694  			return sanitize_err(env, insn, ret, off_reg, dst_reg);
12695  	}
12696  
12697  	return 0;
12698  }
12699  
scalar32_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12700  static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12701  				 struct bpf_reg_state *src_reg)
12702  {
12703  	s32 smin_val = src_reg->s32_min_value;
12704  	s32 smax_val = src_reg->s32_max_value;
12705  	u32 umin_val = src_reg->u32_min_value;
12706  	u32 umax_val = src_reg->u32_max_value;
12707  
12708  	if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12709  	    signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12710  		dst_reg->s32_min_value = S32_MIN;
12711  		dst_reg->s32_max_value = S32_MAX;
12712  	} else {
12713  		dst_reg->s32_min_value += smin_val;
12714  		dst_reg->s32_max_value += smax_val;
12715  	}
12716  	if (dst_reg->u32_min_value + umin_val < umin_val ||
12717  	    dst_reg->u32_max_value + umax_val < umax_val) {
12718  		dst_reg->u32_min_value = 0;
12719  		dst_reg->u32_max_value = U32_MAX;
12720  	} else {
12721  		dst_reg->u32_min_value += umin_val;
12722  		dst_reg->u32_max_value += umax_val;
12723  	}
12724  }
12725  
scalar_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12726  static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12727  			       struct bpf_reg_state *src_reg)
12728  {
12729  	s64 smin_val = src_reg->smin_value;
12730  	s64 smax_val = src_reg->smax_value;
12731  	u64 umin_val = src_reg->umin_value;
12732  	u64 umax_val = src_reg->umax_value;
12733  
12734  	if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12735  	    signed_add_overflows(dst_reg->smax_value, smax_val)) {
12736  		dst_reg->smin_value = S64_MIN;
12737  		dst_reg->smax_value = S64_MAX;
12738  	} else {
12739  		dst_reg->smin_value += smin_val;
12740  		dst_reg->smax_value += smax_val;
12741  	}
12742  	if (dst_reg->umin_value + umin_val < umin_val ||
12743  	    dst_reg->umax_value + umax_val < umax_val) {
12744  		dst_reg->umin_value = 0;
12745  		dst_reg->umax_value = U64_MAX;
12746  	} else {
12747  		dst_reg->umin_value += umin_val;
12748  		dst_reg->umax_value += umax_val;
12749  	}
12750  }
12751  
scalar32_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12752  static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12753  				 struct bpf_reg_state *src_reg)
12754  {
12755  	s32 smin_val = src_reg->s32_min_value;
12756  	s32 smax_val = src_reg->s32_max_value;
12757  	u32 umin_val = src_reg->u32_min_value;
12758  	u32 umax_val = src_reg->u32_max_value;
12759  
12760  	if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12761  	    signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12762  		/* Overflow possible, we know nothing */
12763  		dst_reg->s32_min_value = S32_MIN;
12764  		dst_reg->s32_max_value = S32_MAX;
12765  	} else {
12766  		dst_reg->s32_min_value -= smax_val;
12767  		dst_reg->s32_max_value -= smin_val;
12768  	}
12769  	if (dst_reg->u32_min_value < umax_val) {
12770  		/* Overflow possible, we know nothing */
12771  		dst_reg->u32_min_value = 0;
12772  		dst_reg->u32_max_value = U32_MAX;
12773  	} else {
12774  		/* Cannot overflow (as long as bounds are consistent) */
12775  		dst_reg->u32_min_value -= umax_val;
12776  		dst_reg->u32_max_value -= umin_val;
12777  	}
12778  }
12779  
scalar_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12780  static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12781  			       struct bpf_reg_state *src_reg)
12782  {
12783  	s64 smin_val = src_reg->smin_value;
12784  	s64 smax_val = src_reg->smax_value;
12785  	u64 umin_val = src_reg->umin_value;
12786  	u64 umax_val = src_reg->umax_value;
12787  
12788  	if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12789  	    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12790  		/* Overflow possible, we know nothing */
12791  		dst_reg->smin_value = S64_MIN;
12792  		dst_reg->smax_value = S64_MAX;
12793  	} else {
12794  		dst_reg->smin_value -= smax_val;
12795  		dst_reg->smax_value -= smin_val;
12796  	}
12797  	if (dst_reg->umin_value < umax_val) {
12798  		/* Overflow possible, we know nothing */
12799  		dst_reg->umin_value = 0;
12800  		dst_reg->umax_value = U64_MAX;
12801  	} else {
12802  		/* Cannot overflow (as long as bounds are consistent) */
12803  		dst_reg->umin_value -= umax_val;
12804  		dst_reg->umax_value -= umin_val;
12805  	}
12806  }
12807  
scalar32_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12808  static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12809  				 struct bpf_reg_state *src_reg)
12810  {
12811  	s32 smin_val = src_reg->s32_min_value;
12812  	u32 umin_val = src_reg->u32_min_value;
12813  	u32 umax_val = src_reg->u32_max_value;
12814  
12815  	if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12816  		/* Ain't nobody got time to multiply that sign */
12817  		__mark_reg32_unbounded(dst_reg);
12818  		return;
12819  	}
12820  	/* Both values are positive, so we can work with unsigned and
12821  	 * copy the result to signed (unless it exceeds S32_MAX).
12822  	 */
12823  	if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12824  		/* Potential overflow, we know nothing */
12825  		__mark_reg32_unbounded(dst_reg);
12826  		return;
12827  	}
12828  	dst_reg->u32_min_value *= umin_val;
12829  	dst_reg->u32_max_value *= umax_val;
12830  	if (dst_reg->u32_max_value > S32_MAX) {
12831  		/* Overflow possible, we know nothing */
12832  		dst_reg->s32_min_value = S32_MIN;
12833  		dst_reg->s32_max_value = S32_MAX;
12834  	} else {
12835  		dst_reg->s32_min_value = dst_reg->u32_min_value;
12836  		dst_reg->s32_max_value = dst_reg->u32_max_value;
12837  	}
12838  }
12839  
scalar_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12840  static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12841  			       struct bpf_reg_state *src_reg)
12842  {
12843  	s64 smin_val = src_reg->smin_value;
12844  	u64 umin_val = src_reg->umin_value;
12845  	u64 umax_val = src_reg->umax_value;
12846  
12847  	if (smin_val < 0 || dst_reg->smin_value < 0) {
12848  		/* Ain't nobody got time to multiply that sign */
12849  		__mark_reg64_unbounded(dst_reg);
12850  		return;
12851  	}
12852  	/* Both values are positive, so we can work with unsigned and
12853  	 * copy the result to signed (unless it exceeds S64_MAX).
12854  	 */
12855  	if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12856  		/* Potential overflow, we know nothing */
12857  		__mark_reg64_unbounded(dst_reg);
12858  		return;
12859  	}
12860  	dst_reg->umin_value *= umin_val;
12861  	dst_reg->umax_value *= umax_val;
12862  	if (dst_reg->umax_value > S64_MAX) {
12863  		/* Overflow possible, we know nothing */
12864  		dst_reg->smin_value = S64_MIN;
12865  		dst_reg->smax_value = S64_MAX;
12866  	} else {
12867  		dst_reg->smin_value = dst_reg->umin_value;
12868  		dst_reg->smax_value = dst_reg->umax_value;
12869  	}
12870  }
12871  
scalar32_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12872  static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12873  				 struct bpf_reg_state *src_reg)
12874  {
12875  	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12876  	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12877  	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12878  	s32 smin_val = src_reg->s32_min_value;
12879  	u32 umax_val = src_reg->u32_max_value;
12880  
12881  	if (src_known && dst_known) {
12882  		__mark_reg32_known(dst_reg, var32_off.value);
12883  		return;
12884  	}
12885  
12886  	/* We get our minimum from the var_off, since that's inherently
12887  	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12888  	 */
12889  	dst_reg->u32_min_value = var32_off.value;
12890  	dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12891  	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12892  		/* Lose signed bounds when ANDing negative numbers,
12893  		 * ain't nobody got time for that.
12894  		 */
12895  		dst_reg->s32_min_value = S32_MIN;
12896  		dst_reg->s32_max_value = S32_MAX;
12897  	} else {
12898  		/* ANDing two positives gives a positive, so safe to
12899  		 * cast result into s64.
12900  		 */
12901  		dst_reg->s32_min_value = dst_reg->u32_min_value;
12902  		dst_reg->s32_max_value = dst_reg->u32_max_value;
12903  	}
12904  }
12905  
scalar_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12906  static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12907  			       struct bpf_reg_state *src_reg)
12908  {
12909  	bool src_known = tnum_is_const(src_reg->var_off);
12910  	bool dst_known = tnum_is_const(dst_reg->var_off);
12911  	s64 smin_val = src_reg->smin_value;
12912  	u64 umax_val = src_reg->umax_value;
12913  
12914  	if (src_known && dst_known) {
12915  		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12916  		return;
12917  	}
12918  
12919  	/* We get our minimum from the var_off, since that's inherently
12920  	 * bitwise.  Our maximum is the minimum of the operands' maxima.
12921  	 */
12922  	dst_reg->umin_value = dst_reg->var_off.value;
12923  	dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12924  	if (dst_reg->smin_value < 0 || smin_val < 0) {
12925  		/* Lose signed bounds when ANDing negative numbers,
12926  		 * ain't nobody got time for that.
12927  		 */
12928  		dst_reg->smin_value = S64_MIN;
12929  		dst_reg->smax_value = S64_MAX;
12930  	} else {
12931  		/* ANDing two positives gives a positive, so safe to
12932  		 * cast result into s64.
12933  		 */
12934  		dst_reg->smin_value = dst_reg->umin_value;
12935  		dst_reg->smax_value = dst_reg->umax_value;
12936  	}
12937  	/* We may learn something more from the var_off */
12938  	__update_reg_bounds(dst_reg);
12939  }
12940  
scalar32_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12941  static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12942  				struct bpf_reg_state *src_reg)
12943  {
12944  	bool src_known = tnum_subreg_is_const(src_reg->var_off);
12945  	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12946  	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12947  	s32 smin_val = src_reg->s32_min_value;
12948  	u32 umin_val = src_reg->u32_min_value;
12949  
12950  	if (src_known && dst_known) {
12951  		__mark_reg32_known(dst_reg, var32_off.value);
12952  		return;
12953  	}
12954  
12955  	/* We get our maximum from the var_off, and our minimum is the
12956  	 * maximum of the operands' minima
12957  	 */
12958  	dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12959  	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12960  	if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12961  		/* Lose signed bounds when ORing negative numbers,
12962  		 * ain't nobody got time for that.
12963  		 */
12964  		dst_reg->s32_min_value = S32_MIN;
12965  		dst_reg->s32_max_value = S32_MAX;
12966  	} else {
12967  		/* ORing two positives gives a positive, so safe to
12968  		 * cast result into s64.
12969  		 */
12970  		dst_reg->s32_min_value = dst_reg->u32_min_value;
12971  		dst_reg->s32_max_value = dst_reg->u32_max_value;
12972  	}
12973  }
12974  
scalar_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12975  static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12976  			      struct bpf_reg_state *src_reg)
12977  {
12978  	bool src_known = tnum_is_const(src_reg->var_off);
12979  	bool dst_known = tnum_is_const(dst_reg->var_off);
12980  	s64 smin_val = src_reg->smin_value;
12981  	u64 umin_val = src_reg->umin_value;
12982  
12983  	if (src_known && dst_known) {
12984  		__mark_reg_known(dst_reg, dst_reg->var_off.value);
12985  		return;
12986  	}
12987  
12988  	/* We get our maximum from the var_off, and our minimum is the
12989  	 * maximum of the operands' minima
12990  	 */
12991  	dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12992  	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12993  	if (dst_reg->smin_value < 0 || smin_val < 0) {
12994  		/* Lose signed bounds when ORing negative numbers,
12995  		 * ain't nobody got time for that.
12996  		 */
12997  		dst_reg->smin_value = S64_MIN;
12998  		dst_reg->smax_value = S64_MAX;
12999  	} else {
13000  		/* ORing two positives gives a positive, so safe to
13001  		 * cast result into s64.
13002  		 */
13003  		dst_reg->smin_value = dst_reg->umin_value;
13004  		dst_reg->smax_value = dst_reg->umax_value;
13005  	}
13006  	/* We may learn something more from the var_off */
13007  	__update_reg_bounds(dst_reg);
13008  }
13009  
scalar32_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13010  static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13011  				 struct bpf_reg_state *src_reg)
13012  {
13013  	bool src_known = tnum_subreg_is_const(src_reg->var_off);
13014  	bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13015  	struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13016  	s32 smin_val = src_reg->s32_min_value;
13017  
13018  	if (src_known && dst_known) {
13019  		__mark_reg32_known(dst_reg, var32_off.value);
13020  		return;
13021  	}
13022  
13023  	/* We get both minimum and maximum from the var32_off. */
13024  	dst_reg->u32_min_value = var32_off.value;
13025  	dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13026  
13027  	if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13028  		/* XORing two positive sign numbers gives a positive,
13029  		 * so safe to cast u32 result into s32.
13030  		 */
13031  		dst_reg->s32_min_value = dst_reg->u32_min_value;
13032  		dst_reg->s32_max_value = dst_reg->u32_max_value;
13033  	} else {
13034  		dst_reg->s32_min_value = S32_MIN;
13035  		dst_reg->s32_max_value = S32_MAX;
13036  	}
13037  }
13038  
scalar_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13039  static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13040  			       struct bpf_reg_state *src_reg)
13041  {
13042  	bool src_known = tnum_is_const(src_reg->var_off);
13043  	bool dst_known = tnum_is_const(dst_reg->var_off);
13044  	s64 smin_val = src_reg->smin_value;
13045  
13046  	if (src_known && dst_known) {
13047  		/* dst_reg->var_off.value has been updated earlier */
13048  		__mark_reg_known(dst_reg, dst_reg->var_off.value);
13049  		return;
13050  	}
13051  
13052  	/* We get both minimum and maximum from the var_off. */
13053  	dst_reg->umin_value = dst_reg->var_off.value;
13054  	dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13055  
13056  	if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13057  		/* XORing two positive sign numbers gives a positive,
13058  		 * so safe to cast u64 result into s64.
13059  		 */
13060  		dst_reg->smin_value = dst_reg->umin_value;
13061  		dst_reg->smax_value = dst_reg->umax_value;
13062  	} else {
13063  		dst_reg->smin_value = S64_MIN;
13064  		dst_reg->smax_value = S64_MAX;
13065  	}
13066  
13067  	__update_reg_bounds(dst_reg);
13068  }
13069  
__scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)13070  static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13071  				   u64 umin_val, u64 umax_val)
13072  {
13073  	/* We lose all sign bit information (except what we can pick
13074  	 * up from var_off)
13075  	 */
13076  	dst_reg->s32_min_value = S32_MIN;
13077  	dst_reg->s32_max_value = S32_MAX;
13078  	/* If we might shift our top bit out, then we know nothing */
13079  	if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13080  		dst_reg->u32_min_value = 0;
13081  		dst_reg->u32_max_value = U32_MAX;
13082  	} else {
13083  		dst_reg->u32_min_value <<= umin_val;
13084  		dst_reg->u32_max_value <<= umax_val;
13085  	}
13086  }
13087  
scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13088  static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13089  				 struct bpf_reg_state *src_reg)
13090  {
13091  	u32 umax_val = src_reg->u32_max_value;
13092  	u32 umin_val = src_reg->u32_min_value;
13093  	/* u32 alu operation will zext upper bits */
13094  	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13095  
13096  	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13097  	dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13098  	/* Not required but being careful mark reg64 bounds as unknown so
13099  	 * that we are forced to pick them up from tnum and zext later and
13100  	 * if some path skips this step we are still safe.
13101  	 */
13102  	__mark_reg64_unbounded(dst_reg);
13103  	__update_reg32_bounds(dst_reg);
13104  }
13105  
__scalar64_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)13106  static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13107  				   u64 umin_val, u64 umax_val)
13108  {
13109  	/* Special case <<32 because it is a common compiler pattern to sign
13110  	 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13111  	 * positive we know this shift will also be positive so we can track
13112  	 * bounds correctly. Otherwise we lose all sign bit information except
13113  	 * what we can pick up from var_off. Perhaps we can generalize this
13114  	 * later to shifts of any length.
13115  	 */
13116  	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13117  		dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13118  	else
13119  		dst_reg->smax_value = S64_MAX;
13120  
13121  	if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13122  		dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13123  	else
13124  		dst_reg->smin_value = S64_MIN;
13125  
13126  	/* If we might shift our top bit out, then we know nothing */
13127  	if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13128  		dst_reg->umin_value = 0;
13129  		dst_reg->umax_value = U64_MAX;
13130  	} else {
13131  		dst_reg->umin_value <<= umin_val;
13132  		dst_reg->umax_value <<= umax_val;
13133  	}
13134  }
13135  
scalar_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13136  static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13137  			       struct bpf_reg_state *src_reg)
13138  {
13139  	u64 umax_val = src_reg->umax_value;
13140  	u64 umin_val = src_reg->umin_value;
13141  
13142  	/* scalar64 calc uses 32bit unshifted bounds so must be called first */
13143  	__scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13144  	__scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13145  
13146  	dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13147  	/* We may learn something more from the var_off */
13148  	__update_reg_bounds(dst_reg);
13149  }
13150  
scalar32_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13151  static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13152  				 struct bpf_reg_state *src_reg)
13153  {
13154  	struct tnum subreg = tnum_subreg(dst_reg->var_off);
13155  	u32 umax_val = src_reg->u32_max_value;
13156  	u32 umin_val = src_reg->u32_min_value;
13157  
13158  	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13159  	 * be negative, then either:
13160  	 * 1) src_reg might be zero, so the sign bit of the result is
13161  	 *    unknown, so we lose our signed bounds
13162  	 * 2) it's known negative, thus the unsigned bounds capture the
13163  	 *    signed bounds
13164  	 * 3) the signed bounds cross zero, so they tell us nothing
13165  	 *    about the result
13166  	 * If the value in dst_reg is known nonnegative, then again the
13167  	 * unsigned bounds capture the signed bounds.
13168  	 * Thus, in all cases it suffices to blow away our signed bounds
13169  	 * and rely on inferring new ones from the unsigned bounds and
13170  	 * var_off of the result.
13171  	 */
13172  	dst_reg->s32_min_value = S32_MIN;
13173  	dst_reg->s32_max_value = S32_MAX;
13174  
13175  	dst_reg->var_off = tnum_rshift(subreg, umin_val);
13176  	dst_reg->u32_min_value >>= umax_val;
13177  	dst_reg->u32_max_value >>= umin_val;
13178  
13179  	__mark_reg64_unbounded(dst_reg);
13180  	__update_reg32_bounds(dst_reg);
13181  }
13182  
scalar_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13183  static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13184  			       struct bpf_reg_state *src_reg)
13185  {
13186  	u64 umax_val = src_reg->umax_value;
13187  	u64 umin_val = src_reg->umin_value;
13188  
13189  	/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13190  	 * be negative, then either:
13191  	 * 1) src_reg might be zero, so the sign bit of the result is
13192  	 *    unknown, so we lose our signed bounds
13193  	 * 2) it's known negative, thus the unsigned bounds capture the
13194  	 *    signed bounds
13195  	 * 3) the signed bounds cross zero, so they tell us nothing
13196  	 *    about the result
13197  	 * If the value in dst_reg is known nonnegative, then again the
13198  	 * unsigned bounds capture the signed bounds.
13199  	 * Thus, in all cases it suffices to blow away our signed bounds
13200  	 * and rely on inferring new ones from the unsigned bounds and
13201  	 * var_off of the result.
13202  	 */
13203  	dst_reg->smin_value = S64_MIN;
13204  	dst_reg->smax_value = S64_MAX;
13205  	dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13206  	dst_reg->umin_value >>= umax_val;
13207  	dst_reg->umax_value >>= umin_val;
13208  
13209  	/* Its not easy to operate on alu32 bounds here because it depends
13210  	 * on bits being shifted in. Take easy way out and mark unbounded
13211  	 * so we can recalculate later from tnum.
13212  	 */
13213  	__mark_reg32_unbounded(dst_reg);
13214  	__update_reg_bounds(dst_reg);
13215  }
13216  
scalar32_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13217  static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13218  				  struct bpf_reg_state *src_reg)
13219  {
13220  	u64 umin_val = src_reg->u32_min_value;
13221  
13222  	/* Upon reaching here, src_known is true and
13223  	 * umax_val is equal to umin_val.
13224  	 */
13225  	dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13226  	dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13227  
13228  	dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13229  
13230  	/* blow away the dst_reg umin_value/umax_value and rely on
13231  	 * dst_reg var_off to refine the result.
13232  	 */
13233  	dst_reg->u32_min_value = 0;
13234  	dst_reg->u32_max_value = U32_MAX;
13235  
13236  	__mark_reg64_unbounded(dst_reg);
13237  	__update_reg32_bounds(dst_reg);
13238  }
13239  
scalar_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13240  static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13241  				struct bpf_reg_state *src_reg)
13242  {
13243  	u64 umin_val = src_reg->umin_value;
13244  
13245  	/* Upon reaching here, src_known is true and umax_val is equal
13246  	 * to umin_val.
13247  	 */
13248  	dst_reg->smin_value >>= umin_val;
13249  	dst_reg->smax_value >>= umin_val;
13250  
13251  	dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13252  
13253  	/* blow away the dst_reg umin_value/umax_value and rely on
13254  	 * dst_reg var_off to refine the result.
13255  	 */
13256  	dst_reg->umin_value = 0;
13257  	dst_reg->umax_value = U64_MAX;
13258  
13259  	/* Its not easy to operate on alu32 bounds here because it depends
13260  	 * on bits being shifted in from upper 32-bits. Take easy way out
13261  	 * and mark unbounded so we can recalculate later from tnum.
13262  	 */
13263  	__mark_reg32_unbounded(dst_reg);
13264  	__update_reg_bounds(dst_reg);
13265  }
13266  
13267  /* WARNING: This function does calculations on 64-bit values, but the actual
13268   * execution may occur on 32-bit values. Therefore, things like bitshifts
13269   * need extra checks in the 32-bit case.
13270   */
adjust_scalar_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_reg_state * dst_reg,struct bpf_reg_state src_reg)13271  static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13272  				      struct bpf_insn *insn,
13273  				      struct bpf_reg_state *dst_reg,
13274  				      struct bpf_reg_state src_reg)
13275  {
13276  	struct bpf_reg_state *regs = cur_regs(env);
13277  	u8 opcode = BPF_OP(insn->code);
13278  	bool src_known;
13279  	s64 smin_val, smax_val;
13280  	u64 umin_val, umax_val;
13281  	s32 s32_min_val, s32_max_val;
13282  	u32 u32_min_val, u32_max_val;
13283  	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13284  	bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13285  	int ret;
13286  
13287  	smin_val = src_reg.smin_value;
13288  	smax_val = src_reg.smax_value;
13289  	umin_val = src_reg.umin_value;
13290  	umax_val = src_reg.umax_value;
13291  
13292  	s32_min_val = src_reg.s32_min_value;
13293  	s32_max_val = src_reg.s32_max_value;
13294  	u32_min_val = src_reg.u32_min_value;
13295  	u32_max_val = src_reg.u32_max_value;
13296  
13297  	if (alu32) {
13298  		src_known = tnum_subreg_is_const(src_reg.var_off);
13299  		if ((src_known &&
13300  		     (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13301  		    s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13302  			/* Taint dst register if offset had invalid bounds
13303  			 * derived from e.g. dead branches.
13304  			 */
13305  			__mark_reg_unknown(env, dst_reg);
13306  			return 0;
13307  		}
13308  	} else {
13309  		src_known = tnum_is_const(src_reg.var_off);
13310  		if ((src_known &&
13311  		     (smin_val != smax_val || umin_val != umax_val)) ||
13312  		    smin_val > smax_val || umin_val > umax_val) {
13313  			/* Taint dst register if offset had invalid bounds
13314  			 * derived from e.g. dead branches.
13315  			 */
13316  			__mark_reg_unknown(env, dst_reg);
13317  			return 0;
13318  		}
13319  	}
13320  
13321  	if (!src_known &&
13322  	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13323  		__mark_reg_unknown(env, dst_reg);
13324  		return 0;
13325  	}
13326  
13327  	if (sanitize_needed(opcode)) {
13328  		ret = sanitize_val_alu(env, insn);
13329  		if (ret < 0)
13330  			return sanitize_err(env, insn, ret, NULL, NULL);
13331  	}
13332  
13333  	/* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13334  	 * There are two classes of instructions: The first class we track both
13335  	 * alu32 and alu64 sign/unsigned bounds independently this provides the
13336  	 * greatest amount of precision when alu operations are mixed with jmp32
13337  	 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13338  	 * and BPF_OR. This is possible because these ops have fairly easy to
13339  	 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13340  	 * See alu32 verifier tests for examples. The second class of
13341  	 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13342  	 * with regards to tracking sign/unsigned bounds because the bits may
13343  	 * cross subreg boundaries in the alu64 case. When this happens we mark
13344  	 * the reg unbounded in the subreg bound space and use the resulting
13345  	 * tnum to calculate an approximation of the sign/unsigned bounds.
13346  	 */
13347  	switch (opcode) {
13348  	case BPF_ADD:
13349  		scalar32_min_max_add(dst_reg, &src_reg);
13350  		scalar_min_max_add(dst_reg, &src_reg);
13351  		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13352  		break;
13353  	case BPF_SUB:
13354  		scalar32_min_max_sub(dst_reg, &src_reg);
13355  		scalar_min_max_sub(dst_reg, &src_reg);
13356  		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13357  		break;
13358  	case BPF_MUL:
13359  		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13360  		scalar32_min_max_mul(dst_reg, &src_reg);
13361  		scalar_min_max_mul(dst_reg, &src_reg);
13362  		break;
13363  	case BPF_AND:
13364  		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13365  		scalar32_min_max_and(dst_reg, &src_reg);
13366  		scalar_min_max_and(dst_reg, &src_reg);
13367  		break;
13368  	case BPF_OR:
13369  		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13370  		scalar32_min_max_or(dst_reg, &src_reg);
13371  		scalar_min_max_or(dst_reg, &src_reg);
13372  		break;
13373  	case BPF_XOR:
13374  		dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13375  		scalar32_min_max_xor(dst_reg, &src_reg);
13376  		scalar_min_max_xor(dst_reg, &src_reg);
13377  		break;
13378  	case BPF_LSH:
13379  		if (umax_val >= insn_bitness) {
13380  			/* Shifts greater than 31 or 63 are undefined.
13381  			 * This includes shifts by a negative number.
13382  			 */
13383  			mark_reg_unknown(env, regs, insn->dst_reg);
13384  			break;
13385  		}
13386  		if (alu32)
13387  			scalar32_min_max_lsh(dst_reg, &src_reg);
13388  		else
13389  			scalar_min_max_lsh(dst_reg, &src_reg);
13390  		break;
13391  	case BPF_RSH:
13392  		if (umax_val >= insn_bitness) {
13393  			/* Shifts greater than 31 or 63 are undefined.
13394  			 * This includes shifts by a negative number.
13395  			 */
13396  			mark_reg_unknown(env, regs, insn->dst_reg);
13397  			break;
13398  		}
13399  		if (alu32)
13400  			scalar32_min_max_rsh(dst_reg, &src_reg);
13401  		else
13402  			scalar_min_max_rsh(dst_reg, &src_reg);
13403  		break;
13404  	case BPF_ARSH:
13405  		if (umax_val >= insn_bitness) {
13406  			/* Shifts greater than 31 or 63 are undefined.
13407  			 * This includes shifts by a negative number.
13408  			 */
13409  			mark_reg_unknown(env, regs, insn->dst_reg);
13410  			break;
13411  		}
13412  		if (alu32)
13413  			scalar32_min_max_arsh(dst_reg, &src_reg);
13414  		else
13415  			scalar_min_max_arsh(dst_reg, &src_reg);
13416  		break;
13417  	default:
13418  		mark_reg_unknown(env, regs, insn->dst_reg);
13419  		break;
13420  	}
13421  
13422  	/* ALU32 ops are zero extended into 64bit register */
13423  	if (alu32)
13424  		zext_32_to_64(dst_reg);
13425  	reg_bounds_sync(dst_reg);
13426  	return 0;
13427  }
13428  
13429  /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13430   * and var_off.
13431   */
adjust_reg_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn)13432  static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13433  				   struct bpf_insn *insn)
13434  {
13435  	struct bpf_verifier_state *vstate = env->cur_state;
13436  	struct bpf_func_state *state = vstate->frame[vstate->curframe];
13437  	struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13438  	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13439  	u8 opcode = BPF_OP(insn->code);
13440  	int err;
13441  
13442  	dst_reg = &regs[insn->dst_reg];
13443  	src_reg = NULL;
13444  	if (dst_reg->type != SCALAR_VALUE)
13445  		ptr_reg = dst_reg;
13446  	else
13447  		/* Make sure ID is cleared otherwise dst_reg min/max could be
13448  		 * incorrectly propagated into other registers by find_equal_scalars()
13449  		 */
13450  		dst_reg->id = 0;
13451  	if (BPF_SRC(insn->code) == BPF_X) {
13452  		src_reg = &regs[insn->src_reg];
13453  		if (src_reg->type != SCALAR_VALUE) {
13454  			if (dst_reg->type != SCALAR_VALUE) {
13455  				/* Combining two pointers by any ALU op yields
13456  				 * an arbitrary scalar. Disallow all math except
13457  				 * pointer subtraction
13458  				 */
13459  				if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13460  					mark_reg_unknown(env, regs, insn->dst_reg);
13461  					return 0;
13462  				}
13463  				verbose(env, "R%d pointer %s pointer prohibited\n",
13464  					insn->dst_reg,
13465  					bpf_alu_string[opcode >> 4]);
13466  				return -EACCES;
13467  			} else {
13468  				/* scalar += pointer
13469  				 * This is legal, but we have to reverse our
13470  				 * src/dest handling in computing the range
13471  				 */
13472  				err = mark_chain_precision(env, insn->dst_reg);
13473  				if (err)
13474  					return err;
13475  				return adjust_ptr_min_max_vals(env, insn,
13476  							       src_reg, dst_reg);
13477  			}
13478  		} else if (ptr_reg) {
13479  			/* pointer += scalar */
13480  			err = mark_chain_precision(env, insn->src_reg);
13481  			if (err)
13482  				return err;
13483  			return adjust_ptr_min_max_vals(env, insn,
13484  						       dst_reg, src_reg);
13485  		} else if (dst_reg->precise) {
13486  			/* if dst_reg is precise, src_reg should be precise as well */
13487  			err = mark_chain_precision(env, insn->src_reg);
13488  			if (err)
13489  				return err;
13490  		}
13491  	} else {
13492  		/* Pretend the src is a reg with a known value, since we only
13493  		 * need to be able to read from this state.
13494  		 */
13495  		off_reg.type = SCALAR_VALUE;
13496  		__mark_reg_known(&off_reg, insn->imm);
13497  		src_reg = &off_reg;
13498  		if (ptr_reg) /* pointer += K */
13499  			return adjust_ptr_min_max_vals(env, insn,
13500  						       ptr_reg, src_reg);
13501  	}
13502  
13503  	/* Got here implies adding two SCALAR_VALUEs */
13504  	if (WARN_ON_ONCE(ptr_reg)) {
13505  		print_verifier_state(env, state, true);
13506  		verbose(env, "verifier internal error: unexpected ptr_reg\n");
13507  		return -EINVAL;
13508  	}
13509  	if (WARN_ON(!src_reg)) {
13510  		print_verifier_state(env, state, true);
13511  		verbose(env, "verifier internal error: no src_reg\n");
13512  		return -EINVAL;
13513  	}
13514  	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13515  }
13516  
13517  /* check validity of 32-bit and 64-bit arithmetic operations */
check_alu_op(struct bpf_verifier_env * env,struct bpf_insn * insn)13518  static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13519  {
13520  	struct bpf_reg_state *regs = cur_regs(env);
13521  	u8 opcode = BPF_OP(insn->code);
13522  	int err;
13523  
13524  	if (opcode == BPF_END || opcode == BPF_NEG) {
13525  		if (opcode == BPF_NEG) {
13526  			if (BPF_SRC(insn->code) != BPF_K ||
13527  			    insn->src_reg != BPF_REG_0 ||
13528  			    insn->off != 0 || insn->imm != 0) {
13529  				verbose(env, "BPF_NEG uses reserved fields\n");
13530  				return -EINVAL;
13531  			}
13532  		} else {
13533  			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13534  			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13535  			    (BPF_CLASS(insn->code) == BPF_ALU64 &&
13536  			     BPF_SRC(insn->code) != BPF_TO_LE)) {
13537  				verbose(env, "BPF_END uses reserved fields\n");
13538  				return -EINVAL;
13539  			}
13540  		}
13541  
13542  		/* check src operand */
13543  		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13544  		if (err)
13545  			return err;
13546  
13547  		if (is_pointer_value(env, insn->dst_reg)) {
13548  			verbose(env, "R%d pointer arithmetic prohibited\n",
13549  				insn->dst_reg);
13550  			return -EACCES;
13551  		}
13552  
13553  		/* check dest operand */
13554  		err = check_reg_arg(env, insn->dst_reg, DST_OP);
13555  		if (err)
13556  			return err;
13557  
13558  	} else if (opcode == BPF_MOV) {
13559  
13560  		if (BPF_SRC(insn->code) == BPF_X) {
13561  			if (insn->imm != 0) {
13562  				verbose(env, "BPF_MOV uses reserved fields\n");
13563  				return -EINVAL;
13564  			}
13565  
13566  			if (BPF_CLASS(insn->code) == BPF_ALU) {
13567  				if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13568  					verbose(env, "BPF_MOV uses reserved fields\n");
13569  					return -EINVAL;
13570  				}
13571  			} else {
13572  				if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13573  				    insn->off != 32) {
13574  					verbose(env, "BPF_MOV uses reserved fields\n");
13575  					return -EINVAL;
13576  				}
13577  			}
13578  
13579  			/* check src operand */
13580  			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13581  			if (err)
13582  				return err;
13583  		} else {
13584  			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13585  				verbose(env, "BPF_MOV uses reserved fields\n");
13586  				return -EINVAL;
13587  			}
13588  		}
13589  
13590  		/* check dest operand, mark as required later */
13591  		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13592  		if (err)
13593  			return err;
13594  
13595  		if (BPF_SRC(insn->code) == BPF_X) {
13596  			struct bpf_reg_state *src_reg = regs + insn->src_reg;
13597  			struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13598  			bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13599  				       !tnum_is_const(src_reg->var_off);
13600  
13601  			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13602  				if (insn->off == 0) {
13603  					/* case: R1 = R2
13604  					 * copy register state to dest reg
13605  					 */
13606  					if (need_id)
13607  						/* Assign src and dst registers the same ID
13608  						 * that will be used by find_equal_scalars()
13609  						 * to propagate min/max range.
13610  						 */
13611  						src_reg->id = ++env->id_gen;
13612  					copy_register_state(dst_reg, src_reg);
13613  					dst_reg->live |= REG_LIVE_WRITTEN;
13614  					dst_reg->subreg_def = DEF_NOT_SUBREG;
13615  				} else {
13616  					/* case: R1 = (s8, s16 s32)R2 */
13617  					if (is_pointer_value(env, insn->src_reg)) {
13618  						verbose(env,
13619  							"R%d sign-extension part of pointer\n",
13620  							insn->src_reg);
13621  						return -EACCES;
13622  					} else if (src_reg->type == SCALAR_VALUE) {
13623  						bool no_sext;
13624  
13625  						no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13626  						if (no_sext && need_id)
13627  							src_reg->id = ++env->id_gen;
13628  						copy_register_state(dst_reg, src_reg);
13629  						if (!no_sext)
13630  							dst_reg->id = 0;
13631  						coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13632  						dst_reg->live |= REG_LIVE_WRITTEN;
13633  						dst_reg->subreg_def = DEF_NOT_SUBREG;
13634  					} else {
13635  						mark_reg_unknown(env, regs, insn->dst_reg);
13636  					}
13637  				}
13638  			} else {
13639  				/* R1 = (u32) R2 */
13640  				if (is_pointer_value(env, insn->src_reg)) {
13641  					verbose(env,
13642  						"R%d partial copy of pointer\n",
13643  						insn->src_reg);
13644  					return -EACCES;
13645  				} else if (src_reg->type == SCALAR_VALUE) {
13646  					if (insn->off == 0) {
13647  						bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13648  
13649  						if (is_src_reg_u32 && need_id)
13650  							src_reg->id = ++env->id_gen;
13651  						copy_register_state(dst_reg, src_reg);
13652  						/* Make sure ID is cleared if src_reg is not in u32
13653  						 * range otherwise dst_reg min/max could be incorrectly
13654  						 * propagated into src_reg by find_equal_scalars()
13655  						 */
13656  						if (!is_src_reg_u32)
13657  							dst_reg->id = 0;
13658  						dst_reg->live |= REG_LIVE_WRITTEN;
13659  						dst_reg->subreg_def = env->insn_idx + 1;
13660  					} else {
13661  						/* case: W1 = (s8, s16)W2 */
13662  						bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13663  
13664  						if (no_sext && need_id)
13665  							src_reg->id = ++env->id_gen;
13666  						copy_register_state(dst_reg, src_reg);
13667  						if (!no_sext)
13668  							dst_reg->id = 0;
13669  						dst_reg->live |= REG_LIVE_WRITTEN;
13670  						dst_reg->subreg_def = env->insn_idx + 1;
13671  						coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13672  					}
13673  				} else {
13674  					mark_reg_unknown(env, regs,
13675  							 insn->dst_reg);
13676  				}
13677  				zext_32_to_64(dst_reg);
13678  				reg_bounds_sync(dst_reg);
13679  			}
13680  		} else {
13681  			/* case: R = imm
13682  			 * remember the value we stored into this reg
13683  			 */
13684  			/* clear any state __mark_reg_known doesn't set */
13685  			mark_reg_unknown(env, regs, insn->dst_reg);
13686  			regs[insn->dst_reg].type = SCALAR_VALUE;
13687  			if (BPF_CLASS(insn->code) == BPF_ALU64) {
13688  				__mark_reg_known(regs + insn->dst_reg,
13689  						 insn->imm);
13690  			} else {
13691  				__mark_reg_known(regs + insn->dst_reg,
13692  						 (u32)insn->imm);
13693  			}
13694  		}
13695  
13696  	} else if (opcode > BPF_END) {
13697  		verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13698  		return -EINVAL;
13699  
13700  	} else {	/* all other ALU ops: and, sub, xor, add, ... */
13701  
13702  		if (BPF_SRC(insn->code) == BPF_X) {
13703  			if (insn->imm != 0 || insn->off > 1 ||
13704  			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13705  				verbose(env, "BPF_ALU uses reserved fields\n");
13706  				return -EINVAL;
13707  			}
13708  			/* check src1 operand */
13709  			err = check_reg_arg(env, insn->src_reg, SRC_OP);
13710  			if (err)
13711  				return err;
13712  		} else {
13713  			if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13714  			    (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13715  				verbose(env, "BPF_ALU uses reserved fields\n");
13716  				return -EINVAL;
13717  			}
13718  		}
13719  
13720  		/* check src2 operand */
13721  		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13722  		if (err)
13723  			return err;
13724  
13725  		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13726  		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13727  			verbose(env, "div by zero\n");
13728  			return -EINVAL;
13729  		}
13730  
13731  		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13732  		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13733  			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13734  
13735  			if (insn->imm < 0 || insn->imm >= size) {
13736  				verbose(env, "invalid shift %d\n", insn->imm);
13737  				return -EINVAL;
13738  			}
13739  		}
13740  
13741  		/* check dest operand */
13742  		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13743  		if (err)
13744  			return err;
13745  
13746  		return adjust_reg_min_max_vals(env, insn);
13747  	}
13748  
13749  	return 0;
13750  }
13751  
find_good_pkt_pointers(struct bpf_verifier_state * vstate,struct bpf_reg_state * dst_reg,enum bpf_reg_type type,bool range_right_open)13752  static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13753  				   struct bpf_reg_state *dst_reg,
13754  				   enum bpf_reg_type type,
13755  				   bool range_right_open)
13756  {
13757  	struct bpf_func_state *state;
13758  	struct bpf_reg_state *reg;
13759  	int new_range;
13760  
13761  	if (dst_reg->off < 0 ||
13762  	    (dst_reg->off == 0 && range_right_open))
13763  		/* This doesn't give us any range */
13764  		return;
13765  
13766  	if (dst_reg->umax_value > MAX_PACKET_OFF ||
13767  	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13768  		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
13769  		 * than pkt_end, but that's because it's also less than pkt.
13770  		 */
13771  		return;
13772  
13773  	new_range = dst_reg->off;
13774  	if (range_right_open)
13775  		new_range++;
13776  
13777  	/* Examples for register markings:
13778  	 *
13779  	 * pkt_data in dst register:
13780  	 *
13781  	 *   r2 = r3;
13782  	 *   r2 += 8;
13783  	 *   if (r2 > pkt_end) goto <handle exception>
13784  	 *   <access okay>
13785  	 *
13786  	 *   r2 = r3;
13787  	 *   r2 += 8;
13788  	 *   if (r2 < pkt_end) goto <access okay>
13789  	 *   <handle exception>
13790  	 *
13791  	 *   Where:
13792  	 *     r2 == dst_reg, pkt_end == src_reg
13793  	 *     r2=pkt(id=n,off=8,r=0)
13794  	 *     r3=pkt(id=n,off=0,r=0)
13795  	 *
13796  	 * pkt_data in src register:
13797  	 *
13798  	 *   r2 = r3;
13799  	 *   r2 += 8;
13800  	 *   if (pkt_end >= r2) goto <access okay>
13801  	 *   <handle exception>
13802  	 *
13803  	 *   r2 = r3;
13804  	 *   r2 += 8;
13805  	 *   if (pkt_end <= r2) goto <handle exception>
13806  	 *   <access okay>
13807  	 *
13808  	 *   Where:
13809  	 *     pkt_end == dst_reg, r2 == src_reg
13810  	 *     r2=pkt(id=n,off=8,r=0)
13811  	 *     r3=pkt(id=n,off=0,r=0)
13812  	 *
13813  	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13814  	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13815  	 * and [r3, r3 + 8-1) respectively is safe to access depending on
13816  	 * the check.
13817  	 */
13818  
13819  	/* If our ids match, then we must have the same max_value.  And we
13820  	 * don't care about the other reg's fixed offset, since if it's too big
13821  	 * the range won't allow anything.
13822  	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13823  	 */
13824  	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13825  		if (reg->type == type && reg->id == dst_reg->id)
13826  			/* keep the maximum range already checked */
13827  			reg->range = max(reg->range, new_range);
13828  	}));
13829  }
13830  
is_branch32_taken(struct bpf_reg_state * reg,u32 val,u8 opcode)13831  static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13832  {
13833  	struct tnum subreg = tnum_subreg(reg->var_off);
13834  	s32 sval = (s32)val;
13835  
13836  	switch (opcode) {
13837  	case BPF_JEQ:
13838  		if (tnum_is_const(subreg))
13839  			return !!tnum_equals_const(subreg, val);
13840  		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13841  			return 0;
13842  		break;
13843  	case BPF_JNE:
13844  		if (tnum_is_const(subreg))
13845  			return !tnum_equals_const(subreg, val);
13846  		else if (val < reg->u32_min_value || val > reg->u32_max_value)
13847  			return 1;
13848  		break;
13849  	case BPF_JSET:
13850  		if ((~subreg.mask & subreg.value) & val)
13851  			return 1;
13852  		if (!((subreg.mask | subreg.value) & val))
13853  			return 0;
13854  		break;
13855  	case BPF_JGT:
13856  		if (reg->u32_min_value > val)
13857  			return 1;
13858  		else if (reg->u32_max_value <= val)
13859  			return 0;
13860  		break;
13861  	case BPF_JSGT:
13862  		if (reg->s32_min_value > sval)
13863  			return 1;
13864  		else if (reg->s32_max_value <= sval)
13865  			return 0;
13866  		break;
13867  	case BPF_JLT:
13868  		if (reg->u32_max_value < val)
13869  			return 1;
13870  		else if (reg->u32_min_value >= val)
13871  			return 0;
13872  		break;
13873  	case BPF_JSLT:
13874  		if (reg->s32_max_value < sval)
13875  			return 1;
13876  		else if (reg->s32_min_value >= sval)
13877  			return 0;
13878  		break;
13879  	case BPF_JGE:
13880  		if (reg->u32_min_value >= val)
13881  			return 1;
13882  		else if (reg->u32_max_value < val)
13883  			return 0;
13884  		break;
13885  	case BPF_JSGE:
13886  		if (reg->s32_min_value >= sval)
13887  			return 1;
13888  		else if (reg->s32_max_value < sval)
13889  			return 0;
13890  		break;
13891  	case BPF_JLE:
13892  		if (reg->u32_max_value <= val)
13893  			return 1;
13894  		else if (reg->u32_min_value > val)
13895  			return 0;
13896  		break;
13897  	case BPF_JSLE:
13898  		if (reg->s32_max_value <= sval)
13899  			return 1;
13900  		else if (reg->s32_min_value > sval)
13901  			return 0;
13902  		break;
13903  	}
13904  
13905  	return -1;
13906  }
13907  
13908  
is_branch64_taken(struct bpf_reg_state * reg,u64 val,u8 opcode)13909  static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13910  {
13911  	s64 sval = (s64)val;
13912  
13913  	switch (opcode) {
13914  	case BPF_JEQ:
13915  		if (tnum_is_const(reg->var_off))
13916  			return !!tnum_equals_const(reg->var_off, val);
13917  		else if (val < reg->umin_value || val > reg->umax_value)
13918  			return 0;
13919  		break;
13920  	case BPF_JNE:
13921  		if (tnum_is_const(reg->var_off))
13922  			return !tnum_equals_const(reg->var_off, val);
13923  		else if (val < reg->umin_value || val > reg->umax_value)
13924  			return 1;
13925  		break;
13926  	case BPF_JSET:
13927  		if ((~reg->var_off.mask & reg->var_off.value) & val)
13928  			return 1;
13929  		if (!((reg->var_off.mask | reg->var_off.value) & val))
13930  			return 0;
13931  		break;
13932  	case BPF_JGT:
13933  		if (reg->umin_value > val)
13934  			return 1;
13935  		else if (reg->umax_value <= val)
13936  			return 0;
13937  		break;
13938  	case BPF_JSGT:
13939  		if (reg->smin_value > sval)
13940  			return 1;
13941  		else if (reg->smax_value <= sval)
13942  			return 0;
13943  		break;
13944  	case BPF_JLT:
13945  		if (reg->umax_value < val)
13946  			return 1;
13947  		else if (reg->umin_value >= val)
13948  			return 0;
13949  		break;
13950  	case BPF_JSLT:
13951  		if (reg->smax_value < sval)
13952  			return 1;
13953  		else if (reg->smin_value >= sval)
13954  			return 0;
13955  		break;
13956  	case BPF_JGE:
13957  		if (reg->umin_value >= val)
13958  			return 1;
13959  		else if (reg->umax_value < val)
13960  			return 0;
13961  		break;
13962  	case BPF_JSGE:
13963  		if (reg->smin_value >= sval)
13964  			return 1;
13965  		else if (reg->smax_value < sval)
13966  			return 0;
13967  		break;
13968  	case BPF_JLE:
13969  		if (reg->umax_value <= val)
13970  			return 1;
13971  		else if (reg->umin_value > val)
13972  			return 0;
13973  		break;
13974  	case BPF_JSLE:
13975  		if (reg->smax_value <= sval)
13976  			return 1;
13977  		else if (reg->smin_value > sval)
13978  			return 0;
13979  		break;
13980  	}
13981  
13982  	return -1;
13983  }
13984  
13985  /* compute branch direction of the expression "if (reg opcode val) goto target;"
13986   * and return:
13987   *  1 - branch will be taken and "goto target" will be executed
13988   *  0 - branch will not be taken and fall-through to next insn
13989   * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13990   *      range [0,10]
13991   */
is_branch_taken(struct bpf_reg_state * reg,u64 val,u8 opcode,bool is_jmp32)13992  static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13993  			   bool is_jmp32)
13994  {
13995  	if (__is_pointer_value(false, reg)) {
13996  		if (!reg_not_null(reg))
13997  			return -1;
13998  
13999  		/* If pointer is valid tests against zero will fail so we can
14000  		 * use this to direct branch taken.
14001  		 */
14002  		if (val != 0)
14003  			return -1;
14004  
14005  		switch (opcode) {
14006  		case BPF_JEQ:
14007  			return 0;
14008  		case BPF_JNE:
14009  			return 1;
14010  		default:
14011  			return -1;
14012  		}
14013  	}
14014  
14015  	if (is_jmp32)
14016  		return is_branch32_taken(reg, val, opcode);
14017  	return is_branch64_taken(reg, val, opcode);
14018  }
14019  
flip_opcode(u32 opcode)14020  static int flip_opcode(u32 opcode)
14021  {
14022  	/* How can we transform "a <op> b" into "b <op> a"? */
14023  	static const u8 opcode_flip[16] = {
14024  		/* these stay the same */
14025  		[BPF_JEQ  >> 4] = BPF_JEQ,
14026  		[BPF_JNE  >> 4] = BPF_JNE,
14027  		[BPF_JSET >> 4] = BPF_JSET,
14028  		/* these swap "lesser" and "greater" (L and G in the opcodes) */
14029  		[BPF_JGE  >> 4] = BPF_JLE,
14030  		[BPF_JGT  >> 4] = BPF_JLT,
14031  		[BPF_JLE  >> 4] = BPF_JGE,
14032  		[BPF_JLT  >> 4] = BPF_JGT,
14033  		[BPF_JSGE >> 4] = BPF_JSLE,
14034  		[BPF_JSGT >> 4] = BPF_JSLT,
14035  		[BPF_JSLE >> 4] = BPF_JSGE,
14036  		[BPF_JSLT >> 4] = BPF_JSGT
14037  	};
14038  	return opcode_flip[opcode >> 4];
14039  }
14040  
is_pkt_ptr_branch_taken(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg,u8 opcode)14041  static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14042  				   struct bpf_reg_state *src_reg,
14043  				   u8 opcode)
14044  {
14045  	struct bpf_reg_state *pkt;
14046  
14047  	if (src_reg->type == PTR_TO_PACKET_END) {
14048  		pkt = dst_reg;
14049  	} else if (dst_reg->type == PTR_TO_PACKET_END) {
14050  		pkt = src_reg;
14051  		opcode = flip_opcode(opcode);
14052  	} else {
14053  		return -1;
14054  	}
14055  
14056  	if (pkt->range >= 0)
14057  		return -1;
14058  
14059  	switch (opcode) {
14060  	case BPF_JLE:
14061  		/* pkt <= pkt_end */
14062  		fallthrough;
14063  	case BPF_JGT:
14064  		/* pkt > pkt_end */
14065  		if (pkt->range == BEYOND_PKT_END)
14066  			/* pkt has at last one extra byte beyond pkt_end */
14067  			return opcode == BPF_JGT;
14068  		break;
14069  	case BPF_JLT:
14070  		/* pkt < pkt_end */
14071  		fallthrough;
14072  	case BPF_JGE:
14073  		/* pkt >= pkt_end */
14074  		if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14075  			return opcode == BPF_JGE;
14076  		break;
14077  	}
14078  	return -1;
14079  }
14080  
14081  /* Adjusts the register min/max values in the case that the dst_reg is the
14082   * variable register that we are working on, and src_reg is a constant or we're
14083   * simply doing a BPF_K check.
14084   * In JEQ/JNE cases we also adjust the var_off values.
14085   */
reg_set_min_max(struct bpf_reg_state * true_reg,struct bpf_reg_state * false_reg,u64 val,u32 val32,u8 opcode,bool is_jmp32)14086  static void reg_set_min_max(struct bpf_reg_state *true_reg,
14087  			    struct bpf_reg_state *false_reg,
14088  			    u64 val, u32 val32,
14089  			    u8 opcode, bool is_jmp32)
14090  {
14091  	struct tnum false_32off = tnum_subreg(false_reg->var_off);
14092  	struct tnum false_64off = false_reg->var_off;
14093  	struct tnum true_32off = tnum_subreg(true_reg->var_off);
14094  	struct tnum true_64off = true_reg->var_off;
14095  	s64 sval = (s64)val;
14096  	s32 sval32 = (s32)val32;
14097  
14098  	/* If the dst_reg is a pointer, we can't learn anything about its
14099  	 * variable offset from the compare (unless src_reg were a pointer into
14100  	 * the same object, but we don't bother with that.
14101  	 * Since false_reg and true_reg have the same type by construction, we
14102  	 * only need to check one of them for pointerness.
14103  	 */
14104  	if (__is_pointer_value(false, false_reg))
14105  		return;
14106  
14107  	switch (opcode) {
14108  	/* JEQ/JNE comparison doesn't change the register equivalence.
14109  	 *
14110  	 * r1 = r2;
14111  	 * if (r1 == 42) goto label;
14112  	 * ...
14113  	 * label: // here both r1 and r2 are known to be 42.
14114  	 *
14115  	 * Hence when marking register as known preserve it's ID.
14116  	 */
14117  	case BPF_JEQ:
14118  		if (is_jmp32) {
14119  			__mark_reg32_known(true_reg, val32);
14120  			true_32off = tnum_subreg(true_reg->var_off);
14121  		} else {
14122  			___mark_reg_known(true_reg, val);
14123  			true_64off = true_reg->var_off;
14124  		}
14125  		break;
14126  	case BPF_JNE:
14127  		if (is_jmp32) {
14128  			__mark_reg32_known(false_reg, val32);
14129  			false_32off = tnum_subreg(false_reg->var_off);
14130  		} else {
14131  			___mark_reg_known(false_reg, val);
14132  			false_64off = false_reg->var_off;
14133  		}
14134  		break;
14135  	case BPF_JSET:
14136  		if (is_jmp32) {
14137  			false_32off = tnum_and(false_32off, tnum_const(~val32));
14138  			if (is_power_of_2(val32))
14139  				true_32off = tnum_or(true_32off,
14140  						     tnum_const(val32));
14141  		} else {
14142  			false_64off = tnum_and(false_64off, tnum_const(~val));
14143  			if (is_power_of_2(val))
14144  				true_64off = tnum_or(true_64off,
14145  						     tnum_const(val));
14146  		}
14147  		break;
14148  	case BPF_JGE:
14149  	case BPF_JGT:
14150  	{
14151  		if (is_jmp32) {
14152  			u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
14153  			u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
14154  
14155  			false_reg->u32_max_value = min(false_reg->u32_max_value,
14156  						       false_umax);
14157  			true_reg->u32_min_value = max(true_reg->u32_min_value,
14158  						      true_umin);
14159  		} else {
14160  			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
14161  			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
14162  
14163  			false_reg->umax_value = min(false_reg->umax_value, false_umax);
14164  			true_reg->umin_value = max(true_reg->umin_value, true_umin);
14165  		}
14166  		break;
14167  	}
14168  	case BPF_JSGE:
14169  	case BPF_JSGT:
14170  	{
14171  		if (is_jmp32) {
14172  			s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
14173  			s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
14174  
14175  			false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
14176  			true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
14177  		} else {
14178  			s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
14179  			s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
14180  
14181  			false_reg->smax_value = min(false_reg->smax_value, false_smax);
14182  			true_reg->smin_value = max(true_reg->smin_value, true_smin);
14183  		}
14184  		break;
14185  	}
14186  	case BPF_JLE:
14187  	case BPF_JLT:
14188  	{
14189  		if (is_jmp32) {
14190  			u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
14191  			u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
14192  
14193  			false_reg->u32_min_value = max(false_reg->u32_min_value,
14194  						       false_umin);
14195  			true_reg->u32_max_value = min(true_reg->u32_max_value,
14196  						      true_umax);
14197  		} else {
14198  			u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
14199  			u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
14200  
14201  			false_reg->umin_value = max(false_reg->umin_value, false_umin);
14202  			true_reg->umax_value = min(true_reg->umax_value, true_umax);
14203  		}
14204  		break;
14205  	}
14206  	case BPF_JSLE:
14207  	case BPF_JSLT:
14208  	{
14209  		if (is_jmp32) {
14210  			s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
14211  			s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
14212  
14213  			false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
14214  			true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
14215  		} else {
14216  			s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
14217  			s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
14218  
14219  			false_reg->smin_value = max(false_reg->smin_value, false_smin);
14220  			true_reg->smax_value = min(true_reg->smax_value, true_smax);
14221  		}
14222  		break;
14223  	}
14224  	default:
14225  		return;
14226  	}
14227  
14228  	if (is_jmp32) {
14229  		false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
14230  					     tnum_subreg(false_32off));
14231  		true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
14232  					    tnum_subreg(true_32off));
14233  		__reg_combine_32_into_64(false_reg);
14234  		__reg_combine_32_into_64(true_reg);
14235  	} else {
14236  		false_reg->var_off = false_64off;
14237  		true_reg->var_off = true_64off;
14238  		__reg_combine_64_into_32(false_reg);
14239  		__reg_combine_64_into_32(true_reg);
14240  	}
14241  }
14242  
14243  /* Same as above, but for the case that dst_reg holds a constant and src_reg is
14244   * the variable reg.
14245   */
reg_set_min_max_inv(struct bpf_reg_state * true_reg,struct bpf_reg_state * false_reg,u64 val,u32 val32,u8 opcode,bool is_jmp32)14246  static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
14247  				struct bpf_reg_state *false_reg,
14248  				u64 val, u32 val32,
14249  				u8 opcode, bool is_jmp32)
14250  {
14251  	opcode = flip_opcode(opcode);
14252  	/* This uses zero as "not present in table"; luckily the zero opcode,
14253  	 * BPF_JA, can't get here.
14254  	 */
14255  	if (opcode)
14256  		reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
14257  }
14258  
14259  /* Regs are known to be equal, so intersect their min/max/var_off */
__reg_combine_min_max(struct bpf_reg_state * src_reg,struct bpf_reg_state * dst_reg)14260  static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
14261  				  struct bpf_reg_state *dst_reg)
14262  {
14263  	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
14264  							dst_reg->umin_value);
14265  	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
14266  							dst_reg->umax_value);
14267  	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
14268  							dst_reg->smin_value);
14269  	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
14270  							dst_reg->smax_value);
14271  	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
14272  							     dst_reg->var_off);
14273  	reg_bounds_sync(src_reg);
14274  	reg_bounds_sync(dst_reg);
14275  }
14276  
reg_combine_min_max(struct bpf_reg_state * true_src,struct bpf_reg_state * true_dst,struct bpf_reg_state * false_src,struct bpf_reg_state * false_dst,u8 opcode)14277  static void reg_combine_min_max(struct bpf_reg_state *true_src,
14278  				struct bpf_reg_state *true_dst,
14279  				struct bpf_reg_state *false_src,
14280  				struct bpf_reg_state *false_dst,
14281  				u8 opcode)
14282  {
14283  	switch (opcode) {
14284  	case BPF_JEQ:
14285  		__reg_combine_min_max(true_src, true_dst);
14286  		break;
14287  	case BPF_JNE:
14288  		__reg_combine_min_max(false_src, false_dst);
14289  		break;
14290  	}
14291  }
14292  
mark_ptr_or_null_reg(struct bpf_func_state * state,struct bpf_reg_state * reg,u32 id,bool is_null)14293  static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14294  				 struct bpf_reg_state *reg, u32 id,
14295  				 bool is_null)
14296  {
14297  	if (type_may_be_null(reg->type) && reg->id == id &&
14298  	    (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14299  		/* Old offset (both fixed and variable parts) should have been
14300  		 * known-zero, because we don't allow pointer arithmetic on
14301  		 * pointers that might be NULL. If we see this happening, don't
14302  		 * convert the register.
14303  		 *
14304  		 * But in some cases, some helpers that return local kptrs
14305  		 * advance offset for the returned pointer. In those cases, it
14306  		 * is fine to expect to see reg->off.
14307  		 */
14308  		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14309  			return;
14310  		if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14311  		    WARN_ON_ONCE(reg->off))
14312  			return;
14313  
14314  		if (is_null) {
14315  			reg->type = SCALAR_VALUE;
14316  			/* We don't need id and ref_obj_id from this point
14317  			 * onwards anymore, thus we should better reset it,
14318  			 * so that state pruning has chances to take effect.
14319  			 */
14320  			reg->id = 0;
14321  			reg->ref_obj_id = 0;
14322  
14323  			return;
14324  		}
14325  
14326  		mark_ptr_not_null_reg(reg);
14327  
14328  		if (!reg_may_point_to_spin_lock(reg)) {
14329  			/* For not-NULL ptr, reg->ref_obj_id will be reset
14330  			 * in release_reference().
14331  			 *
14332  			 * reg->id is still used by spin_lock ptr. Other
14333  			 * than spin_lock ptr type, reg->id can be reset.
14334  			 */
14335  			reg->id = 0;
14336  		}
14337  	}
14338  }
14339  
14340  /* The logic is similar to find_good_pkt_pointers(), both could eventually
14341   * be folded together at some point.
14342   */
mark_ptr_or_null_regs(struct bpf_verifier_state * vstate,u32 regno,bool is_null)14343  static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14344  				  bool is_null)
14345  {
14346  	struct bpf_func_state *state = vstate->frame[vstate->curframe];
14347  	struct bpf_reg_state *regs = state->regs, *reg;
14348  	u32 ref_obj_id = regs[regno].ref_obj_id;
14349  	u32 id = regs[regno].id;
14350  
14351  	if (ref_obj_id && ref_obj_id == id && is_null)
14352  		/* regs[regno] is in the " == NULL" branch.
14353  		 * No one could have freed the reference state before
14354  		 * doing the NULL check.
14355  		 */
14356  		WARN_ON_ONCE(release_reference_state(state, id));
14357  
14358  	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14359  		mark_ptr_or_null_reg(state, reg, id, is_null);
14360  	}));
14361  }
14362  
try_match_pkt_pointers(const struct bpf_insn * insn,struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg,struct bpf_verifier_state * this_branch,struct bpf_verifier_state * other_branch)14363  static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14364  				   struct bpf_reg_state *dst_reg,
14365  				   struct bpf_reg_state *src_reg,
14366  				   struct bpf_verifier_state *this_branch,
14367  				   struct bpf_verifier_state *other_branch)
14368  {
14369  	if (BPF_SRC(insn->code) != BPF_X)
14370  		return false;
14371  
14372  	/* Pointers are always 64-bit. */
14373  	if (BPF_CLASS(insn->code) == BPF_JMP32)
14374  		return false;
14375  
14376  	switch (BPF_OP(insn->code)) {
14377  	case BPF_JGT:
14378  		if ((dst_reg->type == PTR_TO_PACKET &&
14379  		     src_reg->type == PTR_TO_PACKET_END) ||
14380  		    (dst_reg->type == PTR_TO_PACKET_META &&
14381  		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14382  			/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14383  			find_good_pkt_pointers(this_branch, dst_reg,
14384  					       dst_reg->type, false);
14385  			mark_pkt_end(other_branch, insn->dst_reg, true);
14386  		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14387  			    src_reg->type == PTR_TO_PACKET) ||
14388  			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14389  			    src_reg->type == PTR_TO_PACKET_META)) {
14390  			/* pkt_end > pkt_data', pkt_data > pkt_meta' */
14391  			find_good_pkt_pointers(other_branch, src_reg,
14392  					       src_reg->type, true);
14393  			mark_pkt_end(this_branch, insn->src_reg, false);
14394  		} else {
14395  			return false;
14396  		}
14397  		break;
14398  	case BPF_JLT:
14399  		if ((dst_reg->type == PTR_TO_PACKET &&
14400  		     src_reg->type == PTR_TO_PACKET_END) ||
14401  		    (dst_reg->type == PTR_TO_PACKET_META &&
14402  		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14403  			/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14404  			find_good_pkt_pointers(other_branch, dst_reg,
14405  					       dst_reg->type, true);
14406  			mark_pkt_end(this_branch, insn->dst_reg, false);
14407  		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14408  			    src_reg->type == PTR_TO_PACKET) ||
14409  			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14410  			    src_reg->type == PTR_TO_PACKET_META)) {
14411  			/* pkt_end < pkt_data', pkt_data > pkt_meta' */
14412  			find_good_pkt_pointers(this_branch, src_reg,
14413  					       src_reg->type, false);
14414  			mark_pkt_end(other_branch, insn->src_reg, true);
14415  		} else {
14416  			return false;
14417  		}
14418  		break;
14419  	case BPF_JGE:
14420  		if ((dst_reg->type == PTR_TO_PACKET &&
14421  		     src_reg->type == PTR_TO_PACKET_END) ||
14422  		    (dst_reg->type == PTR_TO_PACKET_META &&
14423  		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14424  			/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14425  			find_good_pkt_pointers(this_branch, dst_reg,
14426  					       dst_reg->type, true);
14427  			mark_pkt_end(other_branch, insn->dst_reg, false);
14428  		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14429  			    src_reg->type == PTR_TO_PACKET) ||
14430  			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14431  			    src_reg->type == PTR_TO_PACKET_META)) {
14432  			/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14433  			find_good_pkt_pointers(other_branch, src_reg,
14434  					       src_reg->type, false);
14435  			mark_pkt_end(this_branch, insn->src_reg, true);
14436  		} else {
14437  			return false;
14438  		}
14439  		break;
14440  	case BPF_JLE:
14441  		if ((dst_reg->type == PTR_TO_PACKET &&
14442  		     src_reg->type == PTR_TO_PACKET_END) ||
14443  		    (dst_reg->type == PTR_TO_PACKET_META &&
14444  		     reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14445  			/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14446  			find_good_pkt_pointers(other_branch, dst_reg,
14447  					       dst_reg->type, false);
14448  			mark_pkt_end(this_branch, insn->dst_reg, true);
14449  		} else if ((dst_reg->type == PTR_TO_PACKET_END &&
14450  			    src_reg->type == PTR_TO_PACKET) ||
14451  			   (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14452  			    src_reg->type == PTR_TO_PACKET_META)) {
14453  			/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14454  			find_good_pkt_pointers(this_branch, src_reg,
14455  					       src_reg->type, true);
14456  			mark_pkt_end(other_branch, insn->src_reg, false);
14457  		} else {
14458  			return false;
14459  		}
14460  		break;
14461  	default:
14462  		return false;
14463  	}
14464  
14465  	return true;
14466  }
14467  
find_equal_scalars(struct bpf_verifier_state * vstate,struct bpf_reg_state * known_reg)14468  static void find_equal_scalars(struct bpf_verifier_state *vstate,
14469  			       struct bpf_reg_state *known_reg)
14470  {
14471  	struct bpf_func_state *state;
14472  	struct bpf_reg_state *reg;
14473  
14474  	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14475  		if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) {
14476  			s32 saved_subreg_def = reg->subreg_def;
14477  			copy_register_state(reg, known_reg);
14478  			reg->subreg_def = saved_subreg_def;
14479  		}
14480  	}));
14481  }
14482  
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)14483  static int check_cond_jmp_op(struct bpf_verifier_env *env,
14484  			     struct bpf_insn *insn, int *insn_idx)
14485  {
14486  	struct bpf_verifier_state *this_branch = env->cur_state;
14487  	struct bpf_verifier_state *other_branch;
14488  	struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14489  	struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14490  	struct bpf_reg_state *eq_branch_regs;
14491  	u8 opcode = BPF_OP(insn->code);
14492  	bool is_jmp32;
14493  	int pred = -1;
14494  	int err;
14495  
14496  	/* Only conditional jumps are expected to reach here. */
14497  	if (opcode == BPF_JA || opcode > BPF_JSLE) {
14498  		verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14499  		return -EINVAL;
14500  	}
14501  
14502  	/* check src2 operand */
14503  	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14504  	if (err)
14505  		return err;
14506  
14507  	dst_reg = &regs[insn->dst_reg];
14508  	if (BPF_SRC(insn->code) == BPF_X) {
14509  		if (insn->imm != 0) {
14510  			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14511  			return -EINVAL;
14512  		}
14513  
14514  		/* check src1 operand */
14515  		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14516  		if (err)
14517  			return err;
14518  
14519  		src_reg = &regs[insn->src_reg];
14520  		if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14521  		    is_pointer_value(env, insn->src_reg)) {
14522  			verbose(env, "R%d pointer comparison prohibited\n",
14523  				insn->src_reg);
14524  			return -EACCES;
14525  		}
14526  	} else {
14527  		if (insn->src_reg != BPF_REG_0) {
14528  			verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14529  			return -EINVAL;
14530  		}
14531  	}
14532  
14533  	is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14534  
14535  	if (BPF_SRC(insn->code) == BPF_K) {
14536  		pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14537  	} else if (src_reg->type == SCALAR_VALUE &&
14538  		   is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14539  		pred = is_branch_taken(dst_reg,
14540  				       tnum_subreg(src_reg->var_off).value,
14541  				       opcode,
14542  				       is_jmp32);
14543  	} else if (src_reg->type == SCALAR_VALUE &&
14544  		   !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14545  		pred = is_branch_taken(dst_reg,
14546  				       src_reg->var_off.value,
14547  				       opcode,
14548  				       is_jmp32);
14549  	} else if (dst_reg->type == SCALAR_VALUE &&
14550  		   is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14551  		pred = is_branch_taken(src_reg,
14552  				       tnum_subreg(dst_reg->var_off).value,
14553  				       flip_opcode(opcode),
14554  				       is_jmp32);
14555  	} else if (dst_reg->type == SCALAR_VALUE &&
14556  		   !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14557  		pred = is_branch_taken(src_reg,
14558  				       dst_reg->var_off.value,
14559  				       flip_opcode(opcode),
14560  				       is_jmp32);
14561  	} else if (reg_is_pkt_pointer_any(dst_reg) &&
14562  		   reg_is_pkt_pointer_any(src_reg) &&
14563  		   !is_jmp32) {
14564  		pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14565  	}
14566  
14567  	if (pred >= 0) {
14568  		/* If we get here with a dst_reg pointer type it is because
14569  		 * above is_branch_taken() special cased the 0 comparison.
14570  		 */
14571  		if (!__is_pointer_value(false, dst_reg))
14572  			err = mark_chain_precision(env, insn->dst_reg);
14573  		if (BPF_SRC(insn->code) == BPF_X && !err &&
14574  		    !__is_pointer_value(false, src_reg))
14575  			err = mark_chain_precision(env, insn->src_reg);
14576  		if (err)
14577  			return err;
14578  	}
14579  
14580  	if (pred == 1) {
14581  		/* Only follow the goto, ignore fall-through. If needed, push
14582  		 * the fall-through branch for simulation under speculative
14583  		 * execution.
14584  		 */
14585  		if (!env->bypass_spec_v1 &&
14586  		    !sanitize_speculative_path(env, insn, *insn_idx + 1,
14587  					       *insn_idx))
14588  			return -EFAULT;
14589  		if (env->log.level & BPF_LOG_LEVEL)
14590  			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14591  		*insn_idx += insn->off;
14592  		return 0;
14593  	} else if (pred == 0) {
14594  		/* Only follow the fall-through branch, since that's where the
14595  		 * program will go. If needed, push the goto branch for
14596  		 * simulation under speculative execution.
14597  		 */
14598  		if (!env->bypass_spec_v1 &&
14599  		    !sanitize_speculative_path(env, insn,
14600  					       *insn_idx + insn->off + 1,
14601  					       *insn_idx))
14602  			return -EFAULT;
14603  		if (env->log.level & BPF_LOG_LEVEL)
14604  			print_insn_state(env, this_branch->frame[this_branch->curframe]);
14605  		return 0;
14606  	}
14607  
14608  	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14609  				  false);
14610  	if (!other_branch)
14611  		return -EFAULT;
14612  	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14613  
14614  	/* detect if we are comparing against a constant value so we can adjust
14615  	 * our min/max values for our dst register.
14616  	 * this is only legit if both are scalars (or pointers to the same
14617  	 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14618  	 * because otherwise the different base pointers mean the offsets aren't
14619  	 * comparable.
14620  	 */
14621  	if (BPF_SRC(insn->code) == BPF_X) {
14622  		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
14623  
14624  		if (dst_reg->type == SCALAR_VALUE &&
14625  		    src_reg->type == SCALAR_VALUE) {
14626  			if (tnum_is_const(src_reg->var_off) ||
14627  			    (is_jmp32 &&
14628  			     tnum_is_const(tnum_subreg(src_reg->var_off))))
14629  				reg_set_min_max(&other_branch_regs[insn->dst_reg],
14630  						dst_reg,
14631  						src_reg->var_off.value,
14632  						tnum_subreg(src_reg->var_off).value,
14633  						opcode, is_jmp32);
14634  			else if (tnum_is_const(dst_reg->var_off) ||
14635  				 (is_jmp32 &&
14636  				  tnum_is_const(tnum_subreg(dst_reg->var_off))))
14637  				reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14638  						    src_reg,
14639  						    dst_reg->var_off.value,
14640  						    tnum_subreg(dst_reg->var_off).value,
14641  						    opcode, is_jmp32);
14642  			else if (!is_jmp32 &&
14643  				 (opcode == BPF_JEQ || opcode == BPF_JNE))
14644  				/* Comparing for equality, we can combine knowledge */
14645  				reg_combine_min_max(&other_branch_regs[insn->src_reg],
14646  						    &other_branch_regs[insn->dst_reg],
14647  						    src_reg, dst_reg, opcode);
14648  			if (src_reg->id &&
14649  			    !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14650  				find_equal_scalars(this_branch, src_reg);
14651  				find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14652  			}
14653  
14654  		}
14655  	} else if (dst_reg->type == SCALAR_VALUE) {
14656  		reg_set_min_max(&other_branch_regs[insn->dst_reg],
14657  					dst_reg, insn->imm, (u32)insn->imm,
14658  					opcode, is_jmp32);
14659  	}
14660  
14661  	if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14662  	    !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14663  		find_equal_scalars(this_branch, dst_reg);
14664  		find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14665  	}
14666  
14667  	/* if one pointer register is compared to another pointer
14668  	 * register check if PTR_MAYBE_NULL could be lifted.
14669  	 * E.g. register A - maybe null
14670  	 *      register B - not null
14671  	 * for JNE A, B, ... - A is not null in the false branch;
14672  	 * for JEQ A, B, ... - A is not null in the true branch.
14673  	 *
14674  	 * Since PTR_TO_BTF_ID points to a kernel struct that does
14675  	 * not need to be null checked by the BPF program, i.e.,
14676  	 * could be null even without PTR_MAYBE_NULL marking, so
14677  	 * only propagate nullness when neither reg is that type.
14678  	 */
14679  	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14680  	    __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14681  	    type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14682  	    base_type(src_reg->type) != PTR_TO_BTF_ID &&
14683  	    base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14684  		eq_branch_regs = NULL;
14685  		switch (opcode) {
14686  		case BPF_JEQ:
14687  			eq_branch_regs = other_branch_regs;
14688  			break;
14689  		case BPF_JNE:
14690  			eq_branch_regs = regs;
14691  			break;
14692  		default:
14693  			/* do nothing */
14694  			break;
14695  		}
14696  		if (eq_branch_regs) {
14697  			if (type_may_be_null(src_reg->type))
14698  				mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14699  			else
14700  				mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14701  		}
14702  	}
14703  
14704  	/* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14705  	 * NOTE: these optimizations below are related with pointer comparison
14706  	 *       which will never be JMP32.
14707  	 */
14708  	if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14709  	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14710  	    type_may_be_null(dst_reg->type)) {
14711  		/* Mark all identical registers in each branch as either
14712  		 * safe or unknown depending R == 0 or R != 0 conditional.
14713  		 */
14714  		mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14715  				      opcode == BPF_JNE);
14716  		mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14717  				      opcode == BPF_JEQ);
14718  	} else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14719  					   this_branch, other_branch) &&
14720  		   is_pointer_value(env, insn->dst_reg)) {
14721  		verbose(env, "R%d pointer comparison prohibited\n",
14722  			insn->dst_reg);
14723  		return -EACCES;
14724  	}
14725  	if (env->log.level & BPF_LOG_LEVEL)
14726  		print_insn_state(env, this_branch->frame[this_branch->curframe]);
14727  	return 0;
14728  }
14729  
14730  /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)14731  static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14732  {
14733  	struct bpf_insn_aux_data *aux = cur_aux(env);
14734  	struct bpf_reg_state *regs = cur_regs(env);
14735  	struct bpf_reg_state *dst_reg;
14736  	struct bpf_map *map;
14737  	int err;
14738  
14739  	if (BPF_SIZE(insn->code) != BPF_DW) {
14740  		verbose(env, "invalid BPF_LD_IMM insn\n");
14741  		return -EINVAL;
14742  	}
14743  	if (insn->off != 0) {
14744  		verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14745  		return -EINVAL;
14746  	}
14747  
14748  	err = check_reg_arg(env, insn->dst_reg, DST_OP);
14749  	if (err)
14750  		return err;
14751  
14752  	dst_reg = &regs[insn->dst_reg];
14753  	if (insn->src_reg == 0) {
14754  		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14755  
14756  		dst_reg->type = SCALAR_VALUE;
14757  		__mark_reg_known(&regs[insn->dst_reg], imm);
14758  		return 0;
14759  	}
14760  
14761  	/* All special src_reg cases are listed below. From this point onwards
14762  	 * we either succeed and assign a corresponding dst_reg->type after
14763  	 * zeroing the offset, or fail and reject the program.
14764  	 */
14765  	mark_reg_known_zero(env, regs, insn->dst_reg);
14766  
14767  	if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14768  		dst_reg->type = aux->btf_var.reg_type;
14769  		switch (base_type(dst_reg->type)) {
14770  		case PTR_TO_MEM:
14771  			dst_reg->mem_size = aux->btf_var.mem_size;
14772  			break;
14773  		case PTR_TO_BTF_ID:
14774  			dst_reg->btf = aux->btf_var.btf;
14775  			dst_reg->btf_id = aux->btf_var.btf_id;
14776  			break;
14777  		default:
14778  			verbose(env, "bpf verifier is misconfigured\n");
14779  			return -EFAULT;
14780  		}
14781  		return 0;
14782  	}
14783  
14784  	if (insn->src_reg == BPF_PSEUDO_FUNC) {
14785  		struct bpf_prog_aux *aux = env->prog->aux;
14786  		u32 subprogno = find_subprog(env,
14787  					     env->insn_idx + insn->imm + 1);
14788  
14789  		if (!aux->func_info) {
14790  			verbose(env, "missing btf func_info\n");
14791  			return -EINVAL;
14792  		}
14793  		if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14794  			verbose(env, "callback function not static\n");
14795  			return -EINVAL;
14796  		}
14797  
14798  		dst_reg->type = PTR_TO_FUNC;
14799  		dst_reg->subprogno = subprogno;
14800  		return 0;
14801  	}
14802  
14803  	map = env->used_maps[aux->map_index];
14804  	dst_reg->map_ptr = map;
14805  
14806  	if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14807  	    insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14808  		dst_reg->type = PTR_TO_MAP_VALUE;
14809  		dst_reg->off = aux->map_off;
14810  		WARN_ON_ONCE(map->max_entries != 1);
14811  		/* We want reg->id to be same (0) as map_value is not distinct */
14812  	} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14813  		   insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14814  		dst_reg->type = CONST_PTR_TO_MAP;
14815  	} else {
14816  		verbose(env, "bpf verifier is misconfigured\n");
14817  		return -EINVAL;
14818  	}
14819  
14820  	return 0;
14821  }
14822  
may_access_skb(enum bpf_prog_type type)14823  static bool may_access_skb(enum bpf_prog_type type)
14824  {
14825  	switch (type) {
14826  	case BPF_PROG_TYPE_SOCKET_FILTER:
14827  	case BPF_PROG_TYPE_SCHED_CLS:
14828  	case BPF_PROG_TYPE_SCHED_ACT:
14829  		return true;
14830  	default:
14831  		return false;
14832  	}
14833  }
14834  
14835  /* verify safety of LD_ABS|LD_IND instructions:
14836   * - they can only appear in the programs where ctx == skb
14837   * - since they are wrappers of function calls, they scratch R1-R5 registers,
14838   *   preserve R6-R9, and store return value into R0
14839   *
14840   * Implicit input:
14841   *   ctx == skb == R6 == CTX
14842   *
14843   * Explicit input:
14844   *   SRC == any register
14845   *   IMM == 32-bit immediate
14846   *
14847   * Output:
14848   *   R0 - 8/16/32-bit skb data converted to cpu endianness
14849   */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)14850  static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14851  {
14852  	struct bpf_reg_state *regs = cur_regs(env);
14853  	static const int ctx_reg = BPF_REG_6;
14854  	u8 mode = BPF_MODE(insn->code);
14855  	int i, err;
14856  
14857  	if (!may_access_skb(resolve_prog_type(env->prog))) {
14858  		verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14859  		return -EINVAL;
14860  	}
14861  
14862  	if (!env->ops->gen_ld_abs) {
14863  		verbose(env, "bpf verifier is misconfigured\n");
14864  		return -EINVAL;
14865  	}
14866  
14867  	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14868  	    BPF_SIZE(insn->code) == BPF_DW ||
14869  	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14870  		verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14871  		return -EINVAL;
14872  	}
14873  
14874  	/* check whether implicit source operand (register R6) is readable */
14875  	err = check_reg_arg(env, ctx_reg, SRC_OP);
14876  	if (err)
14877  		return err;
14878  
14879  	/* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14880  	 * gen_ld_abs() may terminate the program at runtime, leading to
14881  	 * reference leak.
14882  	 */
14883  	err = check_reference_leak(env);
14884  	if (err) {
14885  		verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14886  		return err;
14887  	}
14888  
14889  	if (env->cur_state->active_lock.ptr) {
14890  		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14891  		return -EINVAL;
14892  	}
14893  
14894  	if (env->cur_state->active_rcu_lock) {
14895  		verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14896  		return -EINVAL;
14897  	}
14898  
14899  	if (regs[ctx_reg].type != PTR_TO_CTX) {
14900  		verbose(env,
14901  			"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14902  		return -EINVAL;
14903  	}
14904  
14905  	if (mode == BPF_IND) {
14906  		/* check explicit source operand */
14907  		err = check_reg_arg(env, insn->src_reg, SRC_OP);
14908  		if (err)
14909  			return err;
14910  	}
14911  
14912  	err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14913  	if (err < 0)
14914  		return err;
14915  
14916  	/* reset caller saved regs to unreadable */
14917  	for (i = 0; i < CALLER_SAVED_REGS; i++) {
14918  		mark_reg_not_init(env, regs, caller_saved[i]);
14919  		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14920  	}
14921  
14922  	/* mark destination R0 register as readable, since it contains
14923  	 * the value fetched from the packet.
14924  	 * Already marked as written above.
14925  	 */
14926  	mark_reg_unknown(env, regs, BPF_REG_0);
14927  	/* ld_abs load up to 32-bit skb data. */
14928  	regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14929  	return 0;
14930  }
14931  
check_return_code(struct bpf_verifier_env * env)14932  static int check_return_code(struct bpf_verifier_env *env)
14933  {
14934  	struct tnum enforce_attach_type_range = tnum_unknown;
14935  	const struct bpf_prog *prog = env->prog;
14936  	struct bpf_reg_state *reg;
14937  	struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
14938  	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14939  	int err;
14940  	struct bpf_func_state *frame = env->cur_state->frame[0];
14941  	const bool is_subprog = frame->subprogno;
14942  
14943  	/* LSM and struct_ops func-ptr's return type could be "void" */
14944  	if (!is_subprog) {
14945  		switch (prog_type) {
14946  		case BPF_PROG_TYPE_LSM:
14947  			if (prog->expected_attach_type == BPF_LSM_CGROUP)
14948  				/* See below, can be 0 or 0-1 depending on hook. */
14949  				break;
14950  			fallthrough;
14951  		case BPF_PROG_TYPE_STRUCT_OPS:
14952  			if (!prog->aux->attach_func_proto->type)
14953  				return 0;
14954  			break;
14955  		default:
14956  			break;
14957  		}
14958  	}
14959  
14960  	/* eBPF calling convention is such that R0 is used
14961  	 * to return the value from eBPF program.
14962  	 * Make sure that it's readable at this time
14963  	 * of bpf_exit, which means that program wrote
14964  	 * something into it earlier
14965  	 */
14966  	err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14967  	if (err)
14968  		return err;
14969  
14970  	if (is_pointer_value(env, BPF_REG_0)) {
14971  		verbose(env, "R0 leaks addr as return value\n");
14972  		return -EACCES;
14973  	}
14974  
14975  	reg = cur_regs(env) + BPF_REG_0;
14976  
14977  	if (frame->in_async_callback_fn) {
14978  		/* enforce return zero from async callbacks like timer */
14979  		if (reg->type != SCALAR_VALUE) {
14980  			verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14981  				reg_type_str(env, reg->type));
14982  			return -EINVAL;
14983  		}
14984  
14985  		if (!tnum_in(const_0, reg->var_off)) {
14986  			verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
14987  			return -EINVAL;
14988  		}
14989  		return 0;
14990  	}
14991  
14992  	if (is_subprog) {
14993  		if (reg->type != SCALAR_VALUE) {
14994  			verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14995  				reg_type_str(env, reg->type));
14996  			return -EINVAL;
14997  		}
14998  		return 0;
14999  	}
15000  
15001  	switch (prog_type) {
15002  	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15003  		if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15004  		    env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15005  		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15006  		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15007  		    env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15008  		    env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
15009  			range = tnum_range(1, 1);
15010  		if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15011  		    env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15012  			range = tnum_range(0, 3);
15013  		break;
15014  	case BPF_PROG_TYPE_CGROUP_SKB:
15015  		if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15016  			range = tnum_range(0, 3);
15017  			enforce_attach_type_range = tnum_range(2, 3);
15018  		}
15019  		break;
15020  	case BPF_PROG_TYPE_CGROUP_SOCK:
15021  	case BPF_PROG_TYPE_SOCK_OPS:
15022  	case BPF_PROG_TYPE_CGROUP_DEVICE:
15023  	case BPF_PROG_TYPE_CGROUP_SYSCTL:
15024  	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15025  		break;
15026  	case BPF_PROG_TYPE_RAW_TRACEPOINT:
15027  		if (!env->prog->aux->attach_btf_id)
15028  			return 0;
15029  		range = tnum_const(0);
15030  		break;
15031  	case BPF_PROG_TYPE_TRACING:
15032  		switch (env->prog->expected_attach_type) {
15033  		case BPF_TRACE_FENTRY:
15034  		case BPF_TRACE_FEXIT:
15035  			range = tnum_const(0);
15036  			break;
15037  		case BPF_TRACE_RAW_TP:
15038  		case BPF_MODIFY_RETURN:
15039  			return 0;
15040  		case BPF_TRACE_ITER:
15041  			break;
15042  		default:
15043  			return -ENOTSUPP;
15044  		}
15045  		break;
15046  	case BPF_PROG_TYPE_SK_LOOKUP:
15047  		range = tnum_range(SK_DROP, SK_PASS);
15048  		break;
15049  
15050  	case BPF_PROG_TYPE_LSM:
15051  		if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15052  			/* Regular BPF_PROG_TYPE_LSM programs can return
15053  			 * any value.
15054  			 */
15055  			return 0;
15056  		}
15057  		if (!env->prog->aux->attach_func_proto->type) {
15058  			/* Make sure programs that attach to void
15059  			 * hooks don't try to modify return value.
15060  			 */
15061  			range = tnum_range(1, 1);
15062  		}
15063  		break;
15064  
15065  	case BPF_PROG_TYPE_NETFILTER:
15066  		range = tnum_range(NF_DROP, NF_ACCEPT);
15067  		break;
15068  	case BPF_PROG_TYPE_EXT:
15069  		/* freplace program can return anything as its return value
15070  		 * depends on the to-be-replaced kernel func or bpf program.
15071  		 */
15072  	default:
15073  		return 0;
15074  	}
15075  
15076  	if (reg->type != SCALAR_VALUE) {
15077  		verbose(env, "At program exit the register R0 is not a known value (%s)\n",
15078  			reg_type_str(env, reg->type));
15079  		return -EINVAL;
15080  	}
15081  
15082  	if (!tnum_in(range, reg->var_off)) {
15083  		verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
15084  		if (prog->expected_attach_type == BPF_LSM_CGROUP &&
15085  		    prog_type == BPF_PROG_TYPE_LSM &&
15086  		    !prog->aux->attach_func_proto->type)
15087  			verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15088  		return -EINVAL;
15089  	}
15090  
15091  	if (!tnum_is_unknown(enforce_attach_type_range) &&
15092  	    tnum_in(enforce_attach_type_range, reg->var_off))
15093  		env->prog->enforce_expected_attach_type = 1;
15094  	return 0;
15095  }
15096  
15097  /* non-recursive DFS pseudo code
15098   * 1  procedure DFS-iterative(G,v):
15099   * 2      label v as discovered
15100   * 3      let S be a stack
15101   * 4      S.push(v)
15102   * 5      while S is not empty
15103   * 6            t <- S.peek()
15104   * 7            if t is what we're looking for:
15105   * 8                return t
15106   * 9            for all edges e in G.adjacentEdges(t) do
15107   * 10               if edge e is already labelled
15108   * 11                   continue with the next edge
15109   * 12               w <- G.adjacentVertex(t,e)
15110   * 13               if vertex w is not discovered and not explored
15111   * 14                   label e as tree-edge
15112   * 15                   label w as discovered
15113   * 16                   S.push(w)
15114   * 17                   continue at 5
15115   * 18               else if vertex w is discovered
15116   * 19                   label e as back-edge
15117   * 20               else
15118   * 21                   // vertex w is explored
15119   * 22                   label e as forward- or cross-edge
15120   * 23           label t as explored
15121   * 24           S.pop()
15122   *
15123   * convention:
15124   * 0x10 - discovered
15125   * 0x11 - discovered and fall-through edge labelled
15126   * 0x12 - discovered and fall-through and branch edges labelled
15127   * 0x20 - explored
15128   */
15129  
15130  enum {
15131  	DISCOVERED = 0x10,
15132  	EXPLORED = 0x20,
15133  	FALLTHROUGH = 1,
15134  	BRANCH = 2,
15135  };
15136  
mark_prune_point(struct bpf_verifier_env * env,int idx)15137  static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15138  {
15139  	env->insn_aux_data[idx].prune_point = true;
15140  }
15141  
is_prune_point(struct bpf_verifier_env * env,int insn_idx)15142  static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15143  {
15144  	return env->insn_aux_data[insn_idx].prune_point;
15145  }
15146  
mark_force_checkpoint(struct bpf_verifier_env * env,int idx)15147  static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15148  {
15149  	env->insn_aux_data[idx].force_checkpoint = true;
15150  }
15151  
is_force_checkpoint(struct bpf_verifier_env * env,int insn_idx)15152  static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15153  {
15154  	return env->insn_aux_data[insn_idx].force_checkpoint;
15155  }
15156  
mark_calls_callback(struct bpf_verifier_env * env,int idx)15157  static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15158  {
15159  	env->insn_aux_data[idx].calls_callback = true;
15160  }
15161  
calls_callback(struct bpf_verifier_env * env,int insn_idx)15162  static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15163  {
15164  	return env->insn_aux_data[insn_idx].calls_callback;
15165  }
15166  
15167  enum {
15168  	DONE_EXPLORING = 0,
15169  	KEEP_EXPLORING = 1,
15170  };
15171  
15172  /* t, w, e - match pseudo-code above:
15173   * t - index of current instruction
15174   * w - next instruction
15175   * e - edge
15176   */
push_insn(int t,int w,int e,struct bpf_verifier_env * env)15177  static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15178  {
15179  	int *insn_stack = env->cfg.insn_stack;
15180  	int *insn_state = env->cfg.insn_state;
15181  
15182  	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15183  		return DONE_EXPLORING;
15184  
15185  	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15186  		return DONE_EXPLORING;
15187  
15188  	if (w < 0 || w >= env->prog->len) {
15189  		verbose_linfo(env, t, "%d: ", t);
15190  		verbose(env, "jump out of range from insn %d to %d\n", t, w);
15191  		return -EINVAL;
15192  	}
15193  
15194  	if (e == BRANCH) {
15195  		/* mark branch target for state pruning */
15196  		mark_prune_point(env, w);
15197  		mark_jmp_point(env, w);
15198  	}
15199  
15200  	if (insn_state[w] == 0) {
15201  		/* tree-edge */
15202  		insn_state[t] = DISCOVERED | e;
15203  		insn_state[w] = DISCOVERED;
15204  		if (env->cfg.cur_stack >= env->prog->len)
15205  			return -E2BIG;
15206  		insn_stack[env->cfg.cur_stack++] = w;
15207  		return KEEP_EXPLORING;
15208  	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15209  		if (env->bpf_capable)
15210  			return DONE_EXPLORING;
15211  		verbose_linfo(env, t, "%d: ", t);
15212  		verbose_linfo(env, w, "%d: ", w);
15213  		verbose(env, "back-edge from insn %d to %d\n", t, w);
15214  		return -EINVAL;
15215  	} else if (insn_state[w] == EXPLORED) {
15216  		/* forward- or cross-edge */
15217  		insn_state[t] = DISCOVERED | e;
15218  	} else {
15219  		verbose(env, "insn state internal bug\n");
15220  		return -EFAULT;
15221  	}
15222  	return DONE_EXPLORING;
15223  }
15224  
visit_func_call_insn(int t,struct bpf_insn * insns,struct bpf_verifier_env * env,bool visit_callee)15225  static int visit_func_call_insn(int t, struct bpf_insn *insns,
15226  				struct bpf_verifier_env *env,
15227  				bool visit_callee)
15228  {
15229  	int ret, insn_sz;
15230  
15231  	insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15232  	ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15233  	if (ret)
15234  		return ret;
15235  
15236  	mark_prune_point(env, t + insn_sz);
15237  	/* when we exit from subprog, we need to record non-linear history */
15238  	mark_jmp_point(env, t + insn_sz);
15239  
15240  	if (visit_callee) {
15241  		mark_prune_point(env, t);
15242  		ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15243  	}
15244  	return ret;
15245  }
15246  
15247  /* Visits the instruction at index t and returns one of the following:
15248   *  < 0 - an error occurred
15249   *  DONE_EXPLORING - the instruction was fully explored
15250   *  KEEP_EXPLORING - there is still work to be done before it is fully explored
15251   */
visit_insn(int t,struct bpf_verifier_env * env)15252  static int visit_insn(int t, struct bpf_verifier_env *env)
15253  {
15254  	struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15255  	int ret, off, insn_sz;
15256  
15257  	if (bpf_pseudo_func(insn))
15258  		return visit_func_call_insn(t, insns, env, true);
15259  
15260  	/* All non-branch instructions have a single fall-through edge. */
15261  	if (BPF_CLASS(insn->code) != BPF_JMP &&
15262  	    BPF_CLASS(insn->code) != BPF_JMP32) {
15263  		insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15264  		return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15265  	}
15266  
15267  	switch (BPF_OP(insn->code)) {
15268  	case BPF_EXIT:
15269  		return DONE_EXPLORING;
15270  
15271  	case BPF_CALL:
15272  		if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15273  			/* Mark this call insn as a prune point to trigger
15274  			 * is_state_visited() check before call itself is
15275  			 * processed by __check_func_call(). Otherwise new
15276  			 * async state will be pushed for further exploration.
15277  			 */
15278  			mark_prune_point(env, t);
15279  		/* For functions that invoke callbacks it is not known how many times
15280  		 * callback would be called. Verifier models callback calling functions
15281  		 * by repeatedly visiting callback bodies and returning to origin call
15282  		 * instruction.
15283  		 * In order to stop such iteration verifier needs to identify when a
15284  		 * state identical some state from a previous iteration is reached.
15285  		 * Check below forces creation of checkpoint before callback calling
15286  		 * instruction to allow search for such identical states.
15287  		 */
15288  		if (is_sync_callback_calling_insn(insn)) {
15289  			mark_calls_callback(env, t);
15290  			mark_force_checkpoint(env, t);
15291  			mark_prune_point(env, t);
15292  			mark_jmp_point(env, t);
15293  		}
15294  		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15295  			struct bpf_kfunc_call_arg_meta meta;
15296  
15297  			ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15298  			if (ret == 0 && is_iter_next_kfunc(&meta)) {
15299  				mark_prune_point(env, t);
15300  				/* Checking and saving state checkpoints at iter_next() call
15301  				 * is crucial for fast convergence of open-coded iterator loop
15302  				 * logic, so we need to force it. If we don't do that,
15303  				 * is_state_visited() might skip saving a checkpoint, causing
15304  				 * unnecessarily long sequence of not checkpointed
15305  				 * instructions and jumps, leading to exhaustion of jump
15306  				 * history buffer, and potentially other undesired outcomes.
15307  				 * It is expected that with correct open-coded iterators
15308  				 * convergence will happen quickly, so we don't run a risk of
15309  				 * exhausting memory.
15310  				 */
15311  				mark_force_checkpoint(env, t);
15312  			}
15313  		}
15314  		return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15315  
15316  	case BPF_JA:
15317  		if (BPF_SRC(insn->code) != BPF_K)
15318  			return -EINVAL;
15319  
15320  		if (BPF_CLASS(insn->code) == BPF_JMP)
15321  			off = insn->off;
15322  		else
15323  			off = insn->imm;
15324  
15325  		/* unconditional jump with single edge */
15326  		ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15327  		if (ret)
15328  			return ret;
15329  
15330  		mark_prune_point(env, t + off + 1);
15331  		mark_jmp_point(env, t + off + 1);
15332  
15333  		return ret;
15334  
15335  	default:
15336  		/* conditional jump with two edges */
15337  		mark_prune_point(env, t);
15338  
15339  		ret = push_insn(t, t + 1, FALLTHROUGH, env);
15340  		if (ret)
15341  			return ret;
15342  
15343  		return push_insn(t, t + insn->off + 1, BRANCH, env);
15344  	}
15345  }
15346  
15347  /* non-recursive depth-first-search to detect loops in BPF program
15348   * loop == back-edge in directed graph
15349   */
check_cfg(struct bpf_verifier_env * env)15350  static int check_cfg(struct bpf_verifier_env *env)
15351  {
15352  	int insn_cnt = env->prog->len;
15353  	int *insn_stack, *insn_state;
15354  	int ret = 0;
15355  	int i;
15356  
15357  	insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15358  	if (!insn_state)
15359  		return -ENOMEM;
15360  
15361  	insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15362  	if (!insn_stack) {
15363  		kvfree(insn_state);
15364  		return -ENOMEM;
15365  	}
15366  
15367  	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15368  	insn_stack[0] = 0; /* 0 is the first instruction */
15369  	env->cfg.cur_stack = 1;
15370  
15371  	while (env->cfg.cur_stack > 0) {
15372  		int t = insn_stack[env->cfg.cur_stack - 1];
15373  
15374  		ret = visit_insn(t, env);
15375  		switch (ret) {
15376  		case DONE_EXPLORING:
15377  			insn_state[t] = EXPLORED;
15378  			env->cfg.cur_stack--;
15379  			break;
15380  		case KEEP_EXPLORING:
15381  			break;
15382  		default:
15383  			if (ret > 0) {
15384  				verbose(env, "visit_insn internal bug\n");
15385  				ret = -EFAULT;
15386  			}
15387  			goto err_free;
15388  		}
15389  	}
15390  
15391  	if (env->cfg.cur_stack < 0) {
15392  		verbose(env, "pop stack internal bug\n");
15393  		ret = -EFAULT;
15394  		goto err_free;
15395  	}
15396  
15397  	for (i = 0; i < insn_cnt; i++) {
15398  		struct bpf_insn *insn = &env->prog->insnsi[i];
15399  
15400  		if (insn_state[i] != EXPLORED) {
15401  			verbose(env, "unreachable insn %d\n", i);
15402  			ret = -EINVAL;
15403  			goto err_free;
15404  		}
15405  		if (bpf_is_ldimm64(insn)) {
15406  			if (insn_state[i + 1] != 0) {
15407  				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15408  				ret = -EINVAL;
15409  				goto err_free;
15410  			}
15411  			i++; /* skip second half of ldimm64 */
15412  		}
15413  	}
15414  	ret = 0; /* cfg looks good */
15415  
15416  err_free:
15417  	kvfree(insn_state);
15418  	kvfree(insn_stack);
15419  	env->cfg.insn_state = env->cfg.insn_stack = NULL;
15420  	return ret;
15421  }
15422  
check_abnormal_return(struct bpf_verifier_env * env)15423  static int check_abnormal_return(struct bpf_verifier_env *env)
15424  {
15425  	int i;
15426  
15427  	for (i = 1; i < env->subprog_cnt; i++) {
15428  		if (env->subprog_info[i].has_ld_abs) {
15429  			verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15430  			return -EINVAL;
15431  		}
15432  		if (env->subprog_info[i].has_tail_call) {
15433  			verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15434  			return -EINVAL;
15435  		}
15436  	}
15437  	return 0;
15438  }
15439  
15440  /* The minimum supported BTF func info size */
15441  #define MIN_BPF_FUNCINFO_SIZE	8
15442  #define MAX_FUNCINFO_REC_SIZE	252
15443  
check_btf_func(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)15444  static int check_btf_func(struct bpf_verifier_env *env,
15445  			  const union bpf_attr *attr,
15446  			  bpfptr_t uattr)
15447  {
15448  	const struct btf_type *type, *func_proto, *ret_type;
15449  	u32 i, nfuncs, urec_size, min_size;
15450  	u32 krec_size = sizeof(struct bpf_func_info);
15451  	struct bpf_func_info *krecord;
15452  	struct bpf_func_info_aux *info_aux = NULL;
15453  	struct bpf_prog *prog;
15454  	const struct btf *btf;
15455  	bpfptr_t urecord;
15456  	u32 prev_offset = 0;
15457  	bool scalar_return;
15458  	int ret = -ENOMEM;
15459  
15460  	nfuncs = attr->func_info_cnt;
15461  	if (!nfuncs) {
15462  		if (check_abnormal_return(env))
15463  			return -EINVAL;
15464  		return 0;
15465  	}
15466  
15467  	if (nfuncs != env->subprog_cnt) {
15468  		verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15469  		return -EINVAL;
15470  	}
15471  
15472  	urec_size = attr->func_info_rec_size;
15473  	if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15474  	    urec_size > MAX_FUNCINFO_REC_SIZE ||
15475  	    urec_size % sizeof(u32)) {
15476  		verbose(env, "invalid func info rec size %u\n", urec_size);
15477  		return -EINVAL;
15478  	}
15479  
15480  	prog = env->prog;
15481  	btf = prog->aux->btf;
15482  
15483  	urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15484  	min_size = min_t(u32, krec_size, urec_size);
15485  
15486  	krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15487  	if (!krecord)
15488  		return -ENOMEM;
15489  	info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15490  	if (!info_aux)
15491  		goto err_free;
15492  
15493  	for (i = 0; i < nfuncs; i++) {
15494  		ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15495  		if (ret) {
15496  			if (ret == -E2BIG) {
15497  				verbose(env, "nonzero tailing record in func info");
15498  				/* set the size kernel expects so loader can zero
15499  				 * out the rest of the record.
15500  				 */
15501  				if (copy_to_bpfptr_offset(uattr,
15502  							  offsetof(union bpf_attr, func_info_rec_size),
15503  							  &min_size, sizeof(min_size)))
15504  					ret = -EFAULT;
15505  			}
15506  			goto err_free;
15507  		}
15508  
15509  		if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15510  			ret = -EFAULT;
15511  			goto err_free;
15512  		}
15513  
15514  		/* check insn_off */
15515  		ret = -EINVAL;
15516  		if (i == 0) {
15517  			if (krecord[i].insn_off) {
15518  				verbose(env,
15519  					"nonzero insn_off %u for the first func info record",
15520  					krecord[i].insn_off);
15521  				goto err_free;
15522  			}
15523  		} else if (krecord[i].insn_off <= prev_offset) {
15524  			verbose(env,
15525  				"same or smaller insn offset (%u) than previous func info record (%u)",
15526  				krecord[i].insn_off, prev_offset);
15527  			goto err_free;
15528  		}
15529  
15530  		if (env->subprog_info[i].start != krecord[i].insn_off) {
15531  			verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15532  			goto err_free;
15533  		}
15534  
15535  		/* check type_id */
15536  		type = btf_type_by_id(btf, krecord[i].type_id);
15537  		if (!type || !btf_type_is_func(type)) {
15538  			verbose(env, "invalid type id %d in func info",
15539  				krecord[i].type_id);
15540  			goto err_free;
15541  		}
15542  		info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15543  
15544  		func_proto = btf_type_by_id(btf, type->type);
15545  		if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15546  			/* btf_func_check() already verified it during BTF load */
15547  			goto err_free;
15548  		ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15549  		scalar_return =
15550  			btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15551  		if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15552  			verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15553  			goto err_free;
15554  		}
15555  		if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15556  			verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15557  			goto err_free;
15558  		}
15559  
15560  		prev_offset = krecord[i].insn_off;
15561  		bpfptr_add(&urecord, urec_size);
15562  	}
15563  
15564  	prog->aux->func_info = krecord;
15565  	prog->aux->func_info_cnt = nfuncs;
15566  	prog->aux->func_info_aux = info_aux;
15567  	return 0;
15568  
15569  err_free:
15570  	kvfree(krecord);
15571  	kfree(info_aux);
15572  	return ret;
15573  }
15574  
adjust_btf_func(struct bpf_verifier_env * env)15575  static void adjust_btf_func(struct bpf_verifier_env *env)
15576  {
15577  	struct bpf_prog_aux *aux = env->prog->aux;
15578  	int i;
15579  
15580  	if (!aux->func_info)
15581  		return;
15582  
15583  	for (i = 0; i < env->subprog_cnt; i++)
15584  		aux->func_info[i].insn_off = env->subprog_info[i].start;
15585  }
15586  
15587  #define MIN_BPF_LINEINFO_SIZE	offsetofend(struct bpf_line_info, line_col)
15588  #define MAX_LINEINFO_REC_SIZE	MAX_FUNCINFO_REC_SIZE
15589  
check_btf_line(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)15590  static int check_btf_line(struct bpf_verifier_env *env,
15591  			  const union bpf_attr *attr,
15592  			  bpfptr_t uattr)
15593  {
15594  	u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15595  	struct bpf_subprog_info *sub;
15596  	struct bpf_line_info *linfo;
15597  	struct bpf_prog *prog;
15598  	const struct btf *btf;
15599  	bpfptr_t ulinfo;
15600  	int err;
15601  
15602  	nr_linfo = attr->line_info_cnt;
15603  	if (!nr_linfo)
15604  		return 0;
15605  	if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15606  		return -EINVAL;
15607  
15608  	rec_size = attr->line_info_rec_size;
15609  	if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15610  	    rec_size > MAX_LINEINFO_REC_SIZE ||
15611  	    rec_size & (sizeof(u32) - 1))
15612  		return -EINVAL;
15613  
15614  	/* Need to zero it in case the userspace may
15615  	 * pass in a smaller bpf_line_info object.
15616  	 */
15617  	linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15618  			 GFP_KERNEL | __GFP_NOWARN);
15619  	if (!linfo)
15620  		return -ENOMEM;
15621  
15622  	prog = env->prog;
15623  	btf = prog->aux->btf;
15624  
15625  	s = 0;
15626  	sub = env->subprog_info;
15627  	ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15628  	expected_size = sizeof(struct bpf_line_info);
15629  	ncopy = min_t(u32, expected_size, rec_size);
15630  	for (i = 0; i < nr_linfo; i++) {
15631  		err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15632  		if (err) {
15633  			if (err == -E2BIG) {
15634  				verbose(env, "nonzero tailing record in line_info");
15635  				if (copy_to_bpfptr_offset(uattr,
15636  							  offsetof(union bpf_attr, line_info_rec_size),
15637  							  &expected_size, sizeof(expected_size)))
15638  					err = -EFAULT;
15639  			}
15640  			goto err_free;
15641  		}
15642  
15643  		if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15644  			err = -EFAULT;
15645  			goto err_free;
15646  		}
15647  
15648  		/*
15649  		 * Check insn_off to ensure
15650  		 * 1) strictly increasing AND
15651  		 * 2) bounded by prog->len
15652  		 *
15653  		 * The linfo[0].insn_off == 0 check logically falls into
15654  		 * the later "missing bpf_line_info for func..." case
15655  		 * because the first linfo[0].insn_off must be the
15656  		 * first sub also and the first sub must have
15657  		 * subprog_info[0].start == 0.
15658  		 */
15659  		if ((i && linfo[i].insn_off <= prev_offset) ||
15660  		    linfo[i].insn_off >= prog->len) {
15661  			verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15662  				i, linfo[i].insn_off, prev_offset,
15663  				prog->len);
15664  			err = -EINVAL;
15665  			goto err_free;
15666  		}
15667  
15668  		if (!prog->insnsi[linfo[i].insn_off].code) {
15669  			verbose(env,
15670  				"Invalid insn code at line_info[%u].insn_off\n",
15671  				i);
15672  			err = -EINVAL;
15673  			goto err_free;
15674  		}
15675  
15676  		if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15677  		    !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15678  			verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15679  			err = -EINVAL;
15680  			goto err_free;
15681  		}
15682  
15683  		if (s != env->subprog_cnt) {
15684  			if (linfo[i].insn_off == sub[s].start) {
15685  				sub[s].linfo_idx = i;
15686  				s++;
15687  			} else if (sub[s].start < linfo[i].insn_off) {
15688  				verbose(env, "missing bpf_line_info for func#%u\n", s);
15689  				err = -EINVAL;
15690  				goto err_free;
15691  			}
15692  		}
15693  
15694  		prev_offset = linfo[i].insn_off;
15695  		bpfptr_add(&ulinfo, rec_size);
15696  	}
15697  
15698  	if (s != env->subprog_cnt) {
15699  		verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15700  			env->subprog_cnt - s, s);
15701  		err = -EINVAL;
15702  		goto err_free;
15703  	}
15704  
15705  	prog->aux->linfo = linfo;
15706  	prog->aux->nr_linfo = nr_linfo;
15707  
15708  	return 0;
15709  
15710  err_free:
15711  	kvfree(linfo);
15712  	return err;
15713  }
15714  
15715  #define MIN_CORE_RELO_SIZE	sizeof(struct bpf_core_relo)
15716  #define MAX_CORE_RELO_SIZE	MAX_FUNCINFO_REC_SIZE
15717  
check_core_relo(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)15718  static int check_core_relo(struct bpf_verifier_env *env,
15719  			   const union bpf_attr *attr,
15720  			   bpfptr_t uattr)
15721  {
15722  	u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15723  	struct bpf_core_relo core_relo = {};
15724  	struct bpf_prog *prog = env->prog;
15725  	const struct btf *btf = prog->aux->btf;
15726  	struct bpf_core_ctx ctx = {
15727  		.log = &env->log,
15728  		.btf = btf,
15729  	};
15730  	bpfptr_t u_core_relo;
15731  	int err;
15732  
15733  	nr_core_relo = attr->core_relo_cnt;
15734  	if (!nr_core_relo)
15735  		return 0;
15736  	if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15737  		return -EINVAL;
15738  
15739  	rec_size = attr->core_relo_rec_size;
15740  	if (rec_size < MIN_CORE_RELO_SIZE ||
15741  	    rec_size > MAX_CORE_RELO_SIZE ||
15742  	    rec_size % sizeof(u32))
15743  		return -EINVAL;
15744  
15745  	u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15746  	expected_size = sizeof(struct bpf_core_relo);
15747  	ncopy = min_t(u32, expected_size, rec_size);
15748  
15749  	/* Unlike func_info and line_info, copy and apply each CO-RE
15750  	 * relocation record one at a time.
15751  	 */
15752  	for (i = 0; i < nr_core_relo; i++) {
15753  		/* future proofing when sizeof(bpf_core_relo) changes */
15754  		err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15755  		if (err) {
15756  			if (err == -E2BIG) {
15757  				verbose(env, "nonzero tailing record in core_relo");
15758  				if (copy_to_bpfptr_offset(uattr,
15759  							  offsetof(union bpf_attr, core_relo_rec_size),
15760  							  &expected_size, sizeof(expected_size)))
15761  					err = -EFAULT;
15762  			}
15763  			break;
15764  		}
15765  
15766  		if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15767  			err = -EFAULT;
15768  			break;
15769  		}
15770  
15771  		if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15772  			verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15773  				i, core_relo.insn_off, prog->len);
15774  			err = -EINVAL;
15775  			break;
15776  		}
15777  
15778  		err = bpf_core_apply(&ctx, &core_relo, i,
15779  				     &prog->insnsi[core_relo.insn_off / 8]);
15780  		if (err)
15781  			break;
15782  		bpfptr_add(&u_core_relo, rec_size);
15783  	}
15784  	return err;
15785  }
15786  
check_btf_info(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)15787  static int check_btf_info(struct bpf_verifier_env *env,
15788  			  const union bpf_attr *attr,
15789  			  bpfptr_t uattr)
15790  {
15791  	struct btf *btf;
15792  	int err;
15793  
15794  	if (!attr->func_info_cnt && !attr->line_info_cnt) {
15795  		if (check_abnormal_return(env))
15796  			return -EINVAL;
15797  		return 0;
15798  	}
15799  
15800  	btf = btf_get_by_fd(attr->prog_btf_fd);
15801  	if (IS_ERR(btf))
15802  		return PTR_ERR(btf);
15803  	if (btf_is_kernel(btf)) {
15804  		btf_put(btf);
15805  		return -EACCES;
15806  	}
15807  	env->prog->aux->btf = btf;
15808  
15809  	err = check_btf_func(env, attr, uattr);
15810  	if (err)
15811  		return err;
15812  
15813  	err = check_btf_line(env, attr, uattr);
15814  	if (err)
15815  		return err;
15816  
15817  	err = check_core_relo(env, attr, uattr);
15818  	if (err)
15819  		return err;
15820  
15821  	return 0;
15822  }
15823  
15824  /* check %cur's range satisfies %old's */
range_within(struct bpf_reg_state * old,struct bpf_reg_state * cur)15825  static bool range_within(struct bpf_reg_state *old,
15826  			 struct bpf_reg_state *cur)
15827  {
15828  	return old->umin_value <= cur->umin_value &&
15829  	       old->umax_value >= cur->umax_value &&
15830  	       old->smin_value <= cur->smin_value &&
15831  	       old->smax_value >= cur->smax_value &&
15832  	       old->u32_min_value <= cur->u32_min_value &&
15833  	       old->u32_max_value >= cur->u32_max_value &&
15834  	       old->s32_min_value <= cur->s32_min_value &&
15835  	       old->s32_max_value >= cur->s32_max_value;
15836  }
15837  
15838  /* If in the old state two registers had the same id, then they need to have
15839   * the same id in the new state as well.  But that id could be different from
15840   * the old state, so we need to track the mapping from old to new ids.
15841   * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15842   * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15843   * regs with a different old id could still have new id 9, we don't care about
15844   * that.
15845   * So we look through our idmap to see if this old id has been seen before.  If
15846   * so, we require the new id to match; otherwise, we add the id pair to the map.
15847   */
check_ids(u32 old_id,u32 cur_id,struct bpf_idmap * idmap)15848  static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15849  {
15850  	struct bpf_id_pair *map = idmap->map;
15851  	unsigned int i;
15852  
15853  	/* either both IDs should be set or both should be zero */
15854  	if (!!old_id != !!cur_id)
15855  		return false;
15856  
15857  	if (old_id == 0) /* cur_id == 0 as well */
15858  		return true;
15859  
15860  	for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15861  		if (!map[i].old) {
15862  			/* Reached an empty slot; haven't seen this id before */
15863  			map[i].old = old_id;
15864  			map[i].cur = cur_id;
15865  			return true;
15866  		}
15867  		if (map[i].old == old_id)
15868  			return map[i].cur == cur_id;
15869  		if (map[i].cur == cur_id)
15870  			return false;
15871  	}
15872  	/* We ran out of idmap slots, which should be impossible */
15873  	WARN_ON_ONCE(1);
15874  	return false;
15875  }
15876  
15877  /* Similar to check_ids(), but allocate a unique temporary ID
15878   * for 'old_id' or 'cur_id' of zero.
15879   * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15880   */
check_scalar_ids(u32 old_id,u32 cur_id,struct bpf_idmap * idmap)15881  static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15882  {
15883  	old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15884  	cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15885  
15886  	return check_ids(old_id, cur_id, idmap);
15887  }
15888  
clean_func_state(struct bpf_verifier_env * env,struct bpf_func_state * st)15889  static void clean_func_state(struct bpf_verifier_env *env,
15890  			     struct bpf_func_state *st)
15891  {
15892  	enum bpf_reg_liveness live;
15893  	int i, j;
15894  
15895  	for (i = 0; i < BPF_REG_FP; i++) {
15896  		live = st->regs[i].live;
15897  		/* liveness must not touch this register anymore */
15898  		st->regs[i].live |= REG_LIVE_DONE;
15899  		if (!(live & REG_LIVE_READ))
15900  			/* since the register is unused, clear its state
15901  			 * to make further comparison simpler
15902  			 */
15903  			__mark_reg_not_init(env, &st->regs[i]);
15904  	}
15905  
15906  	for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15907  		live = st->stack[i].spilled_ptr.live;
15908  		/* liveness must not touch this stack slot anymore */
15909  		st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15910  		if (!(live & REG_LIVE_READ)) {
15911  			__mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15912  			for (j = 0; j < BPF_REG_SIZE; j++)
15913  				st->stack[i].slot_type[j] = STACK_INVALID;
15914  		}
15915  	}
15916  }
15917  
clean_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state * st)15918  static void clean_verifier_state(struct bpf_verifier_env *env,
15919  				 struct bpf_verifier_state *st)
15920  {
15921  	int i;
15922  
15923  	if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15924  		/* all regs in this state in all frames were already marked */
15925  		return;
15926  
15927  	for (i = 0; i <= st->curframe; i++)
15928  		clean_func_state(env, st->frame[i]);
15929  }
15930  
15931  /* the parentage chains form a tree.
15932   * the verifier states are added to state lists at given insn and
15933   * pushed into state stack for future exploration.
15934   * when the verifier reaches bpf_exit insn some of the verifer states
15935   * stored in the state lists have their final liveness state already,
15936   * but a lot of states will get revised from liveness point of view when
15937   * the verifier explores other branches.
15938   * Example:
15939   * 1: r0 = 1
15940   * 2: if r1 == 100 goto pc+1
15941   * 3: r0 = 2
15942   * 4: exit
15943   * when the verifier reaches exit insn the register r0 in the state list of
15944   * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15945   * of insn 2 and goes exploring further. At the insn 4 it will walk the
15946   * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15947   *
15948   * Since the verifier pushes the branch states as it sees them while exploring
15949   * the program the condition of walking the branch instruction for the second
15950   * time means that all states below this branch were already explored and
15951   * their final liveness marks are already propagated.
15952   * Hence when the verifier completes the search of state list in is_state_visited()
15953   * we can call this clean_live_states() function to mark all liveness states
15954   * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15955   * will not be used.
15956   * This function also clears the registers and stack for states that !READ
15957   * to simplify state merging.
15958   *
15959   * Important note here that walking the same branch instruction in the callee
15960   * doesn't meant that the states are DONE. The verifier has to compare
15961   * the callsites
15962   */
clean_live_states(struct bpf_verifier_env * env,int insn,struct bpf_verifier_state * cur)15963  static void clean_live_states(struct bpf_verifier_env *env, int insn,
15964  			      struct bpf_verifier_state *cur)
15965  {
15966  	struct bpf_verifier_state_list *sl;
15967  
15968  	sl = *explored_state(env, insn);
15969  	while (sl) {
15970  		if (sl->state.branches)
15971  			goto next;
15972  		if (sl->state.insn_idx != insn ||
15973  		    !same_callsites(&sl->state, cur))
15974  			goto next;
15975  		clean_verifier_state(env, &sl->state);
15976  next:
15977  		sl = sl->next;
15978  	}
15979  }
15980  
regs_exact(const struct bpf_reg_state * rold,const struct bpf_reg_state * rcur,struct bpf_idmap * idmap)15981  static bool regs_exact(const struct bpf_reg_state *rold,
15982  		       const struct bpf_reg_state *rcur,
15983  		       struct bpf_idmap *idmap)
15984  {
15985  	return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15986  	       check_ids(rold->id, rcur->id, idmap) &&
15987  	       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15988  }
15989  
15990  /* Returns true if (rold safe implies rcur safe) */
regsafe(struct bpf_verifier_env * env,struct bpf_reg_state * rold,struct bpf_reg_state * rcur,struct bpf_idmap * idmap,bool exact)15991  static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15992  		    struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
15993  {
15994  	if (exact)
15995  		return regs_exact(rold, rcur, idmap);
15996  
15997  	if (!(rold->live & REG_LIVE_READ))
15998  		/* explored state didn't use this */
15999  		return true;
16000  	if (rold->type == NOT_INIT)
16001  		/* explored state can't have used this */
16002  		return true;
16003  	if (rcur->type == NOT_INIT)
16004  		return false;
16005  
16006  	/* Enforce that register types have to match exactly, including their
16007  	 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16008  	 * rule.
16009  	 *
16010  	 * One can make a point that using a pointer register as unbounded
16011  	 * SCALAR would be technically acceptable, but this could lead to
16012  	 * pointer leaks because scalars are allowed to leak while pointers
16013  	 * are not. We could make this safe in special cases if root is
16014  	 * calling us, but it's probably not worth the hassle.
16015  	 *
16016  	 * Also, register types that are *not* MAYBE_NULL could technically be
16017  	 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16018  	 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16019  	 * to the same map).
16020  	 * However, if the old MAYBE_NULL register then got NULL checked,
16021  	 * doing so could have affected others with the same id, and we can't
16022  	 * check for that because we lost the id when we converted to
16023  	 * a non-MAYBE_NULL variant.
16024  	 * So, as a general rule we don't allow mixing MAYBE_NULL and
16025  	 * non-MAYBE_NULL registers as well.
16026  	 */
16027  	if (rold->type != rcur->type)
16028  		return false;
16029  
16030  	switch (base_type(rold->type)) {
16031  	case SCALAR_VALUE:
16032  		if (env->explore_alu_limits) {
16033  			/* explore_alu_limits disables tnum_in() and range_within()
16034  			 * logic and requires everything to be strict
16035  			 */
16036  			return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16037  			       check_scalar_ids(rold->id, rcur->id, idmap);
16038  		}
16039  		if (!rold->precise)
16040  			return true;
16041  		/* Why check_ids() for scalar registers?
16042  		 *
16043  		 * Consider the following BPF code:
16044  		 *   1: r6 = ... unbound scalar, ID=a ...
16045  		 *   2: r7 = ... unbound scalar, ID=b ...
16046  		 *   3: if (r6 > r7) goto +1
16047  		 *   4: r6 = r7
16048  		 *   5: if (r6 > X) goto ...
16049  		 *   6: ... memory operation using r7 ...
16050  		 *
16051  		 * First verification path is [1-6]:
16052  		 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16053  		 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16054  		 *   r7 <= X, because r6 and r7 share same id.
16055  		 * Next verification path is [1-4, 6].
16056  		 *
16057  		 * Instruction (6) would be reached in two states:
16058  		 *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
16059  		 *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16060  		 *
16061  		 * Use check_ids() to distinguish these states.
16062  		 * ---
16063  		 * Also verify that new value satisfies old value range knowledge.
16064  		 */
16065  		return range_within(rold, rcur) &&
16066  		       tnum_in(rold->var_off, rcur->var_off) &&
16067  		       check_scalar_ids(rold->id, rcur->id, idmap);
16068  	case PTR_TO_MAP_KEY:
16069  	case PTR_TO_MAP_VALUE:
16070  	case PTR_TO_MEM:
16071  	case PTR_TO_BUF:
16072  	case PTR_TO_TP_BUFFER:
16073  		/* If the new min/max/var_off satisfy the old ones and
16074  		 * everything else matches, we are OK.
16075  		 */
16076  		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16077  		       range_within(rold, rcur) &&
16078  		       tnum_in(rold->var_off, rcur->var_off) &&
16079  		       check_ids(rold->id, rcur->id, idmap) &&
16080  		       check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16081  	case PTR_TO_PACKET_META:
16082  	case PTR_TO_PACKET:
16083  		/* We must have at least as much range as the old ptr
16084  		 * did, so that any accesses which were safe before are
16085  		 * still safe.  This is true even if old range < old off,
16086  		 * since someone could have accessed through (ptr - k), or
16087  		 * even done ptr -= k in a register, to get a safe access.
16088  		 */
16089  		if (rold->range > rcur->range)
16090  			return false;
16091  		/* If the offsets don't match, we can't trust our alignment;
16092  		 * nor can we be sure that we won't fall out of range.
16093  		 */
16094  		if (rold->off != rcur->off)
16095  			return false;
16096  		/* id relations must be preserved */
16097  		if (!check_ids(rold->id, rcur->id, idmap))
16098  			return false;
16099  		/* new val must satisfy old val knowledge */
16100  		return range_within(rold, rcur) &&
16101  		       tnum_in(rold->var_off, rcur->var_off);
16102  	case PTR_TO_STACK:
16103  		/* two stack pointers are equal only if they're pointing to
16104  		 * the same stack frame, since fp-8 in foo != fp-8 in bar
16105  		 */
16106  		return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16107  	default:
16108  		return regs_exact(rold, rcur, idmap);
16109  	}
16110  }
16111  
stacksafe(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_idmap * idmap,bool exact)16112  static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16113  		      struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
16114  {
16115  	int i, spi;
16116  
16117  	/* walk slots of the explored stack and ignore any additional
16118  	 * slots in the current stack, since explored(safe) state
16119  	 * didn't use them
16120  	 */
16121  	for (i = 0; i < old->allocated_stack; i++) {
16122  		struct bpf_reg_state *old_reg, *cur_reg;
16123  
16124  		spi = i / BPF_REG_SIZE;
16125  
16126  		if (exact &&
16127  		    (i >= cur->allocated_stack ||
16128  		     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16129  		     cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
16130  			return false;
16131  
16132  		if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
16133  			i += BPF_REG_SIZE - 1;
16134  			/* explored state didn't use this */
16135  			continue;
16136  		}
16137  
16138  		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16139  			continue;
16140  
16141  		if (env->allow_uninit_stack &&
16142  		    old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16143  			continue;
16144  
16145  		/* explored stack has more populated slots than current stack
16146  		 * and these slots were used
16147  		 */
16148  		if (i >= cur->allocated_stack)
16149  			return false;
16150  
16151  		/* if old state was safe with misc data in the stack
16152  		 * it will be safe with zero-initialized stack.
16153  		 * The opposite is not true
16154  		 */
16155  		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16156  		    cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16157  			continue;
16158  		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16159  		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16160  			/* Ex: old explored (safe) state has STACK_SPILL in
16161  			 * this stack slot, but current has STACK_MISC ->
16162  			 * this verifier states are not equivalent,
16163  			 * return false to continue verification of this path
16164  			 */
16165  			return false;
16166  		if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16167  			continue;
16168  		/* Both old and cur are having same slot_type */
16169  		switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16170  		case STACK_SPILL:
16171  			/* when explored and current stack slot are both storing
16172  			 * spilled registers, check that stored pointers types
16173  			 * are the same as well.
16174  			 * Ex: explored safe path could have stored
16175  			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16176  			 * but current path has stored:
16177  			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16178  			 * such verifier states are not equivalent.
16179  			 * return false to continue verification of this path
16180  			 */
16181  			if (!regsafe(env, &old->stack[spi].spilled_ptr,
16182  				     &cur->stack[spi].spilled_ptr, idmap, exact))
16183  				return false;
16184  			break;
16185  		case STACK_DYNPTR:
16186  			old_reg = &old->stack[spi].spilled_ptr;
16187  			cur_reg = &cur->stack[spi].spilled_ptr;
16188  			if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16189  			    old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16190  			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16191  				return false;
16192  			break;
16193  		case STACK_ITER:
16194  			old_reg = &old->stack[spi].spilled_ptr;
16195  			cur_reg = &cur->stack[spi].spilled_ptr;
16196  			/* iter.depth is not compared between states as it
16197  			 * doesn't matter for correctness and would otherwise
16198  			 * prevent convergence; we maintain it only to prevent
16199  			 * infinite loop check triggering, see
16200  			 * iter_active_depths_differ()
16201  			 */
16202  			if (old_reg->iter.btf != cur_reg->iter.btf ||
16203  			    old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16204  			    old_reg->iter.state != cur_reg->iter.state ||
16205  			    /* ignore {old_reg,cur_reg}->iter.depth, see above */
16206  			    !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16207  				return false;
16208  			break;
16209  		case STACK_MISC:
16210  		case STACK_ZERO:
16211  		case STACK_INVALID:
16212  			continue;
16213  		/* Ensure that new unhandled slot types return false by default */
16214  		default:
16215  			return false;
16216  		}
16217  	}
16218  	return true;
16219  }
16220  
refsafe(struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_idmap * idmap)16221  static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16222  		    struct bpf_idmap *idmap)
16223  {
16224  	int i;
16225  
16226  	if (old->acquired_refs != cur->acquired_refs)
16227  		return false;
16228  
16229  	for (i = 0; i < old->acquired_refs; i++) {
16230  		if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16231  			return false;
16232  	}
16233  
16234  	return true;
16235  }
16236  
16237  /* compare two verifier states
16238   *
16239   * all states stored in state_list are known to be valid, since
16240   * verifier reached 'bpf_exit' instruction through them
16241   *
16242   * this function is called when verifier exploring different branches of
16243   * execution popped from the state stack. If it sees an old state that has
16244   * more strict register state and more strict stack state then this execution
16245   * branch doesn't need to be explored further, since verifier already
16246   * concluded that more strict state leads to valid finish.
16247   *
16248   * Therefore two states are equivalent if register state is more conservative
16249   * and explored stack state is more conservative than the current one.
16250   * Example:
16251   *       explored                   current
16252   * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16253   * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16254   *
16255   * In other words if current stack state (one being explored) has more
16256   * valid slots than old one that already passed validation, it means
16257   * the verifier can stop exploring and conclude that current state is valid too
16258   *
16259   * Similarly with registers. If explored state has register type as invalid
16260   * whereas register type in current state is meaningful, it means that
16261   * the current state will reach 'bpf_exit' instruction safely
16262   */
func_states_equal(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,bool exact)16263  static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16264  			      struct bpf_func_state *cur, bool exact)
16265  {
16266  	int i;
16267  
16268  	if (old->callback_depth > cur->callback_depth)
16269  		return false;
16270  
16271  	for (i = 0; i < MAX_BPF_REG; i++)
16272  		if (!regsafe(env, &old->regs[i], &cur->regs[i],
16273  			     &env->idmap_scratch, exact))
16274  			return false;
16275  
16276  	if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16277  		return false;
16278  
16279  	if (!refsafe(old, cur, &env->idmap_scratch))
16280  		return false;
16281  
16282  	return true;
16283  }
16284  
reset_idmap_scratch(struct bpf_verifier_env * env)16285  static void reset_idmap_scratch(struct bpf_verifier_env *env)
16286  {
16287  	env->idmap_scratch.tmp_id_gen = env->id_gen;
16288  	memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16289  }
16290  
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur,bool exact)16291  static bool states_equal(struct bpf_verifier_env *env,
16292  			 struct bpf_verifier_state *old,
16293  			 struct bpf_verifier_state *cur,
16294  			 bool exact)
16295  {
16296  	int i;
16297  
16298  	if (old->curframe != cur->curframe)
16299  		return false;
16300  
16301  	reset_idmap_scratch(env);
16302  
16303  	/* Verification state from speculative execution simulation
16304  	 * must never prune a non-speculative execution one.
16305  	 */
16306  	if (old->speculative && !cur->speculative)
16307  		return false;
16308  
16309  	if (old->active_lock.ptr != cur->active_lock.ptr)
16310  		return false;
16311  
16312  	/* Old and cur active_lock's have to be either both present
16313  	 * or both absent.
16314  	 */
16315  	if (!!old->active_lock.id != !!cur->active_lock.id)
16316  		return false;
16317  
16318  	if (old->active_lock.id &&
16319  	    !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16320  		return false;
16321  
16322  	if (old->active_rcu_lock != cur->active_rcu_lock)
16323  		return false;
16324  
16325  	/* for states to be equal callsites have to be the same
16326  	 * and all frame states need to be equivalent
16327  	 */
16328  	for (i = 0; i <= old->curframe; i++) {
16329  		if (old->frame[i]->callsite != cur->frame[i]->callsite)
16330  			return false;
16331  		if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16332  			return false;
16333  	}
16334  	return true;
16335  }
16336  
16337  /* Return 0 if no propagation happened. Return negative error code if error
16338   * happened. Otherwise, return the propagated bit.
16339   */
propagate_liveness_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct bpf_reg_state * parent_reg)16340  static int propagate_liveness_reg(struct bpf_verifier_env *env,
16341  				  struct bpf_reg_state *reg,
16342  				  struct bpf_reg_state *parent_reg)
16343  {
16344  	u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16345  	u8 flag = reg->live & REG_LIVE_READ;
16346  	int err;
16347  
16348  	/* When comes here, read flags of PARENT_REG or REG could be any of
16349  	 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16350  	 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16351  	 */
16352  	if (parent_flag == REG_LIVE_READ64 ||
16353  	    /* Or if there is no read flag from REG. */
16354  	    !flag ||
16355  	    /* Or if the read flag from REG is the same as PARENT_REG. */
16356  	    parent_flag == flag)
16357  		return 0;
16358  
16359  	err = mark_reg_read(env, reg, parent_reg, flag);
16360  	if (err)
16361  		return err;
16362  
16363  	return flag;
16364  }
16365  
16366  /* A write screens off any subsequent reads; but write marks come from the
16367   * straight-line code between a state and its parent.  When we arrive at an
16368   * equivalent state (jump target or such) we didn't arrive by the straight-line
16369   * code, so read marks in the state must propagate to the parent regardless
16370   * of the state's write marks. That's what 'parent == state->parent' comparison
16371   * in mark_reg_read() is for.
16372   */
propagate_liveness(struct bpf_verifier_env * env,const struct bpf_verifier_state * vstate,struct bpf_verifier_state * vparent)16373  static int propagate_liveness(struct bpf_verifier_env *env,
16374  			      const struct bpf_verifier_state *vstate,
16375  			      struct bpf_verifier_state *vparent)
16376  {
16377  	struct bpf_reg_state *state_reg, *parent_reg;
16378  	struct bpf_func_state *state, *parent;
16379  	int i, frame, err = 0;
16380  
16381  	if (vparent->curframe != vstate->curframe) {
16382  		WARN(1, "propagate_live: parent frame %d current frame %d\n",
16383  		     vparent->curframe, vstate->curframe);
16384  		return -EFAULT;
16385  	}
16386  	/* Propagate read liveness of registers... */
16387  	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16388  	for (frame = 0; frame <= vstate->curframe; frame++) {
16389  		parent = vparent->frame[frame];
16390  		state = vstate->frame[frame];
16391  		parent_reg = parent->regs;
16392  		state_reg = state->regs;
16393  		/* We don't need to worry about FP liveness, it's read-only */
16394  		for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16395  			err = propagate_liveness_reg(env, &state_reg[i],
16396  						     &parent_reg[i]);
16397  			if (err < 0)
16398  				return err;
16399  			if (err == REG_LIVE_READ64)
16400  				mark_insn_zext(env, &parent_reg[i]);
16401  		}
16402  
16403  		/* Propagate stack slots. */
16404  		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16405  			    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16406  			parent_reg = &parent->stack[i].spilled_ptr;
16407  			state_reg = &state->stack[i].spilled_ptr;
16408  			err = propagate_liveness_reg(env, state_reg,
16409  						     parent_reg);
16410  			if (err < 0)
16411  				return err;
16412  		}
16413  	}
16414  	return 0;
16415  }
16416  
16417  /* find precise scalars in the previous equivalent state and
16418   * propagate them into the current state
16419   */
propagate_precision(struct bpf_verifier_env * env,const struct bpf_verifier_state * old)16420  static int propagate_precision(struct bpf_verifier_env *env,
16421  			       const struct bpf_verifier_state *old)
16422  {
16423  	struct bpf_reg_state *state_reg;
16424  	struct bpf_func_state *state;
16425  	int i, err = 0, fr;
16426  	bool first;
16427  
16428  	for (fr = old->curframe; fr >= 0; fr--) {
16429  		state = old->frame[fr];
16430  		state_reg = state->regs;
16431  		first = true;
16432  		for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16433  			if (state_reg->type != SCALAR_VALUE ||
16434  			    !state_reg->precise ||
16435  			    !(state_reg->live & REG_LIVE_READ))
16436  				continue;
16437  			if (env->log.level & BPF_LOG_LEVEL2) {
16438  				if (first)
16439  					verbose(env, "frame %d: propagating r%d", fr, i);
16440  				else
16441  					verbose(env, ",r%d", i);
16442  			}
16443  			bt_set_frame_reg(&env->bt, fr, i);
16444  			first = false;
16445  		}
16446  
16447  		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16448  			if (!is_spilled_reg(&state->stack[i]))
16449  				continue;
16450  			state_reg = &state->stack[i].spilled_ptr;
16451  			if (state_reg->type != SCALAR_VALUE ||
16452  			    !state_reg->precise ||
16453  			    !(state_reg->live & REG_LIVE_READ))
16454  				continue;
16455  			if (env->log.level & BPF_LOG_LEVEL2) {
16456  				if (first)
16457  					verbose(env, "frame %d: propagating fp%d",
16458  						fr, (-i - 1) * BPF_REG_SIZE);
16459  				else
16460  					verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16461  			}
16462  			bt_set_frame_slot(&env->bt, fr, i);
16463  			first = false;
16464  		}
16465  		if (!first)
16466  			verbose(env, "\n");
16467  	}
16468  
16469  	err = mark_chain_precision_batch(env);
16470  	if (err < 0)
16471  		return err;
16472  
16473  	return 0;
16474  }
16475  
states_maybe_looping(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)16476  static bool states_maybe_looping(struct bpf_verifier_state *old,
16477  				 struct bpf_verifier_state *cur)
16478  {
16479  	struct bpf_func_state *fold, *fcur;
16480  	int i, fr = cur->curframe;
16481  
16482  	if (old->curframe != fr)
16483  		return false;
16484  
16485  	fold = old->frame[fr];
16486  	fcur = cur->frame[fr];
16487  	for (i = 0; i < MAX_BPF_REG; i++)
16488  		if (memcmp(&fold->regs[i], &fcur->regs[i],
16489  			   offsetof(struct bpf_reg_state, parent)))
16490  			return false;
16491  	return true;
16492  }
16493  
is_iter_next_insn(struct bpf_verifier_env * env,int insn_idx)16494  static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16495  {
16496  	return env->insn_aux_data[insn_idx].is_iter_next;
16497  }
16498  
16499  /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16500   * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16501   * states to match, which otherwise would look like an infinite loop. So while
16502   * iter_next() calls are taken care of, we still need to be careful and
16503   * prevent erroneous and too eager declaration of "ininite loop", when
16504   * iterators are involved.
16505   *
16506   * Here's a situation in pseudo-BPF assembly form:
16507   *
16508   *   0: again:                          ; set up iter_next() call args
16509   *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16510   *   2:   call bpf_iter_num_next        ; this is iter_next() call
16511   *   3:   if r0 == 0 goto done
16512   *   4:   ... something useful here ...
16513   *   5:   goto again                    ; another iteration
16514   *   6: done:
16515   *   7:   r1 = &it
16516   *   8:   call bpf_iter_num_destroy     ; clean up iter state
16517   *   9:   exit
16518   *
16519   * This is a typical loop. Let's assume that we have a prune point at 1:,
16520   * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16521   * again`, assuming other heuristics don't get in a way).
16522   *
16523   * When we first time come to 1:, let's say we have some state X. We proceed
16524   * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16525   * Now we come back to validate that forked ACTIVE state. We proceed through
16526   * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16527   * are converging. But the problem is that we don't know that yet, as this
16528   * convergence has to happen at iter_next() call site only. So if nothing is
16529   * done, at 1: verifier will use bounded loop logic and declare infinite
16530   * looping (and would be *technically* correct, if not for iterator's
16531   * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16532   * don't want that. So what we do in process_iter_next_call() when we go on
16533   * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16534   * a different iteration. So when we suspect an infinite loop, we additionally
16535   * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16536   * pretend we are not looping and wait for next iter_next() call.
16537   *
16538   * This only applies to ACTIVE state. In DRAINED state we don't expect to
16539   * loop, because that would actually mean infinite loop, as DRAINED state is
16540   * "sticky", and so we'll keep returning into the same instruction with the
16541   * same state (at least in one of possible code paths).
16542   *
16543   * This approach allows to keep infinite loop heuristic even in the face of
16544   * active iterator. E.g., C snippet below is and will be detected as
16545   * inifintely looping:
16546   *
16547   *   struct bpf_iter_num it;
16548   *   int *p, x;
16549   *
16550   *   bpf_iter_num_new(&it, 0, 10);
16551   *   while ((p = bpf_iter_num_next(&t))) {
16552   *       x = p;
16553   *       while (x--) {} // <<-- infinite loop here
16554   *   }
16555   *
16556   */
iter_active_depths_differ(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)16557  static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16558  {
16559  	struct bpf_reg_state *slot, *cur_slot;
16560  	struct bpf_func_state *state;
16561  	int i, fr;
16562  
16563  	for (fr = old->curframe; fr >= 0; fr--) {
16564  		state = old->frame[fr];
16565  		for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16566  			if (state->stack[i].slot_type[0] != STACK_ITER)
16567  				continue;
16568  
16569  			slot = &state->stack[i].spilled_ptr;
16570  			if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16571  				continue;
16572  
16573  			cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16574  			if (cur_slot->iter.depth != slot->iter.depth)
16575  				return true;
16576  		}
16577  	}
16578  	return false;
16579  }
16580  
is_state_visited(struct bpf_verifier_env * env,int insn_idx)16581  static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16582  {
16583  	struct bpf_verifier_state_list *new_sl;
16584  	struct bpf_verifier_state_list *sl, **pprev;
16585  	struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
16586  	int i, j, n, err, states_cnt = 0;
16587  	bool force_new_state, add_new_state, force_exact;
16588  
16589  	force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) ||
16590  			  /* Avoid accumulating infinitely long jmp history */
16591  			  cur->jmp_history_cnt > 40;
16592  
16593  	/* bpf progs typically have pruning point every 4 instructions
16594  	 * http://vger.kernel.org/bpfconf2019.html#session-1
16595  	 * Do not add new state for future pruning if the verifier hasn't seen
16596  	 * at least 2 jumps and at least 8 instructions.
16597  	 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16598  	 * In tests that amounts to up to 50% reduction into total verifier
16599  	 * memory consumption and 20% verifier time speedup.
16600  	 */
16601  	add_new_state = force_new_state;
16602  	if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16603  	    env->insn_processed - env->prev_insn_processed >= 8)
16604  		add_new_state = true;
16605  
16606  	pprev = explored_state(env, insn_idx);
16607  	sl = *pprev;
16608  
16609  	clean_live_states(env, insn_idx, cur);
16610  
16611  	while (sl) {
16612  		states_cnt++;
16613  		if (sl->state.insn_idx != insn_idx)
16614  			goto next;
16615  
16616  		if (sl->state.branches) {
16617  			struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16618  
16619  			if (frame->in_async_callback_fn &&
16620  			    frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16621  				/* Different async_entry_cnt means that the verifier is
16622  				 * processing another entry into async callback.
16623  				 * Seeing the same state is not an indication of infinite
16624  				 * loop or infinite recursion.
16625  				 * But finding the same state doesn't mean that it's safe
16626  				 * to stop processing the current state. The previous state
16627  				 * hasn't yet reached bpf_exit, since state.branches > 0.
16628  				 * Checking in_async_callback_fn alone is not enough either.
16629  				 * Since the verifier still needs to catch infinite loops
16630  				 * inside async callbacks.
16631  				 */
16632  				goto skip_inf_loop_check;
16633  			}
16634  			/* BPF open-coded iterators loop detection is special.
16635  			 * states_maybe_looping() logic is too simplistic in detecting
16636  			 * states that *might* be equivalent, because it doesn't know
16637  			 * about ID remapping, so don't even perform it.
16638  			 * See process_iter_next_call() and iter_active_depths_differ()
16639  			 * for overview of the logic. When current and one of parent
16640  			 * states are detected as equivalent, it's a good thing: we prove
16641  			 * convergence and can stop simulating further iterations.
16642  			 * It's safe to assume that iterator loop will finish, taking into
16643  			 * account iter_next() contract of eventually returning
16644  			 * sticky NULL result.
16645  			 *
16646  			 * Note, that states have to be compared exactly in this case because
16647  			 * read and precision marks might not be finalized inside the loop.
16648  			 * E.g. as in the program below:
16649  			 *
16650  			 *     1. r7 = -16
16651  			 *     2. r6 = bpf_get_prandom_u32()
16652  			 *     3. while (bpf_iter_num_next(&fp[-8])) {
16653  			 *     4.   if (r6 != 42) {
16654  			 *     5.     r7 = -32
16655  			 *     6.     r6 = bpf_get_prandom_u32()
16656  			 *     7.     continue
16657  			 *     8.   }
16658  			 *     9.   r0 = r10
16659  			 *    10.   r0 += r7
16660  			 *    11.   r8 = *(u64 *)(r0 + 0)
16661  			 *    12.   r6 = bpf_get_prandom_u32()
16662  			 *    13. }
16663  			 *
16664  			 * Here verifier would first visit path 1-3, create a checkpoint at 3
16665  			 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
16666  			 * not have read or precision mark for r7 yet, thus inexact states
16667  			 * comparison would discard current state with r7=-32
16668  			 * => unsafe memory access at 11 would not be caught.
16669  			 */
16670  			if (is_iter_next_insn(env, insn_idx)) {
16671  				if (states_equal(env, &sl->state, cur, true)) {
16672  					struct bpf_func_state *cur_frame;
16673  					struct bpf_reg_state *iter_state, *iter_reg;
16674  					int spi;
16675  
16676  					cur_frame = cur->frame[cur->curframe];
16677  					/* btf_check_iter_kfuncs() enforces that
16678  					 * iter state pointer is always the first arg
16679  					 */
16680  					iter_reg = &cur_frame->regs[BPF_REG_1];
16681  					/* current state is valid due to states_equal(),
16682  					 * so we can assume valid iter and reg state,
16683  					 * no need for extra (re-)validations
16684  					 */
16685  					spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16686  					iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16687  					if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
16688  						update_loop_entry(cur, &sl->state);
16689  						goto hit;
16690  					}
16691  				}
16692  				goto skip_inf_loop_check;
16693  			}
16694  			if (calls_callback(env, insn_idx)) {
16695  				if (states_equal(env, &sl->state, cur, true))
16696  					goto hit;
16697  				goto skip_inf_loop_check;
16698  			}
16699  			/* attempt to detect infinite loop to avoid unnecessary doomed work */
16700  			if (states_maybe_looping(&sl->state, cur) &&
16701  			    states_equal(env, &sl->state, cur, false) &&
16702  			    !iter_active_depths_differ(&sl->state, cur) &&
16703  			    sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
16704  				verbose_linfo(env, insn_idx, "; ");
16705  				verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16706  				verbose(env, "cur state:");
16707  				print_verifier_state(env, cur->frame[cur->curframe], true);
16708  				verbose(env, "old state:");
16709  				print_verifier_state(env, sl->state.frame[cur->curframe], true);
16710  				return -EINVAL;
16711  			}
16712  			/* if the verifier is processing a loop, avoid adding new state
16713  			 * too often, since different loop iterations have distinct
16714  			 * states and may not help future pruning.
16715  			 * This threshold shouldn't be too low to make sure that
16716  			 * a loop with large bound will be rejected quickly.
16717  			 * The most abusive loop will be:
16718  			 * r1 += 1
16719  			 * if r1 < 1000000 goto pc-2
16720  			 * 1M insn_procssed limit / 100 == 10k peak states.
16721  			 * This threshold shouldn't be too high either, since states
16722  			 * at the end of the loop are likely to be useful in pruning.
16723  			 */
16724  skip_inf_loop_check:
16725  			if (!force_new_state &&
16726  			    env->jmps_processed - env->prev_jmps_processed < 20 &&
16727  			    env->insn_processed - env->prev_insn_processed < 100)
16728  				add_new_state = false;
16729  			goto miss;
16730  		}
16731  		/* If sl->state is a part of a loop and this loop's entry is a part of
16732  		 * current verification path then states have to be compared exactly.
16733  		 * 'force_exact' is needed to catch the following case:
16734  		 *
16735  		 *                initial     Here state 'succ' was processed first,
16736  		 *                  |         it was eventually tracked to produce a
16737  		 *                  V         state identical to 'hdr'.
16738  		 *     .---------> hdr        All branches from 'succ' had been explored
16739  		 *     |            |         and thus 'succ' has its .branches == 0.
16740  		 *     |            V
16741  		 *     |    .------...        Suppose states 'cur' and 'succ' correspond
16742  		 *     |    |       |         to the same instruction + callsites.
16743  		 *     |    V       V         In such case it is necessary to check
16744  		 *     |   ...     ...        if 'succ' and 'cur' are states_equal().
16745  		 *     |    |       |         If 'succ' and 'cur' are a part of the
16746  		 *     |    V       V         same loop exact flag has to be set.
16747  		 *     |   succ <- cur        To check if that is the case, verify
16748  		 *     |    |                 if loop entry of 'succ' is in current
16749  		 *     |    V                 DFS path.
16750  		 *     |   ...
16751  		 *     |    |
16752  		 *     '----'
16753  		 *
16754  		 * Additional details are in the comment before get_loop_entry().
16755  		 */
16756  		loop_entry = get_loop_entry(&sl->state);
16757  		force_exact = loop_entry && loop_entry->branches > 0;
16758  		if (states_equal(env, &sl->state, cur, force_exact)) {
16759  			if (force_exact)
16760  				update_loop_entry(cur, loop_entry);
16761  hit:
16762  			sl->hit_cnt++;
16763  			/* reached equivalent register/stack state,
16764  			 * prune the search.
16765  			 * Registers read by the continuation are read by us.
16766  			 * If we have any write marks in env->cur_state, they
16767  			 * will prevent corresponding reads in the continuation
16768  			 * from reaching our parent (an explored_state).  Our
16769  			 * own state will get the read marks recorded, but
16770  			 * they'll be immediately forgotten as we're pruning
16771  			 * this state and will pop a new one.
16772  			 */
16773  			err = propagate_liveness(env, &sl->state, cur);
16774  
16775  			/* if previous state reached the exit with precision and
16776  			 * current state is equivalent to it (except precsion marks)
16777  			 * the precision needs to be propagated back in
16778  			 * the current state.
16779  			 */
16780  			err = err ? : push_jmp_history(env, cur);
16781  			err = err ? : propagate_precision(env, &sl->state);
16782  			if (err)
16783  				return err;
16784  			return 1;
16785  		}
16786  miss:
16787  		/* when new state is not going to be added do not increase miss count.
16788  		 * Otherwise several loop iterations will remove the state
16789  		 * recorded earlier. The goal of these heuristics is to have
16790  		 * states from some iterations of the loop (some in the beginning
16791  		 * and some at the end) to help pruning.
16792  		 */
16793  		if (add_new_state)
16794  			sl->miss_cnt++;
16795  		/* heuristic to determine whether this state is beneficial
16796  		 * to keep checking from state equivalence point of view.
16797  		 * Higher numbers increase max_states_per_insn and verification time,
16798  		 * but do not meaningfully decrease insn_processed.
16799  		 * 'n' controls how many times state could miss before eviction.
16800  		 * Use bigger 'n' for checkpoints because evicting checkpoint states
16801  		 * too early would hinder iterator convergence.
16802  		 */
16803  		n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
16804  		if (sl->miss_cnt > sl->hit_cnt * n + n) {
16805  			/* the state is unlikely to be useful. Remove it to
16806  			 * speed up verification
16807  			 */
16808  			*pprev = sl->next;
16809  			if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
16810  			    !sl->state.used_as_loop_entry) {
16811  				u32 br = sl->state.branches;
16812  
16813  				WARN_ONCE(br,
16814  					  "BUG live_done but branches_to_explore %d\n",
16815  					  br);
16816  				free_verifier_state(&sl->state, false);
16817  				kfree(sl);
16818  				env->peak_states--;
16819  			} else {
16820  				/* cannot free this state, since parentage chain may
16821  				 * walk it later. Add it for free_list instead to
16822  				 * be freed at the end of verification
16823  				 */
16824  				sl->next = env->free_list;
16825  				env->free_list = sl;
16826  			}
16827  			sl = *pprev;
16828  			continue;
16829  		}
16830  next:
16831  		pprev = &sl->next;
16832  		sl = *pprev;
16833  	}
16834  
16835  	if (env->max_states_per_insn < states_cnt)
16836  		env->max_states_per_insn = states_cnt;
16837  
16838  	if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16839  		return 0;
16840  
16841  	if (!add_new_state)
16842  		return 0;
16843  
16844  	/* There were no equivalent states, remember the current one.
16845  	 * Technically the current state is not proven to be safe yet,
16846  	 * but it will either reach outer most bpf_exit (which means it's safe)
16847  	 * or it will be rejected. When there are no loops the verifier won't be
16848  	 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16849  	 * again on the way to bpf_exit.
16850  	 * When looping the sl->state.branches will be > 0 and this state
16851  	 * will not be considered for equivalence until branches == 0.
16852  	 */
16853  	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16854  	if (!new_sl)
16855  		return -ENOMEM;
16856  	env->total_states++;
16857  	env->peak_states++;
16858  	env->prev_jmps_processed = env->jmps_processed;
16859  	env->prev_insn_processed = env->insn_processed;
16860  
16861  	/* forget precise markings we inherited, see __mark_chain_precision */
16862  	if (env->bpf_capable)
16863  		mark_all_scalars_imprecise(env, cur);
16864  
16865  	/* add new state to the head of linked list */
16866  	new = &new_sl->state;
16867  	err = copy_verifier_state(new, cur);
16868  	if (err) {
16869  		free_verifier_state(new, false);
16870  		kfree(new_sl);
16871  		return err;
16872  	}
16873  	new->insn_idx = insn_idx;
16874  	WARN_ONCE(new->branches != 1,
16875  		  "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16876  
16877  	cur->parent = new;
16878  	cur->first_insn_idx = insn_idx;
16879  	cur->dfs_depth = new->dfs_depth + 1;
16880  	clear_jmp_history(cur);
16881  	new_sl->next = *explored_state(env, insn_idx);
16882  	*explored_state(env, insn_idx) = new_sl;
16883  	/* connect new state to parentage chain. Current frame needs all
16884  	 * registers connected. Only r6 - r9 of the callers are alive (pushed
16885  	 * to the stack implicitly by JITs) so in callers' frames connect just
16886  	 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16887  	 * the state of the call instruction (with WRITTEN set), and r0 comes
16888  	 * from callee with its full parentage chain, anyway.
16889  	 */
16890  	/* clear write marks in current state: the writes we did are not writes
16891  	 * our child did, so they don't screen off its reads from us.
16892  	 * (There are no read marks in current state, because reads always mark
16893  	 * their parent and current state never has children yet.  Only
16894  	 * explored_states can get read marks.)
16895  	 */
16896  	for (j = 0; j <= cur->curframe; j++) {
16897  		for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16898  			cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16899  		for (i = 0; i < BPF_REG_FP; i++)
16900  			cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16901  	}
16902  
16903  	/* all stack frames are accessible from callee, clear them all */
16904  	for (j = 0; j <= cur->curframe; j++) {
16905  		struct bpf_func_state *frame = cur->frame[j];
16906  		struct bpf_func_state *newframe = new->frame[j];
16907  
16908  		for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16909  			frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16910  			frame->stack[i].spilled_ptr.parent =
16911  						&newframe->stack[i].spilled_ptr;
16912  		}
16913  	}
16914  	return 0;
16915  }
16916  
16917  /* Return true if it's OK to have the same insn return a different type. */
reg_type_mismatch_ok(enum bpf_reg_type type)16918  static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16919  {
16920  	switch (base_type(type)) {
16921  	case PTR_TO_CTX:
16922  	case PTR_TO_SOCKET:
16923  	case PTR_TO_SOCK_COMMON:
16924  	case PTR_TO_TCP_SOCK:
16925  	case PTR_TO_XDP_SOCK:
16926  	case PTR_TO_BTF_ID:
16927  		return false;
16928  	default:
16929  		return true;
16930  	}
16931  }
16932  
16933  /* If an instruction was previously used with particular pointer types, then we
16934   * need to be careful to avoid cases such as the below, where it may be ok
16935   * for one branch accessing the pointer, but not ok for the other branch:
16936   *
16937   * R1 = sock_ptr
16938   * goto X;
16939   * ...
16940   * R1 = some_other_valid_ptr;
16941   * goto X;
16942   * ...
16943   * R2 = *(u32 *)(R1 + 0);
16944   */
reg_type_mismatch(enum bpf_reg_type src,enum bpf_reg_type prev)16945  static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16946  {
16947  	return src != prev && (!reg_type_mismatch_ok(src) ||
16948  			       !reg_type_mismatch_ok(prev));
16949  }
16950  
save_aux_ptr_type(struct bpf_verifier_env * env,enum bpf_reg_type type,bool allow_trust_missmatch)16951  static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16952  			     bool allow_trust_missmatch)
16953  {
16954  	enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16955  
16956  	if (*prev_type == NOT_INIT) {
16957  		/* Saw a valid insn
16958  		 * dst_reg = *(u32 *)(src_reg + off)
16959  		 * save type to validate intersecting paths
16960  		 */
16961  		*prev_type = type;
16962  	} else if (reg_type_mismatch(type, *prev_type)) {
16963  		/* Abuser program is trying to use the same insn
16964  		 * dst_reg = *(u32*) (src_reg + off)
16965  		 * with different pointer types:
16966  		 * src_reg == ctx in one branch and
16967  		 * src_reg == stack|map in some other branch.
16968  		 * Reject it.
16969  		 */
16970  		if (allow_trust_missmatch &&
16971  		    base_type(type) == PTR_TO_BTF_ID &&
16972  		    base_type(*prev_type) == PTR_TO_BTF_ID) {
16973  			/*
16974  			 * Have to support a use case when one path through
16975  			 * the program yields TRUSTED pointer while another
16976  			 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16977  			 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16978  			 */
16979  			*prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16980  		} else {
16981  			verbose(env, "same insn cannot be used with different pointers\n");
16982  			return -EINVAL;
16983  		}
16984  	}
16985  
16986  	return 0;
16987  }
16988  
do_check(struct bpf_verifier_env * env)16989  static int do_check(struct bpf_verifier_env *env)
16990  {
16991  	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16992  	struct bpf_verifier_state *state = env->cur_state;
16993  	struct bpf_insn *insns = env->prog->insnsi;
16994  	struct bpf_reg_state *regs;
16995  	int insn_cnt = env->prog->len;
16996  	bool do_print_state = false;
16997  	int prev_insn_idx = -1;
16998  
16999  	for (;;) {
17000  		struct bpf_insn *insn;
17001  		u8 class;
17002  		int err;
17003  
17004  		env->prev_insn_idx = prev_insn_idx;
17005  		if (env->insn_idx >= insn_cnt) {
17006  			verbose(env, "invalid insn idx %d insn_cnt %d\n",
17007  				env->insn_idx, insn_cnt);
17008  			return -EFAULT;
17009  		}
17010  
17011  		insn = &insns[env->insn_idx];
17012  		class = BPF_CLASS(insn->code);
17013  
17014  		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17015  			verbose(env,
17016  				"BPF program is too large. Processed %d insn\n",
17017  				env->insn_processed);
17018  			return -E2BIG;
17019  		}
17020  
17021  		state->last_insn_idx = env->prev_insn_idx;
17022  
17023  		if (is_prune_point(env, env->insn_idx)) {
17024  			err = is_state_visited(env, env->insn_idx);
17025  			if (err < 0)
17026  				return err;
17027  			if (err == 1) {
17028  				/* found equivalent state, can prune the search */
17029  				if (env->log.level & BPF_LOG_LEVEL) {
17030  					if (do_print_state)
17031  						verbose(env, "\nfrom %d to %d%s: safe\n",
17032  							env->prev_insn_idx, env->insn_idx,
17033  							env->cur_state->speculative ?
17034  							" (speculative execution)" : "");
17035  					else
17036  						verbose(env, "%d: safe\n", env->insn_idx);
17037  				}
17038  				goto process_bpf_exit;
17039  			}
17040  		}
17041  
17042  		if (is_jmp_point(env, env->insn_idx)) {
17043  			err = push_jmp_history(env, state);
17044  			if (err)
17045  				return err;
17046  		}
17047  
17048  		if (signal_pending(current))
17049  			return -EAGAIN;
17050  
17051  		if (need_resched())
17052  			cond_resched();
17053  
17054  		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17055  			verbose(env, "\nfrom %d to %d%s:",
17056  				env->prev_insn_idx, env->insn_idx,
17057  				env->cur_state->speculative ?
17058  				" (speculative execution)" : "");
17059  			print_verifier_state(env, state->frame[state->curframe], true);
17060  			do_print_state = false;
17061  		}
17062  
17063  		if (env->log.level & BPF_LOG_LEVEL) {
17064  			const struct bpf_insn_cbs cbs = {
17065  				.cb_call	= disasm_kfunc_name,
17066  				.cb_print	= verbose,
17067  				.private_data	= env,
17068  			};
17069  
17070  			if (verifier_state_scratched(env))
17071  				print_insn_state(env, state->frame[state->curframe]);
17072  
17073  			verbose_linfo(env, env->insn_idx, "; ");
17074  			env->prev_log_pos = env->log.end_pos;
17075  			verbose(env, "%d: ", env->insn_idx);
17076  			print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17077  			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17078  			env->prev_log_pos = env->log.end_pos;
17079  		}
17080  
17081  		if (bpf_prog_is_offloaded(env->prog->aux)) {
17082  			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17083  							   env->prev_insn_idx);
17084  			if (err)
17085  				return err;
17086  		}
17087  
17088  		regs = cur_regs(env);
17089  		sanitize_mark_insn_seen(env);
17090  		prev_insn_idx = env->insn_idx;
17091  
17092  		if (class == BPF_ALU || class == BPF_ALU64) {
17093  			err = check_alu_op(env, insn);
17094  			if (err)
17095  				return err;
17096  
17097  		} else if (class == BPF_LDX) {
17098  			enum bpf_reg_type src_reg_type;
17099  
17100  			/* check for reserved fields is already done */
17101  
17102  			/* check src operand */
17103  			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17104  			if (err)
17105  				return err;
17106  
17107  			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17108  			if (err)
17109  				return err;
17110  
17111  			src_reg_type = regs[insn->src_reg].type;
17112  
17113  			/* check that memory (src_reg + off) is readable,
17114  			 * the state of dst_reg will be updated by this func
17115  			 */
17116  			err = check_mem_access(env, env->insn_idx, insn->src_reg,
17117  					       insn->off, BPF_SIZE(insn->code),
17118  					       BPF_READ, insn->dst_reg, false,
17119  					       BPF_MODE(insn->code) == BPF_MEMSX);
17120  			if (err)
17121  				return err;
17122  
17123  			err = save_aux_ptr_type(env, src_reg_type, true);
17124  			if (err)
17125  				return err;
17126  		} else if (class == BPF_STX) {
17127  			enum bpf_reg_type dst_reg_type;
17128  
17129  			if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17130  				err = check_atomic(env, env->insn_idx, insn);
17131  				if (err)
17132  					return err;
17133  				env->insn_idx++;
17134  				continue;
17135  			}
17136  
17137  			if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17138  				verbose(env, "BPF_STX uses reserved fields\n");
17139  				return -EINVAL;
17140  			}
17141  
17142  			/* check src1 operand */
17143  			err = check_reg_arg(env, insn->src_reg, SRC_OP);
17144  			if (err)
17145  				return err;
17146  			/* check src2 operand */
17147  			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17148  			if (err)
17149  				return err;
17150  
17151  			dst_reg_type = regs[insn->dst_reg].type;
17152  
17153  			/* check that memory (dst_reg + off) is writeable */
17154  			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17155  					       insn->off, BPF_SIZE(insn->code),
17156  					       BPF_WRITE, insn->src_reg, false, false);
17157  			if (err)
17158  				return err;
17159  
17160  			err = save_aux_ptr_type(env, dst_reg_type, false);
17161  			if (err)
17162  				return err;
17163  		} else if (class == BPF_ST) {
17164  			enum bpf_reg_type dst_reg_type;
17165  
17166  			if (BPF_MODE(insn->code) != BPF_MEM ||
17167  			    insn->src_reg != BPF_REG_0) {
17168  				verbose(env, "BPF_ST uses reserved fields\n");
17169  				return -EINVAL;
17170  			}
17171  			/* check src operand */
17172  			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17173  			if (err)
17174  				return err;
17175  
17176  			dst_reg_type = regs[insn->dst_reg].type;
17177  
17178  			/* check that memory (dst_reg + off) is writeable */
17179  			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17180  					       insn->off, BPF_SIZE(insn->code),
17181  					       BPF_WRITE, -1, false, false);
17182  			if (err)
17183  				return err;
17184  
17185  			err = save_aux_ptr_type(env, dst_reg_type, false);
17186  			if (err)
17187  				return err;
17188  		} else if (class == BPF_JMP || class == BPF_JMP32) {
17189  			u8 opcode = BPF_OP(insn->code);
17190  
17191  			env->jmps_processed++;
17192  			if (opcode == BPF_CALL) {
17193  				if (BPF_SRC(insn->code) != BPF_K ||
17194  				    (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17195  				     && insn->off != 0) ||
17196  				    (insn->src_reg != BPF_REG_0 &&
17197  				     insn->src_reg != BPF_PSEUDO_CALL &&
17198  				     insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17199  				    insn->dst_reg != BPF_REG_0 ||
17200  				    class == BPF_JMP32) {
17201  					verbose(env, "BPF_CALL uses reserved fields\n");
17202  					return -EINVAL;
17203  				}
17204  
17205  				if (env->cur_state->active_lock.ptr) {
17206  					if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17207  					    (insn->src_reg == BPF_PSEUDO_CALL) ||
17208  					    (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17209  					     (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17210  						verbose(env, "function calls are not allowed while holding a lock\n");
17211  						return -EINVAL;
17212  					}
17213  				}
17214  				if (insn->src_reg == BPF_PSEUDO_CALL)
17215  					err = check_func_call(env, insn, &env->insn_idx);
17216  				else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
17217  					err = check_kfunc_call(env, insn, &env->insn_idx);
17218  				else
17219  					err = check_helper_call(env, insn, &env->insn_idx);
17220  				if (err)
17221  					return err;
17222  
17223  				mark_reg_scratched(env, BPF_REG_0);
17224  			} else if (opcode == BPF_JA) {
17225  				if (BPF_SRC(insn->code) != BPF_K ||
17226  				    insn->src_reg != BPF_REG_0 ||
17227  				    insn->dst_reg != BPF_REG_0 ||
17228  				    (class == BPF_JMP && insn->imm != 0) ||
17229  				    (class == BPF_JMP32 && insn->off != 0)) {
17230  					verbose(env, "BPF_JA uses reserved fields\n");
17231  					return -EINVAL;
17232  				}
17233  
17234  				if (class == BPF_JMP)
17235  					env->insn_idx += insn->off + 1;
17236  				else
17237  					env->insn_idx += insn->imm + 1;
17238  				continue;
17239  
17240  			} else if (opcode == BPF_EXIT) {
17241  				if (BPF_SRC(insn->code) != BPF_K ||
17242  				    insn->imm != 0 ||
17243  				    insn->src_reg != BPF_REG_0 ||
17244  				    insn->dst_reg != BPF_REG_0 ||
17245  				    class == BPF_JMP32) {
17246  					verbose(env, "BPF_EXIT uses reserved fields\n");
17247  					return -EINVAL;
17248  				}
17249  
17250  				if (env->cur_state->active_lock.ptr &&
17251  				    !in_rbtree_lock_required_cb(env)) {
17252  					verbose(env, "bpf_spin_unlock is missing\n");
17253  					return -EINVAL;
17254  				}
17255  
17256  				if (env->cur_state->active_rcu_lock &&
17257  				    !in_rbtree_lock_required_cb(env)) {
17258  					verbose(env, "bpf_rcu_read_unlock is missing\n");
17259  					return -EINVAL;
17260  				}
17261  
17262  				/* We must do check_reference_leak here before
17263  				 * prepare_func_exit to handle the case when
17264  				 * state->curframe > 0, it may be a callback
17265  				 * function, for which reference_state must
17266  				 * match caller reference state when it exits.
17267  				 */
17268  				err = check_reference_leak(env);
17269  				if (err)
17270  					return err;
17271  
17272  				if (state->curframe) {
17273  					/* exit from nested function */
17274  					err = prepare_func_exit(env, &env->insn_idx);
17275  					if (err)
17276  						return err;
17277  					do_print_state = true;
17278  					continue;
17279  				}
17280  
17281  				err = check_return_code(env);
17282  				if (err)
17283  					return err;
17284  process_bpf_exit:
17285  				mark_verifier_state_scratched(env);
17286  				update_branch_counts(env, env->cur_state);
17287  				err = pop_stack(env, &prev_insn_idx,
17288  						&env->insn_idx, pop_log);
17289  				if (err < 0) {
17290  					if (err != -ENOENT)
17291  						return err;
17292  					break;
17293  				} else {
17294  					do_print_state = true;
17295  					continue;
17296  				}
17297  			} else {
17298  				err = check_cond_jmp_op(env, insn, &env->insn_idx);
17299  				if (err)
17300  					return err;
17301  			}
17302  		} else if (class == BPF_LD) {
17303  			u8 mode = BPF_MODE(insn->code);
17304  
17305  			if (mode == BPF_ABS || mode == BPF_IND) {
17306  				err = check_ld_abs(env, insn);
17307  				if (err)
17308  					return err;
17309  
17310  			} else if (mode == BPF_IMM) {
17311  				err = check_ld_imm(env, insn);
17312  				if (err)
17313  					return err;
17314  
17315  				env->insn_idx++;
17316  				sanitize_mark_insn_seen(env);
17317  			} else {
17318  				verbose(env, "invalid BPF_LD mode\n");
17319  				return -EINVAL;
17320  			}
17321  		} else {
17322  			verbose(env, "unknown insn class %d\n", class);
17323  			return -EINVAL;
17324  		}
17325  
17326  		env->insn_idx++;
17327  	}
17328  
17329  	return 0;
17330  }
17331  
find_btf_percpu_datasec(struct btf * btf)17332  static int find_btf_percpu_datasec(struct btf *btf)
17333  {
17334  	const struct btf_type *t;
17335  	const char *tname;
17336  	int i, n;
17337  
17338  	/*
17339  	 * Both vmlinux and module each have their own ".data..percpu"
17340  	 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17341  	 * types to look at only module's own BTF types.
17342  	 */
17343  	n = btf_nr_types(btf);
17344  	if (btf_is_module(btf))
17345  		i = btf_nr_types(btf_vmlinux);
17346  	else
17347  		i = 1;
17348  
17349  	for(; i < n; i++) {
17350  		t = btf_type_by_id(btf, i);
17351  		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17352  			continue;
17353  
17354  		tname = btf_name_by_offset(btf, t->name_off);
17355  		if (!strcmp(tname, ".data..percpu"))
17356  			return i;
17357  	}
17358  
17359  	return -ENOENT;
17360  }
17361  
17362  /* replace pseudo btf_id with kernel symbol address */
check_pseudo_btf_id(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_insn_aux_data * aux)17363  static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17364  			       struct bpf_insn *insn,
17365  			       struct bpf_insn_aux_data *aux)
17366  {
17367  	const struct btf_var_secinfo *vsi;
17368  	const struct btf_type *datasec;
17369  	struct btf_mod_pair *btf_mod;
17370  	const struct btf_type *t;
17371  	const char *sym_name;
17372  	bool percpu = false;
17373  	u32 type, id = insn->imm;
17374  	struct btf *btf;
17375  	s32 datasec_id;
17376  	u64 addr;
17377  	int i, btf_fd, err;
17378  
17379  	btf_fd = insn[1].imm;
17380  	if (btf_fd) {
17381  		btf = btf_get_by_fd(btf_fd);
17382  		if (IS_ERR(btf)) {
17383  			verbose(env, "invalid module BTF object FD specified.\n");
17384  			return -EINVAL;
17385  		}
17386  	} else {
17387  		if (!btf_vmlinux) {
17388  			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17389  			return -EINVAL;
17390  		}
17391  		btf = btf_vmlinux;
17392  		btf_get(btf);
17393  	}
17394  
17395  	t = btf_type_by_id(btf, id);
17396  	if (!t) {
17397  		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17398  		err = -ENOENT;
17399  		goto err_put;
17400  	}
17401  
17402  	if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17403  		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17404  		err = -EINVAL;
17405  		goto err_put;
17406  	}
17407  
17408  	sym_name = btf_name_by_offset(btf, t->name_off);
17409  	addr = kallsyms_lookup_name(sym_name);
17410  	if (!addr) {
17411  		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17412  			sym_name);
17413  		err = -ENOENT;
17414  		goto err_put;
17415  	}
17416  	insn[0].imm = (u32)addr;
17417  	insn[1].imm = addr >> 32;
17418  
17419  	if (btf_type_is_func(t)) {
17420  		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17421  		aux->btf_var.mem_size = 0;
17422  		goto check_btf;
17423  	}
17424  
17425  	datasec_id = find_btf_percpu_datasec(btf);
17426  	if (datasec_id > 0) {
17427  		datasec = btf_type_by_id(btf, datasec_id);
17428  		for_each_vsi(i, datasec, vsi) {
17429  			if (vsi->type == id) {
17430  				percpu = true;
17431  				break;
17432  			}
17433  		}
17434  	}
17435  
17436  	type = t->type;
17437  	t = btf_type_skip_modifiers(btf, type, NULL);
17438  	if (percpu) {
17439  		aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17440  		aux->btf_var.btf = btf;
17441  		aux->btf_var.btf_id = type;
17442  	} else if (!btf_type_is_struct(t)) {
17443  		const struct btf_type *ret;
17444  		const char *tname;
17445  		u32 tsize;
17446  
17447  		/* resolve the type size of ksym. */
17448  		ret = btf_resolve_size(btf, t, &tsize);
17449  		if (IS_ERR(ret)) {
17450  			tname = btf_name_by_offset(btf, t->name_off);
17451  			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17452  				tname, PTR_ERR(ret));
17453  			err = -EINVAL;
17454  			goto err_put;
17455  		}
17456  		aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17457  		aux->btf_var.mem_size = tsize;
17458  	} else {
17459  		aux->btf_var.reg_type = PTR_TO_BTF_ID;
17460  		aux->btf_var.btf = btf;
17461  		aux->btf_var.btf_id = type;
17462  	}
17463  check_btf:
17464  	/* check whether we recorded this BTF (and maybe module) already */
17465  	for (i = 0; i < env->used_btf_cnt; i++) {
17466  		if (env->used_btfs[i].btf == btf) {
17467  			btf_put(btf);
17468  			return 0;
17469  		}
17470  	}
17471  
17472  	if (env->used_btf_cnt >= MAX_USED_BTFS) {
17473  		err = -E2BIG;
17474  		goto err_put;
17475  	}
17476  
17477  	btf_mod = &env->used_btfs[env->used_btf_cnt];
17478  	btf_mod->btf = btf;
17479  	btf_mod->module = NULL;
17480  
17481  	/* if we reference variables from kernel module, bump its refcount */
17482  	if (btf_is_module(btf)) {
17483  		btf_mod->module = btf_try_get_module(btf);
17484  		if (!btf_mod->module) {
17485  			err = -ENXIO;
17486  			goto err_put;
17487  		}
17488  	}
17489  
17490  	env->used_btf_cnt++;
17491  
17492  	return 0;
17493  err_put:
17494  	btf_put(btf);
17495  	return err;
17496  }
17497  
is_tracing_prog_type(enum bpf_prog_type type)17498  static bool is_tracing_prog_type(enum bpf_prog_type type)
17499  {
17500  	switch (type) {
17501  	case BPF_PROG_TYPE_KPROBE:
17502  	case BPF_PROG_TYPE_TRACEPOINT:
17503  	case BPF_PROG_TYPE_PERF_EVENT:
17504  	case BPF_PROG_TYPE_RAW_TRACEPOINT:
17505  	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17506  		return true;
17507  	default:
17508  		return false;
17509  	}
17510  }
17511  
check_map_prog_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,struct bpf_prog * prog)17512  static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17513  					struct bpf_map *map,
17514  					struct bpf_prog *prog)
17515  
17516  {
17517  	enum bpf_prog_type prog_type = resolve_prog_type(prog);
17518  
17519  	if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17520  	    btf_record_has_field(map->record, BPF_RB_ROOT)) {
17521  		if (is_tracing_prog_type(prog_type)) {
17522  			verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17523  			return -EINVAL;
17524  		}
17525  	}
17526  
17527  	if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17528  		if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17529  			verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17530  			return -EINVAL;
17531  		}
17532  
17533  		if (is_tracing_prog_type(prog_type)) {
17534  			verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17535  			return -EINVAL;
17536  		}
17537  	}
17538  
17539  	if (btf_record_has_field(map->record, BPF_TIMER)) {
17540  		if (is_tracing_prog_type(prog_type)) {
17541  			verbose(env, "tracing progs cannot use bpf_timer yet\n");
17542  			return -EINVAL;
17543  		}
17544  	}
17545  
17546  	if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17547  	    !bpf_offload_prog_map_match(prog, map)) {
17548  		verbose(env, "offload device mismatch between prog and map\n");
17549  		return -EINVAL;
17550  	}
17551  
17552  	if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17553  		verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17554  		return -EINVAL;
17555  	}
17556  
17557  	if (prog->aux->sleepable)
17558  		switch (map->map_type) {
17559  		case BPF_MAP_TYPE_HASH:
17560  		case BPF_MAP_TYPE_LRU_HASH:
17561  		case BPF_MAP_TYPE_ARRAY:
17562  		case BPF_MAP_TYPE_PERCPU_HASH:
17563  		case BPF_MAP_TYPE_PERCPU_ARRAY:
17564  		case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17565  		case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17566  		case BPF_MAP_TYPE_HASH_OF_MAPS:
17567  		case BPF_MAP_TYPE_RINGBUF:
17568  		case BPF_MAP_TYPE_USER_RINGBUF:
17569  		case BPF_MAP_TYPE_INODE_STORAGE:
17570  		case BPF_MAP_TYPE_SK_STORAGE:
17571  		case BPF_MAP_TYPE_TASK_STORAGE:
17572  		case BPF_MAP_TYPE_CGRP_STORAGE:
17573  			break;
17574  		default:
17575  			verbose(env,
17576  				"Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17577  			return -EINVAL;
17578  		}
17579  
17580  	return 0;
17581  }
17582  
bpf_map_is_cgroup_storage(struct bpf_map * map)17583  static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17584  {
17585  	return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17586  		map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17587  }
17588  
17589  /* find and rewrite pseudo imm in ld_imm64 instructions:
17590   *
17591   * 1. if it accesses map FD, replace it with actual map pointer.
17592   * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17593   *
17594   * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17595   */
resolve_pseudo_ldimm64(struct bpf_verifier_env * env)17596  static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17597  {
17598  	struct bpf_insn *insn = env->prog->insnsi;
17599  	int insn_cnt = env->prog->len;
17600  	int i, j, err;
17601  
17602  	err = bpf_prog_calc_tag(env->prog);
17603  	if (err)
17604  		return err;
17605  
17606  	for (i = 0; i < insn_cnt; i++, insn++) {
17607  		if (BPF_CLASS(insn->code) == BPF_LDX &&
17608  		    ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17609  		    insn->imm != 0)) {
17610  			verbose(env, "BPF_LDX uses reserved fields\n");
17611  			return -EINVAL;
17612  		}
17613  
17614  		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17615  			struct bpf_insn_aux_data *aux;
17616  			struct bpf_map *map;
17617  			struct fd f;
17618  			u64 addr;
17619  			u32 fd;
17620  
17621  			if (i == insn_cnt - 1 || insn[1].code != 0 ||
17622  			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17623  			    insn[1].off != 0) {
17624  				verbose(env, "invalid bpf_ld_imm64 insn\n");
17625  				return -EINVAL;
17626  			}
17627  
17628  			if (insn[0].src_reg == 0)
17629  				/* valid generic load 64-bit imm */
17630  				goto next_insn;
17631  
17632  			if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17633  				aux = &env->insn_aux_data[i];
17634  				err = check_pseudo_btf_id(env, insn, aux);
17635  				if (err)
17636  					return err;
17637  				goto next_insn;
17638  			}
17639  
17640  			if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17641  				aux = &env->insn_aux_data[i];
17642  				aux->ptr_type = PTR_TO_FUNC;
17643  				goto next_insn;
17644  			}
17645  
17646  			/* In final convert_pseudo_ld_imm64() step, this is
17647  			 * converted into regular 64-bit imm load insn.
17648  			 */
17649  			switch (insn[0].src_reg) {
17650  			case BPF_PSEUDO_MAP_VALUE:
17651  			case BPF_PSEUDO_MAP_IDX_VALUE:
17652  				break;
17653  			case BPF_PSEUDO_MAP_FD:
17654  			case BPF_PSEUDO_MAP_IDX:
17655  				if (insn[1].imm == 0)
17656  					break;
17657  				fallthrough;
17658  			default:
17659  				verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17660  				return -EINVAL;
17661  			}
17662  
17663  			switch (insn[0].src_reg) {
17664  			case BPF_PSEUDO_MAP_IDX_VALUE:
17665  			case BPF_PSEUDO_MAP_IDX:
17666  				if (bpfptr_is_null(env->fd_array)) {
17667  					verbose(env, "fd_idx without fd_array is invalid\n");
17668  					return -EPROTO;
17669  				}
17670  				if (copy_from_bpfptr_offset(&fd, env->fd_array,
17671  							    insn[0].imm * sizeof(fd),
17672  							    sizeof(fd)))
17673  					return -EFAULT;
17674  				break;
17675  			default:
17676  				fd = insn[0].imm;
17677  				break;
17678  			}
17679  
17680  			f = fdget(fd);
17681  			map = __bpf_map_get(f);
17682  			if (IS_ERR(map)) {
17683  				verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
17684  				return PTR_ERR(map);
17685  			}
17686  
17687  			err = check_map_prog_compatibility(env, map, env->prog);
17688  			if (err) {
17689  				fdput(f);
17690  				return err;
17691  			}
17692  
17693  			aux = &env->insn_aux_data[i];
17694  			if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17695  			    insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17696  				addr = (unsigned long)map;
17697  			} else {
17698  				u32 off = insn[1].imm;
17699  
17700  				if (off >= BPF_MAX_VAR_OFF) {
17701  					verbose(env, "direct value offset of %u is not allowed\n", off);
17702  					fdput(f);
17703  					return -EINVAL;
17704  				}
17705  
17706  				if (!map->ops->map_direct_value_addr) {
17707  					verbose(env, "no direct value access support for this map type\n");
17708  					fdput(f);
17709  					return -EINVAL;
17710  				}
17711  
17712  				err = map->ops->map_direct_value_addr(map, &addr, off);
17713  				if (err) {
17714  					verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17715  						map->value_size, off);
17716  					fdput(f);
17717  					return err;
17718  				}
17719  
17720  				aux->map_off = off;
17721  				addr += off;
17722  			}
17723  
17724  			insn[0].imm = (u32)addr;
17725  			insn[1].imm = addr >> 32;
17726  
17727  			/* check whether we recorded this map already */
17728  			for (j = 0; j < env->used_map_cnt; j++) {
17729  				if (env->used_maps[j] == map) {
17730  					aux->map_index = j;
17731  					fdput(f);
17732  					goto next_insn;
17733  				}
17734  			}
17735  
17736  			if (env->used_map_cnt >= MAX_USED_MAPS) {
17737  				fdput(f);
17738  				return -E2BIG;
17739  			}
17740  
17741  			if (env->prog->aux->sleepable)
17742  				atomic64_inc(&map->sleepable_refcnt);
17743  			/* hold the map. If the program is rejected by verifier,
17744  			 * the map will be released by release_maps() or it
17745  			 * will be used by the valid program until it's unloaded
17746  			 * and all maps are released in bpf_free_used_maps()
17747  			 */
17748  			bpf_map_inc(map);
17749  
17750  			aux->map_index = env->used_map_cnt;
17751  			env->used_maps[env->used_map_cnt++] = map;
17752  
17753  			if (bpf_map_is_cgroup_storage(map) &&
17754  			    bpf_cgroup_storage_assign(env->prog->aux, map)) {
17755  				verbose(env, "only one cgroup storage of each type is allowed\n");
17756  				fdput(f);
17757  				return -EBUSY;
17758  			}
17759  
17760  			fdput(f);
17761  next_insn:
17762  			insn++;
17763  			i++;
17764  			continue;
17765  		}
17766  
17767  		/* Basic sanity check before we invest more work here. */
17768  		if (!bpf_opcode_in_insntable(insn->code)) {
17769  			verbose(env, "unknown opcode %02x\n", insn->code);
17770  			return -EINVAL;
17771  		}
17772  	}
17773  
17774  	/* now all pseudo BPF_LD_IMM64 instructions load valid
17775  	 * 'struct bpf_map *' into a register instead of user map_fd.
17776  	 * These pointers will be used later by verifier to validate map access.
17777  	 */
17778  	return 0;
17779  }
17780  
17781  /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)17782  static void release_maps(struct bpf_verifier_env *env)
17783  {
17784  	__bpf_free_used_maps(env->prog->aux, env->used_maps,
17785  			     env->used_map_cnt);
17786  }
17787  
17788  /* drop refcnt of maps used by the rejected program */
release_btfs(struct bpf_verifier_env * env)17789  static void release_btfs(struct bpf_verifier_env *env)
17790  {
17791  	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17792  			     env->used_btf_cnt);
17793  }
17794  
17795  /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)17796  static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17797  {
17798  	struct bpf_insn *insn = env->prog->insnsi;
17799  	int insn_cnt = env->prog->len;
17800  	int i;
17801  
17802  	for (i = 0; i < insn_cnt; i++, insn++) {
17803  		if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17804  			continue;
17805  		if (insn->src_reg == BPF_PSEUDO_FUNC)
17806  			continue;
17807  		insn->src_reg = 0;
17808  	}
17809  }
17810  
17811  /* single env->prog->insni[off] instruction was replaced with the range
17812   * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
17813   * [0, off) and [off, end) to new locations, so the patched range stays zero
17814   */
adjust_insn_aux_data(struct bpf_verifier_env * env,struct bpf_insn_aux_data * new_data,struct bpf_prog * new_prog,u32 off,u32 cnt)17815  static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17816  				 struct bpf_insn_aux_data *new_data,
17817  				 struct bpf_prog *new_prog, u32 off, u32 cnt)
17818  {
17819  	struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17820  	struct bpf_insn *insn = new_prog->insnsi;
17821  	u32 old_seen = old_data[off].seen;
17822  	u32 prog_len;
17823  	int i;
17824  
17825  	/* aux info at OFF always needs adjustment, no matter fast path
17826  	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17827  	 * original insn at old prog.
17828  	 */
17829  	old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17830  
17831  	if (cnt == 1)
17832  		return;
17833  	prog_len = new_prog->len;
17834  
17835  	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17836  	memcpy(new_data + off + cnt - 1, old_data + off,
17837  	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17838  	for (i = off; i < off + cnt - 1; i++) {
17839  		/* Expand insni[off]'s seen count to the patched range. */
17840  		new_data[i].seen = old_seen;
17841  		new_data[i].zext_dst = insn_has_def32(env, insn + i);
17842  	}
17843  	env->insn_aux_data = new_data;
17844  	vfree(old_data);
17845  }
17846  
adjust_subprog_starts(struct bpf_verifier_env * env,u32 off,u32 len)17847  static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17848  {
17849  	int i;
17850  
17851  	if (len == 1)
17852  		return;
17853  	/* NOTE: fake 'exit' subprog should be updated as well. */
17854  	for (i = 0; i <= env->subprog_cnt; i++) {
17855  		if (env->subprog_info[i].start <= off)
17856  			continue;
17857  		env->subprog_info[i].start += len - 1;
17858  	}
17859  }
17860  
adjust_poke_descs(struct bpf_prog * prog,u32 off,u32 len)17861  static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17862  {
17863  	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17864  	int i, sz = prog->aux->size_poke_tab;
17865  	struct bpf_jit_poke_descriptor *desc;
17866  
17867  	for (i = 0; i < sz; i++) {
17868  		desc = &tab[i];
17869  		if (desc->insn_idx <= off)
17870  			continue;
17871  		desc->insn_idx += len - 1;
17872  	}
17873  }
17874  
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)17875  static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17876  					    const struct bpf_insn *patch, u32 len)
17877  {
17878  	struct bpf_prog *new_prog;
17879  	struct bpf_insn_aux_data *new_data = NULL;
17880  
17881  	if (len > 1) {
17882  		new_data = vzalloc(array_size(env->prog->len + len - 1,
17883  					      sizeof(struct bpf_insn_aux_data)));
17884  		if (!new_data)
17885  			return NULL;
17886  	}
17887  
17888  	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17889  	if (IS_ERR(new_prog)) {
17890  		if (PTR_ERR(new_prog) == -ERANGE)
17891  			verbose(env,
17892  				"insn %d cannot be patched due to 16-bit range\n",
17893  				env->insn_aux_data[off].orig_idx);
17894  		vfree(new_data);
17895  		return NULL;
17896  	}
17897  	adjust_insn_aux_data(env, new_data, new_prog, off, len);
17898  	adjust_subprog_starts(env, off, len);
17899  	adjust_poke_descs(new_prog, off, len);
17900  	return new_prog;
17901  }
17902  
adjust_subprog_starts_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)17903  static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17904  					      u32 off, u32 cnt)
17905  {
17906  	int i, j;
17907  
17908  	/* find first prog starting at or after off (first to remove) */
17909  	for (i = 0; i < env->subprog_cnt; i++)
17910  		if (env->subprog_info[i].start >= off)
17911  			break;
17912  	/* find first prog starting at or after off + cnt (first to stay) */
17913  	for (j = i; j < env->subprog_cnt; j++)
17914  		if (env->subprog_info[j].start >= off + cnt)
17915  			break;
17916  	/* if j doesn't start exactly at off + cnt, we are just removing
17917  	 * the front of previous prog
17918  	 */
17919  	if (env->subprog_info[j].start != off + cnt)
17920  		j--;
17921  
17922  	if (j > i) {
17923  		struct bpf_prog_aux *aux = env->prog->aux;
17924  		int move;
17925  
17926  		/* move fake 'exit' subprog as well */
17927  		move = env->subprog_cnt + 1 - j;
17928  
17929  		memmove(env->subprog_info + i,
17930  			env->subprog_info + j,
17931  			sizeof(*env->subprog_info) * move);
17932  		env->subprog_cnt -= j - i;
17933  
17934  		/* remove func_info */
17935  		if (aux->func_info) {
17936  			move = aux->func_info_cnt - j;
17937  
17938  			memmove(aux->func_info + i,
17939  				aux->func_info + j,
17940  				sizeof(*aux->func_info) * move);
17941  			aux->func_info_cnt -= j - i;
17942  			/* func_info->insn_off is set after all code rewrites,
17943  			 * in adjust_btf_func() - no need to adjust
17944  			 */
17945  		}
17946  	} else {
17947  		/* convert i from "first prog to remove" to "first to adjust" */
17948  		if (env->subprog_info[i].start == off)
17949  			i++;
17950  	}
17951  
17952  	/* update fake 'exit' subprog as well */
17953  	for (; i <= env->subprog_cnt; i++)
17954  		env->subprog_info[i].start -= cnt;
17955  
17956  	return 0;
17957  }
17958  
bpf_adj_linfo_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)17959  static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17960  				      u32 cnt)
17961  {
17962  	struct bpf_prog *prog = env->prog;
17963  	u32 i, l_off, l_cnt, nr_linfo;
17964  	struct bpf_line_info *linfo;
17965  
17966  	nr_linfo = prog->aux->nr_linfo;
17967  	if (!nr_linfo)
17968  		return 0;
17969  
17970  	linfo = prog->aux->linfo;
17971  
17972  	/* find first line info to remove, count lines to be removed */
17973  	for (i = 0; i < nr_linfo; i++)
17974  		if (linfo[i].insn_off >= off)
17975  			break;
17976  
17977  	l_off = i;
17978  	l_cnt = 0;
17979  	for (; i < nr_linfo; i++)
17980  		if (linfo[i].insn_off < off + cnt)
17981  			l_cnt++;
17982  		else
17983  			break;
17984  
17985  	/* First live insn doesn't match first live linfo, it needs to "inherit"
17986  	 * last removed linfo.  prog is already modified, so prog->len == off
17987  	 * means no live instructions after (tail of the program was removed).
17988  	 */
17989  	if (prog->len != off && l_cnt &&
17990  	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17991  		l_cnt--;
17992  		linfo[--i].insn_off = off + cnt;
17993  	}
17994  
17995  	/* remove the line info which refer to the removed instructions */
17996  	if (l_cnt) {
17997  		memmove(linfo + l_off, linfo + i,
17998  			sizeof(*linfo) * (nr_linfo - i));
17999  
18000  		prog->aux->nr_linfo -= l_cnt;
18001  		nr_linfo = prog->aux->nr_linfo;
18002  	}
18003  
18004  	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
18005  	for (i = l_off; i < nr_linfo; i++)
18006  		linfo[i].insn_off -= cnt;
18007  
18008  	/* fix up all subprogs (incl. 'exit') which start >= off */
18009  	for (i = 0; i <= env->subprog_cnt; i++)
18010  		if (env->subprog_info[i].linfo_idx > l_off) {
18011  			/* program may have started in the removed region but
18012  			 * may not be fully removed
18013  			 */
18014  			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18015  				env->subprog_info[i].linfo_idx -= l_cnt;
18016  			else
18017  				env->subprog_info[i].linfo_idx = l_off;
18018  		}
18019  
18020  	return 0;
18021  }
18022  
verifier_remove_insns(struct bpf_verifier_env * env,u32 off,u32 cnt)18023  static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18024  {
18025  	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18026  	unsigned int orig_prog_len = env->prog->len;
18027  	int err;
18028  
18029  	if (bpf_prog_is_offloaded(env->prog->aux))
18030  		bpf_prog_offload_remove_insns(env, off, cnt);
18031  
18032  	err = bpf_remove_insns(env->prog, off, cnt);
18033  	if (err)
18034  		return err;
18035  
18036  	err = adjust_subprog_starts_after_remove(env, off, cnt);
18037  	if (err)
18038  		return err;
18039  
18040  	err = bpf_adj_linfo_after_remove(env, off, cnt);
18041  	if (err)
18042  		return err;
18043  
18044  	memmove(aux_data + off,	aux_data + off + cnt,
18045  		sizeof(*aux_data) * (orig_prog_len - off - cnt));
18046  
18047  	return 0;
18048  }
18049  
18050  /* The verifier does more data flow analysis than llvm and will not
18051   * explore branches that are dead at run time. Malicious programs can
18052   * have dead code too. Therefore replace all dead at-run-time code
18053   * with 'ja -1'.
18054   *
18055   * Just nops are not optimal, e.g. if they would sit at the end of the
18056   * program and through another bug we would manage to jump there, then
18057   * we'd execute beyond program memory otherwise. Returning exception
18058   * code also wouldn't work since we can have subprogs where the dead
18059   * code could be located.
18060   */
sanitize_dead_code(struct bpf_verifier_env * env)18061  static void sanitize_dead_code(struct bpf_verifier_env *env)
18062  {
18063  	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18064  	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18065  	struct bpf_insn *insn = env->prog->insnsi;
18066  	const int insn_cnt = env->prog->len;
18067  	int i;
18068  
18069  	for (i = 0; i < insn_cnt; i++) {
18070  		if (aux_data[i].seen)
18071  			continue;
18072  		memcpy(insn + i, &trap, sizeof(trap));
18073  		aux_data[i].zext_dst = false;
18074  	}
18075  }
18076  
insn_is_cond_jump(u8 code)18077  static bool insn_is_cond_jump(u8 code)
18078  {
18079  	u8 op;
18080  
18081  	op = BPF_OP(code);
18082  	if (BPF_CLASS(code) == BPF_JMP32)
18083  		return op != BPF_JA;
18084  
18085  	if (BPF_CLASS(code) != BPF_JMP)
18086  		return false;
18087  
18088  	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18089  }
18090  
opt_hard_wire_dead_code_branches(struct bpf_verifier_env * env)18091  static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18092  {
18093  	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18094  	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18095  	struct bpf_insn *insn = env->prog->insnsi;
18096  	const int insn_cnt = env->prog->len;
18097  	int i;
18098  
18099  	for (i = 0; i < insn_cnt; i++, insn++) {
18100  		if (!insn_is_cond_jump(insn->code))
18101  			continue;
18102  
18103  		if (!aux_data[i + 1].seen)
18104  			ja.off = insn->off;
18105  		else if (!aux_data[i + 1 + insn->off].seen)
18106  			ja.off = 0;
18107  		else
18108  			continue;
18109  
18110  		if (bpf_prog_is_offloaded(env->prog->aux))
18111  			bpf_prog_offload_replace_insn(env, i, &ja);
18112  
18113  		memcpy(insn, &ja, sizeof(ja));
18114  	}
18115  }
18116  
opt_remove_dead_code(struct bpf_verifier_env * env)18117  static int opt_remove_dead_code(struct bpf_verifier_env *env)
18118  {
18119  	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18120  	int insn_cnt = env->prog->len;
18121  	int i, err;
18122  
18123  	for (i = 0; i < insn_cnt; i++) {
18124  		int j;
18125  
18126  		j = 0;
18127  		while (i + j < insn_cnt && !aux_data[i + j].seen)
18128  			j++;
18129  		if (!j)
18130  			continue;
18131  
18132  		err = verifier_remove_insns(env, i, j);
18133  		if (err)
18134  			return err;
18135  		insn_cnt = env->prog->len;
18136  	}
18137  
18138  	return 0;
18139  }
18140  
opt_remove_nops(struct bpf_verifier_env * env)18141  static int opt_remove_nops(struct bpf_verifier_env *env)
18142  {
18143  	const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18144  	struct bpf_insn *insn = env->prog->insnsi;
18145  	int insn_cnt = env->prog->len;
18146  	int i, err;
18147  
18148  	for (i = 0; i < insn_cnt; i++) {
18149  		if (memcmp(&insn[i], &ja, sizeof(ja)))
18150  			continue;
18151  
18152  		err = verifier_remove_insns(env, i, 1);
18153  		if (err)
18154  			return err;
18155  		insn_cnt--;
18156  		i--;
18157  	}
18158  
18159  	return 0;
18160  }
18161  
opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env * env,const union bpf_attr * attr)18162  static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18163  					 const union bpf_attr *attr)
18164  {
18165  	struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18166  	struct bpf_insn_aux_data *aux = env->insn_aux_data;
18167  	int i, patch_len, delta = 0, len = env->prog->len;
18168  	struct bpf_insn *insns = env->prog->insnsi;
18169  	struct bpf_prog *new_prog;
18170  	bool rnd_hi32;
18171  
18172  	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18173  	zext_patch[1] = BPF_ZEXT_REG(0);
18174  	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18175  	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18176  	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18177  	for (i = 0; i < len; i++) {
18178  		int adj_idx = i + delta;
18179  		struct bpf_insn insn;
18180  		int load_reg;
18181  
18182  		insn = insns[adj_idx];
18183  		load_reg = insn_def_regno(&insn);
18184  		if (!aux[adj_idx].zext_dst) {
18185  			u8 code, class;
18186  			u32 imm_rnd;
18187  
18188  			if (!rnd_hi32)
18189  				continue;
18190  
18191  			code = insn.code;
18192  			class = BPF_CLASS(code);
18193  			if (load_reg == -1)
18194  				continue;
18195  
18196  			/* NOTE: arg "reg" (the fourth one) is only used for
18197  			 *       BPF_STX + SRC_OP, so it is safe to pass NULL
18198  			 *       here.
18199  			 */
18200  			if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18201  				if (class == BPF_LD &&
18202  				    BPF_MODE(code) == BPF_IMM)
18203  					i++;
18204  				continue;
18205  			}
18206  
18207  			/* ctx load could be transformed into wider load. */
18208  			if (class == BPF_LDX &&
18209  			    aux[adj_idx].ptr_type == PTR_TO_CTX)
18210  				continue;
18211  
18212  			imm_rnd = get_random_u32();
18213  			rnd_hi32_patch[0] = insn;
18214  			rnd_hi32_patch[1].imm = imm_rnd;
18215  			rnd_hi32_patch[3].dst_reg = load_reg;
18216  			patch = rnd_hi32_patch;
18217  			patch_len = 4;
18218  			goto apply_patch_buffer;
18219  		}
18220  
18221  		/* Add in an zero-extend instruction if a) the JIT has requested
18222  		 * it or b) it's a CMPXCHG.
18223  		 *
18224  		 * The latter is because: BPF_CMPXCHG always loads a value into
18225  		 * R0, therefore always zero-extends. However some archs'
18226  		 * equivalent instruction only does this load when the
18227  		 * comparison is successful. This detail of CMPXCHG is
18228  		 * orthogonal to the general zero-extension behaviour of the
18229  		 * CPU, so it's treated independently of bpf_jit_needs_zext.
18230  		 */
18231  		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18232  			continue;
18233  
18234  		/* Zero-extension is done by the caller. */
18235  		if (bpf_pseudo_kfunc_call(&insn))
18236  			continue;
18237  
18238  		if (WARN_ON(load_reg == -1)) {
18239  			verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18240  			return -EFAULT;
18241  		}
18242  
18243  		zext_patch[0] = insn;
18244  		zext_patch[1].dst_reg = load_reg;
18245  		zext_patch[1].src_reg = load_reg;
18246  		patch = zext_patch;
18247  		patch_len = 2;
18248  apply_patch_buffer:
18249  		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18250  		if (!new_prog)
18251  			return -ENOMEM;
18252  		env->prog = new_prog;
18253  		insns = new_prog->insnsi;
18254  		aux = env->insn_aux_data;
18255  		delta += patch_len - 1;
18256  	}
18257  
18258  	return 0;
18259  }
18260  
18261  /* convert load instructions that access fields of a context type into a
18262   * sequence of instructions that access fields of the underlying structure:
18263   *     struct __sk_buff    -> struct sk_buff
18264   *     struct bpf_sock_ops -> struct sock
18265   */
convert_ctx_accesses(struct bpf_verifier_env * env)18266  static int convert_ctx_accesses(struct bpf_verifier_env *env)
18267  {
18268  	const struct bpf_verifier_ops *ops = env->ops;
18269  	int i, cnt, size, ctx_field_size, delta = 0;
18270  	const int insn_cnt = env->prog->len;
18271  	struct bpf_insn insn_buf[16], *insn;
18272  	u32 target_size, size_default, off;
18273  	struct bpf_prog *new_prog;
18274  	enum bpf_access_type type;
18275  	bool is_narrower_load;
18276  
18277  	if (ops->gen_prologue || env->seen_direct_write) {
18278  		if (!ops->gen_prologue) {
18279  			verbose(env, "bpf verifier is misconfigured\n");
18280  			return -EINVAL;
18281  		}
18282  		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18283  					env->prog);
18284  		if (cnt >= ARRAY_SIZE(insn_buf)) {
18285  			verbose(env, "bpf verifier is misconfigured\n");
18286  			return -EINVAL;
18287  		} else if (cnt) {
18288  			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18289  			if (!new_prog)
18290  				return -ENOMEM;
18291  
18292  			env->prog = new_prog;
18293  			delta += cnt - 1;
18294  		}
18295  	}
18296  
18297  	if (bpf_prog_is_offloaded(env->prog->aux))
18298  		return 0;
18299  
18300  	insn = env->prog->insnsi + delta;
18301  
18302  	for (i = 0; i < insn_cnt; i++, insn++) {
18303  		bpf_convert_ctx_access_t convert_ctx_access;
18304  		u8 mode;
18305  
18306  		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18307  		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18308  		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18309  		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18310  		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18311  		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18312  		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18313  			type = BPF_READ;
18314  		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18315  			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18316  			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18317  			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18318  			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18319  			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18320  			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18321  			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18322  			type = BPF_WRITE;
18323  		} else {
18324  			continue;
18325  		}
18326  
18327  		if (type == BPF_WRITE &&
18328  		    env->insn_aux_data[i + delta].sanitize_stack_spill) {
18329  			struct bpf_insn patch[] = {
18330  				*insn,
18331  				BPF_ST_NOSPEC(),
18332  			};
18333  
18334  			cnt = ARRAY_SIZE(patch);
18335  			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18336  			if (!new_prog)
18337  				return -ENOMEM;
18338  
18339  			delta    += cnt - 1;
18340  			env->prog = new_prog;
18341  			insn      = new_prog->insnsi + i + delta;
18342  			continue;
18343  		}
18344  
18345  		switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18346  		case PTR_TO_CTX:
18347  			if (!ops->convert_ctx_access)
18348  				continue;
18349  			convert_ctx_access = ops->convert_ctx_access;
18350  			break;
18351  		case PTR_TO_SOCKET:
18352  		case PTR_TO_SOCK_COMMON:
18353  			convert_ctx_access = bpf_sock_convert_ctx_access;
18354  			break;
18355  		case PTR_TO_TCP_SOCK:
18356  			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18357  			break;
18358  		case PTR_TO_XDP_SOCK:
18359  			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18360  			break;
18361  		case PTR_TO_BTF_ID:
18362  		case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18363  		/* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18364  		 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18365  		 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18366  		 * any faults for loads into such types. BPF_WRITE is disallowed
18367  		 * for this case.
18368  		 */
18369  		case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18370  			if (type == BPF_READ) {
18371  				if (BPF_MODE(insn->code) == BPF_MEM)
18372  					insn->code = BPF_LDX | BPF_PROBE_MEM |
18373  						     BPF_SIZE((insn)->code);
18374  				else
18375  					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18376  						     BPF_SIZE((insn)->code);
18377  				env->prog->aux->num_exentries++;
18378  			}
18379  			continue;
18380  		default:
18381  			continue;
18382  		}
18383  
18384  		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18385  		size = BPF_LDST_BYTES(insn);
18386  		mode = BPF_MODE(insn->code);
18387  
18388  		/* If the read access is a narrower load of the field,
18389  		 * convert to a 4/8-byte load, to minimum program type specific
18390  		 * convert_ctx_access changes. If conversion is successful,
18391  		 * we will apply proper mask to the result.
18392  		 */
18393  		is_narrower_load = size < ctx_field_size;
18394  		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18395  		off = insn->off;
18396  		if (is_narrower_load) {
18397  			u8 size_code;
18398  
18399  			if (type == BPF_WRITE) {
18400  				verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18401  				return -EINVAL;
18402  			}
18403  
18404  			size_code = BPF_H;
18405  			if (ctx_field_size == 4)
18406  				size_code = BPF_W;
18407  			else if (ctx_field_size == 8)
18408  				size_code = BPF_DW;
18409  
18410  			insn->off = off & ~(size_default - 1);
18411  			insn->code = BPF_LDX | BPF_MEM | size_code;
18412  		}
18413  
18414  		target_size = 0;
18415  		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18416  					 &target_size);
18417  		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18418  		    (ctx_field_size && !target_size)) {
18419  			verbose(env, "bpf verifier is misconfigured\n");
18420  			return -EINVAL;
18421  		}
18422  
18423  		if (is_narrower_load && size < target_size) {
18424  			u8 shift = bpf_ctx_narrow_access_offset(
18425  				off, size, size_default) * 8;
18426  			if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18427  				verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18428  				return -EINVAL;
18429  			}
18430  			if (ctx_field_size <= 4) {
18431  				if (shift)
18432  					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18433  									insn->dst_reg,
18434  									shift);
18435  				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18436  								(1 << size * 8) - 1);
18437  			} else {
18438  				if (shift)
18439  					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18440  									insn->dst_reg,
18441  									shift);
18442  				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18443  								(1ULL << size * 8) - 1);
18444  			}
18445  		}
18446  		if (mode == BPF_MEMSX)
18447  			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18448  						       insn->dst_reg, insn->dst_reg,
18449  						       size * 8, 0);
18450  
18451  		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18452  		if (!new_prog)
18453  			return -ENOMEM;
18454  
18455  		delta += cnt - 1;
18456  
18457  		/* keep walking new program and skip insns we just inserted */
18458  		env->prog = new_prog;
18459  		insn      = new_prog->insnsi + i + delta;
18460  	}
18461  
18462  	return 0;
18463  }
18464  
jit_subprogs(struct bpf_verifier_env * env)18465  static int jit_subprogs(struct bpf_verifier_env *env)
18466  {
18467  	struct bpf_prog *prog = env->prog, **func, *tmp;
18468  	int i, j, subprog_start, subprog_end = 0, len, subprog;
18469  	struct bpf_map *map_ptr;
18470  	struct bpf_insn *insn;
18471  	void *old_bpf_func;
18472  	int err, num_exentries;
18473  
18474  	if (env->subprog_cnt <= 1)
18475  		return 0;
18476  
18477  	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18478  		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18479  			continue;
18480  
18481  		/* Upon error here we cannot fall back to interpreter but
18482  		 * need a hard reject of the program. Thus -EFAULT is
18483  		 * propagated in any case.
18484  		 */
18485  		subprog = find_subprog(env, i + insn->imm + 1);
18486  		if (subprog < 0) {
18487  			WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18488  				  i + insn->imm + 1);
18489  			return -EFAULT;
18490  		}
18491  		/* temporarily remember subprog id inside insn instead of
18492  		 * aux_data, since next loop will split up all insns into funcs
18493  		 */
18494  		insn->off = subprog;
18495  		/* remember original imm in case JIT fails and fallback
18496  		 * to interpreter will be needed
18497  		 */
18498  		env->insn_aux_data[i].call_imm = insn->imm;
18499  		/* point imm to __bpf_call_base+1 from JITs point of view */
18500  		insn->imm = 1;
18501  		if (bpf_pseudo_func(insn))
18502  			/* jit (e.g. x86_64) may emit fewer instructions
18503  			 * if it learns a u32 imm is the same as a u64 imm.
18504  			 * Force a non zero here.
18505  			 */
18506  			insn[1].imm = 1;
18507  	}
18508  
18509  	err = bpf_prog_alloc_jited_linfo(prog);
18510  	if (err)
18511  		goto out_undo_insn;
18512  
18513  	err = -ENOMEM;
18514  	func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18515  	if (!func)
18516  		goto out_undo_insn;
18517  
18518  	for (i = 0; i < env->subprog_cnt; i++) {
18519  		subprog_start = subprog_end;
18520  		subprog_end = env->subprog_info[i + 1].start;
18521  
18522  		len = subprog_end - subprog_start;
18523  		/* bpf_prog_run() doesn't call subprogs directly,
18524  		 * hence main prog stats include the runtime of subprogs.
18525  		 * subprogs don't have IDs and not reachable via prog_get_next_id
18526  		 * func[i]->stats will never be accessed and stays NULL
18527  		 */
18528  		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18529  		if (!func[i])
18530  			goto out_free;
18531  		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18532  		       len * sizeof(struct bpf_insn));
18533  		func[i]->type = prog->type;
18534  		func[i]->len = len;
18535  		if (bpf_prog_calc_tag(func[i]))
18536  			goto out_free;
18537  		func[i]->is_func = 1;
18538  		func[i]->aux->func_idx = i;
18539  		/* Below members will be freed only at prog->aux */
18540  		func[i]->aux->btf = prog->aux->btf;
18541  		func[i]->aux->func_info = prog->aux->func_info;
18542  		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18543  		func[i]->aux->poke_tab = prog->aux->poke_tab;
18544  		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18545  
18546  		for (j = 0; j < prog->aux->size_poke_tab; j++) {
18547  			struct bpf_jit_poke_descriptor *poke;
18548  
18549  			poke = &prog->aux->poke_tab[j];
18550  			if (poke->insn_idx < subprog_end &&
18551  			    poke->insn_idx >= subprog_start)
18552  				poke->aux = func[i]->aux;
18553  		}
18554  
18555  		func[i]->aux->name[0] = 'F';
18556  		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18557  		func[i]->jit_requested = 1;
18558  		func[i]->blinding_requested = prog->blinding_requested;
18559  		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18560  		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18561  		func[i]->aux->linfo = prog->aux->linfo;
18562  		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18563  		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18564  		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18565  		num_exentries = 0;
18566  		insn = func[i]->insnsi;
18567  		for (j = 0; j < func[i]->len; j++, insn++) {
18568  			if (BPF_CLASS(insn->code) == BPF_LDX &&
18569  			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18570  			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18571  				num_exentries++;
18572  		}
18573  		func[i]->aux->num_exentries = num_exentries;
18574  		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18575  		func[i] = bpf_int_jit_compile(func[i]);
18576  		if (!func[i]->jited) {
18577  			err = -ENOTSUPP;
18578  			goto out_free;
18579  		}
18580  		cond_resched();
18581  	}
18582  
18583  	/* at this point all bpf functions were successfully JITed
18584  	 * now populate all bpf_calls with correct addresses and
18585  	 * run last pass of JIT
18586  	 */
18587  	for (i = 0; i < env->subprog_cnt; i++) {
18588  		insn = func[i]->insnsi;
18589  		for (j = 0; j < func[i]->len; j++, insn++) {
18590  			if (bpf_pseudo_func(insn)) {
18591  				subprog = insn->off;
18592  				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18593  				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18594  				continue;
18595  			}
18596  			if (!bpf_pseudo_call(insn))
18597  				continue;
18598  			subprog = insn->off;
18599  			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18600  		}
18601  
18602  		/* we use the aux data to keep a list of the start addresses
18603  		 * of the JITed images for each function in the program
18604  		 *
18605  		 * for some architectures, such as powerpc64, the imm field
18606  		 * might not be large enough to hold the offset of the start
18607  		 * address of the callee's JITed image from __bpf_call_base
18608  		 *
18609  		 * in such cases, we can lookup the start address of a callee
18610  		 * by using its subprog id, available from the off field of
18611  		 * the call instruction, as an index for this list
18612  		 */
18613  		func[i]->aux->func = func;
18614  		func[i]->aux->func_cnt = env->subprog_cnt;
18615  	}
18616  	for (i = 0; i < env->subprog_cnt; i++) {
18617  		old_bpf_func = func[i]->bpf_func;
18618  		tmp = bpf_int_jit_compile(func[i]);
18619  		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18620  			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18621  			err = -ENOTSUPP;
18622  			goto out_free;
18623  		}
18624  		cond_resched();
18625  	}
18626  
18627  	/* finally lock prog and jit images for all functions and
18628  	 * populate kallsysm. Begin at the first subprogram, since
18629  	 * bpf_prog_load will add the kallsyms for the main program.
18630  	 */
18631  	for (i = 1; i < env->subprog_cnt; i++) {
18632  		bpf_prog_lock_ro(func[i]);
18633  		bpf_prog_kallsyms_add(func[i]);
18634  	}
18635  
18636  	/* Last step: make now unused interpreter insns from main
18637  	 * prog consistent for later dump requests, so they can
18638  	 * later look the same as if they were interpreted only.
18639  	 */
18640  	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18641  		if (bpf_pseudo_func(insn)) {
18642  			insn[0].imm = env->insn_aux_data[i].call_imm;
18643  			insn[1].imm = insn->off;
18644  			insn->off = 0;
18645  			continue;
18646  		}
18647  		if (!bpf_pseudo_call(insn))
18648  			continue;
18649  		insn->off = env->insn_aux_data[i].call_imm;
18650  		subprog = find_subprog(env, i + insn->off + 1);
18651  		insn->imm = subprog;
18652  	}
18653  
18654  	prog->jited = 1;
18655  	prog->bpf_func = func[0]->bpf_func;
18656  	prog->jited_len = func[0]->jited_len;
18657  	prog->aux->extable = func[0]->aux->extable;
18658  	prog->aux->num_exentries = func[0]->aux->num_exentries;
18659  	prog->aux->func = func;
18660  	prog->aux->func_cnt = env->subprog_cnt;
18661  	bpf_prog_jit_attempt_done(prog);
18662  	return 0;
18663  out_free:
18664  	/* We failed JIT'ing, so at this point we need to unregister poke
18665  	 * descriptors from subprogs, so that kernel is not attempting to
18666  	 * patch it anymore as we're freeing the subprog JIT memory.
18667  	 */
18668  	for (i = 0; i < prog->aux->size_poke_tab; i++) {
18669  		map_ptr = prog->aux->poke_tab[i].tail_call.map;
18670  		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18671  	}
18672  	/* At this point we're guaranteed that poke descriptors are not
18673  	 * live anymore. We can just unlink its descriptor table as it's
18674  	 * released with the main prog.
18675  	 */
18676  	for (i = 0; i < env->subprog_cnt; i++) {
18677  		if (!func[i])
18678  			continue;
18679  		func[i]->aux->poke_tab = NULL;
18680  		bpf_jit_free(func[i]);
18681  	}
18682  	kfree(func);
18683  out_undo_insn:
18684  	/* cleanup main prog to be interpreted */
18685  	prog->jit_requested = 0;
18686  	prog->blinding_requested = 0;
18687  	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18688  		if (!bpf_pseudo_call(insn))
18689  			continue;
18690  		insn->off = 0;
18691  		insn->imm = env->insn_aux_data[i].call_imm;
18692  	}
18693  	bpf_prog_jit_attempt_done(prog);
18694  	return err;
18695  }
18696  
fixup_call_args(struct bpf_verifier_env * env)18697  static int fixup_call_args(struct bpf_verifier_env *env)
18698  {
18699  #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18700  	struct bpf_prog *prog = env->prog;
18701  	struct bpf_insn *insn = prog->insnsi;
18702  	bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18703  	int i, depth;
18704  #endif
18705  	int err = 0;
18706  
18707  	if (env->prog->jit_requested &&
18708  	    !bpf_prog_is_offloaded(env->prog->aux)) {
18709  		err = jit_subprogs(env);
18710  		if (err == 0)
18711  			return 0;
18712  		if (err == -EFAULT)
18713  			return err;
18714  	}
18715  #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18716  	if (has_kfunc_call) {
18717  		verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18718  		return -EINVAL;
18719  	}
18720  	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18721  		/* When JIT fails the progs with bpf2bpf calls and tail_calls
18722  		 * have to be rejected, since interpreter doesn't support them yet.
18723  		 */
18724  		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18725  		return -EINVAL;
18726  	}
18727  	for (i = 0; i < prog->len; i++, insn++) {
18728  		if (bpf_pseudo_func(insn)) {
18729  			/* When JIT fails the progs with callback calls
18730  			 * have to be rejected, since interpreter doesn't support them yet.
18731  			 */
18732  			verbose(env, "callbacks are not allowed in non-JITed programs\n");
18733  			return -EINVAL;
18734  		}
18735  
18736  		if (!bpf_pseudo_call(insn))
18737  			continue;
18738  		depth = get_callee_stack_depth(env, insn, i);
18739  		if (depth < 0)
18740  			return depth;
18741  		bpf_patch_call_args(insn, depth);
18742  	}
18743  	err = 0;
18744  #endif
18745  	return err;
18746  }
18747  
18748  /* replace a generic kfunc with a specialized version if necessary */
specialize_kfunc(struct bpf_verifier_env * env,u32 func_id,u16 offset,unsigned long * addr)18749  static void specialize_kfunc(struct bpf_verifier_env *env,
18750  			     u32 func_id, u16 offset, unsigned long *addr)
18751  {
18752  	struct bpf_prog *prog = env->prog;
18753  	bool seen_direct_write;
18754  	void *xdp_kfunc;
18755  	bool is_rdonly;
18756  
18757  	if (bpf_dev_bound_kfunc_id(func_id)) {
18758  		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18759  		if (xdp_kfunc) {
18760  			*addr = (unsigned long)xdp_kfunc;
18761  			return;
18762  		}
18763  		/* fallback to default kfunc when not supported by netdev */
18764  	}
18765  
18766  	if (offset)
18767  		return;
18768  
18769  	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18770  		seen_direct_write = env->seen_direct_write;
18771  		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18772  
18773  		if (is_rdonly)
18774  			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18775  
18776  		/* restore env->seen_direct_write to its original value, since
18777  		 * may_access_direct_pkt_data mutates it
18778  		 */
18779  		env->seen_direct_write = seen_direct_write;
18780  	}
18781  }
18782  
__fixup_collection_insert_kfunc(struct bpf_insn_aux_data * insn_aux,u16 struct_meta_reg,u16 node_offset_reg,struct bpf_insn * insn,struct bpf_insn * insn_buf,int * cnt)18783  static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18784  					    u16 struct_meta_reg,
18785  					    u16 node_offset_reg,
18786  					    struct bpf_insn *insn,
18787  					    struct bpf_insn *insn_buf,
18788  					    int *cnt)
18789  {
18790  	struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18791  	struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18792  
18793  	insn_buf[0] = addr[0];
18794  	insn_buf[1] = addr[1];
18795  	insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18796  	insn_buf[3] = *insn;
18797  	*cnt = 4;
18798  }
18799  
fixup_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_insn * insn_buf,int insn_idx,int * cnt)18800  static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18801  			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18802  {
18803  	const struct bpf_kfunc_desc *desc;
18804  
18805  	if (!insn->imm) {
18806  		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18807  		return -EINVAL;
18808  	}
18809  
18810  	*cnt = 0;
18811  
18812  	/* insn->imm has the btf func_id. Replace it with an offset relative to
18813  	 * __bpf_call_base, unless the JIT needs to call functions that are
18814  	 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18815  	 */
18816  	desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18817  	if (!desc) {
18818  		verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18819  			insn->imm);
18820  		return -EFAULT;
18821  	}
18822  
18823  	if (!bpf_jit_supports_far_kfunc_call())
18824  		insn->imm = BPF_CALL_IMM(desc->addr);
18825  	if (insn->off)
18826  		return 0;
18827  	if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18828  		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18829  		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18830  		u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18831  
18832  		insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18833  		insn_buf[1] = addr[0];
18834  		insn_buf[2] = addr[1];
18835  		insn_buf[3] = *insn;
18836  		*cnt = 4;
18837  	} else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18838  		   desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18839  		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18840  		struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18841  
18842  		if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
18843  		    !kptr_struct_meta) {
18844  			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18845  				insn_idx);
18846  			return -EFAULT;
18847  		}
18848  
18849  		insn_buf[0] = addr[0];
18850  		insn_buf[1] = addr[1];
18851  		insn_buf[2] = *insn;
18852  		*cnt = 3;
18853  	} else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18854  		   desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18855  		   desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18856  		struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18857  		int struct_meta_reg = BPF_REG_3;
18858  		int node_offset_reg = BPF_REG_4;
18859  
18860  		/* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18861  		if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18862  			struct_meta_reg = BPF_REG_4;
18863  			node_offset_reg = BPF_REG_5;
18864  		}
18865  
18866  		if (!kptr_struct_meta) {
18867  			verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18868  				insn_idx);
18869  			return -EFAULT;
18870  		}
18871  
18872  		__fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18873  						node_offset_reg, insn, insn_buf, cnt);
18874  	} else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18875  		   desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18876  		insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18877  		*cnt = 1;
18878  	}
18879  	return 0;
18880  }
18881  
18882  /* Do various post-verification rewrites in a single program pass.
18883   * These rewrites simplify JIT and interpreter implementations.
18884   */
do_misc_fixups(struct bpf_verifier_env * env)18885  static int do_misc_fixups(struct bpf_verifier_env *env)
18886  {
18887  	struct bpf_prog *prog = env->prog;
18888  	enum bpf_attach_type eatype = prog->expected_attach_type;
18889  	enum bpf_prog_type prog_type = resolve_prog_type(prog);
18890  	struct bpf_insn *insn = prog->insnsi;
18891  	const struct bpf_func_proto *fn;
18892  	const int insn_cnt = prog->len;
18893  	const struct bpf_map_ops *ops;
18894  	struct bpf_insn_aux_data *aux;
18895  	struct bpf_insn insn_buf[16];
18896  	struct bpf_prog *new_prog;
18897  	struct bpf_map *map_ptr;
18898  	int i, ret, cnt, delta = 0;
18899  
18900  	for (i = 0; i < insn_cnt; i++, insn++) {
18901  		/* Make divide-by-zero exceptions impossible. */
18902  		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18903  		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18904  		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18905  		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18906  			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18907  			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18908  			struct bpf_insn *patchlet;
18909  			struct bpf_insn chk_and_div[] = {
18910  				/* [R,W]x div 0 -> 0 */
18911  				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18912  					     BPF_JNE | BPF_K, insn->src_reg,
18913  					     0, 2, 0),
18914  				BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18915  				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18916  				*insn,
18917  			};
18918  			struct bpf_insn chk_and_mod[] = {
18919  				/* [R,W]x mod 0 -> [R,W]x */
18920  				BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18921  					     BPF_JEQ | BPF_K, insn->src_reg,
18922  					     0, 1 + (is64 ? 0 : 1), 0),
18923  				*insn,
18924  				BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18925  				BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18926  			};
18927  
18928  			patchlet = isdiv ? chk_and_div : chk_and_mod;
18929  			cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18930  				      ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18931  
18932  			new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18933  			if (!new_prog)
18934  				return -ENOMEM;
18935  
18936  			delta    += cnt - 1;
18937  			env->prog = prog = new_prog;
18938  			insn      = new_prog->insnsi + i + delta;
18939  			continue;
18940  		}
18941  
18942  		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18943  		if (BPF_CLASS(insn->code) == BPF_LD &&
18944  		    (BPF_MODE(insn->code) == BPF_ABS ||
18945  		     BPF_MODE(insn->code) == BPF_IND)) {
18946  			cnt = env->ops->gen_ld_abs(insn, insn_buf);
18947  			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18948  				verbose(env, "bpf verifier is misconfigured\n");
18949  				return -EINVAL;
18950  			}
18951  
18952  			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18953  			if (!new_prog)
18954  				return -ENOMEM;
18955  
18956  			delta    += cnt - 1;
18957  			env->prog = prog = new_prog;
18958  			insn      = new_prog->insnsi + i + delta;
18959  			continue;
18960  		}
18961  
18962  		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
18963  		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18964  		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18965  			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18966  			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18967  			struct bpf_insn *patch = &insn_buf[0];
18968  			bool issrc, isneg, isimm;
18969  			u32 off_reg;
18970  
18971  			aux = &env->insn_aux_data[i + delta];
18972  			if (!aux->alu_state ||
18973  			    aux->alu_state == BPF_ALU_NON_POINTER)
18974  				continue;
18975  
18976  			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18977  			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18978  				BPF_ALU_SANITIZE_SRC;
18979  			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18980  
18981  			off_reg = issrc ? insn->src_reg : insn->dst_reg;
18982  			if (isimm) {
18983  				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18984  			} else {
18985  				if (isneg)
18986  					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18987  				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18988  				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18989  				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18990  				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18991  				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18992  				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18993  			}
18994  			if (!issrc)
18995  				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18996  			insn->src_reg = BPF_REG_AX;
18997  			if (isneg)
18998  				insn->code = insn->code == code_add ?
18999  					     code_sub : code_add;
19000  			*patch++ = *insn;
19001  			if (issrc && isneg && !isimm)
19002  				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19003  			cnt = patch - insn_buf;
19004  
19005  			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19006  			if (!new_prog)
19007  				return -ENOMEM;
19008  
19009  			delta    += cnt - 1;
19010  			env->prog = prog = new_prog;
19011  			insn      = new_prog->insnsi + i + delta;
19012  			continue;
19013  		}
19014  
19015  		if (insn->code != (BPF_JMP | BPF_CALL))
19016  			continue;
19017  		if (insn->src_reg == BPF_PSEUDO_CALL)
19018  			continue;
19019  		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19020  			ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
19021  			if (ret)
19022  				return ret;
19023  			if (cnt == 0)
19024  				continue;
19025  
19026  			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19027  			if (!new_prog)
19028  				return -ENOMEM;
19029  
19030  			delta	 += cnt - 1;
19031  			env->prog = prog = new_prog;
19032  			insn	  = new_prog->insnsi + i + delta;
19033  			continue;
19034  		}
19035  
19036  		if (insn->imm == BPF_FUNC_get_route_realm)
19037  			prog->dst_needed = 1;
19038  		if (insn->imm == BPF_FUNC_get_prandom_u32)
19039  			bpf_user_rnd_init_once();
19040  		if (insn->imm == BPF_FUNC_override_return)
19041  			prog->kprobe_override = 1;
19042  		if (insn->imm == BPF_FUNC_tail_call) {
19043  			/* If we tail call into other programs, we
19044  			 * cannot make any assumptions since they can
19045  			 * be replaced dynamically during runtime in
19046  			 * the program array.
19047  			 */
19048  			prog->cb_access = 1;
19049  			if (!allow_tail_call_in_subprogs(env))
19050  				prog->aux->stack_depth = MAX_BPF_STACK;
19051  			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19052  
19053  			/* mark bpf_tail_call as different opcode to avoid
19054  			 * conditional branch in the interpreter for every normal
19055  			 * call and to prevent accidental JITing by JIT compiler
19056  			 * that doesn't support bpf_tail_call yet
19057  			 */
19058  			insn->imm = 0;
19059  			insn->code = BPF_JMP | BPF_TAIL_CALL;
19060  
19061  			aux = &env->insn_aux_data[i + delta];
19062  			if (env->bpf_capable && !prog->blinding_requested &&
19063  			    prog->jit_requested &&
19064  			    !bpf_map_key_poisoned(aux) &&
19065  			    !bpf_map_ptr_poisoned(aux) &&
19066  			    !bpf_map_ptr_unpriv(aux)) {
19067  				struct bpf_jit_poke_descriptor desc = {
19068  					.reason = BPF_POKE_REASON_TAIL_CALL,
19069  					.tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19070  					.tail_call.key = bpf_map_key_immediate(aux),
19071  					.insn_idx = i + delta,
19072  				};
19073  
19074  				ret = bpf_jit_add_poke_descriptor(prog, &desc);
19075  				if (ret < 0) {
19076  					verbose(env, "adding tail call poke descriptor failed\n");
19077  					return ret;
19078  				}
19079  
19080  				insn->imm = ret + 1;
19081  				continue;
19082  			}
19083  
19084  			if (!bpf_map_ptr_unpriv(aux))
19085  				continue;
19086  
19087  			/* instead of changing every JIT dealing with tail_call
19088  			 * emit two extra insns:
19089  			 * if (index >= max_entries) goto out;
19090  			 * index &= array->index_mask;
19091  			 * to avoid out-of-bounds cpu speculation
19092  			 */
19093  			if (bpf_map_ptr_poisoned(aux)) {
19094  				verbose(env, "tail_call abusing map_ptr\n");
19095  				return -EINVAL;
19096  			}
19097  
19098  			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19099  			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19100  						  map_ptr->max_entries, 2);
19101  			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19102  						    container_of(map_ptr,
19103  								 struct bpf_array,
19104  								 map)->index_mask);
19105  			insn_buf[2] = *insn;
19106  			cnt = 3;
19107  			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19108  			if (!new_prog)
19109  				return -ENOMEM;
19110  
19111  			delta    += cnt - 1;
19112  			env->prog = prog = new_prog;
19113  			insn      = new_prog->insnsi + i + delta;
19114  			continue;
19115  		}
19116  
19117  		if (insn->imm == BPF_FUNC_timer_set_callback) {
19118  			/* The verifier will process callback_fn as many times as necessary
19119  			 * with different maps and the register states prepared by
19120  			 * set_timer_callback_state will be accurate.
19121  			 *
19122  			 * The following use case is valid:
19123  			 *   map1 is shared by prog1, prog2, prog3.
19124  			 *   prog1 calls bpf_timer_init for some map1 elements
19125  			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
19126  			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
19127  			 *   prog3 calls bpf_timer_start for some map1 elements.
19128  			 *     Those that were not both bpf_timer_init-ed and
19129  			 *     bpf_timer_set_callback-ed will return -EINVAL.
19130  			 */
19131  			struct bpf_insn ld_addrs[2] = {
19132  				BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19133  			};
19134  
19135  			insn_buf[0] = ld_addrs[0];
19136  			insn_buf[1] = ld_addrs[1];
19137  			insn_buf[2] = *insn;
19138  			cnt = 3;
19139  
19140  			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19141  			if (!new_prog)
19142  				return -ENOMEM;
19143  
19144  			delta    += cnt - 1;
19145  			env->prog = prog = new_prog;
19146  			insn      = new_prog->insnsi + i + delta;
19147  			goto patch_call_imm;
19148  		}
19149  
19150  		if (is_storage_get_function(insn->imm)) {
19151  			if (!env->prog->aux->sleepable ||
19152  			    env->insn_aux_data[i + delta].storage_get_func_atomic)
19153  				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19154  			else
19155  				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19156  			insn_buf[1] = *insn;
19157  			cnt = 2;
19158  
19159  			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19160  			if (!new_prog)
19161  				return -ENOMEM;
19162  
19163  			delta += cnt - 1;
19164  			env->prog = prog = new_prog;
19165  			insn = new_prog->insnsi + i + delta;
19166  			goto patch_call_imm;
19167  		}
19168  
19169  		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19170  		 * and other inlining handlers are currently limited to 64 bit
19171  		 * only.
19172  		 */
19173  		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19174  		    (insn->imm == BPF_FUNC_map_lookup_elem ||
19175  		     insn->imm == BPF_FUNC_map_update_elem ||
19176  		     insn->imm == BPF_FUNC_map_delete_elem ||
19177  		     insn->imm == BPF_FUNC_map_push_elem   ||
19178  		     insn->imm == BPF_FUNC_map_pop_elem    ||
19179  		     insn->imm == BPF_FUNC_map_peek_elem   ||
19180  		     insn->imm == BPF_FUNC_redirect_map    ||
19181  		     insn->imm == BPF_FUNC_for_each_map_elem ||
19182  		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19183  			aux = &env->insn_aux_data[i + delta];
19184  			if (bpf_map_ptr_poisoned(aux))
19185  				goto patch_call_imm;
19186  
19187  			map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19188  			ops = map_ptr->ops;
19189  			if (insn->imm == BPF_FUNC_map_lookup_elem &&
19190  			    ops->map_gen_lookup) {
19191  				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19192  				if (cnt == -EOPNOTSUPP)
19193  					goto patch_map_ops_generic;
19194  				if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19195  					verbose(env, "bpf verifier is misconfigured\n");
19196  					return -EINVAL;
19197  				}
19198  
19199  				new_prog = bpf_patch_insn_data(env, i + delta,
19200  							       insn_buf, cnt);
19201  				if (!new_prog)
19202  					return -ENOMEM;
19203  
19204  				delta    += cnt - 1;
19205  				env->prog = prog = new_prog;
19206  				insn      = new_prog->insnsi + i + delta;
19207  				continue;
19208  			}
19209  
19210  			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19211  				     (void *(*)(struct bpf_map *map, void *key))NULL));
19212  			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19213  				     (long (*)(struct bpf_map *map, void *key))NULL));
19214  			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19215  				     (long (*)(struct bpf_map *map, void *key, void *value,
19216  					      u64 flags))NULL));
19217  			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19218  				     (long (*)(struct bpf_map *map, void *value,
19219  					      u64 flags))NULL));
19220  			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19221  				     (long (*)(struct bpf_map *map, void *value))NULL));
19222  			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19223  				     (long (*)(struct bpf_map *map, void *value))NULL));
19224  			BUILD_BUG_ON(!__same_type(ops->map_redirect,
19225  				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19226  			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19227  				     (long (*)(struct bpf_map *map,
19228  					      bpf_callback_t callback_fn,
19229  					      void *callback_ctx,
19230  					      u64 flags))NULL));
19231  			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19232  				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19233  
19234  patch_map_ops_generic:
19235  			switch (insn->imm) {
19236  			case BPF_FUNC_map_lookup_elem:
19237  				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19238  				continue;
19239  			case BPF_FUNC_map_update_elem:
19240  				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19241  				continue;
19242  			case BPF_FUNC_map_delete_elem:
19243  				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19244  				continue;
19245  			case BPF_FUNC_map_push_elem:
19246  				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19247  				continue;
19248  			case BPF_FUNC_map_pop_elem:
19249  				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19250  				continue;
19251  			case BPF_FUNC_map_peek_elem:
19252  				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19253  				continue;
19254  			case BPF_FUNC_redirect_map:
19255  				insn->imm = BPF_CALL_IMM(ops->map_redirect);
19256  				continue;
19257  			case BPF_FUNC_for_each_map_elem:
19258  				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19259  				continue;
19260  			case BPF_FUNC_map_lookup_percpu_elem:
19261  				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19262  				continue;
19263  			}
19264  
19265  			goto patch_call_imm;
19266  		}
19267  
19268  		/* Implement bpf_jiffies64 inline. */
19269  		if (prog->jit_requested && BITS_PER_LONG == 64 &&
19270  		    insn->imm == BPF_FUNC_jiffies64) {
19271  			struct bpf_insn ld_jiffies_addr[2] = {
19272  				BPF_LD_IMM64(BPF_REG_0,
19273  					     (unsigned long)&jiffies),
19274  			};
19275  
19276  			insn_buf[0] = ld_jiffies_addr[0];
19277  			insn_buf[1] = ld_jiffies_addr[1];
19278  			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19279  						  BPF_REG_0, 0);
19280  			cnt = 3;
19281  
19282  			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19283  						       cnt);
19284  			if (!new_prog)
19285  				return -ENOMEM;
19286  
19287  			delta    += cnt - 1;
19288  			env->prog = prog = new_prog;
19289  			insn      = new_prog->insnsi + i + delta;
19290  			continue;
19291  		}
19292  
19293  		/* Implement bpf_get_func_arg inline. */
19294  		if (prog_type == BPF_PROG_TYPE_TRACING &&
19295  		    insn->imm == BPF_FUNC_get_func_arg) {
19296  			/* Load nr_args from ctx - 8 */
19297  			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19298  			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19299  			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19300  			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19301  			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19302  			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19303  			insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19304  			insn_buf[7] = BPF_JMP_A(1);
19305  			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19306  			cnt = 9;
19307  
19308  			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19309  			if (!new_prog)
19310  				return -ENOMEM;
19311  
19312  			delta    += cnt - 1;
19313  			env->prog = prog = new_prog;
19314  			insn      = new_prog->insnsi + i + delta;
19315  			continue;
19316  		}
19317  
19318  		/* Implement bpf_get_func_ret inline. */
19319  		if (prog_type == BPF_PROG_TYPE_TRACING &&
19320  		    insn->imm == BPF_FUNC_get_func_ret) {
19321  			if (eatype == BPF_TRACE_FEXIT ||
19322  			    eatype == BPF_MODIFY_RETURN) {
19323  				/* Load nr_args from ctx - 8 */
19324  				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19325  				insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19326  				insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19327  				insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19328  				insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19329  				insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19330  				cnt = 6;
19331  			} else {
19332  				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19333  				cnt = 1;
19334  			}
19335  
19336  			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19337  			if (!new_prog)
19338  				return -ENOMEM;
19339  
19340  			delta    += cnt - 1;
19341  			env->prog = prog = new_prog;
19342  			insn      = new_prog->insnsi + i + delta;
19343  			continue;
19344  		}
19345  
19346  		/* Implement get_func_arg_cnt inline. */
19347  		if (prog_type == BPF_PROG_TYPE_TRACING &&
19348  		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
19349  			/* Load nr_args from ctx - 8 */
19350  			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19351  
19352  			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19353  			if (!new_prog)
19354  				return -ENOMEM;
19355  
19356  			env->prog = prog = new_prog;
19357  			insn      = new_prog->insnsi + i + delta;
19358  			continue;
19359  		}
19360  
19361  		/* Implement bpf_get_func_ip inline. */
19362  		if (prog_type == BPF_PROG_TYPE_TRACING &&
19363  		    insn->imm == BPF_FUNC_get_func_ip) {
19364  			/* Load IP address from ctx - 16 */
19365  			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19366  
19367  			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19368  			if (!new_prog)
19369  				return -ENOMEM;
19370  
19371  			env->prog = prog = new_prog;
19372  			insn      = new_prog->insnsi + i + delta;
19373  			continue;
19374  		}
19375  
19376  patch_call_imm:
19377  		fn = env->ops->get_func_proto(insn->imm, env->prog);
19378  		/* all functions that have prototype and verifier allowed
19379  		 * programs to call them, must be real in-kernel functions
19380  		 */
19381  		if (!fn->func) {
19382  			verbose(env,
19383  				"kernel subsystem misconfigured func %s#%d\n",
19384  				func_id_name(insn->imm), insn->imm);
19385  			return -EFAULT;
19386  		}
19387  		insn->imm = fn->func - __bpf_call_base;
19388  	}
19389  
19390  	/* Since poke tab is now finalized, publish aux to tracker. */
19391  	for (i = 0; i < prog->aux->size_poke_tab; i++) {
19392  		map_ptr = prog->aux->poke_tab[i].tail_call.map;
19393  		if (!map_ptr->ops->map_poke_track ||
19394  		    !map_ptr->ops->map_poke_untrack ||
19395  		    !map_ptr->ops->map_poke_run) {
19396  			verbose(env, "bpf verifier is misconfigured\n");
19397  			return -EINVAL;
19398  		}
19399  
19400  		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19401  		if (ret < 0) {
19402  			verbose(env, "tracking tail call prog failed\n");
19403  			return ret;
19404  		}
19405  	}
19406  
19407  	sort_kfunc_descs_by_imm_off(env->prog);
19408  
19409  	return 0;
19410  }
19411  
inline_bpf_loop(struct bpf_verifier_env * env,int position,s32 stack_base,u32 callback_subprogno,u32 * cnt)19412  static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19413  					int position,
19414  					s32 stack_base,
19415  					u32 callback_subprogno,
19416  					u32 *cnt)
19417  {
19418  	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19419  	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19420  	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19421  	int reg_loop_max = BPF_REG_6;
19422  	int reg_loop_cnt = BPF_REG_7;
19423  	int reg_loop_ctx = BPF_REG_8;
19424  
19425  	struct bpf_prog *new_prog;
19426  	u32 callback_start;
19427  	u32 call_insn_offset;
19428  	s32 callback_offset;
19429  
19430  	/* This represents an inlined version of bpf_iter.c:bpf_loop,
19431  	 * be careful to modify this code in sync.
19432  	 */
19433  	struct bpf_insn insn_buf[] = {
19434  		/* Return error and jump to the end of the patch if
19435  		 * expected number of iterations is too big.
19436  		 */
19437  		BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19438  		BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19439  		BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19440  		/* spill R6, R7, R8 to use these as loop vars */
19441  		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19442  		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
19443  		BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
19444  		/* initialize loop vars */
19445  		BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
19446  		BPF_MOV32_IMM(reg_loop_cnt, 0),
19447  		BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
19448  		/* loop header,
19449  		 * if reg_loop_cnt >= reg_loop_max skip the loop body
19450  		 */
19451  		BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
19452  		/* callback call,
19453  		 * correct callback offset would be set after patching
19454  		 */
19455  		BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
19456  		BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
19457  		BPF_CALL_REL(0),
19458  		/* increment loop counter */
19459  		BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
19460  		/* jump to loop header if callback returned 0 */
19461  		BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
19462  		/* return value of bpf_loop,
19463  		 * set R0 to the number of iterations
19464  		 */
19465  		BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
19466  		/* restore original values of R6, R7, R8 */
19467  		BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
19468  		BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
19469  		BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
19470  	};
19471  
19472  	*cnt = ARRAY_SIZE(insn_buf);
19473  	new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
19474  	if (!new_prog)
19475  		return new_prog;
19476  
19477  	/* callback start is known only after patching */
19478  	callback_start = env->subprog_info[callback_subprogno].start;
19479  	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
19480  	call_insn_offset = position + 12;
19481  	callback_offset = callback_start - call_insn_offset - 1;
19482  	new_prog->insnsi[call_insn_offset].imm = callback_offset;
19483  
19484  	return new_prog;
19485  }
19486  
is_bpf_loop_call(struct bpf_insn * insn)19487  static bool is_bpf_loop_call(struct bpf_insn *insn)
19488  {
19489  	return insn->code == (BPF_JMP | BPF_CALL) &&
19490  		insn->src_reg == 0 &&
19491  		insn->imm == BPF_FUNC_loop;
19492  }
19493  
19494  /* For all sub-programs in the program (including main) check
19495   * insn_aux_data to see if there are bpf_loop calls that require
19496   * inlining. If such calls are found the calls are replaced with a
19497   * sequence of instructions produced by `inline_bpf_loop` function and
19498   * subprog stack_depth is increased by the size of 3 registers.
19499   * This stack space is used to spill values of the R6, R7, R8.  These
19500   * registers are used to store the loop bound, counter and context
19501   * variables.
19502   */
optimize_bpf_loop(struct bpf_verifier_env * env)19503  static int optimize_bpf_loop(struct bpf_verifier_env *env)
19504  {
19505  	struct bpf_subprog_info *subprogs = env->subprog_info;
19506  	int i, cur_subprog = 0, cnt, delta = 0;
19507  	struct bpf_insn *insn = env->prog->insnsi;
19508  	int insn_cnt = env->prog->len;
19509  	u16 stack_depth = subprogs[cur_subprog].stack_depth;
19510  	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19511  	u16 stack_depth_extra = 0;
19512  
19513  	for (i = 0; i < insn_cnt; i++, insn++) {
19514  		struct bpf_loop_inline_state *inline_state =
19515  			&env->insn_aux_data[i + delta].loop_inline_state;
19516  
19517  		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
19518  			struct bpf_prog *new_prog;
19519  
19520  			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
19521  			new_prog = inline_bpf_loop(env,
19522  						   i + delta,
19523  						   -(stack_depth + stack_depth_extra),
19524  						   inline_state->callback_subprogno,
19525  						   &cnt);
19526  			if (!new_prog)
19527  				return -ENOMEM;
19528  
19529  			delta     += cnt - 1;
19530  			env->prog  = new_prog;
19531  			insn       = new_prog->insnsi + i + delta;
19532  		}
19533  
19534  		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19535  			subprogs[cur_subprog].stack_depth += stack_depth_extra;
19536  			cur_subprog++;
19537  			stack_depth = subprogs[cur_subprog].stack_depth;
19538  			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19539  			stack_depth_extra = 0;
19540  		}
19541  	}
19542  
19543  	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19544  
19545  	return 0;
19546  }
19547  
free_states(struct bpf_verifier_env * env)19548  static void free_states(struct bpf_verifier_env *env)
19549  {
19550  	struct bpf_verifier_state_list *sl, *sln;
19551  	int i;
19552  
19553  	sl = env->free_list;
19554  	while (sl) {
19555  		sln = sl->next;
19556  		free_verifier_state(&sl->state, false);
19557  		kfree(sl);
19558  		sl = sln;
19559  	}
19560  	env->free_list = NULL;
19561  
19562  	if (!env->explored_states)
19563  		return;
19564  
19565  	for (i = 0; i < state_htab_size(env); i++) {
19566  		sl = env->explored_states[i];
19567  
19568  		while (sl) {
19569  			sln = sl->next;
19570  			free_verifier_state(&sl->state, false);
19571  			kfree(sl);
19572  			sl = sln;
19573  		}
19574  		env->explored_states[i] = NULL;
19575  	}
19576  }
19577  
do_check_common(struct bpf_verifier_env * env,int subprog)19578  static int do_check_common(struct bpf_verifier_env *env, int subprog)
19579  {
19580  	bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19581  	struct bpf_verifier_state *state;
19582  	struct bpf_reg_state *regs;
19583  	int ret, i;
19584  
19585  	env->prev_linfo = NULL;
19586  	env->pass_cnt++;
19587  
19588  	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19589  	if (!state)
19590  		return -ENOMEM;
19591  	state->curframe = 0;
19592  	state->speculative = false;
19593  	state->branches = 1;
19594  	state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19595  	if (!state->frame[0]) {
19596  		kfree(state);
19597  		return -ENOMEM;
19598  	}
19599  	env->cur_state = state;
19600  	init_func_state(env, state->frame[0],
19601  			BPF_MAIN_FUNC /* callsite */,
19602  			0 /* frameno */,
19603  			subprog);
19604  	state->first_insn_idx = env->subprog_info[subprog].start;
19605  	state->last_insn_idx = -1;
19606  
19607  	regs = state->frame[state->curframe]->regs;
19608  	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19609  		ret = btf_prepare_func_args(env, subprog, regs);
19610  		if (ret)
19611  			goto out;
19612  		for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19613  			if (regs[i].type == PTR_TO_CTX)
19614  				mark_reg_known_zero(env, regs, i);
19615  			else if (regs[i].type == SCALAR_VALUE)
19616  				mark_reg_unknown(env, regs, i);
19617  			else if (base_type(regs[i].type) == PTR_TO_MEM) {
19618  				const u32 mem_size = regs[i].mem_size;
19619  
19620  				mark_reg_known_zero(env, regs, i);
19621  				regs[i].mem_size = mem_size;
19622  				regs[i].id = ++env->id_gen;
19623  			}
19624  		}
19625  	} else {
19626  		/* 1st arg to a function */
19627  		regs[BPF_REG_1].type = PTR_TO_CTX;
19628  		mark_reg_known_zero(env, regs, BPF_REG_1);
19629  		ret = btf_check_subprog_arg_match(env, subprog, regs);
19630  		if (ret == -EFAULT)
19631  			/* unlikely verifier bug. abort.
19632  			 * ret == 0 and ret < 0 are sadly acceptable for
19633  			 * main() function due to backward compatibility.
19634  			 * Like socket filter program may be written as:
19635  			 * int bpf_prog(struct pt_regs *ctx)
19636  			 * and never dereference that ctx in the program.
19637  			 * 'struct pt_regs' is a type mismatch for socket
19638  			 * filter that should be using 'struct __sk_buff'.
19639  			 */
19640  			goto out;
19641  	}
19642  
19643  	ret = do_check(env);
19644  out:
19645  	/* check for NULL is necessary, since cur_state can be freed inside
19646  	 * do_check() under memory pressure.
19647  	 */
19648  	if (env->cur_state) {
19649  		free_verifier_state(env->cur_state, true);
19650  		env->cur_state = NULL;
19651  	}
19652  	while (!pop_stack(env, NULL, NULL, false));
19653  	if (!ret && pop_log)
19654  		bpf_vlog_reset(&env->log, 0);
19655  	free_states(env);
19656  	return ret;
19657  }
19658  
19659  /* Verify all global functions in a BPF program one by one based on their BTF.
19660   * All global functions must pass verification. Otherwise the whole program is rejected.
19661   * Consider:
19662   * int bar(int);
19663   * int foo(int f)
19664   * {
19665   *    return bar(f);
19666   * }
19667   * int bar(int b)
19668   * {
19669   *    ...
19670   * }
19671   * foo() will be verified first for R1=any_scalar_value. During verification it
19672   * will be assumed that bar() already verified successfully and call to bar()
19673   * from foo() will be checked for type match only. Later bar() will be verified
19674   * independently to check that it's safe for R1=any_scalar_value.
19675   */
do_check_subprogs(struct bpf_verifier_env * env)19676  static int do_check_subprogs(struct bpf_verifier_env *env)
19677  {
19678  	struct bpf_prog_aux *aux = env->prog->aux;
19679  	int i, ret;
19680  
19681  	if (!aux->func_info)
19682  		return 0;
19683  
19684  	for (i = 1; i < env->subprog_cnt; i++) {
19685  		if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19686  			continue;
19687  		env->insn_idx = env->subprog_info[i].start;
19688  		WARN_ON_ONCE(env->insn_idx == 0);
19689  		ret = do_check_common(env, i);
19690  		if (ret) {
19691  			return ret;
19692  		} else if (env->log.level & BPF_LOG_LEVEL) {
19693  			verbose(env,
19694  				"Func#%d is safe for any args that match its prototype\n",
19695  				i);
19696  		}
19697  	}
19698  	return 0;
19699  }
19700  
do_check_main(struct bpf_verifier_env * env)19701  static int do_check_main(struct bpf_verifier_env *env)
19702  {
19703  	int ret;
19704  
19705  	env->insn_idx = 0;
19706  	ret = do_check_common(env, 0);
19707  	if (!ret)
19708  		env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19709  	return ret;
19710  }
19711  
19712  
print_verification_stats(struct bpf_verifier_env * env)19713  static void print_verification_stats(struct bpf_verifier_env *env)
19714  {
19715  	int i;
19716  
19717  	if (env->log.level & BPF_LOG_STATS) {
19718  		verbose(env, "verification time %lld usec\n",
19719  			div_u64(env->verification_time, 1000));
19720  		verbose(env, "stack depth ");
19721  		for (i = 0; i < env->subprog_cnt; i++) {
19722  			u32 depth = env->subprog_info[i].stack_depth;
19723  
19724  			verbose(env, "%d", depth);
19725  			if (i + 1 < env->subprog_cnt)
19726  				verbose(env, "+");
19727  		}
19728  		verbose(env, "\n");
19729  	}
19730  	verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19731  		"total_states %d peak_states %d mark_read %d\n",
19732  		env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19733  		env->max_states_per_insn, env->total_states,
19734  		env->peak_states, env->longest_mark_read_walk);
19735  }
19736  
check_struct_ops_btf_id(struct bpf_verifier_env * env)19737  static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19738  {
19739  	const struct btf_type *t, *func_proto;
19740  	const struct bpf_struct_ops *st_ops;
19741  	const struct btf_member *member;
19742  	struct bpf_prog *prog = env->prog;
19743  	u32 btf_id, member_idx;
19744  	const char *mname;
19745  
19746  	if (!prog->gpl_compatible) {
19747  		verbose(env, "struct ops programs must have a GPL compatible license\n");
19748  		return -EINVAL;
19749  	}
19750  
19751  	btf_id = prog->aux->attach_btf_id;
19752  	st_ops = bpf_struct_ops_find(btf_id);
19753  	if (!st_ops) {
19754  		verbose(env, "attach_btf_id %u is not a supported struct\n",
19755  			btf_id);
19756  		return -ENOTSUPP;
19757  	}
19758  
19759  	t = st_ops->type;
19760  	member_idx = prog->expected_attach_type;
19761  	if (member_idx >= btf_type_vlen(t)) {
19762  		verbose(env, "attach to invalid member idx %u of struct %s\n",
19763  			member_idx, st_ops->name);
19764  		return -EINVAL;
19765  	}
19766  
19767  	member = &btf_type_member(t)[member_idx];
19768  	mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19769  	func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19770  					       NULL);
19771  	if (!func_proto) {
19772  		verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19773  			mname, member_idx, st_ops->name);
19774  		return -EINVAL;
19775  	}
19776  
19777  	if (st_ops->check_member) {
19778  		int err = st_ops->check_member(t, member, prog);
19779  
19780  		if (err) {
19781  			verbose(env, "attach to unsupported member %s of struct %s\n",
19782  				mname, st_ops->name);
19783  			return err;
19784  		}
19785  	}
19786  
19787  	prog->aux->attach_func_proto = func_proto;
19788  	prog->aux->attach_func_name = mname;
19789  	env->ops = st_ops->verifier_ops;
19790  
19791  	return 0;
19792  }
19793  #define SECURITY_PREFIX "security_"
19794  
check_attach_modify_return(unsigned long addr,const char * func_name)19795  static int check_attach_modify_return(unsigned long addr, const char *func_name)
19796  {
19797  	if (within_error_injection_list(addr) ||
19798  	    !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19799  		return 0;
19800  
19801  	return -EINVAL;
19802  }
19803  
19804  /* list of non-sleepable functions that are otherwise on
19805   * ALLOW_ERROR_INJECTION list
19806   */
19807  BTF_SET_START(btf_non_sleepable_error_inject)
19808  /* Three functions below can be called from sleepable and non-sleepable context.
19809   * Assume non-sleepable from bpf safety point of view.
19810   */
BTF_ID(func,__filemap_add_folio)19811  BTF_ID(func, __filemap_add_folio)
19812  BTF_ID(func, should_fail_alloc_page)
19813  BTF_ID(func, should_failslab)
19814  BTF_SET_END(btf_non_sleepable_error_inject)
19815  
19816  static int check_non_sleepable_error_inject(u32 btf_id)
19817  {
19818  	return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19819  }
19820  
bpf_check_attach_target(struct bpf_verifier_log * log,const struct bpf_prog * prog,const struct bpf_prog * tgt_prog,u32 btf_id,struct bpf_attach_target_info * tgt_info)19821  int bpf_check_attach_target(struct bpf_verifier_log *log,
19822  			    const struct bpf_prog *prog,
19823  			    const struct bpf_prog *tgt_prog,
19824  			    u32 btf_id,
19825  			    struct bpf_attach_target_info *tgt_info)
19826  {
19827  	bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19828  	const char prefix[] = "btf_trace_";
19829  	int ret = 0, subprog = -1, i;
19830  	const struct btf_type *t;
19831  	bool conservative = true;
19832  	const char *tname;
19833  	struct btf *btf;
19834  	long addr = 0;
19835  	struct module *mod = NULL;
19836  
19837  	if (!btf_id) {
19838  		bpf_log(log, "Tracing programs must provide btf_id\n");
19839  		return -EINVAL;
19840  	}
19841  	btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19842  	if (!btf) {
19843  		bpf_log(log,
19844  			"FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19845  		return -EINVAL;
19846  	}
19847  	t = btf_type_by_id(btf, btf_id);
19848  	if (!t) {
19849  		bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19850  		return -EINVAL;
19851  	}
19852  	tname = btf_name_by_offset(btf, t->name_off);
19853  	if (!tname) {
19854  		bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19855  		return -EINVAL;
19856  	}
19857  	if (tgt_prog) {
19858  		struct bpf_prog_aux *aux = tgt_prog->aux;
19859  
19860  		if (bpf_prog_is_dev_bound(prog->aux) &&
19861  		    !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19862  			bpf_log(log, "Target program bound device mismatch");
19863  			return -EINVAL;
19864  		}
19865  
19866  		for (i = 0; i < aux->func_info_cnt; i++)
19867  			if (aux->func_info[i].type_id == btf_id) {
19868  				subprog = i;
19869  				break;
19870  			}
19871  		if (subprog == -1) {
19872  			bpf_log(log, "Subprog %s doesn't exist\n", tname);
19873  			return -EINVAL;
19874  		}
19875  		conservative = aux->func_info_aux[subprog].unreliable;
19876  		if (prog_extension) {
19877  			if (conservative) {
19878  				bpf_log(log,
19879  					"Cannot replace static functions\n");
19880  				return -EINVAL;
19881  			}
19882  			if (!prog->jit_requested) {
19883  				bpf_log(log,
19884  					"Extension programs should be JITed\n");
19885  				return -EINVAL;
19886  			}
19887  		}
19888  		if (!tgt_prog->jited) {
19889  			bpf_log(log, "Can attach to only JITed progs\n");
19890  			return -EINVAL;
19891  		}
19892  		if (tgt_prog->type == prog->type) {
19893  			/* Cannot fentry/fexit another fentry/fexit program.
19894  			 * Cannot attach program extension to another extension.
19895  			 * It's ok to attach fentry/fexit to extension program.
19896  			 */
19897  			bpf_log(log, "Cannot recursively attach\n");
19898  			return -EINVAL;
19899  		}
19900  		if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19901  		    prog_extension &&
19902  		    (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19903  		     tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19904  			/* Program extensions can extend all program types
19905  			 * except fentry/fexit. The reason is the following.
19906  			 * The fentry/fexit programs are used for performance
19907  			 * analysis, stats and can be attached to any program
19908  			 * type except themselves. When extension program is
19909  			 * replacing XDP function it is necessary to allow
19910  			 * performance analysis of all functions. Both original
19911  			 * XDP program and its program extension. Hence
19912  			 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19913  			 * allowed. If extending of fentry/fexit was allowed it
19914  			 * would be possible to create long call chain
19915  			 * fentry->extension->fentry->extension beyond
19916  			 * reasonable stack size. Hence extending fentry is not
19917  			 * allowed.
19918  			 */
19919  			bpf_log(log, "Cannot extend fentry/fexit\n");
19920  			return -EINVAL;
19921  		}
19922  	} else {
19923  		if (prog_extension) {
19924  			bpf_log(log, "Cannot replace kernel functions\n");
19925  			return -EINVAL;
19926  		}
19927  	}
19928  
19929  	switch (prog->expected_attach_type) {
19930  	case BPF_TRACE_RAW_TP:
19931  		if (tgt_prog) {
19932  			bpf_log(log,
19933  				"Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19934  			return -EINVAL;
19935  		}
19936  		if (!btf_type_is_typedef(t)) {
19937  			bpf_log(log, "attach_btf_id %u is not a typedef\n",
19938  				btf_id);
19939  			return -EINVAL;
19940  		}
19941  		if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19942  			bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19943  				btf_id, tname);
19944  			return -EINVAL;
19945  		}
19946  		tname += sizeof(prefix) - 1;
19947  		t = btf_type_by_id(btf, t->type);
19948  		if (!btf_type_is_ptr(t))
19949  			/* should never happen in valid vmlinux build */
19950  			return -EINVAL;
19951  		t = btf_type_by_id(btf, t->type);
19952  		if (!btf_type_is_func_proto(t))
19953  			/* should never happen in valid vmlinux build */
19954  			return -EINVAL;
19955  
19956  		break;
19957  	case BPF_TRACE_ITER:
19958  		if (!btf_type_is_func(t)) {
19959  			bpf_log(log, "attach_btf_id %u is not a function\n",
19960  				btf_id);
19961  			return -EINVAL;
19962  		}
19963  		t = btf_type_by_id(btf, t->type);
19964  		if (!btf_type_is_func_proto(t))
19965  			return -EINVAL;
19966  		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19967  		if (ret)
19968  			return ret;
19969  		break;
19970  	default:
19971  		if (!prog_extension)
19972  			return -EINVAL;
19973  		fallthrough;
19974  	case BPF_MODIFY_RETURN:
19975  	case BPF_LSM_MAC:
19976  	case BPF_LSM_CGROUP:
19977  	case BPF_TRACE_FENTRY:
19978  	case BPF_TRACE_FEXIT:
19979  		if (!btf_type_is_func(t)) {
19980  			bpf_log(log, "attach_btf_id %u is not a function\n",
19981  				btf_id);
19982  			return -EINVAL;
19983  		}
19984  		if (prog_extension &&
19985  		    btf_check_type_match(log, prog, btf, t))
19986  			return -EINVAL;
19987  		t = btf_type_by_id(btf, t->type);
19988  		if (!btf_type_is_func_proto(t))
19989  			return -EINVAL;
19990  
19991  		if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19992  		    (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19993  		     prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19994  			return -EINVAL;
19995  
19996  		if (tgt_prog && conservative)
19997  			t = NULL;
19998  
19999  		ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20000  		if (ret < 0)
20001  			return ret;
20002  
20003  		if (tgt_prog) {
20004  			if (subprog == 0)
20005  				addr = (long) tgt_prog->bpf_func;
20006  			else
20007  				addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
20008  		} else {
20009  			if (btf_is_module(btf)) {
20010  				mod = btf_try_get_module(btf);
20011  				if (mod)
20012  					addr = find_kallsyms_symbol_value(mod, tname);
20013  				else
20014  					addr = 0;
20015  			} else {
20016  				addr = kallsyms_lookup_name(tname);
20017  			}
20018  			if (!addr) {
20019  				module_put(mod);
20020  				bpf_log(log,
20021  					"The address of function %s cannot be found\n",
20022  					tname);
20023  				return -ENOENT;
20024  			}
20025  		}
20026  
20027  		if (prog->aux->sleepable) {
20028  			ret = -EINVAL;
20029  			switch (prog->type) {
20030  			case BPF_PROG_TYPE_TRACING:
20031  
20032  				/* fentry/fexit/fmod_ret progs can be sleepable if they are
20033  				 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20034  				 */
20035  				if (!check_non_sleepable_error_inject(btf_id) &&
20036  				    within_error_injection_list(addr))
20037  					ret = 0;
20038  				/* fentry/fexit/fmod_ret progs can also be sleepable if they are
20039  				 * in the fmodret id set with the KF_SLEEPABLE flag.
20040  				 */
20041  				else {
20042  					u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20043  										prog);
20044  
20045  					if (flags && (*flags & KF_SLEEPABLE))
20046  						ret = 0;
20047  				}
20048  				break;
20049  			case BPF_PROG_TYPE_LSM:
20050  				/* LSM progs check that they are attached to bpf_lsm_*() funcs.
20051  				 * Only some of them are sleepable.
20052  				 */
20053  				if (bpf_lsm_is_sleepable_hook(btf_id))
20054  					ret = 0;
20055  				break;
20056  			default:
20057  				break;
20058  			}
20059  			if (ret) {
20060  				module_put(mod);
20061  				bpf_log(log, "%s is not sleepable\n", tname);
20062  				return ret;
20063  			}
20064  		} else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20065  			if (tgt_prog) {
20066  				module_put(mod);
20067  				bpf_log(log, "can't modify return codes of BPF programs\n");
20068  				return -EINVAL;
20069  			}
20070  			ret = -EINVAL;
20071  			if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20072  			    !check_attach_modify_return(addr, tname))
20073  				ret = 0;
20074  			if (ret) {
20075  				module_put(mod);
20076  				bpf_log(log, "%s() is not modifiable\n", tname);
20077  				return ret;
20078  			}
20079  		}
20080  
20081  		break;
20082  	}
20083  	tgt_info->tgt_addr = addr;
20084  	tgt_info->tgt_name = tname;
20085  	tgt_info->tgt_type = t;
20086  	tgt_info->tgt_mod = mod;
20087  	return 0;
20088  }
20089  
BTF_SET_START(btf_id_deny)20090  BTF_SET_START(btf_id_deny)
20091  BTF_ID_UNUSED
20092  #ifdef CONFIG_SMP
20093  BTF_ID(func, migrate_disable)
20094  BTF_ID(func, migrate_enable)
20095  #endif
20096  #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20097  BTF_ID(func, rcu_read_unlock_strict)
20098  #endif
20099  #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20100  BTF_ID(func, preempt_count_add)
20101  BTF_ID(func, preempt_count_sub)
20102  #endif
20103  #ifdef CONFIG_PREEMPT_RCU
20104  BTF_ID(func, __rcu_read_lock)
20105  BTF_ID(func, __rcu_read_unlock)
20106  #endif
20107  BTF_SET_END(btf_id_deny)
20108  
20109  static bool can_be_sleepable(struct bpf_prog *prog)
20110  {
20111  	if (prog->type == BPF_PROG_TYPE_TRACING) {
20112  		switch (prog->expected_attach_type) {
20113  		case BPF_TRACE_FENTRY:
20114  		case BPF_TRACE_FEXIT:
20115  		case BPF_MODIFY_RETURN:
20116  		case BPF_TRACE_ITER:
20117  			return true;
20118  		default:
20119  			return false;
20120  		}
20121  	}
20122  	return prog->type == BPF_PROG_TYPE_LSM ||
20123  	       prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20124  	       prog->type == BPF_PROG_TYPE_STRUCT_OPS;
20125  }
20126  
check_attach_btf_id(struct bpf_verifier_env * env)20127  static int check_attach_btf_id(struct bpf_verifier_env *env)
20128  {
20129  	struct bpf_prog *prog = env->prog;
20130  	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20131  	struct bpf_attach_target_info tgt_info = {};
20132  	u32 btf_id = prog->aux->attach_btf_id;
20133  	struct bpf_trampoline *tr;
20134  	int ret;
20135  	u64 key;
20136  
20137  	if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20138  		if (prog->aux->sleepable)
20139  			/* attach_btf_id checked to be zero already */
20140  			return 0;
20141  		verbose(env, "Syscall programs can only be sleepable\n");
20142  		return -EINVAL;
20143  	}
20144  
20145  	if (prog->aux->sleepable && !can_be_sleepable(prog)) {
20146  		verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
20147  		return -EINVAL;
20148  	}
20149  
20150  	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20151  		return check_struct_ops_btf_id(env);
20152  
20153  	if (prog->type != BPF_PROG_TYPE_TRACING &&
20154  	    prog->type != BPF_PROG_TYPE_LSM &&
20155  	    prog->type != BPF_PROG_TYPE_EXT)
20156  		return 0;
20157  
20158  	ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20159  	if (ret)
20160  		return ret;
20161  
20162  	if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20163  		/* to make freplace equivalent to their targets, they need to
20164  		 * inherit env->ops and expected_attach_type for the rest of the
20165  		 * verification
20166  		 */
20167  		env->ops = bpf_verifier_ops[tgt_prog->type];
20168  		prog->expected_attach_type = tgt_prog->expected_attach_type;
20169  	}
20170  
20171  	/* store info about the attachment target that will be used later */
20172  	prog->aux->attach_func_proto = tgt_info.tgt_type;
20173  	prog->aux->attach_func_name = tgt_info.tgt_name;
20174  	prog->aux->mod = tgt_info.tgt_mod;
20175  
20176  	if (tgt_prog) {
20177  		prog->aux->saved_dst_prog_type = tgt_prog->type;
20178  		prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20179  	}
20180  
20181  	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20182  		prog->aux->attach_btf_trace = true;
20183  		return 0;
20184  	} else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20185  		if (!bpf_iter_prog_supported(prog))
20186  			return -EINVAL;
20187  		return 0;
20188  	}
20189  
20190  	if (prog->type == BPF_PROG_TYPE_LSM) {
20191  		ret = bpf_lsm_verify_prog(&env->log, prog);
20192  		if (ret < 0)
20193  			return ret;
20194  	} else if (prog->type == BPF_PROG_TYPE_TRACING &&
20195  		   btf_id_set_contains(&btf_id_deny, btf_id)) {
20196  		return -EINVAL;
20197  	}
20198  
20199  	key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20200  	tr = bpf_trampoline_get(key, &tgt_info);
20201  	if (!tr)
20202  		return -ENOMEM;
20203  
20204  	if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20205  		tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20206  
20207  	prog->aux->dst_trampoline = tr;
20208  	return 0;
20209  }
20210  
bpf_get_btf_vmlinux(void)20211  struct btf *bpf_get_btf_vmlinux(void)
20212  {
20213  	if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20214  		mutex_lock(&bpf_verifier_lock);
20215  		if (!btf_vmlinux)
20216  			btf_vmlinux = btf_parse_vmlinux();
20217  		mutex_unlock(&bpf_verifier_lock);
20218  	}
20219  	return btf_vmlinux;
20220  }
20221  
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr,bpfptr_t uattr,__u32 uattr_size)20222  int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20223  {
20224  	u64 start_time = ktime_get_ns();
20225  	struct bpf_verifier_env *env;
20226  	int i, len, ret = -EINVAL, err;
20227  	u32 log_true_size;
20228  	bool is_priv;
20229  
20230  	/* no program is valid */
20231  	if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20232  		return -EINVAL;
20233  
20234  	/* 'struct bpf_verifier_env' can be global, but since it's not small,
20235  	 * allocate/free it every time bpf_check() is called
20236  	 */
20237  	env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20238  	if (!env)
20239  		return -ENOMEM;
20240  
20241  	env->bt.env = env;
20242  
20243  	len = (*prog)->len;
20244  	env->insn_aux_data =
20245  		vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20246  	ret = -ENOMEM;
20247  	if (!env->insn_aux_data)
20248  		goto err_free_env;
20249  	for (i = 0; i < len; i++)
20250  		env->insn_aux_data[i].orig_idx = i;
20251  	env->prog = *prog;
20252  	env->ops = bpf_verifier_ops[env->prog->type];
20253  	env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20254  	is_priv = bpf_capable();
20255  
20256  	bpf_get_btf_vmlinux();
20257  
20258  	/* grab the mutex to protect few globals used by verifier */
20259  	if (!is_priv)
20260  		mutex_lock(&bpf_verifier_lock);
20261  
20262  	/* user could have requested verbose verifier output
20263  	 * and supplied buffer to store the verification trace
20264  	 */
20265  	ret = bpf_vlog_init(&env->log, attr->log_level,
20266  			    (char __user *) (unsigned long) attr->log_buf,
20267  			    attr->log_size);
20268  	if (ret)
20269  		goto err_unlock;
20270  
20271  	mark_verifier_state_clean(env);
20272  
20273  	if (IS_ERR(btf_vmlinux)) {
20274  		/* Either gcc or pahole or kernel are broken. */
20275  		verbose(env, "in-kernel BTF is malformed\n");
20276  		ret = PTR_ERR(btf_vmlinux);
20277  		goto skip_full_check;
20278  	}
20279  
20280  	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20281  	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20282  		env->strict_alignment = true;
20283  	if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20284  		env->strict_alignment = false;
20285  
20286  	env->allow_ptr_leaks = bpf_allow_ptr_leaks();
20287  	env->allow_uninit_stack = bpf_allow_uninit_stack();
20288  	env->bypass_spec_v1 = bpf_bypass_spec_v1();
20289  	env->bypass_spec_v4 = bpf_bypass_spec_v4();
20290  	env->bpf_capable = bpf_capable();
20291  
20292  	if (is_priv)
20293  		env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20294  
20295  	env->explored_states = kvcalloc(state_htab_size(env),
20296  				       sizeof(struct bpf_verifier_state_list *),
20297  				       GFP_USER);
20298  	ret = -ENOMEM;
20299  	if (!env->explored_states)
20300  		goto skip_full_check;
20301  
20302  	ret = add_subprog_and_kfunc(env);
20303  	if (ret < 0)
20304  		goto skip_full_check;
20305  
20306  	ret = check_subprogs(env);
20307  	if (ret < 0)
20308  		goto skip_full_check;
20309  
20310  	ret = check_btf_info(env, attr, uattr);
20311  	if (ret < 0)
20312  		goto skip_full_check;
20313  
20314  	ret = check_attach_btf_id(env);
20315  	if (ret)
20316  		goto skip_full_check;
20317  
20318  	ret = resolve_pseudo_ldimm64(env);
20319  	if (ret < 0)
20320  		goto skip_full_check;
20321  
20322  	if (bpf_prog_is_offloaded(env->prog->aux)) {
20323  		ret = bpf_prog_offload_verifier_prep(env->prog);
20324  		if (ret)
20325  			goto skip_full_check;
20326  	}
20327  
20328  	ret = check_cfg(env);
20329  	if (ret < 0)
20330  		goto skip_full_check;
20331  
20332  	ret = do_check_subprogs(env);
20333  	ret = ret ?: do_check_main(env);
20334  
20335  	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
20336  		ret = bpf_prog_offload_finalize(env);
20337  
20338  skip_full_check:
20339  	kvfree(env->explored_states);
20340  
20341  	if (ret == 0)
20342  		ret = check_max_stack_depth(env);
20343  
20344  	/* instruction rewrites happen after this point */
20345  	if (ret == 0)
20346  		ret = optimize_bpf_loop(env);
20347  
20348  	if (is_priv) {
20349  		if (ret == 0)
20350  			opt_hard_wire_dead_code_branches(env);
20351  		if (ret == 0)
20352  			ret = opt_remove_dead_code(env);
20353  		if (ret == 0)
20354  			ret = opt_remove_nops(env);
20355  	} else {
20356  		if (ret == 0)
20357  			sanitize_dead_code(env);
20358  	}
20359  
20360  	if (ret == 0)
20361  		/* program is valid, convert *(u32*)(ctx + off) accesses */
20362  		ret = convert_ctx_accesses(env);
20363  
20364  	if (ret == 0)
20365  		ret = do_misc_fixups(env);
20366  
20367  	/* do 32-bit optimization after insn patching has done so those patched
20368  	 * insns could be handled correctly.
20369  	 */
20370  	if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
20371  		ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
20372  		env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
20373  								     : false;
20374  	}
20375  
20376  	if (ret == 0)
20377  		ret = fixup_call_args(env);
20378  
20379  	env->verification_time = ktime_get_ns() - start_time;
20380  	print_verification_stats(env);
20381  	env->prog->aux->verified_insns = env->insn_processed;
20382  
20383  	/* preserve original error even if log finalization is successful */
20384  	err = bpf_vlog_finalize(&env->log, &log_true_size);
20385  	if (err)
20386  		ret = err;
20387  
20388  	if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
20389  	    copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
20390  				  &log_true_size, sizeof(log_true_size))) {
20391  		ret = -EFAULT;
20392  		goto err_release_maps;
20393  	}
20394  
20395  	if (ret)
20396  		goto err_release_maps;
20397  
20398  	if (env->used_map_cnt) {
20399  		/* if program passed verifier, update used_maps in bpf_prog_info */
20400  		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
20401  							  sizeof(env->used_maps[0]),
20402  							  GFP_KERNEL);
20403  
20404  		if (!env->prog->aux->used_maps) {
20405  			ret = -ENOMEM;
20406  			goto err_release_maps;
20407  		}
20408  
20409  		memcpy(env->prog->aux->used_maps, env->used_maps,
20410  		       sizeof(env->used_maps[0]) * env->used_map_cnt);
20411  		env->prog->aux->used_map_cnt = env->used_map_cnt;
20412  	}
20413  	if (env->used_btf_cnt) {
20414  		/* if program passed verifier, update used_btfs in bpf_prog_aux */
20415  		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
20416  							  sizeof(env->used_btfs[0]),
20417  							  GFP_KERNEL);
20418  		if (!env->prog->aux->used_btfs) {
20419  			ret = -ENOMEM;
20420  			goto err_release_maps;
20421  		}
20422  
20423  		memcpy(env->prog->aux->used_btfs, env->used_btfs,
20424  		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20425  		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20426  	}
20427  	if (env->used_map_cnt || env->used_btf_cnt) {
20428  		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
20429  		 * bpf_ld_imm64 instructions
20430  		 */
20431  		convert_pseudo_ld_imm64(env);
20432  	}
20433  
20434  	adjust_btf_func(env);
20435  
20436  err_release_maps:
20437  	if (!env->prog->aux->used_maps)
20438  		/* if we didn't copy map pointers into bpf_prog_info, release
20439  		 * them now. Otherwise free_used_maps() will release them.
20440  		 */
20441  		release_maps(env);
20442  	if (!env->prog->aux->used_btfs)
20443  		release_btfs(env);
20444  
20445  	/* extension progs temporarily inherit the attach_type of their targets
20446  	   for verification purposes, so set it back to zero before returning
20447  	 */
20448  	if (env->prog->type == BPF_PROG_TYPE_EXT)
20449  		env->prog->expected_attach_type = 0;
20450  
20451  	*prog = env->prog;
20452  err_unlock:
20453  	if (!is_priv)
20454  		mutex_unlock(&bpf_verifier_lock);
20455  	vfree(env->insn_aux_data);
20456  err_free_env:
20457  	kvfree(env);
20458  	return ret;
20459  }
20460