TER1 (Statement): 98.18%
TER2 (Branch): 90.37%
TER3 (LCSAJ): 100.0% (24/24)
Approximate LCSAJ segments: 219
โ Covered โ this LCSAJ path was executed during testing.
โ Not covered โ this LCSAJ path was never executed. These are the paths to focus on.
Multiple dots on a line indicate that multiple control-flow paths begin at that line. Hovering over any dot shows:
start โ end โ jump
Uncovered paths show [NOT COVERED] in the tooltip.
1: package App::Test::Generator::CoverageGuidedFuzzer; 2: 3: use strict; 4: use warnings; 5: use Carp qw(croak); 6: use feature 'state'; 7: use Readonly; 8: 9: # -------------------------------------------------- 10: # Fuzzing loop parameters 11: # -------------------------------------------------- 12: Readonly my $DEFAULT_ITERATIONS => 100; 13: Readonly my $DEFAULT_TIMEOUT_SECS => 5; # per-call alarm() timeout; 0 disables 14: Readonly my $CORPUS_MUTATE_RATIO => 0.70; # 70% mutate, 30% explore 15: Readonly my $RANDOM_KEEP_RATIO => 0.20; # keep 20% random when no coverage 16: Readonly my $EDGE_CASE_RATIO => 0.40; # 40% chance to use declared edge case 17: Readonly my $INT_BOUNDARY_RATIO => 0.30; # 30% chance to use boundary int 18: Readonly my $STR_BOUNDARY_RATIO => 0.30; # 30% chance to use boundary length 19: Readonly my $SEED_CORPUS_SIZE => 5; # initial random inputs to seed corpus 20: Readonly my $DEFAULT_MAX_STR_LEN => 64; 21: Readonly my $MATCHES_REGEX_TIMEOUT_SECS => 1; # ReDoS guard for schema 'matches' patterns 22: Readonly my $DEFAULT_MAX_ARRAY => 4; # max elements in random array (0..N) 23: Readonly my $INT32_MAX => 2**31 - 1; 24: Readonly my $INT32_MIN => -(2**31); 25: 26: # -------------------------------------------------- 27: # Character set and interesting-string constants â 28: # computed once at load time rather than rebuilt on 29: # every _rand_string / _mutate_string call. 30: # -------------------------------------------------- 31: Readonly my @RAND_CHARS => ('a'..'z', 'A'..'Z', '0'..'9', ' ', "\t", "\n", "\0"); 32: Readonly my @INTERESTING_STRINGS => ( 33: '', ' ', "\0", "\n", "\t", 34: 'a' x 256, 35: 'null', 'undefined', 36: "'; DROP TABLE foo; --", 37: '<script>alert(1)</script>', 38: ); 39: 40: # -------------------------------------------------- 41: # Type name constants â used in schema dispatch 42: # -------------------------------------------------- 43: Readonly my $TYPE_INTEGER => 'integer'; 44: Readonly my $TYPE_NUMBER => 'number'; 45: Readonly my $TYPE_BOOLEAN => 'boolean'; 46: Readonly my $TYPE_ARRAY => 'arrayref'; 47: Readonly my $TYPE_HASH => 'hashref'; 48: Readonly my $TYPE_STRING => 'string'; 49: 50: # -------------------------------------------------- 51: # JSON module preference order 52: # -------------------------------------------------- 53: Readonly my @JSON_MODULES => qw(JSON::MaybeXS JSON); 54: 55: # Devel::Cover files a branch with no else/elsif, and every && / ||, 56: # under 'condition' rather than 'branch', so both must be read. 57: Readonly my @COVER_CRITERIA => qw(branch condition); 58: 59: Readonly my $SOFT_BUG_WARNING_RE => qr/uninitialized|undefined|blessed|invalid/i; 60: 61: our $VERSION = '0.52'; 62: 63: =encoding utf8 64: 65: =head1 NAME 66: 67: App::Test::Generator::CoverageGuidedFuzzer - AFL-style coverage-guided fuzzing for App::Test::Generator 68: 69: =head1 VERSION 70: 71: Version 0.52 72: 73: =head1 SYNOPSIS 74: 75: "Fuzzing" means calling a function many times with machine-made input, 76: to find input that makes it fail. The "corpus" is the list of inputs 77: that the fuzzer decided to keep. 78: 79: Pattern 1: fuzz a function that takes one number, then show the failures. 80: The C<input> key of the schema describes the one argument. 81: 82: use App::Test::Generator::CoverageGuidedFuzzer; 83: 84: my $fuzzer = App::Test::Generator::CoverageGuidedFuzzer->new( 85: schema => { input => { type => 'integer', min => 0, max => 100 } }, 86: target_sub => \&My::Module::validate, 87: iterations => 200, 88: seed => 42, 89: ); 90: 91: my $report = $fuzzer->run(); 92: printf "%d failures in %d calls\n", 93: $report->{bugs_found}, $report->{total_iterations}; 94: print " failed with: $_->{error}" for @{ $report->{bugs} }; 95: 96: Pattern 2: keep what was learned between two runs of your program. 97: 98: my $file = 't/corpus/validate.json'; 99: $fuzzer->load_corpus($file) if -e $file; # start from the last run 100: $fuzzer->run(); 101: 102: # Optional: trim corpus to minimum branch-covering subset before saving 103: my $stats = $fuzzer->minimize_corpus(); 104: printf "corpus %d -> %d entries\n", $stats->{before}, $stats->{after}; 105: 106: $fuzzer->save_corpus($file); 107: 108: Pattern 3: fuzz a method of an object. The object is passed first and 109: the generated input second. 110: 111: my $fuzzer = App::Test::Generator::CoverageGuidedFuzzer->new( 112: schema => { input => { type => 'string', max => 20 } }, 113: target_sub => \&My::Parser::parse, 114: instance => My::Parser->new(), 115: ); 116: $fuzzer->run(); 117: 118: Pattern 4: test with your own special values, here with non-ASCII text. 119: About 4 in 10 new inputs are taken from C<edge_case_array>. 120: 121: use utf8; 122: my $fuzzer = App::Test::Generator::CoverageGuidedFuzzer->new( 123: schema => { 124: input => { 125: type => 'string', 126: edge_case_array => [ '', 'na\x{EF}ve', "\x{1F600}" ], 127: }, 128: }, 129: target_sub => sub { length $_[0] }, 130: timeout => 2, 131: ); 132: $fuzzer->run(); 133: 134: =head1 DESCRIPTION 135: 136: Implements coverage-guided fuzzing on top of App::Test::Generator's 137: existing schema-driven input generation. Instead of purely random 138: generation it: 139: 140: =over 4 141: 142: =item 1. Generates or mutates a structured input 143: 144: =item 2. Runs the target sub under Devel::Cover to capture branch hits 145: 146: =item 3. Keeps inputs that discover new branches in a corpus 147: 148: =item 4. Preferentially mutates corpus entries in future iterations 149: 150: =back 151: 152: This is the Perl equivalent of what AFL/libFuzzer do at the byte level, 153: but operating on typed, schema-validated Perl data structures. 154: 155: =head1 METHODS 156: 157: =head2 new 158: 159: Construct a new coverage-guided fuzzer. 160: 161: my $fuzzer = App::Test::Generator::CoverageGuidedFuzzer->new( 162: schema => $yaml_schema, 163: target_sub => \&My::Module::validate, 164: iterations => 200, 165: seed => 42, 166: instance => $obj, # optional pre-built object for method calls 167: ); 168: 169: =head3 Arguments 170: 171: =over 4 172: 173: =item * C<schema> 174: 175: A hashref representing the parsed YAML schema for the target function. 176: Required. Only two keys are used: C<input>, which describes the single 177: argument that will be generated, and C<input_style>. Inside C<input> the 178: keys C<type>, C<min>, C<max>, C<sample_max>, C<matches>, C<items>, 179: C<properties>, C<optional> and C<edge_case_array> are used. For a string, 180: C<min> and C<max> are lengths counted in characters. 181: 182: C<sample_max> caps the integers and numbers that are generated, while C<max> 183: stays the bound a value is validated against: a documented maximum far above 184: the documented default (a PBKDF2 round count) costs time in proportion to its 185: value, so valid data stops at C<sample_max> while a mutated value between the 186: two is still accepted as valid. Mutations are kept out of the band between 187: the two: a mutated value that would land there becomes C<max + 1>, which the 188: routine refuses cheaply, so a slow value is never mistaken for a bug. 189: 190: =item * C<target_sub> 191: 192: A CODE reference to the function under test. Required.193: 194: =item * C<iterations> 195: 196: Number of fuzzing iterations to run. Optional - defaults to 100.Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_192_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
197: 198: =item * C<seed> 199: 200: Random seed for reproducible runs. Optional - defaults to C<time()>. 201: 202: =item * C<instance> 203: 204: An optional pre-built object to use as the invocant when calling the 205: target sub as a method. 206: 207: =item * C<timeout> 208: 209: Seconds to allow each C<target_sub> call before it is aborted via 210: C<alarm()> and recorded as a bug. Optional - defaults to 5. Set to 0 211: to disable the timeout (e.g. for target subs that legitimately block). 212: 213: =back 214: 215: =head3 Returns 216: 217: A blessed hashref. Croaks if C<schema> or C<target_sub> is missing. 218: 219: =head3 Side effects 220: 221: Calls Perl's C<srand> with the seed. This restarts the random number 222: sequence for the whole program, not only for this object. 223: Prints one warning per program if L<Devel::Cover> cannot be loaded. 224: 225: =head3 API SPECIFICATION 226: 227: =head4 input 228: 229: { 230: schema => { type => HASHREF }, 231: target_sub => { type => CODEREF }, 232: iterations => { type => SCALAR, optional => 1 }, 233: seed => { type => SCALAR, optional => 1 }, 234: instance => { type => OBJECT, optional => 1 }, 235: timeout => { type => SCALAR, optional => 1 }, 236: } 237: 238: =head4 output 239: 240: { 241: type => OBJECT, 242: isa => 'App::Test::Generator::CoverageGuidedFuzzer', 243: } 244: 245: =head3 EXAMPLE 246: 247: my $fuzzer = App::Test::Generator::CoverageGuidedFuzzer->new( 248: schema => { input => { type => 'string' } }, 249: target_sub => sub { length($_[0]) }, 250: iterations => 50, 251: seed => 1234, 252: ); 253: 254: =head3 MESSAGES 255: 256: =over 4 257: 258: =item C<schema required>
259: 260: C<schema> was not supplied or was falsy (e.g. C<undef> or C<0>). 261: 262: =item C<target_sub required> 263: 264: C<target_sub> was not supplied or was falsy. 265: 266: =back 267: 268: The mathematical description is in L</FORMAL SPECIFICATION>. 269: 270: =cut 271: 272: sub new {Mutants (Total: 4, Killed: 0, Survived: 4)
- NUM_BOUNDARY_258_37_>: Numeric boundary flip < to >
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_258_37_<=: Numeric boundary flip < to <=
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_258_37_>=: Numeric boundary flip < to >=
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- COND_INV_258_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
โ273 โ 304 โ 308 273: my ($class, %args) = @_; 274: 275: croak 'schema required' unless $args{schema}; 276: croak 'target_sub required' unless $args{target_sub}; 277: 278: my $self = bless { 279: schema => $args{schema}, 280: target_sub => $args{target_sub}, 281: instance => $args{instance}, 282: iterations => $args{iterations} // $DEFAULT_ITERATIONS, 283: seed => $args{seed} // time(), 284: timeout => $args{timeout} // $DEFAULT_TIMEOUT_SECS, 285: corpus => [], # [{input => ..., coverage => {...}}] 286: covered => {}, # "file:line:branch" => 1 287: bugs => [], # [{input => ..., error => ...}] 288: stats => { 289: total => 0, 290: interesting => 0, 291: bugs => 0, 292: coverage => 0, 293: }, 294: _cover_available => undef, 295: }, $class; 296: 297: srand($self->{seed}); 298: 299: # Probe for Devel::Cover availability once at construction time 300: $self->{_cover_available} = eval { require Devel::Cover; 1 } ? 1 : 0; 301: 302: # Warn once per process if coverage guidance is unavailable 303: state $cover_warned = 0; 304: if(!$self->{_cover_available} && !$cover_warned++) { 305: warn 'Devel::Cover not available; fuzzing without coverage guidance.'; 306: } 307: 308: return $self; 309: } 310: 311: =head2 run 312: 313: Run the coverage-guided fuzzing loop and return a summary report. 314: 315: my $report = $fuzzer->run(); 316: printf "Branches covered: %d\n", $report->{branches_covered}; 317: printf "Bugs found: %d\n", $report->{bugs_found}; 318: 319: =head3 Arguments 320: 321: None beyond C<$self>. 322: 323: =head3 Returns 324: 325: A hashref with keys C<total_iterations>, C<interesting_inputs>, 326: C<corpus_size>, C<branches_covered>, C<bugs_found>, and C<bugs>. 327: 328: The numbers are totals for the life of the object. If you call C<run> 329: twice, C<total_iterations> is twice the C<iterations> value. 330: 331: =head3 Side effects 332: 333: Calls C<target_sub> once per iteration. Adds five new random inputs to 334: the corpus at the start of every call. Uses C<alarm> and the C<ALRM> 335: signal for the timeout, so any alarm that your own program had set is 336: cancelled. 337: 338: =head3 Notes 339: 340: A call that takes longer than C<timeout> seconds is stopped and recorded 341: as a bug with the error C<target_sub timed out after Ns>. 342: 343: The same failing input can be recorded more than once. The C<bugs> list 344: is not checked for duplicates. 345: 346: A C<target_sub> call that dies is only recorded in C<bugs> when the 347: input that triggered it is valid per C<schema>. A die triggered by an 348: input the schema itself marks invalid (e.g. out of the declared 349: C<min>/C<max> range) is expected behaviour, not a bug, and is silently 350: discarded. 351: 352: =head3 API SPECIFICATION 353: 354: =head4 input 355: 356: { 357: self => { type => OBJECT, isa => 'App::Test::Generator::CoverageGuidedFuzzer' }, 358: } 359: 360: =head4 output 361: 362: { 363: type => HASHREF, 364: keys => { 365: total_iterations => { type => SCALAR }, 366: interesting_inputs => { type => SCALAR }, 367: corpus_size => { type => SCALAR }, 368: branches_covered => { type => SCALAR }, 369: bugs_found => { type => SCALAR }, 370: bugs => { type => ARRAYREF }, 371: }, 372: } 373: 374: =head3 EXAMPLE 375: 376: my $report = $fuzzer->run(); 377: printf "Iterations: %d\n", $report->{total_iterations}; 378: printf "Corpus size: %d\n", $report->{corpus_size}; 379: printf "Bugs found: %d\n", $report->{bugs_found}; 380: for my $bug (@{ $report->{bugs} }) { 381: printf " input=%s error=%s\n", $bug->{input}, $bug->{error}; 382: } 383: 384: The mathematical description is in L</FORMAL SPECIFICATION>. 385: 386: =head3 PSEUDOCODE 387: 388: seed corpus with SEED_CORPUS_SIZE random inputs 389: for i in 1..iterations: 390: if corpus non-empty and rand < CORPUS_MUTATE_RATIO: 391: input = mutate(random corpus entry) 392: else: 393: input = generate_random() 394: run target_sub(input), record coverage and bugs 395: return report hashref 396: 397: =cut 398: 399: sub run { โ400 โ 406 โ 422 400: my ($self) = @_; 401: 402: # Phase 1: seed the corpus with a small set of random inputs 403: $self->_seed_corpus(); 404: 405: # Phase 2: main fuzzing loop â alternate between mutation and exploration 406: for my $i (1 .. $self->{iterations}) { 407: my $input; 408: 409: if(@{ $self->{corpus} } && rand() < $CORPUS_MUTATE_RATIO) { 410: # Mutate a randomly chosen corpus entry 411: my $parent = $self->{corpus}[ int(rand(@{ $self->{corpus} })) ]; 412: $input = $self->_mutate($parent->{input}, $self->{schema}{input}); 413: } else { 414: # Fresh random generation for exploration 415: $input = $self->_generate_random(); 416: } 417: 418: $self->_run_one($input); 419: $self->{stats}{total}++; 420: } 421: 422: $self->{stats}{coverage} = scalar keys %{ $self->{covered} }; 423: return $self->_build_report(); 424: } 425: 426: =head2 corpus 427: 428: Return the accumulated corpus as an arrayref of hashrefs with keys 429: C<input> and C<coverage>. 430: 431: my $corpus = $fuzzer->corpus(); 432: 433: The arrayref is the fuzzer's own list, not a copy. Do not change it. 434: The list is empty until C<run> or C<load_corpus> has been called. 435: 436: =head3 API SPECIFICATION 437: 438: =head4 input 439: 440: { self => { type => OBJECT, isa => 'App::Test::Generator::CoverageGuidedFuzzer' } } 441: 442: =head4 output 443: 444: { type => ARRAYREF } 445: 446: =head3 EXAMPLE 447: 448: my $corpus = $fuzzer->corpus(); 449: printf "%d entries in corpus\n", scalar @{$corpus}; 450: # Each entry: { input => ..., coverage => { 'file:line:branch' => 1, ... } } 451: 452: =cut 453: 454: sub corpus { $_[0]->{corpus} } 455: 456: =head2 bugs 457: 458: Return bugs found as an arrayref of hashrefs with keys C<input> and 459: C<error>. 460: 461: my $bugs = $fuzzer->bugs(); 462: 463: The arrayref is the fuzzer's own list, not a copy. Do not change it. 464: C<error> is always text. C<input> can be C<undef>.
Mutants (Total: 2, Killed: 2, Survived: 0)
465: 466: =head3 API SPECIFICATION 467: 468: =head4 input 469: 470: { self => { type => OBJECT, isa => 'App::Test::Generator::CoverageGuidedFuzzer' } } 471: 472: =head4 output 473: 474: { type => ARRAYREF } 475: 476: =head3 EXAMPLE 477: 478: my $bugs = $fuzzer->bugs(); 479: for my $b (@{$bugs}) { 480: printf "Bug: input=%s error=%s\n", $b->{input}, $b->{error}; 481: } 482: 483: =cut 484: 485: sub bugs { $_[0]->{bugs} } 486: 487: =head2 save_corpus 488: 489: Serialise the corpus to a JSON file for replay or extension on future 490: runs. 491: 492: $fuzzer->save_corpus('t/corpus/validate.json'); 493: 494: =head3 Arguments
495: 496: =over 4 497: 498: =item * C<$path> 499: 500: Path to write the JSON corpus file. Required. 501: 502: =back 503: 504: =head3 Returns 505: 506: Nothing useful. Croaks if the file cannot be written or no JSON module is 507: available. 508: 509: =head3 Side effects 510: 511: Writes a JSON file to C<$path>. An existing file is replaced. 512: The file holds the seed, the corpus inputs and the bugs. 513: Branch data is not saved. The file is UTF-8. 514: 515: =head3 API SPECIFICATION 516: 517: =head4 input 518: 519: {Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_494_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes520: self => { type => OBJECT, isa => 'App::Test::Generator::CoverageGuidedFuzzer' }, 521: path => { type => SCALAR }, 522: } 523: 524: =head4 output 525: 526: { type => UNDEF } 527: 528: =head3 EXAMPLEMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_519_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
529: 530: $fuzzer->run(); 531: $fuzzer->minimize_corpus(); 532: $fuzzer->save_corpus('t/corpus/my_func.json'); 533: 534: =head3 MESSAGES
535: 536: =over 4 537: 538: =item C<path required> 539: 540: No path argument was supplied. 541: 542: =item C<Cannot write corpus to $path: $!> 543: 544: The file could not be opened for writing (permissions, missing directory, etc.). 545: 546: =item C<No JSON module available; install JSON or JSON::MaybeXS> 547: 548: Neither C<JSON::MaybeXS> nor C<JSON> is installed. 549: 550: =item C<encountered object ...> or C<encountered CODE ...> 551: 552: Raised by the JSON module. A corpus input or bug input holds an object 553: or a code reference, which JSON cannot store. This check happens after 554: the file has been opened, so the file is left empty. 555: 556: =back 557: 558: The mathematical description is in L</FORMAL SPECIFICATION>. 559: 560: =cut 561: 562: sub save_corpus { 563: my ($self, $path) = @_; 564: 565: croak 'path required' unless defined $path; 566: 567: my $json = _load_json_module(); 568: 569: open my $fh, '>:raw', $path 570: or croak "Cannot write corpus to $path: $!"; 571: 572: print $fh $json->new->utf8->pretty->encode({ 573: seed => $self->{seed}, 574: corpus => [ map { { input => $_->{input} } } @{ $self->{corpus} } ], 575: bugs => $self->{bugs}, 576: }); 577: 578: close $fh; 579: } 580: 581: =head2 load_corpus 582: 583: Load a previously saved corpus JSON file, pre-seeding the fuzzer so 584: it continues from where it left off. 585: 586: $fuzzer->load_corpus('t/corpus/validate.json'); 587: 588: =head3 Arguments 589: 590: =over 4 591: 592: =item * C<$path> 593: 594: Path to the JSON corpus file to load. Required. 595: 596: =back 597: 598: =head3 Returns 599: 600: Nothing useful. Croaks if the file cannot be read or no JSON module isMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_534_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
601: available. 602: 603: =head3 Side effects 604: 605: Appends loaded entries to C<< $self->{corpus} >>. Entries already in the 606: corpus are kept, so loading the same file twice gives every entry twice. 607: C<minimize_corpus> removes such copies. 608: 609: =head3 API SPECIFICATION 610: 611: =head4 input 612: 613: { 614: self => { type => OBJECT, isa => 'App::Test::Generator::CoverageGuidedFuzzer' }, 615: path => { type => SCALAR }, 616: } 617: 618: =head4 output 619: 620: { type => UNDEF } 621: 622: =head3 EXAMPLE 623: 624: my $fuzzer2 = App::Test::Generator::CoverageGuidedFuzzer->new( 625: schema => $schema, 626: target_sub => \&My::Module::validate, 627: ); 628: $fuzzer2->load_corpus('t/corpus/my_func.json'); 629: my $report = $fuzzer2->run(); 630: 631: =head3 MESSAGES 632: 633: =over 4 634: 635: =item C<path required> 636: 637: No path argument was supplied. 638:
639: =item C<Cannot read corpus from $path: $!> 640: 641: The file could not be opened for reading (missing file, permissions, etc.). 642: 643: =item C<malformed JSON string ...> and similar 644: 645: Raised by the JSON module. The file is not valid JSON. 646: 647: =back 648: 649: =head3 Notes 650: 651: C<load_corpus> does B<not> restore C<bugs> from the JSON file. 652: The C<bugs> array in the JSON is written by C<save_corpus> but ignored on load. 653: The loaded fuzzer starts with an empty C<bugs> list. Seed values are also not 654: restored; the constructor-supplied seed is retained. 655: 656: The mathematical description is in L</FORMAL SPECIFICATION>. 657: 658: =cut 659: 660: sub load_corpus { โ661 โ 680 โ 0 661: my ($self, $path) = @_; 662: 663: croak 'path required' unless defined $path;Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_638_2: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes๐งช Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_638_2: Replace return expression with undef
LOW: Mutation survived, but impact may be minor๐งช Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 2, Killed: 2, Survived: 0)
664: 665: my $json = _load_json_module(); 666: 667: open my $fh, '<:raw', $path
668: or croak "Cannot read corpus from $path: $!"; 669:Mutants (Total: 5, Killed: 0, Survived: 5)
- NUM_BOUNDARY_667_16_>: Numeric boundary flip < to >
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_667_16_<=: Numeric boundary flip < to <=
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_667_16_>=: Numeric boundary flip < to >=
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- BOOL_NEGATE_667_2: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes๐งช Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_667_2: Replace return expression with undef
LOW: Mutation survived, but impact may be minor๐งช Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 2, Killed: 2, Survived: 0)
670: my $text = do { local $/; <$fh> }; 671: close $fh; 672: 673: # Files written before 0.48 hold Latin-1 bytes rather than UTF-8; 674: # those fail the UTF-8 decode and are read the old way instead. 675: my $data = eval { $json->new->utf8->decode($text) } 676: // $json->new->decode($text); 677: 678: # Load corpus entries with empty coverage â coverage state from a 679: # previous process cannot be restored, only the inputs themselves 680: for my $entry (@{ $data->{corpus} // [] }) { 681: push @{ $self->{corpus} }, { 682: input => $entry->{input}, 683: coverage => {}, 684: }; 685: } 686: } 687: 688: =head2 minimize_corpus 689: 690: Reduce the corpus to the smallest subset that still covers every 691: branch hit by the full corpus, using a greedy set-cover algorithm. 692: 693: Entries without branch data (loaded from a previous run, or kept by 694: random sampling when Devel::Cover is unavailable) are deduplicated by 695: input fingerprint and retained in full. They cannot be evaluated for 696: coverage contribution without re-running them. Bug-triggering inputs 697: are always kept regardless of coverage contribution. 698: 699: my $stats = $fuzzer->minimize_corpus();
Mutants (Total: 2, Killed: 2, Survived: 0)
700: printf "Corpus: %d -> %d entries (%d branches covered)\n", 701: $stats->{before}, $stats->{after}, $stats->{branches}; 702: 703: =head3 Returns 704: 705: A hashref with keys C<before> (corpus size before), C<after> (corpus 706: size after), and C<branches> (total unique branches still covered). 707: 708: =head3 API SPECIFICATION 709: 710: =head4 input 711: 712: { self => { type => OBJECT, isa => 'App::Test::Generator::CoverageGuidedFuzzer' } } 713: 714: =head4 output 715: 716: { 717: type => HASHREF, 718: constraint => sub { defined $_[0]{before} && defined $_[0]{after} && defined $_[0]{branches} }, 719: } 720: 721: =head3 EXAMPLE 722: 723: $fuzzer->run(); 724: my $stats = $fuzzer->minimize_corpus();
Mutants (Total: 2, Killed: 2, Survived: 0)
725: printf "Corpus: %d -> %d entries (%d branches)\n",
Mutants (Total: 2, Killed: 2, Survived: 0)
726: $stats->{before}, $stats->{after}, $stats->{branches}; 727: $fuzzer->save_corpus('t/corpus/my_func.json'); 728: 729: The mathematical description is in L</FORMAL SPECIFICATION>. 730:
731: =head3 PSEUDOCODE 732:Mutants (Total: 4, Killed: 1, Survived: 3)
- NUM_BOUNDARY_730_54_>: Numeric boundary flip < to >
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_730_54_<=: Numeric boundary flip < to <=
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_730_54_>=: Numeric boundary flip < to >=
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );Mutants (Total: 2, Killed: 2, Survived: 0)
733: partition corpus into with-coverage and without-coverage entries 734: greedy set-cover: repeatedly pick entry covering most uncovered branches 735: deduplicate without-coverage entries by JSON fingerprint 736: unconditionally add all bug inputs not already in minimized set
Mutants (Total: 3, Killed: 3, Survived: 0)
737: replace self.corpus with minimized list
738: return { before, after, branches }Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_737_35: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes๐งช Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_737_35: Replace return expression with undef
LOW: Mutation survived, but impact may be minor๐งช Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );739:Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_738_35: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes๐งช Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_738_35: Replace return expression with undef
LOW: Mutation survived, but impact may be minor๐งช Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 2, Killed: 2, Survived: 0)
740: =cut
Mutants (Total: 2, Killed: 2, Survived: 0)
741:
742: sub minimize_corpus { โ743 โ 758 โ 777 743: my ($self) = @_; 744: 745: my @all = @{ $self->{corpus} }; 746: my $before = scalar @all; 747: 748: my @with_cov = grep { %{ $_->{coverage} } } @all; 749: my @without_cov = grep { !%{ $_->{coverage} } } @all; 750: 751: # Greedy set-cover: find the smallest subset of with-coverage entries 752: # that still covers every branch seen across the whole corpus. 753: my %uncovered; 754: $uncovered{$_} = 1 for map { keys %{ $_->{coverage} } } @with_cov; 755: my $total_branches = scalar keys %uncovered; 756: 757: my @selected; 758: while (%uncovered && @with_cov) { 759: my ($best, $best_idx, $best_n) = (undef, -1, 0); 760: for my $i (0 .. $#with_cov) { 761: my $n = grep { $uncovered{$_} } keys %{ $with_cov[$i]{coverage} }; 762: if ($n > $best_n) {Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_741_35: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes๐งช Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_741_35: Replace return expression with undef
LOW: Mutation survived, but impact may be minor๐งช Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );763: $best_n = $n; 764: $best_idx = $i;Mutants (Total: 4, Killed: 0, Survived: 4)
- NUM_BOUNDARY_762_12_>: Numeric boundary flip < to >
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_762_12_<=: Numeric boundary flip < to <=
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_762_12_>=: Numeric boundary flip < to >=
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- COND_INV_762_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
765: $best = $with_cov[$i]; 766: } 767: }
Mutants (Total: 2, Killed: 2, Survived: 0)
768: last unless $best_n; 769: 770: push @selected, $best; 771: splice @with_cov, $best_idx, 1; 772: delete $uncovered{$_} for keys %{ $best->{coverage} }; 773: } 774: 775: # Deduplicate no-coverage entries by input fingerprint so that repeated 776: # loads of the same corpus file do not cause the entry count to grow. โ777 โ 779 โ 785 777: my %seen; 778: my @deduped; 779: for my $entry (@without_cov) { 780: my $key = _fingerprint($entry->{input}); 781: next if $seen{$key}++; 782: push @deduped, $entry; 783: } 784: โ785 โ 790 โ 797 785: my @minimized = (@selected, @deduped); 786:
787: # Bug-triggering inputs are always kept â they are the most valuable 788: # findings regardless of whether they add unique branch coverage. 789: my %kept = map { _fingerprint($_->{input}) => 1 } @minimized; 790: for my $bug (@{ $self->{bugs} }) { 791: my $key = _fingerprint($bug->{input}); 792: unless ($kept{$key}++) { 793: push @minimized, { input => $bug->{input}, coverage => {} }; 794: } 795: } 796: 797: $self->{corpus} = \@minimized; 798: 799: return { 800: before => $before, 801: after => scalar @minimized, 802: branches => $total_branches, 803: }; 804: } 805: 806: # -------------------------------------------------- 807: # _fingerprint 808: # 809: # Purpose: Produce a stable, canonical string key 810: # for an arbitrary Perl value, for use as 811: # a deduplication key.Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_786_2: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes๐งช Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_786_2: Replace return expression with undef
LOW: Mutation survived, but impact may be minor๐งช Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );812: # 813: # Entry: $val - any Perl value (scalar, ref, undef). 814: # Exit: Returns a deterministic string. 815: # Side effects: None. 816: # 817: # Notes: Uses the JSON module in canonical mode so 818: # hash keys are always sorted. Avoids 819: # Data::Dumper whose output includes blessedMutants (Total: 4, Killed: 0, Survived: 4)
- NUM_BOUNDARY_811_12_>: Numeric boundary flip < to >
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_811_12_<=: Numeric boundary flip < to <=
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_811_12_>=: Numeric boundary flip < to >=
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- COND_INV_811_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes820: # class names that vary across Perl versions. 821: # -------------------------------------------------- 822: sub _fingerprint {Mutants (Total: 3, Killed: 0, Survived: 3)
- NUM_BOUNDARY_819_19_>: Numeric boundary flip < to >
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_819_19_<=: Numeric boundary flip < to <=
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_819_19_>=: Numeric boundary flip < to >=
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );โ823 โ 826 โ 830 823: my ($val) = @_; 824: return 'null' unless defined $val; 825: state $encoder; 826: unless ($encoder) { 827: my $mod = _load_json_module(); 828: $encoder = eval { $mod->new->canonical(1) }; 829: } 830: return eval { $encoder->encode($val) } // "$val"; 831: } 832: 833: # -------------------------------------------------- 834: # _load_json_module 835: # 836: # Find and load the first available JSON 837: # module from the preference list. 838: # 839: # Entry: None. 840: # Exit: Returns the name of the loaded module. 841: # Croaks if none are available. 842: # 843: # Side effects: Loads a JSON module into the process. 844: # 845: # Notes: Uses explicit require rather than string 846: # eval for safety. JSON::MaybeXS is 847: # preferred over JSON. 848: # -------------------------------------------------- 849: sub _load_json_module { โ850 โ 852 โ 861 850: state $cached; 851: return $cached if defined $cached; 852: for my $mod (@JSON_MODULES) { 853: # Convert package name to file path â require $var does not 854: # do the :: -> / conversion that bareword require does 855: (my $file = $mod) =~ s{::}{/}g; 856: $file .= '.pm'; 857: if (eval { require $file; 1 }) { 858: return $cached = $mod; 859: } 860: } 861: croak 'No JSON module available; install JSON or JSON::MaybeXS'; 862: } 863: 864: # -------------------------------------------------- 865: # _run_oneMutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_822_2: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes๐งช Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_822_2: Replace return expression with undef
LOW: Mutation survived, but impact may be minor๐งช Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 2, Killed: 2, Survived: 0)
866: # 867: # Run the target sub with a single input, 868: # record coverage, detect bugs, and update 869: # the corpus if the input is interesting. 870: # 871: # Entry: $input - the value to pass to target_sub. 872: # 873: # Exit: Returns nothing. Updates $self->{corpus}, 874: # $self->{bugs}, and $self->{covered}. 875: # 876: # Side effects: Calls target_sub. May update corpus 877: # and covered hashes. 878: # 879: # Notes: When Devel::Cover is available, coverage 880: # is captured via _run_with_cover. 881: # Unexpected warnings are treated as soft 882: # bugs if they match known warning patterns. 883: # -------------------------------------------------- 884: sub _run_one { โ885 โ 889 โ 898 885: my ($self, $input) = @_; 886: 887: my ($result, $error, $coverage); 888:
Mutants (Total: 2, Killed: 2, Survived: 0)
889: if($self->{_cover_available}) { 890: $coverage = $self->_run_with_cover($input, \$result, \$error); 891: } else { 892: $coverage = {};
Mutants (Total: 1, Killed: 1, Survived: 0)
893: ($result, $error) = $self->_call_target($input);
Mutants (Total: 2, Killed: 2, Survived: 0)
894: } 895: 896: # Record bugs â only when the input was valid per the schema.
Mutants (Total: 2, Killed: 2, Survived: 0)
897: # A die on invalid input is correct behaviour, not a bug. โ898 โ 898 โ 904 898: if($error && $self->_input_is_valid($input)) { 899: push @{ $self->{bugs} }, { input => $input, error => "$error" }; 900: $self->{stats}{bugs}++; 901: } 902: 903: # Keep the input in the corpus if it exercised new branches โ904 โ 904 โ 0 904: if($self->_is_interesting($coverage)) { 905: push @{ $self->{corpus} }, { input => $input, coverage => $coverage }; 906: $self->_update_covered($coverage); 907: $self->{stats}{interesting}++; 908: } 909: } 910: 911: # -------------------------------------------------- 912: # _call_target 913: #
Mutants (Total: 2, Killed: 2, Survived: 0)
914: # Purpose: Call the target sub once with a single 915: # input, bounded by the timeout. 916: # 917: # Entry: $input - value to pass to target_sub. 918: # 919: # Exit: Returns ($result, $error). $error is undef 920: # when the call neither died nor warned in 921: # a way that counts as a soft bug. 922: # 923: # Side effects: Calls target_sub. Uses alarm(). 924: # 925: # Notes: A hanging target_sub would otherwise hang
Mutants (Total: 1, Killed: 1, Survived: 0)
926: # the whole fuzzing run; alarm() bounds it
Mutants (Total: 2, Killed: 2, Survived: 0)
927: # and surfaces the timeout as an error. 928: # -------------------------------------------------- 929: sub _call_target { โ930 โ 948 โ 953 930: my ($self, $input) = @_; 931:
Mutants (Total: 2, Killed: 2, Survived: 0)
932: # Include instance as invocant for method calls 933: my @call_args = defined($self->{instance}) 934: ? ($self->{instance}, $input)
Mutants (Total: 2, Killed: 2, Survived: 0)
935: : ($input); 936: 937: my ($result, $error, @warnings); 938: eval { 939: local $SIG{__WARN__} = sub { push @warnings, @_ }; 940: local $SIG{__DIE__}; 941: local $SIG{ALRM} = sub { die "target_sub timed out after $self->{timeout}s\n" }; 942: alarm($self->{timeout}) if $self->{timeout}; 943: $result = $self->{target_sub}->(@call_args); 944: }; 945: alarm(0) if $self->{timeout}; 946: $error = $@ if $@; 947: 948: if(!defined($error) && @warnings) { 949: my $w = join '', @warnings; 950: $error = "warning: $w" if $w =~ $SOFT_BUG_WARNING_RE; 951: } 952: 953: return ($result, $error); 954: } 955: 956: # -------------------------------------------------- 957: # _run_with_cover
Mutants (Total: 2, Killed: 2, Survived: 0)
958: # 959: # Purpose: Run the target sub with Devel::Cover 960: # active and return the set of newly hit 961: # branches as a hashref.
Mutants (Total: 1, Killed: 1, Survived: 0)
962: #
Mutants (Total: 2, Killed: 2, Survived: 0)
963: # Entry: $input - value to pass to target_sub.
Mutants (Total: 5, Killed: 5, Survived: 0)
964: # $result_ref - scalar ref to store result.
Mutants (Total: 5, Killed: 5, Survived: 0)
965: # $error_ref - scalar ref to store error. 966: # 967: # Exit: Returns a hashref of newly hit branch 968: # keys ("file:line:branch").
Mutants (Total: 2, Killed: 2, Survived: 0)
969: #
970: # Side effects: Calls Devel::Cover::start/stop.Mutants (Total: 5, Killed: 0, Survived: 5)
- NUM_BOUNDARY_969_47_>: Numeric boundary flip < to >
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_969_47_<=: Numeric boundary flip < to <=
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_969_47_>=: Numeric boundary flip < to >=
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- BOOL_NEGATE_969_3: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes๐งช Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_969_3: Replace return expression with undef
LOW: Mutation survived, but impact may be minor๐งช Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );971: # Sets $$result_ref and $$error_ref. 972: # 973: # Notes: Snapshot comparison is imprecise for 974: # concurrent use but correct for single-Mutants (Total: 5, Killed: 0, Survived: 5)
- NUM_BOUNDARY_970_47_<: Numeric boundary flip > to <
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_970_47_>=: Numeric boundary flip > to >=
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_970_47_<=: Numeric boundary flip > to <=
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- BOOL_NEGATE_970_3: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes๐งช Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_970_3: Replace return expression with undef
LOW: Mutation survived, but impact may be minor๐งช Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 5, Killed: 5, Survived: 0)
975: # threaded fuzzing. Instance is passed
Mutants (Total: 5, Killed: 5, Survived: 0)
976: # as invocant when set. Devel::Cover state
Mutants (Total: 1, Killed: 1, Survived: 0)
977: # only grows, so this iteration's "before" 978: # is exactly the previous iteration's 979: # "after" -- cached in $self to avoid two 980: # full Devel::Cover walks per iteration. 981: # -------------------------------------------------- 982: sub _run_with_cover { โ983 โ 999 โ 1003 983: my ($self, $input, $result_ref, $error_ref) = @_; 984: 985: Devel::Cover::start() if Devel::Cover->can('start'); 986: 987: my $before_ref = $self->{_last_cover_snapshot} || {}; 988: my %before = %{$before_ref}; 989: 990: ($$result_ref, my $error) = $self->_call_target($input); 991: $$error_ref = $error if defined $error; 992:
Mutants (Total: 2, Killed: 2, Survived: 0)
993: my $after = $self->_snapshot_cover(); 994: $self->{_last_cover_snapshot} = $after; 995: Devel::Cover::stop() if Devel::Cover->can('stop'); 996:
Mutants (Total: 2, Killed: 2, Survived: 0)
997: # Return only branches newly hit in this call 998: my %delta; 999: for my $key (keys %{$after}) {
Mutants (Total: 2, Killed: 2, Survived: 0)
1000: $delta{$key} = 1 unless exists $before{$key}; 1001: } 1002:
Mutants (Total: 2, Killed: 2, Survived: 0)
1003: return \%delta; 1004: } 1005:
Mutants (Total: 2, Killed: 2, Survived: 0)
1006: # -------------------------------------------------- 1007: # _snapshot_cover 1008: # 1009: # Purpose: Take a lightweight snapshot of the 1010: # currently hit branches from Devel::Cover. 1011: # 1012: # Entry: None beyond $self. 1013: # Exit: Returns a hashref of "criterion:op:slot" keys. 1014: # 1015: # Side effects: Reads Devel::Cover internal state. 1016: # 1017: # Notes: Falls back to empty hash if the 1018: # Devel::Cover API is not accessible. 1019: # All errors are silently swallowed since 1020: # coverage is best-effort. 1021: # -------------------------------------------------- 1022: sub _snapshot_cover { 1023: my ($self) = @_; 1024: my %snap; 1025: 1026: eval { 1027: # coverage() is the XS accessor for the live counters. It only
Mutants (Total: 1, Killed: 1, Survived: 0)
1028: # exists when the program was started under Devel::Cover; a 1029: # late require leaves it undefined and nothing is collected.
1030: # (get_coverage() returns the criteria names, not the data.) 1031: return unless defined &Devel::Cover::coverage; 1032: my $cover = Devel::Cover::coverage(0) or return; 1033:Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_1029_3: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes๐งช Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_1029_3: Replace return expression with undef
LOW: Mutation survived, but impact may be minor๐งช Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );1034: for my $criterion (@COVER_CRITERIA) {Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_1033_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes1035: my $data = $cover->{$criterion} or next; 1036: for my $key (keys %{$data}) {Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_1034_4: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes๐งช Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_1034_4: Replace return expression with undef
LOW: Mutation survived, but impact may be minor๐งช Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );1037: my $counts = $data->{$key}; 1038: next unless ref($counts) eq 'ARRAY';Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_1036_4: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes๐งช Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_1036_4: Replace return expression with undef
LOW: Mutation survived, but impact may be minor๐งช Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );1039: 1040: # Keys are packed op addresses; hex keeps them printable 1041: my $id = unpack('H*', $key); 1042: for my $i (0 .. $#{$counts}) {Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_1038_4: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes๐งช Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_1038_4: Replace return expression with undef
LOW: Mutation survived, but impact may be minor๐งช Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 2, Killed: 2, Survived: 0)
1043: $snap{"$criterion:$id:$i"} = 1 if $counts->[$i]; 1044: } 1045: }
Mutants (Total: 2, Killed: 2, Survived: 0)
1046: } 1047: }; 1048: 1049: return \%snap;
Mutants (Total: 2, Killed: 2, Survived: 0)
1050: } 1051: 1052: # -------------------------------------------------- 1053: # _is_interesting 1054: # 1055: # Purpose: Return true if the coverage hashref 1056: # contains any branch not yet in the 1057: # global covered set. 1058: # 1059: # Entry: $coverage - hashref of branch keys. 1060: # Exit: Returns 1 if interesting, 0 otherwise. 1061: # 1062: # Side effects: None. 1063: # 1064: # Notes: When no coverage data is available, 1065: # keeps a random sample of inputs at 1066: # RANDOM_KEEP_RATIO so the corpus still 1067: # grows even without branch feedback. 1068: # -------------------------------------------------- 1069: sub _is_interesting {
โ1070 โ 1073 โ 1078 1070: my ($self, $coverage) = @_; 1071: 1072: # Check for any newly covered branch 1073: for my $key (keys %{$coverage}) { 1074: return 1 unless $self->{covered}{$key}; 1075: } 1076:Mutants (Total: 1, Killed: 0, Survived: 1)
- NUM_BOUNDARY_1069_12_!=: Numeric boundary flip == to !=
HIGH: Likely missing edge-case test (boundary value)๐งช Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );Mutants (Total: 2, Killed: 2, Survived: 0)
1077: # No coverage data â keep a random sample to grow the corpus 1078: return rand() < $RANDOM_KEEP_RATIO unless %{$coverage}; 1079: 1080: return 0; 1081: } 1082: 1083: # -------------------------------------------------- 1084: # _update_covered 1085: # 1086: # Purpose: Merge newly covered branches into the 1087: # global covered set. 1088: # 1089: # Entry: $coverage - hashref of branch keys. 1090: # Exit: Returns nothing. Updates $self->{covered}. 1091: # Side effects: Modifies $self->{covered}. 1092: # -------------------------------------------------- 1093: sub _update_covered { 1094: my ($self, $coverage) = @_; 1095: $self->{covered}{$_} = 1 for keys %{$coverage}; 1096: } 1097: 1098: # -------------------------------------------------- 1099: # _generate_random 1100: #
Mutants (Total: 2, Killed: 2, Survived: 0)
1101: # Purpose: Generate a random input value from the 1102: # top-level schema input specification. 1103: # 1104: # Entry: None beyond $self. 1105: # Exit: Returns a randomly generated value. 1106: # Side effects: None. 1107: # -------------------------------------------------- 1108: sub _generate_random { 1109: my ($self) = @_; 1110: return $self->_generate_for_schema($self->{schema}{input}); 1111: } 1112: 1113: # -------------------------------------------------- 1114: # _generate_for_schema 1115: # 1116: # Purpose: Recursively generate a random value 1117: # matching a schema specification hashref. 1118: # 1119: # Entry: $spec - schema spec hashref or scalar 1120: # type hint. 1121: # 1122: # Exit: Returns a generated value appropriate 1123: # for the spec type, or undef if spec is
1124: # absent or 'undef'. 1125: # 1126: # Side effects: None. 1127: # 1128: # Notes: Edge cases declared in edge_case_array 1129: # are selected at EDGE_CASE_RATIO frequency 1130: # to bias toward known interesting values. 1131: # -------------------------------------------------- 1132: sub _generate_for_schema { โ1133 โ 1141 โ 1147 1133: my ($self, $spec) = @_; 1134: 1135: return undef unless defined $spec; 1136: return undef if $spec eq 'undef'; 1137: 1138: my $type = ref($spec) ? ($spec->{type} // $TYPE_STRING) : $TYPE_STRING;Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_1123_4: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes๐งช Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_1123_4: Replace return expression with undef
LOW: Mutation survived, but impact may be minor๐งช Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );1139: 1140: # Bias toward declared edge cases at EDGE_CASE_RATIO frequency 1141: if(ref($spec) && $spec->{edge_case_array} && rand() < $EDGE_CASE_RATIO) { 1142: my @ec = @{ $spec->{edge_case_array} }; 1143: return $ec[ int(rand(@ec)) ]; 1144: } 1145: 1146: # Dispatch to type-specific generator โ1147 โ 1147 โ 0 1147: if ($type eq $TYPE_INTEGER) { return $self->_rand_int($spec) } 1148: elsif ($type eq $TYPE_NUMBER) { return $self->_rand_num($spec) } 1149: elsif ($type eq $TYPE_BOOLEAN) { return int(rand(2)) } 1150: elsif ($type eq $TYPE_ARRAY) { return $self->_rand_array($spec) } 1151: elsif ($type eq $TYPE_HASH) { return $self->_rand_hash($spec) } 1152: else { return $self->_rand_string($spec) } 1153: } 1154: 1155: # -------------------------------------------------- 1156: # _rand_int 1157: # 1158: # Purpose: Generate a random integer within the 1159: # spec's min/max range, biased towardMutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_1138_4: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes๐งช Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_1138_4: Replace return expression with undef
LOW: Mutation survived, but impact may be minor๐งช Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );1160: # boundary values at INT_BOUNDARY_RATIO. 1161: # 1162: # Entry: $spec - schema spec hashref. 1163: # Exit: Returns an integer scalar. 1164: # Side effects: None. 1165: # -------------------------------------------------- 1166: sub _rand_int { โ1167 โ 1178 โ 1183 1167: my ($self, $spec) = @_; 1168: 1169: my $min = $spec->{min} // $INT32_MIN; 1170: # sample_max is the ceiling for generated valid data: a documented 1171: # maximum far above the default (a PBKDF2 round count) costs time in 1172: # proportion to its value, which no fuzzing run can afford. max stays 1173: # the bound _validate_value() checks, so a mutated value between the two 1174: # is still valid and one above max is not. 1175: my $max = $spec->{sample_max} // $spec->{max} // $INT32_MAX; 1176: 1177: # Bias toward boundary values to probe edge conditions 1178: if(rand() < $INT_BOUNDARY_RATIO) { 1179: my @interesting = ($min, $min + 1, 0, -1, 1, $max - 1, $max); 1180: return $interesting[ int(rand(@interesting)) ]; 1181: } 1182: 1183: return $min + int(rand($max - $min + 1)); 1184: } 1185: 1186: # -------------------------------------------------- 1187: # _rand_num 1188: #Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_1159_2: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes๐งช Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_1159_2: Replace return expression with undef
LOW: Mutation survived, but impact may be minor๐งช Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );1189: # Purpose: Generate a random floating point number 1190: # within the spec's min/max range. 1191: # 1192: # Entry: $spec - schema spec hashref. 1193: # Exit: Returns a numeric scalar. 1194: # Side effects: None. 1195: # --------------------------------------------------Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_1188_4: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes๐งช Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_1188_4: Replace return expression with undef
LOW: Mutation survived, but impact may be minor๐งช Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 2, Killed: 2, Survived: 0)
1196: sub _rand_num { 1197: my ($self, $spec) = @_; 1198: 1199: my $min = $spec->{min} // -1e9; 1200: # As in _rand_int: sample_max caps generated data, max stays the bound 1201: # _validate_value() checks. 1202: my $max = $spec->{sample_max} // $spec->{max} // 1e9; 1203:
Mutants (Total: 2, Killed: 2, Survived: 0)
1204: return $min + rand($max - $min); 1205: } 1206: 1207: # -------------------------------------------------- 1208: # _rand_string 1209: # 1210: # Purpose: Generate a random string within the 1211: # spec's min/max length range, biased 1212: # toward boundary lengths. 1213: # 1214: # Entry: $spec - schema spec hashref. 1215: # Exit: Returns a string scalar. 1216: # Side effects: None. 1217: # 1218: # Notes: Character set includes control chars 1219: # and NUL to probe boundary handling. 1220: # -------------------------------------------------- 1221: sub _rand_string { โ1222 โ 1229 โ 1237 1222: my ($self, $spec) = @_; 1223:
Mutants (Total: 2, Killed: 2, Survived: 0)
1224: my $min_len = $spec->{min} // 0; 1225: my $max_len = $spec->{max} // $DEFAULT_MAX_STR_LEN; 1226: 1227: # Bias toward boundary lengths at STR_BOUNDARY_RATIO frequency 1228: my $len;
Mutants (Total: 2, Killed: 2, Survived: 0)
1229: if(rand() < $STR_BOUNDARY_RATIO) { 1230: my @boundary_lens = ($min_len, $min_len + 1, $max_len - 1, $max_len); 1231: $len = $boundary_lens[ int(rand(@boundary_lens)) ]; 1232: } else { 1233: $len = $min_len + int(rand($max_len - $min_len + 1)); 1234: } 1235: 1236: # Clamp to non-negative 1237: $len = 0 if $len < 0; 1238: 1239: return join '', map { $RAND_CHARS[ int(rand(@RAND_CHARS)) ] } 1 .. $len; 1240: } 1241: 1242: # -------------------------------------------------- 1243: # _rand_array 1244: # 1245: # Purpose: Generate a random arrayref with 0 to 1246: # DEFAULT_MAX_ARRAY elements, each 1247: # generated from the items spec. 1248: # 1249: # Entry: $spec - schema spec hashref. 1250: # Exit: Returns an arrayref. 1251: # Side effects: None. 1252: # -------------------------------------------------- 1253: sub _rand_array { 1254: my ($self, $spec) = @_; 1255: 1256: my $items = $spec->{items} // {}; 1257: my $count = int(rand($DEFAULT_MAX_ARRAY + 1)); 1258: 1259: return [ map { $self->_generate_for_schema($items) } 1 .. $count ]; 1260: } 1261: 1262: # -------------------------------------------------- 1263: # _rand_hash 1264: # 1265: # Purpose: Generate a random hashref with values 1266: # generated from the properties spec. 1267: # 1268: # Entry: $spec - schema spec hashref. 1269: # Exit: Returns a hashref. 1270: # Side effects: None. 1271: # -------------------------------------------------- 1272: sub _rand_hash { โ1273 โ 1278 โ 1282 1273: my ($self, $spec) = @_; 1274: 1275: my $props = $spec->{properties} // {}; 1276: my %h; 1277: 1278: for my $key (keys %{$props}) { 1279: $h{$key} = $self->_generate_for_schema($props->{$key}); 1280: } 1281: 1282: return \%h; 1283: } 1284: 1285: # -------------------------------------------------- 1286: # _input_is_valid 1287: # 1288: # Purpose: Return true if the input satisfies all 1289: # constraints in the schema. Used to 1290: # distinguish real bugs (die on valid 1291: # input) from expected failures (die on 1292: # invalid input). 1293: # 1294: # Entry: $input - the value to validate. 1295: # Exit: Returns 1 if valid, 0 if not. 1296: # Returns 1 if no schema is available. 1297: # Side effects: None. 1298: # -------------------------------------------------- 1299: sub _input_is_valid { โ1300 โ 1315 โ 1319 1300: my ($self, $input) = @_; 1301: 1302: my $spec = $self->{schema}{input}; 1303: 1304: # No schema means we cannot judge validity 1305: return 1 unless defined $spec && ref($spec); 1306: 1307: # A scalar 'type' makes $spec the description of one value. Without 1308: # it $spec is a map of named parameters, where a parameter may 1309: # itself be called 'type' (its spec is then a hashref). 1310: my $is_value_spec = ref($spec) eq 'HASH' 1311: && defined($spec->{type}) && !ref($spec->{type}); 1312: 1313: my $input_style = $self->{schema}{input_style} // ''; 1314: 1315: if(!$is_value_spec && ($input_style eq 'hash' || ref($input) eq 'HASH')) { 1316: return $self->_validate_hash_input($input, $spec); 1317: } 1318: 1319: return $self->_validate_value($input, $spec); 1320: } 1321: 1322: # -------------------------------------------------- 1323: # _validate_hash_input 1324: # 1325: # Purpose: Validate a hash-style input against the 1326: # schema spec, checking each named field. 1327: # 1328: # Entry: $input - hashref of named parameters. 1329: # $spec - schema spec hashref. 1330: # Exit: Returns 1 if valid, 0 if not. 1331: # Side effects: None. 1332: # -------------------------------------------------- 1333: sub _validate_hash_input { โ1334 โ 1338 โ 1357 1334: my ($self, $input, $spec) = @_; 1335: 1336: return 0 unless defined $input; 1337: 1338: for my $key (keys %{$spec}) { 1339: # Skip internal metadata keys 1340: next if $key =~ /^_/; 1341: 1342: my $field_spec = $spec->{$key}; 1343: next unless ref($field_spec) eq 'HASH'; 1344: 1345: my $value = ref($input) eq 'HASH' ? $input->{$key} : undef; 1346: 1347: # Required field missing is always invalid 1348: if(!defined($value) && !$field_spec->{optional}) { 1349: return 0; 1350: } 1351: 1352: next unless defined $value; 1353: 1354: return 0 unless $self->_validate_value($value, $field_spec); 1355: } 1356: 1357: return 1; 1358: } 1359: 1360: # -------------------------------------------------- 1361: # _validate_value 1362: # 1363: # Purpose: Validate a single value against a schema 1364: # type spec, checking type and constraints. 1365: # 1366: # Entry: $value - the value to validate. 1367: # $spec - schema spec hashref. 1368: # Exit: Returns 1 if valid, 0 if not. 1369: # Side effects: None. 1370: # 1371: # Notes: Number validation accepts both integer 1372: # and floating point forms including 1373: # scientific notation. Type mismatch 1374: # always returns 0. 1375: # -------------------------------------------------- 1376: sub _validate_value { โ1377 โ 1384 โ 1431 1377: my ($self, $value, $spec) = @_; 1378: 1379: # Undef is never valid unless optional â caller already checked optional 1380: return 0 unless defined $value; 1381: 1382: my $type = $spec->{type} // $TYPE_STRING; 1383: 1384: if($type eq $TYPE_INTEGER) { 1385: return 0 unless $value =~ /^-?\d+$/; 1386: return 0 if defined($spec->{min}) && $value < $spec->{min}; 1387: return 0 if defined($spec->{max}) && $value > $spec->{max}; 1388: } 1389: elsif($type eq $TYPE_NUMBER) { 1390: # Accept integers, decimals, and scientific notation 1391: return 0 unless $value =~ /^-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/; 1392: return 0 if defined($spec->{min}) && $value < $spec->{min}; 1393: return 0 if defined($spec->{max}) && $value > $spec->{max}; 1394: } 1395: elsif($type eq $TYPE_STRING) { 1396: my $len = length($value); 1397: return 0 if defined($spec->{min}) && $len < $spec->{min}; 1398: return 0 if defined($spec->{max}) && $len > $spec->{max}; 1399: if(defined($spec->{matches})) { 1400: (my $pat = $spec->{matches}) =~ s{^/(.+)/$}{$1}; 1401: 1402: # ReDoS guard: a schema-supplied pattern matched against 1403: # fuzzer-generated (attacker-shaped) input could exhibit 1404: # catastrophic backtracking. Bound the match with alarm() 1405: # the same way target_sub calls are bounded elsewhere in 1406: # this module, and treat a timeout as a non-match. 1407: my $matched = eval { 1408: local $SIG{ALRM} = sub { die "matches regex timed out\n" }; 1409: alarm($MATCHES_REGEX_TIMEOUT_SECS); 1410: my $m = $value =~ /$pat/; 1411: alarm(0); 1412: $m; 1413: }; 1414: alarm(0); 1415: return 0 unless $matched; 1416: } 1417: } 1418: elsif($type eq $TYPE_BOOLEAN) { 1419: return 0 unless $value =~ /^[01]$/; 1420: } 1421: elsif($type eq $TYPE_ARRAY || $type eq 'array') { 1422: return 0 unless ref($value) eq 'ARRAY'; 1423: } 1424: elsif($type eq $TYPE_HASH || $type eq 'hash') { 1425: return 0 unless ref($value) eq 'HASH'; 1426: if(ref($spec->{properties}) eq 'HASH') { 1427: return 0 unless $self->_validate_hash_input($value, $spec->{properties}); 1428: } 1429: } 1430: 1431: return 1; 1432: } 1433: 1434: # -------------------------------------------------- 1435: # _mutate 1436: # 1437: # Purpose: Apply a random mutation to an input 1438: # value, dispatching on its type. 1439: # 1440: # Entry: $input - the value to mutate. 1441: # $spec - the schema spec for that value, 1442: # if known. 1443: # Exit: Returns a mutated copy of the input. 1444: # Side effects: None. 1445: # 1446: # Notes: Blessed references are passed through 1447: # unchanged. Undef is replaced with a 1448: # freshly generated random value. 1449: # A numeric mutation is kept out of the 1450: # band between sample_max and max (see 1451: # _outside_sampling_band). 1452: # -------------------------------------------------- 1453: sub _mutate { โ1454 โ 1458 โ 1480 1454: my ($self, $input, $spec) = @_; 1455: 1456: my $type = ref($input); 1457: 1458: if(!defined $input) { 1459: # Replace undef with a fresh random value 1460: return $self->_generate_random(); 1461: } 1462: elsif(!$type) { 1463: # Dispatch scalar mutation based on apparent type 1464: if($input =~ /^-?\d+$/) { 1465: return $self->_mutate_int($input, $spec); 1466: } elsif($input =~ /^-?[\d.]+$/) { 1467: return $self->_mutate_num($input, $spec); 1468: } else { 1469: return $self->_mutate_string($input); 1470: } 1471: } 1472: elsif($type eq 'ARRAY') { 1473: return $self->_mutate_array($input, $spec); 1474: } 1475: elsif($type eq 'HASH') { 1476: return $self->_mutate_hash($input, $spec); 1477: } 1478: 1479: # Blessed refs and other types pass through unchanged 1480: return $input; 1481: } 1482: 1483: # -------------------------------------------------- 1484: # _outside_sampling_band 1485: # 1486: # Purpose: Move a mutated numeric value out of the 1487: # band between sample_max and max. 1488: # 1489: # Entry: $value - the mutated value. 1490: # $spec - the schema spec it belongs to, 1491: # if known. 1492: # Exit: Returns $value unchanged unless it is 1493: # above sample_max and at or below max; 1494: # such a value is returned as max + 1. 1495: # Side effects: None. 1496: # 1497: # Notes: Values in that band are valid per the 1498: # documented maximum, so a call that 1499: # times out there is recorded as a bug 1500: # even though the routine is behaving as 1501: # documented - the value is merely slow 1502: # (a PBKDF2 round count, say). Above max 1503: # the routine refuses it cheaply, and at 1504: # or below sample_max it stays affordable, 1505: # so a mutation lands in one of those two 1506: # places and never creeps upward through 1507: # the slow band by doubling. 1508: # -------------------------------------------------- 1509: sub _outside_sampling_band { 1510: my ($self, $value, $spec) = @_; 1511: 1512: return $value unless ref($spec) eq 'HASH'; 1513: 1514: my $ceiling = $spec->{sample_max}; 1515: my $max = $spec->{max}; 1516: 1517: return $value unless defined($ceiling) && defined($max); 1518: return $value unless defined($value) && ($value > $ceiling) && ($value <= $max); 1519: 1520: return $max + 1; 1521: } 1522: 1523: # -------------------------------------------------- 1524: # _mutate_int 1525: # 1526: # Purpose: Apply a random arithmetic mutation to 1527: # an integer value. 1528: # 1529: # Entry: $n - the integer to mutate. 1530: # $spec - its schema spec, if known. 1531: # Exit: Returns a mutated integer, kept out of 1532: # the slow band between sample_max and max. 1533: # Side effects: None. 1534: # -------------------------------------------------- 1535: sub _mutate_int { 1536: my ($self, $n, $spec) = @_; 1537: my $op = int(rand(8)); 1538: my $value 1539: = $op == 0 ? $n + 1 1540: : $op == 1 ? $n - 1 1541: : $op == 2 ? $n * 2 1542: : $op == 3 ? ($n == 0 ? 1 : int($n / 2)) 1543: : $op == 4 ? -$n 1544: : $op == 5 ? 0 1545: : $op == 6 ? $INT32_MAX 1546: : $INT32_MIN; 1547: 1548: return $self->_outside_sampling_band($value, $spec); 1549: } 1550: 1551: # -------------------------------------------------- 1552: # _mutate_num 1553: # 1554: # Purpose: Apply a random arithmetic mutation to 1555: # a floating point value. 1556: # 1557: # Entry: $n - the number to mutate. 1558: # $spec - its schema spec, if known. 1559: # Exit: Returns a mutated number, kept out of 1560: # the slow band between sample_max and max. 1561: # Side effects: None. 1562: # -------------------------------------------------- 1563: sub _mutate_num { 1564: my ($self, $n, $spec) = @_; 1565: my $op = int(rand(5)); 1566: my $value 1567: = $op == 0 ? $n + rand(10) 1568: : $op == 1 ? $n - rand(10) 1569: : $op == 2 ? $n * (1 + rand()) 1570: : $op == 3 ? 0 1571: : -$n; 1572: 1573: return $self->_outside_sampling_band($value, $spec); 1574: } 1575: 1576: # -------------------------------------------------- 1577: # _mutate_string 1578: # 1579: # Purpose: Apply a random structural mutation to 1580: # a string value â bit flip, insert, 1581: # delete, truncate, repeat, or replace 1582: # with an interesting known value. 1583: # 1584: # Entry: $s - the string to mutate. 1585: # Exit: Returns a mutated string. 1586: # Side effects: None. 1587: # -------------------------------------------------- 1588: sub _mutate_string { 1589: my ($self, $s) = @_; 1590: 1591: my $len = length($s); 1592: 1593: my @ops = ( 1594: # Bit flip a random character 1595: sub { 1596: return $s unless $len; 1597: my $pos = int(rand($len)); 1598: my $char = substr($s, $pos, 1); 1599: substr($s, $pos, 1) = chr(ord($char) ^ (1 << int(rand(8)))); 1600: $s 1601: }, 1602: # Insert a random byte 1603: sub { 1604: my $pos = int(rand($len + 1)); 1605: my $char = chr(int(rand(256))); 1606: substr($s, $pos, 0, $char); 1607: $s 1608: }, 1609: # Delete a random character 1610: sub { 1611: return $s unless $len; 1612: substr($s, int(rand($len)), 1, ''); 1613: $s 1614: }, 1615: # Truncate at a random position 1616: sub { substr($s, 0, int(rand($len + 1))) }, 1617: # Double the string 1618: sub { $s x 2 }, 1619: # Replace with a known interesting string 1620: sub { $INTERESTING_STRINGS[ int(rand(@INTERESTING_STRINGS)) ] }, 1621: ); 1622: 1623: return $ops[ int(rand(@ops)) ]->(); 1624: } 1625: 1626: # -------------------------------------------------- 1627: # _mutate_array 1628: # 1629: # Purpose: Apply a random structural mutation to 1630: # an arrayref â mutate element, duplicate, 1631: # delete, or empty. 1632: # 1633: # Entry: $arr - the arrayref to mutate. 1634: # Exit: Returns a mutated arrayref copy. 1635: # Side effects: None. 1636: # -------------------------------------------------- 1637: sub _mutate_array { 1638: my ($self, $arr, $spec) = @_; 1639: 1640: my $items = (ref($spec) eq 'HASH') ? $spec->{items} : undef; 1641: my @copy = @{$arr}; 1642: 1643: my @ops = ( 1644: # Mutate a random element 1645: sub { 1646: return [] unless @copy; 1647: my $i = int(rand(@copy)); 1648: $copy[$i] = $self->_mutate($copy[$i], $items); 1649: \@copy 1650: }, 1651: # Duplicate a random element 1652: sub { 1653: return \@copy unless @copy; 1654: my $i = int(rand(@copy)); 1655: splice @copy, $i, 0, $copy[$i]; 1656: \@copy 1657: }, 1658: # Delete a random element 1659: sub { 1660: return \@copy unless @copy; 1661: splice @copy, int(rand(@copy)), 1; 1662: \@copy 1663: }, 1664: # Return empty array 1665: sub { [] }, 1666: ); 1667: 1668: return $ops[ int(rand(@ops)) ]->(); 1669: } 1670: 1671: # -------------------------------------------------- 1672: # _mutate_hash 1673: # 1674: # Purpose: Apply a random mutation to one value 1675: # in a hashref copy. 1676: # 1677: # Entry: $h - the hashref to mutate. 1678: # Exit: Returns a mutated hashref copy. 1679: # Side effects: None. 1680: # -------------------------------------------------- 1681: sub _mutate_hash { 1682: my ($self, $h, $spec) = @_; 1683: 1684: my $properties = (ref($spec) eq 'HASH' && ref($spec->{properties}) eq 'HASH') 1685: ? $spec->{properties} : {}; 1686: my %copy = %{$h}; 1687: my @keys = keys %copy; 1688: 1689: # Return unchanged if hash is empty 1690: return \%copy unless @keys; 1691: 1692: my $k = $keys[ int(rand(@keys)) ]; 1693: $copy{$k} = $self->_mutate($copy{$k}, $properties->{$k}); 1694: 1695: return \%copy; 1696: } 1697: 1698: # -------------------------------------------------- 1699: # _seed_corpus 1700: # 1701: # Purpose: Pre-populate the corpus with a small 1702: # set of randomly generated inputs to 1703: # give the fuzzing loop a starting point. 1704: # 1705: # Entry: None beyond $self. 1706: # Exit: Returns nothing. Appends to $self->{corpus}. 1707: # Side effects: Modifies $self->{corpus}. 1708: # -------------------------------------------------- 1709: sub _seed_corpus { โ1710 โ 1712 โ 0 1710: my $self = $_[0]; 1711: 1712: for (1 .. $SEED_CORPUS_SIZE) { 1713: push @{ $self->{corpus} }, { 1714: input => $self->_generate_random(), 1715: coverage => {}, 1716: }; 1717: } 1718: } 1719: 1720: # -------------------------------------------------- 1721: # _build_report 1722: # 1723: # Purpose: Construct the summary report hashref 1724: # returned by run(). 1725: # 1726: # Entry: None beyond $self. 1727: # Exit: Returns a report hashref. 1728: # Side effects: None. 1729: # -------------------------------------------------- 1730: sub _build_report { 1731: my $self = $_[0]; 1732: 1733: return { 1734: total_iterations => $self->{stats}{total}, 1735: interesting_inputs => $self->{stats}{interesting}, 1736: corpus_size => scalar @{ $self->{corpus} }, 1737: branches_covered => $self->{stats}{coverage}, 1738: bugs_found => $self->{stats}{bugs}, 1739: bugs => $self->{bugs}, 1740: }; 1741: } 1742: 1743: =head1 COMMON PITFALLS 1744: 1745: =over 4 1746: 1747: =item Forgetting that C<load_corpus> does not restore bugs 1748: 1749: The JSON written by C<save_corpus> contains a C<bugs> array, but C<load_corpus> 1750: reads only the C<corpus> key. A freshly loaded fuzzer always starts with an 1751: empty bugs list. If you need to carry bugs across sessions, persist them 1752: separately. 1753: 1754: =item Assuming coverage guidance is always active 1755: 1756: If C<Devel::Cover> is not installed, the fuzzer falls back to random-only mode 1757: and emits a warning. Corpus entries in this mode have C<coverage =E<gt> {}> 1758: and are kept using the C<RANDOM_KEEP_RATIO> (20%) heuristic rather than branch 1759: novelty. Install C<Devel::Cover> (or C<cpanm --with-recommends 1760: App::Test::Generator>) for full coverage-guided behaviour. 1761: 1762: =item Using C<refaddr> on C<corpus()> after C<minimize_corpus> 1763: 1764: C<minimize_corpus> replaces C<$self-E<gt>{corpus}> with a B<new> arrayref. 1765: Any caller that holds a reference to the old arrayref (e.g. from a prior 1766: C<corpus()> call) will see a stale snapshot. Always call C<corpus()> after 1767: C<minimize_corpus> if you need the current list. 1768: 1769: =item Setting C<timeout =E<gt> 0> on blocking targets 1770: 1771: Setting C<timeout> to 0 disables the per-call C<alarm()>. This is correct for 1772: targets that legitimately block (e.g. sleeping, waiting on I/O), but means a 1773: hung target_sub will hang the whole fuzzing run indefinitely. Use a 1774: process-level timeout (e.g. C<Sys::AlarmCall>) if you need a safety net for 1775: blocking code. 1776: 1777: =item A C<timeout> below one second turns the timeout off 1778: 1779: C<timeout> is passed to Perl's C<alarm>, which works in whole seconds. 1780: A value such as C<0.5> becomes C<0>, and C<0> means "no timeout". 1781: 1782: =item A schema without an C<input> key 1783: 1784: The generator reads only C<< $schema->{input} >>. If that key is missing, 1785: every generated input is C<undef>, and C<target_sub> is called with 1786: C<undef> each time. No error is raised. 1787: 1788: schema => { name => { type => 'string' } } # wrong 1789: schema => { input => { type => 'string' } } # right 1790: 1791: =item C<target_sub> always gets exactly one generated argument 1792: 1793: C<input> describes B<one> value. If C<input> is a list of named 1794: parameters without a C<type> key of its own, one random string is 1795: generated, not a hash. To pass a hashref, describe it: 1796: 1797: input => { 1798: type => 'hashref', 1799: properties => { age => { type => 'integer', min => 0 } }, 1800: } 1801: 1802: The C<position> and C<named> keys of an extracted schema describe a 1803: multi-argument call that this fuzzer does not build. A parameter map without 1804: a C<type> of its own still yields the single string described above, so a 1805: routine written as C<my ($first, %opts) = @_> receives it as C<$first> and the 1806: trailing named options are left at their defaults. 1807: 1808: =item How C<undef> and other false values are handled 1809: 1810: =over 4 1811: 1812: =item * C<schema> and C<target_sub> must be B<true> values, not only 1813: defined. An empty hashref C<{}> is true and is accepted. 1814: 1815: =item * C<target_sub> is not checked to be a code reference. A wrong 1816: value is accepted by C<new>, and then every call in C<run> fails. 1817: 1818: =item * C<iterations>, C<seed> and C<timeout> use their default only when 1819: they are missing or C<undef>. The value C<0> is kept: C<< iterations => 0 >> 1820: runs no calls, C<< seed => 0 >> is a valid fixed seed, C<< timeout => 0 >> 1821: means no time limit. 1822: 1823: =item * An C<undef> input can be generated (see above) and can be saved. 1824: It is written to the JSON file as C<null> and comes back as C<undef>. 1825: 1826: =item * An C<undef> value for a required field makes an input invalid. 1827: An C<undef> value for a field marked C<optional> is valid. 1828: 1829: =item * C<save_corpus(undef)> and C<load_corpus(undef)> croak with 1830: C<path required>. 1831: 1832: =back 1833: 1834: =item Nested data is copied only one level deep 1835: 1836: When a hashref or arrayref input is mutated, only the top level is copied. 1837: Deeper hashes and arrays are shared between the old and the new corpus 1838: entry. If your C<target_sub> changes its argument in place, it can 1839: silently change other corpus entries too. Write C<target_sub> so that it 1840: only reads its argument, or make it take a deep copy first. 1841: 1842: =item C<load_corpus> adds entries. It does not merge or replace. 1843: 1844: Loaded entries are put after the entries already in the corpus. Nothing 1845: is compared and nothing is overwritten. Load a file twice and you have 1846: two copies of each entry. 1847: 1848: =item Every C<run> adds five more random seed inputs 1849: 1850: The corpus grows by at least five entries per C<run> call. Call 1851: C<minimize_corpus> before C<save_corpus> if the object is used for many 1852: runs. 1853: 1854: =item Some warnings are recorded as bugs 1855: 1856: A warning from C<target_sub> that contains the word C<uninitialized>, 1857: C<undefined>, C<blessed> or C<invalid> is recorded as a bug, even though 1858: the call did not die. Warnings are caught during the call, so they are 1859: not printed. Other warnings are thrown away. 1860: 1861: =item C<branches_covered> is 0 1862: 1863: This means that no branch data was received. Branch data is only 1864: available when the whole program is started under C<Devel::Cover>, for 1865: example with C<perl -MDevel::Cover script.pl>. Having the module 1866: installed is not enough. Without it the run is random-only. Do not read 1867: a value of 0 as "the target has no branches". 1868: 1869: =item Branch counts include more than your target 1870: 1871: C<Devel::Cover> counts every branch in the program. A few of the 1872: branches counted in C<branches_covered> belong to the fuzzer and to other 1873: modules, not to C<target_sub>. Use the number to compare two runs, not 1874: as an exact size. 1875: 1876: =back 1877: 1878: =head1 ENCODING 1879: 1880: =over 4 1881: 1882: =item * Inputs given to C<target_sub> 1883: 1884: All strings are Perl character strings. Strings made by the fuzzer use 1885: ASCII letters, digits, space, tab, newline and the NUL character. 1886: Mutation can also produce any character from 0 to 255. The fuzzer never 1887: invents characters above 255 (for example emojis) by itself. 1888: 1889: =item * C<edge_case_array> and C<matches> in the schema 1890: 1891: Full Unicode is supported, including non-ASCII letters and emojis. Give 1892: them as decoded character strings (C<use utf8> in your source, or a YAML 1893: file loaded with L<YAML::XS>). Such values are passed to C<target_sub> 1894: unchanged and are mutated one character at a time. 1895: 1896: =item * String C<min> and C<max> 1897: 1898: Lengths are counted in characters, not bytes. 1899: 1900: =item * C<save_corpus> and C<load_corpus> 1901: 1902: Full Unicode is supported. The file is written as UTF-8 JSON, and every 1903: string, including non-ASCII letters and emojis, is loaded back exactly as 1904: it was saved. A corpus file written by version 0.47 or earlier, which 1905: could hold Latin-1 bytes, is still read correctly. 1906: 1907: =item * The C<path> argument 1908: 1909: Passed to the operating system unchanged. ASCII paths always work. 1910: 1911: =item * Error text in C<bugs> 1912: 1913: The C<error> value is whatever C<target_sub> died with, turned into a 1914: string. It is not encoded or decoded. 1915: 1916: =back 1917: 1918: =head1 LIMITATIONS 1919: 1920: =over 4 1921: 1922: =item Single-threaded 1923: 1924: All fuzzing iterations run sequentially in the calling process. For large 1925: iteration counts, wall-clock time scales linearly. Parallelism requires 1926: splitting the iteration budget across multiple fuzzer instances and merging 1927: their corpora. 1928: 1929: =item Coverage granularity is branch-level 1930: 1931: Branch coverage is the finest granularity Devel::Cover exposes via its public 1932: API. Path coverage (distinct sequences of branches) is not tracked. Two 1933: inputs that cover the same branches but exercise different call orders are 1934: treated as equivalent. 1935: 1936: =item No inter-run learning without save/load 1937: 1938: The corpus is entirely in memory. To carry learning across separate 1939: invocations, call C<save_corpus> at the end and C<load_corpus> at the start of 1940: each subsequent run. 1941: 1942: =back 1943: 1944: =head1 SEE ALSO 1945: 1946: =over 4 1947: 1948: =item L<Devel::Cover> 1949: 1950: =item L<App::Test::Generator> 1951: 1952: =item C<bin/extract-schemas> (the C<--minimize-corpus> flag) 1953: 1954: =back 1955: 1956: =head1 AUTHOR 1957: 1958: Nigel Horne, C<< <njh at nigelhorne.com> >> 1959: 1960: Portions of this module's initial design and documentation were created 1961: with the assistance of AI. 1962: 1963: =head1 FORMAL SPECIFICATION 1964: 1965: This section describes each method in Z notation. It is for readers who 1966: want an exact, mathematical statement. You do not need it to use the module. 1967: 1968: How to read it: a name ending in C<?> is an input, a name ending in C<!> is 1969: an output, and a name ending in C<'> is the value after the call. 1970: E<0x0394> before the state name means "this call may change the object". 1971: E<0x039E> means "this call does not change the object". 1972: C<#> is the number of items in a list or set. 1973: 1974: Entry == [ input : VALUE ; coverage : â BRANCH ] 1975: Bug == [ input : VALUE ; error : STRING ] 1976: 1977: ââ Fuzzer ââââââââââââââââââââââââââââââââââââââââââ 1978: â schema : VALUE 1979: â target_sub : VALUE 1980: â instance : VALUE 1981: â iterations, seed, timeout : NUMBER 1982: â corpus : seq Entry 1983: â bugs : seq Bug 1984: â covered : â BRANCH 1985: â total, interesting : â 1986: ââââââââââââââââââââââââââââââââââââââââââââââââââââ 1987: â schema and target_sub are true values 1988: â â { e : ran corpus ⢠e.coverage } â covered 1989: â interesting ⤠#corpus 1990: ââââââââââââââââââââââââââââââââââââââââââââââââââââ 1991: 1992: =head2 new 1993: 1994: ââ New âââââââââââââââââââââââââââââââââââââââââââââ 1995: â Fuzzerâ² 1996: â schema?, target_sub?, instance? : VALUE 1997: â iterations?, seed?, timeout? : NUMBER ⪠{ undef } 1998: â result! : Fuzzer 1999: ââââââââââââââââââââââââââââââââââââââââââââââââââââ 2000: â pre schema? is true â§ target_sub? is true 2001: â post schemaâ² = schema? â§ target_subâ² = target_sub? 2002: â instanceâ² = instance? 2003: â iterationsâ² = if iterations? = undef then 100 else iterations? 2004: â seedâ² = if seed? = undef then time() else seed? 2005: â timeoutâ² = if timeout? = undef then 5 else timeout? 2006: â corpusâ² = â¨â© â§ bugsâ² = â¨â© â§ coveredâ² = â 2007: â totalâ² = 0 â§ interestingâ² = 0 2008: â srand(seedâ²) has been called 2009: â result! = θ Fuzzerâ² 2010: ââââââââââââââââââââââââââââââââââââââââââââââââââââ 2011: 2012: schema? is false â croak 'schema required' 2013: target_sub? is false â croak 'target_sub required' 2014: 2015: =head2 run 2016: 2017: ââ Run âââââââââââââââââââââââââââââââââââââââââââââ 2018: â Î Fuzzer 2019: â result! : REPORT 2020: ââââââââââââââââââââââââââââââââââââââââââââââââââââ 2021: â post totalâ² = total + iterations 2022: â corpus prefix corpusâ² 2023: â #corpusⲠ⥠#corpus + 5 2024: â #corpusâ² â #corpus â 5 = interestingâ² â interesting 2025: â bugs prefix bugsâ² 2026: â covered â coveredâ² 2027: â â b : ran bugsâ² â ran bugs ⢠2028: â b.input is valid for schema.input 2029: â result!.total_iterations = totalâ² 2030: â result!.interesting_inputs = interestingâ² 2031: â result!.corpus_size = #corpusâ² 2032: â result!.branches_covered = #coveredâ² 2033: â result!.bugs_found = #bugsâ² 2034: â result!.bugs = bugsâ² 2035: â schemaâ² = schema â§ seedâ² = seed 2036: ââââââââââââââââââââââââââââââââââââââââââââââââââââ 2037: 2038: =head2 corpus 2039: 2040: ââ Corpus ââââââââââââââââââââââââââââââââââââââââââ 2041: â Î Fuzzer 2042: â result! : seq Entry 2043: ââââââââââââââââââââââââââââââââââââââââââââââââââââ 2044: â post result! = corpus (the same list, not a copy) 2045: ââââââââââââââââââââââââââââââââââââââââââââââââââââ 2046: 2047: =head2 bugs 2048: 2049: ââ Bugs ââââââââââââââââââââââââââââââââââââââââââââ 2050: â Î Fuzzer 2051: â result! : seq Bug 2052: ââââââââââââââââââââââââââââââââââââââââââââââââââââ 2053: â post result! = bugs (the same list, not a copy) 2054: ââââââââââââââââââââââââââââââââââââââââââââââââââââ 2055: 2056: =head2 save_corpus 2057: 2058: ââ SaveCorpus ââââââââââââââââââââââââââââââââââââââ 2059: â Î Fuzzer 2060: â path? : PATH 2061: ââââââââââââââââââââââââââââââââââââââââââââââââââââ 2062: â pre path? â undef â§ path? can be written 2063: â every input in corpus and bugs is plain data 2064: â post contentâ²(path?) = JSON of 2065: â [ seed ⦠seed, 2066: â corpus ⦠⨠e : corpus ⢠[ input ⦠e.input ] â©, 2067: â bugs ⦠bugs ] 2068: ââââââââââââââââââââââââââââââââââââââââââââââââââââ 2069: 2070: path? = undef â croak 'path required' 2071: path? cannot be written â croak 'Cannot write corpus to ...' 2072: 2073: =head2 load_corpus 2074: 2075: ââ LoadCorpus ââââââââââââââââââââââââââââââââââââââ 2076: â Î Fuzzer 2077: â path? : PATH 2078: â loaded : seq VALUE 2079: ââââââââââââââââââââââââââââââââââââââââââââââââââââ 2080: â pre path? â undef â§ path? holds valid JSON 2081: â post loaded = the inputs under the 'corpus' key of the file 2082: â corpusâ² = corpus â ⨠v : loaded ⢠[ input ⦠v, coverage ⦠â ] â© 2083: â bugsâ² = bugs â§ seedâ² = seed â§ coveredâ² = covered 2084: â totalâ² = total â§ interestingâ² = interesting 2085: ââââââââââââââââââââââââââââââââââââââââââââââââââââ 2086: 2087: path? = undef â croak 'path required' 2088: path? cannot be read â croak 'Cannot read corpus from ...' 2089: 2090: =head2 minimize_corpus 2091: 2092: fp(v) == the canonical JSON text of v (the "fingerprint") 2093: 2094: ââ MinimizeCorpus ââââââââââââââââââââââââââââââââââ 2095: â Î Fuzzer 2096: â result! : [ before, after, branches : â ] 2097: â with, without : seq Entry 2098: ââââââââââââââââââââââââââââââââââââââââââââââââââââ 2099: â post with = corpus filtered to entries with coverage â â 2100: â without = corpus filtered to entries with coverage = â 2101: â result!.before = #corpus 2102: â result!.after = #corpusâ² 2103: â result!.branches = # â { e : ran with ⢠e.coverage } 2104: â â { e : ran corpusⲠ⢠e.coverage } 2105: â = â { e : ran corpus ⢠e.coverage } 2106: â â e : ran without ⢠â k : ran corpusⲠ⢠2107: â fp(k.input) = fp(e.input) 2108: â â b : ran bugs ⢠â k : ran corpusⲠ⢠2109: â fp(k.input) = fp(b.input) 2110: â corpusâ² is a new list (old references are stale) 2111: â bugsâ² = bugs â§ coveredâ² = covered 2112: â totalâ² = total â§ interestingâ² = interesting 2113: ââââââââââââââââââââââââââââââââââââââââââââââââââââ 2114: 2115: Calling it a second time changes nothing: 2116: result!.before = result!.after on the second call. 2117: 2118: =head1 STATE DIAGRAM 2119: 2120: The state of a fuzzer is the state of its corpus. 2121: 2122: new(schema or target_sub missing or false) 2123: +--------------------------------------------------+ 2124: | action: croak, no object | 2125: v | 2126: +-------------+ | 2127: | NO OBJECT |--------------------------------------+ 2128: +-------------+ 2129: | 2130: | new(schema, target_sub, ...) 2131: | action: store settings, call srand(seed), 2132: | try to load Devel::Cover 2133: v 2134: +---------------------+ minimize_corpus() 2135: | |-----------------------------------------+ 2136: | EMPTY | action: returns 0 / 0 / 0 | 2137: | (corpus is empty) |<----------------------------------------+ 2138: | | 2139: | | save_corpus(path) 2140: | |-----------------------------------------+ 2141: | | action: write a file with no entries | 2142: | |<----------------------------------------+ 2143: +---------------------+ 2144: | 2145: | run() 2146: | action: add 5 random inputs, call target_sub 2147: | 'iterations' times, keep interesting inputs, 2148: | record bugs, return the report 2149: | load_corpus(path) 2150: | action: add the inputs from the file (no branch data) 2151: v 2152: +---------------------+ run() 2153: | |-----------------------------------------+ 2154: | GROWING | action: as above; corpus gets bigger, | 2155: | (corpus may hold | totals are added to the old totals | 2156: | copies and spare |<----------------------------------------+ 2157: | entries) | 2158: | | load_corpus(path) 2159: | |-----------------------------------------+ 2160: | | action: add the file's inputs again | 2161: | |<----------------------------------------+ 2162: | | 2163: | | save_corpus(path) 2164: | |-----------------------------------------+ 2165: | | action: write the file, no change | 2166: | |<----------------------------------------+ 2167: +---------------------+ 2168: | ^ 2169: | | run() or load_corpus(path) 2170: | | action: as above 2171: | minimize_corpus() 2172: | action: replace the corpus with a new, smaller list; 2173: | keep every covered branch and every bug input; 2174: | return before / after / branches 2175: v | 2176: +---------------------+ minimize_corpus() 2177: | |-----------------------------------------+ 2178: | MINIMIZED | action: nothing changes (before=after) | 2179: | (no spare entries) |<----------------------------------------+ 2180: | | 2181: | | save_corpus(path) 2182: | |-----------------------------------------+ 2183: | | action: write the smallest file | 2184: | |<----------------------------------------+ 2185: +---------------------+ 2186: 2187: In every state: corpus() and bugs() return the current lists and 2188: change nothing. A call that croaks (bad path, unwritable file, 2189: unreadable file) changes nothing. 2190: 2191: The usual order of calls in one program run is: 2192: 2193: new -> load_corpus -> run -> minimize_corpus -> save_corpus 2194: 2195: =head1 LICENCE AND COPYRIGHT 2196: 2197: Copyright 2026 Nigel Horne. 2198: 2199: Usage is subject to GPL2 licence terms. 2200: If you use it, 2201: please let me know. 2202: 2203: =cut 2204: 2205: 1;