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