| 1 | // Copyright 2021 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // This package generates source code for a stand-alone Go program |
| 6 | // useful for function signature fuzzing. The generated program is a |
| 7 | // series of function pairs, a "Caller" function and a "Checker" |
| 8 | // function. The signature of the Checker function is generated |
| 9 | // randomly (random number of parameters and returns, each with |
| 10 | // randomly chosen types). The "Caller" func contains invocations of |
| 11 | // the "Checker" function, each passing randomly chosen values to the |
| 12 | // params of the "Checker", then the caller verifies that expected |
| 13 | // values are returned correctly. The "Checker" function in turn has |
| 14 | // code to verify that the expected values arrive correctly, and so |
| 15 | // on. |
| 16 | // |
| 17 | // The main exported items of interest for this package are: |
| 18 | // |
| 19 | // - the Generate function, which takes a GenConfig object and emits |
| 20 | // code according to the config's specification |
| 21 | // |
| 22 | // - the GenConfig struct, which is basically a large collection of |
| 23 | // knobs/switches to control the mechanics of how/where code is |
| 24 | // generated |
| 25 | // |
| 26 | // - the TunableParams struct, which controls the nature of the |
| 27 | // generated code (for example, the maximum number of function |
| 28 | // parameters, etc), and the SetTunables func which tells the |
| 29 | // package what tunable parameters to use. |
| 30 | |
| 31 | // Notes for posterity: |
| 32 | // - many parts of this package would have been better off being written |
| 33 | // using text/template instead of generating code directly; perhaps |
| 34 | // at some point it could be converted over (big job). |
| 35 | // - for the various 'fractions' fields in the TunableParams struct, |
| 36 | // it would be good to have a named type of some sort, with methods |
| 37 | // for managing things like checking to make sure values sum to 100. |
| 38 | |
| 39 | package generator |
| 40 | |
| 41 | import ( |
| 42 | "bytes" |
| 43 | "crypto/sha1" |
| 44 | "errors" |
| 45 | "fmt" |
| 46 | "html/template" |
| 47 | "log" |
| 48 | "os" |
| 49 | "os/exec" |
| 50 | "path/filepath" |
| 51 | "slices" |
| 52 | "strconv" |
| 53 | "strings" |
| 54 | ) |
| 55 | |
| 56 | // GenConfig contains configuration parameters relating to the |
| 57 | // mechanics of the code generation, e.g. how many packages/functions |
| 58 | // to emit, path to a directory into which we place the generated |
| 59 | // code, prefixes/packagenames for the generate code, and so on. |
| 60 | type GenConfig struct { |
| 61 | // Tag is a string prefix prepended to functions within |
| 62 | // the generated code. |
| 63 | Tag string |
| 64 | |
| 65 | // Output directory in to which we'll emit generated code. |
| 66 | // This will be created if it does not exist. |
| 67 | OutDir string |
| 68 | |
| 69 | // Packagepath prefix given to the generated code. |
| 70 | PkgPath string |
| 71 | |
| 72 | // Number of test packages created within the generated corpus. |
| 73 | // Each test package is essentially an independent collection |
| 74 | // generated code; the point of having multiple packages is to |
| 75 | // be able to get faster builds (more parallelism), and to avoid |
| 76 | // the compile time issues that crop up with 'giant' packages. |
| 77 | NumTestPackages int |
| 78 | |
| 79 | // Number of test function pairs within each generated test package. |
| 80 | // Each pair consists of a "caller" function and "callee" function. |
| 81 | NumTestFunctions int |
| 82 | |
| 83 | // Seed for random number generator. |
| 84 | Seed int64 |
| 85 | |
| 86 | // Pragma is a "// go:..." compiler directive to apply to the |
| 87 | // callee function as part of a generated function pair. |
| 88 | Pragma string |
| 89 | |
| 90 | // Function and package mask used for minimization purposes. |
| 91 | // If a given mask is non-nil, then the generator will only |
| 92 | // emit code for a given func or package if its index is |
| 93 | // present in the mask map. |
| 94 | FcnMask map[int]int |
| 95 | PkgMask map[int]int |
| 96 | |
| 97 | // Maximum number of failures to encounter before bailing out. |
| 98 | MaxFail int |
| 99 | |
| 100 | // forcestackgrowth if set tells the generator to insert |
| 101 | // calls to runtime.gcTestMoveStackOnNextCall at various points |
| 102 | // in the generated code. |
| 103 | ForceStackGrowth bool |
| 104 | |
| 105 | // Random number generator control flag (debugging) |
| 106 | RandCtl int |
| 107 | |
| 108 | // Tells the generator to run "goimports" on the emitted code. |
| 109 | RunGoImports bool |
| 110 | |
| 111 | // Debugging/testing hook. If set to 1, emit code that will cause the |
| 112 | // build to fail; if set to 2, emit code that will cause a test to fail. |
| 113 | EmitBad int |
| 114 | |
| 115 | // If EmitBad above is set, then these can be used to select the ID of |
| 116 | // a specific bad func/package. |
| 117 | BadPackageIdx int |
| 118 | BadFuncIdx int |
| 119 | } |
| 120 | |
| 121 | const CallerName = "Caller" |
| 122 | const CheckerName = "Checker" |
| 123 | |
| 124 | // TunableParams contains configuration parameters that control the |
| 125 | // flavor of code generated for a given test function. This includes |
| 126 | // things like the number of params/returns, the percentages of types |
| 127 | // (int, struct, etc) of the params/returns, and so on. |
| 128 | type TunableParams struct { |
| 129 | // between 0 and N params |
| 130 | nParmRange uint8 |
| 131 | |
| 132 | // between 0 and N returns |
| 133 | nReturnRange uint8 |
| 134 | |
| 135 | // structs have between 0 and N members |
| 136 | nStructFields uint8 |
| 137 | |
| 138 | // arrays/slices have between 0 and N elements |
| 139 | nArrayElements uint8 |
| 140 | |
| 141 | // fraction of slices vs arrays. This is a value between 0 and 100 (0 meaning |
| 142 | // no slices [only arrays] and 100 meaning all slices, no arrays). |
| 143 | sliceFraction uint8 |
| 144 | |
| 145 | // Controls how often "int" vars wind up as 8/16/32/64, should |
| 146 | // add up to 100. Ex: 100 0 0 0 means all ints are 8 bit, 25 |
| 147 | // 25 25 25 means equal likelihood of all types. |
| 148 | intBitRanges [4]uint8 |
| 149 | |
| 150 | // Similar to the above but for 32/64 float types |
| 151 | floatBitRanges [2]uint8 |
| 152 | |
| 153 | // Similar to the above but for unsigned, signed ints. |
| 154 | unsignedRanges [2]uint8 |
| 155 | |
| 156 | // Percentage of params, struct fields that should be "_". Ranges |
| 157 | // from 0 to 100. |
| 158 | blankPerc uint8 |
| 159 | |
| 160 | // How deeply structs are allowed to be nested (ranges from 0 to N). |
| 161 | structDepth uint8 |
| 162 | |
| 163 | // Fraction of param and return types assigned to each of: |
| 164 | // struct/array/map/pointer/int/float/complex/byte/string at the |
| 165 | // top level. If nesting precludes using a struct, other types |
| 166 | // are chosen from instead according to same proportions. The sum |
| 167 | // of typeFractions values should add up to 100. |
| 168 | typeFractions [9]uint8 |
| 169 | |
| 170 | // Percentage of the time we'll emit recursive calls, from 0 to 100. |
| 171 | recurPerc uint8 |
| 172 | |
| 173 | // Percentage of time that we turn the test function into a method, |
| 174 | // and if it is a method, fraction of time that we use a pointer |
| 175 | // method call vs value method call. Each range from 0 to 100. |
| 176 | methodPerc uint8 |
| 177 | pointerMethodCallPerc uint8 |
| 178 | |
| 179 | // If true, test reflect.Call path as well. |
| 180 | doReflectCall bool |
| 181 | |
| 182 | // If true, then randomly take addresses of params/returns. |
| 183 | takeAddress bool |
| 184 | |
| 185 | // Fraction of the time that any params/returns are address taken. |
| 186 | // Ranges from 0 to 100. |
| 187 | takenFraction uint8 |
| 188 | |
| 189 | // For a given address-taken param or return, controls the |
| 190 | // manner in which the indirect read or write takes |
| 191 | // place. This is a set of percentages for |
| 192 | // not/simple/passed/heap, where "not" means not address |
| 193 | // taken, "simple" means a simple read or write, "passed" |
| 194 | // means that the address is passed to a well-behaved |
| 195 | // function, and "heap" means that the address is assigned to |
| 196 | // a global. Values in addrFractions should add up to 100. |
| 197 | addrFractions [4]uint8 |
| 198 | |
| 199 | // If true, then perform testing of go/defer statements. |
| 200 | doDefer bool |
| 201 | |
| 202 | // fraction of test functions for which we emit a defer. Ranges from 0 to 100. |
| 203 | deferFraction uint8 |
| 204 | |
| 205 | // If true, randomly pick between emitting a value by literal |
| 206 | // (e.g. "int(1)" vs emitting a call to a function that |
| 207 | // will produce the same value (e.g. "myHelperEmitsInt1()"). |
| 208 | doFuncCallValues bool |
| 209 | |
| 210 | // Fraction of the time that we emit a function call to create |
| 211 | // a param value vs emitting a literal. Ranges from 0 to 100. |
| 212 | funcCallValFraction uint8 |
| 213 | |
| 214 | // If true, randomly decide to not check selected components of |
| 215 | // a composite value (e.g. for a struct, check field F1 but not F2). |
| 216 | // The intent is to generate partially live values. |
| 217 | doSkipCompare bool |
| 218 | |
| 219 | // Fraction of the time that we decided to skip sub-components of |
| 220 | // composite values. Ranges from 0 to 100. |
| 221 | skipCompareFraction uint8 |
| 222 | } |
| 223 | |
| 224 | // SetTunables accepts a TunableParams object, checks to make sure |
| 225 | // that the settings in it are sane/logical, and applies the |
| 226 | // parameters for any subsequent calls to the Generate function. This |
| 227 | // function will issue a fatal error if any of the tunable params are |
| 228 | // incorrect/insane (for example, a 'percentage' value outside the |
| 229 | // range of 0-100). |
| 230 | func SetTunables(t TunableParams) { |
| 231 | checkTunables(t) |
| 232 | tunables = t |
| 233 | } |
| 234 | |
| 235 | var defaultTypeFractions = [9]uint8{ |
| 236 | 10, // struct |
| 237 | 10, // array |
| 238 | 10, // map |
| 239 | 15, // pointer |
| 240 | 20, // numeric |
| 241 | 15, // float |
| 242 | 5, // complex |
| 243 | 5, // byte |
| 244 | 10, // string |
| 245 | } |
| 246 | |
| 247 | const ( |
| 248 | // Param not address taken. |
| 249 | StructTfIdx = iota |
| 250 | ArrayTfIdx |
| 251 | MapTfIdx |
| 252 | PointerTfIdx |
| 253 | NumericTfIdx |
| 254 | FloatTfIdx |
| 255 | ComplexTfIdx |
| 256 | ByteTfIdx |
| 257 | StringTfIdx |
| 258 | ) |
| 259 | |
| 260 | var tunables = TunableParams{ |
| 261 | nParmRange: 15, |
| 262 | nReturnRange: 7, |
| 263 | nStructFields: 7, |
| 264 | nArrayElements: 5, |
| 265 | sliceFraction: 50, |
| 266 | intBitRanges: [4]uint8{30, 20, 20, 30}, |
| 267 | floatBitRanges: [2]uint8{50, 50}, |
| 268 | unsignedRanges: [2]uint8{50, 50}, |
| 269 | blankPerc: 15, |
| 270 | structDepth: 3, |
| 271 | typeFractions: defaultTypeFractions, |
| 272 | recurPerc: 20, |
| 273 | methodPerc: 10, |
| 274 | pointerMethodCallPerc: 50, |
| 275 | doReflectCall: true, |
| 276 | doDefer: true, |
| 277 | takeAddress: true, |
| 278 | doFuncCallValues: true, |
| 279 | takenFraction: 20, |
| 280 | deferFraction: 30, |
| 281 | funcCallValFraction: 5, |
| 282 | doSkipCompare: true, |
| 283 | skipCompareFraction: 10, |
| 284 | addrFractions: [4]uint8{50, 25, 15, 10}, |
| 285 | } |
| 286 | |
| 287 | func DefaultTunables() TunableParams { |
| 288 | return tunables |
| 289 | } |
| 290 | |
| 291 | func checkTunables(t TunableParams) { |
| 292 | var s int = 0 |
| 293 | |
| 294 | for _, v := range t.intBitRanges { |
| 295 | s += int(v) |
| 296 | } |
| 297 | if s != 100 { |
| 298 | log.Fatal(errors.New("intBitRanges tunable does not sum to 100")) |
| 299 | } |
| 300 | |
| 301 | s = 0 |
| 302 | for _, v := range t.unsignedRanges { |
| 303 | s += int(v) |
| 304 | } |
| 305 | if s != 100 { |
| 306 | log.Fatal(errors.New("unsignedRanges tunable does not sum to 100")) |
| 307 | } |
| 308 | |
| 309 | if t.blankPerc > 100 { |
| 310 | log.Fatal(errors.New("blankPerc bad value, over 100")) |
| 311 | } |
| 312 | if t.recurPerc > 100 { |
| 313 | log.Fatal(errors.New("recurPerc bad value, over 100")) |
| 314 | } |
| 315 | if t.methodPerc > 100 { |
| 316 | log.Fatal(errors.New("methodPerc bad value, over 100")) |
| 317 | } |
| 318 | if t.pointerMethodCallPerc > 100 { |
| 319 | log.Fatal(errors.New("pointerMethodCallPerc bad value, over 100")) |
| 320 | } |
| 321 | |
| 322 | s = 0 |
| 323 | for _, v := range t.floatBitRanges { |
| 324 | s += int(v) |
| 325 | } |
| 326 | if s != 100 { |
| 327 | log.Fatal(errors.New("floatBitRanges tunable does not sum to 100")) |
| 328 | } |
| 329 | |
| 330 | s = 0 |
| 331 | for _, v := range t.typeFractions { |
| 332 | s += int(v) |
| 333 | } |
| 334 | if s != 100 { |
| 335 | panic(errors.New("typeFractions tunable does not sum to 100")) |
| 336 | } |
| 337 | |
| 338 | s = 0 |
| 339 | for _, v := range t.addrFractions { |
| 340 | s += int(v) |
| 341 | } |
| 342 | if s != 100 { |
| 343 | log.Fatal(errors.New("addrFractions tunable does not sum to 100")) |
| 344 | } |
| 345 | if t.takenFraction > 100 { |
| 346 | log.Fatal(errors.New("takenFraction not between 0 and 100")) |
| 347 | } |
| 348 | if t.deferFraction > 100 { |
| 349 | log.Fatal(errors.New("deferFraction not between 0 and 100")) |
| 350 | } |
| 351 | if t.sliceFraction > 100 { |
| 352 | log.Fatal(errors.New("sliceFraction not between 0 and 100")) |
| 353 | } |
| 354 | if t.skipCompareFraction > 100 { |
| 355 | log.Fatal(errors.New("skipCompareFraction not between 0 and 100")) |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | func (t *TunableParams) DisableReflectionCalls() { |
| 360 | t.doReflectCall = false |
| 361 | } |
| 362 | |
| 363 | func (t *TunableParams) DisableRecursiveCalls() { |
| 364 | t.recurPerc = 0 |
| 365 | } |
| 366 | |
| 367 | func (t *TunableParams) DisableMethodCalls() { |
| 368 | t.methodPerc = 0 |
| 369 | } |
| 370 | |
| 371 | func (t *TunableParams) DisableTakeAddr() { |
| 372 | t.takeAddress = false |
| 373 | } |
| 374 | |
| 375 | func (t *TunableParams) DisableDefer() { |
| 376 | t.doDefer = false |
| 377 | } |
| 378 | |
| 379 | func (t *TunableParams) LimitInputs(n int) error { |
| 380 | if n > 100 { |
| 381 | return fmt.Errorf("value %d passed to LimitInputs is too large *(max 100)", n) |
| 382 | } |
| 383 | if n < 0 { |
| 384 | return fmt.Errorf("value %d passed to LimitInputs is invalid", n) |
| 385 | } |
| 386 | t.nParmRange = uint8(n) |
| 387 | return nil |
| 388 | } |
| 389 | |
| 390 | func (t *TunableParams) LimitOutputs(n int) error { |
| 391 | if n > 100 { |
| 392 | return fmt.Errorf("value %d passed to LimitOutputs is too large *(max 100)", n) |
| 393 | } |
| 394 | if n < 0 { |
| 395 | return fmt.Errorf("value %d passed to LimitOutputs is invalid", n) |
| 396 | } |
| 397 | t.nReturnRange = uint8(n) |
| 398 | return nil |
| 399 | } |
| 400 | |
| 401 | // ParseMaskString parses a string of the form K,J,...,M-N,Q-R,...,Z |
| 402 | // e.g. comma-separated integers or ranges of integers, returning the |
| 403 | // result in a form suitable for FcnMask or PkgMask fields in a |
| 404 | // Config. Here "tag" holds the mask flavor (fcn or pkg) and "arg" is |
| 405 | // the string argument to be parsed. |
| 406 | func ParseMaskString(arg string, tag string) (map[int]int, error) { |
| 407 | if arg == "" { |
| 408 | return nil, nil |
| 409 | } |
| 410 | verb(1, "%s mask is %s", tag, arg) |
| 411 | m := make(map[int]int) |
| 412 | for s := range strings.SplitSeq(arg, ":") { |
| 413 | if strings.Contains(s, "-") { |
| 414 | rng := strings.Split(s, "-") |
| 415 | if len(rng) != 2 { |
| 416 | return nil, fmt.Errorf("malformed range %s in %s mask arg", s, tag) |
| 417 | } |
| 418 | i, err := strconv.Atoi(rng[0]) |
| 419 | if err != nil { |
| 420 | return nil, fmt.Errorf("malformed range value %s in %s mask arg", rng[0], tag) |
| 421 | } |
| 422 | j, err2 := strconv.Atoi(rng[1]) |
| 423 | if err2 != nil { |
| 424 | return nil, fmt.Errorf("malformed range value %s in %s mask arg", rng[1], tag) |
| 425 | } |
| 426 | for k := i; k < j; k++ { |
| 427 | m[k] = 1 |
| 428 | } |
| 429 | } else { |
| 430 | i, err := strconv.Atoi(s) |
| 431 | if err != nil { |
| 432 | return nil, fmt.Errorf("malformed value %s in %s mask arg", s, tag) |
| 433 | } |
| 434 | m[i] = 1 |
| 435 | } |
| 436 | } |
| 437 | return m, nil |
| 438 | } |
| 439 | |
| 440 | func writeCom(b *bytes.Buffer, i int) { |
| 441 | if i != 0 { |
| 442 | b.WriteString(", ") |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | var Verbctl int = 0 |
| 447 | |
| 448 | func verb(vlevel int, s string, a ...any) { |
| 449 | if Verbctl >= vlevel { |
| 450 | fmt.Printf(s, a...) |
| 451 | fmt.Printf("\n") |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | type funcdef struct { |
| 456 | idx int |
| 457 | structdefs []structparm |
| 458 | arraydefs []arrayparm |
| 459 | typedefs []typedefparm |
| 460 | mapdefs []mapparm |
| 461 | mapkeytypes []parm |
| 462 | mapkeytmps []string |
| 463 | mapkeyts string |
| 464 | receiver parm |
| 465 | params []parm |
| 466 | returns []parm |
| 467 | values []int |
| 468 | dodefc uint8 |
| 469 | dodefp []uint8 |
| 470 | rstack int |
| 471 | recur bool |
| 472 | isMethod bool |
| 473 | } |
| 474 | |
| 475 | type genstate struct { |
| 476 | GenConfig |
| 477 | ipref string |
| 478 | //tag string |
| 479 | //numtpk int |
| 480 | pkidx int |
| 481 | errs int |
| 482 | //pragma string |
| 483 | //sforce bool |
| 484 | //randctl int |
| 485 | tunables TunableParams |
| 486 | tstack []TunableParams |
| 487 | derefFuncs map[string]string |
| 488 | newDerefFuncs []funcdesc |
| 489 | assignFuncs map[string]string |
| 490 | newAssignFuncs []funcdesc |
| 491 | allocFuncs map[string]string |
| 492 | newAllocFuncs []funcdesc |
| 493 | genvalFuncs map[string]string |
| 494 | newGenvalFuncs []funcdesc |
| 495 | globVars map[string]string |
| 496 | newGlobVars []funcdesc |
| 497 | wr *wraprand |
| 498 | } |
| 499 | |
| 500 | func (s *genstate) intFlavor() string { |
| 501 | which := uint8(s.wr.Intn(100)) |
| 502 | if which < s.tunables.unsignedRanges[0] { |
| 503 | return "uint" |
| 504 | } |
| 505 | return "int" |
| 506 | } |
| 507 | |
| 508 | func (s *genstate) intBits() uint32 { |
| 509 | which := uint8(s.wr.Intn(100)) |
| 510 | var t uint8 = 0 |
| 511 | var bits uint32 = 8 |
| 512 | for _, v := range s.tunables.intBitRanges { |
| 513 | t += v |
| 514 | if which < t { |
| 515 | return bits |
| 516 | } |
| 517 | bits *= 2 |
| 518 | } |
| 519 | return uint32(s.tunables.intBitRanges[3]) |
| 520 | } |
| 521 | |
| 522 | func (s *genstate) floatBits() uint32 { |
| 523 | which := uint8(s.wr.Intn(100)) |
| 524 | if which < s.tunables.floatBitRanges[0] { |
| 525 | return uint32(32) |
| 526 | } |
| 527 | return uint32(64) |
| 528 | } |
| 529 | |
| 530 | func (s *genstate) genAddrTaken() addrTakenHow { |
| 531 | which := uint8(s.wr.Intn(100)) |
| 532 | res := notAddrTaken |
| 533 | var t uint8 = 0 |
| 534 | for _, v := range s.tunables.addrFractions { |
| 535 | t += v |
| 536 | if which < t { |
| 537 | return res |
| 538 | } |
| 539 | res++ |
| 540 | } |
| 541 | return notAddrTaken |
| 542 | } |
| 543 | |
| 544 | func (s *genstate) pushTunables() { |
| 545 | s.tstack = append(s.tstack, s.tunables) |
| 546 | } |
| 547 | |
| 548 | func (s *genstate) popTunables() { |
| 549 | if len(s.tstack) == 0 { |
| 550 | panic("untables stack underflow") |
| 551 | } |
| 552 | s.tunables = s.tstack[0] |
| 553 | s.tstack = s.tstack[1:] |
| 554 | } |
| 555 | |
| 556 | // redistributeFraction accepts a value 'toIncorporate' and updates |
| 557 | // 'typeFraction' to add in the values from 'toIncorporate' equally to |
| 558 | // all slots not in 'avoid'. This is done by successively walking |
| 559 | // through 'typeFraction' adding 1 to each non-avoid slot, then |
| 560 | // repeating until we've added a total of 'toIncorporate' elements. |
| 561 | // See precludeSelectedTypes below for more info. |
| 562 | func (s *genstate) redistributeFraction(toIncorporate uint8, avoid []int) { |
| 563 | inavoid := func(j int) bool { |
| 564 | return slices.Contains(avoid, j) |
| 565 | } |
| 566 | |
| 567 | doredis := func() { |
| 568 | for { |
| 569 | for i := range s.tunables.typeFractions { |
| 570 | if inavoid(i) { |
| 571 | continue |
| 572 | } |
| 573 | s.tunables.typeFractions[i]++ |
| 574 | toIncorporate-- |
| 575 | if toIncorporate == 0 { |
| 576 | return |
| 577 | } |
| 578 | } |
| 579 | } |
| 580 | } |
| 581 | doredis() |
| 582 | checkTunables(s.tunables) |
| 583 | } |
| 584 | |
| 585 | // precludeSelectedTypes accepts a set of values (t, t2, ...) |
| 586 | // corresponding to slots in 'typeFractions', sums up the values from |
| 587 | // the slots, zeroes out the slots, and finally takes the values and |
| 588 | // redistributes them equally to the other slots. For example, |
| 589 | // suppose 'typeFractions' starts as [10, 10, 10, 15, 20, 15, 5, 5, 10], |
| 590 | // then we decide we want to eliminate or 'knock out' map types and |
| 591 | // pointer types (slots 2 and 3 in the array above) going forward. To |
| 592 | // restore the invariant that values in 'typeFractions' sum to 100, we |
| 593 | // take the values from slots 2 and 3 (a total of 25) and evenly |
| 594 | // distribute those values to the other slots in the array. |
| 595 | func (s *genstate) precludeSelectedTypes(t int, t2 ...int) { |
| 596 | avoid := []int{t} |
| 597 | avoid = append(avoid, t2...) |
| 598 | f := uint8(0) |
| 599 | for _, idx := range avoid { |
| 600 | f += s.tunables.typeFractions[idx] |
| 601 | s.tunables.typeFractions[idx] = 0 |
| 602 | } |
| 603 | s.redistributeFraction(f, avoid) |
| 604 | } |
| 605 | |
| 606 | func (s *genstate) GenMapKeyType(f *funcdef, depth int, pidx int) parm { |
| 607 | s.pushTunables() |
| 608 | defer s.popTunables() |
| 609 | // maps we can't allow at all; pointers might be possible but |
| 610 | // would be too much work to arrange. Avoid slices as well. |
| 611 | s.tunables.sliceFraction = 0 |
| 612 | s.precludeSelectedTypes(MapTfIdx, PointerTfIdx) |
| 613 | return s.GenParm(f, depth+1, false, pidx) |
| 614 | } |
| 615 | |
| 616 | func (s *genstate) GenParm(f *funcdef, depth int, mkctl bool, pidx int) parm { |
| 617 | |
| 618 | // Enforcement for struct/array/map/pointer array nesting depth. |
| 619 | toodeep := depth >= int(s.tunables.structDepth) |
| 620 | if toodeep { |
| 621 | s.pushTunables() |
| 622 | defer s.popTunables() |
| 623 | s.precludeSelectedTypes(StructTfIdx, ArrayTfIdx, MapTfIdx, PointerTfIdx) |
| 624 | } |
| 625 | |
| 626 | // Convert tf into a cumulative sum |
| 627 | tf := s.tunables.typeFractions |
| 628 | sum := uint8(0) |
| 629 | for i := range len(tf) { |
| 630 | sum += tf[i] |
| 631 | tf[i] = sum |
| 632 | } |
| 633 | |
| 634 | isblank := uint8(s.wr.Intn(100)) < s.tunables.blankPerc |
| 635 | addrTaken := notAddrTaken |
| 636 | if depth == 0 && tunables.takeAddress && !isblank { |
| 637 | addrTaken = s.genAddrTaken() |
| 638 | } |
| 639 | isGenValFunc := tunables.doFuncCallValues && |
| 640 | uint8(s.wr.Intn(100)) < s.tunables.funcCallValFraction |
| 641 | |
| 642 | // Make adjusted selection (pick a bucket within tf) |
| 643 | which := uint8(s.wr.Intn(100)) |
| 644 | verb(3, "which=%d", which) |
| 645 | var retval parm |
| 646 | switch { |
| 647 | case which < tf[StructTfIdx]: |
| 648 | { |
| 649 | if toodeep { |
| 650 | panic("should not be here") |
| 651 | } |
| 652 | var sp structparm |
| 653 | ns := len(f.structdefs) |
| 654 | sp.sname = fmt.Sprintf("StructF%dS%d", f.idx, ns) |
| 655 | sp.qname = fmt.Sprintf("%s.StructF%dS%d", |
| 656 | s.checkerPkg(pidx), f.idx, ns) |
| 657 | f.structdefs = append(f.structdefs, sp) |
| 658 | tnf := int64(s.tunables.nStructFields) / int64(depth+1) |
| 659 | nf := int(s.wr.Intn(tnf)) |
| 660 | for range nf { |
| 661 | fp := s.GenParm(f, depth+1, false, pidx) |
| 662 | skComp := tunables.doSkipCompare && |
| 663 | uint8(s.wr.Intn(100)) < s.tunables.skipCompareFraction |
| 664 | if skComp && checkableElements(fp) != 0 { |
| 665 | fp.SetSkipCompare(SkipAll) |
| 666 | } |
| 667 | sp.fields = append(sp.fields, fp) |
| 668 | } |
| 669 | f.structdefs[ns] = sp |
| 670 | retval = &sp |
| 671 | } |
| 672 | case which < tf[ArrayTfIdx]: |
| 673 | { |
| 674 | if toodeep { |
| 675 | panic("should not be here") |
| 676 | } |
| 677 | var ap arrayparm |
| 678 | ns := len(f.arraydefs) |
| 679 | nel := uint8(s.wr.Intn(int64(s.tunables.nArrayElements))) |
| 680 | issl := uint8(s.wr.Intn(100)) < s.tunables.sliceFraction |
| 681 | ap.aname = fmt.Sprintf("ArrayF%dS%dE%d", f.idx, ns, nel) |
| 682 | ap.qname = fmt.Sprintf("%s.ArrayF%dS%dE%d", s.checkerPkg(pidx), |
| 683 | f.idx, ns, nel) |
| 684 | f.arraydefs = append(f.arraydefs, ap) |
| 685 | ap.nelements = nel |
| 686 | ap.slice = issl |
| 687 | ap.eltype = s.GenParm(f, depth+1, false, pidx) |
| 688 | ap.eltype.SetBlank(false) |
| 689 | skComp := tunables.doSkipCompare && |
| 690 | uint8(s.wr.Intn(100)) < s.tunables.skipCompareFraction |
| 691 | if skComp && checkableElements(ap.eltype) != 0 { |
| 692 | if issl { |
| 693 | ap.SetSkipCompare(SkipPayload) |
| 694 | } |
| 695 | } |
| 696 | f.arraydefs[ns] = ap |
| 697 | retval = &ap |
| 698 | } |
| 699 | case which < tf[MapTfIdx]: |
| 700 | { |
| 701 | if toodeep { |
| 702 | panic("should not be here") |
| 703 | } |
| 704 | var mp mapparm |
| 705 | ns := len(f.mapdefs) |
| 706 | |
| 707 | // append early, since calls below might also append |
| 708 | f.mapdefs = append(f.mapdefs, mp) |
| 709 | f.mapkeytmps = append(f.mapkeytmps, "") |
| 710 | f.mapkeytypes = append(f.mapkeytypes, mp.keytype) |
| 711 | mp.aname = fmt.Sprintf("MapF%dM%d", f.idx, ns) |
| 712 | if f.mapkeyts == "" { |
| 713 | f.mapkeyts = fmt.Sprintf("MapKeysF%d", f.idx) |
| 714 | } |
| 715 | mp.qname = fmt.Sprintf("%s.MapF%dM%d", s.checkerPkg(pidx), |
| 716 | f.idx, ns) |
| 717 | mkt := fmt.Sprintf("Mk%dt%d", f.idx, ns) |
| 718 | mp.keytmp = mkt |
| 719 | mk := s.GenMapKeyType(f, depth+1, pidx) |
| 720 | mp.keytype = mk |
| 721 | mp.valtype = s.GenParm(f, depth+1, false, pidx) |
| 722 | mp.valtype.SetBlank(false) |
| 723 | mp.keytype.SetBlank(false) |
| 724 | // now update the previously appended placeholders |
| 725 | f.mapdefs[ns] = mp |
| 726 | f.mapkeytypes[ns] = mk |
| 727 | f.mapkeytmps[ns] = mkt |
| 728 | retval = &mp |
| 729 | } |
| 730 | case which < tf[PointerTfIdx]: |
| 731 | { |
| 732 | if toodeep { |
| 733 | panic("should not be here") |
| 734 | } |
| 735 | pp := mkPointerParm(s.GenParm(f, depth+1, false, pidx)) |
| 736 | retval = &pp |
| 737 | } |
| 738 | case which < tf[NumericTfIdx]: |
| 739 | { |
| 740 | var ip numparm |
| 741 | ip.tag = s.intFlavor() |
| 742 | ip.widthInBits = s.intBits() |
| 743 | if mkctl { |
| 744 | ip.ctl = true |
| 745 | } |
| 746 | retval = &ip |
| 747 | } |
| 748 | case which < tf[FloatTfIdx]: |
| 749 | { |
| 750 | var fp numparm |
| 751 | fp.tag = "float" |
| 752 | fp.widthInBits = s.floatBits() |
| 753 | retval = &fp |
| 754 | } |
| 755 | case which < tf[ComplexTfIdx]: |
| 756 | { |
| 757 | var fp numparm |
| 758 | fp.tag = "complex" |
| 759 | fp.widthInBits = s.floatBits() * 2 |
| 760 | retval = &fp |
| 761 | } |
| 762 | case which < tf[ByteTfIdx]: |
| 763 | { |
| 764 | var bp numparm |
| 765 | bp.tag = "byte" |
| 766 | bp.widthInBits = 8 |
| 767 | retval = &bp |
| 768 | } |
| 769 | case which < tf[StringTfIdx]: |
| 770 | { |
| 771 | var sp stringparm |
| 772 | sp.tag = "string" |
| 773 | skComp := tunables.doSkipCompare && |
| 774 | uint8(s.wr.Intn(100)) < s.tunables.skipCompareFraction |
| 775 | if skComp { |
| 776 | sp.SetSkipCompare(SkipPayload) |
| 777 | } |
| 778 | retval = &sp |
| 779 | } |
| 780 | default: |
| 781 | { |
| 782 | // fallback |
| 783 | var ip numparm |
| 784 | ip.tag = "uint" |
| 785 | ip.widthInBits = 8 |
| 786 | retval = &ip |
| 787 | } |
| 788 | } |
| 789 | if !mkctl { |
| 790 | retval.SetBlank(isblank) |
| 791 | } |
| 792 | retval.SetAddrTaken(addrTaken) |
| 793 | retval.SetIsGenVal(isGenValFunc) |
| 794 | return retval |
| 795 | } |
| 796 | |
| 797 | func (s *genstate) GenReturn(f *funcdef, depth int, pidx int) parm { |
| 798 | return s.GenParm(f, depth, false, pidx) |
| 799 | } |
| 800 | |
| 801 | // GenFunc cooks up the random signature (and other attributes) of a |
| 802 | // given checker function, returning a funcdef object that describes |
| 803 | // the new fcn. |
| 804 | func (s *genstate) GenFunc(fidx int, pidx int) *funcdef { |
| 805 | f := new(funcdef) |
| 806 | f.idx = fidx |
| 807 | numParams := int(s.wr.Intn(int64(1 + int(s.tunables.nParmRange)))) |
| 808 | numReturns := int(s.wr.Intn(int64(1 + int(s.tunables.nReturnRange)))) |
| 809 | f.recur = uint8(s.wr.Intn(100)) < s.tunables.recurPerc |
| 810 | f.isMethod = uint8(s.wr.Intn(100)) < s.tunables.methodPerc |
| 811 | genReceiverType := func() { |
| 812 | // Receiver type can't be pointer type. Temporarily update |
| 813 | // tunables to eliminate that possibility. |
| 814 | s.pushTunables() |
| 815 | defer s.popTunables() |
| 816 | s.precludeSelectedTypes(PointerTfIdx) |
| 817 | target := s.GenParm(f, 0, false, pidx) |
| 818 | target.SetBlank(false) |
| 819 | f.receiver = s.makeTypedefParm(f, target, pidx) |
| 820 | if f.receiver.IsBlank() { |
| 821 | f.recur = false |
| 822 | } |
| 823 | } |
| 824 | if f.isMethod { |
| 825 | genReceiverType() |
| 826 | } |
| 827 | needControl := f.recur |
| 828 | f.dodefc = uint8(s.wr.Intn(100)) |
| 829 | pTaken := uint8(s.wr.Intn(100)) < s.tunables.takenFraction |
| 830 | for range numParams { |
| 831 | newparm := s.GenParm(f, 0, needControl, pidx) |
| 832 | if !pTaken { |
| 833 | newparm.SetAddrTaken(notAddrTaken) |
| 834 | } |
| 835 | if newparm.IsControl() { |
| 836 | needControl = false |
| 837 | } |
| 838 | f.params = append(f.params, newparm) |
| 839 | f.dodefp = append(f.dodefp, uint8(s.wr.Intn(100))) |
| 840 | } |
| 841 | if f.recur && needControl { |
| 842 | f.recur = false |
| 843 | } |
| 844 | |
| 845 | rTaken := uint8(s.wr.Intn(100)) < s.tunables.takenFraction |
| 846 | for range numReturns { |
| 847 | r := s.GenReturn(f, 0, pidx) |
| 848 | if !rTaken { |
| 849 | r.SetAddrTaken(notAddrTaken) |
| 850 | } |
| 851 | f.returns = append(f.returns, r) |
| 852 | } |
| 853 | spw := uint(s.wr.Intn(11)) |
| 854 | rstack := max(1<<spw, 4) |
| 855 | f.rstack = rstack |
| 856 | return f |
| 857 | } |
| 858 | |
| 859 | func genDeref(p parm) (parm, string) { |
| 860 | curp := p |
| 861 | var star strings.Builder |
| 862 | for { |
| 863 | if pp, ok := curp.(*pointerparm); ok { |
| 864 | star.WriteString("*") |
| 865 | curp = pp.totype |
| 866 | } else { |
| 867 | return curp, star.String() |
| 868 | } |
| 869 | } |
| 870 | } |
| 871 | |
| 872 | func (s *genstate) eqFuncRef(f *funcdef, t parm, caller bool) string { |
| 873 | cp := "" |
| 874 | if f.mapkeyts != "" { |
| 875 | cp = "mkt." |
| 876 | } else if caller { |
| 877 | cp = s.checkerPkg(s.pkidx) + "." |
| 878 | } |
| 879 | return cp + "Equal" + t.TypeName() |
| 880 | } |
| 881 | |
| 882 | // emitCompareFunc creates an 'equals' function for a specific |
| 883 | // generated type (this is basically a way to compare objects that |
| 884 | // contain pointer fields / pointery things). |
| 885 | func (s *genstate) emitCompareFunc(f *funcdef, b *bytes.Buffer, p parm) { |
| 886 | if !p.HasPointer() { |
| 887 | return |
| 888 | } |
| 889 | |
| 890 | tn := p.TypeName() |
| 891 | b.WriteString(fmt.Sprintf("// equal func for %s\n", tn)) |
| 892 | b.WriteString("//go:noinline\n") |
| 893 | rcvr := "" |
| 894 | if f.mapkeyts != "" { |
| 895 | rcvr = fmt.Sprintf("(mkt *%s) ", f.mapkeyts) |
| 896 | } |
| 897 | b.WriteString(fmt.Sprintf("func %sEqual%s(left %s, right %s) bool {\n", rcvr, tn, tn, tn)) |
| 898 | b.WriteString(" return ") |
| 899 | numel := p.NumElements() |
| 900 | ncmp := 0 |
| 901 | for i := range numel { |
| 902 | lelref, lelparm := p.GenElemRef(i, "left") |
| 903 | relref, _ := p.GenElemRef(i, "right") |
| 904 | if lelref == "" || lelref == "_" { |
| 905 | continue |
| 906 | } |
| 907 | basep, star := genDeref(lelparm) |
| 908 | // Handle *p where p is an empty struct. |
| 909 | if basep.NumElements() == 0 { |
| 910 | continue |
| 911 | } |
| 912 | if ncmp != 0 { |
| 913 | b.WriteString(" && ") |
| 914 | } |
| 915 | ncmp++ |
| 916 | if basep.HasPointer() { |
| 917 | efn := s.eqFuncRef(f, basep, false) |
| 918 | b.WriteString(fmt.Sprintf(" %s(%s%s, %s%s)", efn, star, lelref, star, relref)) |
| 919 | } else { |
| 920 | b.WriteString(fmt.Sprintf("%s%s == %s%s", star, lelref, star, relref)) |
| 921 | } |
| 922 | } |
| 923 | if ncmp == 0 { |
| 924 | b.WriteString("true") |
| 925 | } |
| 926 | b.WriteString("\n}\n\n") |
| 927 | } |
| 928 | |
| 929 | // emitStructAndArrayDefs writes out definitions of the random types |
| 930 | // we happened to cook up while generating code for a specific |
| 931 | // function pair. |
| 932 | func (s *genstate) emitStructAndArrayDefs(f *funcdef, b *bytes.Buffer) { |
| 933 | for _, str := range f.structdefs { |
| 934 | b.WriteString(fmt.Sprintf("type %s struct {\n", str.sname)) |
| 935 | for fi, sp := range str.fields { |
| 936 | sp.Declare(b, " "+str.FieldName(fi), "\n", false) |
| 937 | } |
| 938 | b.WriteString("}\n\n") |
| 939 | s.emitCompareFunc(f, b, &str) |
| 940 | } |
| 941 | for _, a := range f.arraydefs { |
| 942 | elems := fmt.Sprintf("%d", a.nelements) |
| 943 | if a.slice { |
| 944 | elems = "" |
| 945 | } |
| 946 | b.WriteString(fmt.Sprintf("type %s [%s]%s\n\n", a.aname, |
| 947 | elems, a.eltype.TypeName())) |
| 948 | s.emitCompareFunc(f, b, &a) |
| 949 | } |
| 950 | for _, a := range f.mapdefs { |
| 951 | b.WriteString(fmt.Sprintf("type %s map[%s]%s\n\n", a.aname, |
| 952 | a.keytype.TypeName(), a.valtype.TypeName())) |
| 953 | s.emitCompareFunc(f, b, &a) |
| 954 | } |
| 955 | for _, td := range f.typedefs { |
| 956 | b.WriteString(fmt.Sprintf("type %s %s\n\n", td.aname, |
| 957 | td.target.TypeName())) |
| 958 | s.emitCompareFunc(f, b, &td) |
| 959 | } |
| 960 | if f.mapkeyts != "" { |
| 961 | b.WriteString(fmt.Sprintf("type %s struct {\n", f.mapkeyts)) |
| 962 | for i := range f.mapkeytypes { |
| 963 | f.mapkeytypes[i].Declare(b, " "+f.mapkeytmps[i], "\n", false) |
| 964 | } |
| 965 | b.WriteString("}\n\n") |
| 966 | } |
| 967 | } |
| 968 | |
| 969 | // GenValue method of genstate wraps the parm method of the same |
| 970 | // name, but optionally returns a call to a function to produce |
| 971 | // the value as opposed to a literal value. |
| 972 | func (s *genstate) GenValue(f *funcdef, p parm, value int, caller bool) (string, int) { |
| 973 | var valstr string |
| 974 | valstr, value = p.GenValue(s, f, value, caller) |
| 975 | if !s.tunables.doFuncCallValues || !p.IsGenVal() || caller { |
| 976 | return valstr, value |
| 977 | } |
| 978 | |
| 979 | mkInvoc := func(fname string) string { |
| 980 | meth := "" |
| 981 | if f.mapkeyts != "" { |
| 982 | meth = "mkt." |
| 983 | } |
| 984 | return fmt.Sprintf("%s%s()", meth, fname) |
| 985 | } |
| 986 | |
| 987 | b := bytes.NewBuffer(nil) |
| 988 | p.Declare(b, "x", "", false) |
| 989 | h := sha1.New() |
| 990 | h.Write([]byte(valstr)) |
| 991 | h.Write(b.Bytes()) |
| 992 | if f.mapkeyts != "" { |
| 993 | h.Write([]byte(f.mapkeyts)) |
| 994 | } |
| 995 | h.Write(b.Bytes()) |
| 996 | bs := h.Sum(nil) |
| 997 | hashstr := fmt.Sprintf("%x", bs) |
| 998 | b.WriteString(hashstr) |
| 999 | tag := b.String() |
| 1000 | fname, ok := s.genvalFuncs[tag] |
| 1001 | if ok { |
| 1002 | return mkInvoc(fname), value |
| 1003 | } |
| 1004 | |
| 1005 | fname = fmt.Sprintf("genval_%d", len(s.genvalFuncs)) |
| 1006 | s.newGenvalFuncs = append(s.newGenvalFuncs, funcdesc{p: p, name: fname, tag: tag, payload: valstr}) |
| 1007 | s.genvalFuncs[tag] = fname |
| 1008 | return mkInvoc(fname), value |
| 1009 | } |
| 1010 | |
| 1011 | func (s *genstate) emitMapKeyTmps(f *funcdef, b *bytes.Buffer, pidx int, value int, caller bool) int { |
| 1012 | if f.mapkeyts == "" { |
| 1013 | return value |
| 1014 | } |
| 1015 | // map key tmps |
| 1016 | cp := "" |
| 1017 | if caller { |
| 1018 | cp = s.checkerPkg(pidx) + "." |
| 1019 | } |
| 1020 | b.WriteString(" var mkt " + cp + f.mapkeyts + "\n") |
| 1021 | for i, t := range f.mapkeytypes { |
| 1022 | var keystr string |
| 1023 | keystr, value = s.GenValue(f, t, value, caller) |
| 1024 | tname := f.mapkeytmps[i] |
| 1025 | b.WriteString(fmt.Sprintf(" %s := %s\n", tname, keystr)) |
| 1026 | b.WriteString(fmt.Sprintf(" mkt.%s = %s\n", tname, tname)) |
| 1027 | } |
| 1028 | return value |
| 1029 | } |
| 1030 | |
| 1031 | func (s *genstate) emitCheckReturnsInCaller(f *funcdef, b *bytes.Buffer, pidx int, reflectCall bool) { |
| 1032 | cm := f.complexityMeasure() |
| 1033 | rvalp := func(ri int) string { |
| 1034 | if reflectCall { |
| 1035 | return fmt.Sprintf("rr%dv", ri) |
| 1036 | } |
| 1037 | return fmt.Sprintf("r%d", ri) |
| 1038 | } |
| 1039 | failTag := "\"return\"" |
| 1040 | if reflectCall { |
| 1041 | failTag = "\"reflect return\"" |
| 1042 | } |
| 1043 | for ri, rp := range f.returns { |
| 1044 | if reflectCall { |
| 1045 | b.WriteString(fmt.Sprintf(" rr%di := rvslice[%d].Interface()\n", ri, ri)) |
| 1046 | b.WriteString(fmt.Sprintf(" rr%dv:= rr%di.(", ri, ri)) |
| 1047 | rp.Declare(b, "", "", true) |
| 1048 | b.WriteString(")\n") |
| 1049 | } |
| 1050 | pfc := "" |
| 1051 | curp, star := genDeref(rp) |
| 1052 | // Handle *p where p is an empty struct. |
| 1053 | if curp.NumElements() == 0 { |
| 1054 | b.WriteString(fmt.Sprintf(" _, _ = %s, c%d // zero size\n", rvalp(ri), ri)) |
| 1055 | continue |
| 1056 | } |
| 1057 | if star != "" { |
| 1058 | pfc = fmt.Sprintf("ParamFailCount[%d] == 0 && ", pidx) |
| 1059 | } |
| 1060 | if curp.HasPointer() { |
| 1061 | efn := "!" + s.eqFuncRef(f, curp, true) |
| 1062 | b.WriteString(fmt.Sprintf(" if %s%s(%s%s, %sc%d) {\n", pfc, efn, star, rvalp(ri), star, ri)) |
| 1063 | } else { |
| 1064 | b.WriteString(fmt.Sprintf(" if %s%s%s != %sc%d {\n", pfc, star, rvalp(ri), star, ri)) |
| 1065 | } |
| 1066 | b.WriteString(fmt.Sprintf(" NoteFailure(%d, %d, %d, \"%s\", %s, %d, true, uint64(0))\n", cm, pidx, f.idx, s.checkerPkg(pidx), failTag, ri)) |
| 1067 | b.WriteString(" }\n") |
| 1068 | } |
| 1069 | } |
| 1070 | |
| 1071 | func (s *genstate) emitCaller(f *funcdef, b *bytes.Buffer, pidx int) { |
| 1072 | |
| 1073 | b.WriteString(fmt.Sprintf("func %s%d(mode string) {\n", CallerName, f.idx)) |
| 1074 | |
| 1075 | b.WriteString(fmt.Sprintf(" BeginFcn(%d)\n", pidx)) |
| 1076 | |
| 1077 | if s.EmitBad == 1 { |
| 1078 | if s.BadPackageIdx == pidx && s.BadFuncIdx == f.idx { |
| 1079 | b.WriteString(" bad code here, should cause build failure <<==\n") |
| 1080 | } |
| 1081 | } |
| 1082 | |
| 1083 | var value int = 1 |
| 1084 | |
| 1085 | s.wr.Checkpoint("before mapkeytmps") |
| 1086 | value = s.emitMapKeyTmps(f, b, pidx, value, true) |
| 1087 | |
| 1088 | // generate return constants |
| 1089 | s.wr.Checkpoint("before return constants") |
| 1090 | for ri, r := range f.returns { |
| 1091 | rc := fmt.Sprintf("c%d", ri) |
| 1092 | value = s.emitVarAssign(f, b, r, rc, value, true) |
| 1093 | } |
| 1094 | |
| 1095 | // generate param constants |
| 1096 | s.wr.Checkpoint("before param constants") |
| 1097 | for pi, p := range f.params { |
| 1098 | verb(4, "emitCaller gen p%d value=%d", pi, value) |
| 1099 | if p.IsControl() { |
| 1100 | _ = uint8(s.wr.Intn(100)) < 50 |
| 1101 | p.Declare(b, fmt.Sprintf(" var p%d ", pi), " = 10\n", true) |
| 1102 | } else { |
| 1103 | pc := fmt.Sprintf("p%d", pi) |
| 1104 | value = s.emitVarAssign(f, b, p, pc, value, true) |
| 1105 | } |
| 1106 | f.values = append(f.values, value) |
| 1107 | } |
| 1108 | |
| 1109 | // generate receiver constant if applicable |
| 1110 | if f.isMethod { |
| 1111 | s.wr.Checkpoint("before receiver constant") |
| 1112 | f.receiver.Declare(b, " var rcvr", "\n", true) |
| 1113 | valstr, value := s.GenValue(f, f.receiver, value, true) |
| 1114 | b.WriteString(fmt.Sprintf(" rcvr = %s\n", valstr)) |
| 1115 | f.values = append(f.values, value) |
| 1116 | } |
| 1117 | |
| 1118 | b.WriteString(fmt.Sprintf(" Mode[%d] = \"\"\n", pidx)) |
| 1119 | |
| 1120 | // calling code |
| 1121 | b.WriteString(fmt.Sprintf(" // %d returns %d params\n", |
| 1122 | len(f.returns), len(f.params))) |
| 1123 | if s.ForceStackGrowth { |
| 1124 | b.WriteString(" hackStack() // force stack growth on next call\n") |
| 1125 | } |
| 1126 | b.WriteString(" if mode == \"normal\" {\n") |
| 1127 | b.WriteString(" ") |
| 1128 | for ri := range f.returns { |
| 1129 | writeCom(b, ri) |
| 1130 | b.WriteString(fmt.Sprintf("r%d", ri)) |
| 1131 | } |
| 1132 | if len(f.returns) > 0 { |
| 1133 | b.WriteString(" := ") |
| 1134 | } |
| 1135 | pref := s.checkerPkg(pidx) |
| 1136 | if f.isMethod { |
| 1137 | pref = "rcvr" |
| 1138 | } |
| 1139 | b.WriteString(fmt.Sprintf("%s.Test%d(", pref, f.idx)) |
| 1140 | for pi := range f.params { |
| 1141 | writeCom(b, pi) |
| 1142 | b.WriteString(fmt.Sprintf("p%d", pi)) |
| 1143 | } |
| 1144 | b.WriteString(")\n") |
| 1145 | |
| 1146 | // check values returned (normal call case) |
| 1147 | s.emitCheckReturnsInCaller(f, b, pidx, false /* not a reflect call */) |
| 1148 | b.WriteString(" }") // end of 'if normal call' block |
| 1149 | if s.tunables.doReflectCall { |
| 1150 | b.WriteString("else {\n") // beginning of reflect call block |
| 1151 | // now make the same call via reflection |
| 1152 | b.WriteString(" // same call via reflection\n") |
| 1153 | b.WriteString(fmt.Sprintf(" Mode[%d] = \"reflect\"\n", pidx)) |
| 1154 | if f.isMethod { |
| 1155 | b.WriteString(" rcv := reflect.ValueOf(rcvr)\n") |
| 1156 | b.WriteString(fmt.Sprintf(" rc := rcv.MethodByName(\"Test%d\")\n", f.idx)) |
| 1157 | } else { |
| 1158 | b.WriteString(fmt.Sprintf(" rc := reflect.ValueOf(%s.Test%d)\n", |
| 1159 | s.checkerPkg(pidx), f.idx)) |
| 1160 | } |
| 1161 | b.WriteString(" ") |
| 1162 | if len(f.returns) > 0 { |
| 1163 | b.WriteString("rvslice := ") |
| 1164 | } |
| 1165 | b.WriteString(" rc.Call([]reflect.Value{") |
| 1166 | for pi := range f.params { |
| 1167 | writeCom(b, pi) |
| 1168 | b.WriteString(fmt.Sprintf("reflect.ValueOf(p%d)", pi)) |
| 1169 | } |
| 1170 | b.WriteString("})\n") |
| 1171 | |
| 1172 | // check values returned (reflect call case) |
| 1173 | s.emitCheckReturnsInCaller(f, b, pidx, true /* is a reflect call */) |
| 1174 | b.WriteString("}\n") // end of reflect call block |
| 1175 | } |
| 1176 | |
| 1177 | b.WriteString(fmt.Sprintf("\n EndFcn(%d)\n", pidx)) |
| 1178 | |
| 1179 | b.WriteString("}\n\n") |
| 1180 | } |
| 1181 | |
| 1182 | func checkableElements(p parm) int { |
| 1183 | if p.IsBlank() { |
| 1184 | return 0 |
| 1185 | } |
| 1186 | sp, isstruct := p.(*structparm) |
| 1187 | if isstruct { |
| 1188 | s := 0 |
| 1189 | for fi := range sp.fields { |
| 1190 | s += checkableElements(sp.fields[fi]) |
| 1191 | } |
| 1192 | return s |
| 1193 | } |
| 1194 | ap, isarray := p.(*arrayparm) |
| 1195 | if isarray { |
| 1196 | if ap.nelements == 0 { |
| 1197 | return 0 |
| 1198 | } |
| 1199 | return int(ap.nelements) * checkableElements(ap.eltype) |
| 1200 | } |
| 1201 | return 1 |
| 1202 | } |
| 1203 | |
| 1204 | // funcdesc describes an auto-generated helper function or global |
| 1205 | // variable, such as an allocation function (returns new(T)) or a |
| 1206 | // pointer assignment function (assigns value of T to type *T). Here |
| 1207 | // 'p' is a param type T, 'pp' is a pointer type *T, 'name' is the |
| 1208 | // name within the generated code of the function or variable and |
| 1209 | // 'tag' is a descriptive tag used to look up the entity in a map (so |
| 1210 | // that we don't have to emit multiple copies of a function that |
| 1211 | // assigns int to *int, for example). |
| 1212 | type funcdesc struct { |
| 1213 | p parm |
| 1214 | pp parm |
| 1215 | name string |
| 1216 | tag string |
| 1217 | payload string |
| 1218 | } |
| 1219 | |
| 1220 | func (s *genstate) emitDerefFuncs(b *bytes.Buffer, emit bool) { |
| 1221 | b.WriteString("// dereference helpers\n") |
| 1222 | for _, fd := range s.newDerefFuncs { |
| 1223 | if !emit { |
| 1224 | b.WriteString(fmt.Sprintf("\n// skip derefunc %s\n", fd.name)) |
| 1225 | delete(s.derefFuncs, fd.tag) |
| 1226 | continue |
| 1227 | } |
| 1228 | b.WriteString("\n//go:noinline\n") |
| 1229 | b.WriteString(fmt.Sprintf("func %s(", fd.name)) |
| 1230 | fd.pp.Declare(b, "x", "", false) |
| 1231 | b.WriteString(") ") |
| 1232 | fd.p.Declare(b, "", "", false) |
| 1233 | b.WriteString(" {\n") |
| 1234 | b.WriteString(" return *x\n") |
| 1235 | b.WriteString("}\n") |
| 1236 | } |
| 1237 | s.newDerefFuncs = nil |
| 1238 | } |
| 1239 | |
| 1240 | func (s *genstate) emitAssignFuncs(b *bytes.Buffer, emit bool) { |
| 1241 | b.WriteString("// assign helpers\n") |
| 1242 | for _, fd := range s.newAssignFuncs { |
| 1243 | if !emit { |
| 1244 | b.WriteString(fmt.Sprintf("\n// skip assignfunc %s\n", fd.name)) |
| 1245 | delete(s.assignFuncs, fd.tag) |
| 1246 | continue |
| 1247 | } |
| 1248 | b.WriteString("\n//go:noinline\n") |
| 1249 | b.WriteString(fmt.Sprintf("func %s(", fd.name)) |
| 1250 | fd.pp.Declare(b, "x", "", false) |
| 1251 | b.WriteString(", ") |
| 1252 | fd.p.Declare(b, "v", "", false) |
| 1253 | b.WriteString(") {\n") |
| 1254 | b.WriteString(" *x = v\n") |
| 1255 | b.WriteString("}\n") |
| 1256 | } |
| 1257 | s.newAssignFuncs = nil |
| 1258 | } |
| 1259 | |
| 1260 | func (s *genstate) emitNewFuncs(b *bytes.Buffer, emit bool) { |
| 1261 | b.WriteString("// 'new' funcs\n") |
| 1262 | for _, fd := range s.newAllocFuncs { |
| 1263 | if !emit { |
| 1264 | b.WriteString(fmt.Sprintf("\n// skip newfunc %s\n", fd.name)) |
| 1265 | delete(s.allocFuncs, fd.tag) |
| 1266 | continue |
| 1267 | } |
| 1268 | b.WriteString("\n//go:noinline\n") |
| 1269 | b.WriteString(fmt.Sprintf("func %s(", fd.name)) |
| 1270 | fd.p.Declare(b, "i", "", false) |
| 1271 | b.WriteString(") ") |
| 1272 | fd.pp.Declare(b, "", "", false) |
| 1273 | b.WriteString(" {\n") |
| 1274 | b.WriteString(" x := new(") |
| 1275 | fd.p.Declare(b, "", "", false) |
| 1276 | b.WriteString(")\n") |
| 1277 | b.WriteString(" *x = i\n") |
| 1278 | b.WriteString(" return x\n") |
| 1279 | b.WriteString("}\n\n") |
| 1280 | } |
| 1281 | s.newAllocFuncs = nil |
| 1282 | } |
| 1283 | |
| 1284 | func (s *genstate) emitGlobalVars(b *bytes.Buffer, emit bool) { |
| 1285 | b.WriteString("// global vars\n") |
| 1286 | for _, fd := range s.newGlobVars { |
| 1287 | if !emit { |
| 1288 | b.WriteString(fmt.Sprintf("\n// skip gvar %s\n", fd.name)) |
| 1289 | delete(s.globVars, fd.tag) |
| 1290 | continue |
| 1291 | } |
| 1292 | b.WriteString("var ") |
| 1293 | fd.pp.Declare(b, fd.name, "", false) |
| 1294 | b.WriteString("\n") |
| 1295 | } |
| 1296 | s.newGlobVars = nil |
| 1297 | b.WriteString("\n") |
| 1298 | } |
| 1299 | |
| 1300 | func (s *genstate) emitGenValFuncs(f *funcdef, b *bytes.Buffer, emit bool) { |
| 1301 | b.WriteString("// genval helpers\n") |
| 1302 | for _, fd := range s.newGenvalFuncs { |
| 1303 | if !emit { |
| 1304 | b.WriteString(fmt.Sprintf("\n// skip genvalfunc %s\n", fd.name)) |
| 1305 | delete(s.genvalFuncs, fd.tag) |
| 1306 | continue |
| 1307 | } |
| 1308 | b.WriteString("\n//go:noinline\n") |
| 1309 | rcvr := "" |
| 1310 | if f.mapkeyts != "" { |
| 1311 | rcvr = fmt.Sprintf("(mkt *%s) ", f.mapkeyts) |
| 1312 | } |
| 1313 | b.WriteString(fmt.Sprintf("func %s%s() ", rcvr, fd.name)) |
| 1314 | fd.p.Declare(b, "", "", false) |
| 1315 | b.WriteString(" {\n") |
| 1316 | if f.mapkeyts != "" { |
| 1317 | contained := containedParms(fd.p) |
| 1318 | for _, cp := range contained { |
| 1319 | mp, ismap := cp.(*mapparm) |
| 1320 | if ismap { |
| 1321 | b.WriteString(fmt.Sprintf(" %s := mkt.%s\n", |
| 1322 | mp.keytmp, mp.keytmp)) |
| 1323 | b.WriteString(fmt.Sprintf(" _ = %s\n", mp.keytmp)) |
| 1324 | } |
| 1325 | } |
| 1326 | } |
| 1327 | b.WriteString(fmt.Sprintf(" return %s\n", fd.payload)) |
| 1328 | b.WriteString("}\n") |
| 1329 | } |
| 1330 | s.newGenvalFuncs = nil |
| 1331 | } |
| 1332 | |
| 1333 | func (s *genstate) emitAddrTakenHelpers(f *funcdef, b *bytes.Buffer, emit bool) { |
| 1334 | b.WriteString("// begin addr taken helpers\n") |
| 1335 | s.emitDerefFuncs(b, emit) |
| 1336 | s.emitAssignFuncs(b, emit) |
| 1337 | s.emitNewFuncs(b, emit) |
| 1338 | s.emitGlobalVars(b, emit) |
| 1339 | s.emitGenValFuncs(f, b, emit) |
| 1340 | b.WriteString("// end addr taken helpers\n") |
| 1341 | } |
| 1342 | |
| 1343 | func (s *genstate) genGlobVar(p parm) string { |
| 1344 | var pp parm |
| 1345 | ppp := mkPointerParm(p) |
| 1346 | pp = &ppp |
| 1347 | b := bytes.NewBuffer(nil) |
| 1348 | pp.Declare(b, "gv", "", false) |
| 1349 | tag := b.String() |
| 1350 | gv, ok := s.globVars[tag] |
| 1351 | if ok { |
| 1352 | return gv |
| 1353 | } |
| 1354 | gv = fmt.Sprintf("gvar_%d", len(s.globVars)) |
| 1355 | s.newGlobVars = append(s.newGlobVars, funcdesc{pp: pp, p: p, name: gv, tag: tag}) |
| 1356 | s.globVars[tag] = gv |
| 1357 | return gv |
| 1358 | } |
| 1359 | |
| 1360 | func (s *genstate) genParamDerefFunc(p parm) string { |
| 1361 | var pp parm |
| 1362 | ppp := mkPointerParm(p) |
| 1363 | pp = &ppp |
| 1364 | b := bytes.NewBuffer(nil) |
| 1365 | pp.Declare(b, "x", "", false) |
| 1366 | tag := b.String() |
| 1367 | f, ok := s.derefFuncs[tag] |
| 1368 | if ok { |
| 1369 | return f |
| 1370 | } |
| 1371 | f = fmt.Sprintf("deref_%d", len(s.derefFuncs)) |
| 1372 | s.newDerefFuncs = append(s.newDerefFuncs, funcdesc{pp: pp, p: p, name: f, tag: tag}) |
| 1373 | s.derefFuncs[tag] = f |
| 1374 | return f |
| 1375 | } |
| 1376 | |
| 1377 | func (s *genstate) genAssignFunc(p parm) string { |
| 1378 | var pp parm |
| 1379 | ppp := mkPointerParm(p) |
| 1380 | pp = &ppp |
| 1381 | b := bytes.NewBuffer(nil) |
| 1382 | pp.Declare(b, "x", "", false) |
| 1383 | tag := b.String() |
| 1384 | f, ok := s.assignFuncs[tag] |
| 1385 | if ok { |
| 1386 | return f |
| 1387 | } |
| 1388 | f = fmt.Sprintf("retassign_%d", len(s.assignFuncs)) |
| 1389 | s.newAssignFuncs = append(s.newAssignFuncs, funcdesc{pp: pp, p: p, name: f, tag: tag}) |
| 1390 | s.assignFuncs[tag] = f |
| 1391 | return f |
| 1392 | } |
| 1393 | |
| 1394 | func (s *genstate) genAllocFunc(p parm) string { |
| 1395 | var pp parm |
| 1396 | ppp := mkPointerParm(p) |
| 1397 | pp = &ppp |
| 1398 | b := bytes.NewBuffer(nil) |
| 1399 | pp.Declare(b, "x", "", false) |
| 1400 | tag := b.String() |
| 1401 | f, ok := s.allocFuncs[tag] |
| 1402 | if ok { |
| 1403 | return f |
| 1404 | } |
| 1405 | f = fmt.Sprintf("New_%d", len(s.allocFuncs)) |
| 1406 | s.newAllocFuncs = append(s.newAllocFuncs, funcdesc{pp: pp, p: p, name: f, tag: tag}) |
| 1407 | s.allocFuncs[tag] = f |
| 1408 | return f |
| 1409 | } |
| 1410 | |
| 1411 | func (s *genstate) genParamRef(p parm, idx int) string { |
| 1412 | switch p.AddrTaken() { |
| 1413 | case notAddrTaken: |
| 1414 | return fmt.Sprintf("p%d", idx) |
| 1415 | case addrTakenSimple, addrTakenHeap: |
| 1416 | return fmt.Sprintf("(*ap%d)", idx) |
| 1417 | case addrTakenPassed: |
| 1418 | f := s.genParamDerefFunc(p) |
| 1419 | return fmt.Sprintf("%s(ap%d)", f, idx) |
| 1420 | default: |
| 1421 | panic("bad") |
| 1422 | } |
| 1423 | } |
| 1424 | |
| 1425 | func (s *genstate) genReturnAssign(b *bytes.Buffer, r parm, idx int, val string) { |
| 1426 | switch r.AddrTaken() { |
| 1427 | case notAddrTaken: |
| 1428 | b.WriteString(fmt.Sprintf(" r%d = %s\n", idx, val)) |
| 1429 | case addrTakenSimple, addrTakenHeap: |
| 1430 | b.WriteString(fmt.Sprintf(" (*ar%d) = %v\n", idx, val)) |
| 1431 | case addrTakenPassed: |
| 1432 | f := s.genAssignFunc(r) |
| 1433 | b.WriteString(fmt.Sprintf(" %s(ar%d, %v)\n", f, idx, val)) |
| 1434 | default: |
| 1435 | panic("bad") |
| 1436 | } |
| 1437 | } |
| 1438 | |
| 1439 | func (s *genstate) emitParamElemCheck(f *funcdef, b *bytes.Buffer, p parm, pvar string, cvar string, paramidx int, elemidx int) { |
| 1440 | if p.SkipCompare() == SkipAll { |
| 1441 | b.WriteString(fmt.Sprintf(" // selective skip of %s\n", pvar)) |
| 1442 | b.WriteString(fmt.Sprintf(" _ = %s\n", cvar)) |
| 1443 | return |
| 1444 | } else if p.SkipCompare() == SkipPayload { |
| 1445 | switch p.(type) { |
| 1446 | case *stringparm, *arrayparm: |
| 1447 | b.WriteString(fmt.Sprintf(" if len(%s) != len(%s) { // skip payload\n", |
| 1448 | pvar, cvar)) |
| 1449 | default: |
| 1450 | panic("should never happen") |
| 1451 | } |
| 1452 | } else { |
| 1453 | basep, star := genDeref(p) |
| 1454 | // Handle *p where p is an empty struct. |
| 1455 | if basep.NumElements() == 0 { |
| 1456 | return |
| 1457 | } |
| 1458 | if basep.HasPointer() { |
| 1459 | efn := s.eqFuncRef(f, basep, false) |
| 1460 | b.WriteString(fmt.Sprintf(" if !%s(%s%s, %s%s) {\n", |
| 1461 | efn, star, pvar, star, cvar)) |
| 1462 | } else { |
| 1463 | b.WriteString(fmt.Sprintf(" if %s%s != %s%s {\n", |
| 1464 | star, pvar, star, cvar)) |
| 1465 | } |
| 1466 | } |
| 1467 | cm := f.complexityMeasure() |
| 1468 | b.WriteString(fmt.Sprintf(" NoteFailureElem(%d, %d, %d, \"%s\", \"parm\", %d, %d, false, pad[0])\n", cm, s.pkidx, f.idx, s.checkerPkg(s.pkidx), paramidx, elemidx)) |
| 1469 | b.WriteString(" return\n") |
| 1470 | b.WriteString(" }\n") |
| 1471 | } |
| 1472 | |
| 1473 | func (s *genstate) emitParamChecks(f *funcdef, b *bytes.Buffer, pidx int, value int) (int, bool) { |
| 1474 | var valstr string |
| 1475 | haveControl := false |
| 1476 | dangling := []int{} |
| 1477 | for pi, p := range f.params { |
| 1478 | verb(4, "emitting parmcheck p%d numel=%d pt=%s value=%d", |
| 1479 | pi, p.NumElements(), p.TypeName(), value) |
| 1480 | // To balance code in caller |
| 1481 | _ = uint8(s.wr.Intn(100)) < 50 |
| 1482 | if p.IsControl() { |
| 1483 | b.WriteString(fmt.Sprintf(" if %s == 0 {\n", |
| 1484 | s.genParamRef(p, pi))) |
| 1485 | s.emitReturn(f, b, false) |
| 1486 | b.WriteString(" }\n") |
| 1487 | haveControl = true |
| 1488 | |
| 1489 | } else if p.IsBlank() { |
| 1490 | valstr, value = s.GenValue(f, p, value, false) |
| 1491 | if f.recur { |
| 1492 | b.WriteString(fmt.Sprintf(" brc%d := %s\n", pi, valstr)) |
| 1493 | } else { |
| 1494 | b.WriteString(fmt.Sprintf(" _ = %s\n", valstr)) |
| 1495 | } |
| 1496 | } else { |
| 1497 | numel := p.NumElements() |
| 1498 | cel := checkableElements(p) |
| 1499 | for i := range numel { |
| 1500 | verb(4, "emitting check-code for p%d el %d value=%d", pi, i, value) |
| 1501 | elref, elparm := p.GenElemRef(i, s.genParamRef(p, pi)) |
| 1502 | valstr, value = s.GenValue(f, elparm, value, false) |
| 1503 | if elref == "" || elref == "_" || cel == 0 { |
| 1504 | b.WriteString(fmt.Sprintf(" // blank skip: %s\n", valstr)) |
| 1505 | continue |
| 1506 | } else { |
| 1507 | basep, _ := genDeref(elparm) |
| 1508 | // Handle *p where p is an empty struct. |
| 1509 | if basep.NumElements() == 0 { |
| 1510 | continue |
| 1511 | } |
| 1512 | cvar := fmt.Sprintf("p%df%dc", pi, i) |
| 1513 | b.WriteString(fmt.Sprintf(" %s := %s\n", cvar, valstr)) |
| 1514 | s.emitParamElemCheck(f, b, elparm, elref, cvar, pi, i) |
| 1515 | } |
| 1516 | } |
| 1517 | if p.AddrTaken() != notAddrTaken { |
| 1518 | dangling = append(dangling, pi) |
| 1519 | } |
| 1520 | } |
| 1521 | if value != f.values[pi] { |
| 1522 | fmt.Fprintf(os.Stderr, "internal error: checker/caller value mismatch after emitting param %d func Test%d pkg %s: caller %d checker %d\n", pi, f.idx, s.checkerPkg(pidx), f.values[pi], value) |
| 1523 | s.errs++ |
| 1524 | } |
| 1525 | } |
| 1526 | for _, pi := range dangling { |
| 1527 | b.WriteString(fmt.Sprintf(" _ = ap%d // ref\n", pi)) |
| 1528 | } |
| 1529 | |
| 1530 | // receiver value check |
| 1531 | if f.isMethod { |
| 1532 | numel := f.receiver.NumElements() |
| 1533 | for i := range numel { |
| 1534 | verb(4, "emitting check-code for rcvr el %d value=%d", i, value) |
| 1535 | elref, elparm := f.receiver.GenElemRef(i, "rcvr") |
| 1536 | valstr, value = s.GenValue(f, elparm, value, false) |
| 1537 | if elref == "" || strings.HasPrefix(elref, "_") || f.receiver.IsBlank() { |
| 1538 | verb(4, "empty skip rcvr el %d", i) |
| 1539 | continue |
| 1540 | } else { |
| 1541 | |
| 1542 | basep, _ := genDeref(elparm) |
| 1543 | // Handle *p where p is an empty struct. |
| 1544 | if basep.NumElements() == 0 { |
| 1545 | continue |
| 1546 | } |
| 1547 | cvar := fmt.Sprintf("rcvrf%dc", i) |
| 1548 | b.WriteString(fmt.Sprintf(" %s := %s\n", cvar, valstr)) |
| 1549 | s.emitParamElemCheck(f, b, elparm, elref, cvar, -1, i) |
| 1550 | } |
| 1551 | } |
| 1552 | } |
| 1553 | |
| 1554 | return value, haveControl |
| 1555 | } |
| 1556 | |
| 1557 | // emitDeferChecks creates code like |
| 1558 | // |
| 1559 | // defer func(...args...) { |
| 1560 | // check arg |
| 1561 | // check param |
| 1562 | // }(...) |
| 1563 | // |
| 1564 | // where we randomly choose to either pass a param through to the |
| 1565 | // function literal, or have the param captured by the closure, then |
| 1566 | // check its value in the defer. |
| 1567 | func (s *genstate) emitDeferChecks(f *funcdef, b *bytes.Buffer, value int) int { |
| 1568 | |
| 1569 | if len(f.params) == 0 { |
| 1570 | return value |
| 1571 | } |
| 1572 | |
| 1573 | // make a pass through the params and randomly decide which will be passed into the func. |
| 1574 | passed := []bool{} |
| 1575 | for i := range f.params { |
| 1576 | p := f.dodefp[i] < 50 |
| 1577 | passed = append(passed, p) |
| 1578 | } |
| 1579 | |
| 1580 | b.WriteString(" defer func(") |
| 1581 | pc := 0 |
| 1582 | for pi, p := range f.params { |
| 1583 | if p.IsControl() || p.IsBlank() { |
| 1584 | continue |
| 1585 | } |
| 1586 | if passed[pi] { |
| 1587 | writeCom(b, pc) |
| 1588 | n := fmt.Sprintf("p%d", pi) |
| 1589 | p.Declare(b, n, "", false) |
| 1590 | pc++ |
| 1591 | } |
| 1592 | } |
| 1593 | b.WriteString(") {\n") |
| 1594 | |
| 1595 | for pi, p := range f.params { |
| 1596 | if p.IsControl() || p.IsBlank() { |
| 1597 | continue |
| 1598 | } |
| 1599 | which := "passed" |
| 1600 | if !passed[pi] { |
| 1601 | which = "captured" |
| 1602 | } |
| 1603 | b.WriteString(" // check parm " + which + "\n") |
| 1604 | numel := p.NumElements() |
| 1605 | cel := checkableElements(p) |
| 1606 | for i := range numel { |
| 1607 | elref, elparm := p.GenElemRef(i, s.genParamRef(p, pi)) |
| 1608 | if elref == "" || elref == "_" || cel == 0 { |
| 1609 | verb(4, "empty skip p%d el %d", pi, i) |
| 1610 | continue |
| 1611 | } else { |
| 1612 | basep, _ := genDeref(elparm) |
| 1613 | // Handle *p where p is an empty struct. |
| 1614 | if basep.NumElements() == 0 { |
| 1615 | continue |
| 1616 | } |
| 1617 | cvar := fmt.Sprintf("p%df%dc", pi, i) |
| 1618 | s.emitParamElemCheck(f, b, elparm, elref, cvar, pi, i) |
| 1619 | } |
| 1620 | } |
| 1621 | } |
| 1622 | b.WriteString(" } (") |
| 1623 | pc = 0 |
| 1624 | for pi, p := range f.params { |
| 1625 | if p.IsControl() || p.IsBlank() { |
| 1626 | continue |
| 1627 | } |
| 1628 | if passed[pi] { |
| 1629 | writeCom(b, pc) |
| 1630 | b.WriteString(fmt.Sprintf("p%d", pi)) |
| 1631 | pc++ |
| 1632 | } |
| 1633 | } |
| 1634 | b.WriteString(")\n\n") |
| 1635 | |
| 1636 | return value |
| 1637 | } |
| 1638 | |
| 1639 | func (s *genstate) emitVarAssign(f *funcdef, b *bytes.Buffer, r parm, rname string, value int, caller bool) int { |
| 1640 | var valstr string |
| 1641 | isassign := uint8(s.wr.Intn(100)) < 50 |
| 1642 | if rmp, ismap := r.(*mapparm); ismap && isassign { |
| 1643 | // emit: var m ... ; m[k] = v |
| 1644 | r.Declare(b, " "+rname+" := make(", ")\n", caller) |
| 1645 | valstr, value = s.GenValue(f, rmp.valtype, value, caller) |
| 1646 | b.WriteString(fmt.Sprintf(" %s[mkt.%s] = %s\n", |
| 1647 | rname, rmp.keytmp, valstr)) |
| 1648 | } else { |
| 1649 | // emit r = c |
| 1650 | valstr, value = s.GenValue(f, r, value, caller) |
| 1651 | b.WriteString(fmt.Sprintf(" %s := %s\n", rname, valstr)) |
| 1652 | } |
| 1653 | return value |
| 1654 | } |
| 1655 | |
| 1656 | func (s *genstate) emitChecker(f *funcdef, b *bytes.Buffer, pidx int, emit bool) { |
| 1657 | verb(4, "emitting struct and array defs") |
| 1658 | s.emitStructAndArrayDefs(f, b) |
| 1659 | b.WriteString(fmt.Sprintf("// %d returns %d params\n", len(f.returns), len(f.params))) |
| 1660 | if s.Pragma != "" { |
| 1661 | b.WriteString("//go:" + s.Pragma + "\n") |
| 1662 | } |
| 1663 | b.WriteString("//go:noinline\n") |
| 1664 | |
| 1665 | b.WriteString("func") |
| 1666 | |
| 1667 | if f.isMethod { |
| 1668 | b.WriteString(" (") |
| 1669 | n := "rcvr" |
| 1670 | if f.receiver.IsBlank() { |
| 1671 | n = "_" |
| 1672 | } |
| 1673 | f.receiver.Declare(b, n, "", false) |
| 1674 | b.WriteString(")") |
| 1675 | } |
| 1676 | |
| 1677 | b.WriteString(fmt.Sprintf(" Test%d(", f.idx)) |
| 1678 | |
| 1679 | verb(4, "emitting checker p%d/Test%d", pidx, f.idx) |
| 1680 | |
| 1681 | // params |
| 1682 | for pi, p := range f.params { |
| 1683 | writeCom(b, pi) |
| 1684 | n := fmt.Sprintf("p%d", pi) |
| 1685 | if p.IsBlank() { |
| 1686 | n = "_" |
| 1687 | } |
| 1688 | p.Declare(b, n, "", false) |
| 1689 | } |
| 1690 | b.WriteString(") ") |
| 1691 | |
| 1692 | // returns |
| 1693 | if len(f.returns) > 0 { |
| 1694 | b.WriteString("(") |
| 1695 | } |
| 1696 | for ri, r := range f.returns { |
| 1697 | writeCom(b, ri) |
| 1698 | r.Declare(b, fmt.Sprintf("r%d", ri), "", false) |
| 1699 | } |
| 1700 | if len(f.returns) > 0 { |
| 1701 | b.WriteString(")") |
| 1702 | } |
| 1703 | b.WriteString(" {\n") |
| 1704 | |
| 1705 | // local storage |
| 1706 | b.WriteString(" // consume some stack space, so as to trigger morestack\n") |
| 1707 | b.WriteString(fmt.Sprintf(" var pad [%d]uint64\n", f.rstack)) |
| 1708 | b.WriteString(fmt.Sprintf(" pad[FailCount[%d] & 0x1]++\n", pidx)) |
| 1709 | |
| 1710 | value := 1 |
| 1711 | |
| 1712 | // generate map key tmps |
| 1713 | s.wr.Checkpoint("before map key temps") |
| 1714 | value = s.emitMapKeyTmps(f, b, pidx, value, false) |
| 1715 | |
| 1716 | // generate return constants |
| 1717 | s.wr.Checkpoint("before return constants") |
| 1718 | for ri, r := range f.returns { |
| 1719 | rc := fmt.Sprintf("rc%d", ri) |
| 1720 | value = s.emitVarAssign(f, b, r, rc, value, false) |
| 1721 | } |
| 1722 | |
| 1723 | // Prepare to reference params/returns by address. |
| 1724 | lists := [][]parm{f.params, f.returns} |
| 1725 | names := []string{"p", "r"} |
| 1726 | var aCounts [2]int |
| 1727 | for i, lst := range lists { |
| 1728 | for pi, p := range lst { |
| 1729 | if p.AddrTaken() == notAddrTaken { |
| 1730 | continue |
| 1731 | } |
| 1732 | aCounts[i]++ |
| 1733 | n := names[i] |
| 1734 | b.WriteString(fmt.Sprintf(" a%s%d := &%s%d\n", n, pi, n, pi)) |
| 1735 | if p.AddrTaken() == addrTakenHeap { |
| 1736 | gv := s.genGlobVar(p) |
| 1737 | b.WriteString(fmt.Sprintf(" %s = a%s%d\n", gv, n, pi)) |
| 1738 | } |
| 1739 | } |
| 1740 | } |
| 1741 | |
| 1742 | if s.EmitBad == 2 { |
| 1743 | if s.BadPackageIdx == pidx && s.BadFuncIdx == f.idx { |
| 1744 | b.WriteString(" // force runtime failure here (debugging)\n") |
| 1745 | b.WriteString(fmt.Sprintf(" NoteFailure(%d, %d, %d, \"%s\", \"artificial\", %d, true, uint64(0))\n", f.complexityMeasure(), pidx, f.idx, s.checkerPkg(pidx), 0)) |
| 1746 | } |
| 1747 | } |
| 1748 | |
| 1749 | // parameter checking code |
| 1750 | var haveControl bool |
| 1751 | s.wr.Checkpoint("before param checks") |
| 1752 | value, haveControl = s.emitParamChecks(f, b, pidx, value) |
| 1753 | |
| 1754 | // defer testing |
| 1755 | if s.tunables.doDefer && f.dodefc < s.tunables.deferFraction { |
| 1756 | s.wr.Checkpoint("before defer checks") |
| 1757 | _ = s.emitDeferChecks(f, b, value) |
| 1758 | } |
| 1759 | |
| 1760 | // returns |
| 1761 | s.emitReturn(f, b, haveControl) |
| 1762 | |
| 1763 | b.WriteString(fmt.Sprintf(" // %d addr-taken params, %d addr-taken returns\n", |
| 1764 | aCounts[0], aCounts[1])) |
| 1765 | |
| 1766 | b.WriteString("}\n\n") |
| 1767 | |
| 1768 | // emit any new helper funcs referenced by this test function |
| 1769 | s.emitAddrTakenHelpers(f, b, emit) |
| 1770 | } |
| 1771 | |
| 1772 | // complexityMeasure returns an integer that estimates how complex a |
| 1773 | // given test function is relative to some other function. The more |
| 1774 | // parameters + returns and the more complicated the types of the |
| 1775 | // params/returns, the higher the number returned here. In theory this |
| 1776 | // could be worked into the minimization process (e.g. pick the least |
| 1777 | // complex func that reproduces the failure), but for now that isn't |
| 1778 | // wired up yet. |
| 1779 | func (f *funcdef) complexityMeasure() int { |
| 1780 | v := int(0) |
| 1781 | if f.isMethod { |
| 1782 | v += f.receiver.NumElements() |
| 1783 | } |
| 1784 | for _, p := range f.params { |
| 1785 | v += p.NumElements() |
| 1786 | } |
| 1787 | for _, r := range f.returns { |
| 1788 | v += r.NumElements() |
| 1789 | } |
| 1790 | return v |
| 1791 | } |
| 1792 | |
| 1793 | // emitRecursiveCall generates a recursive call to the test function in question. |
| 1794 | func (s *genstate) emitRecursiveCall(f *funcdef) string { |
| 1795 | b := bytes.NewBuffer(nil) |
| 1796 | rcvr := "" |
| 1797 | if f.isMethod { |
| 1798 | rcvr = "rcvr." |
| 1799 | } |
| 1800 | b.WriteString(fmt.Sprintf(" %sTest%d(", rcvr, f.idx)) |
| 1801 | for pi, p := range f.params { |
| 1802 | writeCom(b, pi) |
| 1803 | if p.IsControl() { |
| 1804 | b.WriteString(fmt.Sprintf(" %s-1", s.genParamRef(p, pi))) |
| 1805 | } else { |
| 1806 | if !p.IsBlank() { |
| 1807 | b.WriteString(fmt.Sprintf(" %s", s.genParamRef(p, pi))) |
| 1808 | } else { |
| 1809 | b.WriteString(fmt.Sprintf(" brc%d", pi)) |
| 1810 | } |
| 1811 | } |
| 1812 | } |
| 1813 | b.WriteString(")") |
| 1814 | return b.String() |
| 1815 | } |
| 1816 | |
| 1817 | // emitReturn generates a return sequence. |
| 1818 | func (s *genstate) emitReturn(f *funcdef, b *bytes.Buffer, doRecursiveCall bool) { |
| 1819 | // If any of the return values are address-taken, then instead of |
| 1820 | // |
| 1821 | // return x, y, z |
| 1822 | // |
| 1823 | // we emit |
| 1824 | // |
| 1825 | // r1 = ... |
| 1826 | // r2 = ... |
| 1827 | // ... |
| 1828 | // return |
| 1829 | // |
| 1830 | // Make an initial pass through the returns to see if we need to do this. |
| 1831 | // Figure out the final return values in the process. |
| 1832 | indirectReturn := false |
| 1833 | retvals := []string{} |
| 1834 | for ri, r := range f.returns { |
| 1835 | if r.AddrTaken() != notAddrTaken { |
| 1836 | indirectReturn = true |
| 1837 | } |
| 1838 | t := "" |
| 1839 | if doRecursiveCall { |
| 1840 | t = "t" |
| 1841 | } |
| 1842 | retvals = append(retvals, fmt.Sprintf("rc%s%d", t, ri)) |
| 1843 | } |
| 1844 | |
| 1845 | // generate the recursive call itself if applicable |
| 1846 | if doRecursiveCall { |
| 1847 | b.WriteString(" // recursive call\n ") |
| 1848 | if s.ForceStackGrowth { |
| 1849 | b.WriteString(" hackStack() // force stack growth on next call\n") |
| 1850 | } |
| 1851 | rcall := s.emitRecursiveCall(f) |
| 1852 | if indirectReturn { |
| 1853 | for ri := range f.returns { |
| 1854 | writeCom(b, ri) |
| 1855 | b.WriteString(fmt.Sprintf(" rct%d", ri)) |
| 1856 | } |
| 1857 | b.WriteString(" := ") |
| 1858 | b.WriteString(rcall) |
| 1859 | b.WriteString("\n") |
| 1860 | } else { |
| 1861 | if len(f.returns) == 0 { |
| 1862 | b.WriteString(fmt.Sprintf("%s\n return\n", rcall)) |
| 1863 | } else { |
| 1864 | b.WriteString(fmt.Sprintf(" return %s\n", rcall)) |
| 1865 | } |
| 1866 | return |
| 1867 | } |
| 1868 | } |
| 1869 | |
| 1870 | // now the actual return |
| 1871 | if indirectReturn { |
| 1872 | for ri, r := range f.returns { |
| 1873 | s.genReturnAssign(b, r, ri, retvals[ri]) |
| 1874 | } |
| 1875 | b.WriteString(" return\n") |
| 1876 | } else { |
| 1877 | b.WriteString(" return ") |
| 1878 | for ri := range f.returns { |
| 1879 | writeCom(b, ri) |
| 1880 | b.WriteString(retvals[ri]) |
| 1881 | } |
| 1882 | b.WriteString("\n") |
| 1883 | } |
| 1884 | } |
| 1885 | |
| 1886 | func (s *genstate) GenPair(calloutfile *os.File, checkoutfile *os.File, fidx int, pidx int, b *bytes.Buffer, seed int64, emit bool) int64 { |
| 1887 | |
| 1888 | verb(1, "gen fidx %d pidx %d", fidx, pidx) |
| 1889 | |
| 1890 | checkTunables(tunables) |
| 1891 | s.tunables = tunables |
| 1892 | |
| 1893 | // Generate a function with a random number of params and returns |
| 1894 | s.wr = NewWrapRand(seed, s.RandCtl) |
| 1895 | s.wr.tag = "genfunc" |
| 1896 | fp := s.GenFunc(fidx, pidx) |
| 1897 | |
| 1898 | // Emit caller side |
| 1899 | wrcaller := NewWrapRand(seed, s.RandCtl) |
| 1900 | s.wr = wrcaller |
| 1901 | s.wr.tag = "caller" |
| 1902 | s.emitCaller(fp, b, pidx) |
| 1903 | if emit { |
| 1904 | b.WriteTo(calloutfile) |
| 1905 | } |
| 1906 | b.Reset() |
| 1907 | |
| 1908 | // Emit checker side |
| 1909 | wrchecker := NewWrapRand(seed, s.RandCtl) |
| 1910 | s.wr = wrchecker |
| 1911 | s.wr.tag = "checker" |
| 1912 | s.emitChecker(fp, b, pidx, emit) |
| 1913 | if emit { |
| 1914 | b.WriteTo(checkoutfile) |
| 1915 | } |
| 1916 | b.Reset() |
| 1917 | wrchecker.Check(wrcaller) |
| 1918 | |
| 1919 | return seed + 1 |
| 1920 | } |
| 1921 | |
| 1922 | func (s *genstate) openOutputFile(filename string, pk string, imports []string, ipref string) *os.File { |
| 1923 | iprefix := func(f string) string { |
| 1924 | if ipref == "" { |
| 1925 | return f |
| 1926 | } |
| 1927 | return ipref + "/" + f |
| 1928 | } |
| 1929 | verb(1, "opening %s", filename) |
| 1930 | outf, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666) |
| 1931 | if err != nil { |
| 1932 | log.Fatal(err) |
| 1933 | } |
| 1934 | haveunsafe := false |
| 1935 | outf.WriteString(fmt.Sprintf("package %s\n\n", pk)) |
| 1936 | for _, imp := range imports { |
| 1937 | if imp == "reflect" { |
| 1938 | outf.WriteString("import \"reflect\"\n") |
| 1939 | continue |
| 1940 | } |
| 1941 | if imp == "unsafe" { |
| 1942 | outf.WriteString("import _ \"unsafe\"\n") |
| 1943 | haveunsafe = true |
| 1944 | continue |
| 1945 | } |
| 1946 | if imp == s.utilsPkg() { |
| 1947 | |
| 1948 | outf.WriteString(fmt.Sprintf("import . \"%s\"\n", iprefix(imp))) |
| 1949 | continue |
| 1950 | } |
| 1951 | outf.WriteString(fmt.Sprintf("import \"%s\"\n", iprefix(imp))) |
| 1952 | } |
| 1953 | outf.WriteString("\n") |
| 1954 | if s.ForceStackGrowth && haveunsafe { |
| 1955 | outf.WriteString("// Hack: reach into runtime to grab this testing hook.\n") |
| 1956 | outf.WriteString("//go:linkname hackStack runtime.gcTestMoveStackOnNextCall\n") |
| 1957 | outf.WriteString("func hackStack()\n\n") |
| 1958 | } |
| 1959 | return outf |
| 1960 | } |
| 1961 | |
| 1962 | type miscVals struct { |
| 1963 | NumTpk int |
| 1964 | MaxFail int |
| 1965 | NumTests int |
| 1966 | } |
| 1967 | |
| 1968 | const utilsTemplate = ` |
| 1969 | |
| 1970 | import ( |
| 1971 | "fmt" |
| 1972 | "os" |
| 1973 | ) |
| 1974 | |
| 1975 | type UtilsType int |
| 1976 | var ParamFailCount [{{.NumTpk}}]int |
| 1977 | var ReturnFailCount [{{.NumTpk}}]int |
| 1978 | var FailCount [{{.NumTpk}}]int |
| 1979 | var Mode [{{.NumTpk}}]string |
| 1980 | |
| 1981 | //go:noinline |
| 1982 | func NoteFailure(cm int, pidx int, fidx int, pkg string, pref string, parmNo int, isret bool, _ uint64) { |
| 1983 | if isret { |
| 1984 | if ParamFailCount[pidx] != 0 { |
| 1985 | return |
| 1986 | } |
| 1987 | ReturnFailCount[pidx]++ |
| 1988 | } else { |
| 1989 | ParamFailCount[pidx]++ |
| 1990 | } |
| 1991 | fmt.Fprintf(os.Stderr, "Error: fail %s |%d|%d|%d| =%s.Test%d= %s %d\n", Mode, cm, pidx, fidx, pkg, fidx, pref, parmNo) |
| 1992 | |
| 1993 | if ParamFailCount[pidx]+FailCount[pidx]+ReturnFailCount[pidx] > {{.MaxFail}} { |
| 1994 | os.Exit(1) |
| 1995 | } |
| 1996 | } |
| 1997 | |
| 1998 | //go:noinline |
| 1999 | func NoteFailureElem(cm int, pidx int, fidx int, pkg string, pref string, parmNo int, elem int, isret bool, _ uint64) { |
| 2000 | |
| 2001 | if isret { |
| 2002 | if ParamFailCount[pidx] != 0 { |
| 2003 | return |
| 2004 | } |
| 2005 | ReturnFailCount[pidx]++ |
| 2006 | } else { |
| 2007 | ParamFailCount[pidx]++ |
| 2008 | } |
| 2009 | fmt.Fprintf(os.Stderr, "Error: fail %s |%d|%d|%d| =%s.Test%d= %s %d elem %d\n", Mode, cm, pidx, fidx, pkg, fidx, pref, parmNo, elem) |
| 2010 | |
| 2011 | if ParamFailCount[pidx]+FailCount[pidx]+ReturnFailCount[pidx] > {{.MaxFail}} { |
| 2012 | os.Exit(1) |
| 2013 | } |
| 2014 | } |
| 2015 | |
| 2016 | func BeginFcn(p int) { |
| 2017 | ParamFailCount[p] = 0 |
| 2018 | ReturnFailCount[p] = 0 |
| 2019 | } |
| 2020 | |
| 2021 | func EndFcn(p int) { |
| 2022 | FailCount[p] += ParamFailCount[p] |
| 2023 | FailCount[p] += ReturnFailCount[p] |
| 2024 | } |
| 2025 | ` |
| 2026 | |
| 2027 | func (s *genstate) emitUtils(outf *os.File, maxfail int, numtpk int) { |
| 2028 | vals := miscVals{ |
| 2029 | NumTpk: numtpk, |
| 2030 | MaxFail: maxfail, |
| 2031 | } |
| 2032 | t := template.Must(template.New("utils").Parse(utilsTemplate)) |
| 2033 | err := t.Execute(outf, vals) |
| 2034 | if err != nil { |
| 2035 | log.Fatal(err) |
| 2036 | } |
| 2037 | } |
| 2038 | |
| 2039 | const mainPreamble = ` |
| 2040 | |
| 2041 | import ( |
| 2042 | "fmt" |
| 2043 | "os" |
| 2044 | ) |
| 2045 | |
| 2046 | func main() { |
| 2047 | fmt.Fprintf(os.Stderr, "starting main\n") |
| 2048 | ` |
| 2049 | |
| 2050 | func (s *genstate) emitMain(outf *os.File, numit int, fcnmask map[int]int, pkmask map[int]int) { |
| 2051 | fmt.Fprintf(outf, "%s", mainPreamble) |
| 2052 | fmt.Fprintf(outf, " pch := make(chan bool, %d)\n", s.NumTestPackages) |
| 2053 | for k := 0; k < s.NumTestPackages; k++ { |
| 2054 | cp := fmt.Sprintf("%s%s%d", s.Tag, CallerName, k) |
| 2055 | fmt.Fprintf(outf, " go func(ch chan bool) {\n") |
| 2056 | for i := range numit { |
| 2057 | if shouldEmitFP(i, k, fcnmask, pkmask) { |
| 2058 | fmt.Fprintf(outf, " %s.%s%d(\"normal\")\n", cp, CallerName, i) |
| 2059 | if s.tunables.doReflectCall { |
| 2060 | fmt.Fprintf(outf, " %s.%s%d(\"reflect\")\n", cp, CallerName, i) |
| 2061 | } |
| 2062 | } |
| 2063 | } |
| 2064 | fmt.Fprintf(outf, " pch <- true\n") |
| 2065 | fmt.Fprintf(outf, " }(pch)\n") |
| 2066 | } |
| 2067 | fmt.Fprintf(outf, " for pidx := 0; pidx < %d; pidx++ {\n", s.NumTestPackages) |
| 2068 | fmt.Fprintf(outf, " _ = <- pch\n") |
| 2069 | fmt.Fprintf(outf, " }\n") |
| 2070 | fmt.Fprintf(outf, " tf := 0\n") |
| 2071 | fmt.Fprintf(outf, " for pidx := 0; pidx < %d; pidx++ {\n", s.NumTestPackages) |
| 2072 | fmt.Fprintf(outf, " tf += FailCount[pidx]\n") |
| 2073 | fmt.Fprintf(outf, " }\n") |
| 2074 | fmt.Fprintf(outf, " if tf != 0 {\n") |
| 2075 | fmt.Fprintf(outf, " fmt.Fprintf(os.Stderr, \"FAILURES: %%d\\n\", tf)\n") |
| 2076 | fmt.Fprintf(outf, " os.Exit(2)\n") |
| 2077 | fmt.Fprintf(outf, " }\n") |
| 2078 | fmt.Fprintf(outf, " fmt.Fprintf(os.Stderr, \"finished %d tests\\n\")\n", numit*s.NumTestPackages) |
| 2079 | fmt.Fprintf(outf, "}\n") |
| 2080 | } |
| 2081 | |
| 2082 | func makeDir(d string) { |
| 2083 | fi, err := os.Stat(d) |
| 2084 | if err == nil && fi.IsDir() { |
| 2085 | return |
| 2086 | } |
| 2087 | verb(1, "creating %s", d) |
| 2088 | if err := os.Mkdir(d, 0777); err != nil { |
| 2089 | log.Fatal(err) |
| 2090 | } |
| 2091 | } |
| 2092 | |
| 2093 | func (s *genstate) callerPkg(which int) string { |
| 2094 | return s.Tag + CallerName + strconv.Itoa(which) |
| 2095 | } |
| 2096 | |
| 2097 | func (s *genstate) callerFile(which int) string { |
| 2098 | cp := s.callerPkg(which) |
| 2099 | return filepath.Join(s.OutDir, cp, cp+".go") |
| 2100 | } |
| 2101 | |
| 2102 | func (s *genstate) checkerPkg(which int) string { |
| 2103 | return s.Tag + CheckerName + strconv.Itoa(which) |
| 2104 | } |
| 2105 | |
| 2106 | func (s *genstate) checkerFile(which int) string { |
| 2107 | cp := s.checkerPkg(which) |
| 2108 | return filepath.Join(s.OutDir, cp, cp+".go") |
| 2109 | } |
| 2110 | |
| 2111 | func (s *genstate) utilsPkg() string { |
| 2112 | return s.Tag + "Utils" |
| 2113 | } |
| 2114 | |
| 2115 | func (s *genstate) beginPackage(pkidx int) { |
| 2116 | s.pkidx = pkidx |
| 2117 | s.derefFuncs = make(map[string]string) |
| 2118 | s.assignFuncs = make(map[string]string) |
| 2119 | s.allocFuncs = make(map[string]string) |
| 2120 | s.globVars = make(map[string]string) |
| 2121 | s.genvalFuncs = make(map[string]string) |
| 2122 | } |
| 2123 | |
| 2124 | func runImports(files []string) { |
| 2125 | verb(1, "... running goimports") |
| 2126 | args := make([]string, 0, len(files)+1) |
| 2127 | args = append(args, "-w") |
| 2128 | args = append(args, files...) |
| 2129 | cmd := exec.Command("goimports", args...) |
| 2130 | coutput, cerr := cmd.CombinedOutput() |
| 2131 | if cerr != nil { |
| 2132 | log.Fatalf("goimports command failed: %s", string(coutput)) |
| 2133 | } |
| 2134 | verb(1, "... goimports run complete") |
| 2135 | } |
| 2136 | |
| 2137 | // shouldEmitFP returns true if we should actually emit code for the function |
| 2138 | // with the specified package + fcn indices. For "regular" runs, fcnmask and pkmask |
| 2139 | // will be empty, meaning we want to emit every function in every package. The |
| 2140 | // fuzz-runner program also tries to do testcase "minimization", which means that it |
| 2141 | // will try to whittle down the set of packages and functions (by running the generator |
| 2142 | // using the fcnmask and pkmask options) to emit only specific packages or functions. |
| 2143 | func shouldEmitFP(fn int, pk int, fcnmask map[int]int, pkmask map[int]int) bool { |
| 2144 | emitpk := true |
| 2145 | emitfn := true |
| 2146 | if len(pkmask) != 0 { |
| 2147 | emitpk = false |
| 2148 | if _, ok := pkmask[pk]; ok { |
| 2149 | emitpk = true |
| 2150 | } |
| 2151 | } |
| 2152 | if len(fcnmask) != 0 { |
| 2153 | emitfn = false |
| 2154 | if _, ok := fcnmask[fn]; ok { |
| 2155 | emitfn = true |
| 2156 | } |
| 2157 | } |
| 2158 | doemit := emitpk && emitfn |
| 2159 | verb(2, "shouldEmitFP(F=%d,P=%d) returns %v", fn, pk, doemit) |
| 2160 | return doemit |
| 2161 | } |
| 2162 | |
| 2163 | // Generate is the top level code generation hook for this package. |
| 2164 | // Emits code according to the schema in config object 'c'. |
| 2165 | func Generate(c GenConfig) int { |
| 2166 | mainpkg := c.Tag + "Main" |
| 2167 | |
| 2168 | var ipref string |
| 2169 | if len(c.PkgPath) > 0 { |
| 2170 | ipref = c.PkgPath |
| 2171 | } |
| 2172 | |
| 2173 | s := genstate{ |
| 2174 | GenConfig: c, |
| 2175 | ipref: ipref, |
| 2176 | } |
| 2177 | |
| 2178 | if s.OutDir != "." { |
| 2179 | verb(1, "creating %s", s.OutDir) |
| 2180 | makeDir(s.OutDir) |
| 2181 | } |
| 2182 | |
| 2183 | mainimports := []string{} |
| 2184 | for i := 0; i < s.NumTestPackages; i++ { |
| 2185 | if shouldEmitFP(-1, i, nil, s.PkgMask) { |
| 2186 | makeDir(s.OutDir + "/" + s.callerPkg(i)) |
| 2187 | makeDir(s.OutDir + "/" + s.checkerPkg(i)) |
| 2188 | makeDir(s.OutDir + "/" + s.utilsPkg()) |
| 2189 | mainimports = append(mainimports, s.callerPkg(i)) |
| 2190 | } |
| 2191 | } |
| 2192 | mainimports = append(mainimports, s.utilsPkg()) |
| 2193 | |
| 2194 | // Emit utils package. |
| 2195 | verb(1, "emit utils") |
| 2196 | utilsfile := s.OutDir + "/" + s.utilsPkg() + "/" + s.utilsPkg() + ".go" |
| 2197 | utilsoutfile := s.openOutputFile(utilsfile, s.utilsPkg(), []string{}, "") |
| 2198 | s.emitUtils(utilsoutfile, s.MaxFail, s.NumTestPackages) |
| 2199 | utilsoutfile.Close() |
| 2200 | |
| 2201 | mainfile := s.OutDir + "/" + mainpkg + ".go" |
| 2202 | mainoutfile := s.openOutputFile(mainfile, "main", mainimports, ipref) |
| 2203 | |
| 2204 | allfiles := []string{mainfile, utilsfile} |
| 2205 | for k := 0; k < s.NumTestPackages; k++ { |
| 2206 | callerImports := []string{s.checkerPkg(k), s.utilsPkg()} |
| 2207 | checkerImports := []string{s.utilsPkg()} |
| 2208 | if tunables.doReflectCall { |
| 2209 | callerImports = append(callerImports, "reflect") |
| 2210 | } |
| 2211 | if s.ForceStackGrowth { |
| 2212 | callerImports = append(callerImports, "unsafe") |
| 2213 | checkerImports = append(checkerImports, "unsafe") |
| 2214 | } |
| 2215 | var calleroutfile, checkeroutfile *os.File |
| 2216 | if shouldEmitFP(-1, k, nil, s.PkgMask) { |
| 2217 | calleroutfile = s.openOutputFile(s.callerFile(k), s.callerPkg(k), |
| 2218 | callerImports, ipref) |
| 2219 | checkeroutfile = s.openOutputFile(s.checkerFile(k), s.checkerPkg(k), |
| 2220 | checkerImports, ipref) |
| 2221 | allfiles = append(allfiles, s.callerFile(k), s.checkerFile(k)) |
| 2222 | } |
| 2223 | |
| 2224 | s.beginPackage(k) |
| 2225 | |
| 2226 | var b bytes.Buffer |
| 2227 | for i := 0; i < s.NumTestFunctions; i++ { |
| 2228 | doemit := shouldEmitFP(i, k, s.FcnMask, s.PkgMask) |
| 2229 | s.Seed = s.GenPair(calleroutfile, checkeroutfile, i, k, |
| 2230 | &b, s.Seed, doemit) |
| 2231 | } |
| 2232 | |
| 2233 | // When minimization is in effect, we sometimes wind |
| 2234 | // up eliminating all refs to the utils package. Add a |
| 2235 | // dummy to help with this. |
| 2236 | fmt.Fprintf(calleroutfile, "\n// dummy\nvar Dummy UtilsType\n") |
| 2237 | fmt.Fprintf(checkeroutfile, "\n// dummy\nvar Dummy UtilsType\n") |
| 2238 | calleroutfile.Close() |
| 2239 | checkeroutfile.Close() |
| 2240 | } |
| 2241 | s.emitMain(mainoutfile, s.NumTestFunctions, s.FcnMask, s.PkgMask) |
| 2242 | |
| 2243 | // emit go.mod |
| 2244 | verb(1, "opening go.mod") |
| 2245 | fn := s.OutDir + "/go.mod" |
| 2246 | outf, err := os.OpenFile(fn, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666) |
| 2247 | if err != nil { |
| 2248 | log.Fatal(err) |
| 2249 | } |
| 2250 | outf.WriteString(fmt.Sprintf("module %s\n\ngo 1.17\n", s.PkgPath)) |
| 2251 | outf.Close() |
| 2252 | |
| 2253 | verb(1, "closing files") |
| 2254 | mainoutfile.Close() |
| 2255 | |
| 2256 | if s.errs == 0 && s.RunGoImports { |
| 2257 | runImports(allfiles) |
| 2258 | } |
| 2259 | |
| 2260 | return s.errs |
| 2261 | } |