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