OSDN Git Service

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