Coverage Report

Created: 2026-09-03 06:05

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