Coverage Report

Created: 2026-09-28 07:09

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