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