fuzz.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. /*
  2. Copyright 2014 Google Inc. All rights reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package fuzz
  14. import (
  15. "fmt"
  16. "math/rand"
  17. "reflect"
  18. "regexp"
  19. "time"
  20. "github.com/google/gofuzz/bytesource"
  21. "strings"
  22. )
  23. // fuzzFuncMap is a map from a type to a fuzzFunc that handles that type.
  24. type fuzzFuncMap map[reflect.Type]reflect.Value
  25. // Fuzzer knows how to fill any object with random fields.
  26. type Fuzzer struct {
  27. fuzzFuncs fuzzFuncMap
  28. defaultFuzzFuncs fuzzFuncMap
  29. r *rand.Rand
  30. nilChance float64
  31. minElements int
  32. maxElements int
  33. maxDepth int
  34. skipFieldPatterns []*regexp.Regexp
  35. }
  36. // New returns a new Fuzzer. Customize your Fuzzer further by calling Funcs,
  37. // RandSource, NilChance, or NumElements in any order.
  38. func New() *Fuzzer {
  39. return NewWithSeed(time.Now().UnixNano())
  40. }
  41. func NewWithSeed(seed int64) *Fuzzer {
  42. f := &Fuzzer{
  43. defaultFuzzFuncs: fuzzFuncMap{
  44. reflect.TypeOf(&time.Time{}): reflect.ValueOf(fuzzTime),
  45. },
  46. fuzzFuncs: fuzzFuncMap{},
  47. r: rand.New(rand.NewSource(seed)),
  48. nilChance: .2,
  49. minElements: 1,
  50. maxElements: 10,
  51. maxDepth: 100,
  52. }
  53. return f
  54. }
  55. // NewFromGoFuzz is a helper function that enables using gofuzz (this
  56. // project) with go-fuzz (https://github.com/dvyukov/go-fuzz) for continuous
  57. // fuzzing. Essentially, it enables translating the fuzzing bytes from
  58. // go-fuzz to any Go object using this library.
  59. //
  60. // This implementation promises a constant translation from a given slice of
  61. // bytes to the fuzzed objects. This promise will remain over future
  62. // versions of Go and of this library.
  63. //
  64. // Note: the returned Fuzzer should not be shared between multiple goroutines,
  65. // as its deterministic output will no longer be available.
  66. //
  67. // Example: use go-fuzz to test the function `MyFunc(int)` in the package
  68. // `mypackage`. Add the file: "mypacakge_fuzz.go" with the content:
  69. //
  70. // // +build gofuzz
  71. // package mypacakge
  72. // import fuzz "github.com/google/gofuzz"
  73. // func Fuzz(data []byte) int {
  74. // var i int
  75. // fuzz.NewFromGoFuzz(data).Fuzz(&i)
  76. // MyFunc(i)
  77. // return 0
  78. // }
  79. func NewFromGoFuzz(data []byte) *Fuzzer {
  80. return New().RandSource(bytesource.New(data))
  81. }
  82. // Funcs adds each entry in fuzzFuncs as a custom fuzzing function.
  83. //
  84. // Each entry in fuzzFuncs must be a function taking two parameters.
  85. // The first parameter must be a pointer or map. It is the variable that
  86. // function will fill with random data. The second parameter must be a
  87. // fuzz.Continue, which will provide a source of randomness and a way
  88. // to automatically continue fuzzing smaller pieces of the first parameter.
  89. //
  90. // These functions are called sensibly, e.g., if you wanted custom string
  91. // fuzzing, the function `func(s *string, c fuzz.Continue)` would get
  92. // called and passed the address of strings. Maps and pointers will always
  93. // be made/new'd for you, ignoring the NilChange option. For slices, it
  94. // doesn't make much sense to pre-create them--Fuzzer doesn't know how
  95. // long you want your slice--so take a pointer to a slice, and make it
  96. // yourself. (If you don't want your map/pointer type pre-made, take a
  97. // pointer to it, and make it yourself.) See the examples for a range of
  98. // custom functions.
  99. func (f *Fuzzer) Funcs(fuzzFuncs ...interface{}) *Fuzzer {
  100. for i := range fuzzFuncs {
  101. v := reflect.ValueOf(fuzzFuncs[i])
  102. if v.Kind() != reflect.Func {
  103. panic("Need only funcs!")
  104. }
  105. t := v.Type()
  106. if t.NumIn() != 2 || t.NumOut() != 0 {
  107. panic("Need 2 in and 0 out params!")
  108. }
  109. argT := t.In(0)
  110. switch argT.Kind() {
  111. case reflect.Ptr, reflect.Map:
  112. default:
  113. panic("fuzzFunc must take pointer or map type")
  114. }
  115. if t.In(1) != reflect.TypeOf(Continue{}) {
  116. panic("fuzzFunc's second parameter must be type fuzz.Continue")
  117. }
  118. f.fuzzFuncs[argT] = v
  119. }
  120. return f
  121. }
  122. // RandSource causes f to get values from the given source of randomness.
  123. // Use if you want deterministic fuzzing.
  124. func (f *Fuzzer) RandSource(s rand.Source) *Fuzzer {
  125. f.r = rand.New(s)
  126. return f
  127. }
  128. // NilChance sets the probability of creating a nil pointer, map, or slice to
  129. // 'p'. 'p' should be between 0 (no nils) and 1 (all nils), inclusive.
  130. func (f *Fuzzer) NilChance(p float64) *Fuzzer {
  131. if p < 0 || p > 1 {
  132. panic("p should be between 0 and 1, inclusive.")
  133. }
  134. f.nilChance = p
  135. return f
  136. }
  137. // NumElements sets the minimum and maximum number of elements that will be
  138. // added to a non-nil map or slice.
  139. func (f *Fuzzer) NumElements(atLeast, atMost int) *Fuzzer {
  140. if atLeast > atMost {
  141. panic("atLeast must be <= atMost")
  142. }
  143. if atLeast < 0 {
  144. panic("atLeast must be >= 0")
  145. }
  146. f.minElements = atLeast
  147. f.maxElements = atMost
  148. return f
  149. }
  150. func (f *Fuzzer) genElementCount() int {
  151. if f.minElements == f.maxElements {
  152. return f.minElements
  153. }
  154. return f.minElements + f.r.Intn(f.maxElements-f.minElements+1)
  155. }
  156. func (f *Fuzzer) genShouldFill() bool {
  157. return f.r.Float64() >= f.nilChance
  158. }
  159. // MaxDepth sets the maximum number of recursive fuzz calls that will be made
  160. // before stopping. This includes struct members, pointers, and map and slice
  161. // elements.
  162. func (f *Fuzzer) MaxDepth(d int) *Fuzzer {
  163. f.maxDepth = d
  164. return f
  165. }
  166. // Skip fields which match the supplied pattern. Call this multiple times if needed
  167. // This is useful to skip XXX_ fields generated by protobuf
  168. func (f *Fuzzer) SkipFieldsWithPattern(pattern *regexp.Regexp) *Fuzzer {
  169. f.skipFieldPatterns = append(f.skipFieldPatterns, pattern)
  170. return f
  171. }
  172. // Fuzz recursively fills all of obj's fields with something random. First
  173. // this tries to find a custom fuzz function (see Funcs). If there is no
  174. // custom function this tests whether the object implements fuzz.Interface and,
  175. // if so, calls Fuzz on it to fuzz itself. If that fails, this will see if
  176. // there is a default fuzz function provided by this package. If all of that
  177. // fails, this will generate random values for all primitive fields and then
  178. // recurse for all non-primitives.
  179. //
  180. // This is safe for cyclic or tree-like structs, up to a limit. Use the
  181. // MaxDepth method to adjust how deep you need it to recurse.
  182. //
  183. // obj must be a pointer. Only exported (public) fields can be set (thanks,
  184. // golang :/ ) Intended for tests, so will panic on bad input or unimplemented
  185. // fields.
  186. func (f *Fuzzer) Fuzz(obj interface{}) {
  187. v := reflect.ValueOf(obj)
  188. if v.Kind() != reflect.Ptr {
  189. panic("needed ptr!")
  190. }
  191. v = v.Elem()
  192. f.fuzzWithContext(v, 0)
  193. }
  194. // FuzzNoCustom is just like Fuzz, except that any custom fuzz function for
  195. // obj's type will not be called and obj will not be tested for fuzz.Interface
  196. // conformance. This applies only to obj and not other instances of obj's
  197. // type.
  198. // Not safe for cyclic or tree-like structs!
  199. // obj must be a pointer. Only exported (public) fields can be set (thanks, golang :/ )
  200. // Intended for tests, so will panic on bad input or unimplemented fields.
  201. func (f *Fuzzer) FuzzNoCustom(obj interface{}) {
  202. v := reflect.ValueOf(obj)
  203. if v.Kind() != reflect.Ptr {
  204. panic("needed ptr!")
  205. }
  206. v = v.Elem()
  207. f.fuzzWithContext(v, flagNoCustomFuzz)
  208. }
  209. const (
  210. // Do not try to find a custom fuzz function. Does not apply recursively.
  211. flagNoCustomFuzz uint64 = 1 << iota
  212. )
  213. func (f *Fuzzer) fuzzWithContext(v reflect.Value, flags uint64) {
  214. fc := &fuzzerContext{fuzzer: f}
  215. fc.doFuzz(v, flags)
  216. }
  217. // fuzzerContext carries context about a single fuzzing run, which lets Fuzzer
  218. // be thread-safe.
  219. type fuzzerContext struct {
  220. fuzzer *Fuzzer
  221. curDepth int
  222. }
  223. func (fc *fuzzerContext) doFuzz(v reflect.Value, flags uint64) {
  224. if fc.curDepth >= fc.fuzzer.maxDepth {
  225. return
  226. }
  227. fc.curDepth++
  228. defer func() { fc.curDepth-- }()
  229. if !v.CanSet() {
  230. return
  231. }
  232. if flags&flagNoCustomFuzz == 0 {
  233. // Check for both pointer and non-pointer custom functions.
  234. if v.CanAddr() && fc.tryCustom(v.Addr()) {
  235. return
  236. }
  237. if fc.tryCustom(v) {
  238. return
  239. }
  240. }
  241. if fn, ok := fillFuncMap[v.Kind()]; ok {
  242. fn(v, fc.fuzzer.r)
  243. return
  244. }
  245. switch v.Kind() {
  246. case reflect.Map:
  247. if fc.fuzzer.genShouldFill() {
  248. v.Set(reflect.MakeMap(v.Type()))
  249. n := fc.fuzzer.genElementCount()
  250. for i := 0; i < n; i++ {
  251. key := reflect.New(v.Type().Key()).Elem()
  252. fc.doFuzz(key, 0)
  253. val := reflect.New(v.Type().Elem()).Elem()
  254. fc.doFuzz(val, 0)
  255. v.SetMapIndex(key, val)
  256. }
  257. return
  258. }
  259. v.Set(reflect.Zero(v.Type()))
  260. case reflect.Ptr:
  261. if fc.fuzzer.genShouldFill() {
  262. v.Set(reflect.New(v.Type().Elem()))
  263. fc.doFuzz(v.Elem(), 0)
  264. return
  265. }
  266. v.Set(reflect.Zero(v.Type()))
  267. case reflect.Slice:
  268. if fc.fuzzer.genShouldFill() {
  269. n := fc.fuzzer.genElementCount()
  270. v.Set(reflect.MakeSlice(v.Type(), n, n))
  271. for i := 0; i < n; i++ {
  272. fc.doFuzz(v.Index(i), 0)
  273. }
  274. return
  275. }
  276. v.Set(reflect.Zero(v.Type()))
  277. case reflect.Array:
  278. if fc.fuzzer.genShouldFill() {
  279. n := v.Len()
  280. for i := 0; i < n; i++ {
  281. fc.doFuzz(v.Index(i), 0)
  282. }
  283. return
  284. }
  285. v.Set(reflect.Zero(v.Type()))
  286. case reflect.Struct:
  287. for i := 0; i < v.NumField(); i++ {
  288. skipField := false
  289. fieldName := v.Type().Field(i).Name
  290. for _, pattern := range fc.fuzzer.skipFieldPatterns {
  291. if pattern.MatchString(fieldName) {
  292. skipField = true
  293. break
  294. }
  295. }
  296. if !skipField {
  297. fc.doFuzz(v.Field(i), 0)
  298. }
  299. }
  300. case reflect.Chan:
  301. fallthrough
  302. case reflect.Func:
  303. fallthrough
  304. case reflect.Interface:
  305. fallthrough
  306. default:
  307. panic(fmt.Sprintf("Can't handle %#v", v.Interface()))
  308. }
  309. }
  310. // tryCustom searches for custom handlers, and returns true iff it finds a match
  311. // and successfully randomizes v.
  312. func (fc *fuzzerContext) tryCustom(v reflect.Value) bool {
  313. // First: see if we have a fuzz function for it.
  314. doCustom, ok := fc.fuzzer.fuzzFuncs[v.Type()]
  315. if !ok {
  316. // Second: see if it can fuzz itself.
  317. if v.CanInterface() {
  318. intf := v.Interface()
  319. if fuzzable, ok := intf.(Interface); ok {
  320. fuzzable.Fuzz(Continue{fc: fc, Rand: fc.fuzzer.r})
  321. return true
  322. }
  323. }
  324. // Finally: see if there is a default fuzz function.
  325. doCustom, ok = fc.fuzzer.defaultFuzzFuncs[v.Type()]
  326. if !ok {
  327. return false
  328. }
  329. }
  330. switch v.Kind() {
  331. case reflect.Ptr:
  332. if v.IsNil() {
  333. if !v.CanSet() {
  334. return false
  335. }
  336. v.Set(reflect.New(v.Type().Elem()))
  337. }
  338. case reflect.Map:
  339. if v.IsNil() {
  340. if !v.CanSet() {
  341. return false
  342. }
  343. v.Set(reflect.MakeMap(v.Type()))
  344. }
  345. default:
  346. return false
  347. }
  348. doCustom.Call([]reflect.Value{v, reflect.ValueOf(Continue{
  349. fc: fc,
  350. Rand: fc.fuzzer.r,
  351. })})
  352. return true
  353. }
  354. // Interface represents an object that knows how to fuzz itself. Any time we
  355. // find a type that implements this interface we will delegate the act of
  356. // fuzzing itself.
  357. type Interface interface {
  358. Fuzz(c Continue)
  359. }
  360. // Continue can be passed to custom fuzzing functions to allow them to use
  361. // the correct source of randomness and to continue fuzzing their members.
  362. type Continue struct {
  363. fc *fuzzerContext
  364. // For convenience, Continue implements rand.Rand via embedding.
  365. // Use this for generating any randomness if you want your fuzzing
  366. // to be repeatable for a given seed.
  367. *rand.Rand
  368. }
  369. // Fuzz continues fuzzing obj. obj must be a pointer.
  370. func (c Continue) Fuzz(obj interface{}) {
  371. v := reflect.ValueOf(obj)
  372. if v.Kind() != reflect.Ptr {
  373. panic("needed ptr!")
  374. }
  375. v = v.Elem()
  376. c.fc.doFuzz(v, 0)
  377. }
  378. // FuzzNoCustom continues fuzzing obj, except that any custom fuzz function for
  379. // obj's type will not be called and obj will not be tested for fuzz.Interface
  380. // conformance. This applies only to obj and not other instances of obj's
  381. // type.
  382. func (c Continue) FuzzNoCustom(obj interface{}) {
  383. v := reflect.ValueOf(obj)
  384. if v.Kind() != reflect.Ptr {
  385. panic("needed ptr!")
  386. }
  387. v = v.Elem()
  388. c.fc.doFuzz(v, flagNoCustomFuzz)
  389. }
  390. // RandString makes a random string up to 20 characters long. The returned string
  391. // may include a variety of (valid) UTF-8 encodings.
  392. func (c Continue) RandString() string {
  393. return randString(c.Rand)
  394. }
  395. // RandUint64 makes random 64 bit numbers.
  396. // Weirdly, rand doesn't have a function that gives you 64 random bits.
  397. func (c Continue) RandUint64() uint64 {
  398. return randUint64(c.Rand)
  399. }
  400. // RandBool returns true or false randomly.
  401. func (c Continue) RandBool() bool {
  402. return randBool(c.Rand)
  403. }
  404. func fuzzInt(v reflect.Value, r *rand.Rand) {
  405. v.SetInt(int64(randUint64(r)))
  406. }
  407. func fuzzUint(v reflect.Value, r *rand.Rand) {
  408. v.SetUint(randUint64(r))
  409. }
  410. func fuzzTime(t *time.Time, c Continue) {
  411. var sec, nsec int64
  412. // Allow for about 1000 years of random time values, which keeps things
  413. // like JSON parsing reasonably happy.
  414. sec = c.Rand.Int63n(1000 * 365 * 24 * 60 * 60)
  415. c.Fuzz(&nsec)
  416. *t = time.Unix(sec, nsec)
  417. }
  418. var fillFuncMap = map[reflect.Kind]func(reflect.Value, *rand.Rand){
  419. reflect.Bool: func(v reflect.Value, r *rand.Rand) {
  420. v.SetBool(randBool(r))
  421. },
  422. reflect.Int: fuzzInt,
  423. reflect.Int8: fuzzInt,
  424. reflect.Int16: fuzzInt,
  425. reflect.Int32: fuzzInt,
  426. reflect.Int64: fuzzInt,
  427. reflect.Uint: fuzzUint,
  428. reflect.Uint8: fuzzUint,
  429. reflect.Uint16: fuzzUint,
  430. reflect.Uint32: fuzzUint,
  431. reflect.Uint64: fuzzUint,
  432. reflect.Uintptr: fuzzUint,
  433. reflect.Float32: func(v reflect.Value, r *rand.Rand) {
  434. v.SetFloat(float64(r.Float32()))
  435. },
  436. reflect.Float64: func(v reflect.Value, r *rand.Rand) {
  437. v.SetFloat(r.Float64())
  438. },
  439. reflect.Complex64: func(v reflect.Value, r *rand.Rand) {
  440. v.SetComplex(complex128(complex(r.Float32(), r.Float32())))
  441. },
  442. reflect.Complex128: func(v reflect.Value, r *rand.Rand) {
  443. v.SetComplex(complex(r.Float64(), r.Float64()))
  444. },
  445. reflect.String: func(v reflect.Value, r *rand.Rand) {
  446. v.SetString(randString(r))
  447. },
  448. reflect.UnsafePointer: func(v reflect.Value, r *rand.Rand) {
  449. panic("unimplemented")
  450. },
  451. }
  452. // randBool returns true or false randomly.
  453. func randBool(r *rand.Rand) bool {
  454. return r.Int31()&(1<<30) == 0
  455. }
  456. type int63nPicker interface {
  457. Int63n(int64) int64
  458. }
  459. // UnicodeRange describes a sequential range of unicode characters.
  460. // Last must be numerically greater than First.
  461. type UnicodeRange struct {
  462. First, Last rune
  463. }
  464. // UnicodeRanges describes an arbitrary number of sequential ranges of unicode characters.
  465. // To be useful, each range must have at least one character (First <= Last) and
  466. // there must be at least one range.
  467. type UnicodeRanges []UnicodeRange
  468. // choose returns a random unicode character from the given range, using the
  469. // given randomness source.
  470. func (ur UnicodeRange) choose(r int63nPicker) rune {
  471. count := int64(ur.Last - ur.First + 1)
  472. return ur.First + rune(r.Int63n(count))
  473. }
  474. // CustomStringFuzzFunc constructs a FuzzFunc which produces random strings.
  475. // Each character is selected from the range ur. If there are no characters
  476. // in the range (cr.Last < cr.First), this will panic.
  477. func (ur UnicodeRange) CustomStringFuzzFunc() func(s *string, c Continue) {
  478. ur.check()
  479. return func(s *string, c Continue) {
  480. *s = ur.randString(c.Rand)
  481. }
  482. }
  483. // check is a function that used to check whether the first of ur(UnicodeRange)
  484. // is greater than the last one.
  485. func (ur UnicodeRange) check() {
  486. if ur.Last < ur.First {
  487. panic("The last encoding must be greater than the first one.")
  488. }
  489. }
  490. // randString of UnicodeRange makes a random string up to 20 characters long.
  491. // Each character is selected form ur(UnicodeRange).
  492. func (ur UnicodeRange) randString(r *rand.Rand) string {
  493. n := r.Intn(20)
  494. sb := strings.Builder{}
  495. sb.Grow(n)
  496. for i := 0; i < n; i++ {
  497. sb.WriteRune(ur.choose(r))
  498. }
  499. return sb.String()
  500. }
  501. // defaultUnicodeRanges sets a default unicode range when user do not set
  502. // CustomStringFuzzFunc() but wants fuzz string.
  503. var defaultUnicodeRanges = UnicodeRanges{
  504. {' ', '~'}, // ASCII characters
  505. {'\u00a0', '\u02af'}, // Multi-byte encoded characters
  506. {'\u4e00', '\u9fff'}, // Common CJK (even longer encodings)
  507. }
  508. // CustomStringFuzzFunc constructs a FuzzFunc which produces random strings.
  509. // Each character is selected from one of the ranges of ur(UnicodeRanges).
  510. // Each range has an equal probability of being chosen. If there are no ranges,
  511. // or a selected range has no characters (.Last < .First), this will panic.
  512. // Do not modify any of the ranges in ur after calling this function.
  513. func (ur UnicodeRanges) CustomStringFuzzFunc() func(s *string, c Continue) {
  514. // Check unicode ranges slice is empty.
  515. if len(ur) == 0 {
  516. panic("UnicodeRanges is empty.")
  517. }
  518. // if not empty, each range should be checked.
  519. for i := range ur {
  520. ur[i].check()
  521. }
  522. return func(s *string, c Continue) {
  523. *s = ur.randString(c.Rand)
  524. }
  525. }
  526. // randString of UnicodeRanges makes a random string up to 20 characters long.
  527. // Each character is selected form one of the ranges of ur(UnicodeRanges),
  528. // and each range has an equal probability of being chosen.
  529. func (ur UnicodeRanges) randString(r *rand.Rand) string {
  530. n := r.Intn(20)
  531. sb := strings.Builder{}
  532. sb.Grow(n)
  533. for i := 0; i < n; i++ {
  534. sb.WriteRune(ur[r.Intn(len(ur))].choose(r))
  535. }
  536. return sb.String()
  537. }
  538. // randString makes a random string up to 20 characters long. The returned string
  539. // may include a variety of (valid) UTF-8 encodings.
  540. func randString(r *rand.Rand) string {
  541. return defaultUnicodeRanges.randString(r)
  542. }
  543. // randUint64 makes random 64 bit numbers.
  544. // Weirdly, rand doesn't have a function that gives you 64 random bits.
  545. func randUint64(r *rand.Rand) uint64 {
  546. return uint64(r.Uint32())<<32 | uint64(r.Uint32())
  547. }