Coverage Report

Created: 2026-10-28 06:57

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libpcap/optimize.c
Line
Count
Source
1
/*
2
 * Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994, 1995, 1996
3
 *  The Regents of the University of California.  All rights reserved.
4
 *
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
16
 * written permission.
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.
20
 *
21
 *  Optimization module for BPF code intermediate representation.
22
 */
23
24
#include <config.h>
25
26
#include <pcap-types.h>
27
28
#include <stdio.h>
29
#include <stdlib.h>
30
#include <memory.h>
31
#include <setjmp.h>
32
#include <string.h>
33
#include <limits.h> /* for SIZE_MAX */
34
#include <errno.h>
35
#include <stdbool.h>
36
#include <stdint.h>
37
38
#include "pcap-int.h"
39
40
#include "gencode.h"
41
#include "optimize.h"
42
#include "diag-control.h"
43
#include "no_sanitize.h"
44
45
#ifdef HAVE_OS_PROTO_H
46
#include "os-proto.h"
47
#endif
48
49
#ifdef BDEBUG
50
/*
51
 * The internal "debug printout" flag for the filter expression optimizer.
52
 * The code to print that stuff is present only if BDEBUG is defined, so
53
 * the flag, and the routine to set it, are defined only if BDEBUG is
54
 * defined.
55
 */
56
static int pcap_optimizer_debug;
57
58
/*
59
 * Routine to set that flag.
60
 *
61
 * This is intended for libpcap developers, not for general use.
62
 * If you want to set these in a program, you'll have to declare this
63
 * routine yourself, with the appropriate DLL import attribute on Windows;
64
 * it's not declared in any header file, and won't be declared in any
65
 * header file provided by libpcap.
66
 */
67
PCAP_API void pcap_set_optimizer_debug(int value);
68
69
PCAP_API_DEF void
70
pcap_set_optimizer_debug(int value)
71
{
72
  pcap_optimizer_debug = value;
73
}
74
75
/*
76
 * The internal "print dot graph" flag for the filter expression optimizer.
77
 * The code to print that stuff is present only if BDEBUG is defined, so
78
 * the flag, and the routine to set it, are defined only if BDEBUG is
79
 * defined.
80
 */
81
static int pcap_print_dot_graph;
82
83
/*
84
 * Routine to set that flag.
85
 *
86
 * This is intended for libpcap developers, not for general use.
87
 * If you want to set these in a program, you'll have to declare this
88
 * routine yourself, with the appropriate DLL import attribute on Windows;
89
 * it's not declared in any header file, and won't be declared in any
90
 * header file provided by libpcap.
91
 */
92
PCAP_API void pcap_set_print_dot_graph(int value);
93
94
PCAP_API_DEF void
95
pcap_set_print_dot_graph(int value)
96
{
97
  pcap_print_dot_graph = value;
98
}
99
100
#endif
101
102
/*
103
 * lowest_set_bit().
104
 *
105
 * Takes a 32-bit integer as an argument.
106
 *
107
 * If handed a non-zero value, returns the index of the lowest set bit,
108
 * counting upwards from zero.
109
 *
110
 * If handed zero, the results are platform- and compiler-dependent.
111
 * Keep it out of the light, don't give it any water, don't feed it
112
 * after midnight, and don't pass zero to it.
113
 *
114
 * This is the same as the count of trailing zeroes in the word.
115
 *
116
 * Because lowest_set_bit() is intended to be used as a function, to define
117
 * HAVE_BUILTIN_CTZ it is sufficient to verify that __builtin_ctz() can return
118
 * a value (the builtin does not have to evaluate to a compile-time constant).
119
 */
120
#ifdef HAVE_BUILTIN_CTZ
121
2.42M
  #define lowest_set_bit(mask) ((u_int)__builtin_ctz(mask))
122
#elif defined(_MSC_VER)
123
  /*
124
   * Visual Studio; we support only 2015 and later, so use
125
   * _BitScanForward().
126
   */
127
#include <intrin.h>
128
129
#ifndef __clang__
130
#pragma intrinsic(_BitScanForward)
131
#endif
132
133
static __forceinline u_int
134
lowest_set_bit(int mask)
135
{
136
  unsigned long bit;
137
138
  /*
139
   * Don't sign-extend mask if long is longer than int.
140
   * (It's currently not, in MSVC, even on 64-bit platforms, but....)
141
   */
142
  if (_BitScanForward(&bit, (unsigned int)mask) == 0)
143
    abort();  /* mask is zero */
144
  return (u_int)bit;
145
}
146
#else
147
  /*
148
   * POSIX.1-2001 says ffs() is in <strings.h>.  Every supported non-Windows OS
149
   * (including Linux with musl libc and uclibc-ng) has the header and (except
150
   * HP-UX) declares the function there.  HP-UX declares the function in
151
   * <string.h>, which has already been included.
152
   */
153
  #include <strings.h>
154
  #define lowest_set_bit(mask)  ((u_int)(ffs((mask)) - 1))
155
#endif
156
157
/*
158
 * This is an extern shim to be invoked from translatetest.c because
159
 * lowest_set_bit() can be an inline function (which can be unnecessarily
160
 * complicated to declare extern) or a macro.
161
 */
162
uint32_t
163
pcapint_lowest_set_bit(const uint32_t x)
164
0
{
165
0
  return lowest_set_bit(x);
166
0
}
167
168
/*
169
 * Represents a deleted instruction.
170
 */
171
50.6M
#define NOP -1
172
173
/*
174
 * Register numbers for use-def values.
175
 * 0 through BPF_MEMWORDS-1 represent the corresponding scratch memory
176
 * location.  A_ATOM is the accumulator and X_ATOM is the index
177
 * register.
178
 */
179
16.7M
#define A_ATOM BPF_MEMWORDS
180
2.68M
#define X_ATOM (BPF_MEMWORDS+1)
181
182
/*
183
 * This define is used to represent *both* the accumulator and
184
 * x register in use-def computations.
185
 * Currently, the use-def code assumes only one definition per instruction.
186
 */
187
4.52M
#define AX_ATOM N_ATOMS
188
189
/*
190
 * These data structures are used in a Cocke and Schwartz style
191
 * value numbering scheme.  Since the flowgraph is acyclic,
192
 * exit values can be propagated from a node's predecessors
193
 * provided it is uniquely defined.
194
 */
195
struct valnode {
196
  int code;
197
  bpf_u_int32 v0, v1;
198
  int val;    /* the value number */
199
  struct valnode *next;
200
};
201
202
/* Integer constants mapped with the load immediate opcode. */
203
969k
#define K(i) F(opt_state, BPF_LD|BPF_IMM|BPF_W, i, 0U)
204
205
struct vmapinfo {
206
  int is_const;
207
  bpf_u_int32 const_val;
208
};
209
210
typedef struct {
211
  /*
212
   * Place to longjmp to on an error.
213
   */
214
  jmp_buf top_ctx;
215
216
  /*
217
   * The buffer into which to put error message.
218
   */
219
  char *errbuf;
220
221
  /*
222
   * A flag to indicate that further optimization is needed.
223
   * Iterative passes are continued until a given pass yields no
224
   * code simplification or branch movement.
225
   */
226
  int done;
227
228
  /*
229
   * XXX - detect loops that do nothing but repeated AND/OR pullups
230
   * and edge moves.
231
   * If 100 passes in a row do nothing but that, treat that as a
232
   * sign that we're in a loop that just shuffles in a cycle in
233
   * which each pass just shuffles the code and we eventually
234
   * get back to the original configuration.
235
   *
236
   * XXX - we need a non-heuristic way of detecting, or preventing,
237
   * such a cycle.
238
   */
239
  int non_branch_movement_performed;
240
241
  u_int n_blocks;   /* number of blocks in the CFG; guaranteed to be > 0, as it's a RET instruction at a minimum */
242
  struct block **blocks;
243
  u_int n_edges;    /* twice n_blocks, so guaranteed to be > 0 */
244
  struct edge **edges;
245
246
  /*
247
   * A bit vector set representation of the dominators.
248
   * We round up the set size to the next power of two.
249
   */
250
  u_int nodewords;  /* number of 32-bit words for a bit vector of "number of nodes" bits; guaranteed to be > 0 */
251
  u_int edgewords;  /* number of 32-bit words for a bit vector of "number of edges" bits; guaranteed to be > 0 */
252
  struct block **levels;
253
  bpf_u_int32 *space;
254
255
9.83M
#define BITS_PER_WORD (8*sizeof(bpf_u_int32))
256
/*
257
 * True if a is in uset {p}
258
 */
259
739k
#define SET_MEMBER(p, a) \
260
739k
((p)[(unsigned)(a) / BITS_PER_WORD] & ((bpf_u_int32)1 << ((unsigned)(a) % BITS_PER_WORD)))
261
262
/*
263
 * Add 'a' to uset p.
264
 */
265
2.95M
#define SET_INSERT(p, a) \
266
2.95M
(p)[(unsigned)(a) / BITS_PER_WORD] |= ((bpf_u_int32)1 << ((unsigned)(a) % BITS_PER_WORD))
267
268
/*
269
 * Delete 'a' from uset p.
270
 */
271
#define SET_DELETE(p, a) \
272
(p)[(unsigned)(a) / BITS_PER_WORD] &= ~((bpf_u_int32)1 << ((unsigned)(a) % BITS_PER_WORD))
273
274
/*
275
 * a := a intersect b
276
 * n must be guaranteed to be > 0
277
 */
278
4.03M
#define SET_INTERSECT(a, b, n)\
279
4.03M
{\
280
4.03M
  bpf_u_int32 *_x = a, *_y = b;\
281
4.03M
  u_int _n = n;\
282
46.6M
  do *_x++ &= *_y++; while (--_n != 0);\
283
4.03M
}
284
285
/*
286
 * a := a - b
287
 * n must be guaranteed to be > 0
288
 */
289
#define SET_SUBTRACT(a, b, n)\
290
{\
291
  bpf_u_int32 *_x = a, *_y = b;\
292
  u_int _n = n;\
293
  do *_x++ &=~ *_y++; while (--_n != 0);\
294
}
295
296
/*
297
 * a := a union b
298
 * n must be guaranteed to be > 0
299
 */
300
1.10M
#define SET_UNION(a, b, n)\
301
1.10M
{\
302
1.10M
  bpf_u_int32 *_x = a, *_y = b;\
303
1.10M
  u_int _n = n;\
304
8.80M
  do *_x++ |= *_y++; while (--_n != 0);\
305
1.10M
}
306
307
  uset all_dom_sets;
308
  uset all_closure_sets;
309
  uset all_edge_sets;
310
311
2.34M
#define MODULUS 213
312
  struct valnode *hashtbl[MODULUS];
313
  bpf_u_int32 curval;
314
  bpf_u_int32 maxval;
315
316
  struct vmapinfo *vmap;
317
  struct valnode *vnode_base;
318
  struct valnode *next_vnode;
319
} opt_state_t;
320
321
typedef struct {
322
  /*
323
   * Place to longjmp to on an error.
324
   */
325
  jmp_buf top_ctx;
326
327
  /*
328
   * The buffer into which to put error message.
329
   */
330
  char *errbuf;
331
332
  /*
333
   * Some pointers used to convert the basic block form of the code,
334
   * into the array form that BPF requires.  'fstart' will point to
335
   * the allocated array while 'ftail' is used during the recursive
336
   * traversal.
337
   */
338
  struct bpf_insn *fstart;
339
  struct bpf_insn *ftail;
340
} conv_state_t;
341
342
static void opt_init(opt_state_t *, struct icode *);
343
static void opt_cleanup(opt_state_t *);
344
static void PCAP_NORETURN opt_error(opt_state_t *, const char *, ...)
345
    PCAP_PRINTFLIKE(2, 3);
346
static void PCAP_NORETURN conv_error(conv_state_t *, const char *, ...)
347
    PCAP_PRINTFLIKE(2, 3);
348
349
static void intern_blocks(opt_state_t *, struct icode *);
350
351
static void find_inedges(opt_state_t *, const struct block *);
352
#ifdef BDEBUG
353
static void opt_dump(opt_state_t *, struct icode *);
354
#endif
355
356
static void
357
find_levels_r(opt_state_t *opt_state, struct icode *ic, struct block *b)
358
1.15M
{
359
1.15M
  int level;
360
361
1.15M
  if (isMarked(ic, b))
362
514k
    return;
363
364
642k
  Mark(ic, b);
365
642k
  b->link = 0;
366
367
642k
  if (JT(b)) {
368
552k
    find_levels_r(opt_state, ic, JT(b));
369
552k
    find_levels_r(opt_state, ic, JF(b));
370
552k
    level = max(JT(b)->level, JF(b)->level) + 1;
371
552k
  } else
372
89.2k
    level = 0;
373
642k
  b->level = level;
374
642k
  b->link = opt_state->levels[level];
375
642k
  opt_state->levels[level] = b;
376
642k
}
377
378
/*
379
 * Level graph.  The levels go from 0 at the leaves to
380
 * N_LEVELS at the root.  The opt_state->levels[] array points to the
381
 * first node of the level list, whose elements are linked
382
 * with the 'link' field of the struct block.
383
 */
384
static void
385
find_levels(opt_state_t *opt_state, struct icode *ic)
386
51.1k
{
387
51.1k
  memset((char *)opt_state->levels, 0, opt_state->n_blocks * sizeof(*opt_state->levels));
388
51.1k
  unMarkAll(ic);
389
51.1k
  find_levels_r(opt_state, ic, ic->root);
390
51.1k
}
391
392
/*
393
 * Find dominator relationships.
394
 * Assumes graph has been leveled.
395
 */
396
static void
397
find_dom(opt_state_t *opt_state, struct block *root)
398
64.8k
{
399
64.8k
  u_int i;
400
64.8k
  int level;
401
64.8k
  struct block *b;
402
64.8k
  bpf_u_int32 *x;
403
404
  /*
405
   * Initialize sets to contain all nodes.
406
   */
407
64.8k
  x = opt_state->all_dom_sets;
408
  /*
409
   * In opt_init(), we've made sure the product doesn't overflow.
410
   */
411
64.8k
  i = opt_state->n_blocks * opt_state->nodewords;
412
9.81M
  while (i != 0) {
413
9.74M
    --i;
414
9.74M
    *x++ = 0xFFFFFFFFU;
415
9.74M
  }
416
  /* Root starts off empty. */
417
160k
  for (i = opt_state->nodewords; i != 0;) {
418
95.4k
    --i;
419
95.4k
    root->dom[i] = 0;
420
95.4k
  }
421
422
  /* root->level is the highest level no found. */
423
764k
  for (level = root->level; level >= 0; --level) {
424
1.72M
    for (b = opt_state->levels[level]; b; b = b->link) {
425
1.02M
      SET_INSERT(b->dom, b->id);
426
1.02M
      if (JT(b) == NULL)
427
116k
        continue;
428
912k
      SET_INTERSECT(JT(b)->dom, b->dom, opt_state->nodewords);
429
912k
      SET_INTERSECT(JF(b)->dom, b->dom, opt_state->nodewords);
430
912k
    }
431
699k
  }
432
64.8k
}
433
434
static void
435
propedom(const opt_state_t *opt_state, struct edge *ep)
436
1.28M
{
437
1.28M
  SET_INSERT(ep->edom, ep->id);
438
1.28M
  if (ep->succ) {
439
1.10M
    SET_INTERSECT(ep->succ->et.edom, ep->edom, opt_state->edgewords);
440
1.10M
    SET_INTERSECT(ep->succ->ef.edom, ep->edom, opt_state->edgewords);
441
1.10M
  }
442
1.28M
}
443
444
/*
445
 * Compute edge dominators.
446
 * Assumes graph has been leveled and predecessors established.
447
 */
448
static void
449
find_edom(opt_state_t *opt_state, struct block *root)
450
51.1k
{
451
51.1k
  u_int i;
452
51.1k
  uset x;
453
51.1k
  int level;
454
51.1k
  struct block *b;
455
456
51.1k
  x = opt_state->all_edge_sets;
457
  /*
458
   * In opt_init(), we've made sure the product doesn't overflow.
459
   */
460
22.7M
  for (i = opt_state->n_edges * opt_state->edgewords; i != 0; ) {
461
22.7M
    --i;
462
22.7M
    x[i] = 0xFFFFFFFFU;
463
22.7M
  }
464
465
  /* root->level is the highest level no found. */
466
51.1k
  memset(root->et.edom, 0, opt_state->edgewords * sizeof(*(uset)0));
467
51.1k
  memset(root->ef.edom, 0, opt_state->edgewords * sizeof(*(uset)0));
468
542k
  for (level = root->level; level >= 0; --level) {
469
1.13M
    for (b = opt_state->levels[level]; b != 0; b = b->link) {
470
642k
      propedom(opt_state, &b->et);
471
642k
      propedom(opt_state, &b->ef);
472
642k
    }
473
491k
  }
474
51.1k
}
475
476
/*
477
 * Find the backwards transitive closure of the flow graph.  These sets
478
 * are backwards in the sense that we find the set of nodes that reach
479
 * a given node, not the set of nodes that can be reached by a node.
480
 *
481
 * Assumes graph has been leveled.
482
 */
483
static void
484
find_closure(opt_state_t *opt_state, const struct block *root)
485
51.1k
{
486
51.1k
  int level;
487
51.1k
  struct block *b;
488
489
  /*
490
   * Initialize sets to contain no nodes.
491
   */
492
51.1k
  memset((char *)opt_state->all_closure_sets, 0,
493
51.1k
        opt_state->n_blocks * opt_state->nodewords * sizeof(*opt_state->all_closure_sets));
494
495
  /* root->level is the highest level no found. */
496
542k
  for (level = root->level; level >= 0; --level) {
497
1.13M
    for (b = opt_state->levels[level]; b; b = b->link) {
498
642k
      SET_INSERT(b->closure, b->id);
499
642k
      if (JT(b) == NULL)
500
89.2k
        continue;
501
552k
      SET_UNION(JT(b)->closure, b->closure, opt_state->nodewords);
502
552k
      SET_UNION(JF(b)->closure, b->closure, opt_state->nodewords);
503
552k
    }
504
491k
  }
505
51.1k
}
506
507
/*
508
 * Return the register number that is used by s.
509
 *
510
 * Returns ATOM_A if A is used, ATOM_X if X is used, AX_ATOM if both A and X
511
 * are used, the scratch memory location's number if a scratch memory
512
 * location is used (e.g., 0 for M[0]), or -1 if none of those are used.
513
 *
514
 * The implementation should probably change to an array access.
515
 */
516
static int
517
atomuse(const struct stmt *s)
518
8.59M
{
519
8.59M
  int c = s->code;
520
521
8.59M
  if (c == NOP)
522
3.09M
    return -1;
523
524
5.49M
  switch (BPF_CLASS(c)) {
525
526
50.9k
  case BPF_RET:
527
50.9k
    return BPF_RVAL(c) == BPF_A ? A_ATOM : -1;
528
529
1.72M
  case BPF_LD:
530
2.02M
  case BPF_LDX:
531
    /*
532
     * As there are fewer than 2^31 memory locations,
533
     * s->k should be convertible to int without problems.
534
     */
535
2.02M
    return (BPF_MODE(c) == BPF_IND) ? X_ATOM :
536
2.02M
      (BPF_MODE(c) == BPF_MEM) ? (int)s->k : -1;
537
538
490k
  case BPF_ST:
539
490k
    return A_ATOM;
540
541
0
  case BPF_STX:
542
0
    return X_ATOM;
543
544
1.10M
  case BPF_JMP:
545
2.71M
  case BPF_ALU:
546
2.71M
    if (BPF_SRC(c) == BPF_X)
547
277k
      return AX_ATOM;
548
2.43M
    return A_ATOM;
549
550
222k
  case BPF_MISC:
551
222k
    return BPF_MISCOP(c) == BPF_TXA ? X_ATOM : A_ATOM;
552
5.49M
  }
553
554
  /*
555
   * BPF_CLASS() evaluates to [0x00, 0x07], each of which is a case
556
   * above, hence this function always returns from within the switch
557
   * statement.  At least one compiler (TinyCC) fails to see this and
558
   * without the mock last-resort return statement below would generate
559
   * a "function might return no value" warning.
560
   */
561
  /* NOTREACHED */
562
0
  return -1;
563
5.49M
}
564
565
/*
566
 * Return the register number that is defined by 's'.  We assume that
567
 * a single stmt cannot define more than one register.  If no register
568
 * is defined, return -1.
569
 *
570
 * The implementation should probably change to an array access.
571
 */
572
static int
573
atomdef(struct stmt *s)
574
8.04M
{
575
8.04M
  if (s->code == NOP)
576
3.09M
    return -1;
577
578
4.94M
  switch (BPF_CLASS(s->code)) {
579
580
1.72M
  case BPF_LD:
581
3.33M
  case BPF_ALU:
582
3.33M
    return A_ATOM;
583
584
296k
  case BPF_LDX:
585
296k
    return X_ATOM;
586
587
490k
  case BPF_ST:
588
490k
  case BPF_STX:
589
490k
    return s->k;
590
591
222k
  case BPF_MISC:
592
222k
    return BPF_MISCOP(s->code) == BPF_TAX ? X_ATOM : A_ATOM;
593
4.94M
  }
594
600k
  return -1;
595
4.94M
}
596
597
/*
598
 * Compute the sets of registers used, defined, and killed by 'b'.
599
 *
600
 * "Used" means that a statement in 'b' uses the register before any
601
 * statement in 'b' defines it, i.e. it uses the value left in
602
 * that register by a predecessor block of this block.
603
 * "Defined" means that a statement in 'b' defines it.
604
 * "Killed" means that a statement in 'b' defines it before any
605
 * statement in 'b' uses it, i.e. it kills the value left in that
606
 * register by a predecessor block of this block.
607
 */
608
static void
609
compute_local_ud(struct block *b)
610
642k
{
611
642k
  struct slist *s;
612
642k
  atomset def = 0, use = 0, killed = 0;
613
642k
  int atom;
614
615
5.88M
  for (s = b->stmts; s; s = s->next) {
616
5.24M
    if (s->s.code == NOP)
617
3.03M
      continue;
618
2.20M
    atom = atomuse(&s->s);
619
2.20M
    if (atom >= 0) {
620
1.60M
      if (atom == AX_ATOM) {
621
120k
        if (!ATOMELEM(def, X_ATOM))
622
1.73k
          use |= ATOMMASK(X_ATOM);
623
120k
        if (!ATOMELEM(def, A_ATOM))
624
209
          use |= ATOMMASK(A_ATOM);
625
120k
      }
626
1.48M
      else if (atom < N_ATOMS) {
627
1.48M
        if (!ATOMELEM(def, atom))
628
79.6k
          use |= ATOMMASK(atom);
629
1.48M
      }
630
0
      else
631
0
        abort();
632
1.60M
    }
633
2.20M
    atom = atomdef(&s->s);
634
2.20M
    if (atom >= 0) {
635
2.20M
      if (!ATOMELEM(use, atom))
636
2.20M
        killed |= ATOMMASK(atom);
637
2.20M
      def |= ATOMMASK(atom);
638
2.20M
    }
639
2.20M
  }
640
642k
  if (BPF_CLASS(b->s.code) == BPF_JMP) {
641
    /*
642
     * XXX - what about RET?
643
     */
644
552k
    atom = atomuse(&b->s);
645
552k
    if (atom >= 0) {
646
552k
      if (atom == AX_ATOM) {
647
26.9k
        if (!ATOMELEM(def, X_ATOM))
648
591
          use |= ATOMMASK(X_ATOM);
649
26.9k
        if (!ATOMELEM(def, A_ATOM))
650
290
          use |= ATOMMASK(A_ATOM);
651
26.9k
      }
652
525k
      else if (atom < N_ATOMS) {
653
525k
        if (!ATOMELEM(def, atom))
654
26.5k
          use |= ATOMMASK(atom);
655
525k
      }
656
0
      else
657
0
        abort();
658
552k
    }
659
552k
  }
660
661
642k
  b->def = def;
662
642k
  b->kill = killed;
663
642k
  b->in_use = use;
664
642k
}
665
666
/*
667
 * Assume graph is already leveled.
668
 */
669
static void
670
find_ud(const opt_state_t *opt_state, const struct block *root)
671
51.1k
{
672
51.1k
  int i, maxlevel;
673
51.1k
  struct block *p;
674
675
  /*
676
   * root->level is the highest level no found;
677
   * count down from there.
678
   */
679
51.1k
  maxlevel = root->level;
680
542k
  for (i = maxlevel; i >= 0; --i)
681
1.13M
    for (p = opt_state->levels[i]; p; p = p->link) {
682
642k
      compute_local_ud(p);
683
642k
      p->out_use = 0;
684
642k
    }
685
686
491k
  for (i = 1; i <= maxlevel; ++i) {
687
992k
    for (p = opt_state->levels[i]; p; p = p->link) {
688
552k
      p->out_use |= JT(p)->in_use | JF(p)->in_use;
689
552k
      p->in_use |= p->out_use &~ p->kill;
690
552k
    }
691
439k
  }
692
51.1k
}
693
static void
694
init_val(opt_state_t *opt_state)
695
51.1k
{
696
51.1k
  opt_state->curval = 0;
697
51.1k
  opt_state->next_vnode = opt_state->vnode_base;
698
51.1k
  memset((char *)opt_state->vmap, 0, opt_state->maxval * sizeof(*opt_state->vmap));
699
51.1k
  memset((char *)opt_state->hashtbl, 0, sizeof opt_state->hashtbl);
700
51.1k
}
701
702
/*
703
 * Because we really don't have an IR, this stuff is a little messy.
704
 *
705
 * This routine looks in the table of existing value number for a value
706
 * with generated from an operation with the specified opcode and
707
 * the specified values.  If it finds it, it returns its value number,
708
 * otherwise it makes a new entry in the table and returns the
709
 * value number of that entry.
710
 */
711
UNSIGNED_SHIFT_OK static bpf_u_int32
712
F(opt_state_t *opt_state, int code, bpf_u_int32 v0, bpf_u_int32 v1)
713
2.34M
{
714
2.34M
  u_int hash;
715
2.34M
  bpf_u_int32 val;
716
2.34M
  struct valnode *p;
717
718
2.34M
  hash = (u_int)code ^ (v0 << 4) ^ (v1 << 8);
719
2.34M
  hash %= MODULUS;
720
721
2.60M
  for (p = opt_state->hashtbl[hash]; p; p = p->next)
722
1.48M
    if (p->code == code && p->v0 == v0 && p->v1 == v1)
723
1.22M
      return p->val;
724
725
  /*
726
   * Not found.  Allocate a new value, and assign it a new
727
   * value number.
728
   *
729
   * opt_state->curval starts out as 0, which means VAL_UNKNOWN; we
730
   * increment it before using it as the new value number, which
731
   * means we never assign VAL_UNKNOWN.
732
   *
733
   * XXX - unless we overflow, but we probably won't have 2^32-1
734
   * values; we treat 32 bits as effectively infinite.
735
   */
736
1.11M
  val = ++opt_state->curval;
737
1.11M
  if (BPF_MODE(code) == BPF_IMM &&
738
358k
      (BPF_CLASS(code) == BPF_LD || BPF_CLASS(code) == BPF_LDX)) {
739
320k
    opt_state->vmap[val].const_val = v0;
740
320k
    opt_state->vmap[val].is_const = 1;
741
320k
  }
742
1.11M
  p = opt_state->next_vnode++;
743
1.11M
  p->val = val;
744
1.11M
  p->code = code;
745
1.11M
  p->v0 = v0;
746
1.11M
  p->v1 = v1;
747
1.11M
  p->next = opt_state->hashtbl[hash];
748
1.11M
  opt_state->hashtbl[hash] = p;
749
750
1.11M
  return val;
751
2.34M
}
752
753
static inline void
754
vstore(struct stmt *s, bpf_u_int32 *valp, bpf_u_int32 newval, int alter)
755
1.42M
{
756
1.42M
  if (alter && newval != VAL_UNKNOWN && *valp == newval)
757
62.4k
    s->code = NOP;
758
1.36M
  else
759
1.36M
    *valp = newval;
760
1.42M
}
761
762
/*
763
 * Do constant-folding on binary operators.
764
 * (Unary operators are handled elsewhere.)
765
 */
766
static void
767
fold_op(opt_state_t *opt_state, struct stmt *s, bpf_u_int32 v0, bpf_u_int32 v1)
768
6.16k
{
769
6.16k
  bpf_u_int32 a, b;
770
771
6.16k
  a = opt_state->vmap[v0].const_val;
772
6.16k
  b = opt_state->vmap[v1].const_val;
773
774
6.16k
  switch (BPF_OP(s->code)) {
775
1.01k
  case BPF_ADD:
776
1.01k
    a += b;
777
1.01k
    break;
778
779
394
  case BPF_SUB:
780
394
    a -= b;
781
394
    break;
782
783
1.69k
  case BPF_MUL:
784
1.69k
    a *= b;
785
1.69k
    break;
786
787
792
  case BPF_DIV:
788
792
    if (b == 0)
789
3
      opt_error(opt_state, ERRSTR_DIV_BY_ZERO);
790
789
    a /= b;
791
789
    break;
792
793
401
  case BPF_MOD:
794
401
    if (b == 0)
795
29
      opt_error(opt_state, ERRSTR_MOD_BY_ZERO);
796
372
    a %= b;
797
372
    break;
798
799
538
  case BPF_AND:
800
538
    a &= b;
801
538
    break;
802
803
535
  case BPF_OR:
804
535
    a |= b;
805
535
    break;
806
807
295
  case BPF_XOR:
808
295
    a ^= b;
809
295
    break;
810
811
284
  case BPF_LSH:
812
    // See the comment in gencode.h.
813
284
    a = UINT32_LSH(a, b);
814
284
    break;
815
816
213
  case BPF_RSH:
817
    // See the comment in gencode.h.
818
213
    a = UINT32_RSH(a, b);
819
213
    break;
820
821
0
  default:
822
0
    abort();
823
6.16k
  }
824
6.13k
  s->k = a;
825
6.13k
  s->code = BPF_LD|BPF_W|BPF_IMM;
826
6.13k
  opt_state->done = 0;
827
  /*
828
   * XXX - optimizer loop detection.
829
   */
830
6.13k
  opt_state->non_branch_movement_performed = 1;
831
6.13k
}
832
833
static inline struct slist *
834
this_op(struct slist *s)
835
4.35M
{
836
7.47M
  while (s != 0 && s->s.code == NOP)
837
3.11M
    s = s->next;
838
4.35M
  return s;
839
4.35M
}
840
841
static void
842
opt_not(struct block *b)
843
684
{
844
684
  struct block *tmp = JT(b);
845
846
684
  JT(b) = JF(b);
847
684
  JF(b) = tmp;
848
684
}
849
850
static void
851
opt_peep(opt_state_t *opt_state, struct block *b)
852
600k
{
853
600k
  struct slist *s;
854
600k
  struct slist *next, *last;
855
600k
  bpf_u_int32 val;
856
857
600k
  s = b->stmts;
858
600k
  if (s == NULL)
859
54.0k
    return;
860
861
546k
  last = s;
862
2.18M
  for (/*empty*/; /*empty*/; s = next) {
863
    /*
864
     * Skip over nops.
865
     */
866
2.18M
    s = this_op(s);
867
2.18M
    if (s == NULL)
868
42.2k
      break;  /* nothing left in the block */
869
870
    /*
871
     * Find the next real instruction after that one
872
     * (skipping nops).
873
     */
874
2.13M
    next = this_op(s->next);
875
2.13M
    if (next == NULL)
876
504k
      break;  /* no next instruction */
877
1.63M
    last = next;
878
879
    /*
880
     * st  M[k] --> st  M[k]
881
     * ldx M[k]   tax
882
     */
883
1.63M
    if (s->s.code == BPF_ST &&
884
243k
        next->s.code == (BPF_LDX|BPF_W|BPF_MEM) &&
885
22.1k
        s->s.k == next->s.k) {
886
19.1k
      opt_state->done = 0;
887
19.1k
      next->s.code = BPF_MISC|BPF_TAX;
888
      /*
889
       * The value of 'k' is still the scratch memory
890
       * register index from the "ldx M[k]", so if it is not
891
       * zero, the replacement "tax" is not identical to a
892
       * "tax" produced in pcap_parse().  Make it identical
893
       * to eliminate the need to reason whether it will be
894
       * equivalent in all possible contexts.
895
       *
896
       * Belt and braces: the replacement "tax" very likely
897
       * will have been optimised away before opt_loop()
898
       * returns, and even if it gets to eq_slist(), the
899
       * latter will ignore 'k' if it is irrelevant for the
900
       * opcode, but let's make bugs less likely elsewhere
901
       * too.
902
       */
903
19.1k
      next->s.k = 0;
904
      /*
905
       * XXX - optimizer loop detection.
906
       */
907
19.1k
      opt_state->non_branch_movement_performed = 1;
908
19.1k
    }
909
    /*
910
     * ld  #k --> ldx  #k
911
     * tax      txa
912
     */
913
1.63M
    if (s->s.code == (BPF_LD|BPF_W|BPF_IMM) &&
914
112k
        next->s.code == (BPF_MISC|BPF_TAX)) {
915
11.3k
      s->s.code = BPF_LDX|BPF_W|BPF_IMM;
916
11.3k
      next->s.code = BPF_MISC|BPF_TXA;
917
11.3k
      opt_state->done = 0;
918
      /*
919
       * XXX - optimizer loop detection.
920
       */
921
11.3k
      opt_state->non_branch_movement_performed = 1;
922
11.3k
    }
923
    /*
924
     * This is an ugly special case, but it happens
925
     * when you say tcp[k] or udp[k] where k is a constant.
926
     */
927
1.63M
    if (s->s.code == (BPF_LD|BPF_W|BPF_IMM)) {
928
100k
      struct slist *add, *tax, *ild;
929
930
      /*
931
       * Check that X isn't used on exit from this
932
       * block (which the optimizer might cause).
933
       * We know the code generator won't generate
934
       * any local dependencies.
935
       */
936
100k
      if (ATOMELEM(b->out_use, X_ATOM))
937
1.18k
        continue;
938
939
      /*
940
       * Check that the instruction following the
941
       * "ld #k" is an "add x", or it's an
942
       * "ldxb 4*([k]&0xf)" with an "add x"
943
       * following it (with 0 or more nops between the
944
       * "ldxb 4*([k]&0xf)" and "add x").
945
       */
946
99.5k
      if (next->s.code != (BPF_LDX|BPF_MSH|BPF_B))
947
98.9k
        add = next;
948
569
      else
949
569
        add = this_op(next->next);
950
99.5k
      if (add == NULL || add->s.code != (BPF_ALU|BPF_ADD|BPF_X))
951
95.4k
        continue;
952
953
      /*
954
       * Check that a tax follows that (with 0 or more
955
       * nops between them).
956
       */
957
4.03k
      tax = this_op(add->next);
958
4.03k
      if (tax == NULL || tax->s.code != (BPF_MISC|BPF_TAX))
959
1.35k
        continue;
960
961
      /*
962
       * Check that an "ld [x+k]", an "ldh [x+k]" or an
963
       * "ldb [x+k]" follows that (with 0 or more
964
       * nops between them).
965
       */
966
2.67k
      ild = this_op(tax->next);
967
2.67k
      if (ild == NULL || BPF_CLASS(ild->s.code) != BPF_LD ||
968
2.14k
          BPF_MODE(ild->s.code) != BPF_IND)
969
2.10k
        continue;
970
      /*
971
       * We want to turn this sequence:
972
       *
973
       * (004) ld      #0x2   {s}
974
       * (005) ldxb    4*([14]&0xf) {next}  -- optional
975
       * (006) add x      {add}
976
       * (007) tax      {tax}
977
       * (008) ld      [x+0]    {ild}
978
       *
979
       * into this sequence:
980
       *
981
       * (004) nop
982
       * (005) ldxb    4*([14]&0xf)
983
       * (006) nop
984
       * (007) nop
985
       * (008) ld      [x+2]
986
       *
987
       * XXX We need to check that X is not
988
       * subsequently used, because we want to change
989
       * what'll be in it after this sequence.
990
       *
991
       * We know we can eliminate the accumulator
992
       * modifications earlier in the sequence since
993
       * it is defined by the last stmt of this sequence
994
       * (i.e., the last statement of the sequence loads
995
       * a value into the accumulator, so we can eliminate
996
       * earlier operations on the accumulator).
997
       */
998
575
      ild->s.k += s->s.k;
999
575
      s->s.code = NOP;
1000
575
      add->s.code = NOP;
1001
575
      tax->s.code = NOP;
1002
575
      opt_state->done = 0;
1003
      /*
1004
       * XXX - optimizer loop detection.
1005
       */
1006
575
      opt_state->non_branch_movement_performed = 1;
1007
575
    }
1008
1.63M
  }
1009
  /*
1010
   * If the comparison at the end of a block is an equality
1011
   * comparison against a constant, and nobody uses the value
1012
   * we leave in the A register at the end of a block, and
1013
   * the operation preceding the comparison is an arithmetic
1014
   * operation, we can sometimes optimize it away.
1015
   */
1016
546k
  if (b->s.code == (BPF_JMP|BPF_JEQ|BPF_K) &&
1017
479k
      !ATOMELEM(b->out_use, A_ATOM)) {
1018
    /*
1019
     * We can optimize away certain subtractions of the
1020
     * X register.
1021
     */
1022
454k
    if (last->s.code == (BPF_ALU|BPF_SUB|BPF_X)) {
1023
354
      val = b->val[X_ATOM];
1024
354
      if (opt_state->vmap[val].is_const) {
1025
        /*
1026
         * If we have a subtract to do a comparison,
1027
         * and the X register is a known constant,
1028
         * we can merge this value into the
1029
         * comparison:
1030
         *
1031
         * sub x  ->  nop
1032
         * jeq #y jeq #(x+y)
1033
         */
1034
0
        b->s.k += opt_state->vmap[val].const_val;
1035
0
        last->s.code = NOP;
1036
0
        opt_state->done = 0;
1037
        /*
1038
         * XXX - optimizer loop detection.
1039
         */
1040
0
        opt_state->non_branch_movement_performed = 1;
1041
354
      } else if (b->s.k == 0) {
1042
        /*
1043
         * If the X register isn't a constant,
1044
         * and the comparison in the test is
1045
         * against 0, we can compare with the
1046
         * X register, instead:
1047
         *
1048
         * sub x  ->  nop
1049
         * jeq #0 jeq x
1050
         */
1051
15
        last->s.code = NOP;
1052
15
        b->s.code = BPF_JMP|BPF_JEQ|BPF_X;
1053
15
        opt_state->done = 0;
1054
        /*
1055
         * XXX - optimizer loop detection.
1056
         */
1057
15
        opt_state->non_branch_movement_performed = 1;
1058
15
      }
1059
354
    }
1060
    /*
1061
     * Likewise, a constant subtract can be simplified:
1062
     *
1063
     * sub #x ->  nop
1064
     * jeq #y ->  jeq #(x+y)
1065
     */
1066
453k
    else if (last->s.code == (BPF_ALU|BPF_SUB|BPF_K)) {
1067
84
      last->s.code = NOP;
1068
84
      b->s.k += last->s.k;
1069
84
      opt_state->done = 0;
1070
      /*
1071
       * XXX - optimizer loop detection.
1072
       */
1073
84
      opt_state->non_branch_movement_performed = 1;
1074
84
    }
1075
    /*
1076
     * And, similarly, a constant AND can be simplified
1077
     * if we're testing against 0, i.e.:
1078
     *
1079
     * and #k nop
1080
     * jeq #0  -> jset #k
1081
     */
1082
453k
    else if (last->s.code == (BPF_ALU|BPF_AND|BPF_K) &&
1083
115k
        b->s.k == 0) {
1084
673
      b->s.k = last->s.k;
1085
673
      b->s.code = BPF_JMP|BPF_K|BPF_JSET;
1086
673
      last->s.code = NOP;
1087
673
      opt_state->done = 0;
1088
673
      opt_not(b);
1089
      /*
1090
       * XXX - optimizer loop detection.
1091
       */
1092
673
      opt_state->non_branch_movement_performed = 1;
1093
673
    }
1094
454k
  }
1095
  /*
1096
   * jset #0x0         ->  never
1097
   * jset #0xffffffff  ->  iff A != 0
1098
   */
1099
546k
  if (b->s.code == (BPF_JMP|BPF_K|BPF_JSET)) {
1100
    /*
1101
     * This can be, but not necessarily is a result of the folding
1102
     * into "jset #k" above.
1103
     */
1104
24.5k
    if (b->s.k == 0)
1105
289
      JT(b) = JF(b);
1106
24.2k
    else if (b->s.k == 0xffffffffU) {
1107
      /*
1108
       * For any A: "A has at least one bit set" means the
1109
       * same as "A != 0".  Test the latter condition, which
1110
       * executes slightly faster and is easier to read.
1111
       * This is not meant to be the inverse of the folding,
1112
       * hence do not prepend a [no-op] "and #0xffffffff".
1113
       */
1114
11
      b->s.code = BPF_JMP|BPF_JEQ|BPF_K;
1115
11
      b->s.k = 0;
1116
11
      opt_not(b);
1117
11
      opt_state->done = 0;
1118
      /*
1119
       * XXX - optimizer loop detection.
1120
       */
1121
11
      opt_state->non_branch_movement_performed = 1;
1122
11
    }
1123
24.5k
  }
1124
  /*
1125
   * If we're comparing against the index register, and the index
1126
   * register is a known constant, we can just compare against that
1127
   * constant.
1128
   */
1129
546k
  val = b->val[X_ATOM];
1130
546k
  if (opt_state->vmap[val].is_const && BPF_SRC(b->s.code) == BPF_X) {
1131
2.60k
    bpf_u_int32 v = opt_state->vmap[val].const_val;
1132
    // Make "BPF_SRC(b->s.code) == BPF_K" true.
1133
2.60k
    b->s.code &= ~BPF_X;
1134
2.60k
    b->s.k = v;
1135
2.60k
  }
1136
  /*
1137
   * If the accumulator is a known constant, we can compute the
1138
   * comparison result.
1139
   */
1140
546k
  val = b->val[A_ATOM];
1141
546k
  if (opt_state->vmap[val].is_const && BPF_SRC(b->s.code) == BPF_K) {
1142
16.1k
    bpf_u_int32 v = opt_state->vmap[val].const_val;
1143
16.1k
    switch (BPF_OP(b->s.code)) {
1144
1145
5.78k
    case BPF_JEQ:
1146
5.78k
      v = v == b->s.k;
1147
5.78k
      break;
1148
1149
5.01k
    case BPF_JGT:
1150
5.01k
      v = v > b->s.k;
1151
5.01k
      break;
1152
1153
4.93k
    case BPF_JGE:
1154
4.93k
      v = v >= b->s.k;
1155
4.93k
      break;
1156
1157
417
    case BPF_JSET:
1158
417
      v &= b->s.k;
1159
417
      break;
1160
1161
0
    default:
1162
0
      abort();
1163
16.1k
    }
1164
16.1k
    if (JF(b) != JT(b)) {
1165
2.52k
      opt_state->done = 0;
1166
      /*
1167
       * XXX - optimizer loop detection.
1168
       */
1169
2.52k
      opt_state->non_branch_movement_performed = 1;
1170
2.52k
    }
1171
16.1k
    if (v)
1172
6.94k
      JF(b) = JT(b);
1173
9.21k
    else
1174
9.21k
      JT(b) = JF(b);
1175
16.1k
  }
1176
546k
}
1177
1178
/*
1179
 * Compute the symbolic value of expression of 's', and update
1180
 * anything it defines in the value table 'val'.  If 'alter' is true,
1181
 * do various optimizations.  This code would be cleaner if symbolic
1182
 * evaluation and code transformations weren't folded together.
1183
 */
1184
static void
1185
opt_stmt(opt_state_t *opt_state, struct stmt *s, bpf_u_int32 val[], int alter)
1186
5.24M
{
1187
5.24M
  int op;
1188
5.24M
  bpf_u_int32 v;
1189
1190
5.24M
  switch (s->code) {
1191
1192
174k
  case BPF_LD|BPF_ABS|BPF_W:
1193
266k
  case BPF_LD|BPF_ABS|BPF_H:
1194
394k
  case BPF_LD|BPF_ABS|BPF_B:
1195
394k
    v = F(opt_state, s->code, s->k, 0L);
1196
394k
    vstore(s, &val[A_ATOM], v, alter);
1197
394k
    break;
1198
1199
8.31k
  case BPF_LD|BPF_IND|BPF_W:
1200
61.0k
  case BPF_LD|BPF_IND|BPF_H:
1201
129k
  case BPF_LD|BPF_IND|BPF_B:
1202
129k
    v = val[X_ATOM];
1203
129k
    if (alter && opt_state->vmap[v].is_const) {
1204
6.08k
      s->code = BPF_LD|BPF_ABS|BPF_SIZE(s->code);
1205
6.08k
      s->k += opt_state->vmap[v].const_val;
1206
6.08k
      v = F(opt_state, s->code, s->k, 0L);
1207
6.08k
      opt_state->done = 0;
1208
      /*
1209
       * XXX - optimizer loop detection.
1210
       */
1211
6.08k
      opt_state->non_branch_movement_performed = 1;
1212
6.08k
    }
1213
123k
    else
1214
123k
      v = F(opt_state, s->code, s->k, v);
1215
129k
    vstore(s, &val[A_ATOM], v, alter);
1216
129k
    break;
1217
1218
25.4k
  case BPF_LD|BPF_W|BPF_LEN:
1219
25.4k
    v = F(opt_state, s->code, 0L, 0L);
1220
25.4k
    vstore(s, &val[A_ATOM], v, alter);
1221
25.4k
    break;
1222
1223
119k
  case BPF_LD|BPF_W|BPF_IMM:
1224
119k
    v = K(s->k);
1225
119k
    vstore(s, &val[A_ATOM], v, alter);
1226
119k
    break;
1227
1228
42.1k
  case BPF_LDX|BPF_W|BPF_IMM:
1229
42.1k
    v = K(s->k);
1230
42.1k
    vstore(s, &val[X_ATOM], v, alter);
1231
42.1k
    break;
1232
1233
22.4k
  case BPF_LDX|BPF_MSH|BPF_B:
1234
22.4k
    v = F(opt_state, s->code, s->k, 0L);
1235
22.4k
    vstore(s, &val[X_ATOM], v, alter);
1236
22.4k
    break;
1237
1238
513k
  case BPF_ALU|BPF_NEG:
1239
513k
    if (alter && opt_state->vmap[val[A_ATOM]].is_const) {
1240
884
      s->code = BPF_LD|BPF_W|BPF_IMM;
1241
      // See the comment in gencode.h.
1242
884
      s->k = UINT_NEG(opt_state->vmap[val[A_ATOM]].const_val);
1243
884
      val[A_ATOM] = K(s->k);
1244
884
    }
1245
512k
    else
1246
512k
      val[A_ATOM] = F(opt_state, s->code, val[A_ATOM], 0L);
1247
513k
    break;
1248
1249
7.59k
  case BPF_ALU|BPF_ADD|BPF_K:
1250
9.99k
  case BPF_ALU|BPF_SUB|BPF_K:
1251
15.6k
  case BPF_ALU|BPF_MUL|BPF_K:
1252
17.1k
  case BPF_ALU|BPF_DIV|BPF_K:
1253
18.5k
  case BPF_ALU|BPF_MOD|BPF_K:
1254
157k
  case BPF_ALU|BPF_AND|BPF_K:
1255
157k
  case BPF_ALU|BPF_OR|BPF_K:
1256
158k
  case BPF_ALU|BPF_XOR|BPF_K:
1257
176k
  case BPF_ALU|BPF_LSH|BPF_K:
1258
177k
  case BPF_ALU|BPF_RSH|BPF_K:
1259
177k
    op = BPF_OP(s->code);
1260
177k
    if (alter) {
1261
58.2k
      if (s->k == 0) {
1262
        /*
1263
         * Optimize operations where the constant
1264
         * is zero.
1265
         *
1266
         * Don't optimize away "sub #0"
1267
         * as it may be needed later to
1268
         * fixup the generated math code.
1269
         *
1270
         * Fail if we're dividing by zero or taking
1271
         * a modulo by zero.
1272
         */
1273
2.57k
        if (op == BPF_ADD ||
1274
2.25k
            op == BPF_LSH || op == BPF_RSH ||
1275
2.09k
            op == BPF_OR || op == BPF_XOR) {
1276
640
          s->code = NOP;
1277
640
          break;
1278
640
        }
1279
1.93k
        if (op == BPF_MUL || op == BPF_AND) {
1280
867
          s->code = BPF_LD|BPF_W|BPF_IMM;
1281
867
          val[A_ATOM] = K(s->k);
1282
867
          break;
1283
867
        }
1284
1.07k
        if (op == BPF_DIV)
1285
2
          opt_error(opt_state,
1286
2
              ERRSTR_DIV_BY_ZERO);
1287
1.06k
        if (op == BPF_MOD)
1288
24
          opt_error(opt_state,
1289
24
              ERRSTR_MOD_BY_ZERO);
1290
1.06k
      }
1291
56.7k
      if (opt_state->vmap[val[A_ATOM]].is_const) {
1292
1.19k
        fold_op(opt_state, s, val[A_ATOM], K(s->k));
1293
1.19k
        val[A_ATOM] = K(s->k);
1294
1.19k
        break;
1295
1.19k
      }
1296
56.7k
    }
1297
174k
    val[A_ATOM] = F(opt_state, s->code, val[A_ATOM], K(s->k));
1298
174k
    break;
1299
1300
35.7k
  case BPF_ALU|BPF_ADD|BPF_X:
1301
43.8k
  case BPF_ALU|BPF_SUB|BPF_X:
1302
62.7k
  case BPF_ALU|BPF_MUL|BPF_X:
1303
69.7k
  case BPF_ALU|BPF_DIV|BPF_X:
1304
83.6k
  case BPF_ALU|BPF_MOD|BPF_X:
1305
97.5k
  case BPF_ALU|BPF_AND|BPF_X:
1306
105k
  case BPF_ALU|BPF_OR|BPF_X:
1307
111k
  case BPF_ALU|BPF_XOR|BPF_X:
1308
116k
  case BPF_ALU|BPF_LSH|BPF_X:
1309
119k
  case BPF_ALU|BPF_RSH|BPF_X:
1310
119k
    op = BPF_OP(s->code);
1311
119k
    if (alter && opt_state->vmap[val[X_ATOM]].is_const) {
1312
11.1k
      if (opt_state->vmap[val[A_ATOM]].is_const) {
1313
4.97k
        fold_op(opt_state, s, val[A_ATOM], val[X_ATOM]);
1314
4.97k
        val[A_ATOM] = K(s->k);
1315
4.97k
      }
1316
6.19k
      else {
1317
6.19k
        s->code = BPF_ALU|BPF_K|op;
1318
6.19k
        s->k = opt_state->vmap[val[X_ATOM]].const_val;
1319
6.19k
        if ((op == BPF_LSH || op == BPF_RSH) &&
1320
532
            s->k > 31)
1321
1
          opt_error(opt_state,
1322
1
              ERRSTR_SHIFT_BY_MORE);
1323
6.19k
        opt_state->done = 0;
1324
6.19k
        val[A_ATOM] =
1325
6.19k
          F(opt_state, s->code, val[A_ATOM], K(s->k));
1326
        /*
1327
         * XXX - optimizer loop detection.
1328
         */
1329
6.19k
        opt_state->non_branch_movement_performed = 1;
1330
6.19k
      }
1331
11.1k
      break;
1332
11.1k
    }
1333
    /*
1334
     * Check if we're doing something to an accumulator
1335
     * that is 0, and simplify.  This may not seem like
1336
     * much of a simplification but it could open up further
1337
     * optimizations.
1338
     * XXX We could also check for mul by 1, etc.
1339
     */
1340
108k
    if (alter && opt_state->vmap[val[A_ATOM]].is_const
1341
16.3k
        && opt_state->vmap[val[A_ATOM]].const_val == 0) {
1342
2.36k
      if (op == BPF_ADD || op == BPF_OR || op == BPF_XOR) {
1343
650
        s->code = BPF_MISC|BPF_TXA;
1344
650
        vstore(s, &val[A_ATOM], val[X_ATOM], alter);
1345
650
        break;
1346
650
      }
1347
1.71k
      else if (op == BPF_MUL || op == BPF_DIV || op == BPF_MOD ||
1348
1.32k
         op == BPF_AND || op == BPF_LSH || op == BPF_RSH) {
1349
863
        s->code = BPF_LD|BPF_W|BPF_IMM;
1350
863
        s->k = 0;
1351
863
        vstore(s, &val[A_ATOM], K(s->k), alter);
1352
863
        break;
1353
863
      }
1354
851
      else if (op == BPF_NEG) {
1355
0
        s->code = NOP;
1356
0
        break;
1357
0
      }
1358
2.36k
    }
1359
107k
    val[A_ATOM] = F(opt_state, s->code, val[A_ATOM], val[X_ATOM]);
1360
107k
    break;
1361
1362
2.20k
  case BPF_MISC|BPF_TXA:
1363
2.20k
    vstore(s, &val[A_ATOM], val[X_ATOM], alter);
1364
2.20k
    break;
1365
1366
221k
  case BPF_LD|BPF_W|BPF_MEM:
1367
221k
    v = val[s->k];
1368
221k
    if (alter && opt_state->vmap[v].is_const) {
1369
12.6k
      s->code = BPF_LD|BPF_W|BPF_IMM;
1370
12.6k
      s->k = opt_state->vmap[v].const_val;
1371
12.6k
      opt_state->done = 0;
1372
      /*
1373
       * XXX - optimizer loop detection.
1374
       */
1375
12.6k
      opt_state->non_branch_movement_performed = 1;
1376
12.6k
    }
1377
221k
    vstore(s, &val[A_ATOM], v, alter);
1378
221k
    break;
1379
1380
100k
  case BPF_MISC|BPF_TAX:
1381
100k
    vstore(s, &val[X_ATOM], val[A_ATOM], alter);
1382
100k
    break;
1383
1384
92.0k
  case BPF_LDX|BPF_W|BPF_MEM:
1385
92.0k
    v = val[s->k];
1386
92.0k
    if (alter && opt_state->vmap[v].is_const) {
1387
5.50k
      s->code = BPF_LDX|BPF_W|BPF_IMM;
1388
5.50k
      s->k = opt_state->vmap[v].const_val;
1389
5.50k
      opt_state->done = 0;
1390
      /*
1391
       * XXX - optimizer loop detection.
1392
       */
1393
5.50k
      opt_state->non_branch_movement_performed = 1;
1394
5.50k
    }
1395
92.0k
    vstore(s, &val[X_ATOM], v, alter);
1396
92.0k
    break;
1397
1398
246k
  case BPF_ST:
1399
246k
    vstore(s, &val[s->k], val[A_ATOM], alter);
1400
246k
    break;
1401
1402
0
  case BPF_STX:
1403
0
    vstore(s, &val[s->k], val[X_ATOM], alter);
1404
0
    break;
1405
5.24M
  }
1406
5.24M
}
1407
1408
static void
1409
deadstmt(opt_state_t *opt_state, struct stmt *s, struct stmt *last[])
1410
5.83M
{
1411
5.83M
  int atom;
1412
1413
5.83M
  atom = atomuse(s);
1414
5.83M
  if (atom >= 0) {
1415
2.08M
    if (atom == AX_ATOM) {
1416
130k
      last[X_ATOM] = 0;
1417
130k
      last[A_ATOM] = 0;
1418
130k
    }
1419
1.95M
    else
1420
1.95M
      last[atom] = 0;
1421
2.08M
  }
1422
5.83M
  atom = atomdef(s);
1423
5.83M
  if (atom >= 0) {
1424
2.13M
    if (last[atom]) {
1425
78.7k
      opt_state->done = 0;
1426
78.7k
      last[atom]->code = NOP;
1427
      /*
1428
       * XXX - optimizer loop detection.
1429
       */
1430
78.7k
      opt_state->non_branch_movement_performed = 1;
1431
78.7k
    }
1432
2.13M
    last[atom] = s;
1433
2.13M
  }
1434
5.83M
}
1435
1436
static void
1437
opt_deadstores(opt_state_t *opt_state, struct block *b)
1438
600k
{
1439
600k
  struct slist *s;
1440
600k
  int atom;
1441
600k
  struct stmt *last[N_ATOMS];
1442
1443
600k
  memset((char *)last, 0, sizeof last);
1444
1445
5.83M
  for (s = b->stmts; s != 0; s = s->next)
1446
5.23M
    deadstmt(opt_state, &s->s, last);
1447
600k
  deadstmt(opt_state, &b->s, last);
1448
1449
11.4M
  for (atom = 0; atom < N_ATOMS; ++atom)
1450
10.8M
    if (last[atom] && !ATOMELEM(b->out_use, atom)) {
1451
26.9k
      last[atom]->code = NOP;
1452
      /*
1453
       * The store was removed as it's dead,
1454
       * so the value stored into now has
1455
       * an unknown value.
1456
       */
1457
26.9k
      vstore(0, &b->val[atom], VAL_UNKNOWN, 0);
1458
26.9k
      opt_state->done = 0;
1459
      /*
1460
       * XXX - optimizer loop detection.
1461
       */
1462
26.9k
      opt_state->non_branch_movement_performed = 1;
1463
26.9k
    }
1464
600k
}
1465
1466
static void
1467
opt_blk(opt_state_t *opt_state, struct block *b, int do_stmts)
1468
641k
{
1469
641k
  struct slist *s;
1470
641k
  struct edge *p;
1471
641k
  int i;
1472
641k
  bpf_u_int32 aval, xval;
1473
1474
#if 0
1475
  for (s = b->stmts; s && s->next; s = s->next)
1476
    if (BPF_CLASS(s->s.code) == BPF_JMP) {
1477
      do_stmts = 0;
1478
      break;
1479
    }
1480
#endif
1481
1482
  /*
1483
   * Initialize the atom values.
1484
   */
1485
641k
  p = b->in_edges;
1486
641k
  if (p == NULL) {
1487
    /*
1488
     * We have no predecessors, so everything is undefined
1489
     * upon entry to this block.
1490
     */
1491
51.1k
    memset((char *)b->val, 0, sizeof(b->val));
1492
590k
  } else {
1493
    /*
1494
     * Inherit values from our predecessors.
1495
     *
1496
     * First, get the values from the predecessor along the
1497
     * first edge leading to this node.
1498
     */
1499
590k
    memcpy((char *)b->val, (char *)p->pred->val, sizeof(b->val));
1500
    /*
1501
     * Now look at all the other nodes leading to this node.
1502
     * If, for the predecessor along that edge, a register
1503
     * has a different value from the one we have (i.e.,
1504
     * control paths are merging, and the merging paths
1505
     * assign different values to that register), give the
1506
     * register the undefined value of 0.
1507
     */
1508
1.10M
    while ((p = p->next) != NULL) {
1509
9.77M
      for (i = 0; i < N_ATOMS; ++i)
1510
9.26M
        if (b->val[i] != p->pred->val[i])
1511
518k
          b->val[i] = 0;
1512
514k
    }
1513
590k
  }
1514
641k
  aval = b->val[A_ATOM];
1515
641k
  xval = b->val[X_ATOM];
1516
5.88M
  for (s = b->stmts; s; s = s->next)
1517
5.24M
    opt_stmt(opt_state, &s->s, b->val, do_stmts);
1518
1519
  /*
1520
   * This is a special case: if we don't use anything from this
1521
   * block, and we load the accumulator or index register with a
1522
   * value that is already there, or if this block is a return,
1523
   * eliminate all the statements.
1524
   *
1525
   * XXX - what if it does a store?  Presumably that falls under
1526
   * the heading of "if we don't use anything from this block",
1527
   * i.e., if we use any memory location set to a different
1528
   * value by this block, then we use something from this block.
1529
   *
1530
   * XXX - why does it matter whether we use anything from this
1531
   * block?  If the accumulator or index register doesn't change
1532
   * its value, isn't that OK even if we use that value?
1533
   *
1534
   * XXX - if we load the accumulator with a different value,
1535
   * and the block ends with a conditional branch, we obviously
1536
   * can't eliminate it, as the branch depends on that value.
1537
   * For the index register, the conditional branch only depends
1538
   * on the index register value if the test is against the index
1539
   * register value rather than a constant; if nothing uses the
1540
   * value we put into the index register, and we're not testing
1541
   * against the index register's value, and there aren't any
1542
   * other problems that would keep us from eliminating this
1543
   * block, can we eliminate it?
1544
   */
1545
641k
  if (do_stmts &&
1546
204k
      ((b->out_use == 0 &&
1547
147k
        aval != VAL_UNKNOWN && b->val[A_ATOM] == aval &&
1548
57.3k
        xval != VAL_UNKNOWN && b->val[X_ATOM] == xval) ||
1549
183k
       BPF_CLASS(b->s.code) == BPF_RET)) {
1550
41.1k
    if (b->stmts != 0) {
1551
1.90k
      b->stmts = 0;
1552
1.90k
      opt_state->done = 0;
1553
      /*
1554
       * XXX - optimizer loop detection.
1555
       */
1556
1.90k
      opt_state->non_branch_movement_performed = 1;
1557
1.90k
    }
1558
600k
  } else {
1559
600k
    opt_peep(opt_state, b);
1560
600k
    opt_deadstores(opt_state, b);
1561
600k
  }
1562
  /*
1563
   * Set up values for branch optimizer.
1564
   */
1565
641k
  if (BPF_SRC(b->s.code) == BPF_K)
1566
617k
    b->oval = K(b->s.k);
1567
24.4k
  else
1568
24.4k
    b->oval = b->val[X_ATOM];
1569
641k
  b->et.code = b->s.code;
1570
641k
  b->ef.code = -b->s.code;
1571
641k
}
1572
1573
/*
1574
 * Return true if any register that is used on exit from 'succ', has
1575
 * an exit value that is different from the corresponding exit value
1576
 * from 'b'.
1577
 */
1578
static int
1579
use_conflict(const struct block *b, const struct block *succ)
1580
225k
{
1581
225k
  int atom;
1582
225k
  atomset use = succ->out_use;
1583
1584
225k
  if (use == 0)
1585
208k
    return 0;
1586
1587
313k
  for (atom = 0; atom < N_ATOMS; ++atom)
1588
297k
    if (ATOMELEM(use, atom))
1589
17.2k
      if (b->val[atom] != succ->val[atom])
1590
826
        return 1;
1591
16.3k
  return 0;
1592
17.1k
}
1593
1594
/*
1595
 * Given a block that is the successor of an edge, and an edge that
1596
 * dominates that edge, return either a pointer to a child of that
1597
 * block (a block to which that block jumps) if that block is a
1598
 * candidate to replace the successor of the latter edge or NULL
1599
 * if neither of the children of the first block are candidates.
1600
 */
1601
static struct block *
1602
fold_edge(struct block *child, struct edge *ep)
1603
2.42M
{
1604
2.42M
  int sense;
1605
2.42M
  bpf_u_int32 aval0, aval1, oval0, oval1;
1606
2.42M
  int code = ep->code;
1607
1608
2.42M
  if (code < 0) {
1609
    /*
1610
     * This edge is a "branch if false" edge.
1611
     */
1612
1.42M
    code = -code;
1613
1.42M
    sense = 0;
1614
1.42M
  } else {
1615
    /*
1616
     * This edge is a "branch if true" edge.
1617
     */
1618
1.00M
    sense = 1;
1619
1.00M
  }
1620
1621
  /*
1622
   * If the opcode for the branch at the end of the block we
1623
   * were handed isn't the same as the opcode for the branch
1624
   * to which the edge we were handed corresponds, the tests
1625
   * for those branches aren't testing the same conditions,
1626
   * so the blocks to which the first block branches aren't
1627
   * candidates to replace the successor of the edge.
1628
   */
1629
2.42M
  if (child->s.code != code)
1630
567k
    return 0;
1631
1632
1.86M
  aval0 = child->val[A_ATOM];
1633
1.86M
  oval0 = child->oval;
1634
1.86M
  aval1 = ep->pred->val[A_ATOM];
1635
1.86M
  oval1 = ep->pred->oval;
1636
1637
  /*
1638
   * If the A register value on exit from the successor block
1639
   * isn't the same as the A register value on exit from the
1640
   * predecessor of the edge, the blocks to which the first
1641
   * block branches aren't candidates to replace the successor
1642
   * of the edge.
1643
   */
1644
1.86M
  if (aval0 != aval1)
1645
1.26M
    return 0;
1646
1647
597k
  if (oval0 == oval1)
1648
    /*
1649
     * The operands of the branch instructions are
1650
     * identical, so the branches are testing the
1651
     * same condition, and the result is true if a true
1652
     * branch was taken to get here, otherwise false.
1653
     */
1654
131k
    return sense ? JT(child) : JF(child);
1655
1656
465k
  if (sense && code == (BPF_JMP|BPF_JEQ|BPF_K))
1657
    /*
1658
     * At this point, we only know the comparison if we
1659
     * came down the true branch, and it was an equality
1660
     * comparison with a constant.
1661
     *
1662
     * I.e., if we came down the true branch, and the branch
1663
     * was an equality comparison with a constant, we know the
1664
     * accumulator contains that constant.  If we came down
1665
     * the false branch, or the comparison wasn't with a
1666
     * constant, we don't know what was in the accumulator.
1667
     *
1668
     * We rely on the fact that distinct constants have distinct
1669
     * value numbers.
1670
     */
1671
87.1k
    return JF(child);
1672
1673
378k
  return 0;
1674
465k
}
1675
1676
/*
1677
 * If we can make this edge go directly to a child of the edge's current
1678
 * successor, do so.
1679
 */
1680
static void
1681
opt_j(opt_state_t *opt_state, struct edge *ep)
1682
773k
{
1683
773k
  u_int i, k;
1684
773k
  struct block *target;
1685
1686
  /*
1687
   * Does this edge go to a block where, if the test
1688
   * at the end of it succeeds, it goes to a block
1689
   * that's a leaf node of the DAG, i.e. a return
1690
   * statement?
1691
   * If so, there's nothing to optimize.
1692
   */
1693
773k
  if (JT(ep->succ) == NULL)
1694
187k
    return;
1695
1696
  /*
1697
   * Does this edge go to a block that goes, in turn, to
1698
   * the same block regardless of whether the test at the
1699
   * end succeeds or fails?
1700
   */
1701
585k
  if (JT(ep->succ) == JF(ep->succ)) {
1702
    /*
1703
     * Common branch targets can be eliminated, provided
1704
     * there is no data dependency.
1705
     *
1706
     * Check whether any register used on exit from the
1707
     * block to which the successor of this edge goes
1708
     * has a value at that point that's different from
1709
     * the value it has on exit from the predecessor of
1710
     * this edge.  If not, the predecessor of this edge
1711
     * can just go to the block to which the successor
1712
     * of this edge goes, bypassing the successor of this
1713
     * edge, as the successor of this edge isn't doing
1714
     * any calculations whose results are different
1715
     * from what the blocks before it did and isn't
1716
     * doing any tests the results of which matter.
1717
     */
1718
7.45k
    if (!use_conflict(ep->pred, JT(ep->succ))) {
1719
      /*
1720
       * No, there isn't.
1721
       * Make this edge go to the block to
1722
       * which the successor of that edge
1723
       * goes.
1724
       */
1725
6.96k
      opt_state->done = 0;
1726
6.96k
      ep->succ = JT(ep->succ);
1727
      /*
1728
       * XXX - optimizer loop detection.
1729
       */
1730
6.96k
      opt_state->non_branch_movement_performed = 1;
1731
6.96k
    }
1732
7.45k
  }
1733
  /*
1734
   * For each edge dominator that matches the successor of this
1735
   * edge, promote the edge successor to the its grandchild.
1736
   *
1737
   * XXX We violate the set abstraction here in favor a reasonably
1738
   * efficient loop.
1739
   */
1740
762k
 top:
1741
10.9M
  for (i = 0; i < opt_state->edgewords; ++i) {
1742
    /* i'th word in the bitset of dominators */
1743
10.4M
    bpf_u_int32 x = ep->edom[i];
1744
1745
12.6M
    while (x != 0) {
1746
      /* Find the next dominator in that word and mark it as found */
1747
2.42M
      k = lowest_set_bit(x);
1748
2.42M
      x &=~ ((bpf_u_int32)1 << k);
1749
2.42M
      k += i * BITS_PER_WORD;
1750
1751
2.42M
      target = fold_edge(ep->succ, opt_state->edges[k]);
1752
      /*
1753
       * We have a candidate to replace the successor
1754
       * of ep.
1755
       *
1756
       * Check that there is no data dependency between
1757
       * nodes that will be violated if we move the edge;
1758
       * i.e., if any register used on exit from the
1759
       * candidate has a value at that point different
1760
       * from the value it has when we exit the
1761
       * predecessor of that edge, there's a data
1762
       * dependency that will be violated.
1763
       */
1764
2.42M
      if (target != 0 && !use_conflict(ep->pred, target)) {
1765
        /*
1766
         * It's safe to replace the successor of
1767
         * ep; do so, and note that we've made
1768
         * at least one change.
1769
         *
1770
         * XXX - this is one of the operations that
1771
         * happens when the optimizer gets into
1772
         * one of those infinite loops.
1773
         */
1774
218k
        opt_state->done = 0;
1775
218k
        ep->succ = target;
1776
218k
        if (JT(target) != 0)
1777
          /*
1778
           * Start over unless we hit a leaf.
1779
           */
1780
176k
          goto top;
1781
41.2k
        return;
1782
218k
      }
1783
2.42M
    }
1784
10.4M
  }
1785
762k
}
1786
1787
/*
1788
 * XXX - is this, and and_pullup(), what's described in section 6.1.2
1789
 * "Predicate Assertion Propagation" in the BPF+ paper?
1790
 *
1791
 * Note that this looks at block dominators, not edge dominators.
1792
 * Don't think so.
1793
 *
1794
 * "A or B" compiles into
1795
 *
1796
 *          A
1797
 *       t / \ f
1798
 *        /   B
1799
 *       / t / \ f
1800
 *      \   /
1801
 *       \ /
1802
 *        X
1803
 *
1804
 *
1805
 */
1806
static void
1807
or_pullup(opt_state_t *opt_state, struct block *b, struct block *root)
1808
386k
{
1809
386k
  bpf_u_int32 val;
1810
386k
  int at_top;
1811
386k
  struct block *pull;
1812
386k
  struct block **diffp, **samep;
1813
386k
  struct edge *ep;
1814
1815
386k
  ep = b->in_edges;
1816
386k
  if (ep == NULL)
1817
50.8k
    return;
1818
1819
  /*
1820
   * Make sure each predecessor loads the same value.
1821
   * XXX why?
1822
   */
1823
335k
  val = ep->pred->val[A_ATOM];
1824
426k
  for (ep = ep->next; ep != 0; ep = ep->next)
1825
152k
    if (val != ep->pred->val[A_ATOM])
1826
61.9k
      return;
1827
1828
  /*
1829
   * For the first edge in the list of edges coming into this block,
1830
   * see whether the predecessor of that edge comes here via a true
1831
   * branch or a false branch.
1832
   */
1833
274k
  if (JT(b->in_edges->pred) == b)
1834
96.8k
    diffp = &JT(b->in_edges->pred); /* jt */
1835
177k
  else
1836
177k
    diffp = &JF(b->in_edges->pred);  /* jf */
1837
1838
  /*
1839
   * diffp is a pointer to a pointer to the block.
1840
   *
1841
   * Go down the false chain looking as far as you can,
1842
   * making sure that each jump-compare is doing the
1843
   * same as the original block.
1844
   *
1845
   * If you reach the bottom before you reach a
1846
   * different jump-compare, just exit.  There's nothing
1847
   * to do here.  XXX - no, this version is checking for
1848
   * the value leaving the block; that's from the BPF+
1849
   * pullup routine.
1850
   */
1851
274k
  at_top = 1;
1852
428k
  for (;;) {
1853
    /*
1854
     * Done if that's not going anywhere XXX
1855
     */
1856
428k
    if (*diffp == NULL)
1857
0
      return;
1858
1859
    /*
1860
     * Done if that predecessor blah blah blah isn't
1861
     * going the same place we're going XXX
1862
     *
1863
     * Does the true edge of this block point to the same
1864
     * location as the true edge of b?
1865
     */
1866
428k
    if (JT(*diffp) != JT(b))
1867
83.6k
      return;
1868
1869
    /*
1870
     * Done if this node isn't a dominator of that
1871
     * node blah blah blah XXX
1872
     *
1873
     * Does b dominate diffp?
1874
     */
1875
345k
    if (!SET_MEMBER((*diffp)->dom, b->id))
1876
2.45k
      return;
1877
1878
    /*
1879
     * Break out of the loop if that node's value of A
1880
     * isn't the value of A above XXX
1881
     */
1882
342k
    if ((*diffp)->val[A_ATOM] != val)
1883
187k
      break;
1884
1885
    /*
1886
     * Get the JF for that node XXX
1887
     * Go down the false path.
1888
     */
1889
154k
    diffp = &JF(*diffp);
1890
154k
    at_top = 0;
1891
154k
  }
1892
1893
  /*
1894
   * Now that we've found a different jump-compare in a chain
1895
   * below b, search further down until we find another
1896
   * jump-compare that looks at the original value.  This
1897
   * jump-compare should get pulled up.  XXX again we're
1898
   * comparing values not jump-compares.
1899
   */
1900
187k
  samep = &JF(*diffp);
1901
269k
  for (;;) {
1902
    /*
1903
     * Done if that's not going anywhere XXX
1904
     */
1905
269k
    if (*samep == NULL)
1906
0
      return;
1907
1908
    /*
1909
     * Done if that predecessor blah blah blah isn't
1910
     * going the same place we're going XXX
1911
     */
1912
269k
    if (JT(*samep) != JT(b))
1913
164k
      return;
1914
1915
    /*
1916
     * Done if this node isn't a dominator of that
1917
     * node blah blah blah XXX
1918
     *
1919
     * Does b dominate samep?
1920
     */
1921
105k
    if (!SET_MEMBER((*samep)->dom, b->id))
1922
10.8k
      return;
1923
1924
    /*
1925
     * Break out of the loop if that node's value of A
1926
     * is the value of A above XXX
1927
     */
1928
94.7k
    if ((*samep)->val[A_ATOM] == val)
1929
12.8k
      break;
1930
1931
    /* XXX Need to check that there are no data dependencies
1932
       between dp0 and dp1.  Currently, the code generator
1933
       will not produce such dependencies. */
1934
81.8k
    samep = &JF(*samep);
1935
81.8k
  }
1936
#ifdef notdef
1937
  /* XXX This doesn't cover everything. */
1938
  for (i = 0; i < N_ATOMS; ++i)
1939
    if ((*samep)->val[i] != pred->val[i])
1940
      return;
1941
#endif
1942
  /* Pull up the node. */
1943
12.8k
  pull = *samep;
1944
12.8k
  *samep = JF(pull);
1945
12.8k
  JF(pull) = *diffp;
1946
1947
  /*
1948
   * At the top of the chain, each predecessor needs to point at the
1949
   * pulled up node.  Inside the chain, there is only one predecessor
1950
   * to worry about.
1951
   */
1952
12.8k
  if (at_top) {
1953
26.4k
    for (ep = b->in_edges; ep != 0; ep = ep->next) {
1954
14.2k
      if (JT(ep->pred) == b)
1955
11.1k
        JT(ep->pred) = pull;
1956
3.05k
      else
1957
3.05k
        JF(ep->pred) = pull;
1958
14.2k
    }
1959
12.2k
  }
1960
581
  else
1961
581
    *diffp = pull;
1962
1963
  /*
1964
   * XXX - this is one of the operations that happens when the
1965
   * optimizer gets into one of those infinite loops.
1966
   */
1967
12.8k
  opt_state->done = 0;
1968
1969
  /*
1970
   * Recompute dominator sets as control flow graph has changed.
1971
   */
1972
12.8k
  find_dom(opt_state, root);
1973
12.8k
}
1974
1975
static void
1976
and_pullup(opt_state_t *opt_state, struct block *b, struct block *root)
1977
386k
{
1978
386k
  bpf_u_int32 val;
1979
386k
  int at_top;
1980
386k
  struct block *pull;
1981
386k
  struct block **diffp, **samep;
1982
386k
  struct edge *ep;
1983
1984
386k
  ep = b->in_edges;
1985
386k
  if (ep == NULL)
1986
50.8k
    return;
1987
1988
  /*
1989
   * Make sure each predecessor loads the same value.
1990
   */
1991
335k
  val = ep->pred->val[A_ATOM];
1992
426k
  for (ep = ep->next; ep != 0; ep = ep->next)
1993
152k
    if (val != ep->pred->val[A_ATOM])
1994
61.9k
      return;
1995
1996
274k
  if (JT(b->in_edges->pred) == b)
1997
87.5k
    diffp = &JT(b->in_edges->pred);
1998
186k
  else
1999
186k
    diffp = &JF(b->in_edges->pred);
2000
2001
274k
  at_top = 1;
2002
366k
  for (;;) {
2003
366k
    if (*diffp == NULL)
2004
0
      return;
2005
2006
366k
    if (JF(*diffp) != JF(b))
2007
97.3k
      return;
2008
2009
269k
    if (!SET_MEMBER((*diffp)->dom, b->id))
2010
4.86k
      return;
2011
2012
264k
    if ((*diffp)->val[A_ATOM] != val)
2013
171k
      break;
2014
2015
92.7k
    diffp = &JT(*diffp);
2016
92.7k
    at_top = 0;
2017
92.7k
  }
2018
171k
  samep = &JT(*diffp);
2019
185k
  for (;;) {
2020
185k
    if (*samep == NULL)
2021
0
      return;
2022
2023
185k
    if (JF(*samep) != JF(b))
2024
166k
      return;
2025
2026
19.1k
    if (!SET_MEMBER((*samep)->dom, b->id))
2027
4.23k
      return;
2028
2029
14.9k
    if ((*samep)->val[A_ATOM] == val)
2030
862
      break;
2031
2032
    /* XXX Need to check that there are no data dependencies
2033
       between diffp and samep.  Currently, the code generator
2034
       will not produce such dependencies. */
2035
14.0k
    samep = &JT(*samep);
2036
14.0k
  }
2037
#ifdef notdef
2038
  /* XXX This doesn't cover everything. */
2039
  for (i = 0; i < N_ATOMS; ++i)
2040
    if ((*samep)->val[i] != pred->val[i])
2041
      return;
2042
#endif
2043
  /* Pull up the node. */
2044
862
  pull = *samep;
2045
862
  *samep = JT(pull);
2046
862
  JT(pull) = *diffp;
2047
2048
  /*
2049
   * At the top of the chain, each predecessor needs to point at the
2050
   * pulled up node.  Inside the chain, there is only one predecessor
2051
   * to worry about.
2052
   */
2053
862
  if (at_top) {
2054
2.35k
    for (ep = b->in_edges; ep != 0; ep = ep->next) {
2055
1.54k
      if (JT(ep->pred) == b)
2056
792
        JT(ep->pred) = pull;
2057
749
      else
2058
749
        JF(ep->pred) = pull;
2059
1.54k
    }
2060
812
  }
2061
50
  else
2062
50
    *diffp = pull;
2063
2064
  /*
2065
   * XXX - this is one of the operations that happens when the
2066
   * optimizer gets into one of those infinite loops.
2067
   */
2068
862
  opt_state->done = 0;
2069
2070
  /*
2071
   * Recompute dominator sets as control flow graph has changed.
2072
   */
2073
862
  find_dom(opt_state, root);
2074
862
}
2075
2076
static void
2077
opt_blks(opt_state_t *opt_state, struct icode *ic, int do_stmts)
2078
51.1k
{
2079
51.1k
  int i, maxlevel;
2080
51.1k
  struct block *p;
2081
2082
51.1k
  init_val(opt_state);
2083
51.1k
  maxlevel = ic->root->level;
2084
2085
51.1k
  find_inedges(opt_state, ic->root);
2086
542k
  for (i = maxlevel; i >= 0; --i)
2087
1.13M
    for (p = opt_state->levels[i]; p; p = p->link)
2088
641k
      opt_blk(opt_state, p, do_stmts);
2089
2090
51.1k
  if (do_stmts)
2091
    /*
2092
     * No point trying to move branches; it can't possibly
2093
     * make a difference at this point.
2094
     *
2095
     * XXX - this might be after we detect a loop where
2096
     * we were just looping infinitely moving branches
2097
     * in such a fashion that we went through two or more
2098
     * versions of the machine code, eventually returning
2099
     * to the first version.  (We're really not doing a
2100
     * full loop detection, we're just testing for two
2101
     * passes in a row where we do nothing but
2102
     * move branches.)
2103
     */
2104
23.8k
    return;
2105
2106
  /*
2107
   * Is this what the BPF+ paper describes in sections 6.1.1,
2108
   * 6.1.2, and 6.1.3?
2109
   */
2110
336k
  for (i = 1; i <= maxlevel; ++i) {
2111
695k
    for (p = opt_state->levels[i]; p; p = p->link) {
2112
386k
      opt_j(opt_state, &p->et);
2113
386k
      opt_j(opt_state, &p->ef);
2114
386k
    }
2115
308k
  }
2116
2117
27.3k
  find_inedges(opt_state, ic->root);
2118
336k
  for (i = 1; i <= maxlevel; ++i) {
2119
695k
    for (p = opt_state->levels[i]; p; p = p->link) {
2120
386k
      or_pullup(opt_state, p, ic->root);
2121
386k
      and_pullup(opt_state, p, ic->root);
2122
386k
    }
2123
308k
  }
2124
27.3k
}
2125
2126
static inline void
2127
link_inedge(struct edge *parent, struct block *child)
2128
1.87M
{
2129
1.87M
  parent->next = child->in_edges;
2130
1.87M
  child->in_edges = parent;
2131
1.87M
}
2132
2133
static void
2134
find_inedges(opt_state_t *opt_state, const struct block *root)
2135
78.4k
{
2136
78.4k
  u_int i;
2137
78.4k
  int level;
2138
78.4k
  struct block *b;
2139
2140
1.45M
  for (i = 0; i < opt_state->n_blocks; ++i)
2141
1.37M
    opt_state->blocks[i]->in_edges = 0;
2142
2143
  /*
2144
   * Traverse the graph, adding each edge to the predecessor
2145
   * list of its successors.  Skip the leaves (i.e. level 0).
2146
   */
2147
827k
  for (level = root->level; level > 0; --level) {
2148
1.68M
    for (b = opt_state->levels[level]; b != 0; b = b->link) {
2149
939k
      link_inedge(&b->et, JT(b));
2150
939k
      link_inedge(&b->ef, JF(b));
2151
939k
    }
2152
748k
  }
2153
78.4k
}
2154
2155
static void
2156
opt_root(struct block **b)
2157
8.39k
{
2158
8.39k
  struct slist *tmp, *s;
2159
2160
8.39k
  s = (*b)->stmts;
2161
8.39k
  (*b)->stmts = 0;
2162
10.2k
  while (BPF_CLASS((*b)->s.code) == BPF_JMP && JT(*b) == JF(*b))
2163
1.89k
    *b = JT(*b);
2164
2165
8.39k
  tmp = (*b)->stmts;
2166
8.39k
  if (tmp != 0)
2167
134
    sappend(s, tmp);
2168
8.39k
  (*b)->stmts = s;
2169
2170
  /*
2171
   * If the root node is a return, then there is no
2172
   * point executing any statements (since the bpf machine
2173
   * has no side effects).
2174
   */
2175
8.39k
  if (BPF_CLASS((*b)->s.code) == BPF_RET)
2176
4.15k
    (*b)->stmts = 0;
2177
8.39k
}
2178
2179
static void
2180
opt_loop(opt_state_t *opt_state, struct icode *ic, int do_stmts)
2181
16.9k
{
2182
2183
#ifdef BDEBUG
2184
  if (pcap_optimizer_debug > 1 || pcap_print_dot_graph) {
2185
    printf("%s(root, %d) begin\n", __func__, do_stmts);
2186
    opt_dump(opt_state, ic);
2187
  }
2188
#endif
2189
2190
  /*
2191
   * XXX - optimizer loop detection.
2192
   */
2193
16.9k
  int loop_count = 0;
2194
51.1k
  for (;;) {
2195
    /*
2196
     * XXX - optimizer loop detection.
2197
     */
2198
51.1k
    opt_state->non_branch_movement_performed = 0;
2199
51.1k
    opt_state->done = 1;
2200
51.1k
    find_levels(opt_state, ic);
2201
51.1k
    find_dom(opt_state, ic->root);
2202
51.1k
    find_closure(opt_state, ic->root);
2203
51.1k
    find_ud(opt_state, ic->root);
2204
51.1k
    find_edom(opt_state, ic->root);
2205
51.1k
    opt_blks(opt_state, ic, do_stmts);
2206
#ifdef BDEBUG
2207
    if (pcap_optimizer_debug > 1 || pcap_print_dot_graph) {
2208
      printf("%s(root, %d) bottom, done=%d\n", __func__, do_stmts, opt_state->done);
2209
      opt_dump(opt_state, ic);
2210
    }
2211
#endif
2212
2213
    /*
2214
     * Was anything done in this optimizer pass?
2215
     */
2216
51.1k
    if (opt_state->done) {
2217
      /*
2218
       * No, so we've reached a fixed point.
2219
       * We're done.
2220
       */
2221
16.7k
      break;
2222
16.7k
    }
2223
2224
    /*
2225
     * XXX - was anything done other than branch movement
2226
     * in this pass?
2227
     */
2228
34.4k
    if (opt_state->non_branch_movement_performed) {
2229
      /*
2230
       * Yes.  Clear any loop-detection counter;
2231
       * we're making some form of progress (assuming
2232
       * we can't get into a cycle doing *other*
2233
       * optimizations...).
2234
       */
2235
22.5k
      loop_count = 0;
2236
22.5k
    } else {
2237
      /*
2238
       * No - increment the counter, and quit if
2239
       * it's up to 100.
2240
       */
2241
11.8k
      loop_count++;
2242
11.8k
      if (loop_count >= 100) {
2243
        /*
2244
         * We've done nothing but branch movement
2245
         * for 100 passes; we're probably
2246
         * in a cycle and will never reach a
2247
         * fixed point.
2248
         *
2249
         * XXX - yes, we really need a non-
2250
         * heuristic way of detecting a cycle.
2251
         */
2252
95
        opt_state->done = 1;
2253
95
        break;
2254
95
      }
2255
11.8k
    }
2256
34.4k
  }
2257
16.9k
}
2258
2259
/*
2260
 * Optimize the filter code in its dag representation.
2261
 * Return 0 on success, -1 on error.
2262
 */
2263
int
2264
bpf_optimize(struct icode *ic, char *errbuf)
2265
8.45k
{
2266
8.45k
  opt_state_t opt_state;
2267
2268
8.45k
  memset(&opt_state, 0, sizeof(opt_state));
2269
8.45k
  opt_state.errbuf = errbuf;
2270
8.45k
  if (setjmp(opt_state.top_ctx)) {
2271
59
    opt_cleanup(&opt_state);
2272
59
    return -1;
2273
59
  }
2274
8.39k
  opt_init(&opt_state, ic);
2275
8.39k
  opt_loop(&opt_state, ic, 0);
2276
8.39k
  opt_loop(&opt_state, ic, 1);
2277
8.39k
  intern_blocks(&opt_state, ic);
2278
#ifdef BDEBUG
2279
  if (pcap_optimizer_debug > 1 || pcap_print_dot_graph) {
2280
    printf("after intern_blocks()\n");
2281
    opt_dump(&opt_state, ic);
2282
  }
2283
#endif
2284
8.39k
  opt_root(&ic->root);
2285
#ifdef BDEBUG
2286
  if (pcap_optimizer_debug > 1 || pcap_print_dot_graph) {
2287
    printf("after opt_root()\n");
2288
    opt_dump(&opt_state, ic);
2289
  }
2290
#endif
2291
8.39k
  opt_cleanup(&opt_state);
2292
8.39k
  return 0;
2293
8.45k
}
2294
2295
static void
2296
make_marks(struct icode *ic, struct block *p)
2297
686k
{
2298
686k
  if (!isMarked(ic, p)) {
2299
354k
    Mark(ic, p);
2300
354k
    if (BPF_CLASS(p->s.code) != BPF_RET) {
2301
337k
      make_marks(ic, JT(p));
2302
337k
      make_marks(ic, JF(p));
2303
337k
    }
2304
354k
  }
2305
686k
}
2306
2307
/*
2308
 * Mark code array such that isMarked(ic->cur_mark, i) is true
2309
 * only for nodes that are alive.
2310
 */
2311
static void
2312
mark_code(struct icode *ic)
2313
10.7k
{
2314
10.7k
  ic->cur_mark += 1;
2315
10.7k
  make_marks(ic, ic->root);
2316
10.7k
}
2317
2318
// Return 1 iff opcode is valid and uses the 'k' field.
2319
bool
2320
pcapint_opcode_without_k(const uint16_t opcode)
2321
9.67k
{
2322
9.67k
  static const bool without_k[UINT8_MAX + 1] = {
2323
9.67k
    [BPF_LD   | BPF_W  | BPF_LEN] = true,
2324
9.67k
    [BPF_LDX  | BPF_W  | BPF_LEN] = true,
2325
9.67k
    [BPF_JMP  | BPF_JA          ] = true, // no_optimize == 1
2326
9.67k
    [BPF_JMP  | BPF_JEQ  | BPF_X] = true, // block exit only
2327
9.67k
    [BPF_JMP  | BPF_JGT  | BPF_X] = true, // block exit only
2328
9.67k
    [BPF_JMP  | BPF_JGE  | BPF_X] = true, // block exit only
2329
9.67k
    [BPF_JMP  | BPF_JSET | BPF_X] = true, // block exit only
2330
9.67k
    [BPF_ALU  | BPF_ADD  | BPF_X] = true,
2331
9.67k
    [BPF_ALU  | BPF_SUB  | BPF_X] = true,
2332
9.67k
    [BPF_ALU  | BPF_MUL  | BPF_X] = true,
2333
9.67k
    [BPF_ALU  | BPF_DIV  | BPF_X] = true,
2334
9.67k
    [BPF_ALU  | BPF_OR   | BPF_X] = true,
2335
9.67k
    [BPF_ALU  | BPF_AND  | BPF_X] = true,
2336
9.67k
    [BPF_ALU  | BPF_LSH  | BPF_X] = true,
2337
9.67k
    [BPF_ALU  | BPF_RSH  | BPF_X] = true,
2338
9.67k
    [BPF_ALU  | BPF_NEG         ] = true,
2339
9.67k
    [BPF_ALU  | BPF_MOD  | BPF_X] = true,
2340
9.67k
    [BPF_ALU  | BPF_XOR  | BPF_X] = true,
2341
9.67k
    [BPF_RET  | BPF_A           ] = true,
2342
9.67k
    [BPF_MISC | BPF_TAX         ] = true,
2343
9.67k
    [BPF_MISC | BPF_TXA         ] = true,
2344
9.67k
  };
2345
9.67k
  return opcode <= UINT8_MAX && without_k[(uint8_t)opcode];
2346
9.67k
}
2347
2348
/*
2349
 * True iff the two stmt lists load the same value from the packet into
2350
 * the accumulator.
2351
 */
2352
static int
2353
eq_slist(struct slist *x, struct slist *y)
2354
9.10k
{
2355
14.2k
  for (;;) {
2356
14.2k
    x = this_op(x);
2357
14.2k
    y = this_op(y);
2358
    /*
2359
     * If at least one list has been exhausted, return true iff
2360
     * both lists have been exhausted.
2361
     */
2362
14.2k
    if (! (x && y))
2363
4.09k
      return ! (x || y);
2364
    /*
2365
     * After this_op() neither of the two opcodes is NOP, so the
2366
     * type cast is as safe as in convert_code_r().
2367
     */
2368
10.1k
    if (x->s.code != y->s.code ||
2369
9.67k
        (! pcapint_opcode_without_k((uint16_t)x->s.code) &&
2370
9.54k
         x->s.k != y->s.k))
2371
5.01k
      return 0;
2372
5.16k
    x = x->next;
2373
5.16k
    y = y->next;
2374
5.16k
  }
2375
9.10k
}
2376
2377
static inline int
2378
eq_blk(struct block *b0, struct block *b1)
2379
50.8M
{
2380
50.8M
  if (b0->s.code == b1->s.code &&
2381
49.0M
      b0->s.k == b1->s.k &&
2382
5.70M
      b0->et.succ == b1->et.succ &&
2383
204k
      b0->ef.succ == b1->ef.succ)
2384
9.10k
    return eq_slist(b0->stmts, b1->stmts);
2385
50.8M
  return 0;
2386
50.8M
}
2387
2388
static void
2389
intern_blocks(opt_state_t *opt_state, struct icode *ic)
2390
8.39k
{
2391
8.39k
  struct block *p;
2392
8.39k
  u_int i, j;
2393
8.39k
  int done1;
2394
10.7k
 top:
2395
10.7k
  done1 = 1;
2396
634k
  for (i = 0; i < opt_state->n_blocks; ++i)
2397
623k
    opt_state->blocks[i]->link = 0;
2398
2399
10.7k
  mark_code(ic);
2400
2401
623k
  for (i = opt_state->n_blocks - 1; i != 0; ) {
2402
612k
    --i;
2403
612k
    if (!isMarked(ic, opt_state->blocks[i]))
2404
267k
      continue;
2405
67.0M
    for (j = i + 1; j < opt_state->n_blocks; ++j) {
2406
66.6M
      if (!isMarked(ic, opt_state->blocks[j]))
2407
15.8M
        continue;
2408
50.8M
      if (eq_blk(opt_state->blocks[i], opt_state->blocks[j])) {
2409
3.59k
        opt_state->blocks[i]->link = opt_state->blocks[j]->link ?
2410
3.03k
          opt_state->blocks[j]->link : opt_state->blocks[j];
2411
3.59k
        break;
2412
3.59k
      }
2413
50.8M
    }
2414
344k
  }
2415
634k
  for (i = 0; i < opt_state->n_blocks; ++i) {
2416
623k
    p = opt_state->blocks[i];
2417
623k
    if (JT(p) == NULL)
2418
18.9k
      continue;
2419
604k
    if (JT(p)->link) {
2420
3.99k
      done1 = 0;
2421
3.99k
      JT(p) = JT(p)->link;
2422
3.99k
    }
2423
604k
    if (JF(p)->link) {
2424
3.33k
      done1 = 0;
2425
3.33k
      JF(p) = JF(p)->link;
2426
3.33k
    }
2427
604k
  }
2428
10.7k
  if (!done1)
2429
2.33k
    goto top;
2430
10.7k
}
2431
2432
static void
2433
opt_cleanup(opt_state_t *opt_state)
2434
8.45k
{
2435
8.45k
  free(opt_state->vnode_base);
2436
8.45k
  free(opt_state->vmap);
2437
8.45k
  free(opt_state->edges);
2438
8.45k
  free(opt_state->space);
2439
8.45k
  free(opt_state->levels);
2440
8.45k
  free(opt_state->blocks);
2441
8.45k
}
2442
2443
/*
2444
 * For optimizer errors.
2445
 */
2446
static void PCAP_NORETURN
2447
opt_error(opt_state_t *opt_state, const char *fmt, ...)
2448
59
{
2449
59
  va_list ap;
2450
2451
59
  if (opt_state->errbuf != NULL) {
2452
59
    va_start(ap, fmt);
2453
59
    (void)vsnprintf(opt_state->errbuf,
2454
59
        PCAP_ERRBUF_SIZE, fmt, ap);
2455
59
    va_end(ap);
2456
59
  }
2457
59
  longjmp(opt_state->top_ctx, 1);
2458
  /* NOTREACHED */
2459
#ifdef _AIX
2460
  PCAP_UNREACHABLE
2461
#endif /* _AIX */
2462
59
}
2463
2464
/*
2465
 * Return the number of stmts in 's'.
2466
 */
2467
static u_int
2468
slength(struct slist *s)
2469
8.17M
{
2470
8.17M
  u_int n = 0;
2471
2472
24.0M
  for (; s; s = s->next)
2473
15.8M
    if (s->s.code != NOP)
2474
12.1M
      ++n;
2475
8.17M
  return n;
2476
8.17M
}
2477
2478
/*
2479
 * Return the number of nodes reachable by 'p'.
2480
 * All nodes should be initially unmarked.
2481
 */
2482
static int
2483
count_blocks(struct icode *ic, struct block *p)
2484
281k
{
2485
281k
  if (p == NULL || isMarked(ic, p))
2486
144k
    return 0;
2487
136k
  Mark(ic, p);
2488
136k
  return count_blocks(ic, JT(p)) + count_blocks(ic, JF(p)) + 1;
2489
281k
}
2490
2491
/*
2492
 * Do a depth first search on the flow graph, numbering the
2493
 * the basic blocks, and entering them into the 'blocks' array.`
2494
 */
2495
static void
2496
number_blks_r(opt_state_t *opt_state, struct icode *ic, struct block *p)
2497
281k
{
2498
281k
  u_int n;
2499
2500
281k
  if (p == NULL || isMarked(ic, p))
2501
144k
    return;
2502
2503
136k
  Mark(ic, p);
2504
136k
  n = opt_state->n_blocks++;
2505
136k
  if (opt_state->n_blocks == 0) {
2506
    /*
2507
     * Overflow.
2508
     */
2509
0
    opt_error(opt_state, "filter is too complex to optimize");
2510
0
  }
2511
136k
  p->id = n;
2512
136k
  opt_state->blocks[n] = p;
2513
2514
136k
  number_blks_r(opt_state, ic, JT(p));
2515
136k
  number_blks_r(opt_state, ic, JF(p));
2516
136k
}
2517
2518
/*
2519
 * Return the number of stmts in the flowgraph reachable by 'p'.
2520
 * The nodes should be unmarked before calling.
2521
 *
2522
 * Note that "stmts" means "instructions", and that this includes
2523
 *
2524
 *  side-effect statements in 'p' (slength(p->stmts));
2525
 *
2526
 *  statements in the true branch from 'p' (count_stmts(JT(p)));
2527
 *
2528
 *  statements in the false branch from 'p' (count_stmts(JF(p)));
2529
 *
2530
 *  the conditional jump itself (1);
2531
 *
2532
 *  an extra long jump if the true branch requires it (p->longjt);
2533
 *
2534
 *  an extra long jump if the false branch requires it (p->longjf).
2535
 */
2536
static u_int
2537
count_stmts(struct icode *ic, struct block *p)
2538
10.0M
{
2539
10.0M
  u_int n;
2540
2541
10.0M
  if (p == NULL || isMarked(ic, p))
2542
5.04M
    return 0;
2543
5.02M
  Mark(ic, p);
2544
5.02M
  n = count_stmts(ic, JT(p)) + count_stmts(ic, JF(p));
2545
5.02M
  return slength(p->stmts) + n + 1 + p->longjt + p->longjf;
2546
10.0M
}
2547
2548
/*
2549
 * Allocate memory.  All allocation is done before optimization
2550
 * is begun.  A linear bound on the size of all data structures is computed
2551
 * from the total number of blocks and/or statements.
2552
 */
2553
static void
2554
opt_init(opt_state_t *opt_state, struct icode *ic)
2555
8.45k
{
2556
8.45k
  bpf_u_int32 *p;
2557
8.45k
  int i, n, max_stmts;
2558
8.45k
  u_int product;
2559
8.45k
  size_t block_memsize, edge_memsize;
2560
2561
  /*
2562
   * First, count the blocks, so we can allocate an array to map
2563
   * block number to block.  Then, put the blocks into the array.
2564
   */
2565
8.45k
  unMarkAll(ic);
2566
8.45k
  n = count_blocks(ic, ic->root);
2567
8.45k
  opt_state->blocks = (struct block **)calloc(n, sizeof(*opt_state->blocks));
2568
8.45k
  if (opt_state->blocks == NULL)
2569
0
    opt_error(opt_state, "calloc");
2570
8.45k
  unMarkAll(ic);
2571
8.45k
  opt_state->n_blocks = 0;
2572
8.45k
  number_blks_r(opt_state, ic, ic->root);
2573
2574
  /*
2575
   * This "should not happen".
2576
   */
2577
8.45k
  if (opt_state->n_blocks == 0)
2578
0
    opt_error(opt_state, "filter has no instructions; please report this as a libpcap issue");
2579
2580
8.45k
  opt_state->n_edges = 2 * opt_state->n_blocks;
2581
8.45k
  if ((opt_state->n_edges / 2) != opt_state->n_blocks) {
2582
    /*
2583
     * Overflow.
2584
     */
2585
0
    opt_error(opt_state, "filter is too complex to optimize");
2586
0
  }
2587
8.45k
  opt_state->edges = (struct edge **)calloc(opt_state->n_edges, sizeof(*opt_state->edges));
2588
8.45k
  if (opt_state->edges == NULL) {
2589
0
    opt_error(opt_state, "calloc");
2590
0
  }
2591
2592
  /*
2593
   * The number of levels is bounded by the number of nodes.
2594
   */
2595
8.45k
  opt_state->levels = (struct block **)calloc(opt_state->n_blocks, sizeof(*opt_state->levels));
2596
8.45k
  if (opt_state->levels == NULL) {
2597
0
    opt_error(opt_state, "calloc");
2598
0
  }
2599
2600
8.45k
  opt_state->edgewords = opt_state->n_edges / BITS_PER_WORD + 1;
2601
8.45k
  opt_state->nodewords = opt_state->n_blocks / BITS_PER_WORD + 1;
2602
2603
  /*
2604
   * Make sure opt_state->n_blocks * opt_state->nodewords fits
2605
   * in a u_int; we use it as a u_int number-of-iterations
2606
   * value.
2607
   */
2608
8.45k
  product = opt_state->n_blocks * opt_state->nodewords;
2609
8.45k
  if ((product / opt_state->n_blocks) != opt_state->nodewords) {
2610
    /*
2611
     * XXX - just punt and don't try to optimize?
2612
     * In practice, this is unlikely to happen with
2613
     * a normal filter.
2614
     */
2615
0
    opt_error(opt_state, "filter is too complex to optimize");
2616
0
  }
2617
2618
  /*
2619
   * Make sure the total memory required for that doesn't
2620
   * overflow.
2621
   */
2622
8.45k
  block_memsize = (size_t)2 * product * sizeof(*opt_state->space);
2623
8.45k
  if ((block_memsize / product) != 2 * sizeof(*opt_state->space)) {
2624
0
    opt_error(opt_state, "filter is too complex to optimize");
2625
0
  }
2626
2627
  /*
2628
   * Make sure opt_state->n_edges * opt_state->edgewords fits
2629
   * in a u_int; we use it as a u_int number-of-iterations
2630
   * value.
2631
   */
2632
8.45k
  product = opt_state->n_edges * opt_state->edgewords;
2633
8.45k
  if ((product / opt_state->n_edges) != opt_state->edgewords) {
2634
0
    opt_error(opt_state, "filter is too complex to optimize");
2635
0
  }
2636
2637
  /*
2638
   * Make sure the total memory required for that doesn't
2639
   * overflow.
2640
   */
2641
8.45k
  edge_memsize = (size_t)product * sizeof(*opt_state->space);
2642
8.45k
  if (edge_memsize / product != sizeof(*opt_state->space)) {
2643
0
    opt_error(opt_state, "filter is too complex to optimize");
2644
0
  }
2645
2646
  /*
2647
   * Make sure the total memory required for both of them doesn't
2648
   * overflow.
2649
   */
2650
8.45k
  if (block_memsize > SIZE_MAX - edge_memsize) {
2651
0
    opt_error(opt_state, "filter is too complex to optimize");
2652
0
  }
2653
2654
  /* XXX */
2655
8.45k
  opt_state->space = (bpf_u_int32 *)malloc(block_memsize + edge_memsize);
2656
8.45k
  if (opt_state->space == NULL) {
2657
0
    opt_error(opt_state, "malloc");
2658
0
  }
2659
8.45k
  p = opt_state->space;
2660
8.45k
  opt_state->all_dom_sets = p;
2661
144k
  for (i = 0; i < n; ++i) {
2662
136k
    opt_state->blocks[i]->dom = p;
2663
136k
    p += opt_state->nodewords;
2664
136k
  }
2665
8.45k
  opt_state->all_closure_sets = p;
2666
144k
  for (i = 0; i < n; ++i) {
2667
136k
    opt_state->blocks[i]->closure = p;
2668
136k
    p += opt_state->nodewords;
2669
136k
  }
2670
8.45k
  opt_state->all_edge_sets = p;
2671
144k
  for (i = 0; i < n; ++i) {
2672
136k
    struct block *b = opt_state->blocks[i];
2673
2674
136k
    b->et.edom = p;
2675
136k
    p += opt_state->edgewords;
2676
136k
    b->ef.edom = p;
2677
136k
    p += opt_state->edgewords;
2678
136k
    b->et.id = i;
2679
136k
    opt_state->edges[i] = &b->et;
2680
136k
    b->ef.id = opt_state->n_blocks + i;
2681
136k
    opt_state->edges[opt_state->n_blocks + i] = &b->ef;
2682
136k
    b->et.pred = b;
2683
136k
    b->ef.pred = b;
2684
136k
  }
2685
8.45k
  max_stmts = 0;
2686
144k
  for (i = 0; i < n; ++i)
2687
136k
    max_stmts += slength(opt_state->blocks[i]->stmts) + 1;
2688
  /*
2689
   * We allocate at most 3 value numbers per statement,
2690
   * so this is an upper bound on the number of valnodes
2691
   * we'll need.
2692
   */
2693
8.45k
  opt_state->maxval = 3 * max_stmts;
2694
8.45k
  opt_state->vmap = (struct vmapinfo *)calloc(opt_state->maxval, sizeof(*opt_state->vmap));
2695
8.45k
  if (opt_state->vmap == NULL) {
2696
0
    opt_error(opt_state, "calloc");
2697
0
  }
2698
8.45k
  opt_state->vnode_base = (struct valnode *)calloc(opt_state->maxval, sizeof(*opt_state->vnode_base));
2699
8.45k
  if (opt_state->vnode_base == NULL) {
2700
0
    opt_error(opt_state, "calloc");
2701
0
  }
2702
8.45k
}
2703
2704
/*
2705
 * This is only used when supporting optimizer debugging.  It is
2706
 * global state, so do *not* do more than one compile in parallel
2707
 * and expect it to provide meaningful information.
2708
 */
2709
#ifdef BDEBUG
2710
int bids[NBIDS];
2711
#endif
2712
2713
/*
2714
 * Returns true if successful.  Returns false if a branch has
2715
 * an offset that is too large.  If so, we have marked that
2716
 * branch so that on a subsequent iteration, it will be treated
2717
 * properly.
2718
 */
2719
static int
2720
convert_code_r(conv_state_t *conv_state, struct icode *ic, struct block *p)
2721
7.31M
{
2722
7.31M
  struct bpf_insn *dst;
2723
7.31M
  struct slist *src;
2724
7.31M
  u_int slen;
2725
7.31M
  u_int off;
2726
7.31M
  struct slist **offset = NULL;
2727
2728
7.31M
  if (p == NULL || isMarked(ic, p))
2729
3.32M
    return (1);
2730
3.98M
  Mark(ic, p);
2731
2732
3.98M
  if (convert_code_r(conv_state, ic, JF(p)) == 0)
2733
682k
    return (0);
2734
3.30M
  if (convert_code_r(conv_state, ic, JT(p)) == 0)
2735
293k
    return (0);
2736
2737
3.01M
  slen = slength(p->stmts);
2738
3.01M
  dst = conv_state->ftail -= (slen + 1 + p->longjt + p->longjf);
2739
    /* inflate length by any extra jumps */
2740
2741
3.01M
  p->offset = (int)(dst - conv_state->fstart);
2742
2743
  /* generate offset[] for convenience  */
2744
3.01M
  if (slen) {
2745
2.18M
    offset = (struct slist **)calloc(slen, sizeof(struct slist *));
2746
2.18M
    if (!offset) {
2747
0
      conv_error(conv_state, "not enough core");
2748
      /*NOTREACHED*/
2749
0
    }
2750
2.18M
  }
2751
3.01M
  src = p->stmts;
2752
7.40M
  for (off = 0; off < slen && src; off++) {
2753
#if 0
2754
    printf("off=%d src=%x\n", off, src);
2755
#endif
2756
4.39M
    offset[off] = src;
2757
4.39M
    src = src->next;
2758
4.39M
  }
2759
2760
3.01M
  off = 0;
2761
8.75M
  for (src = p->stmts; src; src = src->next) {
2762
5.74M
    if (src->s.code == NOP)
2763
1.34M
      continue;
2764
4.39M
    dst->code = (u_short)src->s.code;
2765
4.39M
    dst->k = src->s.k;
2766
2767
    /* fill block-local relative jump */
2768
4.39M
    if (BPF_CLASS(src->s.code) != BPF_JMP || src->s.code == (BPF_JMP|BPF_JA)) {
2769
#if 0
2770
      if (src->s.jt || src->s.jf) {
2771
        free(offset);
2772
        conv_error(conv_state, "illegal jmp destination");
2773
        /*NOTREACHED*/
2774
      }
2775
#endif
2776
4.37M
      goto filled;
2777
4.37M
    }
2778
12.1k
    if (off == slen - 2)  /*???*/
2779
0
      goto filled;
2780
2781
12.1k
      {
2782
12.1k
    u_int i;
2783
12.1k
    int jt, jf;
2784
12.1k
    const char ljerr[] = "%s for block-local relative jump: off=%d";
2785
2786
#if 0
2787
    printf("code=%x off=%d %x %x\n", src->s.code,
2788
      off, src->s.jt, src->s.jf);
2789
#endif
2790
2791
12.1k
    if (!src->s.jt || !src->s.jf) {
2792
0
      free(offset);
2793
0
      conv_error(conv_state, ljerr, "no jmp destination", off);
2794
      /*NOTREACHED*/
2795
0
    }
2796
2797
12.1k
    jt = jf = 0;
2798
310k
    for (i = 0; i < slen; i++) {
2799
297k
      if (offset[i] == src->s.jt) {
2800
12.1k
        if (jt) {
2801
0
          free(offset);
2802
0
          conv_error(conv_state, ljerr, "multiple matches", off);
2803
          /*NOTREACHED*/
2804
0
        }
2805
2806
12.1k
        if (i - off - 1 >= 256) {
2807
0
          free(offset);
2808
0
          conv_error(conv_state, ljerr, "out-of-range jump", off);
2809
          /*NOTREACHED*/
2810
0
        }
2811
12.1k
        dst->jt = (u_char)(i - off - 1);
2812
12.1k
        jt++;
2813
12.1k
      }
2814
297k
      if (offset[i] == src->s.jf) {
2815
12.1k
        if (jf) {
2816
0
          free(offset);
2817
0
          conv_error(conv_state, ljerr, "multiple matches", off);
2818
          /*NOTREACHED*/
2819
0
        }
2820
12.1k
        if (i - off - 1 >= 256) {
2821
0
          free(offset);
2822
0
          conv_error(conv_state, ljerr, "out-of-range jump", off);
2823
          /*NOTREACHED*/
2824
0
        }
2825
12.1k
        dst->jf = (u_char)(i - off - 1);
2826
12.1k
        jf++;
2827
12.1k
      }
2828
297k
    }
2829
12.1k
    if (!jt || !jf) {
2830
0
      free(offset);
2831
0
      conv_error(conv_state, ljerr, "no destination found", off);
2832
      /*NOTREACHED*/
2833
0
    }
2834
12.1k
      }
2835
4.39M
filled:
2836
4.39M
    ++dst;
2837
4.39M
    ++off;
2838
4.39M
  }
2839
3.01M
  if (offset)
2840
2.18M
    free(offset);
2841
2842
#ifdef BDEBUG
2843
  if (dst - conv_state->fstart < NBIDS)
2844
    bids[dst - conv_state->fstart] = p->id + 1;
2845
#endif
2846
3.01M
  dst->code = (u_short)p->s.code;
2847
3.01M
  dst->k = p->s.k;
2848
3.01M
  if (JT(p)) {
2849
    /* number of extra jumps inserted */
2850
2.98M
    u_char extrajmps = 0;
2851
2.98M
    off = JT(p)->offset - (p->offset + slen) - 1;
2852
2.98M
    if (off >= 256) {
2853
        /* offset too large for branch, must add a jump */
2854
217k
        if (p->longjt == 0) {
2855
      /* mark this instruction and retry */
2856
3.92k
      p->longjt++;
2857
3.92k
      return(0);
2858
3.92k
        }
2859
213k
        dst->jt = extrajmps;
2860
213k
        extrajmps++;
2861
213k
        dst[extrajmps].code = BPF_JMP|BPF_JA;
2862
213k
        dst[extrajmps].k = off - extrajmps;
2863
213k
    }
2864
2.76M
    else
2865
2.76M
        dst->jt = (u_char)off;
2866
2.97M
    off = JF(p)->offset - (p->offset + slen) - 1;
2867
2.97M
    if (off >= 256) {
2868
        /* offset too large for branch, must add a jump */
2869
385k
        if (p->longjf == 0) {
2870
      /* mark this instruction and retry */
2871
5.71k
      p->longjf++;
2872
5.71k
      return(0);
2873
5.71k
        }
2874
        /* branch if F to following jump */
2875
        /* if two jumps are inserted, F goes to second one */
2876
380k
        dst->jf = extrajmps;
2877
380k
        extrajmps++;
2878
380k
        dst[extrajmps].code = BPF_JMP|BPF_JA;
2879
380k
        dst[extrajmps].k = off - extrajmps;
2880
380k
    }
2881
2.59M
    else
2882
2.59M
        dst->jf = (u_char)off;
2883
2.97M
  }
2884
3.00M
  return (1);
2885
3.01M
}
2886
2887
2888
/*
2889
 * Convert flowgraph intermediate representation to the
2890
 * BPF array representation.  Set *lenp to the number of instructions.
2891
 *
2892
 * This routine does *NOT* leak the memory pointed to by fp.  It *must
2893
 * not* do free(fp) before returning fp; doing so would make no sense,
2894
 * as the BPF array pointed to by the return value of icode_to_fcode()
2895
 * must be valid - it's being returned for use in a bpf_program structure.
2896
 *
2897
 * If it appears that icode_to_fcode() is leaking, the problem is that
2898
 * the program using pcap_compile() is failing to free the memory in
2899
 * the BPF program when it's done - the leak is in the program, not in
2900
 * the routine that happens to be allocating the memory.  (By analogy, if
2901
 * a program calls fopen() without ever calling fclose() on the FILE *,
2902
 * it will leak the FILE structure; the leak is not in fopen(), it's in
2903
 * the program.)  Change the program to use pcap_freecode() when it's
2904
 * done with the filter program.  See the pcap man page.
2905
 */
2906
struct bpf_insn *
2907
icode_to_fcode(struct icode *ic, struct block *root, u_int *lenp,
2908
    char *errbuf)
2909
8.27k
{
2910
8.27k
  u_int n;
2911
8.27k
  struct bpf_insn *fp;
2912
8.27k
  conv_state_t conv_state;
2913
2914
8.27k
  conv_state.fstart = NULL;
2915
8.27k
  conv_state.errbuf = errbuf;
2916
8.27k
  if (setjmp(conv_state.top_ctx) != 0) {
2917
0
    free(conv_state.fstart);
2918
0
    return NULL;
2919
0
  }
2920
2921
  /*
2922
   * Loop doing convert_code_r() until no branches remain
2923
   * with too-large offsets.
2924
   */
2925
17.9k
  for (;;) {
2926
17.9k
      unMarkAll(ic);
2927
17.9k
      n = count_stmts(ic, root);
2928
2929
17.9k
      fp = (struct bpf_insn *)calloc(n, sizeof(*fp));
2930
17.9k
      if (fp == NULL) {
2931
0
    snprintf(errbuf, PCAP_ERRBUF_SIZE, "calloc");
2932
0
    return NULL;
2933
0
      }
2934
17.9k
      conv_state.fstart = fp;
2935
17.9k
      conv_state.ftail = fp + n;
2936
2937
17.9k
      unMarkAll(ic);
2938
17.9k
      if (convert_code_r(&conv_state, ic, root))
2939
8.27k
    break;
2940
9.63k
      free(fp);
2941
9.63k
  }
2942
2943
8.27k
  *lenp = n;
2944
8.27k
  return fp;
2945
8.27k
}
2946
2947
/*
2948
 * For iconv_to_fconv() errors.
2949
 */
2950
static void PCAP_NORETURN
2951
conv_error(conv_state_t *conv_state, const char *fmt, ...)
2952
0
{
2953
0
  va_list ap;
2954
2955
0
  va_start(ap, fmt);
2956
0
  (void)vsnprintf(conv_state->errbuf,
2957
0
      PCAP_ERRBUF_SIZE, fmt, ap);
2958
0
  va_end(ap);
2959
0
  longjmp(conv_state->top_ctx, 1);
2960
  /* NOTREACHED */
2961
#ifdef _AIX
2962
  PCAP_UNREACHABLE
2963
#endif /* _AIX */
2964
0
}
2965
2966
/*
2967
 * Make a copy of a BPF program and put it in the "fcode" member of
2968
 * a "pcap_t".
2969
 *
2970
 * If we fail to allocate memory for the copy, fill in the "errbuf"
2971
 * member of the "pcap_t" with an error message, and return -1;
2972
 * otherwise, return 0.
2973
 */
2974
int
2975
pcapint_install_bpf_program(pcap_t *p, struct bpf_program *fp)
2976
0
{
2977
0
  size_t prog_size;
2978
2979
  /*
2980
   * Validate the program.
2981
   */
2982
0
  if (!pcapint_validate_filter(fp->bf_insns, fp->bf_len)) {
2983
0
    snprintf(p->errbuf, sizeof(p->errbuf),
2984
0
      "BPF program is not valid");
2985
0
    return (-1);
2986
0
  }
2987
2988
  /*
2989
   * Free up any already installed program.
2990
   */
2991
0
  pcap_freecode(&p->fcode);
2992
2993
0
  prog_size = sizeof(*fp->bf_insns) * fp->bf_len;
2994
0
  p->fcode.bf_len = fp->bf_len;
2995
0
  p->fcode.bf_insns = (struct bpf_insn *)malloc(prog_size);
2996
0
  if (p->fcode.bf_insns == NULL) {
2997
0
    pcapint_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
2998
0
        errno, "malloc");
2999
0
    return (-1);
3000
0
  }
3001
0
  memcpy(p->fcode.bf_insns, fp->bf_insns, prog_size);
3002
0
  return (0);
3003
0
}
3004
3005
#ifdef BDEBUG
3006
static void
3007
dot_dump_node(const struct icode *ic, struct block *block,
3008
    const struct bpf_program *prog, FILE *out)
3009
{
3010
  if (block == NULL || isMarked(ic, block))
3011
    return;
3012
  Mark(ic, block);
3013
3014
  {
3015
    const unsigned icount = slength(block->stmts) + 1 + block->longjt + block->longjf;
3016
    const unsigned noffset = min(block->offset + icount, prog->bf_len);
3017
3018
    fprintf(out, "\tblock%u [label=\"BLOCK%u\\l\\l", block->id, block->id);
3019
    for (unsigned i = block->offset; i < noffset; i++)
3020
      fprintf(out, "%s\\l", bpf_image(prog->bf_insns + i, i));
3021
    fprintf(out, "\"");
3022
  }
3023
3024
  {
3025
    bool tooltip = false;
3026
    tooltip |= IS_KNOWN(block, A_ATOM);
3027
    tooltip |= IS_KNOWN(block, X_ATOM);
3028
    for (unsigned i = 0; i < BPF_MEMWORDS; i++)
3029
      tooltip |= IS_KNOWN(block, i);
3030
3031
    if (tooltip) {
3032
      const char *sep = "";
3033
      fprintf(out, ", tooltip=\"");
3034
      if (IS_KNOWN(block, A_ATOM)) {
3035
        fprintf(out, "val[A]=%d", block->val[A_ATOM]);
3036
        sep = " ";
3037
      }
3038
      if (IS_KNOWN(block, X_ATOM)) {
3039
        fprintf(out, "%sval[X]=%d", sep, block->val[X_ATOM]);
3040
        sep = " ";
3041
      }
3042
      for (unsigned i = 0; i < BPF_MEMWORDS; i++)
3043
        if (IS_KNOWN(block, i)) {
3044
          fprintf(out, "%sval[%d]=%d", sep, i, block->val[i]);
3045
          sep = " ";
3046
        }
3047
      fprintf(out, "\"");
3048
    }
3049
  }
3050
3051
  if (JT(block) == NULL && JF(block) == NULL)
3052
    fprintf(out, ", peripheries=2");
3053
  fprintf(out, "];\n");
3054
3055
  dot_dump_node(ic, JT(block), prog, out);
3056
  dot_dump_node(ic, JF(block), prog, out);
3057
}
3058
3059
static void
3060
dot_dump_edge(const struct icode *ic, struct block *block, FILE *out)
3061
{
3062
  if (block == NULL || isMarked(ic, block))
3063
    return;
3064
  Mark(ic, block);
3065
3066
  if (JT(block))
3067
    fprintf(out, "\t\"block%u\":se -> \"block%u\" [label=\"T\"];\n",
3068
            block->id, JT(block)->id);
3069
  if (JF(block))
3070
    fprintf(out, "\t\"block%u\":sw -> \"block%u\" [label=\"F\"];\n",
3071
            block->id, JF(block)->id);
3072
  dot_dump_edge(ic, JT(block), out);
3073
  dot_dump_edge(ic, JF(block), out);
3074
}
3075
3076
/*
3077
 * Output the filter program's CFG using Graphviz DOT language.  Show each
3078
 * block with the instructions and every known value index for the registers at
3079
 * exit.  Show all jumps between the blocks.
3080
 *
3081
 * Example DOT output for DLT_EN10MB and the expression "ip src host 1.1.1.1":
3082
 * ----------------
3083
    digraph BPF {
3084
  node [shape=box, fontname="Courier"];
3085
  edge [fontname="Courier"];
3086
  block0 [label="BLOCK0\l\l(000) ldh      [12]\l(001) jeq      #0x800           jt 2  jf 5\l", tooltip="val[A]=1"];
3087
  block1 [label="BLOCK1\l\l(002) ld       [26]\l(003) jeq      #0x1010101       jt 4  jf 5\l", tooltip="val[A]=3"];
3088
  block2 [label="BLOCK2\l\l(004) ret      #262144\l", tooltip="val[A]=3", peripheries=2];
3089
  block3 [label="BLOCK3\l\l(005) ret      #0\l", peripheries=2];
3090
  "block0":se -> "block1" [label="T"];
3091
  "block0":sw -> "block3" [label="F"];
3092
  "block1":se -> "block2" [label="T"];
3093
  "block1":sw -> "block3" [label="F"];
3094
    }
3095
 * ----------------
3096
 * After installing Graphviz from a package or directly from [1], save the DOT
3097
 * output as bpf.dot and run `dot -Tpng -O bpf.dot' to produce an image.
3098
 * Alternatively, use XDot to browse .dot files directly or BPF Exam [2] to see
3099
 * multiple CFGs on one web page.
3100
 *
3101
 * 1: https://www.graphviz.org/
3102
 * 2: https://www.tcpdump.org/bpfexam/
3103
 */
3104
static void
3105
dot_dump(struct icode *ic, const struct bpf_program *f, FILE *out)
3106
{
3107
  /*
3108
   * Do not specify "strict" because in opt_loop() a graph can have two
3109
   * edges between the same pair of nodes, e.g. after "JF(b) = JT(b);".
3110
   */
3111
  fprintf(out, "digraph BPF {\n");
3112
  fprintf(out, "\tnode [shape=box, fontname=\"Courier\"];\n");
3113
  fprintf(out, "\tedge [fontname=\"Courier\"];\n");
3114
  unMarkAll(ic);
3115
  dot_dump_node(ic, ic->root, f, out);
3116
  unMarkAll(ic);
3117
  dot_dump_edge(ic, ic->root, out);
3118
  fprintf(out, "}\n");
3119
}
3120
3121
static void
3122
opt_dump(opt_state_t *opt_state, struct icode *ic)
3123
{
3124
  memset(bids, 0, sizeof(bids));
3125
  char errbuf[PCAP_ERRBUF_SIZE];
3126
  struct bpf_program f;
3127
  f.bf_insns = icode_to_fcode(ic, ic->root, &f.bf_len, errbuf);
3128
  if (f.bf_insns == NULL)
3129
    opt_error(opt_state, "%s: icode_to_fcode failed: %s", __func__, errbuf);
3130
3131
  /*
3132
   * If the CFG, in DOT format, is requested, output it rather than
3133
   * the code that would be generated from that graph.
3134
   */
3135
  if (pcap_print_dot_graph)
3136
    dot_dump(ic, &f, stdout);
3137
  else {
3138
    bpf_dump(&f, 1);
3139
    putchar('\n');
3140
  }
3141
  free(f.bf_insns);
3142
}
3143
#endif