github.com/hirochachacha/plua@v0.0.0-20170217012138-c82f520cc725/fuzz.go (about)

     1  // +build gofuzz
     2  
     3  package plua
     4  
     5  import (
     6  	"io/ioutil"
     7  	"os"
     8  
     9  	"github.com/hirochachacha/plua/compiler"
    10  	"github.com/hirochachacha/plua/compiler/ast/printer"
    11  	"github.com/hirochachacha/plua/compiler/parser"
    12  	"github.com/hirochachacha/plua/object"
    13  	"github.com/hirochachacha/plua/runtime"
    14  	"github.com/hirochachacha/plua/stdlib"
    15  )
    16  
    17  func Fuzz(data []byte) int {
    18  	f, err := ioutil.TempFile("", "plua")
    19  	if err != nil {
    20  		return 0
    21  	}
    22  	defer os.Remove(f.Name())
    23  	defer f.Close()
    24  
    25  	_, err = f.Write(data)
    26  	if err != nil {
    27  		return 0
    28  	}
    29  
    30  	var text bool
    31  
    32  	if ast, err := parser.ParseFile(f.Name(), parser.ParseComments); err == nil {
    33  		tmp, err := ioutil.TempFile("", "plua")
    34  		if err != nil {
    35  			return 0
    36  		}
    37  		defer os.Remove(tmp.Name())
    38  		defer tmp.Close()
    39  
    40  		err = printer.Fprint(tmp, ast)
    41  		if err != nil {
    42  			panic(err)
    43  		}
    44  
    45  		_, err = parser.ParseFile(tmp.Name(), parser.ParseComments)
    46  		if err != nil {
    47  			panic(err)
    48  		}
    49  
    50  		text = true
    51  	}
    52  
    53  	c := compiler.NewCompiler()
    54  
    55  	proto, err := c.CompileFile(f.Name(), compiler.Either)
    56  	if err != nil {
    57  		if text {
    58  			panic(err)
    59  		}
    60  		return 0
    61  	}
    62  
    63  	err = object.FprintProto(ioutil.Discard, proto)
    64  	if err != nil {
    65  		panic(err)
    66  	}
    67  
    68  	p := runtime.NewProcess()
    69  
    70  	p.Require("", stdlib.Open)
    71  
    72  	_, err = p.Exec(proto)
    73  	if err != nil {
    74  		err = object.FprintError(ioutil.Discard, err)
    75  		if err != nil {
    76  			panic(err)
    77  		}
    78  
    79  		return 0
    80  	}
    81  
    82  	return 1
    83  }