github.com/cilium/ebpf@v0.15.1-0.20240517100537-8079b37aa138/btf/fuzz_test.go (about)

     1  package btf
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/binary"
     6  	"fmt"
     7  	"io"
     8  	"testing"
     9  
    10  	"github.com/cilium/ebpf/internal"
    11  )
    12  
    13  func FuzzSpec(f *testing.F) {
    14  	var buf bytes.Buffer
    15  	err := binary.Write(&buf, internal.NativeEndian, &btfHeader{
    16  		Magic:   btfMagic,
    17  		Version: 1,
    18  		HdrLen:  uint32(binary.Size(btfHeader{})),
    19  	})
    20  	if err != nil {
    21  		f.Fatal(err)
    22  	}
    23  	f.Add(buf.Bytes())
    24  	f.Fuzz(func(t *testing.T, data []byte) {
    25  		if len(data) < binary.Size(btfHeader{}) {
    26  			t.Skip("data is too short")
    27  		}
    28  
    29  		spec, err := loadRawSpec(bytes.NewReader(data), internal.NativeEndian, nil)
    30  		if err != nil {
    31  			if spec != nil {
    32  				t.Fatal("spec is not nil")
    33  			}
    34  			return
    35  		}
    36  
    37  		if spec == nil {
    38  			t.Fatal("spec is nil")
    39  		}
    40  
    41  		iter := spec.Iterate()
    42  		for iter.Next() {
    43  			fmt.Fprintf(io.Discard, "%+10v", iter.Type)
    44  		}
    45  	})
    46  }
    47  
    48  func FuzzExtInfo(f *testing.F) {
    49  	var buf bytes.Buffer
    50  	err := binary.Write(&buf, internal.NativeEndian, &btfExtHeader{
    51  		Magic:   btfMagic,
    52  		Version: 1,
    53  		HdrLen:  uint32(binary.Size(btfExtHeader{})),
    54  	})
    55  	if err != nil {
    56  		f.Fatal(err)
    57  	}
    58  	f.Add(buf.Bytes(), []byte("\x00foo\x00barfoo\x00"))
    59  
    60  	f.Fuzz(func(t *testing.T, data, strings []byte) {
    61  		if len(data) < binary.Size(btfExtHeader{}) {
    62  			t.Skip("data is too short")
    63  		}
    64  
    65  		table, err := readStringTable(bytes.NewReader(strings), nil)
    66  		if err != nil {
    67  			t.Skip("invalid string table")
    68  		}
    69  
    70  		emptySpec := specFromTypes(t, nil)
    71  		emptySpec.strings = table
    72  
    73  		info, err := loadExtInfos(bytes.NewReader(data), internal.NativeEndian, emptySpec)
    74  		if err != nil {
    75  			if info != nil {
    76  				t.Fatal("info is not nil")
    77  			}
    78  		} else if info == nil {
    79  			t.Fatal("info is nil")
    80  		}
    81  	})
    82  }