fuzz_test.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright (C) 2015 The Protocol Authors.
  2. // +build gofuzz
  3. package protocol
  4. import (
  5. "encoding/binary"
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "strings"
  10. "testing"
  11. "testing/quick"
  12. )
  13. // This can be used to generate a corpus of valid messages as a starting point
  14. // for the fuzzer.
  15. func TestGenerateCorpus(t *testing.T) {
  16. t.Skip("Use to generate initial corpus only")
  17. n := 0
  18. check := func(idx IndexMessage) bool {
  19. for i := range idx.Options {
  20. if len(idx.Options[i].Key) > 64 {
  21. idx.Options[i].Key = idx.Options[i].Key[:64]
  22. }
  23. }
  24. hdr := header{
  25. version: 0,
  26. msgID: 42,
  27. msgType: messageTypeIndex,
  28. compression: false,
  29. }
  30. msgBs := idx.MustMarshalXDR()
  31. buf := make([]byte, 8)
  32. binary.BigEndian.PutUint32(buf, encodeHeader(hdr))
  33. binary.BigEndian.PutUint32(buf[4:], uint32(len(msgBs)))
  34. buf = append(buf, msgBs...)
  35. ioutil.WriteFile(fmt.Sprintf("testdata/corpus/test-%03d.xdr", n), buf, 0644)
  36. n++
  37. return true
  38. }
  39. if err := quick.Check(check, &quick.Config{MaxCount: 1000}); err != nil {
  40. t.Fatal(err)
  41. }
  42. }
  43. // Tests any crashers found by the fuzzer, for closer investigation.
  44. func TestCrashers(t *testing.T) {
  45. testFiles(t, "testdata/crashers")
  46. }
  47. // Tests the entire corpus, which should PASS before the fuzzer starts
  48. // fuzzing.
  49. func TestCorpus(t *testing.T) {
  50. testFiles(t, "testdata/corpus")
  51. }
  52. func testFiles(t *testing.T, dir string) {
  53. fd, err := os.Open(dir)
  54. if err != nil {
  55. t.Fatal(err)
  56. }
  57. crashers, err := fd.Readdirnames(-1)
  58. if err != nil {
  59. t.Fatal(err)
  60. }
  61. for _, name := range crashers {
  62. if strings.HasSuffix(name, ".output") {
  63. continue
  64. }
  65. if strings.HasSuffix(name, ".quoted") {
  66. continue
  67. }
  68. t.Log(name)
  69. crasher, err := ioutil.ReadFile(dir + "/" + name)
  70. if err != nil {
  71. t.Fatal(err)
  72. }
  73. Fuzz(crasher)
  74. }
  75. }