fuzz.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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)
  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.Struct:
  212. for i := 0; i < v.NumField(); i++ {
  213. f.doFuzz(v.Field(i), 0)
  214. }
  215. case reflect.Array:
  216. fallthrough
  217. case reflect.Chan:
  218. fallthrough
  219. case reflect.Func:
  220. fallthrough
  221. case reflect.Interface:
  222. fallthrough
  223. default:
  224. panic(fmt.Sprintf("Can't handle %#v", v.Interface()))
  225. }
  226. }
  227. // tryCustom searches for custom handlers, and returns true iff it finds a match
  228. // and successfully randomizes v.
  229. func (f *Fuzzer) tryCustom(v reflect.Value) bool {
  230. // First: see if we have a fuzz function for it.
  231. doCustom, ok := f.fuzzFuncs[v.Type()]
  232. if !ok {
  233. // Second: see if it can fuzz itself.
  234. if v.CanInterface() {
  235. intf := v.Interface()
  236. if fuzzable, ok := intf.(Interface); ok {
  237. fuzzable.Fuzz(Continue{f: f, Rand: f.r})
  238. return true
  239. }
  240. }
  241. // Finally: see if there is a default fuzz function.
  242. doCustom, ok = f.defaultFuzzFuncs[v.Type()]
  243. if !ok {
  244. return false
  245. }
  246. }
  247. switch v.Kind() {
  248. case reflect.Ptr:
  249. if v.IsNil() {
  250. if !v.CanSet() {
  251. return false
  252. }
  253. v.Set(reflect.New(v.Type().Elem()))
  254. }
  255. case reflect.Map:
  256. if v.IsNil() {
  257. if !v.CanSet() {
  258. return false
  259. }
  260. v.Set(reflect.MakeMap(v.Type()))
  261. }
  262. default:
  263. return false
  264. }
  265. doCustom.Call([]reflect.Value{v, reflect.ValueOf(Continue{
  266. f: f,
  267. Rand: f.r,
  268. })})
  269. return true
  270. }
  271. // Interface represents an object that knows how to fuzz itself. Any time we
  272. // find a type that implements this interface we will delegate the act of
  273. // fuzzing itself.
  274. type Interface interface {
  275. Fuzz(c Continue)
  276. }
  277. // Continue can be passed to custom fuzzing functions to allow them to use
  278. // the correct source of randomness and to continue fuzzing their members.
  279. type Continue struct {
  280. f *Fuzzer
  281. // For convenience, Continue implements rand.Rand via embedding.
  282. // Use this for generating any randomness if you want your fuzzing
  283. // to be repeatable for a given seed.
  284. *rand.Rand
  285. }
  286. // Fuzz continues fuzzing obj. obj must be a pointer.
  287. func (c Continue) Fuzz(obj interface{}) {
  288. v := reflect.ValueOf(obj)
  289. if v.Kind() != reflect.Ptr {
  290. panic("needed ptr!")
  291. }
  292. v = v.Elem()
  293. c.f.doFuzz(v, 0)
  294. }
  295. // FuzzNoCustom continues fuzzing obj, except that any custom fuzz function for
  296. // obj's type will not be called and obj will not be tested for fuzz.Interface
  297. // conformance. This applies only to obj and not other instances of obj's
  298. // type.
  299. func (c Continue) FuzzNoCustom(obj interface{}) {
  300. v := reflect.ValueOf(obj)
  301. if v.Kind() != reflect.Ptr {
  302. panic("needed ptr!")
  303. }
  304. v = v.Elem()
  305. c.f.doFuzz(v, flagNoCustomFuzz)
  306. }
  307. // RandString makes a random string up to 20 characters long. The returned string
  308. // may include a variety of (valid) UTF-8 encodings.
  309. func (c Continue) RandString() string {
  310. return randString(c.Rand)
  311. }
  312. // RandUint64 makes random 64 bit numbers.
  313. // Weirdly, rand doesn't have a function that gives you 64 random bits.
  314. func (c Continue) RandUint64() uint64 {
  315. return randUint64(c.Rand)
  316. }
  317. // RandBool returns true or false randomly.
  318. func (c Continue) RandBool() bool {
  319. return randBool(c.Rand)
  320. }
  321. func fuzzInt(v reflect.Value, r *rand.Rand) {
  322. v.SetInt(int64(randUint64(r)))
  323. }
  324. func fuzzUint(v reflect.Value, r *rand.Rand) {
  325. v.SetUint(randUint64(r))
  326. }
  327. func fuzzTime(t *time.Time, c Continue) {
  328. var sec, nsec int64
  329. // Allow for about 1000 years of random time values, which keeps things
  330. // like JSON parsing reasonably happy.
  331. sec = c.Rand.Int63n(1000 * 365 * 24 * 60 * 60)
  332. c.Fuzz(&nsec)
  333. *t = time.Unix(sec, nsec)
  334. }
  335. var fillFuncMap = map[reflect.Kind]func(reflect.Value, *rand.Rand){
  336. reflect.Bool: func(v reflect.Value, r *rand.Rand) {
  337. v.SetBool(randBool(r))
  338. },
  339. reflect.Int: fuzzInt,
  340. reflect.Int8: fuzzInt,
  341. reflect.Int16: fuzzInt,
  342. reflect.Int32: fuzzInt,
  343. reflect.Int64: fuzzInt,
  344. reflect.Uint: fuzzUint,
  345. reflect.Uint8: fuzzUint,
  346. reflect.Uint16: fuzzUint,
  347. reflect.Uint32: fuzzUint,
  348. reflect.Uint64: fuzzUint,
  349. reflect.Uintptr: fuzzUint,
  350. reflect.Float32: func(v reflect.Value, r *rand.Rand) {
  351. v.SetFloat(float64(r.Float32()))
  352. },
  353. reflect.Float64: func(v reflect.Value, r *rand.Rand) {
  354. v.SetFloat(r.Float64())
  355. },
  356. reflect.Complex64: func(v reflect.Value, r *rand.Rand) {
  357. panic("unimplemented")
  358. },
  359. reflect.Complex128: func(v reflect.Value, r *rand.Rand) {
  360. panic("unimplemented")
  361. },
  362. reflect.String: func(v reflect.Value, r *rand.Rand) {
  363. v.SetString(randString(r))
  364. },
  365. reflect.UnsafePointer: func(v reflect.Value, r *rand.Rand) {
  366. panic("unimplemented")
  367. },
  368. }
  369. // randBool returns true or false randomly.
  370. func randBool(r *rand.Rand) bool {
  371. if r.Int()&1 == 1 {
  372. return true
  373. }
  374. return false
  375. }
  376. type charRange struct {
  377. first, last rune
  378. }
  379. // choose returns a random unicode character from the given range, using the
  380. // given randomness source.
  381. func (r *charRange) choose(rand *rand.Rand) rune {
  382. count := int64(r.last - r.first)
  383. return r.first + rune(rand.Int63n(count))
  384. }
  385. var unicodeRanges = []charRange{
  386. {' ', '~'}, // ASCII characters
  387. {'\u00a0', '\u02af'}, // Multi-byte encoded characters
  388. {'\u4e00', '\u9fff'}, // Common CJK (even longer encodings)
  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 randString(r *rand.Rand) string {
  393. n := r.Intn(20)
  394. runes := make([]rune, n)
  395. for i := range runes {
  396. runes[i] = unicodeRanges[r.Intn(len(unicodeRanges))].choose(r)
  397. }
  398. return string(runes)
  399. }
  400. // randUint64 makes random 64 bit numbers.
  401. // Weirdly, rand doesn't have a function that gives you 64 random bits.
  402. func randUint64(r *rand.Rand) uint64 {
  403. return uint64(r.Uint32())<<32 | uint64(r.Uint32())
  404. }