1 /* $NetBSD: optimize.c,v 1.8 2015/03/31 21:39:42 christos Exp $ */
4 * Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994, 1995, 1996
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that: (1) source code distributions
9 * retain the above copyright notice and this paragraph in its entirety, (2)
10 * distributions including binary code include the above copyright notice and
11 * this paragraph in its entirety in the documentation or other materials
12 * provided with the distribution, and (3) all advertising materials mentioning
13 * features or use of this software display the following acknowledgement:
14 * ``This product includes software developed by the University of California,
15 * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
16 * the University nor the names of its contributors may be used to endorse
17 * or promote products derived from this software without specific prior
19 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
20 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
23 * Optimization module for tcpdump intermediate representation.
26 #include <sys/cdefs.h>
27 __RCSID("$NetBSD: optimize.c,v 1.8 2015/03/31 21:39:42 christos Exp $");
34 #include <pcap-stdinc.h>
41 #ifdef HAVE_SYS_BITYPES_H
42 #include <sys/bitypes.h>
44 #include <sys/types.h>
58 #ifdef HAVE_OS_PROTO_H
66 #if defined(MSDOS) && !defined(__DJGPP__)
67 extern int _w32_ffs (int mask
);
71 #if defined(WIN32) && defined (_MSC_VER)
76 * Represents a deleted instruction.
81 * Register numbers for use-def values.
82 * 0 through BPF_MEMWORDS-1 represent the corresponding scratch memory
83 * location. A_ATOM is the accumulator and X_ATOM is the index
86 #define A_ATOM BPF_MEMWORDS
87 #define X_ATOM (BPF_MEMWORDS+1)
90 * This define is used to represent *both* the accumulator and
91 * x register in use-def computations.
92 * Currently, the use-def code assumes only one definition per instruction.
94 #define AX_ATOM N_ATOMS
97 * A flag to indicate that further optimization is needed.
98 * Iterative passes are continued until a given pass yields no
104 * A block is marked if only if its mark equals the current mark.
105 * Rather than traverse the code array, marking each item, 'cur_mark' is
106 * incremented. This automatically makes each element unmarked.
109 #define isMarked(p) ((p)->mark == cur_mark)
110 #define unMarkAll() cur_mark += 1
111 #define Mark(p) ((p)->mark = cur_mark)
113 static void opt_init(struct block
*);
114 static void opt_cleanup(void);
116 static void intern_blocks(struct block
*);
118 static void find_inedges(struct block
*);
120 static void opt_dump(struct block
*);
124 struct block
**blocks
;
129 * A bit vector set representation of the dominators.
130 * We round up the set size to the next power of two.
132 static int nodewords
;
133 static int edgewords
;
134 struct block
**levels
;
136 #define BITS_PER_WORD (8*sizeof(bpf_u_int32))
138 * True if a is in uset {p}
140 #define SET_MEMBER(p, a) \
141 ((p)[(unsigned)(a) / BITS_PER_WORD] & (1 << ((unsigned)(a) % BITS_PER_WORD)))
146 #define SET_INSERT(p, a) \
147 (p)[(unsigned)(a) / BITS_PER_WORD] |= (1 << ((unsigned)(a) % BITS_PER_WORD))
150 * Delete 'a' from uset p.
152 #define SET_DELETE(p, a) \
153 (p)[(unsigned)(a) / BITS_PER_WORD] &= ~(1 << ((unsigned)(a) % BITS_PER_WORD))
158 #define SET_INTERSECT(a, b, n)\
160 register bpf_u_int32 *_x = a, *_y = b;\
161 register int _n = n;\
162 while (--_n >= 0) *_x++ &= *_y++;\
168 #define SET_SUBTRACT(a, b, n)\
170 register bpf_u_int32 *_x = a, *_y = b;\
171 register int _n = n;\
172 while (--_n >= 0) *_x++ &=~ *_y++;\
178 #define SET_UNION(a, b, n)\
180 register bpf_u_int32 *_x = a, *_y = b;\
181 register int _n = n;\
182 while (--_n >= 0) *_x++ |= *_y++;\
185 static uset all_dom_sets
;
186 static uset all_closure_sets
;
187 static uset all_edge_sets
;
190 #define MAX(a,b) ((a)>(b)?(a):(b))
194 find_levels_r(struct block
*b
)
205 find_levels_r(JT(b
));
206 find_levels_r(JF(b
));
207 level
= MAX(JT(b
)->level
, JF(b
)->level
) + 1;
211 b
->link
= levels
[level
];
216 * Level graph. The levels go from 0 at the leaves to
217 * N_LEVELS at the root. The levels[] array points to the
218 * first node of the level list, whose elements are linked
219 * with the 'link' field of the struct block.
222 find_levels(struct block
*root
)
224 memset((char *)levels
, 0, n_blocks
* sizeof(*levels
));
230 * Find dominator relationships.
231 * Assumes graph has been leveled.
234 find_dom(struct block
*root
)
241 * Initialize sets to contain all nodes.
244 i
= n_blocks
* nodewords
;
247 /* Root starts off empty. */
248 for (i
= nodewords
; --i
>= 0;)
251 /* root->level is the highest level no found. */
252 for (i
= root
->level
; i
>= 0; --i
) {
253 for (b
= levels
[i
]; b
; b
= b
->link
) {
254 SET_INSERT(b
->dom
, b
->id
);
257 SET_INTERSECT(JT(b
)->dom
, b
->dom
, nodewords
);
258 SET_INTERSECT(JF(b
)->dom
, b
->dom
, nodewords
);
264 propedom(struct edge
*ep
)
266 SET_INSERT(ep
->edom
, ep
->id
);
268 SET_INTERSECT(ep
->succ
->et
.edom
, ep
->edom
, edgewords
);
269 SET_INTERSECT(ep
->succ
->ef
.edom
, ep
->edom
, edgewords
);
274 * Compute edge dominators.
275 * Assumes graph has been leveled and predecessors established.
278 find_edom(struct block
*root
)
285 for (i
= n_edges
* edgewords
; --i
>= 0; )
288 /* root->level is the highest level no found. */
289 memset(root
->et
.edom
, 0, edgewords
* sizeof(*(uset
)0));
290 memset(root
->ef
.edom
, 0, edgewords
* sizeof(*(uset
)0));
291 for (i
= root
->level
; i
>= 0; --i
) {
292 for (b
= levels
[i
]; b
!= 0; b
= b
->link
) {
300 * Find the backwards transitive closure of the flow graph. These sets
301 * are backwards in the sense that we find the set of nodes that reach
302 * a given node, not the set of nodes that can be reached by a node.
304 * Assumes graph has been leveled.
307 find_closure(struct block
*root
)
313 * Initialize sets to contain no nodes.
315 memset((char *)all_closure_sets
, 0,
316 n_blocks
* nodewords
* sizeof(*all_closure_sets
));
318 /* root->level is the highest level no found. */
319 for (i
= root
->level
; i
>= 0; --i
) {
320 for (b
= levels
[i
]; b
; b
= b
->link
) {
321 SET_INSERT(b
->closure
, b
->id
);
324 SET_UNION(JT(b
)->closure
, b
->closure
, nodewords
);
325 SET_UNION(JF(b
)->closure
, b
->closure
, nodewords
);
331 * Return the register number that is used by s. If A and X are both
332 * used, return AX_ATOM. If no register is used, return -1.
334 * The implementation should probably change to an array access.
337 atomuse(struct stmt
*s
)
339 register int c
= s
->code
;
344 switch (BPF_CLASS(c
)) {
347 return (BPF_RVAL(c
) == BPF_A
) ? A_ATOM
:
348 (BPF_RVAL(c
) == BPF_X
) ? X_ATOM
: -1;
352 return (BPF_MODE(c
) == BPF_IND
) ? X_ATOM
:
353 (BPF_MODE(c
) == BPF_MEM
) ? s
->k
: -1;
363 if (BPF_SRC(c
) == BPF_X
)
368 return BPF_MISCOP(c
) == BPF_TXA
? X_ATOM
: A_ATOM
;
375 * Return the register number that is defined by 's'. We assume that
376 * a single stmt cannot define more than one register. If no register
377 * is defined, return -1.
379 * The implementation should probably change to an array access.
382 atomdef(struct stmt
*s
)
387 switch (BPF_CLASS(s
->code
)) {
401 return BPF_MISCOP(s
->code
) == BPF_TAX
? X_ATOM
: A_ATOM
;
407 * Compute the sets of registers used, defined, and killed by 'b'.
409 * "Used" means that a statement in 'b' uses the register before any
410 * statement in 'b' defines it, i.e. it uses the value left in
411 * that register by a predecessor block of this block.
412 * "Defined" means that a statement in 'b' defines it.
413 * "Killed" means that a statement in 'b' defines it before any
414 * statement in 'b' uses it, i.e. it kills the value left in that
415 * register by a predecessor block of this block.
418 compute_local_ud(struct block
*b
)
421 atomset def
= 0, use
= 0, kill
= 0;
424 for (s
= b
->stmts
; s
; s
= s
->next
) {
425 if (s
->s
.code
== NOP
)
427 atom
= atomuse(&s
->s
);
429 if (atom
== AX_ATOM
) {
430 if (!ATOMELEM(def
, X_ATOM
))
431 use
|= ATOMMASK(X_ATOM
);
432 if (!ATOMELEM(def
, A_ATOM
))
433 use
|= ATOMMASK(A_ATOM
);
435 else if (atom
< N_ATOMS
) {
436 if (!ATOMELEM(def
, atom
))
437 use
|= ATOMMASK(atom
);
442 atom
= atomdef(&s
->s
);
444 if (!ATOMELEM(use
, atom
))
445 kill
|= ATOMMASK(atom
);
446 def
|= ATOMMASK(atom
);
449 if (BPF_CLASS(b
->s
.code
) == BPF_JMP
) {
451 * XXX - what about RET?
453 atom
= atomuse(&b
->s
);
455 if (atom
== AX_ATOM
) {
456 if (!ATOMELEM(def
, X_ATOM
))
457 use
|= ATOMMASK(X_ATOM
);
458 if (!ATOMELEM(def
, A_ATOM
))
459 use
|= ATOMMASK(A_ATOM
);
461 else if (atom
< N_ATOMS
) {
462 if (!ATOMELEM(def
, atom
))
463 use
|= ATOMMASK(atom
);
476 * Assume graph is already leveled.
479 find_ud(struct block
*root
)
485 * root->level is the highest level no found;
486 * count down from there.
488 maxlevel
= root
->level
;
489 for (i
= maxlevel
; i
>= 0; --i
)
490 for (p
= levels
[i
]; p
; p
= p
->link
) {
495 for (i
= 1; i
<= maxlevel
; ++i
) {
496 for (p
= levels
[i
]; p
; p
= p
->link
) {
497 p
->out_use
|= JT(p
)->in_use
| JF(p
)->in_use
;
498 p
->in_use
|= p
->out_use
&~ p
->kill
;
504 * These data structures are used in a Cocke and Shwarz style
505 * value numbering scheme. Since the flowgraph is acyclic,
506 * exit values can be propagated from a node's predecessors
507 * provided it is uniquely defined.
513 struct valnode
*next
;
517 static struct valnode
*hashtbl
[MODULUS
];
521 /* Integer constants mapped with the load immediate opcode. */
522 #define K(i) F(BPF_LD|BPF_IMM|BPF_W, i, 0L)
529 struct vmapinfo
*vmap
;
530 struct valnode
*vnode_base
;
531 struct valnode
*next_vnode
;
537 next_vnode
= vnode_base
;
538 memset((char *)vmap
, 0, maxval
* sizeof(*vmap
));
539 memset((char *)hashtbl
, 0, sizeof hashtbl
);
542 /* Because we really don't have an IR, this stuff is a little messy. */
544 F(int code
, int v0
, int v1
)
550 hash
= (u_int
)code
^ (v0
<< 4) ^ (v1
<< 8);
553 for (p
= hashtbl
[hash
]; p
; p
= p
->next
)
554 if (p
->code
== code
&& p
->v0
== v0
&& p
->v1
== v1
)
558 if (BPF_MODE(code
) == BPF_IMM
&&
559 (BPF_CLASS(code
) == BPF_LD
|| BPF_CLASS(code
) == BPF_LDX
)) {
560 vmap
[val
].const_val
= v0
;
561 vmap
[val
].is_const
= 1;
568 p
->next
= hashtbl
[hash
];
575 vstore(struct stmt
*s
, int *valp
, int newval
, int alter
)
577 if (alter
&& *valp
== newval
)
584 * Do constant-folding on binary operators.
585 * (Unary operators are handled elsewhere.)
588 fold_op(struct stmt
*s
, int v0
, int v1
)
592 a
= vmap
[v0
].const_val
;
593 b
= vmap
[v1
].const_val
;
595 switch (BPF_OP(s
->code
)) {
610 bpf_error("division by zero");
616 bpf_error("modulus by zero");
644 s
->code
= BPF_LD
|BPF_IMM
;
648 static inline struct slist
*
649 this_op(struct slist
*s
)
651 while (s
!= 0 && s
->s
.code
== NOP
)
657 opt_not(struct block
*b
)
659 struct block
*tmp
= JT(b
);
666 opt_peep(struct block
*b
)
669 struct slist
*next
, *last
;
677 for (/*empty*/; /*empty*/; s
= next
) {
683 break; /* nothing left in the block */
686 * Find the next real instruction after that one
689 next
= this_op(s
->next
);
691 break; /* no next instruction */
695 * st M[k] --> st M[k]
698 if (s
->s
.code
== BPF_ST
&&
699 next
->s
.code
== (BPF_LDX
|BPF_MEM
) &&
700 s
->s
.k
== next
->s
.k
) {
702 next
->s
.code
= BPF_MISC
|BPF_TAX
;
708 if (s
->s
.code
== (BPF_LD
|BPF_IMM
) &&
709 next
->s
.code
== (BPF_MISC
|BPF_TAX
)) {
710 s
->s
.code
= BPF_LDX
|BPF_IMM
;
711 next
->s
.code
= BPF_MISC
|BPF_TXA
;
715 * This is an ugly special case, but it happens
716 * when you say tcp[k] or udp[k] where k is a constant.
718 if (s
->s
.code
== (BPF_LD
|BPF_IMM
)) {
719 struct slist
*add
, *tax
, *ild
;
722 * Check that X isn't used on exit from this
723 * block (which the optimizer might cause).
724 * We know the code generator won't generate
725 * any local dependencies.
727 if (ATOMELEM(b
->out_use
, X_ATOM
))
731 * Check that the instruction following the ldi
732 * is an addx, or it's an ldxms with an addx
733 * following it (with 0 or more nops between the
736 if (next
->s
.code
!= (BPF_LDX
|BPF_MSH
|BPF_B
))
739 add
= this_op(next
->next
);
740 if (add
== 0 || add
->s
.code
!= (BPF_ALU
|BPF_ADD
|BPF_X
))
744 * Check that a tax follows that (with 0 or more
745 * nops between them).
747 tax
= this_op(add
->next
);
748 if (tax
== 0 || tax
->s
.code
!= (BPF_MISC
|BPF_TAX
))
752 * Check that an ild follows that (with 0 or more
753 * nops between them).
755 ild
= this_op(tax
->next
);
756 if (ild
== 0 || BPF_CLASS(ild
->s
.code
) != BPF_LD
||
757 BPF_MODE(ild
->s
.code
) != BPF_IND
)
760 * We want to turn this sequence:
763 * (005) ldxms [14] {next} -- optional
766 * (008) ild [x+0] {ild}
768 * into this sequence:
776 * XXX We need to check that X is not
777 * subsequently used, because we want to change
778 * what'll be in it after this sequence.
780 * We know we can eliminate the accumulator
781 * modifications earlier in the sequence since
782 * it is defined by the last stmt of this sequence
783 * (i.e., the last statement of the sequence loads
784 * a value into the accumulator, so we can eliminate
785 * earlier operations on the accumulator).
795 * If the comparison at the end of a block is an equality
796 * comparison against a constant, and nobody uses the value
797 * we leave in the A register at the end of a block, and
798 * the operation preceding the comparison is an arithmetic
799 * operation, we can sometime optimize it away.
801 if (b
->s
.code
== (BPF_JMP
|BPF_JEQ
|BPF_K
) &&
802 !ATOMELEM(b
->out_use
, A_ATOM
)) {
804 * We can optimize away certain subtractions of the
807 if (last
->s
.code
== (BPF_ALU
|BPF_SUB
|BPF_X
)) {
808 val
= b
->val
[X_ATOM
];
809 if (vmap
[val
].is_const
) {
811 * If we have a subtract to do a comparison,
812 * and the X register is a known constant,
813 * we can merge this value into the
819 b
->s
.k
+= vmap
[val
].const_val
;
822 } else if (b
->s
.k
== 0) {
824 * If the X register isn't a constant,
825 * and the comparison in the test is
826 * against 0, we can compare with the
827 * X register, instead:
833 b
->s
.code
= BPF_JMP
|BPF_JEQ
|BPF_X
;
838 * Likewise, a constant subtract can be simplified:
841 * jeq #y -> jeq #(x+y)
843 else if (last
->s
.code
== (BPF_ALU
|BPF_SUB
|BPF_K
)) {
849 * And, similarly, a constant AND can be simplified
850 * if we're testing against 0, i.e.:
855 else if (last
->s
.code
== (BPF_ALU
|BPF_AND
|BPF_K
) &&
858 b
->s
.code
= BPF_JMP
|BPF_K
|BPF_JSET
;
866 * jset #ffffffff -> always
868 if (b
->s
.code
== (BPF_JMP
|BPF_K
|BPF_JSET
)) {
871 if (b
->s
.k
== (int)0xffffffff)
875 * If we're comparing against the index register, and the index
876 * register is a known constant, we can just compare against that
879 val
= b
->val
[X_ATOM
];
880 if (vmap
[val
].is_const
&& BPF_SRC(b
->s
.code
) == BPF_X
) {
881 bpf_int32 v
= vmap
[val
].const_val
;
886 * If the accumulator is a known constant, we can compute the
889 val
= b
->val
[A_ATOM
];
890 if (vmap
[val
].is_const
&& BPF_SRC(b
->s
.code
) == BPF_K
) {
891 bpf_int32 v
= vmap
[val
].const_val
;
892 switch (BPF_OP(b
->s
.code
)) {
899 v
= (unsigned)v
> (unsigned)b
->s
.k
;
903 v
= (unsigned)v
>= (unsigned)b
->s
.k
;
923 * Compute the symbolic value of expression of 's', and update
924 * anything it defines in the value table 'val'. If 'alter' is true,
925 * do various optimizations. This code would be cleaner if symbolic
926 * evaluation and code transformations weren't folded together.
929 opt_stmt(struct stmt
*s
, int val
[], int alter
)
936 case BPF_LD
|BPF_ABS
|BPF_W
:
937 case BPF_LD
|BPF_ABS
|BPF_H
:
938 case BPF_LD
|BPF_ABS
|BPF_B
:
939 v
= F(s
->code
, s
->k
, 0L);
940 vstore(s
, &val
[A_ATOM
], v
, alter
);
943 case BPF_LD
|BPF_IND
|BPF_W
:
944 case BPF_LD
|BPF_IND
|BPF_H
:
945 case BPF_LD
|BPF_IND
|BPF_B
:
947 if (alter
&& vmap
[v
].is_const
) {
948 s
->code
= BPF_LD
|BPF_ABS
|BPF_SIZE(s
->code
);
949 s
->k
+= vmap
[v
].const_val
;
950 v
= F(s
->code
, s
->k
, 0L);
954 v
= F(s
->code
, s
->k
, v
);
955 vstore(s
, &val
[A_ATOM
], v
, alter
);
959 v
= F(s
->code
, 0L, 0L);
960 vstore(s
, &val
[A_ATOM
], v
, alter
);
965 vstore(s
, &val
[A_ATOM
], v
, alter
);
968 case BPF_LDX
|BPF_IMM
:
970 vstore(s
, &val
[X_ATOM
], v
, alter
);
973 case BPF_LDX
|BPF_MSH
|BPF_B
:
974 v
= F(s
->code
, s
->k
, 0L);
975 vstore(s
, &val
[X_ATOM
], v
, alter
);
978 case BPF_ALU
|BPF_NEG
:
979 if (alter
&& vmap
[val
[A_ATOM
]].is_const
) {
980 s
->code
= BPF_LD
|BPF_IMM
;
981 s
->k
= -vmap
[val
[A_ATOM
]].const_val
;
982 val
[A_ATOM
] = K(s
->k
);
985 val
[A_ATOM
] = F(s
->code
, val
[A_ATOM
], 0L);
988 case BPF_ALU
|BPF_ADD
|BPF_K
:
989 case BPF_ALU
|BPF_SUB
|BPF_K
:
990 case BPF_ALU
|BPF_MUL
|BPF_K
:
991 case BPF_ALU
|BPF_DIV
|BPF_K
:
992 case BPF_ALU
|BPF_MOD
|BPF_K
:
993 case BPF_ALU
|BPF_AND
|BPF_K
:
994 case BPF_ALU
|BPF_OR
|BPF_K
:
995 case BPF_ALU
|BPF_XOR
|BPF_K
:
996 case BPF_ALU
|BPF_LSH
|BPF_K
:
997 case BPF_ALU
|BPF_RSH
|BPF_K
:
998 op
= BPF_OP(s
->code
);
1001 /* don't optimize away "sub #0"
1002 * as it may be needed later to
1003 * fixup the generated math code */
1004 if (op
== BPF_ADD
||
1005 op
== BPF_LSH
|| op
== BPF_RSH
||
1006 op
== BPF_OR
|| op
== BPF_XOR
) {
1010 if (op
== BPF_MUL
|| op
== BPF_AND
) {
1011 s
->code
= BPF_LD
|BPF_IMM
;
1012 val
[A_ATOM
] = K(s
->k
);
1016 if (vmap
[val
[A_ATOM
]].is_const
) {
1017 fold_op(s
, val
[A_ATOM
], K(s
->k
));
1018 val
[A_ATOM
] = K(s
->k
);
1022 val
[A_ATOM
] = F(s
->code
, val
[A_ATOM
], K(s
->k
));
1025 case BPF_ALU
|BPF_ADD
|BPF_X
:
1026 case BPF_ALU
|BPF_SUB
|BPF_X
:
1027 case BPF_ALU
|BPF_MUL
|BPF_X
:
1028 case BPF_ALU
|BPF_DIV
|BPF_X
:
1029 case BPF_ALU
|BPF_MOD
|BPF_X
:
1030 case BPF_ALU
|BPF_AND
|BPF_X
:
1031 case BPF_ALU
|BPF_OR
|BPF_X
:
1032 case BPF_ALU
|BPF_XOR
|BPF_X
:
1033 case BPF_ALU
|BPF_LSH
|BPF_X
:
1034 case BPF_ALU
|BPF_RSH
|BPF_X
:
1035 op
= BPF_OP(s
->code
);
1036 if (alter
&& vmap
[val
[X_ATOM
]].is_const
) {
1037 if (vmap
[val
[A_ATOM
]].is_const
) {
1038 fold_op(s
, val
[A_ATOM
], val
[X_ATOM
]);
1039 val
[A_ATOM
] = K(s
->k
);
1042 s
->code
= BPF_ALU
|BPF_K
|op
;
1043 s
->k
= vmap
[val
[X_ATOM
]].const_val
;
1046 F(s
->code
, val
[A_ATOM
], K(s
->k
));
1051 * Check if we're doing something to an accumulator
1052 * that is 0, and simplify. This may not seem like
1053 * much of a simplification but it could open up further
1055 * XXX We could also check for mul by 1, etc.
1057 if (alter
&& vmap
[val
[A_ATOM
]].is_const
1058 && vmap
[val
[A_ATOM
]].const_val
== 0) {
1059 if (op
== BPF_ADD
|| op
== BPF_OR
|| op
== BPF_XOR
) {
1060 s
->code
= BPF_MISC
|BPF_TXA
;
1061 vstore(s
, &val
[A_ATOM
], val
[X_ATOM
], alter
);
1064 else if (op
== BPF_MUL
|| op
== BPF_DIV
|| op
== BPF_MOD
||
1065 op
== BPF_AND
|| op
== BPF_LSH
|| op
== BPF_RSH
) {
1066 s
->code
= BPF_LD
|BPF_IMM
;
1068 vstore(s
, &val
[A_ATOM
], K(s
->k
), alter
);
1071 else if (op
== BPF_NEG
) {
1076 val
[A_ATOM
] = F(s
->code
, val
[A_ATOM
], val
[X_ATOM
]);
1079 case BPF_MISC
|BPF_TXA
:
1080 vstore(s
, &val
[A_ATOM
], val
[X_ATOM
], alter
);
1083 case BPF_LD
|BPF_MEM
:
1085 if (alter
&& vmap
[v
].is_const
) {
1086 s
->code
= BPF_LD
|BPF_IMM
;
1087 s
->k
= vmap
[v
].const_val
;
1090 vstore(s
, &val
[A_ATOM
], v
, alter
);
1093 case BPF_MISC
|BPF_TAX
:
1094 vstore(s
, &val
[X_ATOM
], val
[A_ATOM
], alter
);
1097 case BPF_LDX
|BPF_MEM
:
1099 if (alter
&& vmap
[v
].is_const
) {
1100 s
->code
= BPF_LDX
|BPF_IMM
;
1101 s
->k
= vmap
[v
].const_val
;
1104 vstore(s
, &val
[X_ATOM
], v
, alter
);
1108 vstore(s
, &val
[s
->k
], val
[A_ATOM
], alter
);
1112 vstore(s
, &val
[s
->k
], val
[X_ATOM
], alter
);
1118 deadstmt(register struct stmt
*s
, register struct stmt
*last
[])
1124 if (atom
== AX_ATOM
) {
1135 last
[atom
]->code
= NOP
;
1142 opt_deadstores(register struct block
*b
)
1144 register struct slist
*s
;
1146 struct stmt
*last
[N_ATOMS
];
1148 memset((char *)last
, 0, sizeof last
);
1150 for (s
= b
->stmts
; s
!= 0; s
= s
->next
)
1151 deadstmt(&s
->s
, last
);
1152 deadstmt(&b
->s
, last
);
1154 for (atom
= 0; atom
< N_ATOMS
; ++atom
)
1155 if (last
[atom
] && !ATOMELEM(b
->out_use
, atom
)) {
1156 last
[atom
]->code
= NOP
;
1162 opt_blk(struct block
*b
, int do_stmts
)
1167 bpf_int32 aval
, xval
;
1170 for (s
= b
->stmts
; s
&& s
->next
; s
= s
->next
)
1171 if (BPF_CLASS(s
->s
.code
) == BPF_JMP
) {
1178 * Initialize the atom values.
1183 * We have no predecessors, so everything is undefined
1184 * upon entry to this block.
1186 memset((char *)b
->val
, 0, sizeof(b
->val
));
1189 * Inherit values from our predecessors.
1191 * First, get the values from the predecessor along the
1192 * first edge leading to this node.
1194 memcpy((char *)b
->val
, (char *)p
->pred
->val
, sizeof(b
->val
));
1196 * Now look at all the other nodes leading to this node.
1197 * If, for the predecessor along that edge, a register
1198 * has a different value from the one we have (i.e.,
1199 * control paths are merging, and the merging paths
1200 * assign different values to that register), give the
1201 * register the undefined value of 0.
1203 while ((p
= p
->next
) != NULL
) {
1204 for (i
= 0; i
< N_ATOMS
; ++i
)
1205 if (b
->val
[i
] != p
->pred
->val
[i
])
1209 aval
= b
->val
[A_ATOM
];
1210 xval
= b
->val
[X_ATOM
];
1211 for (s
= b
->stmts
; s
; s
= s
->next
)
1212 opt_stmt(&s
->s
, b
->val
, do_stmts
);
1215 * This is a special case: if we don't use anything from this
1216 * block, and we load the accumulator or index register with a
1217 * value that is already there, or if this block is a return,
1218 * eliminate all the statements.
1220 * XXX - what if it does a store?
1222 * XXX - why does it matter whether we use anything from this
1223 * block? If the accumulator or index register doesn't change
1224 * its value, isn't that OK even if we use that value?
1226 * XXX - if we load the accumulator with a different value,
1227 * and the block ends with a conditional branch, we obviously
1228 * can't eliminate it, as the branch depends on that value.
1229 * For the index register, the conditional branch only depends
1230 * on the index register value if the test is against the index
1231 * register value rather than a constant; if nothing uses the
1232 * value we put into the index register, and we're not testing
1233 * against the index register's value, and there aren't any
1234 * other problems that would keep us from eliminating this
1235 * block, can we eliminate it?
1238 ((b
->out_use
== 0 && aval
!= 0 && b
->val
[A_ATOM
] == aval
&&
1239 xval
!= 0 && b
->val
[X_ATOM
] == xval
) ||
1240 BPF_CLASS(b
->s
.code
) == BPF_RET
)) {
1241 if (b
->stmts
!= 0) {
1250 * Set up values for branch optimizer.
1252 if (BPF_SRC(b
->s
.code
) == BPF_K
)
1253 b
->oval
= K(b
->s
.k
);
1255 b
->oval
= b
->val
[X_ATOM
];
1256 b
->et
.code
= b
->s
.code
;
1257 b
->ef
.code
= -b
->s
.code
;
1261 * Return true if any register that is used on exit from 'succ', has
1262 * an exit value that is different from the corresponding exit value
1266 use_conflict(struct block
*b
, struct block
*succ
)
1269 atomset use
= succ
->out_use
;
1274 for (atom
= 0; atom
< N_ATOMS
; ++atom
)
1275 if (ATOMELEM(use
, atom
))
1276 if (b
->val
[atom
] != succ
->val
[atom
])
1281 static struct block
*
1282 fold_edge(struct block
*child
, struct edge
*ep
)
1285 int aval0
, aval1
, oval0
, oval1
;
1286 int code
= ep
->code
;
1294 if (child
->s
.code
!= code
)
1297 aval0
= child
->val
[A_ATOM
];
1298 oval0
= child
->oval
;
1299 aval1
= ep
->pred
->val
[A_ATOM
];
1300 oval1
= ep
->pred
->oval
;
1307 * The operands of the branch instructions are
1308 * identical, so the result is true if a true
1309 * branch was taken to get here, otherwise false.
1311 return sense
? JT(child
) : JF(child
);
1313 if (sense
&& code
== (BPF_JMP
|BPF_JEQ
|BPF_K
))
1315 * At this point, we only know the comparison if we
1316 * came down the true branch, and it was an equality
1317 * comparison with a constant.
1319 * I.e., if we came down the true branch, and the branch
1320 * was an equality comparison with a constant, we know the
1321 * accumulator contains that constant. If we came down
1322 * the false branch, or the comparison wasn't with a
1323 * constant, we don't know what was in the accumulator.
1325 * We rely on the fact that distinct constants have distinct
1334 opt_j(struct edge
*ep
)
1337 register struct block
*target
;
1339 if (JT(ep
->succ
) == 0)
1342 if (JT(ep
->succ
) == JF(ep
->succ
)) {
1344 * Common branch targets can be eliminated, provided
1345 * there is no data dependency.
1347 if (!use_conflict(ep
->pred
, ep
->succ
->et
.succ
)) {
1349 ep
->succ
= JT(ep
->succ
);
1353 * For each edge dominator that matches the successor of this
1354 * edge, promote the edge successor to the its grandchild.
1356 * XXX We violate the set abstraction here in favor a reasonably
1360 for (i
= 0; i
< edgewords
; ++i
) {
1361 register bpf_u_int32 x
= ep
->edom
[i
];
1366 k
+= i
* BITS_PER_WORD
;
1368 target
= fold_edge(ep
->succ
, edges
[k
]);
1370 * Check that there is no data dependency between
1371 * nodes that will be violated if we move the edge.
1373 if (target
!= 0 && !use_conflict(ep
->pred
, target
)) {
1376 if (JT(target
) != 0)
1378 * Start over unless we hit a leaf.
1389 or_pullup(struct block
*b
)
1393 struct block
**diffp
, **samep
;
1401 * Make sure each predecessor loads the same value.
1404 val
= ep
->pred
->val
[A_ATOM
];
1405 for (ep
= ep
->next
; ep
!= 0; ep
= ep
->next
)
1406 if (val
!= ep
->pred
->val
[A_ATOM
])
1409 if (JT(b
->in_edges
->pred
) == b
)
1410 diffp
= &JT(b
->in_edges
->pred
);
1412 diffp
= &JF(b
->in_edges
->pred
);
1419 if (JT(*diffp
) != JT(b
))
1422 if (!SET_MEMBER((*diffp
)->dom
, b
->id
))
1425 if ((*diffp
)->val
[A_ATOM
] != val
)
1428 diffp
= &JF(*diffp
);
1431 samep
= &JF(*diffp
);
1436 if (JT(*samep
) != JT(b
))
1439 if (!SET_MEMBER((*samep
)->dom
, b
->id
))
1442 if ((*samep
)->val
[A_ATOM
] == val
)
1445 /* XXX Need to check that there are no data dependencies
1446 between dp0 and dp1. Currently, the code generator
1447 will not produce such dependencies. */
1448 samep
= &JF(*samep
);
1451 /* XXX This doesn't cover everything. */
1452 for (i
= 0; i
< N_ATOMS
; ++i
)
1453 if ((*samep
)->val
[i
] != pred
->val
[i
])
1456 /* Pull up the node. */
1462 * At the top of the chain, each predecessor needs to point at the
1463 * pulled up node. Inside the chain, there is only one predecessor
1467 for (ep
= b
->in_edges
; ep
!= 0; ep
= ep
->next
) {
1468 if (JT(ep
->pred
) == b
)
1469 JT(ep
->pred
) = pull
;
1471 JF(ep
->pred
) = pull
;
1481 and_pullup(struct block
*b
)
1485 struct block
**diffp
, **samep
;
1493 * Make sure each predecessor loads the same value.
1495 val
= ep
->pred
->val
[A_ATOM
];
1496 for (ep
= ep
->next
; ep
!= 0; ep
= ep
->next
)
1497 if (val
!= ep
->pred
->val
[A_ATOM
])
1500 if (JT(b
->in_edges
->pred
) == b
)
1501 diffp
= &JT(b
->in_edges
->pred
);
1503 diffp
= &JF(b
->in_edges
->pred
);
1510 if (JF(*diffp
) != JF(b
))
1513 if (!SET_MEMBER((*diffp
)->dom
, b
->id
))
1516 if ((*diffp
)->val
[A_ATOM
] != val
)
1519 diffp
= &JT(*diffp
);
1522 samep
= &JT(*diffp
);
1527 if (JF(*samep
) != JF(b
))
1530 if (!SET_MEMBER((*samep
)->dom
, b
->id
))
1533 if ((*samep
)->val
[A_ATOM
] == val
)
1536 /* XXX Need to check that there are no data dependencies
1537 between diffp and samep. Currently, the code generator
1538 will not produce such dependencies. */
1539 samep
= &JT(*samep
);
1542 /* XXX This doesn't cover everything. */
1543 for (i
= 0; i
< N_ATOMS
; ++i
)
1544 if ((*samep
)->val
[i
] != pred
->val
[i
])
1547 /* Pull up the node. */
1553 * At the top of the chain, each predecessor needs to point at the
1554 * pulled up node. Inside the chain, there is only one predecessor
1558 for (ep
= b
->in_edges
; ep
!= 0; ep
= ep
->next
) {
1559 if (JT(ep
->pred
) == b
)
1560 JT(ep
->pred
) = pull
;
1562 JF(ep
->pred
) = pull
;
1572 opt_blks(struct block
*root
, int do_stmts
)
1578 maxlevel
= root
->level
;
1581 for (i
= maxlevel
; i
>= 0; --i
)
1582 for (p
= levels
[i
]; p
; p
= p
->link
)
1583 opt_blk(p
, do_stmts
);
1587 * No point trying to move branches; it can't possibly
1588 * make a difference at this point.
1592 for (i
= 1; i
<= maxlevel
; ++i
) {
1593 for (p
= levels
[i
]; p
; p
= p
->link
) {
1600 for (i
= 1; i
<= maxlevel
; ++i
) {
1601 for (p
= levels
[i
]; p
; p
= p
->link
) {
1609 link_inedge(struct edge
*parent
, struct block
*child
)
1611 parent
->next
= child
->in_edges
;
1612 child
->in_edges
= parent
;
1616 find_inedges(struct block
*root
)
1621 for (i
= 0; i
< n_blocks
; ++i
)
1622 blocks
[i
]->in_edges
= 0;
1625 * Traverse the graph, adding each edge to the predecessor
1626 * list of its successors. Skip the leaves (i.e. level 0).
1628 for (i
= root
->level
; i
> 0; --i
) {
1629 for (b
= levels
[i
]; b
!= 0; b
= b
->link
) {
1630 link_inedge(&b
->et
, JT(b
));
1631 link_inedge(&b
->ef
, JF(b
));
1637 opt_root(struct block
**b
)
1639 struct slist
*tmp
, *s
;
1643 while (BPF_CLASS((*b
)->s
.code
) == BPF_JMP
&& JT(*b
) == JF(*b
))
1652 * If the root node is a return, then there is no
1653 * point executing any statements (since the bpf machine
1654 * has no side effects).
1656 if (BPF_CLASS((*b
)->s
.code
) == BPF_RET
)
1661 opt_loop(struct block
*root
, int do_stmts
)
1666 printf("opt_loop(root, %d) begin\n", do_stmts
);
1677 opt_blks(root
, do_stmts
);
1680 printf("opt_loop(root, %d) bottom, done=%d\n", do_stmts
, done
);
1688 * Optimize the filter code in its dag representation.
1691 bpf_optimize(struct block
**rootp
)
1700 intern_blocks(root
);
1703 printf("after intern_blocks()\n");
1710 printf("after opt_root()\n");
1718 make_marks(struct block
*p
)
1722 if (BPF_CLASS(p
->s
.code
) != BPF_RET
) {
1730 * Mark code array such that isMarked(i) is true
1731 * only for nodes that are alive.
1734 mark_code(struct block
*p
)
1741 * True iff the two stmt lists load the same value from the packet into
1745 eq_slist(struct slist
*x
, struct slist
*y
)
1748 while (x
&& x
->s
.code
== NOP
)
1750 while (y
&& y
->s
.code
== NOP
)
1756 if (x
->s
.code
!= y
->s
.code
|| x
->s
.k
!= y
->s
.k
)
1764 eq_blk(struct block
*b0
, struct block
*b1
)
1766 if (b0
->s
.code
== b1
->s
.code
&&
1767 b0
->s
.k
== b1
->s
.k
&&
1768 b0
->et
.succ
== b1
->et
.succ
&&
1769 b0
->ef
.succ
== b1
->ef
.succ
)
1770 return eq_slist(b0
->stmts
, b1
->stmts
);
1775 intern_blocks(struct block
*root
)
1779 int done1
; /* don't shadow global */
1782 for (i
= 0; i
< n_blocks
; ++i
)
1783 blocks
[i
]->link
= 0;
1787 for (i
= n_blocks
- 1; --i
>= 0; ) {
1788 if (!isMarked(blocks
[i
]))
1790 for (j
= i
+ 1; j
< n_blocks
; ++j
) {
1791 if (!isMarked(blocks
[j
]))
1793 if (eq_blk(blocks
[i
], blocks
[j
])) {
1794 blocks
[i
]->link
= blocks
[j
]->link
?
1795 blocks
[j
]->link
: blocks
[j
];
1800 for (i
= 0; i
< n_blocks
; ++i
) {
1806 JT(p
) = JT(p
)->link
;
1810 JF(p
) = JF(p
)->link
;
1820 free((void *)vnode_base
);
1822 free((void *)edges
);
1823 free((void *)space
);
1824 free((void *)levels
);
1825 free((void *)blocks
);
1829 * Return the number of stmts in 's'.
1832 slength(struct slist
*s
)
1836 for (; s
; s
= s
->next
)
1837 if (s
->s
.code
!= NOP
)
1843 * Return the number of nodes reachable by 'p'.
1844 * All nodes should be initially unmarked.
1847 count_blocks(struct block
*p
)
1849 if (p
== 0 || isMarked(p
))
1852 return count_blocks(JT(p
)) + count_blocks(JF(p
)) + 1;
1856 * Do a depth first search on the flow graph, numbering the
1857 * the basic blocks, and entering them into the 'blocks' array.`
1860 number_blks_r(struct block
*p
)
1864 if (p
== 0 || isMarked(p
))
1872 number_blks_r(JT(p
));
1873 number_blks_r(JF(p
));
1877 * Return the number of stmts in the flowgraph reachable by 'p'.
1878 * The nodes should be unmarked before calling.
1880 * Note that "stmts" means "instructions", and that this includes
1882 * side-effect statements in 'p' (slength(p->stmts));
1884 * statements in the true branch from 'p' (count_stmts(JT(p)));
1886 * statements in the false branch from 'p' (count_stmts(JF(p)));
1888 * the conditional jump itself (1);
1890 * an extra long jump if the true branch requires it (p->longjt);
1892 * an extra long jump if the false branch requires it (p->longjf).
1895 count_stmts(struct block
*p
)
1899 if (p
== 0 || isMarked(p
))
1902 n
= count_stmts(JT(p
)) + count_stmts(JF(p
));
1903 return slength(p
->stmts
) + n
+ 1 + p
->longjt
+ p
->longjf
;
1907 * Allocate memory. All allocation is done before optimization
1908 * is begun. A linear bound on the size of all data structures is computed
1909 * from the total number of blocks and/or statements.
1912 opt_init(struct block
*root
)
1915 int i
, n
, max_stmts
;
1918 * First, count the blocks, so we can malloc an array to map
1919 * block number to block. Then, put the blocks into the array.
1922 n
= count_blocks(root
);
1923 blocks
= (struct block
**)calloc(n
, sizeof(*blocks
));
1925 bpf_error("malloc");
1928 number_blks_r(root
);
1930 n_edges
= 2 * n_blocks
;
1931 edges
= (struct edge
**)calloc(n_edges
, sizeof(*edges
));
1933 bpf_error("malloc");
1936 * The number of levels is bounded by the number of nodes.
1938 levels
= (struct block
**)calloc(n_blocks
, sizeof(*levels
));
1940 bpf_error("malloc");
1942 edgewords
= n_edges
/ (8 * sizeof(bpf_u_int32
)) + 1;
1943 nodewords
= n_blocks
/ (8 * sizeof(bpf_u_int32
)) + 1;
1946 space
= (bpf_u_int32
*)malloc(2 * n_blocks
* nodewords
* sizeof(*space
)
1947 + n_edges
* edgewords
* sizeof(*space
));
1949 bpf_error("malloc");
1952 for (i
= 0; i
< n
; ++i
) {
1956 all_closure_sets
= p
;
1957 for (i
= 0; i
< n
; ++i
) {
1958 blocks
[i
]->closure
= p
;
1962 for (i
= 0; i
< n
; ++i
) {
1963 register struct block
*b
= blocks
[i
];
1971 b
->ef
.id
= n_blocks
+ i
;
1972 edges
[n_blocks
+ i
] = &b
->ef
;
1977 for (i
= 0; i
< n
; ++i
)
1978 max_stmts
+= slength(blocks
[i
]->stmts
) + 1;
1980 * We allocate at most 3 value numbers per statement,
1981 * so this is an upper bound on the number of valnodes
1984 maxval
= 3 * max_stmts
;
1985 vmap
= (struct vmapinfo
*)calloc(maxval
, sizeof(*vmap
));
1986 vnode_base
= (struct valnode
*)calloc(maxval
, sizeof(*vnode_base
));
1987 if (vmap
== NULL
|| vnode_base
== NULL
)
1988 bpf_error("malloc");
1992 * Some pointers used to convert the basic block form of the code,
1993 * into the array form that BPF requires. 'fstart' will point to
1994 * the malloc'd array while 'ftail' is used during the recursive traversal.
1996 static struct bpf_insn
*fstart
;
1997 static struct bpf_insn
*ftail
;
2004 * Returns true if successful. Returns false if a branch has
2005 * an offset that is too large. If so, we have marked that
2006 * branch so that on a subsequent iteration, it will be treated
2010 convert_code_r(struct block
*p
)
2012 struct bpf_insn
*dst
;
2016 int extrajmps
; /* number of extra jumps inserted */
2017 struct slist
**offset
= NULL
;
2019 if (p
== 0 || isMarked(p
))
2023 if (convert_code_r(JF(p
)) == 0)
2025 if (convert_code_r(JT(p
)) == 0)
2028 slen
= slength(p
->stmts
);
2029 dst
= ftail
-= (slen
+ 1 + p
->longjt
+ p
->longjf
);
2030 /* inflate length by any extra jumps */
2032 p
->offset
= dst
- fstart
;
2034 /* generate offset[] for convenience */
2036 offset
= (struct slist
**)calloc(slen
, sizeof(struct slist
*));
2038 bpf_error("not enough core");
2043 for (off
= 0; off
< slen
&& src
; off
++) {
2045 printf("off=%d src=%x\n", off
, src
);
2052 for (src
= p
->stmts
; src
; src
= src
->next
) {
2053 if (src
->s
.code
== NOP
)
2055 dst
->code
= (u_short
)src
->s
.code
;
2058 /* fill block-local relative jump */
2059 if (BPF_CLASS(src
->s
.code
) != BPF_JMP
|| src
->s
.code
== (BPF_JMP
|BPF_JA
)) {
2061 if (src
->s
.jt
|| src
->s
.jf
) {
2062 bpf_error("illegal jmp destination");
2068 if (off
== slen
- 2) /*???*/
2074 static const char ljerr
[] = "%s for block-local relative jump: off=%d";
2077 printf("code=%x off=%d %x %x\n", src
->s
.code
,
2078 off
, src
->s
.jt
, src
->s
.jf
);
2081 if (!src
->s
.jt
|| !src
->s
.jf
) {
2082 bpf_error(ljerr
, "no jmp destination", off
);
2087 for (i
= 0; i
< slen
; i
++) {
2088 if (offset
[i
] == src
->s
.jt
) {
2090 bpf_error(ljerr
, "multiple matches", off
);
2094 dst
->jt
= i
- off
- 1;
2097 if (offset
[i
] == src
->s
.jf
) {
2099 bpf_error(ljerr
, "multiple matches", off
);
2102 dst
->jf
= i
- off
- 1;
2107 bpf_error(ljerr
, "no destination found", off
);
2119 bids
[dst
- fstart
] = p
->id
+ 1;
2121 dst
->code
= (u_short
)p
->s
.code
;
2125 off
= JT(p
)->offset
- (p
->offset
+ slen
) - 1;
2127 /* offset too large for branch, must add a jump */
2128 if (p
->longjt
== 0) {
2129 /* mark this instruction and retry */
2133 /* branch if T to following jump */
2134 dst
->jt
= extrajmps
;
2136 dst
[extrajmps
].code
= BPF_JMP
|BPF_JA
;
2137 dst
[extrajmps
].k
= off
- extrajmps
;
2141 off
= JF(p
)->offset
- (p
->offset
+ slen
) - 1;
2143 /* offset too large for branch, must add a jump */
2144 if (p
->longjf
== 0) {
2145 /* mark this instruction and retry */
2149 /* branch if F to following jump */
2150 /* if two jumps are inserted, F goes to second one */
2151 dst
->jf
= extrajmps
;
2153 dst
[extrajmps
].code
= BPF_JMP
|BPF_JA
;
2154 dst
[extrajmps
].k
= off
- extrajmps
;
2164 * Convert flowgraph intermediate representation to the
2165 * BPF array representation. Set *lenp to the number of instructions.
2167 * This routine does *NOT* leak the memory pointed to by fp. It *must
2168 * not* do free(fp) before returning fp; doing so would make no sense,
2169 * as the BPF array pointed to by the return value of icode_to_fcode()
2170 * must be valid - it's being returned for use in a bpf_program structure.
2172 * If it appears that icode_to_fcode() is leaking, the problem is that
2173 * the program using pcap_compile() is failing to free the memory in
2174 * the BPF program when it's done - the leak is in the program, not in
2175 * the routine that happens to be allocating the memory. (By analogy, if
2176 * a program calls fopen() without ever calling fclose() on the FILE *,
2177 * it will leak the FILE structure; the leak is not in fopen(), it's in
2178 * the program.) Change the program to use pcap_freecode() when it's
2179 * done with the filter program. See the pcap man page.
2182 icode_to_fcode(struct block
*root
, u_int
*lenp
)
2185 struct bpf_insn
*fp
;
2188 * Loop doing convert_code_r() until no branches remain
2189 * with too-large offsets.
2193 n
= *lenp
= count_stmts(root
);
2195 fp
= (struct bpf_insn
*)malloc(sizeof(*fp
) * n
);
2197 bpf_error("malloc");
2198 memset((char *)fp
, 0, sizeof(*fp
) * n
);
2203 if (convert_code_r(root
))
2212 * Make a copy of a BPF program and put it in the "fcode" member of
2215 * If we fail to allocate memory for the copy, fill in the "errbuf"
2216 * member of the "pcap_t" with an error message, and return -1;
2217 * otherwise, return 0.
2220 install_bpf_program(pcap_t
*p
, struct bpf_program
*fp
)
2225 * Validate the program.
2227 if (!bpf_validate(fp
->bf_insns
, fp
->bf_len
)) {
2228 snprintf(p
->errbuf
, sizeof(p
->errbuf
),
2229 "BPF program is not valid");
2234 * Free up any already installed program.
2236 pcap_freecode(&p
->fcode
);
2238 prog_size
= sizeof(*fp
->bf_insns
) * fp
->bf_len
;
2239 p
->fcode
.bf_len
= fp
->bf_len
;
2240 p
->fcode
.bf_insns
= (struct bpf_insn
*)malloc(prog_size
);
2241 if (p
->fcode
.bf_insns
== NULL
) {
2242 snprintf(p
->errbuf
, sizeof(p
->errbuf
),
2243 "malloc: %s", pcap_strerror(errno
));
2246 memcpy(p
->fcode
.bf_insns
, fp
->bf_insns
, prog_size
);
2252 dot_dump_node(struct block
*block
, struct bpf_program
*prog
, FILE *out
)
2254 int icount
, noffset
;
2257 if (block
== NULL
|| isMarked(block
))
2261 icount
= slength(block
->stmts
) + 1 + block
->longjt
+ block
->longjf
;
2262 noffset
= min(block
->offset
+ icount
, (int)prog
->bf_len
);
2264 fprintf(out
, "\tblock%d [shape=ellipse, id=\"block-%d\" label=\"BLOCK%d\\n", block
->id
, block
->id
, block
->id
);
2265 for (i
= block
->offset
; i
< noffset
; i
++) {
2266 fprintf(out
, "\\n%s", bpf_image(prog
->bf_insns
+ i
, i
));
2268 fprintf(out
, "\" tooltip=\"");
2269 for (i
= 0; i
< BPF_MEMWORDS
; i
++)
2270 if (block
->val
[i
] != 0)
2271 fprintf(out
, "val[%d]=%d ", i
, block
->val
[i
]);
2272 fprintf(out
, "val[A]=%d ", block
->val
[A_ATOM
]);
2273 fprintf(out
, "val[X]=%d", block
->val
[X_ATOM
]);
2275 if (JT(block
) == NULL
)
2276 fprintf(out
, ", peripheries=2");
2277 fprintf(out
, "];\n");
2279 dot_dump_node(JT(block
), prog
, out
);
2280 dot_dump_node(JF(block
), prog
, out
);
2283 dot_dump_edge(struct block
*block
, FILE *out
)
2285 if (block
== NULL
|| isMarked(block
))
2290 fprintf(out
, "\t\"block%d\":se -> \"block%d\":n [label=\"T\"]; \n",
2291 block
->id
, JT(block
)->id
);
2292 fprintf(out
, "\t\"block%d\":sw -> \"block%d\":n [label=\"F\"]; \n",
2293 block
->id
, JF(block
)->id
);
2295 dot_dump_edge(JT(block
), out
);
2296 dot_dump_edge(JF(block
), out
);
2298 /* Output the block CFG using graphviz/DOT language
2299 * In the CFG, block's code, value index for each registers at EXIT,
2300 * and the jump relationship is show.
2302 * example DOT for BPF `ip src host 1.1.1.1' is:
2304 block0 [shape=ellipse, id="block-0" label="BLOCK0\n\n(000) ldh [12]\n(001) jeq #0x800 jt 2 jf 5" tooltip="val[A]=0 val[X]=0"];
2305 block1 [shape=ellipse, id="block-1" label="BLOCK1\n\n(002) ld [26]\n(003) jeq #0x1010101 jt 4 jf 5" tooltip="val[A]=0 val[X]=0"];
2306 block2 [shape=ellipse, id="block-2" label="BLOCK2\n\n(004) ret #68" tooltip="val[A]=0 val[X]=0", peripheries=2];
2307 block3 [shape=ellipse, id="block-3" label="BLOCK3\n\n(005) ret #0" tooltip="val[A]=0 val[X]=0", peripheries=2];
2308 "block0":se -> "block1":n [label="T"];
2309 "block0":sw -> "block3":n [label="F"];
2310 "block1":se -> "block2":n [label="T"];
2311 "block1":sw -> "block3":n [label="F"];
2314 * After install graphviz on http://www.graphviz.org/, save it as bpf.dot
2315 * and run `dot -Tpng -O bpf.dot' to draw the graph.
2318 dot_dump(struct block
*root
)
2320 struct bpf_program f
;
2323 memset(bids
, 0, sizeof bids
);
2324 f
.bf_insns
= icode_to_fcode(root
, &f
.bf_len
);
2326 fprintf(out
, "digraph BPF {\n");
2328 dot_dump_node(root
, &f
, out
);
2330 dot_dump_edge(root
, out
);
2331 fprintf(out
, "}\n");
2333 free((char *)f
.bf_insns
);
2337 plain_dump(struct block
*root
)
2339 struct bpf_program f
;
2341 memset(bids
, 0, sizeof bids
);
2342 f
.bf_insns
= icode_to_fcode(root
, &f
.bf_len
);
2345 free((char *)f
.bf_insns
);
2348 opt_dump(struct block
*root
)
2350 /* if optimizer debugging is enabled, output DOT graph
2351 * `dflag=4' is equivalent to -dddd to follow -d/-dd/-ddd
2352 * convention in tcpdump command line