| File: | blib/lib/App/Test/Generator/CoverageGuidedFuzzer.pm |
| Coverage: | 92.7% |
| line | stmt | bran | cond | sub | time | code |
|---|---|---|---|---|---|---|
| 1 | package App::Test::Generator::CoverageGuidedFuzzer; | |||||
| 2 | ||||||
| 3 | 15 15 15 | 172176 12 144 | use strict; | |||
| 4 | 15 15 15 | 17 9 271 | use warnings; | |||
| 5 | 15 15 15 | 18 6 248 | use Carp qw(croak); | |||
| 6 | 15 15 15 | 22 9 718 | use feature 'state'; | |||
| 7 | 15 15 15 | 348 2364 28507 | 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 - 270 | =head1 NAME
App::Test::Generator::CoverageGuidedFuzzer - AFL-style coverage-guided fuzzing for App::Test::Generator
=head1 VERSION
Version 0.52
=head1 SYNOPSIS
"Fuzzing" means calling a function many times with machine-made input,
to find input that makes it fail. The "corpus" is the list of inputs
that the fuzzer decided to keep.
Pattern 1: fuzz a function that takes one number, then show the failures.
The C<input> key of the schema describes the one argument.
use App::Test::Generator::CoverageGuidedFuzzer;
my $fuzzer = App::Test::Generator::CoverageGuidedFuzzer->new(
schema => { input => { type => 'integer', min => 0, max => 100 } },
target_sub => \&My::Module::validate,
iterations => 200,
seed => 42,
);
my $report = $fuzzer->run();
printf "%d failures in %d calls\n",
$report->{bugs_found}, $report->{total_iterations};
print " failed with: $_->{error}" for @{ $report->{bugs} };
Pattern 2: keep what was learned between two runs of your program.
my $file = 't/corpus/validate.json';
$fuzzer->load_corpus($file) if -e $file; # start from the last run
$fuzzer->run();
# Optional: trim corpus to minimum branch-covering subset before saving
my $stats = $fuzzer->minimize_corpus();
printf "corpus %d -> %d entries\n", $stats->{before}, $stats->{after};
$fuzzer->save_corpus($file);
Pattern 3: fuzz a method of an object. The object is passed first and
the generated input second.
my $fuzzer = App::Test::Generator::CoverageGuidedFuzzer->new(
schema => { input => { type => 'string', max => 20 } },
target_sub => \&My::Parser::parse,
instance => My::Parser->new(),
);
$fuzzer->run();
Pattern 4: test with your own special values, here with non-ASCII text.
About 4 in 10 new inputs are taken from C<edge_case_array>.
use utf8;
my $fuzzer = App::Test::Generator::CoverageGuidedFuzzer->new(
schema => {
input => {
type => 'string',
edge_case_array => [ '', 'na\x{EF}ve', "\x{1F600}" ],
},
},
target_sub => sub { length $_[0] },
timeout => 2,
);
$fuzzer->run();
=head1 DESCRIPTION
Implements coverage-guided fuzzing on top of App::Test::Generator's
existing schema-driven input generation. Instead of purely random
generation it:
=over 4
=item 1. Generates or mutates a structured input
=item 2. Runs the target sub under Devel::Cover to capture branch hits
=item 3. Keeps inputs that discover new branches in a corpus
=item 4. Preferentially mutates corpus entries in future iterations
=back
This is the Perl equivalent of what AFL/libFuzzer do at the byte level,
but operating on typed, schema-validated Perl data structures.
=head1 METHODS
=head2 new
Construct a new coverage-guided fuzzer.
my $fuzzer = App::Test::Generator::CoverageGuidedFuzzer->new(
schema => $yaml_schema,
target_sub => \&My::Module::validate,
iterations => 200,
seed => 42,
instance => $obj, # optional pre-built object for method calls
);
=head3 Arguments
=over 4
=item * C<schema>
A hashref representing the parsed YAML schema for the target function.
Required. Only two keys are used: C<input>, which describes the single
argument that will be generated, and C<input_style>. Inside C<input> the
keys C<type>, C<min>, C<max>, C<sample_max>, C<matches>, C<items>,
C<properties>, C<optional> and C<edge_case_array> are used. For a string,
C<min> and C<max> are lengths counted in characters.
C<sample_max> caps the integers and numbers that are generated, while C<max>
stays the bound a value is validated against: a documented maximum far above
the documented default (a PBKDF2 round count) costs time in proportion to its
value, so valid data stops at C<sample_max> while a mutated value between the
two is still accepted as valid. Mutations are kept out of the band between
the two: a mutated value that would land there becomes C<max + 1>, which the
routine refuses cheaply, so a slow value is never mistaken for a bug.
=item * C<target_sub>
A CODE reference to the function under test. Required.
=item * C<iterations>
Number of fuzzing iterations to run. Optional - defaults to 100.
=item * C<seed>
Random seed for reproducible runs. Optional - defaults to C<time()>.
=item * C<instance>
An optional pre-built object to use as the invocant when calling the
target sub as a method.
=item * C<timeout>
Seconds to allow each C<target_sub> call before it is aborted via
C<alarm()> and recorded as a bug. Optional - defaults to 5. Set to 0
to disable the timeout (e.g. for target subs that legitimately block).
=back
=head3 Returns
A blessed hashref. Croaks if C<schema> or C<target_sub> is missing.
=head3 Side effects
Calls Perl's C<srand> with the seed. This restarts the random number
sequence for the whole program, not only for this object.
Prints one warning per program if L<Devel::Cover> cannot be loaded.
=head3 API SPECIFICATION
=head4 input
{
schema => { type => HASHREF },
target_sub => { type => CODEREF },
iterations => { type => SCALAR, optional => 1 },
seed => { type => SCALAR, optional => 1 },
instance => { type => OBJECT, optional => 1 },
timeout => { type => SCALAR, optional => 1 },
}
=head4 output
{
type => OBJECT,
isa => 'App::Test::Generator::CoverageGuidedFuzzer',
}
=head3 EXAMPLE
my $fuzzer = App::Test::Generator::CoverageGuidedFuzzer->new(
schema => { input => { type => 'string' } },
target_sub => sub { length($_[0]) },
iterations => 50,
seed => 1234,
);
=head3 MESSAGES
=over 4
=item C<schema required>
C<schema> was not supplied or was falsy (e.g. C<undef> or C<0>).
=item C<target_sub required>
C<target_sub> was not supplied or was falsy.
=back
The mathematical description is in L</FORMAL SPECIFICATION>.
=cut | |||||
| 271 | ||||||
| 272 | sub new { | |||||
| 273 | 224 | 683530 | my ($class, %args) = @_; | |||
| 274 | ||||||
| 275 | 224 | 391 | croak 'schema required' unless $args{schema}; | |||
| 276 | 219 | 216 | 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 | 214 | 655 | 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 | 214 | 1122 | srand($self->{seed}); | |||
| 298 | ||||||
| 299 | # Probe for Devel::Cover availability once at construction time | |||||
| 300 | 214 214 214 | 131 371 222 | $self->{_cover_available} = eval { require Devel::Cover; 1 } ? 1 : 0; | |||
| 301 | ||||||
| 302 | # Warn once per process if coverage guidance is unavailable | |||||
| 303 | 214 | 132 | state $cover_warned = 0; | |||
| 304 | 214 | 207 | if(!$self->{_cover_available} && !$cover_warned++) { | |||
| 305 | 0 | 0 | warn 'Devel::Cover not available; fuzzing without coverage guidance.'; | |||
| 306 | } | |||||
| 307 | ||||||
| 308 | 214 | 250 | return $self; | |||
| 309 | } | |||||
| 310 | ||||||
| 311 - 397 | =head2 run
Run the coverage-guided fuzzing loop and return a summary report.
my $report = $fuzzer->run();
printf "Branches covered: %d\n", $report->{branches_covered};
printf "Bugs found: %d\n", $report->{bugs_found};
=head3 Arguments
None beyond C<$self>.
=head3 Returns
A hashref with keys C<total_iterations>, C<interesting_inputs>,
C<corpus_size>, C<branches_covered>, C<bugs_found>, and C<bugs>.
The numbers are totals for the life of the object. If you call C<run>
twice, C<total_iterations> is twice the C<iterations> value.
=head3 Side effects
Calls C<target_sub> once per iteration. Adds five new random inputs to
the corpus at the start of every call. Uses C<alarm> and the C<ALRM>
signal for the timeout, so any alarm that your own program had set is
cancelled.
=head3 Notes
A call that takes longer than C<timeout> seconds is stopped and recorded
as a bug with the error C<target_sub timed out after Ns>.
The same failing input can be recorded more than once. The C<bugs> list
is not checked for duplicates.
A C<target_sub> call that dies is only recorded in C<bugs> when the
input that triggered it is valid per C<schema>. A die triggered by an
input the schema itself marks invalid (e.g. out of the declared
C<min>/C<max> range) is expected behaviour, not a bug, and is silently
discarded.
=head3 API SPECIFICATION
=head4 input
{
self => { type => OBJECT, isa => 'App::Test::Generator::CoverageGuidedFuzzer' },
}
=head4 output
{
type => HASHREF,
keys => {
total_iterations => { type => SCALAR },
interesting_inputs => { type => SCALAR },
corpus_size => { type => SCALAR },
branches_covered => { type => SCALAR },
bugs_found => { type => SCALAR },
bugs => { type => ARRAYREF },
},
}
=head3 EXAMPLE
my $report = $fuzzer->run();
printf "Iterations: %d\n", $report->{total_iterations};
printf "Corpus size: %d\n", $report->{corpus_size};
printf "Bugs found: %d\n", $report->{bugs_found};
for my $bug (@{ $report->{bugs} }) {
printf " input=%s error=%s\n", $bug->{input}, $bug->{error};
}
The mathematical description is in L</FORMAL SPECIFICATION>.
=head3 PSEUDOCODE
seed corpus with SEED_CORPUS_SIZE random inputs
for i in 1..iterations:
if corpus non-empty and rand < CORPUS_MUTATE_RATIO:
input = mutate(random corpus entry)
else:
input = generate_random()
run target_sub(input), record coverage and bugs
return report hashref
=cut | |||||
| 398 | ||||||
| 399 | sub run { | |||||
| 400 | 71 | 394 | my ($self) = @_; | |||
| 401 | ||||||
| 402 | # Phase 1: seed the corpus with a small set of random inputs | |||||
| 403 | 71 | 111 | $self->_seed_corpus(); | |||
| 404 | ||||||
| 405 | # Phase 2: main fuzzing loop â alternate between mutation and exploration | |||||
| 406 | 71 | 441 | for my $i (1 .. $self->{iterations}) { | |||
| 407 | 677 | 359 | my $input; | |||
| 408 | ||||||
| 409 | 677 677 | 323 785 | if(@{ $self->{corpus} } && rand() < $CORPUS_MUTATE_RATIO) { | |||
| 410 | # Mutate a randomly chosen corpus entry | |||||
| 411 | 448 448 | 812 356 | my $parent = $self->{corpus}[ int(rand(@{ $self->{corpus} })) ]; | |||
| 412 | 448 | 444 | $input = $self->_mutate($parent->{input}, $self->{schema}{input}); | |||
| 413 | } else { | |||||
| 414 | # Fresh random generation for exploration | |||||
| 415 | 229 | 429 | $input = $self->_generate_random(); | |||
| 416 | } | |||||
| 417 | ||||||
| 418 | 677 | 1722 | $self->_run_one($input); | |||
| 419 | 677 | 1060 | $self->{stats}{total}++; | |||
| 420 | } | |||||
| 421 | ||||||
| 422 | 71 71 | 51 89 | $self->{stats}{coverage} = scalar keys %{ $self->{covered} }; | |||
| 423 | 71 | 102 | return $self->_build_report(); | |||
| 424 | } | |||||
| 425 | ||||||
| 426 - 452 | =head2 corpus
Return the accumulated corpus as an arrayref of hashrefs with keys
C<input> and C<coverage>.
my $corpus = $fuzzer->corpus();
The arrayref is the fuzzer's own list, not a copy. Do not change it.
The list is empty until C<run> or C<load_corpus> has been called.
=head3 API SPECIFICATION
=head4 input
{ self => { type => OBJECT, isa => 'App::Test::Generator::CoverageGuidedFuzzer' } }
=head4 output
{ type => ARRAYREF }
=head3 EXAMPLE
my $corpus = $fuzzer->corpus();
printf "%d entries in corpus\n", scalar @{$corpus};
# Each entry: { input => ..., coverage => { 'file:line:branch' => 1, ... } }
=cut | |||||
| 453 | ||||||
| 454 | 49 | 4430 | sub corpus { $_[0]->{corpus} } | |||
| 455 | ||||||
| 456 - 483 | =head2 bugs
Return bugs found as an arrayref of hashrefs with keys C<input> and
C<error>.
my $bugs = $fuzzer->bugs();
The arrayref is the fuzzer's own list, not a copy. Do not change it.
C<error> is always text. C<input> can be C<undef>.
=head3 API SPECIFICATION
=head4 input
{ self => { type => OBJECT, isa => 'App::Test::Generator::CoverageGuidedFuzzer' } }
=head4 output
{ type => ARRAYREF }
=head3 EXAMPLE
my $bugs = $fuzzer->bugs();
for my $b (@{$bugs}) {
printf "Bug: input=%s error=%s\n", $b->{input}, $b->{error};
}
=cut | |||||
| 484 | ||||||
| 485 | 15 | 639 | sub bugs { $_[0]->{bugs} } | |||
| 486 | ||||||
| 487 - 560 | =head2 save_corpus
Serialise the corpus to a JSON file for replay or extension on future
runs.
$fuzzer->save_corpus('t/corpus/validate.json');
=head3 Arguments
=over 4
=item * C<$path>
Path to write the JSON corpus file. Required.
=back
=head3 Returns
Nothing useful. Croaks if the file cannot be written or no JSON module is
available.
=head3 Side effects
Writes a JSON file to C<$path>. An existing file is replaced.
The file holds the seed, the corpus inputs and the bugs.
Branch data is not saved. The file is UTF-8.
=head3 API SPECIFICATION
=head4 input
{
self => { type => OBJECT, isa => 'App::Test::Generator::CoverageGuidedFuzzer' },
path => { type => SCALAR },
}
=head4 output
{ type => UNDEF }
=head3 EXAMPLE
$fuzzer->run();
$fuzzer->minimize_corpus();
$fuzzer->save_corpus('t/corpus/my_func.json');
=head3 MESSAGES
=over 4
=item C<path required>
No path argument was supplied.
=item C<Cannot write corpus to $path: $!>
The file could not be opened for writing (permissions, missing directory, etc.).
=item C<No JSON module available; install JSON or JSON::MaybeXS>
Neither C<JSON::MaybeXS> nor C<JSON> is installed.
=item C<encountered object ...> or C<encountered CODE ...>
Raised by the JSON module. A corpus input or bug input holds an object
or a code reference, which JSON cannot store. This check happens after
the file has been opened, so the file is left empty.
=back
The mathematical description is in L</FORMAL SPECIFICATION>.
=cut | |||||
| 561 | ||||||
| 562 | sub save_corpus { | |||||
| 563 | 26 | 2687 | my ($self, $path) = @_; | |||
| 564 | ||||||
| 565 | 26 | 51 | croak 'path required' unless defined $path; | |||
| 566 | ||||||
| 567 | 23 | 35 | my $json = _load_json_module(); | |||
| 568 | ||||||
| 569 | 23 | 968 | 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 | 184 19 | 335 155 | corpus => [ map { { input => $_->{input} } } @{ $self->{corpus} } ], | |||
| 575 | bugs => $self->{bugs}, | |||||
| 576 | 19 | 202 | }); | |||
| 577 | ||||||
| 578 | 19 | 604 | close $fh; | |||
| 579 | } | |||||
| 580 | ||||||
| 581 - 658 | =head2 load_corpus
Load a previously saved corpus JSON file, pre-seeding the fuzzer so
it continues from where it left off.
$fuzzer->load_corpus('t/corpus/validate.json');
=head3 Arguments
=over 4
=item * C<$path>
Path to the JSON corpus file to load. Required.
=back
=head3 Returns
Nothing useful. Croaks if the file cannot be read or no JSON module is
available.
=head3 Side effects
Appends loaded entries to C<< $self->{corpus} >>. Entries already in the
corpus are kept, so loading the same file twice gives every entry twice.
C<minimize_corpus> removes such copies.
=head3 API SPECIFICATION
=head4 input
{
self => { type => OBJECT, isa => 'App::Test::Generator::CoverageGuidedFuzzer' },
path => { type => SCALAR },
}
=head4 output
{ type => UNDEF }
=head3 EXAMPLE
my $fuzzer2 = App::Test::Generator::CoverageGuidedFuzzer->new(
schema => $schema,
target_sub => \&My::Module::validate,
);
$fuzzer2->load_corpus('t/corpus/my_func.json');
my $report = $fuzzer2->run();
=head3 MESSAGES
=over 4
=item C<path required>
No path argument was supplied.
=item C<Cannot read corpus from $path: $!>
The file could not be opened for reading (missing file, permissions, etc.).
=item C<malformed JSON string ...> and similar
Raised by the JSON module. The file is not valid JSON.
=back
=head3 Notes
C<load_corpus> does B<not> restore C<bugs> from the JSON file.
The C<bugs> array in the JSON is written by C<save_corpus> but ignored on load.
The loaded fuzzer starts with an empty C<bugs> list. Seed values are also not
restored; the constructor-supplied seed is retained.
The mathematical description is in L</FORMAL SPECIFICATION>.
=cut | |||||
| 659 | ||||||
| 660 | sub load_corpus { | |||||
| 661 | 22 | 648 | my ($self, $path) = @_; | |||
| 662 | ||||||
| 663 | 22 | 35 | croak 'path required' unless defined $path; | |||
| 664 | ||||||
| 665 | 19 | 19 | my $json = _load_json_module(); | |||
| 666 | ||||||
| 667 | 19 | 243 | open my $fh, '<:raw', $path | |||
| 668 | or croak "Cannot read corpus from $path: $!"; | |||||
| 669 | ||||||
| 670 | 14 14 14 | 9 32 153 | my $text = do { local $/; <$fh> }; | |||
| 671 | 14 | 65 | 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 | 14 14 | 10 225 | 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 | 13 13 | 13 25 | for my $entry (@{ $data->{corpus} // [] }) { | |||
| 681 | 117 | 221 | push @{ $self->{corpus} }, { | |||
| 682 | input => $entry->{input}, | |||||
| 683 | 117 | 54 | coverage => {}, | |||
| 684 | }; | |||||
| 685 | } | |||||
| 686 | } | |||||
| 687 | ||||||
| 688 - 740 | =head2 minimize_corpus
Reduce the corpus to the smallest subset that still covers every
branch hit by the full corpus, using a greedy set-cover algorithm.
Entries without branch data (loaded from a previous run, or kept by
random sampling when Devel::Cover is unavailable) are deduplicated by
input fingerprint and retained in full. They cannot be evaluated for
coverage contribution without re-running them. Bug-triggering inputs
are always kept regardless of coverage contribution.
my $stats = $fuzzer->minimize_corpus();
printf "Corpus: %d -> %d entries (%d branches covered)\n",
$stats->{before}, $stats->{after}, $stats->{branches};
=head3 Returns
A hashref with keys C<before> (corpus size before), C<after> (corpus
size after), and C<branches> (total unique branches still covered).
=head3 API SPECIFICATION
=head4 input
{ self => { type => OBJECT, isa => 'App::Test::Generator::CoverageGuidedFuzzer' } }
=head4 output
{
type => HASHREF,
constraint => sub { defined $_[0]{before} && defined $_[0]{after} && defined $_[0]{branches} },
}
=head3 EXAMPLE
$fuzzer->run();
my $stats = $fuzzer->minimize_corpus();
printf "Corpus: %d -> %d entries (%d branches)\n",
$stats->{before}, $stats->{after}, $stats->{branches};
$fuzzer->save_corpus('t/corpus/my_func.json');
The mathematical description is in L</FORMAL SPECIFICATION>.
=head3 PSEUDOCODE
partition corpus into with-coverage and without-coverage entries
greedy set-cover: repeatedly pick entry covering most uncovered branches
deduplicate without-coverage entries by JSON fingerprint
unconditionally add all bug inputs not already in minimized set
replace self.corpus with minimized list
return { before, after, branches }
=cut | |||||
| 741 | ||||||
| 742 | sub minimize_corpus { | |||||
| 743 | 24 | 7340 | my ($self) = @_; | |||
| 744 | ||||||
| 745 | 24 24 | 20 23 | my @all = @{ $self->{corpus} }; | |||
| 746 | 24 | 17 | my $before = scalar @all; | |||
| 747 | ||||||
| 748 | 24 117 117 | 19 49 88 | my @with_cov = grep { %{ $_->{coverage} } } @all; | |||
| 749 | 24 117 117 | 21 42 82 | 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 | 24 | 18 | my %uncovered; | |||
| 754 | 24 31 31 | 22 18 721 | $uncovered{$_} = 1 for map { keys %{ $_->{coverage} } } @with_cov; | |||
| 755 | 24 | 89 | my $total_branches = scalar keys %uncovered; | |||
| 756 | ||||||
| 757 | 24 | 16 | my @selected; | |||
| 758 | 24 | 38 | while (%uncovered && @with_cov) { | |||
| 759 | 27 | 21 | my ($best, $best_idx, $best_n) = (undef, -1, 0); | |||
| 760 | 27 | 29 | for my $i (0 .. $#with_cov) { | |||
| 761 | 52 5764 52 | 24 2775 152 | my $n = grep { $uncovered{$_} } keys %{ $with_cov[$i]{coverage} }; | |||
| 762 | 52 | 112 | if ($n > $best_n) { | |||
| 763 | 28 | 20 | $best_n = $n; | |||
| 764 | 28 | 10 | $best_idx = $i; | |||
| 765 | 28 | 22 | $best = $with_cov[$i]; | |||
| 766 | } | |||||
| 767 | } | |||||
| 768 | 27 | 24 | last unless $best_n; | |||
| 769 | ||||||
| 770 | 27 | 29 | push @selected, $best; | |||
| 771 | 27 | 17 | splice @with_cov, $best_idx, 1; | |||
| 772 | 27 27 | 18 507 | 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 | 24 | 16 | my %seen; | |||
| 778 | my @deduped; | |||||
| 779 | 24 | 21 | for my $entry (@without_cov) { | |||
| 780 | 86 | 69 | my $key = _fingerprint($entry->{input}); | |||
| 781 | 86 | 82 | next if $seen{$key}++; | |||
| 782 | 75 | 42 | push @deduped, $entry; | |||
| 783 | } | |||||
| 784 | ||||||
| 785 | 24 | 21 | 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 | 24 102 | 19 66 | my %kept = map { _fingerprint($_->{input}) => 1 } @minimized; | |||
| 790 | 24 24 | 19 24 | for my $bug (@{ $self->{bugs} }) { | |||
| 791 | 59 | 36 | my $key = _fingerprint($bug->{input}); | |||
| 792 | 59 | 52 | unless ($kept{$key}++) { | |||
| 793 | 29 | 24 | push @minimized, { input => $bug->{input}, coverage => {} }; | |||
| 794 | } | |||||
| 795 | } | |||||
| 796 | ||||||
| 797 | 24 | 25 | $self->{corpus} = \@minimized; | |||
| 798 | ||||||
| 799 | return { | |||||
| 800 | 24 | 63 | 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. | |||||
| 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 blessed | |||||
| 820 | # class names that vary across Perl versions. | |||||
| 821 | # -------------------------------------------------- | |||||
| 822 | sub _fingerprint { | |||||
| 823 | 247 | 126 | my ($val) = @_; | |||
| 824 | 247 | 158 | return 'null' unless defined $val; | |||
| 825 | 234 | 99 | state $encoder; | |||
| 826 | 234 | 154 | unless ($encoder) { | |||
| 827 | 5 | 4 | my $mod = _load_json_module(); | |||
| 828 | 5 5 | 4 49 | $encoder = eval { $mod->new->canonical(1) }; | |||
| 829 | } | |||||
| 830 | 234 234 | 98 428 | 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 | 49 | 1989 | state $cached; | |||
| 851 | 49 | 77 | return $cached if defined $cached; | |||
| 852 | 11 | 22 | 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 | 11 | 40 | (my $file = $mod) =~ s{::}{/}g; | |||
| 856 | 11 | 49 | $file .= '.pm'; | |||
| 857 | 11 11 11 | 10 29 18 | if (eval { require $file; 1 }) { | |||
| 858 | 11 | 16 | return $cached = $mod; | |||
| 859 | } | |||||
| 860 | } | |||||
| 861 | 0 | 0 | croak 'No JSON module available; install JSON or JSON::MaybeXS'; | |||
| 862 | } | |||||
| 863 | ||||||
| 864 | # -------------------------------------------------- | |||||
| 865 | # _run_one | |||||
| 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 | 678 | 706 | my ($self, $input) = @_; | |||
| 886 | ||||||
| 887 | 678 | 358 | my ($result, $error, $coverage); | |||
| 888 | ||||||
| 889 | 678 | 460 | if($self->{_cover_available}) { | |||
| 890 | 675 | 546 | $coverage = $self->_run_with_cover($input, \$result, \$error); | |||
| 891 | } else { | |||||
| 892 | 3 | 1 | $coverage = {}; | |||
| 893 | 3 | 3 | ($result, $error) = $self->_call_target($input); | |||
| 894 | } | |||||
| 895 | ||||||
| 896 | # Record bugs â only when the input was valid per the schema. | |||||
| 897 | # A die on invalid input is correct behaviour, not a bug. | |||||
| 898 | 678 | 651 | if($error && $self->_input_is_valid($input)) { | |||
| 899 | 184 184 | 96 212 | push @{ $self->{bugs} }, { input => $input, error => "$error" }; | |||
| 900 | 184 | 121 | $self->{stats}{bugs}++; | |||
| 901 | } | |||||
| 902 | ||||||
| 903 | # Keep the input in the corpus if it exercised new branches | |||||
| 904 | 678 | 534 | if($self->_is_interesting($coverage)) { | |||
| 905 | 287 287 | 324 350 | push @{ $self->{corpus} }, { input => $input, coverage => $coverage }; | |||
| 906 | 287 | 308 | $self->_update_covered($coverage); | |||
| 907 | 287 | 633 | $self->{stats}{interesting}++; | |||
| 908 | } | |||||
| 909 | } | |||||
| 910 | ||||||
| 911 | # -------------------------------------------------- | |||||
| 912 | # _call_target | |||||
| 913 | # | |||||
| 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 | |||||
| 926 | # the whole fuzzing run; alarm() bounds it | |||||
| 927 | # and surfaces the timeout as an error. | |||||
| 928 | # -------------------------------------------------- | |||||
| 929 | sub _call_target { | |||||
| 930 | 679 | 436 | my ($self, $input) = @_; | |||
| 931 | ||||||
| 932 | # Include instance as invocant for method calls | |||||
| 933 | my @call_args = defined($self->{instance}) | |||||
| 934 | 679 | 551 | ? ($self->{instance}, $input) | |||
| 935 | : ($input); | |||||
| 936 | ||||||
| 937 | 679 | 356 | my ($result, $error, @warnings); | |||
| 938 | 679 | 357 | eval { | |||
| 939 | 679 14 | 985 65 | local $SIG{__WARN__} = sub { push @warnings, @_ }; | |||
| 940 | 679 | 506 | local $SIG{__DIE__}; | |||
| 941 | 679 1 | 2328 1000140 | local $SIG{ALRM} = sub { die "target_sub timed out after $self->{timeout}s\n" }; | |||
| 942 | 679 | 1108 | alarm($self->{timeout}) if $self->{timeout}; | |||
| 943 | 679 | 596 | $result = $self->{target_sub}->(@call_args); | |||
| 944 | }; | |||||
| 945 | 679 | 3401 | alarm(0) if $self->{timeout}; | |||
| 946 | 679 | 468 | $error = $@ if $@; | |||
| 947 | ||||||
| 948 | 679 | 681 | if(!defined($error) && @warnings) { | |||
| 949 | 14 | 12 | my $w = join '', @warnings; | |||
| 950 | 14 | 17 | $error = "warning: $w" if $w =~ $SOFT_BUG_WARNING_RE; | |||
| 951 | } | |||||
| 952 | ||||||
| 953 | 679 | 687 | return ($result, $error); | |||
| 954 | } | |||||
| 955 | ||||||
| 956 | # -------------------------------------------------- | |||||
| 957 | # _run_with_cover | |||||
| 958 | # | |||||
| 959 | # Purpose: Run the target sub with Devel::Cover | |||||
| 960 | # active and return the set of newly hit | |||||
| 961 | # branches as a hashref. | |||||
| 962 | # | |||||
| 963 | # Entry: $input - value to pass to target_sub. | |||||
| 964 | # $result_ref - scalar ref to store result. | |||||
| 965 | # $error_ref - scalar ref to store error. | |||||
| 966 | # | |||||
| 967 | # Exit: Returns a hashref of newly hit branch | |||||
| 968 | # keys ("file:line:branch"). | |||||
| 969 | # | |||||
| 970 | # Side effects: Calls Devel::Cover::start/stop. | |||||
| 971 | # Sets $$result_ref and $$error_ref. | |||||
| 972 | # | |||||
| 973 | # Notes: Snapshot comparison is imprecise for | |||||
| 974 | # concurrent use but correct for single- | |||||
| 975 | # threaded fuzzing. Instance is passed | |||||
| 976 | # as invocant when set. Devel::Cover state | |||||
| 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 | 676 | 556 | my ($self, $input, $result_ref, $error_ref) = @_; | |||
| 984 | ||||||
| 985 | 676 | 824 | Devel::Cover::start() if Devel::Cover->can('start'); | |||
| 986 | ||||||
| 987 | 676 | 554 | my $before_ref = $self->{_last_cover_snapshot} || {}; | |||
| 988 | 676 676 | 340 15056 | my %before = %{$before_ref}; | |||
| 989 | ||||||
| 990 | 676 | 3707 | ($$result_ref, my $error) = $self->_call_target($input); | |||
| 991 | 676 | 487 | $$error_ref = $error if defined $error; | |||
| 992 | ||||||
| 993 | 676 | 477 | my $after = $self->_snapshot_cover(); | |||
| 994 | 676 | 461 | $self->{_last_cover_snapshot} = $after; | |||
| 995 | 676 | 883 | Devel::Cover::stop() if Devel::Cover->can('stop'); | |||
| 996 | ||||||
| 997 | # Return only branches newly hit in this call | |||||
| 998 | 676 | 336 | my %delta; | |||
| 999 | 676 676 | 338 7548 | for my $key (keys %{$after}) { | |||
| 1000 | 269943 | 148213 | $delta{$key} = 1 unless exists $before{$key}; | |||
| 1001 | } | |||||
| 1002 | ||||||
| 1003 | 676 | 14078 | return \%delta; | |||
| 1004 | } | |||||
| 1005 | ||||||
| 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 | 677 | 383 | my ($self) = @_; | |||
| 1024 | 677 | 348 | my %snap; | |||
| 1025 | ||||||
| 1026 | 677 | 346 | eval { | |||
| 1027 | # coverage() is the XS accessor for the live counters. It only | |||||
| 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 | 677 | 509 | return unless defined &Devel::Cover::coverage; | |||
| 1032 | 677 | 529 | my $cover = Devel::Cover::coverage(0) or return; | |||
| 1033 | ||||||
| 1034 | 677 | 587 | for my $criterion (@COVER_CRITERIA) { | |||
| 1035 | 1354 | 2310 | my $data = $cover->{$criterion} or next; | |||
| 1036 | 1354 1354 | 2536 5694 | for my $key (keys %{$data}) { | |||
| 1037 | 154927 | 79260 | my $counts = $data->{$key}; | |||
| 1038 | 154927 | 88677 | next unless ref($counts) eq 'ARRAY'; | |||
| 1039 | ||||||
| 1040 | # Keys are packed op addresses; hex keeps them printable | |||||
| 1041 | 154927 | 110436 | my $id = unpack('H*', $key); | |||
| 1042 | 154927 154927 | 68559 85428 | for my $i (0 .. $#{$counts}) { | |||
| 1043 | 799987 | 515820 | $snap{"$criterion:$id:$i"} = 1 if $counts->[$i]; | |||
| 1044 | } | |||||
| 1045 | } | |||||
| 1046 | } | |||||
| 1047 | }; | |||||
| 1048 | ||||||
| 1049 | 677 | 1725 | return \%snap; | |||
| 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 | 681 | 449 | my ($self, $coverage) = @_; | |||
| 1071 | ||||||
| 1072 | # Check for any newly covered branch | |||||
| 1073 | 681 681 | 336 1181 | for my $key (keys %{$coverage}) { | |||
| 1074 | 156 | 610 | return 1 unless $self->{covered}{$key}; | |||
| 1075 | } | |||||
| 1076 | ||||||
| 1077 | # No coverage data â keep a random sample to grow the corpus | |||||
| 1078 | 526 526 | 246 595 | return rand() < $RANDOM_KEEP_RATIO unless %{$coverage}; | |||
| 1079 | ||||||
| 1080 | 1 | 1 | 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 | 289 | 167 | my ($self, $coverage) = @_; | |||
| 1095 | 289 289 | 178 4251 | $self->{covered}{$_} = 1 for keys %{$coverage}; | |||
| 1096 | } | |||||
| 1097 | ||||||
| 1098 | # -------------------------------------------------- | |||||
| 1099 | # _generate_random | |||||
| 1100 | # | |||||
| 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 | 616 | 375 | my ($self) = @_; | |||
| 1110 | 616 | 501 | 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 | 1061 | 1386 | my ($self, $spec) = @_; | |||
| 1134 | ||||||
| 1135 | 1061 | 738 | return undef unless defined $spec; | |||
| 1136 | 1035 | 733 | return undef if $spec eq 'undef'; | |||
| 1137 | ||||||
| 1138 | 1034 | 944 | my $type = ref($spec) ? ($spec->{type} // $TYPE_STRING) : $TYPE_STRING; | |||
| 1139 | ||||||
| 1140 | # Bias toward declared edge cases at EDGE_CASE_RATIO frequency | |||||
| 1141 | 1034 | 1547 | if(ref($spec) && $spec->{edge_case_array} && rand() < $EDGE_CASE_RATIO) { | |||
| 1142 | 6 6 | 9 4 | my @ec = @{ $spec->{edge_case_array} }; | |||
| 1143 | 6 | 5 | return $ec[ int(rand(@ec)) ]; | |||
| 1144 | } | |||||
| 1145 | ||||||
| 1146 | # Dispatch to type-specific generator | |||||
| 1147 | 1028 452 | 747 704 | if ($type eq $TYPE_INTEGER) { return $self->_rand_int($spec) } | |||
| 1148 | 0 | 0 | elsif ($type eq $TYPE_NUMBER) { return $self->_rand_num($spec) } | |||
| 1149 | 19 | 77 | elsif ($type eq $TYPE_BOOLEAN) { return int(rand(2)) } | |||
| 1150 | 7 | 40 | elsif ($type eq $TYPE_ARRAY) { return $self->_rand_array($spec) } | |||
| 1151 | 28 | 167 | elsif ($type eq $TYPE_HASH) { return $self->_rand_hash($spec) } | |||
| 1152 | 522 | 2949 | 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 toward | |||||
| 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 | 1492 | 5086 | my ($self, $spec) = @_; | |||
| 1168 | ||||||
| 1169 | 1492 | 962 | 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 | 1492 | 1921 | my $max = $spec->{sample_max} // $spec->{max} // $INT32_MAX; | |||
| 1176 | ||||||
| 1177 | # Bias toward boundary values to probe edge conditions | |||||
| 1178 | 1492 | 1616 | if(rand() < $INT_BOUNDARY_RATIO) { | |||
| 1179 | 467 | 741 | my @interesting = ($min, $min + 1, 0, -1, 1, $max - 1, $max); | |||
| 1180 | 467 | 514 | return $interesting[ int(rand(@interesting)) ]; | |||
| 1181 | } | |||||
| 1182 | ||||||
| 1183 | 1025 | 1793 | return $min + int(rand($max - $min + 1)); | |||
| 1184 | } | |||||
| 1185 | ||||||
| 1186 | # -------------------------------------------------- | |||||
| 1187 | # _rand_num | |||||
| 1188 | # | |||||
| 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 | # -------------------------------------------------- | |||||
| 1196 | sub _rand_num { | |||||
| 1197 | 510 | 1205 | my ($self, $spec) = @_; | |||
| 1198 | ||||||
| 1199 | 510 | 294 | my $min = $spec->{min} // -1e9; | |||
| 1200 | # As in _rand_int: sample_max caps generated data, max stays the bound | |||||
| 1201 | # _validate_value() checks. | |||||
| 1202 | 510 | 271 | my $max = $spec->{sample_max} // $spec->{max} // 1e9; | |||
| 1203 | ||||||
| 1204 | 510 | 348 | 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 | 523 | 325 | my ($self, $spec) = @_; | |||
| 1223 | ||||||
| 1224 | 523 | 479 | my $min_len = $spec->{min} // 0; | |||
| 1225 | 523 | 444 | my $max_len = $spec->{max} // $DEFAULT_MAX_STR_LEN; | |||
| 1226 | ||||||
| 1227 | # Bias toward boundary lengths at STR_BOUNDARY_RATIO frequency | |||||
| 1228 | 523 | 1157 | my $len; | |||
| 1229 | 523 | 343 | if(rand() < $STR_BOUNDARY_RATIO) { | |||
| 1230 | 71 | 148 | my @boundary_lens = ($min_len, $min_len + 1, $max_len - 1, $max_len); | |||
| 1231 | 71 | 75 | $len = $boundary_lens[ int(rand(@boundary_lens)) ]; | |||
| 1232 | } else { | |||||
| 1233 | 452 | 719 | $len = $min_len + int(rand($max_len - $min_len + 1)); | |||
| 1234 | } | |||||
| 1235 | ||||||
| 1236 | # Clamp to non-negative | |||||
| 1237 | 523 | 350 | $len = 0 if $len < 0; | |||
| 1238 | ||||||
| 1239 | 523 20043 | 488 53401 | 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 | 207 | 51448 | my ($self, $spec) = @_; | |||
| 1255 | ||||||
| 1256 | 207 | 158 | my $items = $spec->{items} // {}; | |||
| 1257 | 207 | 150 | my $count = int(rand($DEFAULT_MAX_ARRAY + 1)); | |||
| 1258 | ||||||
| 1259 | 207 391 | 414 250 | 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 | 28 | 14 | my ($self, $spec) = @_; | |||
| 1274 | ||||||
| 1275 | 28 | 28 | my $props = $spec->{properties} // {}; | |||
| 1276 | 28 | 20 | my %h; | |||
| 1277 | ||||||
| 1278 | 28 28 | 18 21 | for my $key (keys %{$props}) { | |||
| 1279 | 19 | 22 | $h{$key} = $self->_generate_for_schema($props->{$key}); | |||
| 1280 | } | |||||
| 1281 | ||||||
| 1282 | 28 | 47 | 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 | 239 | 170 | my ($self, $input) = @_; | |||
| 1301 | ||||||
| 1302 | 239 | 146 | my $spec = $self->{schema}{input}; | |||
| 1303 | ||||||
| 1304 | # No schema means we cannot judge validity | |||||
| 1305 | 239 | 246 | 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 | 238 | 296 | && defined($spec->{type}) && !ref($spec->{type}); | |||
| 1312 | ||||||
| 1313 | 238 | 214 | my $input_style = $self->{schema}{input_style} // ''; | |||
| 1314 | ||||||
| 1315 | 238 | 229 | if(!$is_value_spec && ($input_style eq 'hash' || ref($input) eq 'HASH')) { | |||
| 1316 | 5 | 4 | return $self->_validate_hash_input($input, $spec); | |||
| 1317 | } | |||||
| 1318 | ||||||
| 1319 | 233 | 165 | 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 | 60 | 58 | my ($self, $input, $spec) = @_; | |||
| 1335 | ||||||
| 1336 | 60 | 40 | return 0 unless defined $input; | |||
| 1337 | ||||||
| 1338 | 58 58 | 32 35 | for my $key (keys %{$spec}) { | |||
| 1339 | # Skip internal metadata keys | |||||
| 1340 | 65 | 55 | next if $key =~ /^_/; | |||
| 1341 | ||||||
| 1342 | 63 | 37 | my $field_spec = $spec->{$key}; | |||
| 1343 | 63 | 38 | next unless ref($field_spec) eq 'HASH'; | |||
| 1344 | ||||||
| 1345 | 63 | 48 | my $value = ref($input) eq 'HASH' ? $input->{$key} : undef; | |||
| 1346 | ||||||
| 1347 | # Required field missing is always invalid | |||||
| 1348 | 63 | 48 | if(!defined($value) && !$field_spec->{optional}) { | |||
| 1349 | 5 | 7 | return 0; | |||
| 1350 | } | |||||
| 1351 | ||||||
| 1352 | 58 | 36 | next unless defined $value; | |||
| 1353 | ||||||
| 1354 | 55 | 44 | return 0 unless $self->_validate_value($value, $field_spec); | |||
| 1355 | } | |||||
| 1356 | ||||||
| 1357 | 31 | 33 | 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 | 330 | 232 | my ($self, $value, $spec) = @_; | |||
| 1378 | ||||||
| 1379 | # Undef is never valid unless optional â caller already checked optional | |||||
| 1380 | 330 | 210 | return 0 unless defined $value; | |||
| 1381 | ||||||
| 1382 | 328 | 264 | my $type = $spec->{type} // $TYPE_STRING; | |||
| 1383 | ||||||
| 1384 | 328 | 459 | if($type eq $TYPE_INTEGER) { | |||
| 1385 | 98 | 260 | return 0 unless $value =~ /^-?\d+$/; | |||
| 1386 | 94 | 151 | return 0 if defined($spec->{min}) && $value < $spec->{min}; | |||
| 1387 | 63 | 84 | return 0 if defined($spec->{max}) && $value > $spec->{max}; | |||
| 1388 | } | |||||
| 1389 | elsif($type eq $TYPE_NUMBER) { | |||||
| 1390 | # Accept integers, decimals, and scientific notation | |||||
| 1391 | 5 | 26 | return 0 unless $value =~ /^-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/; | |||
| 1392 | 4 | 7 | return 0 if defined($spec->{min}) && $value < $spec->{min}; | |||
| 1393 | 4 | 6 | return 0 if defined($spec->{max}) && $value > $spec->{max}; | |||
| 1394 | } | |||||
| 1395 | elsif($type eq $TYPE_STRING) { | |||||
| 1396 | 167 | 608 | my $len = length($value); | |||
| 1397 | 167 | 145 | return 0 if defined($spec->{min}) && $len < $spec->{min}; | |||
| 1398 | 165 | 137 | return 0 if defined($spec->{max}) && $len > $spec->{max}; | |||
| 1399 | 159 | 117 | if(defined($spec->{matches})) { | |||
| 1400 | 5 | 14 | (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 | 5 | 3 | my $matched = eval { | |||
| 1408 | 5 0 | 30 0 | local $SIG{ALRM} = sub { die "matches regex timed out\n" }; | |||
| 1409 | 5 | 6 | alarm($MATCHES_REGEX_TIMEOUT_SECS); | |||
| 1410 | 5 | 117 | my $m = $value =~ /$pat/; | |||
| 1411 | 5 | 6 | alarm(0); | |||
| 1412 | 5 | 19 | $m; | |||
| 1413 | }; | |||||
| 1414 | 5 | 7 | alarm(0); | |||
| 1415 | 5 | 9 | return 0 unless $matched; | |||
| 1416 | } | |||||
| 1417 | } | |||||
| 1418 | elsif($type eq $TYPE_BOOLEAN) { | |||||
| 1419 | 6 | 38 | return 0 unless $value =~ /^[01]$/; | |||
| 1420 | } | |||||
| 1421 | elsif($type eq $TYPE_ARRAY || $type eq 'array') { | |||||
| 1422 | 4 | 29 | return 0 unless ref($value) eq 'ARRAY'; | |||
| 1423 | } | |||||
| 1424 | elsif($type eq $TYPE_HASH || $type eq 'hash') { | |||||
| 1425 | 48 | 369 | return 0 unless ref($value) eq 'HASH'; | |||
| 1426 | 46 | 38 | if(ref($spec->{properties}) eq 'HASH') { | |||
| 1427 | 44 | 27 | return 0 unless $self->_validate_hash_input($value, $spec->{properties}); | |||
| 1428 | } | |||||
| 1429 | } | |||||
| 1430 | ||||||
| 1431 | 241 | 271 | 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 | 896 | 1491 | my ($self, $input, $spec) = @_; | |||
| 1455 | ||||||
| 1456 | 896 | 480 | my $type = ref($input); | |||
| 1457 | ||||||
| 1458 | 896 | 668 | if(!defined $input) { | |||
| 1459 | # Replace undef with a fresh random value | |||||
| 1460 | 12 | 14 | return $self->_generate_random(); | |||
| 1461 | } | |||||
| 1462 | elsif(!$type) { | |||||
| 1463 | # Dispatch scalar mutation based on apparent type | |||||
| 1464 | 836 | 993 | if($input =~ /^-?\d+$/) { | |||
| 1465 | 483 | 308 | return $self->_mutate_int($input, $spec); | |||
| 1466 | } elsif($input =~ /^-?[\d.]+$/) { | |||||
| 1467 | 2 | 4 | return $self->_mutate_num($input, $spec); | |||
| 1468 | } else { | |||||
| 1469 | 351 | 293 | return $self->_mutate_string($input); | |||
| 1470 | } | |||||
| 1471 | } | |||||
| 1472 | elsif($type eq 'ARRAY') { | |||||
| 1473 | 11 | 18 | return $self->_mutate_array($input, $spec); | |||
| 1474 | } | |||||
| 1475 | elsif($type eq 'HASH') { | |||||
| 1476 | 35 | 32 | return $self->_mutate_hash($input, $spec); | |||
| 1477 | } | |||||
| 1478 | ||||||
| 1479 | # Blessed refs and other types pass through unchanged | |||||
| 1480 | 2 | 3 | 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 | 1093 | 566 | my ($self, $value, $spec) = @_; | |||
| 1511 | ||||||
| 1512 | 1093 | 702 | return $value unless ref($spec) eq 'HASH'; | |||
| 1513 | ||||||
| 1514 | 1077 | 521 | my $ceiling = $spec->{sample_max}; | |||
| 1515 | 1077 | 517 | my $max = $spec->{max}; | |||
| 1516 | ||||||
| 1517 | 1077 | 897 | return $value unless defined($ceiling) && defined($max); | |||
| 1518 | 1000 | 1188 | return $value unless defined($value) && ($value > $ceiling) && ($value <= $max); | |||
| 1519 | ||||||
| 1520 | 104 | 72 | 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 | 888 | 1853 | my ($self, $n, $spec) = @_; | |||
| 1537 | 888 | 476 | my $op = int(rand(8)); | |||
| 1538 | 888 | 838 | 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 | 888 | 696 | 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 | 205 | 860 | my ($self, $n, $spec) = @_; | |||
| 1565 | 205 | 105 | my $op = int(rand(5)); | |||
| 1566 | 205 | 147 | 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 | 205 | 133 | 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 | 354 | 415 | my ($self, $s) = @_; | |||
| 1590 | ||||||
| 1591 | 354 | 208 | my $len = length($s); | |||
| 1592 | ||||||
| 1593 | my @ops = ( | |||||
| 1594 | # Bit flip a random character | |||||
| 1595 | sub { | |||||
| 1596 | 35 | 26 | return $s unless $len; | |||
| 1597 | 34 | 27 | my $pos = int(rand($len)); | |||
| 1598 | 34 | 31 | my $char = substr($s, $pos, 1); | |||
| 1599 | 34 | 48 | substr($s, $pos, 1) = chr(ord($char) ^ (1 << int(rand(8)))); | |||
| 1600 | 34 | 104 | $s | |||
| 1601 | }, | |||||
| 1602 | # Insert a random byte | |||||
| 1603 | sub { | |||||
| 1604 | 78 | 78 | my $pos = int(rand($len + 1)); | |||
| 1605 | 78 | 92 | my $char = chr(int(rand(256))); | |||
| 1606 | 78 | 82 | substr($s, $pos, 0, $char); | |||
| 1607 | 78 | 295 | $s | |||
| 1608 | }, | |||||
| 1609 | # Delete a random character | |||||
| 1610 | sub { | |||||
| 1611 | 44 | 48 | return $s unless $len; | |||
| 1612 | 40 | 42 | substr($s, int(rand($len)), 1, ''); | |||
| 1613 | 40 | 128 | $s | |||
| 1614 | }, | |||||
| 1615 | # Truncate at a random position | |||||
| 1616 | 76 | 286 | sub { substr($s, 0, int(rand($len + 1))) }, | |||
| 1617 | # Double the string | |||||
| 1618 | 73 | 272 | sub { $s x 2 }, | |||
| 1619 | # Replace with a known interesting string | |||||
| 1620 | 48 | 44 | sub { $INTERESTING_STRINGS[ int(rand(@INTERESTING_STRINGS)) ] }, | |||
| 1621 | 354 | 951 | ); | |||
| 1622 | ||||||
| 1623 | 354 | 296 | 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 | 13 | 13 | my ($self, $arr, $spec) = @_; | |||
| 1639 | ||||||
| 1640 | 13 | 21 | my $items = (ref($spec) eq 'HASH') ? $spec->{items} : undef; | |||
| 1641 | 13 13 | 13 12 | my @copy = @{$arr}; | |||
| 1642 | ||||||
| 1643 | my @ops = ( | |||||
| 1644 | # Mutate a random element | |||||
| 1645 | sub { | |||||
| 1646 | 2 | 1 | return [] unless @copy; | |||
| 1647 | 2 | 4 | my $i = int(rand(@copy)); | |||
| 1648 | 2 | 5 | $copy[$i] = $self->_mutate($copy[$i], $items); | |||
| 1649 | \@copy | |||||
| 1650 | 2 | 6 | }, | |||
| 1651 | # Duplicate a random element | |||||
| 1652 | sub { | |||||
| 1653 | 1 | 6 | return \@copy unless @copy; | |||
| 1654 | 0 | 0 | my $i = int(rand(@copy)); | |||
| 1655 | 0 | 0 | splice @copy, $i, 0, $copy[$i]; | |||
| 1656 | \@copy | |||||
| 1657 | 0 | 0 | }, | |||
| 1658 | # Delete a random element | |||||
| 1659 | sub { | |||||
| 1660 | 8 | 14 | return \@copy unless @copy; | |||
| 1661 | 7 | 7 | splice @copy, int(rand(@copy)), 1; | |||
| 1662 | \@copy | |||||
| 1663 | 7 | 24 | }, | |||
| 1664 | # Return empty array | |||||
| 1665 | 2 | 7 | sub { [] }, | |||
| 1666 | 13 | 51 | ); | |||
| 1667 | ||||||
| 1668 | 13 | 18 | 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 | 238 | 559 | my ($self, $h, $spec) = @_; | |||
| 1683 | ||||||
| 1684 | my $properties = (ref($spec) eq 'HASH' && ref($spec->{properties}) eq 'HASH') | |||||
| 1685 | 238 | 236 | ? $spec->{properties} : {}; | |||
| 1686 | 238 238 | 119 157 | my %copy = %{$h}; | |||
| 1687 | 238 | 173 | my @keys = keys %copy; | |||
| 1688 | ||||||
| 1689 | # Return unchanged if hash is empty | |||||
| 1690 | 238 | 138 | return \%copy unless @keys; | |||
| 1691 | ||||||
| 1692 | 231 | 134 | my $k = $keys[ int(rand(@keys)) ]; | |||
| 1693 | 231 | 158 | $copy{$k} = $self->_mutate($copy{$k}, $properties->{$k}); | |||
| 1694 | ||||||
| 1695 | 231 | 200 | 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 | 75 | 61 | my $self = $_[0]; | |||
| 1711 | ||||||
| 1712 | 75 | 98 | for (1 .. $SEED_CORPUS_SIZE) { | |||
| 1713 | 375 375 | 1752 309 | 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 | 73 | 65 | my $self = $_[0]; | |||
| 1732 | ||||||
| 1733 | return { | |||||
| 1734 | total_iterations => $self->{stats}{total}, | |||||
| 1735 | interesting_inputs => $self->{stats}{interesting}, | |||||
| 1736 | 73 | 253 | corpus_size => scalar @{ $self->{corpus} }, | |||
| 1737 | branches_covered => $self->{stats}{coverage}, | |||||
| 1738 | bugs_found => $self->{stats}{bugs}, | |||||
| 1739 | bugs => $self->{bugs}, | |||||
| 1740 | 73 | 87 | }; | |||
| 1741 | } | |||||
| 1742 | ||||||
| 1743 - 2203 | =head1 COMMON PITFALLS
=over 4
=item Forgetting that C<load_corpus> does not restore bugs
The JSON written by C<save_corpus> contains a C<bugs> array, but C<load_corpus>
reads only the C<corpus> key. A freshly loaded fuzzer always starts with an
empty bugs list. If you need to carry bugs across sessions, persist them
separately.
=item Assuming coverage guidance is always active
If C<Devel::Cover> is not installed, the fuzzer falls back to random-only mode
and emits a warning. Corpus entries in this mode have C<coverage =E<gt> {}>
and are kept using the C<RANDOM_KEEP_RATIO> (20%) heuristic rather than branch
novelty. Install C<Devel::Cover> (or C<cpanm --with-recommends
App::Test::Generator>) for full coverage-guided behaviour.
=item Using C<refaddr> on C<corpus()> after C<minimize_corpus>
C<minimize_corpus> replaces C<$self-E<gt>{corpus}> with a B<new> arrayref.
Any caller that holds a reference to the old arrayref (e.g. from a prior
C<corpus()> call) will see a stale snapshot. Always call C<corpus()> after
C<minimize_corpus> if you need the current list.
=item Setting C<timeout =E<gt> 0> on blocking targets
Setting C<timeout> to 0 disables the per-call C<alarm()>. This is correct for
targets that legitimately block (e.g. sleeping, waiting on I/O), but means a
hung target_sub will hang the whole fuzzing run indefinitely. Use a
process-level timeout (e.g. C<Sys::AlarmCall>) if you need a safety net for
blocking code.
=item A C<timeout> below one second turns the timeout off
C<timeout> is passed to Perl's C<alarm>, which works in whole seconds.
A value such as C<0.5> becomes C<0>, and C<0> means "no timeout".
=item A schema without an C<input> key
The generator reads only C<< $schema->{input} >>. If that key is missing,
every generated input is C<undef>, and C<target_sub> is called with
C<undef> each time. No error is raised.
schema => { name => { type => 'string' } } # wrong
schema => { input => { type => 'string' } } # right
=item C<target_sub> always gets exactly one generated argument
C<input> describes B<one> value. If C<input> is a list of named
parameters without a C<type> key of its own, one random string is
generated, not a hash. To pass a hashref, describe it:
input => {
type => 'hashref',
properties => { age => { type => 'integer', min => 0 } },
}
The C<position> and C<named> keys of an extracted schema describe a
multi-argument call that this fuzzer does not build. A parameter map without
a C<type> of its own still yields the single string described above, so a
routine written as C<my ($first, %opts) = @_> receives it as C<$first> and the
trailing named options are left at their defaults.
=item How C<undef> and other false values are handled
=over 4
=item * C<schema> and C<target_sub> must be B<true> values, not only
defined. An empty hashref C<{}> is true and is accepted.
=item * C<target_sub> is not checked to be a code reference. A wrong
value is accepted by C<new>, and then every call in C<run> fails.
=item * C<iterations>, C<seed> and C<timeout> use their default only when
they are missing or C<undef>. The value C<0> is kept: C<< iterations => 0 >>
runs no calls, C<< seed => 0 >> is a valid fixed seed, C<< timeout => 0 >>
means no time limit.
=item * An C<undef> input can be generated (see above) and can be saved.
It is written to the JSON file as C<null> and comes back as C<undef>.
=item * An C<undef> value for a required field makes an input invalid.
An C<undef> value for a field marked C<optional> is valid.
=item * C<save_corpus(undef)> and C<load_corpus(undef)> croak with
C<path required>.
=back
=item Nested data is copied only one level deep
When a hashref or arrayref input is mutated, only the top level is copied.
Deeper hashes and arrays are shared between the old and the new corpus
entry. If your C<target_sub> changes its argument in place, it can
silently change other corpus entries too. Write C<target_sub> so that it
only reads its argument, or make it take a deep copy first.
=item C<load_corpus> adds entries. It does not merge or replace.
Loaded entries are put after the entries already in the corpus. Nothing
is compared and nothing is overwritten. Load a file twice and you have
two copies of each entry.
=item Every C<run> adds five more random seed inputs
The corpus grows by at least five entries per C<run> call. Call
C<minimize_corpus> before C<save_corpus> if the object is used for many
runs.
=item Some warnings are recorded as bugs
A warning from C<target_sub> that contains the word C<uninitialized>,
C<undefined>, C<blessed> or C<invalid> is recorded as a bug, even though
the call did not die. Warnings are caught during the call, so they are
not printed. Other warnings are thrown away.
=item C<branches_covered> is 0
This means that no branch data was received. Branch data is only
available when the whole program is started under C<Devel::Cover>, for
example with C<perl -MDevel::Cover script.pl>. Having the module
installed is not enough. Without it the run is random-only. Do not read
a value of 0 as "the target has no branches".
=item Branch counts include more than your target
C<Devel::Cover> counts every branch in the program. A few of the
branches counted in C<branches_covered> belong to the fuzzer and to other
modules, not to C<target_sub>. Use the number to compare two runs, not
as an exact size.
=back
=head1 ENCODING
=over 4
=item * Inputs given to C<target_sub>
All strings are Perl character strings. Strings made by the fuzzer use
ASCII letters, digits, space, tab, newline and the NUL character.
Mutation can also produce any character from 0 to 255. The fuzzer never
invents characters above 255 (for example emojis) by itself.
=item * C<edge_case_array> and C<matches> in the schema
Full Unicode is supported, including non-ASCII letters and emojis. Give
them as decoded character strings (C<use utf8> in your source, or a YAML
file loaded with L<YAML::XS>). Such values are passed to C<target_sub>
unchanged and are mutated one character at a time.
=item * String C<min> and C<max>
Lengths are counted in characters, not bytes.
=item * C<save_corpus> and C<load_corpus>
Full Unicode is supported. The file is written as UTF-8 JSON, and every
string, including non-ASCII letters and emojis, is loaded back exactly as
it was saved. A corpus file written by version 0.47 or earlier, which
could hold Latin-1 bytes, is still read correctly.
=item * The C<path> argument
Passed to the operating system unchanged. ASCII paths always work.
=item * Error text in C<bugs>
The C<error> value is whatever C<target_sub> died with, turned into a
string. It is not encoded or decoded.
=back
=head1 LIMITATIONS
=over 4
=item Single-threaded
All fuzzing iterations run sequentially in the calling process. For large
iteration counts, wall-clock time scales linearly. Parallelism requires
splitting the iteration budget across multiple fuzzer instances and merging
their corpora.
=item Coverage granularity is branch-level
Branch coverage is the finest granularity Devel::Cover exposes via its public
API. Path coverage (distinct sequences of branches) is not tracked. Two
inputs that cover the same branches but exercise different call orders are
treated as equivalent.
=item No inter-run learning without save/load
The corpus is entirely in memory. To carry learning across separate
invocations, call C<save_corpus> at the end and C<load_corpus> at the start of
each subsequent run.
=back
=head1 SEE ALSO
=over 4
=item L<Devel::Cover>
=item L<App::Test::Generator>
=item C<bin/extract-schemas> (the C<--minimize-corpus> flag)
=back
=head1 AUTHOR
Nigel Horne, C<< <njh at nigelhorne.com> >>
Portions of this module's initial design and documentation were created
with the assistance of AI.
=head1 FORMAL SPECIFICATION
This section describes each method in Z notation. It is for readers who
want an exact, mathematical statement. You do not need it to use the module.
How to read it: a name ending in C<?> is an input, a name ending in C<!> is
an output, and a name ending in C<'> is the value after the call.
E<0x0394> before the state name means "this call may change the object".
E<0x039E> means "this call does not change the object".
C<#> is the number of items in a list or set.
Entry == [ input : VALUE ; coverage : â BRANCH ]
Bug == [ input : VALUE ; error : STRING ]
ââ Fuzzer ââââââââââââââââââââââââââââââââââââââââââ
â schema : VALUE
â target_sub : VALUE
â instance : VALUE
â iterations, seed, timeout : NUMBER
â corpus : seq Entry
â bugs : seq Bug
â covered : â BRANCH
â total, interesting : â
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
â schema and target_sub are true values
â â { e : ran corpus ⢠e.coverage } â covered
â interesting ⤠#corpus
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
=head2 new
ââ New âââââââââââââââââââââââââââââââââââââââââââââ
â Fuzzerâ²
â schema?, target_sub?, instance? : VALUE
â iterations?, seed?, timeout? : NUMBER ⪠{ undef }
â result! : Fuzzer
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
â pre schema? is true â§ target_sub? is true
â post schemaâ² = schema? â§ target_subâ² = target_sub?
â instanceâ² = instance?
â iterationsâ² = if iterations? = undef then 100 else iterations?
â seedâ² = if seed? = undef then time() else seed?
â timeoutâ² = if timeout? = undef then 5 else timeout?
â corpusâ² = â¨â© â§ bugsâ² = â¨â© â§ coveredâ² = â
â totalâ² = 0 â§ interestingâ² = 0
â srand(seedâ²) has been called
â result! = θ Fuzzerâ²
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
schema? is false â croak 'schema required'
target_sub? is false â croak 'target_sub required'
=head2 run
ââ Run âââââââââââââââââââââââââââââââââââââââââââââ
â Î Fuzzer
â result! : REPORT
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
â post totalâ² = total + iterations
â corpus prefix corpusâ²
â #corpusⲠ⥠#corpus + 5
â #corpusâ² â #corpus â 5 = interestingâ² â interesting
â bugs prefix bugsâ²
â covered â coveredâ²
â â b : ran bugsâ² â ran bugs â¢
â b.input is valid for schema.input
â result!.total_iterations = totalâ²
â result!.interesting_inputs = interestingâ²
â result!.corpus_size = #corpusâ²
â result!.branches_covered = #coveredâ²
â result!.bugs_found = #bugsâ²
â result!.bugs = bugsâ²
â schemaâ² = schema â§ seedâ² = seed
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
=head2 corpus
ââ Corpus ââââââââââââââââââââââââââââââââââââââââââ
â Î Fuzzer
â result! : seq Entry
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
â post result! = corpus (the same list, not a copy)
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
=head2 bugs
ââ Bugs ââââââââââââââââââââââââââââââââââââââââââââ
â Î Fuzzer
â result! : seq Bug
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
â post result! = bugs (the same list, not a copy)
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
=head2 save_corpus
ââ SaveCorpus ââââââââââââââââââââââââââââââââââââââ
â Î Fuzzer
â path? : PATH
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
â pre path? â undef â§ path? can be written
â every input in corpus and bugs is plain data
â post contentâ²(path?) = JSON of
â [ seed ⦠seed,
â corpus ⦠⨠e : corpus ⢠[ input ⦠e.input ] â©,
â bugs ⦠bugs ]
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
path? = undef â croak 'path required'
path? cannot be written â croak 'Cannot write corpus to ...'
=head2 load_corpus
ââ LoadCorpus ââââââââââââââââââââââââââââââââââââââ
â Î Fuzzer
â path? : PATH
â loaded : seq VALUE
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
â pre path? â undef â§ path? holds valid JSON
â post loaded = the inputs under the 'corpus' key of the file
â corpusâ² = corpus â ⨠v : loaded ⢠[ input ⦠v, coverage ⦠â
] â©
â bugsâ² = bugs â§ seedâ² = seed â§ coveredâ² = covered
â totalâ² = total â§ interestingâ² = interesting
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
path? = undef â croak 'path required'
path? cannot be read â croak 'Cannot read corpus from ...'
=head2 minimize_corpus
fp(v) == the canonical JSON text of v (the "fingerprint")
ââ MinimizeCorpus ââââââââââââââââââââââââââââââââââ
â Î Fuzzer
â result! : [ before, after, branches : â ]
â with, without : seq Entry
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
â post with = corpus filtered to entries with coverage â â
â without = corpus filtered to entries with coverage = â
â result!.before = #corpus
â result!.after = #corpusâ²
â result!.branches = # â { e : ran with ⢠e.coverage }
â â { e : ran corpusⲠ⢠e.coverage }
â = â { e : ran corpus ⢠e.coverage }
â â e : ran without ⢠â k : ran corpusâ² â¢
â fp(k.input) = fp(e.input)
â â b : ran bugs ⢠â k : ran corpusâ² â¢
â fp(k.input) = fp(b.input)
â corpusâ² is a new list (old references are stale)
â bugsâ² = bugs â§ coveredâ² = covered
â totalâ² = total â§ interestingâ² = interesting
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
Calling it a second time changes nothing:
result!.before = result!.after on the second call.
=head1 STATE DIAGRAM
The state of a fuzzer is the state of its corpus.
new(schema or target_sub missing or false)
+--------------------------------------------------+
| action: croak, no object |
v |
+-------------+ |
| NO OBJECT |--------------------------------------+
+-------------+
|
| new(schema, target_sub, ...)
| action: store settings, call srand(seed),
| try to load Devel::Cover
v
+---------------------+ minimize_corpus()
| |-----------------------------------------+
| EMPTY | action: returns 0 / 0 / 0 |
| (corpus is empty) |<----------------------------------------+
| |
| | save_corpus(path)
| |-----------------------------------------+
| | action: write a file with no entries |
| |<----------------------------------------+
+---------------------+
|
| run()
| action: add 5 random inputs, call target_sub
| 'iterations' times, keep interesting inputs,
| record bugs, return the report
| load_corpus(path)
| action: add the inputs from the file (no branch data)
v
+---------------------+ run()
| |-----------------------------------------+
| GROWING | action: as above; corpus gets bigger, |
| (corpus may hold | totals are added to the old totals |
| copies and spare |<----------------------------------------+
| entries) |
| | load_corpus(path)
| |-----------------------------------------+
| | action: add the file's inputs again |
| |<----------------------------------------+
| |
| | save_corpus(path)
| |-----------------------------------------+
| | action: write the file, no change |
| |<----------------------------------------+
+---------------------+
| ^
| | run() or load_corpus(path)
| | action: as above
| minimize_corpus()
| action: replace the corpus with a new, smaller list;
| keep every covered branch and every bug input;
| return before / after / branches
v |
+---------------------+ minimize_corpus()
| |-----------------------------------------+
| MINIMIZED | action: nothing changes (before=after) |
| (no spare entries) |<----------------------------------------+
| |
| | save_corpus(path)
| |-----------------------------------------+
| | action: write the smallest file |
| |<----------------------------------------+
+---------------------+
In every state: corpus() and bugs() return the current lists and
change nothing. A call that croaks (bad path, unwritable file,
unreadable file) changes nothing.
The usual order of calls in one program run is:
new -> load_corpus -> run -> minimize_corpus -> save_corpus
=head1 LICENCE AND COPYRIGHT
Copyright 2026 Nigel Horne.
Usage is subject to GPL2 licence terms.
If you use it,
please let me know.
=cut | |||||
| 2204 | ||||||
| 2205 | 1; | |||||