]>
The Tcpdump Group git mirrors - libpcap/blob - optimize.c
714194539c4e49ff886aac7589c4d6da9c87fec7
2 * Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994, 1995, 1996
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that: (1) source code distributions
7 * retain the above copyright notice and this paragraph in its entirety, (2)
8 * distributions including binary code include the above copyright notice and
9 * this paragraph in its entirety in the documentation or other materials
10 * provided with the distribution, and (3) all advertising materials mentioning
11 * features or use of this software display the following acknowledgement:
12 * ``This product includes software developed by the University of California,
13 * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
14 * the University nor the names of its contributors may be used to endorse
15 * or promote products derived from this software without specific prior
17 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
19 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
21 * Optimization module for tcpdump intermediate representation.
29 #include <pcap-stdinc.h>
36 #ifdef HAVE_SYS_BITYPES_H
37 #include <sys/bitypes.h>
39 #include <sys/types.h>
53 #ifdef HAVE_OS_PROTO_H
58 int pcap_optimizer_debug
;
61 #if defined(MSDOS) && !defined(__DJGPP__)
62 extern int _w32_ffs (int mask
);
67 * So is the check for _MSC_VER done because MinGW has this?
69 #if defined(_WIN32) && defined (_MSC_VER)
71 * ffs -- vax ffs instruction
73 * XXX - with versions of VS that have it, use _BitScanForward()?
82 for (bit
= 1; !(mask
& 1); bit
++)
89 * Represents a deleted instruction.
94 * Register numbers for use-def values.
95 * 0 through BPF_MEMWORDS-1 represent the corresponding scratch memory
96 * location. A_ATOM is the accumulator and X_ATOM is the index
99 #define A_ATOM BPF_MEMWORDS
100 #define X_ATOM (BPF_MEMWORDS+1)
103 * This define is used to represent *both* the accumulator and
104 * x register in use-def computations.
105 * Currently, the use-def code assumes only one definition per instruction.
107 #define AX_ATOM N_ATOMS
110 * A flag to indicate that further optimization is needed.
111 * Iterative passes are continued until a given pass yields no
117 * A block is marked if only if its mark equals the current mark.
118 * Rather than traverse the code array, marking each item, 'cur_mark' is
119 * incremented. This automatically makes each element unmarked.
122 #define isMarked(p) ((p)->mark == cur_mark)
123 #define unMarkAll() cur_mark += 1
124 #define Mark(p) ((p)->mark = cur_mark)
126 static void opt_init(struct block
*);
127 static void opt_cleanup(void);
129 static void intern_blocks(struct block
*);
131 static void find_inedges(struct block
*);
133 static void opt_dump(struct block
*);
137 struct block
**blocks
;
142 * A bit vector set representation of the dominators.
143 * We round up the set size to the next power of two.
145 static int nodewords
;
146 static int edgewords
;
147 struct block
**levels
;
149 #define BITS_PER_WORD (8*sizeof(bpf_u_int32))
151 * True if a is in uset {p}
153 #define SET_MEMBER(p, a) \
154 ((p)[(unsigned)(a) / BITS_PER_WORD] & (1 << ((unsigned)(a) % BITS_PER_WORD)))
159 #define SET_INSERT(p, a) \
160 (p)[(unsigned)(a) / BITS_PER_WORD] |= (1 << ((unsigned)(a) % BITS_PER_WORD))
163 * Delete 'a' from uset p.
165 #define SET_DELETE(p, a) \
166 (p)[(unsigned)(a) / BITS_PER_WORD] &= ~(1 << ((unsigned)(a) % BITS_PER_WORD))
171 #define SET_INTERSECT(a, b, n)\
173 register bpf_u_int32 *_x = a, *_y = b;\
174 register int _n = n;\
175 while (--_n >= 0) *_x++ &= *_y++;\
181 #define SET_SUBTRACT(a, b, n)\
183 register bpf_u_int32 *_x = a, *_y = b;\
184 register int _n = n;\
185 while (--_n >= 0) *_x++ &=~ *_y++;\
191 #define SET_UNION(a, b, n)\
193 register bpf_u_int32 *_x = a, *_y = b;\
194 register int _n = n;\
195 while (--_n >= 0) *_x++ |= *_y++;\
198 static uset all_dom_sets
;
199 static uset all_closure_sets
;
200 static uset all_edge_sets
;
203 #define MAX(a,b) ((a)>(b)?(a):(b))
207 find_levels_r(struct block
*b
)
218 find_levels_r(JT(b
));
219 find_levels_r(JF(b
));
220 level
= MAX(JT(b
)->level
, JF(b
)->level
) + 1;
224 b
->link
= levels
[level
];
229 * Level graph. The levels go from 0 at the leaves to
230 * N_LEVELS at the root. The levels[] array points to the
231 * first node of the level list, whose elements are linked
232 * with the 'link' field of the struct block.
235 find_levels(struct block
*root
)
237 memset((char *)levels
, 0, n_blocks
* sizeof(*levels
));
243 * Find dominator relationships.
244 * Assumes graph has been leveled.
247 find_dom(struct block
*root
)
254 * Initialize sets to contain all nodes.
257 i
= n_blocks
* nodewords
;
260 /* Root starts off empty. */
261 for (i
= nodewords
; --i
>= 0;)
264 /* root->level is the highest level no found. */
265 for (i
= root
->level
; i
>= 0; --i
) {
266 for (b
= levels
[i
]; b
; b
= b
->link
) {
267 SET_INSERT(b
->dom
, b
->id
);
270 SET_INTERSECT(JT(b
)->dom
, b
->dom
, nodewords
);
271 SET_INTERSECT(JF(b
)->dom
, b
->dom
, nodewords
);
277 propedom(struct edge
*ep
)
279 SET_INSERT(ep
->edom
, ep
->id
);
281 SET_INTERSECT(ep
->succ
->et
.edom
, ep
->edom
, edgewords
);
282 SET_INTERSECT(ep
->succ
->ef
.edom
, ep
->edom
, edgewords
);
287 * Compute edge dominators.
288 * Assumes graph has been leveled and predecessors established.
291 find_edom(struct block
*root
)
298 for (i
= n_edges
* edgewords
; --i
>= 0; )
301 /* root->level is the highest level no found. */
302 memset(root
->et
.edom
, 0, edgewords
* sizeof(*(uset
)0));
303 memset(root
->ef
.edom
, 0, edgewords
* sizeof(*(uset
)0));
304 for (i
= root
->level
; i
>= 0; --i
) {
305 for (b
= levels
[i
]; b
!= 0; b
= b
->link
) {
313 * Find the backwards transitive closure of the flow graph. These sets
314 * are backwards in the sense that we find the set of nodes that reach
315 * a given node, not the set of nodes that can be reached by a node.
317 * Assumes graph has been leveled.
320 find_closure(struct block
*root
)
326 * Initialize sets to contain no nodes.
328 memset((char *)all_closure_sets
, 0,
329 n_blocks
* nodewords
* sizeof(*all_closure_sets
));
331 /* root->level is the highest level no found. */
332 for (i
= root
->level
; i
>= 0; --i
) {
333 for (b
= levels
[i
]; b
; b
= b
->link
) {
334 SET_INSERT(b
->closure
, b
->id
);
337 SET_UNION(JT(b
)->closure
, b
->closure
, nodewords
);
338 SET_UNION(JF(b
)->closure
, b
->closure
, nodewords
);
344 * Return the register number that is used by s. If A and X are both
345 * used, return AX_ATOM. If no register is used, return -1.
347 * The implementation should probably change to an array access.
350 atomuse(struct stmt
*s
)
352 register int c
= s
->code
;
357 switch (BPF_CLASS(c
)) {
360 return (BPF_RVAL(c
) == BPF_A
) ? A_ATOM
:
361 (BPF_RVAL(c
) == BPF_X
) ? X_ATOM
: -1;
365 return (BPF_MODE(c
) == BPF_IND
) ? X_ATOM
:
366 (BPF_MODE(c
) == BPF_MEM
) ? s
->k
: -1;
376 if (BPF_SRC(c
) == BPF_X
)
381 return BPF_MISCOP(c
) == BPF_TXA
? X_ATOM
: A_ATOM
;
388 * Return the register number that is defined by 's'. We assume that
389 * a single stmt cannot define more than one register. If no register
390 * is defined, return -1.
392 * The implementation should probably change to an array access.
395 atomdef(struct stmt
*s
)
400 switch (BPF_CLASS(s
->code
)) {
414 return BPF_MISCOP(s
->code
) == BPF_TAX
? X_ATOM
: A_ATOM
;
420 * Compute the sets of registers used, defined, and killed by 'b'.
422 * "Used" means that a statement in 'b' uses the register before any
423 * statement in 'b' defines it, i.e. it uses the value left in
424 * that register by a predecessor block of this block.
425 * "Defined" means that a statement in 'b' defines it.
426 * "Killed" means that a statement in 'b' defines it before any
427 * statement in 'b' uses it, i.e. it kills the value left in that
428 * register by a predecessor block of this block.
431 compute_local_ud(struct block
*b
)
434 atomset def
= 0, use
= 0, kill
= 0;
437 for (s
= b
->stmts
; s
; s
= s
->next
) {
438 if (s
->s
.code
== NOP
)
440 atom
= atomuse(&s
->s
);
442 if (atom
== AX_ATOM
) {
443 if (!ATOMELEM(def
, X_ATOM
))
444 use
|= ATOMMASK(X_ATOM
);
445 if (!ATOMELEM(def
, A_ATOM
))
446 use
|= ATOMMASK(A_ATOM
);
448 else if (atom
< N_ATOMS
) {
449 if (!ATOMELEM(def
, atom
))
450 use
|= ATOMMASK(atom
);
455 atom
= atomdef(&s
->s
);
457 if (!ATOMELEM(use
, atom
))
458 kill
|= ATOMMASK(atom
);
459 def
|= ATOMMASK(atom
);
462 if (BPF_CLASS(b
->s
.code
) == BPF_JMP
) {
464 * XXX - what about RET?
466 atom
= atomuse(&b
->s
);
468 if (atom
== AX_ATOM
) {
469 if (!ATOMELEM(def
, X_ATOM
))
470 use
|= ATOMMASK(X_ATOM
);
471 if (!ATOMELEM(def
, A_ATOM
))
472 use
|= ATOMMASK(A_ATOM
);
474 else if (atom
< N_ATOMS
) {
475 if (!ATOMELEM(def
, atom
))
476 use
|= ATOMMASK(atom
);
489 * Assume graph is already leveled.
492 find_ud(struct block
*root
)
498 * root->level is the highest level no found;
499 * count down from there.
501 maxlevel
= root
->level
;
502 for (i
= maxlevel
; i
>= 0; --i
)
503 for (p
= levels
[i
]; p
; p
= p
->link
) {
508 for (i
= 1; i
<= maxlevel
; ++i
) {
509 for (p
= levels
[i
]; p
; p
= p
->link
) {
510 p
->out_use
|= JT(p
)->in_use
| JF(p
)->in_use
;
511 p
->in_use
|= p
->out_use
&~ p
->kill
;
517 * These data structures are used in a Cocke and Shwarz style
518 * value numbering scheme. Since the flowgraph is acyclic,
519 * exit values can be propagated from a node's predecessors
520 * provided it is uniquely defined.
526 struct valnode
*next
;
530 static struct valnode
*hashtbl
[MODULUS
];
534 /* Integer constants mapped with the load immediate opcode. */
535 #define K(i) F(BPF_LD|BPF_IMM|BPF_W, i, 0L)
542 struct vmapinfo
*vmap
;
543 struct valnode
*vnode_base
;
544 struct valnode
*next_vnode
;
550 next_vnode
= vnode_base
;
551 memset((char *)vmap
, 0, maxval
* sizeof(*vmap
));
552 memset((char *)hashtbl
, 0, sizeof hashtbl
);
555 /* Because we really don't have an IR, this stuff is a little messy. */
557 F(int code
, int v0
, int v1
)
563 hash
= (u_int
)code
^ (v0
<< 4) ^ (v1
<< 8);
566 for (p
= hashtbl
[hash
]; p
; p
= p
->next
)
567 if (p
->code
== code
&& p
->v0
== v0
&& p
->v1
== v1
)
571 if (BPF_MODE(code
) == BPF_IMM
&&
572 (BPF_CLASS(code
) == BPF_LD
|| BPF_CLASS(code
) == BPF_LDX
)) {
573 vmap
[val
].const_val
= v0
;
574 vmap
[val
].is_const
= 1;
581 p
->next
= hashtbl
[hash
];
588 vstore(struct stmt
*s
, int *valp
, int newval
, int alter
)
590 if (alter
&& *valp
== newval
)
597 * Do constant-folding on binary operators.
598 * (Unary operators are handled elsewhere.)
601 fold_op(struct stmt
*s
, int v0
, int v1
)
605 a
= vmap
[v0
].const_val
;
606 b
= vmap
[v1
].const_val
;
608 switch (BPF_OP(s
->code
)) {
623 bpf_error("division by zero");
629 bpf_error("modulus by zero");
657 s
->code
= BPF_LD
|BPF_IMM
;
661 static inline struct slist
*
662 this_op(struct slist
*s
)
664 while (s
!= 0 && s
->s
.code
== NOP
)
670 opt_not(struct block
*b
)
672 struct block
*tmp
= JT(b
);
679 opt_peep(struct block
*b
)
682 struct slist
*next
, *last
;
690 for (/*empty*/; /*empty*/; s
= next
) {
696 break; /* nothing left in the block */
699 * Find the next real instruction after that one
702 next
= this_op(s
->next
);
704 break; /* no next instruction */
708 * st M[k] --> st M[k]
711 if (s
->s
.code
== BPF_ST
&&
712 next
->s
.code
== (BPF_LDX
|BPF_MEM
) &&
713 s
->s
.k
== next
->s
.k
) {
715 next
->s
.code
= BPF_MISC
|BPF_TAX
;
721 if (s
->s
.code
== (BPF_LD
|BPF_IMM
) &&
722 next
->s
.code
== (BPF_MISC
|BPF_TAX
)) {
723 s
->s
.code
= BPF_LDX
|BPF_IMM
;
724 next
->s
.code
= BPF_MISC
|BPF_TXA
;
728 * This is an ugly special case, but it happens
729 * when you say tcp[k] or udp[k] where k is a constant.
731 if (s
->s
.code
== (BPF_LD
|BPF_IMM
)) {
732 struct slist
*add
, *tax
, *ild
;
735 * Check that X isn't used on exit from this
736 * block (which the optimizer might cause).
737 * We know the code generator won't generate
738 * any local dependencies.
740 if (ATOMELEM(b
->out_use
, X_ATOM
))
744 * Check that the instruction following the ldi
745 * is an addx, or it's an ldxms with an addx
746 * following it (with 0 or more nops between the
749 if (next
->s
.code
!= (BPF_LDX
|BPF_MSH
|BPF_B
))
752 add
= this_op(next
->next
);
753 if (add
== 0 || add
->s
.code
!= (BPF_ALU
|BPF_ADD
|BPF_X
))
757 * Check that a tax follows that (with 0 or more
758 * nops between them).
760 tax
= this_op(add
->next
);
761 if (tax
== 0 || tax
->s
.code
!= (BPF_MISC
|BPF_TAX
))
765 * Check that an ild follows that (with 0 or more
766 * nops between them).
768 ild
= this_op(tax
->next
);
769 if (ild
== 0 || BPF_CLASS(ild
->s
.code
) != BPF_LD
||
770 BPF_MODE(ild
->s
.code
) != BPF_IND
)
773 * We want to turn this sequence:
776 * (005) ldxms [14] {next} -- optional
779 * (008) ild [x+0] {ild}
781 * into this sequence:
789 * XXX We need to check that X is not
790 * subsequently used, because we want to change
791 * what'll be in it after this sequence.
793 * We know we can eliminate the accumulator
794 * modifications earlier in the sequence since
795 * it is defined by the last stmt of this sequence
796 * (i.e., the last statement of the sequence loads
797 * a value into the accumulator, so we can eliminate
798 * earlier operations on the accumulator).
808 * If the comparison at the end of a block is an equality
809 * comparison against a constant, and nobody uses the value
810 * we leave in the A register at the end of a block, and
811 * the operation preceding the comparison is an arithmetic
812 * operation, we can sometime optimize it away.
814 if (b
->s
.code
== (BPF_JMP
|BPF_JEQ
|BPF_K
) &&
815 !ATOMELEM(b
->out_use
, A_ATOM
)) {
817 * We can optimize away certain subtractions of the
820 if (last
->s
.code
== (BPF_ALU
|BPF_SUB
|BPF_X
)) {
821 val
= b
->val
[X_ATOM
];
822 if (vmap
[val
].is_const
) {
824 * If we have a subtract to do a comparison,
825 * and the X register is a known constant,
826 * we can merge this value into the
832 b
->s
.k
+= vmap
[val
].const_val
;
835 } else if (b
->s
.k
== 0) {
837 * If the X register isn't a constant,
838 * and the comparison in the test is
839 * against 0, we can compare with the
840 * X register, instead:
846 b
->s
.code
= BPF_JMP
|BPF_JEQ
|BPF_X
;
851 * Likewise, a constant subtract can be simplified:
854 * jeq #y -> jeq #(x+y)
856 else if (last
->s
.code
== (BPF_ALU
|BPF_SUB
|BPF_K
)) {
862 * And, similarly, a constant AND can be simplified
863 * if we're testing against 0, i.e.:
868 else if (last
->s
.code
== (BPF_ALU
|BPF_AND
|BPF_K
) &&
871 b
->s
.code
= BPF_JMP
|BPF_K
|BPF_JSET
;
879 * jset #ffffffff -> always
881 if (b
->s
.code
== (BPF_JMP
|BPF_K
|BPF_JSET
)) {
884 if (b
->s
.k
== 0xffffffff)
888 * If we're comparing against the index register, and the index
889 * register is a known constant, we can just compare against that
892 val
= b
->val
[X_ATOM
];
893 if (vmap
[val
].is_const
&& BPF_SRC(b
->s
.code
) == BPF_X
) {
894 bpf_int32 v
= vmap
[val
].const_val
;
899 * If the accumulator is a known constant, we can compute the
902 val
= b
->val
[A_ATOM
];
903 if (vmap
[val
].is_const
&& BPF_SRC(b
->s
.code
) == BPF_K
) {
904 bpf_int32 v
= vmap
[val
].const_val
;
905 switch (BPF_OP(b
->s
.code
)) {
912 v
= (unsigned)v
> b
->s
.k
;
916 v
= (unsigned)v
>= b
->s
.k
;
936 * Compute the symbolic value of expression of 's', and update
937 * anything it defines in the value table 'val'. If 'alter' is true,
938 * do various optimizations. This code would be cleaner if symbolic
939 * evaluation and code transformations weren't folded together.
942 opt_stmt(struct stmt
*s
, int val
[], int alter
)
949 case BPF_LD
|BPF_ABS
|BPF_W
:
950 case BPF_LD
|BPF_ABS
|BPF_H
:
951 case BPF_LD
|BPF_ABS
|BPF_B
:
952 v
= F(s
->code
, s
->k
, 0L);
953 vstore(s
, &val
[A_ATOM
], v
, alter
);
956 case BPF_LD
|BPF_IND
|BPF_W
:
957 case BPF_LD
|BPF_IND
|BPF_H
:
958 case BPF_LD
|BPF_IND
|BPF_B
:
960 if (alter
&& vmap
[v
].is_const
) {
961 s
->code
= BPF_LD
|BPF_ABS
|BPF_SIZE(s
->code
);
962 s
->k
+= vmap
[v
].const_val
;
963 v
= F(s
->code
, s
->k
, 0L);
967 v
= F(s
->code
, s
->k
, v
);
968 vstore(s
, &val
[A_ATOM
], v
, alter
);
972 v
= F(s
->code
, 0L, 0L);
973 vstore(s
, &val
[A_ATOM
], v
, alter
);
978 vstore(s
, &val
[A_ATOM
], v
, alter
);
981 case BPF_LDX
|BPF_IMM
:
983 vstore(s
, &val
[X_ATOM
], v
, alter
);
986 case BPF_LDX
|BPF_MSH
|BPF_B
:
987 v
= F(s
->code
, s
->k
, 0L);
988 vstore(s
, &val
[X_ATOM
], v
, alter
);
991 case BPF_ALU
|BPF_NEG
:
992 if (alter
&& vmap
[val
[A_ATOM
]].is_const
) {
993 s
->code
= BPF_LD
|BPF_IMM
;
994 s
->k
= -vmap
[val
[A_ATOM
]].const_val
;
995 val
[A_ATOM
] = K(s
->k
);
998 val
[A_ATOM
] = F(s
->code
, val
[A_ATOM
], 0L);
1001 case BPF_ALU
|BPF_ADD
|BPF_K
:
1002 case BPF_ALU
|BPF_SUB
|BPF_K
:
1003 case BPF_ALU
|BPF_MUL
|BPF_K
:
1004 case BPF_ALU
|BPF_DIV
|BPF_K
:
1005 case BPF_ALU
|BPF_MOD
|BPF_K
:
1006 case BPF_ALU
|BPF_AND
|BPF_K
:
1007 case BPF_ALU
|BPF_OR
|BPF_K
:
1008 case BPF_ALU
|BPF_XOR
|BPF_K
:
1009 case BPF_ALU
|BPF_LSH
|BPF_K
:
1010 case BPF_ALU
|BPF_RSH
|BPF_K
:
1011 op
= BPF_OP(s
->code
);
1014 /* don't optimize away "sub #0"
1015 * as it may be needed later to
1016 * fixup the generated math code */
1017 if (op
== BPF_ADD
||
1018 op
== BPF_LSH
|| op
== BPF_RSH
||
1019 op
== BPF_OR
|| op
== BPF_XOR
) {
1023 if (op
== BPF_MUL
|| op
== BPF_AND
) {
1024 s
->code
= BPF_LD
|BPF_IMM
;
1025 val
[A_ATOM
] = K(s
->k
);
1029 if (vmap
[val
[A_ATOM
]].is_const
) {
1030 fold_op(s
, val
[A_ATOM
], K(s
->k
));
1031 val
[A_ATOM
] = K(s
->k
);
1035 val
[A_ATOM
] = F(s
->code
, val
[A_ATOM
], K(s
->k
));
1038 case BPF_ALU
|BPF_ADD
|BPF_X
:
1039 case BPF_ALU
|BPF_SUB
|BPF_X
:
1040 case BPF_ALU
|BPF_MUL
|BPF_X
:
1041 case BPF_ALU
|BPF_DIV
|BPF_X
:
1042 case BPF_ALU
|BPF_MOD
|BPF_X
:
1043 case BPF_ALU
|BPF_AND
|BPF_X
:
1044 case BPF_ALU
|BPF_OR
|BPF_X
:
1045 case BPF_ALU
|BPF_XOR
|BPF_X
:
1046 case BPF_ALU
|BPF_LSH
|BPF_X
:
1047 case BPF_ALU
|BPF_RSH
|BPF_X
:
1048 op
= BPF_OP(s
->code
);
1049 if (alter
&& vmap
[val
[X_ATOM
]].is_const
) {
1050 if (vmap
[val
[A_ATOM
]].is_const
) {
1051 fold_op(s
, val
[A_ATOM
], val
[X_ATOM
]);
1052 val
[A_ATOM
] = K(s
->k
);
1055 s
->code
= BPF_ALU
|BPF_K
|op
;
1056 s
->k
= vmap
[val
[X_ATOM
]].const_val
;
1059 F(s
->code
, val
[A_ATOM
], K(s
->k
));
1064 * Check if we're doing something to an accumulator
1065 * that is 0, and simplify. This may not seem like
1066 * much of a simplification but it could open up further
1068 * XXX We could also check for mul by 1, etc.
1070 if (alter
&& vmap
[val
[A_ATOM
]].is_const
1071 && vmap
[val
[A_ATOM
]].const_val
== 0) {
1072 if (op
== BPF_ADD
|| op
== BPF_OR
|| op
== BPF_XOR
) {
1073 s
->code
= BPF_MISC
|BPF_TXA
;
1074 vstore(s
, &val
[A_ATOM
], val
[X_ATOM
], alter
);
1077 else if (op
== BPF_MUL
|| op
== BPF_DIV
|| op
== BPF_MOD
||
1078 op
== BPF_AND
|| op
== BPF_LSH
|| op
== BPF_RSH
) {
1079 s
->code
= BPF_LD
|BPF_IMM
;
1081 vstore(s
, &val
[A_ATOM
], K(s
->k
), alter
);
1084 else if (op
== BPF_NEG
) {
1089 val
[A_ATOM
] = F(s
->code
, val
[A_ATOM
], val
[X_ATOM
]);
1092 case BPF_MISC
|BPF_TXA
:
1093 vstore(s
, &val
[A_ATOM
], val
[X_ATOM
], alter
);
1096 case BPF_LD
|BPF_MEM
:
1098 if (alter
&& vmap
[v
].is_const
) {
1099 s
->code
= BPF_LD
|BPF_IMM
;
1100 s
->k
= vmap
[v
].const_val
;
1103 vstore(s
, &val
[A_ATOM
], v
, alter
);
1106 case BPF_MISC
|BPF_TAX
:
1107 vstore(s
, &val
[X_ATOM
], val
[A_ATOM
], alter
);
1110 case BPF_LDX
|BPF_MEM
:
1112 if (alter
&& vmap
[v
].is_const
) {
1113 s
->code
= BPF_LDX
|BPF_IMM
;
1114 s
->k
= vmap
[v
].const_val
;
1117 vstore(s
, &val
[X_ATOM
], v
, alter
);
1121 vstore(s
, &val
[s
->k
], val
[A_ATOM
], alter
);
1125 vstore(s
, &val
[s
->k
], val
[X_ATOM
], alter
);
1131 deadstmt(register struct stmt
*s
, register struct stmt
*last
[])
1137 if (atom
== AX_ATOM
) {
1148 last
[atom
]->code
= NOP
;
1155 opt_deadstores(register struct block
*b
)
1157 register struct slist
*s
;
1159 struct stmt
*last
[N_ATOMS
];
1161 memset((char *)last
, 0, sizeof last
);
1163 for (s
= b
->stmts
; s
!= 0; s
= s
->next
)
1164 deadstmt(&s
->s
, last
);
1165 deadstmt(&b
->s
, last
);
1167 for (atom
= 0; atom
< N_ATOMS
; ++atom
)
1168 if (last
[atom
] && !ATOMELEM(b
->out_use
, atom
)) {
1169 last
[atom
]->code
= NOP
;
1175 opt_blk(struct block
*b
, int do_stmts
)
1180 bpf_int32 aval
, xval
;
1183 for (s
= b
->stmts
; s
&& s
->next
; s
= s
->next
)
1184 if (BPF_CLASS(s
->s
.code
) == BPF_JMP
) {
1191 * Initialize the atom values.
1196 * We have no predecessors, so everything is undefined
1197 * upon entry to this block.
1199 memset((char *)b
->val
, 0, sizeof(b
->val
));
1202 * Inherit values from our predecessors.
1204 * First, get the values from the predecessor along the
1205 * first edge leading to this node.
1207 memcpy((char *)b
->val
, (char *)p
->pred
->val
, sizeof(b
->val
));
1209 * Now look at all the other nodes leading to this node.
1210 * If, for the predecessor along that edge, a register
1211 * has a different value from the one we have (i.e.,
1212 * control paths are merging, and the merging paths
1213 * assign different values to that register), give the
1214 * register the undefined value of 0.
1216 while ((p
= p
->next
) != NULL
) {
1217 for (i
= 0; i
< N_ATOMS
; ++i
)
1218 if (b
->val
[i
] != p
->pred
->val
[i
])
1222 aval
= b
->val
[A_ATOM
];
1223 xval
= b
->val
[X_ATOM
];
1224 for (s
= b
->stmts
; s
; s
= s
->next
)
1225 opt_stmt(&s
->s
, b
->val
, do_stmts
);
1228 * This is a special case: if we don't use anything from this
1229 * block, and we load the accumulator or index register with a
1230 * value that is already there, or if this block is a return,
1231 * eliminate all the statements.
1233 * XXX - what if it does a store?
1235 * XXX - why does it matter whether we use anything from this
1236 * block? If the accumulator or index register doesn't change
1237 * its value, isn't that OK even if we use that value?
1239 * XXX - if we load the accumulator with a different value,
1240 * and the block ends with a conditional branch, we obviously
1241 * can't eliminate it, as the branch depends on that value.
1242 * For the index register, the conditional branch only depends
1243 * on the index register value if the test is against the index
1244 * register value rather than a constant; if nothing uses the
1245 * value we put into the index register, and we're not testing
1246 * against the index register's value, and there aren't any
1247 * other problems that would keep us from eliminating this
1248 * block, can we eliminate it?
1251 ((b
->out_use
== 0 && aval
!= 0 && b
->val
[A_ATOM
] == aval
&&
1252 xval
!= 0 && b
->val
[X_ATOM
] == xval
) ||
1253 BPF_CLASS(b
->s
.code
) == BPF_RET
)) {
1254 if (b
->stmts
!= 0) {
1263 * Set up values for branch optimizer.
1265 if (BPF_SRC(b
->s
.code
) == BPF_K
)
1266 b
->oval
= K(b
->s
.k
);
1268 b
->oval
= b
->val
[X_ATOM
];
1269 b
->et
.code
= b
->s
.code
;
1270 b
->ef
.code
= -b
->s
.code
;
1274 * Return true if any register that is used on exit from 'succ', has
1275 * an exit value that is different from the corresponding exit value
1279 use_conflict(struct block
*b
, struct block
*succ
)
1282 atomset use
= succ
->out_use
;
1287 for (atom
= 0; atom
< N_ATOMS
; ++atom
)
1288 if (ATOMELEM(use
, atom
))
1289 if (b
->val
[atom
] != succ
->val
[atom
])
1294 static struct block
*
1295 fold_edge(struct block
*child
, struct edge
*ep
)
1298 int aval0
, aval1
, oval0
, oval1
;
1299 int code
= ep
->code
;
1307 if (child
->s
.code
!= code
)
1310 aval0
= child
->val
[A_ATOM
];
1311 oval0
= child
->oval
;
1312 aval1
= ep
->pred
->val
[A_ATOM
];
1313 oval1
= ep
->pred
->oval
;
1320 * The operands of the branch instructions are
1321 * identical, so the result is true if a true
1322 * branch was taken to get here, otherwise false.
1324 return sense
? JT(child
) : JF(child
);
1326 if (sense
&& code
== (BPF_JMP
|BPF_JEQ
|BPF_K
))
1328 * At this point, we only know the comparison if we
1329 * came down the true branch, and it was an equality
1330 * comparison with a constant.
1332 * I.e., if we came down the true branch, and the branch
1333 * was an equality comparison with a constant, we know the
1334 * accumulator contains that constant. If we came down
1335 * the false branch, or the comparison wasn't with a
1336 * constant, we don't know what was in the accumulator.
1338 * We rely on the fact that distinct constants have distinct
1347 opt_j(struct edge
*ep
)
1350 register struct block
*target
;
1352 if (JT(ep
->succ
) == 0)
1355 if (JT(ep
->succ
) == JF(ep
->succ
)) {
1357 * Common branch targets can be eliminated, provided
1358 * there is no data dependency.
1360 if (!use_conflict(ep
->pred
, ep
->succ
->et
.succ
)) {
1362 ep
->succ
= JT(ep
->succ
);
1366 * For each edge dominator that matches the successor of this
1367 * edge, promote the edge successor to the its grandchild.
1369 * XXX We violate the set abstraction here in favor a reasonably
1373 for (i
= 0; i
< edgewords
; ++i
) {
1374 register bpf_u_int32 x
= ep
->edom
[i
];
1379 k
+= i
* BITS_PER_WORD
;
1381 target
= fold_edge(ep
->succ
, edges
[k
]);
1383 * Check that there is no data dependency between
1384 * nodes that will be violated if we move the edge.
1386 if (target
!= 0 && !use_conflict(ep
->pred
, target
)) {
1389 if (JT(target
) != 0)
1391 * Start over unless we hit a leaf.
1402 or_pullup(struct block
*b
)
1406 struct block
**diffp
, **samep
;
1414 * Make sure each predecessor loads the same value.
1417 val
= ep
->pred
->val
[A_ATOM
];
1418 for (ep
= ep
->next
; ep
!= 0; ep
= ep
->next
)
1419 if (val
!= ep
->pred
->val
[A_ATOM
])
1422 if (JT(b
->in_edges
->pred
) == b
)
1423 diffp
= &JT(b
->in_edges
->pred
);
1425 diffp
= &JF(b
->in_edges
->pred
);
1432 if (JT(*diffp
) != JT(b
))
1435 if (!SET_MEMBER((*diffp
)->dom
, b
->id
))
1438 if ((*diffp
)->val
[A_ATOM
] != val
)
1441 diffp
= &JF(*diffp
);
1444 samep
= &JF(*diffp
);
1449 if (JT(*samep
) != JT(b
))
1452 if (!SET_MEMBER((*samep
)->dom
, b
->id
))
1455 if ((*samep
)->val
[A_ATOM
] == val
)
1458 /* XXX Need to check that there are no data dependencies
1459 between dp0 and dp1. Currently, the code generator
1460 will not produce such dependencies. */
1461 samep
= &JF(*samep
);
1464 /* XXX This doesn't cover everything. */
1465 for (i
= 0; i
< N_ATOMS
; ++i
)
1466 if ((*samep
)->val
[i
] != pred
->val
[i
])
1469 /* Pull up the node. */
1475 * At the top of the chain, each predecessor needs to point at the
1476 * pulled up node. Inside the chain, there is only one predecessor
1480 for (ep
= b
->in_edges
; ep
!= 0; ep
= ep
->next
) {
1481 if (JT(ep
->pred
) == b
)
1482 JT(ep
->pred
) = pull
;
1484 JF(ep
->pred
) = pull
;
1494 and_pullup(struct block
*b
)
1498 struct block
**diffp
, **samep
;
1506 * Make sure each predecessor loads the same value.
1508 val
= ep
->pred
->val
[A_ATOM
];
1509 for (ep
= ep
->next
; ep
!= 0; ep
= ep
->next
)
1510 if (val
!= ep
->pred
->val
[A_ATOM
])
1513 if (JT(b
->in_edges
->pred
) == b
)
1514 diffp
= &JT(b
->in_edges
->pred
);
1516 diffp
= &JF(b
->in_edges
->pred
);
1523 if (JF(*diffp
) != JF(b
))
1526 if (!SET_MEMBER((*diffp
)->dom
, b
->id
))
1529 if ((*diffp
)->val
[A_ATOM
] != val
)
1532 diffp
= &JT(*diffp
);
1535 samep
= &JT(*diffp
);
1540 if (JF(*samep
) != JF(b
))
1543 if (!SET_MEMBER((*samep
)->dom
, b
->id
))
1546 if ((*samep
)->val
[A_ATOM
] == val
)
1549 /* XXX Need to check that there are no data dependencies
1550 between diffp and samep. Currently, the code generator
1551 will not produce such dependencies. */
1552 samep
= &JT(*samep
);
1555 /* XXX This doesn't cover everything. */
1556 for (i
= 0; i
< N_ATOMS
; ++i
)
1557 if ((*samep
)->val
[i
] != pred
->val
[i
])
1560 /* Pull up the node. */
1566 * At the top of the chain, each predecessor needs to point at the
1567 * pulled up node. Inside the chain, there is only one predecessor
1571 for (ep
= b
->in_edges
; ep
!= 0; ep
= ep
->next
) {
1572 if (JT(ep
->pred
) == b
)
1573 JT(ep
->pred
) = pull
;
1575 JF(ep
->pred
) = pull
;
1585 opt_blks(struct block
*root
, int do_stmts
)
1591 maxlevel
= root
->level
;
1594 for (i
= maxlevel
; i
>= 0; --i
)
1595 for (p
= levels
[i
]; p
; p
= p
->link
)
1596 opt_blk(p
, do_stmts
);
1600 * No point trying to move branches; it can't possibly
1601 * make a difference at this point.
1605 for (i
= 1; i
<= maxlevel
; ++i
) {
1606 for (p
= levels
[i
]; p
; p
= p
->link
) {
1613 for (i
= 1; i
<= maxlevel
; ++i
) {
1614 for (p
= levels
[i
]; p
; p
= p
->link
) {
1622 link_inedge(struct edge
*parent
, struct block
*child
)
1624 parent
->next
= child
->in_edges
;
1625 child
->in_edges
= parent
;
1629 find_inedges(struct block
*root
)
1634 for (i
= 0; i
< n_blocks
; ++i
)
1635 blocks
[i
]->in_edges
= 0;
1638 * Traverse the graph, adding each edge to the predecessor
1639 * list of its successors. Skip the leaves (i.e. level 0).
1641 for (i
= root
->level
; i
> 0; --i
) {
1642 for (b
= levels
[i
]; b
!= 0; b
= b
->link
) {
1643 link_inedge(&b
->et
, JT(b
));
1644 link_inedge(&b
->ef
, JF(b
));
1650 opt_root(struct block
**b
)
1652 struct slist
*tmp
, *s
;
1656 while (BPF_CLASS((*b
)->s
.code
) == BPF_JMP
&& JT(*b
) == JF(*b
))
1665 * If the root node is a return, then there is no
1666 * point executing any statements (since the bpf machine
1667 * has no side effects).
1669 if (BPF_CLASS((*b
)->s
.code
) == BPF_RET
)
1674 opt_loop(struct block
*root
, int do_stmts
)
1678 if (pcap_optimizer_debug
> 1) {
1679 printf("opt_loop(root, %d) begin\n", do_stmts
);
1690 opt_blks(root
, do_stmts
);
1692 if (pcap_optimizer_debug
> 1) {
1693 printf("opt_loop(root, %d) bottom, done=%d\n", do_stmts
, done
);
1701 * Optimize the filter code in its dag representation.
1704 bpf_optimize(struct block
**rootp
)
1713 intern_blocks(root
);
1715 if (pcap_optimizer_debug
> 1) {
1716 printf("after intern_blocks()\n");
1722 if (pcap_optimizer_debug
> 1) {
1723 printf("after opt_root()\n");
1731 make_marks(struct block
*p
)
1735 if (BPF_CLASS(p
->s
.code
) != BPF_RET
) {
1743 * Mark code array such that isMarked(i) is true
1744 * only for nodes that are alive.
1747 mark_code(struct block
*p
)
1754 * True iff the two stmt lists load the same value from the packet into
1758 eq_slist(struct slist
*x
, struct slist
*y
)
1761 while (x
&& x
->s
.code
== NOP
)
1763 while (y
&& y
->s
.code
== NOP
)
1769 if (x
->s
.code
!= y
->s
.code
|| x
->s
.k
!= y
->s
.k
)
1777 eq_blk(struct block
*b0
, struct block
*b1
)
1779 if (b0
->s
.code
== b1
->s
.code
&&
1780 b0
->s
.k
== b1
->s
.k
&&
1781 b0
->et
.succ
== b1
->et
.succ
&&
1782 b0
->ef
.succ
== b1
->ef
.succ
)
1783 return eq_slist(b0
->stmts
, b1
->stmts
);
1788 intern_blocks(struct block
*root
)
1792 int done1
; /* don't shadow global */
1795 for (i
= 0; i
< n_blocks
; ++i
)
1796 blocks
[i
]->link
= 0;
1800 for (i
= n_blocks
- 1; --i
>= 0; ) {
1801 if (!isMarked(blocks
[i
]))
1803 for (j
= i
+ 1; j
< n_blocks
; ++j
) {
1804 if (!isMarked(blocks
[j
]))
1806 if (eq_blk(blocks
[i
], blocks
[j
])) {
1807 blocks
[i
]->link
= blocks
[j
]->link
?
1808 blocks
[j
]->link
: blocks
[j
];
1813 for (i
= 0; i
< n_blocks
; ++i
) {
1819 JT(p
) = JT(p
)->link
;
1823 JF(p
) = JF(p
)->link
;
1833 free((void *)vnode_base
);
1835 free((void *)edges
);
1836 free((void *)space
);
1837 free((void *)levels
);
1838 free((void *)blocks
);
1842 * Return the number of stmts in 's'.
1845 slength(struct slist
*s
)
1849 for (; s
; s
= s
->next
)
1850 if (s
->s
.code
!= NOP
)
1856 * Return the number of nodes reachable by 'p'.
1857 * All nodes should be initially unmarked.
1860 count_blocks(struct block
*p
)
1862 if (p
== 0 || isMarked(p
))
1865 return count_blocks(JT(p
)) + count_blocks(JF(p
)) + 1;
1869 * Do a depth first search on the flow graph, numbering the
1870 * the basic blocks, and entering them into the 'blocks' array.`
1873 number_blks_r(struct block
*p
)
1877 if (p
== 0 || isMarked(p
))
1885 number_blks_r(JT(p
));
1886 number_blks_r(JF(p
));
1890 * Return the number of stmts in the flowgraph reachable by 'p'.
1891 * The nodes should be unmarked before calling.
1893 * Note that "stmts" means "instructions", and that this includes
1895 * side-effect statements in 'p' (slength(p->stmts));
1897 * statements in the true branch from 'p' (count_stmts(JT(p)));
1899 * statements in the false branch from 'p' (count_stmts(JF(p)));
1901 * the conditional jump itself (1);
1903 * an extra long jump if the true branch requires it (p->longjt);
1905 * an extra long jump if the false branch requires it (p->longjf).
1908 count_stmts(struct block
*p
)
1912 if (p
== 0 || isMarked(p
))
1915 n
= count_stmts(JT(p
)) + count_stmts(JF(p
));
1916 return slength(p
->stmts
) + n
+ 1 + p
->longjt
+ p
->longjf
;
1920 * Allocate memory. All allocation is done before optimization
1921 * is begun. A linear bound on the size of all data structures is computed
1922 * from the total number of blocks and/or statements.
1925 opt_init(struct block
*root
)
1928 int i
, n
, max_stmts
;
1931 * First, count the blocks, so we can malloc an array to map
1932 * block number to block. Then, put the blocks into the array.
1935 n
= count_blocks(root
);
1936 blocks
= (struct block
**)calloc(n
, sizeof(*blocks
));
1938 bpf_error("malloc");
1941 number_blks_r(root
);
1943 n_edges
= 2 * n_blocks
;
1944 edges
= (struct edge
**)calloc(n_edges
, sizeof(*edges
));
1946 bpf_error("malloc");
1949 * The number of levels is bounded by the number of nodes.
1951 levels
= (struct block
**)calloc(n_blocks
, sizeof(*levels
));
1953 bpf_error("malloc");
1955 edgewords
= n_edges
/ (8 * sizeof(bpf_u_int32
)) + 1;
1956 nodewords
= n_blocks
/ (8 * sizeof(bpf_u_int32
)) + 1;
1959 space
= (bpf_u_int32
*)malloc(2 * n_blocks
* nodewords
* sizeof(*space
)
1960 + n_edges
* edgewords
* sizeof(*space
));
1962 bpf_error("malloc");
1965 for (i
= 0; i
< n
; ++i
) {
1969 all_closure_sets
= p
;
1970 for (i
= 0; i
< n
; ++i
) {
1971 blocks
[i
]->closure
= p
;
1975 for (i
= 0; i
< n
; ++i
) {
1976 register struct block
*b
= blocks
[i
];
1984 b
->ef
.id
= n_blocks
+ i
;
1985 edges
[n_blocks
+ i
] = &b
->ef
;
1990 for (i
= 0; i
< n
; ++i
)
1991 max_stmts
+= slength(blocks
[i
]->stmts
) + 1;
1993 * We allocate at most 3 value numbers per statement,
1994 * so this is an upper bound on the number of valnodes
1997 maxval
= 3 * max_stmts
;
1998 vmap
= (struct vmapinfo
*)calloc(maxval
, sizeof(*vmap
));
1999 vnode_base
= (struct valnode
*)calloc(maxval
, sizeof(*vnode_base
));
2000 if (vmap
== NULL
|| vnode_base
== NULL
)
2001 bpf_error("malloc");
2005 * Some pointers used to convert the basic block form of the code,
2006 * into the array form that BPF requires. 'fstart' will point to
2007 * the malloc'd array while 'ftail' is used during the recursive traversal.
2009 static struct bpf_insn
*fstart
;
2010 static struct bpf_insn
*ftail
;
2017 * Returns true if successful. Returns false if a branch has
2018 * an offset that is too large. If so, we have marked that
2019 * branch so that on a subsequent iteration, it will be treated
2023 convert_code_r(struct block
*p
)
2025 struct bpf_insn
*dst
;
2029 int extrajmps
; /* number of extra jumps inserted */
2030 struct slist
**offset
= NULL
;
2032 if (p
== 0 || isMarked(p
))
2036 if (convert_code_r(JF(p
)) == 0)
2038 if (convert_code_r(JT(p
)) == 0)
2041 slen
= slength(p
->stmts
);
2042 dst
= ftail
-= (slen
+ 1 + p
->longjt
+ p
->longjf
);
2043 /* inflate length by any extra jumps */
2045 p
->offset
= dst
- fstart
;
2047 /* generate offset[] for convenience */
2049 offset
= (struct slist
**)calloc(slen
, sizeof(struct slist
*));
2051 bpf_error("not enough core");
2056 for (off
= 0; off
< slen
&& src
; off
++) {
2058 printf("off=%d src=%x\n", off
, src
);
2065 for (src
= p
->stmts
; src
; src
= src
->next
) {
2066 if (src
->s
.code
== NOP
)
2068 dst
->code
= (u_short
)src
->s
.code
;
2071 /* fill block-local relative jump */
2072 if (BPF_CLASS(src
->s
.code
) != BPF_JMP
|| src
->s
.code
== (BPF_JMP
|BPF_JA
)) {
2074 if (src
->s
.jt
|| src
->s
.jf
) {
2075 bpf_error("illegal jmp destination");
2081 if (off
== slen
- 2) /*???*/
2087 const char *ljerr
= "%s for block-local relative jump: off=%d";
2090 printf("code=%x off=%d %x %x\n", src
->s
.code
,
2091 off
, src
->s
.jt
, src
->s
.jf
);
2094 if (!src
->s
.jt
|| !src
->s
.jf
) {
2095 bpf_error(ljerr
, "no jmp destination", off
);
2100 for (i
= 0; i
< slen
; i
++) {
2101 if (offset
[i
] == src
->s
.jt
) {
2103 bpf_error(ljerr
, "multiple matches", off
);
2107 dst
->jt
= i
- off
- 1;
2110 if (offset
[i
] == src
->s
.jf
) {
2112 bpf_error(ljerr
, "multiple matches", off
);
2115 dst
->jf
= i
- off
- 1;
2120 bpf_error(ljerr
, "no destination found", off
);
2132 bids
[dst
- fstart
] = p
->id
+ 1;
2134 dst
->code
= (u_short
)p
->s
.code
;
2138 off
= JT(p
)->offset
- (p
->offset
+ slen
) - 1;
2140 /* offset too large for branch, must add a jump */
2141 if (p
->longjt
== 0) {
2142 /* mark this instruction and retry */
2146 /* branch if T to following jump */
2147 dst
->jt
= extrajmps
;
2149 dst
[extrajmps
].code
= BPF_JMP
|BPF_JA
;
2150 dst
[extrajmps
].k
= off
- extrajmps
;
2154 off
= JF(p
)->offset
- (p
->offset
+ slen
) - 1;
2156 /* offset too large for branch, must add a jump */
2157 if (p
->longjf
== 0) {
2158 /* mark this instruction and retry */
2162 /* branch if F to following jump */
2163 /* if two jumps are inserted, F goes to second one */
2164 dst
->jf
= extrajmps
;
2166 dst
[extrajmps
].code
= BPF_JMP
|BPF_JA
;
2167 dst
[extrajmps
].k
= off
- extrajmps
;
2177 * Convert flowgraph intermediate representation to the
2178 * BPF array representation. Set *lenp to the number of instructions.
2180 * This routine does *NOT* leak the memory pointed to by fp. It *must
2181 * not* do free(fp) before returning fp; doing so would make no sense,
2182 * as the BPF array pointed to by the return value of icode_to_fcode()
2183 * must be valid - it's being returned for use in a bpf_program structure.
2185 * If it appears that icode_to_fcode() is leaking, the problem is that
2186 * the program using pcap_compile() is failing to free the memory in
2187 * the BPF program when it's done - the leak is in the program, not in
2188 * the routine that happens to be allocating the memory. (By analogy, if
2189 * a program calls fopen() without ever calling fclose() on the FILE *,
2190 * it will leak the FILE structure; the leak is not in fopen(), it's in
2191 * the program.) Change the program to use pcap_freecode() when it's
2192 * done with the filter program. See the pcap man page.
2195 icode_to_fcode(struct block
*root
, u_int
*lenp
)
2198 struct bpf_insn
*fp
;
2201 * Loop doing convert_code_r() until no branches remain
2202 * with too-large offsets.
2206 n
= *lenp
= count_stmts(root
);
2208 fp
= (struct bpf_insn
*)malloc(sizeof(*fp
) * n
);
2210 bpf_error("malloc");
2211 memset((char *)fp
, 0, sizeof(*fp
) * n
);
2216 if (convert_code_r(root
))
2225 * Make a copy of a BPF program and put it in the "fcode" member of
2228 * If we fail to allocate memory for the copy, fill in the "errbuf"
2229 * member of the "pcap_t" with an error message, and return -1;
2230 * otherwise, return 0.
2233 install_bpf_program(pcap_t
*p
, struct bpf_program
*fp
)
2238 * Validate the program.
2240 if (!bpf_validate(fp
->bf_insns
, fp
->bf_len
)) {
2241 pcap_snprintf(p
->errbuf
, sizeof(p
->errbuf
),
2242 "BPF program is not valid");
2247 * Free up any already installed program.
2249 pcap_freecode(&p
->fcode
);
2251 prog_size
= sizeof(*fp
->bf_insns
) * fp
->bf_len
;
2252 p
->fcode
.bf_len
= fp
->bf_len
;
2253 p
->fcode
.bf_insns
= (struct bpf_insn
*)malloc(prog_size
);
2254 if (p
->fcode
.bf_insns
== NULL
) {
2255 pcap_snprintf(p
->errbuf
, sizeof(p
->errbuf
),
2256 "malloc: %s", pcap_strerror(errno
));
2259 memcpy(p
->fcode
.bf_insns
, fp
->bf_insns
, prog_size
);
2265 dot_dump_node(struct block
*block
, struct bpf_program
*prog
, FILE *out
)
2267 int icount
, noffset
;
2270 if (block
== NULL
|| isMarked(block
))
2274 icount
= slength(block
->stmts
) + 1 + block
->longjt
+ block
->longjf
;
2275 noffset
= min(block
->offset
+ icount
, (int)prog
->bf_len
);
2277 fprintf(out
, "\tblock%d [shape=ellipse, id=\"block-%d\" label=\"BLOCK%d\\n", block
->id
, block
->id
, block
->id
);
2278 for (i
= block
->offset
; i
< noffset
; i
++) {
2279 fprintf(out
, "\\n%s", bpf_image(prog
->bf_insns
+ i
, i
));
2281 fprintf(out
, "\" tooltip=\"");
2282 for (i
= 0; i
< BPF_MEMWORDS
; i
++)
2283 if (block
->val
[i
] != 0)
2284 fprintf(out
, "val[%d]=%d ", i
, block
->val
[i
]);
2285 fprintf(out
, "val[A]=%d ", block
->val
[A_ATOM
]);
2286 fprintf(out
, "val[X]=%d", block
->val
[X_ATOM
]);
2288 if (JT(block
) == NULL
)
2289 fprintf(out
, ", peripheries=2");
2290 fprintf(out
, "];\n");
2292 dot_dump_node(JT(block
), prog
, out
);
2293 dot_dump_node(JF(block
), prog
, out
);
2297 dot_dump_edge(struct block
*block
, FILE *out
)
2299 if (block
== NULL
|| isMarked(block
))
2304 fprintf(out
, "\t\"block%d\":se -> \"block%d\":n [label=\"T\"]; \n",
2305 block
->id
, JT(block
)->id
);
2306 fprintf(out
, "\t\"block%d\":sw -> \"block%d\":n [label=\"F\"]; \n",
2307 block
->id
, JF(block
)->id
);
2309 dot_dump_edge(JT(block
), out
);
2310 dot_dump_edge(JF(block
), out
);
2313 /* Output the block CFG using graphviz/DOT language
2314 * In the CFG, block's code, value index for each registers at EXIT,
2315 * and the jump relationship is show.
2317 * example DOT for BPF `ip src host 1.1.1.1' is:
2319 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"];
2320 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"];
2321 block2 [shape=ellipse, id="block-2" label="BLOCK2\n\n(004) ret #68" tooltip="val[A]=0 val[X]=0", peripheries=2];
2322 block3 [shape=ellipse, id="block-3" label="BLOCK3\n\n(005) ret #0" tooltip="val[A]=0 val[X]=0", peripheries=2];
2323 "block0":se -> "block1":n [label="T"];
2324 "block0":sw -> "block3":n [label="F"];
2325 "block1":se -> "block2":n [label="T"];
2326 "block1":sw -> "block3":n [label="F"];
2329 * After install graphviz on http://www.graphviz.org/, save it as bpf.dot
2330 * and run `dot -Tpng -O bpf.dot' to draw the graph.
2333 dot_dump(struct block
*root
)
2335 struct bpf_program f
;
2338 memset(bids
, 0, sizeof bids
);
2339 f
.bf_insns
= icode_to_fcode(root
, &f
.bf_len
);
2341 fprintf(out
, "digraph BPF {\n");
2343 dot_dump_node(root
, &f
, out
);
2345 dot_dump_edge(root
, out
);
2346 fprintf(out
, "}\n");
2348 free((char *)f
.bf_insns
);
2352 plain_dump(struct block
*root
)
2354 struct bpf_program f
;
2356 memset(bids
, 0, sizeof bids
);
2357 f
.bf_insns
= icode_to_fcode(root
, &f
.bf_len
);
2360 free((char *)f
.bf_insns
);
2364 opt_dump(struct block
*root
)
2366 /* if optimizer debugging is enabled, output DOT graph
2367 * `pcap_optimizer_debug=4' is equivalent to -dddd to follow -d/-dd/-ddd
2368 * convention in tcpdump command line
2370 if (pcap_optimizer_debug
> 3)