Coverage Report

Created: 2026-08-14 06:29

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