1 /*-
2  * Copyright (c) 2011-2012 Alexander Nasonov.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in
13  *    the documentation and/or other materials provided with the
14  *    distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
19  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
20  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
22  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
26  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <bpfjit.h>
31 
32 #include <stdint.h>
33 
34 #include "util.h"
35 #include "tests.h"
36 
37 static void
test_misc_tax(void)38 test_misc_tax(void)
39 {
40 	static struct bpf_insn insns[] = {
41 		BPF_STMT(BPF_LD+BPF_IMM, 3),
42 		BPF_STMT(BPF_MISC+BPF_TAX, 0),
43 		BPF_STMT(BPF_LD+BPF_B+BPF_IND, 2),
44 		BPF_STMT(BPF_RET+BPF_A, 0)
45 	};
46 
47 	bpfjit_func_t code;
48 	uint8_t pkt[] = { 0, 11, 22, 33, 44, 55 };
49 
50 	size_t insn_count = sizeof(insns) / sizeof(insns[0]);
51 
52 	CHECK(bpf_validate(insns, insn_count));
53 
54 	code = bpfjit_generate_code(NULL, insns, insn_count);
55 	REQUIRE(code != NULL);
56 
57 	CHECK(jitcall(code, pkt, sizeof(pkt), sizeof(pkt)) == 55);
58 
59 	bpfjit_free_code(code);
60 }
61 
62 static void
test_misc_txa(void)63 test_misc_txa(void)
64 {
65 	static struct bpf_insn insns[] = {
66 		BPF_STMT(BPF_LDX+BPF_W+BPF_IMM, 391),
67 		BPF_STMT(BPF_MISC+BPF_TXA, 0),
68 		BPF_STMT(BPF_RET+BPF_A, 0)
69 	};
70 
71 	bpfjit_func_t code;
72 	uint8_t pkt[1]; /* the program doesn't read any data */
73 
74 	size_t insn_count = sizeof(insns) / sizeof(insns[0]);
75 
76 	CHECK(bpf_validate(insns, insn_count));
77 
78 	code = bpfjit_generate_code(NULL, insns, insn_count);
79 	REQUIRE(code != NULL);
80 
81 	CHECK(jitcall(code, pkt, 1, 1) == 391);
82 
83 	bpfjit_free_code(code);
84 }
85 
86 void
test_misc(void)87 test_misc(void)
88 {
89 
90 	test_misc_tax();
91 	test_misc_txa();
92 }
93