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