qla2xxx: Replace two macros with an inline function
[linux/fpc-iii.git] / samples / seccomp / bpf-helper.c
blob05cb4d5ff9f5bef632baa98eb687f1781dcb5e5e
1 /*
2 * Seccomp BPF helper functions
4 * Copyright (c) 2012 The Chromium OS Authors <chromium-os-dev@chromium.org>
5 * Author: Will Drewry <wad@chromium.org>
7 * The code may be used by anyone for any purpose,
8 * and can serve as a starting point for developing
9 * applications using prctl(PR_ATTACH_SECCOMP_FILTER).
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
16 #include "bpf-helper.h"
18 int bpf_resolve_jumps(struct bpf_labels *labels,
19 struct sock_filter *filter, size_t count)
21 struct sock_filter *begin = filter;
22 __u8 insn = count - 1;
24 if (count < 1)
25 return -1;
27 * Walk it once, backwards, to build the label table and do fixups.
28 * Since backward jumps are disallowed by BPF, this is easy.
30 filter += insn;
31 for (; filter >= begin; --insn, --filter) {
32 if (filter->code != (BPF_JMP+BPF_JA))
33 continue;
34 switch ((filter->jt<<8)|filter->jf) {
35 case (JUMP_JT<<8)|JUMP_JF:
36 if (labels->labels[filter->k].location == 0xffffffff) {
37 fprintf(stderr, "Unresolved label: '%s'\n",
38 labels->labels[filter->k].label);
39 return 1;
41 filter->k = labels->labels[filter->k].location -
42 (insn + 1);
43 filter->jt = 0;
44 filter->jf = 0;
45 continue;
46 case (LABEL_JT<<8)|LABEL_JF:
47 if (labels->labels[filter->k].location != 0xffffffff) {
48 fprintf(stderr, "Duplicate label use: '%s'\n",
49 labels->labels[filter->k].label);
50 return 1;
52 labels->labels[filter->k].location = insn;
53 filter->k = 0; /* fall through */
54 filter->jt = 0;
55 filter->jf = 0;
56 continue;
59 return 0;
62 /* Simple lookup table for labels. */
63 __u32 seccomp_bpf_label(struct bpf_labels *labels, const char *label)
65 struct __bpf_label *begin = labels->labels, *end;
66 int id;
68 if (labels->count == BPF_LABELS_MAX) {
69 fprintf(stderr, "Too many labels\n");
70 exit(1);
72 if (labels->count == 0) {
73 begin->label = label;
74 begin->location = 0xffffffff;
75 labels->count++;
76 return 0;
78 end = begin + labels->count;
79 for (id = 0; begin < end; ++begin, ++id) {
80 if (!strcmp(label, begin->label))
81 return id;
83 begin->label = label;
84 begin->location = 0xffffffff;
85 labels->count++;
86 return id;
89 void seccomp_bpf_print(struct sock_filter *filter, size_t count)
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);