github.com/cilium/ebpf@v0.16.0/cmd/bpf2go/gen/types.go (about)

     1  package gen
     2  
     3  import (
     4  	"github.com/cilium/ebpf"
     5  	"github.com/cilium/ebpf/btf"
     6  )
     7  
     8  // CollectGlobalTypes finds all types which are used in the global scope.
     9  //
    10  // This currently includes the types of map keys and values.
    11  func CollectGlobalTypes(spec *ebpf.CollectionSpec) []btf.Type {
    12  	var types []btf.Type
    13  	for _, typ := range collectMapTypes(spec.Maps) {
    14  		switch btf.UnderlyingType(typ).(type) {
    15  		case *btf.Datasec:
    16  			// Avoid emitting .rodata, .bss, etc. for now. We might want to
    17  			// name these types differently, etc.
    18  			continue
    19  
    20  		case *btf.Int:
    21  			// Don't emit primitive types by default.
    22  			continue
    23  		}
    24  
    25  		types = append(types, typ)
    26  	}
    27  
    28  	return types
    29  }
    30  
    31  // collectMapTypes returns a list of all types used as map keys or values.
    32  func collectMapTypes(maps map[string]*ebpf.MapSpec) []btf.Type {
    33  	var result []btf.Type
    34  	for _, m := range maps {
    35  		if m.Key != nil && m.Key.TypeName() != "" {
    36  			result = append(result, m.Key)
    37  		}
    38  
    39  		if m.Value != nil && m.Value.TypeName() != "" {
    40  			result = append(result, m.Value)
    41  		}
    42  	}
    43  	return result
    44  }