-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_bpf.c
131 lines (124 loc) · 2.56 KB
/
test_bpf.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include "./bpf.h"
#include "./bpf_private.h"
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
#define BPF_LD_IMM64(reg, v) \
{ \
.code = BPF_LD | BPF_DW | BPF_IMM, \
.dst_reg = (reg), \
.off = 0, \
.imm = (__u32) (v), \
}, \
{ \
.code = BPF_LD | BPF_W | BPF_IMM, \
.dst_reg = 0, \
.src_reg = 0, \
.off = 0, \
.imm = (__u32)(((__u64) (v)) >> 32), \
},
static
int test_st = 0;
static
int test_stx = 0;
int do_test(void)
{
struct bpf_insn bytecode[] = {
{
.code = BPF_LD | BPF_W | BPF_IMM,
.dst_reg = BPF_REG_0,
.imm = 123,
},
BPF_LD_IMM64(BPF_REG_1, 4566666666999)
{
.code = BPF_ALU64 | BPF_X | BPF_ADD,
.dst_reg = BPF_REG_0,
.src_reg = BPF_REG_1,
},
{
.code = BPF_JMP | BPF_JLT | BPF_X,
.dst_reg = BPF_REG_1,
.src_reg = BPF_REG_0,
.off = 1,
},
{
.code = BPF_LD | BPF_W | BPF_IMM,
.dst_reg = BPF_REG_9,
.imm = 666,
},
{
.code = BPF_LD | BPF_W | BPF_IMM,
.dst_reg = BPF_REG_10,
.imm = 777,
},
BPF_LD_IMM64(BPF_REG_2, (unsigned long) &test_st)
{
.code = BPF_ST | BPF_W | BPF_MEM,
.dst_reg = BPF_REG_2,
.off = 0,
.imm = 444,
},
BPF_LD_IMM64(BPF_REG_3, (unsigned long) &test_stx)
{
.code = BPF_STX | BPF_W | BPF_MEM,
.dst_reg = BPF_REG_3,
.src_reg = BPF_REG_10,
.off = 0,
},
};
if (validate_bytecode(bytecode, ARRAY_SIZE(bytecode))) {
fprintf(stderr, "Error validating bytecode\n");
return -1;
}
if (print_bytecode(bytecode, ARRAY_SIZE(bytecode))) {
fprintf(stderr, "Error printing bytecode\n");
return -1;
}
if (interpret_bytecode(bytecode, ARRAY_SIZE(bytecode))) {
fprintf(stderr, "Error interpreting bytecode\n");
return -1;
}
printf("test_st: %d\n", test_st);
printf("test_stx: %d\n", test_stx);
return 0;
}
int do_loop(void)
{
struct bpf_insn bytecode[] = {
{
.code = BPF_ALU | BPF_ADD | BPF_K,
.dst_reg = BPF_REG_0,
.imm = 1,
},
{
.code = BPF_JMP | BPF_JA,
.off = -2,
},
};
if (validate_bytecode(bytecode, ARRAY_SIZE(bytecode))) {
fprintf(stderr, "Error validating bytecode\n");
return -1;
}
if (print_bytecode(bytecode, ARRAY_SIZE(bytecode))) {
fprintf(stderr, "Error printing bytecode\n");
return -1;
}
/* Expect error. */
if (interpret_bytecode(bytecode, ARRAY_SIZE(bytecode))) {
fprintf(stderr, "Error interpreting bytecode\n");
return -1;
}
return 0;
}
int main(int argc, char **argv)
{
if (do_test()) {
return -1;
}
if (do_loop() == 0) {
return -1;
}
return 0;
}