-
Notifications
You must be signed in to change notification settings - Fork 10
/
manager.go
1721 lines (1514 loc) · 52 KB
/
manager.go
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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package manager
import (
"errors"
"fmt"
"io"
"maps"
"os"
"slices"
"sync"
"time"
"github.com/cilium/ebpf"
"github.com/cilium/ebpf/asm"
"github.com/cilium/ebpf/btf"
"github.com/cilium/ebpf/features"
"golang.org/x/sys/unix"
)
// FunctionExcluder - An interface for types that can be used for `AdditionalExcludedFunctionCollector`
type FunctionExcluder interface {
// ShouldExcludeFunction - Returns true if the function should be excluded
ShouldExcludeFunction(name string, prog *ebpf.ProgramSpec) bool
// CleanCaches - Is called when the manager is done with the excluder (for memory reclaiming for example)
CleanCaches()
}
// Options - Options of a Manager. These options define how a manager should be initialized.
type Options struct {
// ActivatedProbes - List of the probes that should be activated, identified by their identification string.
// If the list is empty, all probes will be activated.
ActivatedProbes []ProbesSelector
// KeepUnmappedProgramSpecs - Defines if the manager should keep unmapped ProgramSpec instances in the collection.
// Enable this feature if you're going to clone one of these ProgramSpec.
KeepUnmappedProgramSpecs bool
// ExcludedFunctions - A list of functions that should not even be verified. This list overrides the ActivatedProbes
// list: since the excluded sections aren't loaded in the kernel, all the probes using those sections will be
// deactivated.
ExcludedFunctions []string
// AdditionalExcludedFunctionCollector - A dynamic function excluder, allowing to exclude functions with a callback.
AdditionalExcludedFunctionCollector FunctionExcluder
// ExcludedMaps - A list of maps that should not be created.
ExcludedMaps []string
// ConstantsEditor - Post-compilation constant edition. See ConstantEditor for more.
ConstantEditors []ConstantEditor
// MapSpecEditor - Pre-loading MapSpec editors.
MapSpecEditors map[string]MapSpecEditor
// VerifierOptions - Defines the log level of the verifier and the size of its log buffer. Set to 0 to disable
// logging and 1 to get a verbose output of the error. Increase the buffer size if the output is truncated.
VerifierOptions ebpf.CollectionOptions
// MapEditors - External map editor. The provided eBPF maps will overwrite the maps of the Manager if their names
// match.
// This is particularly useful to share maps across Managers (and therefore across isolated eBPF programs), without
// having to use the MapRouter indirection. However, this technique only works before the eBPF programs are loaded,
// and therefore before the Manager is started. The keys of the map are the names of the maps to edit, as defined
// in their sections SEC("maps/[name]").
MapEditors map[string]*ebpf.Map
// MapEditorsIgnoreMissingMaps - If MapEditorsIgnoreMissingMaps is set to true, the map edition process will return an
// error if a map was missing in at least one program
MapEditorsIgnoreMissingMaps bool
// MapRouter - External map routing. See MapRoute for more.
MapRouter []MapRoute
// InnerOuterMapSpecs - Defines the mapping between inner and outer maps. See InnerOuterMapSpec for more.
InnerOuterMapSpecs []InnerOuterMapSpec
// TailCallRouter - External tail call routing. See TailCallRoute for more.
TailCallRouter []TailCallRoute
// SymFile - Kernel symbol file. If not provided, the default `/proc/kallsyms` will be used.
SymFile string
// PerfRingBufferSize - Manager-level default value for the perf ring buffers. Defaults to the size of 1 page
// on the system. See PerfMap.PerfRingBuffer for more.
DefaultPerfRingBufferSize int
// Watermark - Manager-level default value for the watermarks of the perf ring buffers.
// See PerfMap.Watermark for more.
DefaultWatermark int
// DefaultKProbeMaxActive - Manager-level default value for the kprobe max active parameter.
// See Probe.MaxActive for more.
DefaultKProbeMaxActive int
// DefaultKprobeAttachMethod - Manager-level default value for the Kprobe attach method. Defaults to AttachKprobeWithPerfEventOpen if unset.
DefaultKprobeAttachMethod KprobeAttachMethod
// DefaultUprobeAttachMethod - Manager-level default value for the Uprobe attach method. Defaults to AttachWithPerfEventOpen if unset.
DefaultUprobeAttachMethod AttachMethod
// ProbeRetry - Defines the number of times that a probe will retry to attach / detach on error.
DefaultProbeRetry uint
// ProbeRetryDelay - Defines the delay to wait before a probe should retry to attach / detach on error.
DefaultProbeRetryDelay time.Duration
// RLimit - The maps & programs provided to the manager might exceed the maximum allowed memory lock.
// `RLIMIT_MEMLOCK` If a limit is provided here it will be applied when the manager is initialized.
RLimit *unix.Rlimit
// KeepKernelBTF - Defines if the kernel types defined in VerifierOptions.Programs.KernelTypes and KernelModuleTypes should be cleaned up
// once the manager is done using them. By default, the manager will clean them up to save up space. DISCLAIMER: if
// your program uses "manager.CloneProgram", you might want to enable "KeepKernelBTF". As a workaround, you can also
// try to strip as much as possible the content of "KernelTypes" to reduce the memory overhead.
KeepKernelBTF bool
// SkipPerfMapReaderStartup - Perf maps whose name is set to true with this option will not have their reader goroutine started when calling the manager.Start() function.
// PerfMap.Start() can then be used to start reading events from the corresponding PerfMap.
SkipPerfMapReaderStartup map[string]bool
// SkipRingbufferReaderStartup - Ringbuffer maps whose name is set to true with this option will not have their reader goroutine started when calling the manager.Start() function.
// RingBuffer.Start() can then be used to start reading events from the corresponding RingBuffer.
SkipRingbufferReaderStartup map[string]bool
// KernelModuleBTFLoadFunc is a function to provide custom loading of BTF for kernel modules on-demand as programs are loaded
KernelModuleBTFLoadFunc func(kmodName string) (*btf.Spec, error)
// BypassEnabled controls whether program bypass is enabled for this manager
BypassEnabled bool
}
// InstructionPatcherFunc - A function that patches the instructions of a program
type InstructionPatcherFunc func(m *Manager) error
// Manager - Helper structure that manages multiple eBPF programs and maps
type Manager struct {
collectionSpec *ebpf.CollectionSpec
collection *ebpf.Collection
options Options
netlinkSocketCache *netlinkSocketCache
state state
stateLock sync.RWMutex
bypassIndexes map[string]uint32
maxBypassIndex uint32
// Probes - List of probes handled by the manager
Probes []*Probe
// Maps - List of maps handled by the manager. PerfMaps should not be defined here, but instead in the PerfMaps
// section
Maps []*Map
// PerfMaps - List of perf ring buffers handled by the manager
PerfMaps []*PerfMap
// RingBuffers - List of perf ring buffers handled by the manager
RingBuffers []*RingBuffer
// DumpHandler - Callback function called when manager.DumpMaps() is called
// and dump the current state (human-readable)
DumpHandler func(w io.Writer, manager *Manager, mapName string, currentMap *ebpf.Map)
// InstructionPatchers - Callback functions called before loading probes, to
// provide user the ability to perform last minute instruction patching.
InstructionPatchers []InstructionPatcherFunc
}
// DumpMaps - Write in the w writer argument human-readable info about eBPF maps
// Dumps the set of maps provided, otherwise dumping all maps with a DumpHandler set.
func (m *Manager) DumpMaps(w io.Writer, maps ...string) error {
m.stateLock.RLock()
defer m.stateLock.RUnlock()
if m.collection == nil || m.state < initialized {
return ErrManagerNotInitialized
}
if m.DumpHandler == nil {
return nil
}
var mapsToDump map[string]struct{}
if len(maps) > 0 {
mapsToDump = make(map[string]struct{})
for _, m := range maps {
mapsToDump[m] = struct{}{}
}
}
needDump := func(name string) bool {
if mapsToDump == nil {
// dump all maps
return true
}
_, found := mapsToDump[name]
return found
}
// Look in the list of maps
for mapName, currentMap := range m.collection.Maps {
if needDump(mapName) {
m.DumpHandler(w, m, mapName, currentMap)
}
}
return nil
}
// getMap - Thread unsafe version of GetMap
func (m *Manager) getMap(name string) (*ebpf.Map, bool, error) {
eBPFMap, ok := m.collection.Maps[name]
if ok {
return eBPFMap, true, nil
}
// Look in the list of maps
for _, managerMap := range m.Maps {
if managerMap.Name == name {
return managerMap.array, true, nil
}
}
if perfMap, found := m.getPerfMap(name); found {
return perfMap.array, true, nil
}
if ringBuffer, found := m.getRingBuffer(name); found {
return ringBuffer.array, true, nil
}
return nil, false, nil
}
// GetMap - Return a pointer to the requested eBPF map
// name: name of the map, as defined by its section SEC("maps/[name]")
func (m *Manager) GetMap(name string) (*ebpf.Map, bool, error) {
m.stateLock.RLock()
defer m.stateLock.RUnlock()
if m.collection == nil || m.state < initialized {
return nil, false, ErrManagerNotInitialized
}
return m.getMap(name)
}
// GetMaps - Return the list of eBPF maps in the manager
func (m *Manager) GetMaps() (map[string]*ebpf.Map, error) {
m.stateLock.RLock()
defer m.stateLock.RUnlock()
if m.collection == nil || m.state < initialized {
return nil, ErrManagerNotInitialized
}
output := make(map[string]*ebpf.Map, len(m.collection.Maps))
for section, m := range m.collection.Maps {
output[section] = m
}
return output, nil
}
// getMapSpec - Thread unsafe version of GetMapSpec
func (m *Manager) getMapSpec(name string) (*ebpf.MapSpec, bool, error) {
eBPFMap, ok := m.collectionSpec.Maps[name]
if ok {
return eBPFMap, true, nil
}
// Look in the list of maps
for _, managerMap := range m.Maps {
if managerMap.Name == name {
return managerMap.arraySpec, true, nil
}
}
if perfMap, found := m.getPerfMap(name); found {
return perfMap.arraySpec, true, nil
}
if ringBuffer, found := m.getRingBuffer(name); found {
return ringBuffer.arraySpec, true, nil
}
return nil, false, nil
}
// GetMapSpec - Return a pointer to the requested eBPF MapSpec. This is useful when duplicating a map.
func (m *Manager) GetMapSpec(name string) (*ebpf.MapSpec, bool, error) {
m.stateLock.RLock()
defer m.stateLock.RUnlock()
if m.collectionSpec == nil || m.state < elfLoaded {
return nil, false, ErrManagerNotELFLoaded
}
return m.getMapSpec(name)
}
// getPerfMap - Thread unsafe version of GetPerfMap
func (m *Manager) getPerfMap(name string) (*PerfMap, bool) {
for _, perfMap := range m.PerfMaps {
if perfMap.Name == name {
return perfMap, true
}
}
return nil, false
}
// GetPerfMap - Select a perf map by its name
func (m *Manager) GetPerfMap(name string) (*PerfMap, bool) {
m.stateLock.RLock()
defer m.stateLock.RUnlock()
return m.getPerfMap(name)
}
// getRingBuffer - Thread unsafe version of GetRingBuffer
func (m *Manager) getRingBuffer(name string) (*RingBuffer, bool) {
for _, ringBuffer := range m.RingBuffers {
if ringBuffer.Name == name {
return ringBuffer, true
}
}
return nil, false
}
// GetRingBuffer - Select a ring buffer by its name
func (m *Manager) GetRingBuffer(name string) (*RingBuffer, bool) {
m.stateLock.RLock()
defer m.stateLock.RUnlock()
return m.getRingBuffer(name)
}
// getProgram - Thread unsafe version of GetProgram
func (m *Manager) getProgram(id ProbeIdentificationPair) ([]*ebpf.Program, bool, error) {
var programs []*ebpf.Program
if id.UID == "" {
for _, probe := range m.Probes {
if probe.EBPFFuncName == id.EBPFFuncName {
programs = append(programs, probe.program)
}
}
if len(programs) > 0 {
return programs, true, nil
}
prog, ok := m.collection.Programs[id.EBPFFuncName]
return []*ebpf.Program{prog}, ok, nil
}
for _, probe := range m.Probes {
if probe.ProbeIdentificationPair == id {
return []*ebpf.Program{probe.program}, true, nil
}
}
return programs, false, nil
}
// GetProgram - Return a pointer to the requested eBPF program
// section: section of the program, as defined by its section SEC("[section]")
// id: unique identifier given to a probe. If UID is empty, then all the programs matching the provided section are
// returned.
func (m *Manager) GetProgram(id ProbeIdentificationPair) ([]*ebpf.Program, bool, error) {
m.stateLock.RLock()
defer m.stateLock.RUnlock()
if m.collection == nil || m.state < initialized {
return nil, false, ErrManagerNotInitialized
}
return m.getProgram(id)
}
// GetPrograms - Return the list of eBPF programs in the manager
func (m *Manager) GetPrograms() (map[string]*ebpf.Program, error) {
m.stateLock.RLock()
defer m.stateLock.RUnlock()
if m.collection == nil || m.state < initialized {
return nil, ErrManagerNotInitialized
}
return maps.Clone(m.collection.Programs), nil
}
// GetMapSpecs - Return the list of eBPF map specs in the manager
func (m *Manager) GetMapSpecs() (map[string]*ebpf.MapSpec, error) {
m.stateLock.RLock()
defer m.stateLock.RUnlock()
if m.collectionSpec == nil || m.state < elfLoaded {
return nil, ErrManagerNotELFLoaded
}
return maps.Clone(m.collectionSpec.Maps), nil
}
// GetProgramSpecs - Return the list of eBPF program specs in the manager
func (m *Manager) GetProgramSpecs() (map[string]*ebpf.ProgramSpec, error) {
m.stateLock.RLock()
defer m.stateLock.RUnlock()
if m.collectionSpec == nil || m.state < elfLoaded {
return nil, ErrManagerNotELFLoaded
}
return maps.Clone(m.collectionSpec.Programs), nil
}
// getProgramSpec - Thread unsafe version of GetProgramSpec
func (m *Manager) getProgramSpec(id ProbeIdentificationPair) ([]*ebpf.ProgramSpec, bool, error) {
var programs []*ebpf.ProgramSpec
if id.UID == "" {
for _, probe := range m.Probes {
if probe.EBPFFuncName == id.EBPFFuncName {
programs = append(programs, probe.programSpec)
}
}
if len(programs) > 0 {
return programs, true, nil
}
prog, ok := m.collectionSpec.Programs[id.EBPFFuncName]
return []*ebpf.ProgramSpec{prog}, ok, nil
}
for _, probe := range m.Probes {
if probe.ProbeIdentificationPair == id {
return []*ebpf.ProgramSpec{probe.programSpec}, true, nil
}
}
return programs, false, nil
}
// GetProgramSpec - Return a pointer to the requested eBPF program spec
// section: section of the program, as defined by its section SEC("[section]")
// id: unique identifier given to a probe. If UID is empty, then the original program spec with the right section in the
// collection spec (if found) is return
func (m *Manager) GetProgramSpec(id ProbeIdentificationPair) ([]*ebpf.ProgramSpec, bool, error) {
m.stateLock.RLock()
defer m.stateLock.RUnlock()
if m.collectionSpec == nil || m.state < elfLoaded {
return nil, false, ErrManagerNotELFLoaded
}
return m.getProgramSpec(id)
}
// getProbe - Thread unsafe version of GetProbe
func (m *Manager) getProbe(id ProbeIdentificationPair) (*Probe, bool) {
for _, managerProbe := range m.Probes {
if managerProbe.ProbeIdentificationPair == id {
return managerProbe, true
}
}
return nil, false
}
// GetProbe - Select a probe by its section and UID
func (m *Manager) GetProbe(id ProbeIdentificationPair) (*Probe, bool) {
m.stateLock.RLock()
defer m.stateLock.RUnlock()
return m.getProbe(id)
}
// LoadELF loads the collection spec from the provided ELF reader
func (m *Manager) LoadELF(elf io.ReaderAt) error {
m.stateLock.Lock()
defer m.stateLock.Unlock()
if m.state >= elfLoaded {
return ErrManagerELFLoaded
}
return m.loadELF(elf)
}
func (m *Manager) loadELF(elf io.ReaderAt) error {
// Load the provided elf buffer
var err error
m.collectionSpec, err = ebpf.LoadCollectionSpecFromReader(elf)
if err != nil {
return err
}
m.state = elfLoaded
return nil
}
// Init - Initialize the manager.
// elf: reader containing the eBPF bytecode, must be nil if LoadELF already called
func (m *Manager) Init(elf io.ReaderAt) error {
return m.InitWithOptions(elf, Options{})
}
// InitWithOptions - Initialize the manager.
// elf: reader containing the eBPF bytecode, must be nil if LoadELF already called
// options: options provided to the manager to configure its initialization
func (m *Manager) InitWithOptions(elf io.ReaderAt, options Options) error {
m.stateLock.Lock()
if m.state > initialized {
m.stateLock.Unlock()
return ErrManagerRunning
}
m.options = options
m.netlinkSocketCache = newNetlinkSocketCache()
if m.options.DefaultPerfRingBufferSize == 0 {
m.options.DefaultPerfRingBufferSize = os.Getpagesize()
}
// perform a quick sanity check on the provided probes and maps
if err := m.sanityCheck(); err != nil {
m.stateLock.Unlock()
return err
}
// set resource limit if requested
if m.options.RLimit != nil {
err := unix.Setrlimit(unix.RLIMIT_MEMLOCK, m.options.RLimit)
if err != nil {
m.stateLock.Unlock()
return fmt.Errorf("couldn't adjust RLIMIT_MEMLOCK: %w", err)
}
}
if m.state < elfLoaded {
if elf == nil {
m.stateLock.Unlock()
return fmt.Errorf("nil ELF reader")
}
if err := m.loadELF(elf); err != nil {
m.stateLock.Unlock()
return err
}
} else if elf != nil {
m.stateLock.Unlock()
return ErrManagerELFLoaded
}
if m.options.AdditionalExcludedFunctionCollector != nil {
for key, prog := range m.collectionSpec.Programs {
if m.options.AdditionalExcludedFunctionCollector.ShouldExcludeFunction(key, prog) {
m.options.ExcludedFunctions = append(m.options.ExcludedFunctions, key)
}
}
m.options.AdditionalExcludedFunctionCollector.CleanCaches()
}
// Remove excluded programs
for _, excludedFuncName := range m.options.ExcludedFunctions {
delete(m.collectionSpec.Programs, excludedFuncName)
}
for i := 0; i < len(m.Probes); {
if slices.Contains(m.options.ExcludedFunctions, m.Probes[i].EBPFFuncName) {
m.Probes = slices.Delete(m.Probes, i, i+1)
} else {
i++
}
}
// Remove ConstantEditors that point to only excluded functions
for i := 0; i < len(m.options.ConstantEditors); {
ce := m.options.ConstantEditors[i]
isSpecific := len(ce.ProbeIdentificationPairs) > 0
// remove excluded ProbeIdentificationPairs
for j := 0; j < len(ce.ProbeIdentificationPairs); {
if slices.Contains(m.options.ExcludedFunctions, ce.ProbeIdentificationPairs[j].EBPFFuncName) {
ce.ProbeIdentificationPairs = slices.Delete(ce.ProbeIdentificationPairs, j, j+1)
} else {
j++
}
}
// was a specific constant editor, but all the probes are excluded
if isSpecific && len(ce.ProbeIdentificationPairs) == 0 {
m.options.ConstantEditors = slices.Delete(m.options.ConstantEditors, i, i+1)
} else {
i++
}
}
// must run before map exclusion in case bypass is disabled
bypassMap, err := m.setupBypass()
if err != nil {
m.stateLock.Unlock()
return err
}
// Remove excluded maps
for _, excludeMapName := range m.options.ExcludedMaps {
delete(m.collectionSpec.Maps, excludeMapName)
}
for i := 0; i < len(m.Maps); {
if slices.Contains(m.options.ExcludedMaps, m.Maps[i].Name) {
m.Maps = slices.Delete(m.Maps, i, i+1)
} else {
i++
}
}
// Match Maps and program specs
if err = m.matchSpecs(); err != nil {
m.stateLock.Unlock()
return err
}
// Configure activated probes
m.activateProbes()
// populate bypass indexes on Probe objects
// this must run after matchSpecs due to CopyProgram handling
if bypassMap != nil {
for _, mProbe := range m.Probes {
if idx, ok := m.bypassIndexes[mProbe.GetEBPFFuncName()]; ok {
mProbe.bypassIndex = idx
mProbe.bypassMap = bypassMap
}
}
}
m.state = initialized
m.stateLock.Unlock()
resetManager := func(m *Manager) {
m.stateLock.Lock()
m.state = reset
m.stateLock.Unlock()
}
// newEditor program constants
if len(options.ConstantEditors) > 0 {
if err = m.editConstants(); err != nil {
resetManager(m)
return err
}
}
// newEditor map spec
if len(options.MapSpecEditors) > 0 {
if err = m.editMapSpecs(); err != nil {
resetManager(m)
return err
}
}
// Setup map routes
if len(options.InnerOuterMapSpecs) > 0 {
for _, ioMapSpec := range options.InnerOuterMapSpecs {
if err = m.editInnerOuterMapSpec(ioMapSpec); err != nil {
resetManager(m)
return err
}
}
}
// Patch instructions
for _, patcher := range m.InstructionPatchers {
if err := patcher(m); err != nil {
resetManager(m)
return err
}
}
if options.KernelModuleBTFLoadFunc != nil {
for _, p := range m.collectionSpec.Programs {
mod, err := p.KernelModule()
if err != nil {
resetManager(m)
return fmt.Errorf("kernel module search for %s: %w", p.AttachTo, err)
}
if mod == "" {
continue
}
if options.VerifierOptions.Programs.KernelModuleTypes == nil {
options.VerifierOptions.Programs.KernelModuleTypes = make(map[string]*btf.Spec)
}
// try default BTF first
modBTF, err := btf.LoadKernelModuleSpec(mod)
if err != nil {
// try callback function next
modBTF, err = options.KernelModuleBTFLoadFunc(mod)
if err != nil {
resetManager(m)
return fmt.Errorf("kernel module BTF load for %s: %w", mod, err)
}
}
options.VerifierOptions.Programs.KernelModuleTypes[mod] = modBTF
}
}
// Load pinned maps and pinned programs to avoid loading them twice
if err = m.loadPinnedObjects(); err != nil {
resetManager(m)
return err
}
// Load eBPF program with the provided verifier options
if err = m.loadCollection(); err != nil {
if m.collection != nil {
m.collection.Close()
}
resetManager(m)
return err
}
return nil
}
func (m *Manager) setupBypass() (*Map, error) {
_, hasBypassMapSpec := m.collectionSpec.Maps[bypassMapName]
if !hasBypassMapSpec {
return nil, nil
}
if !m.options.BypassEnabled {
m.options.ExcludedMaps = append(m.options.ExcludedMaps, bypassMapName)
return nil, nil
}
// start with 1, so we know if programs even have a valid index set
m.maxBypassIndex = 1
const stackOffset = -8
// place a limit on how far we will inject from the start of a program
// otherwise we aren't sure what register we need to save/restore, and it could inflate the number of instructions.
const maxInstructionOffsetFromProgramStart = 1
// setup bypass constants for all programs
m.bypassIndexes = make(map[string]uint32, len(m.collectionSpec.Programs))
for name, p := range m.collectionSpec.Programs {
for i := 0; i < len(p.Instructions); i++ {
ins := p.Instructions[i]
if ins.Reference() != bypassOptInReference {
continue
}
// return error here to ensure we only error on programs that do have a bypass reference
if i > maxInstructionOffsetFromProgramStart {
return nil, fmt.Errorf("unable to inject bypass instructions into program %s: bypass reference occurs too late in program", name)
}
if i > 0 && p.Instructions[i-1].Src != asm.R1 {
return nil, fmt.Errorf("unable to inject bypass instructions into program %s: register other than r1 used before injection point", name)
}
m.bypassIndexes[name] = m.maxBypassIndex
newInsns := append([]asm.Instruction{
asm.Mov.Reg(asm.R6, asm.R1),
// save bypass index to stack
asm.StoreImm(asm.RFP, stackOffset, int64(m.maxBypassIndex), asm.Word),
// store pointer to bypass index
asm.Mov.Reg(asm.R2, asm.RFP),
asm.Add.Imm(asm.R2, stackOffset),
// load map reference
asm.LoadMapPtr(asm.R1, 0).WithReference(bypassMapName),
// bpf_map_lookup_elem
asm.FnMapLookupElem.Call(),
// if ret == 0, jump to `return 0`
{
OpCode: asm.JEq.Op(asm.ImmSource),
Dst: asm.R0,
Offset: 3, // jump TO return
Constant: int64(0),
},
// pointer indirection of result from map lookup
asm.LoadMem(asm.R1, asm.R0, 0, asm.Word),
// if bypass NOT enabled, jump over return
{
OpCode: asm.JEq.Op(asm.ImmSource),
Dst: asm.R1,
Offset: 2, // jump over return on next instruction
Constant: int64(0),
},
asm.Return(),
// zero out used stack slot
asm.StoreImm(asm.RFP, stackOffset, 0, asm.Word),
asm.Mov.Reg(asm.R1, asm.R6),
}, p.Instructions[i+1:]...)
// necessary to keep kernel happy about source information for start of program
newInsns[0] = newInsns[0].WithSource(ins.Source())
p.Instructions = append(p.Instructions[:i], newInsns...)
m.maxBypassIndex += 1
break
}
}
// no programs modified
if m.maxBypassIndex == 1 {
m.options.ExcludedMaps = append(m.options.ExcludedMaps, bypassMapName)
return nil, nil
}
hasPerCPU := false
if err := features.HaveMapType(ebpf.PerCPUArray); err == nil {
hasPerCPU = true
}
bypassMap := &Map{Name: bypassMapName}
m.Maps = append(m.Maps, bypassMap)
if m.options.MapSpecEditors == nil {
m.options.MapSpecEditors = make(map[string]MapSpecEditor)
}
m.options.MapSpecEditors[bypassMapName] = MapSpecEditor{
MaxEntries: m.maxBypassIndex + 1,
EditorFlag: EditMaxEntries,
}
if !hasPerCPU {
// use scalar value for bypass/enable
bypassValue = 1
enableValue = 0
return bypassMap, nil
}
// upgrade map type to per-cpu, if available
specEditor := m.options.MapSpecEditors[bypassMapName]
specEditor.Type = ebpf.PerCPUArray
specEditor.EditorFlag |= EditType
m.options.MapSpecEditors[bypassMapName] = specEditor
// allocate per-cpu slices used for bypass/enable
cpus, err := ebpf.PossibleCPU()
if err != nil {
return nil, err
}
if bypassValue == nil {
bypassValue = makeAndSet(cpus, uint32(1))
}
if enableValue == nil {
enableValue = makeAndSet(cpus, uint32(0))
}
return bypassMap, nil
}
// Start - Attach eBPF programs, start perf ring readers and apply maps and tail calls routing.
func (m *Manager) Start() error {
m.stateLock.Lock()
if m.state < initialized {
m.stateLock.Unlock()
return ErrManagerNotInitialized
}
if m.state >= running {
m.stateLock.Unlock()
return nil
}
if !m.options.KeepKernelBTF {
// release kernel BTF. It should no longer be needed
m.options.VerifierOptions.Programs.KernelTypes = nil
m.options.VerifierOptions.Programs.KernelModuleTypes = nil
}
// clean up tracefs
if err := m.cleanupTraceFS(); err != nil {
m.stateLock.Unlock()
return fmt.Errorf("failed to cleanup tracefs: %w", err)
}
// Start perf ring readers
for _, perfRing := range m.PerfMaps {
if m.options.SkipPerfMapReaderStartup[perfRing.Name] {
continue
}
if err := perfRing.Start(); err != nil {
// Clean up
_ = m.stop(CleanInternal)
m.stateLock.Unlock()
return err
}
}
// Start ring buffer readers
for _, ringBuffer := range m.RingBuffers {
if m.options.SkipRingbufferReaderStartup[ringBuffer.Name] {
continue
}
if err := ringBuffer.Start(); err != nil {
// Clean up
_ = m.stop(CleanInternal)
m.stateLock.Unlock()
return err
}
}
// Attach eBPF programs
for _, probe := range m.Probes {
// ignore the error, they are already collected per probes and will be surfaced by the
// activation validators if needed.
_ = probe.Attach()
}
m.state = running
m.stateLock.Unlock()
// Check probe selectors
var validationErrs error
for _, selector := range m.options.ActivatedProbes {
if err := selector.RunValidator(m); err != nil {
validationErrs = errors.Join(validationErrs, err)
}
}
if validationErrs != nil {
// Clean up
_ = m.Stop(CleanInternal)
return fmt.Errorf("probes activation validation failed: %w", validationErrs)
}
// Handle Maps router
if err := m.UpdateMapRoutes(m.options.MapRouter...); err != nil {
// Clean up
_ = m.Stop(CleanInternal)
return err
}
// Handle Program router
if err := m.UpdateTailCallRoutes(m.options.TailCallRouter...); err != nil {
// Clean up
_ = m.Stop(CleanInternal)
return err
}
return nil
}
func (m *Manager) Pause() error {
m.stateLock.Lock()
defer m.stateLock.Unlock()
if m.state == paused {
return nil
}
if m.state <= initialized {
return ErrManagerNotStarted
}
if !m.options.BypassEnabled {
return nil
}
for _, probe := range m.Probes {
if err := probe.Pause(); err != nil {
return err
}
}
m.state = paused
return nil
}
func (m *Manager) Resume() error {
m.stateLock.Lock()
defer m.stateLock.Unlock()
if m.state == running {
return nil
}
if m.state <= initialized {
return ErrManagerNotStarted
}
if !m.options.BypassEnabled {
return nil
}
for _, probe := range m.Probes {
if err := probe.Resume(); err != nil {
return err
}
}
m.state = running
return nil
}
// Stop - Detach all eBPF programs and stop perf ring readers. The cleanup parameter defines which maps should be closed.
// See MapCleanupType for mode.
func (m *Manager) Stop(cleanup MapCleanupType) error {
m.stateLock.Lock()
defer m.stateLock.Unlock()
if m.state < initialized {
return ErrManagerNotInitialized
}
return m.stop(cleanup)
}
// StopReaders stop the kernel events readers Perf or Ring buffer
func (m *Manager) StopReaders(cleanup MapCleanupType) error {
m.stateLock.Lock()
defer m.stateLock.Unlock()
return m.stopReaders(cleanup)
}
func (m *Manager) stopReaders(cleanup MapCleanupType) error {
var errs []error
// Stop perf ring readers
for _, perfRing := range m.PerfMaps {
if stopErr := perfRing.Stop(cleanup); stopErr != nil {
errs = append(errs, fmt.Errorf("perf ring reader %s couldn't gracefully shut down: %w", perfRing.Name, stopErr))
}
}
// Stop ring buffer readers
for _, ringBuffer := range m.RingBuffers {
if stopErr := ringBuffer.Stop(cleanup); stopErr != nil {
errs = append(errs, fmt.Errorf("ring buffer reader %s couldn't gracefully shut down: %w", ringBuffer.Name, stopErr))
}
}
return errors.Join(errs...)
}
func (m *Manager) stop(cleanup MapCleanupType) error {
var errs []error
errs = append(errs, m.stopReaders(cleanup))
// Detach eBPF programs
for _, probe := range m.Probes {
if stopErr := probe.Stop(); stopErr != nil {
errs = append(errs, fmt.Errorf("program %s couldn't gracefully shut down: %w", probe.ProbeIdentificationPair, stopErr))
}
}
// Close maps
for _, managerMap := range m.Maps {
if closeErr := managerMap.Close(cleanup); closeErr != nil {
errs = append(errs, fmt.Errorf("couldn't gracefully close map %s: %w", managerMap.Name, closeErr))
}
}
// Close all netlink sockets
m.netlinkSocketCache.cleanup()
// Clean up collection
// Note: we might end up closing the same programs or maps multiple times but the library gracefully handles those
// situations. We can't rely only on the collection to close all maps and programs because some pinned objects were
// removed from the collection.
m.collection.Close()
m.state = reset