Coverage Report

Created: 2026-10-17 08:12

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