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