1
2
3
4
5
6
7
8
9
10
11
12#include <stdio.h>
13#include <stdlib.h>
14#include <string.h>
15
16#include "bpf-helper.h"
17
18int bpf_resolve_jumps(struct bpf_labels *labels,
19 struct sock_filter *filter, size_t count)
20{
21 size_t i;
22
23 if (count < 1 || count > BPF_MAXINSNS)
24 return -1;
25
26
27
28
29 for (i = 0; i < count; ++i) {
30 size_t offset = count - i - 1;
31 struct sock_filter *instr = &filter[offset];
32 if (instr->code != (BPF_JMP+BPF_JA))
33 continue;
34 switch ((instr->jt<<8)|instr->jf) {
35 case (JUMP_JT<<8)|JUMP_JF:
36 if (labels->labels[instr->k].location == 0xffffffff) {
37 fprintf(stderr, "Unresolved label: '%s'\n",
38 labels->labels[instr->k].label);
39 return 1;
40 }
41 instr->k = labels->labels[instr->k].location -
42 (offset + 1);
43 instr->jt = 0;
44 instr->jf = 0;
45 continue;
46 case (LABEL_JT<<8)|LABEL_JF:
47 if (labels->labels[instr->k].location != 0xffffffff) {
48 fprintf(stderr, "Duplicate label use: '%s'\n",
49 labels->labels[instr->k].label);
50 return 1;
51 }
52 labels->labels[instr->k].location = offset;
53 instr->k = 0;
54 instr->jt = 0;
55 instr->jf = 0;
56 continue;
57 }
58 }
59 return 0;
60}
61
62
63__u32 seccomp_bpf_label(struct bpf_labels *labels, const char *label)
64{
65 struct __bpf_label *begin = labels->labels, *end;
66 int id;
67
68 if (labels->count == BPF_LABELS_MAX) {
69 fprintf(stderr, "Too many labels\n");
70 exit(1);
71 }
72 if (labels->count == 0) {
73 begin->label = label;
74 begin->location = 0xffffffff;
75 labels->count++;
76 return 0;
77 }
78 end = begin + labels->count;
79 for (id = 0; begin < end; ++begin, ++id) {
80 if (!strcmp(label, begin->label))
81 return id;
82 }
83 begin->label = label;
84 begin->location = 0xffffffff;
85 labels->count++;
86 return id;
87}
88
89void seccomp_bpf_print(struct sock_filter *filter, size_t count)
90{
91 struct sock_filter *end = filter + count;
92 for ( ; filter < end; ++filter)
93 printf("{ code=%u,jt=%u,jf=%u,k=%u },\n",
94 filter->code, filter->jt, filter->jf, filter->k);
95}
96