bpf: Verifier, do explicit ALU32 bounds tracking
[linux-2.6-microblaze.git] / kernel / bpf / verifier.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/kernel.h>
8 #include <linux/types.h>
9 #include <linux/slab.h>
10 #include <linux/bpf.h>
11 #include <linux/btf.h>
12 #include <linux/bpf_verifier.h>
13 #include <linux/filter.h>
14 #include <net/netlink.h>
15 #include <linux/file.h>
16 #include <linux/vmalloc.h>
17 #include <linux/stringify.h>
18 #include <linux/bsearch.h>
19 #include <linux/sort.h>
20 #include <linux/perf_event.h>
21 #include <linux/ctype.h>
22 #include <linux/error-injection.h>
23 #include <linux/bpf_lsm.h>
24
25 #include "disasm.h"
26
27 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
28 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
29         [_id] = & _name ## _verifier_ops,
30 #define BPF_MAP_TYPE(_id, _ops)
31 #include <linux/bpf_types.h>
32 #undef BPF_PROG_TYPE
33 #undef BPF_MAP_TYPE
34 };
35
36 /* bpf_check() is a static code analyzer that walks eBPF program
37  * instruction by instruction and updates register/stack state.
38  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
39  *
40  * The first pass is depth-first-search to check that the program is a DAG.
41  * It rejects the following programs:
42  * - larger than BPF_MAXINSNS insns
43  * - if loop is present (detected via back-edge)
44  * - unreachable insns exist (shouldn't be a forest. program = one function)
45  * - out of bounds or malformed jumps
46  * The second pass is all possible path descent from the 1st insn.
47  * Since it's analyzing all pathes through the program, the length of the
48  * analysis is limited to 64k insn, which may be hit even if total number of
49  * insn is less then 4K, but there are too many branches that change stack/regs.
50  * Number of 'branches to be analyzed' is limited to 1k
51  *
52  * On entry to each instruction, each register has a type, and the instruction
53  * changes the types of the registers depending on instruction semantics.
54  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
55  * copied to R1.
56  *
57  * All registers are 64-bit.
58  * R0 - return register
59  * R1-R5 argument passing registers
60  * R6-R9 callee saved registers
61  * R10 - frame pointer read-only
62  *
63  * At the start of BPF program the register R1 contains a pointer to bpf_context
64  * and has type PTR_TO_CTX.
65  *
66  * Verifier tracks arithmetic operations on pointers in case:
67  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
68  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
69  * 1st insn copies R10 (which has FRAME_PTR) type into R1
70  * and 2nd arithmetic instruction is pattern matched to recognize
71  * that it wants to construct a pointer to some element within stack.
72  * So after 2nd insn, the register R1 has type PTR_TO_STACK
73  * (and -20 constant is saved for further stack bounds checking).
74  * Meaning that this reg is a pointer to stack plus known immediate constant.
75  *
76  * Most of the time the registers have SCALAR_VALUE type, which
77  * means the register has some value, but it's not a valid pointer.
78  * (like pointer plus pointer becomes SCALAR_VALUE type)
79  *
80  * When verifier sees load or store instructions the type of base register
81  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
82  * four pointer types recognized by check_mem_access() function.
83  *
84  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
85  * and the range of [ptr, ptr + map's value_size) is accessible.
86  *
87  * registers used to pass values to function calls are checked against
88  * function argument constraints.
89  *
90  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
91  * It means that the register type passed to this function must be
92  * PTR_TO_STACK and it will be used inside the function as
93  * 'pointer to map element key'
94  *
95  * For example the argument constraints for bpf_map_lookup_elem():
96  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
97  *   .arg1_type = ARG_CONST_MAP_PTR,
98  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
99  *
100  * ret_type says that this function returns 'pointer to map elem value or null'
101  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
102  * 2nd argument should be a pointer to stack, which will be used inside
103  * the helper function as a pointer to map element key.
104  *
105  * On the kernel side the helper function looks like:
106  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
107  * {
108  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
109  *    void *key = (void *) (unsigned long) r2;
110  *    void *value;
111  *
112  *    here kernel can access 'key' and 'map' pointers safely, knowing that
113  *    [key, key + map->key_size) bytes are valid and were initialized on
114  *    the stack of eBPF program.
115  * }
116  *
117  * Corresponding eBPF program may look like:
118  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
119  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
120  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
121  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
122  * here verifier looks at prototype of map_lookup_elem() and sees:
123  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
124  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
125  *
126  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
127  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
128  * and were initialized prior to this call.
129  * If it's ok, then verifier allows this BPF_CALL insn and looks at
130  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
131  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
132  * returns ether pointer to map value or NULL.
133  *
134  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
135  * insn, the register holding that pointer in the true branch changes state to
136  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
137  * branch. See check_cond_jmp_op().
138  *
139  * After the call R0 is set to return type of the function and registers R1-R5
140  * are set to NOT_INIT to indicate that they are no longer readable.
141  *
142  * The following reference types represent a potential reference to a kernel
143  * resource which, after first being allocated, must be checked and freed by
144  * the BPF program:
145  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
146  *
147  * When the verifier sees a helper call return a reference type, it allocates a
148  * pointer id for the reference and stores it in the current function state.
149  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
150  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
151  * passes through a NULL-check conditional. For the branch wherein the state is
152  * changed to CONST_IMM, the verifier releases the reference.
153  *
154  * For each helper function that allocates a reference, such as
155  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
156  * bpf_sk_release(). When a reference type passes into the release function,
157  * the verifier also releases the reference. If any unchecked or unreleased
158  * reference remains at the end of the program, the verifier rejects it.
159  */
160
161 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
162 struct bpf_verifier_stack_elem {
163         /* verifer state is 'st'
164          * before processing instruction 'insn_idx'
165          * and after processing instruction 'prev_insn_idx'
166          */
167         struct bpf_verifier_state st;
168         int insn_idx;
169         int prev_insn_idx;
170         struct bpf_verifier_stack_elem *next;
171 };
172
173 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ    8192
174 #define BPF_COMPLEXITY_LIMIT_STATES     64
175
176 #define BPF_MAP_KEY_POISON      (1ULL << 63)
177 #define BPF_MAP_KEY_SEEN        (1ULL << 62)
178
179 #define BPF_MAP_PTR_UNPRIV      1UL
180 #define BPF_MAP_PTR_POISON      ((void *)((0xeB9FUL << 1) +     \
181                                           POISON_POINTER_DELTA))
182 #define BPF_MAP_PTR(X)          ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
183
184 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
185 {
186         return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
187 }
188
189 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
190 {
191         return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
192 }
193
194 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
195                               const struct bpf_map *map, bool unpriv)
196 {
197         BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
198         unpriv |= bpf_map_ptr_unpriv(aux);
199         aux->map_ptr_state = (unsigned long)map |
200                              (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
201 }
202
203 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
204 {
205         return aux->map_key_state & BPF_MAP_KEY_POISON;
206 }
207
208 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
209 {
210         return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
211 }
212
213 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
214 {
215         return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
216 }
217
218 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
219 {
220         bool poisoned = bpf_map_key_poisoned(aux);
221
222         aux->map_key_state = state | BPF_MAP_KEY_SEEN |
223                              (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
224 }
225
226 struct bpf_call_arg_meta {
227         struct bpf_map *map_ptr;
228         bool raw_mode;
229         bool pkt_access;
230         int regno;
231         int access_size;
232         u64 msize_max_value;
233         int ref_obj_id;
234         int func_id;
235         u32 btf_id;
236 };
237
238 struct btf *btf_vmlinux;
239
240 static DEFINE_MUTEX(bpf_verifier_lock);
241
242 static const struct bpf_line_info *
243 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
244 {
245         const struct bpf_line_info *linfo;
246         const struct bpf_prog *prog;
247         u32 i, nr_linfo;
248
249         prog = env->prog;
250         nr_linfo = prog->aux->nr_linfo;
251
252         if (!nr_linfo || insn_off >= prog->len)
253                 return NULL;
254
255         linfo = prog->aux->linfo;
256         for (i = 1; i < nr_linfo; i++)
257                 if (insn_off < linfo[i].insn_off)
258                         break;
259
260         return &linfo[i - 1];
261 }
262
263 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
264                        va_list args)
265 {
266         unsigned int n;
267
268         n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
269
270         WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
271                   "verifier log line truncated - local buffer too short\n");
272
273         n = min(log->len_total - log->len_used - 1, n);
274         log->kbuf[n] = '\0';
275
276         if (log->level == BPF_LOG_KERNEL) {
277                 pr_err("BPF:%s\n", log->kbuf);
278                 return;
279         }
280         if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
281                 log->len_used += n;
282         else
283                 log->ubuf = NULL;
284 }
285
286 /* log_level controls verbosity level of eBPF verifier.
287  * bpf_verifier_log_write() is used to dump the verification trace to the log,
288  * so the user can figure out what's wrong with the program
289  */
290 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
291                                            const char *fmt, ...)
292 {
293         va_list args;
294
295         if (!bpf_verifier_log_needed(&env->log))
296                 return;
297
298         va_start(args, fmt);
299         bpf_verifier_vlog(&env->log, fmt, args);
300         va_end(args);
301 }
302 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
303
304 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
305 {
306         struct bpf_verifier_env *env = private_data;
307         va_list args;
308
309         if (!bpf_verifier_log_needed(&env->log))
310                 return;
311
312         va_start(args, fmt);
313         bpf_verifier_vlog(&env->log, fmt, args);
314         va_end(args);
315 }
316
317 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
318                             const char *fmt, ...)
319 {
320         va_list args;
321
322         if (!bpf_verifier_log_needed(log))
323                 return;
324
325         va_start(args, fmt);
326         bpf_verifier_vlog(log, fmt, args);
327         va_end(args);
328 }
329
330 static const char *ltrim(const char *s)
331 {
332         while (isspace(*s))
333                 s++;
334
335         return s;
336 }
337
338 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
339                                          u32 insn_off,
340                                          const char *prefix_fmt, ...)
341 {
342         const struct bpf_line_info *linfo;
343
344         if (!bpf_verifier_log_needed(&env->log))
345                 return;
346
347         linfo = find_linfo(env, insn_off);
348         if (!linfo || linfo == env->prev_linfo)
349                 return;
350
351         if (prefix_fmt) {
352                 va_list args;
353
354                 va_start(args, prefix_fmt);
355                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
356                 va_end(args);
357         }
358
359         verbose(env, "%s\n",
360                 ltrim(btf_name_by_offset(env->prog->aux->btf,
361                                          linfo->line_off)));
362
363         env->prev_linfo = linfo;
364 }
365
366 static bool type_is_pkt_pointer(enum bpf_reg_type type)
367 {
368         return type == PTR_TO_PACKET ||
369                type == PTR_TO_PACKET_META;
370 }
371
372 static bool type_is_sk_pointer(enum bpf_reg_type type)
373 {
374         return type == PTR_TO_SOCKET ||
375                 type == PTR_TO_SOCK_COMMON ||
376                 type == PTR_TO_TCP_SOCK ||
377                 type == PTR_TO_XDP_SOCK;
378 }
379
380 static bool reg_type_may_be_null(enum bpf_reg_type type)
381 {
382         return type == PTR_TO_MAP_VALUE_OR_NULL ||
383                type == PTR_TO_SOCKET_OR_NULL ||
384                type == PTR_TO_SOCK_COMMON_OR_NULL ||
385                type == PTR_TO_TCP_SOCK_OR_NULL;
386 }
387
388 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
389 {
390         return reg->type == PTR_TO_MAP_VALUE &&
391                 map_value_has_spin_lock(reg->map_ptr);
392 }
393
394 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
395 {
396         return type == PTR_TO_SOCKET ||
397                 type == PTR_TO_SOCKET_OR_NULL ||
398                 type == PTR_TO_TCP_SOCK ||
399                 type == PTR_TO_TCP_SOCK_OR_NULL;
400 }
401
402 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
403 {
404         return type == ARG_PTR_TO_SOCK_COMMON;
405 }
406
407 /* Determine whether the function releases some resources allocated by another
408  * function call. The first reference type argument will be assumed to be
409  * released by release_reference().
410  */
411 static bool is_release_function(enum bpf_func_id func_id)
412 {
413         return func_id == BPF_FUNC_sk_release;
414 }
415
416 static bool is_acquire_function(enum bpf_func_id func_id)
417 {
418         return func_id == BPF_FUNC_sk_lookup_tcp ||
419                 func_id == BPF_FUNC_sk_lookup_udp ||
420                 func_id == BPF_FUNC_skc_lookup_tcp;
421 }
422
423 static bool is_ptr_cast_function(enum bpf_func_id func_id)
424 {
425         return func_id == BPF_FUNC_tcp_sock ||
426                 func_id == BPF_FUNC_sk_fullsock;
427 }
428
429 /* string representation of 'enum bpf_reg_type' */
430 static const char * const reg_type_str[] = {
431         [NOT_INIT]              = "?",
432         [SCALAR_VALUE]          = "inv",
433         [PTR_TO_CTX]            = "ctx",
434         [CONST_PTR_TO_MAP]      = "map_ptr",
435         [PTR_TO_MAP_VALUE]      = "map_value",
436         [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
437         [PTR_TO_STACK]          = "fp",
438         [PTR_TO_PACKET]         = "pkt",
439         [PTR_TO_PACKET_META]    = "pkt_meta",
440         [PTR_TO_PACKET_END]     = "pkt_end",
441         [PTR_TO_FLOW_KEYS]      = "flow_keys",
442         [PTR_TO_SOCKET]         = "sock",
443         [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
444         [PTR_TO_SOCK_COMMON]    = "sock_common",
445         [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
446         [PTR_TO_TCP_SOCK]       = "tcp_sock",
447         [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
448         [PTR_TO_TP_BUFFER]      = "tp_buffer",
449         [PTR_TO_XDP_SOCK]       = "xdp_sock",
450         [PTR_TO_BTF_ID]         = "ptr_",
451 };
452
453 static char slot_type_char[] = {
454         [STACK_INVALID] = '?',
455         [STACK_SPILL]   = 'r',
456         [STACK_MISC]    = 'm',
457         [STACK_ZERO]    = '0',
458 };
459
460 static void print_liveness(struct bpf_verifier_env *env,
461                            enum bpf_reg_liveness live)
462 {
463         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
464             verbose(env, "_");
465         if (live & REG_LIVE_READ)
466                 verbose(env, "r");
467         if (live & REG_LIVE_WRITTEN)
468                 verbose(env, "w");
469         if (live & REG_LIVE_DONE)
470                 verbose(env, "D");
471 }
472
473 static struct bpf_func_state *func(struct bpf_verifier_env *env,
474                                    const struct bpf_reg_state *reg)
475 {
476         struct bpf_verifier_state *cur = env->cur_state;
477
478         return cur->frame[reg->frameno];
479 }
480
481 const char *kernel_type_name(u32 id)
482 {
483         return btf_name_by_offset(btf_vmlinux,
484                                   btf_type_by_id(btf_vmlinux, id)->name_off);
485 }
486
487 static void print_verifier_state(struct bpf_verifier_env *env,
488                                  const struct bpf_func_state *state)
489 {
490         const struct bpf_reg_state *reg;
491         enum bpf_reg_type t;
492         int i;
493
494         if (state->frameno)
495                 verbose(env, " frame%d:", state->frameno);
496         for (i = 0; i < MAX_BPF_REG; i++) {
497                 reg = &state->regs[i];
498                 t = reg->type;
499                 if (t == NOT_INIT)
500                         continue;
501                 verbose(env, " R%d", i);
502                 print_liveness(env, reg->live);
503                 verbose(env, "=%s", reg_type_str[t]);
504                 if (t == SCALAR_VALUE && reg->precise)
505                         verbose(env, "P");
506                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
507                     tnum_is_const(reg->var_off)) {
508                         /* reg->off should be 0 for SCALAR_VALUE */
509                         verbose(env, "%lld", reg->var_off.value + reg->off);
510                 } else {
511                         if (t == PTR_TO_BTF_ID)
512                                 verbose(env, "%s", kernel_type_name(reg->btf_id));
513                         verbose(env, "(id=%d", reg->id);
514                         if (reg_type_may_be_refcounted_or_null(t))
515                                 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
516                         if (t != SCALAR_VALUE)
517                                 verbose(env, ",off=%d", reg->off);
518                         if (type_is_pkt_pointer(t))
519                                 verbose(env, ",r=%d", reg->range);
520                         else if (t == CONST_PTR_TO_MAP ||
521                                  t == PTR_TO_MAP_VALUE ||
522                                  t == PTR_TO_MAP_VALUE_OR_NULL)
523                                 verbose(env, ",ks=%d,vs=%d",
524                                         reg->map_ptr->key_size,
525                                         reg->map_ptr->value_size);
526                         if (tnum_is_const(reg->var_off)) {
527                                 /* Typically an immediate SCALAR_VALUE, but
528                                  * could be a pointer whose offset is too big
529                                  * for reg->off
530                                  */
531                                 verbose(env, ",imm=%llx", reg->var_off.value);
532                         } else {
533                                 if (reg->smin_value != reg->umin_value &&
534                                     reg->smin_value != S64_MIN)
535                                         verbose(env, ",smin_value=%lld",
536                                                 (long long)reg->smin_value);
537                                 if (reg->smax_value != reg->umax_value &&
538                                     reg->smax_value != S64_MAX)
539                                         verbose(env, ",smax_value=%lld",
540                                                 (long long)reg->smax_value);
541                                 if (reg->umin_value != 0)
542                                         verbose(env, ",umin_value=%llu",
543                                                 (unsigned long long)reg->umin_value);
544                                 if (reg->umax_value != U64_MAX)
545                                         verbose(env, ",umax_value=%llu",
546                                                 (unsigned long long)reg->umax_value);
547                                 if (!tnum_is_unknown(reg->var_off)) {
548                                         char tn_buf[48];
549
550                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
551                                         verbose(env, ",var_off=%s", tn_buf);
552                                 }
553                                 if (reg->s32_min_value != reg->smin_value &&
554                                     reg->s32_min_value != S32_MIN)
555                                         verbose(env, ",s32_min_value=%d",
556                                                 (int)(reg->s32_min_value));
557                                 if (reg->s32_max_value != reg->smax_value &&
558                                     reg->s32_max_value != S32_MAX)
559                                         verbose(env, ",s32_max_value=%d",
560                                                 (int)(reg->s32_max_value));
561                                 if (reg->u32_min_value != reg->umin_value &&
562                                     reg->u32_min_value != U32_MIN)
563                                         verbose(env, ",u32_min_value=%d",
564                                                 (int)(reg->u32_min_value));
565                                 if (reg->u32_max_value != reg->umax_value &&
566                                     reg->u32_max_value != U32_MAX)
567                                         verbose(env, ",u32_max_value=%d",
568                                                 (int)(reg->u32_max_value));
569                         }
570                         verbose(env, ")");
571                 }
572         }
573         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
574                 char types_buf[BPF_REG_SIZE + 1];
575                 bool valid = false;
576                 int j;
577
578                 for (j = 0; j < BPF_REG_SIZE; j++) {
579                         if (state->stack[i].slot_type[j] != STACK_INVALID)
580                                 valid = true;
581                         types_buf[j] = slot_type_char[
582                                         state->stack[i].slot_type[j]];
583                 }
584                 types_buf[BPF_REG_SIZE] = 0;
585                 if (!valid)
586                         continue;
587                 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
588                 print_liveness(env, state->stack[i].spilled_ptr.live);
589                 if (state->stack[i].slot_type[0] == STACK_SPILL) {
590                         reg = &state->stack[i].spilled_ptr;
591                         t = reg->type;
592                         verbose(env, "=%s", reg_type_str[t]);
593                         if (t == SCALAR_VALUE && reg->precise)
594                                 verbose(env, "P");
595                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
596                                 verbose(env, "%lld", reg->var_off.value + reg->off);
597                 } else {
598                         verbose(env, "=%s", types_buf);
599                 }
600         }
601         if (state->acquired_refs && state->refs[0].id) {
602                 verbose(env, " refs=%d", state->refs[0].id);
603                 for (i = 1; i < state->acquired_refs; i++)
604                         if (state->refs[i].id)
605                                 verbose(env, ",%d", state->refs[i].id);
606         }
607         verbose(env, "\n");
608 }
609
610 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE)                         \
611 static int copy_##NAME##_state(struct bpf_func_state *dst,              \
612                                const struct bpf_func_state *src)        \
613 {                                                                       \
614         if (!src->FIELD)                                                \
615                 return 0;                                               \
616         if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) {                    \
617                 /* internal bug, make state invalid to reject the program */ \
618                 memset(dst, 0, sizeof(*dst));                           \
619                 return -EFAULT;                                         \
620         }                                                               \
621         memcpy(dst->FIELD, src->FIELD,                                  \
622                sizeof(*src->FIELD) * (src->COUNT / SIZE));              \
623         return 0;                                                       \
624 }
625 /* copy_reference_state() */
626 COPY_STATE_FN(reference, acquired_refs, refs, 1)
627 /* copy_stack_state() */
628 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
629 #undef COPY_STATE_FN
630
631 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE)                      \
632 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
633                                   bool copy_old)                        \
634 {                                                                       \
635         u32 old_size = state->COUNT;                                    \
636         struct bpf_##NAME##_state *new_##FIELD;                         \
637         int slot = size / SIZE;                                         \
638                                                                         \
639         if (size <= old_size || !size) {                                \
640                 if (copy_old)                                           \
641                         return 0;                                       \
642                 state->COUNT = slot * SIZE;                             \
643                 if (!size && old_size) {                                \
644                         kfree(state->FIELD);                            \
645                         state->FIELD = NULL;                            \
646                 }                                                       \
647                 return 0;                                               \
648         }                                                               \
649         new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
650                                     GFP_KERNEL);                        \
651         if (!new_##FIELD)                                               \
652                 return -ENOMEM;                                         \
653         if (copy_old) {                                                 \
654                 if (state->FIELD)                                       \
655                         memcpy(new_##FIELD, state->FIELD,               \
656                                sizeof(*new_##FIELD) * (old_size / SIZE)); \
657                 memset(new_##FIELD + old_size / SIZE, 0,                \
658                        sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
659         }                                                               \
660         state->COUNT = slot * SIZE;                                     \
661         kfree(state->FIELD);                                            \
662         state->FIELD = new_##FIELD;                                     \
663         return 0;                                                       \
664 }
665 /* realloc_reference_state() */
666 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
667 /* realloc_stack_state() */
668 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
669 #undef REALLOC_STATE_FN
670
671 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
672  * make it consume minimal amount of memory. check_stack_write() access from
673  * the program calls into realloc_func_state() to grow the stack size.
674  * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
675  * which realloc_stack_state() copies over. It points to previous
676  * bpf_verifier_state which is never reallocated.
677  */
678 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
679                               int refs_size, bool copy_old)
680 {
681         int err = realloc_reference_state(state, refs_size, copy_old);
682         if (err)
683                 return err;
684         return realloc_stack_state(state, stack_size, copy_old);
685 }
686
687 /* Acquire a pointer id from the env and update the state->refs to include
688  * this new pointer reference.
689  * On success, returns a valid pointer id to associate with the register
690  * On failure, returns a negative errno.
691  */
692 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
693 {
694         struct bpf_func_state *state = cur_func(env);
695         int new_ofs = state->acquired_refs;
696         int id, err;
697
698         err = realloc_reference_state(state, state->acquired_refs + 1, true);
699         if (err)
700                 return err;
701         id = ++env->id_gen;
702         state->refs[new_ofs].id = id;
703         state->refs[new_ofs].insn_idx = insn_idx;
704
705         return id;
706 }
707
708 /* release function corresponding to acquire_reference_state(). Idempotent. */
709 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
710 {
711         int i, last_idx;
712
713         last_idx = state->acquired_refs - 1;
714         for (i = 0; i < state->acquired_refs; i++) {
715                 if (state->refs[i].id == ptr_id) {
716                         if (last_idx && i != last_idx)
717                                 memcpy(&state->refs[i], &state->refs[last_idx],
718                                        sizeof(*state->refs));
719                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
720                         state->acquired_refs--;
721                         return 0;
722                 }
723         }
724         return -EINVAL;
725 }
726
727 static int transfer_reference_state(struct bpf_func_state *dst,
728                                     struct bpf_func_state *src)
729 {
730         int err = realloc_reference_state(dst, src->acquired_refs, false);
731         if (err)
732                 return err;
733         err = copy_reference_state(dst, src);
734         if (err)
735                 return err;
736         return 0;
737 }
738
739 static void free_func_state(struct bpf_func_state *state)
740 {
741         if (!state)
742                 return;
743         kfree(state->refs);
744         kfree(state->stack);
745         kfree(state);
746 }
747
748 static void clear_jmp_history(struct bpf_verifier_state *state)
749 {
750         kfree(state->jmp_history);
751         state->jmp_history = NULL;
752         state->jmp_history_cnt = 0;
753 }
754
755 static void free_verifier_state(struct bpf_verifier_state *state,
756                                 bool free_self)
757 {
758         int i;
759
760         for (i = 0; i <= state->curframe; i++) {
761                 free_func_state(state->frame[i]);
762                 state->frame[i] = NULL;
763         }
764         clear_jmp_history(state);
765         if (free_self)
766                 kfree(state);
767 }
768
769 /* copy verifier state from src to dst growing dst stack space
770  * when necessary to accommodate larger src stack
771  */
772 static int copy_func_state(struct bpf_func_state *dst,
773                            const struct bpf_func_state *src)
774 {
775         int err;
776
777         err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
778                                  false);
779         if (err)
780                 return err;
781         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
782         err = copy_reference_state(dst, src);
783         if (err)
784                 return err;
785         return copy_stack_state(dst, src);
786 }
787
788 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
789                                const struct bpf_verifier_state *src)
790 {
791         struct bpf_func_state *dst;
792         u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
793         int i, err;
794
795         if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
796                 kfree(dst_state->jmp_history);
797                 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
798                 if (!dst_state->jmp_history)
799                         return -ENOMEM;
800         }
801         memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
802         dst_state->jmp_history_cnt = src->jmp_history_cnt;
803
804         /* if dst has more stack frames then src frame, free them */
805         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
806                 free_func_state(dst_state->frame[i]);
807                 dst_state->frame[i] = NULL;
808         }
809         dst_state->speculative = src->speculative;
810         dst_state->curframe = src->curframe;
811         dst_state->active_spin_lock = src->active_spin_lock;
812         dst_state->branches = src->branches;
813         dst_state->parent = src->parent;
814         dst_state->first_insn_idx = src->first_insn_idx;
815         dst_state->last_insn_idx = src->last_insn_idx;
816         for (i = 0; i <= src->curframe; i++) {
817                 dst = dst_state->frame[i];
818                 if (!dst) {
819                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
820                         if (!dst)
821                                 return -ENOMEM;
822                         dst_state->frame[i] = dst;
823                 }
824                 err = copy_func_state(dst, src->frame[i]);
825                 if (err)
826                         return err;
827         }
828         return 0;
829 }
830
831 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
832 {
833         while (st) {
834                 u32 br = --st->branches;
835
836                 /* WARN_ON(br > 1) technically makes sense here,
837                  * but see comment in push_stack(), hence:
838                  */
839                 WARN_ONCE((int)br < 0,
840                           "BUG update_branch_counts:branches_to_explore=%d\n",
841                           br);
842                 if (br)
843                         break;
844                 st = st->parent;
845         }
846 }
847
848 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
849                      int *insn_idx)
850 {
851         struct bpf_verifier_state *cur = env->cur_state;
852         struct bpf_verifier_stack_elem *elem, *head = env->head;
853         int err;
854
855         if (env->head == NULL)
856                 return -ENOENT;
857
858         if (cur) {
859                 err = copy_verifier_state(cur, &head->st);
860                 if (err)
861                         return err;
862         }
863         if (insn_idx)
864                 *insn_idx = head->insn_idx;
865         if (prev_insn_idx)
866                 *prev_insn_idx = head->prev_insn_idx;
867         elem = head->next;
868         free_verifier_state(&head->st, false);
869         kfree(head);
870         env->head = elem;
871         env->stack_size--;
872         return 0;
873 }
874
875 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
876                                              int insn_idx, int prev_insn_idx,
877                                              bool speculative)
878 {
879         struct bpf_verifier_state *cur = env->cur_state;
880         struct bpf_verifier_stack_elem *elem;
881         int err;
882
883         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
884         if (!elem)
885                 goto err;
886
887         elem->insn_idx = insn_idx;
888         elem->prev_insn_idx = prev_insn_idx;
889         elem->next = env->head;
890         env->head = elem;
891         env->stack_size++;
892         err = copy_verifier_state(&elem->st, cur);
893         if (err)
894                 goto err;
895         elem->st.speculative |= speculative;
896         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
897                 verbose(env, "The sequence of %d jumps is too complex.\n",
898                         env->stack_size);
899                 goto err;
900         }
901         if (elem->st.parent) {
902                 ++elem->st.parent->branches;
903                 /* WARN_ON(branches > 2) technically makes sense here,
904                  * but
905                  * 1. speculative states will bump 'branches' for non-branch
906                  * instructions
907                  * 2. is_state_visited() heuristics may decide not to create
908                  * a new state for a sequence of branches and all such current
909                  * and cloned states will be pointing to a single parent state
910                  * which might have large 'branches' count.
911                  */
912         }
913         return &elem->st;
914 err:
915         free_verifier_state(env->cur_state, true);
916         env->cur_state = NULL;
917         /* pop all elements and return */
918         while (!pop_stack(env, NULL, NULL));
919         return NULL;
920 }
921
922 #define CALLER_SAVED_REGS 6
923 static const int caller_saved[CALLER_SAVED_REGS] = {
924         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
925 };
926
927 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
928                                 struct bpf_reg_state *reg);
929
930 /* Mark the unknown part of a register (variable offset or scalar value) as
931  * known to have the value @imm.
932  */
933 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
934 {
935         /* Clear id, off, and union(map_ptr, range) */
936         memset(((u8 *)reg) + sizeof(reg->type), 0,
937                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
938         reg->var_off = tnum_const(imm);
939         reg->smin_value = (s64)imm;
940         reg->smax_value = (s64)imm;
941         reg->umin_value = imm;
942         reg->umax_value = imm;
943
944         reg->s32_min_value = (s32)imm;
945         reg->s32_max_value = (s32)imm;
946         reg->u32_min_value = (u32)imm;
947         reg->u32_max_value = (u32)imm;
948 }
949
950 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
951 {
952         reg->var_off = tnum_const_subreg(reg->var_off, imm);
953         reg->s32_min_value = (s32)imm;
954         reg->s32_max_value = (s32)imm;
955         reg->u32_min_value = (u32)imm;
956         reg->u32_max_value = (u32)imm;
957 }
958
959 /* Mark the 'variable offset' part of a register as zero.  This should be
960  * used only on registers holding a pointer type.
961  */
962 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
963 {
964         __mark_reg_known(reg, 0);
965 }
966
967 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
968 {
969         __mark_reg_known(reg, 0);
970         reg->type = SCALAR_VALUE;
971 }
972
973 static void mark_reg_known_zero(struct bpf_verifier_env *env,
974                                 struct bpf_reg_state *regs, u32 regno)
975 {
976         if (WARN_ON(regno >= MAX_BPF_REG)) {
977                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
978                 /* Something bad happened, let's kill all regs */
979                 for (regno = 0; regno < MAX_BPF_REG; regno++)
980                         __mark_reg_not_init(env, regs + regno);
981                 return;
982         }
983         __mark_reg_known_zero(regs + regno);
984 }
985
986 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
987 {
988         return type_is_pkt_pointer(reg->type);
989 }
990
991 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
992 {
993         return reg_is_pkt_pointer(reg) ||
994                reg->type == PTR_TO_PACKET_END;
995 }
996
997 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
998 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
999                                     enum bpf_reg_type which)
1000 {
1001         /* The register can already have a range from prior markings.
1002          * This is fine as long as it hasn't been advanced from its
1003          * origin.
1004          */
1005         return reg->type == which &&
1006                reg->id == 0 &&
1007                reg->off == 0 &&
1008                tnum_equals_const(reg->var_off, 0);
1009 }
1010
1011 /* Reset the min/max bounds of a register */
1012 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1013 {
1014         reg->smin_value = S64_MIN;
1015         reg->smax_value = S64_MAX;
1016         reg->umin_value = 0;
1017         reg->umax_value = U64_MAX;
1018
1019         reg->s32_min_value = S32_MIN;
1020         reg->s32_max_value = S32_MAX;
1021         reg->u32_min_value = 0;
1022         reg->u32_max_value = U32_MAX;
1023 }
1024
1025 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1026 {
1027         reg->smin_value = S64_MIN;
1028         reg->smax_value = S64_MAX;
1029         reg->umin_value = 0;
1030         reg->umax_value = U64_MAX;
1031 }
1032
1033 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1034 {
1035         reg->s32_min_value = S32_MIN;
1036         reg->s32_max_value = S32_MAX;
1037         reg->u32_min_value = 0;
1038         reg->u32_max_value = U32_MAX;
1039 }
1040
1041 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1042 {
1043         struct tnum var32_off = tnum_subreg(reg->var_off);
1044
1045         /* min signed is max(sign bit) | min(other bits) */
1046         reg->s32_min_value = max_t(s32, reg->s32_min_value,
1047                         var32_off.value | (var32_off.mask & S32_MIN));
1048         /* max signed is min(sign bit) | max(other bits) */
1049         reg->s32_max_value = min_t(s32, reg->s32_max_value,
1050                         var32_off.value | (var32_off.mask & S32_MAX));
1051         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1052         reg->u32_max_value = min(reg->u32_max_value,
1053                                  (u32)(var32_off.value | var32_off.mask));
1054 }
1055
1056 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1057 {
1058         /* min signed is max(sign bit) | min(other bits) */
1059         reg->smin_value = max_t(s64, reg->smin_value,
1060                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1061         /* max signed is min(sign bit) | max(other bits) */
1062         reg->smax_value = min_t(s64, reg->smax_value,
1063                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1064         reg->umin_value = max(reg->umin_value, reg->var_off.value);
1065         reg->umax_value = min(reg->umax_value,
1066                               reg->var_off.value | reg->var_off.mask);
1067 }
1068
1069 static void __update_reg_bounds(struct bpf_reg_state *reg)
1070 {
1071         __update_reg32_bounds(reg);
1072         __update_reg64_bounds(reg);
1073 }
1074
1075 /* Uses signed min/max values to inform unsigned, and vice-versa */
1076 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1077 {
1078         /* Learn sign from signed bounds.
1079          * If we cannot cross the sign boundary, then signed and unsigned bounds
1080          * are the same, so combine.  This works even in the negative case, e.g.
1081          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1082          */
1083         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1084                 reg->s32_min_value = reg->u32_min_value =
1085                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1086                 reg->s32_max_value = reg->u32_max_value =
1087                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1088                 return;
1089         }
1090         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1091          * boundary, so we must be careful.
1092          */
1093         if ((s32)reg->u32_max_value >= 0) {
1094                 /* Positive.  We can't learn anything from the smin, but smax
1095                  * is positive, hence safe.
1096                  */
1097                 reg->s32_min_value = reg->u32_min_value;
1098                 reg->s32_max_value = reg->u32_max_value =
1099                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1100         } else if ((s32)reg->u32_min_value < 0) {
1101                 /* Negative.  We can't learn anything from the smax, but smin
1102                  * is negative, hence safe.
1103                  */
1104                 reg->s32_min_value = reg->u32_min_value =
1105                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1106                 reg->s32_max_value = reg->u32_max_value;
1107         }
1108 }
1109
1110 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1111 {
1112         /* Learn sign from signed bounds.
1113          * If we cannot cross the sign boundary, then signed and unsigned bounds
1114          * are the same, so combine.  This works even in the negative case, e.g.
1115          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1116          */
1117         if (reg->smin_value >= 0 || reg->smax_value < 0) {
1118                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1119                                                           reg->umin_value);
1120                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1121                                                           reg->umax_value);
1122                 return;
1123         }
1124         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1125          * boundary, so we must be careful.
1126          */
1127         if ((s64)reg->umax_value >= 0) {
1128                 /* Positive.  We can't learn anything from the smin, but smax
1129                  * is positive, hence safe.
1130                  */
1131                 reg->smin_value = reg->umin_value;
1132                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1133                                                           reg->umax_value);
1134         } else if ((s64)reg->umin_value < 0) {
1135                 /* Negative.  We can't learn anything from the smax, but smin
1136                  * is negative, hence safe.
1137                  */
1138                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1139                                                           reg->umin_value);
1140                 reg->smax_value = reg->umax_value;
1141         }
1142 }
1143
1144 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1145 {
1146         __reg32_deduce_bounds(reg);
1147         __reg64_deduce_bounds(reg);
1148 }
1149
1150 /* Attempts to improve var_off based on unsigned min/max information */
1151 static void __reg_bound_offset(struct bpf_reg_state *reg)
1152 {
1153         struct tnum var64_off = tnum_intersect(reg->var_off,
1154                                                tnum_range(reg->umin_value,
1155                                                           reg->umax_value));
1156         struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1157                                                 tnum_range(reg->u32_min_value,
1158                                                            reg->u32_max_value));
1159
1160         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1161 }
1162
1163 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1164 {
1165         reg->umin_value = reg->u32_min_value;
1166         reg->umax_value = reg->u32_max_value;
1167         /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1168          * but must be positive otherwise set to worse case bounds
1169          * and refine later from tnum.
1170          */
1171         if (reg->s32_min_value > 0)
1172                 reg->smin_value = reg->s32_min_value;
1173         else
1174                 reg->smin_value = 0;
1175         if (reg->s32_max_value > 0)
1176                 reg->smax_value = reg->s32_max_value;
1177         else
1178                 reg->smax_value = U32_MAX;
1179 }
1180
1181 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1182 {
1183         /* special case when 64-bit register has upper 32-bit register
1184          * zeroed. Typically happens after zext or <<32, >>32 sequence
1185          * allowing us to use 32-bit bounds directly,
1186          */
1187         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1188                 __reg_assign_32_into_64(reg);
1189         } else {
1190                 /* Otherwise the best we can do is push lower 32bit known and
1191                  * unknown bits into register (var_off set from jmp logic)
1192                  * then learn as much as possible from the 64-bit tnum
1193                  * known and unknown bits. The previous smin/smax bounds are
1194                  * invalid here because of jmp32 compare so mark them unknown
1195                  * so they do not impact tnum bounds calculation.
1196                  */
1197                 __mark_reg64_unbounded(reg);
1198                 __update_reg_bounds(reg);
1199         }
1200
1201         /* Intersecting with the old var_off might have improved our bounds
1202          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1203          * then new var_off is (0; 0x7f...fc) which improves our umax.
1204          */
1205         __reg_deduce_bounds(reg);
1206         __reg_bound_offset(reg);
1207         __update_reg_bounds(reg);
1208 }
1209
1210 static bool __reg64_bound_s32(s64 a)
1211 {
1212         if (a > S32_MIN && a < S32_MAX)
1213                 return true;
1214         return false;
1215 }
1216
1217 static bool __reg64_bound_u32(u64 a)
1218 {
1219         if (a > U32_MIN && a < U32_MAX)
1220                 return true;
1221         return false;
1222 }
1223
1224 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1225 {
1226         __mark_reg32_unbounded(reg);
1227
1228         if (__reg64_bound_s32(reg->smin_value))
1229                 reg->s32_min_value = (s32)reg->smin_value;
1230         if (__reg64_bound_s32(reg->smax_value))
1231                 reg->s32_max_value = (s32)reg->smax_value;
1232         if (__reg64_bound_u32(reg->umin_value))
1233                 reg->u32_min_value = (u32)reg->umin_value;
1234         if (__reg64_bound_u32(reg->umax_value))
1235                 reg->u32_max_value = (u32)reg->umax_value;
1236
1237         /* Intersecting with the old var_off might have improved our bounds
1238          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1239          * then new var_off is (0; 0x7f...fc) which improves our umax.
1240          */
1241         __reg_deduce_bounds(reg);
1242         __reg_bound_offset(reg);
1243         __update_reg_bounds(reg);
1244 }
1245
1246 /* Mark a register as having a completely unknown (scalar) value. */
1247 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1248                                struct bpf_reg_state *reg)
1249 {
1250         /*
1251          * Clear type, id, off, and union(map_ptr, range) and
1252          * padding between 'type' and union
1253          */
1254         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1255         reg->type = SCALAR_VALUE;
1256         reg->var_off = tnum_unknown;
1257         reg->frameno = 0;
1258         reg->precise = env->subprog_cnt > 1 || !env->allow_ptr_leaks ?
1259                        true : false;
1260         __mark_reg_unbounded(reg);
1261 }
1262
1263 static void mark_reg_unknown(struct bpf_verifier_env *env,
1264                              struct bpf_reg_state *regs, u32 regno)
1265 {
1266         if (WARN_ON(regno >= MAX_BPF_REG)) {
1267                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1268                 /* Something bad happened, let's kill all regs except FP */
1269                 for (regno = 0; regno < BPF_REG_FP; regno++)
1270                         __mark_reg_not_init(env, regs + regno);
1271                 return;
1272         }
1273         __mark_reg_unknown(env, regs + regno);
1274 }
1275
1276 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1277                                 struct bpf_reg_state *reg)
1278 {
1279         __mark_reg_unknown(env, reg);
1280         reg->type = NOT_INIT;
1281 }
1282
1283 static void mark_reg_not_init(struct bpf_verifier_env *env,
1284                               struct bpf_reg_state *regs, u32 regno)
1285 {
1286         if (WARN_ON(regno >= MAX_BPF_REG)) {
1287                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1288                 /* Something bad happened, let's kill all regs except FP */
1289                 for (regno = 0; regno < BPF_REG_FP; regno++)
1290                         __mark_reg_not_init(env, regs + regno);
1291                 return;
1292         }
1293         __mark_reg_not_init(env, regs + regno);
1294 }
1295
1296 #define DEF_NOT_SUBREG  (0)
1297 static void init_reg_state(struct bpf_verifier_env *env,
1298                            struct bpf_func_state *state)
1299 {
1300         struct bpf_reg_state *regs = state->regs;
1301         int i;
1302
1303         for (i = 0; i < MAX_BPF_REG; i++) {
1304                 mark_reg_not_init(env, regs, i);
1305                 regs[i].live = REG_LIVE_NONE;
1306                 regs[i].parent = NULL;
1307                 regs[i].subreg_def = DEF_NOT_SUBREG;
1308         }
1309
1310         /* frame pointer */
1311         regs[BPF_REG_FP].type = PTR_TO_STACK;
1312         mark_reg_known_zero(env, regs, BPF_REG_FP);
1313         regs[BPF_REG_FP].frameno = state->frameno;
1314 }
1315
1316 #define BPF_MAIN_FUNC (-1)
1317 static void init_func_state(struct bpf_verifier_env *env,
1318                             struct bpf_func_state *state,
1319                             int callsite, int frameno, int subprogno)
1320 {
1321         state->callsite = callsite;
1322         state->frameno = frameno;
1323         state->subprogno = subprogno;
1324         init_reg_state(env, state);
1325 }
1326
1327 enum reg_arg_type {
1328         SRC_OP,         /* register is used as source operand */
1329         DST_OP,         /* register is used as destination operand */
1330         DST_OP_NO_MARK  /* same as above, check only, don't mark */
1331 };
1332
1333 static int cmp_subprogs(const void *a, const void *b)
1334 {
1335         return ((struct bpf_subprog_info *)a)->start -
1336                ((struct bpf_subprog_info *)b)->start;
1337 }
1338
1339 static int find_subprog(struct bpf_verifier_env *env, int off)
1340 {
1341         struct bpf_subprog_info *p;
1342
1343         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1344                     sizeof(env->subprog_info[0]), cmp_subprogs);
1345         if (!p)
1346                 return -ENOENT;
1347         return p - env->subprog_info;
1348
1349 }
1350
1351 static int add_subprog(struct bpf_verifier_env *env, int off)
1352 {
1353         int insn_cnt = env->prog->len;
1354         int ret;
1355
1356         if (off >= insn_cnt || off < 0) {
1357                 verbose(env, "call to invalid destination\n");
1358                 return -EINVAL;
1359         }
1360         ret = find_subprog(env, off);
1361         if (ret >= 0)
1362                 return 0;
1363         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1364                 verbose(env, "too many subprograms\n");
1365                 return -E2BIG;
1366         }
1367         env->subprog_info[env->subprog_cnt++].start = off;
1368         sort(env->subprog_info, env->subprog_cnt,
1369              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1370         return 0;
1371 }
1372
1373 static int check_subprogs(struct bpf_verifier_env *env)
1374 {
1375         int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
1376         struct bpf_subprog_info *subprog = env->subprog_info;
1377         struct bpf_insn *insn = env->prog->insnsi;
1378         int insn_cnt = env->prog->len;
1379
1380         /* Add entry function. */
1381         ret = add_subprog(env, 0);
1382         if (ret < 0)
1383                 return ret;
1384
1385         /* determine subprog starts. The end is one before the next starts */
1386         for (i = 0; i < insn_cnt; i++) {
1387                 if (insn[i].code != (BPF_JMP | BPF_CALL))
1388                         continue;
1389                 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1390                         continue;
1391                 if (!env->allow_ptr_leaks) {
1392                         verbose(env, "function calls to other bpf functions are allowed for root only\n");
1393                         return -EPERM;
1394                 }
1395                 ret = add_subprog(env, i + insn[i].imm + 1);
1396                 if (ret < 0)
1397                         return ret;
1398         }
1399
1400         /* Add a fake 'exit' subprog which could simplify subprog iteration
1401          * logic. 'subprog_cnt' should not be increased.
1402          */
1403         subprog[env->subprog_cnt].start = insn_cnt;
1404
1405         if (env->log.level & BPF_LOG_LEVEL2)
1406                 for (i = 0; i < env->subprog_cnt; i++)
1407                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
1408
1409         /* now check that all jumps are within the same subprog */
1410         subprog_start = subprog[cur_subprog].start;
1411         subprog_end = subprog[cur_subprog + 1].start;
1412         for (i = 0; i < insn_cnt; i++) {
1413                 u8 code = insn[i].code;
1414
1415                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1416                         goto next;
1417                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1418                         goto next;
1419                 off = i + insn[i].off + 1;
1420                 if (off < subprog_start || off >= subprog_end) {
1421                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
1422                         return -EINVAL;
1423                 }
1424 next:
1425                 if (i == subprog_end - 1) {
1426                         /* to avoid fall-through from one subprog into another
1427                          * the last insn of the subprog should be either exit
1428                          * or unconditional jump back
1429                          */
1430                         if (code != (BPF_JMP | BPF_EXIT) &&
1431                             code != (BPF_JMP | BPF_JA)) {
1432                                 verbose(env, "last insn is not an exit or jmp\n");
1433                                 return -EINVAL;
1434                         }
1435                         subprog_start = subprog_end;
1436                         cur_subprog++;
1437                         if (cur_subprog < env->subprog_cnt)
1438                                 subprog_end = subprog[cur_subprog + 1].start;
1439                 }
1440         }
1441         return 0;
1442 }
1443
1444 /* Parentage chain of this register (or stack slot) should take care of all
1445  * issues like callee-saved registers, stack slot allocation time, etc.
1446  */
1447 static int mark_reg_read(struct bpf_verifier_env *env,
1448                          const struct bpf_reg_state *state,
1449                          struct bpf_reg_state *parent, u8 flag)
1450 {
1451         bool writes = parent == state->parent; /* Observe write marks */
1452         int cnt = 0;
1453
1454         while (parent) {
1455                 /* if read wasn't screened by an earlier write ... */
1456                 if (writes && state->live & REG_LIVE_WRITTEN)
1457                         break;
1458                 if (parent->live & REG_LIVE_DONE) {
1459                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1460                                 reg_type_str[parent->type],
1461                                 parent->var_off.value, parent->off);
1462                         return -EFAULT;
1463                 }
1464                 /* The first condition is more likely to be true than the
1465                  * second, checked it first.
1466                  */
1467                 if ((parent->live & REG_LIVE_READ) == flag ||
1468                     parent->live & REG_LIVE_READ64)
1469                         /* The parentage chain never changes and
1470                          * this parent was already marked as LIVE_READ.
1471                          * There is no need to keep walking the chain again and
1472                          * keep re-marking all parents as LIVE_READ.
1473                          * This case happens when the same register is read
1474                          * multiple times without writes into it in-between.
1475                          * Also, if parent has the stronger REG_LIVE_READ64 set,
1476                          * then no need to set the weak REG_LIVE_READ32.
1477                          */
1478                         break;
1479                 /* ... then we depend on parent's value */
1480                 parent->live |= flag;
1481                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1482                 if (flag == REG_LIVE_READ64)
1483                         parent->live &= ~REG_LIVE_READ32;
1484                 state = parent;
1485                 parent = state->parent;
1486                 writes = true;
1487                 cnt++;
1488         }
1489
1490         if (env->longest_mark_read_walk < cnt)
1491                 env->longest_mark_read_walk = cnt;
1492         return 0;
1493 }
1494
1495 /* This function is supposed to be used by the following 32-bit optimization
1496  * code only. It returns TRUE if the source or destination register operates
1497  * on 64-bit, otherwise return FALSE.
1498  */
1499 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1500                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1501 {
1502         u8 code, class, op;
1503
1504         code = insn->code;
1505         class = BPF_CLASS(code);
1506         op = BPF_OP(code);
1507         if (class == BPF_JMP) {
1508                 /* BPF_EXIT for "main" will reach here. Return TRUE
1509                  * conservatively.
1510                  */
1511                 if (op == BPF_EXIT)
1512                         return true;
1513                 if (op == BPF_CALL) {
1514                         /* BPF to BPF call will reach here because of marking
1515                          * caller saved clobber with DST_OP_NO_MARK for which we
1516                          * don't care the register def because they are anyway
1517                          * marked as NOT_INIT already.
1518                          */
1519                         if (insn->src_reg == BPF_PSEUDO_CALL)
1520                                 return false;
1521                         /* Helper call will reach here because of arg type
1522                          * check, conservatively return TRUE.
1523                          */
1524                         if (t == SRC_OP)
1525                                 return true;
1526
1527                         return false;
1528                 }
1529         }
1530
1531         if (class == BPF_ALU64 || class == BPF_JMP ||
1532             /* BPF_END always use BPF_ALU class. */
1533             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1534                 return true;
1535
1536         if (class == BPF_ALU || class == BPF_JMP32)
1537                 return false;
1538
1539         if (class == BPF_LDX) {
1540                 if (t != SRC_OP)
1541                         return BPF_SIZE(code) == BPF_DW;
1542                 /* LDX source must be ptr. */
1543                 return true;
1544         }
1545
1546         if (class == BPF_STX) {
1547                 if (reg->type != SCALAR_VALUE)
1548                         return true;
1549                 return BPF_SIZE(code) == BPF_DW;
1550         }
1551
1552         if (class == BPF_LD) {
1553                 u8 mode = BPF_MODE(code);
1554
1555                 /* LD_IMM64 */
1556                 if (mode == BPF_IMM)
1557                         return true;
1558
1559                 /* Both LD_IND and LD_ABS return 32-bit data. */
1560                 if (t != SRC_OP)
1561                         return  false;
1562
1563                 /* Implicit ctx ptr. */
1564                 if (regno == BPF_REG_6)
1565                         return true;
1566
1567                 /* Explicit source could be any width. */
1568                 return true;
1569         }
1570
1571         if (class == BPF_ST)
1572                 /* The only source register for BPF_ST is a ptr. */
1573                 return true;
1574
1575         /* Conservatively return true at default. */
1576         return true;
1577 }
1578
1579 /* Return TRUE if INSN doesn't have explicit value define. */
1580 static bool insn_no_def(struct bpf_insn *insn)
1581 {
1582         u8 class = BPF_CLASS(insn->code);
1583
1584         return (class == BPF_JMP || class == BPF_JMP32 ||
1585                 class == BPF_STX || class == BPF_ST);
1586 }
1587
1588 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1589 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1590 {
1591         if (insn_no_def(insn))
1592                 return false;
1593
1594         return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1595 }
1596
1597 static void mark_insn_zext(struct bpf_verifier_env *env,
1598                            struct bpf_reg_state *reg)
1599 {
1600         s32 def_idx = reg->subreg_def;
1601
1602         if (def_idx == DEF_NOT_SUBREG)
1603                 return;
1604
1605         env->insn_aux_data[def_idx - 1].zext_dst = true;
1606         /* The dst will be zero extended, so won't be sub-register anymore. */
1607         reg->subreg_def = DEF_NOT_SUBREG;
1608 }
1609
1610 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1611                          enum reg_arg_type t)
1612 {
1613         struct bpf_verifier_state *vstate = env->cur_state;
1614         struct bpf_func_state *state = vstate->frame[vstate->curframe];
1615         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
1616         struct bpf_reg_state *reg, *regs = state->regs;
1617         bool rw64;
1618
1619         if (regno >= MAX_BPF_REG) {
1620                 verbose(env, "R%d is invalid\n", regno);
1621                 return -EINVAL;
1622         }
1623
1624         reg = &regs[regno];
1625         rw64 = is_reg64(env, insn, regno, reg, t);
1626         if (t == SRC_OP) {
1627                 /* check whether register used as source operand can be read */
1628                 if (reg->type == NOT_INIT) {
1629                         verbose(env, "R%d !read_ok\n", regno);
1630                         return -EACCES;
1631                 }
1632                 /* We don't need to worry about FP liveness because it's read-only */
1633                 if (regno == BPF_REG_FP)
1634                         return 0;
1635
1636                 if (rw64)
1637                         mark_insn_zext(env, reg);
1638
1639                 return mark_reg_read(env, reg, reg->parent,
1640                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
1641         } else {
1642                 /* check whether register used as dest operand can be written to */
1643                 if (regno == BPF_REG_FP) {
1644                         verbose(env, "frame pointer is read only\n");
1645                         return -EACCES;
1646                 }
1647                 reg->live |= REG_LIVE_WRITTEN;
1648                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
1649                 if (t == DST_OP)
1650                         mark_reg_unknown(env, regs, regno);
1651         }
1652         return 0;
1653 }
1654
1655 /* for any branch, call, exit record the history of jmps in the given state */
1656 static int push_jmp_history(struct bpf_verifier_env *env,
1657                             struct bpf_verifier_state *cur)
1658 {
1659         u32 cnt = cur->jmp_history_cnt;
1660         struct bpf_idx_pair *p;
1661
1662         cnt++;
1663         p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1664         if (!p)
1665                 return -ENOMEM;
1666         p[cnt - 1].idx = env->insn_idx;
1667         p[cnt - 1].prev_idx = env->prev_insn_idx;
1668         cur->jmp_history = p;
1669         cur->jmp_history_cnt = cnt;
1670         return 0;
1671 }
1672
1673 /* Backtrack one insn at a time. If idx is not at the top of recorded
1674  * history then previous instruction came from straight line execution.
1675  */
1676 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1677                              u32 *history)
1678 {
1679         u32 cnt = *history;
1680
1681         if (cnt && st->jmp_history[cnt - 1].idx == i) {
1682                 i = st->jmp_history[cnt - 1].prev_idx;
1683                 (*history)--;
1684         } else {
1685                 i--;
1686         }
1687         return i;
1688 }
1689
1690 /* For given verifier state backtrack_insn() is called from the last insn to
1691  * the first insn. Its purpose is to compute a bitmask of registers and
1692  * stack slots that needs precision in the parent verifier state.
1693  */
1694 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1695                           u32 *reg_mask, u64 *stack_mask)
1696 {
1697         const struct bpf_insn_cbs cbs = {
1698                 .cb_print       = verbose,
1699                 .private_data   = env,
1700         };
1701         struct bpf_insn *insn = env->prog->insnsi + idx;
1702         u8 class = BPF_CLASS(insn->code);
1703         u8 opcode = BPF_OP(insn->code);
1704         u8 mode = BPF_MODE(insn->code);
1705         u32 dreg = 1u << insn->dst_reg;
1706         u32 sreg = 1u << insn->src_reg;
1707         u32 spi;
1708
1709         if (insn->code == 0)
1710                 return 0;
1711         if (env->log.level & BPF_LOG_LEVEL) {
1712                 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1713                 verbose(env, "%d: ", idx);
1714                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1715         }
1716
1717         if (class == BPF_ALU || class == BPF_ALU64) {
1718                 if (!(*reg_mask & dreg))
1719                         return 0;
1720                 if (opcode == BPF_MOV) {
1721                         if (BPF_SRC(insn->code) == BPF_X) {
1722                                 /* dreg = sreg
1723                                  * dreg needs precision after this insn
1724                                  * sreg needs precision before this insn
1725                                  */
1726                                 *reg_mask &= ~dreg;
1727                                 *reg_mask |= sreg;
1728                         } else {
1729                                 /* dreg = K
1730                                  * dreg needs precision after this insn.
1731                                  * Corresponding register is already marked
1732                                  * as precise=true in this verifier state.
1733                                  * No further markings in parent are necessary
1734                                  */
1735                                 *reg_mask &= ~dreg;
1736                         }
1737                 } else {
1738                         if (BPF_SRC(insn->code) == BPF_X) {
1739                                 /* dreg += sreg
1740                                  * both dreg and sreg need precision
1741                                  * before this insn
1742                                  */
1743                                 *reg_mask |= sreg;
1744                         } /* else dreg += K
1745                            * dreg still needs precision before this insn
1746                            */
1747                 }
1748         } else if (class == BPF_LDX) {
1749                 if (!(*reg_mask & dreg))
1750                         return 0;
1751                 *reg_mask &= ~dreg;
1752
1753                 /* scalars can only be spilled into stack w/o losing precision.
1754                  * Load from any other memory can be zero extended.
1755                  * The desire to keep that precision is already indicated
1756                  * by 'precise' mark in corresponding register of this state.
1757                  * No further tracking necessary.
1758                  */
1759                 if (insn->src_reg != BPF_REG_FP)
1760                         return 0;
1761                 if (BPF_SIZE(insn->code) != BPF_DW)
1762                         return 0;
1763
1764                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1765                  * that [fp - off] slot contains scalar that needs to be
1766                  * tracked with precision
1767                  */
1768                 spi = (-insn->off - 1) / BPF_REG_SIZE;
1769                 if (spi >= 64) {
1770                         verbose(env, "BUG spi %d\n", spi);
1771                         WARN_ONCE(1, "verifier backtracking bug");
1772                         return -EFAULT;
1773                 }
1774                 *stack_mask |= 1ull << spi;
1775         } else if (class == BPF_STX || class == BPF_ST) {
1776                 if (*reg_mask & dreg)
1777                         /* stx & st shouldn't be using _scalar_ dst_reg
1778                          * to access memory. It means backtracking
1779                          * encountered a case of pointer subtraction.
1780                          */
1781                         return -ENOTSUPP;
1782                 /* scalars can only be spilled into stack */
1783                 if (insn->dst_reg != BPF_REG_FP)
1784                         return 0;
1785                 if (BPF_SIZE(insn->code) != BPF_DW)
1786                         return 0;
1787                 spi = (-insn->off - 1) / BPF_REG_SIZE;
1788                 if (spi >= 64) {
1789                         verbose(env, "BUG spi %d\n", spi);
1790                         WARN_ONCE(1, "verifier backtracking bug");
1791                         return -EFAULT;
1792                 }
1793                 if (!(*stack_mask & (1ull << spi)))
1794                         return 0;
1795                 *stack_mask &= ~(1ull << spi);
1796                 if (class == BPF_STX)
1797                         *reg_mask |= sreg;
1798         } else if (class == BPF_JMP || class == BPF_JMP32) {
1799                 if (opcode == BPF_CALL) {
1800                         if (insn->src_reg == BPF_PSEUDO_CALL)
1801                                 return -ENOTSUPP;
1802                         /* regular helper call sets R0 */
1803                         *reg_mask &= ~1;
1804                         if (*reg_mask & 0x3f) {
1805                                 /* if backtracing was looking for registers R1-R5
1806                                  * they should have been found already.
1807                                  */
1808                                 verbose(env, "BUG regs %x\n", *reg_mask);
1809                                 WARN_ONCE(1, "verifier backtracking bug");
1810                                 return -EFAULT;
1811                         }
1812                 } else if (opcode == BPF_EXIT) {
1813                         return -ENOTSUPP;
1814                 }
1815         } else if (class == BPF_LD) {
1816                 if (!(*reg_mask & dreg))
1817                         return 0;
1818                 *reg_mask &= ~dreg;
1819                 /* It's ld_imm64 or ld_abs or ld_ind.
1820                  * For ld_imm64 no further tracking of precision
1821                  * into parent is necessary
1822                  */
1823                 if (mode == BPF_IND || mode == BPF_ABS)
1824                         /* to be analyzed */
1825                         return -ENOTSUPP;
1826         }
1827         return 0;
1828 }
1829
1830 /* the scalar precision tracking algorithm:
1831  * . at the start all registers have precise=false.
1832  * . scalar ranges are tracked as normal through alu and jmp insns.
1833  * . once precise value of the scalar register is used in:
1834  *   .  ptr + scalar alu
1835  *   . if (scalar cond K|scalar)
1836  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
1837  *   backtrack through the verifier states and mark all registers and
1838  *   stack slots with spilled constants that these scalar regisers
1839  *   should be precise.
1840  * . during state pruning two registers (or spilled stack slots)
1841  *   are equivalent if both are not precise.
1842  *
1843  * Note the verifier cannot simply walk register parentage chain,
1844  * since many different registers and stack slots could have been
1845  * used to compute single precise scalar.
1846  *
1847  * The approach of starting with precise=true for all registers and then
1848  * backtrack to mark a register as not precise when the verifier detects
1849  * that program doesn't care about specific value (e.g., when helper
1850  * takes register as ARG_ANYTHING parameter) is not safe.
1851  *
1852  * It's ok to walk single parentage chain of the verifier states.
1853  * It's possible that this backtracking will go all the way till 1st insn.
1854  * All other branches will be explored for needing precision later.
1855  *
1856  * The backtracking needs to deal with cases like:
1857  *   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)
1858  * r9 -= r8
1859  * r5 = r9
1860  * if r5 > 0x79f goto pc+7
1861  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1862  * r5 += 1
1863  * ...
1864  * call bpf_perf_event_output#25
1865  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1866  *
1867  * and this case:
1868  * r6 = 1
1869  * call foo // uses callee's r6 inside to compute r0
1870  * r0 += r6
1871  * if r0 == 0 goto
1872  *
1873  * to track above reg_mask/stack_mask needs to be independent for each frame.
1874  *
1875  * Also if parent's curframe > frame where backtracking started,
1876  * the verifier need to mark registers in both frames, otherwise callees
1877  * may incorrectly prune callers. This is similar to
1878  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1879  *
1880  * For now backtracking falls back into conservative marking.
1881  */
1882 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
1883                                      struct bpf_verifier_state *st)
1884 {
1885         struct bpf_func_state *func;
1886         struct bpf_reg_state *reg;
1887         int i, j;
1888
1889         /* big hammer: mark all scalars precise in this path.
1890          * pop_stack may still get !precise scalars.
1891          */
1892         for (; st; st = st->parent)
1893                 for (i = 0; i <= st->curframe; i++) {
1894                         func = st->frame[i];
1895                         for (j = 0; j < BPF_REG_FP; j++) {
1896                                 reg = &func->regs[j];
1897                                 if (reg->type != SCALAR_VALUE)
1898                                         continue;
1899                                 reg->precise = true;
1900                         }
1901                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
1902                                 if (func->stack[j].slot_type[0] != STACK_SPILL)
1903                                         continue;
1904                                 reg = &func->stack[j].spilled_ptr;
1905                                 if (reg->type != SCALAR_VALUE)
1906                                         continue;
1907                                 reg->precise = true;
1908                         }
1909                 }
1910 }
1911
1912 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
1913                                   int spi)
1914 {
1915         struct bpf_verifier_state *st = env->cur_state;
1916         int first_idx = st->first_insn_idx;
1917         int last_idx = env->insn_idx;
1918         struct bpf_func_state *func;
1919         struct bpf_reg_state *reg;
1920         u32 reg_mask = regno >= 0 ? 1u << regno : 0;
1921         u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
1922         bool skip_first = true;
1923         bool new_marks = false;
1924         int i, err;
1925
1926         if (!env->allow_ptr_leaks)
1927                 /* backtracking is root only for now */
1928                 return 0;
1929
1930         func = st->frame[st->curframe];
1931         if (regno >= 0) {
1932                 reg = &func->regs[regno];
1933                 if (reg->type != SCALAR_VALUE) {
1934                         WARN_ONCE(1, "backtracing misuse");
1935                         return -EFAULT;
1936                 }
1937                 if (!reg->precise)
1938                         new_marks = true;
1939                 else
1940                         reg_mask = 0;
1941                 reg->precise = true;
1942         }
1943
1944         while (spi >= 0) {
1945                 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
1946                         stack_mask = 0;
1947                         break;
1948                 }
1949                 reg = &func->stack[spi].spilled_ptr;
1950                 if (reg->type != SCALAR_VALUE) {
1951                         stack_mask = 0;
1952                         break;
1953                 }
1954                 if (!reg->precise)
1955                         new_marks = true;
1956                 else
1957                         stack_mask = 0;
1958                 reg->precise = true;
1959                 break;
1960         }
1961
1962         if (!new_marks)
1963                 return 0;
1964         if (!reg_mask && !stack_mask)
1965                 return 0;
1966         for (;;) {
1967                 DECLARE_BITMAP(mask, 64);
1968                 u32 history = st->jmp_history_cnt;
1969
1970                 if (env->log.level & BPF_LOG_LEVEL)
1971                         verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
1972                 for (i = last_idx;;) {
1973                         if (skip_first) {
1974                                 err = 0;
1975                                 skip_first = false;
1976                         } else {
1977                                 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
1978                         }
1979                         if (err == -ENOTSUPP) {
1980                                 mark_all_scalars_precise(env, st);
1981                                 return 0;
1982                         } else if (err) {
1983                                 return err;
1984                         }
1985                         if (!reg_mask && !stack_mask)
1986                                 /* Found assignment(s) into tracked register in this state.
1987                                  * Since this state is already marked, just return.
1988                                  * Nothing to be tracked further in the parent state.
1989                                  */
1990                                 return 0;
1991                         if (i == first_idx)
1992                                 break;
1993                         i = get_prev_insn_idx(st, i, &history);
1994                         if (i >= env->prog->len) {
1995                                 /* This can happen if backtracking reached insn 0
1996                                  * and there are still reg_mask or stack_mask
1997                                  * to backtrack.
1998                                  * It means the backtracking missed the spot where
1999                                  * particular register was initialized with a constant.
2000                                  */
2001                                 verbose(env, "BUG backtracking idx %d\n", i);
2002                                 WARN_ONCE(1, "verifier backtracking bug");
2003                                 return -EFAULT;
2004                         }
2005                 }
2006                 st = st->parent;
2007                 if (!st)
2008                         break;
2009
2010                 new_marks = false;
2011                 func = st->frame[st->curframe];
2012                 bitmap_from_u64(mask, reg_mask);
2013                 for_each_set_bit(i, mask, 32) {
2014                         reg = &func->regs[i];
2015                         if (reg->type != SCALAR_VALUE) {
2016                                 reg_mask &= ~(1u << i);
2017                                 continue;
2018                         }
2019                         if (!reg->precise)
2020                                 new_marks = true;
2021                         reg->precise = true;
2022                 }
2023
2024                 bitmap_from_u64(mask, stack_mask);
2025                 for_each_set_bit(i, mask, 64) {
2026                         if (i >= func->allocated_stack / BPF_REG_SIZE) {
2027                                 /* the sequence of instructions:
2028                                  * 2: (bf) r3 = r10
2029                                  * 3: (7b) *(u64 *)(r3 -8) = r0
2030                                  * 4: (79) r4 = *(u64 *)(r10 -8)
2031                                  * doesn't contain jmps. It's backtracked
2032                                  * as a single block.
2033                                  * During backtracking insn 3 is not recognized as
2034                                  * stack access, so at the end of backtracking
2035                                  * stack slot fp-8 is still marked in stack_mask.
2036                                  * However the parent state may not have accessed
2037                                  * fp-8 and it's "unallocated" stack space.
2038                                  * In such case fallback to conservative.
2039                                  */
2040                                 mark_all_scalars_precise(env, st);
2041                                 return 0;
2042                         }
2043
2044                         if (func->stack[i].slot_type[0] != STACK_SPILL) {
2045                                 stack_mask &= ~(1ull << i);
2046                                 continue;
2047                         }
2048                         reg = &func->stack[i].spilled_ptr;
2049                         if (reg->type != SCALAR_VALUE) {
2050                                 stack_mask &= ~(1ull << i);
2051                                 continue;
2052                         }
2053                         if (!reg->precise)
2054                                 new_marks = true;
2055                         reg->precise = true;
2056                 }
2057                 if (env->log.level & BPF_LOG_LEVEL) {
2058                         print_verifier_state(env, func);
2059                         verbose(env, "parent %s regs=%x stack=%llx marks\n",
2060                                 new_marks ? "didn't have" : "already had",
2061                                 reg_mask, stack_mask);
2062                 }
2063
2064                 if (!reg_mask && !stack_mask)
2065                         break;
2066                 if (!new_marks)
2067                         break;
2068
2069                 last_idx = st->last_insn_idx;
2070                 first_idx = st->first_insn_idx;
2071         }
2072         return 0;
2073 }
2074
2075 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2076 {
2077         return __mark_chain_precision(env, regno, -1);
2078 }
2079
2080 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2081 {
2082         return __mark_chain_precision(env, -1, spi);
2083 }
2084
2085 static bool is_spillable_regtype(enum bpf_reg_type type)
2086 {
2087         switch (type) {
2088         case PTR_TO_MAP_VALUE:
2089         case PTR_TO_MAP_VALUE_OR_NULL:
2090         case PTR_TO_STACK:
2091         case PTR_TO_CTX:
2092         case PTR_TO_PACKET:
2093         case PTR_TO_PACKET_META:
2094         case PTR_TO_PACKET_END:
2095         case PTR_TO_FLOW_KEYS:
2096         case CONST_PTR_TO_MAP:
2097         case PTR_TO_SOCKET:
2098         case PTR_TO_SOCKET_OR_NULL:
2099         case PTR_TO_SOCK_COMMON:
2100         case PTR_TO_SOCK_COMMON_OR_NULL:
2101         case PTR_TO_TCP_SOCK:
2102         case PTR_TO_TCP_SOCK_OR_NULL:
2103         case PTR_TO_XDP_SOCK:
2104         case PTR_TO_BTF_ID:
2105                 return true;
2106         default:
2107                 return false;
2108         }
2109 }
2110
2111 /* Does this register contain a constant zero? */
2112 static bool register_is_null(struct bpf_reg_state *reg)
2113 {
2114         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2115 }
2116
2117 static bool register_is_const(struct bpf_reg_state *reg)
2118 {
2119         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2120 }
2121
2122 static void save_register_state(struct bpf_func_state *state,
2123                                 int spi, struct bpf_reg_state *reg)
2124 {
2125         int i;
2126
2127         state->stack[spi].spilled_ptr = *reg;
2128         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2129
2130         for (i = 0; i < BPF_REG_SIZE; i++)
2131                 state->stack[spi].slot_type[i] = STACK_SPILL;
2132 }
2133
2134 /* check_stack_read/write functions track spill/fill of registers,
2135  * stack boundary and alignment are checked in check_mem_access()
2136  */
2137 static int check_stack_write(struct bpf_verifier_env *env,
2138                              struct bpf_func_state *state, /* func where register points to */
2139                              int off, int size, int value_regno, int insn_idx)
2140 {
2141         struct bpf_func_state *cur; /* state of the current function */
2142         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2143         u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2144         struct bpf_reg_state *reg = NULL;
2145
2146         err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
2147                                  state->acquired_refs, true);
2148         if (err)
2149                 return err;
2150         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2151          * so it's aligned access and [off, off + size) are within stack limits
2152          */
2153         if (!env->allow_ptr_leaks &&
2154             state->stack[spi].slot_type[0] == STACK_SPILL &&
2155             size != BPF_REG_SIZE) {
2156                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2157                 return -EACCES;
2158         }
2159
2160         cur = env->cur_state->frame[env->cur_state->curframe];
2161         if (value_regno >= 0)
2162                 reg = &cur->regs[value_regno];
2163
2164         if (reg && size == BPF_REG_SIZE && register_is_const(reg) &&
2165             !register_is_null(reg) && env->allow_ptr_leaks) {
2166                 if (dst_reg != BPF_REG_FP) {
2167                         /* The backtracking logic can only recognize explicit
2168                          * stack slot address like [fp - 8]. Other spill of
2169                          * scalar via different register has to be conervative.
2170                          * Backtrack from here and mark all registers as precise
2171                          * that contributed into 'reg' being a constant.
2172                          */
2173                         err = mark_chain_precision(env, value_regno);
2174                         if (err)
2175                                 return err;
2176                 }
2177                 save_register_state(state, spi, reg);
2178         } else if (reg && is_spillable_regtype(reg->type)) {
2179                 /* register containing pointer is being spilled into stack */
2180                 if (size != BPF_REG_SIZE) {
2181                         verbose_linfo(env, insn_idx, "; ");
2182                         verbose(env, "invalid size of register spill\n");
2183                         return -EACCES;
2184                 }
2185
2186                 if (state != cur && reg->type == PTR_TO_STACK) {
2187                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2188                         return -EINVAL;
2189                 }
2190
2191                 if (!env->allow_ptr_leaks) {
2192                         bool sanitize = false;
2193
2194                         if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2195                             register_is_const(&state->stack[spi].spilled_ptr))
2196                                 sanitize = true;
2197                         for (i = 0; i < BPF_REG_SIZE; i++)
2198                                 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2199                                         sanitize = true;
2200                                         break;
2201                                 }
2202                         if (sanitize) {
2203                                 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2204                                 int soff = (-spi - 1) * BPF_REG_SIZE;
2205
2206                                 /* detected reuse of integer stack slot with a pointer
2207                                  * which means either llvm is reusing stack slot or
2208                                  * an attacker is trying to exploit CVE-2018-3639
2209                                  * (speculative store bypass)
2210                                  * Have to sanitize that slot with preemptive
2211                                  * store of zero.
2212                                  */
2213                                 if (*poff && *poff != soff) {
2214                                         /* disallow programs where single insn stores
2215                                          * into two different stack slots, since verifier
2216                                          * cannot sanitize them
2217                                          */
2218                                         verbose(env,
2219                                                 "insn %d cannot access two stack slots fp%d and fp%d",
2220                                                 insn_idx, *poff, soff);
2221                                         return -EINVAL;
2222                                 }
2223                                 *poff = soff;
2224                         }
2225                 }
2226                 save_register_state(state, spi, reg);
2227         } else {
2228                 u8 type = STACK_MISC;
2229
2230                 /* regular write of data into stack destroys any spilled ptr */
2231                 state->stack[spi].spilled_ptr.type = NOT_INIT;
2232                 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2233                 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2234                         for (i = 0; i < BPF_REG_SIZE; i++)
2235                                 state->stack[spi].slot_type[i] = STACK_MISC;
2236
2237                 /* only mark the slot as written if all 8 bytes were written
2238                  * otherwise read propagation may incorrectly stop too soon
2239                  * when stack slots are partially written.
2240                  * This heuristic means that read propagation will be
2241                  * conservative, since it will add reg_live_read marks
2242                  * to stack slots all the way to first state when programs
2243                  * writes+reads less than 8 bytes
2244                  */
2245                 if (size == BPF_REG_SIZE)
2246                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2247
2248                 /* when we zero initialize stack slots mark them as such */
2249                 if (reg && register_is_null(reg)) {
2250                         /* backtracking doesn't work for STACK_ZERO yet. */
2251                         err = mark_chain_precision(env, value_regno);
2252                         if (err)
2253                                 return err;
2254                         type = STACK_ZERO;
2255                 }
2256
2257                 /* Mark slots affected by this stack write. */
2258                 for (i = 0; i < size; i++)
2259                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2260                                 type;
2261         }
2262         return 0;
2263 }
2264
2265 static int check_stack_read(struct bpf_verifier_env *env,
2266                             struct bpf_func_state *reg_state /* func where register points to */,
2267                             int off, int size, int value_regno)
2268 {
2269         struct bpf_verifier_state *vstate = env->cur_state;
2270         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2271         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2272         struct bpf_reg_state *reg;
2273         u8 *stype;
2274
2275         if (reg_state->allocated_stack <= slot) {
2276                 verbose(env, "invalid read from stack off %d+0 size %d\n",
2277                         off, size);
2278                 return -EACCES;
2279         }
2280         stype = reg_state->stack[spi].slot_type;
2281         reg = &reg_state->stack[spi].spilled_ptr;
2282
2283         if (stype[0] == STACK_SPILL) {
2284                 if (size != BPF_REG_SIZE) {
2285                         if (reg->type != SCALAR_VALUE) {
2286                                 verbose_linfo(env, env->insn_idx, "; ");
2287                                 verbose(env, "invalid size of register fill\n");
2288                                 return -EACCES;
2289                         }
2290                         if (value_regno >= 0) {
2291                                 mark_reg_unknown(env, state->regs, value_regno);
2292                                 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2293                         }
2294                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2295                         return 0;
2296                 }
2297                 for (i = 1; i < BPF_REG_SIZE; i++) {
2298                         if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2299                                 verbose(env, "corrupted spill memory\n");
2300                                 return -EACCES;
2301                         }
2302                 }
2303
2304                 if (value_regno >= 0) {
2305                         /* restore register state from stack */
2306                         state->regs[value_regno] = *reg;
2307                         /* mark reg as written since spilled pointer state likely
2308                          * has its liveness marks cleared by is_state_visited()
2309                          * which resets stack/reg liveness for state transitions
2310                          */
2311                         state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2312                 }
2313                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2314         } else {
2315                 int zeros = 0;
2316
2317                 for (i = 0; i < size; i++) {
2318                         if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
2319                                 continue;
2320                         if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
2321                                 zeros++;
2322                                 continue;
2323                         }
2324                         verbose(env, "invalid read from stack off %d+%d size %d\n",
2325                                 off, i, size);
2326                         return -EACCES;
2327                 }
2328                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2329                 if (value_regno >= 0) {
2330                         if (zeros == size) {
2331                                 /* any size read into register is zero extended,
2332                                  * so the whole register == const_zero
2333                                  */
2334                                 __mark_reg_const_zero(&state->regs[value_regno]);
2335                                 /* backtracking doesn't support STACK_ZERO yet,
2336                                  * so mark it precise here, so that later
2337                                  * backtracking can stop here.
2338                                  * Backtracking may not need this if this register
2339                                  * doesn't participate in pointer adjustment.
2340                                  * Forward propagation of precise flag is not
2341                                  * necessary either. This mark is only to stop
2342                                  * backtracking. Any register that contributed
2343                                  * to const 0 was marked precise before spill.
2344                                  */
2345                                 state->regs[value_regno].precise = true;
2346                         } else {
2347                                 /* have read misc data from the stack */
2348                                 mark_reg_unknown(env, state->regs, value_regno);
2349                         }
2350                         state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2351                 }
2352         }
2353         return 0;
2354 }
2355
2356 static int check_stack_access(struct bpf_verifier_env *env,
2357                               const struct bpf_reg_state *reg,
2358                               int off, int size)
2359 {
2360         /* Stack accesses must be at a fixed offset, so that we
2361          * can determine what type of data were returned. See
2362          * check_stack_read().
2363          */
2364         if (!tnum_is_const(reg->var_off)) {
2365                 char tn_buf[48];
2366
2367                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2368                 verbose(env, "variable stack access var_off=%s off=%d size=%d\n",
2369                         tn_buf, off, size);
2370                 return -EACCES;
2371         }
2372
2373         if (off >= 0 || off < -MAX_BPF_STACK) {
2374                 verbose(env, "invalid stack off=%d size=%d\n", off, size);
2375                 return -EACCES;
2376         }
2377
2378         return 0;
2379 }
2380
2381 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2382                                  int off, int size, enum bpf_access_type type)
2383 {
2384         struct bpf_reg_state *regs = cur_regs(env);
2385         struct bpf_map *map = regs[regno].map_ptr;
2386         u32 cap = bpf_map_flags_to_cap(map);
2387
2388         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2389                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2390                         map->value_size, off, size);
2391                 return -EACCES;
2392         }
2393
2394         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2395                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2396                         map->value_size, off, size);
2397                 return -EACCES;
2398         }
2399
2400         return 0;
2401 }
2402
2403 /* check read/write into map element returned by bpf_map_lookup_elem() */
2404 static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
2405                               int size, bool zero_size_allowed)
2406 {
2407         struct bpf_reg_state *regs = cur_regs(env);
2408         struct bpf_map *map = regs[regno].map_ptr;
2409
2410         if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
2411             off + size > map->value_size) {
2412                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
2413                         map->value_size, off, size);
2414                 return -EACCES;
2415         }
2416         return 0;
2417 }
2418
2419 /* check read/write into a map element with possible variable offset */
2420 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2421                             int off, int size, bool zero_size_allowed)
2422 {
2423         struct bpf_verifier_state *vstate = env->cur_state;
2424         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2425         struct bpf_reg_state *reg = &state->regs[regno];
2426         int err;
2427
2428         /* We may have adjusted the register to this map value, so we
2429          * need to try adding each of min_value and max_value to off
2430          * to make sure our theoretical access will be safe.
2431          */
2432         if (env->log.level & BPF_LOG_LEVEL)
2433                 print_verifier_state(env, state);
2434
2435         /* The minimum value is only important with signed
2436          * comparisons where we can't assume the floor of a
2437          * value is 0.  If we are using signed variables for our
2438          * index'es we need to make sure that whatever we use
2439          * will have a set floor within our range.
2440          */
2441         if (reg->smin_value < 0 &&
2442             (reg->smin_value == S64_MIN ||
2443              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2444               reg->smin_value + off < 0)) {
2445                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2446                         regno);
2447                 return -EACCES;
2448         }
2449         err = __check_map_access(env, regno, reg->smin_value + off, size,
2450                                  zero_size_allowed);
2451         if (err) {
2452                 verbose(env, "R%d min value is outside of the array range\n",
2453                         regno);
2454                 return err;
2455         }
2456
2457         /* If we haven't set a max value then we need to bail since we can't be
2458          * sure we won't do bad things.
2459          * If reg->umax_value + off could overflow, treat that as unbounded too.
2460          */
2461         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
2462                 verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
2463                         regno);
2464                 return -EACCES;
2465         }
2466         err = __check_map_access(env, regno, reg->umax_value + off, size,
2467                                  zero_size_allowed);
2468         if (err)
2469                 verbose(env, "R%d max value is outside of the array range\n",
2470                         regno);
2471
2472         if (map_value_has_spin_lock(reg->map_ptr)) {
2473                 u32 lock = reg->map_ptr->spin_lock_off;
2474
2475                 /* if any part of struct bpf_spin_lock can be touched by
2476                  * load/store reject this program.
2477                  * To check that [x1, x2) overlaps with [y1, y2)
2478                  * it is sufficient to check x1 < y2 && y1 < x2.
2479                  */
2480                 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2481                      lock < reg->umax_value + off + size) {
2482                         verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2483                         return -EACCES;
2484                 }
2485         }
2486         return err;
2487 }
2488
2489 #define MAX_PACKET_OFF 0xffff
2490
2491 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
2492                                        const struct bpf_call_arg_meta *meta,
2493                                        enum bpf_access_type t)
2494 {
2495         switch (env->prog->type) {
2496         /* Program types only with direct read access go here! */
2497         case BPF_PROG_TYPE_LWT_IN:
2498         case BPF_PROG_TYPE_LWT_OUT:
2499         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2500         case BPF_PROG_TYPE_SK_REUSEPORT:
2501         case BPF_PROG_TYPE_FLOW_DISSECTOR:
2502         case BPF_PROG_TYPE_CGROUP_SKB:
2503                 if (t == BPF_WRITE)
2504                         return false;
2505                 /* fallthrough */
2506
2507         /* Program types with direct read + write access go here! */
2508         case BPF_PROG_TYPE_SCHED_CLS:
2509         case BPF_PROG_TYPE_SCHED_ACT:
2510         case BPF_PROG_TYPE_XDP:
2511         case BPF_PROG_TYPE_LWT_XMIT:
2512         case BPF_PROG_TYPE_SK_SKB:
2513         case BPF_PROG_TYPE_SK_MSG:
2514                 if (meta)
2515                         return meta->pkt_access;
2516
2517                 env->seen_direct_write = true;
2518                 return true;
2519
2520         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2521                 if (t == BPF_WRITE)
2522                         env->seen_direct_write = true;
2523
2524                 return true;
2525
2526         default:
2527                 return false;
2528         }
2529 }
2530
2531 static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
2532                                  int off, int size, bool zero_size_allowed)
2533 {
2534         struct bpf_reg_state *regs = cur_regs(env);
2535         struct bpf_reg_state *reg = &regs[regno];
2536
2537         if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
2538             (u64)off + size > reg->range) {
2539                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2540                         off, size, regno, reg->id, reg->off, reg->range);
2541                 return -EACCES;
2542         }
2543         return 0;
2544 }
2545
2546 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
2547                                int size, bool zero_size_allowed)
2548 {
2549         struct bpf_reg_state *regs = cur_regs(env);
2550         struct bpf_reg_state *reg = &regs[regno];
2551         int err;
2552
2553         /* We may have added a variable offset to the packet pointer; but any
2554          * reg->range we have comes after that.  We are only checking the fixed
2555          * offset.
2556          */
2557
2558         /* We don't allow negative numbers, because we aren't tracking enough
2559          * detail to prove they're safe.
2560          */
2561         if (reg->smin_value < 0) {
2562                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2563                         regno);
2564                 return -EACCES;
2565         }
2566         err = __check_packet_access(env, regno, off, size, zero_size_allowed);
2567         if (err) {
2568                 verbose(env, "R%d offset is outside of the packet\n", regno);
2569                 return err;
2570         }
2571
2572         /* __check_packet_access has made sure "off + size - 1" is within u16.
2573          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
2574          * otherwise find_good_pkt_pointers would have refused to set range info
2575          * that __check_packet_access would have rejected this pkt access.
2576          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
2577          */
2578         env->prog->aux->max_pkt_offset =
2579                 max_t(u32, env->prog->aux->max_pkt_offset,
2580                       off + reg->umax_value + size - 1);
2581
2582         return err;
2583 }
2584
2585 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
2586 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
2587                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
2588                             u32 *btf_id)
2589 {
2590         struct bpf_insn_access_aux info = {
2591                 .reg_type = *reg_type,
2592                 .log = &env->log,
2593         };
2594
2595         if (env->ops->is_valid_access &&
2596             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
2597                 /* A non zero info.ctx_field_size indicates that this field is a
2598                  * candidate for later verifier transformation to load the whole
2599                  * field and then apply a mask when accessed with a narrower
2600                  * access than actual ctx access size. A zero info.ctx_field_size
2601                  * will only allow for whole field access and rejects any other
2602                  * type of narrower access.
2603                  */
2604                 *reg_type = info.reg_type;
2605
2606                 if (*reg_type == PTR_TO_BTF_ID)
2607                         *btf_id = info.btf_id;
2608                 else
2609                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
2610                 /* remember the offset of last byte accessed in ctx */
2611                 if (env->prog->aux->max_ctx_offset < off + size)
2612                         env->prog->aux->max_ctx_offset = off + size;
2613                 return 0;
2614         }
2615
2616         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
2617         return -EACCES;
2618 }
2619
2620 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
2621                                   int size)
2622 {
2623         if (size < 0 || off < 0 ||
2624             (u64)off + size > sizeof(struct bpf_flow_keys)) {
2625                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
2626                         off, size);
2627                 return -EACCES;
2628         }
2629         return 0;
2630 }
2631
2632 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
2633                              u32 regno, int off, int size,
2634                              enum bpf_access_type t)
2635 {
2636         struct bpf_reg_state *regs = cur_regs(env);
2637         struct bpf_reg_state *reg = &regs[regno];
2638         struct bpf_insn_access_aux info = {};
2639         bool valid;
2640
2641         if (reg->smin_value < 0) {
2642                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2643                         regno);
2644                 return -EACCES;
2645         }
2646
2647         switch (reg->type) {
2648         case PTR_TO_SOCK_COMMON:
2649                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
2650                 break;
2651         case PTR_TO_SOCKET:
2652                 valid = bpf_sock_is_valid_access(off, size, t, &info);
2653                 break;
2654         case PTR_TO_TCP_SOCK:
2655                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
2656                 break;
2657         case PTR_TO_XDP_SOCK:
2658                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
2659                 break;
2660         default:
2661                 valid = false;
2662         }
2663
2664
2665         if (valid) {
2666                 env->insn_aux_data[insn_idx].ctx_field_size =
2667                         info.ctx_field_size;
2668                 return 0;
2669         }
2670
2671         verbose(env, "R%d invalid %s access off=%d size=%d\n",
2672                 regno, reg_type_str[reg->type], off, size);
2673
2674         return -EACCES;
2675 }
2676
2677 static bool __is_pointer_value(bool allow_ptr_leaks,
2678                                const struct bpf_reg_state *reg)
2679 {
2680         if (allow_ptr_leaks)
2681                 return false;
2682
2683         return reg->type != SCALAR_VALUE;
2684 }
2685
2686 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2687 {
2688         return cur_regs(env) + regno;
2689 }
2690
2691 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
2692 {
2693         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
2694 }
2695
2696 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
2697 {
2698         const struct bpf_reg_state *reg = reg_state(env, regno);
2699
2700         return reg->type == PTR_TO_CTX;
2701 }
2702
2703 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
2704 {
2705         const struct bpf_reg_state *reg = reg_state(env, regno);
2706
2707         return type_is_sk_pointer(reg->type);
2708 }
2709
2710 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
2711 {
2712         const struct bpf_reg_state *reg = reg_state(env, regno);
2713
2714         return type_is_pkt_pointer(reg->type);
2715 }
2716
2717 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
2718 {
2719         const struct bpf_reg_state *reg = reg_state(env, regno);
2720
2721         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
2722         return reg->type == PTR_TO_FLOW_KEYS;
2723 }
2724
2725 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
2726                                    const struct bpf_reg_state *reg,
2727                                    int off, int size, bool strict)
2728 {
2729         struct tnum reg_off;
2730         int ip_align;
2731
2732         /* Byte size accesses are always allowed. */
2733         if (!strict || size == 1)
2734                 return 0;
2735
2736         /* For platforms that do not have a Kconfig enabling
2737          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
2738          * NET_IP_ALIGN is universally set to '2'.  And on platforms
2739          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
2740          * to this code only in strict mode where we want to emulate
2741          * the NET_IP_ALIGN==2 checking.  Therefore use an
2742          * unconditional IP align value of '2'.
2743          */
2744         ip_align = 2;
2745
2746         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
2747         if (!tnum_is_aligned(reg_off, size)) {
2748                 char tn_buf[48];
2749
2750                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2751                 verbose(env,
2752                         "misaligned packet access off %d+%s+%d+%d size %d\n",
2753                         ip_align, tn_buf, reg->off, off, size);
2754                 return -EACCES;
2755         }
2756
2757         return 0;
2758 }
2759
2760 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
2761                                        const struct bpf_reg_state *reg,
2762                                        const char *pointer_desc,
2763                                        int off, int size, bool strict)
2764 {
2765         struct tnum reg_off;
2766
2767         /* Byte size accesses are always allowed. */
2768         if (!strict || size == 1)
2769                 return 0;
2770
2771         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
2772         if (!tnum_is_aligned(reg_off, size)) {
2773                 char tn_buf[48];
2774
2775                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2776                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
2777                         pointer_desc, tn_buf, reg->off, off, size);
2778                 return -EACCES;
2779         }
2780
2781         return 0;
2782 }
2783
2784 static int check_ptr_alignment(struct bpf_verifier_env *env,
2785                                const struct bpf_reg_state *reg, int off,
2786                                int size, bool strict_alignment_once)
2787 {
2788         bool strict = env->strict_alignment || strict_alignment_once;
2789         const char *pointer_desc = "";
2790
2791         switch (reg->type) {
2792         case PTR_TO_PACKET:
2793         case PTR_TO_PACKET_META:
2794                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
2795                  * right in front, treat it the very same way.
2796                  */
2797                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
2798         case PTR_TO_FLOW_KEYS:
2799                 pointer_desc = "flow keys ";
2800                 break;
2801         case PTR_TO_MAP_VALUE:
2802                 pointer_desc = "value ";
2803                 break;
2804         case PTR_TO_CTX:
2805                 pointer_desc = "context ";
2806                 break;
2807         case PTR_TO_STACK:
2808                 pointer_desc = "stack ";
2809                 /* The stack spill tracking logic in check_stack_write()
2810                  * and check_stack_read() relies on stack accesses being
2811                  * aligned.
2812                  */
2813                 strict = true;
2814                 break;
2815         case PTR_TO_SOCKET:
2816                 pointer_desc = "sock ";
2817                 break;
2818         case PTR_TO_SOCK_COMMON:
2819                 pointer_desc = "sock_common ";
2820                 break;
2821         case PTR_TO_TCP_SOCK:
2822                 pointer_desc = "tcp_sock ";
2823                 break;
2824         case PTR_TO_XDP_SOCK:
2825                 pointer_desc = "xdp_sock ";
2826                 break;
2827         default:
2828                 break;
2829         }
2830         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
2831                                            strict);
2832 }
2833
2834 static int update_stack_depth(struct bpf_verifier_env *env,
2835                               const struct bpf_func_state *func,
2836                               int off)
2837 {
2838         u16 stack = env->subprog_info[func->subprogno].stack_depth;
2839
2840         if (stack >= -off)
2841                 return 0;
2842
2843         /* update known max for given subprogram */
2844         env->subprog_info[func->subprogno].stack_depth = -off;
2845         return 0;
2846 }
2847
2848 /* starting from main bpf function walk all instructions of the function
2849  * and recursively walk all callees that given function can call.
2850  * Ignore jump and exit insns.
2851  * Since recursion is prevented by check_cfg() this algorithm
2852  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
2853  */
2854 static int check_max_stack_depth(struct bpf_verifier_env *env)
2855 {
2856         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
2857         struct bpf_subprog_info *subprog = env->subprog_info;
2858         struct bpf_insn *insn = env->prog->insnsi;
2859         int ret_insn[MAX_CALL_FRAMES];
2860         int ret_prog[MAX_CALL_FRAMES];
2861
2862 process_func:
2863         /* round up to 32-bytes, since this is granularity
2864          * of interpreter stack size
2865          */
2866         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
2867         if (depth > MAX_BPF_STACK) {
2868                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
2869                         frame + 1, depth);
2870                 return -EACCES;
2871         }
2872 continue_func:
2873         subprog_end = subprog[idx + 1].start;
2874         for (; i < subprog_end; i++) {
2875                 if (insn[i].code != (BPF_JMP | BPF_CALL))
2876                         continue;
2877                 if (insn[i].src_reg != BPF_PSEUDO_CALL)
2878                         continue;
2879                 /* remember insn and function to return to */
2880                 ret_insn[frame] = i + 1;
2881                 ret_prog[frame] = idx;
2882
2883                 /* find the callee */
2884                 i = i + insn[i].imm + 1;
2885                 idx = find_subprog(env, i);
2886                 if (idx < 0) {
2887                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
2888                                   i);
2889                         return -EFAULT;
2890                 }
2891                 frame++;
2892                 if (frame >= MAX_CALL_FRAMES) {
2893                         verbose(env, "the call stack of %d frames is too deep !\n",
2894                                 frame);
2895                         return -E2BIG;
2896                 }
2897                 goto process_func;
2898         }
2899         /* end of for() loop means the last insn of the 'subprog'
2900          * was reached. Doesn't matter whether it was JA or EXIT
2901          */
2902         if (frame == 0)
2903                 return 0;
2904         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
2905         frame--;
2906         i = ret_insn[frame];
2907         idx = ret_prog[frame];
2908         goto continue_func;
2909 }
2910
2911 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
2912 static int get_callee_stack_depth(struct bpf_verifier_env *env,
2913                                   const struct bpf_insn *insn, int idx)
2914 {
2915         int start = idx + insn->imm + 1, subprog;
2916
2917         subprog = find_subprog(env, start);
2918         if (subprog < 0) {
2919                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
2920                           start);
2921                 return -EFAULT;
2922         }
2923         return env->subprog_info[subprog].stack_depth;
2924 }
2925 #endif
2926
2927 int check_ctx_reg(struct bpf_verifier_env *env,
2928                   const struct bpf_reg_state *reg, int regno)
2929 {
2930         /* Access to ctx or passing it to a helper is only allowed in
2931          * its original, unmodified form.
2932          */
2933
2934         if (reg->off) {
2935                 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
2936                         regno, reg->off);
2937                 return -EACCES;
2938         }
2939
2940         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
2941                 char tn_buf[48];
2942
2943                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2944                 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
2945                 return -EACCES;
2946         }
2947
2948         return 0;
2949 }
2950
2951 static int check_tp_buffer_access(struct bpf_verifier_env *env,
2952                                   const struct bpf_reg_state *reg,
2953                                   int regno, int off, int size)
2954 {
2955         if (off < 0) {
2956                 verbose(env,
2957                         "R%d invalid tracepoint buffer access: off=%d, size=%d",
2958                         regno, off, size);
2959                 return -EACCES;
2960         }
2961         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
2962                 char tn_buf[48];
2963
2964                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2965                 verbose(env,
2966                         "R%d invalid variable buffer offset: off=%d, var_off=%s",
2967                         regno, off, tn_buf);
2968                 return -EACCES;
2969         }
2970         if (off + size > env->prog->aux->max_tp_access)
2971                 env->prog->aux->max_tp_access = off + size;
2972
2973         return 0;
2974 }
2975
2976 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
2977 static void zext_32_to_64(struct bpf_reg_state *reg)
2978 {
2979         reg->var_off = tnum_subreg(reg->var_off);
2980         __reg_assign_32_into_64(reg);
2981 }
2982
2983 /* truncate register to smaller size (in bytes)
2984  * must be called with size < BPF_REG_SIZE
2985  */
2986 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
2987 {
2988         u64 mask;
2989
2990         /* clear high bits in bit representation */
2991         reg->var_off = tnum_cast(reg->var_off, size);
2992
2993         /* fix arithmetic bounds */
2994         mask = ((u64)1 << (size * 8)) - 1;
2995         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
2996                 reg->umin_value &= mask;
2997                 reg->umax_value &= mask;
2998         } else {
2999                 reg->umin_value = 0;
3000                 reg->umax_value = mask;
3001         }
3002         reg->smin_value = reg->umin_value;
3003         reg->smax_value = reg->umax_value;
3004
3005         /* If size is smaller than 32bit register the 32bit register
3006          * values are also truncated so we push 64-bit bounds into
3007          * 32-bit bounds. Above were truncated < 32-bits already.
3008          */
3009         if (size >= 4)
3010                 return;
3011         __reg_combine_64_into_32(reg);
3012 }
3013
3014 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3015 {
3016         return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3017 }
3018
3019 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3020 {
3021         void *ptr;
3022         u64 addr;
3023         int err;
3024
3025         err = map->ops->map_direct_value_addr(map, &addr, off);
3026         if (err)
3027                 return err;
3028         ptr = (void *)(long)addr + off;
3029
3030         switch (size) {
3031         case sizeof(u8):
3032                 *val = (u64)*(u8 *)ptr;
3033                 break;
3034         case sizeof(u16):
3035                 *val = (u64)*(u16 *)ptr;
3036                 break;
3037         case sizeof(u32):
3038                 *val = (u64)*(u32 *)ptr;
3039                 break;
3040         case sizeof(u64):
3041                 *val = *(u64 *)ptr;
3042                 break;
3043         default:
3044                 return -EINVAL;
3045         }
3046         return 0;
3047 }
3048
3049 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3050                                    struct bpf_reg_state *regs,
3051                                    int regno, int off, int size,
3052                                    enum bpf_access_type atype,
3053                                    int value_regno)
3054 {
3055         struct bpf_reg_state *reg = regs + regno;
3056         const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
3057         const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3058         u32 btf_id;
3059         int ret;
3060
3061         if (off < 0) {
3062                 verbose(env,
3063                         "R%d is ptr_%s invalid negative access: off=%d\n",
3064                         regno, tname, off);
3065                 return -EACCES;
3066         }
3067         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3068                 char tn_buf[48];
3069
3070                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3071                 verbose(env,
3072                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3073                         regno, tname, off, tn_buf);
3074                 return -EACCES;
3075         }
3076
3077         if (env->ops->btf_struct_access) {
3078                 ret = env->ops->btf_struct_access(&env->log, t, off, size,
3079                                                   atype, &btf_id);
3080         } else {
3081                 if (atype != BPF_READ) {
3082                         verbose(env, "only read is supported\n");
3083                         return -EACCES;
3084                 }
3085
3086                 ret = btf_struct_access(&env->log, t, off, size, atype,
3087                                         &btf_id);
3088         }
3089
3090         if (ret < 0)
3091                 return ret;
3092
3093         if (atype == BPF_READ) {
3094                 if (ret == SCALAR_VALUE) {
3095                         mark_reg_unknown(env, regs, value_regno);
3096                         return 0;
3097                 }
3098                 mark_reg_known_zero(env, regs, value_regno);
3099                 regs[value_regno].type = PTR_TO_BTF_ID;
3100                 regs[value_regno].btf_id = btf_id;
3101         }
3102
3103         return 0;
3104 }
3105
3106 /* check whether memory at (regno + off) is accessible for t = (read | write)
3107  * if t==write, value_regno is a register which value is stored into memory
3108  * if t==read, value_regno is a register which will receive the value from memory
3109  * if t==write && value_regno==-1, some unknown value is stored into memory
3110  * if t==read && value_regno==-1, don't care what we read from memory
3111  */
3112 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3113                             int off, int bpf_size, enum bpf_access_type t,
3114                             int value_regno, bool strict_alignment_once)
3115 {
3116         struct bpf_reg_state *regs = cur_regs(env);
3117         struct bpf_reg_state *reg = regs + regno;
3118         struct bpf_func_state *state;
3119         int size, err = 0;
3120
3121         size = bpf_size_to_bytes(bpf_size);
3122         if (size < 0)
3123                 return size;
3124
3125         /* alignment checks will add in reg->off themselves */
3126         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
3127         if (err)
3128                 return err;
3129
3130         /* for access checks, reg->off is just part of off */
3131         off += reg->off;
3132
3133         if (reg->type == PTR_TO_MAP_VALUE) {
3134                 if (t == BPF_WRITE && value_regno >= 0 &&
3135                     is_pointer_value(env, value_regno)) {
3136                         verbose(env, "R%d leaks addr into map\n", value_regno);
3137                         return -EACCES;
3138                 }
3139                 err = check_map_access_type(env, regno, off, size, t);
3140                 if (err)
3141                         return err;
3142                 err = check_map_access(env, regno, off, size, false);
3143                 if (!err && t == BPF_READ && value_regno >= 0) {
3144                         struct bpf_map *map = reg->map_ptr;
3145
3146                         /* if map is read-only, track its contents as scalars */
3147                         if (tnum_is_const(reg->var_off) &&
3148                             bpf_map_is_rdonly(map) &&
3149                             map->ops->map_direct_value_addr) {
3150                                 int map_off = off + reg->var_off.value;
3151                                 u64 val = 0;
3152
3153                                 err = bpf_map_direct_read(map, map_off, size,
3154                                                           &val);
3155                                 if (err)
3156                                         return err;
3157
3158                                 regs[value_regno].type = SCALAR_VALUE;
3159                                 __mark_reg_known(&regs[value_regno], val);
3160                         } else {
3161                                 mark_reg_unknown(env, regs, value_regno);
3162                         }
3163                 }
3164         } else if (reg->type == PTR_TO_CTX) {
3165                 enum bpf_reg_type reg_type = SCALAR_VALUE;
3166                 u32 btf_id = 0;
3167
3168                 if (t == BPF_WRITE && value_regno >= 0 &&
3169                     is_pointer_value(env, value_regno)) {
3170                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
3171                         return -EACCES;
3172                 }
3173
3174                 err = check_ctx_reg(env, reg, regno);
3175                 if (err < 0)
3176                         return err;
3177
3178                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf_id);
3179                 if (err)
3180                         verbose_linfo(env, insn_idx, "; ");
3181                 if (!err && t == BPF_READ && value_regno >= 0) {
3182                         /* ctx access returns either a scalar, or a
3183                          * PTR_TO_PACKET[_META,_END]. In the latter
3184                          * case, we know the offset is zero.
3185                          */
3186                         if (reg_type == SCALAR_VALUE) {
3187                                 mark_reg_unknown(env, regs, value_regno);
3188                         } else {
3189                                 mark_reg_known_zero(env, regs,
3190                                                     value_regno);
3191                                 if (reg_type_may_be_null(reg_type))
3192                                         regs[value_regno].id = ++env->id_gen;
3193                                 /* A load of ctx field could have different
3194                                  * actual load size with the one encoded in the
3195                                  * insn. When the dst is PTR, it is for sure not
3196                                  * a sub-register.
3197                                  */
3198                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
3199                                 if (reg_type == PTR_TO_BTF_ID)
3200                                         regs[value_regno].btf_id = btf_id;
3201                         }
3202                         regs[value_regno].type = reg_type;
3203                 }
3204
3205         } else if (reg->type == PTR_TO_STACK) {
3206                 off += reg->var_off.value;
3207                 err = check_stack_access(env, reg, off, size);
3208                 if (err)
3209                         return err;
3210
3211                 state = func(env, reg);
3212                 err = update_stack_depth(env, state, off);
3213                 if (err)
3214                         return err;
3215
3216                 if (t == BPF_WRITE)
3217                         err = check_stack_write(env, state, off, size,
3218                                                 value_regno, insn_idx);
3219                 else
3220                         err = check_stack_read(env, state, off, size,
3221                                                value_regno);
3222         } else if (reg_is_pkt_pointer(reg)) {
3223                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
3224                         verbose(env, "cannot write into packet\n");
3225                         return -EACCES;
3226                 }
3227                 if (t == BPF_WRITE && value_regno >= 0 &&
3228                     is_pointer_value(env, value_regno)) {
3229                         verbose(env, "R%d leaks addr into packet\n",
3230                                 value_regno);
3231                         return -EACCES;
3232                 }
3233                 err = check_packet_access(env, regno, off, size, false);
3234                 if (!err && t == BPF_READ && value_regno >= 0)
3235                         mark_reg_unknown(env, regs, value_regno);
3236         } else if (reg->type == PTR_TO_FLOW_KEYS) {
3237                 if (t == BPF_WRITE && value_regno >= 0 &&
3238                     is_pointer_value(env, value_regno)) {
3239                         verbose(env, "R%d leaks addr into flow keys\n",
3240                                 value_regno);
3241                         return -EACCES;
3242                 }
3243
3244                 err = check_flow_keys_access(env, off, size);
3245                 if (!err && t == BPF_READ && value_regno >= 0)
3246                         mark_reg_unknown(env, regs, value_regno);
3247         } else if (type_is_sk_pointer(reg->type)) {
3248                 if (t == BPF_WRITE) {
3249                         verbose(env, "R%d cannot write into %s\n",
3250                                 regno, reg_type_str[reg->type]);
3251                         return -EACCES;
3252                 }
3253                 err = check_sock_access(env, insn_idx, regno, off, size, t);
3254                 if (!err && value_regno >= 0)
3255                         mark_reg_unknown(env, regs, value_regno);
3256         } else if (reg->type == PTR_TO_TP_BUFFER) {
3257                 err = check_tp_buffer_access(env, reg, regno, off, size);
3258                 if (!err && t == BPF_READ && value_regno >= 0)
3259                         mark_reg_unknown(env, regs, value_regno);
3260         } else if (reg->type == PTR_TO_BTF_ID) {
3261                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3262                                               value_regno);
3263         } else {
3264                 verbose(env, "R%d invalid mem access '%s'\n", regno,
3265                         reg_type_str[reg->type]);
3266                 return -EACCES;
3267         }
3268
3269         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
3270             regs[value_regno].type == SCALAR_VALUE) {
3271                 /* b/h/w load zero-extends, mark upper bits as known 0 */
3272                 coerce_reg_to_size(&regs[value_regno], size);
3273         }
3274         return err;
3275 }
3276
3277 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
3278 {
3279         int err;
3280
3281         if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
3282             insn->imm != 0) {
3283                 verbose(env, "BPF_XADD uses reserved fields\n");
3284                 return -EINVAL;
3285         }
3286
3287         /* check src1 operand */
3288         err = check_reg_arg(env, insn->src_reg, SRC_OP);
3289         if (err)
3290                 return err;
3291
3292         /* check src2 operand */
3293         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3294         if (err)
3295                 return err;
3296
3297         if (is_pointer_value(env, insn->src_reg)) {
3298                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
3299                 return -EACCES;
3300         }
3301
3302         if (is_ctx_reg(env, insn->dst_reg) ||
3303             is_pkt_reg(env, insn->dst_reg) ||
3304             is_flow_key_reg(env, insn->dst_reg) ||
3305             is_sk_reg(env, insn->dst_reg)) {
3306                 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
3307                         insn->dst_reg,
3308                         reg_type_str[reg_state(env, insn->dst_reg)->type]);
3309                 return -EACCES;
3310         }
3311
3312         /* check whether atomic_add can read the memory */
3313         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
3314                                BPF_SIZE(insn->code), BPF_READ, -1, true);
3315         if (err)
3316                 return err;
3317
3318         /* check whether atomic_add can write into the same memory */
3319         return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
3320                                 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
3321 }
3322
3323 static int __check_stack_boundary(struct bpf_verifier_env *env, u32 regno,
3324                                   int off, int access_size,
3325                                   bool zero_size_allowed)
3326 {
3327         struct bpf_reg_state *reg = reg_state(env, regno);
3328
3329         if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
3330             access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
3331                 if (tnum_is_const(reg->var_off)) {
3332                         verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
3333                                 regno, off, access_size);
3334                 } else {
3335                         char tn_buf[48];
3336
3337                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3338                         verbose(env, "invalid stack type R%d var_off=%s access_size=%d\n",
3339                                 regno, tn_buf, access_size);
3340                 }
3341                 return -EACCES;
3342         }
3343         return 0;
3344 }
3345
3346 /* when register 'regno' is passed into function that will read 'access_size'
3347  * bytes from that pointer, make sure that it's within stack boundary
3348  * and all elements of stack are initialized.
3349  * Unlike most pointer bounds-checking functions, this one doesn't take an
3350  * 'off' argument, so it has to add in reg->off itself.
3351  */
3352 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
3353                                 int access_size, bool zero_size_allowed,
3354                                 struct bpf_call_arg_meta *meta)
3355 {
3356         struct bpf_reg_state *reg = reg_state(env, regno);
3357         struct bpf_func_state *state = func(env, reg);
3358         int err, min_off, max_off, i, j, slot, spi;
3359
3360         if (reg->type != PTR_TO_STACK) {
3361                 /* Allow zero-byte read from NULL, regardless of pointer type */
3362                 if (zero_size_allowed && access_size == 0 &&
3363                     register_is_null(reg))
3364                         return 0;
3365
3366                 verbose(env, "R%d type=%s expected=%s\n", regno,
3367                         reg_type_str[reg->type],
3368                         reg_type_str[PTR_TO_STACK]);
3369                 return -EACCES;
3370         }
3371
3372         if (tnum_is_const(reg->var_off)) {
3373                 min_off = max_off = reg->var_off.value + reg->off;
3374                 err = __check_stack_boundary(env, regno, min_off, access_size,
3375                                              zero_size_allowed);
3376                 if (err)
3377                         return err;
3378         } else {
3379                 /* Variable offset is prohibited for unprivileged mode for
3380                  * simplicity since it requires corresponding support in
3381                  * Spectre masking for stack ALU.
3382                  * See also retrieve_ptr_limit().
3383                  */
3384                 if (!env->allow_ptr_leaks) {
3385                         char tn_buf[48];
3386
3387                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3388                         verbose(env, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
3389                                 regno, tn_buf);
3390                         return -EACCES;
3391                 }
3392                 /* Only initialized buffer on stack is allowed to be accessed
3393                  * with variable offset. With uninitialized buffer it's hard to
3394                  * guarantee that whole memory is marked as initialized on
3395                  * helper return since specific bounds are unknown what may
3396                  * cause uninitialized stack leaking.
3397                  */
3398                 if (meta && meta->raw_mode)
3399                         meta = NULL;
3400
3401                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3402                     reg->smax_value <= -BPF_MAX_VAR_OFF) {
3403                         verbose(env, "R%d unbounded indirect variable offset stack access\n",
3404                                 regno);
3405                         return -EACCES;
3406                 }
3407                 min_off = reg->smin_value + reg->off;
3408                 max_off = reg->smax_value + reg->off;
3409                 err = __check_stack_boundary(env, regno, min_off, access_size,
3410                                              zero_size_allowed);
3411                 if (err) {
3412                         verbose(env, "R%d min value is outside of stack bound\n",
3413                                 regno);
3414                         return err;
3415                 }
3416                 err = __check_stack_boundary(env, regno, max_off, access_size,
3417                                              zero_size_allowed);
3418                 if (err) {
3419                         verbose(env, "R%d max value is outside of stack bound\n",
3420                                 regno);
3421                         return err;
3422                 }
3423         }
3424
3425         if (meta && meta->raw_mode) {
3426                 meta->access_size = access_size;
3427                 meta->regno = regno;
3428                 return 0;
3429         }
3430
3431         for (i = min_off; i < max_off + access_size; i++) {
3432                 u8 *stype;
3433
3434                 slot = -i - 1;
3435                 spi = slot / BPF_REG_SIZE;
3436                 if (state->allocated_stack <= slot)
3437                         goto err;
3438                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3439                 if (*stype == STACK_MISC)
3440                         goto mark;
3441                 if (*stype == STACK_ZERO) {
3442                         /* helper can write anything into the stack */
3443                         *stype = STACK_MISC;
3444                         goto mark;
3445                 }
3446                 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3447                     state->stack[spi].spilled_ptr.type == SCALAR_VALUE) {
3448                         __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
3449                         for (j = 0; j < BPF_REG_SIZE; j++)
3450                                 state->stack[spi].slot_type[j] = STACK_MISC;
3451                         goto mark;
3452                 }
3453
3454 err:
3455                 if (tnum_is_const(reg->var_off)) {
3456                         verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
3457                                 min_off, i - min_off, access_size);
3458                 } else {
3459                         char tn_buf[48];
3460
3461                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3462                         verbose(env, "invalid indirect read from stack var_off %s+%d size %d\n",
3463                                 tn_buf, i - min_off, access_size);
3464                 }
3465                 return -EACCES;
3466 mark:
3467                 /* reading any byte out of 8-byte 'spill_slot' will cause
3468                  * the whole slot to be marked as 'read'
3469                  */
3470                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
3471                               state->stack[spi].spilled_ptr.parent,
3472                               REG_LIVE_READ64);
3473         }
3474         return update_stack_depth(env, state, min_off);
3475 }
3476
3477 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
3478                                    int access_size, bool zero_size_allowed,
3479                                    struct bpf_call_arg_meta *meta)
3480 {
3481         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
3482
3483         switch (reg->type) {
3484         case PTR_TO_PACKET:
3485         case PTR_TO_PACKET_META:
3486                 return check_packet_access(env, regno, reg->off, access_size,
3487                                            zero_size_allowed);
3488         case PTR_TO_MAP_VALUE:
3489                 if (check_map_access_type(env, regno, reg->off, access_size,
3490                                           meta && meta->raw_mode ? BPF_WRITE :
3491                                           BPF_READ))
3492                         return -EACCES;
3493                 return check_map_access(env, regno, reg->off, access_size,
3494                                         zero_size_allowed);
3495         default: /* scalar_value|ptr_to_stack or invalid ptr */
3496                 return check_stack_boundary(env, regno, access_size,
3497                                             zero_size_allowed, meta);
3498         }
3499 }
3500
3501 /* Implementation details:
3502  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
3503  * Two bpf_map_lookups (even with the same key) will have different reg->id.
3504  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
3505  * value_or_null->value transition, since the verifier only cares about
3506  * the range of access to valid map value pointer and doesn't care about actual
3507  * address of the map element.
3508  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
3509  * reg->id > 0 after value_or_null->value transition. By doing so
3510  * two bpf_map_lookups will be considered two different pointers that
3511  * point to different bpf_spin_locks.
3512  * The verifier allows taking only one bpf_spin_lock at a time to avoid
3513  * dead-locks.
3514  * Since only one bpf_spin_lock is allowed the checks are simpler than
3515  * reg_is_refcounted() logic. The verifier needs to remember only
3516  * one spin_lock instead of array of acquired_refs.
3517  * cur_state->active_spin_lock remembers which map value element got locked
3518  * and clears it after bpf_spin_unlock.
3519  */
3520 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
3521                              bool is_lock)
3522 {
3523         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
3524         struct bpf_verifier_state *cur = env->cur_state;
3525         bool is_const = tnum_is_const(reg->var_off);
3526         struct bpf_map *map = reg->map_ptr;
3527         u64 val = reg->var_off.value;
3528
3529         if (reg->type != PTR_TO_MAP_VALUE) {
3530                 verbose(env, "R%d is not a pointer to map_value\n", regno);
3531                 return -EINVAL;
3532         }
3533         if (!is_const) {
3534                 verbose(env,
3535                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
3536                         regno);
3537                 return -EINVAL;
3538         }
3539         if (!map->btf) {
3540                 verbose(env,
3541                         "map '%s' has to have BTF in order to use bpf_spin_lock\n",
3542                         map->name);
3543                 return -EINVAL;
3544         }
3545         if (!map_value_has_spin_lock(map)) {
3546                 if (map->spin_lock_off == -E2BIG)
3547                         verbose(env,
3548                                 "map '%s' has more than one 'struct bpf_spin_lock'\n",
3549                                 map->name);
3550                 else if (map->spin_lock_off == -ENOENT)
3551                         verbose(env,
3552                                 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
3553                                 map->name);
3554                 else
3555                         verbose(env,
3556                                 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
3557                                 map->name);
3558                 return -EINVAL;
3559         }
3560         if (map->spin_lock_off != val + reg->off) {
3561                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
3562                         val + reg->off);
3563                 return -EINVAL;
3564         }
3565         if (is_lock) {
3566                 if (cur->active_spin_lock) {
3567                         verbose(env,
3568                                 "Locking two bpf_spin_locks are not allowed\n");
3569                         return -EINVAL;
3570                 }
3571                 cur->active_spin_lock = reg->id;
3572         } else {
3573                 if (!cur->active_spin_lock) {
3574                         verbose(env, "bpf_spin_unlock without taking a lock\n");
3575                         return -EINVAL;
3576                 }
3577                 if (cur->active_spin_lock != reg->id) {
3578                         verbose(env, "bpf_spin_unlock of different lock\n");
3579                         return -EINVAL;
3580                 }
3581                 cur->active_spin_lock = 0;
3582         }
3583         return 0;
3584 }
3585
3586 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
3587 {
3588         return type == ARG_PTR_TO_MEM ||
3589                type == ARG_PTR_TO_MEM_OR_NULL ||
3590                type == ARG_PTR_TO_UNINIT_MEM;
3591 }
3592
3593 static bool arg_type_is_mem_size(enum bpf_arg_type type)
3594 {
3595         return type == ARG_CONST_SIZE ||
3596                type == ARG_CONST_SIZE_OR_ZERO;
3597 }
3598
3599 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
3600 {
3601         return type == ARG_PTR_TO_INT ||
3602                type == ARG_PTR_TO_LONG;
3603 }
3604
3605 static int int_ptr_type_to_size(enum bpf_arg_type type)
3606 {
3607         if (type == ARG_PTR_TO_INT)
3608                 return sizeof(u32);
3609         else if (type == ARG_PTR_TO_LONG)
3610                 return sizeof(u64);
3611
3612         return -EINVAL;
3613 }
3614
3615 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
3616                           enum bpf_arg_type arg_type,
3617                           struct bpf_call_arg_meta *meta)
3618 {
3619         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
3620         enum bpf_reg_type expected_type, type = reg->type;
3621         int err = 0;
3622
3623         if (arg_type == ARG_DONTCARE)
3624                 return 0;
3625
3626         err = check_reg_arg(env, regno, SRC_OP);
3627         if (err)
3628                 return err;
3629
3630         if (arg_type == ARG_ANYTHING) {
3631                 if (is_pointer_value(env, regno)) {
3632                         verbose(env, "R%d leaks addr into helper function\n",
3633                                 regno);
3634                         return -EACCES;
3635                 }
3636                 return 0;
3637         }
3638
3639         if (type_is_pkt_pointer(type) &&
3640             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
3641                 verbose(env, "helper access to the packet is not allowed\n");
3642                 return -EACCES;
3643         }
3644
3645         if (arg_type == ARG_PTR_TO_MAP_KEY ||
3646             arg_type == ARG_PTR_TO_MAP_VALUE ||
3647             arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
3648             arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
3649                 expected_type = PTR_TO_STACK;
3650                 if (register_is_null(reg) &&
3651                     arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL)
3652                         /* final test in check_stack_boundary() */;
3653                 else if (!type_is_pkt_pointer(type) &&
3654                          type != PTR_TO_MAP_VALUE &&
3655                          type != expected_type)
3656                         goto err_type;
3657         } else if (arg_type == ARG_CONST_SIZE ||
3658                    arg_type == ARG_CONST_SIZE_OR_ZERO) {
3659                 expected_type = SCALAR_VALUE;
3660                 if (type != expected_type)
3661                         goto err_type;
3662         } else if (arg_type == ARG_CONST_MAP_PTR) {
3663                 expected_type = CONST_PTR_TO_MAP;
3664                 if (type != expected_type)
3665                         goto err_type;
3666         } else if (arg_type == ARG_PTR_TO_CTX ||
3667                    arg_type == ARG_PTR_TO_CTX_OR_NULL) {
3668                 expected_type = PTR_TO_CTX;
3669                 if (!(register_is_null(reg) &&
3670                       arg_type == ARG_PTR_TO_CTX_OR_NULL)) {
3671                         if (type != expected_type)
3672                                 goto err_type;
3673                         err = check_ctx_reg(env, reg, regno);
3674                         if (err < 0)
3675                                 return err;
3676                 }
3677         } else if (arg_type == ARG_PTR_TO_SOCK_COMMON) {
3678                 expected_type = PTR_TO_SOCK_COMMON;
3679                 /* Any sk pointer can be ARG_PTR_TO_SOCK_COMMON */
3680                 if (!type_is_sk_pointer(type))
3681                         goto err_type;
3682                 if (reg->ref_obj_id) {
3683                         if (meta->ref_obj_id) {
3684                                 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
3685                                         regno, reg->ref_obj_id,
3686                                         meta->ref_obj_id);
3687                                 return -EFAULT;
3688                         }
3689                         meta->ref_obj_id = reg->ref_obj_id;
3690                 }
3691         } else if (arg_type == ARG_PTR_TO_SOCKET) {
3692                 expected_type = PTR_TO_SOCKET;
3693                 if (type != expected_type)
3694                         goto err_type;
3695         } else if (arg_type == ARG_PTR_TO_BTF_ID) {
3696                 expected_type = PTR_TO_BTF_ID;
3697                 if (type != expected_type)
3698                         goto err_type;
3699                 if (reg->btf_id != meta->btf_id) {
3700                         verbose(env, "Helper has type %s got %s in R%d\n",
3701                                 kernel_type_name(meta->btf_id),
3702                                 kernel_type_name(reg->btf_id), regno);
3703
3704                         return -EACCES;
3705                 }
3706                 if (!tnum_is_const(reg->var_off) || reg->var_off.value || reg->off) {
3707                         verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
3708                                 regno);
3709                         return -EACCES;
3710                 }
3711         } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
3712                 if (meta->func_id == BPF_FUNC_spin_lock) {
3713                         if (process_spin_lock(env, regno, true))
3714                                 return -EACCES;
3715                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
3716                         if (process_spin_lock(env, regno, false))
3717                                 return -EACCES;
3718                 } else {
3719                         verbose(env, "verifier internal error\n");
3720                         return -EFAULT;
3721                 }
3722         } else if (arg_type_is_mem_ptr(arg_type)) {
3723                 expected_type = PTR_TO_STACK;
3724                 /* One exception here. In case function allows for NULL to be
3725                  * passed in as argument, it's a SCALAR_VALUE type. Final test
3726                  * happens during stack boundary checking.
3727                  */
3728                 if (register_is_null(reg) &&
3729                     arg_type == ARG_PTR_TO_MEM_OR_NULL)
3730                         /* final test in check_stack_boundary() */;
3731                 else if (!type_is_pkt_pointer(type) &&
3732                          type != PTR_TO_MAP_VALUE &&
3733                          type != expected_type)
3734                         goto err_type;
3735                 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
3736         } else if (arg_type_is_int_ptr(arg_type)) {
3737                 expected_type = PTR_TO_STACK;
3738                 if (!type_is_pkt_pointer(type) &&
3739                     type != PTR_TO_MAP_VALUE &&
3740                     type != expected_type)
3741                         goto err_type;
3742         } else {
3743                 verbose(env, "unsupported arg_type %d\n", arg_type);
3744                 return -EFAULT;
3745         }
3746
3747         if (arg_type == ARG_CONST_MAP_PTR) {
3748                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
3749                 meta->map_ptr = reg->map_ptr;
3750         } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
3751                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
3752                  * check that [key, key + map->key_size) are within
3753                  * stack limits and initialized
3754                  */
3755                 if (!meta->map_ptr) {
3756                         /* in function declaration map_ptr must come before
3757                          * map_key, so that it's verified and known before
3758                          * we have to check map_key here. Otherwise it means
3759                          * that kernel subsystem misconfigured verifier
3760                          */
3761                         verbose(env, "invalid map_ptr to access map->key\n");
3762                         return -EACCES;
3763                 }
3764                 err = check_helper_mem_access(env, regno,
3765                                               meta->map_ptr->key_size, false,
3766                                               NULL);
3767         } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
3768                    (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
3769                     !register_is_null(reg)) ||
3770                    arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
3771                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
3772                  * check [value, value + map->value_size) validity
3773                  */
3774                 if (!meta->map_ptr) {
3775                         /* kernel subsystem misconfigured verifier */
3776                         verbose(env, "invalid map_ptr to access map->value\n");
3777                         return -EACCES;
3778                 }
3779                 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
3780                 err = check_helper_mem_access(env, regno,
3781                                               meta->map_ptr->value_size, false,
3782                                               meta);
3783         } else if (arg_type_is_mem_size(arg_type)) {
3784                 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
3785
3786                 /* This is used to refine r0 return value bounds for helpers
3787                  * that enforce this value as an upper bound on return values.
3788                  * See do_refine_retval_range() for helpers that can refine
3789                  * the return value. C type of helper is u32 so we pull register
3790                  * bound from umax_value however, if negative verifier errors
3791                  * out. Only upper bounds can be learned because retval is an
3792                  * int type and negative retvals are allowed.
3793                  */
3794                 meta->msize_max_value = reg->umax_value;
3795
3796                 /* The register is SCALAR_VALUE; the access check
3797                  * happens using its boundaries.
3798                  */
3799                 if (!tnum_is_const(reg->var_off))
3800                         /* For unprivileged variable accesses, disable raw
3801                          * mode so that the program is required to
3802                          * initialize all the memory that the helper could
3803                          * just partially fill up.
3804                          */
3805                         meta = NULL;
3806
3807                 if (reg->smin_value < 0) {
3808                         verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
3809                                 regno);
3810                         return -EACCES;
3811                 }
3812
3813                 if (reg->umin_value == 0) {
3814                         err = check_helper_mem_access(env, regno - 1, 0,
3815                                                       zero_size_allowed,
3816                                                       meta);
3817                         if (err)
3818                                 return err;
3819                 }
3820
3821                 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
3822                         verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
3823                                 regno);
3824                         return -EACCES;
3825                 }
3826                 err = check_helper_mem_access(env, regno - 1,
3827                                               reg->umax_value,
3828                                               zero_size_allowed, meta);
3829                 if (!err)
3830                         err = mark_chain_precision(env, regno);
3831         } else if (arg_type_is_int_ptr(arg_type)) {
3832                 int size = int_ptr_type_to_size(arg_type);
3833
3834                 err = check_helper_mem_access(env, regno, size, false, meta);
3835                 if (err)
3836                         return err;
3837                 err = check_ptr_alignment(env, reg, 0, size, true);
3838         }
3839
3840         return err;
3841 err_type:
3842         verbose(env, "R%d type=%s expected=%s\n", regno,
3843                 reg_type_str[type], reg_type_str[expected_type]);
3844         return -EACCES;
3845 }
3846
3847 static int check_map_func_compatibility(struct bpf_verifier_env *env,
3848                                         struct bpf_map *map, int func_id)
3849 {
3850         if (!map)
3851                 return 0;
3852
3853         /* We need a two way check, first is from map perspective ... */
3854         switch (map->map_type) {
3855         case BPF_MAP_TYPE_PROG_ARRAY:
3856                 if (func_id != BPF_FUNC_tail_call)
3857                         goto error;
3858                 break;
3859         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
3860                 if (func_id != BPF_FUNC_perf_event_read &&
3861                     func_id != BPF_FUNC_perf_event_output &&
3862                     func_id != BPF_FUNC_skb_output &&
3863                     func_id != BPF_FUNC_perf_event_read_value &&
3864                     func_id != BPF_FUNC_xdp_output)
3865                         goto error;
3866                 break;
3867         case BPF_MAP_TYPE_STACK_TRACE:
3868                 if (func_id != BPF_FUNC_get_stackid)
3869                         goto error;
3870                 break;
3871         case BPF_MAP_TYPE_CGROUP_ARRAY:
3872                 if (func_id != BPF_FUNC_skb_under_cgroup &&
3873                     func_id != BPF_FUNC_current_task_under_cgroup)
3874                         goto error;
3875                 break;
3876         case BPF_MAP_TYPE_CGROUP_STORAGE:
3877         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
3878                 if (func_id != BPF_FUNC_get_local_storage)
3879                         goto error;
3880                 break;
3881         case BPF_MAP_TYPE_DEVMAP:
3882         case BPF_MAP_TYPE_DEVMAP_HASH:
3883                 if (func_id != BPF_FUNC_redirect_map &&
3884                     func_id != BPF_FUNC_map_lookup_elem)
3885                         goto error;
3886                 break;
3887         /* Restrict bpf side of cpumap and xskmap, open when use-cases
3888          * appear.
3889          */
3890         case BPF_MAP_TYPE_CPUMAP:
3891                 if (func_id != BPF_FUNC_redirect_map)
3892                         goto error;
3893                 break;
3894         case BPF_MAP_TYPE_XSKMAP:
3895                 if (func_id != BPF_FUNC_redirect_map &&
3896                     func_id != BPF_FUNC_map_lookup_elem)
3897                         goto error;
3898                 break;
3899         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
3900         case BPF_MAP_TYPE_HASH_OF_MAPS:
3901                 if (func_id != BPF_FUNC_map_lookup_elem)
3902                         goto error;
3903                 break;
3904         case BPF_MAP_TYPE_SOCKMAP:
3905                 if (func_id != BPF_FUNC_sk_redirect_map &&
3906                     func_id != BPF_FUNC_sock_map_update &&
3907                     func_id != BPF_FUNC_map_delete_elem &&
3908                     func_id != BPF_FUNC_msg_redirect_map &&
3909                     func_id != BPF_FUNC_sk_select_reuseport)
3910                         goto error;
3911                 break;
3912         case BPF_MAP_TYPE_SOCKHASH:
3913                 if (func_id != BPF_FUNC_sk_redirect_hash &&
3914                     func_id != BPF_FUNC_sock_hash_update &&
3915                     func_id != BPF_FUNC_map_delete_elem &&
3916                     func_id != BPF_FUNC_msg_redirect_hash &&
3917                     func_id != BPF_FUNC_sk_select_reuseport)
3918                         goto error;
3919                 break;
3920         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
3921                 if (func_id != BPF_FUNC_sk_select_reuseport)
3922                         goto error;
3923                 break;
3924         case BPF_MAP_TYPE_QUEUE:
3925         case BPF_MAP_TYPE_STACK:
3926                 if (func_id != BPF_FUNC_map_peek_elem &&
3927                     func_id != BPF_FUNC_map_pop_elem &&
3928                     func_id != BPF_FUNC_map_push_elem)
3929                         goto error;
3930                 break;
3931         case BPF_MAP_TYPE_SK_STORAGE:
3932                 if (func_id != BPF_FUNC_sk_storage_get &&
3933                     func_id != BPF_FUNC_sk_storage_delete)
3934                         goto error;
3935                 break;
3936         default:
3937                 break;
3938         }
3939
3940         /* ... and second from the function itself. */
3941         switch (func_id) {
3942         case BPF_FUNC_tail_call:
3943                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
3944                         goto error;
3945                 if (env->subprog_cnt > 1) {
3946                         verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
3947                         return -EINVAL;
3948                 }
3949                 break;
3950         case BPF_FUNC_perf_event_read:
3951         case BPF_FUNC_perf_event_output:
3952         case BPF_FUNC_perf_event_read_value:
3953         case BPF_FUNC_skb_output:
3954         case BPF_FUNC_xdp_output:
3955                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
3956                         goto error;
3957                 break;
3958         case BPF_FUNC_get_stackid:
3959                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
3960                         goto error;
3961                 break;
3962         case BPF_FUNC_current_task_under_cgroup:
3963         case BPF_FUNC_skb_under_cgroup:
3964                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
3965                         goto error;
3966                 break;
3967         case BPF_FUNC_redirect_map:
3968                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
3969                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
3970                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
3971                     map->map_type != BPF_MAP_TYPE_XSKMAP)
3972                         goto error;
3973                 break;
3974         case BPF_FUNC_sk_redirect_map:
3975         case BPF_FUNC_msg_redirect_map:
3976         case BPF_FUNC_sock_map_update:
3977                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
3978                         goto error;
3979                 break;
3980         case BPF_FUNC_sk_redirect_hash:
3981         case BPF_FUNC_msg_redirect_hash:
3982         case BPF_FUNC_sock_hash_update:
3983                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
3984                         goto error;
3985                 break;
3986         case BPF_FUNC_get_local_storage:
3987                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
3988                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
3989                         goto error;
3990                 break;
3991         case BPF_FUNC_sk_select_reuseport:
3992                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
3993                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
3994                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
3995                         goto error;
3996                 break;
3997         case BPF_FUNC_map_peek_elem:
3998         case BPF_FUNC_map_pop_elem:
3999         case BPF_FUNC_map_push_elem:
4000                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
4001                     map->map_type != BPF_MAP_TYPE_STACK)
4002                         goto error;
4003                 break;
4004         case BPF_FUNC_sk_storage_get:
4005         case BPF_FUNC_sk_storage_delete:
4006                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
4007                         goto error;
4008                 break;
4009         default:
4010                 break;
4011         }
4012
4013         return 0;
4014 error:
4015         verbose(env, "cannot pass map_type %d into func %s#%d\n",
4016                 map->map_type, func_id_name(func_id), func_id);
4017         return -EINVAL;
4018 }
4019
4020 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
4021 {
4022         int count = 0;
4023
4024         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
4025                 count++;
4026         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
4027                 count++;
4028         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
4029                 count++;
4030         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
4031                 count++;
4032         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
4033                 count++;
4034
4035         /* We only support one arg being in raw mode at the moment,
4036          * which is sufficient for the helper functions we have
4037          * right now.
4038          */
4039         return count <= 1;
4040 }
4041
4042 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
4043                                     enum bpf_arg_type arg_next)
4044 {
4045         return (arg_type_is_mem_ptr(arg_curr) &&
4046                 !arg_type_is_mem_size(arg_next)) ||
4047                (!arg_type_is_mem_ptr(arg_curr) &&
4048                 arg_type_is_mem_size(arg_next));
4049 }
4050
4051 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
4052 {
4053         /* bpf_xxx(..., buf, len) call will access 'len'
4054          * bytes from memory 'buf'. Both arg types need
4055          * to be paired, so make sure there's no buggy
4056          * helper function specification.
4057          */
4058         if (arg_type_is_mem_size(fn->arg1_type) ||
4059             arg_type_is_mem_ptr(fn->arg5_type)  ||
4060             check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
4061             check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
4062             check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
4063             check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
4064                 return false;
4065
4066         return true;
4067 }
4068
4069 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
4070 {
4071         int count = 0;
4072
4073         if (arg_type_may_be_refcounted(fn->arg1_type))
4074                 count++;
4075         if (arg_type_may_be_refcounted(fn->arg2_type))
4076                 count++;
4077         if (arg_type_may_be_refcounted(fn->arg3_type))
4078                 count++;
4079         if (arg_type_may_be_refcounted(fn->arg4_type))
4080                 count++;
4081         if (arg_type_may_be_refcounted(fn->arg5_type))
4082                 count++;
4083
4084         /* A reference acquiring function cannot acquire
4085          * another refcounted ptr.
4086          */
4087         if (is_acquire_function(func_id) && count)
4088                 return false;
4089
4090         /* We only support one arg being unreferenced at the moment,
4091          * which is sufficient for the helper functions we have right now.
4092          */
4093         return count <= 1;
4094 }
4095
4096 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
4097 {
4098         return check_raw_mode_ok(fn) &&
4099                check_arg_pair_ok(fn) &&
4100                check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
4101 }
4102
4103 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
4104  * are now invalid, so turn them into unknown SCALAR_VALUE.
4105  */
4106 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
4107                                      struct bpf_func_state *state)
4108 {
4109         struct bpf_reg_state *regs = state->regs, *reg;
4110         int i;
4111
4112         for (i = 0; i < MAX_BPF_REG; i++)
4113                 if (reg_is_pkt_pointer_any(&regs[i]))
4114                         mark_reg_unknown(env, regs, i);
4115
4116         bpf_for_each_spilled_reg(i, state, reg) {
4117                 if (!reg)
4118                         continue;
4119                 if (reg_is_pkt_pointer_any(reg))
4120                         __mark_reg_unknown(env, reg);
4121         }
4122 }
4123
4124 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
4125 {
4126         struct bpf_verifier_state *vstate = env->cur_state;
4127         int i;
4128
4129         for (i = 0; i <= vstate->curframe; i++)
4130                 __clear_all_pkt_pointers(env, vstate->frame[i]);
4131 }
4132
4133 static void release_reg_references(struct bpf_verifier_env *env,
4134                                    struct bpf_func_state *state,
4135                                    int ref_obj_id)
4136 {
4137         struct bpf_reg_state *regs = state->regs, *reg;
4138         int i;
4139
4140         for (i = 0; i < MAX_BPF_REG; i++)
4141                 if (regs[i].ref_obj_id == ref_obj_id)
4142                         mark_reg_unknown(env, regs, i);
4143
4144         bpf_for_each_spilled_reg(i, state, reg) {
4145                 if (!reg)
4146                         continue;
4147                 if (reg->ref_obj_id == ref_obj_id)
4148                         __mark_reg_unknown(env, reg);
4149         }
4150 }
4151
4152 /* The pointer with the specified id has released its reference to kernel
4153  * resources. Identify all copies of the same pointer and clear the reference.
4154  */
4155 static int release_reference(struct bpf_verifier_env *env,
4156                              int ref_obj_id)
4157 {
4158         struct bpf_verifier_state *vstate = env->cur_state;
4159         int err;
4160         int i;
4161
4162         err = release_reference_state(cur_func(env), ref_obj_id);
4163         if (err)
4164                 return err;
4165
4166         for (i = 0; i <= vstate->curframe; i++)
4167                 release_reg_references(env, vstate->frame[i], ref_obj_id);
4168
4169         return 0;
4170 }
4171
4172 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
4173                                     struct bpf_reg_state *regs)
4174 {
4175         int i;
4176
4177         /* after the call registers r0 - r5 were scratched */
4178         for (i = 0; i < CALLER_SAVED_REGS; i++) {
4179                 mark_reg_not_init(env, regs, caller_saved[i]);
4180                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4181         }
4182 }
4183
4184 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
4185                            int *insn_idx)
4186 {
4187         struct bpf_verifier_state *state = env->cur_state;
4188         struct bpf_func_info_aux *func_info_aux;
4189         struct bpf_func_state *caller, *callee;
4190         int i, err, subprog, target_insn;
4191         bool is_global = false;
4192
4193         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
4194                 verbose(env, "the call stack of %d frames is too deep\n",
4195                         state->curframe + 2);
4196                 return -E2BIG;
4197         }
4198
4199         target_insn = *insn_idx + insn->imm;
4200         subprog = find_subprog(env, target_insn + 1);
4201         if (subprog < 0) {
4202                 verbose(env, "verifier bug. No program starts at insn %d\n",
4203                         target_insn + 1);
4204                 return -EFAULT;
4205         }
4206
4207         caller = state->frame[state->curframe];
4208         if (state->frame[state->curframe + 1]) {
4209                 verbose(env, "verifier bug. Frame %d already allocated\n",
4210                         state->curframe + 1);
4211                 return -EFAULT;
4212         }
4213
4214         func_info_aux = env->prog->aux->func_info_aux;
4215         if (func_info_aux)
4216                 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
4217         err = btf_check_func_arg_match(env, subprog, caller->regs);
4218         if (err == -EFAULT)
4219                 return err;
4220         if (is_global) {
4221                 if (err) {
4222                         verbose(env, "Caller passes invalid args into func#%d\n",
4223                                 subprog);
4224                         return err;
4225                 } else {
4226                         if (env->log.level & BPF_LOG_LEVEL)
4227                                 verbose(env,
4228                                         "Func#%d is global and valid. Skipping.\n",
4229                                         subprog);
4230                         clear_caller_saved_regs(env, caller->regs);
4231
4232                         /* All global functions return SCALAR_VALUE */
4233                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
4234
4235                         /* continue with next insn after call */
4236                         return 0;
4237                 }
4238         }
4239
4240         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
4241         if (!callee)
4242                 return -ENOMEM;
4243         state->frame[state->curframe + 1] = callee;
4244
4245         /* callee cannot access r0, r6 - r9 for reading and has to write
4246          * into its own stack before reading from it.
4247          * callee can read/write into caller's stack
4248          */
4249         init_func_state(env, callee,
4250                         /* remember the callsite, it will be used by bpf_exit */
4251                         *insn_idx /* callsite */,
4252                         state->curframe + 1 /* frameno within this callchain */,
4253                         subprog /* subprog number within this prog */);
4254
4255         /* Transfer references to the callee */
4256         err = transfer_reference_state(callee, caller);
4257         if (err)
4258                 return err;
4259
4260         /* copy r1 - r5 args that callee can access.  The copy includes parent
4261          * pointers, which connects us up to the liveness chain
4262          */
4263         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4264                 callee->regs[i] = caller->regs[i];
4265
4266         clear_caller_saved_regs(env, caller->regs);
4267
4268         /* only increment it after check_reg_arg() finished */
4269         state->curframe++;
4270
4271         /* and go analyze first insn of the callee */
4272         *insn_idx = target_insn;
4273
4274         if (env->log.level & BPF_LOG_LEVEL) {
4275                 verbose(env, "caller:\n");
4276                 print_verifier_state(env, caller);
4277                 verbose(env, "callee:\n");
4278                 print_verifier_state(env, callee);
4279         }
4280         return 0;
4281 }
4282
4283 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
4284 {
4285         struct bpf_verifier_state *state = env->cur_state;
4286         struct bpf_func_state *caller, *callee;
4287         struct bpf_reg_state *r0;
4288         int err;
4289
4290         callee = state->frame[state->curframe];
4291         r0 = &callee->regs[BPF_REG_0];
4292         if (r0->type == PTR_TO_STACK) {
4293                 /* technically it's ok to return caller's stack pointer
4294                  * (or caller's caller's pointer) back to the caller,
4295                  * since these pointers are valid. Only current stack
4296                  * pointer will be invalid as soon as function exits,
4297                  * but let's be conservative
4298                  */
4299                 verbose(env, "cannot return stack pointer to the caller\n");
4300                 return -EINVAL;
4301         }
4302
4303         state->curframe--;
4304         caller = state->frame[state->curframe];
4305         /* return to the caller whatever r0 had in the callee */
4306         caller->regs[BPF_REG_0] = *r0;
4307
4308         /* Transfer references to the caller */
4309         err = transfer_reference_state(caller, callee);
4310         if (err)
4311                 return err;
4312
4313         *insn_idx = callee->callsite + 1;
4314         if (env->log.level & BPF_LOG_LEVEL) {
4315                 verbose(env, "returning from callee:\n");
4316                 print_verifier_state(env, callee);
4317                 verbose(env, "to caller at %d:\n", *insn_idx);
4318                 print_verifier_state(env, caller);
4319         }
4320         /* clear everything in the callee */
4321         free_func_state(callee);
4322         state->frame[state->curframe + 1] = NULL;
4323         return 0;
4324 }
4325
4326 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
4327                                    int func_id,
4328                                    struct bpf_call_arg_meta *meta)
4329 {
4330         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
4331
4332         if (ret_type != RET_INTEGER ||
4333             (func_id != BPF_FUNC_get_stack &&
4334              func_id != BPF_FUNC_probe_read_str))
4335                 return;
4336
4337         ret_reg->smax_value = meta->msize_max_value;
4338         __reg_deduce_bounds(ret_reg);
4339         __reg_bound_offset(ret_reg);
4340         __update_reg_bounds(ret_reg);
4341 }
4342
4343 static int
4344 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4345                 int func_id, int insn_idx)
4346 {
4347         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
4348         struct bpf_map *map = meta->map_ptr;
4349
4350         if (func_id != BPF_FUNC_tail_call &&
4351             func_id != BPF_FUNC_map_lookup_elem &&
4352             func_id != BPF_FUNC_map_update_elem &&
4353             func_id != BPF_FUNC_map_delete_elem &&
4354             func_id != BPF_FUNC_map_push_elem &&
4355             func_id != BPF_FUNC_map_pop_elem &&
4356             func_id != BPF_FUNC_map_peek_elem)
4357                 return 0;
4358
4359         if (map == NULL) {
4360                 verbose(env, "kernel subsystem misconfigured verifier\n");
4361                 return -EINVAL;
4362         }
4363
4364         /* In case of read-only, some additional restrictions
4365          * need to be applied in order to prevent altering the
4366          * state of the map from program side.
4367          */
4368         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
4369             (func_id == BPF_FUNC_map_delete_elem ||
4370              func_id == BPF_FUNC_map_update_elem ||
4371              func_id == BPF_FUNC_map_push_elem ||
4372              func_id == BPF_FUNC_map_pop_elem)) {
4373                 verbose(env, "write into map forbidden\n");
4374                 return -EACCES;
4375         }
4376
4377         if (!BPF_MAP_PTR(aux->map_ptr_state))
4378                 bpf_map_ptr_store(aux, meta->map_ptr,
4379                                   meta->map_ptr->unpriv_array);
4380         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
4381                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
4382                                   meta->map_ptr->unpriv_array);
4383         return 0;
4384 }
4385
4386 static int
4387 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4388                 int func_id, int insn_idx)
4389 {
4390         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
4391         struct bpf_reg_state *regs = cur_regs(env), *reg;
4392         struct bpf_map *map = meta->map_ptr;
4393         struct tnum range;
4394         u64 val;
4395         int err;
4396
4397         if (func_id != BPF_FUNC_tail_call)
4398                 return 0;
4399         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
4400                 verbose(env, "kernel subsystem misconfigured verifier\n");
4401                 return -EINVAL;
4402         }
4403
4404         range = tnum_range(0, map->max_entries - 1);
4405         reg = &regs[BPF_REG_3];
4406
4407         if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
4408                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4409                 return 0;
4410         }
4411
4412         err = mark_chain_precision(env, BPF_REG_3);
4413         if (err)
4414                 return err;
4415
4416         val = reg->var_off.value;
4417         if (bpf_map_key_unseen(aux))
4418                 bpf_map_key_store(aux, val);
4419         else if (!bpf_map_key_poisoned(aux) &&
4420                   bpf_map_key_immediate(aux) != val)
4421                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4422         return 0;
4423 }
4424
4425 static int check_reference_leak(struct bpf_verifier_env *env)
4426 {
4427         struct bpf_func_state *state = cur_func(env);
4428         int i;
4429
4430         for (i = 0; i < state->acquired_refs; i++) {
4431                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
4432                         state->refs[i].id, state->refs[i].insn_idx);
4433         }
4434         return state->acquired_refs ? -EINVAL : 0;
4435 }
4436
4437 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
4438 {
4439         const struct bpf_func_proto *fn = NULL;
4440         struct bpf_reg_state *regs;
4441         struct bpf_call_arg_meta meta;
4442         bool changes_data;
4443         int i, err;
4444
4445         /* find function prototype */
4446         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
4447                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
4448                         func_id);
4449                 return -EINVAL;
4450         }
4451
4452         if (env->ops->get_func_proto)
4453                 fn = env->ops->get_func_proto(func_id, env->prog);
4454         if (!fn) {
4455                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
4456                         func_id);
4457                 return -EINVAL;
4458         }
4459
4460         /* eBPF programs must be GPL compatible to use GPL-ed functions */
4461         if (!env->prog->gpl_compatible && fn->gpl_only) {
4462                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
4463                 return -EINVAL;
4464         }
4465
4466         /* With LD_ABS/IND some JITs save/restore skb from r1. */
4467         changes_data = bpf_helper_changes_pkt_data(fn->func);
4468         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
4469                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
4470                         func_id_name(func_id), func_id);
4471                 return -EINVAL;
4472         }
4473
4474         memset(&meta, 0, sizeof(meta));
4475         meta.pkt_access = fn->pkt_access;
4476
4477         err = check_func_proto(fn, func_id);
4478         if (err) {
4479                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
4480                         func_id_name(func_id), func_id);
4481                 return err;
4482         }
4483
4484         meta.func_id = func_id;
4485         /* check args */
4486         for (i = 0; i < 5; i++) {
4487                 err = btf_resolve_helper_id(&env->log, fn, i);
4488                 if (err > 0)
4489                         meta.btf_id = err;
4490                 err = check_func_arg(env, BPF_REG_1 + i, fn->arg_type[i], &meta);
4491                 if (err)
4492                         return err;
4493         }
4494
4495         err = record_func_map(env, &meta, func_id, insn_idx);
4496         if (err)
4497                 return err;
4498
4499         err = record_func_key(env, &meta, func_id, insn_idx);
4500         if (err)
4501                 return err;
4502
4503         /* Mark slots with STACK_MISC in case of raw mode, stack offset
4504          * is inferred from register state.
4505          */
4506         for (i = 0; i < meta.access_size; i++) {
4507                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
4508                                        BPF_WRITE, -1, false);
4509                 if (err)
4510                         return err;
4511         }
4512
4513         if (func_id == BPF_FUNC_tail_call) {
4514                 err = check_reference_leak(env);
4515                 if (err) {
4516                         verbose(env, "tail_call would lead to reference leak\n");
4517                         return err;
4518                 }
4519         } else if (is_release_function(func_id)) {
4520                 err = release_reference(env, meta.ref_obj_id);
4521                 if (err) {
4522                         verbose(env, "func %s#%d reference has not been acquired before\n",
4523                                 func_id_name(func_id), func_id);
4524                         return err;
4525                 }
4526         }
4527
4528         regs = cur_regs(env);
4529
4530         /* check that flags argument in get_local_storage(map, flags) is 0,
4531          * this is required because get_local_storage() can't return an error.
4532          */
4533         if (func_id == BPF_FUNC_get_local_storage &&
4534             !register_is_null(&regs[BPF_REG_2])) {
4535                 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
4536                 return -EINVAL;
4537         }
4538
4539         /* reset caller saved regs */
4540         for (i = 0; i < CALLER_SAVED_REGS; i++) {
4541                 mark_reg_not_init(env, regs, caller_saved[i]);
4542                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4543         }
4544
4545         /* helper call returns 64-bit value. */
4546         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
4547
4548         /* update return register (already marked as written above) */
4549         if (fn->ret_type == RET_INTEGER) {
4550                 /* sets type to SCALAR_VALUE */
4551                 mark_reg_unknown(env, regs, BPF_REG_0);
4552         } else if (fn->ret_type == RET_VOID) {
4553                 regs[BPF_REG_0].type = NOT_INIT;
4554         } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
4555                    fn->ret_type == RET_PTR_TO_MAP_VALUE) {
4556                 /* There is no offset yet applied, variable or fixed */
4557                 mark_reg_known_zero(env, regs, BPF_REG_0);
4558                 /* remember map_ptr, so that check_map_access()
4559                  * can check 'value_size' boundary of memory access
4560                  * to map element returned from bpf_map_lookup_elem()
4561                  */
4562                 if (meta.map_ptr == NULL) {
4563                         verbose(env,
4564                                 "kernel subsystem misconfigured verifier\n");
4565                         return -EINVAL;
4566                 }
4567                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
4568                 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
4569                         regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
4570                         if (map_value_has_spin_lock(meta.map_ptr))
4571                                 regs[BPF_REG_0].id = ++env->id_gen;
4572                 } else {
4573                         regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
4574                         regs[BPF_REG_0].id = ++env->id_gen;
4575                 }
4576         } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
4577                 mark_reg_known_zero(env, regs, BPF_REG_0);
4578                 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
4579                 regs[BPF_REG_0].id = ++env->id_gen;
4580         } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
4581                 mark_reg_known_zero(env, regs, BPF_REG_0);
4582                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
4583                 regs[BPF_REG_0].id = ++env->id_gen;
4584         } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
4585                 mark_reg_known_zero(env, regs, BPF_REG_0);
4586                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
4587                 regs[BPF_REG_0].id = ++env->id_gen;
4588         } else {
4589                 verbose(env, "unknown return type %d of func %s#%d\n",
4590                         fn->ret_type, func_id_name(func_id), func_id);
4591                 return -EINVAL;
4592         }
4593
4594         if (is_ptr_cast_function(func_id)) {
4595                 /* For release_reference() */
4596                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
4597         } else if (is_acquire_function(func_id)) {
4598                 int id = acquire_reference_state(env, insn_idx);
4599
4600                 if (id < 0)
4601                         return id;
4602                 /* For mark_ptr_or_null_reg() */
4603                 regs[BPF_REG_0].id = id;
4604                 /* For release_reference() */
4605                 regs[BPF_REG_0].ref_obj_id = id;
4606         }
4607
4608         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
4609
4610         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
4611         if (err)
4612                 return err;
4613
4614         if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) {
4615                 const char *err_str;
4616
4617 #ifdef CONFIG_PERF_EVENTS
4618                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
4619                 err_str = "cannot get callchain buffer for func %s#%d\n";
4620 #else
4621                 err = -ENOTSUPP;
4622                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
4623 #endif
4624                 if (err) {
4625                         verbose(env, err_str, func_id_name(func_id), func_id);
4626                         return err;
4627                 }
4628
4629                 env->prog->has_callchain_buf = true;
4630         }
4631
4632         if (changes_data)
4633                 clear_all_pkt_pointers(env);
4634         return 0;
4635 }
4636
4637 static bool signed_add_overflows(s64 a, s64 b)
4638 {
4639         /* Do the add in u64, where overflow is well-defined */
4640         s64 res = (s64)((u64)a + (u64)b);
4641
4642         if (b < 0)
4643                 return res > a;
4644         return res < a;
4645 }
4646
4647 static bool signed_add32_overflows(s64 a, s64 b)
4648 {
4649         /* Do the add in u32, where overflow is well-defined */
4650         s32 res = (s32)((u32)a + (u32)b);
4651
4652         if (b < 0)
4653                 return res > a;
4654         return res < a;
4655 }
4656
4657 static bool signed_sub_overflows(s32 a, s32 b)
4658 {
4659         /* Do the sub in u64, where overflow is well-defined */
4660         s64 res = (s64)((u64)a - (u64)b);
4661
4662         if (b < 0)
4663                 return res < a;
4664         return res > a;
4665 }
4666
4667 static bool signed_sub32_overflows(s32 a, s32 b)
4668 {
4669         /* Do the sub in u64, where overflow is well-defined */
4670         s32 res = (s32)((u32)a - (u32)b);
4671
4672         if (b < 0)
4673                 return res < a;
4674         return res > a;
4675 }
4676
4677 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
4678                                   const struct bpf_reg_state *reg,
4679                                   enum bpf_reg_type type)
4680 {
4681         bool known = tnum_is_const(reg->var_off);
4682         s64 val = reg->var_off.value;
4683         s64 smin = reg->smin_value;
4684
4685         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
4686                 verbose(env, "math between %s pointer and %lld is not allowed\n",
4687                         reg_type_str[type], val);
4688                 return false;
4689         }
4690
4691         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
4692                 verbose(env, "%s pointer offset %d is not allowed\n",
4693                         reg_type_str[type], reg->off);
4694                 return false;
4695         }
4696
4697         if (smin == S64_MIN) {
4698                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
4699                         reg_type_str[type]);
4700                 return false;
4701         }
4702
4703         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
4704                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
4705                         smin, reg_type_str[type]);
4706                 return false;
4707         }
4708
4709         return true;
4710 }
4711
4712 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
4713 {
4714         return &env->insn_aux_data[env->insn_idx];
4715 }
4716
4717 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
4718                               u32 *ptr_limit, u8 opcode, bool off_is_neg)
4719 {
4720         bool mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
4721                             (opcode == BPF_SUB && !off_is_neg);
4722         u32 off;
4723
4724         switch (ptr_reg->type) {
4725         case PTR_TO_STACK:
4726                 /* Indirect variable offset stack access is prohibited in
4727                  * unprivileged mode so it's not handled here.
4728                  */
4729                 off = ptr_reg->off + ptr_reg->var_off.value;
4730                 if (mask_to_left)
4731                         *ptr_limit = MAX_BPF_STACK + off;
4732                 else
4733                         *ptr_limit = -off;
4734                 return 0;
4735         case PTR_TO_MAP_VALUE:
4736                 if (mask_to_left) {
4737                         *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
4738                 } else {
4739                         off = ptr_reg->smin_value + ptr_reg->off;
4740                         *ptr_limit = ptr_reg->map_ptr->value_size - off;
4741                 }
4742                 return 0;
4743         default:
4744                 return -EINVAL;
4745         }
4746 }
4747
4748 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
4749                                     const struct bpf_insn *insn)
4750 {
4751         return env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K;
4752 }
4753
4754 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
4755                                        u32 alu_state, u32 alu_limit)
4756 {
4757         /* If we arrived here from different branches with different
4758          * state or limits to sanitize, then this won't work.
4759          */
4760         if (aux->alu_state &&
4761             (aux->alu_state != alu_state ||
4762              aux->alu_limit != alu_limit))
4763                 return -EACCES;
4764
4765         /* Corresponding fixup done in fixup_bpf_calls(). */
4766         aux->alu_state = alu_state;
4767         aux->alu_limit = alu_limit;
4768         return 0;
4769 }
4770
4771 static int sanitize_val_alu(struct bpf_verifier_env *env,
4772                             struct bpf_insn *insn)
4773 {
4774         struct bpf_insn_aux_data *aux = cur_aux(env);
4775
4776         if (can_skip_alu_sanitation(env, insn))
4777                 return 0;
4778
4779         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
4780 }
4781
4782 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
4783                             struct bpf_insn *insn,
4784                             const struct bpf_reg_state *ptr_reg,
4785                             struct bpf_reg_state *dst_reg,
4786                             bool off_is_neg)
4787 {
4788         struct bpf_verifier_state *vstate = env->cur_state;
4789         struct bpf_insn_aux_data *aux = cur_aux(env);
4790         bool ptr_is_dst_reg = ptr_reg == dst_reg;
4791         u8 opcode = BPF_OP(insn->code);
4792         u32 alu_state, alu_limit;
4793         struct bpf_reg_state tmp;
4794         bool ret;
4795
4796         if (can_skip_alu_sanitation(env, insn))
4797                 return 0;
4798
4799         /* We already marked aux for masking from non-speculative
4800          * paths, thus we got here in the first place. We only care
4801          * to explore bad access from here.
4802          */
4803         if (vstate->speculative)
4804                 goto do_sim;
4805
4806         alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
4807         alu_state |= ptr_is_dst_reg ?
4808                      BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
4809
4810         if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
4811                 return 0;
4812         if (update_alu_sanitation_state(aux, alu_state, alu_limit))
4813                 return -EACCES;
4814 do_sim:
4815         /* Simulate and find potential out-of-bounds access under
4816          * speculative execution from truncation as a result of
4817          * masking when off was not within expected range. If off
4818          * sits in dst, then we temporarily need to move ptr there
4819          * to simulate dst (== 0) +/-= ptr. Needed, for example,
4820          * for cases where we use K-based arithmetic in one direction
4821          * and truncated reg-based in the other in order to explore
4822          * bad access.
4823          */
4824         if (!ptr_is_dst_reg) {
4825                 tmp = *dst_reg;
4826                 *dst_reg = *ptr_reg;
4827         }
4828         ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
4829         if (!ptr_is_dst_reg && ret)
4830                 *dst_reg = tmp;
4831         return !ret ? -EFAULT : 0;
4832 }
4833
4834 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
4835  * Caller should also handle BPF_MOV case separately.
4836  * If we return -EACCES, caller may want to try again treating pointer as a
4837  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
4838  */
4839 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
4840                                    struct bpf_insn *insn,
4841                                    const struct bpf_reg_state *ptr_reg,
4842                                    const struct bpf_reg_state *off_reg)
4843 {
4844         struct bpf_verifier_state *vstate = env->cur_state;
4845         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4846         struct bpf_reg_state *regs = state->regs, *dst_reg;
4847         bool known = tnum_is_const(off_reg->var_off);
4848         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
4849             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
4850         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
4851             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
4852         u32 dst = insn->dst_reg, src = insn->src_reg;
4853         u8 opcode = BPF_OP(insn->code);
4854         int ret;
4855
4856         dst_reg = &regs[dst];
4857
4858         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
4859             smin_val > smax_val || umin_val > umax_val) {
4860                 /* Taint dst register if offset had invalid bounds derived from
4861                  * e.g. dead branches.
4862                  */
4863                 __mark_reg_unknown(env, dst_reg);
4864                 return 0;
4865         }
4866
4867         if (BPF_CLASS(insn->code) != BPF_ALU64) {
4868                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
4869                 verbose(env,
4870                         "R%d 32-bit pointer arithmetic prohibited\n",
4871                         dst);
4872                 return -EACCES;
4873         }
4874
4875         switch (ptr_reg->type) {
4876         case PTR_TO_MAP_VALUE_OR_NULL:
4877                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
4878                         dst, reg_type_str[ptr_reg->type]);
4879                 return -EACCES;
4880         case CONST_PTR_TO_MAP:
4881         case PTR_TO_PACKET_END:
4882         case PTR_TO_SOCKET:
4883         case PTR_TO_SOCKET_OR_NULL:
4884         case PTR_TO_SOCK_COMMON:
4885         case PTR_TO_SOCK_COMMON_OR_NULL:
4886         case PTR_TO_TCP_SOCK:
4887         case PTR_TO_TCP_SOCK_OR_NULL:
4888         case PTR_TO_XDP_SOCK:
4889                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
4890                         dst, reg_type_str[ptr_reg->type]);
4891                 return -EACCES;
4892         case PTR_TO_MAP_VALUE:
4893                 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
4894                         verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
4895                                 off_reg == dst_reg ? dst : src);
4896                         return -EACCES;
4897                 }
4898                 /* fall-through */
4899         default:
4900                 break;
4901         }
4902
4903         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
4904          * The id may be overwritten later if we create a new variable offset.
4905          */
4906         dst_reg->type = ptr_reg->type;
4907         dst_reg->id = ptr_reg->id;
4908
4909         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
4910             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
4911                 return -EINVAL;
4912
4913         /* pointer types do not carry 32-bit bounds at the moment. */
4914         __mark_reg32_unbounded(dst_reg);
4915
4916         switch (opcode) {
4917         case BPF_ADD:
4918                 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
4919                 if (ret < 0) {
4920                         verbose(env, "R%d tried to add from different maps or paths\n", dst);
4921                         return ret;
4922                 }
4923                 /* We can take a fixed offset as long as it doesn't overflow
4924                  * the s32 'off' field
4925                  */
4926                 if (known && (ptr_reg->off + smin_val ==
4927                               (s64)(s32)(ptr_reg->off + smin_val))) {
4928                         /* pointer += K.  Accumulate it into fixed offset */
4929                         dst_reg->smin_value = smin_ptr;
4930                         dst_reg->smax_value = smax_ptr;
4931                         dst_reg->umin_value = umin_ptr;
4932                         dst_reg->umax_value = umax_ptr;
4933                         dst_reg->var_off = ptr_reg->var_off;
4934                         dst_reg->off = ptr_reg->off + smin_val;
4935                         dst_reg->raw = ptr_reg->raw;
4936                         break;
4937                 }
4938                 /* A new variable offset is created.  Note that off_reg->off
4939                  * == 0, since it's a scalar.
4940                  * dst_reg gets the pointer type and since some positive
4941                  * integer value was added to the pointer, give it a new 'id'
4942                  * if it's a PTR_TO_PACKET.
4943                  * this creates a new 'base' pointer, off_reg (variable) gets
4944                  * added into the variable offset, and we copy the fixed offset
4945                  * from ptr_reg.
4946                  */
4947                 if (signed_add_overflows(smin_ptr, smin_val) ||
4948                     signed_add_overflows(smax_ptr, smax_val)) {
4949                         dst_reg->smin_value = S64_MIN;
4950                         dst_reg->smax_value = S64_MAX;
4951                 } else {
4952                         dst_reg->smin_value = smin_ptr + smin_val;
4953                         dst_reg->smax_value = smax_ptr + smax_val;
4954                 }
4955                 if (umin_ptr + umin_val < umin_ptr ||
4956                     umax_ptr + umax_val < umax_ptr) {
4957                         dst_reg->umin_value = 0;
4958                         dst_reg->umax_value = U64_MAX;
4959                 } else {
4960                         dst_reg->umin_value = umin_ptr + umin_val;
4961                         dst_reg->umax_value = umax_ptr + umax_val;
4962                 }
4963                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
4964                 dst_reg->off = ptr_reg->off;
4965                 dst_reg->raw = ptr_reg->raw;
4966                 if (reg_is_pkt_pointer(ptr_reg)) {
4967                         dst_reg->id = ++env->id_gen;
4968                         /* something was added to pkt_ptr, set range to zero */
4969                         dst_reg->raw = 0;
4970                 }
4971                 break;
4972         case BPF_SUB:
4973                 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
4974                 if (ret < 0) {
4975                         verbose(env, "R%d tried to sub from different maps or paths\n", dst);
4976                         return ret;
4977                 }
4978                 if (dst_reg == off_reg) {
4979                         /* scalar -= pointer.  Creates an unknown scalar */
4980                         verbose(env, "R%d tried to subtract pointer from scalar\n",
4981                                 dst);
4982                         return -EACCES;
4983                 }
4984                 /* We don't allow subtraction from FP, because (according to
4985                  * test_verifier.c test "invalid fp arithmetic", JITs might not
4986                  * be able to deal with it.
4987                  */
4988                 if (ptr_reg->type == PTR_TO_STACK) {
4989                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
4990                                 dst);
4991                         return -EACCES;
4992                 }
4993                 if (known && (ptr_reg->off - smin_val ==
4994                               (s64)(s32)(ptr_reg->off - smin_val))) {
4995                         /* pointer -= K.  Subtract it from fixed offset */
4996                         dst_reg->smin_value = smin_ptr;
4997                         dst_reg->smax_value = smax_ptr;
4998                         dst_reg->umin_value = umin_ptr;
4999                         dst_reg->umax_value = umax_ptr;
5000                         dst_reg->var_off = ptr_reg->var_off;
5001                         dst_reg->id = ptr_reg->id;
5002                         dst_reg->off = ptr_reg->off - smin_val;
5003                         dst_reg->raw = ptr_reg->raw;
5004                         break;
5005                 }
5006                 /* A new variable offset is created.  If the subtrahend is known
5007                  * nonnegative, then any reg->range we had before is still good.
5008                  */
5009                 if (signed_sub_overflows(smin_ptr, smax_val) ||
5010                     signed_sub_overflows(smax_ptr, smin_val)) {
5011                         /* Overflow possible, we know nothing */
5012                         dst_reg->smin_value = S64_MIN;
5013                         dst_reg->smax_value = S64_MAX;
5014                 } else {
5015                         dst_reg->smin_value = smin_ptr - smax_val;
5016                         dst_reg->smax_value = smax_ptr - smin_val;
5017                 }
5018                 if (umin_ptr < umax_val) {
5019                         /* Overflow possible, we know nothing */
5020                         dst_reg->umin_value = 0;
5021                         dst_reg->umax_value = U64_MAX;
5022                 } else {
5023                         /* Cannot overflow (as long as bounds are consistent) */
5024                         dst_reg->umin_value = umin_ptr - umax_val;
5025                         dst_reg->umax_value = umax_ptr - umin_val;
5026                 }
5027                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
5028                 dst_reg->off = ptr_reg->off;
5029                 dst_reg->raw = ptr_reg->raw;
5030                 if (reg_is_pkt_pointer(ptr_reg)) {
5031                         dst_reg->id = ++env->id_gen;
5032                         /* something was added to pkt_ptr, set range to zero */
5033                         if (smin_val < 0)
5034                                 dst_reg->raw = 0;
5035                 }
5036                 break;
5037         case BPF_AND:
5038         case BPF_OR:
5039         case BPF_XOR:
5040                 /* bitwise ops on pointers are troublesome, prohibit. */
5041                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
5042                         dst, bpf_alu_string[opcode >> 4]);
5043                 return -EACCES;
5044         default:
5045                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
5046                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
5047                         dst, bpf_alu_string[opcode >> 4]);
5048                 return -EACCES;
5049         }
5050
5051         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
5052                 return -EINVAL;
5053
5054         __update_reg_bounds(dst_reg);
5055         __reg_deduce_bounds(dst_reg);
5056         __reg_bound_offset(dst_reg);
5057
5058         /* For unprivileged we require that resulting offset must be in bounds
5059          * in order to be able to sanitize access later on.
5060          */
5061         if (!env->allow_ptr_leaks) {
5062                 if (dst_reg->type == PTR_TO_MAP_VALUE &&
5063                     check_map_access(env, dst, dst_reg->off, 1, false)) {
5064                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
5065                                 "prohibited for !root\n", dst);
5066                         return -EACCES;
5067                 } else if (dst_reg->type == PTR_TO_STACK &&
5068                            check_stack_access(env, dst_reg, dst_reg->off +
5069                                               dst_reg->var_off.value, 1)) {
5070                         verbose(env, "R%d stack pointer arithmetic goes out of range, "
5071                                 "prohibited for !root\n", dst);
5072                         return -EACCES;
5073                 }
5074         }
5075
5076         return 0;
5077 }
5078
5079 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
5080                                  struct bpf_reg_state *src_reg)
5081 {
5082         s32 smin_val = src_reg->s32_min_value;
5083         s32 smax_val = src_reg->s32_max_value;
5084         u32 umin_val = src_reg->u32_min_value;
5085         u32 umax_val = src_reg->u32_max_value;
5086
5087         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
5088             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
5089                 dst_reg->s32_min_value = S32_MIN;
5090                 dst_reg->s32_max_value = S32_MAX;
5091         } else {
5092                 dst_reg->s32_min_value += smin_val;
5093                 dst_reg->s32_max_value += smax_val;
5094         }
5095         if (dst_reg->u32_min_value + umin_val < umin_val ||
5096             dst_reg->u32_max_value + umax_val < umax_val) {
5097                 dst_reg->u32_min_value = 0;
5098                 dst_reg->u32_max_value = U32_MAX;
5099         } else {
5100                 dst_reg->u32_min_value += umin_val;
5101                 dst_reg->u32_max_value += umax_val;
5102         }
5103 }
5104
5105 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
5106                                struct bpf_reg_state *src_reg)
5107 {
5108         s64 smin_val = src_reg->smin_value;
5109         s64 smax_val = src_reg->smax_value;
5110         u64 umin_val = src_reg->umin_value;
5111         u64 umax_val = src_reg->umax_value;
5112
5113         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
5114             signed_add_overflows(dst_reg->smax_value, smax_val)) {
5115                 dst_reg->smin_value = S64_MIN;
5116                 dst_reg->smax_value = S64_MAX;
5117         } else {
5118                 dst_reg->smin_value += smin_val;
5119                 dst_reg->smax_value += smax_val;
5120         }
5121         if (dst_reg->umin_value + umin_val < umin_val ||
5122             dst_reg->umax_value + umax_val < umax_val) {
5123                 dst_reg->umin_value = 0;
5124                 dst_reg->umax_value = U64_MAX;
5125         } else {
5126                 dst_reg->umin_value += umin_val;
5127                 dst_reg->umax_value += umax_val;
5128         }
5129 }
5130
5131 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
5132                                  struct bpf_reg_state *src_reg)
5133 {
5134         s32 smin_val = src_reg->s32_min_value;
5135         s32 smax_val = src_reg->s32_max_value;
5136         u32 umin_val = src_reg->u32_min_value;
5137         u32 umax_val = src_reg->u32_max_value;
5138
5139         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
5140             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
5141                 /* Overflow possible, we know nothing */
5142                 dst_reg->s32_min_value = S32_MIN;
5143                 dst_reg->s32_max_value = S32_MAX;
5144         } else {
5145                 dst_reg->s32_min_value -= smax_val;
5146                 dst_reg->s32_max_value -= smin_val;
5147         }
5148         if (dst_reg->u32_min_value < umax_val) {
5149                 /* Overflow possible, we know nothing */
5150                 dst_reg->u32_min_value = 0;
5151                 dst_reg->u32_max_value = U32_MAX;
5152         } else {
5153                 /* Cannot overflow (as long as bounds are consistent) */
5154                 dst_reg->u32_min_value -= umax_val;
5155                 dst_reg->u32_max_value -= umin_val;
5156         }
5157 }
5158
5159 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
5160                                struct bpf_reg_state *src_reg)
5161 {
5162         s64 smin_val = src_reg->smin_value;
5163         s64 smax_val = src_reg->smax_value;
5164         u64 umin_val = src_reg->umin_value;
5165         u64 umax_val = src_reg->umax_value;
5166
5167         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
5168             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
5169                 /* Overflow possible, we know nothing */
5170                 dst_reg->smin_value = S64_MIN;
5171                 dst_reg->smax_value = S64_MAX;
5172         } else {
5173                 dst_reg->smin_value -= smax_val;
5174                 dst_reg->smax_value -= smin_val;
5175         }
5176         if (dst_reg->umin_value < umax_val) {
5177                 /* Overflow possible, we know nothing */
5178                 dst_reg->umin_value = 0;
5179                 dst_reg->umax_value = U64_MAX;
5180         } else {
5181                 /* Cannot overflow (as long as bounds are consistent) */
5182                 dst_reg->umin_value -= umax_val;
5183                 dst_reg->umax_value -= umin_val;
5184         }
5185 }
5186
5187 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
5188                                  struct bpf_reg_state *src_reg)
5189 {
5190         s32 smin_val = src_reg->s32_min_value;
5191         u32 umin_val = src_reg->u32_min_value;
5192         u32 umax_val = src_reg->u32_max_value;
5193
5194         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
5195                 /* Ain't nobody got time to multiply that sign */
5196                 __mark_reg32_unbounded(dst_reg);
5197                 return;
5198         }
5199         /* Both values are positive, so we can work with unsigned and
5200          * copy the result to signed (unless it exceeds S32_MAX).
5201          */
5202         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
5203                 /* Potential overflow, we know nothing */
5204                 __mark_reg32_unbounded(dst_reg);
5205                 return;
5206         }
5207         dst_reg->u32_min_value *= umin_val;
5208         dst_reg->u32_max_value *= umax_val;
5209         if (dst_reg->u32_max_value > S32_MAX) {
5210                 /* Overflow possible, we know nothing */
5211                 dst_reg->s32_min_value = S32_MIN;
5212                 dst_reg->s32_max_value = S32_MAX;
5213         } else {
5214                 dst_reg->s32_min_value = dst_reg->u32_min_value;
5215                 dst_reg->s32_max_value = dst_reg->u32_max_value;
5216         }
5217 }
5218
5219 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
5220                                struct bpf_reg_state *src_reg)
5221 {
5222         s64 smin_val = src_reg->smin_value;
5223         u64 umin_val = src_reg->umin_value;
5224         u64 umax_val = src_reg->umax_value;
5225
5226         if (smin_val < 0 || dst_reg->smin_value < 0) {
5227                 /* Ain't nobody got time to multiply that sign */
5228                 __mark_reg64_unbounded(dst_reg);
5229                 return;
5230         }
5231         /* Both values are positive, so we can work with unsigned and
5232          * copy the result to signed (unless it exceeds S64_MAX).
5233          */
5234         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
5235                 /* Potential overflow, we know nothing */
5236                 __mark_reg64_unbounded(dst_reg);
5237                 return;
5238         }
5239         dst_reg->umin_value *= umin_val;
5240         dst_reg->umax_value *= umax_val;
5241         if (dst_reg->umax_value > S64_MAX) {
5242                 /* Overflow possible, we know nothing */
5243                 dst_reg->smin_value = S64_MIN;
5244                 dst_reg->smax_value = S64_MAX;
5245         } else {
5246                 dst_reg->smin_value = dst_reg->umin_value;
5247                 dst_reg->smax_value = dst_reg->umax_value;
5248         }
5249 }
5250
5251 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
5252                                  struct bpf_reg_state *src_reg)
5253 {
5254         bool src_known = tnum_subreg_is_const(src_reg->var_off);
5255         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5256         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5257         s32 smin_val = src_reg->s32_min_value;
5258         u32 umax_val = src_reg->u32_max_value;
5259
5260         /* Assuming scalar64_min_max_and will be called so its safe
5261          * to skip updating register for known 32-bit case.
5262          */
5263         if (src_known && dst_known)
5264                 return;
5265
5266         /* We get our minimum from the var_off, since that's inherently
5267          * bitwise.  Our maximum is the minimum of the operands' maxima.
5268          */
5269         dst_reg->u32_min_value = var32_off.value;
5270         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
5271         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
5272                 /* Lose signed bounds when ANDing negative numbers,
5273                  * ain't nobody got time for that.
5274                  */
5275                 dst_reg->s32_min_value = S32_MIN;
5276                 dst_reg->s32_max_value = S32_MAX;
5277         } else {
5278                 /* ANDing two positives gives a positive, so safe to
5279                  * cast result into s64.
5280                  */
5281                 dst_reg->s32_min_value = dst_reg->u32_min_value;
5282                 dst_reg->s32_max_value = dst_reg->u32_max_value;
5283         }
5284
5285 }
5286
5287 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
5288                                struct bpf_reg_state *src_reg)
5289 {
5290         bool src_known = tnum_is_const(src_reg->var_off);
5291         bool dst_known = tnum_is_const(dst_reg->var_off);
5292         s64 smin_val = src_reg->smin_value;
5293         u64 umax_val = src_reg->umax_value;
5294
5295         if (src_known && dst_known) {
5296                 __mark_reg_known(dst_reg, dst_reg->var_off.value &
5297                                           src_reg->var_off.value);
5298                 return;
5299         }
5300
5301         /* We get our minimum from the var_off, since that's inherently
5302          * bitwise.  Our maximum is the minimum of the operands' maxima.
5303          */
5304         dst_reg->umin_value = dst_reg->var_off.value;
5305         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
5306         if (dst_reg->smin_value < 0 || smin_val < 0) {
5307                 /* Lose signed bounds when ANDing negative numbers,
5308                  * ain't nobody got time for that.
5309                  */
5310                 dst_reg->smin_value = S64_MIN;
5311                 dst_reg->smax_value = S64_MAX;
5312         } else {
5313                 /* ANDing two positives gives a positive, so safe to
5314                  * cast result into s64.
5315                  */
5316                 dst_reg->smin_value = dst_reg->umin_value;
5317                 dst_reg->smax_value = dst_reg->umax_value;
5318         }
5319         /* We may learn something more from the var_off */
5320         __update_reg_bounds(dst_reg);
5321 }
5322
5323 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
5324                                 struct bpf_reg_state *src_reg)
5325 {
5326         bool src_known = tnum_subreg_is_const(src_reg->var_off);
5327         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5328         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5329         s32 smin_val = src_reg->smin_value;
5330         u32 umin_val = src_reg->umin_value;
5331
5332         /* Assuming scalar64_min_max_or will be called so it is safe
5333          * to skip updating register for known case.
5334          */
5335         if (src_known && dst_known)
5336                 return;
5337
5338         /* We get our maximum from the var_off, and our minimum is the
5339          * maximum of the operands' minima
5340          */
5341         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
5342         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
5343         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
5344                 /* Lose signed bounds when ORing negative numbers,
5345                  * ain't nobody got time for that.
5346                  */
5347                 dst_reg->s32_min_value = S32_MIN;
5348                 dst_reg->s32_max_value = S32_MAX;
5349         } else {
5350                 /* ORing two positives gives a positive, so safe to
5351                  * cast result into s64.
5352                  */
5353                 dst_reg->s32_min_value = dst_reg->umin_value;
5354                 dst_reg->s32_max_value = dst_reg->umax_value;
5355         }
5356 }
5357
5358 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
5359                               struct bpf_reg_state *src_reg)
5360 {
5361         bool src_known = tnum_is_const(src_reg->var_off);
5362         bool dst_known = tnum_is_const(dst_reg->var_off);
5363         s64 smin_val = src_reg->smin_value;
5364         u64 umin_val = src_reg->umin_value;
5365
5366         if (src_known && dst_known) {
5367                 __mark_reg_known(dst_reg, dst_reg->var_off.value |
5368                                           src_reg->var_off.value);
5369                 return;
5370         }
5371
5372         /* We get our maximum from the var_off, and our minimum is the
5373          * maximum of the operands' minima
5374          */
5375         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
5376         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
5377         if (dst_reg->smin_value < 0 || smin_val < 0) {
5378                 /* Lose signed bounds when ORing negative numbers,
5379                  * ain't nobody got time for that.
5380                  */
5381                 dst_reg->smin_value = S64_MIN;
5382                 dst_reg->smax_value = S64_MAX;
5383         } else {
5384                 /* ORing two positives gives a positive, so safe to
5385                  * cast result into s64.
5386                  */
5387                 dst_reg->smin_value = dst_reg->umin_value;
5388                 dst_reg->smax_value = dst_reg->umax_value;
5389         }
5390         /* We may learn something more from the var_off */
5391         __update_reg_bounds(dst_reg);
5392 }
5393
5394 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
5395                                    u64 umin_val, u64 umax_val)
5396 {
5397         /* We lose all sign bit information (except what we can pick
5398          * up from var_off)
5399          */
5400         dst_reg->s32_min_value = S32_MIN;
5401         dst_reg->s32_max_value = S32_MAX;
5402         /* If we might shift our top bit out, then we know nothing */
5403         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
5404                 dst_reg->u32_min_value = 0;
5405                 dst_reg->u32_max_value = U32_MAX;
5406         } else {
5407                 dst_reg->u32_min_value <<= umin_val;
5408                 dst_reg->u32_max_value <<= umax_val;
5409         }
5410 }
5411
5412 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
5413                                  struct bpf_reg_state *src_reg)
5414 {
5415         u32 umax_val = src_reg->u32_max_value;
5416         u32 umin_val = src_reg->u32_min_value;
5417         /* u32 alu operation will zext upper bits */
5418         struct tnum subreg = tnum_subreg(dst_reg->var_off);
5419
5420         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
5421         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
5422         /* Not required but being careful mark reg64 bounds as unknown so
5423          * that we are forced to pick them up from tnum and zext later and
5424          * if some path skips this step we are still safe.
5425          */
5426         __mark_reg64_unbounded(dst_reg);
5427         __update_reg32_bounds(dst_reg);
5428 }
5429
5430 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
5431                                    u64 umin_val, u64 umax_val)
5432 {
5433         /* Special case <<32 because it is a common compiler pattern to sign
5434          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
5435          * positive we know this shift will also be positive so we can track
5436          * bounds correctly. Otherwise we lose all sign bit information except
5437          * what we can pick up from var_off. Perhaps we can generalize this
5438          * later to shifts of any length.
5439          */
5440         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
5441                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
5442         else
5443                 dst_reg->smax_value = S64_MAX;
5444
5445         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
5446                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
5447         else
5448                 dst_reg->smin_value = S64_MIN;
5449
5450         /* If we might shift our top bit out, then we know nothing */
5451         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
5452                 dst_reg->umin_value = 0;
5453                 dst_reg->umax_value = U64_MAX;
5454         } else {
5455                 dst_reg->umin_value <<= umin_val;
5456                 dst_reg->umax_value <<= umax_val;
5457         }
5458 }
5459
5460 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
5461                                struct bpf_reg_state *src_reg)
5462 {
5463         u64 umax_val = src_reg->umax_value;
5464         u64 umin_val = src_reg->umin_value;
5465
5466         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
5467         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
5468         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
5469
5470         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
5471         /* We may learn something more from the var_off */
5472         __update_reg_bounds(dst_reg);
5473 }
5474
5475 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
5476                                  struct bpf_reg_state *src_reg)
5477 {
5478         struct tnum subreg = tnum_subreg(dst_reg->var_off);
5479         u32 umax_val = src_reg->u32_max_value;
5480         u32 umin_val = src_reg->u32_min_value;
5481
5482         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
5483          * be negative, then either:
5484          * 1) src_reg might be zero, so the sign bit of the result is
5485          *    unknown, so we lose our signed bounds
5486          * 2) it's known negative, thus the unsigned bounds capture the
5487          *    signed bounds
5488          * 3) the signed bounds cross zero, so they tell us nothing
5489          *    about the result
5490          * If the value in dst_reg is known nonnegative, then again the
5491          * unsigned bounts capture the signed bounds.
5492          * Thus, in all cases it suffices to blow away our signed bounds
5493          * and rely on inferring new ones from the unsigned bounds and
5494          * var_off of the result.
5495          */
5496         dst_reg->s32_min_value = S32_MIN;
5497         dst_reg->s32_max_value = S32_MAX;
5498
5499         dst_reg->var_off = tnum_rshift(subreg, umin_val);
5500         dst_reg->u32_min_value >>= umax_val;
5501         dst_reg->u32_max_value >>= umin_val;
5502
5503         __mark_reg64_unbounded(dst_reg);
5504         __update_reg32_bounds(dst_reg);
5505 }
5506
5507 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
5508                                struct bpf_reg_state *src_reg)
5509 {
5510         u64 umax_val = src_reg->umax_value;
5511         u64 umin_val = src_reg->umin_value;
5512
5513         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
5514          * be negative, then either:
5515          * 1) src_reg might be zero, so the sign bit of the result is
5516          *    unknown, so we lose our signed bounds
5517          * 2) it's known negative, thus the unsigned bounds capture the
5518          *    signed bounds
5519          * 3) the signed bounds cross zero, so they tell us nothing
5520          *    about the result
5521          * If the value in dst_reg is known nonnegative, then again the
5522          * unsigned bounts capture the signed bounds.
5523          * Thus, in all cases it suffices to blow away our signed bounds
5524          * and rely on inferring new ones from the unsigned bounds and
5525          * var_off of the result.
5526          */
5527         dst_reg->smin_value = S64_MIN;
5528         dst_reg->smax_value = S64_MAX;
5529         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
5530         dst_reg->umin_value >>= umax_val;
5531         dst_reg->umax_value >>= umin_val;
5532
5533         /* Its not easy to operate on alu32 bounds here because it depends
5534          * on bits being shifted in. Take easy way out and mark unbounded
5535          * so we can recalculate later from tnum.
5536          */
5537         __mark_reg32_unbounded(dst_reg);
5538         __update_reg_bounds(dst_reg);
5539 }
5540
5541 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
5542                                   struct bpf_reg_state *src_reg)
5543 {
5544         u64 umin_val = src_reg->u32_min_value;
5545
5546         /* Upon reaching here, src_known is true and
5547          * umax_val is equal to umin_val.
5548          */
5549         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
5550         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
5551
5552         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
5553
5554         /* blow away the dst_reg umin_value/umax_value and rely on
5555          * dst_reg var_off to refine the result.
5556          */
5557         dst_reg->u32_min_value = 0;
5558         dst_reg->u32_max_value = U32_MAX;
5559
5560         __mark_reg64_unbounded(dst_reg);
5561         __update_reg32_bounds(dst_reg);
5562 }
5563
5564 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
5565                                 struct bpf_reg_state *src_reg)
5566 {
5567         u64 umin_val = src_reg->umin_value;
5568
5569         /* Upon reaching here, src_known is true and umax_val is equal
5570          * to umin_val.
5571          */
5572         dst_reg->smin_value >>= umin_val;
5573         dst_reg->smax_value >>= umin_val;
5574
5575         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
5576
5577         /* blow away the dst_reg umin_value/umax_value and rely on
5578          * dst_reg var_off to refine the result.
5579          */
5580         dst_reg->umin_value = 0;
5581         dst_reg->umax_value = U64_MAX;
5582
5583         /* Its not easy to operate on alu32 bounds here because it depends
5584          * on bits being shifted in from upper 32-bits. Take easy way out
5585          * and mark unbounded so we can recalculate later from tnum.
5586          */
5587         __mark_reg32_unbounded(dst_reg);
5588         __update_reg_bounds(dst_reg);
5589 }
5590
5591 /* WARNING: This function does calculations on 64-bit values, but the actual
5592  * execution may occur on 32-bit values. Therefore, things like bitshifts
5593  * need extra checks in the 32-bit case.
5594  */
5595 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
5596                                       struct bpf_insn *insn,
5597                                       struct bpf_reg_state *dst_reg,
5598                                       struct bpf_reg_state src_reg)
5599 {
5600         struct bpf_reg_state *regs = cur_regs(env);
5601         u8 opcode = BPF_OP(insn->code);
5602         bool src_known, dst_known;
5603         s64 smin_val, smax_val;
5604         u64 umin_val, umax_val;
5605         s32 s32_min_val, s32_max_val;
5606         u32 u32_min_val, u32_max_val;
5607         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
5608         u32 dst = insn->dst_reg;
5609         int ret;
5610         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
5611
5612         smin_val = src_reg.smin_value;
5613         smax_val = src_reg.smax_value;
5614         umin_val = src_reg.umin_value;
5615         umax_val = src_reg.umax_value;
5616
5617         s32_min_val = src_reg.s32_min_value;
5618         s32_max_val = src_reg.s32_max_value;
5619         u32_min_val = src_reg.u32_min_value;
5620         u32_max_val = src_reg.u32_max_value;
5621
5622         if (alu32) {
5623                 src_known = tnum_subreg_is_const(src_reg.var_off);
5624                 dst_known = tnum_subreg_is_const(dst_reg->var_off);
5625                 if ((src_known &&
5626                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
5627                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
5628                         /* Taint dst register if offset had invalid bounds
5629                          * derived from e.g. dead branches.
5630                          */
5631                         __mark_reg_unknown(env, dst_reg);
5632                         return 0;
5633                 }
5634         } else {
5635                 src_known = tnum_is_const(src_reg.var_off);
5636                 dst_known = tnum_is_const(dst_reg->var_off);
5637                 if ((src_known &&
5638                      (smin_val != smax_val || umin_val != umax_val)) ||
5639                     smin_val > smax_val || umin_val > umax_val) {
5640                         /* Taint dst register if offset had invalid bounds
5641                          * derived from e.g. dead branches.
5642                          */
5643                         __mark_reg_unknown(env, dst_reg);
5644                         return 0;
5645                 }
5646         }
5647
5648         if (!src_known &&
5649             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
5650                 __mark_reg_unknown(env, dst_reg);
5651                 return 0;
5652         }
5653
5654         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
5655          * There are two classes of instructions: The first class we track both
5656          * alu32 and alu64 sign/unsigned bounds independently this provides the
5657          * greatest amount of precision when alu operations are mixed with jmp32
5658          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
5659          * and BPF_OR. This is possible because these ops have fairly easy to
5660          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
5661          * See alu32 verifier tests for examples. The second class of
5662          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
5663          * with regards to tracking sign/unsigned bounds because the bits may
5664          * cross subreg boundaries in the alu64 case. When this happens we mark
5665          * the reg unbounded in the subreg bound space and use the resulting
5666          * tnum to calculate an approximation of the sign/unsigned bounds.
5667          */
5668         switch (opcode) {
5669         case BPF_ADD:
5670                 ret = sanitize_val_alu(env, insn);
5671                 if (ret < 0) {
5672                         verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
5673                         return ret;
5674                 }
5675                 scalar32_min_max_add(dst_reg, &src_reg);
5676                 scalar_min_max_add(dst_reg, &src_reg);
5677                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
5678                 break;
5679         case BPF_SUB:
5680                 ret = sanitize_val_alu(env, insn);
5681                 if (ret < 0) {
5682                         verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
5683                         return ret;
5684                 }
5685                 scalar32_min_max_sub(dst_reg, &src_reg);
5686                 scalar_min_max_sub(dst_reg, &src_reg);
5687                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
5688                 break;
5689         case BPF_MUL:
5690                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
5691                 scalar32_min_max_mul(dst_reg, &src_reg);
5692                 scalar_min_max_mul(dst_reg, &src_reg);
5693                 break;
5694         case BPF_AND:
5695                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
5696                 scalar32_min_max_and(dst_reg, &src_reg);
5697                 scalar_min_max_and(dst_reg, &src_reg);
5698                 break;
5699         case BPF_OR:
5700                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
5701                 scalar32_min_max_or(dst_reg, &src_reg);
5702                 scalar_min_max_or(dst_reg, &src_reg);
5703                 break;
5704         case BPF_LSH:
5705                 if (umax_val >= insn_bitness) {
5706                         /* Shifts greater than 31 or 63 are undefined.
5707                          * This includes shifts by a negative number.
5708                          */
5709                         mark_reg_unknown(env, regs, insn->dst_reg);
5710                         break;
5711                 }
5712                 if (alu32)
5713                         scalar32_min_max_lsh(dst_reg, &src_reg);
5714                 else
5715                         scalar_min_max_lsh(dst_reg, &src_reg);
5716                 break;
5717         case BPF_RSH:
5718                 if (umax_val >= insn_bitness) {
5719                         /* Shifts greater than 31 or 63 are undefined.
5720                          * This includes shifts by a negative number.
5721                          */
5722                         mark_reg_unknown(env, regs, insn->dst_reg);
5723                         break;
5724                 }
5725                 if (alu32)
5726                         scalar32_min_max_rsh(dst_reg, &src_reg);
5727                 else
5728                         scalar_min_max_rsh(dst_reg, &src_reg);
5729                 break;
5730         case BPF_ARSH:
5731                 if (umax_val >= insn_bitness) {
5732                         /* Shifts greater than 31 or 63 are undefined.
5733                          * This includes shifts by a negative number.
5734                          */
5735                         mark_reg_unknown(env, regs, insn->dst_reg);
5736                         break;
5737                 }
5738                 if (alu32)
5739                         scalar32_min_max_arsh(dst_reg, &src_reg);
5740                 else
5741                         scalar_min_max_arsh(dst_reg, &src_reg);
5742                 break;
5743         default:
5744                 mark_reg_unknown(env, regs, insn->dst_reg);
5745                 break;
5746         }
5747
5748         /* ALU32 ops are zero extended into 64bit register */
5749         if (alu32)
5750                 zext_32_to_64(dst_reg);
5751
5752         __update_reg_bounds(dst_reg);
5753         __reg_deduce_bounds(dst_reg);
5754         __reg_bound_offset(dst_reg);
5755         return 0;
5756 }
5757
5758 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
5759  * and var_off.
5760  */
5761 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
5762                                    struct bpf_insn *insn)
5763 {
5764         struct bpf_verifier_state *vstate = env->cur_state;
5765         struct bpf_func_state *state = vstate->frame[vstate->curframe];
5766         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
5767         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
5768         u8 opcode = BPF_OP(insn->code);
5769         int err;
5770
5771         dst_reg = &regs[insn->dst_reg];
5772         src_reg = NULL;
5773         if (dst_reg->type != SCALAR_VALUE)
5774                 ptr_reg = dst_reg;
5775         if (BPF_SRC(insn->code) == BPF_X) {
5776                 src_reg = &regs[insn->src_reg];
5777                 if (src_reg->type != SCALAR_VALUE) {
5778                         if (dst_reg->type != SCALAR_VALUE) {
5779                                 /* Combining two pointers by any ALU op yields
5780                                  * an arbitrary scalar. Disallow all math except
5781                                  * pointer subtraction
5782                                  */
5783                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
5784                                         mark_reg_unknown(env, regs, insn->dst_reg);
5785                                         return 0;
5786                                 }
5787                                 verbose(env, "R%d pointer %s pointer prohibited\n",
5788                                         insn->dst_reg,
5789                                         bpf_alu_string[opcode >> 4]);
5790                                 return -EACCES;
5791                         } else {
5792                                 /* scalar += pointer
5793                                  * This is legal, but we have to reverse our
5794                                  * src/dest handling in computing the range
5795                                  */
5796                                 err = mark_chain_precision(env, insn->dst_reg);
5797                                 if (err)
5798                                         return err;
5799                                 return adjust_ptr_min_max_vals(env, insn,
5800                                                                src_reg, dst_reg);
5801                         }
5802                 } else if (ptr_reg) {
5803                         /* pointer += scalar */
5804                         err = mark_chain_precision(env, insn->src_reg);
5805                         if (err)
5806                                 return err;
5807                         return adjust_ptr_min_max_vals(env, insn,
5808                                                        dst_reg, src_reg);
5809                 }
5810         } else {
5811                 /* Pretend the src is a reg with a known value, since we only
5812                  * need to be able to read from this state.
5813                  */
5814                 off_reg.type = SCALAR_VALUE;
5815                 __mark_reg_known(&off_reg, insn->imm);
5816                 src_reg = &off_reg;
5817                 if (ptr_reg) /* pointer += K */
5818                         return adjust_ptr_min_max_vals(env, insn,
5819                                                        ptr_reg, src_reg);
5820         }
5821
5822         /* Got here implies adding two SCALAR_VALUEs */
5823         if (WARN_ON_ONCE(ptr_reg)) {
5824                 print_verifier_state(env, state);
5825                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
5826                 return -EINVAL;
5827         }
5828         if (WARN_ON(!src_reg)) {
5829                 print_verifier_state(env, state);
5830                 verbose(env, "verifier internal error: no src_reg\n");
5831                 return -EINVAL;
5832         }
5833         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
5834 }
5835
5836 /* check validity of 32-bit and 64-bit arithmetic operations */
5837 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
5838 {
5839         struct bpf_reg_state *regs = cur_regs(env);
5840         u8 opcode = BPF_OP(insn->code);
5841         int err;
5842
5843         if (opcode == BPF_END || opcode == BPF_NEG) {
5844                 if (opcode == BPF_NEG) {
5845                         if (BPF_SRC(insn->code) != 0 ||
5846                             insn->src_reg != BPF_REG_0 ||
5847                             insn->off != 0 || insn->imm != 0) {
5848                                 verbose(env, "BPF_NEG uses reserved fields\n");
5849                                 return -EINVAL;
5850                         }
5851                 } else {
5852                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
5853                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
5854                             BPF_CLASS(insn->code) == BPF_ALU64) {
5855                                 verbose(env, "BPF_END uses reserved fields\n");
5856                                 return -EINVAL;
5857                         }
5858                 }
5859
5860                 /* check src operand */
5861                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5862                 if (err)
5863                         return err;
5864
5865                 if (is_pointer_value(env, insn->dst_reg)) {
5866                         verbose(env, "R%d pointer arithmetic prohibited\n",
5867                                 insn->dst_reg);
5868                         return -EACCES;
5869                 }
5870
5871                 /* check dest operand */
5872                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
5873                 if (err)
5874                         return err;
5875
5876         } else if (opcode == BPF_MOV) {
5877
5878                 if (BPF_SRC(insn->code) == BPF_X) {
5879                         if (insn->imm != 0 || insn->off != 0) {
5880                                 verbose(env, "BPF_MOV uses reserved fields\n");
5881                                 return -EINVAL;
5882                         }
5883
5884                         /* check src operand */
5885                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
5886                         if (err)
5887                                 return err;
5888                 } else {
5889                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
5890                                 verbose(env, "BPF_MOV uses reserved fields\n");
5891                                 return -EINVAL;
5892                         }
5893                 }
5894
5895                 /* check dest operand, mark as required later */
5896                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
5897                 if (err)
5898                         return err;
5899
5900                 if (BPF_SRC(insn->code) == BPF_X) {
5901                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
5902                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
5903
5904                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
5905                                 /* case: R1 = R2
5906                                  * copy register state to dest reg
5907                                  */
5908                                 *dst_reg = *src_reg;
5909                                 dst_reg->live |= REG_LIVE_WRITTEN;
5910                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
5911                         } else {
5912                                 /* R1 = (u32) R2 */
5913                                 if (is_pointer_value(env, insn->src_reg)) {
5914                                         verbose(env,
5915                                                 "R%d partial copy of pointer\n",
5916                                                 insn->src_reg);
5917                                         return -EACCES;
5918                                 } else if (src_reg->type == SCALAR_VALUE) {
5919                                         *dst_reg = *src_reg;
5920                                         dst_reg->live |= REG_LIVE_WRITTEN;
5921                                         dst_reg->subreg_def = env->insn_idx + 1;
5922                                 } else {
5923                                         mark_reg_unknown(env, regs,
5924                                                          insn->dst_reg);
5925                                 }
5926                                 zext_32_to_64(dst_reg);
5927                         }
5928                 } else {
5929                         /* case: R = imm
5930                          * remember the value we stored into this reg
5931                          */
5932                         /* clear any state __mark_reg_known doesn't set */
5933                         mark_reg_unknown(env, regs, insn->dst_reg);
5934                         regs[insn->dst_reg].type = SCALAR_VALUE;
5935                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
5936                                 __mark_reg_known(regs + insn->dst_reg,
5937                                                  insn->imm);
5938                         } else {
5939                                 __mark_reg_known(regs + insn->dst_reg,
5940                                                  (u32)insn->imm);
5941                         }
5942                 }
5943
5944         } else if (opcode > BPF_END) {
5945                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
5946                 return -EINVAL;
5947
5948         } else {        /* all other ALU ops: and, sub, xor, add, ... */
5949
5950                 if (BPF_SRC(insn->code) == BPF_X) {
5951                         if (insn->imm != 0 || insn->off != 0) {
5952                                 verbose(env, "BPF_ALU uses reserved fields\n");
5953                                 return -EINVAL;
5954                         }
5955                         /* check src1 operand */
5956                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
5957                         if (err)
5958                                 return err;
5959                 } else {
5960                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
5961                                 verbose(env, "BPF_ALU uses reserved fields\n");
5962                                 return -EINVAL;
5963                         }
5964                 }
5965
5966                 /* check src2 operand */
5967                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5968                 if (err)
5969                         return err;
5970
5971                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
5972                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
5973                         verbose(env, "div by zero\n");
5974                         return -EINVAL;
5975                 }
5976
5977                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
5978                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
5979                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
5980
5981                         if (insn->imm < 0 || insn->imm >= size) {
5982                                 verbose(env, "invalid shift %d\n", insn->imm);
5983                                 return -EINVAL;
5984                         }
5985                 }
5986
5987                 /* check dest operand */
5988                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
5989                 if (err)
5990                         return err;
5991
5992                 return adjust_reg_min_max_vals(env, insn);
5993         }
5994
5995         return 0;
5996 }
5997
5998 static void __find_good_pkt_pointers(struct bpf_func_state *state,
5999                                      struct bpf_reg_state *dst_reg,
6000                                      enum bpf_reg_type type, u16 new_range)
6001 {
6002         struct bpf_reg_state *reg;
6003         int i;
6004
6005         for (i = 0; i < MAX_BPF_REG; i++) {
6006                 reg = &state->regs[i];
6007                 if (reg->type == type && reg->id == dst_reg->id)
6008                         /* keep the maximum range already checked */
6009                         reg->range = max(reg->range, new_range);
6010         }
6011
6012         bpf_for_each_spilled_reg(i, state, reg) {
6013                 if (!reg)
6014                         continue;
6015                 if (reg->type == type && reg->id == dst_reg->id)
6016                         reg->range = max(reg->range, new_range);
6017         }
6018 }
6019
6020 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
6021                                    struct bpf_reg_state *dst_reg,
6022                                    enum bpf_reg_type type,
6023                                    bool range_right_open)
6024 {
6025         u16 new_range;
6026         int i;
6027
6028         if (dst_reg->off < 0 ||
6029             (dst_reg->off == 0 && range_right_open))
6030                 /* This doesn't give us any range */
6031                 return;
6032
6033         if (dst_reg->umax_value > MAX_PACKET_OFF ||
6034             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
6035                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
6036                  * than pkt_end, but that's because it's also less than pkt.
6037                  */
6038                 return;
6039
6040         new_range = dst_reg->off;
6041         if (range_right_open)
6042                 new_range--;
6043
6044         /* Examples for register markings:
6045          *
6046          * pkt_data in dst register:
6047          *
6048          *   r2 = r3;
6049          *   r2 += 8;
6050          *   if (r2 > pkt_end) goto <handle exception>
6051          *   <access okay>
6052          *
6053          *   r2 = r3;
6054          *   r2 += 8;
6055          *   if (r2 < pkt_end) goto <access okay>
6056          *   <handle exception>
6057          *
6058          *   Where:
6059          *     r2 == dst_reg, pkt_end == src_reg
6060          *     r2=pkt(id=n,off=8,r=0)
6061          *     r3=pkt(id=n,off=0,r=0)
6062          *
6063          * pkt_data in src register:
6064          *
6065          *   r2 = r3;
6066          *   r2 += 8;
6067          *   if (pkt_end >= r2) goto <access okay>
6068          *   <handle exception>
6069          *
6070          *   r2 = r3;
6071          *   r2 += 8;
6072          *   if (pkt_end <= r2) goto <handle exception>
6073          *   <access okay>
6074          *
6075          *   Where:
6076          *     pkt_end == dst_reg, r2 == src_reg
6077          *     r2=pkt(id=n,off=8,r=0)
6078          *     r3=pkt(id=n,off=0,r=0)
6079          *
6080          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
6081          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
6082          * and [r3, r3 + 8-1) respectively is safe to access depending on
6083          * the check.
6084          */
6085
6086         /* If our ids match, then we must have the same max_value.  And we
6087          * don't care about the other reg's fixed offset, since if it's too big
6088          * the range won't allow anything.
6089          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
6090          */
6091         for (i = 0; i <= vstate->curframe; i++)
6092                 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
6093                                          new_range);
6094 }
6095
6096 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
6097 {
6098         struct tnum subreg = tnum_subreg(reg->var_off);
6099         s32 sval = (s32)val;
6100
6101         switch (opcode) {
6102         case BPF_JEQ:
6103                 if (tnum_is_const(subreg))
6104                         return !!tnum_equals_const(subreg, val);
6105                 break;
6106         case BPF_JNE:
6107                 if (tnum_is_const(subreg))
6108                         return !tnum_equals_const(subreg, val);
6109                 break;
6110         case BPF_JSET:
6111                 if ((~subreg.mask & subreg.value) & val)
6112                         return 1;
6113                 if (!((subreg.mask | subreg.value) & val))
6114                         return 0;
6115                 break;
6116         case BPF_JGT:
6117                 if (reg->u32_min_value > val)
6118                         return 1;
6119                 else if (reg->u32_max_value <= val)
6120                         return 0;
6121                 break;
6122         case BPF_JSGT:
6123                 if (reg->s32_min_value > sval)
6124                         return 1;
6125                 else if (reg->s32_max_value < sval)
6126                         return 0;
6127                 break;
6128         case BPF_JLT:
6129                 if (reg->u32_max_value < val)
6130                         return 1;
6131                 else if (reg->u32_min_value >= val)
6132                         return 0;
6133                 break;
6134         case BPF_JSLT:
6135                 if (reg->s32_max_value < sval)
6136                         return 1;
6137                 else if (reg->s32_min_value >= sval)
6138                         return 0;
6139                 break;
6140         case BPF_JGE:
6141                 if (reg->u32_min_value >= val)
6142                         return 1;
6143                 else if (reg->u32_max_value < val)
6144                         return 0;
6145                 break;
6146         case BPF_JSGE:
6147                 if (reg->s32_min_value >= sval)
6148                         return 1;
6149                 else if (reg->s32_max_value < sval)
6150                         return 0;
6151                 break;
6152         case BPF_JLE:
6153                 if (reg->u32_max_value <= val)
6154                         return 1;
6155                 else if (reg->u32_min_value > val)
6156                         return 0;
6157                 break;
6158         case BPF_JSLE:
6159                 if (reg->s32_max_value <= sval)
6160                         return 1;
6161                 else if (reg->s32_min_value > sval)
6162                         return 0;
6163                 break;
6164         }
6165
6166         return -1;
6167 }
6168
6169
6170 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
6171 {
6172         s64 sval = (s64)val;
6173
6174         switch (opcode) {
6175         case BPF_JEQ:
6176                 if (tnum_is_const(reg->var_off))
6177                         return !!tnum_equals_const(reg->var_off, val);
6178                 break;
6179         case BPF_JNE:
6180                 if (tnum_is_const(reg->var_off))
6181                         return !tnum_equals_const(reg->var_off, val);
6182                 break;
6183         case BPF_JSET:
6184                 if ((~reg->var_off.mask & reg->var_off.value) & val)
6185                         return 1;
6186                 if (!((reg->var_off.mask | reg->var_off.value) & val))
6187                         return 0;
6188                 break;
6189         case BPF_JGT:
6190                 if (reg->umin_value > val)
6191                         return 1;
6192                 else if (reg->umax_value <= val)
6193                         return 0;
6194                 break;
6195         case BPF_JSGT:
6196                 if (reg->smin_value > sval)
6197                         return 1;
6198                 else if (reg->smax_value < sval)
6199                         return 0;
6200                 break;
6201         case BPF_JLT:
6202                 if (reg->umax_value < val)
6203                         return 1;
6204                 else if (reg->umin_value >= val)
6205                         return 0;
6206                 break;
6207         case BPF_JSLT:
6208                 if (reg->smax_value < sval)
6209                         return 1;
6210                 else if (reg->smin_value >= sval)
6211                         return 0;
6212                 break;
6213         case BPF_JGE:
6214                 if (reg->umin_value >= val)
6215                         return 1;
6216                 else if (reg->umax_value < val)
6217                         return 0;
6218                 break;
6219         case BPF_JSGE:
6220                 if (reg->smin_value >= sval)
6221                         return 1;
6222                 else if (reg->smax_value < sval)
6223                         return 0;
6224                 break;
6225         case BPF_JLE:
6226                 if (reg->umax_value <= val)
6227                         return 1;
6228                 else if (reg->umin_value > val)
6229                         return 0;
6230                 break;
6231         case BPF_JSLE:
6232                 if (reg->smax_value <= sval)
6233                         return 1;
6234                 else if (reg->smin_value > sval)
6235                         return 0;
6236                 break;
6237         }
6238
6239         return -1;
6240 }
6241
6242 /* compute branch direction of the expression "if (reg opcode val) goto target;"
6243  * and return:
6244  *  1 - branch will be taken and "goto target" will be executed
6245  *  0 - branch will not be taken and fall-through to next insn
6246  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
6247  *      range [0,10]
6248  */
6249 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
6250                            bool is_jmp32)
6251 {
6252         if (__is_pointer_value(false, reg))
6253                 return -1;
6254
6255         if (is_jmp32)
6256                 return is_branch32_taken(reg, val, opcode);
6257         return is_branch64_taken(reg, val, opcode);
6258 }
6259
6260 /* Adjusts the register min/max values in the case that the dst_reg is the
6261  * variable register that we are working on, and src_reg is a constant or we're
6262  * simply doing a BPF_K check.
6263  * In JEQ/JNE cases we also adjust the var_off values.
6264  */
6265 static void reg_set_min_max(struct bpf_reg_state *true_reg,
6266                             struct bpf_reg_state *false_reg,
6267                             u64 val, u32 val32,
6268                             u8 opcode, bool is_jmp32)
6269 {
6270         struct tnum false_32off = tnum_subreg(false_reg->var_off);
6271         struct tnum false_64off = false_reg->var_off;
6272         struct tnum true_32off = tnum_subreg(true_reg->var_off);
6273         struct tnum true_64off = true_reg->var_off;
6274         s64 sval = (s64)val;
6275         s32 sval32 = (s32)val32;
6276
6277         /* If the dst_reg is a pointer, we can't learn anything about its
6278          * variable offset from the compare (unless src_reg were a pointer into
6279          * the same object, but we don't bother with that.
6280          * Since false_reg and true_reg have the same type by construction, we
6281          * only need to check one of them for pointerness.
6282          */
6283         if (__is_pointer_value(false, false_reg))
6284                 return;
6285
6286         switch (opcode) {
6287         case BPF_JEQ:
6288         case BPF_JNE:
6289         {
6290                 struct bpf_reg_state *reg =
6291                         opcode == BPF_JEQ ? true_reg : false_reg;
6292
6293                 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but
6294                  * if it is true we know the value for sure. Likewise for
6295                  * BPF_JNE.
6296                  */
6297                 if (is_jmp32)
6298                         __mark_reg32_known(reg, val32);
6299                 else
6300                         __mark_reg_known(reg, val);
6301                 break;
6302         }
6303         case BPF_JSET:
6304                 if (is_jmp32) {
6305                         false_32off = tnum_and(false_32off, tnum_const(~val32));
6306                         if (is_power_of_2(val32))
6307                                 true_32off = tnum_or(true_32off,
6308                                                      tnum_const(val32));
6309                 } else {
6310                         false_64off = tnum_and(false_64off, tnum_const(~val));
6311                         if (is_power_of_2(val))
6312                                 true_64off = tnum_or(true_64off,
6313                                                      tnum_const(val));
6314                 }
6315                 break;
6316         case BPF_JGE:
6317         case BPF_JGT:
6318         {
6319                 if (is_jmp32) {
6320                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
6321                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
6322
6323                         false_reg->u32_max_value = min(false_reg->u32_max_value,
6324                                                        false_umax);
6325                         true_reg->u32_min_value = max(true_reg->u32_min_value,
6326                                                       true_umin);
6327                 } else {
6328                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
6329                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
6330
6331                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
6332                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
6333                 }
6334                 break;
6335         }
6336         case BPF_JSGE:
6337         case BPF_JSGT:
6338         {
6339                 if (is_jmp32) {
6340                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
6341                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
6342
6343                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
6344                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
6345                 } else {
6346                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
6347                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
6348
6349                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
6350                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
6351                 }
6352                 break;
6353         }
6354         case BPF_JLE:
6355         case BPF_JLT:
6356         {
6357                 if (is_jmp32) {
6358                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
6359                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
6360
6361                         false_reg->u32_min_value = max(false_reg->u32_min_value,
6362                                                        false_umin);
6363                         true_reg->u32_max_value = min(true_reg->u32_max_value,
6364                                                       true_umax);
6365                 } else {
6366                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
6367                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
6368
6369                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
6370                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
6371                 }
6372                 break;
6373         }
6374         case BPF_JSLE:
6375         case BPF_JSLT:
6376         {
6377                 if (is_jmp32) {
6378                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
6379                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
6380
6381                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
6382                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
6383                 } else {
6384                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
6385                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
6386
6387                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
6388                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
6389                 }
6390                 break;
6391         }
6392         default:
6393                 return;
6394         }
6395
6396         if (is_jmp32) {
6397                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
6398                                              tnum_subreg(false_32off));
6399                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
6400                                             tnum_subreg(true_32off));
6401                 __reg_combine_32_into_64(false_reg);
6402                 __reg_combine_32_into_64(true_reg);
6403         } else {
6404                 false_reg->var_off = false_64off;
6405                 true_reg->var_off = true_64off;
6406                 __reg_combine_64_into_32(false_reg);
6407                 __reg_combine_64_into_32(true_reg);
6408         }
6409 }
6410
6411 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
6412  * the variable reg.
6413  */
6414 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
6415                                 struct bpf_reg_state *false_reg,
6416                                 u64 val, u32 val32,
6417                                 u8 opcode, bool is_jmp32)
6418 {
6419         /* How can we transform "a <op> b" into "b <op> a"? */
6420         static const u8 opcode_flip[16] = {
6421                 /* these stay the same */
6422                 [BPF_JEQ  >> 4] = BPF_JEQ,
6423                 [BPF_JNE  >> 4] = BPF_JNE,
6424                 [BPF_JSET >> 4] = BPF_JSET,
6425                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
6426                 [BPF_JGE  >> 4] = BPF_JLE,
6427                 [BPF_JGT  >> 4] = BPF_JLT,
6428                 [BPF_JLE  >> 4] = BPF_JGE,
6429                 [BPF_JLT  >> 4] = BPF_JGT,
6430                 [BPF_JSGE >> 4] = BPF_JSLE,
6431                 [BPF_JSGT >> 4] = BPF_JSLT,
6432                 [BPF_JSLE >> 4] = BPF_JSGE,
6433                 [BPF_JSLT >> 4] = BPF_JSGT
6434         };
6435         opcode = opcode_flip[opcode >> 4];
6436         /* This uses zero as "not present in table"; luckily the zero opcode,
6437          * BPF_JA, can't get here.
6438          */
6439         if (opcode)
6440                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
6441 }
6442
6443 /* Regs are known to be equal, so intersect their min/max/var_off */
6444 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
6445                                   struct bpf_reg_state *dst_reg)
6446 {
6447         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
6448                                                         dst_reg->umin_value);
6449         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
6450                                                         dst_reg->umax_value);
6451         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
6452                                                         dst_reg->smin_value);
6453         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
6454                                                         dst_reg->smax_value);
6455         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
6456                                                              dst_reg->var_off);
6457         /* We might have learned new bounds from the var_off. */
6458         __update_reg_bounds(src_reg);
6459         __update_reg_bounds(dst_reg);
6460         /* We might have learned something about the sign bit. */
6461         __reg_deduce_bounds(src_reg);
6462         __reg_deduce_bounds(dst_reg);
6463         /* We might have learned some bits from the bounds. */
6464         __reg_bound_offset(src_reg);
6465         __reg_bound_offset(dst_reg);
6466         /* Intersecting with the old var_off might have improved our bounds
6467          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
6468          * then new var_off is (0; 0x7f...fc) which improves our umax.
6469          */
6470         __update_reg_bounds(src_reg);
6471         __update_reg_bounds(dst_reg);
6472 }
6473
6474 static void reg_combine_min_max(struct bpf_reg_state *true_src,
6475                                 struct bpf_reg_state *true_dst,
6476                                 struct bpf_reg_state *false_src,
6477                                 struct bpf_reg_state *false_dst,
6478                                 u8 opcode)
6479 {
6480         switch (opcode) {
6481         case BPF_JEQ:
6482                 __reg_combine_min_max(true_src, true_dst);
6483                 break;
6484         case BPF_JNE:
6485                 __reg_combine_min_max(false_src, false_dst);
6486                 break;
6487         }
6488 }
6489
6490 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
6491                                  struct bpf_reg_state *reg, u32 id,
6492                                  bool is_null)
6493 {
6494         if (reg_type_may_be_null(reg->type) && reg->id == id) {
6495                 /* Old offset (both fixed and variable parts) should
6496                  * have been known-zero, because we don't allow pointer
6497                  * arithmetic on pointers that might be NULL.
6498                  */
6499                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
6500                                  !tnum_equals_const(reg->var_off, 0) ||
6501                                  reg->off)) {
6502                         __mark_reg_known_zero(reg);
6503                         reg->off = 0;
6504                 }
6505                 if (is_null) {
6506                         reg->type = SCALAR_VALUE;
6507                 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
6508                         if (reg->map_ptr->inner_map_meta) {
6509                                 reg->type = CONST_PTR_TO_MAP;
6510                                 reg->map_ptr = reg->map_ptr->inner_map_meta;
6511                         } else if (reg->map_ptr->map_type ==
6512                                    BPF_MAP_TYPE_XSKMAP) {
6513                                 reg->type = PTR_TO_XDP_SOCK;
6514                         } else {
6515                                 reg->type = PTR_TO_MAP_VALUE;
6516                         }
6517                 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
6518                         reg->type = PTR_TO_SOCKET;
6519                 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
6520                         reg->type = PTR_TO_SOCK_COMMON;
6521                 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
6522                         reg->type = PTR_TO_TCP_SOCK;
6523                 }
6524                 if (is_null) {
6525                         /* We don't need id and ref_obj_id from this point
6526                          * onwards anymore, thus we should better reset it,
6527                          * so that state pruning has chances to take effect.
6528                          */
6529                         reg->id = 0;
6530                         reg->ref_obj_id = 0;
6531                 } else if (!reg_may_point_to_spin_lock(reg)) {
6532                         /* For not-NULL ptr, reg->ref_obj_id will be reset
6533                          * in release_reg_references().
6534                          *
6535                          * reg->id is still used by spin_lock ptr. Other
6536                          * than spin_lock ptr type, reg->id can be reset.
6537                          */
6538                         reg->id = 0;
6539                 }
6540         }
6541 }
6542
6543 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
6544                                     bool is_null)
6545 {
6546         struct bpf_reg_state *reg;
6547         int i;
6548
6549         for (i = 0; i < MAX_BPF_REG; i++)
6550                 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
6551
6552         bpf_for_each_spilled_reg(i, state, reg) {
6553                 if (!reg)
6554                         continue;
6555                 mark_ptr_or_null_reg(state, reg, id, is_null);
6556         }
6557 }
6558
6559 /* The logic is similar to find_good_pkt_pointers(), both could eventually
6560  * be folded together at some point.
6561  */
6562 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
6563                                   bool is_null)
6564 {
6565         struct bpf_func_state *state = vstate->frame[vstate->curframe];
6566         struct bpf_reg_state *regs = state->regs;
6567         u32 ref_obj_id = regs[regno].ref_obj_id;
6568         u32 id = regs[regno].id;
6569         int i;
6570
6571         if (ref_obj_id && ref_obj_id == id && is_null)
6572                 /* regs[regno] is in the " == NULL" branch.
6573                  * No one could have freed the reference state before
6574                  * doing the NULL check.
6575                  */
6576                 WARN_ON_ONCE(release_reference_state(state, id));
6577
6578         for (i = 0; i <= vstate->curframe; i++)
6579                 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
6580 }
6581
6582 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
6583                                    struct bpf_reg_state *dst_reg,
6584                                    struct bpf_reg_state *src_reg,
6585                                    struct bpf_verifier_state *this_branch,
6586                                    struct bpf_verifier_state *other_branch)
6587 {
6588         if (BPF_SRC(insn->code) != BPF_X)
6589                 return false;
6590
6591         /* Pointers are always 64-bit. */
6592         if (BPF_CLASS(insn->code) == BPF_JMP32)
6593                 return false;
6594
6595         switch (BPF_OP(insn->code)) {
6596         case BPF_JGT:
6597                 if ((dst_reg->type == PTR_TO_PACKET &&
6598                      src_reg->type == PTR_TO_PACKET_END) ||
6599                     (dst_reg->type == PTR_TO_PACKET_META &&
6600                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6601                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
6602                         find_good_pkt_pointers(this_branch, dst_reg,
6603                                                dst_reg->type, false);
6604                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6605                             src_reg->type == PTR_TO_PACKET) ||
6606                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6607                             src_reg->type == PTR_TO_PACKET_META)) {
6608                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
6609                         find_good_pkt_pointers(other_branch, src_reg,
6610                                                src_reg->type, true);
6611                 } else {
6612                         return false;
6613                 }
6614                 break;
6615         case BPF_JLT:
6616                 if ((dst_reg->type == PTR_TO_PACKET &&
6617                      src_reg->type == PTR_TO_PACKET_END) ||
6618                     (dst_reg->type == PTR_TO_PACKET_META &&
6619                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6620                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
6621                         find_good_pkt_pointers(other_branch, dst_reg,
6622                                                dst_reg->type, true);
6623                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6624                             src_reg->type == PTR_TO_PACKET) ||
6625                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6626                             src_reg->type == PTR_TO_PACKET_META)) {
6627                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
6628                         find_good_pkt_pointers(this_branch, src_reg,
6629                                                src_reg->type, false);
6630                 } else {
6631                         return false;
6632                 }
6633                 break;
6634         case BPF_JGE:
6635                 if ((dst_reg->type == PTR_TO_PACKET &&
6636                      src_reg->type == PTR_TO_PACKET_END) ||
6637                     (dst_reg->type == PTR_TO_PACKET_META &&
6638                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6639                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
6640                         find_good_pkt_pointers(this_branch, dst_reg,
6641                                                dst_reg->type, true);
6642                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6643                             src_reg->type == PTR_TO_PACKET) ||
6644                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6645                             src_reg->type == PTR_TO_PACKET_META)) {
6646                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
6647                         find_good_pkt_pointers(other_branch, src_reg,
6648                                                src_reg->type, false);
6649                 } else {
6650                         return false;
6651                 }
6652                 break;
6653         case BPF_JLE:
6654                 if ((dst_reg->type == PTR_TO_PACKET &&
6655                      src_reg->type == PTR_TO_PACKET_END) ||
6656                     (dst_reg->type == PTR_TO_PACKET_META &&
6657                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6658                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
6659                         find_good_pkt_pointers(other_branch, dst_reg,
6660                                                dst_reg->type, false);
6661                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6662                             src_reg->type == PTR_TO_PACKET) ||
6663                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6664                             src_reg->type == PTR_TO_PACKET_META)) {
6665                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
6666                         find_good_pkt_pointers(this_branch, src_reg,
6667                                                src_reg->type, true);
6668                 } else {
6669                         return false;
6670                 }
6671                 break;
6672         default:
6673                 return false;
6674         }
6675
6676         return true;
6677 }
6678
6679 static int check_cond_jmp_op(struct bpf_verifier_env *env,
6680                              struct bpf_insn *insn, int *insn_idx)
6681 {
6682         struct bpf_verifier_state *this_branch = env->cur_state;
6683         struct bpf_verifier_state *other_branch;
6684         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
6685         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
6686         u8 opcode = BPF_OP(insn->code);
6687         bool is_jmp32;
6688         int pred = -1;
6689         int err;
6690
6691         /* Only conditional jumps are expected to reach here. */
6692         if (opcode == BPF_JA || opcode > BPF_JSLE) {
6693                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
6694                 return -EINVAL;
6695         }
6696
6697         if (BPF_SRC(insn->code) == BPF_X) {
6698                 if (insn->imm != 0) {
6699                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
6700                         return -EINVAL;
6701                 }
6702
6703                 /* check src1 operand */
6704                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6705                 if (err)
6706                         return err;
6707
6708                 if (is_pointer_value(env, insn->src_reg)) {
6709                         verbose(env, "R%d pointer comparison prohibited\n",
6710                                 insn->src_reg);
6711                         return -EACCES;
6712                 }
6713                 src_reg = &regs[insn->src_reg];
6714         } else {
6715                 if (insn->src_reg != BPF_REG_0) {
6716                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
6717                         return -EINVAL;
6718                 }
6719         }
6720
6721         /* check src2 operand */
6722         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6723         if (err)
6724                 return err;
6725
6726         dst_reg = &regs[insn->dst_reg];
6727         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
6728
6729         if (BPF_SRC(insn->code) == BPF_K) {
6730                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
6731         } else if (src_reg->type == SCALAR_VALUE &&
6732                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
6733                 pred = is_branch_taken(dst_reg,
6734                                        tnum_subreg(src_reg->var_off).value,
6735                                        opcode,
6736                                        is_jmp32);
6737         } else if (src_reg->type == SCALAR_VALUE &&
6738                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
6739                 pred = is_branch_taken(dst_reg,
6740                                        src_reg->var_off.value,
6741                                        opcode,
6742                                        is_jmp32);
6743         }
6744
6745         if (pred >= 0) {
6746                 err = mark_chain_precision(env, insn->dst_reg);
6747                 if (BPF_SRC(insn->code) == BPF_X && !err)
6748                         err = mark_chain_precision(env, insn->src_reg);
6749                 if (err)
6750                         return err;
6751         }
6752         if (pred == 1) {
6753                 /* only follow the goto, ignore fall-through */
6754                 *insn_idx += insn->off;
6755                 return 0;
6756         } else if (pred == 0) {
6757                 /* only follow fall-through branch, since
6758                  * that's where the program will go
6759                  */
6760                 return 0;
6761         }
6762
6763         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
6764                                   false);
6765         if (!other_branch)
6766                 return -EFAULT;
6767         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
6768
6769         /* detect if we are comparing against a constant value so we can adjust
6770          * our min/max values for our dst register.
6771          * this is only legit if both are scalars (or pointers to the same
6772          * object, I suppose, but we don't support that right now), because
6773          * otherwise the different base pointers mean the offsets aren't
6774          * comparable.
6775          */
6776         if (BPF_SRC(insn->code) == BPF_X) {
6777                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
6778
6779                 if (dst_reg->type == SCALAR_VALUE &&
6780                     src_reg->type == SCALAR_VALUE) {
6781                         if (tnum_is_const(src_reg->var_off) ||
6782                             (is_jmp32 &&
6783                              tnum_is_const(tnum_subreg(src_reg->var_off))))
6784                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
6785                                                 dst_reg,
6786                                                 src_reg->var_off.value,
6787                                                 tnum_subreg(src_reg->var_off).value,
6788                                                 opcode, is_jmp32);
6789                         else if (tnum_is_const(dst_reg->var_off) ||
6790                                  (is_jmp32 &&
6791                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
6792                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
6793                                                     src_reg,
6794                                                     dst_reg->var_off.value,
6795                                                     tnum_subreg(dst_reg->var_off).value,
6796                                                     opcode, is_jmp32);
6797                         else if (!is_jmp32 &&
6798                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
6799                                 /* Comparing for equality, we can combine knowledge */
6800                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
6801                                                     &other_branch_regs[insn->dst_reg],
6802                                                     src_reg, dst_reg, opcode);
6803                 }
6804         } else if (dst_reg->type == SCALAR_VALUE) {
6805                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
6806                                         dst_reg, insn->imm, (u32)insn->imm,
6807                                         opcode, is_jmp32);
6808         }
6809
6810         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
6811          * NOTE: these optimizations below are related with pointer comparison
6812          *       which will never be JMP32.
6813          */
6814         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
6815             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
6816             reg_type_may_be_null(dst_reg->type)) {
6817                 /* Mark all identical registers in each branch as either
6818                  * safe or unknown depending R == 0 or R != 0 conditional.
6819                  */
6820                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
6821                                       opcode == BPF_JNE);
6822                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
6823                                       opcode == BPF_JEQ);
6824         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
6825                                            this_branch, other_branch) &&
6826                    is_pointer_value(env, insn->dst_reg)) {
6827                 verbose(env, "R%d pointer comparison prohibited\n",
6828                         insn->dst_reg);
6829                 return -EACCES;
6830         }
6831         if (env->log.level & BPF_LOG_LEVEL)
6832                 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
6833         return 0;
6834 }
6835
6836 /* verify BPF_LD_IMM64 instruction */
6837 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
6838 {
6839         struct bpf_insn_aux_data *aux = cur_aux(env);
6840         struct bpf_reg_state *regs = cur_regs(env);
6841         struct bpf_map *map;
6842         int err;
6843
6844         if (BPF_SIZE(insn->code) != BPF_DW) {
6845                 verbose(env, "invalid BPF_LD_IMM insn\n");
6846                 return -EINVAL;
6847         }
6848         if (insn->off != 0) {
6849                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
6850                 return -EINVAL;
6851         }
6852
6853         err = check_reg_arg(env, insn->dst_reg, DST_OP);
6854         if (err)
6855                 return err;
6856
6857         if (insn->src_reg == 0) {
6858                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
6859
6860                 regs[insn->dst_reg].type = SCALAR_VALUE;
6861                 __mark_reg_known(&regs[insn->dst_reg], imm);
6862                 return 0;
6863         }
6864
6865         map = env->used_maps[aux->map_index];
6866         mark_reg_known_zero(env, regs, insn->dst_reg);
6867         regs[insn->dst_reg].map_ptr = map;
6868
6869         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
6870                 regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
6871                 regs[insn->dst_reg].off = aux->map_off;
6872                 if (map_value_has_spin_lock(map))
6873                         regs[insn->dst_reg].id = ++env->id_gen;
6874         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
6875                 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
6876         } else {
6877                 verbose(env, "bpf verifier is misconfigured\n");
6878                 return -EINVAL;
6879         }
6880
6881         return 0;
6882 }
6883
6884 static bool may_access_skb(enum bpf_prog_type type)
6885 {
6886         switch (type) {
6887         case BPF_PROG_TYPE_SOCKET_FILTER:
6888         case BPF_PROG_TYPE_SCHED_CLS:
6889         case BPF_PROG_TYPE_SCHED_ACT:
6890                 return true;
6891         default:
6892                 return false;
6893         }
6894 }
6895
6896 /* verify safety of LD_ABS|LD_IND instructions:
6897  * - they can only appear in the programs where ctx == skb
6898  * - since they are wrappers of function calls, they scratch R1-R5 registers,
6899  *   preserve R6-R9, and store return value into R0
6900  *
6901  * Implicit input:
6902  *   ctx == skb == R6 == CTX
6903  *
6904  * Explicit input:
6905  *   SRC == any register
6906  *   IMM == 32-bit immediate
6907  *
6908  * Output:
6909  *   R0 - 8/16/32-bit skb data converted to cpu endianness
6910  */
6911 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
6912 {
6913         struct bpf_reg_state *regs = cur_regs(env);
6914         static const int ctx_reg = BPF_REG_6;
6915         u8 mode = BPF_MODE(insn->code);
6916         int i, err;
6917
6918         if (!may_access_skb(env->prog->type)) {
6919                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
6920                 return -EINVAL;
6921         }
6922
6923         if (!env->ops->gen_ld_abs) {
6924                 verbose(env, "bpf verifier is misconfigured\n");
6925                 return -EINVAL;
6926         }
6927
6928         if (env->subprog_cnt > 1) {
6929                 /* when program has LD_ABS insn JITs and interpreter assume
6930                  * that r1 == ctx == skb which is not the case for callees
6931                  * that can have arbitrary arguments. It's problematic
6932                  * for main prog as well since JITs would need to analyze
6933                  * all functions in order to make proper register save/restore
6934                  * decisions in the main prog. Hence disallow LD_ABS with calls
6935                  */
6936                 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
6937                 return -EINVAL;
6938         }
6939
6940         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
6941             BPF_SIZE(insn->code) == BPF_DW ||
6942             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
6943                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
6944                 return -EINVAL;
6945         }
6946
6947         /* check whether implicit source operand (register R6) is readable */
6948         err = check_reg_arg(env, ctx_reg, SRC_OP);
6949         if (err)
6950                 return err;
6951
6952         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
6953          * gen_ld_abs() may terminate the program at runtime, leading to
6954          * reference leak.
6955          */
6956         err = check_reference_leak(env);
6957         if (err) {
6958                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
6959                 return err;
6960         }
6961
6962         if (env->cur_state->active_spin_lock) {
6963                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
6964                 return -EINVAL;
6965         }
6966
6967         if (regs[ctx_reg].type != PTR_TO_CTX) {
6968                 verbose(env,
6969                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
6970                 return -EINVAL;
6971         }
6972
6973         if (mode == BPF_IND) {
6974                 /* check explicit source operand */
6975                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6976                 if (err)
6977                         return err;
6978         }
6979
6980         err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
6981         if (err < 0)
6982                 return err;
6983
6984         /* reset caller saved regs to unreadable */
6985         for (i = 0; i < CALLER_SAVED_REGS; i++) {
6986                 mark_reg_not_init(env, regs, caller_saved[i]);
6987                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6988         }
6989
6990         /* mark destination R0 register as readable, since it contains
6991          * the value fetched from the packet.
6992          * Already marked as written above.
6993          */
6994         mark_reg_unknown(env, regs, BPF_REG_0);
6995         /* ld_abs load up to 32-bit skb data. */
6996         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
6997         return 0;
6998 }
6999
7000 static int check_return_code(struct bpf_verifier_env *env)
7001 {
7002         struct tnum enforce_attach_type_range = tnum_unknown;
7003         const struct bpf_prog *prog = env->prog;
7004         struct bpf_reg_state *reg;
7005         struct tnum range = tnum_range(0, 1);
7006         int err;
7007
7008         /* LSM and struct_ops func-ptr's return type could be "void" */
7009         if ((env->prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
7010              env->prog->type == BPF_PROG_TYPE_LSM) &&
7011             !prog->aux->attach_func_proto->type)
7012                 return 0;
7013
7014         /* eBPF calling convetion is such that R0 is used
7015          * to return the value from eBPF program.
7016          * Make sure that it's readable at this time
7017          * of bpf_exit, which means that program wrote
7018          * something into it earlier
7019          */
7020         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
7021         if (err)
7022                 return err;
7023
7024         if (is_pointer_value(env, BPF_REG_0)) {
7025                 verbose(env, "R0 leaks addr as return value\n");
7026                 return -EACCES;
7027         }
7028
7029         switch (env->prog->type) {
7030         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
7031                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
7032                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG)
7033                         range = tnum_range(1, 1);
7034                 break;
7035         case BPF_PROG_TYPE_CGROUP_SKB:
7036                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
7037                         range = tnum_range(0, 3);
7038                         enforce_attach_type_range = tnum_range(2, 3);
7039                 }
7040                 break;
7041         case BPF_PROG_TYPE_CGROUP_SOCK:
7042         case BPF_PROG_TYPE_SOCK_OPS:
7043         case BPF_PROG_TYPE_CGROUP_DEVICE:
7044         case BPF_PROG_TYPE_CGROUP_SYSCTL:
7045         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
7046                 break;
7047         case BPF_PROG_TYPE_RAW_TRACEPOINT:
7048                 if (!env->prog->aux->attach_btf_id)
7049                         return 0;
7050                 range = tnum_const(0);
7051                 break;
7052         default:
7053                 return 0;
7054         }
7055
7056         reg = cur_regs(env) + BPF_REG_0;
7057         if (reg->type != SCALAR_VALUE) {
7058                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
7059                         reg_type_str[reg->type]);
7060                 return -EINVAL;
7061         }
7062
7063         if (!tnum_in(range, reg->var_off)) {
7064                 char tn_buf[48];
7065
7066                 verbose(env, "At program exit the register R0 ");
7067                 if (!tnum_is_unknown(reg->var_off)) {
7068                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7069                         verbose(env, "has value %s", tn_buf);
7070                 } else {
7071                         verbose(env, "has unknown scalar value");
7072                 }
7073                 tnum_strn(tn_buf, sizeof(tn_buf), range);
7074                 verbose(env, " should have been in %s\n", tn_buf);
7075                 return -EINVAL;
7076         }
7077
7078         if (!tnum_is_unknown(enforce_attach_type_range) &&
7079             tnum_in(enforce_attach_type_range, reg->var_off))
7080                 env->prog->enforce_expected_attach_type = 1;
7081         return 0;
7082 }
7083
7084 /* non-recursive DFS pseudo code
7085  * 1  procedure DFS-iterative(G,v):
7086  * 2      label v as discovered
7087  * 3      let S be a stack
7088  * 4      S.push(v)
7089  * 5      while S is not empty
7090  * 6            t <- S.pop()
7091  * 7            if t is what we're looking for:
7092  * 8                return t
7093  * 9            for all edges e in G.adjacentEdges(t) do
7094  * 10               if edge e is already labelled
7095  * 11                   continue with the next edge
7096  * 12               w <- G.adjacentVertex(t,e)
7097  * 13               if vertex w is not discovered and not explored
7098  * 14                   label e as tree-edge
7099  * 15                   label w as discovered
7100  * 16                   S.push(w)
7101  * 17                   continue at 5
7102  * 18               else if vertex w is discovered
7103  * 19                   label e as back-edge
7104  * 20               else
7105  * 21                   // vertex w is explored
7106  * 22                   label e as forward- or cross-edge
7107  * 23           label t as explored
7108  * 24           S.pop()
7109  *
7110  * convention:
7111  * 0x10 - discovered
7112  * 0x11 - discovered and fall-through edge labelled
7113  * 0x12 - discovered and fall-through and branch edges labelled
7114  * 0x20 - explored
7115  */
7116
7117 enum {
7118         DISCOVERED = 0x10,
7119         EXPLORED = 0x20,
7120         FALLTHROUGH = 1,
7121         BRANCH = 2,
7122 };
7123
7124 static u32 state_htab_size(struct bpf_verifier_env *env)
7125 {
7126         return env->prog->len;
7127 }
7128
7129 static struct bpf_verifier_state_list **explored_state(
7130                                         struct bpf_verifier_env *env,
7131                                         int idx)
7132 {
7133         struct bpf_verifier_state *cur = env->cur_state;
7134         struct bpf_func_state *state = cur->frame[cur->curframe];
7135
7136         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
7137 }
7138
7139 static void init_explored_state(struct bpf_verifier_env *env, int idx)
7140 {
7141         env->insn_aux_data[idx].prune_point = true;
7142 }
7143
7144 /* t, w, e - match pseudo-code above:
7145  * t - index of current instruction
7146  * w - next instruction
7147  * e - edge
7148  */
7149 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
7150                      bool loop_ok)
7151 {
7152         int *insn_stack = env->cfg.insn_stack;
7153         int *insn_state = env->cfg.insn_state;
7154
7155         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
7156                 return 0;
7157
7158         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
7159                 return 0;
7160
7161         if (w < 0 || w >= env->prog->len) {
7162                 verbose_linfo(env, t, "%d: ", t);
7163                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
7164                 return -EINVAL;
7165         }
7166
7167         if (e == BRANCH)
7168                 /* mark branch target for state pruning */
7169                 init_explored_state(env, w);
7170
7171         if (insn_state[w] == 0) {
7172                 /* tree-edge */
7173                 insn_state[t] = DISCOVERED | e;
7174                 insn_state[w] = DISCOVERED;
7175                 if (env->cfg.cur_stack >= env->prog->len)
7176                         return -E2BIG;
7177                 insn_stack[env->cfg.cur_stack++] = w;
7178                 return 1;
7179         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
7180                 if (loop_ok && env->allow_ptr_leaks)
7181                         return 0;
7182                 verbose_linfo(env, t, "%d: ", t);
7183                 verbose_linfo(env, w, "%d: ", w);
7184                 verbose(env, "back-edge from insn %d to %d\n", t, w);
7185                 return -EINVAL;
7186         } else if (insn_state[w] == EXPLORED) {
7187                 /* forward- or cross-edge */
7188                 insn_state[t] = DISCOVERED | e;
7189         } else {
7190                 verbose(env, "insn state internal bug\n");
7191                 return -EFAULT;
7192         }
7193         return 0;
7194 }
7195
7196 /* non-recursive depth-first-search to detect loops in BPF program
7197  * loop == back-edge in directed graph
7198  */
7199 static int check_cfg(struct bpf_verifier_env *env)
7200 {
7201         struct bpf_insn *insns = env->prog->insnsi;
7202         int insn_cnt = env->prog->len;
7203         int *insn_stack, *insn_state;
7204         int ret = 0;
7205         int i, t;
7206
7207         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
7208         if (!insn_state)
7209                 return -ENOMEM;
7210
7211         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
7212         if (!insn_stack) {
7213                 kvfree(insn_state);
7214                 return -ENOMEM;
7215         }
7216
7217         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
7218         insn_stack[0] = 0; /* 0 is the first instruction */
7219         env->cfg.cur_stack = 1;
7220
7221 peek_stack:
7222         if (env->cfg.cur_stack == 0)
7223                 goto check_state;
7224         t = insn_stack[env->cfg.cur_stack - 1];
7225
7226         if (BPF_CLASS(insns[t].code) == BPF_JMP ||
7227             BPF_CLASS(insns[t].code) == BPF_JMP32) {
7228                 u8 opcode = BPF_OP(insns[t].code);
7229
7230                 if (opcode == BPF_EXIT) {
7231                         goto mark_explored;
7232                 } else if (opcode == BPF_CALL) {
7233                         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
7234                         if (ret == 1)
7235                                 goto peek_stack;
7236                         else if (ret < 0)
7237                                 goto err_free;
7238                         if (t + 1 < insn_cnt)
7239                                 init_explored_state(env, t + 1);
7240                         if (insns[t].src_reg == BPF_PSEUDO_CALL) {
7241                                 init_explored_state(env, t);
7242                                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
7243                                                 env, false);
7244                                 if (ret == 1)
7245                                         goto peek_stack;
7246                                 else if (ret < 0)
7247                                         goto err_free;
7248                         }
7249                 } else if (opcode == BPF_JA) {
7250                         if (BPF_SRC(insns[t].code) != BPF_K) {
7251                                 ret = -EINVAL;
7252                                 goto err_free;
7253                         }
7254                         /* unconditional jump with single edge */
7255                         ret = push_insn(t, t + insns[t].off + 1,
7256                                         FALLTHROUGH, env, true);
7257                         if (ret == 1)
7258                                 goto peek_stack;
7259                         else if (ret < 0)
7260                                 goto err_free;
7261                         /* unconditional jmp is not a good pruning point,
7262                          * but it's marked, since backtracking needs
7263                          * to record jmp history in is_state_visited().
7264                          */
7265                         init_explored_state(env, t + insns[t].off + 1);
7266                         /* tell verifier to check for equivalent states
7267                          * after every call and jump
7268                          */
7269                         if (t + 1 < insn_cnt)
7270                                 init_explored_state(env, t + 1);
7271                 } else {
7272                         /* conditional jump with two edges */
7273                         init_explored_state(env, t);
7274                         ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
7275                         if (ret == 1)
7276                                 goto peek_stack;
7277                         else if (ret < 0)
7278                                 goto err_free;
7279
7280                         ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
7281                         if (ret == 1)
7282                                 goto peek_stack;
7283                         else if (ret < 0)
7284                                 goto err_free;
7285                 }
7286         } else {
7287                 /* all other non-branch instructions with single
7288                  * fall-through edge
7289                  */
7290                 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
7291                 if (ret == 1)
7292                         goto peek_stack;
7293                 else if (ret < 0)
7294                         goto err_free;
7295         }
7296
7297 mark_explored:
7298         insn_state[t] = EXPLORED;
7299         if (env->cfg.cur_stack-- <= 0) {
7300                 verbose(env, "pop stack internal bug\n");
7301                 ret = -EFAULT;
7302                 goto err_free;
7303         }
7304         goto peek_stack;
7305
7306 check_state:
7307         for (i = 0; i < insn_cnt; i++) {
7308                 if (insn_state[i] != EXPLORED) {
7309                         verbose(env, "unreachable insn %d\n", i);
7310                         ret = -EINVAL;
7311                         goto err_free;
7312                 }
7313         }
7314         ret = 0; /* cfg looks good */
7315
7316 err_free:
7317         kvfree(insn_state);
7318         kvfree(insn_stack);
7319         env->cfg.insn_state = env->cfg.insn_stack = NULL;
7320         return ret;
7321 }
7322
7323 /* The minimum supported BTF func info size */
7324 #define MIN_BPF_FUNCINFO_SIZE   8
7325 #define MAX_FUNCINFO_REC_SIZE   252
7326
7327 static int check_btf_func(struct bpf_verifier_env *env,
7328                           const union bpf_attr *attr,
7329                           union bpf_attr __user *uattr)
7330 {
7331         u32 i, nfuncs, urec_size, min_size;
7332         u32 krec_size = sizeof(struct bpf_func_info);
7333         struct bpf_func_info *krecord;
7334         struct bpf_func_info_aux *info_aux = NULL;
7335         const struct btf_type *type;
7336         struct bpf_prog *prog;
7337         const struct btf *btf;
7338         void __user *urecord;
7339         u32 prev_offset = 0;
7340         int ret = 0;
7341
7342         nfuncs = attr->func_info_cnt;
7343         if (!nfuncs)
7344                 return 0;
7345
7346         if (nfuncs != env->subprog_cnt) {
7347                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
7348                 return -EINVAL;
7349         }
7350
7351         urec_size = attr->func_info_rec_size;
7352         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
7353             urec_size > MAX_FUNCINFO_REC_SIZE ||
7354             urec_size % sizeof(u32)) {
7355                 verbose(env, "invalid func info rec size %u\n", urec_size);
7356                 return -EINVAL;
7357         }
7358
7359         prog = env->prog;
7360         btf = prog->aux->btf;
7361
7362         urecord = u64_to_user_ptr(attr->func_info);
7363         min_size = min_t(u32, krec_size, urec_size);
7364
7365         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
7366         if (!krecord)
7367                 return -ENOMEM;
7368         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
7369         if (!info_aux)
7370                 goto err_free;
7371
7372         for (i = 0; i < nfuncs; i++) {
7373                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
7374                 if (ret) {
7375                         if (ret == -E2BIG) {
7376                                 verbose(env, "nonzero tailing record in func info");
7377                                 /* set the size kernel expects so loader can zero
7378                                  * out the rest of the record.
7379                                  */
7380                                 if (put_user(min_size, &uattr->func_info_rec_size))
7381                                         ret = -EFAULT;
7382                         }
7383                         goto err_free;
7384                 }
7385
7386                 if (copy_from_user(&krecord[i], urecord, min_size)) {
7387                         ret = -EFAULT;
7388                         goto err_free;
7389                 }
7390
7391                 /* check insn_off */
7392                 if (i == 0) {
7393                         if (krecord[i].insn_off) {
7394                                 verbose(env,
7395                                         "nonzero insn_off %u for the first func info record",
7396                                         krecord[i].insn_off);
7397                                 ret = -EINVAL;
7398                                 goto err_free;
7399                         }
7400                 } else if (krecord[i].insn_off <= prev_offset) {
7401                         verbose(env,
7402                                 "same or smaller insn offset (%u) than previous func info record (%u)",
7403                                 krecord[i].insn_off, prev_offset);
7404                         ret = -EINVAL;
7405                         goto err_free;
7406                 }
7407
7408                 if (env->subprog_info[i].start != krecord[i].insn_off) {
7409                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
7410                         ret = -EINVAL;
7411                         goto err_free;
7412                 }
7413
7414                 /* check type_id */
7415                 type = btf_type_by_id(btf, krecord[i].type_id);
7416                 if (!type || !btf_type_is_func(type)) {
7417                         verbose(env, "invalid type id %d in func info",
7418                                 krecord[i].type_id);
7419                         ret = -EINVAL;
7420                         goto err_free;
7421                 }
7422                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
7423                 prev_offset = krecord[i].insn_off;
7424                 urecord += urec_size;
7425         }
7426
7427         prog->aux->func_info = krecord;
7428         prog->aux->func_info_cnt = nfuncs;
7429         prog->aux->func_info_aux = info_aux;
7430         return 0;
7431
7432 err_free:
7433         kvfree(krecord);
7434         kfree(info_aux);
7435         return ret;
7436 }
7437
7438 static void adjust_btf_func(struct bpf_verifier_env *env)
7439 {
7440         struct bpf_prog_aux *aux = env->prog->aux;
7441         int i;
7442
7443         if (!aux->func_info)
7444                 return;
7445
7446         for (i = 0; i < env->subprog_cnt; i++)
7447                 aux->func_info[i].insn_off = env->subprog_info[i].start;
7448 }
7449
7450 #define MIN_BPF_LINEINFO_SIZE   (offsetof(struct bpf_line_info, line_col) + \
7451                 sizeof(((struct bpf_line_info *)(0))->line_col))
7452 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
7453
7454 static int check_btf_line(struct bpf_verifier_env *env,
7455                           const union bpf_attr *attr,
7456                           union bpf_attr __user *uattr)
7457 {
7458         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
7459         struct bpf_subprog_info *sub;
7460         struct bpf_line_info *linfo;
7461         struct bpf_prog *prog;
7462         const struct btf *btf;
7463         void __user *ulinfo;
7464         int err;
7465
7466         nr_linfo = attr->line_info_cnt;
7467         if (!nr_linfo)
7468                 return 0;
7469
7470         rec_size = attr->line_info_rec_size;
7471         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
7472             rec_size > MAX_LINEINFO_REC_SIZE ||
7473             rec_size & (sizeof(u32) - 1))
7474                 return -EINVAL;
7475
7476         /* Need to zero it in case the userspace may
7477          * pass in a smaller bpf_line_info object.
7478          */
7479         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
7480                          GFP_KERNEL | __GFP_NOWARN);
7481         if (!linfo)
7482                 return -ENOMEM;
7483
7484         prog = env->prog;
7485         btf = prog->aux->btf;
7486
7487         s = 0;
7488         sub = env->subprog_info;
7489         ulinfo = u64_to_user_ptr(attr->line_info);
7490         expected_size = sizeof(struct bpf_line_info);
7491         ncopy = min_t(u32, expected_size, rec_size);
7492         for (i = 0; i < nr_linfo; i++) {
7493                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
7494                 if (err) {
7495                         if (err == -E2BIG) {
7496                                 verbose(env, "nonzero tailing record in line_info");
7497                                 if (put_user(expected_size,
7498                                              &uattr->line_info_rec_size))
7499                                         err = -EFAULT;
7500                         }
7501                         goto err_free;
7502                 }
7503
7504                 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
7505                         err = -EFAULT;
7506                         goto err_free;
7507                 }
7508
7509                 /*
7510                  * Check insn_off to ensure
7511                  * 1) strictly increasing AND
7512                  * 2) bounded by prog->len
7513                  *
7514                  * The linfo[0].insn_off == 0 check logically falls into
7515                  * the later "missing bpf_line_info for func..." case
7516                  * because the first linfo[0].insn_off must be the
7517                  * first sub also and the first sub must have
7518                  * subprog_info[0].start == 0.
7519                  */
7520                 if ((i && linfo[i].insn_off <= prev_offset) ||
7521                     linfo[i].insn_off >= prog->len) {
7522                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
7523                                 i, linfo[i].insn_off, prev_offset,
7524                                 prog->len);
7525                         err = -EINVAL;
7526                         goto err_free;
7527                 }
7528
7529                 if (!prog->insnsi[linfo[i].insn_off].code) {
7530                         verbose(env,
7531                                 "Invalid insn code at line_info[%u].insn_off\n",
7532                                 i);
7533                         err = -EINVAL;
7534                         goto err_free;
7535                 }
7536
7537                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
7538                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
7539                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
7540                         err = -EINVAL;
7541                         goto err_free;
7542                 }
7543
7544                 if (s != env->subprog_cnt) {
7545                         if (linfo[i].insn_off == sub[s].start) {
7546                                 sub[s].linfo_idx = i;
7547                                 s++;
7548                         } else if (sub[s].start < linfo[i].insn_off) {
7549                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
7550                                 err = -EINVAL;
7551                                 goto err_free;
7552                         }
7553                 }
7554
7555                 prev_offset = linfo[i].insn_off;
7556                 ulinfo += rec_size;
7557         }
7558
7559         if (s != env->subprog_cnt) {
7560                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
7561                         env->subprog_cnt - s, s);
7562                 err = -EINVAL;
7563                 goto err_free;
7564         }
7565
7566         prog->aux->linfo = linfo;
7567         prog->aux->nr_linfo = nr_linfo;
7568
7569         return 0;
7570
7571 err_free:
7572         kvfree(linfo);
7573         return err;
7574 }
7575
7576 static int check_btf_info(struct bpf_verifier_env *env,
7577                           const union bpf_attr *attr,
7578                           union bpf_attr __user *uattr)
7579 {
7580         struct btf *btf;
7581         int err;
7582
7583         if (!attr->func_info_cnt && !attr->line_info_cnt)
7584                 return 0;
7585
7586         btf = btf_get_by_fd(attr->prog_btf_fd);
7587         if (IS_ERR(btf))
7588                 return PTR_ERR(btf);
7589         env->prog->aux->btf = btf;
7590
7591         err = check_btf_func(env, attr, uattr);
7592         if (err)
7593                 return err;
7594
7595         err = check_btf_line(env, attr, uattr);
7596         if (err)
7597                 return err;
7598
7599         return 0;
7600 }
7601
7602 /* check %cur's range satisfies %old's */
7603 static bool range_within(struct bpf_reg_state *old,
7604                          struct bpf_reg_state *cur)
7605 {
7606         return old->umin_value <= cur->umin_value &&
7607                old->umax_value >= cur->umax_value &&
7608                old->smin_value <= cur->smin_value &&
7609                old->smax_value >= cur->smax_value;
7610 }
7611
7612 /* Maximum number of register states that can exist at once */
7613 #define ID_MAP_SIZE     (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
7614 struct idpair {
7615         u32 old;
7616         u32 cur;
7617 };
7618
7619 /* If in the old state two registers had the same id, then they need to have
7620  * the same id in the new state as well.  But that id could be different from
7621  * the old state, so we need to track the mapping from old to new ids.
7622  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
7623  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
7624  * regs with a different old id could still have new id 9, we don't care about
7625  * that.
7626  * So we look through our idmap to see if this old id has been seen before.  If
7627  * so, we require the new id to match; otherwise, we add the id pair to the map.
7628  */
7629 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
7630 {
7631         unsigned int i;
7632
7633         for (i = 0; i < ID_MAP_SIZE; i++) {
7634                 if (!idmap[i].old) {
7635                         /* Reached an empty slot; haven't seen this id before */
7636                         idmap[i].old = old_id;
7637                         idmap[i].cur = cur_id;
7638                         return true;
7639                 }
7640                 if (idmap[i].old == old_id)
7641                         return idmap[i].cur == cur_id;
7642         }
7643         /* We ran out of idmap slots, which should be impossible */
7644         WARN_ON_ONCE(1);
7645         return false;
7646 }
7647
7648 static void clean_func_state(struct bpf_verifier_env *env,
7649                              struct bpf_func_state *st)
7650 {
7651         enum bpf_reg_liveness live;
7652         int i, j;
7653
7654         for (i = 0; i < BPF_REG_FP; i++) {
7655                 live = st->regs[i].live;
7656                 /* liveness must not touch this register anymore */
7657                 st->regs[i].live |= REG_LIVE_DONE;
7658                 if (!(live & REG_LIVE_READ))
7659                         /* since the register is unused, clear its state
7660                          * to make further comparison simpler
7661                          */
7662                         __mark_reg_not_init(env, &st->regs[i]);
7663         }
7664
7665         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
7666                 live = st->stack[i].spilled_ptr.live;
7667                 /* liveness must not touch this stack slot anymore */
7668                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
7669                 if (!(live & REG_LIVE_READ)) {
7670                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
7671                         for (j = 0; j < BPF_REG_SIZE; j++)
7672                                 st->stack[i].slot_type[j] = STACK_INVALID;
7673                 }
7674         }
7675 }
7676
7677 static void clean_verifier_state(struct bpf_verifier_env *env,
7678                                  struct bpf_verifier_state *st)
7679 {
7680         int i;
7681
7682         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
7683                 /* all regs in this state in all frames were already marked */
7684                 return;
7685
7686         for (i = 0; i <= st->curframe; i++)
7687                 clean_func_state(env, st->frame[i]);
7688 }
7689
7690 /* the parentage chains form a tree.
7691  * the verifier states are added to state lists at given insn and
7692  * pushed into state stack for future exploration.
7693  * when the verifier reaches bpf_exit insn some of the verifer states
7694  * stored in the state lists have their final liveness state already,
7695  * but a lot of states will get revised from liveness point of view when
7696  * the verifier explores other branches.
7697  * Example:
7698  * 1: r0 = 1
7699  * 2: if r1 == 100 goto pc+1
7700  * 3: r0 = 2
7701  * 4: exit
7702  * when the verifier reaches exit insn the register r0 in the state list of
7703  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
7704  * of insn 2 and goes exploring further. At the insn 4 it will walk the
7705  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
7706  *
7707  * Since the verifier pushes the branch states as it sees them while exploring
7708  * the program the condition of walking the branch instruction for the second
7709  * time means that all states below this branch were already explored and
7710  * their final liveness markes are already propagated.
7711  * Hence when the verifier completes the search of state list in is_state_visited()
7712  * we can call this clean_live_states() function to mark all liveness states
7713  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
7714  * will not be used.
7715  * This function also clears the registers and stack for states that !READ
7716  * to simplify state merging.
7717  *
7718  * Important note here that walking the same branch instruction in the callee
7719  * doesn't meant that the states are DONE. The verifier has to compare
7720  * the callsites
7721  */
7722 static void clean_live_states(struct bpf_verifier_env *env, int insn,
7723                               struct bpf_verifier_state *cur)
7724 {
7725         struct bpf_verifier_state_list *sl;
7726         int i;
7727
7728         sl = *explored_state(env, insn);
7729         while (sl) {
7730                 if (sl->state.branches)
7731                         goto next;
7732                 if (sl->state.insn_idx != insn ||
7733                     sl->state.curframe != cur->curframe)
7734                         goto next;
7735                 for (i = 0; i <= cur->curframe; i++)
7736                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
7737                                 goto next;
7738                 clean_verifier_state(env, &sl->state);
7739 next:
7740                 sl = sl->next;
7741         }
7742 }
7743
7744 /* Returns true if (rold safe implies rcur safe) */
7745 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7746                     struct idpair *idmap)
7747 {
7748         bool equal;
7749
7750         if (!(rold->live & REG_LIVE_READ))
7751                 /* explored state didn't use this */
7752                 return true;
7753
7754         equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
7755
7756         if (rold->type == PTR_TO_STACK)
7757                 /* two stack pointers are equal only if they're pointing to
7758                  * the same stack frame, since fp-8 in foo != fp-8 in bar
7759                  */
7760                 return equal && rold->frameno == rcur->frameno;
7761
7762         if (equal)
7763                 return true;
7764
7765         if (rold->type == NOT_INIT)
7766                 /* explored state can't have used this */
7767                 return true;
7768         if (rcur->type == NOT_INIT)
7769                 return false;
7770         switch (rold->type) {
7771         case SCALAR_VALUE:
7772                 if (rcur->type == SCALAR_VALUE) {
7773                         if (!rold->precise && !rcur->precise)
7774                                 return true;
7775                         /* new val must satisfy old val knowledge */
7776                         return range_within(rold, rcur) &&
7777                                tnum_in(rold->var_off, rcur->var_off);
7778                 } else {
7779                         /* We're trying to use a pointer in place of a scalar.
7780                          * Even if the scalar was unbounded, this could lead to
7781                          * pointer leaks because scalars are allowed to leak
7782                          * while pointers are not. We could make this safe in
7783                          * special cases if root is calling us, but it's
7784                          * probably not worth the hassle.
7785                          */
7786                         return false;
7787                 }
7788         case PTR_TO_MAP_VALUE:
7789                 /* If the new min/max/var_off satisfy the old ones and
7790                  * everything else matches, we are OK.
7791                  * 'id' is not compared, since it's only used for maps with
7792                  * bpf_spin_lock inside map element and in such cases if
7793                  * the rest of the prog is valid for one map element then
7794                  * it's valid for all map elements regardless of the key
7795                  * used in bpf_map_lookup()
7796                  */
7797                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
7798                        range_within(rold, rcur) &&
7799                        tnum_in(rold->var_off, rcur->var_off);
7800         case PTR_TO_MAP_VALUE_OR_NULL:
7801                 /* a PTR_TO_MAP_VALUE could be safe to use as a
7802                  * PTR_TO_MAP_VALUE_OR_NULL into the same map.
7803                  * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
7804                  * checked, doing so could have affected others with the same
7805                  * id, and we can't check for that because we lost the id when
7806                  * we converted to a PTR_TO_MAP_VALUE.
7807                  */
7808                 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
7809                         return false;
7810                 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
7811                         return false;
7812                 /* Check our ids match any regs they're supposed to */
7813                 return check_ids(rold->id, rcur->id, idmap);
7814         case PTR_TO_PACKET_META:
7815         case PTR_TO_PACKET:
7816                 if (rcur->type != rold->type)
7817                         return false;
7818                 /* We must have at least as much range as the old ptr
7819                  * did, so that any accesses which were safe before are
7820                  * still safe.  This is true even if old range < old off,
7821                  * since someone could have accessed through (ptr - k), or
7822                  * even done ptr -= k in a register, to get a safe access.
7823                  */
7824                 if (rold->range > rcur->range)
7825                         return false;
7826                 /* If the offsets don't match, we can't trust our alignment;
7827                  * nor can we be sure that we won't fall out of range.
7828                  */
7829                 if (rold->off != rcur->off)
7830                         return false;
7831                 /* id relations must be preserved */
7832                 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
7833                         return false;
7834                 /* new val must satisfy old val knowledge */
7835                 return range_within(rold, rcur) &&
7836                        tnum_in(rold->var_off, rcur->var_off);
7837         case PTR_TO_CTX:
7838         case CONST_PTR_TO_MAP:
7839         case PTR_TO_PACKET_END:
7840         case PTR_TO_FLOW_KEYS:
7841         case PTR_TO_SOCKET:
7842         case PTR_TO_SOCKET_OR_NULL:
7843         case PTR_TO_SOCK_COMMON:
7844         case PTR_TO_SOCK_COMMON_OR_NULL:
7845         case PTR_TO_TCP_SOCK:
7846         case PTR_TO_TCP_SOCK_OR_NULL:
7847         case PTR_TO_XDP_SOCK:
7848                 /* Only valid matches are exact, which memcmp() above
7849                  * would have accepted
7850                  */
7851         default:
7852                 /* Don't know what's going on, just say it's not safe */
7853                 return false;
7854         }
7855
7856         /* Shouldn't get here; if we do, say it's not safe */
7857         WARN_ON_ONCE(1);
7858         return false;
7859 }
7860
7861 static bool stacksafe(struct bpf_func_state *old,
7862                       struct bpf_func_state *cur,
7863                       struct idpair *idmap)
7864 {
7865         int i, spi;
7866
7867         /* walk slots of the explored stack and ignore any additional
7868          * slots in the current stack, since explored(safe) state
7869          * didn't use them
7870          */
7871         for (i = 0; i < old->allocated_stack; i++) {
7872                 spi = i / BPF_REG_SIZE;
7873
7874                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
7875                         i += BPF_REG_SIZE - 1;
7876                         /* explored state didn't use this */
7877                         continue;
7878                 }
7879
7880                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
7881                         continue;
7882
7883                 /* explored stack has more populated slots than current stack
7884                  * and these slots were used
7885                  */
7886                 if (i >= cur->allocated_stack)
7887                         return false;
7888
7889                 /* if old state was safe with misc data in the stack
7890                  * it will be safe with zero-initialized stack.
7891                  * The opposite is not true
7892                  */
7893                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
7894                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
7895                         continue;
7896                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
7897                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
7898                         /* Ex: old explored (safe) state has STACK_SPILL in
7899                          * this stack slot, but current has has STACK_MISC ->
7900                          * this verifier states are not equivalent,
7901                          * return false to continue verification of this path
7902                          */
7903                         return false;
7904                 if (i % BPF_REG_SIZE)
7905                         continue;
7906                 if (old->stack[spi].slot_type[0] != STACK_SPILL)
7907                         continue;
7908                 if (!regsafe(&old->stack[spi].spilled_ptr,
7909                              &cur->stack[spi].spilled_ptr,
7910                              idmap))
7911                         /* when explored and current stack slot are both storing
7912                          * spilled registers, check that stored pointers types
7913                          * are the same as well.
7914                          * Ex: explored safe path could have stored
7915                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
7916                          * but current path has stored:
7917                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
7918                          * such verifier states are not equivalent.
7919                          * return false to continue verification of this path
7920                          */
7921                         return false;
7922         }
7923         return true;
7924 }
7925
7926 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
7927 {
7928         if (old->acquired_refs != cur->acquired_refs)
7929                 return false;
7930         return !memcmp(old->refs, cur->refs,
7931                        sizeof(*old->refs) * old->acquired_refs);
7932 }
7933
7934 /* compare two verifier states
7935  *
7936  * all states stored in state_list are known to be valid, since
7937  * verifier reached 'bpf_exit' instruction through them
7938  *
7939  * this function is called when verifier exploring different branches of
7940  * execution popped from the state stack. If it sees an old state that has
7941  * more strict register state and more strict stack state then this execution
7942  * branch doesn't need to be explored further, since verifier already
7943  * concluded that more strict state leads to valid finish.
7944  *
7945  * Therefore two states are equivalent if register state is more conservative
7946  * and explored stack state is more conservative than the current one.
7947  * Example:
7948  *       explored                   current
7949  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
7950  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
7951  *
7952  * In other words if current stack state (one being explored) has more
7953  * valid slots than old one that already passed validation, it means
7954  * the verifier can stop exploring and conclude that current state is valid too
7955  *
7956  * Similarly with registers. If explored state has register type as invalid
7957  * whereas register type in current state is meaningful, it means that
7958  * the current state will reach 'bpf_exit' instruction safely
7959  */
7960 static bool func_states_equal(struct bpf_func_state *old,
7961                               struct bpf_func_state *cur)
7962 {
7963         struct idpair *idmap;
7964         bool ret = false;
7965         int i;
7966
7967         idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
7968         /* If we failed to allocate the idmap, just say it's not safe */
7969         if (!idmap)
7970                 return false;
7971
7972         for (i = 0; i < MAX_BPF_REG; i++) {
7973                 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
7974                         goto out_free;
7975         }
7976
7977         if (!stacksafe(old, cur, idmap))
7978                 goto out_free;
7979
7980         if (!refsafe(old, cur))
7981                 goto out_free;
7982         ret = true;
7983 out_free:
7984         kfree(idmap);
7985         return ret;
7986 }
7987
7988 static bool states_equal(struct bpf_verifier_env *env,
7989                          struct bpf_verifier_state *old,
7990                          struct bpf_verifier_state *cur)
7991 {
7992         int i;
7993
7994         if (old->curframe != cur->curframe)
7995                 return false;
7996
7997         /* Verification state from speculative execution simulation
7998          * must never prune a non-speculative execution one.
7999          */
8000         if (old->speculative && !cur->speculative)
8001                 return false;
8002
8003         if (old->active_spin_lock != cur->active_spin_lock)
8004                 return false;
8005
8006         /* for states to be equal callsites have to be the same
8007          * and all frame states need to be equivalent
8008          */
8009         for (i = 0; i <= old->curframe; i++) {
8010                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
8011                         return false;
8012                 if (!func_states_equal(old->frame[i], cur->frame[i]))
8013                         return false;
8014         }
8015         return true;
8016 }
8017
8018 /* Return 0 if no propagation happened. Return negative error code if error
8019  * happened. Otherwise, return the propagated bit.
8020  */
8021 static int propagate_liveness_reg(struct bpf_verifier_env *env,
8022                                   struct bpf_reg_state *reg,
8023                                   struct bpf_reg_state *parent_reg)
8024 {
8025         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
8026         u8 flag = reg->live & REG_LIVE_READ;
8027         int err;
8028
8029         /* When comes here, read flags of PARENT_REG or REG could be any of
8030          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
8031          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
8032          */
8033         if (parent_flag == REG_LIVE_READ64 ||
8034             /* Or if there is no read flag from REG. */
8035             !flag ||
8036             /* Or if the read flag from REG is the same as PARENT_REG. */
8037             parent_flag == flag)
8038                 return 0;
8039
8040         err = mark_reg_read(env, reg, parent_reg, flag);
8041         if (err)
8042                 return err;
8043
8044         return flag;
8045 }
8046
8047 /* A write screens off any subsequent reads; but write marks come from the
8048  * straight-line code between a state and its parent.  When we arrive at an
8049  * equivalent state (jump target or such) we didn't arrive by the straight-line
8050  * code, so read marks in the state must propagate to the parent regardless
8051  * of the state's write marks. That's what 'parent == state->parent' comparison
8052  * in mark_reg_read() is for.
8053  */
8054 static int propagate_liveness(struct bpf_verifier_env *env,
8055                               const struct bpf_verifier_state *vstate,
8056                               struct bpf_verifier_state *vparent)
8057 {
8058         struct bpf_reg_state *state_reg, *parent_reg;
8059         struct bpf_func_state *state, *parent;
8060         int i, frame, err = 0;
8061
8062         if (vparent->curframe != vstate->curframe) {
8063                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
8064                      vparent->curframe, vstate->curframe);
8065                 return -EFAULT;
8066         }
8067         /* Propagate read liveness of registers... */
8068         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
8069         for (frame = 0; frame <= vstate->curframe; frame++) {
8070                 parent = vparent->frame[frame];
8071                 state = vstate->frame[frame];
8072                 parent_reg = parent->regs;
8073                 state_reg = state->regs;
8074                 /* We don't need to worry about FP liveness, it's read-only */
8075                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
8076                         err = propagate_liveness_reg(env, &state_reg[i],
8077                                                      &parent_reg[i]);
8078                         if (err < 0)
8079                                 return err;
8080                         if (err == REG_LIVE_READ64)
8081                                 mark_insn_zext(env, &parent_reg[i]);
8082                 }
8083
8084                 /* Propagate stack slots. */
8085                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
8086                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
8087                         parent_reg = &parent->stack[i].spilled_ptr;
8088                         state_reg = &state->stack[i].spilled_ptr;
8089                         err = propagate_liveness_reg(env, state_reg,
8090                                                      parent_reg);
8091                         if (err < 0)
8092                                 return err;
8093                 }
8094         }
8095         return 0;
8096 }
8097
8098 /* find precise scalars in the previous equivalent state and
8099  * propagate them into the current state
8100  */
8101 static int propagate_precision(struct bpf_verifier_env *env,
8102                                const struct bpf_verifier_state *old)
8103 {
8104         struct bpf_reg_state *state_reg;
8105         struct bpf_func_state *state;
8106         int i, err = 0;
8107
8108         state = old->frame[old->curframe];
8109         state_reg = state->regs;
8110         for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
8111                 if (state_reg->type != SCALAR_VALUE ||
8112                     !state_reg->precise)
8113                         continue;
8114                 if (env->log.level & BPF_LOG_LEVEL2)
8115                         verbose(env, "propagating r%d\n", i);
8116                 err = mark_chain_precision(env, i);
8117                 if (err < 0)
8118                         return err;
8119         }
8120
8121         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8122                 if (state->stack[i].slot_type[0] != STACK_SPILL)
8123                         continue;
8124                 state_reg = &state->stack[i].spilled_ptr;
8125                 if (state_reg->type != SCALAR_VALUE ||
8126                     !state_reg->precise)
8127                         continue;
8128                 if (env->log.level & BPF_LOG_LEVEL2)
8129                         verbose(env, "propagating fp%d\n",
8130                                 (-i - 1) * BPF_REG_SIZE);
8131                 err = mark_chain_precision_stack(env, i);
8132                 if (err < 0)
8133                         return err;
8134         }
8135         return 0;
8136 }
8137
8138 static bool states_maybe_looping(struct bpf_verifier_state *old,
8139                                  struct bpf_verifier_state *cur)
8140 {
8141         struct bpf_func_state *fold, *fcur;
8142         int i, fr = cur->curframe;
8143
8144         if (old->curframe != fr)
8145                 return false;
8146
8147         fold = old->frame[fr];
8148         fcur = cur->frame[fr];
8149         for (i = 0; i < MAX_BPF_REG; i++)
8150                 if (memcmp(&fold->regs[i], &fcur->regs[i],
8151                            offsetof(struct bpf_reg_state, parent)))
8152                         return false;
8153         return true;
8154 }
8155
8156
8157 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
8158 {
8159         struct bpf_verifier_state_list *new_sl;
8160         struct bpf_verifier_state_list *sl, **pprev;
8161         struct bpf_verifier_state *cur = env->cur_state, *new;
8162         int i, j, err, states_cnt = 0;
8163         bool add_new_state = env->test_state_freq ? true : false;
8164
8165         cur->last_insn_idx = env->prev_insn_idx;
8166         if (!env->insn_aux_data[insn_idx].prune_point)
8167                 /* this 'insn_idx' instruction wasn't marked, so we will not
8168                  * be doing state search here
8169                  */
8170                 return 0;
8171
8172         /* bpf progs typically have pruning point every 4 instructions
8173          * http://vger.kernel.org/bpfconf2019.html#session-1
8174          * Do not add new state for future pruning if the verifier hasn't seen
8175          * at least 2 jumps and at least 8 instructions.
8176          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
8177          * In tests that amounts to up to 50% reduction into total verifier
8178          * memory consumption and 20% verifier time speedup.
8179          */
8180         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
8181             env->insn_processed - env->prev_insn_processed >= 8)
8182                 add_new_state = true;
8183
8184         pprev = explored_state(env, insn_idx);
8185         sl = *pprev;
8186
8187         clean_live_states(env, insn_idx, cur);
8188
8189         while (sl) {
8190                 states_cnt++;
8191                 if (sl->state.insn_idx != insn_idx)
8192                         goto next;
8193                 if (sl->state.branches) {
8194                         if (states_maybe_looping(&sl->state, cur) &&
8195                             states_equal(env, &sl->state, cur)) {
8196                                 verbose_linfo(env, insn_idx, "; ");
8197                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
8198                                 return -EINVAL;
8199                         }
8200                         /* if the verifier is processing a loop, avoid adding new state
8201                          * too often, since different loop iterations have distinct
8202                          * states and may not help future pruning.
8203                          * This threshold shouldn't be too low to make sure that
8204                          * a loop with large bound will be rejected quickly.
8205                          * The most abusive loop will be:
8206                          * r1 += 1
8207                          * if r1 < 1000000 goto pc-2
8208                          * 1M insn_procssed limit / 100 == 10k peak states.
8209                          * This threshold shouldn't be too high either, since states
8210                          * at the end of the loop are likely to be useful in pruning.
8211                          */
8212                         if (env->jmps_processed - env->prev_jmps_processed < 20 &&
8213                             env->insn_processed - env->prev_insn_processed < 100)
8214                                 add_new_state = false;
8215                         goto miss;
8216                 }
8217                 if (states_equal(env, &sl->state, cur)) {
8218                         sl->hit_cnt++;
8219                         /* reached equivalent register/stack state,
8220                          * prune the search.
8221                          * Registers read by the continuation are read by us.
8222                          * If we have any write marks in env->cur_state, they
8223                          * will prevent corresponding reads in the continuation
8224                          * from reaching our parent (an explored_state).  Our
8225                          * own state will get the read marks recorded, but
8226                          * they'll be immediately forgotten as we're pruning
8227                          * this state and will pop a new one.
8228                          */
8229                         err = propagate_liveness(env, &sl->state, cur);
8230
8231                         /* if previous state reached the exit with precision and
8232                          * current state is equivalent to it (except precsion marks)
8233                          * the precision needs to be propagated back in
8234                          * the current state.
8235                          */
8236                         err = err ? : push_jmp_history(env, cur);
8237                         err = err ? : propagate_precision(env, &sl->state);
8238                         if (err)
8239                                 return err;
8240                         return 1;
8241                 }
8242 miss:
8243                 /* when new state is not going to be added do not increase miss count.
8244                  * Otherwise several loop iterations will remove the state
8245                  * recorded earlier. The goal of these heuristics is to have
8246                  * states from some iterations of the loop (some in the beginning
8247                  * and some at the end) to help pruning.
8248                  */
8249                 if (add_new_state)
8250                         sl->miss_cnt++;
8251                 /* heuristic to determine whether this state is beneficial
8252                  * to keep checking from state equivalence point of view.
8253                  * Higher numbers increase max_states_per_insn and verification time,
8254                  * but do not meaningfully decrease insn_processed.
8255                  */
8256                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
8257                         /* the state is unlikely to be useful. Remove it to
8258                          * speed up verification
8259                          */
8260                         *pprev = sl->next;
8261                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
8262                                 u32 br = sl->state.branches;
8263
8264                                 WARN_ONCE(br,
8265                                           "BUG live_done but branches_to_explore %d\n",
8266                                           br);
8267                                 free_verifier_state(&sl->state, false);
8268                                 kfree(sl);
8269                                 env->peak_states--;
8270                         } else {
8271                                 /* cannot free this state, since parentage chain may
8272                                  * walk it later. Add it for free_list instead to
8273                                  * be freed at the end of verification
8274                                  */
8275                                 sl->next = env->free_list;
8276                                 env->free_list = sl;
8277                         }
8278                         sl = *pprev;
8279                         continue;
8280                 }
8281 next:
8282                 pprev = &sl->next;
8283                 sl = *pprev;
8284         }
8285
8286         if (env->max_states_per_insn < states_cnt)
8287                 env->max_states_per_insn = states_cnt;
8288
8289         if (!env->allow_ptr_leaks && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
8290                 return push_jmp_history(env, cur);
8291
8292         if (!add_new_state)
8293                 return push_jmp_history(env, cur);
8294
8295         /* There were no equivalent states, remember the current one.
8296          * Technically the current state is not proven to be safe yet,
8297          * but it will either reach outer most bpf_exit (which means it's safe)
8298          * or it will be rejected. When there are no loops the verifier won't be
8299          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
8300          * again on the way to bpf_exit.
8301          * When looping the sl->state.branches will be > 0 and this state
8302          * will not be considered for equivalence until branches == 0.
8303          */
8304         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
8305         if (!new_sl)
8306                 return -ENOMEM;
8307         env->total_states++;
8308         env->peak_states++;
8309         env->prev_jmps_processed = env->jmps_processed;
8310         env->prev_insn_processed = env->insn_processed;
8311
8312         /* add new state to the head of linked list */
8313         new = &new_sl->state;
8314         err = copy_verifier_state(new, cur);
8315         if (err) {
8316                 free_verifier_state(new, false);
8317                 kfree(new_sl);
8318                 return err;
8319         }
8320         new->insn_idx = insn_idx;
8321         WARN_ONCE(new->branches != 1,
8322                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
8323
8324         cur->parent = new;
8325         cur->first_insn_idx = insn_idx;
8326         clear_jmp_history(cur);
8327         new_sl->next = *explored_state(env, insn_idx);
8328         *explored_state(env, insn_idx) = new_sl;
8329         /* connect new state to parentage chain. Current frame needs all
8330          * registers connected. Only r6 - r9 of the callers are alive (pushed
8331          * to the stack implicitly by JITs) so in callers' frames connect just
8332          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
8333          * the state of the call instruction (with WRITTEN set), and r0 comes
8334          * from callee with its full parentage chain, anyway.
8335          */
8336         /* clear write marks in current state: the writes we did are not writes
8337          * our child did, so they don't screen off its reads from us.
8338          * (There are no read marks in current state, because reads always mark
8339          * their parent and current state never has children yet.  Only
8340          * explored_states can get read marks.)
8341          */
8342         for (j = 0; j <= cur->curframe; j++) {
8343                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
8344                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
8345                 for (i = 0; i < BPF_REG_FP; i++)
8346                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
8347         }
8348
8349         /* all stack frames are accessible from callee, clear them all */
8350         for (j = 0; j <= cur->curframe; j++) {
8351                 struct bpf_func_state *frame = cur->frame[j];
8352                 struct bpf_func_state *newframe = new->frame[j];
8353
8354                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
8355                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
8356                         frame->stack[i].spilled_ptr.parent =
8357                                                 &newframe->stack[i].spilled_ptr;
8358                 }
8359         }
8360         return 0;
8361 }
8362
8363 /* Return true if it's OK to have the same insn return a different type. */
8364 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
8365 {
8366         switch (type) {
8367         case PTR_TO_CTX:
8368         case PTR_TO_SOCKET:
8369         case PTR_TO_SOCKET_OR_NULL:
8370         case PTR_TO_SOCK_COMMON:
8371         case PTR_TO_SOCK_COMMON_OR_NULL:
8372         case PTR_TO_TCP_SOCK:
8373         case PTR_TO_TCP_SOCK_OR_NULL:
8374         case PTR_TO_XDP_SOCK:
8375         case PTR_TO_BTF_ID:
8376                 return false;
8377         default:
8378                 return true;
8379         }
8380 }
8381
8382 /* If an instruction was previously used with particular pointer types, then we
8383  * need to be careful to avoid cases such as the below, where it may be ok
8384  * for one branch accessing the pointer, but not ok for the other branch:
8385  *
8386  * R1 = sock_ptr
8387  * goto X;
8388  * ...
8389  * R1 = some_other_valid_ptr;
8390  * goto X;
8391  * ...
8392  * R2 = *(u32 *)(R1 + 0);
8393  */
8394 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
8395 {
8396         return src != prev && (!reg_type_mismatch_ok(src) ||
8397                                !reg_type_mismatch_ok(prev));
8398 }
8399
8400 static int do_check(struct bpf_verifier_env *env)
8401 {
8402         struct bpf_verifier_state *state = env->cur_state;
8403         struct bpf_insn *insns = env->prog->insnsi;
8404         struct bpf_reg_state *regs;
8405         int insn_cnt = env->prog->len;
8406         bool do_print_state = false;
8407         int prev_insn_idx = -1;
8408
8409         for (;;) {
8410                 struct bpf_insn *insn;
8411                 u8 class;
8412                 int err;
8413
8414                 env->prev_insn_idx = prev_insn_idx;
8415                 if (env->insn_idx >= insn_cnt) {
8416                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
8417                                 env->insn_idx, insn_cnt);
8418                         return -EFAULT;
8419                 }
8420
8421                 insn = &insns[env->insn_idx];
8422                 class = BPF_CLASS(insn->code);
8423
8424                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
8425                         verbose(env,
8426                                 "BPF program is too large. Processed %d insn\n",
8427                                 env->insn_processed);
8428                         return -E2BIG;
8429                 }
8430
8431                 err = is_state_visited(env, env->insn_idx);
8432                 if (err < 0)
8433                         return err;
8434                 if (err == 1) {
8435                         /* found equivalent state, can prune the search */
8436                         if (env->log.level & BPF_LOG_LEVEL) {
8437                                 if (do_print_state)
8438                                         verbose(env, "\nfrom %d to %d%s: safe\n",
8439                                                 env->prev_insn_idx, env->insn_idx,
8440                                                 env->cur_state->speculative ?
8441                                                 " (speculative execution)" : "");
8442                                 else
8443                                         verbose(env, "%d: safe\n", env->insn_idx);
8444                         }
8445                         goto process_bpf_exit;
8446                 }
8447
8448                 if (signal_pending(current))
8449                         return -EAGAIN;
8450
8451                 if (need_resched())
8452                         cond_resched();
8453
8454                 if (env->log.level & BPF_LOG_LEVEL2 ||
8455                     (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
8456                         if (env->log.level & BPF_LOG_LEVEL2)
8457                                 verbose(env, "%d:", env->insn_idx);
8458                         else
8459                                 verbose(env, "\nfrom %d to %d%s:",
8460                                         env->prev_insn_idx, env->insn_idx,
8461                                         env->cur_state->speculative ?
8462                                         " (speculative execution)" : "");
8463                         print_verifier_state(env, state->frame[state->curframe]);
8464                         do_print_state = false;
8465                 }
8466
8467                 if (env->log.level & BPF_LOG_LEVEL) {
8468                         const struct bpf_insn_cbs cbs = {
8469                                 .cb_print       = verbose,
8470                                 .private_data   = env,
8471                         };
8472
8473                         verbose_linfo(env, env->insn_idx, "; ");
8474                         verbose(env, "%d: ", env->insn_idx);
8475                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
8476                 }
8477
8478                 if (bpf_prog_is_dev_bound(env->prog->aux)) {
8479                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
8480                                                            env->prev_insn_idx);
8481                         if (err)
8482                                 return err;
8483                 }
8484
8485                 regs = cur_regs(env);
8486                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8487                 prev_insn_idx = env->insn_idx;
8488
8489                 if (class == BPF_ALU || class == BPF_ALU64) {
8490                         err = check_alu_op(env, insn);
8491                         if (err)
8492                                 return err;
8493
8494                 } else if (class == BPF_LDX) {
8495                         enum bpf_reg_type *prev_src_type, src_reg_type;
8496
8497                         /* check for reserved fields is already done */
8498
8499                         /* check src operand */
8500                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
8501                         if (err)
8502                                 return err;
8503
8504                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8505                         if (err)
8506                                 return err;
8507
8508                         src_reg_type = regs[insn->src_reg].type;
8509
8510                         /* check that memory (src_reg + off) is readable,
8511                          * the state of dst_reg will be updated by this func
8512                          */
8513                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
8514                                                insn->off, BPF_SIZE(insn->code),
8515                                                BPF_READ, insn->dst_reg, false);
8516                         if (err)
8517                                 return err;
8518
8519                         prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
8520
8521                         if (*prev_src_type == NOT_INIT) {
8522                                 /* saw a valid insn
8523                                  * dst_reg = *(u32 *)(src_reg + off)
8524                                  * save type to validate intersecting paths
8525                                  */
8526                                 *prev_src_type = src_reg_type;
8527
8528                         } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
8529                                 /* ABuser program is trying to use the same insn
8530                                  * dst_reg = *(u32*) (src_reg + off)
8531                                  * with different pointer types:
8532                                  * src_reg == ctx in one branch and
8533                                  * src_reg == stack|map in some other branch.
8534                                  * Reject it.
8535                                  */
8536                                 verbose(env, "same insn cannot be used with different pointers\n");
8537                                 return -EINVAL;
8538                         }
8539
8540                 } else if (class == BPF_STX) {
8541                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
8542
8543                         if (BPF_MODE(insn->code) == BPF_XADD) {
8544                                 err = check_xadd(env, env->insn_idx, insn);
8545                                 if (err)
8546                                         return err;
8547                                 env->insn_idx++;
8548                                 continue;
8549                         }
8550
8551                         /* check src1 operand */
8552                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
8553                         if (err)
8554                                 return err;
8555                         /* check src2 operand */
8556                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8557                         if (err)
8558                                 return err;
8559
8560                         dst_reg_type = regs[insn->dst_reg].type;
8561
8562                         /* check that memory (dst_reg + off) is writeable */
8563                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
8564                                                insn->off, BPF_SIZE(insn->code),
8565                                                BPF_WRITE, insn->src_reg, false);
8566                         if (err)
8567                                 return err;
8568
8569                         prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
8570
8571                         if (*prev_dst_type == NOT_INIT) {
8572                                 *prev_dst_type = dst_reg_type;
8573                         } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
8574                                 verbose(env, "same insn cannot be used with different pointers\n");
8575                                 return -EINVAL;
8576                         }
8577
8578                 } else if (class == BPF_ST) {
8579                         if (BPF_MODE(insn->code) != BPF_MEM ||
8580                             insn->src_reg != BPF_REG_0) {
8581                                 verbose(env, "BPF_ST uses reserved fields\n");
8582                                 return -EINVAL;
8583                         }
8584                         /* check src operand */
8585                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8586                         if (err)
8587                                 return err;
8588
8589                         if (is_ctx_reg(env, insn->dst_reg)) {
8590                                 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
8591                                         insn->dst_reg,
8592                                         reg_type_str[reg_state(env, insn->dst_reg)->type]);
8593                                 return -EACCES;
8594                         }
8595
8596                         /* check that memory (dst_reg + off) is writeable */
8597                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
8598                                                insn->off, BPF_SIZE(insn->code),
8599                                                BPF_WRITE, -1, false);
8600                         if (err)
8601                                 return err;
8602
8603                 } else if (class == BPF_JMP || class == BPF_JMP32) {
8604                         u8 opcode = BPF_OP(insn->code);
8605
8606                         env->jmps_processed++;
8607                         if (opcode == BPF_CALL) {
8608                                 if (BPF_SRC(insn->code) != BPF_K ||
8609                                     insn->off != 0 ||
8610                                     (insn->src_reg != BPF_REG_0 &&
8611                                      insn->src_reg != BPF_PSEUDO_CALL) ||
8612                                     insn->dst_reg != BPF_REG_0 ||
8613                                     class == BPF_JMP32) {
8614                                         verbose(env, "BPF_CALL uses reserved fields\n");
8615                                         return -EINVAL;
8616                                 }
8617
8618                                 if (env->cur_state->active_spin_lock &&
8619                                     (insn->src_reg == BPF_PSEUDO_CALL ||
8620                                      insn->imm != BPF_FUNC_spin_unlock)) {
8621                                         verbose(env, "function calls are not allowed while holding a lock\n");
8622                                         return -EINVAL;
8623                                 }
8624                                 if (insn->src_reg == BPF_PSEUDO_CALL)
8625                                         err = check_func_call(env, insn, &env->insn_idx);
8626                                 else
8627                                         err = check_helper_call(env, insn->imm, env->insn_idx);
8628                                 if (err)
8629                                         return err;
8630
8631                         } else if (opcode == BPF_JA) {
8632                                 if (BPF_SRC(insn->code) != BPF_K ||
8633                                     insn->imm != 0 ||
8634                                     insn->src_reg != BPF_REG_0 ||
8635                                     insn->dst_reg != BPF_REG_0 ||
8636                                     class == BPF_JMP32) {
8637                                         verbose(env, "BPF_JA uses reserved fields\n");
8638                                         return -EINVAL;
8639                                 }
8640
8641                                 env->insn_idx += insn->off + 1;
8642                                 continue;
8643
8644                         } else if (opcode == BPF_EXIT) {
8645                                 if (BPF_SRC(insn->code) != BPF_K ||
8646                                     insn->imm != 0 ||
8647                                     insn->src_reg != BPF_REG_0 ||
8648                                     insn->dst_reg != BPF_REG_0 ||
8649                                     class == BPF_JMP32) {
8650                                         verbose(env, "BPF_EXIT uses reserved fields\n");
8651                                         return -EINVAL;
8652                                 }
8653
8654                                 if (env->cur_state->active_spin_lock) {
8655                                         verbose(env, "bpf_spin_unlock is missing\n");
8656                                         return -EINVAL;
8657                                 }
8658
8659                                 if (state->curframe) {
8660                                         /* exit from nested function */
8661                                         err = prepare_func_exit(env, &env->insn_idx);
8662                                         if (err)
8663                                                 return err;
8664                                         do_print_state = true;
8665                                         continue;
8666                                 }
8667
8668                                 err = check_reference_leak(env);
8669                                 if (err)
8670                                         return err;
8671
8672                                 err = check_return_code(env);
8673                                 if (err)
8674                                         return err;
8675 process_bpf_exit:
8676                                 update_branch_counts(env, env->cur_state);
8677                                 err = pop_stack(env, &prev_insn_idx,
8678                                                 &env->insn_idx);
8679                                 if (err < 0) {
8680                                         if (err != -ENOENT)
8681                                                 return err;
8682                                         break;
8683                                 } else {
8684                                         do_print_state = true;
8685                                         continue;
8686                                 }
8687                         } else {
8688                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
8689                                 if (err)
8690                                         return err;
8691                         }
8692                 } else if (class == BPF_LD) {
8693                         u8 mode = BPF_MODE(insn->code);
8694
8695                         if (mode == BPF_ABS || mode == BPF_IND) {
8696                                 err = check_ld_abs(env, insn);
8697                                 if (err)
8698                                         return err;
8699
8700                         } else if (mode == BPF_IMM) {
8701                                 err = check_ld_imm(env, insn);
8702                                 if (err)
8703                                         return err;
8704
8705                                 env->insn_idx++;
8706                                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8707                         } else {
8708                                 verbose(env, "invalid BPF_LD mode\n");
8709                                 return -EINVAL;
8710                         }
8711                 } else {
8712                         verbose(env, "unknown insn class %d\n", class);
8713                         return -EINVAL;
8714                 }
8715
8716                 env->insn_idx++;
8717         }
8718
8719         return 0;
8720 }
8721
8722 static int check_map_prealloc(struct bpf_map *map)
8723 {
8724         return (map->map_type != BPF_MAP_TYPE_HASH &&
8725                 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8726                 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
8727                 !(map->map_flags & BPF_F_NO_PREALLOC);
8728 }
8729
8730 static bool is_tracing_prog_type(enum bpf_prog_type type)
8731 {
8732         switch (type) {
8733         case BPF_PROG_TYPE_KPROBE:
8734         case BPF_PROG_TYPE_TRACEPOINT:
8735         case BPF_PROG_TYPE_PERF_EVENT:
8736         case BPF_PROG_TYPE_RAW_TRACEPOINT:
8737                 return true;
8738         default:
8739                 return false;
8740         }
8741 }
8742
8743 static bool is_preallocated_map(struct bpf_map *map)
8744 {
8745         if (!check_map_prealloc(map))
8746                 return false;
8747         if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
8748                 return false;
8749         return true;
8750 }
8751
8752 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
8753                                         struct bpf_map *map,
8754                                         struct bpf_prog *prog)
8755
8756 {
8757         /*
8758          * Validate that trace type programs use preallocated hash maps.
8759          *
8760          * For programs attached to PERF events this is mandatory as the
8761          * perf NMI can hit any arbitrary code sequence.
8762          *
8763          * All other trace types using preallocated hash maps are unsafe as
8764          * well because tracepoint or kprobes can be inside locked regions
8765          * of the memory allocator or at a place where a recursion into the
8766          * memory allocator would see inconsistent state.
8767          *
8768          * On RT enabled kernels run-time allocation of all trace type
8769          * programs is strictly prohibited due to lock type constraints. On
8770          * !RT kernels it is allowed for backwards compatibility reasons for
8771          * now, but warnings are emitted so developers are made aware of
8772          * the unsafety and can fix their programs before this is enforced.
8773          */
8774         if (is_tracing_prog_type(prog->type) && !is_preallocated_map(map)) {
8775                 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
8776                         verbose(env, "perf_event programs can only use preallocated hash map\n");
8777                         return -EINVAL;
8778                 }
8779                 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
8780                         verbose(env, "trace type programs can only use preallocated hash map\n");
8781                         return -EINVAL;
8782                 }
8783                 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
8784                 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
8785         }
8786
8787         if ((is_tracing_prog_type(prog->type) ||
8788              prog->type == BPF_PROG_TYPE_SOCKET_FILTER) &&
8789             map_value_has_spin_lock(map)) {
8790                 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
8791                 return -EINVAL;
8792         }
8793
8794         if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
8795             !bpf_offload_prog_map_match(prog, map)) {
8796                 verbose(env, "offload device mismatch between prog and map\n");
8797                 return -EINVAL;
8798         }
8799
8800         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
8801                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
8802                 return -EINVAL;
8803         }
8804
8805         return 0;
8806 }
8807
8808 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
8809 {
8810         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
8811                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
8812 }
8813
8814 /* look for pseudo eBPF instructions that access map FDs and
8815  * replace them with actual map pointers
8816  */
8817 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
8818 {
8819         struct bpf_insn *insn = env->prog->insnsi;
8820         int insn_cnt = env->prog->len;
8821         int i, j, err;
8822
8823         err = bpf_prog_calc_tag(env->prog);
8824         if (err)
8825                 return err;
8826
8827         for (i = 0; i < insn_cnt; i++, insn++) {
8828                 if (BPF_CLASS(insn->code) == BPF_LDX &&
8829                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
8830                         verbose(env, "BPF_LDX uses reserved fields\n");
8831                         return -EINVAL;
8832                 }
8833
8834                 if (BPF_CLASS(insn->code) == BPF_STX &&
8835                     ((BPF_MODE(insn->code) != BPF_MEM &&
8836                       BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
8837                         verbose(env, "BPF_STX uses reserved fields\n");
8838                         return -EINVAL;
8839                 }
8840
8841                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
8842                         struct bpf_insn_aux_data *aux;
8843                         struct bpf_map *map;
8844                         struct fd f;
8845                         u64 addr;
8846
8847                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
8848                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
8849                             insn[1].off != 0) {
8850                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
8851                                 return -EINVAL;
8852                         }
8853
8854                         if (insn[0].src_reg == 0)
8855                                 /* valid generic load 64-bit imm */
8856                                 goto next_insn;
8857
8858                         /* In final convert_pseudo_ld_imm64() step, this is
8859                          * converted into regular 64-bit imm load insn.
8860                          */
8861                         if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
8862                              insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
8863                             (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
8864                              insn[1].imm != 0)) {
8865                                 verbose(env,
8866                                         "unrecognized bpf_ld_imm64 insn\n");
8867                                 return -EINVAL;
8868                         }
8869
8870                         f = fdget(insn[0].imm);
8871                         map = __bpf_map_get(f);
8872                         if (IS_ERR(map)) {
8873                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
8874                                         insn[0].imm);
8875                                 return PTR_ERR(map);
8876                         }
8877
8878                         err = check_map_prog_compatibility(env, map, env->prog);
8879                         if (err) {
8880                                 fdput(f);
8881                                 return err;
8882                         }
8883
8884                         aux = &env->insn_aux_data[i];
8885                         if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8886                                 addr = (unsigned long)map;
8887                         } else {
8888                                 u32 off = insn[1].imm;
8889
8890                                 if (off >= BPF_MAX_VAR_OFF) {
8891                                         verbose(env, "direct value offset of %u is not allowed\n", off);
8892                                         fdput(f);
8893                                         return -EINVAL;
8894                                 }
8895
8896                                 if (!map->ops->map_direct_value_addr) {
8897                                         verbose(env, "no direct value access support for this map type\n");
8898                                         fdput(f);
8899                                         return -EINVAL;
8900                                 }
8901
8902                                 err = map->ops->map_direct_value_addr(map, &addr, off);
8903                                 if (err) {
8904                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
8905                                                 map->value_size, off);
8906                                         fdput(f);
8907                                         return err;
8908                                 }
8909
8910                                 aux->map_off = off;
8911                                 addr += off;
8912                         }
8913
8914                         insn[0].imm = (u32)addr;
8915                         insn[1].imm = addr >> 32;
8916
8917                         /* check whether we recorded this map already */
8918                         for (j = 0; j < env->used_map_cnt; j++) {
8919                                 if (env->used_maps[j] == map) {
8920                                         aux->map_index = j;
8921                                         fdput(f);
8922                                         goto next_insn;
8923                                 }
8924                         }
8925
8926                         if (env->used_map_cnt >= MAX_USED_MAPS) {
8927                                 fdput(f);
8928                                 return -E2BIG;
8929                         }
8930
8931                         /* hold the map. If the program is rejected by verifier,
8932                          * the map will be released by release_maps() or it
8933                          * will be used by the valid program until it's unloaded
8934                          * and all maps are released in free_used_maps()
8935                          */
8936                         bpf_map_inc(map);
8937
8938                         aux->map_index = env->used_map_cnt;
8939                         env->used_maps[env->used_map_cnt++] = map;
8940
8941                         if (bpf_map_is_cgroup_storage(map) &&
8942                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
8943                                 verbose(env, "only one cgroup storage of each type is allowed\n");
8944                                 fdput(f);
8945                                 return -EBUSY;
8946                         }
8947
8948                         fdput(f);
8949 next_insn:
8950                         insn++;
8951                         i++;
8952                         continue;
8953                 }
8954
8955                 /* Basic sanity check before we invest more work here. */
8956                 if (!bpf_opcode_in_insntable(insn->code)) {
8957                         verbose(env, "unknown opcode %02x\n", insn->code);
8958                         return -EINVAL;
8959                 }
8960         }
8961
8962         /* now all pseudo BPF_LD_IMM64 instructions load valid
8963          * 'struct bpf_map *' into a register instead of user map_fd.
8964          * These pointers will be used later by verifier to validate map access.
8965          */
8966         return 0;
8967 }
8968
8969 /* drop refcnt of maps used by the rejected program */
8970 static void release_maps(struct bpf_verifier_env *env)
8971 {
8972         __bpf_free_used_maps(env->prog->aux, env->used_maps,
8973                              env->used_map_cnt);
8974 }
8975
8976 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
8977 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
8978 {
8979         struct bpf_insn *insn = env->prog->insnsi;
8980         int insn_cnt = env->prog->len;
8981         int i;
8982
8983         for (i = 0; i < insn_cnt; i++, insn++)
8984                 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
8985                         insn->src_reg = 0;
8986 }
8987
8988 /* single env->prog->insni[off] instruction was replaced with the range
8989  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
8990  * [0, off) and [off, end) to new locations, so the patched range stays zero
8991  */
8992 static int adjust_insn_aux_data(struct bpf_verifier_env *env,
8993                                 struct bpf_prog *new_prog, u32 off, u32 cnt)
8994 {
8995         struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
8996         struct bpf_insn *insn = new_prog->insnsi;
8997         u32 prog_len;
8998         int i;
8999
9000         /* aux info at OFF always needs adjustment, no matter fast path
9001          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
9002          * original insn at old prog.
9003          */
9004         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
9005
9006         if (cnt == 1)
9007                 return 0;
9008         prog_len = new_prog->len;
9009         new_data = vzalloc(array_size(prog_len,
9010                                       sizeof(struct bpf_insn_aux_data)));
9011         if (!new_data)
9012                 return -ENOMEM;
9013         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
9014         memcpy(new_data + off + cnt - 1, old_data + off,
9015                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
9016         for (i = off; i < off + cnt - 1; i++) {
9017                 new_data[i].seen = env->pass_cnt;
9018                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
9019         }
9020         env->insn_aux_data = new_data;
9021         vfree(old_data);
9022         return 0;
9023 }
9024
9025 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
9026 {
9027         int i;
9028
9029         if (len == 1)
9030                 return;
9031         /* NOTE: fake 'exit' subprog should be updated as well. */
9032         for (i = 0; i <= env->subprog_cnt; i++) {
9033                 if (env->subprog_info[i].start <= off)
9034                         continue;
9035                 env->subprog_info[i].start += len - 1;
9036         }
9037 }
9038
9039 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
9040                                             const struct bpf_insn *patch, u32 len)
9041 {
9042         struct bpf_prog *new_prog;
9043
9044         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
9045         if (IS_ERR(new_prog)) {
9046                 if (PTR_ERR(new_prog) == -ERANGE)
9047                         verbose(env,
9048                                 "insn %d cannot be patched due to 16-bit range\n",
9049                                 env->insn_aux_data[off].orig_idx);
9050                 return NULL;
9051         }
9052         if (adjust_insn_aux_data(env, new_prog, off, len))
9053                 return NULL;
9054         adjust_subprog_starts(env, off, len);
9055         return new_prog;
9056 }
9057
9058 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
9059                                               u32 off, u32 cnt)
9060 {
9061         int i, j;
9062
9063         /* find first prog starting at or after off (first to remove) */
9064         for (i = 0; i < env->subprog_cnt; i++)
9065                 if (env->subprog_info[i].start >= off)
9066                         break;
9067         /* find first prog starting at or after off + cnt (first to stay) */
9068         for (j = i; j < env->subprog_cnt; j++)
9069                 if (env->subprog_info[j].start >= off + cnt)
9070                         break;
9071         /* if j doesn't start exactly at off + cnt, we are just removing
9072          * the front of previous prog
9073          */
9074         if (env->subprog_info[j].start != off + cnt)
9075                 j--;
9076
9077         if (j > i) {
9078                 struct bpf_prog_aux *aux = env->prog->aux;
9079                 int move;
9080
9081                 /* move fake 'exit' subprog as well */
9082                 move = env->subprog_cnt + 1 - j;
9083
9084                 memmove(env->subprog_info + i,
9085                         env->subprog_info + j,
9086                         sizeof(*env->subprog_info) * move);
9087                 env->subprog_cnt -= j - i;
9088
9089                 /* remove func_info */
9090                 if (aux->func_info) {
9091                         move = aux->func_info_cnt - j;
9092
9093                         memmove(aux->func_info + i,
9094                                 aux->func_info + j,
9095                                 sizeof(*aux->func_info) * move);
9096                         aux->func_info_cnt -= j - i;
9097                         /* func_info->insn_off is set after all code rewrites,
9098                          * in adjust_btf_func() - no need to adjust
9099                          */
9100                 }
9101         } else {
9102                 /* convert i from "first prog to remove" to "first to adjust" */
9103                 if (env->subprog_info[i].start == off)
9104                         i++;
9105         }
9106
9107         /* update fake 'exit' subprog as well */
9108         for (; i <= env->subprog_cnt; i++)
9109                 env->subprog_info[i].start -= cnt;
9110
9111         return 0;
9112 }
9113
9114 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
9115                                       u32 cnt)
9116 {
9117         struct bpf_prog *prog = env->prog;
9118         u32 i, l_off, l_cnt, nr_linfo;
9119         struct bpf_line_info *linfo;
9120
9121         nr_linfo = prog->aux->nr_linfo;
9122         if (!nr_linfo)
9123                 return 0;
9124
9125         linfo = prog->aux->linfo;
9126
9127         /* find first line info to remove, count lines to be removed */
9128         for (i = 0; i < nr_linfo; i++)
9129                 if (linfo[i].insn_off >= off)
9130                         break;
9131
9132         l_off = i;
9133         l_cnt = 0;
9134         for (; i < nr_linfo; i++)
9135                 if (linfo[i].insn_off < off + cnt)
9136                         l_cnt++;
9137                 else
9138                         break;
9139
9140         /* First live insn doesn't match first live linfo, it needs to "inherit"
9141          * last removed linfo.  prog is already modified, so prog->len == off
9142          * means no live instructions after (tail of the program was removed).
9143          */
9144         if (prog->len != off && l_cnt &&
9145             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
9146                 l_cnt--;
9147                 linfo[--i].insn_off = off + cnt;
9148         }
9149
9150         /* remove the line info which refer to the removed instructions */
9151         if (l_cnt) {
9152                 memmove(linfo + l_off, linfo + i,
9153                         sizeof(*linfo) * (nr_linfo - i));
9154
9155                 prog->aux->nr_linfo -= l_cnt;
9156                 nr_linfo = prog->aux->nr_linfo;
9157         }
9158
9159         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
9160         for (i = l_off; i < nr_linfo; i++)
9161                 linfo[i].insn_off -= cnt;
9162
9163         /* fix up all subprogs (incl. 'exit') which start >= off */
9164         for (i = 0; i <= env->subprog_cnt; i++)
9165                 if (env->subprog_info[i].linfo_idx > l_off) {
9166                         /* program may have started in the removed region but
9167                          * may not be fully removed
9168                          */
9169                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
9170                                 env->subprog_info[i].linfo_idx -= l_cnt;
9171                         else
9172                                 env->subprog_info[i].linfo_idx = l_off;
9173                 }
9174
9175         return 0;
9176 }
9177
9178 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
9179 {
9180         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9181         unsigned int orig_prog_len = env->prog->len;
9182         int err;
9183
9184         if (bpf_prog_is_dev_bound(env->prog->aux))
9185                 bpf_prog_offload_remove_insns(env, off, cnt);
9186
9187         err = bpf_remove_insns(env->prog, off, cnt);
9188         if (err)
9189                 return err;
9190
9191         err = adjust_subprog_starts_after_remove(env, off, cnt);
9192         if (err)
9193                 return err;
9194
9195         err = bpf_adj_linfo_after_remove(env, off, cnt);
9196         if (err)
9197                 return err;
9198
9199         memmove(aux_data + off, aux_data + off + cnt,
9200                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
9201
9202         return 0;
9203 }
9204
9205 /* The verifier does more data flow analysis than llvm and will not
9206  * explore branches that are dead at run time. Malicious programs can
9207  * have dead code too. Therefore replace all dead at-run-time code
9208  * with 'ja -1'.
9209  *
9210  * Just nops are not optimal, e.g. if they would sit at the end of the
9211  * program and through another bug we would manage to jump there, then
9212  * we'd execute beyond program memory otherwise. Returning exception
9213  * code also wouldn't work since we can have subprogs where the dead
9214  * code could be located.
9215  */
9216 static void sanitize_dead_code(struct bpf_verifier_env *env)
9217 {
9218         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9219         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
9220         struct bpf_insn *insn = env->prog->insnsi;
9221         const int insn_cnt = env->prog->len;
9222         int i;
9223
9224         for (i = 0; i < insn_cnt; i++) {
9225                 if (aux_data[i].seen)
9226                         continue;
9227                 memcpy(insn + i, &trap, sizeof(trap));
9228         }
9229 }
9230
9231 static bool insn_is_cond_jump(u8 code)
9232 {
9233         u8 op;
9234
9235         if (BPF_CLASS(code) == BPF_JMP32)
9236                 return true;
9237
9238         if (BPF_CLASS(code) != BPF_JMP)
9239                 return false;
9240
9241         op = BPF_OP(code);
9242         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
9243 }
9244
9245 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
9246 {
9247         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9248         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
9249         struct bpf_insn *insn = env->prog->insnsi;
9250         const int insn_cnt = env->prog->len;
9251         int i;
9252
9253         for (i = 0; i < insn_cnt; i++, insn++) {
9254                 if (!insn_is_cond_jump(insn->code))
9255                         continue;
9256
9257                 if (!aux_data[i + 1].seen)
9258                         ja.off = insn->off;
9259                 else if (!aux_data[i + 1 + insn->off].seen)
9260                         ja.off = 0;
9261                 else
9262                         continue;
9263
9264                 if (bpf_prog_is_dev_bound(env->prog->aux))
9265                         bpf_prog_offload_replace_insn(env, i, &ja);
9266
9267                 memcpy(insn, &ja, sizeof(ja));
9268         }
9269 }
9270
9271 static int opt_remove_dead_code(struct bpf_verifier_env *env)
9272 {
9273         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9274         int insn_cnt = env->prog->len;
9275         int i, err;
9276
9277         for (i = 0; i < insn_cnt; i++) {
9278                 int j;
9279
9280                 j = 0;
9281                 while (i + j < insn_cnt && !aux_data[i + j].seen)
9282                         j++;
9283                 if (!j)
9284                         continue;
9285
9286                 err = verifier_remove_insns(env, i, j);
9287                 if (err)
9288                         return err;
9289                 insn_cnt = env->prog->len;
9290         }
9291
9292         return 0;
9293 }
9294
9295 static int opt_remove_nops(struct bpf_verifier_env *env)
9296 {
9297         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
9298         struct bpf_insn *insn = env->prog->insnsi;
9299         int insn_cnt = env->prog->len;
9300         int i, err;
9301
9302         for (i = 0; i < insn_cnt; i++) {
9303                 if (memcmp(&insn[i], &ja, sizeof(ja)))
9304                         continue;
9305
9306                 err = verifier_remove_insns(env, i, 1);
9307                 if (err)
9308                         return err;
9309                 insn_cnt--;
9310                 i--;
9311         }
9312
9313         return 0;
9314 }
9315
9316 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
9317                                          const union bpf_attr *attr)
9318 {
9319         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
9320         struct bpf_insn_aux_data *aux = env->insn_aux_data;
9321         int i, patch_len, delta = 0, len = env->prog->len;
9322         struct bpf_insn *insns = env->prog->insnsi;
9323         struct bpf_prog *new_prog;
9324         bool rnd_hi32;
9325
9326         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
9327         zext_patch[1] = BPF_ZEXT_REG(0);
9328         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
9329         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
9330         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
9331         for (i = 0; i < len; i++) {
9332                 int adj_idx = i + delta;
9333                 struct bpf_insn insn;
9334
9335                 insn = insns[adj_idx];
9336                 if (!aux[adj_idx].zext_dst) {
9337                         u8 code, class;
9338                         u32 imm_rnd;
9339
9340                         if (!rnd_hi32)
9341                                 continue;
9342
9343                         code = insn.code;
9344                         class = BPF_CLASS(code);
9345                         if (insn_no_def(&insn))
9346                                 continue;
9347
9348                         /* NOTE: arg "reg" (the fourth one) is only used for
9349                          *       BPF_STX which has been ruled out in above
9350                          *       check, it is safe to pass NULL here.
9351                          */
9352                         if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
9353                                 if (class == BPF_LD &&
9354                                     BPF_MODE(code) == BPF_IMM)
9355                                         i++;
9356                                 continue;
9357                         }
9358
9359                         /* ctx load could be transformed into wider load. */
9360                         if (class == BPF_LDX &&
9361                             aux[adj_idx].ptr_type == PTR_TO_CTX)
9362                                 continue;
9363
9364                         imm_rnd = get_random_int();
9365                         rnd_hi32_patch[0] = insn;
9366                         rnd_hi32_patch[1].imm = imm_rnd;
9367                         rnd_hi32_patch[3].dst_reg = insn.dst_reg;
9368                         patch = rnd_hi32_patch;
9369                         patch_len = 4;
9370                         goto apply_patch_buffer;
9371                 }
9372
9373                 if (!bpf_jit_needs_zext())
9374                         continue;
9375
9376                 zext_patch[0] = insn;
9377                 zext_patch[1].dst_reg = insn.dst_reg;
9378                 zext_patch[1].src_reg = insn.dst_reg;
9379                 patch = zext_patch;
9380                 patch_len = 2;
9381 apply_patch_buffer:
9382                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
9383                 if (!new_prog)
9384                         return -ENOMEM;
9385                 env->prog = new_prog;
9386                 insns = new_prog->insnsi;
9387                 aux = env->insn_aux_data;
9388                 delta += patch_len - 1;
9389         }
9390
9391         return 0;
9392 }
9393
9394 /* convert load instructions that access fields of a context type into a
9395  * sequence of instructions that access fields of the underlying structure:
9396  *     struct __sk_buff    -> struct sk_buff
9397  *     struct bpf_sock_ops -> struct sock
9398  */
9399 static int convert_ctx_accesses(struct bpf_verifier_env *env)
9400 {
9401         const struct bpf_verifier_ops *ops = env->ops;
9402         int i, cnt, size, ctx_field_size, delta = 0;
9403         const int insn_cnt = env->prog->len;
9404         struct bpf_insn insn_buf[16], *insn;
9405         u32 target_size, size_default, off;
9406         struct bpf_prog *new_prog;
9407         enum bpf_access_type type;
9408         bool is_narrower_load;
9409
9410         if (ops->gen_prologue || env->seen_direct_write) {
9411                 if (!ops->gen_prologue) {
9412                         verbose(env, "bpf verifier is misconfigured\n");
9413                         return -EINVAL;
9414                 }
9415                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
9416                                         env->prog);
9417                 if (cnt >= ARRAY_SIZE(insn_buf)) {
9418                         verbose(env, "bpf verifier is misconfigured\n");
9419                         return -EINVAL;
9420                 } else if (cnt) {
9421                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
9422                         if (!new_prog)
9423                                 return -ENOMEM;
9424
9425                         env->prog = new_prog;
9426                         delta += cnt - 1;
9427                 }
9428         }
9429
9430         if (bpf_prog_is_dev_bound(env->prog->aux))
9431                 return 0;
9432
9433         insn = env->prog->insnsi + delta;
9434
9435         for (i = 0; i < insn_cnt; i++, insn++) {
9436                 bpf_convert_ctx_access_t convert_ctx_access;
9437
9438                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
9439                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
9440                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
9441                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
9442                         type = BPF_READ;
9443                 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
9444                          insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
9445                          insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
9446                          insn->code == (BPF_STX | BPF_MEM | BPF_DW))
9447                         type = BPF_WRITE;
9448                 else
9449                         continue;
9450
9451                 if (type == BPF_WRITE &&
9452                     env->insn_aux_data[i + delta].sanitize_stack_off) {
9453                         struct bpf_insn patch[] = {
9454                                 /* Sanitize suspicious stack slot with zero.
9455                                  * There are no memory dependencies for this store,
9456                                  * since it's only using frame pointer and immediate
9457                                  * constant of zero
9458                                  */
9459                                 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
9460                                            env->insn_aux_data[i + delta].sanitize_stack_off,
9461                                            0),
9462                                 /* the original STX instruction will immediately
9463                                  * overwrite the same stack slot with appropriate value
9464                                  */
9465                                 *insn,
9466                         };
9467
9468                         cnt = ARRAY_SIZE(patch);
9469                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
9470                         if (!new_prog)
9471                                 return -ENOMEM;
9472
9473                         delta    += cnt - 1;
9474                         env->prog = new_prog;
9475                         insn      = new_prog->insnsi + i + delta;
9476                         continue;
9477                 }
9478
9479                 switch (env->insn_aux_data[i + delta].ptr_type) {
9480                 case PTR_TO_CTX:
9481                         if (!ops->convert_ctx_access)
9482                                 continue;
9483                         convert_ctx_access = ops->convert_ctx_access;
9484                         break;
9485                 case PTR_TO_SOCKET:
9486                 case PTR_TO_SOCK_COMMON:
9487                         convert_ctx_access = bpf_sock_convert_ctx_access;
9488                         break;
9489                 case PTR_TO_TCP_SOCK:
9490                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
9491                         break;
9492                 case PTR_TO_XDP_SOCK:
9493                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
9494                         break;
9495                 case PTR_TO_BTF_ID:
9496                         if (type == BPF_READ) {
9497                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
9498                                         BPF_SIZE((insn)->code);
9499                                 env->prog->aux->num_exentries++;
9500                         } else if (env->prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9501                                 verbose(env, "Writes through BTF pointers are not allowed\n");
9502                                 return -EINVAL;
9503                         }
9504                         continue;
9505                 default:
9506                         continue;
9507                 }
9508
9509                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
9510                 size = BPF_LDST_BYTES(insn);
9511
9512                 /* If the read access is a narrower load of the field,
9513                  * convert to a 4/8-byte load, to minimum program type specific
9514                  * convert_ctx_access changes. If conversion is successful,
9515                  * we will apply proper mask to the result.
9516                  */
9517                 is_narrower_load = size < ctx_field_size;
9518                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
9519                 off = insn->off;
9520                 if (is_narrower_load) {
9521                         u8 size_code;
9522
9523                         if (type == BPF_WRITE) {
9524                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
9525                                 return -EINVAL;
9526                         }
9527
9528                         size_code = BPF_H;
9529                         if (ctx_field_size == 4)
9530                                 size_code = BPF_W;
9531                         else if (ctx_field_size == 8)
9532                                 size_code = BPF_DW;
9533
9534                         insn->off = off & ~(size_default - 1);
9535                         insn->code = BPF_LDX | BPF_MEM | size_code;
9536                 }
9537
9538                 target_size = 0;
9539                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
9540                                          &target_size);
9541                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
9542                     (ctx_field_size && !target_size)) {
9543                         verbose(env, "bpf verifier is misconfigured\n");
9544                         return -EINVAL;
9545                 }
9546
9547                 if (is_narrower_load && size < target_size) {
9548                         u8 shift = bpf_ctx_narrow_access_offset(
9549                                 off, size, size_default) * 8;
9550                         if (ctx_field_size <= 4) {
9551                                 if (shift)
9552                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
9553                                                                         insn->dst_reg,
9554                                                                         shift);
9555                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
9556                                                                 (1 << size * 8) - 1);
9557                         } else {
9558                                 if (shift)
9559                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
9560                                                                         insn->dst_reg,
9561                                                                         shift);
9562                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
9563                                                                 (1ULL << size * 8) - 1);
9564                         }
9565                 }
9566
9567                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9568                 if (!new_prog)
9569                         return -ENOMEM;
9570
9571                 delta += cnt - 1;
9572
9573                 /* keep walking new program and skip insns we just inserted */
9574                 env->prog = new_prog;
9575                 insn      = new_prog->insnsi + i + delta;
9576         }
9577
9578         return 0;
9579 }
9580
9581 static int jit_subprogs(struct bpf_verifier_env *env)
9582 {
9583         struct bpf_prog *prog = env->prog, **func, *tmp;
9584         int i, j, subprog_start, subprog_end = 0, len, subprog;
9585         struct bpf_insn *insn;
9586         void *old_bpf_func;
9587         int err;
9588
9589         if (env->subprog_cnt <= 1)
9590                 return 0;
9591
9592         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
9593                 if (insn->code != (BPF_JMP | BPF_CALL) ||
9594                     insn->src_reg != BPF_PSEUDO_CALL)
9595                         continue;
9596                 /* Upon error here we cannot fall back to interpreter but
9597                  * need a hard reject of the program. Thus -EFAULT is
9598                  * propagated in any case.
9599                  */
9600                 subprog = find_subprog(env, i + insn->imm + 1);
9601                 if (subprog < 0) {
9602                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
9603                                   i + insn->imm + 1);
9604                         return -EFAULT;
9605                 }
9606                 /* temporarily remember subprog id inside insn instead of
9607                  * aux_data, since next loop will split up all insns into funcs
9608                  */
9609                 insn->off = subprog;
9610                 /* remember original imm in case JIT fails and fallback
9611                  * to interpreter will be needed
9612                  */
9613                 env->insn_aux_data[i].call_imm = insn->imm;
9614                 /* point imm to __bpf_call_base+1 from JITs point of view */
9615                 insn->imm = 1;
9616         }
9617
9618         err = bpf_prog_alloc_jited_linfo(prog);
9619         if (err)
9620                 goto out_undo_insn;
9621
9622         err = -ENOMEM;
9623         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
9624         if (!func)
9625                 goto out_undo_insn;
9626
9627         for (i = 0; i < env->subprog_cnt; i++) {
9628                 subprog_start = subprog_end;
9629                 subprog_end = env->subprog_info[i + 1].start;
9630
9631                 len = subprog_end - subprog_start;
9632                 /* BPF_PROG_RUN doesn't call subprogs directly,
9633                  * hence main prog stats include the runtime of subprogs.
9634                  * subprogs don't have IDs and not reachable via prog_get_next_id
9635                  * func[i]->aux->stats will never be accessed and stays NULL
9636                  */
9637                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
9638                 if (!func[i])
9639                         goto out_free;
9640                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
9641                        len * sizeof(struct bpf_insn));
9642                 func[i]->type = prog->type;
9643                 func[i]->len = len;
9644                 if (bpf_prog_calc_tag(func[i]))
9645                         goto out_free;
9646                 func[i]->is_func = 1;
9647                 func[i]->aux->func_idx = i;
9648                 /* the btf and func_info will be freed only at prog->aux */
9649                 func[i]->aux->btf = prog->aux->btf;
9650                 func[i]->aux->func_info = prog->aux->func_info;
9651
9652                 /* Use bpf_prog_F_tag to indicate functions in stack traces.
9653                  * Long term would need debug info to populate names
9654                  */
9655                 func[i]->aux->name[0] = 'F';
9656                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
9657                 func[i]->jit_requested = 1;
9658                 func[i]->aux->linfo = prog->aux->linfo;
9659                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
9660                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
9661                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
9662                 func[i] = bpf_int_jit_compile(func[i]);
9663                 if (!func[i]->jited) {
9664                         err = -ENOTSUPP;
9665                         goto out_free;
9666                 }
9667                 cond_resched();
9668         }
9669         /* at this point all bpf functions were successfully JITed
9670          * now populate all bpf_calls with correct addresses and
9671          * run last pass of JIT
9672          */
9673         for (i = 0; i < env->subprog_cnt; i++) {
9674                 insn = func[i]->insnsi;
9675                 for (j = 0; j < func[i]->len; j++, insn++) {
9676                         if (insn->code != (BPF_JMP | BPF_CALL) ||
9677                             insn->src_reg != BPF_PSEUDO_CALL)
9678                                 continue;
9679                         subprog = insn->off;
9680                         insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
9681                                     __bpf_call_base;
9682                 }
9683
9684                 /* we use the aux data to keep a list of the start addresses
9685                  * of the JITed images for each function in the program
9686                  *
9687                  * for some architectures, such as powerpc64, the imm field
9688                  * might not be large enough to hold the offset of the start
9689                  * address of the callee's JITed image from __bpf_call_base
9690                  *
9691                  * in such cases, we can lookup the start address of a callee
9692                  * by using its subprog id, available from the off field of
9693                  * the call instruction, as an index for this list
9694                  */
9695                 func[i]->aux->func = func;
9696                 func[i]->aux->func_cnt = env->subprog_cnt;
9697         }
9698         for (i = 0; i < env->subprog_cnt; i++) {
9699                 old_bpf_func = func[i]->bpf_func;
9700                 tmp = bpf_int_jit_compile(func[i]);
9701                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
9702                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
9703                         err = -ENOTSUPP;
9704                         goto out_free;
9705                 }
9706                 cond_resched();
9707         }
9708
9709         /* finally lock prog and jit images for all functions and
9710          * populate kallsysm
9711          */
9712         for (i = 0; i < env->subprog_cnt; i++) {
9713                 bpf_prog_lock_ro(func[i]);
9714                 bpf_prog_kallsyms_add(func[i]);
9715         }
9716
9717         /* Last step: make now unused interpreter insns from main
9718          * prog consistent for later dump requests, so they can
9719          * later look the same as if they were interpreted only.
9720          */
9721         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
9722                 if (insn->code != (BPF_JMP | BPF_CALL) ||
9723                     insn->src_reg != BPF_PSEUDO_CALL)
9724                         continue;
9725                 insn->off = env->insn_aux_data[i].call_imm;
9726                 subprog = find_subprog(env, i + insn->off + 1);
9727                 insn->imm = subprog;
9728         }
9729
9730         prog->jited = 1;
9731         prog->bpf_func = func[0]->bpf_func;
9732         prog->aux->func = func;
9733         prog->aux->func_cnt = env->subprog_cnt;
9734         bpf_prog_free_unused_jited_linfo(prog);
9735         return 0;
9736 out_free:
9737         for (i = 0; i < env->subprog_cnt; i++)
9738                 if (func[i])
9739                         bpf_jit_free(func[i]);
9740         kfree(func);
9741 out_undo_insn:
9742         /* cleanup main prog to be interpreted */
9743         prog->jit_requested = 0;
9744         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
9745                 if (insn->code != (BPF_JMP | BPF_CALL) ||
9746                     insn->src_reg != BPF_PSEUDO_CALL)
9747                         continue;
9748                 insn->off = 0;
9749                 insn->imm = env->insn_aux_data[i].call_imm;
9750         }
9751         bpf_prog_free_jited_linfo(prog);
9752         return err;
9753 }
9754
9755 static int fixup_call_args(struct bpf_verifier_env *env)
9756 {
9757 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
9758         struct bpf_prog *prog = env->prog;
9759         struct bpf_insn *insn = prog->insnsi;
9760         int i, depth;
9761 #endif
9762         int err = 0;
9763
9764         if (env->prog->jit_requested &&
9765             !bpf_prog_is_dev_bound(env->prog->aux)) {
9766                 err = jit_subprogs(env);
9767                 if (err == 0)
9768                         return 0;
9769                 if (err == -EFAULT)
9770                         return err;
9771         }
9772 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
9773         for (i = 0; i < prog->len; i++, insn++) {
9774                 if (insn->code != (BPF_JMP | BPF_CALL) ||
9775                     insn->src_reg != BPF_PSEUDO_CALL)
9776                         continue;
9777                 depth = get_callee_stack_depth(env, insn, i);
9778                 if (depth < 0)
9779                         return depth;
9780                 bpf_patch_call_args(insn, depth);
9781         }
9782         err = 0;
9783 #endif
9784         return err;
9785 }
9786
9787 /* fixup insn->imm field of bpf_call instructions
9788  * and inline eligible helpers as explicit sequence of BPF instructions
9789  *
9790  * this function is called after eBPF program passed verification
9791  */
9792 static int fixup_bpf_calls(struct bpf_verifier_env *env)
9793 {
9794         struct bpf_prog *prog = env->prog;
9795         bool expect_blinding = bpf_jit_blinding_enabled(prog);
9796         struct bpf_insn *insn = prog->insnsi;
9797         const struct bpf_func_proto *fn;
9798         const int insn_cnt = prog->len;
9799         const struct bpf_map_ops *ops;
9800         struct bpf_insn_aux_data *aux;
9801         struct bpf_insn insn_buf[16];
9802         struct bpf_prog *new_prog;
9803         struct bpf_map *map_ptr;
9804         int i, ret, cnt, delta = 0;
9805
9806         for (i = 0; i < insn_cnt; i++, insn++) {
9807                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
9808                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
9809                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
9810                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
9811                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
9812                         struct bpf_insn mask_and_div[] = {
9813                                 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
9814                                 /* Rx div 0 -> 0 */
9815                                 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
9816                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
9817                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
9818                                 *insn,
9819                         };
9820                         struct bpf_insn mask_and_mod[] = {
9821                                 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
9822                                 /* Rx mod 0 -> Rx */
9823                                 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
9824                                 *insn,
9825                         };
9826                         struct bpf_insn *patchlet;
9827
9828                         if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
9829                             insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
9830                                 patchlet = mask_and_div + (is64 ? 1 : 0);
9831                                 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
9832                         } else {
9833                                 patchlet = mask_and_mod + (is64 ? 1 : 0);
9834                                 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
9835                         }
9836
9837                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
9838                         if (!new_prog)
9839                                 return -ENOMEM;
9840
9841                         delta    += cnt - 1;
9842                         env->prog = prog = new_prog;
9843                         insn      = new_prog->insnsi + i + delta;
9844                         continue;
9845                 }
9846
9847                 if (BPF_CLASS(insn->code) == BPF_LD &&
9848                     (BPF_MODE(insn->code) == BPF_ABS ||
9849                      BPF_MODE(insn->code) == BPF_IND)) {
9850                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
9851                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
9852                                 verbose(env, "bpf verifier is misconfigured\n");
9853                                 return -EINVAL;
9854                         }
9855
9856                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9857                         if (!new_prog)
9858                                 return -ENOMEM;
9859
9860                         delta    += cnt - 1;
9861                         env->prog = prog = new_prog;
9862                         insn      = new_prog->insnsi + i + delta;
9863                         continue;
9864                 }
9865
9866                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
9867                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
9868                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
9869                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
9870                         struct bpf_insn insn_buf[16];
9871                         struct bpf_insn *patch = &insn_buf[0];
9872                         bool issrc, isneg;
9873                         u32 off_reg;
9874
9875                         aux = &env->insn_aux_data[i + delta];
9876                         if (!aux->alu_state ||
9877                             aux->alu_state == BPF_ALU_NON_POINTER)
9878                                 continue;
9879
9880                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
9881                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
9882                                 BPF_ALU_SANITIZE_SRC;
9883
9884                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
9885                         if (isneg)
9886                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
9887                         *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
9888                         *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
9889                         *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
9890                         *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
9891                         *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
9892                         if (issrc) {
9893                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
9894                                                          off_reg);
9895                                 insn->src_reg = BPF_REG_AX;
9896                         } else {
9897                                 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
9898                                                          BPF_REG_AX);
9899                         }
9900                         if (isneg)
9901                                 insn->code = insn->code == code_add ?
9902                                              code_sub : code_add;
9903                         *patch++ = *insn;
9904                         if (issrc && isneg)
9905                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
9906                         cnt = patch - insn_buf;
9907
9908                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9909                         if (!new_prog)
9910                                 return -ENOMEM;
9911
9912                         delta    += cnt - 1;
9913                         env->prog = prog = new_prog;
9914                         insn      = new_prog->insnsi + i + delta;
9915                         continue;
9916                 }
9917
9918                 if (insn->code != (BPF_JMP | BPF_CALL))
9919                         continue;
9920                 if (insn->src_reg == BPF_PSEUDO_CALL)
9921                         continue;
9922
9923                 if (insn->imm == BPF_FUNC_get_route_realm)
9924                         prog->dst_needed = 1;
9925                 if (insn->imm == BPF_FUNC_get_prandom_u32)
9926                         bpf_user_rnd_init_once();
9927                 if (insn->imm == BPF_FUNC_override_return)
9928                         prog->kprobe_override = 1;
9929                 if (insn->imm == BPF_FUNC_tail_call) {
9930                         /* If we tail call into other programs, we
9931                          * cannot make any assumptions since they can
9932                          * be replaced dynamically during runtime in
9933                          * the program array.
9934                          */
9935                         prog->cb_access = 1;
9936                         env->prog->aux->stack_depth = MAX_BPF_STACK;
9937                         env->prog->aux->max_pkt_offset = MAX_PACKET_OFF;
9938
9939                         /* mark bpf_tail_call as different opcode to avoid
9940                          * conditional branch in the interpeter for every normal
9941                          * call and to prevent accidental JITing by JIT compiler
9942                          * that doesn't support bpf_tail_call yet
9943                          */
9944                         insn->imm = 0;
9945                         insn->code = BPF_JMP | BPF_TAIL_CALL;
9946
9947                         aux = &env->insn_aux_data[i + delta];
9948                         if (env->allow_ptr_leaks && !expect_blinding &&
9949                             prog->jit_requested &&
9950                             !bpf_map_key_poisoned(aux) &&
9951                             !bpf_map_ptr_poisoned(aux) &&
9952                             !bpf_map_ptr_unpriv(aux)) {
9953                                 struct bpf_jit_poke_descriptor desc = {
9954                                         .reason = BPF_POKE_REASON_TAIL_CALL,
9955                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
9956                                         .tail_call.key = bpf_map_key_immediate(aux),
9957                                 };
9958
9959                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
9960                                 if (ret < 0) {
9961                                         verbose(env, "adding tail call poke descriptor failed\n");
9962                                         return ret;
9963                                 }
9964
9965                                 insn->imm = ret + 1;
9966                                 continue;
9967                         }
9968
9969                         if (!bpf_map_ptr_unpriv(aux))
9970                                 continue;
9971
9972                         /* instead of changing every JIT dealing with tail_call
9973                          * emit two extra insns:
9974                          * if (index >= max_entries) goto out;
9975                          * index &= array->index_mask;
9976                          * to avoid out-of-bounds cpu speculation
9977                          */
9978                         if (bpf_map_ptr_poisoned(aux)) {
9979                                 verbose(env, "tail_call abusing map_ptr\n");
9980                                 return -EINVAL;
9981                         }
9982
9983                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
9984                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
9985                                                   map_ptr->max_entries, 2);
9986                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
9987                                                     container_of(map_ptr,
9988                                                                  struct bpf_array,
9989                                                                  map)->index_mask);
9990                         insn_buf[2] = *insn;
9991                         cnt = 3;
9992                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9993                         if (!new_prog)
9994                                 return -ENOMEM;
9995
9996                         delta    += cnt - 1;
9997                         env->prog = prog = new_prog;
9998                         insn      = new_prog->insnsi + i + delta;
9999                         continue;
10000                 }
10001
10002                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
10003                  * and other inlining handlers are currently limited to 64 bit
10004                  * only.
10005                  */
10006                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
10007                     (insn->imm == BPF_FUNC_map_lookup_elem ||
10008                      insn->imm == BPF_FUNC_map_update_elem ||
10009                      insn->imm == BPF_FUNC_map_delete_elem ||
10010                      insn->imm == BPF_FUNC_map_push_elem   ||
10011                      insn->imm == BPF_FUNC_map_pop_elem    ||
10012                      insn->imm == BPF_FUNC_map_peek_elem)) {
10013                         aux = &env->insn_aux_data[i + delta];
10014                         if (bpf_map_ptr_poisoned(aux))
10015                                 goto patch_call_imm;
10016
10017                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
10018                         ops = map_ptr->ops;
10019                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
10020                             ops->map_gen_lookup) {
10021                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
10022                                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
10023                                         verbose(env, "bpf verifier is misconfigured\n");
10024                                         return -EINVAL;
10025                                 }
10026
10027                                 new_prog = bpf_patch_insn_data(env, i + delta,
10028                                                                insn_buf, cnt);
10029                                 if (!new_prog)
10030                                         return -ENOMEM;
10031
10032                                 delta    += cnt - 1;
10033                                 env->prog = prog = new_prog;
10034                                 insn      = new_prog->insnsi + i + delta;
10035                                 continue;
10036                         }
10037
10038                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
10039                                      (void *(*)(struct bpf_map *map, void *key))NULL));
10040                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
10041                                      (int (*)(struct bpf_map *map, void *key))NULL));
10042                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
10043                                      (int (*)(struct bpf_map *map, void *key, void *value,
10044                                               u64 flags))NULL));
10045                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
10046                                      (int (*)(struct bpf_map *map, void *value,
10047                                               u64 flags))NULL));
10048                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
10049                                      (int (*)(struct bpf_map *map, void *value))NULL));
10050                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
10051                                      (int (*)(struct bpf_map *map, void *value))NULL));
10052
10053                         switch (insn->imm) {
10054                         case BPF_FUNC_map_lookup_elem:
10055                                 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
10056                                             __bpf_call_base;
10057                                 continue;
10058                         case BPF_FUNC_map_update_elem:
10059                                 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
10060                                             __bpf_call_base;
10061                                 continue;
10062                         case BPF_FUNC_map_delete_elem:
10063                                 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
10064                                             __bpf_call_base;
10065                                 continue;
10066                         case BPF_FUNC_map_push_elem:
10067                                 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
10068                                             __bpf_call_base;
10069                                 continue;
10070                         case BPF_FUNC_map_pop_elem:
10071                                 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
10072                                             __bpf_call_base;
10073                                 continue;
10074                         case BPF_FUNC_map_peek_elem:
10075                                 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
10076                                             __bpf_call_base;
10077                                 continue;
10078                         }
10079
10080                         goto patch_call_imm;
10081                 }
10082
10083                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
10084                     insn->imm == BPF_FUNC_jiffies64) {
10085                         struct bpf_insn ld_jiffies_addr[2] = {
10086                                 BPF_LD_IMM64(BPF_REG_0,
10087                                              (unsigned long)&jiffies),
10088                         };
10089
10090                         insn_buf[0] = ld_jiffies_addr[0];
10091                         insn_buf[1] = ld_jiffies_addr[1];
10092                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
10093                                                   BPF_REG_0, 0);
10094                         cnt = 3;
10095
10096                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
10097                                                        cnt);
10098                         if (!new_prog)
10099                                 return -ENOMEM;
10100
10101                         delta    += cnt - 1;
10102                         env->prog = prog = new_prog;
10103                         insn      = new_prog->insnsi + i + delta;
10104                         continue;
10105                 }
10106
10107 patch_call_imm:
10108                 fn = env->ops->get_func_proto(insn->imm, env->prog);
10109                 /* all functions that have prototype and verifier allowed
10110                  * programs to call them, must be real in-kernel functions
10111                  */
10112                 if (!fn->func) {
10113                         verbose(env,
10114                                 "kernel subsystem misconfigured func %s#%d\n",
10115                                 func_id_name(insn->imm), insn->imm);
10116                         return -EFAULT;
10117                 }
10118                 insn->imm = fn->func - __bpf_call_base;
10119         }
10120
10121         /* Since poke tab is now finalized, publish aux to tracker. */
10122         for (i = 0; i < prog->aux->size_poke_tab; i++) {
10123                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
10124                 if (!map_ptr->ops->map_poke_track ||
10125                     !map_ptr->ops->map_poke_untrack ||
10126                     !map_ptr->ops->map_poke_run) {
10127                         verbose(env, "bpf verifier is misconfigured\n");
10128                         return -EINVAL;
10129                 }
10130
10131                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
10132                 if (ret < 0) {
10133                         verbose(env, "tracking tail call prog failed\n");
10134                         return ret;
10135                 }
10136         }
10137
10138         return 0;
10139 }
10140
10141 static void free_states(struct bpf_verifier_env *env)
10142 {
10143         struct bpf_verifier_state_list *sl, *sln;
10144         int i;
10145
10146         sl = env->free_list;
10147         while (sl) {
10148                 sln = sl->next;
10149                 free_verifier_state(&sl->state, false);
10150                 kfree(sl);
10151                 sl = sln;
10152         }
10153         env->free_list = NULL;
10154
10155         if (!env->explored_states)
10156                 return;
10157
10158         for (i = 0; i < state_htab_size(env); i++) {
10159                 sl = env->explored_states[i];
10160
10161                 while (sl) {
10162                         sln = sl->next;
10163                         free_verifier_state(&sl->state, false);
10164                         kfree(sl);
10165                         sl = sln;
10166                 }
10167                 env->explored_states[i] = NULL;
10168         }
10169 }
10170
10171 /* The verifier is using insn_aux_data[] to store temporary data during
10172  * verification and to store information for passes that run after the
10173  * verification like dead code sanitization. do_check_common() for subprogram N
10174  * may analyze many other subprograms. sanitize_insn_aux_data() clears all
10175  * temporary data after do_check_common() finds that subprogram N cannot be
10176  * verified independently. pass_cnt counts the number of times
10177  * do_check_common() was run and insn->aux->seen tells the pass number
10178  * insn_aux_data was touched. These variables are compared to clear temporary
10179  * data from failed pass. For testing and experiments do_check_common() can be
10180  * run multiple times even when prior attempt to verify is unsuccessful.
10181  */
10182 static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
10183 {
10184         struct bpf_insn *insn = env->prog->insnsi;
10185         struct bpf_insn_aux_data *aux;
10186         int i, class;
10187
10188         for (i = 0; i < env->prog->len; i++) {
10189                 class = BPF_CLASS(insn[i].code);
10190                 if (class != BPF_LDX && class != BPF_STX)
10191                         continue;
10192                 aux = &env->insn_aux_data[i];
10193                 if (aux->seen != env->pass_cnt)
10194                         continue;
10195                 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
10196         }
10197 }
10198
10199 static int do_check_common(struct bpf_verifier_env *env, int subprog)
10200 {
10201         struct bpf_verifier_state *state;
10202         struct bpf_reg_state *regs;
10203         int ret, i;
10204
10205         env->prev_linfo = NULL;
10206         env->pass_cnt++;
10207
10208         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
10209         if (!state)
10210                 return -ENOMEM;
10211         state->curframe = 0;
10212         state->speculative = false;
10213         state->branches = 1;
10214         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
10215         if (!state->frame[0]) {
10216                 kfree(state);
10217                 return -ENOMEM;
10218         }
10219         env->cur_state = state;
10220         init_func_state(env, state->frame[0],
10221                         BPF_MAIN_FUNC /* callsite */,
10222                         0 /* frameno */,
10223                         subprog);
10224
10225         regs = state->frame[state->curframe]->regs;
10226         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
10227                 ret = btf_prepare_func_args(env, subprog, regs);
10228                 if (ret)
10229                         goto out;
10230                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
10231                         if (regs[i].type == PTR_TO_CTX)
10232                                 mark_reg_known_zero(env, regs, i);
10233                         else if (regs[i].type == SCALAR_VALUE)
10234                                 mark_reg_unknown(env, regs, i);
10235                 }
10236         } else {
10237                 /* 1st arg to a function */
10238                 regs[BPF_REG_1].type = PTR_TO_CTX;
10239                 mark_reg_known_zero(env, regs, BPF_REG_1);
10240                 ret = btf_check_func_arg_match(env, subprog, regs);
10241                 if (ret == -EFAULT)
10242                         /* unlikely verifier bug. abort.
10243                          * ret == 0 and ret < 0 are sadly acceptable for
10244                          * main() function due to backward compatibility.
10245                          * Like socket filter program may be written as:
10246                          * int bpf_prog(struct pt_regs *ctx)
10247                          * and never dereference that ctx in the program.
10248                          * 'struct pt_regs' is a type mismatch for socket
10249                          * filter that should be using 'struct __sk_buff'.
10250                          */
10251                         goto out;
10252         }
10253
10254         ret = do_check(env);
10255 out:
10256         /* check for NULL is necessary, since cur_state can be freed inside
10257          * do_check() under memory pressure.
10258          */
10259         if (env->cur_state) {
10260                 free_verifier_state(env->cur_state, true);
10261                 env->cur_state = NULL;
10262         }
10263         while (!pop_stack(env, NULL, NULL));
10264         free_states(env);
10265         if (ret)
10266                 /* clean aux data in case subprog was rejected */
10267                 sanitize_insn_aux_data(env);
10268         return ret;
10269 }
10270
10271 /* Verify all global functions in a BPF program one by one based on their BTF.
10272  * All global functions must pass verification. Otherwise the whole program is rejected.
10273  * Consider:
10274  * int bar(int);
10275  * int foo(int f)
10276  * {
10277  *    return bar(f);
10278  * }
10279  * int bar(int b)
10280  * {
10281  *    ...
10282  * }
10283  * foo() will be verified first for R1=any_scalar_value. During verification it
10284  * will be assumed that bar() already verified successfully and call to bar()
10285  * from foo() will be checked for type match only. Later bar() will be verified
10286  * independently to check that it's safe for R1=any_scalar_value.
10287  */
10288 static int do_check_subprogs(struct bpf_verifier_env *env)
10289 {
10290         struct bpf_prog_aux *aux = env->prog->aux;
10291         int i, ret;
10292
10293         if (!aux->func_info)
10294                 return 0;
10295
10296         for (i = 1; i < env->subprog_cnt; i++) {
10297                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
10298                         continue;
10299                 env->insn_idx = env->subprog_info[i].start;
10300                 WARN_ON_ONCE(env->insn_idx == 0);
10301                 ret = do_check_common(env, i);
10302                 if (ret) {
10303                         return ret;
10304                 } else if (env->log.level & BPF_LOG_LEVEL) {
10305                         verbose(env,
10306                                 "Func#%d is safe for any args that match its prototype\n",
10307                                 i);
10308                 }
10309         }
10310         return 0;
10311 }
10312
10313 static int do_check_main(struct bpf_verifier_env *env)
10314 {
10315         int ret;
10316
10317         env->insn_idx = 0;
10318         ret = do_check_common(env, 0);
10319         if (!ret)
10320                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
10321         return ret;
10322 }
10323
10324
10325 static void print_verification_stats(struct bpf_verifier_env *env)
10326 {
10327         int i;
10328
10329         if (env->log.level & BPF_LOG_STATS) {
10330                 verbose(env, "verification time %lld usec\n",
10331                         div_u64(env->verification_time, 1000));
10332                 verbose(env, "stack depth ");
10333                 for (i = 0; i < env->subprog_cnt; i++) {
10334                         u32 depth = env->subprog_info[i].stack_depth;
10335
10336                         verbose(env, "%d", depth);
10337                         if (i + 1 < env->subprog_cnt)
10338                                 verbose(env, "+");
10339                 }
10340                 verbose(env, "\n");
10341         }
10342         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
10343                 "total_states %d peak_states %d mark_read %d\n",
10344                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
10345                 env->max_states_per_insn, env->total_states,
10346                 env->peak_states, env->longest_mark_read_walk);
10347 }
10348
10349 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
10350 {
10351         const struct btf_type *t, *func_proto;
10352         const struct bpf_struct_ops *st_ops;
10353         const struct btf_member *member;
10354         struct bpf_prog *prog = env->prog;
10355         u32 btf_id, member_idx;
10356         const char *mname;
10357
10358         btf_id = prog->aux->attach_btf_id;
10359         st_ops = bpf_struct_ops_find(btf_id);
10360         if (!st_ops) {
10361                 verbose(env, "attach_btf_id %u is not a supported struct\n",
10362                         btf_id);
10363                 return -ENOTSUPP;
10364         }
10365
10366         t = st_ops->type;
10367         member_idx = prog->expected_attach_type;
10368         if (member_idx >= btf_type_vlen(t)) {
10369                 verbose(env, "attach to invalid member idx %u of struct %s\n",
10370                         member_idx, st_ops->name);
10371                 return -EINVAL;
10372         }
10373
10374         member = &btf_type_member(t)[member_idx];
10375         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
10376         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
10377                                                NULL);
10378         if (!func_proto) {
10379                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
10380                         mname, member_idx, st_ops->name);
10381                 return -EINVAL;
10382         }
10383
10384         if (st_ops->check_member) {
10385                 int err = st_ops->check_member(t, member);
10386
10387                 if (err) {
10388                         verbose(env, "attach to unsupported member %s of struct %s\n",
10389                                 mname, st_ops->name);
10390                         return err;
10391                 }
10392         }
10393
10394         prog->aux->attach_func_proto = func_proto;
10395         prog->aux->attach_func_name = mname;
10396         env->ops = st_ops->verifier_ops;
10397
10398         return 0;
10399 }
10400 #define SECURITY_PREFIX "security_"
10401
10402 static int check_attach_modify_return(struct bpf_verifier_env *env)
10403 {
10404         struct bpf_prog *prog = env->prog;
10405         unsigned long addr = (unsigned long) prog->aux->trampoline->func.addr;
10406
10407         /* This is expected to be cleaned up in the future with the KRSI effort
10408          * introducing the LSM_HOOK macro for cleaning up lsm_hooks.h.
10409          */
10410         if (within_error_injection_list(addr) ||
10411             !strncmp(SECURITY_PREFIX, prog->aux->attach_func_name,
10412                      sizeof(SECURITY_PREFIX) - 1))
10413                 return 0;
10414
10415         verbose(env, "fmod_ret attach_btf_id %u (%s) is not modifiable\n",
10416                 prog->aux->attach_btf_id, prog->aux->attach_func_name);
10417
10418         return -EINVAL;
10419 }
10420
10421 static int check_attach_btf_id(struct bpf_verifier_env *env)
10422 {
10423         struct bpf_prog *prog = env->prog;
10424         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
10425         struct bpf_prog *tgt_prog = prog->aux->linked_prog;
10426         u32 btf_id = prog->aux->attach_btf_id;
10427         const char prefix[] = "btf_trace_";
10428         int ret = 0, subprog = -1, i;
10429         struct bpf_trampoline *tr;
10430         const struct btf_type *t;
10431         bool conservative = true;
10432         const char *tname;
10433         struct btf *btf;
10434         long addr;
10435         u64 key;
10436
10437         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
10438                 return check_struct_ops_btf_id(env);
10439
10440         if (prog->type != BPF_PROG_TYPE_TRACING &&
10441             prog->type != BPF_PROG_TYPE_LSM &&
10442             !prog_extension)
10443                 return 0;
10444
10445         if (!btf_id) {
10446                 verbose(env, "Tracing programs must provide btf_id\n");
10447                 return -EINVAL;
10448         }
10449         btf = bpf_prog_get_target_btf(prog);
10450         if (!btf) {
10451                 verbose(env,
10452                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
10453                 return -EINVAL;
10454         }
10455         t = btf_type_by_id(btf, btf_id);
10456         if (!t) {
10457                 verbose(env, "attach_btf_id %u is invalid\n", btf_id);
10458                 return -EINVAL;
10459         }
10460         tname = btf_name_by_offset(btf, t->name_off);
10461         if (!tname) {
10462                 verbose(env, "attach_btf_id %u doesn't have a name\n", btf_id);
10463                 return -EINVAL;
10464         }
10465         if (tgt_prog) {
10466                 struct bpf_prog_aux *aux = tgt_prog->aux;
10467
10468                 for (i = 0; i < aux->func_info_cnt; i++)
10469                         if (aux->func_info[i].type_id == btf_id) {
10470                                 subprog = i;
10471                                 break;
10472                         }
10473                 if (subprog == -1) {
10474                         verbose(env, "Subprog %s doesn't exist\n", tname);
10475                         return -EINVAL;
10476                 }
10477                 conservative = aux->func_info_aux[subprog].unreliable;
10478                 if (prog_extension) {
10479                         if (conservative) {
10480                                 verbose(env,
10481                                         "Cannot replace static functions\n");
10482                                 return -EINVAL;
10483                         }
10484                         if (!prog->jit_requested) {
10485                                 verbose(env,
10486                                         "Extension programs should be JITed\n");
10487                                 return -EINVAL;
10488                         }
10489                         env->ops = bpf_verifier_ops[tgt_prog->type];
10490                 }
10491                 if (!tgt_prog->jited) {
10492                         verbose(env, "Can attach to only JITed progs\n");
10493                         return -EINVAL;
10494                 }
10495                 if (tgt_prog->type == prog->type) {
10496                         /* Cannot fentry/fexit another fentry/fexit program.
10497                          * Cannot attach program extension to another extension.
10498                          * It's ok to attach fentry/fexit to extension program.
10499                          */
10500                         verbose(env, "Cannot recursively attach\n");
10501                         return -EINVAL;
10502                 }
10503                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
10504                     prog_extension &&
10505                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
10506                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
10507                         /* Program extensions can extend all program types
10508                          * except fentry/fexit. The reason is the following.
10509                          * The fentry/fexit programs are used for performance
10510                          * analysis, stats and can be attached to any program
10511                          * type except themselves. When extension program is
10512                          * replacing XDP function it is necessary to allow
10513                          * performance analysis of all functions. Both original
10514                          * XDP program and its program extension. Hence
10515                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
10516                          * allowed. If extending of fentry/fexit was allowed it
10517                          * would be possible to create long call chain
10518                          * fentry->extension->fentry->extension beyond
10519                          * reasonable stack size. Hence extending fentry is not
10520                          * allowed.
10521                          */
10522                         verbose(env, "Cannot extend fentry/fexit\n");
10523                         return -EINVAL;
10524                 }
10525                 key = ((u64)aux->id) << 32 | btf_id;
10526         } else {
10527                 if (prog_extension) {
10528                         verbose(env, "Cannot replace kernel functions\n");
10529                         return -EINVAL;
10530                 }
10531                 key = btf_id;
10532         }
10533
10534         switch (prog->expected_attach_type) {
10535         case BPF_TRACE_RAW_TP:
10536                 if (tgt_prog) {
10537                         verbose(env,
10538                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
10539                         return -EINVAL;
10540                 }
10541                 if (!btf_type_is_typedef(t)) {
10542                         verbose(env, "attach_btf_id %u is not a typedef\n",
10543                                 btf_id);
10544                         return -EINVAL;
10545                 }
10546                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
10547                         verbose(env, "attach_btf_id %u points to wrong type name %s\n",
10548                                 btf_id, tname);
10549                         return -EINVAL;
10550                 }
10551                 tname += sizeof(prefix) - 1;
10552                 t = btf_type_by_id(btf, t->type);
10553                 if (!btf_type_is_ptr(t))
10554                         /* should never happen in valid vmlinux build */
10555                         return -EINVAL;
10556                 t = btf_type_by_id(btf, t->type);
10557                 if (!btf_type_is_func_proto(t))
10558                         /* should never happen in valid vmlinux build */
10559                         return -EINVAL;
10560
10561                 /* remember two read only pointers that are valid for
10562                  * the life time of the kernel
10563                  */
10564                 prog->aux->attach_func_name = tname;
10565                 prog->aux->attach_func_proto = t;
10566                 prog->aux->attach_btf_trace = true;
10567                 return 0;
10568         default:
10569                 if (!prog_extension)
10570                         return -EINVAL;
10571                 /* fallthrough */
10572         case BPF_MODIFY_RETURN:
10573         case BPF_LSM_MAC:
10574         case BPF_TRACE_FENTRY:
10575         case BPF_TRACE_FEXIT:
10576                 prog->aux->attach_func_name = tname;
10577                 if (prog->type == BPF_PROG_TYPE_LSM) {
10578                         ret = bpf_lsm_verify_prog(&env->log, prog);
10579                         if (ret < 0)
10580                                 return ret;
10581                 }
10582
10583                 if (!btf_type_is_func(t)) {
10584                         verbose(env, "attach_btf_id %u is not a function\n",
10585                                 btf_id);
10586                         return -EINVAL;
10587                 }
10588                 if (prog_extension &&
10589                     btf_check_type_match(env, prog, btf, t))
10590                         return -EINVAL;
10591                 t = btf_type_by_id(btf, t->type);
10592                 if (!btf_type_is_func_proto(t))
10593                         return -EINVAL;
10594                 tr = bpf_trampoline_lookup(key);
10595                 if (!tr)
10596                         return -ENOMEM;
10597                 /* t is either vmlinux type or another program's type */
10598                 prog->aux->attach_func_proto = t;
10599                 mutex_lock(&tr->mutex);
10600                 if (tr->func.addr) {
10601                         prog->aux->trampoline = tr;
10602                         goto out;
10603                 }
10604                 if (tgt_prog && conservative) {
10605                         prog->aux->attach_func_proto = NULL;
10606                         t = NULL;
10607                 }
10608                 ret = btf_distill_func_proto(&env->log, btf, t,
10609                                              tname, &tr->func.model);
10610                 if (ret < 0)
10611                         goto out;
10612                 if (tgt_prog) {
10613                         if (subprog == 0)
10614                                 addr = (long) tgt_prog->bpf_func;
10615                         else
10616                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
10617                 } else {
10618                         addr = kallsyms_lookup_name(tname);
10619                         if (!addr) {
10620                                 verbose(env,
10621                                         "The address of function %s cannot be found\n",
10622                                         tname);
10623                                 ret = -ENOENT;
10624                                 goto out;
10625                         }
10626                 }
10627                 tr->func.addr = (void *)addr;
10628                 prog->aux->trampoline = tr;
10629
10630                 if (prog->expected_attach_type == BPF_MODIFY_RETURN)
10631                         ret = check_attach_modify_return(env);
10632 out:
10633                 mutex_unlock(&tr->mutex);
10634                 if (ret)
10635                         bpf_trampoline_put(tr);
10636                 return ret;
10637         }
10638 }
10639
10640 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
10641               union bpf_attr __user *uattr)
10642 {
10643         u64 start_time = ktime_get_ns();
10644         struct bpf_verifier_env *env;
10645         struct bpf_verifier_log *log;
10646         int i, len, ret = -EINVAL;
10647         bool is_priv;
10648
10649         /* no program is valid */
10650         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
10651                 return -EINVAL;
10652
10653         /* 'struct bpf_verifier_env' can be global, but since it's not small,
10654          * allocate/free it every time bpf_check() is called
10655          */
10656         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
10657         if (!env)
10658                 return -ENOMEM;
10659         log = &env->log;
10660
10661         len = (*prog)->len;
10662         env->insn_aux_data =
10663                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
10664         ret = -ENOMEM;
10665         if (!env->insn_aux_data)
10666                 goto err_free_env;
10667         for (i = 0; i < len; i++)
10668                 env->insn_aux_data[i].orig_idx = i;
10669         env->prog = *prog;
10670         env->ops = bpf_verifier_ops[env->prog->type];
10671         is_priv = capable(CAP_SYS_ADMIN);
10672
10673         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
10674                 mutex_lock(&bpf_verifier_lock);
10675                 if (!btf_vmlinux)
10676                         btf_vmlinux = btf_parse_vmlinux();
10677                 mutex_unlock(&bpf_verifier_lock);
10678         }
10679
10680         /* grab the mutex to protect few globals used by verifier */
10681         if (!is_priv)
10682                 mutex_lock(&bpf_verifier_lock);
10683
10684         if (attr->log_level || attr->log_buf || attr->log_size) {
10685                 /* user requested verbose verifier output
10686                  * and supplied buffer to store the verification trace
10687                  */
10688                 log->level = attr->log_level;
10689                 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
10690                 log->len_total = attr->log_size;
10691
10692                 ret = -EINVAL;
10693                 /* log attributes have to be sane */
10694                 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
10695                     !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
10696                         goto err_unlock;
10697         }
10698
10699         if (IS_ERR(btf_vmlinux)) {
10700                 /* Either gcc or pahole or kernel are broken. */
10701                 verbose(env, "in-kernel BTF is malformed\n");
10702                 ret = PTR_ERR(btf_vmlinux);
10703                 goto skip_full_check;
10704         }
10705
10706         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
10707         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
10708                 env->strict_alignment = true;
10709         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
10710                 env->strict_alignment = false;
10711
10712         env->allow_ptr_leaks = is_priv;
10713
10714         if (is_priv)
10715                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
10716
10717         ret = replace_map_fd_with_map_ptr(env);
10718         if (ret < 0)
10719                 goto skip_full_check;
10720
10721         if (bpf_prog_is_dev_bound(env->prog->aux)) {
10722                 ret = bpf_prog_offload_verifier_prep(env->prog);
10723                 if (ret)
10724                         goto skip_full_check;
10725         }
10726
10727         env->explored_states = kvcalloc(state_htab_size(env),
10728                                        sizeof(struct bpf_verifier_state_list *),
10729                                        GFP_USER);
10730         ret = -ENOMEM;
10731         if (!env->explored_states)
10732                 goto skip_full_check;
10733
10734         ret = check_subprogs(env);
10735         if (ret < 0)
10736                 goto skip_full_check;
10737
10738         ret = check_btf_info(env, attr, uattr);
10739         if (ret < 0)
10740                 goto skip_full_check;
10741
10742         ret = check_attach_btf_id(env);
10743         if (ret)
10744                 goto skip_full_check;
10745
10746         ret = check_cfg(env);
10747         if (ret < 0)
10748                 goto skip_full_check;
10749
10750         ret = do_check_subprogs(env);
10751         ret = ret ?: do_check_main(env);
10752
10753         if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
10754                 ret = bpf_prog_offload_finalize(env);
10755
10756 skip_full_check:
10757         kvfree(env->explored_states);
10758
10759         if (ret == 0)
10760                 ret = check_max_stack_depth(env);
10761
10762         /* instruction rewrites happen after this point */
10763         if (is_priv) {
10764                 if (ret == 0)
10765                         opt_hard_wire_dead_code_branches(env);
10766                 if (ret == 0)
10767                         ret = opt_remove_dead_code(env);
10768                 if (ret == 0)
10769                         ret = opt_remove_nops(env);
10770         } else {
10771                 if (ret == 0)
10772                         sanitize_dead_code(env);
10773         }
10774
10775         if (ret == 0)
10776                 /* program is valid, convert *(u32*)(ctx + off) accesses */
10777                 ret = convert_ctx_accesses(env);
10778
10779         if (ret == 0)
10780                 ret = fixup_bpf_calls(env);
10781
10782         /* do 32-bit optimization after insn patching has done so those patched
10783          * insns could be handled correctly.
10784          */
10785         if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
10786                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
10787                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
10788                                                                      : false;
10789         }
10790
10791         if (ret == 0)
10792                 ret = fixup_call_args(env);
10793
10794         env->verification_time = ktime_get_ns() - start_time;
10795         print_verification_stats(env);
10796
10797         if (log->level && bpf_verifier_log_full(log))
10798                 ret = -ENOSPC;
10799         if (log->level && !log->ubuf) {
10800                 ret = -EFAULT;
10801                 goto err_release_maps;
10802         }
10803
10804         if (ret == 0 && env->used_map_cnt) {
10805                 /* if program passed verifier, update used_maps in bpf_prog_info */
10806                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
10807                                                           sizeof(env->used_maps[0]),
10808                                                           GFP_KERNEL);
10809
10810                 if (!env->prog->aux->used_maps) {
10811                         ret = -ENOMEM;
10812                         goto err_release_maps;
10813                 }
10814
10815                 memcpy(env->prog->aux->used_maps, env->used_maps,
10816                        sizeof(env->used_maps[0]) * env->used_map_cnt);
10817                 env->prog->aux->used_map_cnt = env->used_map_cnt;
10818
10819                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
10820                  * bpf_ld_imm64 instructions
10821                  */
10822                 convert_pseudo_ld_imm64(env);
10823         }
10824
10825         if (ret == 0)
10826                 adjust_btf_func(env);
10827
10828 err_release_maps:
10829         if (!env->prog->aux->used_maps)
10830                 /* if we didn't copy map pointers into bpf_prog_info, release
10831                  * them now. Otherwise free_used_maps() will release them.
10832                  */
10833                 release_maps(env);
10834         *prog = env->prog;
10835 err_unlock:
10836         if (!is_priv)
10837                 mutex_unlock(&bpf_verifier_lock);
10838         vfree(env->insn_aux_data);
10839 err_free_env:
10840         kfree(env);
10841         return ret;
10842 }