github.com/inspektor-gadget/inspektor-gadget@v0.28.1/pkg/operators/ebpf/helpers.go (about) 1 // Copyright 2024 The Inspektor Gadget authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package ebpfoperator 16 17 import ( 18 "errors" 19 "fmt" 20 "os" 21 "strings" 22 "sync" 23 24 "github.com/cilium/ebpf" 25 "github.com/cilium/ebpf/btf" 26 ) 27 28 type ( 29 btfTypeValidator func(btf.Type, string) error 30 btfPopulateFunc func(btf.Type, string) error 31 prefixFunc func(string) (string, bool) 32 populateEntry struct { 33 prefixFunc prefixFunc 34 validator btfTypeValidator 35 populateFunc btfPopulateFunc 36 } 37 ) 38 39 func hasPrefix(prefix string) prefixFunc { 40 return func(s string) (string, bool) { 41 return strings.TrimPrefix(s, prefix), strings.HasPrefix(s, prefix) 42 } 43 } 44 45 var ( 46 onceRingbuf sync.Once 47 ringbufAvailable bool 48 ) 49 50 func isRingbufAvailable() bool { 51 onceRingbuf.Do(func() { 52 ringbuf, err := ebpf.NewMap(&ebpf.MapSpec{ 53 Type: ebpf.RingBuf, 54 MaxEntries: uint32(os.Getpagesize()), 55 }) 56 57 ringbuf.Close() 58 59 ringbufAvailable = err == nil 60 }) 61 62 return ringbufAvailable 63 } 64 65 func (i *ebpfInstance) validateGlobalConstVoidPtrVar(t btf.Type, varName string) error { 66 btfVar, ok := t.(*btf.Var) 67 if !ok { 68 return errors.New("not of type btf.Var") 69 } 70 71 if btfVar.Linkage != btf.GlobalVar { 72 return fmt.Errorf("%q is not a global variable", btfVar.Name) 73 } 74 75 btfPtr, ok := btfVar.Type.(*btf.Pointer) 76 if !ok { 77 return fmt.Errorf("%q is not a pointer", btfVar.Name) 78 } 79 80 btfConst, ok := btfPtr.Target.(*btf.Const) 81 if !ok { 82 return fmt.Errorf("%q is not const", btfVar.Name) 83 } 84 85 _, ok = btfConst.Type.(*btf.Void) 86 if !ok { 87 return fmt.Errorf("%q is not a const void pointer", btfVar.Name) 88 } 89 90 return nil 91 }