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