Home | History | Annotate | Line # | Download | only in net
      1 /*	$NetBSD: bpfjit.c,v 1.52 2026/11/29 21:10:58 alnsn Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2011-2015 Alexander Nasonov.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  *
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in
     15  *    the documentation and/or other materials provided with the
     16  *    distribution.
     17  *
     18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     19  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
     21  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
     22  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
     23  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
     24  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
     26  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
     27  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
     28  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 #ifdef _KERNEL
     34 __KERNEL_RCSID(0, "$NetBSD: bpfjit.c,v 1.52 2026/11/29 21:10:58 alnsn Exp $");
     35 #else
     36 __RCSID("$NetBSD: bpfjit.c,v 1.52 2026/11/29 21:10:58 alnsn Exp $");
     37 #endif
     38 
     39 #include <sys/types.h>
     40 #include <sys/queue.h>
     41 
     42 #ifndef _KERNEL
     43 #include <assert.h>
     44 #define BJ_ASSERT(c) assert(c)
     45 #else
     46 #define BJ_ASSERT(c) KASSERT(c)
     47 #endif
     48 
     49 #ifndef _KERNEL
     50 #include <stdlib.h>
     51 #define BJ_ALLOC(sz) malloc(sz)
     52 #define BJ_FREE(p, sz) free(p)
     53 #else
     54 #include <sys/kmem.h>
     55 #define BJ_ALLOC(sz) kmem_alloc(sz, KM_SLEEP)
     56 #define BJ_FREE(p, sz) kmem_free(p, sz)
     57 #endif
     58 
     59 #ifndef _KERNEL
     60 #include <limits.h>
     61 #include <stdbool.h>
     62 #include <stddef.h>
     63 #include <stdint.h>
     64 #include <string.h>
     65 #else
     66 #include <sys/atomic.h>
     67 #include <sys/module.h>
     68 #endif
     69 
     70 #define	__BPF_PRIVATE
     71 #include <net/bpf.h>
     72 #include <net/bpfjit.h>
     73 #include <sljitLir.h>
     74 
     75 #if !defined(_KERNEL) && defined(SLJIT_VERBOSE) && SLJIT_VERBOSE
     76 #include <stdio.h> /* for stderr */
     77 #endif
     78 
     79 /*
     80  * Number of saved registers to pass to sljit_emit_enter() function.
     81  */
     82 #define NSAVEDS		3
     83 
     84 /*
     85  * Arguments of generated bpfjit_func_t.
     86  * The first argument is reassigned upon entry
     87  * to a more frequently used buf argument.
     88  */
     89 #define BJ_CTX_ARG	SLJIT_S0
     90 #define BJ_ARGS		SLJIT_S1
     91 
     92 /*
     93  * Permanent register assignments.
     94  */
     95 #define BJ_BUF		SLJIT_S0
     96 //#define BJ_ARGS	SLJIT_S1
     97 #define BJ_BUFLEN	SLJIT_S2
     98 #define BJ_AREG		SLJIT_R0
     99 #define BJ_TMP1REG	SLJIT_R1
    100 #define BJ_TMP2REG	SLJIT_R2
    101 #define BJ_XREG		SLJIT_R3
    102 #define BJ_TMP3REG	SLJIT_R4
    103 
    104 #ifdef _KERNEL
    105 #define MAX_MEMWORDS BPF_MAX_MEMWORDS
    106 #else
    107 #define MAX_MEMWORDS BPF_MEMWORDS
    108 #endif
    109 
    110 #define BJ_INIT_NOBITS  ((bpf_memword_init_t)0)
    111 #define BJ_INIT_MBIT(k) BPF_MEMWORD_INIT(k)
    112 #define BJ_INIT_ABIT    BJ_INIT_MBIT(MAX_MEMWORDS)
    113 #define BJ_INIT_XBIT    BJ_INIT_MBIT(MAX_MEMWORDS + 1)
    114 
    115 /*
    116  * Get a number of memwords and external memwords from a bpf_ctx object.
    117  */
    118 #define GET_EXTWORDS(bc) ((bc) ? (bc)->extwords : 0)
    119 #define GET_MEMWORDS(bc) (GET_EXTWORDS(bc) ? GET_EXTWORDS(bc) : BPF_MEMWORDS)
    120 
    121 /*
    122  * Optimization hints.
    123  */
    124 typedef unsigned int bpfjit_hint_t;
    125 #define BJ_HINT_ABS  0x01 /* packet read at absolute offset   */
    126 #define BJ_HINT_IND  0x02 /* packet read at variable offset   */
    127 #define BJ_HINT_MSH  0x04 /* BPF_MSH instruction              */
    128 #define BJ_HINT_COP  0x08 /* BPF_COP or BPF_COPX instruction  */
    129 #define BJ_HINT_COPX 0x10 /* BPF_COPX instruction             */
    130 #define BJ_HINT_XREG 0x20 /* BJ_XREG is needed                */
    131 #define BJ_HINT_LDX  0x40 /* BPF_LDX instruction              */
    132 #define BJ_HINT_PKT  (BJ_HINT_ABS|BJ_HINT_IND|BJ_HINT_MSH)
    133 
    134 /*
    135  * Datatype for Array Bounds Check Elimination (ABC) pass.
    136  */
    137 typedef uint64_t bpfjit_abc_length_t;
    138 #define MAX_ABC_LENGTH (UINT32_MAX + UINT64_C(4)) /* max. width is 4 */
    139 
    140 struct bpfjit_stack
    141 {
    142 	bpf_ctx_t *ctx;
    143 	uint32_t *extmem; /* pointer to external memory store */
    144 	uint32_t reg; /* saved A or X register */
    145 #ifdef _KERNEL
    146 	int err; /* 3rd argument for m_xword/m_xhalf/m_xbyte function call */
    147 #endif
    148 	uint32_t mem[MAX_MEMWORDS]; /* internal memory store */
    149 };
    150 
    151 /*
    152  * Data for BPF_JMP instruction.
    153  * Forward declaration for struct bpfjit_jump.
    154  */
    155 struct bpfjit_jump_data;
    156 
    157 /*
    158  * Node of bjumps list.
    159  */
    160 struct bpfjit_jump {
    161 	struct sljit_jump *sjump;
    162 	SLIST_ENTRY(bpfjit_jump) entries;
    163 	struct bpfjit_jump_data *jdata;
    164 };
    165 
    166 /*
    167  * Data for BPF_JMP instruction.
    168  */
    169 struct bpfjit_jump_data {
    170 	/*
    171 	 * These entries make up bjumps list:
    172 	 * jtf[0] - when coming from jt path,
    173 	 * jtf[1] - when coming from jf path.
    174 	 */
    175 	struct bpfjit_jump jtf[2];
    176 	/*
    177 	 * Length calculated by Array Bounds Check Elimination (ABC) pass.
    178 	 */
    179 	bpfjit_abc_length_t abc_length;
    180 	/*
    181 	 * Length checked by the last out-of-bounds check.
    182 	 */
    183 	bpfjit_abc_length_t checked_length;
    184 };
    185 
    186 /*
    187  * Data for "read from packet" instructions.
    188  * See also read_pkt_insn() function below.
    189  */
    190 struct bpfjit_read_pkt_data {
    191 	/*
    192 	 * Length calculated by Array Bounds Check Elimination (ABC) pass.
    193 	 */
    194 	bpfjit_abc_length_t abc_length;
    195 	/*
    196 	 * If positive, emit "if (buflen < check_length) return 0"
    197 	 * out-of-bounds check.
    198 	 * Values greater than UINT32_MAX generate unconditional "return 0".
    199 	 */
    200 	bpfjit_abc_length_t check_length;
    201 };
    202 
    203 /*
    204  * Additional (optimization-related) data for bpf_insn.
    205  */
    206 struct bpfjit_insn_data {
    207 	/* List of jumps to this insn. */
    208 	SLIST_HEAD(, bpfjit_jump) bjumps;
    209 
    210 	union {
    211 		struct bpfjit_jump_data     jdata;
    212 		struct bpfjit_read_pkt_data rdata;
    213 	} u;
    214 
    215 	bpf_memword_init_t invalid;
    216 	bool unreachable;
    217 };
    218 
    219 #ifdef _KERNEL
    220 
    221 uint32_t m_xword(const struct mbuf *, uint32_t, int *);
    222 uint32_t m_xhalf(const struct mbuf *, uint32_t, int *);
    223 uint32_t m_xbyte(const struct mbuf *, uint32_t, int *);
    224 
    225 MODULE(MODULE_CLASS_MISC, bpfjit, "sljit")
    226 
    227 static int
    228 bpfjit_modcmd(modcmd_t cmd, void *arg)
    229 {
    230 
    231 	switch (cmd) {
    232 	case MODULE_CMD_INIT:
    233 		bpfjit_module_ops.bj_free_code = &bpfjit_free_code;
    234 		atomic_store_release(&bpfjit_module_ops.bj_generate_code,
    235 		    &bpfjit_generate_code);
    236 		return 0;
    237 
    238 	case MODULE_CMD_FINI:
    239 		return EOPNOTSUPP;
    240 
    241 	default:
    242 		return ENOTTY;
    243 	}
    244 }
    245 #endif
    246 
    247 /*
    248  * Return a number of scratch registers to pass
    249  * to sljit_emit_enter() function.
    250  */
    251 static sljit_s32
    252 nscratches(bpfjit_hint_t hints)
    253 {
    254 	sljit_s32 rv = 2;
    255 
    256 #ifdef _KERNEL
    257 	if (hints & BJ_HINT_PKT)
    258 		rv = 3; /* xcall with three arguments */
    259 #endif
    260 
    261 	if (hints & BJ_HINT_IND)
    262 		rv = 3; /* uses BJ_TMP2REG */
    263 
    264 	if (hints & BJ_HINT_COP)
    265 		rv = 3; /* calls copfunc with three arguments */
    266 
    267 	if (hints & BJ_HINT_XREG)
    268 		rv = 4; /* uses BJ_XREG */
    269 
    270 	if (hints & BJ_HINT_COPX)
    271 		rv = 5; /* uses BJ_TMP3REG */
    272 
    273 	return rv;
    274 }
    275 
    276 static uint32_t
    277 read_width(const struct bpf_insn *pc)
    278 {
    279 
    280 	switch (BPF_SIZE(pc->code)) {
    281 	case BPF_W: return 4;
    282 	case BPF_H: return 2;
    283 	case BPF_B: return 1;
    284 	default:    return 0;
    285 	}
    286 }
    287 
    288 /*
    289  * Copy buf and buflen members of bpf_args from BJ_ARGS
    290  * pointer to BJ_BUF and BJ_BUFLEN registers.
    291  */
    292 static int
    293 load_buf_buflen(struct sljit_compiler *compiler)
    294 {
    295 	int status;
    296 
    297 	status = sljit_emit_op1(compiler,
    298 	    SLJIT_MOV_P,
    299 	    BJ_BUF, 0,
    300 	    SLJIT_MEM1(BJ_ARGS),
    301 	    offsetof(struct bpf_args, pkt));
    302 	if (status != SLJIT_SUCCESS)
    303 		return status;
    304 
    305 	status = sljit_emit_op1(compiler,
    306 	    SLJIT_MOV, /* size_t source */
    307 	    BJ_BUFLEN, 0,
    308 	    SLJIT_MEM1(BJ_ARGS),
    309 	    offsetof(struct bpf_args, buflen));
    310 
    311 	return status;
    312 }
    313 
    314 static bool
    315 grow_jumps(struct sljit_jump ***jumps, size_t *size)
    316 {
    317 	struct sljit_jump **newptr;
    318 	const size_t elemsz = sizeof(struct sljit_jump *);
    319 	size_t old_size = *size;
    320 	size_t new_size = 2 * old_size;
    321 
    322 	if (new_size < old_size || new_size > SIZE_MAX / elemsz)
    323 		return false;
    324 
    325 	newptr = BJ_ALLOC(new_size * elemsz);
    326 	if (newptr == NULL)
    327 		return false;
    328 
    329 	memcpy(newptr, *jumps, old_size * elemsz);
    330 	BJ_FREE(*jumps, old_size * elemsz);
    331 
    332 	*jumps = newptr;
    333 	*size = new_size;
    334 	return true;
    335 }
    336 
    337 static bool
    338 append_jump(struct sljit_jump *jump, struct sljit_jump ***jumps,
    339     size_t *size, size_t *max_size)
    340 {
    341 	if (*size == *max_size && !grow_jumps(jumps, max_size))
    342 		return false;
    343 
    344 	(*jumps)[(*size)++] = jump;
    345 	return true;
    346 }
    347 
    348 /*
    349  * Emit code for BPF_LD+BPF_B+BPF_ABS    A <- P[k:1].
    350  */
    351 static int
    352 emit_read8(struct sljit_compiler *compiler, sljit_s32 src, uint32_t k)
    353 {
    354 
    355 	return sljit_emit_op1(compiler,
    356 	    SLJIT_MOV_U8,
    357 	    BJ_AREG, 0,
    358 	    SLJIT_MEM1(src), k);
    359 }
    360 
    361 /*
    362  * Emit code for BPF_LD+BPF_H+BPF_ABS    A <- P[k:2].
    363  */
    364 static int
    365 emit_read16(struct sljit_compiler *compiler, sljit_s32 src, uint32_t k)
    366 {
    367 	int status;
    368 
    369 	BJ_ASSERT(k <= UINT32_MAX - 1);
    370 
    371 	/* A = buf[k]; */
    372 	status = sljit_emit_op1(compiler,
    373 	    SLJIT_MOV_U8,
    374 	    BJ_AREG, 0,
    375 	    SLJIT_MEM1(src), k);
    376 	if (status != SLJIT_SUCCESS)
    377 		return status;
    378 
    379 	/* tmp1 = buf[k+1]; */
    380 	status = sljit_emit_op1(compiler,
    381 	    SLJIT_MOV_U8,
    382 	    BJ_TMP1REG, 0,
    383 	    SLJIT_MEM1(src), k+1);
    384 	if (status != SLJIT_SUCCESS)
    385 		return status;
    386 
    387 	/* A = A << 8; */
    388 	status = sljit_emit_op2(compiler,
    389 	    SLJIT_SHL,
    390 	    BJ_AREG, 0,
    391 	    BJ_AREG, 0,
    392 	    SLJIT_IMM, 8);
    393 	if (status != SLJIT_SUCCESS)
    394 		return status;
    395 
    396 	/* A = A + tmp1; */
    397 	status = sljit_emit_op2(compiler,
    398 	    SLJIT_ADD,
    399 	    BJ_AREG, 0,
    400 	    BJ_AREG, 0,
    401 	    BJ_TMP1REG, 0);
    402 	return status;
    403 }
    404 
    405 /*
    406  * Emit code for BPF_LD+BPF_W+BPF_ABS    A <- P[k:4].
    407  */
    408 static int
    409 emit_read32(struct sljit_compiler *compiler, sljit_s32 src, uint32_t k)
    410 {
    411 	int status;
    412 
    413 	BJ_ASSERT(k <= UINT32_MAX - 3);
    414 
    415 	/* A = buf[k]; */
    416 	status = sljit_emit_op1(compiler,
    417 	    SLJIT_MOV_U8,
    418 	    BJ_AREG, 0,
    419 	    SLJIT_MEM1(src), k);
    420 	if (status != SLJIT_SUCCESS)
    421 		return status;
    422 
    423 	/* tmp1 = buf[k+1]; */
    424 	status = sljit_emit_op1(compiler,
    425 	    SLJIT_MOV_U8,
    426 	    BJ_TMP1REG, 0,
    427 	    SLJIT_MEM1(src), k+1);
    428 	if (status != SLJIT_SUCCESS)
    429 		return status;
    430 
    431 	/* A = A << 8; */
    432 	status = sljit_emit_op2(compiler,
    433 	    SLJIT_SHL,
    434 	    BJ_AREG, 0,
    435 	    BJ_AREG, 0,
    436 	    SLJIT_IMM, 8);
    437 	if (status != SLJIT_SUCCESS)
    438 		return status;
    439 
    440 	/* A = A + tmp1; */
    441 	status = sljit_emit_op2(compiler,
    442 	    SLJIT_ADD,
    443 	    BJ_AREG, 0,
    444 	    BJ_AREG, 0,
    445 	    BJ_TMP1REG, 0);
    446 	if (status != SLJIT_SUCCESS)
    447 		return status;
    448 
    449 	/* tmp1 = buf[k+2]; */
    450 	status = sljit_emit_op1(compiler,
    451 	    SLJIT_MOV_U8,
    452 	    BJ_TMP1REG, 0,
    453 	    SLJIT_MEM1(src), k+2);
    454 	if (status != SLJIT_SUCCESS)
    455 		return status;
    456 
    457 	/* A = A << 8; */
    458 	status = sljit_emit_op2(compiler,
    459 	    SLJIT_SHL,
    460 	    BJ_AREG, 0,
    461 	    BJ_AREG, 0,
    462 	    SLJIT_IMM, 8);
    463 	if (status != SLJIT_SUCCESS)
    464 		return status;
    465 
    466 	/* A = A + tmp1; */
    467 	status = sljit_emit_op2(compiler,
    468 	    SLJIT_ADD,
    469 	    BJ_AREG, 0,
    470 	    BJ_AREG, 0,
    471 	    BJ_TMP1REG, 0);
    472 	if (status != SLJIT_SUCCESS)
    473 		return status;
    474 
    475 	/* tmp1 = buf[k+3]; */
    476 	status = sljit_emit_op1(compiler,
    477 	    SLJIT_MOV_U8,
    478 	    BJ_TMP1REG, 0,
    479 	    SLJIT_MEM1(src), k+3);
    480 	if (status != SLJIT_SUCCESS)
    481 		return status;
    482 
    483 	/* A = A << 8; */
    484 	status = sljit_emit_op2(compiler,
    485 	    SLJIT_SHL,
    486 	    BJ_AREG, 0,
    487 	    BJ_AREG, 0,
    488 	    SLJIT_IMM, 8);
    489 	if (status != SLJIT_SUCCESS)
    490 		return status;
    491 
    492 	/* A = A + tmp1; */
    493 	status = sljit_emit_op2(compiler,
    494 	    SLJIT_ADD,
    495 	    BJ_AREG, 0,
    496 	    BJ_AREG, 0,
    497 	    BJ_TMP1REG, 0);
    498 	return status;
    499 }
    500 
    501 #ifdef _KERNEL
    502 /*
    503  * Emit code for m_xword/m_xhalf/m_xbyte call.
    504  *
    505  * @pc BPF_LD+BPF_W+BPF_ABS    A <- P[k:4]
    506  *     BPF_LD+BPF_H+BPF_ABS    A <- P[k:2]
    507  *     BPF_LD+BPF_B+BPF_ABS    A <- P[k:1]
    508  *     BPF_LD+BPF_W+BPF_IND    A <- P[X+k:4]
    509  *     BPF_LD+BPF_H+BPF_IND    A <- P[X+k:2]
    510  *     BPF_LD+BPF_B+BPF_IND    A <- P[X+k:1]
    511  *     BPF_LDX+BPF_B+BPF_MSH   X <- 4*(P[k:1]&0xf)
    512  */
    513 static int
    514 emit_xcall(struct sljit_compiler *compiler, bpfjit_hint_t hints,
    515     const struct bpf_insn *pc, int dst, struct sljit_jump ***ret0,
    516     size_t *ret0_size, size_t *ret0_maxsize,
    517     uint32_t (*fn)(const struct mbuf *, uint32_t, int *))
    518 {
    519 #if BJ_XREG == SLJIT_RETURN_REG   || \
    520     BJ_XREG == SLJIT_R0 || \
    521     BJ_XREG == SLJIT_R1 || \
    522     BJ_XREG == SLJIT_R2
    523 #error "Not supported assignment of registers."
    524 #endif
    525 	struct sljit_jump *jump;
    526 	sljit_s32 save_reg;
    527 	int status;
    528 
    529 	save_reg = (BPF_CLASS(pc->code) == BPF_LDX) ? BJ_AREG : BJ_XREG;
    530 
    531 	if (save_reg == BJ_AREG || (hints & BJ_HINT_XREG)) {
    532 		/* save A or X */
    533 		status = sljit_emit_op1(compiler,
    534 		    SLJIT_MOV_U32,
    535 		    SLJIT_MEM1(SLJIT_SP),
    536 		    offsetof(struct bpfjit_stack, reg),
    537 		    save_reg, 0);
    538 		if (status != SLJIT_SUCCESS)
    539 			return status;
    540 	}
    541 
    542 	/*
    543 	 * Prepare registers for fn(mbuf, k, &err) call.
    544 	 */
    545 	status = sljit_emit_op1(compiler,
    546 	    SLJIT_MOV,
    547 	    SLJIT_R0, 0,
    548 	    BJ_BUF, 0);
    549 	if (status != SLJIT_SUCCESS)
    550 		return status;
    551 
    552 	if (BPF_CLASS(pc->code) == BPF_LD && BPF_MODE(pc->code) == BPF_IND) {
    553 		if (pc->k == 0) {
    554 			/* k = X; */
    555 			status = sljit_emit_op1(compiler,
    556 			    SLJIT_MOV,
    557 			    SLJIT_R1, 0,
    558 			    BJ_XREG, 0);
    559 			if (status != SLJIT_SUCCESS)
    560 				return status;
    561 		} else {
    562 			/* if (X > UINT32_MAX - pc->k) return 0; */
    563 			jump = sljit_emit_cmp(compiler,
    564 			    SLJIT_GREATER,
    565 			    BJ_XREG, 0,
    566 			    SLJIT_IMM, UINT32_MAX - pc->k);
    567 			if (jump == NULL)
    568 				return SLJIT_ERR_ALLOC_FAILED;
    569 			if (!append_jump(jump, ret0, ret0_size, ret0_maxsize))
    570 				return SLJIT_ERR_ALLOC_FAILED;
    571 
    572 			/* k = X + pc->k; */
    573 			status = sljit_emit_op2(compiler,
    574 			    SLJIT_ADD,
    575 			    SLJIT_R1, 0,
    576 			    BJ_XREG, 0,
    577 			    SLJIT_IMM, (uint32_t)pc->k);
    578 			if (status != SLJIT_SUCCESS)
    579 				return status;
    580 		}
    581 	} else {
    582 		/* k = pc->k */
    583 		status = sljit_emit_op1(compiler,
    584 		    SLJIT_MOV,
    585 		    SLJIT_R1, 0,
    586 		    SLJIT_IMM, (uint32_t)pc->k);
    587 		if (status != SLJIT_SUCCESS)
    588 			return status;
    589 	}
    590 
    591 	/*
    592 	 * The third argument of fn is an address on stack.
    593 	 */
    594 	status = sljit_get_local_base(compiler,
    595 	    SLJIT_R2, 0,
    596 	    offsetof(struct bpfjit_stack, err));
    597 	if (status != SLJIT_SUCCESS)
    598 		return status;
    599 
    600 	/* fn(buf, k, &err); */
    601 	status = sljit_emit_ijump(compiler,
    602 	    SLJIT_CALL3,
    603 	    SLJIT_IMM, SLJIT_FUNC_OFFSET(fn));
    604 	if (status != SLJIT_SUCCESS)
    605 		return status;
    606 
    607 	if (dst != SLJIT_RETURN_REG) {
    608 		/* move return value to dst */
    609 		status = sljit_emit_op1(compiler,
    610 		    SLJIT_MOV,
    611 		    dst, 0,
    612 		    SLJIT_RETURN_REG, 0);
    613 		if (status != SLJIT_SUCCESS)
    614 			return status;
    615 	}
    616 
    617 	/* if (*err != 0) return 0; */
    618 	jump = sljit_emit_cmp(compiler,
    619 	    SLJIT_NOT_EQUAL|SLJIT_I32_OP,
    620 	    SLJIT_MEM1(SLJIT_SP),
    621 	    offsetof(struct bpfjit_stack, err),
    622 	    SLJIT_IMM, 0);
    623 	if (jump == NULL)
    624 		return SLJIT_ERR_ALLOC_FAILED;
    625 
    626 	if (!append_jump(jump, ret0, ret0_size, ret0_maxsize))
    627 		return SLJIT_ERR_ALLOC_FAILED;
    628 
    629 	if (save_reg == BJ_AREG || (hints & BJ_HINT_XREG)) {
    630 		/* restore A or X */
    631 		status = sljit_emit_op1(compiler,
    632 		    SLJIT_MOV_U32,
    633 		    save_reg, 0,
    634 		    SLJIT_MEM1(SLJIT_SP),
    635 		    offsetof(struct bpfjit_stack, reg));
    636 		if (status != SLJIT_SUCCESS)
    637 			return status;
    638 	}
    639 
    640 	return SLJIT_SUCCESS;
    641 }
    642 #endif
    643 
    644 /*
    645  * Emit code for BPF_COP and BPF_COPX instructions.
    646  */
    647 static int
    648 emit_cop(struct sljit_compiler *compiler, bpfjit_hint_t hints,
    649     const bpf_ctx_t *bc, const struct bpf_insn *pc,
    650     struct sljit_jump ***ret0, size_t *ret0_size, size_t *ret0_maxsize)
    651 {
    652 #if BJ_XREG    == SLJIT_RETURN_REG   || \
    653     BJ_XREG    == SLJIT_R0 || \
    654     BJ_XREG    == SLJIT_R1 || \
    655     BJ_XREG    == SLJIT_R2 || \
    656     BJ_TMP3REG == SLJIT_R0 || \
    657     BJ_TMP3REG == SLJIT_R1 || \
    658     BJ_TMP3REG == SLJIT_R2
    659 #error "Not supported assignment of registers."
    660 #endif
    661 
    662 	struct sljit_jump *jump;
    663 	sljit_s32 call_reg;
    664 	sljit_sw call_off;
    665 	int status;
    666 
    667 	BJ_ASSERT(bc != NULL && bc->copfuncs != NULL);
    668 
    669 	if (hints & BJ_HINT_XREG) {
    670 		/* save X */
    671 		status = sljit_emit_op1(compiler,
    672 		    SLJIT_MOV_U32,
    673 		    SLJIT_MEM1(SLJIT_SP),
    674 		    offsetof(struct bpfjit_stack, reg),
    675 		    BJ_XREG, 0);
    676 		if (status != SLJIT_SUCCESS)
    677 			return status;
    678 	}
    679 
    680 	if (BPF_MISCOP(pc->code) == BPF_COP) {
    681 		call_reg = SLJIT_IMM;
    682 		call_off = SLJIT_FUNC_OFFSET(bc->copfuncs[pc->k]);
    683 	} else {
    684 		/* if (X >= bc->nfuncs) return 0; */
    685 		jump = sljit_emit_cmp(compiler,
    686 		    SLJIT_GREATER_EQUAL,
    687 		    BJ_XREG, 0,
    688 		    SLJIT_IMM, bc->nfuncs);
    689 		if (jump == NULL)
    690 			return SLJIT_ERR_ALLOC_FAILED;
    691 		if (!append_jump(jump, ret0, ret0_size, ret0_maxsize))
    692 			return SLJIT_ERR_ALLOC_FAILED;
    693 
    694 		/* tmp1 = ctx; */
    695 		status = sljit_emit_op1(compiler,
    696 		    SLJIT_MOV_P,
    697 		    BJ_TMP1REG, 0,
    698 		    SLJIT_MEM1(SLJIT_SP),
    699 		    offsetof(struct bpfjit_stack, ctx));
    700 		if (status != SLJIT_SUCCESS)
    701 			return status;
    702 
    703 		/* tmp1 = ctx->copfuncs; */
    704 		status = sljit_emit_op1(compiler,
    705 		    SLJIT_MOV_P,
    706 		    BJ_TMP1REG, 0,
    707 		    SLJIT_MEM1(BJ_TMP1REG),
    708 		    offsetof(struct bpf_ctx, copfuncs));
    709 		if (status != SLJIT_SUCCESS)
    710 			return status;
    711 
    712 		/* tmp2 = X; */
    713 		status = sljit_emit_op1(compiler,
    714 		    SLJIT_MOV,
    715 		    BJ_TMP2REG, 0,
    716 		    BJ_XREG, 0);
    717 		if (status != SLJIT_SUCCESS)
    718 			return status;
    719 
    720 		/* tmp3 = ctx->copfuncs[tmp2]; */
    721 		call_reg = BJ_TMP3REG;
    722 		call_off = 0;
    723 		status = sljit_emit_op1(compiler,
    724 		    SLJIT_MOV_P,
    725 		    call_reg, call_off,
    726 		    SLJIT_MEM2(BJ_TMP1REG, BJ_TMP2REG),
    727 		    SLJIT_WORD_SHIFT);
    728 		if (status != SLJIT_SUCCESS)
    729 			return status;
    730 	}
    731 
    732 	/*
    733 	 * Copy bpf_copfunc_t arguments to registers.
    734 	 */
    735 #if BJ_AREG != SLJIT_R2
    736 	status = sljit_emit_op1(compiler,
    737 	    SLJIT_MOV_U32,
    738 	    SLJIT_R2, 0,
    739 	    BJ_AREG, 0);
    740 	if (status != SLJIT_SUCCESS)
    741 		return status;
    742 #endif
    743 
    744 	status = sljit_emit_op1(compiler,
    745 	    SLJIT_MOV_P,
    746 	    SLJIT_R0, 0,
    747 	    SLJIT_MEM1(SLJIT_SP),
    748 	    offsetof(struct bpfjit_stack, ctx));
    749 	if (status != SLJIT_SUCCESS)
    750 		return status;
    751 
    752 	status = sljit_emit_op1(compiler,
    753 	    SLJIT_MOV_P,
    754 	    SLJIT_R1, 0,
    755 	    BJ_ARGS, 0);
    756 	if (status != SLJIT_SUCCESS)
    757 		return status;
    758 
    759 	status = sljit_emit_ijump(compiler,
    760 	    SLJIT_CALL3, call_reg, call_off);
    761 	if (status != SLJIT_SUCCESS)
    762 		return status;
    763 
    764 #if BJ_AREG != SLJIT_RETURN_REG
    765 	status = sljit_emit_op1(compiler,
    766 	    SLJIT_MOV,
    767 	    BJ_AREG, 0,
    768 	    SLJIT_RETURN_REG, 0);
    769 	if (status != SLJIT_SUCCESS)
    770 		return status;
    771 #endif
    772 
    773 	if (hints & BJ_HINT_XREG) {
    774 		/* restore X */
    775 		status = sljit_emit_op1(compiler,
    776 		    SLJIT_MOV_U32,
    777 		    BJ_XREG, 0,
    778 		    SLJIT_MEM1(SLJIT_SP),
    779 		    offsetof(struct bpfjit_stack, reg));
    780 		if (status != SLJIT_SUCCESS)
    781 			return status;
    782 	}
    783 
    784 	return SLJIT_SUCCESS;
    785 }
    786 
    787 /*
    788  * Generate code for
    789  * BPF_LD+BPF_W+BPF_ABS    A <- P[k:4]
    790  * BPF_LD+BPF_H+BPF_ABS    A <- P[k:2]
    791  * BPF_LD+BPF_B+BPF_ABS    A <- P[k:1]
    792  * BPF_LD+BPF_W+BPF_IND    A <- P[X+k:4]
    793  * BPF_LD+BPF_H+BPF_IND    A <- P[X+k:2]
    794  * BPF_LD+BPF_B+BPF_IND    A <- P[X+k:1]
    795  */
    796 static int
    797 emit_pkt_read(struct sljit_compiler *compiler, bpfjit_hint_t hints,
    798     const struct bpf_insn *pc, struct sljit_jump *to_mchain_jump,
    799     struct sljit_jump ***ret0, size_t *ret0_size, size_t *ret0_maxsize)
    800 {
    801 	int status = SLJIT_ERR_ALLOC_FAILED;
    802 	uint32_t width;
    803 	sljit_s32 ld_reg;
    804 	struct sljit_jump *jump;
    805 #ifdef _KERNEL
    806 	struct sljit_label *label;
    807 	struct sljit_jump *over_mchain_jump;
    808 	const bool check_zero_buflen = (to_mchain_jump != NULL);
    809 #endif
    810 	const uint32_t k = pc->k;
    811 
    812 #ifdef _KERNEL
    813 	if (to_mchain_jump == NULL) {
    814 		to_mchain_jump = sljit_emit_cmp(compiler,
    815 		    SLJIT_EQUAL,
    816 		    BJ_BUFLEN, 0,
    817 		    SLJIT_IMM, 0);
    818 		if (to_mchain_jump == NULL)
    819 			return SLJIT_ERR_ALLOC_FAILED;
    820 	}
    821 #endif
    822 
    823 	ld_reg = BJ_BUF;
    824 	width = read_width(pc);
    825 	if (width == 0)
    826 		return SLJIT_ERR_ALLOC_FAILED;
    827 
    828 	if (BPF_MODE(pc->code) == BPF_IND) {
    829 		/* tmp1 = buflen - (pc->k + width); */
    830 		status = sljit_emit_op2(compiler,
    831 		    SLJIT_SUB,
    832 		    BJ_TMP1REG, 0,
    833 		    BJ_BUFLEN, 0,
    834 		    SLJIT_IMM, k + width);
    835 		if (status != SLJIT_SUCCESS)
    836 			return status;
    837 
    838 		/* ld_reg = buf + X; */
    839 		ld_reg = BJ_TMP2REG;
    840 		status = sljit_emit_op2(compiler,
    841 		    SLJIT_ADD,
    842 		    ld_reg, 0,
    843 		    BJ_BUF, 0,
    844 		    BJ_XREG, 0);
    845 		if (status != SLJIT_SUCCESS)
    846 			return status;
    847 
    848 		/* if (tmp1 < X) return 0; */
    849 		jump = sljit_emit_cmp(compiler,
    850 		    SLJIT_LESS,
    851 		    BJ_TMP1REG, 0,
    852 		    BJ_XREG, 0);
    853 		if (jump == NULL)
    854 			return SLJIT_ERR_ALLOC_FAILED;
    855 		if (!append_jump(jump, ret0, ret0_size, ret0_maxsize))
    856 			return SLJIT_ERR_ALLOC_FAILED;
    857 	}
    858 
    859 	/*
    860 	 * Don't emit wrapped-around reads. They're dead code but
    861 	 * dead code elimination logic isn't smart enough to figure
    862 	 * it out.
    863 	 */
    864 	if (k <= UINT32_MAX - width + 1) {
    865 		switch (width) {
    866 		case 4:
    867 			status = emit_read32(compiler, ld_reg, k);
    868 			break;
    869 		case 2:
    870 			status = emit_read16(compiler, ld_reg, k);
    871 			break;
    872 		case 1:
    873 			status = emit_read8(compiler, ld_reg, k);
    874 			break;
    875 		}
    876 
    877 		if (status != SLJIT_SUCCESS)
    878 			return status;
    879 	}
    880 
    881 #ifdef _KERNEL
    882 	over_mchain_jump = sljit_emit_jump(compiler, SLJIT_JUMP);
    883 	if (over_mchain_jump == NULL)
    884 		return SLJIT_ERR_ALLOC_FAILED;
    885 
    886 	/* entry point to mchain handler */
    887 	label = sljit_emit_label(compiler);
    888 	if (label == NULL)
    889 		return SLJIT_ERR_ALLOC_FAILED;
    890 	sljit_set_label(to_mchain_jump, label);
    891 
    892 	if (check_zero_buflen) {
    893 		/* if (buflen != 0) return 0; */
    894 		jump = sljit_emit_cmp(compiler,
    895 		    SLJIT_NOT_EQUAL,
    896 		    BJ_BUFLEN, 0,
    897 		    SLJIT_IMM, 0);
    898 		if (jump == NULL)
    899 			return SLJIT_ERR_ALLOC_FAILED;
    900 		if (!append_jump(jump, ret0, ret0_size, ret0_maxsize))
    901 			return SLJIT_ERR_ALLOC_FAILED;
    902 	}
    903 
    904 	switch (width) {
    905 	case 4:
    906 		status = emit_xcall(compiler, hints, pc, BJ_AREG,
    907 		    ret0, ret0_size, ret0_maxsize, &m_xword);
    908 		break;
    909 	case 2:
    910 		status = emit_xcall(compiler, hints, pc, BJ_AREG,
    911 		    ret0, ret0_size, ret0_maxsize, &m_xhalf);
    912 		break;
    913 	case 1:
    914 		status = emit_xcall(compiler, hints, pc, BJ_AREG,
    915 		    ret0, ret0_size, ret0_maxsize, &m_xbyte);
    916 		break;
    917 	}
    918 
    919 	if (status != SLJIT_SUCCESS)
    920 		return status;
    921 
    922 	label = sljit_emit_label(compiler);
    923 	if (label == NULL)
    924 		return SLJIT_ERR_ALLOC_FAILED;
    925 	sljit_set_label(over_mchain_jump, label);
    926 #endif
    927 
    928 	return SLJIT_SUCCESS;
    929 }
    930 
    931 static int
    932 emit_memload(struct sljit_compiler *compiler,
    933     sljit_s32 dst, uint32_t k, size_t extwords)
    934 {
    935 	int status;
    936 	sljit_s32 src;
    937 	sljit_sw srcw;
    938 
    939 	srcw = k * sizeof(uint32_t);
    940 
    941 	if (extwords == 0) {
    942 		src = SLJIT_MEM1(SLJIT_SP);
    943 		srcw += offsetof(struct bpfjit_stack, mem);
    944 	} else {
    945 		/* copy extmem pointer to the tmp1 register */
    946 		status = sljit_emit_op1(compiler,
    947 		    SLJIT_MOV_P,
    948 		    BJ_TMP1REG, 0,
    949 		    SLJIT_MEM1(SLJIT_SP),
    950 		    offsetof(struct bpfjit_stack, extmem));
    951 		if (status != SLJIT_SUCCESS)
    952 			return status;
    953 		src = SLJIT_MEM1(BJ_TMP1REG);
    954 	}
    955 
    956 	return sljit_emit_op1(compiler, SLJIT_MOV_U32, dst, 0, src, srcw);
    957 }
    958 
    959 static int
    960 emit_memstore(struct sljit_compiler *compiler,
    961     sljit_s32 src, uint32_t k, size_t extwords)
    962 {
    963 	int status;
    964 	sljit_s32 dst;
    965 	sljit_sw dstw;
    966 
    967 	dstw = k * sizeof(uint32_t);
    968 
    969 	if (extwords == 0) {
    970 		dst = SLJIT_MEM1(SLJIT_SP);
    971 		dstw += offsetof(struct bpfjit_stack, mem);
    972 	} else {
    973 		/* copy extmem pointer to the tmp1 register */
    974 		status = sljit_emit_op1(compiler,
    975 		    SLJIT_MOV_P,
    976 		    BJ_TMP1REG, 0,
    977 		    SLJIT_MEM1(SLJIT_SP),
    978 		    offsetof(struct bpfjit_stack, extmem));
    979 		if (status != SLJIT_SUCCESS)
    980 			return status;
    981 		dst = SLJIT_MEM1(BJ_TMP1REG);
    982 	}
    983 
    984 	return sljit_emit_op1(compiler, SLJIT_MOV_U32, dst, dstw, src, 0);
    985 }
    986 
    987 /*
    988  * Emit code for BPF_LDX+BPF_B+BPF_MSH    X <- 4*(P[k:1]&0xf).
    989  */
    990 static int
    991 emit_msh(struct sljit_compiler *compiler, bpfjit_hint_t hints,
    992     const struct bpf_insn *pc, struct sljit_jump *to_mchain_jump,
    993     struct sljit_jump ***ret0, size_t *ret0_size, size_t *ret0_maxsize)
    994 {
    995 	int status;
    996 #ifdef _KERNEL
    997 	struct sljit_label *label;
    998 	struct sljit_jump *jump, *over_mchain_jump;
    999 	const bool check_zero_buflen = (to_mchain_jump != NULL);
   1000 #endif
   1001 	const uint32_t k = pc->k;
   1002 
   1003 #ifdef _KERNEL
   1004 	if (to_mchain_jump == NULL) {
   1005 		to_mchain_jump = sljit_emit_cmp(compiler,
   1006 		    SLJIT_EQUAL,
   1007 		    BJ_BUFLEN, 0,
   1008 		    SLJIT_IMM, 0);
   1009 		if (to_mchain_jump == NULL)
   1010 			return SLJIT_ERR_ALLOC_FAILED;
   1011 	}
   1012 #endif
   1013 
   1014 	/* tmp1 = buf[k] */
   1015 	status = sljit_emit_op1(compiler,
   1016 	    SLJIT_MOV_U8,
   1017 	    BJ_TMP1REG, 0,
   1018 	    SLJIT_MEM1(BJ_BUF), k);
   1019 	if (status != SLJIT_SUCCESS)
   1020 		return status;
   1021 
   1022 #ifdef _KERNEL
   1023 	over_mchain_jump = sljit_emit_jump(compiler, SLJIT_JUMP);
   1024 	if (over_mchain_jump == NULL)
   1025 		return SLJIT_ERR_ALLOC_FAILED;
   1026 
   1027 	/* entry point to mchain handler */
   1028 	label = sljit_emit_label(compiler);
   1029 	if (label == NULL)
   1030 		return SLJIT_ERR_ALLOC_FAILED;
   1031 	sljit_set_label(to_mchain_jump, label);
   1032 
   1033 	if (check_zero_buflen) {
   1034 		/* if (buflen != 0) return 0; */
   1035 		jump = sljit_emit_cmp(compiler,
   1036 		    SLJIT_NOT_EQUAL,
   1037 		    BJ_BUFLEN, 0,
   1038 		    SLJIT_IMM, 0);
   1039 		if (jump == NULL)
   1040 			return SLJIT_ERR_ALLOC_FAILED;
   1041 		if (!append_jump(jump, ret0, ret0_size, ret0_maxsize))
   1042 			return SLJIT_ERR_ALLOC_FAILED;
   1043 	}
   1044 
   1045 	status = emit_xcall(compiler, hints, pc, BJ_TMP1REG,
   1046 	    ret0, ret0_size, ret0_maxsize, &m_xbyte);
   1047 	if (status != SLJIT_SUCCESS)
   1048 		return status;
   1049 
   1050 	label = sljit_emit_label(compiler);
   1051 	if (label == NULL)
   1052 		return SLJIT_ERR_ALLOC_FAILED;
   1053 	sljit_set_label(over_mchain_jump, label);
   1054 #endif
   1055 
   1056 	/* tmp1 &= 0xf */
   1057 	status = sljit_emit_op2(compiler,
   1058 	    SLJIT_AND,
   1059 	    BJ_TMP1REG, 0,
   1060 	    BJ_TMP1REG, 0,
   1061 	    SLJIT_IMM, 0xf);
   1062 	if (status != SLJIT_SUCCESS)
   1063 		return status;
   1064 
   1065 	/* X = tmp1 << 2 */
   1066 	status = sljit_emit_op2(compiler,
   1067 	    SLJIT_SHL,
   1068 	    BJ_XREG, 0,
   1069 	    BJ_TMP1REG, 0,
   1070 	    SLJIT_IMM, 2);
   1071 	if (status != SLJIT_SUCCESS)
   1072 		return status;
   1073 
   1074 	return SLJIT_SUCCESS;
   1075 }
   1076 
   1077 /*
   1078  * Emit code for A = A / k or A = A % k when k is a power of 2.
   1079  * @pc BPF_DIV or BPF_MOD instruction.
   1080  */
   1081 static int
   1082 emit_pow2_moddiv(struct sljit_compiler *compiler, const struct bpf_insn *pc)
   1083 {
   1084 	uint32_t k = pc->k;
   1085 	int status = SLJIT_SUCCESS;
   1086 
   1087 	BJ_ASSERT(k != 0 && (k & (k - 1)) == 0);
   1088 
   1089 	if (BPF_OP(pc->code) == BPF_MOD) {
   1090 		status = sljit_emit_op2(compiler,
   1091 		    SLJIT_AND,
   1092 		    BJ_AREG, 0,
   1093 		    BJ_AREG, 0,
   1094 		    SLJIT_IMM, k - 1);
   1095 	} else {
   1096 		int shift = 0;
   1097 
   1098 		/*
   1099 		 * Do shift = __builtin_ctz(k).
   1100 		 * The loop is slower, but that's ok.
   1101 		 */
   1102 		while (k > 1) {
   1103 			k >>= 1;
   1104 			shift++;
   1105 		}
   1106 
   1107 		if (shift != 0) {
   1108 			status = sljit_emit_op2(compiler,
   1109 			    SLJIT_LSHR|SLJIT_I32_OP,
   1110 			    BJ_AREG, 0,
   1111 			    BJ_AREG, 0,
   1112 			    SLJIT_IMM, shift);
   1113 		}
   1114 	}
   1115 
   1116 	return status;
   1117 }
   1118 
   1119 #if !defined(BPFJIT_USE_UDIV)
   1120 static sljit_uw
   1121 divide(sljit_uw x, sljit_uw y)
   1122 {
   1123 
   1124 	return (uint32_t)x / (uint32_t)y;
   1125 }
   1126 
   1127 static sljit_uw
   1128 modulus(sljit_uw x, sljit_uw y)
   1129 {
   1130 
   1131 	return (uint32_t)x % (uint32_t)y;
   1132 }
   1133 #endif
   1134 
   1135 /*
   1136  * Emit code for A = A / div or A = A % div.
   1137  * @pc BPF_DIV or BPF_MOD instruction.
   1138  */
   1139 static int
   1140 emit_moddiv(struct sljit_compiler *compiler, const struct bpf_insn *pc)
   1141 {
   1142 	int status;
   1143 	const bool xdiv = BPF_OP(pc->code) == BPF_DIV;
   1144 	const bool xreg = BPF_SRC(pc->code) == BPF_X;
   1145 
   1146 #if BJ_XREG == SLJIT_RETURN_REG   || \
   1147     BJ_XREG == SLJIT_R0 || \
   1148     BJ_XREG == SLJIT_R1 || \
   1149     BJ_AREG == SLJIT_R1
   1150 #error "Not supported assignment of registers."
   1151 #endif
   1152 
   1153 #if BJ_AREG != SLJIT_R0
   1154 	status = sljit_emit_op1(compiler,
   1155 	    SLJIT_MOV,
   1156 	    SLJIT_R0, 0,
   1157 	    BJ_AREG, 0);
   1158 	if (status != SLJIT_SUCCESS)
   1159 		return status;
   1160 #endif
   1161 
   1162 	status = sljit_emit_op1(compiler,
   1163 	    SLJIT_MOV,
   1164 	    SLJIT_R1, 0,
   1165 	    xreg ? BJ_XREG : SLJIT_IMM,
   1166 	    xreg ? 0 : (uint32_t)pc->k);
   1167 	if (status != SLJIT_SUCCESS)
   1168 		return status;
   1169 
   1170 #if defined(BPFJIT_USE_UDIV)
   1171 	status = sljit_emit_op0(compiler, SLJIT_UDIV|SLJIT_I32_OP);
   1172 
   1173 	if (BPF_OP(pc->code) == BPF_DIV) {
   1174 #if BJ_AREG != SLJIT_R0
   1175 		status = sljit_emit_op1(compiler,
   1176 		    SLJIT_MOV,
   1177 		    BJ_AREG, 0,
   1178 		    SLJIT_R0, 0);
   1179 #endif
   1180 	} else {
   1181 #if BJ_AREG != SLJIT_R1
   1182 		/* Remainder is in SLJIT_R1. */
   1183 		status = sljit_emit_op1(compiler,
   1184 		    SLJIT_MOV,
   1185 		    BJ_AREG, 0,
   1186 		    SLJIT_R1, 0);
   1187 #endif
   1188 	}
   1189 
   1190 	if (status != SLJIT_SUCCESS)
   1191 		return status;
   1192 #else
   1193 	status = sljit_emit_ijump(compiler,
   1194 	    SLJIT_CALL2,
   1195 	    SLJIT_IMM, xdiv ? SLJIT_FUNC_OFFSET(divide) :
   1196 		SLJIT_FUNC_OFFSET(modulus));
   1197 
   1198 #if BJ_AREG != SLJIT_RETURN_REG
   1199 	status = sljit_emit_op1(compiler,
   1200 	    SLJIT_MOV,
   1201 	    BJ_AREG, 0,
   1202 	    SLJIT_RETURN_REG, 0);
   1203 	if (status != SLJIT_SUCCESS)
   1204 		return status;
   1205 #endif
   1206 #endif
   1207 
   1208 	return status;
   1209 }
   1210 
   1211 /*
   1212  * Return true if pc is a "read from packet" instruction.
   1213  * If length is not NULL and return value is true, *length will
   1214  * be set to a safe length required to read a packet.
   1215  */
   1216 static bool
   1217 read_pkt_insn(const struct bpf_insn *pc, bpfjit_abc_length_t *length)
   1218 {
   1219 	bool rv;
   1220 	bpfjit_abc_length_t width = 0; /* XXXuninit */
   1221 
   1222 	switch (BPF_CLASS(pc->code)) {
   1223 	default:
   1224 		rv = false;
   1225 		break;
   1226 
   1227 	case BPF_LD:
   1228 		rv = BPF_MODE(pc->code) == BPF_ABS ||
   1229 		     BPF_MODE(pc->code) == BPF_IND;
   1230 		if (rv) {
   1231 			width = read_width(pc);
   1232 			rv = (width != 0);
   1233 		}
   1234 		break;
   1235 
   1236 	case BPF_LDX:
   1237 		rv = BPF_MODE(pc->code) == BPF_MSH &&
   1238 		     BPF_SIZE(pc->code) == BPF_B;
   1239 		width = 1;
   1240 		break;
   1241 	}
   1242 
   1243 	if (rv && length != NULL) {
   1244 		/*
   1245 		 * Values greater than UINT32_MAX will generate
   1246 		 * unconditional "return 0".
   1247 		 */
   1248 		*length = (uint32_t)pc->k + width;
   1249 	}
   1250 
   1251 	return rv;
   1252 }
   1253 
   1254 static void
   1255 optimize_init(struct bpfjit_insn_data *insn_dat, size_t insn_count)
   1256 {
   1257 	size_t i;
   1258 
   1259 	for (i = 0; i < insn_count; i++) {
   1260 		SLIST_INIT(&insn_dat[i].bjumps);
   1261 		insn_dat[i].invalid = BJ_INIT_NOBITS;
   1262 	}
   1263 }
   1264 
   1265 /*
   1266  * The function divides instructions into blocks. Destination of a jump
   1267  * instruction starts a new block. BPF_RET and BPF_JMP instructions
   1268  * terminate a block. Blocks are linear, that is, there are no jumps out
   1269  * from the middle of a block and there are no jumps in to the middle of
   1270  * a block.
   1271  *
   1272  * The function also sets bits in *initmask for memwords that
   1273  * need to be initialized to zero. Note that this set should be empty
   1274  * for any valid kernel filter program.
   1275  */
   1276 static bool
   1277 optimize_pass1(const bpf_ctx_t *bc, const struct bpf_insn *insns,
   1278     struct bpfjit_insn_data *insn_dat, size_t insn_count,
   1279     bpf_memword_init_t *initmask, bpfjit_hint_t *hints)
   1280 {
   1281 	struct bpfjit_jump *jtf;
   1282 	size_t i;
   1283 	uint32_t jt, jf;
   1284 	bpfjit_abc_length_t length;
   1285 	bpf_memword_init_t invalid; /* borrowed from bpf_filter() */
   1286 	bool unreachable;
   1287 
   1288 	const size_t memwords = GET_MEMWORDS(bc);
   1289 
   1290 	*hints = 0;
   1291 	*initmask = BJ_INIT_NOBITS;
   1292 
   1293 	unreachable = false;
   1294 	invalid = ~BJ_INIT_NOBITS;
   1295 
   1296 	for (i = 0; i < insn_count; i++) {
   1297 		if (!SLIST_EMPTY(&insn_dat[i].bjumps))
   1298 			unreachable = false;
   1299 		insn_dat[i].unreachable = unreachable;
   1300 
   1301 		if (unreachable)
   1302 			continue;
   1303 
   1304 		invalid |= insn_dat[i].invalid;
   1305 
   1306 		if (read_pkt_insn(&insns[i], &length) && length > UINT32_MAX)
   1307 			unreachable = true;
   1308 
   1309 		switch (BPF_CLASS(insns[i].code)) {
   1310 		case BPF_RET:
   1311 			if (BPF_RVAL(insns[i].code) == BPF_A)
   1312 				*initmask |= invalid & BJ_INIT_ABIT;
   1313 
   1314 			unreachable = true;
   1315 			continue;
   1316 
   1317 		case BPF_LD:
   1318 			if (BPF_MODE(insns[i].code) == BPF_ABS)
   1319 				*hints |= BJ_HINT_ABS;
   1320 
   1321 			if (BPF_MODE(insns[i].code) == BPF_IND) {
   1322 				*hints |= BJ_HINT_IND | BJ_HINT_XREG;
   1323 				*initmask |= invalid & BJ_INIT_XBIT;
   1324 			}
   1325 
   1326 			if (BPF_MODE(insns[i].code) == BPF_MEM &&
   1327 			    (uint32_t)insns[i].k < memwords) {
   1328 				*initmask |= invalid & BJ_INIT_MBIT(insns[i].k);
   1329 			}
   1330 
   1331 			invalid &= ~BJ_INIT_ABIT;
   1332 			continue;
   1333 
   1334 		case BPF_LDX:
   1335 			*hints |= BJ_HINT_XREG | BJ_HINT_LDX;
   1336 
   1337 			if (BPF_MODE(insns[i].code) == BPF_MEM &&
   1338 			    (uint32_t)insns[i].k < memwords) {
   1339 				*initmask |= invalid & BJ_INIT_MBIT(insns[i].k);
   1340 			}
   1341 
   1342 			if (BPF_MODE(insns[i].code) == BPF_MSH &&
   1343 			    BPF_SIZE(insns[i].code) == BPF_B) {
   1344 				*hints |= BJ_HINT_MSH;
   1345 			}
   1346 
   1347 			invalid &= ~BJ_INIT_XBIT;
   1348 			continue;
   1349 
   1350 		case BPF_ST:
   1351 			*initmask |= invalid & BJ_INIT_ABIT;
   1352 
   1353 			if ((uint32_t)insns[i].k < memwords)
   1354 				invalid &= ~BJ_INIT_MBIT(insns[i].k);
   1355 
   1356 			continue;
   1357 
   1358 		case BPF_STX:
   1359 			*hints |= BJ_HINT_XREG;
   1360 			*initmask |= invalid & BJ_INIT_XBIT;
   1361 
   1362 			if ((uint32_t)insns[i].k < memwords)
   1363 				invalid &= ~BJ_INIT_MBIT(insns[i].k);
   1364 
   1365 			continue;
   1366 
   1367 		case BPF_ALU:
   1368 			*initmask |= invalid & BJ_INIT_ABIT;
   1369 
   1370 			if (insns[i].code != (BPF_ALU|BPF_NEG) &&
   1371 			    BPF_SRC(insns[i].code) == BPF_X) {
   1372 				*hints |= BJ_HINT_XREG;
   1373 				*initmask |= invalid & BJ_INIT_XBIT;
   1374 			}
   1375 
   1376 			invalid &= ~BJ_INIT_ABIT;
   1377 			continue;
   1378 
   1379 		case BPF_MISC:
   1380 			switch (BPF_MISCOP(insns[i].code)) {
   1381 			case BPF_TAX: // X <- A
   1382 				*hints |= BJ_HINT_XREG;
   1383 				*initmask |= invalid & BJ_INIT_ABIT;
   1384 				invalid &= ~BJ_INIT_XBIT;
   1385 				continue;
   1386 
   1387 			case BPF_TXA: // A <- X
   1388 				*hints |= BJ_HINT_XREG;
   1389 				*initmask |= invalid & BJ_INIT_XBIT;
   1390 				invalid &= ~BJ_INIT_ABIT;
   1391 				continue;
   1392 
   1393 			case BPF_COPX:
   1394 				*hints |= BJ_HINT_XREG | BJ_HINT_COPX;
   1395 				/* FALLTHROUGH */
   1396 
   1397 			case BPF_COP:
   1398 				*hints |= BJ_HINT_COP;
   1399 				*initmask |= invalid & BJ_INIT_ABIT;
   1400 				invalid &= ~BJ_INIT_ABIT;
   1401 				continue;
   1402 			}
   1403 
   1404 			continue;
   1405 
   1406 		case BPF_JMP:
   1407 			/* Initialize abc_length for ABC pass. */
   1408 			insn_dat[i].u.jdata.abc_length = MAX_ABC_LENGTH;
   1409 
   1410 			*initmask |= invalid & BJ_INIT_ABIT;
   1411 
   1412 			if (BPF_SRC(insns[i].code) == BPF_X) {
   1413 				*hints |= BJ_HINT_XREG;
   1414 				*initmask |= invalid & BJ_INIT_XBIT;
   1415 			}
   1416 
   1417 			switch (BPF_OP(insns[i].code)) {
   1418 			case BPF_JA:
   1419 				jt = jf = insns[i].k;
   1420 				break;
   1421 			case BPF_JEQ:
   1422 			case BPF_JGT:
   1423 			case BPF_JGE:
   1424 			case BPF_JSET:
   1425 				jt = insns[i].jt;
   1426 				jf = insns[i].jf;
   1427 				break;
   1428 			default:
   1429 				return false;
   1430 			}
   1431 
   1432 			if (jt >= insn_count - (i + 1) ||
   1433 			    jf >= insn_count - (i + 1)) {
   1434 				return false;
   1435 			}
   1436 
   1437 			if (jt > 0 && jf > 0)
   1438 				unreachable = true;
   1439 
   1440 			jt += i + 1;
   1441 			jf += i + 1;
   1442 
   1443 			jtf = insn_dat[i].u.jdata.jtf;
   1444 
   1445 			jtf[0].jdata = &insn_dat[i].u.jdata;
   1446 			SLIST_INSERT_HEAD(&insn_dat[jt].bjumps,
   1447 			    &jtf[0], entries);
   1448 
   1449 			if (jf != jt) {
   1450 				jtf[1].jdata = &insn_dat[i].u.jdata;
   1451 				SLIST_INSERT_HEAD(&insn_dat[jf].bjumps,
   1452 				    &jtf[1], entries);
   1453 			}
   1454 
   1455 			insn_dat[jf].invalid |= invalid;
   1456 			insn_dat[jt].invalid |= invalid;
   1457 			invalid = 0;
   1458 
   1459 			continue;
   1460 		}
   1461 	}
   1462 
   1463 	return true;
   1464 }
   1465 
   1466 /*
   1467  * Array Bounds Check Elimination (ABC) pass.
   1468  */
   1469 static void
   1470 optimize_pass2(const bpf_ctx_t *bc, const struct bpf_insn *insns,
   1471     struct bpfjit_insn_data *insn_dat, size_t insn_count)
   1472 {
   1473 	struct bpfjit_jump *jmp;
   1474 	const struct bpf_insn *pc;
   1475 	struct bpfjit_insn_data *pd;
   1476 	size_t i;
   1477 	bpfjit_abc_length_t length, abc_length = 0;
   1478 
   1479 	const size_t extwords = GET_EXTWORDS(bc);
   1480 
   1481 	for (i = insn_count; i != 0; i--) {
   1482 		pc = &insns[i-1];
   1483 		pd = &insn_dat[i-1];
   1484 
   1485 		if (pd->unreachable)
   1486 			continue;
   1487 
   1488 		switch (BPF_CLASS(pc->code)) {
   1489 		case BPF_RET:
   1490 			/*
   1491 			 * It's quite common for bpf programs to
   1492 			 * check packet bytes in increasing order
   1493 			 * and return zero if bytes don't match
   1494 			 * specified critetion. Such programs disable
   1495 			 * ABC optimization completely because for
   1496 			 * every jump there is a branch with no read
   1497 			 * instruction.
   1498 			 * With no side effects, BPF_STMT(BPF_RET+BPF_K, 0)
   1499 			 * is indistinguishable from out-of-bound load.
   1500 			 * Therefore, abc_length can be set to
   1501 			 * MAX_ABC_LENGTH and enable ABC for many
   1502 			 * bpf programs.
   1503 			 * If this optimization encounters any
   1504 			 * instruction with a side effect, it will
   1505 			 * reset abc_length.
   1506 			 */
   1507 			if (BPF_RVAL(pc->code) == BPF_K && pc->k == 0)
   1508 				abc_length = MAX_ABC_LENGTH;
   1509 			else
   1510 				abc_length = 0;
   1511 			break;
   1512 
   1513 		case BPF_MISC:
   1514 			if (BPF_MISCOP(pc->code) == BPF_COP ||
   1515 			    BPF_MISCOP(pc->code) == BPF_COPX) {
   1516 				/* COP instructions can have side effects. */
   1517 				abc_length = 0;
   1518 			}
   1519 			break;
   1520 
   1521 		case BPF_ST:
   1522 		case BPF_STX:
   1523 			if (extwords != 0) {
   1524 				/* Write to memory is visible after a call. */
   1525 				abc_length = 0;
   1526 			}
   1527 			break;
   1528 
   1529 		case BPF_JMP:
   1530 			abc_length = pd->u.jdata.abc_length;
   1531 			break;
   1532 
   1533 		default:
   1534 			if (read_pkt_insn(pc, &length)) {
   1535 				if (abc_length < length)
   1536 					abc_length = length;
   1537 				pd->u.rdata.abc_length = abc_length;
   1538 			}
   1539 			break;
   1540 		}
   1541 
   1542 		SLIST_FOREACH(jmp, &pd->bjumps, entries) {
   1543 			if (jmp->jdata->abc_length > abc_length)
   1544 				jmp->jdata->abc_length = abc_length;
   1545 		}
   1546 	}
   1547 }
   1548 
   1549 static void
   1550 optimize_pass3(const struct bpf_insn *insns,
   1551     struct bpfjit_insn_data *insn_dat, size_t insn_count)
   1552 {
   1553 	struct bpfjit_jump *jmp;
   1554 	size_t i;
   1555 	bpfjit_abc_length_t checked_length = 0;
   1556 
   1557 	for (i = 0; i < insn_count; i++) {
   1558 		if (insn_dat[i].unreachable)
   1559 			continue;
   1560 
   1561 		SLIST_FOREACH(jmp, &insn_dat[i].bjumps, entries) {
   1562 			if (jmp->jdata->checked_length < checked_length)
   1563 				checked_length = jmp->jdata->checked_length;
   1564 		}
   1565 
   1566 		if (BPF_CLASS(insns[i].code) == BPF_JMP) {
   1567 			insn_dat[i].u.jdata.checked_length = checked_length;
   1568 		} else if (read_pkt_insn(&insns[i], NULL)) {
   1569 			struct bpfjit_read_pkt_data *rdata =
   1570 			    &insn_dat[i].u.rdata;
   1571 			rdata->check_length = 0;
   1572 			if (checked_length < rdata->abc_length) {
   1573 				checked_length = rdata->abc_length;
   1574 				rdata->check_length = checked_length;
   1575 			}
   1576 		}
   1577 	}
   1578 }
   1579 
   1580 static bool
   1581 optimize(const bpf_ctx_t *bc, const struct bpf_insn *insns,
   1582     struct bpfjit_insn_data *insn_dat, size_t insn_count,
   1583     bpf_memword_init_t *initmask, bpfjit_hint_t *hints)
   1584 {
   1585 
   1586 	optimize_init(insn_dat, insn_count);
   1587 
   1588 	if (!optimize_pass1(bc, insns, insn_dat, insn_count, initmask, hints))
   1589 		return false;
   1590 
   1591 	optimize_pass2(bc, insns, insn_dat, insn_count);
   1592 	optimize_pass3(insns, insn_dat, insn_count);
   1593 
   1594 	return true;
   1595 }
   1596 
   1597 /*
   1598  * Convert BPF_ALU operations except BPF_NEG and BPF_DIV to sljit operation.
   1599  */
   1600 static bool
   1601 alu_to_op(const struct bpf_insn *pc, int *res)
   1602 {
   1603 	/*
   1604 	 * bpf_validate() accepts all shifts, bpfjit doesn't
   1605 	 * accept shifts by a constant K greater than 31.
   1606 	 */
   1607 	const bool valid_shift = BPF_SRC(pc->code) != BPF_K || pc->k < 32;
   1608 
   1609 	/*
   1610 	 * Note: all supported 64bit arches have 32bit multiply
   1611 	 * instruction so SLJIT_I32_OP doesn't have any overhead.
   1612 	 */
   1613 	switch (BPF_OP(pc->code)) {
   1614 	case BPF_ADD:
   1615 		*res = SLJIT_ADD;
   1616 		return true;
   1617 	case BPF_SUB:
   1618 		*res = SLJIT_SUB;
   1619 		return true;
   1620 	case BPF_MUL:
   1621 		*res = SLJIT_MUL|SLJIT_I32_OP;
   1622 		return true;
   1623 	case BPF_OR:
   1624 		*res = SLJIT_OR;
   1625 		return true;
   1626 	case BPF_XOR:
   1627 		*res = SLJIT_XOR;
   1628 		return true;
   1629 	case BPF_AND:
   1630 		*res = SLJIT_AND;
   1631 		return true;
   1632 	case BPF_LSH:
   1633 		*res = SLJIT_SHL|SLJIT_I32_OP;
   1634 		return valid_shift;
   1635 	case BPF_RSH:
   1636 		*res = SLJIT_LSHR|SLJIT_I32_OP;
   1637 		return valid_shift;
   1638 	default:
   1639 		return false;
   1640 	}
   1641 }
   1642 
   1643 /*
   1644  * Convert BPF_JMP operations except BPF_JA to sljit condition.
   1645  */
   1646 static bool
   1647 jmp_to_cond(const struct bpf_insn *pc, bool negate, int *res)
   1648 {
   1649 
   1650 	/*
   1651 	 * Note: all supported 64bit arches have 32bit comparison
   1652 	 * instructions so SLJIT_I32_OP doesn't have any overhead.
   1653 	 */
   1654 	*res = SLJIT_I32_OP;
   1655 
   1656 	switch (BPF_OP(pc->code)) {
   1657 	case BPF_JGT:
   1658 		*res |= negate ? SLJIT_LESS_EQUAL : SLJIT_GREATER;
   1659 		return true;
   1660 	case BPF_JGE:
   1661 		*res |= negate ? SLJIT_LESS : SLJIT_GREATER_EQUAL;
   1662 		return true;
   1663 	case BPF_JEQ:
   1664 		*res |= negate ? SLJIT_NOT_EQUAL : SLJIT_EQUAL;
   1665 		return true;
   1666 	case BPF_JSET:
   1667 		*res |= negate ? SLJIT_EQUAL : SLJIT_NOT_EQUAL;
   1668 		return true;
   1669 	default:
   1670 		return false;
   1671 	}
   1672 }
   1673 
   1674 /*
   1675  * Convert BPF_K and BPF_X to sljit register.
   1676  */
   1677 static int
   1678 kx_to_reg(const struct bpf_insn *pc)
   1679 {
   1680 
   1681 	switch (BPF_SRC(pc->code)) {
   1682 	case BPF_K: return SLJIT_IMM;
   1683 	case BPF_X: return BJ_XREG;
   1684 	default:
   1685 		BJ_ASSERT(false);
   1686 		return 0;
   1687 	}
   1688 }
   1689 
   1690 static sljit_sw
   1691 kx_to_reg_arg(const struct bpf_insn *pc)
   1692 {
   1693 
   1694 	switch (BPF_SRC(pc->code)) {
   1695 	case BPF_K: return (uint32_t)pc->k; /* SLJIT_IMM, pc->k, */
   1696 	case BPF_X: return 0;               /* BJ_XREG, 0,      */
   1697 	default:
   1698 		BJ_ASSERT(false);
   1699 		return 0;
   1700 	}
   1701 }
   1702 
   1703 static bool
   1704 generate_insn_code(struct sljit_compiler *compiler, bpfjit_hint_t hints,
   1705     const bpf_ctx_t *bc, const struct bpf_insn *insns,
   1706     struct bpfjit_insn_data *insn_dat, size_t insn_count)
   1707 {
   1708 	/* a list of jumps to out-of-bound return from a generated function */
   1709 	struct sljit_jump **ret0;
   1710 	size_t ret0_size, ret0_maxsize;
   1711 
   1712 	struct sljit_jump *jump;
   1713 	struct sljit_label *label;
   1714 	const struct bpf_insn *pc;
   1715 	struct bpfjit_jump *bjump, *jtf;
   1716 	struct sljit_jump *to_mchain_jump;
   1717 
   1718 	size_t i;
   1719 	unsigned int mode, src, op;
   1720 	int branching, negate;
   1721 	int status, cond, op2;
   1722 	uint32_t jt, jf;
   1723 
   1724 	bool unconditional_ret;
   1725 	bool rv;
   1726 
   1727 	const size_t extwords = GET_EXTWORDS(bc);
   1728 	const size_t memwords = GET_MEMWORDS(bc);
   1729 
   1730 	ret0 = NULL;
   1731 	rv = false;
   1732 
   1733 	ret0_size = 0;
   1734 	ret0_maxsize = 64;
   1735 	ret0 = BJ_ALLOC(ret0_maxsize * sizeof(ret0[0]));
   1736 	if (ret0 == NULL)
   1737 		goto fail;
   1738 
   1739 	/* reset sjump members of jdata */
   1740 	for (i = 0; i < insn_count; i++) {
   1741 		if (insn_dat[i].unreachable ||
   1742 		    BPF_CLASS(insns[i].code) != BPF_JMP) {
   1743 			continue;
   1744 		}
   1745 
   1746 		jtf = insn_dat[i].u.jdata.jtf;
   1747 		jtf[0].sjump = jtf[1].sjump = NULL;
   1748 	}
   1749 
   1750 	/* main loop */
   1751 	for (i = 0; i < insn_count; i++) {
   1752 		if (insn_dat[i].unreachable)
   1753 			continue;
   1754 
   1755 		/*
   1756 		 * Resolve jumps to the current insn.
   1757 		 */
   1758 		label = NULL;
   1759 		SLIST_FOREACH(bjump, &insn_dat[i].bjumps, entries) {
   1760 			if (bjump->sjump != NULL) {
   1761 				if (label == NULL)
   1762 					label = sljit_emit_label(compiler);
   1763 				if (label == NULL)
   1764 					goto fail;
   1765 				sljit_set_label(bjump->sjump, label);
   1766 			}
   1767 		}
   1768 
   1769 		to_mchain_jump = NULL;
   1770 		unconditional_ret = false;
   1771 
   1772 		if (read_pkt_insn(&insns[i], NULL)) {
   1773 			if (insn_dat[i].u.rdata.check_length > UINT32_MAX) {
   1774 				/* Jump to "return 0" unconditionally. */
   1775 				unconditional_ret = true;
   1776 				jump = sljit_emit_jump(compiler, SLJIT_JUMP);
   1777 				if (jump == NULL)
   1778 					goto fail;
   1779 				if (!append_jump(jump, &ret0,
   1780 				    &ret0_size, &ret0_maxsize))
   1781 					goto fail;
   1782 			} else if (insn_dat[i].u.rdata.check_length > 0) {
   1783 				/* if (buflen < check_length) return 0; */
   1784 				jump = sljit_emit_cmp(compiler,
   1785 				    SLJIT_LESS,
   1786 				    BJ_BUFLEN, 0,
   1787 				    SLJIT_IMM,
   1788 				    insn_dat[i].u.rdata.check_length);
   1789 				if (jump == NULL)
   1790 					goto fail;
   1791 #ifdef _KERNEL
   1792 				to_mchain_jump = jump;
   1793 #else
   1794 				if (!append_jump(jump, &ret0,
   1795 				    &ret0_size, &ret0_maxsize))
   1796 					goto fail;
   1797 #endif
   1798 			}
   1799 		}
   1800 
   1801 		pc = &insns[i];
   1802 		switch (BPF_CLASS(pc->code)) {
   1803 
   1804 		default:
   1805 			goto fail;
   1806 
   1807 		case BPF_LD:
   1808 			/* BPF_LD+BPF_IMM          A <- k */
   1809 			if (pc->code == (BPF_LD|BPF_IMM)) {
   1810 				status = sljit_emit_op1(compiler,
   1811 				    SLJIT_MOV,
   1812 				    BJ_AREG, 0,
   1813 				    SLJIT_IMM, (uint32_t)pc->k);
   1814 				if (status != SLJIT_SUCCESS)
   1815 					goto fail;
   1816 
   1817 				continue;
   1818 			}
   1819 
   1820 			/* BPF_LD+BPF_MEM          A <- M[k] */
   1821 			if (pc->code == (BPF_LD|BPF_MEM)) {
   1822 				if ((uint32_t)pc->k >= memwords)
   1823 					goto fail;
   1824 				status = emit_memload(compiler,
   1825 				    BJ_AREG, pc->k, extwords);
   1826 				if (status != SLJIT_SUCCESS)
   1827 					goto fail;
   1828 
   1829 				continue;
   1830 			}
   1831 
   1832 			/* BPF_LD+BPF_W+BPF_LEN    A <- len */
   1833 			if (pc->code == (BPF_LD|BPF_W|BPF_LEN)) {
   1834 				status = sljit_emit_op1(compiler,
   1835 				    SLJIT_MOV, /* size_t source */
   1836 				    BJ_AREG, 0,
   1837 				    SLJIT_MEM1(BJ_ARGS),
   1838 				    offsetof(struct bpf_args, wirelen));
   1839 				if (status != SLJIT_SUCCESS)
   1840 					goto fail;
   1841 
   1842 				continue;
   1843 			}
   1844 
   1845 			mode = BPF_MODE(pc->code);
   1846 			if (mode != BPF_ABS && mode != BPF_IND)
   1847 				goto fail;
   1848 
   1849 			if (unconditional_ret)
   1850 				continue;
   1851 
   1852 			status = emit_pkt_read(compiler, hints, pc,
   1853 			    to_mchain_jump, &ret0, &ret0_size, &ret0_maxsize);
   1854 			if (status != SLJIT_SUCCESS)
   1855 				goto fail;
   1856 
   1857 			continue;
   1858 
   1859 		case BPF_LDX:
   1860 			mode = BPF_MODE(pc->code);
   1861 
   1862 			/* BPF_LDX+BPF_W+BPF_IMM    X <- k */
   1863 			if (mode == BPF_IMM) {
   1864 				if (BPF_SIZE(pc->code) != BPF_W)
   1865 					goto fail;
   1866 				status = sljit_emit_op1(compiler,
   1867 				    SLJIT_MOV,
   1868 				    BJ_XREG, 0,
   1869 				    SLJIT_IMM, (uint32_t)pc->k);
   1870 				if (status != SLJIT_SUCCESS)
   1871 					goto fail;
   1872 
   1873 				continue;
   1874 			}
   1875 
   1876 			/* BPF_LDX+BPF_W+BPF_LEN    X <- len */
   1877 			if (mode == BPF_LEN) {
   1878 				if (BPF_SIZE(pc->code) != BPF_W)
   1879 					goto fail;
   1880 				status = sljit_emit_op1(compiler,
   1881 				    SLJIT_MOV, /* size_t source */
   1882 				    BJ_XREG, 0,
   1883 				    SLJIT_MEM1(BJ_ARGS),
   1884 				    offsetof(struct bpf_args, wirelen));
   1885 				if (status != SLJIT_SUCCESS)
   1886 					goto fail;
   1887 
   1888 				continue;
   1889 			}
   1890 
   1891 			/* BPF_LDX+BPF_W+BPF_MEM    X <- M[k] */
   1892 			if (mode == BPF_MEM) {
   1893 				if (BPF_SIZE(pc->code) != BPF_W)
   1894 					goto fail;
   1895 				if ((uint32_t)pc->k >= memwords)
   1896 					goto fail;
   1897 				status = emit_memload(compiler,
   1898 				    BJ_XREG, pc->k, extwords);
   1899 				if (status != SLJIT_SUCCESS)
   1900 					goto fail;
   1901 
   1902 				continue;
   1903 			}
   1904 
   1905 			/* BPF_LDX+BPF_B+BPF_MSH    X <- 4*(P[k:1]&0xf) */
   1906 			if (mode != BPF_MSH || BPF_SIZE(pc->code) != BPF_B)
   1907 				goto fail;
   1908 
   1909 			if (unconditional_ret)
   1910 				continue;
   1911 
   1912 			status = emit_msh(compiler, hints, pc,
   1913 			    to_mchain_jump, &ret0, &ret0_size, &ret0_maxsize);
   1914 			if (status != SLJIT_SUCCESS)
   1915 				goto fail;
   1916 
   1917 			continue;
   1918 
   1919 		case BPF_ST:
   1920 			if (pc->code != BPF_ST ||
   1921 			    (uint32_t)pc->k >= memwords) {
   1922 				goto fail;
   1923 			}
   1924 
   1925 			status = emit_memstore(compiler,
   1926 			    BJ_AREG, pc->k, extwords);
   1927 			if (status != SLJIT_SUCCESS)
   1928 				goto fail;
   1929 
   1930 			continue;
   1931 
   1932 		case BPF_STX:
   1933 			if (pc->code != BPF_STX ||
   1934 			    (uint32_t)pc->k >= memwords) {
   1935 				goto fail;
   1936 			}
   1937 
   1938 			status = emit_memstore(compiler,
   1939 			    BJ_XREG, pc->k, extwords);
   1940 			if (status != SLJIT_SUCCESS)
   1941 				goto fail;
   1942 
   1943 			continue;
   1944 
   1945 		case BPF_ALU:
   1946 			if (pc->code == (BPF_ALU|BPF_NEG)) {
   1947 				status = sljit_emit_op1(compiler,
   1948 				    SLJIT_NEG,
   1949 				    BJ_AREG, 0,
   1950 				    BJ_AREG, 0);
   1951 				if (status != SLJIT_SUCCESS)
   1952 					goto fail;
   1953 
   1954 				continue;
   1955 			}
   1956 
   1957 			op = BPF_OP(pc->code);
   1958 			if (op != BPF_DIV && op != BPF_MOD) {
   1959 				if (!alu_to_op(pc, &op2))
   1960 					goto fail;
   1961 
   1962 				status = sljit_emit_op2(compiler,
   1963 				    op2, BJ_AREG, 0, BJ_AREG, 0,
   1964 				    kx_to_reg(pc), kx_to_reg_arg(pc));
   1965 				if (status != SLJIT_SUCCESS)
   1966 					goto fail;
   1967 
   1968 				continue;
   1969 			}
   1970 
   1971 			/* BPF_DIV/BPF_MOD */
   1972 
   1973 			src = BPF_SRC(pc->code);
   1974 			if (src != BPF_X && src != BPF_K)
   1975 				goto fail;
   1976 
   1977 			/* division by zero? */
   1978 			if (src == BPF_X) {
   1979 				jump = sljit_emit_cmp(compiler,
   1980 				    SLJIT_EQUAL|SLJIT_I32_OP,
   1981 				    BJ_XREG, 0,
   1982 				    SLJIT_IMM, 0);
   1983 				if (jump == NULL)
   1984 					goto fail;
   1985 				if (!append_jump(jump, &ret0,
   1986 				    &ret0_size, &ret0_maxsize))
   1987 					goto fail;
   1988 			} else if (pc->k == 0) {
   1989 				/* bpf_validate() fails */
   1990 				goto fail;
   1991 			}
   1992 
   1993 			if (src == BPF_X) {
   1994 				status = emit_moddiv(compiler, pc);
   1995 				if (status != SLJIT_SUCCESS)
   1996 					goto fail;
   1997 			} else if (pc->k != 0) {
   1998 				if (pc->k & (pc->k - 1)) {
   1999 					status = emit_moddiv(compiler, pc);
   2000 				} else {
   2001 					status = emit_pow2_moddiv(compiler, pc);
   2002 				}
   2003 				if (status != SLJIT_SUCCESS)
   2004 					goto fail;
   2005 			}
   2006 
   2007 			continue;
   2008 
   2009 		case BPF_JMP:
   2010 			op = BPF_OP(pc->code);
   2011 			if (op == BPF_JA) {
   2012 				jt = jf = pc->k;
   2013 			} else {
   2014 				jt = pc->jt;
   2015 				jf = pc->jf;
   2016 			}
   2017 
   2018 			negate = (jt == 0) ? 1 : 0;
   2019 			branching = (jt == jf) ? 0 : 1;
   2020 			jtf = insn_dat[i].u.jdata.jtf;
   2021 
   2022 			if (branching) {
   2023 				if (op != BPF_JSET) {
   2024 					if (!jmp_to_cond(pc, negate, &cond))
   2025 						goto fail;
   2026 					jump = sljit_emit_cmp(compiler,
   2027 					    cond, BJ_AREG, 0,
   2028 					    kx_to_reg(pc), kx_to_reg_arg(pc));
   2029 				} else {
   2030 					status = sljit_emit_op2(compiler,
   2031 					    SLJIT_AND,
   2032 					    BJ_TMP1REG, 0,
   2033 					    BJ_AREG, 0,
   2034 					    kx_to_reg(pc), kx_to_reg_arg(pc));
   2035 					if (status != SLJIT_SUCCESS)
   2036 						goto fail;
   2037 
   2038 					if (!jmp_to_cond(pc, negate, &cond))
   2039 						goto fail;
   2040 					jump = sljit_emit_cmp(compiler,
   2041 					    cond, BJ_TMP1REG, 0, SLJIT_IMM, 0);
   2042 				}
   2043 
   2044 				if (jump == NULL)
   2045 					goto fail;
   2046 
   2047 				BJ_ASSERT(jtf[negate].sjump == NULL);
   2048 				jtf[negate].sjump = jump;
   2049 			}
   2050 
   2051 			if (!branching || (jt != 0 && jf != 0)) {
   2052 				jump = sljit_emit_jump(compiler, SLJIT_JUMP);
   2053 				if (jump == NULL)
   2054 					goto fail;
   2055 
   2056 				BJ_ASSERT(jtf[branching].sjump == NULL);
   2057 				jtf[branching].sjump = jump;
   2058 			}
   2059 
   2060 			continue;
   2061 
   2062 		case BPF_RET:
   2063 			if (pc->code == (BPF_RET|BPF_K)) {
   2064 				/* accept k bytes */
   2065 				status = sljit_emit_return(compiler,
   2066 				    SLJIT_MOV_U32,
   2067 				    SLJIT_IMM, (uint32_t)pc->k);
   2068 				if (status != SLJIT_SUCCESS)
   2069 					goto fail;
   2070 			}
   2071 			else if (pc->code == (BPF_RET|BPF_A)) {
   2072 				/* accept A bytes */
   2073 				status = sljit_emit_return(compiler,
   2074 				    SLJIT_MOV_U32,
   2075 				    BJ_AREG, 0);
   2076 				if (status != SLJIT_SUCCESS)
   2077 					goto fail;
   2078 			} else {
   2079 				/* return 0; */
   2080 				jump = sljit_emit_jump(compiler, SLJIT_JUMP);
   2081 				if (jump == NULL)
   2082 					goto fail;
   2083 				if (!append_jump(jump, &ret0,
   2084 				    &ret0_size, &ret0_maxsize))
   2085 					goto fail;
   2086 			}
   2087 
   2088 			continue;
   2089 
   2090 		case BPF_MISC:
   2091 			switch (BPF_MISCOP(pc->code)) {
   2092 			case BPF_TAX:
   2093 				status = sljit_emit_op1(compiler,
   2094 				    SLJIT_MOV_U32,
   2095 				    BJ_XREG, 0,
   2096 				    BJ_AREG, 0);
   2097 				if (status != SLJIT_SUCCESS)
   2098 					goto fail;
   2099 
   2100 				continue;
   2101 
   2102 			case BPF_TXA:
   2103 				status = sljit_emit_op1(compiler,
   2104 				    SLJIT_MOV,
   2105 				    BJ_AREG, 0,
   2106 				    BJ_XREG, 0);
   2107 				if (status != SLJIT_SUCCESS)
   2108 					goto fail;
   2109 
   2110 				continue;
   2111 
   2112 			case BPF_COP:
   2113 			case BPF_COPX:
   2114 				if (bc == NULL || bc->copfuncs == NULL)
   2115 					goto fail;
   2116 				if (BPF_MISCOP(pc->code) == BPF_COP &&
   2117 				    (uint32_t)pc->k >= bc->nfuncs) {
   2118 					goto fail;
   2119 				}
   2120 
   2121 				status = emit_cop(compiler, hints, bc, pc,
   2122 				    &ret0, &ret0_size, &ret0_maxsize);
   2123 				if (status != SLJIT_SUCCESS)
   2124 					goto fail;
   2125 
   2126 				continue;
   2127 			}
   2128 
   2129 			goto fail;
   2130 		} /* switch */
   2131 	} /* main loop */
   2132 
   2133 	BJ_ASSERT(ret0_size <= ret0_maxsize);
   2134 
   2135 	if (ret0_size > 0) {
   2136 		label = sljit_emit_label(compiler);
   2137 		if (label == NULL)
   2138 			goto fail;
   2139 		for (i = 0; i < ret0_size; i++)
   2140 			sljit_set_label(ret0[i], label);
   2141 	}
   2142 
   2143 	status = sljit_emit_return(compiler,
   2144 	    SLJIT_MOV_U32,
   2145 	    SLJIT_IMM, 0);
   2146 	if (status != SLJIT_SUCCESS)
   2147 		goto fail;
   2148 
   2149 	rv = true;
   2150 
   2151 fail:
   2152 	if (ret0 != NULL)
   2153 		BJ_FREE(ret0, ret0_maxsize * sizeof(ret0[0]));
   2154 
   2155 	return rv;
   2156 }
   2157 
   2158 bpfjit_func_t
   2159 bpfjit_generate_code(const bpf_ctx_t *bc,
   2160     const struct bpf_insn *insns, size_t insn_count)
   2161 {
   2162 	void *rv;
   2163 	struct sljit_compiler *compiler;
   2164 
   2165 	size_t i;
   2166 	int status;
   2167 
   2168 	/* optimization related */
   2169 	bpf_memword_init_t initmask;
   2170 	bpfjit_hint_t hints;
   2171 
   2172 	/* memory store location for initial zero initialization */
   2173 	sljit_s32 mem_reg;
   2174 	sljit_sw mem_off;
   2175 
   2176 	struct bpfjit_insn_data *insn_dat;
   2177 
   2178 	const size_t extwords = GET_EXTWORDS(bc);
   2179 	const size_t memwords = GET_MEMWORDS(bc);
   2180 	const bpf_memword_init_t preinited = extwords ? bc->preinited : 0;
   2181 
   2182 	rv = NULL;
   2183 	compiler = NULL;
   2184 	insn_dat = NULL;
   2185 
   2186 	if (memwords > MAX_MEMWORDS)
   2187 		goto fail;
   2188 
   2189 	if (insn_count == 0 || insn_count > SIZE_MAX / sizeof(insn_dat[0]))
   2190 		goto fail;
   2191 
   2192 	/*
   2193 	 * Follow bpf_validate() and fail if a program doesn't end
   2194 	 * with a canonical RET. Other RETs arent' checked rigorously
   2195 	 * by bpf_validate() and non-canonical RETs may sneak in but
   2196 	 * they will be rejected by bpf_filter().
   2197 	 */
   2198 	if (insns[insn_count - 1].code != (BPF_RET|BPF_K) &&
   2199 	    insns[insn_count - 1].code != (BPF_RET|BPF_A)) {
   2200 		goto fail;
   2201 	}
   2202 
   2203 	insn_dat = BJ_ALLOC(insn_count * sizeof(insn_dat[0]));
   2204 	if (insn_dat == NULL)
   2205 		goto fail;
   2206 
   2207 	if (!optimize(bc, insns, insn_dat, insn_count, &initmask, &hints))
   2208 		goto fail;
   2209 
   2210 	compiler = sljit_create_compiler(NULL);
   2211 	if (compiler == NULL)
   2212 		goto fail;
   2213 
   2214 #if !defined(_KERNEL) && defined(SLJIT_VERBOSE) && SLJIT_VERBOSE
   2215 	sljit_compiler_verbose(compiler, stderr);
   2216 #endif
   2217 
   2218 	status = sljit_emit_enter(compiler, 0, 2, nscratches(hints),
   2219 	    NSAVEDS, 0, 0, sizeof(struct bpfjit_stack));
   2220 	if (status != SLJIT_SUCCESS)
   2221 		goto fail;
   2222 
   2223 	if (hints & BJ_HINT_COP) {
   2224 		/* save ctx argument */
   2225 		status = sljit_emit_op1(compiler,
   2226 		    SLJIT_MOV_P,
   2227 		    SLJIT_MEM1(SLJIT_SP),
   2228 		    offsetof(struct bpfjit_stack, ctx),
   2229 		    BJ_CTX_ARG, 0);
   2230 		if (status != SLJIT_SUCCESS)
   2231 			goto fail;
   2232 	}
   2233 
   2234 	if (extwords == 0) {
   2235 		mem_reg = SLJIT_MEM1(SLJIT_SP);
   2236 		mem_off = offsetof(struct bpfjit_stack, mem);
   2237 	} else {
   2238 		/* copy "mem" argument from bpf_args to bpfjit_stack */
   2239 		status = sljit_emit_op1(compiler,
   2240 		    SLJIT_MOV_P,
   2241 		    BJ_TMP1REG, 0,
   2242 		    SLJIT_MEM1(BJ_ARGS), offsetof(struct bpf_args, mem));
   2243 		if (status != SLJIT_SUCCESS)
   2244 			goto fail;
   2245 
   2246 		status = sljit_emit_op1(compiler,
   2247 		    SLJIT_MOV_P,
   2248 		    SLJIT_MEM1(SLJIT_SP),
   2249 		    offsetof(struct bpfjit_stack, extmem),
   2250 		    BJ_TMP1REG, 0);
   2251 		if (status != SLJIT_SUCCESS)
   2252 			goto fail;
   2253 
   2254 		mem_reg = SLJIT_MEM1(BJ_TMP1REG);
   2255 		mem_off = 0;
   2256 	}
   2257 
   2258 	/*
   2259 	 * Exclude pre-initialised external memory words but keep
   2260 	 * initialization statuses of A and X registers in case
   2261 	 * bc->preinited wrongly sets those two bits.
   2262 	 */
   2263 	initmask &= ~preinited | BJ_INIT_ABIT | BJ_INIT_XBIT;
   2264 
   2265 #if defined(_KERNEL)
   2266 	/* bpf_filter() checks initialization of memwords. */
   2267 	BJ_ASSERT((initmask & (BJ_INIT_MBIT(memwords) - 1)) == 0);
   2268 #endif
   2269 	for (i = 0; i < memwords; i++) {
   2270 		if (initmask & BJ_INIT_MBIT(i)) {
   2271 			/* M[i] = 0; */
   2272 			status = sljit_emit_op1(compiler,
   2273 			    SLJIT_MOV_U32,
   2274 			    mem_reg, mem_off + i * sizeof(uint32_t),
   2275 			    SLJIT_IMM, 0);
   2276 			if (status != SLJIT_SUCCESS)
   2277 				goto fail;
   2278 		}
   2279 	}
   2280 
   2281 	if (initmask & BJ_INIT_ABIT) {
   2282 		/* A = 0; */
   2283 		status = sljit_emit_op1(compiler,
   2284 		    SLJIT_MOV,
   2285 		    BJ_AREG, 0,
   2286 		    SLJIT_IMM, 0);
   2287 		if (status != SLJIT_SUCCESS)
   2288 			goto fail;
   2289 	}
   2290 
   2291 	if (initmask & BJ_INIT_XBIT) {
   2292 		/* X = 0; */
   2293 		status = sljit_emit_op1(compiler,
   2294 		    SLJIT_MOV,
   2295 		    BJ_XREG, 0,
   2296 		    SLJIT_IMM, 0);
   2297 		if (status != SLJIT_SUCCESS)
   2298 			goto fail;
   2299 	}
   2300 
   2301 	status = load_buf_buflen(compiler);
   2302 	if (status != SLJIT_SUCCESS)
   2303 		goto fail;
   2304 
   2305 	if (!generate_insn_code(compiler, hints,
   2306 	    bc, insns, insn_dat, insn_count)) {
   2307 		goto fail;
   2308 	}
   2309 
   2310 	rv = sljit_generate_code(compiler);
   2311 
   2312 fail:
   2313 	if (compiler != NULL)
   2314 		sljit_free_compiler(compiler);
   2315 
   2316 	if (insn_dat != NULL)
   2317 		BJ_FREE(insn_dat, insn_count * sizeof(insn_dat[0]));
   2318 
   2319 	return (bpfjit_func_t)rv;
   2320 }
   2321 
   2322 void
   2323 bpfjit_free_code(bpfjit_func_t code)
   2324 {
   2325 
   2326 	sljit_free_code((void *)code);
   2327 }
   2328