github.com/google/syzkaller@v0.0.0-20240517125934-c0f1611a36d6/prog/test/fuzz.go (about)

     1  // Copyright 2019 syzkaller project authors. All rights reserved.
     2  // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
     3  
     4  package test
     5  
     6  import (
     7  	"bytes"
     8  	"fmt"
     9  	"math/rand"
    10  
    11  	"github.com/google/syzkaller/prog"
    12  	"github.com/google/syzkaller/sys/targets"
    13  	_ "github.com/google/syzkaller/sys/test/gen" // import the target we use for fuzzing
    14  )
    15  
    16  func FuzzDeserialize(data []byte) int {
    17  	p0, err0 := fuzzTarget.Deserialize(data, prog.NonStrict)
    18  	p1, err1 := fuzzTarget.Deserialize(data, prog.Strict)
    19  	if p0 == nil {
    20  		if p1 != nil {
    21  			panic("NonStrict is stricter than Strict")
    22  		}
    23  		if err0 == nil || err1 == nil {
    24  			panic("no error")
    25  		}
    26  		return 0
    27  	}
    28  	if err0 != nil {
    29  		panic("got program and error")
    30  	}
    31  	data0 := p0.Serialize()
    32  	if p1 != nil {
    33  		if err1 != nil {
    34  			panic("got program and error")
    35  		}
    36  		if !bytes.Equal(data0, p1.Serialize()) {
    37  			panic("got different data")
    38  		}
    39  	}
    40  	p2, err2 := fuzzTarget.Deserialize(data0, prog.NonStrict)
    41  	if err2 != nil {
    42  		panic(fmt.Sprintf("failed to parse serialized: %v\n%s", err2, data0))
    43  	}
    44  	if !bytes.Equal(data0, p2.Serialize()) {
    45  		panic("got different data")
    46  	}
    47  	p3 := p0.Clone()
    48  	if !bytes.Equal(data0, p3.Serialize()) {
    49  		panic("got different data")
    50  	}
    51  	if prodData, err := p0.SerializeForExec(); err == nil {
    52  		if _, err := fuzzTarget.DeserializeExec(prodData, nil); err != nil {
    53  			panic(err)
    54  		}
    55  	}
    56  	p3.Mutate(rand.NewSource(0), 3, fuzzChoiceTable, nil, nil)
    57  	return 0
    58  }
    59  
    60  func FuzzParseLog(data []byte) int {
    61  	if len(fuzzTarget.ParseLog(data)) != 0 {
    62  		return 1
    63  	}
    64  	return 0
    65  }
    66  
    67  var fuzzTarget, fuzzChoiceTable = func() (*prog.Target, *prog.ChoiceTable) {
    68  	target, err := prog.GetTarget(targets.TestOS, targets.TestArch64)
    69  	if err != nil {
    70  		panic(err)
    71  	}
    72  	return target, target.DefaultChoiceTable()
    73  }()