fuzz.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. "time"
  19. )
  20. // fuzzFuncMap is a map from a type to a fuzzFunc that handles that type.
  21. type fuzzFuncMap map[reflect.Type]reflect.Value
  22. // Fuzzer knows how to fill any object with random fields.
  23. type Fuzzer struct {
  24. fuzzFuncs fuzzFuncMap
  25. defaultFuzzFuncs fuzzFuncMap
  26. r *rand.Rand
  27. nilChance float64
  28. minElements int
  29. maxElements int
  30. maxDepth int
  31. }
  32. // New returns a new Fuzzer. Customize your Fuzzer further by calling Funcs,
  33. // RandSource, NilChance, or NumElements in any order.
  34. func New() *Fuzzer {
  35. return NewWithSeed(time.Now().UnixNano())
  36. }
  37. func NewWithSeed(seed int64) *Fuzzer {
  38. f := &Fuzzer{
  39. defaultFuzzFuncs: fuzzFuncMap{
  40. reflect.TypeOf(&time.Time{}): reflect.ValueOf(fuzzTime),
  41. },
  42. fuzzFuncs: fuzzFuncMap{},
  43. r: rand.New(rand.NewSource(seed)),
  44. nilChance: .2,
  45. minElements: 1,
  46. maxElements: 10,
  47. maxDepth: 100,
  48. }
  49. return f
  50. }
  51. // Funcs adds each entry in fuzzFuncs as a custom fuzzing function.
  52. //
  53. // Each entry in fuzzFuncs must be a function taking two parameters.
  54. // The first parameter must be a pointer or map. It is the variable that
  55. // function will fill with random data. The second parameter must be a
  56. // fuzz.Continue, which will provide a source of randomness and a way
  57. // to automatically continue fuzzing smaller pieces of the first parameter.
  58. //
  59. // These functions are called sensibly, e.g., if you wanted custom string
  60. // fuzzing, the function `func(s *string, c fuzz.Continue)` would get
  61. // called and passed the address of strings. Maps and pointers will always
  62. // be made/new'd for you, ignoring the NilChange option. For slices, it
  63. // doesn't make much sense to pre-create them--Fuzzer doesn't know how
  64. // long you want your slice--so take a pointer to a slice, and make it
  65. // yourself. (If you don't want your map/pointer type pre-made, take a
  66. // pointer to it, and make it yourself.) See the examples for a range of
  67. // custom functions.
  68. func (f *Fuzzer) Funcs(fuzzFuncs ...interface{}) *Fuzzer {
  69. for i := range fuzzFuncs {
  70. v := reflect.ValueOf(fuzzFuncs[i])
  71. if v.Kind() != reflect.Func {
  72. panic("Need only funcs!")
  73. }
  74. t := v.Type()
  75. if t.NumIn() != 2 || t.NumOut() != 0 {
  76. panic("Need 2 in and 0 out params!")
  77. }
  78. argT := t.In(0)
  79. switch argT.Kind() {
  80. case reflect.Ptr, reflect.Map:
  81. default:
  82. panic("fuzzFunc must take pointer or map type")
  83. }
  84. if t.In(1) != reflect.TypeOf(Continue{}) {
  85. panic("fuzzFunc's second parameter must be type fuzz.Continue")
  86. }
  87. f.fuzzFuncs[argT] = v
  88. }
  89. return f
  90. }
  91. // RandSource causes f to get values from the given source of randomness.
  92. // Use if you want deterministic fuzzing.
  93. func (f *Fuzzer) RandSource(s rand.Source) *Fuzzer {
  94. f.r = rand.New(s)
  95. return f
  96. }
  97. // NilChance sets the probability of creating a nil pointer, map, or slice to
  98. // 'p'. 'p' should be between 0 (no nils) and 1 (all nils), inclusive.
  99. func (f *Fuzzer) NilChance(p float64) *Fuzzer {
  100. if p < 0 || p > 1 {
  101. panic("p should be between 0 and 1, inclusive.")
  102. }
  103. f.nilChance = p
  104. return f
  105. }
  106. // NumElements sets the minimum and maximum number of elements that will be
  107. // added to a non-nil map or slice.
  108. func (f *Fuzzer) NumElements(atLeast, atMost int) *Fuzzer {
  109. if atLeast > atMost {
  110. panic("atLeast must be <= atMost")
  111. }
  112. if atLeast < 0 {
  113. panic("atLeast must be >= 0")
  114. }
  115. f.minElements = atLeast
  116. f.maxElements = atMost
  117. return f
  118. }
  119. func (f *Fuzzer) genElementCount() int {
  120. if f.minElements == f.maxElements {
  121. return f.minElements
  122. }
  123. return f.minElements + f.r.Intn(f.maxElements-f.minElements+1)
  124. }
  125. func (f *Fuzzer) genShouldFill() bool {
  126. return f.r.Float64() > f.nilChance
  127. }
  128. // MaxDepth sets the maximum number of recursive fuzz calls that will be made
  129. // before stopping. This includes struct members, pointers, and map and slice
  130. // elements.
  131. func (f *Fuzzer) MaxDepth(d int) *Fuzzer {
  132. f.maxDepth = d
  133. return f
  134. }
  135. // Fuzz recursively fills all of obj's fields with something random. First
  136. // this tries to find a custom fuzz function (see Funcs). If there is no
  137. // custom function this tests whether the object implements fuzz.Interface and,
  138. // if so, calls Fuzz on it to fuzz itself. If that fails, this will see if
  139. // there is a default fuzz function provided by this package. If all of that
  140. // fails, this will generate random values for all primitive fields and then
  141. // recurse for all non-primitives.
  142. //
  143. // This is safe for cyclic or tree-like structs, up to a limit. Use the
  144. // MaxDepth method to adjust how deep you need it to recurse.
  145. //
  146. // obj must be a pointer. Only exported (public) fields can be set (thanks,
  147. // golang :/ ) Intended for tests, so will panic on bad input or unimplemented
  148. // fields.
  149. func (f *Fuzzer) Fuzz(obj interface{}) {
  150. v := reflect.ValueOf(obj)
  151. if v.Kind() != reflect.Ptr {
  152. panic("needed ptr!")
  153. }
  154. v = v.Elem()
  155. f.fuzzWithContext(v, 0)
  156. }
  157. // FuzzNoCustom is just like Fuzz, except that any custom fuzz function for
  158. // obj's type will not be called and obj will not be tested for fuzz.Interface
  159. // conformance. This applies only to obj and not other instances of obj's
  160. // type.
  161. // Not safe for cyclic or tree-like structs!
  162. // obj must be a pointer. Only exported (public) fields can be set (thanks, golang :/ )
  163. // Intended for tests, so will panic on bad input or unimplemented fields.
  164. func (f *Fuzzer) FuzzNoCustom(obj interface{}) {
  165. v := reflect.ValueOf(obj)
  166. if v.Kind() != reflect.Ptr {
  167. panic("needed ptr!")
  168. }
  169. v = v.Elem()
  170. f.fuzzWithContext(v, flagNoCustomFuzz)
  171. }
  172. const (
  173. // Do not try to find a custom fuzz function. Does not apply recursively.
  174. flagNoCustomFuzz uint64 = 1 << iota
  175. )
  176. func (f *Fuzzer) fuzzWithContext(v reflect.Value, flags uint64) {
  177. fc := &fuzzerContext{fuzzer: f}
  178. fc.doFuzz(v, flags)
  179. }
  180. // fuzzerContext carries context about a single fuzzing run, which lets Fuzzer
  181. // be thread-safe.
  182. type fuzzerContext struct {
  183. fuzzer *Fuzzer
  184. curDepth int
  185. }
  186. func (fc *fuzzerContext) doFuzz(v reflect.Value, flags uint64) {
  187. if fc.curDepth >= fc.fuzzer.maxDepth {
  188. return
  189. }
  190. fc.curDepth++
  191. defer func() { fc.curDepth-- }()
  192. if !v.CanSet() {
  193. return
  194. }
  195. if flags&flagNoCustomFuzz == 0 {
  196. // Check for both pointer and non-pointer custom functions.
  197. if v.CanAddr() && fc.tryCustom(v.Addr()) {
  198. return
  199. }
  200. if fc.tryCustom(v) {
  201. return
  202. }
  203. }
  204. if fn, ok := fillFuncMap[v.Kind()]; ok {
  205. fn(v, fc.fuzzer.r)
  206. return
  207. }
  208. switch v.Kind() {
  209. case reflect.Map:
  210. if fc.fuzzer.genShouldFill() {
  211. v.Set(reflect.MakeMap(v.Type()))
  212. n := fc.fuzzer.genElementCount()
  213. for i := 0; i < n; i++ {
  214. key := reflect.New(v.Type().Key()).Elem()
  215. fc.doFuzz(key, 0)
  216. val := reflect.New(v.Type().Elem()).Elem()
  217. fc.doFuzz(val, 0)
  218. v.SetMapIndex(key, val)
  219. }
  220. return
  221. }
  222. v.Set(reflect.Zero(v.Type()))
  223. case reflect.Ptr:
  224. if fc.fuzzer.genShouldFill() {
  225. v.Set(reflect.New(v.Type().Elem()))
  226. fc.doFuzz(v.Elem(), 0)
  227. return
  228. }
  229. v.Set(reflect.Zero(v.Type()))
  230. case reflect.Slice:
  231. if fc.fuzzer.genShouldFill() {
  232. n := fc.fuzzer.genElementCount()
  233. v.Set(reflect.MakeSlice(v.Type(), n, n))
  234. for i := 0; i < n; i++ {
  235. fc.doFuzz(v.Index(i), 0)
  236. }
  237. return
  238. }
  239. v.Set(reflect.Zero(v.Type()))
  240. case reflect.Array:
  241. if fc.fuzzer.genShouldFill() {
  242. n := v.Len()
  243. for i := 0; i < n; i++ {
  244. fc.doFuzz(v.Index(i), 0)
  245. }
  246. return
  247. }
  248. v.Set(reflect.Zero(v.Type()))
  249. case reflect.Struct:
  250. for i := 0; i < v.NumField(); i++ {
  251. fc.doFuzz(v.Field(i), 0)
  252. }
  253. case reflect.Chan:
  254. fallthrough
  255. case reflect.Func:
  256. fallthrough
  257. case reflect.Interface:
  258. fallthrough
  259. default:
  260. panic(fmt.Sprintf("Can't handle %#v", v.Interface()))
  261. }
  262. }
  263. // tryCustom searches for custom handlers, and returns true iff it finds a match
  264. // and successfully randomizes v.
  265. func (fc *fuzzerContext) tryCustom(v reflect.Value) bool {
  266. // First: see if we have a fuzz function for it.
  267. doCustom, ok := fc.fuzzer.fuzzFuncs[v.Type()]
  268. if !ok {
  269. // Second: see if it can fuzz itself.
  270. if v.CanInterface() {
  271. intf := v.Interface()
  272. if fuzzable, ok := intf.(Interface); ok {
  273. fuzzable.Fuzz(Continue{fc: fc, Rand: fc.fuzzer.r})
  274. return true
  275. }
  276. }
  277. // Finally: see if there is a default fuzz function.
  278. doCustom, ok = fc.fuzzer.defaultFuzzFuncs[v.Type()]
  279. if !ok {
  280. return false
  281. }
  282. }
  283. switch v.Kind() {
  284. case reflect.Ptr:
  285. if v.IsNil() {
  286. if !v.CanSet() {
  287. return false
  288. }
  289. v.Set(reflect.New(v.Type().Elem()))
  290. }
  291. case reflect.Map:
  292. if v.IsNil() {
  293. if !v.CanSet() {
  294. return false
  295. }
  296. v.Set(reflect.MakeMap(v.Type()))
  297. }
  298. default:
  299. return false
  300. }
  301. doCustom.Call([]reflect.Value{v, reflect.ValueOf(Continue{
  302. fc: fc,
  303. Rand: fc.fuzzer.r,
  304. })})
  305. return true
  306. }
  307. // Interface represents an object that knows how to fuzz itself. Any time we
  308. // find a type that implements this interface we will delegate the act of
  309. // fuzzing itself.
  310. type Interface interface {
  311. Fuzz(c Continue)
  312. }
  313. // Continue can be passed to custom fuzzing functions to allow them to use
  314. // the correct source of randomness and to continue fuzzing their members.
  315. type Continue struct {
  316. fc *fuzzerContext
  317. // For convenience, Continue implements rand.Rand via embedding.
  318. // Use this for generating any randomness if you want your fuzzing
  319. // to be repeatable for a given seed.
  320. *rand.Rand
  321. }
  322. // Fuzz continues fuzzing obj. obj must be a pointer.
  323. func (c Continue) Fuzz(obj interface{}) {
  324. v := reflect.ValueOf(obj)
  325. if v.Kind() != reflect.Ptr {
  326. panic("needed ptr!")
  327. }
  328. v = v.Elem()
  329. c.fc.doFuzz(v, 0)
  330. }
  331. // FuzzNoCustom continues fuzzing obj, except that any custom fuzz function for
  332. // obj's type will not be called and obj will not be tested for fuzz.Interface
  333. // conformance. This applies only to obj and not other instances of obj's
  334. // type.
  335. func (c Continue) FuzzNoCustom(obj interface{}) {
  336. v := reflect.ValueOf(obj)
  337. if v.Kind() != reflect.Ptr {
  338. panic("needed ptr!")
  339. }
  340. v = v.Elem()
  341. c.fc.doFuzz(v, flagNoCustomFuzz)
  342. }
  343. // RandString makes a random string up to 20 characters long. The returned string
  344. // may include a variety of (valid) UTF-8 encodings.
  345. func (c Continue) RandString() string {
  346. return randString(c.Rand)
  347. }
  348. // RandUint64 makes random 64 bit numbers.
  349. // Weirdly, rand doesn't have a function that gives you 64 random bits.
  350. func (c Continue) RandUint64() uint64 {
  351. return randUint64(c.Rand)
  352. }
  353. // RandBool returns true or false randomly.
  354. func (c Continue) RandBool() bool {
  355. return randBool(c.Rand)
  356. }
  357. func fuzzInt(v reflect.Value, r *rand.Rand) {
  358. v.SetInt(int64(randUint64(r)))
  359. }
  360. func fuzzUint(v reflect.Value, r *rand.Rand) {
  361. v.SetUint(randUint64(r))
  362. }
  363. func fuzzTime(t *time.Time, c Continue) {
  364. var sec, nsec int64
  365. // Allow for about 1000 years of random time values, which keeps things
  366. // like JSON parsing reasonably happy.
  367. sec = c.Rand.Int63n(1000 * 365 * 24 * 60 * 60)
  368. c.Fuzz(&nsec)
  369. *t = time.Unix(sec, nsec)
  370. }
  371. var fillFuncMap = map[reflect.Kind]func(reflect.Value, *rand.Rand){
  372. reflect.Bool: func(v reflect.Value, r *rand.Rand) {
  373. v.SetBool(randBool(r))
  374. },
  375. reflect.Int: fuzzInt,
  376. reflect.Int8: fuzzInt,
  377. reflect.Int16: fuzzInt,
  378. reflect.Int32: fuzzInt,
  379. reflect.Int64: fuzzInt,
  380. reflect.Uint: fuzzUint,
  381. reflect.Uint8: fuzzUint,
  382. reflect.Uint16: fuzzUint,
  383. reflect.Uint32: fuzzUint,
  384. reflect.Uint64: fuzzUint,
  385. reflect.Uintptr: fuzzUint,
  386. reflect.Float32: func(v reflect.Value, r *rand.Rand) {
  387. v.SetFloat(float64(r.Float32()))
  388. },
  389. reflect.Float64: func(v reflect.Value, r *rand.Rand) {
  390. v.SetFloat(r.Float64())
  391. },
  392. reflect.Complex64: func(v reflect.Value, r *rand.Rand) {
  393. panic("unimplemented")
  394. },
  395. reflect.Complex128: func(v reflect.Value, r *rand.Rand) {
  396. panic("unimplemented")
  397. },
  398. reflect.String: func(v reflect.Value, r *rand.Rand) {
  399. v.SetString(randString(r))
  400. },
  401. reflect.UnsafePointer: func(v reflect.Value, r *rand.Rand) {
  402. panic("unimplemented")
  403. },
  404. }
  405. // randBool returns true or false randomly.
  406. func randBool(r *rand.Rand) bool {
  407. if r.Int()&1 == 1 {
  408. return true
  409. }
  410. return false
  411. }
  412. type charRange struct {
  413. first, last rune
  414. }
  415. // choose returns a random unicode character from the given range, using the
  416. // given randomness source.
  417. func (r *charRange) choose(rand *rand.Rand) rune {
  418. count := int64(r.last - r.first)
  419. return r.first + rune(rand.Int63n(count))
  420. }
  421. var unicodeRanges = []charRange{
  422. {' ', '~'}, // ASCII characters
  423. {'\u00a0', '\u02af'}, // Multi-byte encoded characters
  424. {'\u4e00', '\u9fff'}, // Common CJK (even longer encodings)
  425. }
  426. // randString makes a random string up to 20 characters long. The returned string
  427. // may include a variety of (valid) UTF-8 encodings.
  428. func randString(r *rand.Rand) string {
  429. n := r.Intn(20)
  430. runes := make([]rune, n)
  431. for i := range runes {
  432. runes[i] = unicodeRanges[r.Intn(len(unicodeRanges))].choose(r)
  433. }
  434. return string(runes)
  435. }
  436. // randUint64 makes random 64 bit numbers.
  437. // Weirdly, rand doesn't have a function that gives you 64 random bits.
  438. func randUint64(r *rand.Rand) uint64 {
  439. return uint64(r.Uint32())<<32 | uint64(r.Uint32())
  440. }