Merge tag 'pci-v5.8-fixes-2' of git://git.kernel.org/pub/scm/linux/kernel/git/helgaas...
[linux-2.6-microblaze.git] / kernel / bpf / verifier.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/kernel.h>
8 #include <linux/types.h>
9 #include <linux/slab.h>
10 #include <linux/bpf.h>
11 #include <linux/btf.h>
12 #include <linux/bpf_verifier.h>
13 #include <linux/filter.h>
14 #include <net/netlink.h>
15 #include <linux/file.h>
16 #include <linux/vmalloc.h>
17 #include <linux/stringify.h>
18 #include <linux/bsearch.h>
19 #include <linux/sort.h>
20 #include <linux/perf_event.h>
21 #include <linux/ctype.h>
22 #include <linux/error-injection.h>
23 #include <linux/bpf_lsm.h>
24
25 #include "disasm.h"
26
27 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
28 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
29         [_id] = & _name ## _verifier_ops,
30 #define BPF_MAP_TYPE(_id, _ops)
31 #define BPF_LINK_TYPE(_id, _name)
32 #include <linux/bpf_types.h>
33 #undef BPF_PROG_TYPE
34 #undef BPF_MAP_TYPE
35 #undef BPF_LINK_TYPE
36 };
37
38 /* bpf_check() is a static code analyzer that walks eBPF program
39  * instruction by instruction and updates register/stack state.
40  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
41  *
42  * The first pass is depth-first-search to check that the program is a DAG.
43  * It rejects the following programs:
44  * - larger than BPF_MAXINSNS insns
45  * - if loop is present (detected via back-edge)
46  * - unreachable insns exist (shouldn't be a forest. program = one function)
47  * - out of bounds or malformed jumps
48  * The second pass is all possible path descent from the 1st insn.
49  * Since it's analyzing all pathes through the program, the length of the
50  * analysis is limited to 64k insn, which may be hit even if total number of
51  * insn is less then 4K, but there are too many branches that change stack/regs.
52  * Number of 'branches to be analyzed' is limited to 1k
53  *
54  * On entry to each instruction, each register has a type, and the instruction
55  * changes the types of the registers depending on instruction semantics.
56  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
57  * copied to R1.
58  *
59  * All registers are 64-bit.
60  * R0 - return register
61  * R1-R5 argument passing registers
62  * R6-R9 callee saved registers
63  * R10 - frame pointer read-only
64  *
65  * At the start of BPF program the register R1 contains a pointer to bpf_context
66  * and has type PTR_TO_CTX.
67  *
68  * Verifier tracks arithmetic operations on pointers in case:
69  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
70  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
71  * 1st insn copies R10 (which has FRAME_PTR) type into R1
72  * and 2nd arithmetic instruction is pattern matched to recognize
73  * that it wants to construct a pointer to some element within stack.
74  * So after 2nd insn, the register R1 has type PTR_TO_STACK
75  * (and -20 constant is saved for further stack bounds checking).
76  * Meaning that this reg is a pointer to stack plus known immediate constant.
77  *
78  * Most of the time the registers have SCALAR_VALUE type, which
79  * means the register has some value, but it's not a valid pointer.
80  * (like pointer plus pointer becomes SCALAR_VALUE type)
81  *
82  * When verifier sees load or store instructions the type of base register
83  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
84  * four pointer types recognized by check_mem_access() function.
85  *
86  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
87  * and the range of [ptr, ptr + map's value_size) is accessible.
88  *
89  * registers used to pass values to function calls are checked against
90  * function argument constraints.
91  *
92  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
93  * It means that the register type passed to this function must be
94  * PTR_TO_STACK and it will be used inside the function as
95  * 'pointer to map element key'
96  *
97  * For example the argument constraints for bpf_map_lookup_elem():
98  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
99  *   .arg1_type = ARG_CONST_MAP_PTR,
100  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
101  *
102  * ret_type says that this function returns 'pointer to map elem value or null'
103  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
104  * 2nd argument should be a pointer to stack, which will be used inside
105  * the helper function as a pointer to map element key.
106  *
107  * On the kernel side the helper function looks like:
108  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
109  * {
110  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
111  *    void *key = (void *) (unsigned long) r2;
112  *    void *value;
113  *
114  *    here kernel can access 'key' and 'map' pointers safely, knowing that
115  *    [key, key + map->key_size) bytes are valid and were initialized on
116  *    the stack of eBPF program.
117  * }
118  *
119  * Corresponding eBPF program may look like:
120  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
121  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
122  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
123  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
124  * here verifier looks at prototype of map_lookup_elem() and sees:
125  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
126  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
127  *
128  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
129  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
130  * and were initialized prior to this call.
131  * If it's ok, then verifier allows this BPF_CALL insn and looks at
132  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
133  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
134  * returns ether pointer to map value or NULL.
135  *
136  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
137  * insn, the register holding that pointer in the true branch changes state to
138  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
139  * branch. See check_cond_jmp_op().
140  *
141  * After the call R0 is set to return type of the function and registers R1-R5
142  * are set to NOT_INIT to indicate that they are no longer readable.
143  *
144  * The following reference types represent a potential reference to a kernel
145  * resource which, after first being allocated, must be checked and freed by
146  * the BPF program:
147  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
148  *
149  * When the verifier sees a helper call return a reference type, it allocates a
150  * pointer id for the reference and stores it in the current function state.
151  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
152  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
153  * passes through a NULL-check conditional. For the branch wherein the state is
154  * changed to CONST_IMM, the verifier releases the reference.
155  *
156  * For each helper function that allocates a reference, such as
157  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
158  * bpf_sk_release(). When a reference type passes into the release function,
159  * the verifier also releases the reference. If any unchecked or unreleased
160  * reference remains at the end of the program, the verifier rejects it.
161  */
162
163 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
164 struct bpf_verifier_stack_elem {
165         /* verifer state is 'st'
166          * before processing instruction 'insn_idx'
167          * and after processing instruction 'prev_insn_idx'
168          */
169         struct bpf_verifier_state st;
170         int insn_idx;
171         int prev_insn_idx;
172         struct bpf_verifier_stack_elem *next;
173         /* length of verifier log at the time this state was pushed on stack */
174         u32 log_pos;
175 };
176
177 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ    8192
178 #define BPF_COMPLEXITY_LIMIT_STATES     64
179
180 #define BPF_MAP_KEY_POISON      (1ULL << 63)
181 #define BPF_MAP_KEY_SEEN        (1ULL << 62)
182
183 #define BPF_MAP_PTR_UNPRIV      1UL
184 #define BPF_MAP_PTR_POISON      ((void *)((0xeB9FUL << 1) +     \
185                                           POISON_POINTER_DELTA))
186 #define BPF_MAP_PTR(X)          ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
187
188 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
189 {
190         return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
191 }
192
193 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
194 {
195         return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
196 }
197
198 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
199                               const struct bpf_map *map, bool unpriv)
200 {
201         BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
202         unpriv |= bpf_map_ptr_unpriv(aux);
203         aux->map_ptr_state = (unsigned long)map |
204                              (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
205 }
206
207 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
208 {
209         return aux->map_key_state & BPF_MAP_KEY_POISON;
210 }
211
212 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
213 {
214         return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
215 }
216
217 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
218 {
219         return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
220 }
221
222 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
223 {
224         bool poisoned = bpf_map_key_poisoned(aux);
225
226         aux->map_key_state = state | BPF_MAP_KEY_SEEN |
227                              (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
228 }
229
230 struct bpf_call_arg_meta {
231         struct bpf_map *map_ptr;
232         bool raw_mode;
233         bool pkt_access;
234         int regno;
235         int access_size;
236         int mem_size;
237         u64 msize_max_value;
238         int ref_obj_id;
239         int func_id;
240         u32 btf_id;
241 };
242
243 struct btf *btf_vmlinux;
244
245 static DEFINE_MUTEX(bpf_verifier_lock);
246
247 static const struct bpf_line_info *
248 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
249 {
250         const struct bpf_line_info *linfo;
251         const struct bpf_prog *prog;
252         u32 i, nr_linfo;
253
254         prog = env->prog;
255         nr_linfo = prog->aux->nr_linfo;
256
257         if (!nr_linfo || insn_off >= prog->len)
258                 return NULL;
259
260         linfo = prog->aux->linfo;
261         for (i = 1; i < nr_linfo; i++)
262                 if (insn_off < linfo[i].insn_off)
263                         break;
264
265         return &linfo[i - 1];
266 }
267
268 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
269                        va_list args)
270 {
271         unsigned int n;
272
273         n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
274
275         WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
276                   "verifier log line truncated - local buffer too short\n");
277
278         n = min(log->len_total - log->len_used - 1, n);
279         log->kbuf[n] = '\0';
280
281         if (log->level == BPF_LOG_KERNEL) {
282                 pr_err("BPF:%s\n", log->kbuf);
283                 return;
284         }
285         if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
286                 log->len_used += n;
287         else
288                 log->ubuf = NULL;
289 }
290
291 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
292 {
293         char zero = 0;
294
295         if (!bpf_verifier_log_needed(log))
296                 return;
297
298         log->len_used = new_pos;
299         if (put_user(zero, log->ubuf + new_pos))
300                 log->ubuf = NULL;
301 }
302
303 /* log_level controls verbosity level of eBPF verifier.
304  * bpf_verifier_log_write() is used to dump the verification trace to the log,
305  * so the user can figure out what's wrong with the program
306  */
307 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
308                                            const char *fmt, ...)
309 {
310         va_list args;
311
312         if (!bpf_verifier_log_needed(&env->log))
313                 return;
314
315         va_start(args, fmt);
316         bpf_verifier_vlog(&env->log, fmt, args);
317         va_end(args);
318 }
319 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
320
321 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
322 {
323         struct bpf_verifier_env *env = private_data;
324         va_list args;
325
326         if (!bpf_verifier_log_needed(&env->log))
327                 return;
328
329         va_start(args, fmt);
330         bpf_verifier_vlog(&env->log, fmt, args);
331         va_end(args);
332 }
333
334 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
335                             const char *fmt, ...)
336 {
337         va_list args;
338
339         if (!bpf_verifier_log_needed(log))
340                 return;
341
342         va_start(args, fmt);
343         bpf_verifier_vlog(log, fmt, args);
344         va_end(args);
345 }
346
347 static const char *ltrim(const char *s)
348 {
349         while (isspace(*s))
350                 s++;
351
352         return s;
353 }
354
355 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
356                                          u32 insn_off,
357                                          const char *prefix_fmt, ...)
358 {
359         const struct bpf_line_info *linfo;
360
361         if (!bpf_verifier_log_needed(&env->log))
362                 return;
363
364         linfo = find_linfo(env, insn_off);
365         if (!linfo || linfo == env->prev_linfo)
366                 return;
367
368         if (prefix_fmt) {
369                 va_list args;
370
371                 va_start(args, prefix_fmt);
372                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
373                 va_end(args);
374         }
375
376         verbose(env, "%s\n",
377                 ltrim(btf_name_by_offset(env->prog->aux->btf,
378                                          linfo->line_off)));
379
380         env->prev_linfo = linfo;
381 }
382
383 static bool type_is_pkt_pointer(enum bpf_reg_type type)
384 {
385         return type == PTR_TO_PACKET ||
386                type == PTR_TO_PACKET_META;
387 }
388
389 static bool type_is_sk_pointer(enum bpf_reg_type type)
390 {
391         return type == PTR_TO_SOCKET ||
392                 type == PTR_TO_SOCK_COMMON ||
393                 type == PTR_TO_TCP_SOCK ||
394                 type == PTR_TO_XDP_SOCK;
395 }
396
397 static bool reg_type_not_null(enum bpf_reg_type type)
398 {
399         return type == PTR_TO_SOCKET ||
400                 type == PTR_TO_TCP_SOCK ||
401                 type == PTR_TO_MAP_VALUE ||
402                 type == PTR_TO_SOCK_COMMON;
403 }
404
405 static bool reg_type_may_be_null(enum bpf_reg_type type)
406 {
407         return type == PTR_TO_MAP_VALUE_OR_NULL ||
408                type == PTR_TO_SOCKET_OR_NULL ||
409                type == PTR_TO_SOCK_COMMON_OR_NULL ||
410                type == PTR_TO_TCP_SOCK_OR_NULL ||
411                type == PTR_TO_BTF_ID_OR_NULL ||
412                type == PTR_TO_MEM_OR_NULL;
413 }
414
415 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
416 {
417         return reg->type == PTR_TO_MAP_VALUE &&
418                 map_value_has_spin_lock(reg->map_ptr);
419 }
420
421 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
422 {
423         return type == PTR_TO_SOCKET ||
424                 type == PTR_TO_SOCKET_OR_NULL ||
425                 type == PTR_TO_TCP_SOCK ||
426                 type == PTR_TO_TCP_SOCK_OR_NULL ||
427                 type == PTR_TO_MEM ||
428                 type == PTR_TO_MEM_OR_NULL;
429 }
430
431 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
432 {
433         return type == ARG_PTR_TO_SOCK_COMMON;
434 }
435
436 /* Determine whether the function releases some resources allocated by another
437  * function call. The first reference type argument will be assumed to be
438  * released by release_reference().
439  */
440 static bool is_release_function(enum bpf_func_id func_id)
441 {
442         return func_id == BPF_FUNC_sk_release ||
443                func_id == BPF_FUNC_ringbuf_submit ||
444                func_id == BPF_FUNC_ringbuf_discard;
445 }
446
447 static bool may_be_acquire_function(enum bpf_func_id func_id)
448 {
449         return func_id == BPF_FUNC_sk_lookup_tcp ||
450                 func_id == BPF_FUNC_sk_lookup_udp ||
451                 func_id == BPF_FUNC_skc_lookup_tcp ||
452                 func_id == BPF_FUNC_map_lookup_elem ||
453                 func_id == BPF_FUNC_ringbuf_reserve;
454 }
455
456 static bool is_acquire_function(enum bpf_func_id func_id,
457                                 const struct bpf_map *map)
458 {
459         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
460
461         if (func_id == BPF_FUNC_sk_lookup_tcp ||
462             func_id == BPF_FUNC_sk_lookup_udp ||
463             func_id == BPF_FUNC_skc_lookup_tcp ||
464             func_id == BPF_FUNC_ringbuf_reserve)
465                 return true;
466
467         if (func_id == BPF_FUNC_map_lookup_elem &&
468             (map_type == BPF_MAP_TYPE_SOCKMAP ||
469              map_type == BPF_MAP_TYPE_SOCKHASH))
470                 return true;
471
472         return false;
473 }
474
475 static bool is_ptr_cast_function(enum bpf_func_id func_id)
476 {
477         return func_id == BPF_FUNC_tcp_sock ||
478                 func_id == BPF_FUNC_sk_fullsock;
479 }
480
481 /* string representation of 'enum bpf_reg_type' */
482 static const char * const reg_type_str[] = {
483         [NOT_INIT]              = "?",
484         [SCALAR_VALUE]          = "inv",
485         [PTR_TO_CTX]            = "ctx",
486         [CONST_PTR_TO_MAP]      = "map_ptr",
487         [PTR_TO_MAP_VALUE]      = "map_value",
488         [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
489         [PTR_TO_STACK]          = "fp",
490         [PTR_TO_PACKET]         = "pkt",
491         [PTR_TO_PACKET_META]    = "pkt_meta",
492         [PTR_TO_PACKET_END]     = "pkt_end",
493         [PTR_TO_FLOW_KEYS]      = "flow_keys",
494         [PTR_TO_SOCKET]         = "sock",
495         [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
496         [PTR_TO_SOCK_COMMON]    = "sock_common",
497         [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
498         [PTR_TO_TCP_SOCK]       = "tcp_sock",
499         [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
500         [PTR_TO_TP_BUFFER]      = "tp_buffer",
501         [PTR_TO_XDP_SOCK]       = "xdp_sock",
502         [PTR_TO_BTF_ID]         = "ptr_",
503         [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
504         [PTR_TO_MEM]            = "mem",
505         [PTR_TO_MEM_OR_NULL]    = "mem_or_null",
506 };
507
508 static char slot_type_char[] = {
509         [STACK_INVALID] = '?',
510         [STACK_SPILL]   = 'r',
511         [STACK_MISC]    = 'm',
512         [STACK_ZERO]    = '0',
513 };
514
515 static void print_liveness(struct bpf_verifier_env *env,
516                            enum bpf_reg_liveness live)
517 {
518         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
519             verbose(env, "_");
520         if (live & REG_LIVE_READ)
521                 verbose(env, "r");
522         if (live & REG_LIVE_WRITTEN)
523                 verbose(env, "w");
524         if (live & REG_LIVE_DONE)
525                 verbose(env, "D");
526 }
527
528 static struct bpf_func_state *func(struct bpf_verifier_env *env,
529                                    const struct bpf_reg_state *reg)
530 {
531         struct bpf_verifier_state *cur = env->cur_state;
532
533         return cur->frame[reg->frameno];
534 }
535
536 const char *kernel_type_name(u32 id)
537 {
538         return btf_name_by_offset(btf_vmlinux,
539                                   btf_type_by_id(btf_vmlinux, id)->name_off);
540 }
541
542 static void print_verifier_state(struct bpf_verifier_env *env,
543                                  const struct bpf_func_state *state)
544 {
545         const struct bpf_reg_state *reg;
546         enum bpf_reg_type t;
547         int i;
548
549         if (state->frameno)
550                 verbose(env, " frame%d:", state->frameno);
551         for (i = 0; i < MAX_BPF_REG; i++) {
552                 reg = &state->regs[i];
553                 t = reg->type;
554                 if (t == NOT_INIT)
555                         continue;
556                 verbose(env, " R%d", i);
557                 print_liveness(env, reg->live);
558                 verbose(env, "=%s", reg_type_str[t]);
559                 if (t == SCALAR_VALUE && reg->precise)
560                         verbose(env, "P");
561                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
562                     tnum_is_const(reg->var_off)) {
563                         /* reg->off should be 0 for SCALAR_VALUE */
564                         verbose(env, "%lld", reg->var_off.value + reg->off);
565                 } else {
566                         if (t == PTR_TO_BTF_ID || t == PTR_TO_BTF_ID_OR_NULL)
567                                 verbose(env, "%s", kernel_type_name(reg->btf_id));
568                         verbose(env, "(id=%d", reg->id);
569                         if (reg_type_may_be_refcounted_or_null(t))
570                                 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
571                         if (t != SCALAR_VALUE)
572                                 verbose(env, ",off=%d", reg->off);
573                         if (type_is_pkt_pointer(t))
574                                 verbose(env, ",r=%d", reg->range);
575                         else if (t == CONST_PTR_TO_MAP ||
576                                  t == PTR_TO_MAP_VALUE ||
577                                  t == PTR_TO_MAP_VALUE_OR_NULL)
578                                 verbose(env, ",ks=%d,vs=%d",
579                                         reg->map_ptr->key_size,
580                                         reg->map_ptr->value_size);
581                         if (tnum_is_const(reg->var_off)) {
582                                 /* Typically an immediate SCALAR_VALUE, but
583                                  * could be a pointer whose offset is too big
584                                  * for reg->off
585                                  */
586                                 verbose(env, ",imm=%llx", reg->var_off.value);
587                         } else {
588                                 if (reg->smin_value != reg->umin_value &&
589                                     reg->smin_value != S64_MIN)
590                                         verbose(env, ",smin_value=%lld",
591                                                 (long long)reg->smin_value);
592                                 if (reg->smax_value != reg->umax_value &&
593                                     reg->smax_value != S64_MAX)
594                                         verbose(env, ",smax_value=%lld",
595                                                 (long long)reg->smax_value);
596                                 if (reg->umin_value != 0)
597                                         verbose(env, ",umin_value=%llu",
598                                                 (unsigned long long)reg->umin_value);
599                                 if (reg->umax_value != U64_MAX)
600                                         verbose(env, ",umax_value=%llu",
601                                                 (unsigned long long)reg->umax_value);
602                                 if (!tnum_is_unknown(reg->var_off)) {
603                                         char tn_buf[48];
604
605                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
606                                         verbose(env, ",var_off=%s", tn_buf);
607                                 }
608                                 if (reg->s32_min_value != reg->smin_value &&
609                                     reg->s32_min_value != S32_MIN)
610                                         verbose(env, ",s32_min_value=%d",
611                                                 (int)(reg->s32_min_value));
612                                 if (reg->s32_max_value != reg->smax_value &&
613                                     reg->s32_max_value != S32_MAX)
614                                         verbose(env, ",s32_max_value=%d",
615                                                 (int)(reg->s32_max_value));
616                                 if (reg->u32_min_value != reg->umin_value &&
617                                     reg->u32_min_value != U32_MIN)
618                                         verbose(env, ",u32_min_value=%d",
619                                                 (int)(reg->u32_min_value));
620                                 if (reg->u32_max_value != reg->umax_value &&
621                                     reg->u32_max_value != U32_MAX)
622                                         verbose(env, ",u32_max_value=%d",
623                                                 (int)(reg->u32_max_value));
624                         }
625                         verbose(env, ")");
626                 }
627         }
628         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
629                 char types_buf[BPF_REG_SIZE + 1];
630                 bool valid = false;
631                 int j;
632
633                 for (j = 0; j < BPF_REG_SIZE; j++) {
634                         if (state->stack[i].slot_type[j] != STACK_INVALID)
635                                 valid = true;
636                         types_buf[j] = slot_type_char[
637                                         state->stack[i].slot_type[j]];
638                 }
639                 types_buf[BPF_REG_SIZE] = 0;
640                 if (!valid)
641                         continue;
642                 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
643                 print_liveness(env, state->stack[i].spilled_ptr.live);
644                 if (state->stack[i].slot_type[0] == STACK_SPILL) {
645                         reg = &state->stack[i].spilled_ptr;
646                         t = reg->type;
647                         verbose(env, "=%s", reg_type_str[t]);
648                         if (t == SCALAR_VALUE && reg->precise)
649                                 verbose(env, "P");
650                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
651                                 verbose(env, "%lld", reg->var_off.value + reg->off);
652                 } else {
653                         verbose(env, "=%s", types_buf);
654                 }
655         }
656         if (state->acquired_refs && state->refs[0].id) {
657                 verbose(env, " refs=%d", state->refs[0].id);
658                 for (i = 1; i < state->acquired_refs; i++)
659                         if (state->refs[i].id)
660                                 verbose(env, ",%d", state->refs[i].id);
661         }
662         verbose(env, "\n");
663 }
664
665 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE)                         \
666 static int copy_##NAME##_state(struct bpf_func_state *dst,              \
667                                const struct bpf_func_state *src)        \
668 {                                                                       \
669         if (!src->FIELD)                                                \
670                 return 0;                                               \
671         if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) {                    \
672                 /* internal bug, make state invalid to reject the program */ \
673                 memset(dst, 0, sizeof(*dst));                           \
674                 return -EFAULT;                                         \
675         }                                                               \
676         memcpy(dst->FIELD, src->FIELD,                                  \
677                sizeof(*src->FIELD) * (src->COUNT / SIZE));              \
678         return 0;                                                       \
679 }
680 /* copy_reference_state() */
681 COPY_STATE_FN(reference, acquired_refs, refs, 1)
682 /* copy_stack_state() */
683 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
684 #undef COPY_STATE_FN
685
686 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE)                      \
687 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
688                                   bool copy_old)                        \
689 {                                                                       \
690         u32 old_size = state->COUNT;                                    \
691         struct bpf_##NAME##_state *new_##FIELD;                         \
692         int slot = size / SIZE;                                         \
693                                                                         \
694         if (size <= old_size || !size) {                                \
695                 if (copy_old)                                           \
696                         return 0;                                       \
697                 state->COUNT = slot * SIZE;                             \
698                 if (!size && old_size) {                                \
699                         kfree(state->FIELD);                            \
700                         state->FIELD = NULL;                            \
701                 }                                                       \
702                 return 0;                                               \
703         }                                                               \
704         new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
705                                     GFP_KERNEL);                        \
706         if (!new_##FIELD)                                               \
707                 return -ENOMEM;                                         \
708         if (copy_old) {                                                 \
709                 if (state->FIELD)                                       \
710                         memcpy(new_##FIELD, state->FIELD,               \
711                                sizeof(*new_##FIELD) * (old_size / SIZE)); \
712                 memset(new_##FIELD + old_size / SIZE, 0,                \
713                        sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
714         }                                                               \
715         state->COUNT = slot * SIZE;                                     \
716         kfree(state->FIELD);                                            \
717         state->FIELD = new_##FIELD;                                     \
718         return 0;                                                       \
719 }
720 /* realloc_reference_state() */
721 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
722 /* realloc_stack_state() */
723 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
724 #undef REALLOC_STATE_FN
725
726 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
727  * make it consume minimal amount of memory. check_stack_write() access from
728  * the program calls into realloc_func_state() to grow the stack size.
729  * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
730  * which realloc_stack_state() copies over. It points to previous
731  * bpf_verifier_state which is never reallocated.
732  */
733 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
734                               int refs_size, bool copy_old)
735 {
736         int err = realloc_reference_state(state, refs_size, copy_old);
737         if (err)
738                 return err;
739         return realloc_stack_state(state, stack_size, copy_old);
740 }
741
742 /* Acquire a pointer id from the env and update the state->refs to include
743  * this new pointer reference.
744  * On success, returns a valid pointer id to associate with the register
745  * On failure, returns a negative errno.
746  */
747 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
748 {
749         struct bpf_func_state *state = cur_func(env);
750         int new_ofs = state->acquired_refs;
751         int id, err;
752
753         err = realloc_reference_state(state, state->acquired_refs + 1, true);
754         if (err)
755                 return err;
756         id = ++env->id_gen;
757         state->refs[new_ofs].id = id;
758         state->refs[new_ofs].insn_idx = insn_idx;
759
760         return id;
761 }
762
763 /* release function corresponding to acquire_reference_state(). Idempotent. */
764 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
765 {
766         int i, last_idx;
767
768         last_idx = state->acquired_refs - 1;
769         for (i = 0; i < state->acquired_refs; i++) {
770                 if (state->refs[i].id == ptr_id) {
771                         if (last_idx && i != last_idx)
772                                 memcpy(&state->refs[i], &state->refs[last_idx],
773                                        sizeof(*state->refs));
774                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
775                         state->acquired_refs--;
776                         return 0;
777                 }
778         }
779         return -EINVAL;
780 }
781
782 static int transfer_reference_state(struct bpf_func_state *dst,
783                                     struct bpf_func_state *src)
784 {
785         int err = realloc_reference_state(dst, src->acquired_refs, false);
786         if (err)
787                 return err;
788         err = copy_reference_state(dst, src);
789         if (err)
790                 return err;
791         return 0;
792 }
793
794 static void free_func_state(struct bpf_func_state *state)
795 {
796         if (!state)
797                 return;
798         kfree(state->refs);
799         kfree(state->stack);
800         kfree(state);
801 }
802
803 static void clear_jmp_history(struct bpf_verifier_state *state)
804 {
805         kfree(state->jmp_history);
806         state->jmp_history = NULL;
807         state->jmp_history_cnt = 0;
808 }
809
810 static void free_verifier_state(struct bpf_verifier_state *state,
811                                 bool free_self)
812 {
813         int i;
814
815         for (i = 0; i <= state->curframe; i++) {
816                 free_func_state(state->frame[i]);
817                 state->frame[i] = NULL;
818         }
819         clear_jmp_history(state);
820         if (free_self)
821                 kfree(state);
822 }
823
824 /* copy verifier state from src to dst growing dst stack space
825  * when necessary to accommodate larger src stack
826  */
827 static int copy_func_state(struct bpf_func_state *dst,
828                            const struct bpf_func_state *src)
829 {
830         int err;
831
832         err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
833                                  false);
834         if (err)
835                 return err;
836         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
837         err = copy_reference_state(dst, src);
838         if (err)
839                 return err;
840         return copy_stack_state(dst, src);
841 }
842
843 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
844                                const struct bpf_verifier_state *src)
845 {
846         struct bpf_func_state *dst;
847         u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
848         int i, err;
849
850         if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
851                 kfree(dst_state->jmp_history);
852                 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
853                 if (!dst_state->jmp_history)
854                         return -ENOMEM;
855         }
856         memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
857         dst_state->jmp_history_cnt = src->jmp_history_cnt;
858
859         /* if dst has more stack frames then src frame, free them */
860         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
861                 free_func_state(dst_state->frame[i]);
862                 dst_state->frame[i] = NULL;
863         }
864         dst_state->speculative = src->speculative;
865         dst_state->curframe = src->curframe;
866         dst_state->active_spin_lock = src->active_spin_lock;
867         dst_state->branches = src->branches;
868         dst_state->parent = src->parent;
869         dst_state->first_insn_idx = src->first_insn_idx;
870         dst_state->last_insn_idx = src->last_insn_idx;
871         for (i = 0; i <= src->curframe; i++) {
872                 dst = dst_state->frame[i];
873                 if (!dst) {
874                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
875                         if (!dst)
876                                 return -ENOMEM;
877                         dst_state->frame[i] = dst;
878                 }
879                 err = copy_func_state(dst, src->frame[i]);
880                 if (err)
881                         return err;
882         }
883         return 0;
884 }
885
886 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
887 {
888         while (st) {
889                 u32 br = --st->branches;
890
891                 /* WARN_ON(br > 1) technically makes sense here,
892                  * but see comment in push_stack(), hence:
893                  */
894                 WARN_ONCE((int)br < 0,
895                           "BUG update_branch_counts:branches_to_explore=%d\n",
896                           br);
897                 if (br)
898                         break;
899                 st = st->parent;
900         }
901 }
902
903 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
904                      int *insn_idx, bool pop_log)
905 {
906         struct bpf_verifier_state *cur = env->cur_state;
907         struct bpf_verifier_stack_elem *elem, *head = env->head;
908         int err;
909
910         if (env->head == NULL)
911                 return -ENOENT;
912
913         if (cur) {
914                 err = copy_verifier_state(cur, &head->st);
915                 if (err)
916                         return err;
917         }
918         if (pop_log)
919                 bpf_vlog_reset(&env->log, head->log_pos);
920         if (insn_idx)
921                 *insn_idx = head->insn_idx;
922         if (prev_insn_idx)
923                 *prev_insn_idx = head->prev_insn_idx;
924         elem = head->next;
925         free_verifier_state(&head->st, false);
926         kfree(head);
927         env->head = elem;
928         env->stack_size--;
929         return 0;
930 }
931
932 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
933                                              int insn_idx, int prev_insn_idx,
934                                              bool speculative)
935 {
936         struct bpf_verifier_state *cur = env->cur_state;
937         struct bpf_verifier_stack_elem *elem;
938         int err;
939
940         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
941         if (!elem)
942                 goto err;
943
944         elem->insn_idx = insn_idx;
945         elem->prev_insn_idx = prev_insn_idx;
946         elem->next = env->head;
947         elem->log_pos = env->log.len_used;
948         env->head = elem;
949         env->stack_size++;
950         err = copy_verifier_state(&elem->st, cur);
951         if (err)
952                 goto err;
953         elem->st.speculative |= speculative;
954         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
955                 verbose(env, "The sequence of %d jumps is too complex.\n",
956                         env->stack_size);
957                 goto err;
958         }
959         if (elem->st.parent) {
960                 ++elem->st.parent->branches;
961                 /* WARN_ON(branches > 2) technically makes sense here,
962                  * but
963                  * 1. speculative states will bump 'branches' for non-branch
964                  * instructions
965                  * 2. is_state_visited() heuristics may decide not to create
966                  * a new state for a sequence of branches and all such current
967                  * and cloned states will be pointing to a single parent state
968                  * which might have large 'branches' count.
969                  */
970         }
971         return &elem->st;
972 err:
973         free_verifier_state(env->cur_state, true);
974         env->cur_state = NULL;
975         /* pop all elements and return */
976         while (!pop_stack(env, NULL, NULL, false));
977         return NULL;
978 }
979
980 #define CALLER_SAVED_REGS 6
981 static const int caller_saved[CALLER_SAVED_REGS] = {
982         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
983 };
984
985 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
986                                 struct bpf_reg_state *reg);
987
988 /* Mark the unknown part of a register (variable offset or scalar value) as
989  * known to have the value @imm.
990  */
991 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
992 {
993         /* Clear id, off, and union(map_ptr, range) */
994         memset(((u8 *)reg) + sizeof(reg->type), 0,
995                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
996         reg->var_off = tnum_const(imm);
997         reg->smin_value = (s64)imm;
998         reg->smax_value = (s64)imm;
999         reg->umin_value = imm;
1000         reg->umax_value = imm;
1001
1002         reg->s32_min_value = (s32)imm;
1003         reg->s32_max_value = (s32)imm;
1004         reg->u32_min_value = (u32)imm;
1005         reg->u32_max_value = (u32)imm;
1006 }
1007
1008 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1009 {
1010         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1011         reg->s32_min_value = (s32)imm;
1012         reg->s32_max_value = (s32)imm;
1013         reg->u32_min_value = (u32)imm;
1014         reg->u32_max_value = (u32)imm;
1015 }
1016
1017 /* Mark the 'variable offset' part of a register as zero.  This should be
1018  * used only on registers holding a pointer type.
1019  */
1020 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1021 {
1022         __mark_reg_known(reg, 0);
1023 }
1024
1025 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1026 {
1027         __mark_reg_known(reg, 0);
1028         reg->type = SCALAR_VALUE;
1029 }
1030
1031 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1032                                 struct bpf_reg_state *regs, u32 regno)
1033 {
1034         if (WARN_ON(regno >= MAX_BPF_REG)) {
1035                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1036                 /* Something bad happened, let's kill all regs */
1037                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1038                         __mark_reg_not_init(env, regs + regno);
1039                 return;
1040         }
1041         __mark_reg_known_zero(regs + regno);
1042 }
1043
1044 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1045 {
1046         return type_is_pkt_pointer(reg->type);
1047 }
1048
1049 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1050 {
1051         return reg_is_pkt_pointer(reg) ||
1052                reg->type == PTR_TO_PACKET_END;
1053 }
1054
1055 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1056 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1057                                     enum bpf_reg_type which)
1058 {
1059         /* The register can already have a range from prior markings.
1060          * This is fine as long as it hasn't been advanced from its
1061          * origin.
1062          */
1063         return reg->type == which &&
1064                reg->id == 0 &&
1065                reg->off == 0 &&
1066                tnum_equals_const(reg->var_off, 0);
1067 }
1068
1069 /* Reset the min/max bounds of a register */
1070 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1071 {
1072         reg->smin_value = S64_MIN;
1073         reg->smax_value = S64_MAX;
1074         reg->umin_value = 0;
1075         reg->umax_value = U64_MAX;
1076
1077         reg->s32_min_value = S32_MIN;
1078         reg->s32_max_value = S32_MAX;
1079         reg->u32_min_value = 0;
1080         reg->u32_max_value = U32_MAX;
1081 }
1082
1083 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1084 {
1085         reg->smin_value = S64_MIN;
1086         reg->smax_value = S64_MAX;
1087         reg->umin_value = 0;
1088         reg->umax_value = U64_MAX;
1089 }
1090
1091 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1092 {
1093         reg->s32_min_value = S32_MIN;
1094         reg->s32_max_value = S32_MAX;
1095         reg->u32_min_value = 0;
1096         reg->u32_max_value = U32_MAX;
1097 }
1098
1099 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1100 {
1101         struct tnum var32_off = tnum_subreg(reg->var_off);
1102
1103         /* min signed is max(sign bit) | min(other bits) */
1104         reg->s32_min_value = max_t(s32, reg->s32_min_value,
1105                         var32_off.value | (var32_off.mask & S32_MIN));
1106         /* max signed is min(sign bit) | max(other bits) */
1107         reg->s32_max_value = min_t(s32, reg->s32_max_value,
1108                         var32_off.value | (var32_off.mask & S32_MAX));
1109         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1110         reg->u32_max_value = min(reg->u32_max_value,
1111                                  (u32)(var32_off.value | var32_off.mask));
1112 }
1113
1114 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1115 {
1116         /* min signed is max(sign bit) | min(other bits) */
1117         reg->smin_value = max_t(s64, reg->smin_value,
1118                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1119         /* max signed is min(sign bit) | max(other bits) */
1120         reg->smax_value = min_t(s64, reg->smax_value,
1121                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1122         reg->umin_value = max(reg->umin_value, reg->var_off.value);
1123         reg->umax_value = min(reg->umax_value,
1124                               reg->var_off.value | reg->var_off.mask);
1125 }
1126
1127 static void __update_reg_bounds(struct bpf_reg_state *reg)
1128 {
1129         __update_reg32_bounds(reg);
1130         __update_reg64_bounds(reg);
1131 }
1132
1133 /* Uses signed min/max values to inform unsigned, and vice-versa */
1134 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1135 {
1136         /* Learn sign from signed bounds.
1137          * If we cannot cross the sign boundary, then signed and unsigned bounds
1138          * are the same, so combine.  This works even in the negative case, e.g.
1139          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1140          */
1141         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1142                 reg->s32_min_value = reg->u32_min_value =
1143                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1144                 reg->s32_max_value = reg->u32_max_value =
1145                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1146                 return;
1147         }
1148         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1149          * boundary, so we must be careful.
1150          */
1151         if ((s32)reg->u32_max_value >= 0) {
1152                 /* Positive.  We can't learn anything from the smin, but smax
1153                  * is positive, hence safe.
1154                  */
1155                 reg->s32_min_value = reg->u32_min_value;
1156                 reg->s32_max_value = reg->u32_max_value =
1157                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
1158         } else if ((s32)reg->u32_min_value < 0) {
1159                 /* Negative.  We can't learn anything from the smax, but smin
1160                  * is negative, hence safe.
1161                  */
1162                 reg->s32_min_value = reg->u32_min_value =
1163                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
1164                 reg->s32_max_value = reg->u32_max_value;
1165         }
1166 }
1167
1168 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1169 {
1170         /* Learn sign from signed bounds.
1171          * If we cannot cross the sign boundary, then signed and unsigned bounds
1172          * are the same, so combine.  This works even in the negative case, e.g.
1173          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1174          */
1175         if (reg->smin_value >= 0 || reg->smax_value < 0) {
1176                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1177                                                           reg->umin_value);
1178                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1179                                                           reg->umax_value);
1180                 return;
1181         }
1182         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
1183          * boundary, so we must be careful.
1184          */
1185         if ((s64)reg->umax_value >= 0) {
1186                 /* Positive.  We can't learn anything from the smin, but smax
1187                  * is positive, hence safe.
1188                  */
1189                 reg->smin_value = reg->umin_value;
1190                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1191                                                           reg->umax_value);
1192         } else if ((s64)reg->umin_value < 0) {
1193                 /* Negative.  We can't learn anything from the smax, but smin
1194                  * is negative, hence safe.
1195                  */
1196                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1197                                                           reg->umin_value);
1198                 reg->smax_value = reg->umax_value;
1199         }
1200 }
1201
1202 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1203 {
1204         __reg32_deduce_bounds(reg);
1205         __reg64_deduce_bounds(reg);
1206 }
1207
1208 /* Attempts to improve var_off based on unsigned min/max information */
1209 static void __reg_bound_offset(struct bpf_reg_state *reg)
1210 {
1211         struct tnum var64_off = tnum_intersect(reg->var_off,
1212                                                tnum_range(reg->umin_value,
1213                                                           reg->umax_value));
1214         struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1215                                                 tnum_range(reg->u32_min_value,
1216                                                            reg->u32_max_value));
1217
1218         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1219 }
1220
1221 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1222 {
1223         reg->umin_value = reg->u32_min_value;
1224         reg->umax_value = reg->u32_max_value;
1225         /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1226          * but must be positive otherwise set to worse case bounds
1227          * and refine later from tnum.
1228          */
1229         if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
1230                 reg->smax_value = reg->s32_max_value;
1231         else
1232                 reg->smax_value = U32_MAX;
1233         if (reg->s32_min_value >= 0)
1234                 reg->smin_value = reg->s32_min_value;
1235         else
1236                 reg->smin_value = 0;
1237 }
1238
1239 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1240 {
1241         /* special case when 64-bit register has upper 32-bit register
1242          * zeroed. Typically happens after zext or <<32, >>32 sequence
1243          * allowing us to use 32-bit bounds directly,
1244          */
1245         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1246                 __reg_assign_32_into_64(reg);
1247         } else {
1248                 /* Otherwise the best we can do is push lower 32bit known and
1249                  * unknown bits into register (var_off set from jmp logic)
1250                  * then learn as much as possible from the 64-bit tnum
1251                  * known and unknown bits. The previous smin/smax bounds are
1252                  * invalid here because of jmp32 compare so mark them unknown
1253                  * so they do not impact tnum bounds calculation.
1254                  */
1255                 __mark_reg64_unbounded(reg);
1256                 __update_reg_bounds(reg);
1257         }
1258
1259         /* Intersecting with the old var_off might have improved our bounds
1260          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1261          * then new var_off is (0; 0x7f...fc) which improves our umax.
1262          */
1263         __reg_deduce_bounds(reg);
1264         __reg_bound_offset(reg);
1265         __update_reg_bounds(reg);
1266 }
1267
1268 static bool __reg64_bound_s32(s64 a)
1269 {
1270         if (a > S32_MIN && a < S32_MAX)
1271                 return true;
1272         return false;
1273 }
1274
1275 static bool __reg64_bound_u32(u64 a)
1276 {
1277         if (a > U32_MIN && a < U32_MAX)
1278                 return true;
1279         return false;
1280 }
1281
1282 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1283 {
1284         __mark_reg32_unbounded(reg);
1285
1286         if (__reg64_bound_s32(reg->smin_value))
1287                 reg->s32_min_value = (s32)reg->smin_value;
1288         if (__reg64_bound_s32(reg->smax_value))
1289                 reg->s32_max_value = (s32)reg->smax_value;
1290         if (__reg64_bound_u32(reg->umin_value))
1291                 reg->u32_min_value = (u32)reg->umin_value;
1292         if (__reg64_bound_u32(reg->umax_value))
1293                 reg->u32_max_value = (u32)reg->umax_value;
1294
1295         /* Intersecting with the old var_off might have improved our bounds
1296          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1297          * then new var_off is (0; 0x7f...fc) which improves our umax.
1298          */
1299         __reg_deduce_bounds(reg);
1300         __reg_bound_offset(reg);
1301         __update_reg_bounds(reg);
1302 }
1303
1304 /* Mark a register as having a completely unknown (scalar) value. */
1305 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1306                                struct bpf_reg_state *reg)
1307 {
1308         /*
1309          * Clear type, id, off, and union(map_ptr, range) and
1310          * padding between 'type' and union
1311          */
1312         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1313         reg->type = SCALAR_VALUE;
1314         reg->var_off = tnum_unknown;
1315         reg->frameno = 0;
1316         reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1317         __mark_reg_unbounded(reg);
1318 }
1319
1320 static void mark_reg_unknown(struct bpf_verifier_env *env,
1321                              struct bpf_reg_state *regs, u32 regno)
1322 {
1323         if (WARN_ON(regno >= MAX_BPF_REG)) {
1324                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1325                 /* Something bad happened, let's kill all regs except FP */
1326                 for (regno = 0; regno < BPF_REG_FP; regno++)
1327                         __mark_reg_not_init(env, regs + regno);
1328                 return;
1329         }
1330         __mark_reg_unknown(env, regs + regno);
1331 }
1332
1333 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1334                                 struct bpf_reg_state *reg)
1335 {
1336         __mark_reg_unknown(env, reg);
1337         reg->type = NOT_INIT;
1338 }
1339
1340 static void mark_reg_not_init(struct bpf_verifier_env *env,
1341                               struct bpf_reg_state *regs, u32 regno)
1342 {
1343         if (WARN_ON(regno >= MAX_BPF_REG)) {
1344                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1345                 /* Something bad happened, let's kill all regs except FP */
1346                 for (regno = 0; regno < BPF_REG_FP; regno++)
1347                         __mark_reg_not_init(env, regs + regno);
1348                 return;
1349         }
1350         __mark_reg_not_init(env, regs + regno);
1351 }
1352
1353 #define DEF_NOT_SUBREG  (0)
1354 static void init_reg_state(struct bpf_verifier_env *env,
1355                            struct bpf_func_state *state)
1356 {
1357         struct bpf_reg_state *regs = state->regs;
1358         int i;
1359
1360         for (i = 0; i < MAX_BPF_REG; i++) {
1361                 mark_reg_not_init(env, regs, i);
1362                 regs[i].live = REG_LIVE_NONE;
1363                 regs[i].parent = NULL;
1364                 regs[i].subreg_def = DEF_NOT_SUBREG;
1365         }
1366
1367         /* frame pointer */
1368         regs[BPF_REG_FP].type = PTR_TO_STACK;
1369         mark_reg_known_zero(env, regs, BPF_REG_FP);
1370         regs[BPF_REG_FP].frameno = state->frameno;
1371 }
1372
1373 #define BPF_MAIN_FUNC (-1)
1374 static void init_func_state(struct bpf_verifier_env *env,
1375                             struct bpf_func_state *state,
1376                             int callsite, int frameno, int subprogno)
1377 {
1378         state->callsite = callsite;
1379         state->frameno = frameno;
1380         state->subprogno = subprogno;
1381         init_reg_state(env, state);
1382 }
1383
1384 enum reg_arg_type {
1385         SRC_OP,         /* register is used as source operand */
1386         DST_OP,         /* register is used as destination operand */
1387         DST_OP_NO_MARK  /* same as above, check only, don't mark */
1388 };
1389
1390 static int cmp_subprogs(const void *a, const void *b)
1391 {
1392         return ((struct bpf_subprog_info *)a)->start -
1393                ((struct bpf_subprog_info *)b)->start;
1394 }
1395
1396 static int find_subprog(struct bpf_verifier_env *env, int off)
1397 {
1398         struct bpf_subprog_info *p;
1399
1400         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1401                     sizeof(env->subprog_info[0]), cmp_subprogs);
1402         if (!p)
1403                 return -ENOENT;
1404         return p - env->subprog_info;
1405
1406 }
1407
1408 static int add_subprog(struct bpf_verifier_env *env, int off)
1409 {
1410         int insn_cnt = env->prog->len;
1411         int ret;
1412
1413         if (off >= insn_cnt || off < 0) {
1414                 verbose(env, "call to invalid destination\n");
1415                 return -EINVAL;
1416         }
1417         ret = find_subprog(env, off);
1418         if (ret >= 0)
1419                 return 0;
1420         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1421                 verbose(env, "too many subprograms\n");
1422                 return -E2BIG;
1423         }
1424         env->subprog_info[env->subprog_cnt++].start = off;
1425         sort(env->subprog_info, env->subprog_cnt,
1426              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1427         return 0;
1428 }
1429
1430 static int check_subprogs(struct bpf_verifier_env *env)
1431 {
1432         int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
1433         struct bpf_subprog_info *subprog = env->subprog_info;
1434         struct bpf_insn *insn = env->prog->insnsi;
1435         int insn_cnt = env->prog->len;
1436
1437         /* Add entry function. */
1438         ret = add_subprog(env, 0);
1439         if (ret < 0)
1440                 return ret;
1441
1442         /* determine subprog starts. The end is one before the next starts */
1443         for (i = 0; i < insn_cnt; i++) {
1444                 if (insn[i].code != (BPF_JMP | BPF_CALL))
1445                         continue;
1446                 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1447                         continue;
1448                 if (!env->bpf_capable) {
1449                         verbose(env,
1450                                 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1451                         return -EPERM;
1452                 }
1453                 ret = add_subprog(env, i + insn[i].imm + 1);
1454                 if (ret < 0)
1455                         return ret;
1456         }
1457
1458         /* Add a fake 'exit' subprog which could simplify subprog iteration
1459          * logic. 'subprog_cnt' should not be increased.
1460          */
1461         subprog[env->subprog_cnt].start = insn_cnt;
1462
1463         if (env->log.level & BPF_LOG_LEVEL2)
1464                 for (i = 0; i < env->subprog_cnt; i++)
1465                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
1466
1467         /* now check that all jumps are within the same subprog */
1468         subprog_start = subprog[cur_subprog].start;
1469         subprog_end = subprog[cur_subprog + 1].start;
1470         for (i = 0; i < insn_cnt; i++) {
1471                 u8 code = insn[i].code;
1472
1473                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1474                         goto next;
1475                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1476                         goto next;
1477                 off = i + insn[i].off + 1;
1478                 if (off < subprog_start || off >= subprog_end) {
1479                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
1480                         return -EINVAL;
1481                 }
1482 next:
1483                 if (i == subprog_end - 1) {
1484                         /* to avoid fall-through from one subprog into another
1485                          * the last insn of the subprog should be either exit
1486                          * or unconditional jump back
1487                          */
1488                         if (code != (BPF_JMP | BPF_EXIT) &&
1489                             code != (BPF_JMP | BPF_JA)) {
1490                                 verbose(env, "last insn is not an exit or jmp\n");
1491                                 return -EINVAL;
1492                         }
1493                         subprog_start = subprog_end;
1494                         cur_subprog++;
1495                         if (cur_subprog < env->subprog_cnt)
1496                                 subprog_end = subprog[cur_subprog + 1].start;
1497                 }
1498         }
1499         return 0;
1500 }
1501
1502 /* Parentage chain of this register (or stack slot) should take care of all
1503  * issues like callee-saved registers, stack slot allocation time, etc.
1504  */
1505 static int mark_reg_read(struct bpf_verifier_env *env,
1506                          const struct bpf_reg_state *state,
1507                          struct bpf_reg_state *parent, u8 flag)
1508 {
1509         bool writes = parent == state->parent; /* Observe write marks */
1510         int cnt = 0;
1511
1512         while (parent) {
1513                 /* if read wasn't screened by an earlier write ... */
1514                 if (writes && state->live & REG_LIVE_WRITTEN)
1515                         break;
1516                 if (parent->live & REG_LIVE_DONE) {
1517                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1518                                 reg_type_str[parent->type],
1519                                 parent->var_off.value, parent->off);
1520                         return -EFAULT;
1521                 }
1522                 /* The first condition is more likely to be true than the
1523                  * second, checked it first.
1524                  */
1525                 if ((parent->live & REG_LIVE_READ) == flag ||
1526                     parent->live & REG_LIVE_READ64)
1527                         /* The parentage chain never changes and
1528                          * this parent was already marked as LIVE_READ.
1529                          * There is no need to keep walking the chain again and
1530                          * keep re-marking all parents as LIVE_READ.
1531                          * This case happens when the same register is read
1532                          * multiple times without writes into it in-between.
1533                          * Also, if parent has the stronger REG_LIVE_READ64 set,
1534                          * then no need to set the weak REG_LIVE_READ32.
1535                          */
1536                         break;
1537                 /* ... then we depend on parent's value */
1538                 parent->live |= flag;
1539                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1540                 if (flag == REG_LIVE_READ64)
1541                         parent->live &= ~REG_LIVE_READ32;
1542                 state = parent;
1543                 parent = state->parent;
1544                 writes = true;
1545                 cnt++;
1546         }
1547
1548         if (env->longest_mark_read_walk < cnt)
1549                 env->longest_mark_read_walk = cnt;
1550         return 0;
1551 }
1552
1553 /* This function is supposed to be used by the following 32-bit optimization
1554  * code only. It returns TRUE if the source or destination register operates
1555  * on 64-bit, otherwise return FALSE.
1556  */
1557 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1558                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1559 {
1560         u8 code, class, op;
1561
1562         code = insn->code;
1563         class = BPF_CLASS(code);
1564         op = BPF_OP(code);
1565         if (class == BPF_JMP) {
1566                 /* BPF_EXIT for "main" will reach here. Return TRUE
1567                  * conservatively.
1568                  */
1569                 if (op == BPF_EXIT)
1570                         return true;
1571                 if (op == BPF_CALL) {
1572                         /* BPF to BPF call will reach here because of marking
1573                          * caller saved clobber with DST_OP_NO_MARK for which we
1574                          * don't care the register def because they are anyway
1575                          * marked as NOT_INIT already.
1576                          */
1577                         if (insn->src_reg == BPF_PSEUDO_CALL)
1578                                 return false;
1579                         /* Helper call will reach here because of arg type
1580                          * check, conservatively return TRUE.
1581                          */
1582                         if (t == SRC_OP)
1583                                 return true;
1584
1585                         return false;
1586                 }
1587         }
1588
1589         if (class == BPF_ALU64 || class == BPF_JMP ||
1590             /* BPF_END always use BPF_ALU class. */
1591             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1592                 return true;
1593
1594         if (class == BPF_ALU || class == BPF_JMP32)
1595                 return false;
1596
1597         if (class == BPF_LDX) {
1598                 if (t != SRC_OP)
1599                         return BPF_SIZE(code) == BPF_DW;
1600                 /* LDX source must be ptr. */
1601                 return true;
1602         }
1603
1604         if (class == BPF_STX) {
1605                 if (reg->type != SCALAR_VALUE)
1606                         return true;
1607                 return BPF_SIZE(code) == BPF_DW;
1608         }
1609
1610         if (class == BPF_LD) {
1611                 u8 mode = BPF_MODE(code);
1612
1613                 /* LD_IMM64 */
1614                 if (mode == BPF_IMM)
1615                         return true;
1616
1617                 /* Both LD_IND and LD_ABS return 32-bit data. */
1618                 if (t != SRC_OP)
1619                         return  false;
1620
1621                 /* Implicit ctx ptr. */
1622                 if (regno == BPF_REG_6)
1623                         return true;
1624
1625                 /* Explicit source could be any width. */
1626                 return true;
1627         }
1628
1629         if (class == BPF_ST)
1630                 /* The only source register for BPF_ST is a ptr. */
1631                 return true;
1632
1633         /* Conservatively return true at default. */
1634         return true;
1635 }
1636
1637 /* Return TRUE if INSN doesn't have explicit value define. */
1638 static bool insn_no_def(struct bpf_insn *insn)
1639 {
1640         u8 class = BPF_CLASS(insn->code);
1641
1642         return (class == BPF_JMP || class == BPF_JMP32 ||
1643                 class == BPF_STX || class == BPF_ST);
1644 }
1645
1646 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1647 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1648 {
1649         if (insn_no_def(insn))
1650                 return false;
1651
1652         return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1653 }
1654
1655 static void mark_insn_zext(struct bpf_verifier_env *env,
1656                            struct bpf_reg_state *reg)
1657 {
1658         s32 def_idx = reg->subreg_def;
1659
1660         if (def_idx == DEF_NOT_SUBREG)
1661                 return;
1662
1663         env->insn_aux_data[def_idx - 1].zext_dst = true;
1664         /* The dst will be zero extended, so won't be sub-register anymore. */
1665         reg->subreg_def = DEF_NOT_SUBREG;
1666 }
1667
1668 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1669                          enum reg_arg_type t)
1670 {
1671         struct bpf_verifier_state *vstate = env->cur_state;
1672         struct bpf_func_state *state = vstate->frame[vstate->curframe];
1673         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
1674         struct bpf_reg_state *reg, *regs = state->regs;
1675         bool rw64;
1676
1677         if (regno >= MAX_BPF_REG) {
1678                 verbose(env, "R%d is invalid\n", regno);
1679                 return -EINVAL;
1680         }
1681
1682         reg = &regs[regno];
1683         rw64 = is_reg64(env, insn, regno, reg, t);
1684         if (t == SRC_OP) {
1685                 /* check whether register used as source operand can be read */
1686                 if (reg->type == NOT_INIT) {
1687                         verbose(env, "R%d !read_ok\n", regno);
1688                         return -EACCES;
1689                 }
1690                 /* We don't need to worry about FP liveness because it's read-only */
1691                 if (regno == BPF_REG_FP)
1692                         return 0;
1693
1694                 if (rw64)
1695                         mark_insn_zext(env, reg);
1696
1697                 return mark_reg_read(env, reg, reg->parent,
1698                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
1699         } else {
1700                 /* check whether register used as dest operand can be written to */
1701                 if (regno == BPF_REG_FP) {
1702                         verbose(env, "frame pointer is read only\n");
1703                         return -EACCES;
1704                 }
1705                 reg->live |= REG_LIVE_WRITTEN;
1706                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
1707                 if (t == DST_OP)
1708                         mark_reg_unknown(env, regs, regno);
1709         }
1710         return 0;
1711 }
1712
1713 /* for any branch, call, exit record the history of jmps in the given state */
1714 static int push_jmp_history(struct bpf_verifier_env *env,
1715                             struct bpf_verifier_state *cur)
1716 {
1717         u32 cnt = cur->jmp_history_cnt;
1718         struct bpf_idx_pair *p;
1719
1720         cnt++;
1721         p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1722         if (!p)
1723                 return -ENOMEM;
1724         p[cnt - 1].idx = env->insn_idx;
1725         p[cnt - 1].prev_idx = env->prev_insn_idx;
1726         cur->jmp_history = p;
1727         cur->jmp_history_cnt = cnt;
1728         return 0;
1729 }
1730
1731 /* Backtrack one insn at a time. If idx is not at the top of recorded
1732  * history then previous instruction came from straight line execution.
1733  */
1734 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1735                              u32 *history)
1736 {
1737         u32 cnt = *history;
1738
1739         if (cnt && st->jmp_history[cnt - 1].idx == i) {
1740                 i = st->jmp_history[cnt - 1].prev_idx;
1741                 (*history)--;
1742         } else {
1743                 i--;
1744         }
1745         return i;
1746 }
1747
1748 /* For given verifier state backtrack_insn() is called from the last insn to
1749  * the first insn. Its purpose is to compute a bitmask of registers and
1750  * stack slots that needs precision in the parent verifier state.
1751  */
1752 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1753                           u32 *reg_mask, u64 *stack_mask)
1754 {
1755         const struct bpf_insn_cbs cbs = {
1756                 .cb_print       = verbose,
1757                 .private_data   = env,
1758         };
1759         struct bpf_insn *insn = env->prog->insnsi + idx;
1760         u8 class = BPF_CLASS(insn->code);
1761         u8 opcode = BPF_OP(insn->code);
1762         u8 mode = BPF_MODE(insn->code);
1763         u32 dreg = 1u << insn->dst_reg;
1764         u32 sreg = 1u << insn->src_reg;
1765         u32 spi;
1766
1767         if (insn->code == 0)
1768                 return 0;
1769         if (env->log.level & BPF_LOG_LEVEL) {
1770                 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1771                 verbose(env, "%d: ", idx);
1772                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1773         }
1774
1775         if (class == BPF_ALU || class == BPF_ALU64) {
1776                 if (!(*reg_mask & dreg))
1777                         return 0;
1778                 if (opcode == BPF_MOV) {
1779                         if (BPF_SRC(insn->code) == BPF_X) {
1780                                 /* dreg = sreg
1781                                  * dreg needs precision after this insn
1782                                  * sreg needs precision before this insn
1783                                  */
1784                                 *reg_mask &= ~dreg;
1785                                 *reg_mask |= sreg;
1786                         } else {
1787                                 /* dreg = K
1788                                  * dreg needs precision after this insn.
1789                                  * Corresponding register is already marked
1790                                  * as precise=true in this verifier state.
1791                                  * No further markings in parent are necessary
1792                                  */
1793                                 *reg_mask &= ~dreg;
1794                         }
1795                 } else {
1796                         if (BPF_SRC(insn->code) == BPF_X) {
1797                                 /* dreg += sreg
1798                                  * both dreg and sreg need precision
1799                                  * before this insn
1800                                  */
1801                                 *reg_mask |= sreg;
1802                         } /* else dreg += K
1803                            * dreg still needs precision before this insn
1804                            */
1805                 }
1806         } else if (class == BPF_LDX) {
1807                 if (!(*reg_mask & dreg))
1808                         return 0;
1809                 *reg_mask &= ~dreg;
1810
1811                 /* scalars can only be spilled into stack w/o losing precision.
1812                  * Load from any other memory can be zero extended.
1813                  * The desire to keep that precision is already indicated
1814                  * by 'precise' mark in corresponding register of this state.
1815                  * No further tracking necessary.
1816                  */
1817                 if (insn->src_reg != BPF_REG_FP)
1818                         return 0;
1819                 if (BPF_SIZE(insn->code) != BPF_DW)
1820                         return 0;
1821
1822                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1823                  * that [fp - off] slot contains scalar that needs to be
1824                  * tracked with precision
1825                  */
1826                 spi = (-insn->off - 1) / BPF_REG_SIZE;
1827                 if (spi >= 64) {
1828                         verbose(env, "BUG spi %d\n", spi);
1829                         WARN_ONCE(1, "verifier backtracking bug");
1830                         return -EFAULT;
1831                 }
1832                 *stack_mask |= 1ull << spi;
1833         } else if (class == BPF_STX || class == BPF_ST) {
1834                 if (*reg_mask & dreg)
1835                         /* stx & st shouldn't be using _scalar_ dst_reg
1836                          * to access memory. It means backtracking
1837                          * encountered a case of pointer subtraction.
1838                          */
1839                         return -ENOTSUPP;
1840                 /* scalars can only be spilled into stack */
1841                 if (insn->dst_reg != BPF_REG_FP)
1842                         return 0;
1843                 if (BPF_SIZE(insn->code) != BPF_DW)
1844                         return 0;
1845                 spi = (-insn->off - 1) / BPF_REG_SIZE;
1846                 if (spi >= 64) {
1847                         verbose(env, "BUG spi %d\n", spi);
1848                         WARN_ONCE(1, "verifier backtracking bug");
1849                         return -EFAULT;
1850                 }
1851                 if (!(*stack_mask & (1ull << spi)))
1852                         return 0;
1853                 *stack_mask &= ~(1ull << spi);
1854                 if (class == BPF_STX)
1855                         *reg_mask |= sreg;
1856         } else if (class == BPF_JMP || class == BPF_JMP32) {
1857                 if (opcode == BPF_CALL) {
1858                         if (insn->src_reg == BPF_PSEUDO_CALL)
1859                                 return -ENOTSUPP;
1860                         /* regular helper call sets R0 */
1861                         *reg_mask &= ~1;
1862                         if (*reg_mask & 0x3f) {
1863                                 /* if backtracing was looking for registers R1-R5
1864                                  * they should have been found already.
1865                                  */
1866                                 verbose(env, "BUG regs %x\n", *reg_mask);
1867                                 WARN_ONCE(1, "verifier backtracking bug");
1868                                 return -EFAULT;
1869                         }
1870                 } else if (opcode == BPF_EXIT) {
1871                         return -ENOTSUPP;
1872                 }
1873         } else if (class == BPF_LD) {
1874                 if (!(*reg_mask & dreg))
1875                         return 0;
1876                 *reg_mask &= ~dreg;
1877                 /* It's ld_imm64 or ld_abs or ld_ind.
1878                  * For ld_imm64 no further tracking of precision
1879                  * into parent is necessary
1880                  */
1881                 if (mode == BPF_IND || mode == BPF_ABS)
1882                         /* to be analyzed */
1883                         return -ENOTSUPP;
1884         }
1885         return 0;
1886 }
1887
1888 /* the scalar precision tracking algorithm:
1889  * . at the start all registers have precise=false.
1890  * . scalar ranges are tracked as normal through alu and jmp insns.
1891  * . once precise value of the scalar register is used in:
1892  *   .  ptr + scalar alu
1893  *   . if (scalar cond K|scalar)
1894  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
1895  *   backtrack through the verifier states and mark all registers and
1896  *   stack slots with spilled constants that these scalar regisers
1897  *   should be precise.
1898  * . during state pruning two registers (or spilled stack slots)
1899  *   are equivalent if both are not precise.
1900  *
1901  * Note the verifier cannot simply walk register parentage chain,
1902  * since many different registers and stack slots could have been
1903  * used to compute single precise scalar.
1904  *
1905  * The approach of starting with precise=true for all registers and then
1906  * backtrack to mark a register as not precise when the verifier detects
1907  * that program doesn't care about specific value (e.g., when helper
1908  * takes register as ARG_ANYTHING parameter) is not safe.
1909  *
1910  * It's ok to walk single parentage chain of the verifier states.
1911  * It's possible that this backtracking will go all the way till 1st insn.
1912  * All other branches will be explored for needing precision later.
1913  *
1914  * The backtracking needs to deal with cases like:
1915  *   R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0)
1916  * r9 -= r8
1917  * r5 = r9
1918  * if r5 > 0x79f goto pc+7
1919  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1920  * r5 += 1
1921  * ...
1922  * call bpf_perf_event_output#25
1923  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1924  *
1925  * and this case:
1926  * r6 = 1
1927  * call foo // uses callee's r6 inside to compute r0
1928  * r0 += r6
1929  * if r0 == 0 goto
1930  *
1931  * to track above reg_mask/stack_mask needs to be independent for each frame.
1932  *
1933  * Also if parent's curframe > frame where backtracking started,
1934  * the verifier need to mark registers in both frames, otherwise callees
1935  * may incorrectly prune callers. This is similar to
1936  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1937  *
1938  * For now backtracking falls back into conservative marking.
1939  */
1940 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
1941                                      struct bpf_verifier_state *st)
1942 {
1943         struct bpf_func_state *func;
1944         struct bpf_reg_state *reg;
1945         int i, j;
1946
1947         /* big hammer: mark all scalars precise in this path.
1948          * pop_stack may still get !precise scalars.
1949          */
1950         for (; st; st = st->parent)
1951                 for (i = 0; i <= st->curframe; i++) {
1952                         func = st->frame[i];
1953                         for (j = 0; j < BPF_REG_FP; j++) {
1954                                 reg = &func->regs[j];
1955                                 if (reg->type != SCALAR_VALUE)
1956                                         continue;
1957                                 reg->precise = true;
1958                         }
1959                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
1960                                 if (func->stack[j].slot_type[0] != STACK_SPILL)
1961                                         continue;
1962                                 reg = &func->stack[j].spilled_ptr;
1963                                 if (reg->type != SCALAR_VALUE)
1964                                         continue;
1965                                 reg->precise = true;
1966                         }
1967                 }
1968 }
1969
1970 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
1971                                   int spi)
1972 {
1973         struct bpf_verifier_state *st = env->cur_state;
1974         int first_idx = st->first_insn_idx;
1975         int last_idx = env->insn_idx;
1976         struct bpf_func_state *func;
1977         struct bpf_reg_state *reg;
1978         u32 reg_mask = regno >= 0 ? 1u << regno : 0;
1979         u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
1980         bool skip_first = true;
1981         bool new_marks = false;
1982         int i, err;
1983
1984         if (!env->bpf_capable)
1985                 return 0;
1986
1987         func = st->frame[st->curframe];
1988         if (regno >= 0) {
1989                 reg = &func->regs[regno];
1990                 if (reg->type != SCALAR_VALUE) {
1991                         WARN_ONCE(1, "backtracing misuse");
1992                         return -EFAULT;
1993                 }
1994                 if (!reg->precise)
1995                         new_marks = true;
1996                 else
1997                         reg_mask = 0;
1998                 reg->precise = true;
1999         }
2000
2001         while (spi >= 0) {
2002                 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2003                         stack_mask = 0;
2004                         break;
2005                 }
2006                 reg = &func->stack[spi].spilled_ptr;
2007                 if (reg->type != SCALAR_VALUE) {
2008                         stack_mask = 0;
2009                         break;
2010                 }
2011                 if (!reg->precise)
2012                         new_marks = true;
2013                 else
2014                         stack_mask = 0;
2015                 reg->precise = true;
2016                 break;
2017         }
2018
2019         if (!new_marks)
2020                 return 0;
2021         if (!reg_mask && !stack_mask)
2022                 return 0;
2023         for (;;) {
2024                 DECLARE_BITMAP(mask, 64);
2025                 u32 history = st->jmp_history_cnt;
2026
2027                 if (env->log.level & BPF_LOG_LEVEL)
2028                         verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2029                 for (i = last_idx;;) {
2030                         if (skip_first) {
2031                                 err = 0;
2032                                 skip_first = false;
2033                         } else {
2034                                 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2035                         }
2036                         if (err == -ENOTSUPP) {
2037                                 mark_all_scalars_precise(env, st);
2038                                 return 0;
2039                         } else if (err) {
2040                                 return err;
2041                         }
2042                         if (!reg_mask && !stack_mask)
2043                                 /* Found assignment(s) into tracked register in this state.
2044                                  * Since this state is already marked, just return.
2045                                  * Nothing to be tracked further in the parent state.
2046                                  */
2047                                 return 0;
2048                         if (i == first_idx)
2049                                 break;
2050                         i = get_prev_insn_idx(st, i, &history);
2051                         if (i >= env->prog->len) {
2052                                 /* This can happen if backtracking reached insn 0
2053                                  * and there are still reg_mask or stack_mask
2054                                  * to backtrack.
2055                                  * It means the backtracking missed the spot where
2056                                  * particular register was initialized with a constant.
2057                                  */
2058                                 verbose(env, "BUG backtracking idx %d\n", i);
2059                                 WARN_ONCE(1, "verifier backtracking bug");
2060                                 return -EFAULT;
2061                         }
2062                 }
2063                 st = st->parent;
2064                 if (!st)
2065                         break;
2066
2067                 new_marks = false;
2068                 func = st->frame[st->curframe];
2069                 bitmap_from_u64(mask, reg_mask);
2070                 for_each_set_bit(i, mask, 32) {
2071                         reg = &func->regs[i];
2072                         if (reg->type != SCALAR_VALUE) {
2073                                 reg_mask &= ~(1u << i);
2074                                 continue;
2075                         }
2076                         if (!reg->precise)
2077                                 new_marks = true;
2078                         reg->precise = true;
2079                 }
2080
2081                 bitmap_from_u64(mask, stack_mask);
2082                 for_each_set_bit(i, mask, 64) {
2083                         if (i >= func->allocated_stack / BPF_REG_SIZE) {
2084                                 /* the sequence of instructions:
2085                                  * 2: (bf) r3 = r10
2086                                  * 3: (7b) *(u64 *)(r3 -8) = r0
2087                                  * 4: (79) r4 = *(u64 *)(r10 -8)
2088                                  * doesn't contain jmps. It's backtracked
2089                                  * as a single block.
2090                                  * During backtracking insn 3 is not recognized as
2091                                  * stack access, so at the end of backtracking
2092                                  * stack slot fp-8 is still marked in stack_mask.
2093                                  * However the parent state may not have accessed
2094                                  * fp-8 and it's "unallocated" stack space.
2095                                  * In such case fallback to conservative.
2096                                  */
2097                                 mark_all_scalars_precise(env, st);
2098                                 return 0;
2099                         }
2100
2101                         if (func->stack[i].slot_type[0] != STACK_SPILL) {
2102                                 stack_mask &= ~(1ull << i);
2103                                 continue;
2104                         }
2105                         reg = &func->stack[i].spilled_ptr;
2106                         if (reg->type != SCALAR_VALUE) {
2107                                 stack_mask &= ~(1ull << i);
2108                                 continue;
2109                         }
2110                         if (!reg->precise)
2111                                 new_marks = true;
2112                         reg->precise = true;
2113                 }
2114                 if (env->log.level & BPF_LOG_LEVEL) {
2115                         print_verifier_state(env, func);
2116                         verbose(env, "parent %s regs=%x stack=%llx marks\n",
2117                                 new_marks ? "didn't have" : "already had",
2118                                 reg_mask, stack_mask);
2119                 }
2120
2121                 if (!reg_mask && !stack_mask)
2122                         break;
2123                 if (!new_marks)
2124                         break;
2125
2126                 last_idx = st->last_insn_idx;
2127                 first_idx = st->first_insn_idx;
2128         }
2129         return 0;
2130 }
2131
2132 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2133 {
2134         return __mark_chain_precision(env, regno, -1);
2135 }
2136
2137 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2138 {
2139         return __mark_chain_precision(env, -1, spi);
2140 }
2141
2142 static bool is_spillable_regtype(enum bpf_reg_type type)
2143 {
2144         switch (type) {
2145         case PTR_TO_MAP_VALUE:
2146         case PTR_TO_MAP_VALUE_OR_NULL:
2147         case PTR_TO_STACK:
2148         case PTR_TO_CTX:
2149         case PTR_TO_PACKET:
2150         case PTR_TO_PACKET_META:
2151         case PTR_TO_PACKET_END:
2152         case PTR_TO_FLOW_KEYS:
2153         case CONST_PTR_TO_MAP:
2154         case PTR_TO_SOCKET:
2155         case PTR_TO_SOCKET_OR_NULL:
2156         case PTR_TO_SOCK_COMMON:
2157         case PTR_TO_SOCK_COMMON_OR_NULL:
2158         case PTR_TO_TCP_SOCK:
2159         case PTR_TO_TCP_SOCK_OR_NULL:
2160         case PTR_TO_XDP_SOCK:
2161         case PTR_TO_BTF_ID:
2162         case PTR_TO_BTF_ID_OR_NULL:
2163                 return true;
2164         default:
2165                 return false;
2166         }
2167 }
2168
2169 /* Does this register contain a constant zero? */
2170 static bool register_is_null(struct bpf_reg_state *reg)
2171 {
2172         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2173 }
2174
2175 static bool register_is_const(struct bpf_reg_state *reg)
2176 {
2177         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2178 }
2179
2180 static bool __is_pointer_value(bool allow_ptr_leaks,
2181                                const struct bpf_reg_state *reg)
2182 {
2183         if (allow_ptr_leaks)
2184                 return false;
2185
2186         return reg->type != SCALAR_VALUE;
2187 }
2188
2189 static void save_register_state(struct bpf_func_state *state,
2190                                 int spi, struct bpf_reg_state *reg)
2191 {
2192         int i;
2193
2194         state->stack[spi].spilled_ptr = *reg;
2195         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2196
2197         for (i = 0; i < BPF_REG_SIZE; i++)
2198                 state->stack[spi].slot_type[i] = STACK_SPILL;
2199 }
2200
2201 /* check_stack_read/write functions track spill/fill of registers,
2202  * stack boundary and alignment are checked in check_mem_access()
2203  */
2204 static int check_stack_write(struct bpf_verifier_env *env,
2205                              struct bpf_func_state *state, /* func where register points to */
2206                              int off, int size, int value_regno, int insn_idx)
2207 {
2208         struct bpf_func_state *cur; /* state of the current function */
2209         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2210         u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2211         struct bpf_reg_state *reg = NULL;
2212
2213         err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
2214                                  state->acquired_refs, true);
2215         if (err)
2216                 return err;
2217         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2218          * so it's aligned access and [off, off + size) are within stack limits
2219          */
2220         if (!env->allow_ptr_leaks &&
2221             state->stack[spi].slot_type[0] == STACK_SPILL &&
2222             size != BPF_REG_SIZE) {
2223                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2224                 return -EACCES;
2225         }
2226
2227         cur = env->cur_state->frame[env->cur_state->curframe];
2228         if (value_regno >= 0)
2229                 reg = &cur->regs[value_regno];
2230
2231         if (reg && size == BPF_REG_SIZE && register_is_const(reg) &&
2232             !register_is_null(reg) && env->bpf_capable) {
2233                 if (dst_reg != BPF_REG_FP) {
2234                         /* The backtracking logic can only recognize explicit
2235                          * stack slot address like [fp - 8]. Other spill of
2236                          * scalar via different register has to be conervative.
2237                          * Backtrack from here and mark all registers as precise
2238                          * that contributed into 'reg' being a constant.
2239                          */
2240                         err = mark_chain_precision(env, value_regno);
2241                         if (err)
2242                                 return err;
2243                 }
2244                 save_register_state(state, spi, reg);
2245         } else if (reg && is_spillable_regtype(reg->type)) {
2246                 /* register containing pointer is being spilled into stack */
2247                 if (size != BPF_REG_SIZE) {
2248                         verbose_linfo(env, insn_idx, "; ");
2249                         verbose(env, "invalid size of register spill\n");
2250                         return -EACCES;
2251                 }
2252
2253                 if (state != cur && reg->type == PTR_TO_STACK) {
2254                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2255                         return -EINVAL;
2256                 }
2257
2258                 if (!env->bypass_spec_v4) {
2259                         bool sanitize = false;
2260
2261                         if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2262                             register_is_const(&state->stack[spi].spilled_ptr))
2263                                 sanitize = true;
2264                         for (i = 0; i < BPF_REG_SIZE; i++)
2265                                 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2266                                         sanitize = true;
2267                                         break;
2268                                 }
2269                         if (sanitize) {
2270                                 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2271                                 int soff = (-spi - 1) * BPF_REG_SIZE;
2272
2273                                 /* detected reuse of integer stack slot with a pointer
2274                                  * which means either llvm is reusing stack slot or
2275                                  * an attacker is trying to exploit CVE-2018-3639
2276                                  * (speculative store bypass)
2277                                  * Have to sanitize that slot with preemptive
2278                                  * store of zero.
2279                                  */
2280                                 if (*poff && *poff != soff) {
2281                                         /* disallow programs where single insn stores
2282                                          * into two different stack slots, since verifier
2283                                          * cannot sanitize them
2284                                          */
2285                                         verbose(env,
2286                                                 "insn %d cannot access two stack slots fp%d and fp%d",
2287                                                 insn_idx, *poff, soff);
2288                                         return -EINVAL;
2289                                 }
2290                                 *poff = soff;
2291                         }
2292                 }
2293                 save_register_state(state, spi, reg);
2294         } else {
2295                 u8 type = STACK_MISC;
2296
2297                 /* regular write of data into stack destroys any spilled ptr */
2298                 state->stack[spi].spilled_ptr.type = NOT_INIT;
2299                 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2300                 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2301                         for (i = 0; i < BPF_REG_SIZE; i++)
2302                                 state->stack[spi].slot_type[i] = STACK_MISC;
2303
2304                 /* only mark the slot as written if all 8 bytes were written
2305                  * otherwise read propagation may incorrectly stop too soon
2306                  * when stack slots are partially written.
2307                  * This heuristic means that read propagation will be
2308                  * conservative, since it will add reg_live_read marks
2309                  * to stack slots all the way to first state when programs
2310                  * writes+reads less than 8 bytes
2311                  */
2312                 if (size == BPF_REG_SIZE)
2313                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2314
2315                 /* when we zero initialize stack slots mark them as such */
2316                 if (reg && register_is_null(reg)) {
2317                         /* backtracking doesn't work for STACK_ZERO yet. */
2318                         err = mark_chain_precision(env, value_regno);
2319                         if (err)
2320                                 return err;
2321                         type = STACK_ZERO;
2322                 }
2323
2324                 /* Mark slots affected by this stack write. */
2325                 for (i = 0; i < size; i++)
2326                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2327                                 type;
2328         }
2329         return 0;
2330 }
2331
2332 static int check_stack_read(struct bpf_verifier_env *env,
2333                             struct bpf_func_state *reg_state /* func where register points to */,
2334                             int off, int size, int value_regno)
2335 {
2336         struct bpf_verifier_state *vstate = env->cur_state;
2337         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2338         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2339         struct bpf_reg_state *reg;
2340         u8 *stype;
2341
2342         if (reg_state->allocated_stack <= slot) {
2343                 verbose(env, "invalid read from stack off %d+0 size %d\n",
2344                         off, size);
2345                 return -EACCES;
2346         }
2347         stype = reg_state->stack[spi].slot_type;
2348         reg = &reg_state->stack[spi].spilled_ptr;
2349
2350         if (stype[0] == STACK_SPILL) {
2351                 if (size != BPF_REG_SIZE) {
2352                         if (reg->type != SCALAR_VALUE) {
2353                                 verbose_linfo(env, env->insn_idx, "; ");
2354                                 verbose(env, "invalid size of register fill\n");
2355                                 return -EACCES;
2356                         }
2357                         if (value_regno >= 0) {
2358                                 mark_reg_unknown(env, state->regs, value_regno);
2359                                 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2360                         }
2361                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2362                         return 0;
2363                 }
2364                 for (i = 1; i < BPF_REG_SIZE; i++) {
2365                         if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2366                                 verbose(env, "corrupted spill memory\n");
2367                                 return -EACCES;
2368                         }
2369                 }
2370
2371                 if (value_regno >= 0) {
2372                         /* restore register state from stack */
2373                         state->regs[value_regno] = *reg;
2374                         /* mark reg as written since spilled pointer state likely
2375                          * has its liveness marks cleared by is_state_visited()
2376                          * which resets stack/reg liveness for state transitions
2377                          */
2378                         state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2379                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2380                         /* If value_regno==-1, the caller is asking us whether
2381                          * it is acceptable to use this value as a SCALAR_VALUE
2382                          * (e.g. for XADD).
2383                          * We must not allow unprivileged callers to do that
2384                          * with spilled pointers.
2385                          */
2386                         verbose(env, "leaking pointer from stack off %d\n",
2387                                 off);
2388                         return -EACCES;
2389                 }
2390                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2391         } else {
2392                 int zeros = 0;
2393
2394                 for (i = 0; i < size; i++) {
2395                         if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
2396                                 continue;
2397                         if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
2398                                 zeros++;
2399                                 continue;
2400                         }
2401                         verbose(env, "invalid read from stack off %d+%d size %d\n",
2402                                 off, i, size);
2403                         return -EACCES;
2404                 }
2405                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2406                 if (value_regno >= 0) {
2407                         if (zeros == size) {
2408                                 /* any size read into register is zero extended,
2409                                  * so the whole register == const_zero
2410                                  */
2411                                 __mark_reg_const_zero(&state->regs[value_regno]);
2412                                 /* backtracking doesn't support STACK_ZERO yet,
2413                                  * so mark it precise here, so that later
2414                                  * backtracking can stop here.
2415                                  * Backtracking may not need this if this register
2416                                  * doesn't participate in pointer adjustment.
2417                                  * Forward propagation of precise flag is not
2418                                  * necessary either. This mark is only to stop
2419                                  * backtracking. Any register that contributed
2420                                  * to const 0 was marked precise before spill.
2421                                  */
2422                                 state->regs[value_regno].precise = true;
2423                         } else {
2424                                 /* have read misc data from the stack */
2425                                 mark_reg_unknown(env, state->regs, value_regno);
2426                         }
2427                         state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2428                 }
2429         }
2430         return 0;
2431 }
2432
2433 static int check_stack_access(struct bpf_verifier_env *env,
2434                               const struct bpf_reg_state *reg,
2435                               int off, int size)
2436 {
2437         /* Stack accesses must be at a fixed offset, so that we
2438          * can determine what type of data were returned. See
2439          * check_stack_read().
2440          */
2441         if (!tnum_is_const(reg->var_off)) {
2442                 char tn_buf[48];
2443
2444                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2445                 verbose(env, "variable stack access var_off=%s off=%d size=%d\n",
2446                         tn_buf, off, size);
2447                 return -EACCES;
2448         }
2449
2450         if (off >= 0 || off < -MAX_BPF_STACK) {
2451                 verbose(env, "invalid stack off=%d size=%d\n", off, size);
2452                 return -EACCES;
2453         }
2454
2455         return 0;
2456 }
2457
2458 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2459                                  int off, int size, enum bpf_access_type type)
2460 {
2461         struct bpf_reg_state *regs = cur_regs(env);
2462         struct bpf_map *map = regs[regno].map_ptr;
2463         u32 cap = bpf_map_flags_to_cap(map);
2464
2465         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2466                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2467                         map->value_size, off, size);
2468                 return -EACCES;
2469         }
2470
2471         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2472                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2473                         map->value_size, off, size);
2474                 return -EACCES;
2475         }
2476
2477         return 0;
2478 }
2479
2480 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2481 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2482                               int off, int size, u32 mem_size,
2483                               bool zero_size_allowed)
2484 {
2485         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2486         struct bpf_reg_state *reg;
2487
2488         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2489                 return 0;
2490
2491         reg = &cur_regs(env)[regno];
2492         switch (reg->type) {
2493         case PTR_TO_MAP_VALUE:
2494                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
2495                         mem_size, off, size);
2496                 break;
2497         case PTR_TO_PACKET:
2498         case PTR_TO_PACKET_META:
2499         case PTR_TO_PACKET_END:
2500                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2501                         off, size, regno, reg->id, off, mem_size);
2502                 break;
2503         case PTR_TO_MEM:
2504         default:
2505                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2506                         mem_size, off, size);
2507         }
2508
2509         return -EACCES;
2510 }
2511
2512 /* check read/write into a memory region with possible variable offset */
2513 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2514                                    int off, int size, u32 mem_size,
2515                                    bool zero_size_allowed)
2516 {
2517         struct bpf_verifier_state *vstate = env->cur_state;
2518         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2519         struct bpf_reg_state *reg = &state->regs[regno];
2520         int err;
2521
2522         /* We may have adjusted the register pointing to memory region, so we
2523          * need to try adding each of min_value and max_value to off
2524          * to make sure our theoretical access will be safe.
2525          */
2526         if (env->log.level & BPF_LOG_LEVEL)
2527                 print_verifier_state(env, state);
2528
2529         /* The minimum value is only important with signed
2530          * comparisons where we can't assume the floor of a
2531          * value is 0.  If we are using signed variables for our
2532          * index'es we need to make sure that whatever we use
2533          * will have a set floor within our range.
2534          */
2535         if (reg->smin_value < 0 &&
2536             (reg->smin_value == S64_MIN ||
2537              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2538               reg->smin_value + off < 0)) {
2539                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2540                         regno);
2541                 return -EACCES;
2542         }
2543         err = __check_mem_access(env, regno, reg->smin_value + off, size,
2544                                  mem_size, zero_size_allowed);
2545         if (err) {
2546                 verbose(env, "R%d min value is outside of the allowed memory range\n",
2547                         regno);
2548                 return err;
2549         }
2550
2551         /* If we haven't set a max value then we need to bail since we can't be
2552          * sure we won't do bad things.
2553          * If reg->umax_value + off could overflow, treat that as unbounded too.
2554          */
2555         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
2556                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
2557                         regno);
2558                 return -EACCES;
2559         }
2560         err = __check_mem_access(env, regno, reg->umax_value + off, size,
2561                                  mem_size, zero_size_allowed);
2562         if (err) {
2563                 verbose(env, "R%d max value is outside of the allowed memory range\n",
2564                         regno);
2565                 return err;
2566         }
2567
2568         return 0;
2569 }
2570
2571 /* check read/write into a map element with possible variable offset */
2572 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2573                             int off, int size, bool zero_size_allowed)
2574 {
2575         struct bpf_verifier_state *vstate = env->cur_state;
2576         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2577         struct bpf_reg_state *reg = &state->regs[regno];
2578         struct bpf_map *map = reg->map_ptr;
2579         int err;
2580
2581         err = check_mem_region_access(env, regno, off, size, map->value_size,
2582                                       zero_size_allowed);
2583         if (err)
2584                 return err;
2585
2586         if (map_value_has_spin_lock(map)) {
2587                 u32 lock = map->spin_lock_off;
2588
2589                 /* if any part of struct bpf_spin_lock can be touched by
2590                  * load/store reject this program.
2591                  * To check that [x1, x2) overlaps with [y1, y2)
2592                  * it is sufficient to check x1 < y2 && y1 < x2.
2593                  */
2594                 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2595                      lock < reg->umax_value + off + size) {
2596                         verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2597                         return -EACCES;
2598                 }
2599         }
2600         return err;
2601 }
2602
2603 #define MAX_PACKET_OFF 0xffff
2604
2605 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
2606                                        const struct bpf_call_arg_meta *meta,
2607                                        enum bpf_access_type t)
2608 {
2609         switch (env->prog->type) {
2610         /* Program types only with direct read access go here! */
2611         case BPF_PROG_TYPE_LWT_IN:
2612         case BPF_PROG_TYPE_LWT_OUT:
2613         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2614         case BPF_PROG_TYPE_SK_REUSEPORT:
2615         case BPF_PROG_TYPE_FLOW_DISSECTOR:
2616         case BPF_PROG_TYPE_CGROUP_SKB:
2617                 if (t == BPF_WRITE)
2618                         return false;
2619                 /* fallthrough */
2620
2621         /* Program types with direct read + write access go here! */
2622         case BPF_PROG_TYPE_SCHED_CLS:
2623         case BPF_PROG_TYPE_SCHED_ACT:
2624         case BPF_PROG_TYPE_XDP:
2625         case BPF_PROG_TYPE_LWT_XMIT:
2626         case BPF_PROG_TYPE_SK_SKB:
2627         case BPF_PROG_TYPE_SK_MSG:
2628                 if (meta)
2629                         return meta->pkt_access;
2630
2631                 env->seen_direct_write = true;
2632                 return true;
2633
2634         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2635                 if (t == BPF_WRITE)
2636                         env->seen_direct_write = true;
2637
2638                 return true;
2639
2640         default:
2641                 return false;
2642         }
2643 }
2644
2645 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
2646                                int size, bool zero_size_allowed)
2647 {
2648         struct bpf_reg_state *regs = cur_regs(env);
2649         struct bpf_reg_state *reg = &regs[regno];
2650         int err;
2651
2652         /* We may have added a variable offset to the packet pointer; but any
2653          * reg->range we have comes after that.  We are only checking the fixed
2654          * offset.
2655          */
2656
2657         /* We don't allow negative numbers, because we aren't tracking enough
2658          * detail to prove they're safe.
2659          */
2660         if (reg->smin_value < 0) {
2661                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2662                         regno);
2663                 return -EACCES;
2664         }
2665         err = __check_mem_access(env, regno, off, size, reg->range,
2666                                  zero_size_allowed);
2667         if (err) {
2668                 verbose(env, "R%d offset is outside of the packet\n", regno);
2669                 return err;
2670         }
2671
2672         /* __check_mem_access has made sure "off + size - 1" is within u16.
2673          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
2674          * otherwise find_good_pkt_pointers would have refused to set range info
2675          * that __check_mem_access would have rejected this pkt access.
2676          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
2677          */
2678         env->prog->aux->max_pkt_offset =
2679                 max_t(u32, env->prog->aux->max_pkt_offset,
2680                       off + reg->umax_value + size - 1);
2681
2682         return err;
2683 }
2684
2685 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
2686 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
2687                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
2688                             u32 *btf_id)
2689 {
2690         struct bpf_insn_access_aux info = {
2691                 .reg_type = *reg_type,
2692                 .log = &env->log,
2693         };
2694
2695         if (env->ops->is_valid_access &&
2696             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
2697                 /* A non zero info.ctx_field_size indicates that this field is a
2698                  * candidate for later verifier transformation to load the whole
2699                  * field and then apply a mask when accessed with a narrower
2700                  * access than actual ctx access size. A zero info.ctx_field_size
2701                  * will only allow for whole field access and rejects any other
2702                  * type of narrower access.
2703                  */
2704                 *reg_type = info.reg_type;
2705
2706                 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL)
2707                         *btf_id = info.btf_id;
2708                 else
2709                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
2710                 /* remember the offset of last byte accessed in ctx */
2711                 if (env->prog->aux->max_ctx_offset < off + size)
2712                         env->prog->aux->max_ctx_offset = off + size;
2713                 return 0;
2714         }
2715
2716         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
2717         return -EACCES;
2718 }
2719
2720 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
2721                                   int size)
2722 {
2723         if (size < 0 || off < 0 ||
2724             (u64)off + size > sizeof(struct bpf_flow_keys)) {
2725                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
2726                         off, size);
2727                 return -EACCES;
2728         }
2729         return 0;
2730 }
2731
2732 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
2733                              u32 regno, int off, int size,
2734                              enum bpf_access_type t)
2735 {
2736         struct bpf_reg_state *regs = cur_regs(env);
2737         struct bpf_reg_state *reg = &regs[regno];
2738         struct bpf_insn_access_aux info = {};
2739         bool valid;
2740
2741         if (reg->smin_value < 0) {
2742                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2743                         regno);
2744                 return -EACCES;
2745         }
2746
2747         switch (reg->type) {
2748         case PTR_TO_SOCK_COMMON:
2749                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
2750                 break;
2751         case PTR_TO_SOCKET:
2752                 valid = bpf_sock_is_valid_access(off, size, t, &info);
2753                 break;
2754         case PTR_TO_TCP_SOCK:
2755                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
2756                 break;
2757         case PTR_TO_XDP_SOCK:
2758                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
2759                 break;
2760         default:
2761                 valid = false;
2762         }
2763
2764
2765         if (valid) {
2766                 env->insn_aux_data[insn_idx].ctx_field_size =
2767                         info.ctx_field_size;
2768                 return 0;
2769         }
2770
2771         verbose(env, "R%d invalid %s access off=%d size=%d\n",
2772                 regno, reg_type_str[reg->type], off, size);
2773
2774         return -EACCES;
2775 }
2776
2777 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2778 {
2779         return cur_regs(env) + regno;
2780 }
2781
2782 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
2783 {
2784         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
2785 }
2786
2787 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
2788 {
2789         const struct bpf_reg_state *reg = reg_state(env, regno);
2790
2791         return reg->type == PTR_TO_CTX;
2792 }
2793
2794 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
2795 {
2796         const struct bpf_reg_state *reg = reg_state(env, regno);
2797
2798         return type_is_sk_pointer(reg->type);
2799 }
2800
2801 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
2802 {
2803         const struct bpf_reg_state *reg = reg_state(env, regno);
2804
2805         return type_is_pkt_pointer(reg->type);
2806 }
2807
2808 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
2809 {
2810         const struct bpf_reg_state *reg = reg_state(env, regno);
2811
2812         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
2813         return reg->type == PTR_TO_FLOW_KEYS;
2814 }
2815
2816 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
2817                                    const struct bpf_reg_state *reg,
2818                                    int off, int size, bool strict)
2819 {
2820         struct tnum reg_off;
2821         int ip_align;
2822
2823         /* Byte size accesses are always allowed. */
2824         if (!strict || size == 1)
2825                 return 0;
2826
2827         /* For platforms that do not have a Kconfig enabling
2828          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
2829          * NET_IP_ALIGN is universally set to '2'.  And on platforms
2830          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
2831          * to this code only in strict mode where we want to emulate
2832          * the NET_IP_ALIGN==2 checking.  Therefore use an
2833          * unconditional IP align value of '2'.
2834          */
2835         ip_align = 2;
2836
2837         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
2838         if (!tnum_is_aligned(reg_off, size)) {
2839                 char tn_buf[48];
2840
2841                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2842                 verbose(env,
2843                         "misaligned packet access off %d+%s+%d+%d size %d\n",
2844                         ip_align, tn_buf, reg->off, off, size);
2845                 return -EACCES;
2846         }
2847
2848         return 0;
2849 }
2850
2851 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
2852                                        const struct bpf_reg_state *reg,
2853                                        const char *pointer_desc,
2854                                        int off, int size, bool strict)
2855 {
2856         struct tnum reg_off;
2857
2858         /* Byte size accesses are always allowed. */
2859         if (!strict || size == 1)
2860                 return 0;
2861
2862         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
2863         if (!tnum_is_aligned(reg_off, size)) {
2864                 char tn_buf[48];
2865
2866                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2867                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
2868                         pointer_desc, tn_buf, reg->off, off, size);
2869                 return -EACCES;
2870         }
2871
2872         return 0;
2873 }
2874
2875 static int check_ptr_alignment(struct bpf_verifier_env *env,
2876                                const struct bpf_reg_state *reg, int off,
2877                                int size, bool strict_alignment_once)
2878 {
2879         bool strict = env->strict_alignment || strict_alignment_once;
2880         const char *pointer_desc = "";
2881
2882         switch (reg->type) {
2883         case PTR_TO_PACKET:
2884         case PTR_TO_PACKET_META:
2885                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
2886                  * right in front, treat it the very same way.
2887                  */
2888                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
2889         case PTR_TO_FLOW_KEYS:
2890                 pointer_desc = "flow keys ";
2891                 break;
2892         case PTR_TO_MAP_VALUE:
2893                 pointer_desc = "value ";
2894                 break;
2895         case PTR_TO_CTX:
2896                 pointer_desc = "context ";
2897                 break;
2898         case PTR_TO_STACK:
2899                 pointer_desc = "stack ";
2900                 /* The stack spill tracking logic in check_stack_write()
2901                  * and check_stack_read() relies on stack accesses being
2902                  * aligned.
2903                  */
2904                 strict = true;
2905                 break;
2906         case PTR_TO_SOCKET:
2907                 pointer_desc = "sock ";
2908                 break;
2909         case PTR_TO_SOCK_COMMON:
2910                 pointer_desc = "sock_common ";
2911                 break;
2912         case PTR_TO_TCP_SOCK:
2913                 pointer_desc = "tcp_sock ";
2914                 break;
2915         case PTR_TO_XDP_SOCK:
2916                 pointer_desc = "xdp_sock ";
2917                 break;
2918         default:
2919                 break;
2920         }
2921         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
2922                                            strict);
2923 }
2924
2925 static int update_stack_depth(struct bpf_verifier_env *env,
2926                               const struct bpf_func_state *func,
2927                               int off)
2928 {
2929         u16 stack = env->subprog_info[func->subprogno].stack_depth;
2930
2931         if (stack >= -off)
2932                 return 0;
2933
2934         /* update known max for given subprogram */
2935         env->subprog_info[func->subprogno].stack_depth = -off;
2936         return 0;
2937 }
2938
2939 /* starting from main bpf function walk all instructions of the function
2940  * and recursively walk all callees that given function can call.
2941  * Ignore jump and exit insns.
2942  * Since recursion is prevented by check_cfg() this algorithm
2943  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
2944  */
2945 static int check_max_stack_depth(struct bpf_verifier_env *env)
2946 {
2947         int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
2948         struct bpf_subprog_info *subprog = env->subprog_info;
2949         struct bpf_insn *insn = env->prog->insnsi;
2950         int ret_insn[MAX_CALL_FRAMES];
2951         int ret_prog[MAX_CALL_FRAMES];
2952
2953 process_func:
2954         /* round up to 32-bytes, since this is granularity
2955          * of interpreter stack size
2956          */
2957         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
2958         if (depth > MAX_BPF_STACK) {
2959                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
2960                         frame + 1, depth);
2961                 return -EACCES;
2962         }
2963 continue_func:
2964         subprog_end = subprog[idx + 1].start;
2965         for (; i < subprog_end; i++) {
2966                 if (insn[i].code != (BPF_JMP | BPF_CALL))
2967                         continue;
2968                 if (insn[i].src_reg != BPF_PSEUDO_CALL)
2969                         continue;
2970                 /* remember insn and function to return to */
2971                 ret_insn[frame] = i + 1;
2972                 ret_prog[frame] = idx;
2973
2974                 /* find the callee */
2975                 i = i + insn[i].imm + 1;
2976                 idx = find_subprog(env, i);
2977                 if (idx < 0) {
2978                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
2979                                   i);
2980                         return -EFAULT;
2981                 }
2982                 frame++;
2983                 if (frame >= MAX_CALL_FRAMES) {
2984                         verbose(env, "the call stack of %d frames is too deep !\n",
2985                                 frame);
2986                         return -E2BIG;
2987                 }
2988                 goto process_func;
2989         }
2990         /* end of for() loop means the last insn of the 'subprog'
2991          * was reached. Doesn't matter whether it was JA or EXIT
2992          */
2993         if (frame == 0)
2994                 return 0;
2995         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
2996         frame--;
2997         i = ret_insn[frame];
2998         idx = ret_prog[frame];
2999         goto continue_func;
3000 }
3001
3002 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3003 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3004                                   const struct bpf_insn *insn, int idx)
3005 {
3006         int start = idx + insn->imm + 1, subprog;
3007
3008         subprog = find_subprog(env, start);
3009         if (subprog < 0) {
3010                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3011                           start);
3012                 return -EFAULT;
3013         }
3014         return env->subprog_info[subprog].stack_depth;
3015 }
3016 #endif
3017
3018 int check_ctx_reg(struct bpf_verifier_env *env,
3019                   const struct bpf_reg_state *reg, int regno)
3020 {
3021         /* Access to ctx or passing it to a helper is only allowed in
3022          * its original, unmodified form.
3023          */
3024
3025         if (reg->off) {
3026                 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3027                         regno, reg->off);
3028                 return -EACCES;
3029         }
3030
3031         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3032                 char tn_buf[48];
3033
3034                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3035                 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3036                 return -EACCES;
3037         }
3038
3039         return 0;
3040 }
3041
3042 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3043                                   const struct bpf_reg_state *reg,
3044                                   int regno, int off, int size)
3045 {
3046         if (off < 0) {
3047                 verbose(env,
3048                         "R%d invalid tracepoint buffer access: off=%d, size=%d",
3049                         regno, off, size);
3050                 return -EACCES;
3051         }
3052         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3053                 char tn_buf[48];
3054
3055                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3056                 verbose(env,
3057                         "R%d invalid variable buffer offset: off=%d, var_off=%s",
3058                         regno, off, tn_buf);
3059                 return -EACCES;
3060         }
3061         if (off + size > env->prog->aux->max_tp_access)
3062                 env->prog->aux->max_tp_access = off + size;
3063
3064         return 0;
3065 }
3066
3067 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3068 static void zext_32_to_64(struct bpf_reg_state *reg)
3069 {
3070         reg->var_off = tnum_subreg(reg->var_off);
3071         __reg_assign_32_into_64(reg);
3072 }
3073
3074 /* truncate register to smaller size (in bytes)
3075  * must be called with size < BPF_REG_SIZE
3076  */
3077 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3078 {
3079         u64 mask;
3080
3081         /* clear high bits in bit representation */
3082         reg->var_off = tnum_cast(reg->var_off, size);
3083
3084         /* fix arithmetic bounds */
3085         mask = ((u64)1 << (size * 8)) - 1;
3086         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3087                 reg->umin_value &= mask;
3088                 reg->umax_value &= mask;
3089         } else {
3090                 reg->umin_value = 0;
3091                 reg->umax_value = mask;
3092         }
3093         reg->smin_value = reg->umin_value;
3094         reg->smax_value = reg->umax_value;
3095
3096         /* If size is smaller than 32bit register the 32bit register
3097          * values are also truncated so we push 64-bit bounds into
3098          * 32-bit bounds. Above were truncated < 32-bits already.
3099          */
3100         if (size >= 4)
3101                 return;
3102         __reg_combine_64_into_32(reg);
3103 }
3104
3105 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3106 {
3107         return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3108 }
3109
3110 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3111 {
3112         void *ptr;
3113         u64 addr;
3114         int err;
3115
3116         err = map->ops->map_direct_value_addr(map, &addr, off);
3117         if (err)
3118                 return err;
3119         ptr = (void *)(long)addr + off;
3120
3121         switch (size) {
3122         case sizeof(u8):
3123                 *val = (u64)*(u8 *)ptr;
3124                 break;
3125         case sizeof(u16):
3126                 *val = (u64)*(u16 *)ptr;
3127                 break;
3128         case sizeof(u32):
3129                 *val = (u64)*(u32 *)ptr;
3130                 break;
3131         case sizeof(u64):
3132                 *val = *(u64 *)ptr;
3133                 break;
3134         default:
3135                 return -EINVAL;
3136         }
3137         return 0;
3138 }
3139
3140 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3141                                    struct bpf_reg_state *regs,
3142                                    int regno, int off, int size,
3143                                    enum bpf_access_type atype,
3144                                    int value_regno)
3145 {
3146         struct bpf_reg_state *reg = regs + regno;
3147         const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
3148         const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3149         u32 btf_id;
3150         int ret;
3151
3152         if (off < 0) {
3153                 verbose(env,
3154                         "R%d is ptr_%s invalid negative access: off=%d\n",
3155                         regno, tname, off);
3156                 return -EACCES;
3157         }
3158         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3159                 char tn_buf[48];
3160
3161                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3162                 verbose(env,
3163                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3164                         regno, tname, off, tn_buf);
3165                 return -EACCES;
3166         }
3167
3168         if (env->ops->btf_struct_access) {
3169                 ret = env->ops->btf_struct_access(&env->log, t, off, size,
3170                                                   atype, &btf_id);
3171         } else {
3172                 if (atype != BPF_READ) {
3173                         verbose(env, "only read is supported\n");
3174                         return -EACCES;
3175                 }
3176
3177                 ret = btf_struct_access(&env->log, t, off, size, atype,
3178                                         &btf_id);
3179         }
3180
3181         if (ret < 0)
3182                 return ret;
3183
3184         if (atype == BPF_READ && value_regno >= 0) {
3185                 if (ret == SCALAR_VALUE) {
3186                         mark_reg_unknown(env, regs, value_regno);
3187                         return 0;
3188                 }
3189                 mark_reg_known_zero(env, regs, value_regno);
3190                 regs[value_regno].type = PTR_TO_BTF_ID;
3191                 regs[value_regno].btf_id = btf_id;
3192         }
3193
3194         return 0;
3195 }
3196
3197 /* check whether memory at (regno + off) is accessible for t = (read | write)
3198  * if t==write, value_regno is a register which value is stored into memory
3199  * if t==read, value_regno is a register which will receive the value from memory
3200  * if t==write && value_regno==-1, some unknown value is stored into memory
3201  * if t==read && value_regno==-1, don't care what we read from memory
3202  */
3203 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3204                             int off, int bpf_size, enum bpf_access_type t,
3205                             int value_regno, bool strict_alignment_once)
3206 {
3207         struct bpf_reg_state *regs = cur_regs(env);
3208         struct bpf_reg_state *reg = regs + regno;
3209         struct bpf_func_state *state;
3210         int size, err = 0;
3211
3212         size = bpf_size_to_bytes(bpf_size);
3213         if (size < 0)
3214                 return size;
3215
3216         /* alignment checks will add in reg->off themselves */
3217         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
3218         if (err)
3219                 return err;
3220
3221         /* for access checks, reg->off is just part of off */
3222         off += reg->off;
3223
3224         if (reg->type == PTR_TO_MAP_VALUE) {
3225                 if (t == BPF_WRITE && value_regno >= 0 &&
3226                     is_pointer_value(env, value_regno)) {
3227                         verbose(env, "R%d leaks addr into map\n", value_regno);
3228                         return -EACCES;
3229                 }
3230                 err = check_map_access_type(env, regno, off, size, t);
3231                 if (err)
3232                         return err;
3233                 err = check_map_access(env, regno, off, size, false);
3234                 if (!err && t == BPF_READ && value_regno >= 0) {
3235                         struct bpf_map *map = reg->map_ptr;
3236
3237                         /* if map is read-only, track its contents as scalars */
3238                         if (tnum_is_const(reg->var_off) &&
3239                             bpf_map_is_rdonly(map) &&
3240                             map->ops->map_direct_value_addr) {
3241                                 int map_off = off + reg->var_off.value;
3242                                 u64 val = 0;
3243
3244                                 err = bpf_map_direct_read(map, map_off, size,
3245                                                           &val);
3246                                 if (err)
3247                                         return err;
3248
3249                                 regs[value_regno].type = SCALAR_VALUE;
3250                                 __mark_reg_known(&regs[value_regno], val);
3251                         } else {
3252                                 mark_reg_unknown(env, regs, value_regno);
3253                         }
3254                 }
3255         } else if (reg->type == PTR_TO_MEM) {
3256                 if (t == BPF_WRITE && value_regno >= 0 &&
3257                     is_pointer_value(env, value_regno)) {
3258                         verbose(env, "R%d leaks addr into mem\n", value_regno);
3259                         return -EACCES;
3260                 }
3261                 err = check_mem_region_access(env, regno, off, size,
3262                                               reg->mem_size, false);
3263                 if (!err && t == BPF_READ && value_regno >= 0)
3264                         mark_reg_unknown(env, regs, value_regno);
3265         } else if (reg->type == PTR_TO_CTX) {
3266                 enum bpf_reg_type reg_type = SCALAR_VALUE;
3267                 u32 btf_id = 0;
3268
3269                 if (t == BPF_WRITE && value_regno >= 0 &&
3270                     is_pointer_value(env, value_regno)) {
3271                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
3272                         return -EACCES;
3273                 }
3274
3275                 err = check_ctx_reg(env, reg, regno);
3276                 if (err < 0)
3277                         return err;
3278
3279                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf_id);
3280                 if (err)
3281                         verbose_linfo(env, insn_idx, "; ");
3282                 if (!err && t == BPF_READ && value_regno >= 0) {
3283                         /* ctx access returns either a scalar, or a
3284                          * PTR_TO_PACKET[_META,_END]. In the latter
3285                          * case, we know the offset is zero.
3286                          */
3287                         if (reg_type == SCALAR_VALUE) {
3288                                 mark_reg_unknown(env, regs, value_regno);
3289                         } else {
3290                                 mark_reg_known_zero(env, regs,
3291                                                     value_regno);
3292                                 if (reg_type_may_be_null(reg_type))
3293                                         regs[value_regno].id = ++env->id_gen;
3294                                 /* A load of ctx field could have different
3295                                  * actual load size with the one encoded in the
3296                                  * insn. When the dst is PTR, it is for sure not
3297                                  * a sub-register.
3298                                  */
3299                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
3300                                 if (reg_type == PTR_TO_BTF_ID ||
3301                                     reg_type == PTR_TO_BTF_ID_OR_NULL)
3302                                         regs[value_regno].btf_id = btf_id;
3303                         }
3304                         regs[value_regno].type = reg_type;
3305                 }
3306
3307         } else if (reg->type == PTR_TO_STACK) {
3308                 off += reg->var_off.value;
3309                 err = check_stack_access(env, reg, off, size);
3310                 if (err)
3311                         return err;
3312
3313                 state = func(env, reg);
3314                 err = update_stack_depth(env, state, off);
3315                 if (err)
3316                         return err;
3317
3318                 if (t == BPF_WRITE)
3319                         err = check_stack_write(env, state, off, size,
3320                                                 value_regno, insn_idx);
3321                 else
3322                         err = check_stack_read(env, state, off, size,
3323                                                value_regno);
3324         } else if (reg_is_pkt_pointer(reg)) {
3325                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
3326                         verbose(env, "cannot write into packet\n");
3327                         return -EACCES;
3328                 }
3329                 if (t == BPF_WRITE && value_regno >= 0 &&
3330                     is_pointer_value(env, value_regno)) {
3331                         verbose(env, "R%d leaks addr into packet\n",
3332                                 value_regno);
3333                         return -EACCES;
3334                 }
3335                 err = check_packet_access(env, regno, off, size, false);
3336                 if (!err && t == BPF_READ && value_regno >= 0)
3337                         mark_reg_unknown(env, regs, value_regno);
3338         } else if (reg->type == PTR_TO_FLOW_KEYS) {
3339                 if (t == BPF_WRITE && value_regno >= 0 &&
3340                     is_pointer_value(env, value_regno)) {
3341                         verbose(env, "R%d leaks addr into flow keys\n",
3342                                 value_regno);
3343                         return -EACCES;
3344                 }
3345
3346                 err = check_flow_keys_access(env, off, size);
3347                 if (!err && t == BPF_READ && value_regno >= 0)
3348                         mark_reg_unknown(env, regs, value_regno);
3349         } else if (type_is_sk_pointer(reg->type)) {
3350                 if (t == BPF_WRITE) {
3351                         verbose(env, "R%d cannot write into %s\n",
3352                                 regno, reg_type_str[reg->type]);
3353                         return -EACCES;
3354                 }
3355                 err = check_sock_access(env, insn_idx, regno, off, size, t);
3356                 if (!err && value_regno >= 0)
3357                         mark_reg_unknown(env, regs, value_regno);
3358         } else if (reg->type == PTR_TO_TP_BUFFER) {
3359                 err = check_tp_buffer_access(env, reg, regno, off, size);
3360                 if (!err && t == BPF_READ && value_regno >= 0)
3361                         mark_reg_unknown(env, regs, value_regno);
3362         } else if (reg->type == PTR_TO_BTF_ID) {
3363                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3364                                               value_regno);
3365         } else {
3366                 verbose(env, "R%d invalid mem access '%s'\n", regno,
3367                         reg_type_str[reg->type]);
3368                 return -EACCES;
3369         }
3370
3371         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
3372             regs[value_regno].type == SCALAR_VALUE) {
3373                 /* b/h/w load zero-extends, mark upper bits as known 0 */
3374                 coerce_reg_to_size(&regs[value_regno], size);
3375         }
3376         return err;
3377 }
3378
3379 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
3380 {
3381         int err;
3382
3383         if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
3384             insn->imm != 0) {
3385                 verbose(env, "BPF_XADD uses reserved fields\n");
3386                 return -EINVAL;
3387         }
3388
3389         /* check src1 operand */
3390         err = check_reg_arg(env, insn->src_reg, SRC_OP);
3391         if (err)
3392                 return err;
3393
3394         /* check src2 operand */
3395         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3396         if (err)
3397                 return err;
3398
3399         if (is_pointer_value(env, insn->src_reg)) {
3400                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
3401                 return -EACCES;
3402         }
3403
3404         if (is_ctx_reg(env, insn->dst_reg) ||
3405             is_pkt_reg(env, insn->dst_reg) ||
3406             is_flow_key_reg(env, insn->dst_reg) ||
3407             is_sk_reg(env, insn->dst_reg)) {
3408                 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
3409                         insn->dst_reg,
3410                         reg_type_str[reg_state(env, insn->dst_reg)->type]);
3411                 return -EACCES;
3412         }
3413
3414         /* check whether atomic_add can read the memory */
3415         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
3416                                BPF_SIZE(insn->code), BPF_READ, -1, true);
3417         if (err)
3418                 return err;
3419
3420         /* check whether atomic_add can write into the same memory */
3421         return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
3422                                 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
3423 }
3424
3425 static int __check_stack_boundary(struct bpf_verifier_env *env, u32 regno,
3426                                   int off, int access_size,
3427                                   bool zero_size_allowed)
3428 {
3429         struct bpf_reg_state *reg = reg_state(env, regno);
3430
3431         if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
3432             access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
3433                 if (tnum_is_const(reg->var_off)) {
3434                         verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
3435                                 regno, off, access_size);
3436                 } else {
3437                         char tn_buf[48];
3438
3439                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3440                         verbose(env, "invalid stack type R%d var_off=%s access_size=%d\n",
3441                                 regno, tn_buf, access_size);
3442                 }
3443                 return -EACCES;
3444         }
3445         return 0;
3446 }
3447
3448 /* when register 'regno' is passed into function that will read 'access_size'
3449  * bytes from that pointer, make sure that it's within stack boundary
3450  * and all elements of stack are initialized.
3451  * Unlike most pointer bounds-checking functions, this one doesn't take an
3452  * 'off' argument, so it has to add in reg->off itself.
3453  */
3454 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
3455                                 int access_size, bool zero_size_allowed,
3456                                 struct bpf_call_arg_meta *meta)
3457 {
3458         struct bpf_reg_state *reg = reg_state(env, regno);
3459         struct bpf_func_state *state = func(env, reg);
3460         int err, min_off, max_off, i, j, slot, spi;
3461
3462         if (reg->type != PTR_TO_STACK) {
3463                 /* Allow zero-byte read from NULL, regardless of pointer type */
3464                 if (zero_size_allowed && access_size == 0 &&
3465                     register_is_null(reg))
3466                         return 0;
3467
3468                 verbose(env, "R%d type=%s expected=%s\n", regno,
3469                         reg_type_str[reg->type],
3470                         reg_type_str[PTR_TO_STACK]);
3471                 return -EACCES;
3472         }
3473
3474         if (tnum_is_const(reg->var_off)) {
3475                 min_off = max_off = reg->var_off.value + reg->off;
3476                 err = __check_stack_boundary(env, regno, min_off, access_size,
3477                                              zero_size_allowed);
3478                 if (err)
3479                         return err;
3480         } else {
3481                 /* Variable offset is prohibited for unprivileged mode for
3482                  * simplicity since it requires corresponding support in
3483                  * Spectre masking for stack ALU.
3484                  * See also retrieve_ptr_limit().
3485                  */
3486                 if (!env->bypass_spec_v1) {
3487                         char tn_buf[48];
3488
3489                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3490                         verbose(env, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
3491                                 regno, tn_buf);
3492                         return -EACCES;
3493                 }
3494                 /* Only initialized buffer on stack is allowed to be accessed
3495                  * with variable offset. With uninitialized buffer it's hard to
3496                  * guarantee that whole memory is marked as initialized on
3497                  * helper return since specific bounds are unknown what may
3498                  * cause uninitialized stack leaking.
3499                  */
3500                 if (meta && meta->raw_mode)
3501                         meta = NULL;
3502
3503                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3504                     reg->smax_value <= -BPF_MAX_VAR_OFF) {
3505                         verbose(env, "R%d unbounded indirect variable offset stack access\n",
3506                                 regno);
3507                         return -EACCES;
3508                 }
3509                 min_off = reg->smin_value + reg->off;
3510                 max_off = reg->smax_value + reg->off;
3511                 err = __check_stack_boundary(env, regno, min_off, access_size,
3512                                              zero_size_allowed);
3513                 if (err) {
3514                         verbose(env, "R%d min value is outside of stack bound\n",
3515                                 regno);
3516                         return err;
3517                 }
3518                 err = __check_stack_boundary(env, regno, max_off, access_size,
3519                                              zero_size_allowed);
3520                 if (err) {
3521                         verbose(env, "R%d max value is outside of stack bound\n",
3522                                 regno);
3523                         return err;
3524                 }
3525         }
3526
3527         if (meta && meta->raw_mode) {
3528                 meta->access_size = access_size;
3529                 meta->regno = regno;
3530                 return 0;
3531         }
3532
3533         for (i = min_off; i < max_off + access_size; i++) {
3534                 u8 *stype;
3535
3536                 slot = -i - 1;
3537                 spi = slot / BPF_REG_SIZE;
3538                 if (state->allocated_stack <= slot)
3539                         goto err;
3540                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3541                 if (*stype == STACK_MISC)
3542                         goto mark;
3543                 if (*stype == STACK_ZERO) {
3544                         /* helper can write anything into the stack */
3545                         *stype = STACK_MISC;
3546                         goto mark;
3547                 }
3548
3549                 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3550                     state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
3551                         goto mark;
3552
3553                 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3554                     state->stack[spi].spilled_ptr.type == SCALAR_VALUE) {
3555                         __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
3556                         for (j = 0; j < BPF_REG_SIZE; j++)
3557                                 state->stack[spi].slot_type[j] = STACK_MISC;
3558                         goto mark;
3559                 }
3560
3561 err:
3562                 if (tnum_is_const(reg->var_off)) {
3563                         verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
3564                                 min_off, i - min_off, access_size);
3565                 } else {
3566                         char tn_buf[48];
3567
3568                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3569                         verbose(env, "invalid indirect read from stack var_off %s+%d size %d\n",
3570                                 tn_buf, i - min_off, access_size);
3571                 }
3572                 return -EACCES;
3573 mark:
3574                 /* reading any byte out of 8-byte 'spill_slot' will cause
3575                  * the whole slot to be marked as 'read'
3576                  */
3577                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
3578                               state->stack[spi].spilled_ptr.parent,
3579                               REG_LIVE_READ64);
3580         }
3581         return update_stack_depth(env, state, min_off);
3582 }
3583
3584 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
3585                                    int access_size, bool zero_size_allowed,
3586                                    struct bpf_call_arg_meta *meta)
3587 {
3588         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
3589
3590         switch (reg->type) {
3591         case PTR_TO_PACKET:
3592         case PTR_TO_PACKET_META:
3593                 return check_packet_access(env, regno, reg->off, access_size,
3594                                            zero_size_allowed);
3595         case PTR_TO_MAP_VALUE:
3596                 if (check_map_access_type(env, regno, reg->off, access_size,
3597                                           meta && meta->raw_mode ? BPF_WRITE :
3598                                           BPF_READ))
3599                         return -EACCES;
3600                 return check_map_access(env, regno, reg->off, access_size,
3601                                         zero_size_allowed);
3602         case PTR_TO_MEM:
3603                 return check_mem_region_access(env, regno, reg->off,
3604                                                access_size, reg->mem_size,
3605                                                zero_size_allowed);
3606         default: /* scalar_value|ptr_to_stack or invalid ptr */
3607                 return check_stack_boundary(env, regno, access_size,
3608                                             zero_size_allowed, meta);
3609         }
3610 }
3611
3612 /* Implementation details:
3613  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
3614  * Two bpf_map_lookups (even with the same key) will have different reg->id.
3615  * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
3616  * value_or_null->value transition, since the verifier only cares about
3617  * the range of access to valid map value pointer and doesn't care about actual
3618  * address of the map element.
3619  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
3620  * reg->id > 0 after value_or_null->value transition. By doing so
3621  * two bpf_map_lookups will be considered two different pointers that
3622  * point to different bpf_spin_locks.
3623  * The verifier allows taking only one bpf_spin_lock at a time to avoid
3624  * dead-locks.
3625  * Since only one bpf_spin_lock is allowed the checks are simpler than
3626  * reg_is_refcounted() logic. The verifier needs to remember only
3627  * one spin_lock instead of array of acquired_refs.
3628  * cur_state->active_spin_lock remembers which map value element got locked
3629  * and clears it after bpf_spin_unlock.
3630  */
3631 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
3632                              bool is_lock)
3633 {
3634         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
3635         struct bpf_verifier_state *cur = env->cur_state;
3636         bool is_const = tnum_is_const(reg->var_off);
3637         struct bpf_map *map = reg->map_ptr;
3638         u64 val = reg->var_off.value;
3639
3640         if (reg->type != PTR_TO_MAP_VALUE) {
3641                 verbose(env, "R%d is not a pointer to map_value\n", regno);
3642                 return -EINVAL;
3643         }
3644         if (!is_const) {
3645                 verbose(env,
3646                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
3647                         regno);
3648                 return -EINVAL;
3649         }
3650         if (!map->btf) {
3651                 verbose(env,
3652                         "map '%s' has to have BTF in order to use bpf_spin_lock\n",
3653                         map->name);
3654                 return -EINVAL;
3655         }
3656         if (!map_value_has_spin_lock(map)) {
3657                 if (map->spin_lock_off == -E2BIG)
3658                         verbose(env,
3659                                 "map '%s' has more than one 'struct bpf_spin_lock'\n",
3660                                 map->name);
3661                 else if (map->spin_lock_off == -ENOENT)
3662                         verbose(env,
3663                                 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
3664                                 map->name);
3665                 else
3666                         verbose(env,
3667                                 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
3668                                 map->name);
3669                 return -EINVAL;
3670         }
3671         if (map->spin_lock_off != val + reg->off) {
3672                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
3673                         val + reg->off);
3674                 return -EINVAL;
3675         }
3676         if (is_lock) {
3677                 if (cur->active_spin_lock) {
3678                         verbose(env,
3679                                 "Locking two bpf_spin_locks are not allowed\n");
3680                         return -EINVAL;
3681                 }
3682                 cur->active_spin_lock = reg->id;
3683         } else {
3684                 if (!cur->active_spin_lock) {
3685                         verbose(env, "bpf_spin_unlock without taking a lock\n");
3686                         return -EINVAL;
3687                 }
3688                 if (cur->active_spin_lock != reg->id) {
3689                         verbose(env, "bpf_spin_unlock of different lock\n");
3690                         return -EINVAL;
3691                 }
3692                 cur->active_spin_lock = 0;
3693         }
3694         return 0;
3695 }
3696
3697 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
3698 {
3699         return type == ARG_PTR_TO_MEM ||
3700                type == ARG_PTR_TO_MEM_OR_NULL ||
3701                type == ARG_PTR_TO_UNINIT_MEM;
3702 }
3703
3704 static bool arg_type_is_mem_size(enum bpf_arg_type type)
3705 {
3706         return type == ARG_CONST_SIZE ||
3707                type == ARG_CONST_SIZE_OR_ZERO;
3708 }
3709
3710 static bool arg_type_is_alloc_mem_ptr(enum bpf_arg_type type)
3711 {
3712         return type == ARG_PTR_TO_ALLOC_MEM ||
3713                type == ARG_PTR_TO_ALLOC_MEM_OR_NULL;
3714 }
3715
3716 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
3717 {
3718         return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
3719 }
3720
3721 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
3722 {
3723         return type == ARG_PTR_TO_INT ||
3724                type == ARG_PTR_TO_LONG;
3725 }
3726
3727 static int int_ptr_type_to_size(enum bpf_arg_type type)
3728 {
3729         if (type == ARG_PTR_TO_INT)
3730                 return sizeof(u32);
3731         else if (type == ARG_PTR_TO_LONG)
3732                 return sizeof(u64);
3733
3734         return -EINVAL;
3735 }
3736
3737 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
3738                           enum bpf_arg_type arg_type,
3739                           struct bpf_call_arg_meta *meta)
3740 {
3741         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
3742         enum bpf_reg_type expected_type, type = reg->type;
3743         int err = 0;
3744
3745         if (arg_type == ARG_DONTCARE)
3746                 return 0;
3747
3748         err = check_reg_arg(env, regno, SRC_OP);
3749         if (err)
3750                 return err;
3751
3752         if (arg_type == ARG_ANYTHING) {
3753                 if (is_pointer_value(env, regno)) {
3754                         verbose(env, "R%d leaks addr into helper function\n",
3755                                 regno);
3756                         return -EACCES;
3757                 }
3758                 return 0;
3759         }
3760
3761         if (type_is_pkt_pointer(type) &&
3762             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
3763                 verbose(env, "helper access to the packet is not allowed\n");
3764                 return -EACCES;
3765         }
3766
3767         if (arg_type == ARG_PTR_TO_MAP_KEY ||
3768             arg_type == ARG_PTR_TO_MAP_VALUE ||
3769             arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
3770             arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
3771                 expected_type = PTR_TO_STACK;
3772                 if (register_is_null(reg) &&
3773                     arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL)
3774                         /* final test in check_stack_boundary() */;
3775                 else if (!type_is_pkt_pointer(type) &&
3776                          type != PTR_TO_MAP_VALUE &&
3777                          type != expected_type)
3778                         goto err_type;
3779         } else if (arg_type == ARG_CONST_SIZE ||
3780                    arg_type == ARG_CONST_SIZE_OR_ZERO ||
3781                    arg_type == ARG_CONST_ALLOC_SIZE_OR_ZERO) {
3782                 expected_type = SCALAR_VALUE;
3783                 if (type != expected_type)
3784                         goto err_type;
3785         } else if (arg_type == ARG_CONST_MAP_PTR) {
3786                 expected_type = CONST_PTR_TO_MAP;
3787                 if (type != expected_type)
3788                         goto err_type;
3789         } else if (arg_type == ARG_PTR_TO_CTX ||
3790                    arg_type == ARG_PTR_TO_CTX_OR_NULL) {
3791                 expected_type = PTR_TO_CTX;
3792                 if (!(register_is_null(reg) &&
3793                       arg_type == ARG_PTR_TO_CTX_OR_NULL)) {
3794                         if (type != expected_type)
3795                                 goto err_type;
3796                         err = check_ctx_reg(env, reg, regno);
3797                         if (err < 0)
3798                                 return err;
3799                 }
3800         } else if (arg_type == ARG_PTR_TO_SOCK_COMMON) {
3801                 expected_type = PTR_TO_SOCK_COMMON;
3802                 /* Any sk pointer can be ARG_PTR_TO_SOCK_COMMON */
3803                 if (!type_is_sk_pointer(type))
3804                         goto err_type;
3805                 if (reg->ref_obj_id) {
3806                         if (meta->ref_obj_id) {
3807                                 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
3808                                         regno, reg->ref_obj_id,
3809                                         meta->ref_obj_id);
3810                                 return -EFAULT;
3811                         }
3812                         meta->ref_obj_id = reg->ref_obj_id;
3813                 }
3814         } else if (arg_type == ARG_PTR_TO_SOCKET) {
3815                 expected_type = PTR_TO_SOCKET;
3816                 if (type != expected_type)
3817                         goto err_type;
3818         } else if (arg_type == ARG_PTR_TO_BTF_ID) {
3819                 expected_type = PTR_TO_BTF_ID;
3820                 if (type != expected_type)
3821                         goto err_type;
3822                 if (reg->btf_id != meta->btf_id) {
3823                         verbose(env, "Helper has type %s got %s in R%d\n",
3824                                 kernel_type_name(meta->btf_id),
3825                                 kernel_type_name(reg->btf_id), regno);
3826
3827                         return -EACCES;
3828                 }
3829                 if (!tnum_is_const(reg->var_off) || reg->var_off.value || reg->off) {
3830                         verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
3831                                 regno);
3832                         return -EACCES;
3833                 }
3834         } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
3835                 if (meta->func_id == BPF_FUNC_spin_lock) {
3836                         if (process_spin_lock(env, regno, true))
3837                                 return -EACCES;
3838                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
3839                         if (process_spin_lock(env, regno, false))
3840                                 return -EACCES;
3841                 } else {
3842                         verbose(env, "verifier internal error\n");
3843                         return -EFAULT;
3844                 }
3845         } else if (arg_type_is_mem_ptr(arg_type)) {
3846                 expected_type = PTR_TO_STACK;
3847                 /* One exception here. In case function allows for NULL to be
3848                  * passed in as argument, it's a SCALAR_VALUE type. Final test
3849                  * happens during stack boundary checking.
3850                  */
3851                 if (register_is_null(reg) &&
3852                     (arg_type == ARG_PTR_TO_MEM_OR_NULL ||
3853                      arg_type == ARG_PTR_TO_ALLOC_MEM_OR_NULL))
3854                         /* final test in check_stack_boundary() */;
3855                 else if (!type_is_pkt_pointer(type) &&
3856                          type != PTR_TO_MAP_VALUE &&
3857                          type != PTR_TO_MEM &&
3858                          type != expected_type)
3859                         goto err_type;
3860                 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
3861         } else if (arg_type_is_alloc_mem_ptr(arg_type)) {
3862                 expected_type = PTR_TO_MEM;
3863                 if (register_is_null(reg) &&
3864                     arg_type == ARG_PTR_TO_ALLOC_MEM_OR_NULL)
3865                         /* final test in check_stack_boundary() */;
3866                 else if (type != expected_type)
3867                         goto err_type;
3868                 if (meta->ref_obj_id) {
3869                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
3870                                 regno, reg->ref_obj_id,
3871                                 meta->ref_obj_id);
3872                         return -EFAULT;
3873                 }
3874                 meta->ref_obj_id = reg->ref_obj_id;
3875         } else if (arg_type_is_int_ptr(arg_type)) {
3876                 expected_type = PTR_TO_STACK;
3877                 if (!type_is_pkt_pointer(type) &&
3878                     type != PTR_TO_MAP_VALUE &&
3879                     type != expected_type)
3880                         goto err_type;
3881         } else {
3882                 verbose(env, "unsupported arg_type %d\n", arg_type);
3883                 return -EFAULT;
3884         }
3885
3886         if (arg_type == ARG_CONST_MAP_PTR) {
3887                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
3888                 meta->map_ptr = reg->map_ptr;
3889         } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
3890                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
3891                  * check that [key, key + map->key_size) are within
3892                  * stack limits and initialized
3893                  */
3894                 if (!meta->map_ptr) {
3895                         /* in function declaration map_ptr must come before
3896                          * map_key, so that it's verified and known before
3897                          * we have to check map_key here. Otherwise it means
3898                          * that kernel subsystem misconfigured verifier
3899                          */
3900                         verbose(env, "invalid map_ptr to access map->key\n");
3901                         return -EACCES;
3902                 }
3903                 err = check_helper_mem_access(env, regno,
3904                                               meta->map_ptr->key_size, false,
3905                                               NULL);
3906         } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
3907                    (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
3908                     !register_is_null(reg)) ||
3909                    arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
3910                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
3911                  * check [value, value + map->value_size) validity
3912                  */
3913                 if (!meta->map_ptr) {
3914                         /* kernel subsystem misconfigured verifier */
3915                         verbose(env, "invalid map_ptr to access map->value\n");
3916                         return -EACCES;
3917                 }
3918                 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
3919                 err = check_helper_mem_access(env, regno,
3920                                               meta->map_ptr->value_size, false,
3921                                               meta);
3922         } else if (arg_type_is_mem_size(arg_type)) {
3923                 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
3924
3925                 /* This is used to refine r0 return value bounds for helpers
3926                  * that enforce this value as an upper bound on return values.
3927                  * See do_refine_retval_range() for helpers that can refine
3928                  * the return value. C type of helper is u32 so we pull register
3929                  * bound from umax_value however, if negative verifier errors
3930                  * out. Only upper bounds can be learned because retval is an
3931                  * int type and negative retvals are allowed.
3932                  */
3933                 meta->msize_max_value = reg->umax_value;
3934
3935                 /* The register is SCALAR_VALUE; the access check
3936                  * happens using its boundaries.
3937                  */
3938                 if (!tnum_is_const(reg->var_off))
3939                         /* For unprivileged variable accesses, disable raw
3940                          * mode so that the program is required to
3941                          * initialize all the memory that the helper could
3942                          * just partially fill up.
3943                          */
3944                         meta = NULL;
3945
3946                 if (reg->smin_value < 0) {
3947                         verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
3948                                 regno);
3949                         return -EACCES;
3950                 }
3951
3952                 if (reg->umin_value == 0) {
3953                         err = check_helper_mem_access(env, regno - 1, 0,
3954                                                       zero_size_allowed,
3955                                                       meta);
3956                         if (err)
3957                                 return err;
3958                 }
3959
3960                 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
3961                         verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
3962                                 regno);
3963                         return -EACCES;
3964                 }
3965                 err = check_helper_mem_access(env, regno - 1,
3966                                               reg->umax_value,
3967                                               zero_size_allowed, meta);
3968                 if (!err)
3969                         err = mark_chain_precision(env, regno);
3970         } else if (arg_type_is_alloc_size(arg_type)) {
3971                 if (!tnum_is_const(reg->var_off)) {
3972                         verbose(env, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
3973                                 regno);
3974                         return -EACCES;
3975                 }
3976                 meta->mem_size = reg->var_off.value;
3977         } else if (arg_type_is_int_ptr(arg_type)) {
3978                 int size = int_ptr_type_to_size(arg_type);
3979
3980                 err = check_helper_mem_access(env, regno, size, false, meta);
3981                 if (err)
3982                         return err;
3983                 err = check_ptr_alignment(env, reg, 0, size, true);
3984         }
3985
3986         return err;
3987 err_type:
3988         verbose(env, "R%d type=%s expected=%s\n", regno,
3989                 reg_type_str[type], reg_type_str[expected_type]);
3990         return -EACCES;
3991 }
3992
3993 static int check_map_func_compatibility(struct bpf_verifier_env *env,
3994                                         struct bpf_map *map, int func_id)
3995 {
3996         if (!map)
3997                 return 0;
3998
3999         /* We need a two way check, first is from map perspective ... */
4000         switch (map->map_type) {
4001         case BPF_MAP_TYPE_PROG_ARRAY:
4002                 if (func_id != BPF_FUNC_tail_call)
4003                         goto error;
4004                 break;
4005         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4006                 if (func_id != BPF_FUNC_perf_event_read &&
4007                     func_id != BPF_FUNC_perf_event_output &&
4008                     func_id != BPF_FUNC_skb_output &&
4009                     func_id != BPF_FUNC_perf_event_read_value &&
4010                     func_id != BPF_FUNC_xdp_output)
4011                         goto error;
4012                 break;
4013         case BPF_MAP_TYPE_RINGBUF:
4014                 if (func_id != BPF_FUNC_ringbuf_output &&
4015                     func_id != BPF_FUNC_ringbuf_reserve &&
4016                     func_id != BPF_FUNC_ringbuf_submit &&
4017                     func_id != BPF_FUNC_ringbuf_discard &&
4018                     func_id != BPF_FUNC_ringbuf_query)
4019                         goto error;
4020                 break;
4021         case BPF_MAP_TYPE_STACK_TRACE:
4022                 if (func_id != BPF_FUNC_get_stackid)
4023                         goto error;
4024                 break;
4025         case BPF_MAP_TYPE_CGROUP_ARRAY:
4026                 if (func_id != BPF_FUNC_skb_under_cgroup &&
4027                     func_id != BPF_FUNC_current_task_under_cgroup)
4028                         goto error;
4029                 break;
4030         case BPF_MAP_TYPE_CGROUP_STORAGE:
4031         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
4032                 if (func_id != BPF_FUNC_get_local_storage)
4033                         goto error;
4034                 break;
4035         case BPF_MAP_TYPE_DEVMAP:
4036         case BPF_MAP_TYPE_DEVMAP_HASH:
4037                 if (func_id != BPF_FUNC_redirect_map &&
4038                     func_id != BPF_FUNC_map_lookup_elem)
4039                         goto error;
4040                 break;
4041         /* Restrict bpf side of cpumap and xskmap, open when use-cases
4042          * appear.
4043          */
4044         case BPF_MAP_TYPE_CPUMAP:
4045                 if (func_id != BPF_FUNC_redirect_map)
4046                         goto error;
4047                 break;
4048         case BPF_MAP_TYPE_XSKMAP:
4049                 if (func_id != BPF_FUNC_redirect_map &&
4050                     func_id != BPF_FUNC_map_lookup_elem)
4051                         goto error;
4052                 break;
4053         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4054         case BPF_MAP_TYPE_HASH_OF_MAPS:
4055                 if (func_id != BPF_FUNC_map_lookup_elem)
4056                         goto error;
4057                 break;
4058         case BPF_MAP_TYPE_SOCKMAP:
4059                 if (func_id != BPF_FUNC_sk_redirect_map &&
4060                     func_id != BPF_FUNC_sock_map_update &&
4061                     func_id != BPF_FUNC_map_delete_elem &&
4062                     func_id != BPF_FUNC_msg_redirect_map &&
4063                     func_id != BPF_FUNC_sk_select_reuseport &&
4064                     func_id != BPF_FUNC_map_lookup_elem)
4065                         goto error;
4066                 break;
4067         case BPF_MAP_TYPE_SOCKHASH:
4068                 if (func_id != BPF_FUNC_sk_redirect_hash &&
4069                     func_id != BPF_FUNC_sock_hash_update &&
4070                     func_id != BPF_FUNC_map_delete_elem &&
4071                     func_id != BPF_FUNC_msg_redirect_hash &&
4072                     func_id != BPF_FUNC_sk_select_reuseport &&
4073                     func_id != BPF_FUNC_map_lookup_elem)
4074                         goto error;
4075                 break;
4076         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4077                 if (func_id != BPF_FUNC_sk_select_reuseport)
4078                         goto error;
4079                 break;
4080         case BPF_MAP_TYPE_QUEUE:
4081         case BPF_MAP_TYPE_STACK:
4082                 if (func_id != BPF_FUNC_map_peek_elem &&
4083                     func_id != BPF_FUNC_map_pop_elem &&
4084                     func_id != BPF_FUNC_map_push_elem)
4085                         goto error;
4086                 break;
4087         case BPF_MAP_TYPE_SK_STORAGE:
4088                 if (func_id != BPF_FUNC_sk_storage_get &&
4089                     func_id != BPF_FUNC_sk_storage_delete)
4090                         goto error;
4091                 break;
4092         default:
4093                 break;
4094         }
4095
4096         /* ... and second from the function itself. */
4097         switch (func_id) {
4098         case BPF_FUNC_tail_call:
4099                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
4100                         goto error;
4101                 if (env->subprog_cnt > 1) {
4102                         verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
4103                         return -EINVAL;
4104                 }
4105                 break;
4106         case BPF_FUNC_perf_event_read:
4107         case BPF_FUNC_perf_event_output:
4108         case BPF_FUNC_perf_event_read_value:
4109         case BPF_FUNC_skb_output:
4110         case BPF_FUNC_xdp_output:
4111                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
4112                         goto error;
4113                 break;
4114         case BPF_FUNC_get_stackid:
4115                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
4116                         goto error;
4117                 break;
4118         case BPF_FUNC_current_task_under_cgroup:
4119         case BPF_FUNC_skb_under_cgroup:
4120                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
4121                         goto error;
4122                 break;
4123         case BPF_FUNC_redirect_map:
4124                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
4125                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
4126                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
4127                     map->map_type != BPF_MAP_TYPE_XSKMAP)
4128                         goto error;
4129                 break;
4130         case BPF_FUNC_sk_redirect_map:
4131         case BPF_FUNC_msg_redirect_map:
4132         case BPF_FUNC_sock_map_update:
4133                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
4134                         goto error;
4135                 break;
4136         case BPF_FUNC_sk_redirect_hash:
4137         case BPF_FUNC_msg_redirect_hash:
4138         case BPF_FUNC_sock_hash_update:
4139                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
4140                         goto error;
4141                 break;
4142         case BPF_FUNC_get_local_storage:
4143                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
4144                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
4145                         goto error;
4146                 break;
4147         case BPF_FUNC_sk_select_reuseport:
4148                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
4149                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
4150                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
4151                         goto error;
4152                 break;
4153         case BPF_FUNC_map_peek_elem:
4154         case BPF_FUNC_map_pop_elem:
4155         case BPF_FUNC_map_push_elem:
4156                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
4157                     map->map_type != BPF_MAP_TYPE_STACK)
4158                         goto error;
4159                 break;
4160         case BPF_FUNC_sk_storage_get:
4161         case BPF_FUNC_sk_storage_delete:
4162                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
4163                         goto error;
4164                 break;
4165         default:
4166                 break;
4167         }
4168
4169         return 0;
4170 error:
4171         verbose(env, "cannot pass map_type %d into func %s#%d\n",
4172                 map->map_type, func_id_name(func_id), func_id);
4173         return -EINVAL;
4174 }
4175
4176 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
4177 {
4178         int count = 0;
4179
4180         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
4181                 count++;
4182         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
4183                 count++;
4184         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
4185                 count++;
4186         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
4187                 count++;
4188         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
4189                 count++;
4190
4191         /* We only support one arg being in raw mode at the moment,
4192          * which is sufficient for the helper functions we have
4193          * right now.
4194          */
4195         return count <= 1;
4196 }
4197
4198 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
4199                                     enum bpf_arg_type arg_next)
4200 {
4201         return (arg_type_is_mem_ptr(arg_curr) &&
4202                 !arg_type_is_mem_size(arg_next)) ||
4203                (!arg_type_is_mem_ptr(arg_curr) &&
4204                 arg_type_is_mem_size(arg_next));
4205 }
4206
4207 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
4208 {
4209         /* bpf_xxx(..., buf, len) call will access 'len'
4210          * bytes from memory 'buf'. Both arg types need
4211          * to be paired, so make sure there's no buggy
4212          * helper function specification.
4213          */
4214         if (arg_type_is_mem_size(fn->arg1_type) ||
4215             arg_type_is_mem_ptr(fn->arg5_type)  ||
4216             check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
4217             check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
4218             check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
4219             check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
4220                 return false;
4221
4222         return true;
4223 }
4224
4225 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
4226 {
4227         int count = 0;
4228
4229         if (arg_type_may_be_refcounted(fn->arg1_type))
4230                 count++;
4231         if (arg_type_may_be_refcounted(fn->arg2_type))
4232                 count++;
4233         if (arg_type_may_be_refcounted(fn->arg3_type))
4234                 count++;
4235         if (arg_type_may_be_refcounted(fn->arg4_type))
4236                 count++;
4237         if (arg_type_may_be_refcounted(fn->arg5_type))
4238                 count++;
4239
4240         /* A reference acquiring function cannot acquire
4241          * another refcounted ptr.
4242          */
4243         if (may_be_acquire_function(func_id) && count)
4244                 return false;
4245
4246         /* We only support one arg being unreferenced at the moment,
4247          * which is sufficient for the helper functions we have right now.
4248          */
4249         return count <= 1;
4250 }
4251
4252 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
4253 {
4254         return check_raw_mode_ok(fn) &&
4255                check_arg_pair_ok(fn) &&
4256                check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
4257 }
4258
4259 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
4260  * are now invalid, so turn them into unknown SCALAR_VALUE.
4261  */
4262 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
4263                                      struct bpf_func_state *state)
4264 {
4265         struct bpf_reg_state *regs = state->regs, *reg;
4266         int i;
4267
4268         for (i = 0; i < MAX_BPF_REG; i++)
4269                 if (reg_is_pkt_pointer_any(&regs[i]))
4270                         mark_reg_unknown(env, regs, i);
4271
4272         bpf_for_each_spilled_reg(i, state, reg) {
4273                 if (!reg)
4274                         continue;
4275                 if (reg_is_pkt_pointer_any(reg))
4276                         __mark_reg_unknown(env, reg);
4277         }
4278 }
4279
4280 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
4281 {
4282         struct bpf_verifier_state *vstate = env->cur_state;
4283         int i;
4284
4285         for (i = 0; i <= vstate->curframe; i++)
4286                 __clear_all_pkt_pointers(env, vstate->frame[i]);
4287 }
4288
4289 static void release_reg_references(struct bpf_verifier_env *env,
4290                                    struct bpf_func_state *state,
4291                                    int ref_obj_id)
4292 {
4293         struct bpf_reg_state *regs = state->regs, *reg;
4294         int i;
4295
4296         for (i = 0; i < MAX_BPF_REG; i++)
4297                 if (regs[i].ref_obj_id == ref_obj_id)
4298                         mark_reg_unknown(env, regs, i);
4299
4300         bpf_for_each_spilled_reg(i, state, reg) {
4301                 if (!reg)
4302                         continue;
4303                 if (reg->ref_obj_id == ref_obj_id)
4304                         __mark_reg_unknown(env, reg);
4305         }
4306 }
4307
4308 /* The pointer with the specified id has released its reference to kernel
4309  * resources. Identify all copies of the same pointer and clear the reference.
4310  */
4311 static int release_reference(struct bpf_verifier_env *env,
4312                              int ref_obj_id)
4313 {
4314         struct bpf_verifier_state *vstate = env->cur_state;
4315         int err;
4316         int i;
4317
4318         err = release_reference_state(cur_func(env), ref_obj_id);
4319         if (err)
4320                 return err;
4321
4322         for (i = 0; i <= vstate->curframe; i++)
4323                 release_reg_references(env, vstate->frame[i], ref_obj_id);
4324
4325         return 0;
4326 }
4327
4328 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
4329                                     struct bpf_reg_state *regs)
4330 {
4331         int i;
4332
4333         /* after the call registers r0 - r5 were scratched */
4334         for (i = 0; i < CALLER_SAVED_REGS; i++) {
4335                 mark_reg_not_init(env, regs, caller_saved[i]);
4336                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4337         }
4338 }
4339
4340 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
4341                            int *insn_idx)
4342 {
4343         struct bpf_verifier_state *state = env->cur_state;
4344         struct bpf_func_info_aux *func_info_aux;
4345         struct bpf_func_state *caller, *callee;
4346         int i, err, subprog, target_insn;
4347         bool is_global = false;
4348
4349         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
4350                 verbose(env, "the call stack of %d frames is too deep\n",
4351                         state->curframe + 2);
4352                 return -E2BIG;
4353         }
4354
4355         target_insn = *insn_idx + insn->imm;
4356         subprog = find_subprog(env, target_insn + 1);
4357         if (subprog < 0) {
4358                 verbose(env, "verifier bug. No program starts at insn %d\n",
4359                         target_insn + 1);
4360                 return -EFAULT;
4361         }
4362
4363         caller = state->frame[state->curframe];
4364         if (state->frame[state->curframe + 1]) {
4365                 verbose(env, "verifier bug. Frame %d already allocated\n",
4366                         state->curframe + 1);
4367                 return -EFAULT;
4368         }
4369
4370         func_info_aux = env->prog->aux->func_info_aux;
4371         if (func_info_aux)
4372                 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
4373         err = btf_check_func_arg_match(env, subprog, caller->regs);
4374         if (err == -EFAULT)
4375                 return err;
4376         if (is_global) {
4377                 if (err) {
4378                         verbose(env, "Caller passes invalid args into func#%d\n",
4379                                 subprog);
4380                         return err;
4381                 } else {
4382                         if (env->log.level & BPF_LOG_LEVEL)
4383                                 verbose(env,
4384                                         "Func#%d is global and valid. Skipping.\n",
4385                                         subprog);
4386                         clear_caller_saved_regs(env, caller->regs);
4387
4388                         /* All global functions return SCALAR_VALUE */
4389                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
4390
4391                         /* continue with next insn after call */
4392                         return 0;
4393                 }
4394         }
4395
4396         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
4397         if (!callee)
4398                 return -ENOMEM;
4399         state->frame[state->curframe + 1] = callee;
4400
4401         /* callee cannot access r0, r6 - r9 for reading and has to write
4402          * into its own stack before reading from it.
4403          * callee can read/write into caller's stack
4404          */
4405         init_func_state(env, callee,
4406                         /* remember the callsite, it will be used by bpf_exit */
4407                         *insn_idx /* callsite */,
4408                         state->curframe + 1 /* frameno within this callchain */,
4409                         subprog /* subprog number within this prog */);
4410
4411         /* Transfer references to the callee */
4412         err = transfer_reference_state(callee, caller);
4413         if (err)
4414                 return err;
4415
4416         /* copy r1 - r5 args that callee can access.  The copy includes parent
4417          * pointers, which connects us up to the liveness chain
4418          */
4419         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4420                 callee->regs[i] = caller->regs[i];
4421
4422         clear_caller_saved_regs(env, caller->regs);
4423
4424         /* only increment it after check_reg_arg() finished */
4425         state->curframe++;
4426
4427         /* and go analyze first insn of the callee */
4428         *insn_idx = target_insn;
4429
4430         if (env->log.level & BPF_LOG_LEVEL) {
4431                 verbose(env, "caller:\n");
4432                 print_verifier_state(env, caller);
4433                 verbose(env, "callee:\n");
4434                 print_verifier_state(env, callee);
4435         }
4436         return 0;
4437 }
4438
4439 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
4440 {
4441         struct bpf_verifier_state *state = env->cur_state;
4442         struct bpf_func_state *caller, *callee;
4443         struct bpf_reg_state *r0;
4444         int err;
4445
4446         callee = state->frame[state->curframe];
4447         r0 = &callee->regs[BPF_REG_0];
4448         if (r0->type == PTR_TO_STACK) {
4449                 /* technically it's ok to return caller's stack pointer
4450                  * (or caller's caller's pointer) back to the caller,
4451                  * since these pointers are valid. Only current stack
4452                  * pointer will be invalid as soon as function exits,
4453                  * but let's be conservative
4454                  */
4455                 verbose(env, "cannot return stack pointer to the caller\n");
4456                 return -EINVAL;
4457         }
4458
4459         state->curframe--;
4460         caller = state->frame[state->curframe];
4461         /* return to the caller whatever r0 had in the callee */
4462         caller->regs[BPF_REG_0] = *r0;
4463
4464         /* Transfer references to the caller */
4465         err = transfer_reference_state(caller, callee);
4466         if (err)
4467                 return err;
4468
4469         *insn_idx = callee->callsite + 1;
4470         if (env->log.level & BPF_LOG_LEVEL) {
4471                 verbose(env, "returning from callee:\n");
4472                 print_verifier_state(env, callee);
4473                 verbose(env, "to caller at %d:\n", *insn_idx);
4474                 print_verifier_state(env, caller);
4475         }
4476         /* clear everything in the callee */
4477         free_func_state(callee);
4478         state->frame[state->curframe + 1] = NULL;
4479         return 0;
4480 }
4481
4482 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
4483                                    int func_id,
4484                                    struct bpf_call_arg_meta *meta)
4485 {
4486         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
4487
4488         if (ret_type != RET_INTEGER ||
4489             (func_id != BPF_FUNC_get_stack &&
4490              func_id != BPF_FUNC_probe_read_str &&
4491              func_id != BPF_FUNC_probe_read_kernel_str &&
4492              func_id != BPF_FUNC_probe_read_user_str))
4493                 return;
4494
4495         ret_reg->smax_value = meta->msize_max_value;
4496         ret_reg->s32_max_value = meta->msize_max_value;
4497         __reg_deduce_bounds(ret_reg);
4498         __reg_bound_offset(ret_reg);
4499         __update_reg_bounds(ret_reg);
4500 }
4501
4502 static int
4503 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4504                 int func_id, int insn_idx)
4505 {
4506         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
4507         struct bpf_map *map = meta->map_ptr;
4508
4509         if (func_id != BPF_FUNC_tail_call &&
4510             func_id != BPF_FUNC_map_lookup_elem &&
4511             func_id != BPF_FUNC_map_update_elem &&
4512             func_id != BPF_FUNC_map_delete_elem &&
4513             func_id != BPF_FUNC_map_push_elem &&
4514             func_id != BPF_FUNC_map_pop_elem &&
4515             func_id != BPF_FUNC_map_peek_elem)
4516                 return 0;
4517
4518         if (map == NULL) {
4519                 verbose(env, "kernel subsystem misconfigured verifier\n");
4520                 return -EINVAL;
4521         }
4522
4523         /* In case of read-only, some additional restrictions
4524          * need to be applied in order to prevent altering the
4525          * state of the map from program side.
4526          */
4527         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
4528             (func_id == BPF_FUNC_map_delete_elem ||
4529              func_id == BPF_FUNC_map_update_elem ||
4530              func_id == BPF_FUNC_map_push_elem ||
4531              func_id == BPF_FUNC_map_pop_elem)) {
4532                 verbose(env, "write into map forbidden\n");
4533                 return -EACCES;
4534         }
4535
4536         if (!BPF_MAP_PTR(aux->map_ptr_state))
4537                 bpf_map_ptr_store(aux, meta->map_ptr,
4538                                   !meta->map_ptr->bypass_spec_v1);
4539         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
4540                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
4541                                   !meta->map_ptr->bypass_spec_v1);
4542         return 0;
4543 }
4544
4545 static int
4546 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
4547                 int func_id, int insn_idx)
4548 {
4549         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
4550         struct bpf_reg_state *regs = cur_regs(env), *reg;
4551         struct bpf_map *map = meta->map_ptr;
4552         struct tnum range;
4553         u64 val;
4554         int err;
4555
4556         if (func_id != BPF_FUNC_tail_call)
4557                 return 0;
4558         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
4559                 verbose(env, "kernel subsystem misconfigured verifier\n");
4560                 return -EINVAL;
4561         }
4562
4563         range = tnum_range(0, map->max_entries - 1);
4564         reg = &regs[BPF_REG_3];
4565
4566         if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
4567                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4568                 return 0;
4569         }
4570
4571         err = mark_chain_precision(env, BPF_REG_3);
4572         if (err)
4573                 return err;
4574
4575         val = reg->var_off.value;
4576         if (bpf_map_key_unseen(aux))
4577                 bpf_map_key_store(aux, val);
4578         else if (!bpf_map_key_poisoned(aux) &&
4579                   bpf_map_key_immediate(aux) != val)
4580                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
4581         return 0;
4582 }
4583
4584 static int check_reference_leak(struct bpf_verifier_env *env)
4585 {
4586         struct bpf_func_state *state = cur_func(env);
4587         int i;
4588
4589         for (i = 0; i < state->acquired_refs; i++) {
4590                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
4591                         state->refs[i].id, state->refs[i].insn_idx);
4592         }
4593         return state->acquired_refs ? -EINVAL : 0;
4594 }
4595
4596 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
4597 {
4598         const struct bpf_func_proto *fn = NULL;
4599         struct bpf_reg_state *regs;
4600         struct bpf_call_arg_meta meta;
4601         bool changes_data;
4602         int i, err;
4603
4604         /* find function prototype */
4605         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
4606                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
4607                         func_id);
4608                 return -EINVAL;
4609         }
4610
4611         if (env->ops->get_func_proto)
4612                 fn = env->ops->get_func_proto(func_id, env->prog);
4613         if (!fn) {
4614                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
4615                         func_id);
4616                 return -EINVAL;
4617         }
4618
4619         /* eBPF programs must be GPL compatible to use GPL-ed functions */
4620         if (!env->prog->gpl_compatible && fn->gpl_only) {
4621                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
4622                 return -EINVAL;
4623         }
4624
4625         /* With LD_ABS/IND some JITs save/restore skb from r1. */
4626         changes_data = bpf_helper_changes_pkt_data(fn->func);
4627         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
4628                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
4629                         func_id_name(func_id), func_id);
4630                 return -EINVAL;
4631         }
4632
4633         memset(&meta, 0, sizeof(meta));
4634         meta.pkt_access = fn->pkt_access;
4635
4636         err = check_func_proto(fn, func_id);
4637         if (err) {
4638                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
4639                         func_id_name(func_id), func_id);
4640                 return err;
4641         }
4642
4643         meta.func_id = func_id;
4644         /* check args */
4645         for (i = 0; i < 5; i++) {
4646                 err = btf_resolve_helper_id(&env->log, fn, i);
4647                 if (err > 0)
4648                         meta.btf_id = err;
4649                 err = check_func_arg(env, BPF_REG_1 + i, fn->arg_type[i], &meta);
4650                 if (err)
4651                         return err;
4652         }
4653
4654         err = record_func_map(env, &meta, func_id, insn_idx);
4655         if (err)
4656                 return err;
4657
4658         err = record_func_key(env, &meta, func_id, insn_idx);
4659         if (err)
4660                 return err;
4661
4662         /* Mark slots with STACK_MISC in case of raw mode, stack offset
4663          * is inferred from register state.
4664          */
4665         for (i = 0; i < meta.access_size; i++) {
4666                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
4667                                        BPF_WRITE, -1, false);
4668                 if (err)
4669                         return err;
4670         }
4671
4672         if (func_id == BPF_FUNC_tail_call) {
4673                 err = check_reference_leak(env);
4674                 if (err) {
4675                         verbose(env, "tail_call would lead to reference leak\n");
4676                         return err;
4677                 }
4678         } else if (is_release_function(func_id)) {
4679                 err = release_reference(env, meta.ref_obj_id);
4680                 if (err) {
4681                         verbose(env, "func %s#%d reference has not been acquired before\n",
4682                                 func_id_name(func_id), func_id);
4683                         return err;
4684                 }
4685         }
4686
4687         regs = cur_regs(env);
4688
4689         /* check that flags argument in get_local_storage(map, flags) is 0,
4690          * this is required because get_local_storage() can't return an error.
4691          */
4692         if (func_id == BPF_FUNC_get_local_storage &&
4693             !register_is_null(&regs[BPF_REG_2])) {
4694                 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
4695                 return -EINVAL;
4696         }
4697
4698         /* reset caller saved regs */
4699         for (i = 0; i < CALLER_SAVED_REGS; i++) {
4700                 mark_reg_not_init(env, regs, caller_saved[i]);
4701                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4702         }
4703
4704         /* helper call returns 64-bit value. */
4705         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
4706
4707         /* update return register (already marked as written above) */
4708         if (fn->ret_type == RET_INTEGER) {
4709                 /* sets type to SCALAR_VALUE */
4710                 mark_reg_unknown(env, regs, BPF_REG_0);
4711         } else if (fn->ret_type == RET_VOID) {
4712                 regs[BPF_REG_0].type = NOT_INIT;
4713         } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
4714                    fn->ret_type == RET_PTR_TO_MAP_VALUE) {
4715                 /* There is no offset yet applied, variable or fixed */
4716                 mark_reg_known_zero(env, regs, BPF_REG_0);
4717                 /* remember map_ptr, so that check_map_access()
4718                  * can check 'value_size' boundary of memory access
4719                  * to map element returned from bpf_map_lookup_elem()
4720                  */
4721                 if (meta.map_ptr == NULL) {
4722                         verbose(env,
4723                                 "kernel subsystem misconfigured verifier\n");
4724                         return -EINVAL;
4725                 }
4726                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
4727                 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
4728                         regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
4729                         if (map_value_has_spin_lock(meta.map_ptr))
4730                                 regs[BPF_REG_0].id = ++env->id_gen;
4731                 } else {
4732                         regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
4733                         regs[BPF_REG_0].id = ++env->id_gen;
4734                 }
4735         } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
4736                 mark_reg_known_zero(env, regs, BPF_REG_0);
4737                 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
4738                 regs[BPF_REG_0].id = ++env->id_gen;
4739         } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
4740                 mark_reg_known_zero(env, regs, BPF_REG_0);
4741                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
4742                 regs[BPF_REG_0].id = ++env->id_gen;
4743         } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
4744                 mark_reg_known_zero(env, regs, BPF_REG_0);
4745                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
4746                 regs[BPF_REG_0].id = ++env->id_gen;
4747         } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
4748                 mark_reg_known_zero(env, regs, BPF_REG_0);
4749                 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
4750                 regs[BPF_REG_0].id = ++env->id_gen;
4751                 regs[BPF_REG_0].mem_size = meta.mem_size;
4752         } else {
4753                 verbose(env, "unknown return type %d of func %s#%d\n",
4754                         fn->ret_type, func_id_name(func_id), func_id);
4755                 return -EINVAL;
4756         }
4757
4758         if (is_ptr_cast_function(func_id)) {
4759                 /* For release_reference() */
4760                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
4761         } else if (is_acquire_function(func_id, meta.map_ptr)) {
4762                 int id = acquire_reference_state(env, insn_idx);
4763
4764                 if (id < 0)
4765                         return id;
4766                 /* For mark_ptr_or_null_reg() */
4767                 regs[BPF_REG_0].id = id;
4768                 /* For release_reference() */
4769                 regs[BPF_REG_0].ref_obj_id = id;
4770         }
4771
4772         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
4773
4774         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
4775         if (err)
4776                 return err;
4777
4778         if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) {
4779                 const char *err_str;
4780
4781 #ifdef CONFIG_PERF_EVENTS
4782                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
4783                 err_str = "cannot get callchain buffer for func %s#%d\n";
4784 #else
4785                 err = -ENOTSUPP;
4786                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
4787 #endif
4788                 if (err) {
4789                         verbose(env, err_str, func_id_name(func_id), func_id);
4790                         return err;
4791                 }
4792
4793                 env->prog->has_callchain_buf = true;
4794         }
4795
4796         if (changes_data)
4797                 clear_all_pkt_pointers(env);
4798         return 0;
4799 }
4800
4801 static bool signed_add_overflows(s64 a, s64 b)
4802 {
4803         /* Do the add in u64, where overflow is well-defined */
4804         s64 res = (s64)((u64)a + (u64)b);
4805
4806         if (b < 0)
4807                 return res > a;
4808         return res < a;
4809 }
4810
4811 static bool signed_add32_overflows(s64 a, s64 b)
4812 {
4813         /* Do the add in u32, where overflow is well-defined */
4814         s32 res = (s32)((u32)a + (u32)b);
4815
4816         if (b < 0)
4817                 return res > a;
4818         return res < a;
4819 }
4820
4821 static bool signed_sub_overflows(s32 a, s32 b)
4822 {
4823         /* Do the sub in u64, where overflow is well-defined */
4824         s64 res = (s64)((u64)a - (u64)b);
4825
4826         if (b < 0)
4827                 return res < a;
4828         return res > a;
4829 }
4830
4831 static bool signed_sub32_overflows(s32 a, s32 b)
4832 {
4833         /* Do the sub in u64, where overflow is well-defined */
4834         s32 res = (s32)((u32)a - (u32)b);
4835
4836         if (b < 0)
4837                 return res < a;
4838         return res > a;
4839 }
4840
4841 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
4842                                   const struct bpf_reg_state *reg,
4843                                   enum bpf_reg_type type)
4844 {
4845         bool known = tnum_is_const(reg->var_off);
4846         s64 val = reg->var_off.value;
4847         s64 smin = reg->smin_value;
4848
4849         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
4850                 verbose(env, "math between %s pointer and %lld is not allowed\n",
4851                         reg_type_str[type], val);
4852                 return false;
4853         }
4854
4855         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
4856                 verbose(env, "%s pointer offset %d is not allowed\n",
4857                         reg_type_str[type], reg->off);
4858                 return false;
4859         }
4860
4861         if (smin == S64_MIN) {
4862                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
4863                         reg_type_str[type]);
4864                 return false;
4865         }
4866
4867         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
4868                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
4869                         smin, reg_type_str[type]);
4870                 return false;
4871         }
4872
4873         return true;
4874 }
4875
4876 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
4877 {
4878         return &env->insn_aux_data[env->insn_idx];
4879 }
4880
4881 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
4882                               u32 *ptr_limit, u8 opcode, bool off_is_neg)
4883 {
4884         bool mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
4885                             (opcode == BPF_SUB && !off_is_neg);
4886         u32 off;
4887
4888         switch (ptr_reg->type) {
4889         case PTR_TO_STACK:
4890                 /* Indirect variable offset stack access is prohibited in
4891                  * unprivileged mode so it's not handled here.
4892                  */
4893                 off = ptr_reg->off + ptr_reg->var_off.value;
4894                 if (mask_to_left)
4895                         *ptr_limit = MAX_BPF_STACK + off;
4896                 else
4897                         *ptr_limit = -off;
4898                 return 0;
4899         case PTR_TO_MAP_VALUE:
4900                 if (mask_to_left) {
4901                         *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
4902                 } else {
4903                         off = ptr_reg->smin_value + ptr_reg->off;
4904                         *ptr_limit = ptr_reg->map_ptr->value_size - off;
4905                 }
4906                 return 0;
4907         default:
4908                 return -EINVAL;
4909         }
4910 }
4911
4912 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
4913                                     const struct bpf_insn *insn)
4914 {
4915         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
4916 }
4917
4918 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
4919                                        u32 alu_state, u32 alu_limit)
4920 {
4921         /* If we arrived here from different branches with different
4922          * state or limits to sanitize, then this won't work.
4923          */
4924         if (aux->alu_state &&
4925             (aux->alu_state != alu_state ||
4926              aux->alu_limit != alu_limit))
4927                 return -EACCES;
4928
4929         /* Corresponding fixup done in fixup_bpf_calls(). */
4930         aux->alu_state = alu_state;
4931         aux->alu_limit = alu_limit;
4932         return 0;
4933 }
4934
4935 static int sanitize_val_alu(struct bpf_verifier_env *env,
4936                             struct bpf_insn *insn)
4937 {
4938         struct bpf_insn_aux_data *aux = cur_aux(env);
4939
4940         if (can_skip_alu_sanitation(env, insn))
4941                 return 0;
4942
4943         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
4944 }
4945
4946 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
4947                             struct bpf_insn *insn,
4948                             const struct bpf_reg_state *ptr_reg,
4949                             struct bpf_reg_state *dst_reg,
4950                             bool off_is_neg)
4951 {
4952         struct bpf_verifier_state *vstate = env->cur_state;
4953         struct bpf_insn_aux_data *aux = cur_aux(env);
4954         bool ptr_is_dst_reg = ptr_reg == dst_reg;
4955         u8 opcode = BPF_OP(insn->code);
4956         u32 alu_state, alu_limit;
4957         struct bpf_reg_state tmp;
4958         bool ret;
4959
4960         if (can_skip_alu_sanitation(env, insn))
4961                 return 0;
4962
4963         /* We already marked aux for masking from non-speculative
4964          * paths, thus we got here in the first place. We only care
4965          * to explore bad access from here.
4966          */
4967         if (vstate->speculative)
4968                 goto do_sim;
4969
4970         alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
4971         alu_state |= ptr_is_dst_reg ?
4972                      BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
4973
4974         if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
4975                 return 0;
4976         if (update_alu_sanitation_state(aux, alu_state, alu_limit))
4977                 return -EACCES;
4978 do_sim:
4979         /* Simulate and find potential out-of-bounds access under
4980          * speculative execution from truncation as a result of
4981          * masking when off was not within expected range. If off
4982          * sits in dst, then we temporarily need to move ptr there
4983          * to simulate dst (== 0) +/-= ptr. Needed, for example,
4984          * for cases where we use K-based arithmetic in one direction
4985          * and truncated reg-based in the other in order to explore
4986          * bad access.
4987          */
4988         if (!ptr_is_dst_reg) {
4989                 tmp = *dst_reg;
4990                 *dst_reg = *ptr_reg;
4991         }
4992         ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
4993         if (!ptr_is_dst_reg && ret)
4994                 *dst_reg = tmp;
4995         return !ret ? -EFAULT : 0;
4996 }
4997
4998 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
4999  * Caller should also handle BPF_MOV case separately.
5000  * If we return -EACCES, caller may want to try again treating pointer as a
5001  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
5002  */
5003 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
5004                                    struct bpf_insn *insn,
5005                                    const struct bpf_reg_state *ptr_reg,
5006                                    const struct bpf_reg_state *off_reg)
5007 {
5008         struct bpf_verifier_state *vstate = env->cur_state;
5009         struct bpf_func_state *state = vstate->frame[vstate->curframe];
5010         struct bpf_reg_state *regs = state->regs, *dst_reg;
5011         bool known = tnum_is_const(off_reg->var_off);
5012         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
5013             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
5014         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
5015             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
5016         u32 dst = insn->dst_reg, src = insn->src_reg;
5017         u8 opcode = BPF_OP(insn->code);
5018         int ret;
5019
5020         dst_reg = &regs[dst];
5021
5022         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
5023             smin_val > smax_val || umin_val > umax_val) {
5024                 /* Taint dst register if offset had invalid bounds derived from
5025                  * e.g. dead branches.
5026                  */
5027                 __mark_reg_unknown(env, dst_reg);
5028                 return 0;
5029         }
5030
5031         if (BPF_CLASS(insn->code) != BPF_ALU64) {
5032                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
5033                 verbose(env,
5034                         "R%d 32-bit pointer arithmetic prohibited\n",
5035                         dst);
5036                 return -EACCES;
5037         }
5038
5039         switch (ptr_reg->type) {
5040         case PTR_TO_MAP_VALUE_OR_NULL:
5041                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
5042                         dst, reg_type_str[ptr_reg->type]);
5043                 return -EACCES;
5044         case CONST_PTR_TO_MAP:
5045         case PTR_TO_PACKET_END:
5046         case PTR_TO_SOCKET:
5047         case PTR_TO_SOCKET_OR_NULL:
5048         case PTR_TO_SOCK_COMMON:
5049         case PTR_TO_SOCK_COMMON_OR_NULL:
5050         case PTR_TO_TCP_SOCK:
5051         case PTR_TO_TCP_SOCK_OR_NULL:
5052         case PTR_TO_XDP_SOCK:
5053                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
5054                         dst, reg_type_str[ptr_reg->type]);
5055                 return -EACCES;
5056         case PTR_TO_MAP_VALUE:
5057                 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
5058                         verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
5059                                 off_reg == dst_reg ? dst : src);
5060                         return -EACCES;
5061                 }
5062                 /* fall-through */
5063         default:
5064                 break;
5065         }
5066
5067         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
5068          * The id may be overwritten later if we create a new variable offset.
5069          */
5070         dst_reg->type = ptr_reg->type;
5071         dst_reg->id = ptr_reg->id;
5072
5073         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
5074             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
5075                 return -EINVAL;
5076
5077         /* pointer types do not carry 32-bit bounds at the moment. */
5078         __mark_reg32_unbounded(dst_reg);
5079
5080         switch (opcode) {
5081         case BPF_ADD:
5082                 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
5083                 if (ret < 0) {
5084                         verbose(env, "R%d tried to add from different maps or paths\n", dst);
5085                         return ret;
5086                 }
5087                 /* We can take a fixed offset as long as it doesn't overflow
5088                  * the s32 'off' field
5089                  */
5090                 if (known && (ptr_reg->off + smin_val ==
5091                               (s64)(s32)(ptr_reg->off + smin_val))) {
5092                         /* pointer += K.  Accumulate it into fixed offset */
5093                         dst_reg->smin_value = smin_ptr;
5094                         dst_reg->smax_value = smax_ptr;
5095                         dst_reg->umin_value = umin_ptr;
5096                         dst_reg->umax_value = umax_ptr;
5097                         dst_reg->var_off = ptr_reg->var_off;
5098                         dst_reg->off = ptr_reg->off + smin_val;
5099                         dst_reg->raw = ptr_reg->raw;
5100                         break;
5101                 }
5102                 /* A new variable offset is created.  Note that off_reg->off
5103                  * == 0, since it's a scalar.
5104                  * dst_reg gets the pointer type and since some positive
5105                  * integer value was added to the pointer, give it a new 'id'
5106                  * if it's a PTR_TO_PACKET.
5107                  * this creates a new 'base' pointer, off_reg (variable) gets
5108                  * added into the variable offset, and we copy the fixed offset
5109                  * from ptr_reg.
5110                  */
5111                 if (signed_add_overflows(smin_ptr, smin_val) ||
5112                     signed_add_overflows(smax_ptr, smax_val)) {
5113                         dst_reg->smin_value = S64_MIN;
5114                         dst_reg->smax_value = S64_MAX;
5115                 } else {
5116                         dst_reg->smin_value = smin_ptr + smin_val;
5117                         dst_reg->smax_value = smax_ptr + smax_val;
5118                 }
5119                 if (umin_ptr + umin_val < umin_ptr ||
5120                     umax_ptr + umax_val < umax_ptr) {
5121                         dst_reg->umin_value = 0;
5122                         dst_reg->umax_value = U64_MAX;
5123                 } else {
5124                         dst_reg->umin_value = umin_ptr + umin_val;
5125                         dst_reg->umax_value = umax_ptr + umax_val;
5126                 }
5127                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
5128                 dst_reg->off = ptr_reg->off;
5129                 dst_reg->raw = ptr_reg->raw;
5130                 if (reg_is_pkt_pointer(ptr_reg)) {
5131                         dst_reg->id = ++env->id_gen;
5132                         /* something was added to pkt_ptr, set range to zero */
5133                         dst_reg->raw = 0;
5134                 }
5135                 break;
5136         case BPF_SUB:
5137                 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
5138                 if (ret < 0) {
5139                         verbose(env, "R%d tried to sub from different maps or paths\n", dst);
5140                         return ret;
5141                 }
5142                 if (dst_reg == off_reg) {
5143                         /* scalar -= pointer.  Creates an unknown scalar */
5144                         verbose(env, "R%d tried to subtract pointer from scalar\n",
5145                                 dst);
5146                         return -EACCES;
5147                 }
5148                 /* We don't allow subtraction from FP, because (according to
5149                  * test_verifier.c test "invalid fp arithmetic", JITs might not
5150                  * be able to deal with it.
5151                  */
5152                 if (ptr_reg->type == PTR_TO_STACK) {
5153                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
5154                                 dst);
5155                         return -EACCES;
5156                 }
5157                 if (known && (ptr_reg->off - smin_val ==
5158                               (s64)(s32)(ptr_reg->off - smin_val))) {
5159                         /* pointer -= K.  Subtract it from fixed offset */
5160                         dst_reg->smin_value = smin_ptr;
5161                         dst_reg->smax_value = smax_ptr;
5162                         dst_reg->umin_value = umin_ptr;
5163                         dst_reg->umax_value = umax_ptr;
5164                         dst_reg->var_off = ptr_reg->var_off;
5165                         dst_reg->id = ptr_reg->id;
5166                         dst_reg->off = ptr_reg->off - smin_val;
5167                         dst_reg->raw = ptr_reg->raw;
5168                         break;
5169                 }
5170                 /* A new variable offset is created.  If the subtrahend is known
5171                  * nonnegative, then any reg->range we had before is still good.
5172                  */
5173                 if (signed_sub_overflows(smin_ptr, smax_val) ||
5174                     signed_sub_overflows(smax_ptr, smin_val)) {
5175                         /* Overflow possible, we know nothing */
5176                         dst_reg->smin_value = S64_MIN;
5177                         dst_reg->smax_value = S64_MAX;
5178                 } else {
5179                         dst_reg->smin_value = smin_ptr - smax_val;
5180                         dst_reg->smax_value = smax_ptr - smin_val;
5181                 }
5182                 if (umin_ptr < umax_val) {
5183                         /* Overflow possible, we know nothing */
5184                         dst_reg->umin_value = 0;
5185                         dst_reg->umax_value = U64_MAX;
5186                 } else {
5187                         /* Cannot overflow (as long as bounds are consistent) */
5188                         dst_reg->umin_value = umin_ptr - umax_val;
5189                         dst_reg->umax_value = umax_ptr - umin_val;
5190                 }
5191                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
5192                 dst_reg->off = ptr_reg->off;
5193                 dst_reg->raw = ptr_reg->raw;
5194                 if (reg_is_pkt_pointer(ptr_reg)) {
5195                         dst_reg->id = ++env->id_gen;
5196                         /* something was added to pkt_ptr, set range to zero */
5197                         if (smin_val < 0)
5198                                 dst_reg->raw = 0;
5199                 }
5200                 break;
5201         case BPF_AND:
5202         case BPF_OR:
5203         case BPF_XOR:
5204                 /* bitwise ops on pointers are troublesome, prohibit. */
5205                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
5206                         dst, bpf_alu_string[opcode >> 4]);
5207                 return -EACCES;
5208         default:
5209                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
5210                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
5211                         dst, bpf_alu_string[opcode >> 4]);
5212                 return -EACCES;
5213         }
5214
5215         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
5216                 return -EINVAL;
5217
5218         __update_reg_bounds(dst_reg);
5219         __reg_deduce_bounds(dst_reg);
5220         __reg_bound_offset(dst_reg);
5221
5222         /* For unprivileged we require that resulting offset must be in bounds
5223          * in order to be able to sanitize access later on.
5224          */
5225         if (!env->bypass_spec_v1) {
5226                 if (dst_reg->type == PTR_TO_MAP_VALUE &&
5227                     check_map_access(env, dst, dst_reg->off, 1, false)) {
5228                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
5229                                 "prohibited for !root\n", dst);
5230                         return -EACCES;
5231                 } else if (dst_reg->type == PTR_TO_STACK &&
5232                            check_stack_access(env, dst_reg, dst_reg->off +
5233                                               dst_reg->var_off.value, 1)) {
5234                         verbose(env, "R%d stack pointer arithmetic goes out of range, "
5235                                 "prohibited for !root\n", dst);
5236                         return -EACCES;
5237                 }
5238         }
5239
5240         return 0;
5241 }
5242
5243 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
5244                                  struct bpf_reg_state *src_reg)
5245 {
5246         s32 smin_val = src_reg->s32_min_value;
5247         s32 smax_val = src_reg->s32_max_value;
5248         u32 umin_val = src_reg->u32_min_value;
5249         u32 umax_val = src_reg->u32_max_value;
5250
5251         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
5252             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
5253                 dst_reg->s32_min_value = S32_MIN;
5254                 dst_reg->s32_max_value = S32_MAX;
5255         } else {
5256                 dst_reg->s32_min_value += smin_val;
5257                 dst_reg->s32_max_value += smax_val;
5258         }
5259         if (dst_reg->u32_min_value + umin_val < umin_val ||
5260             dst_reg->u32_max_value + umax_val < umax_val) {
5261                 dst_reg->u32_min_value = 0;
5262                 dst_reg->u32_max_value = U32_MAX;
5263         } else {
5264                 dst_reg->u32_min_value += umin_val;
5265                 dst_reg->u32_max_value += umax_val;
5266         }
5267 }
5268
5269 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
5270                                struct bpf_reg_state *src_reg)
5271 {
5272         s64 smin_val = src_reg->smin_value;
5273         s64 smax_val = src_reg->smax_value;
5274         u64 umin_val = src_reg->umin_value;
5275         u64 umax_val = src_reg->umax_value;
5276
5277         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
5278             signed_add_overflows(dst_reg->smax_value, smax_val)) {
5279                 dst_reg->smin_value = S64_MIN;
5280                 dst_reg->smax_value = S64_MAX;
5281         } else {
5282                 dst_reg->smin_value += smin_val;
5283                 dst_reg->smax_value += smax_val;
5284         }
5285         if (dst_reg->umin_value + umin_val < umin_val ||
5286             dst_reg->umax_value + umax_val < umax_val) {
5287                 dst_reg->umin_value = 0;
5288                 dst_reg->umax_value = U64_MAX;
5289         } else {
5290                 dst_reg->umin_value += umin_val;
5291                 dst_reg->umax_value += umax_val;
5292         }
5293 }
5294
5295 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
5296                                  struct bpf_reg_state *src_reg)
5297 {
5298         s32 smin_val = src_reg->s32_min_value;
5299         s32 smax_val = src_reg->s32_max_value;
5300         u32 umin_val = src_reg->u32_min_value;
5301         u32 umax_val = src_reg->u32_max_value;
5302
5303         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
5304             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
5305                 /* Overflow possible, we know nothing */
5306                 dst_reg->s32_min_value = S32_MIN;
5307                 dst_reg->s32_max_value = S32_MAX;
5308         } else {
5309                 dst_reg->s32_min_value -= smax_val;
5310                 dst_reg->s32_max_value -= smin_val;
5311         }
5312         if (dst_reg->u32_min_value < umax_val) {
5313                 /* Overflow possible, we know nothing */
5314                 dst_reg->u32_min_value = 0;
5315                 dst_reg->u32_max_value = U32_MAX;
5316         } else {
5317                 /* Cannot overflow (as long as bounds are consistent) */
5318                 dst_reg->u32_min_value -= umax_val;
5319                 dst_reg->u32_max_value -= umin_val;
5320         }
5321 }
5322
5323 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
5324                                struct bpf_reg_state *src_reg)
5325 {
5326         s64 smin_val = src_reg->smin_value;
5327         s64 smax_val = src_reg->smax_value;
5328         u64 umin_val = src_reg->umin_value;
5329         u64 umax_val = src_reg->umax_value;
5330
5331         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
5332             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
5333                 /* Overflow possible, we know nothing */
5334                 dst_reg->smin_value = S64_MIN;
5335                 dst_reg->smax_value = S64_MAX;
5336         } else {
5337                 dst_reg->smin_value -= smax_val;
5338                 dst_reg->smax_value -= smin_val;
5339         }
5340         if (dst_reg->umin_value < umax_val) {
5341                 /* Overflow possible, we know nothing */
5342                 dst_reg->umin_value = 0;
5343                 dst_reg->umax_value = U64_MAX;
5344         } else {
5345                 /* Cannot overflow (as long as bounds are consistent) */
5346                 dst_reg->umin_value -= umax_val;
5347                 dst_reg->umax_value -= umin_val;
5348         }
5349 }
5350
5351 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
5352                                  struct bpf_reg_state *src_reg)
5353 {
5354         s32 smin_val = src_reg->s32_min_value;
5355         u32 umin_val = src_reg->u32_min_value;
5356         u32 umax_val = src_reg->u32_max_value;
5357
5358         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
5359                 /* Ain't nobody got time to multiply that sign */
5360                 __mark_reg32_unbounded(dst_reg);
5361                 return;
5362         }
5363         /* Both values are positive, so we can work with unsigned and
5364          * copy the result to signed (unless it exceeds S32_MAX).
5365          */
5366         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
5367                 /* Potential overflow, we know nothing */
5368                 __mark_reg32_unbounded(dst_reg);
5369                 return;
5370         }
5371         dst_reg->u32_min_value *= umin_val;
5372         dst_reg->u32_max_value *= umax_val;
5373         if (dst_reg->u32_max_value > S32_MAX) {
5374                 /* Overflow possible, we know nothing */
5375                 dst_reg->s32_min_value = S32_MIN;
5376                 dst_reg->s32_max_value = S32_MAX;
5377         } else {
5378                 dst_reg->s32_min_value = dst_reg->u32_min_value;
5379                 dst_reg->s32_max_value = dst_reg->u32_max_value;
5380         }
5381 }
5382
5383 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
5384                                struct bpf_reg_state *src_reg)
5385 {
5386         s64 smin_val = src_reg->smin_value;
5387         u64 umin_val = src_reg->umin_value;
5388         u64 umax_val = src_reg->umax_value;
5389
5390         if (smin_val < 0 || dst_reg->smin_value < 0) {
5391                 /* Ain't nobody got time to multiply that sign */
5392                 __mark_reg64_unbounded(dst_reg);
5393                 return;
5394         }
5395         /* Both values are positive, so we can work with unsigned and
5396          * copy the result to signed (unless it exceeds S64_MAX).
5397          */
5398         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
5399                 /* Potential overflow, we know nothing */
5400                 __mark_reg64_unbounded(dst_reg);
5401                 return;
5402         }
5403         dst_reg->umin_value *= umin_val;
5404         dst_reg->umax_value *= umax_val;
5405         if (dst_reg->umax_value > S64_MAX) {
5406                 /* Overflow possible, we know nothing */
5407                 dst_reg->smin_value = S64_MIN;
5408                 dst_reg->smax_value = S64_MAX;
5409         } else {
5410                 dst_reg->smin_value = dst_reg->umin_value;
5411                 dst_reg->smax_value = dst_reg->umax_value;
5412         }
5413 }
5414
5415 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
5416                                  struct bpf_reg_state *src_reg)
5417 {
5418         bool src_known = tnum_subreg_is_const(src_reg->var_off);
5419         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5420         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5421         s32 smin_val = src_reg->s32_min_value;
5422         u32 umax_val = src_reg->u32_max_value;
5423
5424         /* Assuming scalar64_min_max_and will be called so its safe
5425          * to skip updating register for known 32-bit case.
5426          */
5427         if (src_known && dst_known)
5428                 return;
5429
5430         /* We get our minimum from the var_off, since that's inherently
5431          * bitwise.  Our maximum is the minimum of the operands' maxima.
5432          */
5433         dst_reg->u32_min_value = var32_off.value;
5434         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
5435         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
5436                 /* Lose signed bounds when ANDing negative numbers,
5437                  * ain't nobody got time for that.
5438                  */
5439                 dst_reg->s32_min_value = S32_MIN;
5440                 dst_reg->s32_max_value = S32_MAX;
5441         } else {
5442                 /* ANDing two positives gives a positive, so safe to
5443                  * cast result into s64.
5444                  */
5445                 dst_reg->s32_min_value = dst_reg->u32_min_value;
5446                 dst_reg->s32_max_value = dst_reg->u32_max_value;
5447         }
5448
5449 }
5450
5451 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
5452                                struct bpf_reg_state *src_reg)
5453 {
5454         bool src_known = tnum_is_const(src_reg->var_off);
5455         bool dst_known = tnum_is_const(dst_reg->var_off);
5456         s64 smin_val = src_reg->smin_value;
5457         u64 umax_val = src_reg->umax_value;
5458
5459         if (src_known && dst_known) {
5460                 __mark_reg_known(dst_reg, dst_reg->var_off.value &
5461                                           src_reg->var_off.value);
5462                 return;
5463         }
5464
5465         /* We get our minimum from the var_off, since that's inherently
5466          * bitwise.  Our maximum is the minimum of the operands' maxima.
5467          */
5468         dst_reg->umin_value = dst_reg->var_off.value;
5469         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
5470         if (dst_reg->smin_value < 0 || smin_val < 0) {
5471                 /* Lose signed bounds when ANDing negative numbers,
5472                  * ain't nobody got time for that.
5473                  */
5474                 dst_reg->smin_value = S64_MIN;
5475                 dst_reg->smax_value = S64_MAX;
5476         } else {
5477                 /* ANDing two positives gives a positive, so safe to
5478                  * cast result into s64.
5479                  */
5480                 dst_reg->smin_value = dst_reg->umin_value;
5481                 dst_reg->smax_value = dst_reg->umax_value;
5482         }
5483         /* We may learn something more from the var_off */
5484         __update_reg_bounds(dst_reg);
5485 }
5486
5487 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
5488                                 struct bpf_reg_state *src_reg)
5489 {
5490         bool src_known = tnum_subreg_is_const(src_reg->var_off);
5491         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
5492         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5493         s32 smin_val = src_reg->smin_value;
5494         u32 umin_val = src_reg->umin_value;
5495
5496         /* Assuming scalar64_min_max_or will be called so it is safe
5497          * to skip updating register for known case.
5498          */
5499         if (src_known && dst_known)
5500                 return;
5501
5502         /* We get our maximum from the var_off, and our minimum is the
5503          * maximum of the operands' minima
5504          */
5505         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
5506         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
5507         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
5508                 /* Lose signed bounds when ORing negative numbers,
5509                  * ain't nobody got time for that.
5510                  */
5511                 dst_reg->s32_min_value = S32_MIN;
5512                 dst_reg->s32_max_value = S32_MAX;
5513         } else {
5514                 /* ORing two positives gives a positive, so safe to
5515                  * cast result into s64.
5516                  */
5517                 dst_reg->s32_min_value = dst_reg->umin_value;
5518                 dst_reg->s32_max_value = dst_reg->umax_value;
5519         }
5520 }
5521
5522 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
5523                               struct bpf_reg_state *src_reg)
5524 {
5525         bool src_known = tnum_is_const(src_reg->var_off);
5526         bool dst_known = tnum_is_const(dst_reg->var_off);
5527         s64 smin_val = src_reg->smin_value;
5528         u64 umin_val = src_reg->umin_value;
5529
5530         if (src_known && dst_known) {
5531                 __mark_reg_known(dst_reg, dst_reg->var_off.value |
5532                                           src_reg->var_off.value);
5533                 return;
5534         }
5535
5536         /* We get our maximum from the var_off, and our minimum is the
5537          * maximum of the operands' minima
5538          */
5539         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
5540         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
5541         if (dst_reg->smin_value < 0 || smin_val < 0) {
5542                 /* Lose signed bounds when ORing negative numbers,
5543                  * ain't nobody got time for that.
5544                  */
5545                 dst_reg->smin_value = S64_MIN;
5546                 dst_reg->smax_value = S64_MAX;
5547         } else {
5548                 /* ORing two positives gives a positive, so safe to
5549                  * cast result into s64.
5550                  */
5551                 dst_reg->smin_value = dst_reg->umin_value;
5552                 dst_reg->smax_value = dst_reg->umax_value;
5553         }
5554         /* We may learn something more from the var_off */
5555         __update_reg_bounds(dst_reg);
5556 }
5557
5558 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
5559                                    u64 umin_val, u64 umax_val)
5560 {
5561         /* We lose all sign bit information (except what we can pick
5562          * up from var_off)
5563          */
5564         dst_reg->s32_min_value = S32_MIN;
5565         dst_reg->s32_max_value = S32_MAX;
5566         /* If we might shift our top bit out, then we know nothing */
5567         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
5568                 dst_reg->u32_min_value = 0;
5569                 dst_reg->u32_max_value = U32_MAX;
5570         } else {
5571                 dst_reg->u32_min_value <<= umin_val;
5572                 dst_reg->u32_max_value <<= umax_val;
5573         }
5574 }
5575
5576 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
5577                                  struct bpf_reg_state *src_reg)
5578 {
5579         u32 umax_val = src_reg->u32_max_value;
5580         u32 umin_val = src_reg->u32_min_value;
5581         /* u32 alu operation will zext upper bits */
5582         struct tnum subreg = tnum_subreg(dst_reg->var_off);
5583
5584         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
5585         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
5586         /* Not required but being careful mark reg64 bounds as unknown so
5587          * that we are forced to pick them up from tnum and zext later and
5588          * if some path skips this step we are still safe.
5589          */
5590         __mark_reg64_unbounded(dst_reg);
5591         __update_reg32_bounds(dst_reg);
5592 }
5593
5594 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
5595                                    u64 umin_val, u64 umax_val)
5596 {
5597         /* Special case <<32 because it is a common compiler pattern to sign
5598          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
5599          * positive we know this shift will also be positive so we can track
5600          * bounds correctly. Otherwise we lose all sign bit information except
5601          * what we can pick up from var_off. Perhaps we can generalize this
5602          * later to shifts of any length.
5603          */
5604         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
5605                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
5606         else
5607                 dst_reg->smax_value = S64_MAX;
5608
5609         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
5610                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
5611         else
5612                 dst_reg->smin_value = S64_MIN;
5613
5614         /* If we might shift our top bit out, then we know nothing */
5615         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
5616                 dst_reg->umin_value = 0;
5617                 dst_reg->umax_value = U64_MAX;
5618         } else {
5619                 dst_reg->umin_value <<= umin_val;
5620                 dst_reg->umax_value <<= umax_val;
5621         }
5622 }
5623
5624 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
5625                                struct bpf_reg_state *src_reg)
5626 {
5627         u64 umax_val = src_reg->umax_value;
5628         u64 umin_val = src_reg->umin_value;
5629
5630         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
5631         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
5632         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
5633
5634         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
5635         /* We may learn something more from the var_off */
5636         __update_reg_bounds(dst_reg);
5637 }
5638
5639 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
5640                                  struct bpf_reg_state *src_reg)
5641 {
5642         struct tnum subreg = tnum_subreg(dst_reg->var_off);
5643         u32 umax_val = src_reg->u32_max_value;
5644         u32 umin_val = src_reg->u32_min_value;
5645
5646         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
5647          * be negative, then either:
5648          * 1) src_reg might be zero, so the sign bit of the result is
5649          *    unknown, so we lose our signed bounds
5650          * 2) it's known negative, thus the unsigned bounds capture the
5651          *    signed bounds
5652          * 3) the signed bounds cross zero, so they tell us nothing
5653          *    about the result
5654          * If the value in dst_reg is known nonnegative, then again the
5655          * unsigned bounts capture the signed bounds.
5656          * Thus, in all cases it suffices to blow away our signed bounds
5657          * and rely on inferring new ones from the unsigned bounds and
5658          * var_off of the result.
5659          */
5660         dst_reg->s32_min_value = S32_MIN;
5661         dst_reg->s32_max_value = S32_MAX;
5662
5663         dst_reg->var_off = tnum_rshift(subreg, umin_val);
5664         dst_reg->u32_min_value >>= umax_val;
5665         dst_reg->u32_max_value >>= umin_val;
5666
5667         __mark_reg64_unbounded(dst_reg);
5668         __update_reg32_bounds(dst_reg);
5669 }
5670
5671 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
5672                                struct bpf_reg_state *src_reg)
5673 {
5674         u64 umax_val = src_reg->umax_value;
5675         u64 umin_val = src_reg->umin_value;
5676
5677         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
5678          * be negative, then either:
5679          * 1) src_reg might be zero, so the sign bit of the result is
5680          *    unknown, so we lose our signed bounds
5681          * 2) it's known negative, thus the unsigned bounds capture the
5682          *    signed bounds
5683          * 3) the signed bounds cross zero, so they tell us nothing
5684          *    about the result
5685          * If the value in dst_reg is known nonnegative, then again the
5686          * unsigned bounts capture the signed bounds.
5687          * Thus, in all cases it suffices to blow away our signed bounds
5688          * and rely on inferring new ones from the unsigned bounds and
5689          * var_off of the result.
5690          */
5691         dst_reg->smin_value = S64_MIN;
5692         dst_reg->smax_value = S64_MAX;
5693         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
5694         dst_reg->umin_value >>= umax_val;
5695         dst_reg->umax_value >>= umin_val;
5696
5697         /* Its not easy to operate on alu32 bounds here because it depends
5698          * on bits being shifted in. Take easy way out and mark unbounded
5699          * so we can recalculate later from tnum.
5700          */
5701         __mark_reg32_unbounded(dst_reg);
5702         __update_reg_bounds(dst_reg);
5703 }
5704
5705 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
5706                                   struct bpf_reg_state *src_reg)
5707 {
5708         u64 umin_val = src_reg->u32_min_value;
5709
5710         /* Upon reaching here, src_known is true and
5711          * umax_val is equal to umin_val.
5712          */
5713         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
5714         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
5715
5716         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
5717
5718         /* blow away the dst_reg umin_value/umax_value and rely on
5719          * dst_reg var_off to refine the result.
5720          */
5721         dst_reg->u32_min_value = 0;
5722         dst_reg->u32_max_value = U32_MAX;
5723
5724         __mark_reg64_unbounded(dst_reg);
5725         __update_reg32_bounds(dst_reg);
5726 }
5727
5728 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
5729                                 struct bpf_reg_state *src_reg)
5730 {
5731         u64 umin_val = src_reg->umin_value;
5732
5733         /* Upon reaching here, src_known is true and umax_val is equal
5734          * to umin_val.
5735          */
5736         dst_reg->smin_value >>= umin_val;
5737         dst_reg->smax_value >>= umin_val;
5738
5739         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
5740
5741         /* blow away the dst_reg umin_value/umax_value and rely on
5742          * dst_reg var_off to refine the result.
5743          */
5744         dst_reg->umin_value = 0;
5745         dst_reg->umax_value = U64_MAX;
5746
5747         /* Its not easy to operate on alu32 bounds here because it depends
5748          * on bits being shifted in from upper 32-bits. Take easy way out
5749          * and mark unbounded so we can recalculate later from tnum.
5750          */
5751         __mark_reg32_unbounded(dst_reg);
5752         __update_reg_bounds(dst_reg);
5753 }
5754
5755 /* WARNING: This function does calculations on 64-bit values, but the actual
5756  * execution may occur on 32-bit values. Therefore, things like bitshifts
5757  * need extra checks in the 32-bit case.
5758  */
5759 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
5760                                       struct bpf_insn *insn,
5761                                       struct bpf_reg_state *dst_reg,
5762                                       struct bpf_reg_state src_reg)
5763 {
5764         struct bpf_reg_state *regs = cur_regs(env);
5765         u8 opcode = BPF_OP(insn->code);
5766         bool src_known;
5767         s64 smin_val, smax_val;
5768         u64 umin_val, umax_val;
5769         s32 s32_min_val, s32_max_val;
5770         u32 u32_min_val, u32_max_val;
5771         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
5772         u32 dst = insn->dst_reg;
5773         int ret;
5774         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
5775
5776         smin_val = src_reg.smin_value;
5777         smax_val = src_reg.smax_value;
5778         umin_val = src_reg.umin_value;
5779         umax_val = src_reg.umax_value;
5780
5781         s32_min_val = src_reg.s32_min_value;
5782         s32_max_val = src_reg.s32_max_value;
5783         u32_min_val = src_reg.u32_min_value;
5784         u32_max_val = src_reg.u32_max_value;
5785
5786         if (alu32) {
5787                 src_known = tnum_subreg_is_const(src_reg.var_off);
5788                 if ((src_known &&
5789                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
5790                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
5791                         /* Taint dst register if offset had invalid bounds
5792                          * derived from e.g. dead branches.
5793                          */
5794                         __mark_reg_unknown(env, dst_reg);
5795                         return 0;
5796                 }
5797         } else {
5798                 src_known = tnum_is_const(src_reg.var_off);
5799                 if ((src_known &&
5800                      (smin_val != smax_val || umin_val != umax_val)) ||
5801                     smin_val > smax_val || umin_val > umax_val) {
5802                         /* Taint dst register if offset had invalid bounds
5803                          * derived from e.g. dead branches.
5804                          */
5805                         __mark_reg_unknown(env, dst_reg);
5806                         return 0;
5807                 }
5808         }
5809
5810         if (!src_known &&
5811             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
5812                 __mark_reg_unknown(env, dst_reg);
5813                 return 0;
5814         }
5815
5816         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
5817          * There are two classes of instructions: The first class we track both
5818          * alu32 and alu64 sign/unsigned bounds independently this provides the
5819          * greatest amount of precision when alu operations are mixed with jmp32
5820          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
5821          * and BPF_OR. This is possible because these ops have fairly easy to
5822          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
5823          * See alu32 verifier tests for examples. The second class of
5824          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
5825          * with regards to tracking sign/unsigned bounds because the bits may
5826          * cross subreg boundaries in the alu64 case. When this happens we mark
5827          * the reg unbounded in the subreg bound space and use the resulting
5828          * tnum to calculate an approximation of the sign/unsigned bounds.
5829          */
5830         switch (opcode) {
5831         case BPF_ADD:
5832                 ret = sanitize_val_alu(env, insn);
5833                 if (ret < 0) {
5834                         verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
5835                         return ret;
5836                 }
5837                 scalar32_min_max_add(dst_reg, &src_reg);
5838                 scalar_min_max_add(dst_reg, &src_reg);
5839                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
5840                 break;
5841         case BPF_SUB:
5842                 ret = sanitize_val_alu(env, insn);
5843                 if (ret < 0) {
5844                         verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
5845                         return ret;
5846                 }
5847                 scalar32_min_max_sub(dst_reg, &src_reg);
5848                 scalar_min_max_sub(dst_reg, &src_reg);
5849                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
5850                 break;
5851         case BPF_MUL:
5852                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
5853                 scalar32_min_max_mul(dst_reg, &src_reg);
5854                 scalar_min_max_mul(dst_reg, &src_reg);
5855                 break;
5856         case BPF_AND:
5857                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
5858                 scalar32_min_max_and(dst_reg, &src_reg);
5859                 scalar_min_max_and(dst_reg, &src_reg);
5860                 break;
5861         case BPF_OR:
5862                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
5863                 scalar32_min_max_or(dst_reg, &src_reg);
5864                 scalar_min_max_or(dst_reg, &src_reg);
5865                 break;
5866         case BPF_LSH:
5867                 if (umax_val >= insn_bitness) {
5868                         /* Shifts greater than 31 or 63 are undefined.
5869                          * This includes shifts by a negative number.
5870                          */
5871                         mark_reg_unknown(env, regs, insn->dst_reg);
5872                         break;
5873                 }
5874                 if (alu32)
5875                         scalar32_min_max_lsh(dst_reg, &src_reg);
5876                 else
5877                         scalar_min_max_lsh(dst_reg, &src_reg);
5878                 break;
5879         case BPF_RSH:
5880                 if (umax_val >= insn_bitness) {
5881                         /* Shifts greater than 31 or 63 are undefined.
5882                          * This includes shifts by a negative number.
5883                          */
5884                         mark_reg_unknown(env, regs, insn->dst_reg);
5885                         break;
5886                 }
5887                 if (alu32)
5888                         scalar32_min_max_rsh(dst_reg, &src_reg);
5889                 else
5890                         scalar_min_max_rsh(dst_reg, &src_reg);
5891                 break;
5892         case BPF_ARSH:
5893                 if (umax_val >= insn_bitness) {
5894                         /* Shifts greater than 31 or 63 are undefined.
5895                          * This includes shifts by a negative number.
5896                          */
5897                         mark_reg_unknown(env, regs, insn->dst_reg);
5898                         break;
5899                 }
5900                 if (alu32)
5901                         scalar32_min_max_arsh(dst_reg, &src_reg);
5902                 else
5903                         scalar_min_max_arsh(dst_reg, &src_reg);
5904                 break;
5905         default:
5906                 mark_reg_unknown(env, regs, insn->dst_reg);
5907                 break;
5908         }
5909
5910         /* ALU32 ops are zero extended into 64bit register */
5911         if (alu32)
5912                 zext_32_to_64(dst_reg);
5913
5914         __update_reg_bounds(dst_reg);
5915         __reg_deduce_bounds(dst_reg);
5916         __reg_bound_offset(dst_reg);
5917         return 0;
5918 }
5919
5920 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
5921  * and var_off.
5922  */
5923 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
5924                                    struct bpf_insn *insn)
5925 {
5926         struct bpf_verifier_state *vstate = env->cur_state;
5927         struct bpf_func_state *state = vstate->frame[vstate->curframe];
5928         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
5929         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
5930         u8 opcode = BPF_OP(insn->code);
5931         int err;
5932
5933         dst_reg = &regs[insn->dst_reg];
5934         src_reg = NULL;
5935         if (dst_reg->type != SCALAR_VALUE)
5936                 ptr_reg = dst_reg;
5937         if (BPF_SRC(insn->code) == BPF_X) {
5938                 src_reg = &regs[insn->src_reg];
5939                 if (src_reg->type != SCALAR_VALUE) {
5940                         if (dst_reg->type != SCALAR_VALUE) {
5941                                 /* Combining two pointers by any ALU op yields
5942                                  * an arbitrary scalar. Disallow all math except
5943                                  * pointer subtraction
5944                                  */
5945                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
5946                                         mark_reg_unknown(env, regs, insn->dst_reg);
5947                                         return 0;
5948                                 }
5949                                 verbose(env, "R%d pointer %s pointer prohibited\n",
5950                                         insn->dst_reg,
5951                                         bpf_alu_string[opcode >> 4]);
5952                                 return -EACCES;
5953                         } else {
5954                                 /* scalar += pointer
5955                                  * This is legal, but we have to reverse our
5956                                  * src/dest handling in computing the range
5957                                  */
5958                                 err = mark_chain_precision(env, insn->dst_reg);
5959                                 if (err)
5960                                         return err;
5961                                 return adjust_ptr_min_max_vals(env, insn,
5962                                                                src_reg, dst_reg);
5963                         }
5964                 } else if (ptr_reg) {
5965                         /* pointer += scalar */
5966                         err = mark_chain_precision(env, insn->src_reg);
5967                         if (err)
5968                                 return err;
5969                         return adjust_ptr_min_max_vals(env, insn,
5970                                                        dst_reg, src_reg);
5971                 }
5972         } else {
5973                 /* Pretend the src is a reg with a known value, since we only
5974                  * need to be able to read from this state.
5975                  */
5976                 off_reg.type = SCALAR_VALUE;
5977                 __mark_reg_known(&off_reg, insn->imm);
5978                 src_reg = &off_reg;
5979                 if (ptr_reg) /* pointer += K */
5980                         return adjust_ptr_min_max_vals(env, insn,
5981                                                        ptr_reg, src_reg);
5982         }
5983
5984         /* Got here implies adding two SCALAR_VALUEs */
5985         if (WARN_ON_ONCE(ptr_reg)) {
5986                 print_verifier_state(env, state);
5987                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
5988                 return -EINVAL;
5989         }
5990         if (WARN_ON(!src_reg)) {
5991                 print_verifier_state(env, state);
5992                 verbose(env, "verifier internal error: no src_reg\n");
5993                 return -EINVAL;
5994         }
5995         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
5996 }
5997
5998 /* check validity of 32-bit and 64-bit arithmetic operations */
5999 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
6000 {
6001         struct bpf_reg_state *regs = cur_regs(env);
6002         u8 opcode = BPF_OP(insn->code);
6003         int err;
6004
6005         if (opcode == BPF_END || opcode == BPF_NEG) {
6006                 if (opcode == BPF_NEG) {
6007                         if (BPF_SRC(insn->code) != 0 ||
6008                             insn->src_reg != BPF_REG_0 ||
6009                             insn->off != 0 || insn->imm != 0) {
6010                                 verbose(env, "BPF_NEG uses reserved fields\n");
6011                                 return -EINVAL;
6012                         }
6013                 } else {
6014                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
6015                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
6016                             BPF_CLASS(insn->code) == BPF_ALU64) {
6017                                 verbose(env, "BPF_END uses reserved fields\n");
6018                                 return -EINVAL;
6019                         }
6020                 }
6021
6022                 /* check src operand */
6023                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6024                 if (err)
6025                         return err;
6026
6027                 if (is_pointer_value(env, insn->dst_reg)) {
6028                         verbose(env, "R%d pointer arithmetic prohibited\n",
6029                                 insn->dst_reg);
6030                         return -EACCES;
6031                 }
6032
6033                 /* check dest operand */
6034                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
6035                 if (err)
6036                         return err;
6037
6038         } else if (opcode == BPF_MOV) {
6039
6040                 if (BPF_SRC(insn->code) == BPF_X) {
6041                         if (insn->imm != 0 || insn->off != 0) {
6042                                 verbose(env, "BPF_MOV uses reserved fields\n");
6043                                 return -EINVAL;
6044                         }
6045
6046                         /* check src operand */
6047                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
6048                         if (err)
6049                                 return err;
6050                 } else {
6051                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
6052                                 verbose(env, "BPF_MOV uses reserved fields\n");
6053                                 return -EINVAL;
6054                         }
6055                 }
6056
6057                 /* check dest operand, mark as required later */
6058                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
6059                 if (err)
6060                         return err;
6061
6062                 if (BPF_SRC(insn->code) == BPF_X) {
6063                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
6064                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
6065
6066                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
6067                                 /* case: R1 = R2
6068                                  * copy register state to dest reg
6069                                  */
6070                                 *dst_reg = *src_reg;
6071                                 dst_reg->live |= REG_LIVE_WRITTEN;
6072                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
6073                         } else {
6074                                 /* R1 = (u32) R2 */
6075                                 if (is_pointer_value(env, insn->src_reg)) {
6076                                         verbose(env,
6077                                                 "R%d partial copy of pointer\n",
6078                                                 insn->src_reg);
6079                                         return -EACCES;
6080                                 } else if (src_reg->type == SCALAR_VALUE) {
6081                                         *dst_reg = *src_reg;
6082                                         dst_reg->live |= REG_LIVE_WRITTEN;
6083                                         dst_reg->subreg_def = env->insn_idx + 1;
6084                                 } else {
6085                                         mark_reg_unknown(env, regs,
6086                                                          insn->dst_reg);
6087                                 }
6088                                 zext_32_to_64(dst_reg);
6089                         }
6090                 } else {
6091                         /* case: R = imm
6092                          * remember the value we stored into this reg
6093                          */
6094                         /* clear any state __mark_reg_known doesn't set */
6095                         mark_reg_unknown(env, regs, insn->dst_reg);
6096                         regs[insn->dst_reg].type = SCALAR_VALUE;
6097                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
6098                                 __mark_reg_known(regs + insn->dst_reg,
6099                                                  insn->imm);
6100                         } else {
6101                                 __mark_reg_known(regs + insn->dst_reg,
6102                                                  (u32)insn->imm);
6103                         }
6104                 }
6105
6106         } else if (opcode > BPF_END) {
6107                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
6108                 return -EINVAL;
6109
6110         } else {        /* all other ALU ops: and, sub, xor, add, ... */
6111
6112                 if (BPF_SRC(insn->code) == BPF_X) {
6113                         if (insn->imm != 0 || insn->off != 0) {
6114                                 verbose(env, "BPF_ALU uses reserved fields\n");
6115                                 return -EINVAL;
6116                         }
6117                         /* check src1 operand */
6118                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
6119                         if (err)
6120                                 return err;
6121                 } else {
6122                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
6123                                 verbose(env, "BPF_ALU uses reserved fields\n");
6124                                 return -EINVAL;
6125                         }
6126                 }
6127
6128                 /* check src2 operand */
6129                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6130                 if (err)
6131                         return err;
6132
6133                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
6134                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
6135                         verbose(env, "div by zero\n");
6136                         return -EINVAL;
6137                 }
6138
6139                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
6140                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
6141                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
6142
6143                         if (insn->imm < 0 || insn->imm >= size) {
6144                                 verbose(env, "invalid shift %d\n", insn->imm);
6145                                 return -EINVAL;
6146                         }
6147                 }
6148
6149                 /* check dest operand */
6150                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
6151                 if (err)
6152                         return err;
6153
6154                 return adjust_reg_min_max_vals(env, insn);
6155         }
6156
6157         return 0;
6158 }
6159
6160 static void __find_good_pkt_pointers(struct bpf_func_state *state,
6161                                      struct bpf_reg_state *dst_reg,
6162                                      enum bpf_reg_type type, u16 new_range)
6163 {
6164         struct bpf_reg_state *reg;
6165         int i;
6166
6167         for (i = 0; i < MAX_BPF_REG; i++) {
6168                 reg = &state->regs[i];
6169                 if (reg->type == type && reg->id == dst_reg->id)
6170                         /* keep the maximum range already checked */
6171                         reg->range = max(reg->range, new_range);
6172         }
6173
6174         bpf_for_each_spilled_reg(i, state, reg) {
6175                 if (!reg)
6176                         continue;
6177                 if (reg->type == type && reg->id == dst_reg->id)
6178                         reg->range = max(reg->range, new_range);
6179         }
6180 }
6181
6182 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
6183                                    struct bpf_reg_state *dst_reg,
6184                                    enum bpf_reg_type type,
6185                                    bool range_right_open)
6186 {
6187         u16 new_range;
6188         int i;
6189
6190         if (dst_reg->off < 0 ||
6191             (dst_reg->off == 0 && range_right_open))
6192                 /* This doesn't give us any range */
6193                 return;
6194
6195         if (dst_reg->umax_value > MAX_PACKET_OFF ||
6196             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
6197                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
6198                  * than pkt_end, but that's because it's also less than pkt.
6199                  */
6200                 return;
6201
6202         new_range = dst_reg->off;
6203         if (range_right_open)
6204                 new_range--;
6205
6206         /* Examples for register markings:
6207          *
6208          * pkt_data in dst register:
6209          *
6210          *   r2 = r3;
6211          *   r2 += 8;
6212          *   if (r2 > pkt_end) goto <handle exception>
6213          *   <access okay>
6214          *
6215          *   r2 = r3;
6216          *   r2 += 8;
6217          *   if (r2 < pkt_end) goto <access okay>
6218          *   <handle exception>
6219          *
6220          *   Where:
6221          *     r2 == dst_reg, pkt_end == src_reg
6222          *     r2=pkt(id=n,off=8,r=0)
6223          *     r3=pkt(id=n,off=0,r=0)
6224          *
6225          * pkt_data in src register:
6226          *
6227          *   r2 = r3;
6228          *   r2 += 8;
6229          *   if (pkt_end >= r2) goto <access okay>
6230          *   <handle exception>
6231          *
6232          *   r2 = r3;
6233          *   r2 += 8;
6234          *   if (pkt_end <= r2) goto <handle exception>
6235          *   <access okay>
6236          *
6237          *   Where:
6238          *     pkt_end == dst_reg, r2 == src_reg
6239          *     r2=pkt(id=n,off=8,r=0)
6240          *     r3=pkt(id=n,off=0,r=0)
6241          *
6242          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
6243          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
6244          * and [r3, r3 + 8-1) respectively is safe to access depending on
6245          * the check.
6246          */
6247
6248         /* If our ids match, then we must have the same max_value.  And we
6249          * don't care about the other reg's fixed offset, since if it's too big
6250          * the range won't allow anything.
6251          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
6252          */
6253         for (i = 0; i <= vstate->curframe; i++)
6254                 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
6255                                          new_range);
6256 }
6257
6258 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
6259 {
6260         struct tnum subreg = tnum_subreg(reg->var_off);
6261         s32 sval = (s32)val;
6262
6263         switch (opcode) {
6264         case BPF_JEQ:
6265                 if (tnum_is_const(subreg))
6266                         return !!tnum_equals_const(subreg, val);
6267                 break;
6268         case BPF_JNE:
6269                 if (tnum_is_const(subreg))
6270                         return !tnum_equals_const(subreg, val);
6271                 break;
6272         case BPF_JSET:
6273                 if ((~subreg.mask & subreg.value) & val)
6274                         return 1;
6275                 if (!((subreg.mask | subreg.value) & val))
6276                         return 0;
6277                 break;
6278         case BPF_JGT:
6279                 if (reg->u32_min_value > val)
6280                         return 1;
6281                 else if (reg->u32_max_value <= val)
6282                         return 0;
6283                 break;
6284         case BPF_JSGT:
6285                 if (reg->s32_min_value > sval)
6286                         return 1;
6287                 else if (reg->s32_max_value < sval)
6288                         return 0;
6289                 break;
6290         case BPF_JLT:
6291                 if (reg->u32_max_value < val)
6292                         return 1;
6293                 else if (reg->u32_min_value >= val)
6294                         return 0;
6295                 break;
6296         case BPF_JSLT:
6297                 if (reg->s32_max_value < sval)
6298                         return 1;
6299                 else if (reg->s32_min_value >= sval)
6300                         return 0;
6301                 break;
6302         case BPF_JGE:
6303                 if (reg->u32_min_value >= val)
6304                         return 1;
6305                 else if (reg->u32_max_value < val)
6306                         return 0;
6307                 break;
6308         case BPF_JSGE:
6309                 if (reg->s32_min_value >= sval)
6310                         return 1;
6311                 else if (reg->s32_max_value < sval)
6312                         return 0;
6313                 break;
6314         case BPF_JLE:
6315                 if (reg->u32_max_value <= val)
6316                         return 1;
6317                 else if (reg->u32_min_value > val)
6318                         return 0;
6319                 break;
6320         case BPF_JSLE:
6321                 if (reg->s32_max_value <= sval)
6322                         return 1;
6323                 else if (reg->s32_min_value > sval)
6324                         return 0;
6325                 break;
6326         }
6327
6328         return -1;
6329 }
6330
6331
6332 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
6333 {
6334         s64 sval = (s64)val;
6335
6336         switch (opcode) {
6337         case BPF_JEQ:
6338                 if (tnum_is_const(reg->var_off))
6339                         return !!tnum_equals_const(reg->var_off, val);
6340                 break;
6341         case BPF_JNE:
6342                 if (tnum_is_const(reg->var_off))
6343                         return !tnum_equals_const(reg->var_off, val);
6344                 break;
6345         case BPF_JSET:
6346                 if ((~reg->var_off.mask & reg->var_off.value) & val)
6347                         return 1;
6348                 if (!((reg->var_off.mask | reg->var_off.value) & val))
6349                         return 0;
6350                 break;
6351         case BPF_JGT:
6352                 if (reg->umin_value > val)
6353                         return 1;
6354                 else if (reg->umax_value <= val)
6355                         return 0;
6356                 break;
6357         case BPF_JSGT:
6358                 if (reg->smin_value > sval)
6359                         return 1;
6360                 else if (reg->smax_value < sval)
6361                         return 0;
6362                 break;
6363         case BPF_JLT:
6364                 if (reg->umax_value < val)
6365                         return 1;
6366                 else if (reg->umin_value >= val)
6367                         return 0;
6368                 break;
6369         case BPF_JSLT:
6370                 if (reg->smax_value < sval)
6371                         return 1;
6372                 else if (reg->smin_value >= sval)
6373                         return 0;
6374                 break;
6375         case BPF_JGE:
6376                 if (reg->umin_value >= val)
6377                         return 1;
6378                 else if (reg->umax_value < val)
6379                         return 0;
6380                 break;
6381         case BPF_JSGE:
6382                 if (reg->smin_value >= sval)
6383                         return 1;
6384                 else if (reg->smax_value < sval)
6385                         return 0;
6386                 break;
6387         case BPF_JLE:
6388                 if (reg->umax_value <= val)
6389                         return 1;
6390                 else if (reg->umin_value > val)
6391                         return 0;
6392                 break;
6393         case BPF_JSLE:
6394                 if (reg->smax_value <= sval)
6395                         return 1;
6396                 else if (reg->smin_value > sval)
6397                         return 0;
6398                 break;
6399         }
6400
6401         return -1;
6402 }
6403
6404 /* compute branch direction of the expression "if (reg opcode val) goto target;"
6405  * and return:
6406  *  1 - branch will be taken and "goto target" will be executed
6407  *  0 - branch will not be taken and fall-through to next insn
6408  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
6409  *      range [0,10]
6410  */
6411 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
6412                            bool is_jmp32)
6413 {
6414         if (__is_pointer_value(false, reg)) {
6415                 if (!reg_type_not_null(reg->type))
6416                         return -1;
6417
6418                 /* If pointer is valid tests against zero will fail so we can
6419                  * use this to direct branch taken.
6420                  */
6421                 if (val != 0)
6422                         return -1;
6423
6424                 switch (opcode) {
6425                 case BPF_JEQ:
6426                         return 0;
6427                 case BPF_JNE:
6428                         return 1;
6429                 default:
6430                         return -1;
6431                 }
6432         }
6433
6434         if (is_jmp32)
6435                 return is_branch32_taken(reg, val, opcode);
6436         return is_branch64_taken(reg, val, opcode);
6437 }
6438
6439 /* Adjusts the register min/max values in the case that the dst_reg is the
6440  * variable register that we are working on, and src_reg is a constant or we're
6441  * simply doing a BPF_K check.
6442  * In JEQ/JNE cases we also adjust the var_off values.
6443  */
6444 static void reg_set_min_max(struct bpf_reg_state *true_reg,
6445                             struct bpf_reg_state *false_reg,
6446                             u64 val, u32 val32,
6447                             u8 opcode, bool is_jmp32)
6448 {
6449         struct tnum false_32off = tnum_subreg(false_reg->var_off);
6450         struct tnum false_64off = false_reg->var_off;
6451         struct tnum true_32off = tnum_subreg(true_reg->var_off);
6452         struct tnum true_64off = true_reg->var_off;
6453         s64 sval = (s64)val;
6454         s32 sval32 = (s32)val32;
6455
6456         /* If the dst_reg is a pointer, we can't learn anything about its
6457          * variable offset from the compare (unless src_reg were a pointer into
6458          * the same object, but we don't bother with that.
6459          * Since false_reg and true_reg have the same type by construction, we
6460          * only need to check one of them for pointerness.
6461          */
6462         if (__is_pointer_value(false, false_reg))
6463                 return;
6464
6465         switch (opcode) {
6466         case BPF_JEQ:
6467         case BPF_JNE:
6468         {
6469                 struct bpf_reg_state *reg =
6470                         opcode == BPF_JEQ ? true_reg : false_reg;
6471
6472                 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but
6473                  * if it is true we know the value for sure. Likewise for
6474                  * BPF_JNE.
6475                  */
6476                 if (is_jmp32)
6477                         __mark_reg32_known(reg, val32);
6478                 else
6479                         __mark_reg_known(reg, val);
6480                 break;
6481         }
6482         case BPF_JSET:
6483                 if (is_jmp32) {
6484                         false_32off = tnum_and(false_32off, tnum_const(~val32));
6485                         if (is_power_of_2(val32))
6486                                 true_32off = tnum_or(true_32off,
6487                                                      tnum_const(val32));
6488                 } else {
6489                         false_64off = tnum_and(false_64off, tnum_const(~val));
6490                         if (is_power_of_2(val))
6491                                 true_64off = tnum_or(true_64off,
6492                                                      tnum_const(val));
6493                 }
6494                 break;
6495         case BPF_JGE:
6496         case BPF_JGT:
6497         {
6498                 if (is_jmp32) {
6499                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
6500                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
6501
6502                         false_reg->u32_max_value = min(false_reg->u32_max_value,
6503                                                        false_umax);
6504                         true_reg->u32_min_value = max(true_reg->u32_min_value,
6505                                                       true_umin);
6506                 } else {
6507                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
6508                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
6509
6510                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
6511                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
6512                 }
6513                 break;
6514         }
6515         case BPF_JSGE:
6516         case BPF_JSGT:
6517         {
6518                 if (is_jmp32) {
6519                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
6520                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
6521
6522                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
6523                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
6524                 } else {
6525                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
6526                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
6527
6528                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
6529                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
6530                 }
6531                 break;
6532         }
6533         case BPF_JLE:
6534         case BPF_JLT:
6535         {
6536                 if (is_jmp32) {
6537                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
6538                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
6539
6540                         false_reg->u32_min_value = max(false_reg->u32_min_value,
6541                                                        false_umin);
6542                         true_reg->u32_max_value = min(true_reg->u32_max_value,
6543                                                       true_umax);
6544                 } else {
6545                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
6546                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
6547
6548                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
6549                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
6550                 }
6551                 break;
6552         }
6553         case BPF_JSLE:
6554         case BPF_JSLT:
6555         {
6556                 if (is_jmp32) {
6557                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
6558                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
6559
6560                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
6561                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
6562                 } else {
6563                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
6564                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
6565
6566                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
6567                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
6568                 }
6569                 break;
6570         }
6571         default:
6572                 return;
6573         }
6574
6575         if (is_jmp32) {
6576                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
6577                                              tnum_subreg(false_32off));
6578                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
6579                                             tnum_subreg(true_32off));
6580                 __reg_combine_32_into_64(false_reg);
6581                 __reg_combine_32_into_64(true_reg);
6582         } else {
6583                 false_reg->var_off = false_64off;
6584                 true_reg->var_off = true_64off;
6585                 __reg_combine_64_into_32(false_reg);
6586                 __reg_combine_64_into_32(true_reg);
6587         }
6588 }
6589
6590 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
6591  * the variable reg.
6592  */
6593 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
6594                                 struct bpf_reg_state *false_reg,
6595                                 u64 val, u32 val32,
6596                                 u8 opcode, bool is_jmp32)
6597 {
6598         /* How can we transform "a <op> b" into "b <op> a"? */
6599         static const u8 opcode_flip[16] = {
6600                 /* these stay the same */
6601                 [BPF_JEQ  >> 4] = BPF_JEQ,
6602                 [BPF_JNE  >> 4] = BPF_JNE,
6603                 [BPF_JSET >> 4] = BPF_JSET,
6604                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
6605                 [BPF_JGE  >> 4] = BPF_JLE,
6606                 [BPF_JGT  >> 4] = BPF_JLT,
6607                 [BPF_JLE  >> 4] = BPF_JGE,
6608                 [BPF_JLT  >> 4] = BPF_JGT,
6609                 [BPF_JSGE >> 4] = BPF_JSLE,
6610                 [BPF_JSGT >> 4] = BPF_JSLT,
6611                 [BPF_JSLE >> 4] = BPF_JSGE,
6612                 [BPF_JSLT >> 4] = BPF_JSGT
6613         };
6614         opcode = opcode_flip[opcode >> 4];
6615         /* This uses zero as "not present in table"; luckily the zero opcode,
6616          * BPF_JA, can't get here.
6617          */
6618         if (opcode)
6619                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
6620 }
6621
6622 /* Regs are known to be equal, so intersect their min/max/var_off */
6623 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
6624                                   struct bpf_reg_state *dst_reg)
6625 {
6626         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
6627                                                         dst_reg->umin_value);
6628         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
6629                                                         dst_reg->umax_value);
6630         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
6631                                                         dst_reg->smin_value);
6632         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
6633                                                         dst_reg->smax_value);
6634         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
6635                                                              dst_reg->var_off);
6636         /* We might have learned new bounds from the var_off. */
6637         __update_reg_bounds(src_reg);
6638         __update_reg_bounds(dst_reg);
6639         /* We might have learned something about the sign bit. */
6640         __reg_deduce_bounds(src_reg);
6641         __reg_deduce_bounds(dst_reg);
6642         /* We might have learned some bits from the bounds. */
6643         __reg_bound_offset(src_reg);
6644         __reg_bound_offset(dst_reg);
6645         /* Intersecting with the old var_off might have improved our bounds
6646          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
6647          * then new var_off is (0; 0x7f...fc) which improves our umax.
6648          */
6649         __update_reg_bounds(src_reg);
6650         __update_reg_bounds(dst_reg);
6651 }
6652
6653 static void reg_combine_min_max(struct bpf_reg_state *true_src,
6654                                 struct bpf_reg_state *true_dst,
6655                                 struct bpf_reg_state *false_src,
6656                                 struct bpf_reg_state *false_dst,
6657                                 u8 opcode)
6658 {
6659         switch (opcode) {
6660         case BPF_JEQ:
6661                 __reg_combine_min_max(true_src, true_dst);
6662                 break;
6663         case BPF_JNE:
6664                 __reg_combine_min_max(false_src, false_dst);
6665                 break;
6666         }
6667 }
6668
6669 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
6670                                  struct bpf_reg_state *reg, u32 id,
6671                                  bool is_null)
6672 {
6673         if (reg_type_may_be_null(reg->type) && reg->id == id) {
6674                 /* Old offset (both fixed and variable parts) should
6675                  * have been known-zero, because we don't allow pointer
6676                  * arithmetic on pointers that might be NULL.
6677                  */
6678                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
6679                                  !tnum_equals_const(reg->var_off, 0) ||
6680                                  reg->off)) {
6681                         __mark_reg_known_zero(reg);
6682                         reg->off = 0;
6683                 }
6684                 if (is_null) {
6685                         reg->type = SCALAR_VALUE;
6686                 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
6687                         const struct bpf_map *map = reg->map_ptr;
6688
6689                         if (map->inner_map_meta) {
6690                                 reg->type = CONST_PTR_TO_MAP;
6691                                 reg->map_ptr = map->inner_map_meta;
6692                         } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
6693                                 reg->type = PTR_TO_XDP_SOCK;
6694                         } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
6695                                    map->map_type == BPF_MAP_TYPE_SOCKHASH) {
6696                                 reg->type = PTR_TO_SOCKET;
6697                         } else {
6698                                 reg->type = PTR_TO_MAP_VALUE;
6699                         }
6700                 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
6701                         reg->type = PTR_TO_SOCKET;
6702                 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
6703                         reg->type = PTR_TO_SOCK_COMMON;
6704                 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
6705                         reg->type = PTR_TO_TCP_SOCK;
6706                 } else if (reg->type == PTR_TO_BTF_ID_OR_NULL) {
6707                         reg->type = PTR_TO_BTF_ID;
6708                 } else if (reg->type == PTR_TO_MEM_OR_NULL) {
6709                         reg->type = PTR_TO_MEM;
6710                 }
6711                 if (is_null) {
6712                         /* We don't need id and ref_obj_id from this point
6713                          * onwards anymore, thus we should better reset it,
6714                          * so that state pruning has chances to take effect.
6715                          */
6716                         reg->id = 0;
6717                         reg->ref_obj_id = 0;
6718                 } else if (!reg_may_point_to_spin_lock(reg)) {
6719                         /* For not-NULL ptr, reg->ref_obj_id will be reset
6720                          * in release_reg_references().
6721                          *
6722                          * reg->id is still used by spin_lock ptr. Other
6723                          * than spin_lock ptr type, reg->id can be reset.
6724                          */
6725                         reg->id = 0;
6726                 }
6727         }
6728 }
6729
6730 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
6731                                     bool is_null)
6732 {
6733         struct bpf_reg_state *reg;
6734         int i;
6735
6736         for (i = 0; i < MAX_BPF_REG; i++)
6737                 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
6738
6739         bpf_for_each_spilled_reg(i, state, reg) {
6740                 if (!reg)
6741                         continue;
6742                 mark_ptr_or_null_reg(state, reg, id, is_null);
6743         }
6744 }
6745
6746 /* The logic is similar to find_good_pkt_pointers(), both could eventually
6747  * be folded together at some point.
6748  */
6749 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
6750                                   bool is_null)
6751 {
6752         struct bpf_func_state *state = vstate->frame[vstate->curframe];
6753         struct bpf_reg_state *regs = state->regs;
6754         u32 ref_obj_id = regs[regno].ref_obj_id;
6755         u32 id = regs[regno].id;
6756         int i;
6757
6758         if (ref_obj_id && ref_obj_id == id && is_null)
6759                 /* regs[regno] is in the " == NULL" branch.
6760                  * No one could have freed the reference state before
6761                  * doing the NULL check.
6762                  */
6763                 WARN_ON_ONCE(release_reference_state(state, id));
6764
6765         for (i = 0; i <= vstate->curframe; i++)
6766                 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
6767 }
6768
6769 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
6770                                    struct bpf_reg_state *dst_reg,
6771                                    struct bpf_reg_state *src_reg,
6772                                    struct bpf_verifier_state *this_branch,
6773                                    struct bpf_verifier_state *other_branch)
6774 {
6775         if (BPF_SRC(insn->code) != BPF_X)
6776                 return false;
6777
6778         /* Pointers are always 64-bit. */
6779         if (BPF_CLASS(insn->code) == BPF_JMP32)
6780                 return false;
6781
6782         switch (BPF_OP(insn->code)) {
6783         case BPF_JGT:
6784                 if ((dst_reg->type == PTR_TO_PACKET &&
6785                      src_reg->type == PTR_TO_PACKET_END) ||
6786                     (dst_reg->type == PTR_TO_PACKET_META &&
6787                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6788                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
6789                         find_good_pkt_pointers(this_branch, dst_reg,
6790                                                dst_reg->type, false);
6791                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6792                             src_reg->type == PTR_TO_PACKET) ||
6793                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6794                             src_reg->type == PTR_TO_PACKET_META)) {
6795                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
6796                         find_good_pkt_pointers(other_branch, src_reg,
6797                                                src_reg->type, true);
6798                 } else {
6799                         return false;
6800                 }
6801                 break;
6802         case BPF_JLT:
6803                 if ((dst_reg->type == PTR_TO_PACKET &&
6804                      src_reg->type == PTR_TO_PACKET_END) ||
6805                     (dst_reg->type == PTR_TO_PACKET_META &&
6806                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6807                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
6808                         find_good_pkt_pointers(other_branch, dst_reg,
6809                                                dst_reg->type, true);
6810                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6811                             src_reg->type == PTR_TO_PACKET) ||
6812                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6813                             src_reg->type == PTR_TO_PACKET_META)) {
6814                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
6815                         find_good_pkt_pointers(this_branch, src_reg,
6816                                                src_reg->type, false);
6817                 } else {
6818                         return false;
6819                 }
6820                 break;
6821         case BPF_JGE:
6822                 if ((dst_reg->type == PTR_TO_PACKET &&
6823                      src_reg->type == PTR_TO_PACKET_END) ||
6824                     (dst_reg->type == PTR_TO_PACKET_META &&
6825                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6826                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
6827                         find_good_pkt_pointers(this_branch, dst_reg,
6828                                                dst_reg->type, true);
6829                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6830                             src_reg->type == PTR_TO_PACKET) ||
6831                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6832                             src_reg->type == PTR_TO_PACKET_META)) {
6833                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
6834                         find_good_pkt_pointers(other_branch, src_reg,
6835                                                src_reg->type, false);
6836                 } else {
6837                         return false;
6838                 }
6839                 break;
6840         case BPF_JLE:
6841                 if ((dst_reg->type == PTR_TO_PACKET &&
6842                      src_reg->type == PTR_TO_PACKET_END) ||
6843                     (dst_reg->type == PTR_TO_PACKET_META &&
6844                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6845                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
6846                         find_good_pkt_pointers(other_branch, dst_reg,
6847                                                dst_reg->type, false);
6848                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6849                             src_reg->type == PTR_TO_PACKET) ||
6850                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6851                             src_reg->type == PTR_TO_PACKET_META)) {
6852                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
6853                         find_good_pkt_pointers(this_branch, src_reg,
6854                                                src_reg->type, true);
6855                 } else {
6856                         return false;
6857                 }
6858                 break;
6859         default:
6860                 return false;
6861         }
6862
6863         return true;
6864 }
6865
6866 static int check_cond_jmp_op(struct bpf_verifier_env *env,
6867                              struct bpf_insn *insn, int *insn_idx)
6868 {
6869         struct bpf_verifier_state *this_branch = env->cur_state;
6870         struct bpf_verifier_state *other_branch;
6871         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
6872         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
6873         u8 opcode = BPF_OP(insn->code);
6874         bool is_jmp32;
6875         int pred = -1;
6876         int err;
6877
6878         /* Only conditional jumps are expected to reach here. */
6879         if (opcode == BPF_JA || opcode > BPF_JSLE) {
6880                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
6881                 return -EINVAL;
6882         }
6883
6884         if (BPF_SRC(insn->code) == BPF_X) {
6885                 if (insn->imm != 0) {
6886                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
6887                         return -EINVAL;
6888                 }
6889
6890                 /* check src1 operand */
6891                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6892                 if (err)
6893                         return err;
6894
6895                 if (is_pointer_value(env, insn->src_reg)) {
6896                         verbose(env, "R%d pointer comparison prohibited\n",
6897                                 insn->src_reg);
6898                         return -EACCES;
6899                 }
6900                 src_reg = &regs[insn->src_reg];
6901         } else {
6902                 if (insn->src_reg != BPF_REG_0) {
6903                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
6904                         return -EINVAL;
6905                 }
6906         }
6907
6908         /* check src2 operand */
6909         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6910         if (err)
6911                 return err;
6912
6913         dst_reg = &regs[insn->dst_reg];
6914         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
6915
6916         if (BPF_SRC(insn->code) == BPF_K) {
6917                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
6918         } else if (src_reg->type == SCALAR_VALUE &&
6919                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
6920                 pred = is_branch_taken(dst_reg,
6921                                        tnum_subreg(src_reg->var_off).value,
6922                                        opcode,
6923                                        is_jmp32);
6924         } else if (src_reg->type == SCALAR_VALUE &&
6925                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
6926                 pred = is_branch_taken(dst_reg,
6927                                        src_reg->var_off.value,
6928                                        opcode,
6929                                        is_jmp32);
6930         }
6931
6932         if (pred >= 0) {
6933                 /* If we get here with a dst_reg pointer type it is because
6934                  * above is_branch_taken() special cased the 0 comparison.
6935                  */
6936                 if (!__is_pointer_value(false, dst_reg))
6937                         err = mark_chain_precision(env, insn->dst_reg);
6938                 if (BPF_SRC(insn->code) == BPF_X && !err)
6939                         err = mark_chain_precision(env, insn->src_reg);
6940                 if (err)
6941                         return err;
6942         }
6943         if (pred == 1) {
6944                 /* only follow the goto, ignore fall-through */
6945                 *insn_idx += insn->off;
6946                 return 0;
6947         } else if (pred == 0) {
6948                 /* only follow fall-through branch, since
6949                  * that's where the program will go
6950                  */
6951                 return 0;
6952         }
6953
6954         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
6955                                   false);
6956         if (!other_branch)
6957                 return -EFAULT;
6958         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
6959
6960         /* detect if we are comparing against a constant value so we can adjust
6961          * our min/max values for our dst register.
6962          * this is only legit if both are scalars (or pointers to the same
6963          * object, I suppose, but we don't support that right now), because
6964          * otherwise the different base pointers mean the offsets aren't
6965          * comparable.
6966          */
6967         if (BPF_SRC(insn->code) == BPF_X) {
6968                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
6969
6970                 if (dst_reg->type == SCALAR_VALUE &&
6971                     src_reg->type == SCALAR_VALUE) {
6972                         if (tnum_is_const(src_reg->var_off) ||
6973                             (is_jmp32 &&
6974                              tnum_is_const(tnum_subreg(src_reg->var_off))))
6975                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
6976                                                 dst_reg,
6977                                                 src_reg->var_off.value,
6978                                                 tnum_subreg(src_reg->var_off).value,
6979                                                 opcode, is_jmp32);
6980                         else if (tnum_is_const(dst_reg->var_off) ||
6981                                  (is_jmp32 &&
6982                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
6983                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
6984                                                     src_reg,
6985                                                     dst_reg->var_off.value,
6986                                                     tnum_subreg(dst_reg->var_off).value,
6987                                                     opcode, is_jmp32);
6988                         else if (!is_jmp32 &&
6989                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
6990                                 /* Comparing for equality, we can combine knowledge */
6991                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
6992                                                     &other_branch_regs[insn->dst_reg],
6993                                                     src_reg, dst_reg, opcode);
6994                 }
6995         } else if (dst_reg->type == SCALAR_VALUE) {
6996                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
6997                                         dst_reg, insn->imm, (u32)insn->imm,
6998                                         opcode, is_jmp32);
6999         }
7000
7001         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
7002          * NOTE: these optimizations below are related with pointer comparison
7003          *       which will never be JMP32.
7004          */
7005         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
7006             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
7007             reg_type_may_be_null(dst_reg->type)) {
7008                 /* Mark all identical registers in each branch as either
7009                  * safe or unknown depending R == 0 or R != 0 conditional.
7010                  */
7011                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
7012                                       opcode == BPF_JNE);
7013                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
7014                                       opcode == BPF_JEQ);
7015         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
7016                                            this_branch, other_branch) &&
7017                    is_pointer_value(env, insn->dst_reg)) {
7018                 verbose(env, "R%d pointer comparison prohibited\n",
7019                         insn->dst_reg);
7020                 return -EACCES;
7021         }
7022         if (env->log.level & BPF_LOG_LEVEL)
7023                 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
7024         return 0;
7025 }
7026
7027 /* verify BPF_LD_IMM64 instruction */
7028 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
7029 {
7030         struct bpf_insn_aux_data *aux = cur_aux(env);
7031         struct bpf_reg_state *regs = cur_regs(env);
7032         struct bpf_map *map;
7033         int err;
7034
7035         if (BPF_SIZE(insn->code) != BPF_DW) {
7036                 verbose(env, "invalid BPF_LD_IMM insn\n");
7037                 return -EINVAL;
7038         }
7039         if (insn->off != 0) {
7040                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
7041                 return -EINVAL;
7042         }
7043
7044         err = check_reg_arg(env, insn->dst_reg, DST_OP);
7045         if (err)
7046                 return err;
7047
7048         if (insn->src_reg == 0) {
7049                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
7050
7051                 regs[insn->dst_reg].type = SCALAR_VALUE;
7052                 __mark_reg_known(&regs[insn->dst_reg], imm);
7053                 return 0;
7054         }
7055
7056         map = env->used_maps[aux->map_index];
7057         mark_reg_known_zero(env, regs, insn->dst_reg);
7058         regs[insn->dst_reg].map_ptr = map;
7059
7060         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
7061                 regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
7062                 regs[insn->dst_reg].off = aux->map_off;
7063                 if (map_value_has_spin_lock(map))
7064                         regs[insn->dst_reg].id = ++env->id_gen;
7065         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
7066                 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
7067         } else {
7068                 verbose(env, "bpf verifier is misconfigured\n");
7069                 return -EINVAL;
7070         }
7071
7072         return 0;
7073 }
7074
7075 static bool may_access_skb(enum bpf_prog_type type)
7076 {
7077         switch (type) {
7078         case BPF_PROG_TYPE_SOCKET_FILTER:
7079         case BPF_PROG_TYPE_SCHED_CLS:
7080         case BPF_PROG_TYPE_SCHED_ACT:
7081                 return true;
7082         default:
7083                 return false;
7084         }
7085 }
7086
7087 /* verify safety of LD_ABS|LD_IND instructions:
7088  * - they can only appear in the programs where ctx == skb
7089  * - since they are wrappers of function calls, they scratch R1-R5 registers,
7090  *   preserve R6-R9, and store return value into R0
7091  *
7092  * Implicit input:
7093  *   ctx == skb == R6 == CTX
7094  *
7095  * Explicit input:
7096  *   SRC == any register
7097  *   IMM == 32-bit immediate
7098  *
7099  * Output:
7100  *   R0 - 8/16/32-bit skb data converted to cpu endianness
7101  */
7102 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
7103 {
7104         struct bpf_reg_state *regs = cur_regs(env);
7105         static const int ctx_reg = BPF_REG_6;
7106         u8 mode = BPF_MODE(insn->code);
7107         int i, err;
7108
7109         if (!may_access_skb(env->prog->type)) {
7110                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
7111                 return -EINVAL;
7112         }
7113
7114         if (!env->ops->gen_ld_abs) {
7115                 verbose(env, "bpf verifier is misconfigured\n");
7116                 return -EINVAL;
7117         }
7118
7119         if (env->subprog_cnt > 1) {
7120                 /* when program has LD_ABS insn JITs and interpreter assume
7121                  * that r1 == ctx == skb which is not the case for callees
7122                  * that can have arbitrary arguments. It's problematic
7123                  * for main prog as well since JITs would need to analyze
7124                  * all functions in order to make proper register save/restore
7125                  * decisions in the main prog. Hence disallow LD_ABS with calls
7126                  */
7127                 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
7128                 return -EINVAL;
7129         }
7130
7131         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
7132             BPF_SIZE(insn->code) == BPF_DW ||
7133             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
7134                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
7135                 return -EINVAL;
7136         }
7137
7138         /* check whether implicit source operand (register R6) is readable */
7139         err = check_reg_arg(env, ctx_reg, SRC_OP);
7140         if (err)
7141                 return err;
7142
7143         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
7144          * gen_ld_abs() may terminate the program at runtime, leading to
7145          * reference leak.
7146          */
7147         err = check_reference_leak(env);
7148         if (err) {
7149                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
7150                 return err;
7151         }
7152
7153         if (env->cur_state->active_spin_lock) {
7154                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
7155                 return -EINVAL;
7156         }
7157
7158         if (regs[ctx_reg].type != PTR_TO_CTX) {
7159                 verbose(env,
7160                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
7161                 return -EINVAL;
7162         }
7163
7164         if (mode == BPF_IND) {
7165                 /* check explicit source operand */
7166                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7167                 if (err)
7168                         return err;
7169         }
7170
7171         err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
7172         if (err < 0)
7173                 return err;
7174
7175         /* reset caller saved regs to unreadable */
7176         for (i = 0; i < CALLER_SAVED_REGS; i++) {
7177                 mark_reg_not_init(env, regs, caller_saved[i]);
7178                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7179         }
7180
7181         /* mark destination R0 register as readable, since it contains
7182          * the value fetched from the packet.
7183          * Already marked as written above.
7184          */
7185         mark_reg_unknown(env, regs, BPF_REG_0);
7186         /* ld_abs load up to 32-bit skb data. */
7187         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
7188         return 0;
7189 }
7190
7191 static int check_return_code(struct bpf_verifier_env *env)
7192 {
7193         struct tnum enforce_attach_type_range = tnum_unknown;
7194         const struct bpf_prog *prog = env->prog;
7195         struct bpf_reg_state *reg;
7196         struct tnum range = tnum_range(0, 1);
7197         int err;
7198
7199         /* LSM and struct_ops func-ptr's return type could be "void" */
7200         if ((env->prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
7201              env->prog->type == BPF_PROG_TYPE_LSM) &&
7202             !prog->aux->attach_func_proto->type)
7203                 return 0;
7204
7205         /* eBPF calling convetion is such that R0 is used
7206          * to return the value from eBPF program.
7207          * Make sure that it's readable at this time
7208          * of bpf_exit, which means that program wrote
7209          * something into it earlier
7210          */
7211         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
7212         if (err)
7213                 return err;
7214
7215         if (is_pointer_value(env, BPF_REG_0)) {
7216                 verbose(env, "R0 leaks addr as return value\n");
7217                 return -EACCES;
7218         }
7219
7220         switch (env->prog->type) {
7221         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
7222                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
7223                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
7224                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
7225                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
7226                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
7227                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
7228                         range = tnum_range(1, 1);
7229                 break;
7230         case BPF_PROG_TYPE_CGROUP_SKB:
7231                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
7232                         range = tnum_range(0, 3);
7233                         enforce_attach_type_range = tnum_range(2, 3);
7234                 }
7235                 break;
7236         case BPF_PROG_TYPE_CGROUP_SOCK:
7237         case BPF_PROG_TYPE_SOCK_OPS:
7238         case BPF_PROG_TYPE_CGROUP_DEVICE:
7239         case BPF_PROG_TYPE_CGROUP_SYSCTL:
7240         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
7241                 break;
7242         case BPF_PROG_TYPE_RAW_TRACEPOINT:
7243                 if (!env->prog->aux->attach_btf_id)
7244                         return 0;
7245                 range = tnum_const(0);
7246                 break;
7247         case BPF_PROG_TYPE_TRACING:
7248                 switch (env->prog->expected_attach_type) {
7249                 case BPF_TRACE_FENTRY:
7250                 case BPF_TRACE_FEXIT:
7251                         range = tnum_const(0);
7252                         break;
7253                 case BPF_TRACE_RAW_TP:
7254                 case BPF_MODIFY_RETURN:
7255                         return 0;
7256                 case BPF_TRACE_ITER:
7257                         break;
7258                 default:
7259                         return -ENOTSUPP;
7260                 }
7261                 break;
7262         case BPF_PROG_TYPE_EXT:
7263                 /* freplace program can return anything as its return value
7264                  * depends on the to-be-replaced kernel func or bpf program.
7265                  */
7266         default:
7267                 return 0;
7268         }
7269
7270         reg = cur_regs(env) + BPF_REG_0;
7271         if (reg->type != SCALAR_VALUE) {
7272                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
7273                         reg_type_str[reg->type]);
7274                 return -EINVAL;
7275         }
7276
7277         if (!tnum_in(range, reg->var_off)) {
7278                 char tn_buf[48];
7279
7280                 verbose(env, "At program exit the register R0 ");
7281                 if (!tnum_is_unknown(reg->var_off)) {
7282                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7283                         verbose(env, "has value %s", tn_buf);
7284                 } else {
7285                         verbose(env, "has unknown scalar value");
7286                 }
7287                 tnum_strn(tn_buf, sizeof(tn_buf), range);
7288                 verbose(env, " should have been in %s\n", tn_buf);
7289                 return -EINVAL;
7290         }
7291
7292         if (!tnum_is_unknown(enforce_attach_type_range) &&
7293             tnum_in(enforce_attach_type_range, reg->var_off))
7294                 env->prog->enforce_expected_attach_type = 1;
7295         return 0;
7296 }
7297
7298 /* non-recursive DFS pseudo code
7299  * 1  procedure DFS-iterative(G,v):
7300  * 2      label v as discovered
7301  * 3      let S be a stack
7302  * 4      S.push(v)
7303  * 5      while S is not empty
7304  * 6            t <- S.pop()
7305  * 7            if t is what we're looking for:
7306  * 8                return t
7307  * 9            for all edges e in G.adjacentEdges(t) do
7308  * 10               if edge e is already labelled
7309  * 11                   continue with the next edge
7310  * 12               w <- G.adjacentVertex(t,e)
7311  * 13               if vertex w is not discovered and not explored
7312  * 14                   label e as tree-edge
7313  * 15                   label w as discovered
7314  * 16                   S.push(w)
7315  * 17                   continue at 5
7316  * 18               else if vertex w is discovered
7317  * 19                   label e as back-edge
7318  * 20               else
7319  * 21                   // vertex w is explored
7320  * 22                   label e as forward- or cross-edge
7321  * 23           label t as explored
7322  * 24           S.pop()
7323  *
7324  * convention:
7325  * 0x10 - discovered
7326  * 0x11 - discovered and fall-through edge labelled
7327  * 0x12 - discovered and fall-through and branch edges labelled
7328  * 0x20 - explored
7329  */
7330
7331 enum {
7332         DISCOVERED = 0x10,
7333         EXPLORED = 0x20,
7334         FALLTHROUGH = 1,
7335         BRANCH = 2,
7336 };
7337
7338 static u32 state_htab_size(struct bpf_verifier_env *env)
7339 {
7340         return env->prog->len;
7341 }
7342
7343 static struct bpf_verifier_state_list **explored_state(
7344                                         struct bpf_verifier_env *env,
7345                                         int idx)
7346 {
7347         struct bpf_verifier_state *cur = env->cur_state;
7348         struct bpf_func_state *state = cur->frame[cur->curframe];
7349
7350         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
7351 }
7352
7353 static void init_explored_state(struct bpf_verifier_env *env, int idx)
7354 {
7355         env->insn_aux_data[idx].prune_point = true;
7356 }
7357
7358 /* t, w, e - match pseudo-code above:
7359  * t - index of current instruction
7360  * w - next instruction
7361  * e - edge
7362  */
7363 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
7364                      bool loop_ok)
7365 {
7366         int *insn_stack = env->cfg.insn_stack;
7367         int *insn_state = env->cfg.insn_state;
7368
7369         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
7370                 return 0;
7371
7372         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
7373                 return 0;
7374
7375         if (w < 0 || w >= env->prog->len) {
7376                 verbose_linfo(env, t, "%d: ", t);
7377                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
7378                 return -EINVAL;
7379         }
7380
7381         if (e == BRANCH)
7382                 /* mark branch target for state pruning */
7383                 init_explored_state(env, w);
7384
7385         if (insn_state[w] == 0) {
7386                 /* tree-edge */
7387                 insn_state[t] = DISCOVERED | e;
7388                 insn_state[w] = DISCOVERED;
7389                 if (env->cfg.cur_stack >= env->prog->len)
7390                         return -E2BIG;
7391                 insn_stack[env->cfg.cur_stack++] = w;
7392                 return 1;
7393         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
7394                 if (loop_ok && env->bpf_capable)
7395                         return 0;
7396                 verbose_linfo(env, t, "%d: ", t);
7397                 verbose_linfo(env, w, "%d: ", w);
7398                 verbose(env, "back-edge from insn %d to %d\n", t, w);
7399                 return -EINVAL;
7400         } else if (insn_state[w] == EXPLORED) {
7401                 /* forward- or cross-edge */
7402                 insn_state[t] = DISCOVERED | e;
7403         } else {
7404                 verbose(env, "insn state internal bug\n");
7405                 return -EFAULT;
7406         }
7407         return 0;
7408 }
7409
7410 /* non-recursive depth-first-search to detect loops in BPF program
7411  * loop == back-edge in directed graph
7412  */
7413 static int check_cfg(struct bpf_verifier_env *env)
7414 {
7415         struct bpf_insn *insns = env->prog->insnsi;
7416         int insn_cnt = env->prog->len;
7417         int *insn_stack, *insn_state;
7418         int ret = 0;
7419         int i, t;
7420
7421         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
7422         if (!insn_state)
7423                 return -ENOMEM;
7424
7425         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
7426         if (!insn_stack) {
7427                 kvfree(insn_state);
7428                 return -ENOMEM;
7429         }
7430
7431         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
7432         insn_stack[0] = 0; /* 0 is the first instruction */
7433         env->cfg.cur_stack = 1;
7434
7435 peek_stack:
7436         if (env->cfg.cur_stack == 0)
7437                 goto check_state;
7438         t = insn_stack[env->cfg.cur_stack - 1];
7439
7440         if (BPF_CLASS(insns[t].code) == BPF_JMP ||
7441             BPF_CLASS(insns[t].code) == BPF_JMP32) {
7442                 u8 opcode = BPF_OP(insns[t].code);
7443
7444                 if (opcode == BPF_EXIT) {
7445                         goto mark_explored;
7446                 } else if (opcode == BPF_CALL) {
7447                         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
7448                         if (ret == 1)
7449                                 goto peek_stack;
7450                         else if (ret < 0)
7451                                 goto err_free;
7452                         if (t + 1 < insn_cnt)
7453                                 init_explored_state(env, t + 1);
7454                         if (insns[t].src_reg == BPF_PSEUDO_CALL) {
7455                                 init_explored_state(env, t);
7456                                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
7457                                                 env, false);
7458                                 if (ret == 1)
7459                                         goto peek_stack;
7460                                 else if (ret < 0)
7461                                         goto err_free;
7462                         }
7463                 } else if (opcode == BPF_JA) {
7464                         if (BPF_SRC(insns[t].code) != BPF_K) {
7465                                 ret = -EINVAL;
7466                                 goto err_free;
7467                         }
7468                         /* unconditional jump with single edge */
7469                         ret = push_insn(t, t + insns[t].off + 1,
7470                                         FALLTHROUGH, env, true);
7471                         if (ret == 1)
7472                                 goto peek_stack;
7473                         else if (ret < 0)
7474                                 goto err_free;
7475                         /* unconditional jmp is not a good pruning point,
7476                          * but it's marked, since backtracking needs
7477                          * to record jmp history in is_state_visited().
7478                          */
7479                         init_explored_state(env, t + insns[t].off + 1);
7480                         /* tell verifier to check for equivalent states
7481                          * after every call and jump
7482                          */
7483                         if (t + 1 < insn_cnt)
7484                                 init_explored_state(env, t + 1);
7485                 } else {
7486                         /* conditional jump with two edges */
7487                         init_explored_state(env, t);
7488                         ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
7489                         if (ret == 1)
7490                                 goto peek_stack;
7491                         else if (ret < 0)
7492                                 goto err_free;
7493
7494                         ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
7495                         if (ret == 1)
7496                                 goto peek_stack;
7497                         else if (ret < 0)
7498                                 goto err_free;
7499                 }
7500         } else {
7501                 /* all other non-branch instructions with single
7502                  * fall-through edge
7503                  */
7504                 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
7505                 if (ret == 1)
7506                         goto peek_stack;
7507                 else if (ret < 0)
7508                         goto err_free;
7509         }
7510
7511 mark_explored:
7512         insn_state[t] = EXPLORED;
7513         if (env->cfg.cur_stack-- <= 0) {
7514                 verbose(env, "pop stack internal bug\n");
7515                 ret = -EFAULT;
7516                 goto err_free;
7517         }
7518         goto peek_stack;
7519
7520 check_state:
7521         for (i = 0; i < insn_cnt; i++) {
7522                 if (insn_state[i] != EXPLORED) {
7523                         verbose(env, "unreachable insn %d\n", i);
7524                         ret = -EINVAL;
7525                         goto err_free;
7526                 }
7527         }
7528         ret = 0; /* cfg looks good */
7529
7530 err_free:
7531         kvfree(insn_state);
7532         kvfree(insn_stack);
7533         env->cfg.insn_state = env->cfg.insn_stack = NULL;
7534         return ret;
7535 }
7536
7537 /* The minimum supported BTF func info size */
7538 #define MIN_BPF_FUNCINFO_SIZE   8
7539 #define MAX_FUNCINFO_REC_SIZE   252
7540
7541 static int check_btf_func(struct bpf_verifier_env *env,
7542                           const union bpf_attr *attr,
7543                           union bpf_attr __user *uattr)
7544 {
7545         u32 i, nfuncs, urec_size, min_size;
7546         u32 krec_size = sizeof(struct bpf_func_info);
7547         struct bpf_func_info *krecord;
7548         struct bpf_func_info_aux *info_aux = NULL;
7549         const struct btf_type *type;
7550         struct bpf_prog *prog;
7551         const struct btf *btf;
7552         void __user *urecord;
7553         u32 prev_offset = 0;
7554         int ret = -ENOMEM;
7555
7556         nfuncs = attr->func_info_cnt;
7557         if (!nfuncs)
7558                 return 0;
7559
7560         if (nfuncs != env->subprog_cnt) {
7561                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
7562                 return -EINVAL;
7563         }
7564
7565         urec_size = attr->func_info_rec_size;
7566         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
7567             urec_size > MAX_FUNCINFO_REC_SIZE ||
7568             urec_size % sizeof(u32)) {
7569                 verbose(env, "invalid func info rec size %u\n", urec_size);
7570                 return -EINVAL;
7571         }
7572
7573         prog = env->prog;
7574         btf = prog->aux->btf;
7575
7576         urecord = u64_to_user_ptr(attr->func_info);
7577         min_size = min_t(u32, krec_size, urec_size);
7578
7579         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
7580         if (!krecord)
7581                 return -ENOMEM;
7582         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
7583         if (!info_aux)
7584                 goto err_free;
7585
7586         for (i = 0; i < nfuncs; i++) {
7587                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
7588                 if (ret) {
7589                         if (ret == -E2BIG) {
7590                                 verbose(env, "nonzero tailing record in func info");
7591                                 /* set the size kernel expects so loader can zero
7592                                  * out the rest of the record.
7593                                  */
7594                                 if (put_user(min_size, &uattr->func_info_rec_size))
7595                                         ret = -EFAULT;
7596                         }
7597                         goto err_free;
7598                 }
7599
7600                 if (copy_from_user(&krecord[i], urecord, min_size)) {
7601                         ret = -EFAULT;
7602                         goto err_free;
7603                 }
7604
7605                 /* check insn_off */
7606                 if (i == 0) {
7607                         if (krecord[i].insn_off) {
7608                                 verbose(env,
7609                                         "nonzero insn_off %u for the first func info record",
7610                                         krecord[i].insn_off);
7611                                 ret = -EINVAL;
7612                                 goto err_free;
7613                         }
7614                 } else if (krecord[i].insn_off <= prev_offset) {
7615                         verbose(env,
7616                                 "same or smaller insn offset (%u) than previous func info record (%u)",
7617                                 krecord[i].insn_off, prev_offset);
7618                         ret = -EINVAL;
7619                         goto err_free;
7620                 }
7621
7622                 if (env->subprog_info[i].start != krecord[i].insn_off) {
7623                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
7624                         ret = -EINVAL;
7625                         goto err_free;
7626                 }
7627
7628                 /* check type_id */
7629                 type = btf_type_by_id(btf, krecord[i].type_id);
7630                 if (!type || !btf_type_is_func(type)) {
7631                         verbose(env, "invalid type id %d in func info",
7632                                 krecord[i].type_id);
7633                         ret = -EINVAL;
7634                         goto err_free;
7635                 }
7636                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
7637                 prev_offset = krecord[i].insn_off;
7638                 urecord += urec_size;
7639         }
7640
7641         prog->aux->func_info = krecord;
7642         prog->aux->func_info_cnt = nfuncs;
7643         prog->aux->func_info_aux = info_aux;
7644         return 0;
7645
7646 err_free:
7647         kvfree(krecord);
7648         kfree(info_aux);
7649         return ret;
7650 }
7651
7652 static void adjust_btf_func(struct bpf_verifier_env *env)
7653 {
7654         struct bpf_prog_aux *aux = env->prog->aux;
7655         int i;
7656
7657         if (!aux->func_info)
7658                 return;
7659
7660         for (i = 0; i < env->subprog_cnt; i++)
7661                 aux->func_info[i].insn_off = env->subprog_info[i].start;
7662 }
7663
7664 #define MIN_BPF_LINEINFO_SIZE   (offsetof(struct bpf_line_info, line_col) + \
7665                 sizeof(((struct bpf_line_info *)(0))->line_col))
7666 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
7667
7668 static int check_btf_line(struct bpf_verifier_env *env,
7669                           const union bpf_attr *attr,
7670                           union bpf_attr __user *uattr)
7671 {
7672         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
7673         struct bpf_subprog_info *sub;
7674         struct bpf_line_info *linfo;
7675         struct bpf_prog *prog;
7676         const struct btf *btf;
7677         void __user *ulinfo;
7678         int err;
7679
7680         nr_linfo = attr->line_info_cnt;
7681         if (!nr_linfo)
7682                 return 0;
7683
7684         rec_size = attr->line_info_rec_size;
7685         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
7686             rec_size > MAX_LINEINFO_REC_SIZE ||
7687             rec_size & (sizeof(u32) - 1))
7688                 return -EINVAL;
7689
7690         /* Need to zero it in case the userspace may
7691          * pass in a smaller bpf_line_info object.
7692          */
7693         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
7694                          GFP_KERNEL | __GFP_NOWARN);
7695         if (!linfo)
7696                 return -ENOMEM;
7697
7698         prog = env->prog;
7699         btf = prog->aux->btf;
7700
7701         s = 0;
7702         sub = env->subprog_info;
7703         ulinfo = u64_to_user_ptr(attr->line_info);
7704         expected_size = sizeof(struct bpf_line_info);
7705         ncopy = min_t(u32, expected_size, rec_size);
7706         for (i = 0; i < nr_linfo; i++) {
7707                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
7708                 if (err) {
7709                         if (err == -E2BIG) {
7710                                 verbose(env, "nonzero tailing record in line_info");
7711                                 if (put_user(expected_size,
7712                                              &uattr->line_info_rec_size))
7713                                         err = -EFAULT;
7714                         }
7715                         goto err_free;
7716                 }
7717
7718                 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
7719                         err = -EFAULT;
7720                         goto err_free;
7721                 }
7722
7723                 /*
7724                  * Check insn_off to ensure
7725                  * 1) strictly increasing AND
7726                  * 2) bounded by prog->len
7727                  *
7728                  * The linfo[0].insn_off == 0 check logically falls into
7729                  * the later "missing bpf_line_info for func..." case
7730                  * because the first linfo[0].insn_off must be the
7731                  * first sub also and the first sub must have
7732                  * subprog_info[0].start == 0.
7733                  */
7734                 if ((i && linfo[i].insn_off <= prev_offset) ||
7735                     linfo[i].insn_off >= prog->len) {
7736                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
7737                                 i, linfo[i].insn_off, prev_offset,
7738                                 prog->len);
7739                         err = -EINVAL;
7740                         goto err_free;
7741                 }
7742
7743                 if (!prog->insnsi[linfo[i].insn_off].code) {
7744                         verbose(env,
7745                                 "Invalid insn code at line_info[%u].insn_off\n",
7746                                 i);
7747                         err = -EINVAL;
7748                         goto err_free;
7749                 }
7750
7751                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
7752                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
7753                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
7754                         err = -EINVAL;
7755                         goto err_free;
7756                 }
7757
7758                 if (s != env->subprog_cnt) {
7759                         if (linfo[i].insn_off == sub[s].start) {
7760                                 sub[s].linfo_idx = i;
7761                                 s++;
7762                         } else if (sub[s].start < linfo[i].insn_off) {
7763                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
7764                                 err = -EINVAL;
7765                                 goto err_free;
7766                         }
7767                 }
7768
7769                 prev_offset = linfo[i].insn_off;
7770                 ulinfo += rec_size;
7771         }
7772
7773         if (s != env->subprog_cnt) {
7774                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
7775                         env->subprog_cnt - s, s);
7776                 err = -EINVAL;
7777                 goto err_free;
7778         }
7779
7780         prog->aux->linfo = linfo;
7781         prog->aux->nr_linfo = nr_linfo;
7782
7783         return 0;
7784
7785 err_free:
7786         kvfree(linfo);
7787         return err;
7788 }
7789
7790 static int check_btf_info(struct bpf_verifier_env *env,
7791                           const union bpf_attr *attr,
7792                           union bpf_attr __user *uattr)
7793 {
7794         struct btf *btf;
7795         int err;
7796
7797         if (!attr->func_info_cnt && !attr->line_info_cnt)
7798                 return 0;
7799
7800         btf = btf_get_by_fd(attr->prog_btf_fd);
7801         if (IS_ERR(btf))
7802                 return PTR_ERR(btf);
7803         env->prog->aux->btf = btf;
7804
7805         err = check_btf_func(env, attr, uattr);
7806         if (err)
7807                 return err;
7808
7809         err = check_btf_line(env, attr, uattr);
7810         if (err)
7811                 return err;
7812
7813         return 0;
7814 }
7815
7816 /* check %cur's range satisfies %old's */
7817 static bool range_within(struct bpf_reg_state *old,
7818                          struct bpf_reg_state *cur)
7819 {
7820         return old->umin_value <= cur->umin_value &&
7821                old->umax_value >= cur->umax_value &&
7822                old->smin_value <= cur->smin_value &&
7823                old->smax_value >= cur->smax_value;
7824 }
7825
7826 /* Maximum number of register states that can exist at once */
7827 #define ID_MAP_SIZE     (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
7828 struct idpair {
7829         u32 old;
7830         u32 cur;
7831 };
7832
7833 /* If in the old state two registers had the same id, then they need to have
7834  * the same id in the new state as well.  But that id could be different from
7835  * the old state, so we need to track the mapping from old to new ids.
7836  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
7837  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
7838  * regs with a different old id could still have new id 9, we don't care about
7839  * that.
7840  * So we look through our idmap to see if this old id has been seen before.  If
7841  * so, we require the new id to match; otherwise, we add the id pair to the map.
7842  */
7843 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
7844 {
7845         unsigned int i;
7846
7847         for (i = 0; i < ID_MAP_SIZE; i++) {
7848                 if (!idmap[i].old) {
7849                         /* Reached an empty slot; haven't seen this id before */
7850                         idmap[i].old = old_id;
7851                         idmap[i].cur = cur_id;
7852                         return true;
7853                 }
7854                 if (idmap[i].old == old_id)
7855                         return idmap[i].cur == cur_id;
7856         }
7857         /* We ran out of idmap slots, which should be impossible */
7858         WARN_ON_ONCE(1);
7859         return false;
7860 }
7861
7862 static void clean_func_state(struct bpf_verifier_env *env,
7863                              struct bpf_func_state *st)
7864 {
7865         enum bpf_reg_liveness live;
7866         int i, j;
7867
7868         for (i = 0; i < BPF_REG_FP; i++) {
7869                 live = st->regs[i].live;
7870                 /* liveness must not touch this register anymore */
7871                 st->regs[i].live |= REG_LIVE_DONE;
7872                 if (!(live & REG_LIVE_READ))
7873                         /* since the register is unused, clear its state
7874                          * to make further comparison simpler
7875                          */
7876                         __mark_reg_not_init(env, &st->regs[i]);
7877         }
7878
7879         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
7880                 live = st->stack[i].spilled_ptr.live;
7881                 /* liveness must not touch this stack slot anymore */
7882                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
7883                 if (!(live & REG_LIVE_READ)) {
7884                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
7885                         for (j = 0; j < BPF_REG_SIZE; j++)
7886                                 st->stack[i].slot_type[j] = STACK_INVALID;
7887                 }
7888         }
7889 }
7890
7891 static void clean_verifier_state(struct bpf_verifier_env *env,
7892                                  struct bpf_verifier_state *st)
7893 {
7894         int i;
7895
7896         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
7897                 /* all regs in this state in all frames were already marked */
7898                 return;
7899
7900         for (i = 0; i <= st->curframe; i++)
7901                 clean_func_state(env, st->frame[i]);
7902 }
7903
7904 /* the parentage chains form a tree.
7905  * the verifier states are added to state lists at given insn and
7906  * pushed into state stack for future exploration.
7907  * when the verifier reaches bpf_exit insn some of the verifer states
7908  * stored in the state lists have their final liveness state already,
7909  * but a lot of states will get revised from liveness point of view when
7910  * the verifier explores other branches.
7911  * Example:
7912  * 1: r0 = 1
7913  * 2: if r1 == 100 goto pc+1
7914  * 3: r0 = 2
7915  * 4: exit
7916  * when the verifier reaches exit insn the register r0 in the state list of
7917  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
7918  * of insn 2 and goes exploring further. At the insn 4 it will walk the
7919  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
7920  *
7921  * Since the verifier pushes the branch states as it sees them while exploring
7922  * the program the condition of walking the branch instruction for the second
7923  * time means that all states below this branch were already explored and
7924  * their final liveness markes are already propagated.
7925  * Hence when the verifier completes the search of state list in is_state_visited()
7926  * we can call this clean_live_states() function to mark all liveness states
7927  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
7928  * will not be used.
7929  * This function also clears the registers and stack for states that !READ
7930  * to simplify state merging.
7931  *
7932  * Important note here that walking the same branch instruction in the callee
7933  * doesn't meant that the states are DONE. The verifier has to compare
7934  * the callsites
7935  */
7936 static void clean_live_states(struct bpf_verifier_env *env, int insn,
7937                               struct bpf_verifier_state *cur)
7938 {
7939         struct bpf_verifier_state_list *sl;
7940         int i;
7941
7942         sl = *explored_state(env, insn);
7943         while (sl) {
7944                 if (sl->state.branches)
7945                         goto next;
7946                 if (sl->state.insn_idx != insn ||
7947                     sl->state.curframe != cur->curframe)
7948                         goto next;
7949                 for (i = 0; i <= cur->curframe; i++)
7950                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
7951                                 goto next;
7952                 clean_verifier_state(env, &sl->state);
7953 next:
7954                 sl = sl->next;
7955         }
7956 }
7957
7958 /* Returns true if (rold safe implies rcur safe) */
7959 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7960                     struct idpair *idmap)
7961 {
7962         bool equal;
7963
7964         if (!(rold->live & REG_LIVE_READ))
7965                 /* explored state didn't use this */
7966                 return true;
7967
7968         equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
7969
7970         if (rold->type == PTR_TO_STACK)
7971                 /* two stack pointers are equal only if they're pointing to
7972                  * the same stack frame, since fp-8 in foo != fp-8 in bar
7973                  */
7974                 return equal && rold->frameno == rcur->frameno;
7975
7976         if (equal)
7977                 return true;
7978
7979         if (rold->type == NOT_INIT)
7980                 /* explored state can't have used this */
7981                 return true;
7982         if (rcur->type == NOT_INIT)
7983                 return false;
7984         switch (rold->type) {
7985         case SCALAR_VALUE:
7986                 if (rcur->type == SCALAR_VALUE) {
7987                         if (!rold->precise && !rcur->precise)
7988                                 return true;
7989                         /* new val must satisfy old val knowledge */
7990                         return range_within(rold, rcur) &&
7991                                tnum_in(rold->var_off, rcur->var_off);
7992                 } else {
7993                         /* We're trying to use a pointer in place of a scalar.
7994                          * Even if the scalar was unbounded, this could lead to
7995                          * pointer leaks because scalars are allowed to leak
7996                          * while pointers are not. We could make this safe in
7997                          * special cases if root is calling us, but it's
7998                          * probably not worth the hassle.
7999                          */
8000                         return false;
8001                 }
8002         case PTR_TO_MAP_VALUE:
8003                 /* If the new min/max/var_off satisfy the old ones and
8004                  * everything else matches, we are OK.
8005                  * 'id' is not compared, since it's only used for maps with
8006                  * bpf_spin_lock inside map element and in such cases if
8007                  * the rest of the prog is valid for one map element then
8008                  * it's valid for all map elements regardless of the key
8009                  * used in bpf_map_lookup()
8010                  */
8011                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
8012                        range_within(rold, rcur) &&
8013                        tnum_in(rold->var_off, rcur->var_off);
8014         case PTR_TO_MAP_VALUE_OR_NULL:
8015                 /* a PTR_TO_MAP_VALUE could be safe to use as a
8016                  * PTR_TO_MAP_VALUE_OR_NULL into the same map.
8017                  * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
8018                  * checked, doing so could have affected others with the same
8019                  * id, and we can't check for that because we lost the id when
8020                  * we converted to a PTR_TO_MAP_VALUE.
8021                  */
8022                 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
8023                         return false;
8024                 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
8025                         return false;
8026                 /* Check our ids match any regs they're supposed to */
8027                 return check_ids(rold->id, rcur->id, idmap);
8028         case PTR_TO_PACKET_META:
8029         case PTR_TO_PACKET:
8030                 if (rcur->type != rold->type)
8031                         return false;
8032                 /* We must have at least as much range as the old ptr
8033                  * did, so that any accesses which were safe before are
8034                  * still safe.  This is true even if old range < old off,
8035                  * since someone could have accessed through (ptr - k), or
8036                  * even done ptr -= k in a register, to get a safe access.
8037                  */
8038                 if (rold->range > rcur->range)
8039                         return false;
8040                 /* If the offsets don't match, we can't trust our alignment;
8041                  * nor can we be sure that we won't fall out of range.
8042                  */
8043                 if (rold->off != rcur->off)
8044                         return false;
8045                 /* id relations must be preserved */
8046                 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
8047                         return false;
8048                 /* new val must satisfy old val knowledge */
8049                 return range_within(rold, rcur) &&
8050                        tnum_in(rold->var_off, rcur->var_off);
8051         case PTR_TO_CTX:
8052         case CONST_PTR_TO_MAP:
8053         case PTR_TO_PACKET_END:
8054         case PTR_TO_FLOW_KEYS:
8055         case PTR_TO_SOCKET:
8056         case PTR_TO_SOCKET_OR_NULL:
8057         case PTR_TO_SOCK_COMMON:
8058         case PTR_TO_SOCK_COMMON_OR_NULL:
8059         case PTR_TO_TCP_SOCK:
8060         case PTR_TO_TCP_SOCK_OR_NULL:
8061         case PTR_TO_XDP_SOCK:
8062                 /* Only valid matches are exact, which memcmp() above
8063                  * would have accepted
8064                  */
8065         default:
8066                 /* Don't know what's going on, just say it's not safe */
8067                 return false;
8068         }
8069
8070         /* Shouldn't get here; if we do, say it's not safe */
8071         WARN_ON_ONCE(1);
8072         return false;
8073 }
8074
8075 static bool stacksafe(struct bpf_func_state *old,
8076                       struct bpf_func_state *cur,
8077                       struct idpair *idmap)
8078 {
8079         int i, spi;
8080
8081         /* walk slots of the explored stack and ignore any additional
8082          * slots in the current stack, since explored(safe) state
8083          * didn't use them
8084          */
8085         for (i = 0; i < old->allocated_stack; i++) {
8086                 spi = i / BPF_REG_SIZE;
8087
8088                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
8089                         i += BPF_REG_SIZE - 1;
8090                         /* explored state didn't use this */
8091                         continue;
8092                 }
8093
8094                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
8095                         continue;
8096
8097                 /* explored stack has more populated slots than current stack
8098                  * and these slots were used
8099                  */
8100                 if (i >= cur->allocated_stack)
8101                         return false;
8102
8103                 /* if old state was safe with misc data in the stack
8104                  * it will be safe with zero-initialized stack.
8105                  * The opposite is not true
8106                  */
8107                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
8108                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
8109                         continue;
8110                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
8111                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
8112                         /* Ex: old explored (safe) state has STACK_SPILL in
8113                          * this stack slot, but current has has STACK_MISC ->
8114                          * this verifier states are not equivalent,
8115                          * return false to continue verification of this path
8116                          */
8117                         return false;
8118                 if (i % BPF_REG_SIZE)
8119                         continue;
8120                 if (old->stack[spi].slot_type[0] != STACK_SPILL)
8121                         continue;
8122                 if (!regsafe(&old->stack[spi].spilled_ptr,
8123                              &cur->stack[spi].spilled_ptr,
8124                              idmap))
8125                         /* when explored and current stack slot are both storing
8126                          * spilled registers, check that stored pointers types
8127                          * are the same as well.
8128                          * Ex: explored safe path could have stored
8129                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
8130                          * but current path has stored:
8131                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
8132                          * such verifier states are not equivalent.
8133                          * return false to continue verification of this path
8134                          */
8135                         return false;
8136         }
8137         return true;
8138 }
8139
8140 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
8141 {
8142         if (old->acquired_refs != cur->acquired_refs)
8143                 return false;
8144         return !memcmp(old->refs, cur->refs,
8145                        sizeof(*old->refs) * old->acquired_refs);
8146 }
8147
8148 /* compare two verifier states
8149  *
8150  * all states stored in state_list are known to be valid, since
8151  * verifier reached 'bpf_exit' instruction through them
8152  *
8153  * this function is called when verifier exploring different branches of
8154  * execution popped from the state stack. If it sees an old state that has
8155  * more strict register state and more strict stack state then this execution
8156  * branch doesn't need to be explored further, since verifier already
8157  * concluded that more strict state leads to valid finish.
8158  *
8159  * Therefore two states are equivalent if register state is more conservative
8160  * and explored stack state is more conservative than the current one.
8161  * Example:
8162  *       explored                   current
8163  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
8164  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
8165  *
8166  * In other words if current stack state (one being explored) has more
8167  * valid slots than old one that already passed validation, it means
8168  * the verifier can stop exploring and conclude that current state is valid too
8169  *
8170  * Similarly with registers. If explored state has register type as invalid
8171  * whereas register type in current state is meaningful, it means that
8172  * the current state will reach 'bpf_exit' instruction safely
8173  */
8174 static bool func_states_equal(struct bpf_func_state *old,
8175                               struct bpf_func_state *cur)
8176 {
8177         struct idpair *idmap;
8178         bool ret = false;
8179         int i;
8180
8181         idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
8182         /* If we failed to allocate the idmap, just say it's not safe */
8183         if (!idmap)
8184                 return false;
8185
8186         for (i = 0; i < MAX_BPF_REG; i++) {
8187                 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
8188                         goto out_free;
8189         }
8190
8191         if (!stacksafe(old, cur, idmap))
8192                 goto out_free;
8193
8194         if (!refsafe(old, cur))
8195                 goto out_free;
8196         ret = true;
8197 out_free:
8198         kfree(idmap);
8199         return ret;
8200 }
8201
8202 static bool states_equal(struct bpf_verifier_env *env,
8203                          struct bpf_verifier_state *old,
8204                          struct bpf_verifier_state *cur)
8205 {
8206         int i;
8207
8208         if (old->curframe != cur->curframe)
8209                 return false;
8210
8211         /* Verification state from speculative execution simulation
8212          * must never prune a non-speculative execution one.
8213          */
8214         if (old->speculative && !cur->speculative)
8215                 return false;
8216
8217         if (old->active_spin_lock != cur->active_spin_lock)
8218                 return false;
8219
8220         /* for states to be equal callsites have to be the same
8221          * and all frame states need to be equivalent
8222          */
8223         for (i = 0; i <= old->curframe; i++) {
8224                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
8225                         return false;
8226                 if (!func_states_equal(old->frame[i], cur->frame[i]))
8227                         return false;
8228         }
8229         return true;
8230 }
8231
8232 /* Return 0 if no propagation happened. Return negative error code if error
8233  * happened. Otherwise, return the propagated bit.
8234  */
8235 static int propagate_liveness_reg(struct bpf_verifier_env *env,
8236                                   struct bpf_reg_state *reg,
8237                                   struct bpf_reg_state *parent_reg)
8238 {
8239         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
8240         u8 flag = reg->live & REG_LIVE_READ;
8241         int err;
8242
8243         /* When comes here, read flags of PARENT_REG or REG could be any of
8244          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
8245          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
8246          */
8247         if (parent_flag == REG_LIVE_READ64 ||
8248             /* Or if there is no read flag from REG. */
8249             !flag ||
8250             /* Or if the read flag from REG is the same as PARENT_REG. */
8251             parent_flag == flag)
8252                 return 0;
8253
8254         err = mark_reg_read(env, reg, parent_reg, flag);
8255         if (err)
8256                 return err;
8257
8258         return flag;
8259 }
8260
8261 /* A write screens off any subsequent reads; but write marks come from the
8262  * straight-line code between a state and its parent.  When we arrive at an
8263  * equivalent state (jump target or such) we didn't arrive by the straight-line
8264  * code, so read marks in the state must propagate to the parent regardless
8265  * of the state's write marks. That's what 'parent == state->parent' comparison
8266  * in mark_reg_read() is for.
8267  */
8268 static int propagate_liveness(struct bpf_verifier_env *env,
8269                               const struct bpf_verifier_state *vstate,
8270                               struct bpf_verifier_state *vparent)
8271 {
8272         struct bpf_reg_state *state_reg, *parent_reg;
8273         struct bpf_func_state *state, *parent;
8274         int i, frame, err = 0;
8275
8276         if (vparent->curframe != vstate->curframe) {
8277                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
8278                      vparent->curframe, vstate->curframe);
8279                 return -EFAULT;
8280         }
8281         /* Propagate read liveness of registers... */
8282         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
8283         for (frame = 0; frame <= vstate->curframe; frame++) {
8284                 parent = vparent->frame[frame];
8285                 state = vstate->frame[frame];
8286                 parent_reg = parent->regs;
8287                 state_reg = state->regs;
8288                 /* We don't need to worry about FP liveness, it's read-only */
8289                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
8290                         err = propagate_liveness_reg(env, &state_reg[i],
8291                                                      &parent_reg[i]);
8292                         if (err < 0)
8293                                 return err;
8294                         if (err == REG_LIVE_READ64)
8295                                 mark_insn_zext(env, &parent_reg[i]);
8296                 }
8297
8298                 /* Propagate stack slots. */
8299                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
8300                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
8301                         parent_reg = &parent->stack[i].spilled_ptr;
8302                         state_reg = &state->stack[i].spilled_ptr;
8303                         err = propagate_liveness_reg(env, state_reg,
8304                                                      parent_reg);
8305                         if (err < 0)
8306                                 return err;
8307                 }
8308         }
8309         return 0;
8310 }
8311
8312 /* find precise scalars in the previous equivalent state and
8313  * propagate them into the current state
8314  */
8315 static int propagate_precision(struct bpf_verifier_env *env,
8316                                const struct bpf_verifier_state *old)
8317 {
8318         struct bpf_reg_state *state_reg;
8319         struct bpf_func_state *state;
8320         int i, err = 0;
8321
8322         state = old->frame[old->curframe];
8323         state_reg = state->regs;
8324         for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
8325                 if (state_reg->type != SCALAR_VALUE ||
8326                     !state_reg->precise)
8327                         continue;
8328                 if (env->log.level & BPF_LOG_LEVEL2)
8329                         verbose(env, "propagating r%d\n", i);
8330                 err = mark_chain_precision(env, i);
8331                 if (err < 0)
8332                         return err;
8333         }
8334
8335         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8336                 if (state->stack[i].slot_type[0] != STACK_SPILL)
8337                         continue;
8338                 state_reg = &state->stack[i].spilled_ptr;
8339                 if (state_reg->type != SCALAR_VALUE ||
8340                     !state_reg->precise)
8341                         continue;
8342                 if (env->log.level & BPF_LOG_LEVEL2)
8343                         verbose(env, "propagating fp%d\n",
8344                                 (-i - 1) * BPF_REG_SIZE);
8345                 err = mark_chain_precision_stack(env, i);
8346                 if (err < 0)
8347                         return err;
8348         }
8349         return 0;
8350 }
8351
8352 static bool states_maybe_looping(struct bpf_verifier_state *old,
8353                                  struct bpf_verifier_state *cur)
8354 {
8355         struct bpf_func_state *fold, *fcur;
8356         int i, fr = cur->curframe;
8357
8358         if (old->curframe != fr)
8359                 return false;
8360
8361         fold = old->frame[fr];
8362         fcur = cur->frame[fr];
8363         for (i = 0; i < MAX_BPF_REG; i++)
8364                 if (memcmp(&fold->regs[i], &fcur->regs[i],
8365                            offsetof(struct bpf_reg_state, parent)))
8366                         return false;
8367         return true;
8368 }
8369
8370
8371 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
8372 {
8373         struct bpf_verifier_state_list *new_sl;
8374         struct bpf_verifier_state_list *sl, **pprev;
8375         struct bpf_verifier_state *cur = env->cur_state, *new;
8376         int i, j, err, states_cnt = 0;
8377         bool add_new_state = env->test_state_freq ? true : false;
8378
8379         cur->last_insn_idx = env->prev_insn_idx;
8380         if (!env->insn_aux_data[insn_idx].prune_point)
8381                 /* this 'insn_idx' instruction wasn't marked, so we will not
8382                  * be doing state search here
8383                  */
8384                 return 0;
8385
8386         /* bpf progs typically have pruning point every 4 instructions
8387          * http://vger.kernel.org/bpfconf2019.html#session-1
8388          * Do not add new state for future pruning if the verifier hasn't seen
8389          * at least 2 jumps and at least 8 instructions.
8390          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
8391          * In tests that amounts to up to 50% reduction into total verifier
8392          * memory consumption and 20% verifier time speedup.
8393          */
8394         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
8395             env->insn_processed - env->prev_insn_processed >= 8)
8396                 add_new_state = true;
8397
8398         pprev = explored_state(env, insn_idx);
8399         sl = *pprev;
8400
8401         clean_live_states(env, insn_idx, cur);
8402
8403         while (sl) {
8404                 states_cnt++;
8405                 if (sl->state.insn_idx != insn_idx)
8406                         goto next;
8407                 if (sl->state.branches) {
8408                         if (states_maybe_looping(&sl->state, cur) &&
8409                             states_equal(env, &sl->state, cur)) {
8410                                 verbose_linfo(env, insn_idx, "; ");
8411                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
8412                                 return -EINVAL;
8413                         }
8414                         /* if the verifier is processing a loop, avoid adding new state
8415                          * too often, since different loop iterations have distinct
8416                          * states and may not help future pruning.
8417                          * This threshold shouldn't be too low to make sure that
8418                          * a loop with large bound will be rejected quickly.
8419                          * The most abusive loop will be:
8420                          * r1 += 1
8421                          * if r1 < 1000000 goto pc-2
8422                          * 1M insn_procssed limit / 100 == 10k peak states.
8423                          * This threshold shouldn't be too high either, since states
8424                          * at the end of the loop are likely to be useful in pruning.
8425                          */
8426                         if (env->jmps_processed - env->prev_jmps_processed < 20 &&
8427                             env->insn_processed - env->prev_insn_processed < 100)
8428                                 add_new_state = false;
8429                         goto miss;
8430                 }
8431                 if (states_equal(env, &sl->state, cur)) {
8432                         sl->hit_cnt++;
8433                         /* reached equivalent register/stack state,
8434                          * prune the search.
8435                          * Registers read by the continuation are read by us.
8436                          * If we have any write marks in env->cur_state, they
8437                          * will prevent corresponding reads in the continuation
8438                          * from reaching our parent (an explored_state).  Our
8439                          * own state will get the read marks recorded, but
8440                          * they'll be immediately forgotten as we're pruning
8441                          * this state and will pop a new one.
8442                          */
8443                         err = propagate_liveness(env, &sl->state, cur);
8444
8445                         /* if previous state reached the exit with precision and
8446                          * current state is equivalent to it (except precsion marks)
8447                          * the precision needs to be propagated back in
8448                          * the current state.
8449                          */
8450                         err = err ? : push_jmp_history(env, cur);
8451                         err = err ? : propagate_precision(env, &sl->state);
8452                         if (err)
8453                                 return err;
8454                         return 1;
8455                 }
8456 miss:
8457                 /* when new state is not going to be added do not increase miss count.
8458                  * Otherwise several loop iterations will remove the state
8459                  * recorded earlier. The goal of these heuristics is to have
8460                  * states from some iterations of the loop (some in the beginning
8461                  * and some at the end) to help pruning.
8462                  */
8463                 if (add_new_state)
8464                         sl->miss_cnt++;
8465                 /* heuristic to determine whether this state is beneficial
8466                  * to keep checking from state equivalence point of view.
8467                  * Higher numbers increase max_states_per_insn and verification time,
8468                  * but do not meaningfully decrease insn_processed.
8469                  */
8470                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
8471                         /* the state is unlikely to be useful. Remove it to
8472                          * speed up verification
8473                          */
8474                         *pprev = sl->next;
8475                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
8476                                 u32 br = sl->state.branches;
8477
8478                                 WARN_ONCE(br,
8479                                           "BUG live_done but branches_to_explore %d\n",
8480                                           br);
8481                                 free_verifier_state(&sl->state, false);
8482                                 kfree(sl);
8483                                 env->peak_states--;
8484                         } else {
8485                                 /* cannot free this state, since parentage chain may
8486                                  * walk it later. Add it for free_list instead to
8487                                  * be freed at the end of verification
8488                                  */
8489                                 sl->next = env->free_list;
8490                                 env->free_list = sl;
8491                         }
8492                         sl = *pprev;
8493                         continue;
8494                 }
8495 next:
8496                 pprev = &sl->next;
8497                 sl = *pprev;
8498         }
8499
8500         if (env->max_states_per_insn < states_cnt)
8501                 env->max_states_per_insn = states_cnt;
8502
8503         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
8504                 return push_jmp_history(env, cur);
8505
8506         if (!add_new_state)
8507                 return push_jmp_history(env, cur);
8508
8509         /* There were no equivalent states, remember the current one.
8510          * Technically the current state is not proven to be safe yet,
8511          * but it will either reach outer most bpf_exit (which means it's safe)
8512          * or it will be rejected. When there are no loops the verifier won't be
8513          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
8514          * again on the way to bpf_exit.
8515          * When looping the sl->state.branches will be > 0 and this state
8516          * will not be considered for equivalence until branches == 0.
8517          */
8518         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
8519         if (!new_sl)
8520                 return -ENOMEM;
8521         env->total_states++;
8522         env->peak_states++;
8523         env->prev_jmps_processed = env->jmps_processed;
8524         env->prev_insn_processed = env->insn_processed;
8525
8526         /* add new state to the head of linked list */
8527         new = &new_sl->state;
8528         err = copy_verifier_state(new, cur);
8529         if (err) {
8530                 free_verifier_state(new, false);
8531                 kfree(new_sl);
8532                 return err;
8533         }
8534         new->insn_idx = insn_idx;
8535         WARN_ONCE(new->branches != 1,
8536                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
8537
8538         cur->parent = new;
8539         cur->first_insn_idx = insn_idx;
8540         clear_jmp_history(cur);
8541         new_sl->next = *explored_state(env, insn_idx);
8542         *explored_state(env, insn_idx) = new_sl;
8543         /* connect new state to parentage chain. Current frame needs all
8544          * registers connected. Only r6 - r9 of the callers are alive (pushed
8545          * to the stack implicitly by JITs) so in callers' frames connect just
8546          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
8547          * the state of the call instruction (with WRITTEN set), and r0 comes
8548          * from callee with its full parentage chain, anyway.
8549          */
8550         /* clear write marks in current state: the writes we did are not writes
8551          * our child did, so they don't screen off its reads from us.
8552          * (There are no read marks in current state, because reads always mark
8553          * their parent and current state never has children yet.  Only
8554          * explored_states can get read marks.)
8555          */
8556         for (j = 0; j <= cur->curframe; j++) {
8557                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
8558                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
8559                 for (i = 0; i < BPF_REG_FP; i++)
8560                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
8561         }
8562
8563         /* all stack frames are accessible from callee, clear them all */
8564         for (j = 0; j <= cur->curframe; j++) {
8565                 struct bpf_func_state *frame = cur->frame[j];
8566                 struct bpf_func_state *newframe = new->frame[j];
8567
8568                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
8569                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
8570                         frame->stack[i].spilled_ptr.parent =
8571                                                 &newframe->stack[i].spilled_ptr;
8572                 }
8573         }
8574         return 0;
8575 }
8576
8577 /* Return true if it's OK to have the same insn return a different type. */
8578 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
8579 {
8580         switch (type) {
8581         case PTR_TO_CTX:
8582         case PTR_TO_SOCKET:
8583         case PTR_TO_SOCKET_OR_NULL:
8584         case PTR_TO_SOCK_COMMON:
8585         case PTR_TO_SOCK_COMMON_OR_NULL:
8586         case PTR_TO_TCP_SOCK:
8587         case PTR_TO_TCP_SOCK_OR_NULL:
8588         case PTR_TO_XDP_SOCK:
8589         case PTR_TO_BTF_ID:
8590         case PTR_TO_BTF_ID_OR_NULL:
8591                 return false;
8592         default:
8593                 return true;
8594         }
8595 }
8596
8597 /* If an instruction was previously used with particular pointer types, then we
8598  * need to be careful to avoid cases such as the below, where it may be ok
8599  * for one branch accessing the pointer, but not ok for the other branch:
8600  *
8601  * R1 = sock_ptr
8602  * goto X;
8603  * ...
8604  * R1 = some_other_valid_ptr;
8605  * goto X;
8606  * ...
8607  * R2 = *(u32 *)(R1 + 0);
8608  */
8609 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
8610 {
8611         return src != prev && (!reg_type_mismatch_ok(src) ||
8612                                !reg_type_mismatch_ok(prev));
8613 }
8614
8615 static int do_check(struct bpf_verifier_env *env)
8616 {
8617         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
8618         struct bpf_verifier_state *state = env->cur_state;
8619         struct bpf_insn *insns = env->prog->insnsi;
8620         struct bpf_reg_state *regs;
8621         int insn_cnt = env->prog->len;
8622         bool do_print_state = false;
8623         int prev_insn_idx = -1;
8624
8625         for (;;) {
8626                 struct bpf_insn *insn;
8627                 u8 class;
8628                 int err;
8629
8630                 env->prev_insn_idx = prev_insn_idx;
8631                 if (env->insn_idx >= insn_cnt) {
8632                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
8633                                 env->insn_idx, insn_cnt);
8634                         return -EFAULT;
8635                 }
8636
8637                 insn = &insns[env->insn_idx];
8638                 class = BPF_CLASS(insn->code);
8639
8640                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
8641                         verbose(env,
8642                                 "BPF program is too large. Processed %d insn\n",
8643                                 env->insn_processed);
8644                         return -E2BIG;
8645                 }
8646
8647                 err = is_state_visited(env, env->insn_idx);
8648                 if (err < 0)
8649                         return err;
8650                 if (err == 1) {
8651                         /* found equivalent state, can prune the search */
8652                         if (env->log.level & BPF_LOG_LEVEL) {
8653                                 if (do_print_state)
8654                                         verbose(env, "\nfrom %d to %d%s: safe\n",
8655                                                 env->prev_insn_idx, env->insn_idx,
8656                                                 env->cur_state->speculative ?
8657                                                 " (speculative execution)" : "");
8658                                 else
8659                                         verbose(env, "%d: safe\n", env->insn_idx);
8660                         }
8661                         goto process_bpf_exit;
8662                 }
8663
8664                 if (signal_pending(current))
8665                         return -EAGAIN;
8666
8667                 if (need_resched())
8668                         cond_resched();
8669
8670                 if (env->log.level & BPF_LOG_LEVEL2 ||
8671                     (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
8672                         if (env->log.level & BPF_LOG_LEVEL2)
8673                                 verbose(env, "%d:", env->insn_idx);
8674                         else
8675                                 verbose(env, "\nfrom %d to %d%s:",
8676                                         env->prev_insn_idx, env->insn_idx,
8677                                         env->cur_state->speculative ?
8678                                         " (speculative execution)" : "");
8679                         print_verifier_state(env, state->frame[state->curframe]);
8680                         do_print_state = false;
8681                 }
8682
8683                 if (env->log.level & BPF_LOG_LEVEL) {
8684                         const struct bpf_insn_cbs cbs = {
8685                                 .cb_print       = verbose,
8686                                 .private_data   = env,
8687                         };
8688
8689                         verbose_linfo(env, env->insn_idx, "; ");
8690                         verbose(env, "%d: ", env->insn_idx);
8691                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
8692                 }
8693
8694                 if (bpf_prog_is_dev_bound(env->prog->aux)) {
8695                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
8696                                                            env->prev_insn_idx);
8697                         if (err)
8698                                 return err;
8699                 }
8700
8701                 regs = cur_regs(env);
8702                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8703                 prev_insn_idx = env->insn_idx;
8704
8705                 if (class == BPF_ALU || class == BPF_ALU64) {
8706                         err = check_alu_op(env, insn);
8707                         if (err)
8708                                 return err;
8709
8710                 } else if (class == BPF_LDX) {
8711                         enum bpf_reg_type *prev_src_type, src_reg_type;
8712
8713                         /* check for reserved fields is already done */
8714
8715                         /* check src operand */
8716                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
8717                         if (err)
8718                                 return err;
8719
8720                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8721                         if (err)
8722                                 return err;
8723
8724                         src_reg_type = regs[insn->src_reg].type;
8725
8726                         /* check that memory (src_reg + off) is readable,
8727                          * the state of dst_reg will be updated by this func
8728                          */
8729                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
8730                                                insn->off, BPF_SIZE(insn->code),
8731                                                BPF_READ, insn->dst_reg, false);
8732                         if (err)
8733                                 return err;
8734
8735                         prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
8736
8737                         if (*prev_src_type == NOT_INIT) {
8738                                 /* saw a valid insn
8739                                  * dst_reg = *(u32 *)(src_reg + off)
8740                                  * save type to validate intersecting paths
8741                                  */
8742                                 *prev_src_type = src_reg_type;
8743
8744                         } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
8745                                 /* ABuser program is trying to use the same insn
8746                                  * dst_reg = *(u32*) (src_reg + off)
8747                                  * with different pointer types:
8748                                  * src_reg == ctx in one branch and
8749                                  * src_reg == stack|map in some other branch.
8750                                  * Reject it.
8751                                  */
8752                                 verbose(env, "same insn cannot be used with different pointers\n");
8753                                 return -EINVAL;
8754                         }
8755
8756                 } else if (class == BPF_STX) {
8757                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
8758
8759                         if (BPF_MODE(insn->code) == BPF_XADD) {
8760                                 err = check_xadd(env, env->insn_idx, insn);
8761                                 if (err)
8762                                         return err;
8763                                 env->insn_idx++;
8764                                 continue;
8765                         }
8766
8767                         /* check src1 operand */
8768                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
8769                         if (err)
8770                                 return err;
8771                         /* check src2 operand */
8772                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8773                         if (err)
8774                                 return err;
8775
8776                         dst_reg_type = regs[insn->dst_reg].type;
8777
8778                         /* check that memory (dst_reg + off) is writeable */
8779                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
8780                                                insn->off, BPF_SIZE(insn->code),
8781                                                BPF_WRITE, insn->src_reg, false);
8782                         if (err)
8783                                 return err;
8784
8785                         prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
8786
8787                         if (*prev_dst_type == NOT_INIT) {
8788                                 *prev_dst_type = dst_reg_type;
8789                         } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
8790                                 verbose(env, "same insn cannot be used with different pointers\n");
8791                                 return -EINVAL;
8792                         }
8793
8794                 } else if (class == BPF_ST) {
8795                         if (BPF_MODE(insn->code) != BPF_MEM ||
8796                             insn->src_reg != BPF_REG_0) {
8797                                 verbose(env, "BPF_ST uses reserved fields\n");
8798                                 return -EINVAL;
8799                         }
8800                         /* check src operand */
8801                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8802                         if (err)
8803                                 return err;
8804
8805                         if (is_ctx_reg(env, insn->dst_reg)) {
8806                                 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
8807                                         insn->dst_reg,
8808                                         reg_type_str[reg_state(env, insn->dst_reg)->type]);
8809                                 return -EACCES;
8810                         }
8811
8812                         /* check that memory (dst_reg + off) is writeable */
8813                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
8814                                                insn->off, BPF_SIZE(insn->code),
8815                                                BPF_WRITE, -1, false);
8816                         if (err)
8817                                 return err;
8818
8819                 } else if (class == BPF_JMP || class == BPF_JMP32) {
8820                         u8 opcode = BPF_OP(insn->code);
8821
8822                         env->jmps_processed++;
8823                         if (opcode == BPF_CALL) {
8824                                 if (BPF_SRC(insn->code) != BPF_K ||
8825                                     insn->off != 0 ||
8826                                     (insn->src_reg != BPF_REG_0 &&
8827                                      insn->src_reg != BPF_PSEUDO_CALL) ||
8828                                     insn->dst_reg != BPF_REG_0 ||
8829                                     class == BPF_JMP32) {
8830                                         verbose(env, "BPF_CALL uses reserved fields\n");
8831                                         return -EINVAL;
8832                                 }
8833
8834                                 if (env->cur_state->active_spin_lock &&
8835                                     (insn->src_reg == BPF_PSEUDO_CALL ||
8836                                      insn->imm != BPF_FUNC_spin_unlock)) {
8837                                         verbose(env, "function calls are not allowed while holding a lock\n");
8838                                         return -EINVAL;
8839                                 }
8840                                 if (insn->src_reg == BPF_PSEUDO_CALL)
8841                                         err = check_func_call(env, insn, &env->insn_idx);
8842                                 else
8843                                         err = check_helper_call(env, insn->imm, env->insn_idx);
8844                                 if (err)
8845                                         return err;
8846
8847                         } else if (opcode == BPF_JA) {
8848                                 if (BPF_SRC(insn->code) != BPF_K ||
8849                                     insn->imm != 0 ||
8850                                     insn->src_reg != BPF_REG_0 ||
8851                                     insn->dst_reg != BPF_REG_0 ||
8852                                     class == BPF_JMP32) {
8853                                         verbose(env, "BPF_JA uses reserved fields\n");
8854                                         return -EINVAL;
8855                                 }
8856
8857                                 env->insn_idx += insn->off + 1;
8858                                 continue;
8859
8860                         } else if (opcode == BPF_EXIT) {
8861                                 if (BPF_SRC(insn->code) != BPF_K ||
8862                                     insn->imm != 0 ||
8863                                     insn->src_reg != BPF_REG_0 ||
8864                                     insn->dst_reg != BPF_REG_0 ||
8865                                     class == BPF_JMP32) {
8866                                         verbose(env, "BPF_EXIT uses reserved fields\n");
8867                                         return -EINVAL;
8868                                 }
8869
8870                                 if (env->cur_state->active_spin_lock) {
8871                                         verbose(env, "bpf_spin_unlock is missing\n");
8872                                         return -EINVAL;
8873                                 }
8874
8875                                 if (state->curframe) {
8876                                         /* exit from nested function */
8877                                         err = prepare_func_exit(env, &env->insn_idx);
8878                                         if (err)
8879                                                 return err;
8880                                         do_print_state = true;
8881                                         continue;
8882                                 }
8883
8884                                 err = check_reference_leak(env);
8885                                 if (err)
8886                                         return err;
8887
8888                                 err = check_return_code(env);
8889                                 if (err)
8890                                         return err;
8891 process_bpf_exit:
8892                                 update_branch_counts(env, env->cur_state);
8893                                 err = pop_stack(env, &prev_insn_idx,
8894                                                 &env->insn_idx, pop_log);
8895                                 if (err < 0) {
8896                                         if (err != -ENOENT)
8897                                                 return err;
8898                                         break;
8899                                 } else {
8900                                         do_print_state = true;
8901                                         continue;
8902                                 }
8903                         } else {
8904                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
8905                                 if (err)
8906                                         return err;
8907                         }
8908                 } else if (class == BPF_LD) {
8909                         u8 mode = BPF_MODE(insn->code);
8910
8911                         if (mode == BPF_ABS || mode == BPF_IND) {
8912                                 err = check_ld_abs(env, insn);
8913                                 if (err)
8914                                         return err;
8915
8916                         } else if (mode == BPF_IMM) {
8917                                 err = check_ld_imm(env, insn);
8918                                 if (err)
8919                                         return err;
8920
8921                                 env->insn_idx++;
8922                                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8923                         } else {
8924                                 verbose(env, "invalid BPF_LD mode\n");
8925                                 return -EINVAL;
8926                         }
8927                 } else {
8928                         verbose(env, "unknown insn class %d\n", class);
8929                         return -EINVAL;
8930                 }
8931
8932                 env->insn_idx++;
8933         }
8934
8935         return 0;
8936 }
8937
8938 static int check_map_prealloc(struct bpf_map *map)
8939 {
8940         return (map->map_type != BPF_MAP_TYPE_HASH &&
8941                 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8942                 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
8943                 !(map->map_flags & BPF_F_NO_PREALLOC);
8944 }
8945
8946 static bool is_tracing_prog_type(enum bpf_prog_type type)
8947 {
8948         switch (type) {
8949         case BPF_PROG_TYPE_KPROBE:
8950         case BPF_PROG_TYPE_TRACEPOINT:
8951         case BPF_PROG_TYPE_PERF_EVENT:
8952         case BPF_PROG_TYPE_RAW_TRACEPOINT:
8953                 return true;
8954         default:
8955                 return false;
8956         }
8957 }
8958
8959 static bool is_preallocated_map(struct bpf_map *map)
8960 {
8961         if (!check_map_prealloc(map))
8962                 return false;
8963         if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
8964                 return false;
8965         return true;
8966 }
8967
8968 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
8969                                         struct bpf_map *map,
8970                                         struct bpf_prog *prog)
8971
8972 {
8973         /*
8974          * Validate that trace type programs use preallocated hash maps.
8975          *
8976          * For programs attached to PERF events this is mandatory as the
8977          * perf NMI can hit any arbitrary code sequence.
8978          *
8979          * All other trace types using preallocated hash maps are unsafe as
8980          * well because tracepoint or kprobes can be inside locked regions
8981          * of the memory allocator or at a place where a recursion into the
8982          * memory allocator would see inconsistent state.
8983          *
8984          * On RT enabled kernels run-time allocation of all trace type
8985          * programs is strictly prohibited due to lock type constraints. On
8986          * !RT kernels it is allowed for backwards compatibility reasons for
8987          * now, but warnings are emitted so developers are made aware of
8988          * the unsafety and can fix their programs before this is enforced.
8989          */
8990         if (is_tracing_prog_type(prog->type) && !is_preallocated_map(map)) {
8991                 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
8992                         verbose(env, "perf_event programs can only use preallocated hash map\n");
8993                         return -EINVAL;
8994                 }
8995                 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
8996                         verbose(env, "trace type programs can only use preallocated hash map\n");
8997                         return -EINVAL;
8998                 }
8999                 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
9000                 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
9001         }
9002
9003         if ((is_tracing_prog_type(prog->type) ||
9004              prog->type == BPF_PROG_TYPE_SOCKET_FILTER) &&
9005             map_value_has_spin_lock(map)) {
9006                 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
9007                 return -EINVAL;
9008         }
9009
9010         if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
9011             !bpf_offload_prog_map_match(prog, map)) {
9012                 verbose(env, "offload device mismatch between prog and map\n");
9013                 return -EINVAL;
9014         }
9015
9016         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
9017                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
9018                 return -EINVAL;
9019         }
9020
9021         return 0;
9022 }
9023
9024 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
9025 {
9026         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
9027                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
9028 }
9029
9030 /* look for pseudo eBPF instructions that access map FDs and
9031  * replace them with actual map pointers
9032  */
9033 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
9034 {
9035         struct bpf_insn *insn = env->prog->insnsi;
9036         int insn_cnt = env->prog->len;
9037         int i, j, err;
9038
9039         err = bpf_prog_calc_tag(env->prog);
9040         if (err)
9041                 return err;
9042
9043         for (i = 0; i < insn_cnt; i++, insn++) {
9044                 if (BPF_CLASS(insn->code) == BPF_LDX &&
9045                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
9046                         verbose(env, "BPF_LDX uses reserved fields\n");
9047                         return -EINVAL;
9048                 }
9049
9050                 if (BPF_CLASS(insn->code) == BPF_STX &&
9051                     ((BPF_MODE(insn->code) != BPF_MEM &&
9052                       BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
9053                         verbose(env, "BPF_STX uses reserved fields\n");
9054                         return -EINVAL;
9055                 }
9056
9057                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
9058                         struct bpf_insn_aux_data *aux;
9059                         struct bpf_map *map;
9060                         struct fd f;
9061                         u64 addr;
9062
9063                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
9064                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
9065                             insn[1].off != 0) {
9066                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
9067                                 return -EINVAL;
9068                         }
9069
9070                         if (insn[0].src_reg == 0)
9071                                 /* valid generic load 64-bit imm */
9072                                 goto next_insn;
9073
9074                         /* In final convert_pseudo_ld_imm64() step, this is
9075                          * converted into regular 64-bit imm load insn.
9076                          */
9077                         if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
9078                              insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
9079                             (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
9080                              insn[1].imm != 0)) {
9081                                 verbose(env,
9082                                         "unrecognized bpf_ld_imm64 insn\n");
9083                                 return -EINVAL;
9084                         }
9085
9086                         f = fdget(insn[0].imm);
9087                         map = __bpf_map_get(f);
9088                         if (IS_ERR(map)) {
9089                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
9090                                         insn[0].imm);
9091                                 return PTR_ERR(map);
9092                         }
9093
9094                         err = check_map_prog_compatibility(env, map, env->prog);
9095                         if (err) {
9096                                 fdput(f);
9097                                 return err;
9098                         }
9099
9100                         aux = &env->insn_aux_data[i];
9101                         if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
9102                                 addr = (unsigned long)map;
9103                         } else {
9104                                 u32 off = insn[1].imm;
9105
9106                                 if (off >= BPF_MAX_VAR_OFF) {
9107                                         verbose(env, "direct value offset of %u is not allowed\n", off);
9108                                         fdput(f);
9109                                         return -EINVAL;
9110                                 }
9111
9112                                 if (!map->ops->map_direct_value_addr) {
9113                                         verbose(env, "no direct value access support for this map type\n");
9114                                         fdput(f);
9115                                         return -EINVAL;
9116                                 }
9117
9118                                 err = map->ops->map_direct_value_addr(map, &addr, off);
9119                                 if (err) {
9120                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
9121                                                 map->value_size, off);
9122                                         fdput(f);
9123                                         return err;
9124                                 }
9125
9126                                 aux->map_off = off;
9127                                 addr += off;
9128                         }
9129
9130                         insn[0].imm = (u32)addr;
9131                         insn[1].imm = addr >> 32;
9132
9133                         /* check whether we recorded this map already */
9134                         for (j = 0; j < env->used_map_cnt; j++) {
9135                                 if (env->used_maps[j] == map) {
9136                                         aux->map_index = j;
9137                                         fdput(f);
9138                                         goto next_insn;
9139                                 }
9140                         }
9141
9142                         if (env->used_map_cnt >= MAX_USED_MAPS) {
9143                                 fdput(f);
9144                                 return -E2BIG;
9145                         }
9146
9147                         /* hold the map. If the program is rejected by verifier,
9148                          * the map will be released by release_maps() or it
9149                          * will be used by the valid program until it's unloaded
9150                          * and all maps are released in free_used_maps()
9151                          */
9152                         bpf_map_inc(map);
9153
9154                         aux->map_index = env->used_map_cnt;
9155                         env->used_maps[env->used_map_cnt++] = map;
9156
9157                         if (bpf_map_is_cgroup_storage(map) &&
9158                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
9159                                 verbose(env, "only one cgroup storage of each type is allowed\n");
9160                                 fdput(f);
9161                                 return -EBUSY;
9162                         }
9163
9164                         fdput(f);
9165 next_insn:
9166                         insn++;
9167                         i++;
9168                         continue;
9169                 }
9170
9171                 /* Basic sanity check before we invest more work here. */
9172                 if (!bpf_opcode_in_insntable(insn->code)) {
9173                         verbose(env, "unknown opcode %02x\n", insn->code);
9174                         return -EINVAL;
9175                 }
9176         }
9177
9178         /* now all pseudo BPF_LD_IMM64 instructions load valid
9179          * 'struct bpf_map *' into a register instead of user map_fd.
9180          * These pointers will be used later by verifier to validate map access.
9181          */
9182         return 0;
9183 }
9184
9185 /* drop refcnt of maps used by the rejected program */
9186 static void release_maps(struct bpf_verifier_env *env)
9187 {
9188         __bpf_free_used_maps(env->prog->aux, env->used_maps,
9189                              env->used_map_cnt);
9190 }
9191
9192 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
9193 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
9194 {
9195         struct bpf_insn *insn = env->prog->insnsi;
9196         int insn_cnt = env->prog->len;
9197         int i;
9198
9199         for (i = 0; i < insn_cnt; i++, insn++)
9200                 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
9201                         insn->src_reg = 0;
9202 }
9203
9204 /* single env->prog->insni[off] instruction was replaced with the range
9205  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
9206  * [0, off) and [off, end) to new locations, so the patched range stays zero
9207  */
9208 static int adjust_insn_aux_data(struct bpf_verifier_env *env,
9209                                 struct bpf_prog *new_prog, u32 off, u32 cnt)
9210 {
9211         struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
9212         struct bpf_insn *insn = new_prog->insnsi;
9213         u32 prog_len;
9214         int i;
9215
9216         /* aux info at OFF always needs adjustment, no matter fast path
9217          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
9218          * original insn at old prog.
9219          */
9220         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
9221
9222         if (cnt == 1)
9223                 return 0;
9224         prog_len = new_prog->len;
9225         new_data = vzalloc(array_size(prog_len,
9226                                       sizeof(struct bpf_insn_aux_data)));
9227         if (!new_data)
9228                 return -ENOMEM;
9229         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
9230         memcpy(new_data + off + cnt - 1, old_data + off,
9231                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
9232         for (i = off; i < off + cnt - 1; i++) {
9233                 new_data[i].seen = env->pass_cnt;
9234                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
9235         }
9236         env->insn_aux_data = new_data;
9237         vfree(old_data);
9238         return 0;
9239 }
9240
9241 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
9242 {
9243         int i;
9244
9245         if (len == 1)
9246                 return;
9247         /* NOTE: fake 'exit' subprog should be updated as well. */
9248         for (i = 0; i <= env->subprog_cnt; i++) {
9249                 if (env->subprog_info[i].start <= off)
9250                         continue;
9251                 env->subprog_info[i].start += len - 1;
9252         }
9253 }
9254
9255 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
9256                                             const struct bpf_insn *patch, u32 len)
9257 {
9258         struct bpf_prog *new_prog;
9259
9260         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
9261         if (IS_ERR(new_prog)) {
9262                 if (PTR_ERR(new_prog) == -ERANGE)
9263                         verbose(env,
9264                                 "insn %d cannot be patched due to 16-bit range\n",
9265                                 env->insn_aux_data[off].orig_idx);
9266                 return NULL;
9267         }
9268         if (adjust_insn_aux_data(env, new_prog, off, len))
9269                 return NULL;
9270         adjust_subprog_starts(env, off, len);
9271         return new_prog;
9272 }
9273
9274 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
9275                                               u32 off, u32 cnt)
9276 {
9277         int i, j;
9278
9279         /* find first prog starting at or after off (first to remove) */
9280         for (i = 0; i < env->subprog_cnt; i++)
9281                 if (env->subprog_info[i].start >= off)
9282                         break;
9283         /* find first prog starting at or after off + cnt (first to stay) */
9284         for (j = i; j < env->subprog_cnt; j++)
9285                 if (env->subprog_info[j].start >= off + cnt)
9286                         break;
9287         /* if j doesn't start exactly at off + cnt, we are just removing
9288          * the front of previous prog
9289          */
9290         if (env->subprog_info[j].start != off + cnt)
9291                 j--;
9292
9293         if (j > i) {
9294                 struct bpf_prog_aux *aux = env->prog->aux;
9295                 int move;
9296
9297                 /* move fake 'exit' subprog as well */
9298                 move = env->subprog_cnt + 1 - j;
9299
9300                 memmove(env->subprog_info + i,
9301                         env->subprog_info + j,
9302                         sizeof(*env->subprog_info) * move);
9303                 env->subprog_cnt -= j - i;
9304
9305                 /* remove func_info */
9306                 if (aux->func_info) {
9307                         move = aux->func_info_cnt - j;
9308
9309                         memmove(aux->func_info + i,
9310                                 aux->func_info + j,
9311                                 sizeof(*aux->func_info) * move);
9312                         aux->func_info_cnt -= j - i;
9313                         /* func_info->insn_off is set after all code rewrites,
9314                          * in adjust_btf_func() - no need to adjust
9315                          */
9316                 }
9317         } else {
9318                 /* convert i from "first prog to remove" to "first to adjust" */
9319                 if (env->subprog_info[i].start == off)
9320                         i++;
9321         }
9322
9323         /* update fake 'exit' subprog as well */
9324         for (; i <= env->subprog_cnt; i++)
9325                 env->subprog_info[i].start -= cnt;
9326
9327         return 0;
9328 }
9329
9330 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
9331                                       u32 cnt)
9332 {
9333         struct bpf_prog *prog = env->prog;
9334         u32 i, l_off, l_cnt, nr_linfo;
9335         struct bpf_line_info *linfo;
9336
9337         nr_linfo = prog->aux->nr_linfo;
9338         if (!nr_linfo)
9339                 return 0;
9340
9341         linfo = prog->aux->linfo;
9342
9343         /* find first line info to remove, count lines to be removed */
9344         for (i = 0; i < nr_linfo; i++)
9345                 if (linfo[i].insn_off >= off)
9346                         break;
9347
9348         l_off = i;
9349         l_cnt = 0;
9350         for (; i < nr_linfo; i++)
9351                 if (linfo[i].insn_off < off + cnt)
9352                         l_cnt++;
9353                 else
9354                         break;
9355
9356         /* First live insn doesn't match first live linfo, it needs to "inherit"
9357          * last removed linfo.  prog is already modified, so prog->len == off
9358          * means no live instructions after (tail of the program was removed).
9359          */
9360         if (prog->len != off && l_cnt &&
9361             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
9362                 l_cnt--;
9363                 linfo[--i].insn_off = off + cnt;
9364         }
9365
9366         /* remove the line info which refer to the removed instructions */
9367         if (l_cnt) {
9368                 memmove(linfo + l_off, linfo + i,
9369                         sizeof(*linfo) * (nr_linfo - i));
9370
9371                 prog->aux->nr_linfo -= l_cnt;
9372                 nr_linfo = prog->aux->nr_linfo;
9373         }
9374
9375         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
9376         for (i = l_off; i < nr_linfo; i++)
9377                 linfo[i].insn_off -= cnt;
9378
9379         /* fix up all subprogs (incl. 'exit') which start >= off */
9380         for (i = 0; i <= env->subprog_cnt; i++)
9381                 if (env->subprog_info[i].linfo_idx > l_off) {
9382                         /* program may have started in the removed region but
9383                          * may not be fully removed
9384                          */
9385                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
9386                                 env->subprog_info[i].linfo_idx -= l_cnt;
9387                         else
9388                                 env->subprog_info[i].linfo_idx = l_off;
9389                 }
9390
9391         return 0;
9392 }
9393
9394 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
9395 {
9396         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9397         unsigned int orig_prog_len = env->prog->len;
9398         int err;
9399
9400         if (bpf_prog_is_dev_bound(env->prog->aux))
9401                 bpf_prog_offload_remove_insns(env, off, cnt);
9402
9403         err = bpf_remove_insns(env->prog, off, cnt);
9404         if (err)
9405                 return err;
9406
9407         err = adjust_subprog_starts_after_remove(env, off, cnt);
9408         if (err)
9409                 return err;
9410
9411         err = bpf_adj_linfo_after_remove(env, off, cnt);
9412         if (err)
9413                 return err;
9414
9415         memmove(aux_data + off, aux_data + off + cnt,
9416                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
9417
9418         return 0;
9419 }
9420
9421 /* The verifier does more data flow analysis than llvm and will not
9422  * explore branches that are dead at run time. Malicious programs can
9423  * have dead code too. Therefore replace all dead at-run-time code
9424  * with 'ja -1'.
9425  *
9426  * Just nops are not optimal, e.g. if they would sit at the end of the
9427  * program and through another bug we would manage to jump there, then
9428  * we'd execute beyond program memory otherwise. Returning exception
9429  * code also wouldn't work since we can have subprogs where the dead
9430  * code could be located.
9431  */
9432 static void sanitize_dead_code(struct bpf_verifier_env *env)
9433 {
9434         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9435         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
9436         struct bpf_insn *insn = env->prog->insnsi;
9437         const int insn_cnt = env->prog->len;
9438         int i;
9439
9440         for (i = 0; i < insn_cnt; i++) {
9441                 if (aux_data[i].seen)
9442                         continue;
9443                 memcpy(insn + i, &trap, sizeof(trap));
9444         }
9445 }
9446
9447 static bool insn_is_cond_jump(u8 code)
9448 {
9449         u8 op;
9450
9451         if (BPF_CLASS(code) == BPF_JMP32)
9452                 return true;
9453
9454         if (BPF_CLASS(code) != BPF_JMP)
9455                 return false;
9456
9457         op = BPF_OP(code);
9458         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
9459 }
9460
9461 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
9462 {
9463         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9464         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
9465         struct bpf_insn *insn = env->prog->insnsi;
9466         const int insn_cnt = env->prog->len;
9467         int i;
9468
9469         for (i = 0; i < insn_cnt; i++, insn++) {
9470                 if (!insn_is_cond_jump(insn->code))
9471                         continue;
9472
9473                 if (!aux_data[i + 1].seen)
9474                         ja.off = insn->off;
9475                 else if (!aux_data[i + 1 + insn->off].seen)
9476                         ja.off = 0;
9477                 else
9478                         continue;
9479
9480                 if (bpf_prog_is_dev_bound(env->prog->aux))
9481                         bpf_prog_offload_replace_insn(env, i, &ja);
9482
9483                 memcpy(insn, &ja, sizeof(ja));
9484         }
9485 }
9486
9487 static int opt_remove_dead_code(struct bpf_verifier_env *env)
9488 {
9489         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
9490         int insn_cnt = env->prog->len;
9491         int i, err;
9492
9493         for (i = 0; i < insn_cnt; i++) {
9494                 int j;
9495
9496                 j = 0;
9497                 while (i + j < insn_cnt && !aux_data[i + j].seen)
9498                         j++;
9499                 if (!j)
9500                         continue;
9501
9502                 err = verifier_remove_insns(env, i, j);
9503                 if (err)
9504                         return err;
9505                 insn_cnt = env->prog->len;
9506         }
9507
9508         return 0;
9509 }
9510
9511 static int opt_remove_nops(struct bpf_verifier_env *env)
9512 {
9513         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
9514         struct bpf_insn *insn = env->prog->insnsi;
9515         int insn_cnt = env->prog->len;
9516         int i, err;
9517
9518         for (i = 0; i < insn_cnt; i++) {
9519                 if (memcmp(&insn[i], &ja, sizeof(ja)))
9520                         continue;
9521
9522                 err = verifier_remove_insns(env, i, 1);
9523                 if (err)
9524                         return err;
9525                 insn_cnt--;
9526                 i--;
9527         }
9528
9529         return 0;
9530 }
9531
9532 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
9533                                          const union bpf_attr *attr)
9534 {
9535         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
9536         struct bpf_insn_aux_data *aux = env->insn_aux_data;
9537         int i, patch_len, delta = 0, len = env->prog->len;
9538         struct bpf_insn *insns = env->prog->insnsi;
9539         struct bpf_prog *new_prog;
9540         bool rnd_hi32;
9541
9542         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
9543         zext_patch[1] = BPF_ZEXT_REG(0);
9544         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
9545         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
9546         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
9547         for (i = 0; i < len; i++) {
9548                 int adj_idx = i + delta;
9549                 struct bpf_insn insn;
9550
9551                 insn = insns[adj_idx];
9552                 if (!aux[adj_idx].zext_dst) {
9553                         u8 code, class;
9554                         u32 imm_rnd;
9555
9556                         if (!rnd_hi32)
9557                                 continue;
9558
9559                         code = insn.code;
9560                         class = BPF_CLASS(code);
9561                         if (insn_no_def(&insn))
9562                                 continue;
9563
9564                         /* NOTE: arg "reg" (the fourth one) is only used for
9565                          *       BPF_STX which has been ruled out in above
9566                          *       check, it is safe to pass NULL here.
9567                          */
9568                         if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
9569                                 if (class == BPF_LD &&
9570                                     BPF_MODE(code) == BPF_IMM)
9571                                         i++;
9572                                 continue;
9573                         }
9574
9575                         /* ctx load could be transformed into wider load. */
9576                         if (class == BPF_LDX &&
9577                             aux[adj_idx].ptr_type == PTR_TO_CTX)
9578                                 continue;
9579
9580                         imm_rnd = get_random_int();
9581                         rnd_hi32_patch[0] = insn;
9582                         rnd_hi32_patch[1].imm = imm_rnd;
9583                         rnd_hi32_patch[3].dst_reg = insn.dst_reg;
9584                         patch = rnd_hi32_patch;
9585                         patch_len = 4;
9586                         goto apply_patch_buffer;
9587                 }
9588
9589                 if (!bpf_jit_needs_zext())
9590                         continue;
9591
9592                 zext_patch[0] = insn;
9593                 zext_patch[1].dst_reg = insn.dst_reg;
9594                 zext_patch[1].src_reg = insn.dst_reg;
9595                 patch = zext_patch;
9596                 patch_len = 2;
9597 apply_patch_buffer:
9598                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
9599                 if (!new_prog)
9600                         return -ENOMEM;
9601                 env->prog = new_prog;
9602                 insns = new_prog->insnsi;
9603                 aux = env->insn_aux_data;
9604                 delta += patch_len - 1;
9605         }
9606
9607         return 0;
9608 }
9609
9610 /* convert load instructions that access fields of a context type into a
9611  * sequence of instructions that access fields of the underlying structure:
9612  *     struct __sk_buff    -> struct sk_buff
9613  *     struct bpf_sock_ops -> struct sock
9614  */
9615 static int convert_ctx_accesses(struct bpf_verifier_env *env)
9616 {
9617         const struct bpf_verifier_ops *ops = env->ops;
9618         int i, cnt, size, ctx_field_size, delta = 0;
9619         const int insn_cnt = env->prog->len;
9620         struct bpf_insn insn_buf[16], *insn;
9621         u32 target_size, size_default, off;
9622         struct bpf_prog *new_prog;
9623         enum bpf_access_type type;
9624         bool is_narrower_load;
9625
9626         if (ops->gen_prologue || env->seen_direct_write) {
9627                 if (!ops->gen_prologue) {
9628                         verbose(env, "bpf verifier is misconfigured\n");
9629                         return -EINVAL;
9630                 }
9631                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
9632                                         env->prog);
9633                 if (cnt >= ARRAY_SIZE(insn_buf)) {
9634                         verbose(env, "bpf verifier is misconfigured\n");
9635                         return -EINVAL;
9636                 } else if (cnt) {
9637                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
9638                         if (!new_prog)
9639                                 return -ENOMEM;
9640
9641                         env->prog = new_prog;
9642                         delta += cnt - 1;
9643                 }
9644         }
9645
9646         if (bpf_prog_is_dev_bound(env->prog->aux))
9647                 return 0;
9648
9649         insn = env->prog->insnsi + delta;
9650
9651         for (i = 0; i < insn_cnt; i++, insn++) {
9652                 bpf_convert_ctx_access_t convert_ctx_access;
9653
9654                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
9655                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
9656                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
9657                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
9658                         type = BPF_READ;
9659                 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
9660                          insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
9661                          insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
9662                          insn->code == (BPF_STX | BPF_MEM | BPF_DW))
9663                         type = BPF_WRITE;
9664                 else
9665                         continue;
9666
9667                 if (type == BPF_WRITE &&
9668                     env->insn_aux_data[i + delta].sanitize_stack_off) {
9669                         struct bpf_insn patch[] = {
9670                                 /* Sanitize suspicious stack slot with zero.
9671                                  * There are no memory dependencies for this store,
9672                                  * since it's only using frame pointer and immediate
9673                                  * constant of zero
9674                                  */
9675                                 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
9676                                            env->insn_aux_data[i + delta].sanitize_stack_off,
9677                                            0),
9678                                 /* the original STX instruction will immediately
9679                                  * overwrite the same stack slot with appropriate value
9680                                  */
9681                                 *insn,
9682                         };
9683
9684                         cnt = ARRAY_SIZE(patch);
9685                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
9686                         if (!new_prog)
9687                                 return -ENOMEM;
9688
9689                         delta    += cnt - 1;
9690                         env->prog = new_prog;
9691                         insn      = new_prog->insnsi + i + delta;
9692                         continue;
9693                 }
9694
9695                 switch (env->insn_aux_data[i + delta].ptr_type) {
9696                 case PTR_TO_CTX:
9697                         if (!ops->convert_ctx_access)
9698                                 continue;
9699                         convert_ctx_access = ops->convert_ctx_access;
9700                         break;
9701                 case PTR_TO_SOCKET:
9702                 case PTR_TO_SOCK_COMMON:
9703                         convert_ctx_access = bpf_sock_convert_ctx_access;
9704                         break;
9705                 case PTR_TO_TCP_SOCK:
9706                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
9707                         break;
9708                 case PTR_TO_XDP_SOCK:
9709                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
9710                         break;
9711                 case PTR_TO_BTF_ID:
9712                         if (type == BPF_READ) {
9713                                 insn->code = BPF_LDX | BPF_PROBE_MEM |
9714                                         BPF_SIZE((insn)->code);
9715                                 env->prog->aux->num_exentries++;
9716                         } else if (env->prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9717                                 verbose(env, "Writes through BTF pointers are not allowed\n");
9718                                 return -EINVAL;
9719                         }
9720                         continue;
9721                 default:
9722                         continue;
9723                 }
9724
9725                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
9726                 size = BPF_LDST_BYTES(insn);
9727
9728                 /* If the read access is a narrower load of the field,
9729                  * convert to a 4/8-byte load, to minimum program type specific
9730                  * convert_ctx_access changes. If conversion is successful,
9731                  * we will apply proper mask to the result.
9732                  */
9733                 is_narrower_load = size < ctx_field_size;
9734                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
9735                 off = insn->off;
9736                 if (is_narrower_load) {
9737                         u8 size_code;
9738
9739                         if (type == BPF_WRITE) {
9740                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
9741                                 return -EINVAL;
9742                         }
9743
9744                         size_code = BPF_H;
9745                         if (ctx_field_size == 4)
9746                                 size_code = BPF_W;
9747                         else if (ctx_field_size == 8)
9748                                 size_code = BPF_DW;
9749
9750                         insn->off = off & ~(size_default - 1);
9751                         insn->code = BPF_LDX | BPF_MEM | size_code;
9752                 }
9753
9754                 target_size = 0;
9755                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
9756                                          &target_size);
9757                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
9758                     (ctx_field_size && !target_size)) {
9759                         verbose(env, "bpf verifier is misconfigured\n");
9760                         return -EINVAL;
9761                 }
9762
9763                 if (is_narrower_load && size < target_size) {
9764                         u8 shift = bpf_ctx_narrow_access_offset(
9765                                 off, size, size_default) * 8;
9766                         if (ctx_field_size <= 4) {
9767                                 if (shift)
9768                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
9769                                                                         insn->dst_reg,
9770                                                                         shift);
9771                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
9772                                                                 (1 << size * 8) - 1);
9773                         } else {
9774                                 if (shift)
9775                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
9776                                                                         insn->dst_reg,
9777                                                                         shift);
9778                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
9779                                                                 (1ULL << size * 8) - 1);
9780                         }
9781                 }
9782
9783                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9784                 if (!new_prog)
9785                         return -ENOMEM;
9786
9787                 delta += cnt - 1;
9788
9789                 /* keep walking new program and skip insns we just inserted */
9790                 env->prog = new_prog;
9791                 insn      = new_prog->insnsi + i + delta;
9792         }
9793
9794         return 0;
9795 }
9796
9797 static int jit_subprogs(struct bpf_verifier_env *env)
9798 {
9799         struct bpf_prog *prog = env->prog, **func, *tmp;
9800         int i, j, subprog_start, subprog_end = 0, len, subprog;
9801         struct bpf_insn *insn;
9802         void *old_bpf_func;
9803         int err, num_exentries;
9804
9805         if (env->subprog_cnt <= 1)
9806                 return 0;
9807
9808         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
9809                 if (insn->code != (BPF_JMP | BPF_CALL) ||
9810                     insn->src_reg != BPF_PSEUDO_CALL)
9811                         continue;
9812                 /* Upon error here we cannot fall back to interpreter but
9813                  * need a hard reject of the program. Thus -EFAULT is
9814                  * propagated in any case.
9815                  */
9816                 subprog = find_subprog(env, i + insn->imm + 1);
9817                 if (subprog < 0) {
9818                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
9819                                   i + insn->imm + 1);
9820                         return -EFAULT;
9821                 }
9822                 /* temporarily remember subprog id inside insn instead of
9823                  * aux_data, since next loop will split up all insns into funcs
9824                  */
9825                 insn->off = subprog;
9826                 /* remember original imm in case JIT fails and fallback
9827                  * to interpreter will be needed
9828                  */
9829                 env->insn_aux_data[i].call_imm = insn->imm;
9830                 /* point imm to __bpf_call_base+1 from JITs point of view */
9831                 insn->imm = 1;
9832         }
9833
9834         err = bpf_prog_alloc_jited_linfo(prog);
9835         if (err)
9836                 goto out_undo_insn;
9837
9838         err = -ENOMEM;
9839         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
9840         if (!func)
9841                 goto out_undo_insn;
9842
9843         for (i = 0; i < env->subprog_cnt; i++) {
9844                 subprog_start = subprog_end;
9845                 subprog_end = env->subprog_info[i + 1].start;
9846
9847                 len = subprog_end - subprog_start;
9848                 /* BPF_PROG_RUN doesn't call subprogs directly,
9849                  * hence main prog stats include the runtime of subprogs.
9850                  * subprogs don't have IDs and not reachable via prog_get_next_id
9851                  * func[i]->aux->stats will never be accessed and stays NULL
9852                  */
9853                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
9854                 if (!func[i])
9855                         goto out_free;
9856                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
9857                        len * sizeof(struct bpf_insn));
9858                 func[i]->type = prog->type;
9859                 func[i]->len = len;
9860                 if (bpf_prog_calc_tag(func[i]))
9861                         goto out_free;
9862                 func[i]->is_func = 1;
9863                 func[i]->aux->func_idx = i;
9864                 /* the btf and func_info will be freed only at prog->aux */
9865                 func[i]->aux->btf = prog->aux->btf;
9866                 func[i]->aux->func_info = prog->aux->func_info;
9867
9868                 /* Use bpf_prog_F_tag to indicate functions in stack traces.
9869                  * Long term would need debug info to populate names
9870                  */
9871                 func[i]->aux->name[0] = 'F';
9872                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
9873                 func[i]->jit_requested = 1;
9874                 func[i]->aux->linfo = prog->aux->linfo;
9875                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
9876                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
9877                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
9878                 num_exentries = 0;
9879                 insn = func[i]->insnsi;
9880                 for (j = 0; j < func[i]->len; j++, insn++) {
9881                         if (BPF_CLASS(insn->code) == BPF_LDX &&
9882                             BPF_MODE(insn->code) == BPF_PROBE_MEM)
9883                                 num_exentries++;
9884                 }
9885                 func[i]->aux->num_exentries = num_exentries;
9886                 func[i] = bpf_int_jit_compile(func[i]);
9887                 if (!func[i]->jited) {
9888                         err = -ENOTSUPP;
9889                         goto out_free;
9890                 }
9891                 cond_resched();
9892         }
9893         /* at this point all bpf functions were successfully JITed
9894          * now populate all bpf_calls with correct addresses and
9895          * run last pass of JIT
9896          */
9897         for (i = 0; i < env->subprog_cnt; i++) {
9898                 insn = func[i]->insnsi;
9899                 for (j = 0; j < func[i]->len; j++, insn++) {
9900                         if (insn->code != (BPF_JMP | BPF_CALL) ||
9901                             insn->src_reg != BPF_PSEUDO_CALL)
9902                                 continue;
9903                         subprog = insn->off;
9904                         insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
9905                                     __bpf_call_base;
9906                 }
9907
9908                 /* we use the aux data to keep a list of the start addresses
9909                  * of the JITed images for each function in the program
9910                  *
9911                  * for some architectures, such as powerpc64, the imm field
9912                  * might not be large enough to hold the offset of the start
9913                  * address of the callee's JITed image from __bpf_call_base
9914                  *
9915                  * in such cases, we can lookup the start address of a callee
9916                  * by using its subprog id, available from the off field of
9917                  * the call instruction, as an index for this list
9918                  */
9919                 func[i]->aux->func = func;
9920                 func[i]->aux->func_cnt = env->subprog_cnt;
9921         }
9922         for (i = 0; i < env->subprog_cnt; i++) {
9923                 old_bpf_func = func[i]->bpf_func;
9924                 tmp = bpf_int_jit_compile(func[i]);
9925                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
9926                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
9927                         err = -ENOTSUPP;
9928                         goto out_free;
9929                 }
9930                 cond_resched();
9931         }
9932
9933         /* finally lock prog and jit images for all functions and
9934          * populate kallsysm
9935          */
9936         for (i = 0; i < env->subprog_cnt; i++) {
9937                 bpf_prog_lock_ro(func[i]);
9938                 bpf_prog_kallsyms_add(func[i]);
9939         }
9940
9941         /* Last step: make now unused interpreter insns from main
9942          * prog consistent for later dump requests, so they can
9943          * later look the same as if they were interpreted only.
9944          */
9945         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
9946                 if (insn->code != (BPF_JMP | BPF_CALL) ||
9947                     insn->src_reg != BPF_PSEUDO_CALL)
9948                         continue;
9949                 insn->off = env->insn_aux_data[i].call_imm;
9950                 subprog = find_subprog(env, i + insn->off + 1);
9951                 insn->imm = subprog;
9952         }
9953
9954         prog->jited = 1;
9955         prog->bpf_func = func[0]->bpf_func;
9956         prog->aux->func = func;
9957         prog->aux->func_cnt = env->subprog_cnt;
9958         bpf_prog_free_unused_jited_linfo(prog);
9959         return 0;
9960 out_free:
9961         for (i = 0; i < env->subprog_cnt; i++)
9962                 if (func[i])
9963                         bpf_jit_free(func[i]);
9964         kfree(func);
9965 out_undo_insn:
9966         /* cleanup main prog to be interpreted */
9967         prog->jit_requested = 0;
9968         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
9969                 if (insn->code != (BPF_JMP | BPF_CALL) ||
9970                     insn->src_reg != BPF_PSEUDO_CALL)
9971                         continue;
9972                 insn->off = 0;
9973                 insn->imm = env->insn_aux_data[i].call_imm;
9974         }
9975         bpf_prog_free_jited_linfo(prog);
9976         return err;
9977 }
9978
9979 static int fixup_call_args(struct bpf_verifier_env *env)
9980 {
9981 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
9982         struct bpf_prog *prog = env->prog;
9983         struct bpf_insn *insn = prog->insnsi;
9984         int i, depth;
9985 #endif
9986         int err = 0;
9987
9988         if (env->prog->jit_requested &&
9989             !bpf_prog_is_dev_bound(env->prog->aux)) {
9990                 err = jit_subprogs(env);
9991                 if (err == 0)
9992                         return 0;
9993                 if (err == -EFAULT)
9994                         return err;
9995         }
9996 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
9997         for (i = 0; i < prog->len; i++, insn++) {
9998                 if (insn->code != (BPF_JMP | BPF_CALL) ||
9999                     insn->src_reg != BPF_PSEUDO_CALL)
10000                         continue;
10001                 depth = get_callee_stack_depth(env, insn, i);
10002                 if (depth < 0)
10003                         return depth;
10004                 bpf_patch_call_args(insn, depth);
10005         }
10006         err = 0;
10007 #endif
10008         return err;
10009 }
10010
10011 /* fixup insn->imm field of bpf_call instructions
10012  * and inline eligible helpers as explicit sequence of BPF instructions
10013  *
10014  * this function is called after eBPF program passed verification
10015  */
10016 static int fixup_bpf_calls(struct bpf_verifier_env *env)
10017 {
10018         struct bpf_prog *prog = env->prog;
10019         bool expect_blinding = bpf_jit_blinding_enabled(prog);
10020         struct bpf_insn *insn = prog->insnsi;
10021         const struct bpf_func_proto *fn;
10022         const int insn_cnt = prog->len;
10023         const struct bpf_map_ops *ops;
10024         struct bpf_insn_aux_data *aux;
10025         struct bpf_insn insn_buf[16];
10026         struct bpf_prog *new_prog;
10027         struct bpf_map *map_ptr;
10028         int i, ret, cnt, delta = 0;
10029
10030         for (i = 0; i < insn_cnt; i++, insn++) {
10031                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
10032                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
10033                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
10034                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
10035                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
10036                         struct bpf_insn mask_and_div[] = {
10037                                 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
10038                                 /* Rx div 0 -> 0 */
10039                                 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
10040                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
10041                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
10042                                 *insn,
10043                         };
10044                         struct bpf_insn mask_and_mod[] = {
10045                                 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
10046                                 /* Rx mod 0 -> Rx */
10047                                 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
10048                                 *insn,
10049                         };
10050                         struct bpf_insn *patchlet;
10051
10052                         if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
10053                             insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
10054                                 patchlet = mask_and_div + (is64 ? 1 : 0);
10055                                 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
10056                         } else {
10057                                 patchlet = mask_and_mod + (is64 ? 1 : 0);
10058                                 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
10059                         }
10060
10061                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
10062                         if (!new_prog)
10063                                 return -ENOMEM;
10064
10065                         delta    += cnt - 1;
10066                         env->prog = prog = new_prog;
10067                         insn      = new_prog->insnsi + i + delta;
10068                         continue;
10069                 }
10070
10071                 if (BPF_CLASS(insn->code) == BPF_LD &&
10072                     (BPF_MODE(insn->code) == BPF_ABS ||
10073                      BPF_MODE(insn->code) == BPF_IND)) {
10074                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
10075                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
10076                                 verbose(env, "bpf verifier is misconfigured\n");
10077                                 return -EINVAL;
10078                         }
10079
10080                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10081                         if (!new_prog)
10082                                 return -ENOMEM;
10083
10084                         delta    += cnt - 1;
10085                         env->prog = prog = new_prog;
10086                         insn      = new_prog->insnsi + i + delta;
10087                         continue;
10088                 }
10089
10090                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
10091                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
10092                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
10093                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
10094                         struct bpf_insn insn_buf[16];
10095                         struct bpf_insn *patch = &insn_buf[0];
10096                         bool issrc, isneg;
10097                         u32 off_reg;
10098
10099                         aux = &env->insn_aux_data[i + delta];
10100                         if (!aux->alu_state ||
10101                             aux->alu_state == BPF_ALU_NON_POINTER)
10102                                 continue;
10103
10104                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
10105                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
10106                                 BPF_ALU_SANITIZE_SRC;
10107
10108                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
10109                         if (isneg)
10110                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
10111                         *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
10112                         *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
10113                         *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
10114                         *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
10115                         *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
10116                         if (issrc) {
10117                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
10118                                                          off_reg);
10119                                 insn->src_reg = BPF_REG_AX;
10120                         } else {
10121                                 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
10122                                                          BPF_REG_AX);
10123                         }
10124                         if (isneg)
10125                                 insn->code = insn->code == code_add ?
10126                                              code_sub : code_add;
10127                         *patch++ = *insn;
10128                         if (issrc && isneg)
10129                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
10130                         cnt = patch - insn_buf;
10131
10132                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10133                         if (!new_prog)
10134                                 return -ENOMEM;
10135
10136                         delta    += cnt - 1;
10137                         env->prog = prog = new_prog;
10138                         insn      = new_prog->insnsi + i + delta;
10139                         continue;
10140                 }
10141
10142                 if (insn->code != (BPF_JMP | BPF_CALL))
10143                         continue;
10144                 if (insn->src_reg == BPF_PSEUDO_CALL)
10145                         continue;
10146
10147                 if (insn->imm == BPF_FUNC_get_route_realm)
10148                         prog->dst_needed = 1;
10149                 if (insn->imm == BPF_FUNC_get_prandom_u32)
10150                         bpf_user_rnd_init_once();
10151                 if (insn->imm == BPF_FUNC_override_return)
10152                         prog->kprobe_override = 1;
10153                 if (insn->imm == BPF_FUNC_tail_call) {
10154                         /* If we tail call into other programs, we
10155                          * cannot make any assumptions since they can
10156                          * be replaced dynamically during runtime in
10157                          * the program array.
10158                          */
10159                         prog->cb_access = 1;
10160                         env->prog->aux->stack_depth = MAX_BPF_STACK;
10161                         env->prog->aux->max_pkt_offset = MAX_PACKET_OFF;
10162
10163                         /* mark bpf_tail_call as different opcode to avoid
10164                          * conditional branch in the interpeter for every normal
10165                          * call and to prevent accidental JITing by JIT compiler
10166                          * that doesn't support bpf_tail_call yet
10167                          */
10168                         insn->imm = 0;
10169                         insn->code = BPF_JMP | BPF_TAIL_CALL;
10170
10171                         aux = &env->insn_aux_data[i + delta];
10172                         if (env->bpf_capable && !expect_blinding &&
10173                             prog->jit_requested &&
10174                             !bpf_map_key_poisoned(aux) &&
10175                             !bpf_map_ptr_poisoned(aux) &&
10176                             !bpf_map_ptr_unpriv(aux)) {
10177                                 struct bpf_jit_poke_descriptor desc = {
10178                                         .reason = BPF_POKE_REASON_TAIL_CALL,
10179                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
10180                                         .tail_call.key = bpf_map_key_immediate(aux),
10181                                 };
10182
10183                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
10184                                 if (ret < 0) {
10185                                         verbose(env, "adding tail call poke descriptor failed\n");
10186                                         return ret;
10187                                 }
10188
10189                                 insn->imm = ret + 1;
10190                                 continue;
10191                         }
10192
10193                         if (!bpf_map_ptr_unpriv(aux))
10194                                 continue;
10195
10196                         /* instead of changing every JIT dealing with tail_call
10197                          * emit two extra insns:
10198                          * if (index >= max_entries) goto out;
10199                          * index &= array->index_mask;
10200                          * to avoid out-of-bounds cpu speculation
10201                          */
10202                         if (bpf_map_ptr_poisoned(aux)) {
10203                                 verbose(env, "tail_call abusing map_ptr\n");
10204                                 return -EINVAL;
10205                         }
10206
10207                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
10208                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
10209                                                   map_ptr->max_entries, 2);
10210                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
10211                                                     container_of(map_ptr,
10212                                                                  struct bpf_array,
10213                                                                  map)->index_mask);
10214                         insn_buf[2] = *insn;
10215                         cnt = 3;
10216                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
10217                         if (!new_prog)
10218                                 return -ENOMEM;
10219
10220                         delta    += cnt - 1;
10221                         env->prog = prog = new_prog;
10222                         insn      = new_prog->insnsi + i + delta;
10223                         continue;
10224                 }
10225
10226                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
10227                  * and other inlining handlers are currently limited to 64 bit
10228                  * only.
10229                  */
10230                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
10231                     (insn->imm == BPF_FUNC_map_lookup_elem ||
10232                      insn->imm == BPF_FUNC_map_update_elem ||
10233                      insn->imm == BPF_FUNC_map_delete_elem ||
10234                      insn->imm == BPF_FUNC_map_push_elem   ||
10235                      insn->imm == BPF_FUNC_map_pop_elem    ||
10236                      insn->imm == BPF_FUNC_map_peek_elem)) {
10237                         aux = &env->insn_aux_data[i + delta];
10238                         if (bpf_map_ptr_poisoned(aux))
10239                                 goto patch_call_imm;
10240
10241                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
10242                         ops = map_ptr->ops;
10243                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
10244                             ops->map_gen_lookup) {
10245                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
10246                                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
10247                                         verbose(env, "bpf verifier is misconfigured\n");
10248                                         return -EINVAL;
10249                                 }
10250
10251                                 new_prog = bpf_patch_insn_data(env, i + delta,
10252                                                                insn_buf, cnt);
10253                                 if (!new_prog)
10254                                         return -ENOMEM;
10255
10256                                 delta    += cnt - 1;
10257                                 env->prog = prog = new_prog;
10258                                 insn      = new_prog->insnsi + i + delta;
10259                                 continue;
10260                         }
10261
10262                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
10263                                      (void *(*)(struct bpf_map *map, void *key))NULL));
10264                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
10265                                      (int (*)(struct bpf_map *map, void *key))NULL));
10266                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
10267                                      (int (*)(struct bpf_map *map, void *key, void *value,
10268                                               u64 flags))NULL));
10269                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
10270                                      (int (*)(struct bpf_map *map, void *value,
10271                                               u64 flags))NULL));
10272                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
10273                                      (int (*)(struct bpf_map *map, void *value))NULL));
10274                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
10275                                      (int (*)(struct bpf_map *map, void *value))NULL));
10276
10277                         switch (insn->imm) {
10278                         case BPF_FUNC_map_lookup_elem:
10279                                 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
10280                                             __bpf_call_base;
10281                                 continue;
10282                         case BPF_FUNC_map_update_elem:
10283                                 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
10284                                             __bpf_call_base;
10285                                 continue;
10286                         case BPF_FUNC_map_delete_elem:
10287                                 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
10288                                             __bpf_call_base;
10289                                 continue;
10290                         case BPF_FUNC_map_push_elem:
10291                                 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
10292                                             __bpf_call_base;
10293                                 continue;
10294                         case BPF_FUNC_map_pop_elem:
10295                                 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
10296                                             __bpf_call_base;
10297                                 continue;
10298                         case BPF_FUNC_map_peek_elem:
10299                                 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
10300                                             __bpf_call_base;
10301                                 continue;
10302                         }
10303
10304                         goto patch_call_imm;
10305                 }
10306
10307                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
10308                     insn->imm == BPF_FUNC_jiffies64) {
10309                         struct bpf_insn ld_jiffies_addr[2] = {
10310                                 BPF_LD_IMM64(BPF_REG_0,
10311                                              (unsigned long)&jiffies),
10312                         };
10313
10314                         insn_buf[0] = ld_jiffies_addr[0];
10315                         insn_buf[1] = ld_jiffies_addr[1];
10316                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
10317                                                   BPF_REG_0, 0);
10318                         cnt = 3;
10319
10320                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
10321                                                        cnt);
10322                         if (!new_prog)
10323                                 return -ENOMEM;
10324
10325                         delta    += cnt - 1;
10326                         env->prog = prog = new_prog;
10327                         insn      = new_prog->insnsi + i + delta;
10328                         continue;
10329                 }
10330
10331 patch_call_imm:
10332                 fn = env->ops->get_func_proto(insn->imm, env->prog);
10333                 /* all functions that have prototype and verifier allowed
10334                  * programs to call them, must be real in-kernel functions
10335                  */
10336                 if (!fn->func) {
10337                         verbose(env,
10338                                 "kernel subsystem misconfigured func %s#%d\n",
10339                                 func_id_name(insn->imm), insn->imm);
10340                         return -EFAULT;
10341                 }
10342                 insn->imm = fn->func - __bpf_call_base;
10343         }
10344
10345         /* Since poke tab is now finalized, publish aux to tracker. */
10346         for (i = 0; i < prog->aux->size_poke_tab; i++) {
10347                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
10348                 if (!map_ptr->ops->map_poke_track ||
10349                     !map_ptr->ops->map_poke_untrack ||
10350                     !map_ptr->ops->map_poke_run) {
10351                         verbose(env, "bpf verifier is misconfigured\n");
10352                         return -EINVAL;
10353                 }
10354
10355                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
10356                 if (ret < 0) {
10357                         verbose(env, "tracking tail call prog failed\n");
10358                         return ret;
10359                 }
10360         }
10361
10362         return 0;
10363 }
10364
10365 static void free_states(struct bpf_verifier_env *env)
10366 {
10367         struct bpf_verifier_state_list *sl, *sln;
10368         int i;
10369
10370         sl = env->free_list;
10371         while (sl) {
10372                 sln = sl->next;
10373                 free_verifier_state(&sl->state, false);
10374                 kfree(sl);
10375                 sl = sln;
10376         }
10377         env->free_list = NULL;
10378
10379         if (!env->explored_states)
10380                 return;
10381
10382         for (i = 0; i < state_htab_size(env); i++) {
10383                 sl = env->explored_states[i];
10384
10385                 while (sl) {
10386                         sln = sl->next;
10387                         free_verifier_state(&sl->state, false);
10388                         kfree(sl);
10389                         sl = sln;
10390                 }
10391                 env->explored_states[i] = NULL;
10392         }
10393 }
10394
10395 /* The verifier is using insn_aux_data[] to store temporary data during
10396  * verification and to store information for passes that run after the
10397  * verification like dead code sanitization. do_check_common() for subprogram N
10398  * may analyze many other subprograms. sanitize_insn_aux_data() clears all
10399  * temporary data after do_check_common() finds that subprogram N cannot be
10400  * verified independently. pass_cnt counts the number of times
10401  * do_check_common() was run and insn->aux->seen tells the pass number
10402  * insn_aux_data was touched. These variables are compared to clear temporary
10403  * data from failed pass. For testing and experiments do_check_common() can be
10404  * run multiple times even when prior attempt to verify is unsuccessful.
10405  */
10406 static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
10407 {
10408         struct bpf_insn *insn = env->prog->insnsi;
10409         struct bpf_insn_aux_data *aux;
10410         int i, class;
10411
10412         for (i = 0; i < env->prog->len; i++) {
10413                 class = BPF_CLASS(insn[i].code);
10414                 if (class != BPF_LDX && class != BPF_STX)
10415                         continue;
10416                 aux = &env->insn_aux_data[i];
10417                 if (aux->seen != env->pass_cnt)
10418                         continue;
10419                 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
10420         }
10421 }
10422
10423 static int do_check_common(struct bpf_verifier_env *env, int subprog)
10424 {
10425         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
10426         struct bpf_verifier_state *state;
10427         struct bpf_reg_state *regs;
10428         int ret, i;
10429
10430         env->prev_linfo = NULL;
10431         env->pass_cnt++;
10432
10433         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
10434         if (!state)
10435                 return -ENOMEM;
10436         state->curframe = 0;
10437         state->speculative = false;
10438         state->branches = 1;
10439         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
10440         if (!state->frame[0]) {
10441                 kfree(state);
10442                 return -ENOMEM;
10443         }
10444         env->cur_state = state;
10445         init_func_state(env, state->frame[0],
10446                         BPF_MAIN_FUNC /* callsite */,
10447                         0 /* frameno */,
10448                         subprog);
10449
10450         regs = state->frame[state->curframe]->regs;
10451         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
10452                 ret = btf_prepare_func_args(env, subprog, regs);
10453                 if (ret)
10454                         goto out;
10455                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
10456                         if (regs[i].type == PTR_TO_CTX)
10457                                 mark_reg_known_zero(env, regs, i);
10458                         else if (regs[i].type == SCALAR_VALUE)
10459                                 mark_reg_unknown(env, regs, i);
10460                 }
10461         } else {
10462                 /* 1st arg to a function */
10463                 regs[BPF_REG_1].type = PTR_TO_CTX;
10464                 mark_reg_known_zero(env, regs, BPF_REG_1);
10465                 ret = btf_check_func_arg_match(env, subprog, regs);
10466                 if (ret == -EFAULT)
10467                         /* unlikely verifier bug. abort.
10468                          * ret == 0 and ret < 0 are sadly acceptable for
10469                          * main() function due to backward compatibility.
10470                          * Like socket filter program may be written as:
10471                          * int bpf_prog(struct pt_regs *ctx)
10472                          * and never dereference that ctx in the program.
10473                          * 'struct pt_regs' is a type mismatch for socket
10474                          * filter that should be using 'struct __sk_buff'.
10475                          */
10476                         goto out;
10477         }
10478
10479         ret = do_check(env);
10480 out:
10481         /* check for NULL is necessary, since cur_state can be freed inside
10482          * do_check() under memory pressure.
10483          */
10484         if (env->cur_state) {
10485                 free_verifier_state(env->cur_state, true);
10486                 env->cur_state = NULL;
10487         }
10488         while (!pop_stack(env, NULL, NULL, false));
10489         if (!ret && pop_log)
10490                 bpf_vlog_reset(&env->log, 0);
10491         free_states(env);
10492         if (ret)
10493                 /* clean aux data in case subprog was rejected */
10494                 sanitize_insn_aux_data(env);
10495         return ret;
10496 }
10497
10498 /* Verify all global functions in a BPF program one by one based on their BTF.
10499  * All global functions must pass verification. Otherwise the whole program is rejected.
10500  * Consider:
10501  * int bar(int);
10502  * int foo(int f)
10503  * {
10504  *    return bar(f);
10505  * }
10506  * int bar(int b)
10507  * {
10508  *    ...
10509  * }
10510  * foo() will be verified first for R1=any_scalar_value. During verification it
10511  * will be assumed that bar() already verified successfully and call to bar()
10512  * from foo() will be checked for type match only. Later bar() will be verified
10513  * independently to check that it's safe for R1=any_scalar_value.
10514  */
10515 static int do_check_subprogs(struct bpf_verifier_env *env)
10516 {
10517         struct bpf_prog_aux *aux = env->prog->aux;
10518         int i, ret;
10519
10520         if (!aux->func_info)
10521                 return 0;
10522
10523         for (i = 1; i < env->subprog_cnt; i++) {
10524                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
10525                         continue;
10526                 env->insn_idx = env->subprog_info[i].start;
10527                 WARN_ON_ONCE(env->insn_idx == 0);
10528                 ret = do_check_common(env, i);
10529                 if (ret) {
10530                         return ret;
10531                 } else if (env->log.level & BPF_LOG_LEVEL) {
10532                         verbose(env,
10533                                 "Func#%d is safe for any args that match its prototype\n",
10534                                 i);
10535                 }
10536         }
10537         return 0;
10538 }
10539
10540 static int do_check_main(struct bpf_verifier_env *env)
10541 {
10542         int ret;
10543
10544         env->insn_idx = 0;
10545         ret = do_check_common(env, 0);
10546         if (!ret)
10547                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
10548         return ret;
10549 }
10550
10551
10552 static void print_verification_stats(struct bpf_verifier_env *env)
10553 {
10554         int i;
10555
10556         if (env->log.level & BPF_LOG_STATS) {
10557                 verbose(env, "verification time %lld usec\n",
10558                         div_u64(env->verification_time, 1000));
10559                 verbose(env, "stack depth ");
10560                 for (i = 0; i < env->subprog_cnt; i++) {
10561                         u32 depth = env->subprog_info[i].stack_depth;
10562
10563                         verbose(env, "%d", depth);
10564                         if (i + 1 < env->subprog_cnt)
10565                                 verbose(env, "+");
10566                 }
10567                 verbose(env, "\n");
10568         }
10569         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
10570                 "total_states %d peak_states %d mark_read %d\n",
10571                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
10572                 env->max_states_per_insn, env->total_states,
10573                 env->peak_states, env->longest_mark_read_walk);
10574 }
10575
10576 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
10577 {
10578         const struct btf_type *t, *func_proto;
10579         const struct bpf_struct_ops *st_ops;
10580         const struct btf_member *member;
10581         struct bpf_prog *prog = env->prog;
10582         u32 btf_id, member_idx;
10583         const char *mname;
10584
10585         btf_id = prog->aux->attach_btf_id;
10586         st_ops = bpf_struct_ops_find(btf_id);
10587         if (!st_ops) {
10588                 verbose(env, "attach_btf_id %u is not a supported struct\n",
10589                         btf_id);
10590                 return -ENOTSUPP;
10591         }
10592
10593         t = st_ops->type;
10594         member_idx = prog->expected_attach_type;
10595         if (member_idx >= btf_type_vlen(t)) {
10596                 verbose(env, "attach to invalid member idx %u of struct %s\n",
10597                         member_idx, st_ops->name);
10598                 return -EINVAL;
10599         }
10600
10601         member = &btf_type_member(t)[member_idx];
10602         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
10603         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
10604                                                NULL);
10605         if (!func_proto) {
10606                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
10607                         mname, member_idx, st_ops->name);
10608                 return -EINVAL;
10609         }
10610
10611         if (st_ops->check_member) {
10612                 int err = st_ops->check_member(t, member);
10613
10614                 if (err) {
10615                         verbose(env, "attach to unsupported member %s of struct %s\n",
10616                                 mname, st_ops->name);
10617                         return err;
10618                 }
10619         }
10620
10621         prog->aux->attach_func_proto = func_proto;
10622         prog->aux->attach_func_name = mname;
10623         env->ops = st_ops->verifier_ops;
10624
10625         return 0;
10626 }
10627 #define SECURITY_PREFIX "security_"
10628
10629 static int check_attach_modify_return(struct bpf_prog *prog, unsigned long addr)
10630 {
10631         if (within_error_injection_list(addr) ||
10632             !strncmp(SECURITY_PREFIX, prog->aux->attach_func_name,
10633                      sizeof(SECURITY_PREFIX) - 1))
10634                 return 0;
10635
10636         return -EINVAL;
10637 }
10638
10639 static int check_attach_btf_id(struct bpf_verifier_env *env)
10640 {
10641         struct bpf_prog *prog = env->prog;
10642         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
10643         struct bpf_prog *tgt_prog = prog->aux->linked_prog;
10644         u32 btf_id = prog->aux->attach_btf_id;
10645         const char prefix[] = "btf_trace_";
10646         struct btf_func_model fmodel;
10647         int ret = 0, subprog = -1, i;
10648         struct bpf_trampoline *tr;
10649         const struct btf_type *t;
10650         bool conservative = true;
10651         const char *tname;
10652         struct btf *btf;
10653         long addr;
10654         u64 key;
10655
10656         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
10657                 return check_struct_ops_btf_id(env);
10658
10659         if (prog->type != BPF_PROG_TYPE_TRACING &&
10660             prog->type != BPF_PROG_TYPE_LSM &&
10661             !prog_extension)
10662                 return 0;
10663
10664         if (!btf_id) {
10665                 verbose(env, "Tracing programs must provide btf_id\n");
10666                 return -EINVAL;
10667         }
10668         btf = bpf_prog_get_target_btf(prog);
10669         if (!btf) {
10670                 verbose(env,
10671                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
10672                 return -EINVAL;
10673         }
10674         t = btf_type_by_id(btf, btf_id);
10675         if (!t) {
10676                 verbose(env, "attach_btf_id %u is invalid\n", btf_id);
10677                 return -EINVAL;
10678         }
10679         tname = btf_name_by_offset(btf, t->name_off);
10680         if (!tname) {
10681                 verbose(env, "attach_btf_id %u doesn't have a name\n", btf_id);
10682                 return -EINVAL;
10683         }
10684         if (tgt_prog) {
10685                 struct bpf_prog_aux *aux = tgt_prog->aux;
10686
10687                 for (i = 0; i < aux->func_info_cnt; i++)
10688                         if (aux->func_info[i].type_id == btf_id) {
10689                                 subprog = i;
10690                                 break;
10691                         }
10692                 if (subprog == -1) {
10693                         verbose(env, "Subprog %s doesn't exist\n", tname);
10694                         return -EINVAL;
10695                 }
10696                 conservative = aux->func_info_aux[subprog].unreliable;
10697                 if (prog_extension) {
10698                         if (conservative) {
10699                                 verbose(env,
10700                                         "Cannot replace static functions\n");
10701                                 return -EINVAL;
10702                         }
10703                         if (!prog->jit_requested) {
10704                                 verbose(env,
10705                                         "Extension programs should be JITed\n");
10706                                 return -EINVAL;
10707                         }
10708                         env->ops = bpf_verifier_ops[tgt_prog->type];
10709                         prog->expected_attach_type = tgt_prog->expected_attach_type;
10710                 }
10711                 if (!tgt_prog->jited) {
10712                         verbose(env, "Can attach to only JITed progs\n");
10713                         return -EINVAL;
10714                 }
10715                 if (tgt_prog->type == prog->type) {
10716                         /* Cannot fentry/fexit another fentry/fexit program.
10717                          * Cannot attach program extension to another extension.
10718                          * It's ok to attach fentry/fexit to extension program.
10719                          */
10720                         verbose(env, "Cannot recursively attach\n");
10721                         return -EINVAL;
10722                 }
10723                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
10724                     prog_extension &&
10725                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
10726                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
10727                         /* Program extensions can extend all program types
10728                          * except fentry/fexit. The reason is the following.
10729                          * The fentry/fexit programs are used for performance
10730                          * analysis, stats and can be attached to any program
10731                          * type except themselves. When extension program is
10732                          * replacing XDP function it is necessary to allow
10733                          * performance analysis of all functions. Both original
10734                          * XDP program and its program extension. Hence
10735                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
10736                          * allowed. If extending of fentry/fexit was allowed it
10737                          * would be possible to create long call chain
10738                          * fentry->extension->fentry->extension beyond
10739                          * reasonable stack size. Hence extending fentry is not
10740                          * allowed.
10741                          */
10742                         verbose(env, "Cannot extend fentry/fexit\n");
10743                         return -EINVAL;
10744                 }
10745                 key = ((u64)aux->id) << 32 | btf_id;
10746         } else {
10747                 if (prog_extension) {
10748                         verbose(env, "Cannot replace kernel functions\n");
10749                         return -EINVAL;
10750                 }
10751                 key = btf_id;
10752         }
10753
10754         switch (prog->expected_attach_type) {
10755         case BPF_TRACE_RAW_TP:
10756                 if (tgt_prog) {
10757                         verbose(env,
10758                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
10759                         return -EINVAL;
10760                 }
10761                 if (!btf_type_is_typedef(t)) {
10762                         verbose(env, "attach_btf_id %u is not a typedef\n",
10763                                 btf_id);
10764                         return -EINVAL;
10765                 }
10766                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
10767                         verbose(env, "attach_btf_id %u points to wrong type name %s\n",
10768                                 btf_id, tname);
10769                         return -EINVAL;
10770                 }
10771                 tname += sizeof(prefix) - 1;
10772                 t = btf_type_by_id(btf, t->type);
10773                 if (!btf_type_is_ptr(t))
10774                         /* should never happen in valid vmlinux build */
10775                         return -EINVAL;
10776                 t = btf_type_by_id(btf, t->type);
10777                 if (!btf_type_is_func_proto(t))
10778                         /* should never happen in valid vmlinux build */
10779                         return -EINVAL;
10780
10781                 /* remember two read only pointers that are valid for
10782                  * the life time of the kernel
10783                  */
10784                 prog->aux->attach_func_name = tname;
10785                 prog->aux->attach_func_proto = t;
10786                 prog->aux->attach_btf_trace = true;
10787                 return 0;
10788         case BPF_TRACE_ITER:
10789                 if (!btf_type_is_func(t)) {
10790                         verbose(env, "attach_btf_id %u is not a function\n",
10791                                 btf_id);
10792                         return -EINVAL;
10793                 }
10794                 t = btf_type_by_id(btf, t->type);
10795                 if (!btf_type_is_func_proto(t))
10796                         return -EINVAL;
10797                 prog->aux->attach_func_name = tname;
10798                 prog->aux->attach_func_proto = t;
10799                 if (!bpf_iter_prog_supported(prog))
10800                         return -EINVAL;
10801                 ret = btf_distill_func_proto(&env->log, btf, t,
10802                                              tname, &fmodel);
10803                 return ret;
10804         default:
10805                 if (!prog_extension)
10806                         return -EINVAL;
10807                 /* fallthrough */
10808         case BPF_MODIFY_RETURN:
10809         case BPF_LSM_MAC:
10810         case BPF_TRACE_FENTRY:
10811         case BPF_TRACE_FEXIT:
10812                 prog->aux->attach_func_name = tname;
10813                 if (prog->type == BPF_PROG_TYPE_LSM) {
10814                         ret = bpf_lsm_verify_prog(&env->log, prog);
10815                         if (ret < 0)
10816                                 return ret;
10817                 }
10818
10819                 if (!btf_type_is_func(t)) {
10820                         verbose(env, "attach_btf_id %u is not a function\n",
10821                                 btf_id);
10822                         return -EINVAL;
10823                 }
10824                 if (prog_extension &&
10825                     btf_check_type_match(env, prog, btf, t))
10826                         return -EINVAL;
10827                 t = btf_type_by_id(btf, t->type);
10828                 if (!btf_type_is_func_proto(t))
10829                         return -EINVAL;
10830                 tr = bpf_trampoline_lookup(key);
10831                 if (!tr)
10832                         return -ENOMEM;
10833                 /* t is either vmlinux type or another program's type */
10834                 prog->aux->attach_func_proto = t;
10835                 mutex_lock(&tr->mutex);
10836                 if (tr->func.addr) {
10837                         prog->aux->trampoline = tr;
10838                         goto out;
10839                 }
10840                 if (tgt_prog && conservative) {
10841                         prog->aux->attach_func_proto = NULL;
10842                         t = NULL;
10843                 }
10844                 ret = btf_distill_func_proto(&env->log, btf, t,
10845                                              tname, &tr->func.model);
10846                 if (ret < 0)
10847                         goto out;
10848                 if (tgt_prog) {
10849                         if (subprog == 0)
10850                                 addr = (long) tgt_prog->bpf_func;
10851                         else
10852                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
10853                 } else {
10854                         addr = kallsyms_lookup_name(tname);
10855                         if (!addr) {
10856                                 verbose(env,
10857                                         "The address of function %s cannot be found\n",
10858                                         tname);
10859                                 ret = -ENOENT;
10860                                 goto out;
10861                         }
10862                 }
10863
10864                 if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
10865                         ret = check_attach_modify_return(prog, addr);
10866                         if (ret)
10867                                 verbose(env, "%s() is not modifiable\n",
10868                                         prog->aux->attach_func_name);
10869                 }
10870
10871                 if (ret)
10872                         goto out;
10873                 tr->func.addr = (void *)addr;
10874                 prog->aux->trampoline = tr;
10875 out:
10876                 mutex_unlock(&tr->mutex);
10877                 if (ret)
10878                         bpf_trampoline_put(tr);
10879                 return ret;
10880         }
10881 }
10882
10883 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
10884               union bpf_attr __user *uattr)
10885 {
10886         u64 start_time = ktime_get_ns();
10887         struct bpf_verifier_env *env;
10888         struct bpf_verifier_log *log;
10889         int i, len, ret = -EINVAL;
10890         bool is_priv;
10891
10892         /* no program is valid */
10893         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
10894                 return -EINVAL;
10895
10896         /* 'struct bpf_verifier_env' can be global, but since it's not small,
10897          * allocate/free it every time bpf_check() is called
10898          */
10899         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
10900         if (!env)
10901                 return -ENOMEM;
10902         log = &env->log;
10903
10904         len = (*prog)->len;
10905         env->insn_aux_data =
10906                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
10907         ret = -ENOMEM;
10908         if (!env->insn_aux_data)
10909                 goto err_free_env;
10910         for (i = 0; i < len; i++)
10911                 env->insn_aux_data[i].orig_idx = i;
10912         env->prog = *prog;
10913         env->ops = bpf_verifier_ops[env->prog->type];
10914         is_priv = bpf_capable();
10915
10916         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
10917                 mutex_lock(&bpf_verifier_lock);
10918                 if (!btf_vmlinux)
10919                         btf_vmlinux = btf_parse_vmlinux();
10920                 mutex_unlock(&bpf_verifier_lock);
10921         }
10922
10923         /* grab the mutex to protect few globals used by verifier */
10924         if (!is_priv)
10925                 mutex_lock(&bpf_verifier_lock);
10926
10927         if (attr->log_level || attr->log_buf || attr->log_size) {
10928                 /* user requested verbose verifier output
10929                  * and supplied buffer to store the verification trace
10930                  */
10931                 log->level = attr->log_level;
10932                 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
10933                 log->len_total = attr->log_size;
10934
10935                 ret = -EINVAL;
10936                 /* log attributes have to be sane */
10937                 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
10938                     !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
10939                         goto err_unlock;
10940         }
10941
10942         if (IS_ERR(btf_vmlinux)) {
10943                 /* Either gcc or pahole or kernel are broken. */
10944                 verbose(env, "in-kernel BTF is malformed\n");
10945                 ret = PTR_ERR(btf_vmlinux);
10946                 goto skip_full_check;
10947         }
10948
10949         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
10950         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
10951                 env->strict_alignment = true;
10952         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
10953                 env->strict_alignment = false;
10954
10955         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
10956         env->bypass_spec_v1 = bpf_bypass_spec_v1();
10957         env->bypass_spec_v4 = bpf_bypass_spec_v4();
10958         env->bpf_capable = bpf_capable();
10959
10960         if (is_priv)
10961                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
10962
10963         ret = replace_map_fd_with_map_ptr(env);
10964         if (ret < 0)
10965                 goto skip_full_check;
10966
10967         if (bpf_prog_is_dev_bound(env->prog->aux)) {
10968                 ret = bpf_prog_offload_verifier_prep(env->prog);
10969                 if (ret)
10970                         goto skip_full_check;
10971         }
10972
10973         env->explored_states = kvcalloc(state_htab_size(env),
10974                                        sizeof(struct bpf_verifier_state_list *),
10975                                        GFP_USER);
10976         ret = -ENOMEM;
10977         if (!env->explored_states)
10978                 goto skip_full_check;
10979
10980         ret = check_subprogs(env);
10981         if (ret < 0)
10982                 goto skip_full_check;
10983
10984         ret = check_btf_info(env, attr, uattr);
10985         if (ret < 0)
10986                 goto skip_full_check;
10987
10988         ret = check_attach_btf_id(env);
10989         if (ret)
10990                 goto skip_full_check;
10991
10992         ret = check_cfg(env);
10993         if (ret < 0)
10994                 goto skip_full_check;
10995
10996         ret = do_check_subprogs(env);
10997         ret = ret ?: do_check_main(env);
10998
10999         if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
11000                 ret = bpf_prog_offload_finalize(env);
11001
11002 skip_full_check:
11003         kvfree(env->explored_states);
11004
11005         if (ret == 0)
11006                 ret = check_max_stack_depth(env);
11007
11008         /* instruction rewrites happen after this point */
11009         if (is_priv) {
11010                 if (ret == 0)
11011                         opt_hard_wire_dead_code_branches(env);
11012                 if (ret == 0)
11013                         ret = opt_remove_dead_code(env);
11014                 if (ret == 0)
11015                         ret = opt_remove_nops(env);
11016         } else {
11017                 if (ret == 0)
11018                         sanitize_dead_code(env);
11019         }
11020
11021         if (ret == 0)
11022                 /* program is valid, convert *(u32*)(ctx + off) accesses */
11023                 ret = convert_ctx_accesses(env);
11024
11025         if (ret == 0)
11026                 ret = fixup_bpf_calls(env);
11027
11028         /* do 32-bit optimization after insn patching has done so those patched
11029          * insns could be handled correctly.
11030          */
11031         if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
11032                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
11033                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
11034                                                                      : false;
11035         }
11036
11037         if (ret == 0)
11038                 ret = fixup_call_args(env);
11039
11040         env->verification_time = ktime_get_ns() - start_time;
11041         print_verification_stats(env);
11042
11043         if (log->level && bpf_verifier_log_full(log))
11044                 ret = -ENOSPC;
11045         if (log->level && !log->ubuf) {
11046                 ret = -EFAULT;
11047                 goto err_release_maps;
11048         }
11049
11050         if (ret == 0 && env->used_map_cnt) {
11051                 /* if program passed verifier, update used_maps in bpf_prog_info */
11052                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
11053                                                           sizeof(env->used_maps[0]),
11054                                                           GFP_KERNEL);
11055
11056                 if (!env->prog->aux->used_maps) {
11057                         ret = -ENOMEM;
11058                         goto err_release_maps;
11059                 }
11060
11061                 memcpy(env->prog->aux->used_maps, env->used_maps,
11062                        sizeof(env->used_maps[0]) * env->used_map_cnt);
11063                 env->prog->aux->used_map_cnt = env->used_map_cnt;
11064
11065                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
11066                  * bpf_ld_imm64 instructions
11067                  */
11068                 convert_pseudo_ld_imm64(env);
11069         }
11070
11071         if (ret == 0)
11072                 adjust_btf_func(env);
11073
11074 err_release_maps:
11075         if (!env->prog->aux->used_maps)
11076                 /* if we didn't copy map pointers into bpf_prog_info, release
11077                  * them now. Otherwise free_used_maps() will release them.
11078                  */
11079                 release_maps(env);
11080
11081         /* extension progs temporarily inherit the attach_type of their targets
11082            for verification purposes, so set it back to zero before returning
11083          */
11084         if (env->prog->type == BPF_PROG_TYPE_EXT)
11085                 env->prog->expected_attach_type = 0;
11086
11087         *prog = env->prog;
11088 err_unlock:
11089         if (!is_priv)
11090                 mutex_unlock(&bpf_verifier_lock);
11091         vfree(env->insn_aux_data);
11092 err_free_env:
11093         kfree(env);
11094         return ret;
11095 }