fuzz.go 12 KB

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