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