File: seccomp_optimizer.go

package info (click to toggle)
golang-gvisor-gvisor 0.0~20240729.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 21,276 kB
  • sloc: asm: 3,361; ansic: 1,197; cpp: 348; makefile: 92; python: 89; sh: 83
file content (747 lines) | stat: -rw-r--r-- 24,613 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
// Copyright 2023 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package seccomp

import (
	"fmt"
	"strings"
)

// ruleOptimizerFunc is a function type that can optimize a SyscallRule.
// It returns the updated SyscallRule, along with whether any modification
// was made.
type ruleOptimizerFunc func(SyscallRule) (SyscallRule, bool)

// convertSingleCompoundRuleToThatRule replaces `Or` or `And` rules with a
// single branch to just that branch.
func convertSingleCompoundRuleToThatRule[T Or | And](rule SyscallRule) (SyscallRule, bool) {
	if tRule, isT := rule.(T); isT && len(tRule) == 1 {
		return tRule[0], true
	}
	return rule, false
}

// flattenCompoundRules turns compound rules (Or or And) embedded inside
// compound rules of the same type into a flat rule of that type.
func flattenCompoundRules[T Or | And](rule SyscallRule) (SyscallRule, bool) {
	tRule, isT := rule.(T)
	if !isT {
		return rule, false
	}
	anySubT := false
	for _, subRule := range tRule {
		if _, subIsT := subRule.(T); subIsT {
			anySubT = true
			break
		}
	}
	if !anySubT {
		return rule, false
	}
	var newRules []SyscallRule
	for _, subRule := range tRule {
		if subT, subIsT := subRule.(T); subIsT {
			newRules = append(newRules, subT...)
		} else {
			newRules = append(newRules, subRule)
		}
	}
	return SyscallRule(T(newRules)), true
}

// convertMatchAllOrXToMatchAll an Or rule that contains MatchAll to MatchAll.
func convertMatchAllOrXToMatchAll(rule SyscallRule) (SyscallRule, bool) {
	orRule, isOr := rule.(Or)
	if !isOr {
		return rule, false
	}
	for _, subRule := range orRule {
		if _, subIsMatchAll := subRule.(MatchAll); subIsMatchAll {
			return MatchAll{}, true
		}
	}
	return orRule, false
}

// convertMatchAllAndXToX removes MatchAll clauses from And rules.
func convertMatchAllAndXToX(rule SyscallRule) (SyscallRule, bool) {
	andRule, isAnd := rule.(And)
	if !isAnd {
		return rule, false
	}
	hasMatchAll := false
	for _, subRule := range andRule {
		if _, subIsMatchAll := subRule.(MatchAll); subIsMatchAll {
			hasMatchAll = true
			break
		}
	}
	if !hasMatchAll {
		return rule, false
	}
	var newRules []SyscallRule
	for _, subRule := range andRule {
		if _, subIsAny := subRule.(MatchAll); !subIsAny {
			newRules = append(newRules, subRule)
		}
	}
	if len(newRules) == 0 {
		// An `And` rule with zero rules inside is invalid.
		return MatchAll{}, true
	}
	return And(newRules), true
}

// nilInPerArgToAnyValue replaces `nil` values in `PerArg` rules with
// `AnyValue`. This isn't really an optimization, but it simplifies the
// logic of other `PerArg` optimizers to not have to handle the `nil` case
// separately from the `AnyValue` case.
func nilInPerArgToAnyValue(rule SyscallRule) (SyscallRule, bool) {
	perArg, isPerArg := rule.(PerArg)
	if !isPerArg {
		return rule, false
	}
	changed := false
	for argNum, valueMatcher := range perArg {
		if valueMatcher == nil {
			perArg[argNum] = AnyValue{}
			changed = true
		}
	}
	return perArg, changed
}

// convertUselessPerArgToMatchAll looks for `PerArg` rules that match
// anything and replaces them with `MatchAll`.
func convertUselessPerArgToMatchAll(rule SyscallRule) (SyscallRule, bool) {
	perArg, isPerArg := rule.(PerArg)
	if !isPerArg {
		return rule, false
	}
	for _, valueMatcher := range perArg {
		if _, isAnyValue := valueMatcher.(AnyValue); !isAnyValue {
			return rule, false
		}
	}
	return MatchAll{}, true
}

// signature returns a string signature of this `PerArg`.
// This string can be used to identify the behavior of this `PerArg` rule.
func (pa PerArg) signature() string {
	var sb strings.Builder
	for _, valueMatcher := range pa {
		repr := valueMatcher.Repr()
		if strings.ContainsRune(repr, ';') {
			panic(fmt.Sprintf("ValueMatcher %v (type %T) returned representation %q containing illegal character ';'", valueMatcher, valueMatcher, repr))
		}
		sb.WriteString(repr)
		sb.WriteRune(';')
	}
	return sb.String()
}

// deduplicatePerArgs deduplicates PerArg rules with identical matchers.
// This can happen during filter construction, when rules are added across
// multiple files.
func deduplicatePerArgs[T Or | And](rule SyscallRule) (SyscallRule, bool) {
	tRule, isT := rule.(T)
	if !isT || len(tRule) < 2 {
		return rule, false
	}
	knownPerArgs := make(map[string]struct{}, len(tRule))
	newRules := make([]SyscallRule, 0, len(tRule))
	changed := false
	for _, subRule := range tRule {
		subPerArg, subIsPerArg := subRule.(PerArg)
		if !subIsPerArg {
			newRules = append(newRules, subRule)
			continue
		}
		sig := subPerArg.signature()
		if _, isDupe := knownPerArgs[sig]; isDupe {
			changed = true
			continue
		}
		knownPerArgs[sig] = struct{}{}
		newRules = append(newRules, subPerArg)
	}
	if !changed {
		return rule, false
	}
	return SyscallRule(T(newRules)), true
}

// splitMatchers replaces every `splittableValueMatcher` with a
// `splitMatcher` value matcher instead.
// This enables optimizations that are split-aware to run without
// the need to have logic handling this conversion.
func splitMatchers(rule SyscallRule) (SyscallRule, bool) {
	perArg, isPerArg := rule.(PerArg)
	if !isPerArg {
		return rule, false
	}
	changed := false
	for argNum, valueMatcher := range perArg {
		if _, isAlreadySplit := valueMatcher.(splitMatcher); isAlreadySplit {
			continue
		}
		splittableMatcher, isSplittableMatcher := valueMatcher.(splittableValueMatcher)
		if !isSplittableMatcher {
			continue
		}
		perArg[argNum] = splittableMatcher.split()
		changed = true
	}
	return perArg, changed
}

// simplifyHalfValueMatcher may convert a `halfValueMatcher` to a simpler
// (and potentially faster) representation.
func simplifyHalfValueMatcher(hvm halfValueMatcher) halfValueMatcher {
	switch v := hvm.(type) {
	case halfNotSet:
		if v == 0 {
			return halfAnyValue{}
		}
	case halfMaskedEqual:
		switch {
		case v.mask == 0 && v.value == 0:
			return halfAnyValue{}
		case v.mask == 0xffffffff:
			return halfEqualTo(v.value)
		case v.value == 0:
			return halfNotSet(v.mask)
		}
	}
	return hvm
}

// simplifyHalfValueMatchers replace `halfValueMatcher`s with their simplified
// version.
func simplifyHalfValueMatchers(rule SyscallRule) (SyscallRule, bool) {
	perArg, isPerArg := rule.(PerArg)
	if !isPerArg {
		return rule, false
	}
	changed := false
	for i, valueMatcher := range perArg {
		sm, isSplitMatcher := valueMatcher.(splitMatcher)
		if !isSplitMatcher {
			continue
		}
		if newHigh := simplifyHalfValueMatcher(sm.highMatcher); newHigh.Repr() != sm.highMatcher.Repr() {
			sm.highMatcher = newHigh
			perArg[i] = sm
			changed = true
		}
		if newLow := simplifyHalfValueMatcher(sm.lowMatcher); newLow.Repr() != sm.lowMatcher.Repr() {
			sm.lowMatcher = newLow
			perArg[i] = sm
			changed = true
		}
	}
	return perArg, changed
}

// anySplitMatchersToAnyValue converts `splitMatcher`s where both halves
// match any value to a single AnyValue{} rule.
func anySplitMatchersToAnyValue(rule SyscallRule) (SyscallRule, bool) {
	perArg, isPerArg := rule.(PerArg)
	if !isPerArg {
		return rule, false
	}
	changed := false
	for argNum, valueMatcher := range perArg {
		sm, isSplitMatcher := valueMatcher.(splitMatcher)
		if !isSplitMatcher {
			continue
		}
		_, highIsAny := sm.highMatcher.(halfAnyValue)
		_, lowIsAny := sm.lowMatcher.(halfAnyValue)
		if highIsAny && lowIsAny {
			perArg[argNum] = AnyValue{}
			changed = true
		}
	}
	return perArg, changed
}

// invalidValueMatcher is a stand-in `ValueMatcher` with a unique
// representation that doesn't look like any legitimate `ValueMatcher`.
// Calling any method other than `Repr` will panic.
// It is used as an intermediate step for some optimizers.
type invalidValueMatcher struct {
	ValueMatcher
}

// Repr implements `ValueMatcher.Repr`.
func (invalidValueMatcher) Repr() string {
	return "invalidValueMatcher"
}

// invalidHalfValueMatcher is a stand-in `HalfValueMatcher` with a unique
// representation that doesn't look like any legitimate `HalfValueMatcher`.
// Calling any method other than `Repr` will panic.
// It is used as an intermediate step for some optimizers.
type invalidHalfValueMatcher struct {
	halfValueMatcher
}

// Repr implements `HalfValueMatcher.Repr`.
func (invalidHalfValueMatcher) Repr() string {
	return "invalidHalfValueMatcher"
}

// sameStringSet returns whether the given string sets are equal.
func sameStringSet(m1, m2 map[string]struct{}) bool {
	if len(m1) != len(m2) {
		return false
	}
	for k := range m1 {
		if _, found := m2[k]; !found {
			return false
		}
	}
	return true
}

// extractRepeatedMatchers looks for common argument matchers that are
// repeated across all combinations of *other* argument matchers in branches
// of an `Or` rule that contains only `PerArg` rules.
// It removes them from these `PerArg` rules, creates an `Or` of the
// matchers that are repeated across all combinations, and `And`s that
// rule to the rewritten `Or` rule.
// In other words (simplifying `PerArg` to 4 items for simplicity):
//
//	Or{
//		PerArg{A1, B1, C1, D},
//		PerArg{A2, B1, C1, D},
//		PerArg{A1, B2, C2, D},
//		PerArg{A2, B2, C2, D},
//		PerArg{A1, B3, C3, D},
//		PerArg{A2, B3, C3, D},
//	}
//
// becomes (after one pass):
//
//	And{
//		Or{
//			# Note: These will get deduplicated by deduplicatePerArgs
//			PerArg{A1, AnyValue{}, AnyValue{}, AnyValue{}},
//			PerArg{A2, AnyValue{}, AnyValue{}, AnyValue{}},
//			PerArg{A1, AnyValue{}, AnyValue{}, AnyValue{}},
//			PerArg{A2, AnyValue{}, AnyValue{}, AnyValue{}},
//			PerArg{A1, AnyValue{}, AnyValue{}, AnyValue{}},
//			PerArg{A2, AnyValue{}, AnyValue{}, AnyValue{}},
//		},
//		Or{
//			# Note: These will also get deduplicated by deduplicatePerArgs
//			PerArg{AnyValue{}, B1, C1, D},
//			PerArg{AnyValue{}, B1, C1, D},
//			PerArg{AnyValue{}, B2, C2, D},
//			PerArg{AnyValue{}, B2, C2, D},
//			PerArg{AnyValue{}, B3, C3, D},
//			PerArg{AnyValue{}, B3, C3, D},
//		},
//	}
//
// ... then, on the second pass (after deduplication),
// the second inner `Or` rule gets recursively optimized to:
//
//	And{
//		Or{
//			PerArg{A1, AnyValue{}, AnyValue{}, AnyValue{}},
//			PerArg{A2, AnyValue{}, AnyValue{}, AnyValue{}},
//		},
//		And{
//			Or{
//				PerArg{AnyValue{}, AnyValue{}, AnyValue{}, D},
//				PerArg{AnyValue{}, AnyValue{}, AnyValue{}, D},
//				PerArg{AnyValue{}, AnyValue{}, AnyValue{}, D},
//			},
//			Or{
//				PerArg{AnyValue{}, B1, C1, AnyValue{}},
//				PerArg{AnyValue{}, B2, C2, AnyValue{}},
//				PerArg{AnyValue{}, B3, C3, AnyValue{}},
//			},
//		},
//	}
//
// ... which (after other optimizers clean this all up), finally becomes:
//
//	And{
//		Or{
//			PerArg{A1, AnyValue{}, AnyValue{}, AnyValue{}},
//			PerArg{A2, AnyValue{}, AnyValue{}, AnyValue{}},
//		},
//		PerArg{AnyValue{}, AnyValue{}, AnyValue{}, D},
//		Or{
//			PerArg{AnyValue{}, B1, C1, AnyValue{}},
//			PerArg{AnyValue{}, B2, C2, AnyValue{}},
//			PerArg{AnyValue{}, B3, C3, AnyValue{}},
//		},
//	}
//
// ... Turning 24 comparisons into just 9.
func extractRepeatedMatchers(rule SyscallRule) (SyscallRule, bool) {
	orRule, isOr := rule.(Or)
	if !isOr || len(orRule) < 2 {
		return rule, false
	}
	for _, subRule := range orRule {
		if _, subIsPerArg := subRule.(PerArg); !subIsPerArg {
			return rule, false
		}
	}

	// extractData is the result of extracting a matcher at `argNum`.
	type extractData struct {
		// extractedMatcher is the extracted matcher that should be AND'd
		// with the rest.
		extractedMatcher ValueMatcher

		// otherMatchers represents the rest of the matchers after
		// `extractedMatcher` is extracted from a `PerArg`.
		// The matcher that was extracted should be replaced with something
		// that matches any value (i.e. either `AnyValue` or `halfAnyValue`).
		otherMatchers PerArg

		// otherMatchersSig represents the signature of other matchers, with
		// the extracted matcher being replaced with an "invalid" matcher.
		// The "invalid" matcher acts as a token that is equal across all
		// instances of `otherMatchersSig` for the other `PerArg` rules of the
		// `Or` expression.
		// `otherMatchersSig` isn't the same as `otherMatchers.Signature()`,
		// as `otherMatchers` does not contain this "invalid" matcher (it
		// contains a matcher that matches any value instead).
		otherMatchersSig string

		// extractedMatcherIsAnyValue is true iff `extractedMatcher` would
		// match any value thrown at it.
		// If this is the case across all branches of the `Or` expression,
		// the optimization is skipped.
		extractedMatcherIsAnyValue bool

		// otherMatchersAreAllAnyValue is true iff all matchers in
		// `otherMatchers` would match any value thrown at them.
		// If this is the case across all branches of the `Or` expression,
		// the optimization is skipped.
		otherMatchersAreAllAnyValue bool
	}

	allOtherMatchersSigs := make(map[string]struct{}, len(orRule))
	argExprToOtherMatchersSigs := make(map[string]map[string]struct{}, len(orRule))
	for argNum := 0; argNum < len(orRule[0].(PerArg)); argNum++ {
		// Check if `argNum` takes on a set of matchers common for all
		// combinations of all other matchers.
		// We try to extract a common matcher by three ways, which we
		// iterate over here.
		// Each of them returns the result of their extraction attempt,
		// along with a boolean representing whether extraction was
		// possible at all.
		// To "extract" a matcher means to replace it with an "invalid"
		// matcher in the PerArg expression, and checking if their set of
		// signatures is identical for each unique `Repr()` of the extracted
		// matcher. For splittable matcher, we try each half as well.
		// Conceptually (simplify PerArg to 3 arguments for simplicity),
		// if we have:
		//
		//   Or{
		//     PerArg{A, B, C},
		//     PerArg{D, E, F},
		//   }
		//
		// ... then first, we will try:
		//
		//   Or{
		//     PerArg{invalid, B, C}
		//     PerArg{invalid, E, F}
		//   }
		//
		// ... then, assuming both A and D are `splitMatcher`s:
		// we will try:
		//
		//   Or{
		//     PerArg{splitMatcher{invalid, A.lowMatcher}, B, C}
		//     PerArg{splitMatcher{invalid, D.lowMatcher}, E, F}
		//   }
		//
		// ... and finally we will try:
		//
		//   Or{
		//     PerArg{splitMatcher{A.highMatcher, invalid}, B, C}
		//     PerArg{splitMatcher{D.highMatcher, invalid}, E, F}
		//   }
		for _, extractFn := range []func(PerArg) (extractData, bool){
			// Return whole ValueMatcher at a time:
			func(pa PerArg) (extractData, bool) {
				extractedMatcher := pa[argNum]
				_, extractedMatcherIsAnyValue := extractedMatcher.(AnyValue)
				otherMatchers := pa.clone()
				otherMatchers[argNum] = invalidValueMatcher{}
				otherMatchersSig := otherMatchers.signature()
				otherMatchers[argNum] = AnyValue{}
				otherMatchersAreAllAnyValue := true
				for _, valueMatcher := range otherMatchers {
					if _, isAnyValue := valueMatcher.(AnyValue); !isAnyValue {
						otherMatchersAreAllAnyValue = false
						break
					}
				}
				return extractData{
					extractedMatcher:            extractedMatcher,
					otherMatchers:               otherMatchers,
					otherMatchersSig:            otherMatchersSig,
					extractedMatcherIsAnyValue:  extractedMatcherIsAnyValue,
					otherMatchersAreAllAnyValue: otherMatchersAreAllAnyValue,
				}, true
			},
			// Extract a matcher for the high bits only:
			func(pa PerArg) (extractData, bool) {
				split, isSplit := pa[argNum].(splitMatcher)
				if !isSplit {
					return extractData{}, false
				}
				_, extractedMatcherIsAnyValue := split.highMatcher.(halfAnyValue)
				_, lowMatcherIsAnyValue := split.lowMatcher.(halfAnyValue)
				extractedMatcher := high32BitsMatch(split.highMatcher)
				otherMatchers := pa.clone()
				otherMatchers[argNum] = splitMatcher{
					highMatcher: invalidHalfValueMatcher{},
					lowMatcher:  split.lowMatcher,
				}
				otherMatchersSig := otherMatchers.signature()
				otherMatchers[argNum] = low32BitsMatch(split.lowMatcher)
				otherMatchersAreAllAnyValue := lowMatcherIsAnyValue
				for i, valueMatcher := range otherMatchers {
					if i == argNum {
						continue
					}
					if _, isAnyValue := valueMatcher.(AnyValue); !isAnyValue {
						otherMatchersAreAllAnyValue = false
						break
					}
				}
				return extractData{
					extractedMatcher:            extractedMatcher,
					otherMatchers:               otherMatchers,
					otherMatchersSig:            otherMatchersSig,
					extractedMatcherIsAnyValue:  extractedMatcherIsAnyValue,
					otherMatchersAreAllAnyValue: otherMatchersAreAllAnyValue,
				}, true
			},
			// Extract a matcher for the low bits only:
			func(pa PerArg) (extractData, bool) {
				split, isSplit := pa[argNum].(splitMatcher)
				if !isSplit {
					return extractData{}, false
				}
				_, extractedMatcherIsAnyValue := split.lowMatcher.(halfAnyValue)
				_, highMatcherIsAnyValue := split.highMatcher.(halfAnyValue)
				extractedMatcher := low32BitsMatch(split.lowMatcher)
				otherMatchers := pa.clone()
				otherMatchers[argNum] = splitMatcher{
					highMatcher: split.highMatcher,
					lowMatcher:  invalidHalfValueMatcher{},
				}
				otherMatchersSig := otherMatchers.signature()
				otherMatchers[argNum] = high32BitsMatch(split.highMatcher)
				otherMatchersAreAllAnyValue := highMatcherIsAnyValue
				for i, valueMatcher := range otherMatchers {
					if i == argNum {
						continue
					}
					if _, isAnyValue := valueMatcher.(AnyValue); !isAnyValue {
						otherMatchersAreAllAnyValue = false
						break
					}
				}
				return extractData{
					extractedMatcher:            extractedMatcher,
					otherMatchers:               otherMatchers,
					otherMatchersSig:            otherMatchersSig,
					extractedMatcherIsAnyValue:  extractedMatcherIsAnyValue,
					otherMatchersAreAllAnyValue: otherMatchersAreAllAnyValue,
				}, true
			},
		} {
			clear(allOtherMatchersSigs)
			clear(argExprToOtherMatchersSigs)
			allExtractable := true
			allArgNumMatchersAreAnyValue := true
			allOtherMatchersAreAnyValue := true
			for _, subRule := range orRule {
				ed, extractable := extractFn(subRule.(PerArg))
				if allExtractable = allExtractable && extractable; !allExtractable {
					break
				}
				allArgNumMatchersAreAnyValue = allArgNumMatchersAreAnyValue && ed.extractedMatcherIsAnyValue
				allOtherMatchersAreAnyValue = allOtherMatchersAreAnyValue && ed.otherMatchersAreAllAnyValue
				repr := ed.extractedMatcher.Repr()
				allOtherMatchersSigs[ed.otherMatchersSig] = struct{}{}
				if _, reprSeen := argExprToOtherMatchersSigs[repr]; !reprSeen {
					argExprToOtherMatchersSigs[repr] = make(map[string]struct{}, len(orRule))
				}
				argExprToOtherMatchersSigs[repr][ed.otherMatchersSig] = struct{}{}
			}
			if !allExtractable || allArgNumMatchersAreAnyValue || allOtherMatchersAreAnyValue {
				// Cannot optimize.
				continue
			}
			// Now check if each possible repr of `argNum` got the same set of
			// signatures for other matchers as `allOtherMatchersSigs`.
			sameOtherMatchers := true
			for _, omsigs := range argExprToOtherMatchersSigs {
				if !sameStringSet(omsigs, allOtherMatchersSigs) {
					sameOtherMatchers = false
					break
				}
			}
			if !sameOtherMatchers {
				continue
			}
			// We can simplify the rule by extracting `argNum` out.
			// Create two copies of `orRule`: One with only `argNum`,
			// and the other one with all arguments except `argNum`.
			// This will likely contain many duplicates but that's OK,
			// they'll be optimized out by `deduplicatePerArgs`.
			argNumMatch := Or(make([]SyscallRule, len(orRule)))
			otherArgsMatch := Or(make([]SyscallRule, len(orRule)))
			for i, subRule := range orRule {
				ed, _ := extractFn(subRule.(PerArg))
				onlyArg := PerArg{AnyValue{}, AnyValue{}, AnyValue{}, AnyValue{}, AnyValue{}, AnyValue{}, AnyValue{}}
				onlyArg[argNum] = ed.extractedMatcher
				argNumMatch[i] = onlyArg
				otherArgsMatch[i] = ed.otherMatchers
			}
			// Attempt to optimize the "other" arguments:
			otherArgsMatchOpt, _ := extractRepeatedMatchers(otherArgsMatch)
			return And{argNumMatch, otherArgsMatchOpt}, true
		}
	}
	return rule, false
}

// optimizationRun is a stateful struct tracking the state of an optimization
// over a rule. It may not be used concurrently.
type optimizationRun struct {
	// funcs is the list of optimizer functions to run on the rules.
	// Optimizers should be ranked in order of importance, with the most
	// important first.
	// An optimizer will be exhausted before the next one is ever run.
	// Earlier optimizers are re-exhausted if later optimizers cause change.
	funcs []ruleOptimizerFunc

	// recurseFuncs is a list of closures that correspond one-to-one to `funcs`
	// and are suitable for passing to `SyscallRule.Recurse`. They are stored
	// here in order to be allocated once, as opposed to escaping if they were
	// specified directly as argument to `SyscallRule.Recurse`.
	recurseFuncs []func(subRule SyscallRule) SyscallRule

	// changed tracks whether any change has been made in the current pass.
	// It is updated as the optimizer runs.
	changed bool
}

// apply recursively applies `opt.funcs[funcIndex]` to the given `rule`.
// It sets `opt.changed` to true if there has been any change.
func (opt *optimizationRun) apply(rule SyscallRule, funcIndex int) SyscallRule {
	rule.Recurse(opt.recurseFuncs[funcIndex])
	if opt.changed {
		return rule
	}
	rule, opt.changed = opt.funcs[funcIndex](rule)
	return rule
}

// optimize losslessly optimizes a SyscallRule using the `optimizationRun`'s
// optimizer functions.
// It may not be called concurrently.
func (opt *optimizationRun) optimize(rule SyscallRule) SyscallRule {
	opt.recurseFuncs = make([]func(SyscallRule) SyscallRule, len(opt.funcs))
	for i := range opt.funcs {
		funcIndex := i
		opt.recurseFuncs[funcIndex] = func(subRule SyscallRule) SyscallRule {
			return opt.apply(subRule, funcIndex)
		}
	}
	for opt.changed = true; opt.changed; {
		for i := range opt.funcs {
			opt.changed = false
			rule = opt.apply(rule, i)
			if opt.changed {
				break
			}
		}
	}
	return rule
}

// optimizeSyscallRule losslessly optimizes a `SyscallRule`.
func optimizeSyscallRule(rule SyscallRule) SyscallRule {
	return (&optimizationRun{
		funcs: []ruleOptimizerFunc{
			// Convert Or / And rules with a single rule into that single rule.
			convertSingleCompoundRuleToThatRule[Or],
			convertSingleCompoundRuleToThatRule[And],

			// Flatten Or/And rules.
			flattenCompoundRules[Or],
			flattenCompoundRules[And],

			// Handle MatchAll. This is best done after flattening so that we
			// effectively traverse the whole tree to find a MatchAll by just
			// linearly scanning through the first (and only) level of rules.
			convertMatchAllOrXToMatchAll,
			convertMatchAllAndXToX,

			// Replace all `nil` values in `PerArg` to `AnyValue`, to simplify
			// the `PerArg` matchers below.
			nilInPerArgToAnyValue,

			// Deduplicate redundant `PerArg`s in Or and And.
			// This must come after `nilInPerArgToAnyValue` because it does not
			// handle the nil case.
			deduplicatePerArgs[Or],
			deduplicatePerArgs[And],

			// Remove useless `PerArg` matchers.
			// This must come after `nilInPerArgToAnyValue` because it does not
			// handle the nil case.
			convertUselessPerArgToMatchAll,

			// Replace `ValueMatcher`s that are splittable into their split version.
			// Like `nilInPerArgToAnyValue`, this isn't so much an optimization,
			// but allows the matchers below (which are `splitMatcher`-aware) to not
			// have to carry logic to split the matchers they encounter.
			splitMatchers,

			// Replace `halfValueMatcher`s with their simplified version.
			simplifyHalfValueMatchers,

			// Replace `splitMatchers` that match any value with `AnyValue`.
			anySplitMatchersToAnyValue,

			// Extract repeated argument matchers out of `Or` expressions.
			// This must come after `nilInPerArgToAnyValue` because it does not
			// handle the nil case.
			// This should ideally run late in the list because it does a bunch
			// of memory allocations (even in the non-optimizable case), which
			// should be avoided unless there is nothing else left to optimize.
			extractRepeatedMatchers,
		},
	}).optimize(rule)
}