Coverage Report

Created: 2026-08-31 06:07

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