lib/App/Test/Generator/CoverageGuidedFuzzer.pm

filter: Statementstmt 98.3% 404 / 411 Branchbran 90.9% 200 / 220 Conditioncond 82.4% 103 / 125 MC/DCmcdc 66.2% 49 / 74 Subroutinesub 98.0% 51 / 52 Podpod 100% 7 / 7 totaltotal 91.5% 814 / 889 CC 173 SCAR 23.5
CC
173
Cov
94%
_validate_value
33.7
_generate_for_schema
13.1
minimize_corpus
12.0
CRAP 10.5
« blib/lib/Devel/App/Test/Generator/LCSAJ/Runtime.pm ↑ Summary lib/App/Test/Generator/Mutation/Feedback.pm »
1 package App::Test::Generator::CoverageGuidedFuzzer;
2  
3 19 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 19 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 19 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 19 ▶use feature 'state';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 19 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 # --------------------------------------------------
10 # Fuzzing loop parameters
11 # --------------------------------------------------
12 19 Readonly my $DEFAULT_ITERATIONS => 100;
13 19 Readonly my $DEFAULT_TIMEOUT_SECS => 5; # per-call alarm() timeout; 0 disables
14 19 Readonly my $CORPUS_MUTATE_RATIO => 0.70; # 70% mutate, 30% explore
15 19 Readonly my $RANDOM_KEEP_RATIO => 0.20; # keep 20% random when no coverage
16 19 Readonly my $EDGE_CASE_RATIO => 0.40; # 40% chance to use declared edge case
17 19 Readonly my $INT_BOUNDARY_RATIO => 0.30; # 30% chance to use boundary int
18 19 Readonly my $STR_BOUNDARY_RATIO => 0.30; # 30% chance to use boundary length
19 19 Readonly my $SEED_CORPUS_SIZE => 5; # initial random inputs to seed corpus
20 19 Readonly my $DEFAULT_MAX_STR_LEN => 64;
21 19 Readonly my $MATCHES_REGEX_TIMEOUT_SECS => 1; # ReDoS guard for schema 'matches' patterns
22 19 Readonly my $DEFAULT_MAX_ARRAY => 4; # max elements in random array (0..N)
23 19 Readonly my $INT32_MAX => 2**31 - 1;
24 19 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 19 Readonly my @RAND_CHARS => ('a'..'z', 'A'..'Z', '0'..'9', ' ', "\t", "\n", "\0");
32 19 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 19 Readonly my $TYPE_INTEGER => 'integer';
44 19 Readonly my $TYPE_NUMBER => 'number';
45 19 Readonly my $TYPE_BOOLEAN => 'boolean';
46 19 Readonly my $TYPE_ARRAY => 'arrayref';
47 19 Readonly my $TYPE_HASH => 'hashref';
48 19 Readonly my $TYPE_STRING => 'string';
49  
50 # --------------------------------------------------
51 # JSON module preference order
52 # --------------------------------------------------
53 19 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 19 Readonly my @COVER_CRITERIA => qw(branch condition);
58  
59 19 Readonly my $SOFT_BUG_WARNING_RE => qr/uninitialized|undefined|blessed|invalid/i;
60  
61 19 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.
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 224 ▶sub new {
Subroutine new: called CC=9 SCAR=22.3
Pod documented
273 224 my ($class, %args) = @_;
274  
275 224 ▶ croak 'schema required' unless $args{schema};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"schema"} 5 219 224
276 219 ▶ croak 'target_sub required' unless $args{target_sub};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"target_sub"} 5 214 219
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 ▶ timeout => $args{timeout} // $DEFAULT_TIMEOUT_SECS,
Condition100%8/8
$args{"iterations"} // $DEFAULT_ITERATIONS
l!l&&r!l&&!r
196135
$args{"seed"} // time
l!l
18331
$args{"timeout"} // $DEFAULT_TIMEOUT_SECS
l!l&&r!l&&!r
2018014
MC/DC100%2/2
$args{"iterations"} // $DEFAULT_ITERATIONS
$args{"iterations"} $DEFAULT_ITERATIONS
MC/DC100%1/1
$args{"seed"} // time
$args{"seed"}
MC/DC100%2/2
$args{"timeout"} // $DEFAULT_TIMEOUT_SECS
$args{"timeout"} $DEFAULT_TIMEOUT_SECS
Truth table100%3/3
A // B
A= $args{"iterations"}B= $DEFAULT_ITERATIONS
ABresult
1X1
011
000
Truth table100%2/2
A
A= $args{"seed"}
Aresult
11
00
Truth table100%3/3
A // B
A= $args{"timeout"}B= $DEFAULT_TIMEOUT_SECS
ABresult
1X1
011
000
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 srand($self->{seed});
298  
299 # Probe for Devel::Cover availability once at construction time
300 214 ▶ $self->{_cover_available} = eval { require Devel::Cover; 1 } ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require Devel::Cover; 1 } } ? : 214 0 214
301  
302 # Warn once per process if coverage guidance is unavailable
303 214 state $cover_warned = 0;
304 214 ▶ if(!$self->{_cover_available} && !$cover_warned++) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"_cover_available"} or $cover_warned++) 0 214 214
Condition33%1/3
$self->{"_cover_available"} or $cover_warned++
l!l&&r!l&&!r
21400
MC/DC0%0/2
$self->{"_cover_available"} or $cover_warned++
$self->{"_cover_available"} $cover_warned++
Truth table33%1/3
A or B
A= $self->{"_cover_available"}B= $cover_warned++
ABresult
1X1
011
000
305 0 warn 'Devel::Cover not available; fuzzing without coverage guidance.';
306 }
307  
308 214 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 77 ▶sub run {
Subroutine run: called CC=4 SCAR=13.9
Pod documented
400 77 my ($self) = @_;
401  
402 # Phase 1: seed the corpus with a small set of random inputs
403 77 $self->_seed_corpus();
404  
405 # Phase 2: main fuzzing loop — alternate between mutation and exploration
406 77 for my $i (1 .. $self->{iterations}) {
407 737 my $input;
408  
409 737 ▶ if(@{ $self->{corpus} } && rand() < $CORPUS_MUTATE_RATIO) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{'corpus'};} and rand() < $CORPUS_MUTATE_RATIO) { } 528 209 737
Condition66%2/3
@{$self->{"corpus"};} and rand() < $CORPUS_MUTATE_RATIO
!ll&&!rl&&r
0209528
MC/DC50%1/2
@{$self->{"corpus"};} and rand() < $CORPUS_MUTATE_RATIO
@{$self->{"corpus"};} rand() < $CORPUS_MUTATE_RATIO
Truth table66%2/3
A and B
A= @{$self->{"corpus"};}B= rand() < $CORPUS_MUTATE_RATIO
ABresult
0X0
100
111
410 # Mutate a randomly chosen corpus entry
411 528 my $parent = $self->{corpus}[ int(rand(@{ $self->{corpus} })) ];
412 528 $input = $self->_mutate($parent->{input}, $self->{schema}{input});
413 } else {
414 # Fresh random generation for exploration
415 209 $input = $self->_generate_random();
416 }
417  
418 737 $self->_run_one($input);
419 737 $self->{stats}{total}++;
420 }
421  
422 77 $self->{stats}{coverage} = scalar keys %{ $self->{covered} };
423 77 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 52 ▶sub corpus { $_[0]->{corpus} }
Subroutine corpus: called CC=1 SCAR=0.0
Pod documented
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>.
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 19 ▶sub bugs { $_[0]->{bugs} }
Subroutine bugs: called CC=1 SCAR=0.0
Pod documented
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 {
520 self => { type => OBJECT, isa => 'App::Test::Generator::CoverageGuidedFuzzer' },
521 path => { type => SCALAR },
522 }
523  
524 =head4 output
525  
526 { type => UNDEF }
527  
528 =head3 EXAMPLE
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 26 ▶sub save_corpus {
Subroutine save_corpus: called CC=3 SCAR=11.0
Pod documented
563 26 my ($self, $path) = @_;
564  
565 26 ▶ croak 'path required' unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 3 23 26
566  
567 23 my $json = _load_json_module();
568  
569 23 ▶ open my $fh, '>:raw', $path
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">:raw", $path or croak("Cannot write corpus to ${path}: $!") 19 4 23
570 or croak "Cannot write corpus to $path: $!";
571  
572 print $fh $json->new->utf8->pretty->encode({
573 seed => $self->{seed},
574 189 corpus => [ map { { input => $_->{input} } } @{ $self->{corpus} } ],
575 bugs => $self->{bugs},
576 19 });
577  
578 19 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 is
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 23 ▶sub load_corpus {
Subroutine load_corpus: called CC=6 SCAR=17.9
Pod documented
661 23 my ($self, $path) = @_;
662  
663 23 ▶ croak 'path required' unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 3 20 23
664  
665 20 my $json = _load_json_module();
666  
667 20 ▶ open my $fh, '<:raw', $path
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $path or croak("Cannot read corpus from ${path}: $!") 15 5 20
668 or croak "Cannot read corpus from $path: $!";
669  
670 15 my $text = do { local $/; <$fh> };
671 15 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 15 ▶ my $data = eval { $json->new->utf8->decode($text) }
Condition100%3/3
eval { do { $json->new->utf8->decode($text) } } // $json->new->decode($text)
l!l&&r!l&&!r
1311
MC/DC0%0/2
eval { do { $json->new->utf8->decode($text) } } // $json->new->decode($text)
eval { do { $json->new->utf8->decode($text) } } $json->new->decode($text)
Truth table66%2/3
A // B
A= eval { do { $json->new->utf8->decode($text) } }B= $json->new->decode($text)
ABresult
1X1
011
000
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 14 ▶ for my $entry (@{ $data->{corpus} // [] }) {
Condition50%1/2
$data->{"corpus"} // []
l!l
140
MC/DC0%0/1
$data->{"corpus"} // []
$data->{"corpus"}
Truth table50%1/2
A
A= $data->{"corpus"}
Aresult
11
00
681 125 push @{ $self->{corpus} }, {
682 input => $entry->{input},
683 125 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();
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();
725 printf "Corpus: %d -> %d entries (%d branches)\n",
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  
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
737 replace self.corpus with minimized list
738 return { before, after, branches }
739  
740 =cut
741  
742 24 ▶sub minimize_corpus {
Subroutine minimize_corpus: called CC=12 SCAR=24.9
Pod documented
743 24 my ($self) = @_;
744  
745 24 my @all = @{ $self->{corpus} };
746 24 my $before = scalar @all;
747  
748 24 my @with_cov = grep { %{ $_->{coverage} } } @all;
749 24 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 my %uncovered;
754 24 $uncovered{$_} = 1 for map { keys %{ $_->{coverage} } } @with_cov;
755 24 my $total_branches = scalar keys %uncovered;
756  
757 24 my @selected;
758 24 ▶ while (%uncovered && @with_cov) {
Branch: 1 branch
BranchTrueFalseTotal
if (%uncovered and @with_cov) 27 24 51
Condition66%2/3
%uncovered and @with_cov
!ll&&!rl&&r
24027
MC/DC50%1/2
%uncovered and @with_cov
%uncovered @with_cov
Truth table66%2/3
A and B
A= %uncoveredB= @with_cov
ABresult
0X0
100
111
759 27 my ($best, $best_idx, $best_n) = (undef, -1, 0);
760 27 for my $i (0 .. $#with_cov) {
761 52 my $n = grep { $uncovered{$_} } keys %{ $with_cov[$i]{coverage} };
762 52 ▶ if ($n > $best_n) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n > $best_n) 28 24 52
763 28 $best_n = $n;
764 28 $best_idx = $i;
765 28 $best = $with_cov[$i];
766 }
767 }
768 27 ▶ last unless $best_n;
Branch: 1 branch
BranchTrueFalseTotal
unless $best_n 0 27 27
769  
770 27 push @selected, $best;
771 27 splice @with_cov, $best_idx, 1;
772 27 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 my %seen;
778 my @deduped;
779 24 for my $entry (@without_cov) {
780 91 my $key = _fingerprint($entry->{input});
781 91 ▶ next if $seen{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$key}++ 15 76 91
782 76 push @deduped, $entry;
783 }
784  
785 24 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 my %kept = map { _fingerprint($_->{input}) => 1 } @minimized;
790 24 for my $bug (@{ $self->{bugs} }) {
791 59 my $key = _fingerprint($bug->{input});
792 59 ▶ unless ($kept{$key}++) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($kept{$key}++) 29 30 59
793 29 push @minimized, { input => $bug->{input}, coverage => {} };
794 }
795 }
796  
797 24 $self->{corpus} = \@minimized;
798  
799 return {
800 24 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 253 ▶sub _fingerprint {
Subroutine _fingerprint: called CC=4 SCAR=13.9
823 253 my ($val) = @_;
824 253 ▶ return 'null' unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 13 240 253
825 240 state $encoder;
826 240 ▶ unless ($encoder) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($encoder) 5 235 240
827 5 my $mod = _load_json_module();
828 5 $encoder = eval { $mod->new->canonical(1) };
829 }
830 240 ▶ return eval { $encoder->encode($val) } // "$val";
Condition50%1/2
eval { do { $encoder->encode($val) } } // "$val"
l!l
2400
MC/DC0%0/1
eval { do { $encoder->encode($val) } } // "$val"
eval { do { $encoder->encode($val) } }
Truth table50%1/2
A
A= eval { do { $encoder->encode($val) } }
Aresult
11
00
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 50 ▶sub _load_json_module {
Subroutine _load_json_module: called CC=4 SCAR=14.0
850 50 state $cached;
851 50 ▶ return $cached if defined $cached;
Branch: 1 branch
BranchTrueFalseTotal
if defined $cached 39 11 50
852 11 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 (my $file = $mod) =~ s{::}{/}g;
856 11 $file .= '.pm';
857 11 ▶ if (eval { require $file; 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { require $file; 1 } }) 11 0 11
858 11 return $cached = $mod;
859 }
860 }
861 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 738 ▶sub _run_one {
Subroutine _run_one: called CC=5 SCAR=16.1
885 738 my ($self, $input) = @_;
886  
887 738 my ($result, $error, $coverage);
888  
889 738 ▶ if($self->{_cover_available}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_cover_available'}) { } 735 3 738
890 735 $coverage = $self->_run_with_cover($input, \$result, \$error);
891 } else {
892 3 $coverage = {};
893 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 738 ▶ if($error && $self->_input_is_valid($input)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($error and $self->_input_is_valid($input)) 189 549 738
Condition100%3/3
$error and $self->_input_is_valid($input)
!ll&&!rl&&r
50544189
MC/DC100%2/2
$error and $self->_input_is_valid($input)
$error $self->_input_is_valid($input)
Truth table100%3/3
A and B
A= $errorB= $self->_input_is_valid($input)
ABresult
0X0
100
111
899 189 push @{ $self->{bugs} }, { input => $input, error => "$error" };
900 189 $self->{stats}{bugs}++;
901 }
902  
903 # Keep the input in the corpus if it exercised new branches
904 738 ▶ if($self->_is_interesting($coverage)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_is_interesting($coverage)) 321 417 738
905 321 push @{ $self->{corpus} }, { input => $input, coverage => $coverage };
906 321 $self->_update_covered($coverage);
907 321 $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 739 ▶sub _call_target {
Subroutine _call_target: called CC=8 SCAR=20.8
930 739 my ($self, $input) = @_;
931  
932 # Include instance as invocant for method calls
933 my @call_args = defined($self->{instance})
934 739 ▶ ? ($self->{instance}, $input)
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'instance'} ? : 3 736 739
935 : ($input);
936  
937 739 my ($result, $error, @warnings);
938 739 eval {
939 739 ▶ local $SIG{__WARN__} = sub { push @warnings, @_ };
Subroutine __ANON__: called CC=1 SCAR=0.0
940 739 local $SIG{__DIE__};
941 739 ▶ local $SIG{ALRM} = sub { die "target_sub timed out after $self->{timeout}s\n" };
Subroutine __ANON__: called CC=1 SCAR=0.0
942 739 ▶ alarm($self->{timeout}) if $self->{timeout};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"timeout"} 606 133 739
943 739 $result = $self->{target_sub}->(@call_args);
944 };
945 739 ▶ alarm(0) if $self->{timeout};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"timeout"} 606 133 739
946 739 ▶ $error = $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 227 512 739
947  
948 739 ▶ if(!defined($error) && @warnings) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $error and @warnings) 14 725 739
Condition100%3/3
not defined $error and @warnings
!ll&&!rl&&r
22749814
MC/DC100%2/2
not defined $error and @warnings
not defined $error @warnings
Truth table100%3/3
not(A) and B
A= not defined $errorB= @warnings
ABresult
0X0
100
111
949 14 my $w = join '', @warnings;
950 14 ▶ $error = "warning: $w" if $w =~ $SOFT_BUG_WARNING_RE;
Branch: 1 branch
BranchTrueFalseTotal
if $w =~ /$SOFT_BUG_WARNING_RE/ 6 8 14
951 }
952  
953 739 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 736 ▶sub _run_with_cover {
Subroutine _run_with_cover: called CC=7 SCAR=19.5
983 736 my ($self, $input, $result_ref, $error_ref) = @_;
984  
985 736 ▶ Devel::Cover::start() if Devel::Cover->can('start');
Branch: 1 branch
BranchTrueFalseTotal
if "Devel::Cover"->can("start") 0 736 736
986  
987 736 ▶ my $before_ref = $self->{_last_cover_snapshot} || {};
Condition100%2/2
$self->{'_last_cover_snapshot'} || {}
l!l
66868
MC/DC100%1/1
$self->{'_last_cover_snapshot'} || {}
$self->{'_last_cover_snapshot'}
Truth table100%2/2
A
A= $self->{'_last_cover_snapshot'}
Aresult
11
00
988 736 my %before = %{$before_ref};
989  
990 736 ($$result_ref, my $error) = $self->_call_target($input);
991 736 ▶ $$error_ref = $error if defined $error;
Branch: 1 branch
BranchTrueFalseTotal
if defined $error 230 506 736
992  
993 736 my $after = $self->_snapshot_cover();
994 736 $self->{_last_cover_snapshot} = $after;
995 736 ▶ Devel::Cover::stop() if Devel::Cover->can('stop');
Branch: 1 branch
BranchTrueFalseTotal
if "Devel::Cover"->can("stop") 0 736 736
996  
997 # Return only branches newly hit in this call
998 736 my %delta;
999 736 for my $key (keys %{$after}) {
1000 450510 ▶ $delta{$key} = 1 unless exists $before{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $before{$key} 46485 404025 450510
1001 }
1002  
1003 736 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 737 ▶sub _snapshot_cover {
Subroutine _snapshot_cover: called CC=9 SCAR=22.3
1023 737 my ($self) = @_;
1024 737 my %snap;
1025  
1026 737 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 737 ▶ return unless defined &Devel::Cover::coverage;
Branch: 1 branch
BranchTrueFalseTotal
unless defined &Devel::Cover::coverage 0 737 737
1032 737 ▶ my $cover = Devel::Cover::coverage(0) or return;
Branch: 1 branch
BranchTrueFalseTotal
my $cover = &Devel::Cover::coverage(0) or return 737 0 737
1033  
1034 737 for my $criterion (@COVER_CRITERIA) {
1035 1474 ▶ my $data = $cover->{$criterion} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $data = $cover->{$criterion} or next 1474 0 1474
1036 1474 for my $key (keys %{$data}) {
1037 263576 my $counts = $data->{$key};
1038 263576 ▶ next unless ref($counts) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $counts eq "ARRAY" 0 263576 263576
1039  
1040 # Keys are packed op addresses; hex keeps them printable
1041 263576 my $id = unpack('H*', $key);
1042 263576 for my $i (0 .. $#{$counts}) {
1043 1360648 ▶ $snap{"$criterion:$id:$i"} = 1 if $counts->[$i];
Branch: 1 branch
BranchTrueFalseTotal
if $counts->[$i] 450512 910136 1360648
1044 }
1045 }
1046 }
1047 };
1048  
1049 737 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 741 ▶sub _is_interesting {
Subroutine _is_interesting: called CC=4 SCAR=13.9
1070 741 my ($self, $coverage) = @_;
1071  
1072 # Check for any newly covered branch
1073 741 for my $key (keys %{$coverage}) {
1074 167 ▶ return 1 unless $self->{covered}{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"covered"}{$key} 166 1 167
1075 }
1076  
1077 # No coverage data — keep a random sample to grow the corpus
1078 575 ▶ return rand() < $RANDOM_KEEP_RATIO unless %{$coverage};
Branch: 1 branch
BranchTrueFalseTotal
unless %{$coverage;} 574 1 575
1079  
1080 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 323 ▶sub _update_covered {
Subroutine _update_covered: called CC=2 SCAR=6.9
1094 323 my ($self, $coverage) = @_;
1095 323 $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 626 ▶sub _generate_random {
Subroutine _generate_random: called CC=1 SCAR=0.0
1109 626 my ($self) = @_;
1110 626 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 1071 ▶sub _generate_for_schema {
Subroutine _generate_for_schema: called CC=13 SCAR=25.8
1133 1071 my ($self, $spec) = @_;
1134  
1135 1071 ▶ return undef unless defined $spec;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spec 26 1045 1071
1136 1045 ▶ return undef if $spec eq 'undef';
Branch: 1 branch
BranchTrueFalseTotal
if $spec eq "undef" 1 1044 1045
1137  
1138 1044 ▶ my $type = ref($spec) ? ($spec->{type} // $TYPE_STRING) : $TYPE_STRING;
Branch: 1 branch
BranchTrueFalseTotal
ref $spec ? : 1044 0 1044
Condition100%3/3
$spec->{"type"} // $TYPE_STRING
l!l&&r!l&&!r
8312085
MC/DC100%2/2
$spec->{"type"} // $TYPE_STRING
$spec->{"type"} $TYPE_STRING
Truth table100%3/3
A // B
A= $spec->{"type"}B= $TYPE_STRING
ABresult
1X1
011
000
1139  
1140 # Bias toward declared edge cases at EDGE_CASE_RATIO frequency
1141 1044 ▶ if(ref($spec) && $spec->{edge_case_array} && rand() < $EDGE_CASE_RATIO) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $spec and $spec->{"edge_case_array"} and rand() < $EDGE_CASE_RATIO) 6 1038 1044
Condition83%5/6
ref $spec and $spec->{"edge_case_array"} and rand() < $EDGE_CASE_RATIO
!ll&&!rl&&r
1024146
ref $spec and $spec->{"edge_case_array"}
!ll&&!rl&&r
0102420
MC/DC66%2/3
ref $spec and $spec->{"edge_case_array"} and rand() < $EDGE_CASE_RATIO
ref $spec $spec->{"edge_case_array"} rand() < $EDGE_CASE_RATIO
Truth table75%3/4
A and B and C
A= ref $specB= $spec->{"edge_case_array"}C= rand() < $EDGE_CASE_RATIO
ABCresult
0XX0
10X0
1100
1111
1142 6 my @ec = @{ $spec->{edge_case_array} };
1143 6 return $ec[ int(rand(@ec)) ];
1144 }
1145  
1146 # Dispatch to type-specific generator
1147 1038 ▶ if ($type eq $TYPE_INTEGER) { return $self->_rand_int($spec) }
Branch: 5 branches
BranchTrueFalseTotal
if ($type eq $TYPE_INTEGER) { } 452 586 1038
elsif ($type eq $TYPE_NUMBER) { } 0 586 586
elsif ($type eq $TYPE_BOOLEAN) { } 19 567 586
elsif ($type eq $TYPE_ARRAY) { } 7 560 567
elsif ($type eq $TYPE_HASH) { } 28 532 560
1148 0 elsif ($type eq $TYPE_NUMBER) { return $self->_rand_num($spec) }
1149 19 elsif ($type eq $TYPE_BOOLEAN) { return int(rand(2)) }
1150 7 elsif ($type eq $TYPE_ARRAY) { return $self->_rand_array($spec) }
1151 28 elsif ($type eq $TYPE_HASH) { return $self->_rand_hash($spec) }
1152 532 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 1492 ▶sub _rand_int {
Subroutine _rand_int: called CC=5 SCAR=16.1
1167 1492 my ($self, $spec) = @_;
1168  
1169 1492 ▶ my $min = $spec->{min} // $INT32_MIN;
Condition100%3/3
$spec->{"min"} // $INT32_MIN
l!l&&r!l&&!r
10943971
MC/DC100%2/2
$spec->{"min"} // $INT32_MIN
$spec->{"min"} $INT32_MIN
Truth table100%3/3
A // B
A= $spec->{"min"}B= $INT32_MIN
ABresult
1X1
011
000
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 ▶ my $max = $spec->{sample_max} // $spec->{max} // $INT32_MAX;
Condition100%6/6
($spec->{"sample_max"} // $spec->{"max"}) // $INT32_MAX
l!l&&r!l&&!r
10943971
$spec->{"sample_max"} // $spec->{"max"}
l!l&&r!l&&!r
500594398
MC/DC100%3/3
($spec->{"sample_max"} // $spec->{"max"}) // $INT32_MAX
$spec->{"sample_max"} $spec->{"max"} $INT32_MAX
Truth table100%4/4
A // B // C
A= $spec->{"sample_max"}B= $spec->{"max"}C= $INT32_MAX
ABCresult
1XX1
01X1
0011
0000
1176  
1177 # Bias toward boundary values to probe edge conditions
1178 1492 ▶ if(rand() < $INT_BOUNDARY_RATIO) {
Branch: 1 branch
BranchTrueFalseTotal
if (rand() < $INT_BOUNDARY_RATIO) 467 1025 1492
1179 467 my @interesting = ($min, $min + 1, 0, -1, 1, $max - 1, $max);
1180 467 return $interesting[ int(rand(@interesting)) ];
1181 }
1182  
1183 1025 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 510 ▶sub _rand_num {
Subroutine _rand_num: called CC=4 SCAR=14.6
1197 510 my ($self, $spec) = @_;
1198  
1199 510 ▶ my $min = $spec->{min} // -1e9;
Condition50%1/2
$spec->{"min"} // "-1000000000"
l!l
5100
MC/DC0%0/1
$spec->{"min"} // "-1000000000"
$spec->{"min"}
Truth table50%1/2
A
A= $spec->{"min"}
Aresult
11
00
1200 # As in _rand_int: sample_max caps generated data, max stays the bound
1201 # _validate_value() checks.
1202 510 ▶ my $max = $spec->{sample_max} // $spec->{max} // 1e9;
Condition60%3/5
($spec->{"sample_max"} // $spec->{"max"}) // "1000000000"
l!l
5100
$spec->{"sample_max"} // $spec->{"max"}
l!l&&r!l&&!r
500100
MC/DC0%0/2
($spec->{"sample_max"} // $spec->{"max"}) // "1000000000"
$spec->{"sample_max"} $spec->{"max"}
Truth table66%2/3
A // B
A= $spec->{"sample_max"}B= $spec->{"max"}
ABresult
1X1
011
000
1203  
1204 510 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 533 ▶sub _rand_string {
Subroutine _rand_string: called CC=5 SCAR=16.1
1222 533 my ($self, $spec) = @_;
1223  
1224 533 ▶ my $min_len = $spec->{min} // 0;
Condition100%2/2
$spec->{"min"} // 0
l!l
43490
MC/DC100%1/1
$spec->{"min"} // 0
$spec->{"min"}
Truth table100%2/2
A
A= $spec->{"min"}
Aresult
11
00
1225 533 ▶ my $max_len = $spec->{max} // $DEFAULT_MAX_STR_LEN;
Condition100%3/3
$spec->{"max"} // $DEFAULT_MAX_STR_LEN
l!l&&r!l&&!r
5746610
MC/DC100%2/2
$spec->{"max"} // $DEFAULT_MAX_STR_LEN
$spec->{"max"} $DEFAULT_MAX_STR_LEN
Truth table100%3/3
A // B
A= $spec->{"max"}B= $DEFAULT_MAX_STR_LEN
ABresult
1X1
011
000
1226  
1227 # Bias toward boundary lengths at STR_BOUNDARY_RATIO frequency
1228 533 my $len;
1229 533 ▶ if(rand() < $STR_BOUNDARY_RATIO) {
Branch: 1 branch
BranchTrueFalseTotal
if (rand() < $STR_BOUNDARY_RATIO) { } 74 459 533
1230 74 my @boundary_lens = ($min_len, $min_len + 1, $max_len - 1, $max_len);
1231 74 $len = $boundary_lens[ int(rand(@boundary_lens)) ];
1232 } else {
1233 459 $len = $min_len + int(rand($max_len - $min_len + 1));
1234 }
1235  
1236 # Clamp to non-negative
1237 533 ▶ $len = 0 if $len < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $len < 0 0 533 533
1238  
1239 533 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 207 ▶sub _rand_array {
Subroutine _rand_array: called CC=2 SCAR=6.9
1254 207 my ($self, $spec) = @_;
1255  
1256 207 ▶ my $items = $spec->{items} // {};
Condition100%2/2
$spec->{"items"} // {}
l!l
2007
MC/DC100%1/1
$spec->{"items"} // {}
$spec->{"items"}
Truth table100%2/2
A
A= $spec->{"items"}
Aresult
11
00
1257 207 my $count = int(rand($DEFAULT_MAX_ARRAY + 1));
1258  
1259 207 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 28 ▶sub _rand_hash {
Subroutine _rand_hash: called CC=3 SCAR=11.0
1273 28 my ($self, $spec) = @_;
1274  
1275 28 ▶ my $props = $spec->{properties} // {};
Condition100%2/2
$spec->{"properties"} // {}
l!l
199
MC/DC100%1/1
$spec->{"properties"} // {}
$spec->{"properties"}
Truth table100%2/2
A
A= $spec->{"properties"}
Aresult
11
00
1276 28 my %h;
1277  
1278 28 for my $key (keys %{$props}) {
1279 19 $h{$key} = $self->_generate_for_schema($props->{$key});
1280 }
1281  
1282 28 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 246 ▶sub _input_is_valid {
Subroutine _input_is_valid: called CC=9 SCAR=22.0
1300 246 my ($self, $input) = @_;
1301  
1302 246 my $spec = $self->{schema}{input};
1303  
1304 # No schema means we cannot judge validity
1305 246 ▶ return 1 unless defined $spec && ref($spec);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spec and ref $spec 1 245 246
Condition66%2/3
defined $spec and ref $spec
!ll&&!rl&&r
10245
MC/DC50%1/2
defined $spec and ref $spec
defined $spec ref $spec
Truth table66%2/3
A and B
A= defined $specB= ref $spec
ABresult
0X0
100
111
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 245 ▶ && defined($spec->{type}) && !ref($spec->{type});
Condition83%5/6
ref $spec eq 'HASH' && defined $spec->{'type'} && !ref($spec->{'type'})
!ll&&!rl&&r
1133129
ref $spec eq "HASH" and defined $spec->{"type"}
!ll&&!rl&&r
0113132
MC/DC66%2/3
ref $spec eq 'HASH' && defined $spec->{'type'} && !ref($spec->{'type'})
ref $spec eq "HASH" defined $spec->{"type"} !ref($spec->{'type'})
Truth table75%3/4
A and B && not(C)
A= ref $spec eq "HASH"B= defined $spec->{"type"}C= !ref($spec->{'type'})
ABCresult
0XX0
10X0
1100
1111
1312  
1313 245 ▶ my $input_style = $self->{schema}{input_style} // '';
Condition100%2/2
$self->{"schema"}{"input_style"} // ""
l!l
2243
MC/DC100%1/1
$self->{"schema"}{"input_style"} // ""
$self->{"schema"}{"input_style"}
Truth table100%2/2
A
A= $self->{"schema"}{"input_style"}
Aresult
11
00
1314  
1315 245 ▶ if(!$is_value_spec && ($input_style eq 'hash' || ref($input) eq 'HASH')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $is_value_spec and $input_style eq "hash" || ref $input eq "HASH") 5 240 245
Condition100%6/6
not $is_value_spec and $input_style eq "hash" || ref $input eq "HASH"
!ll&&!rl&&r
1291115
$input_style eq "hash" or ref $input eq "HASH"
l!l&&r!l&&!r
23111
MC/DC100%3/3
not $is_value_spec and $input_style eq "hash" || ref $input eq "HASH"
not $is_value_spec $input_style eq "hash" ref $input eq "HASH"
Truth table100%4/4
not(A) and B or C
A= not $is_value_specB= $input_style eq "hash"C= ref $input eq "HASH"
ABCresult
0XX0
1000
11X1
1011
1316 5 return $self->_validate_hash_input($input, $spec);
1317 }
1318  
1319 240 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 60 ▶sub _validate_hash_input {
Subroutine _validate_hash_input: called CC=10 SCAR=23.1
1334 60 my ($self, $input, $spec) = @_;
1335  
1336 60 ▶ return 0 unless defined $input;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $input 2 58 60
1337  
1338 58 for my $key (keys %{$spec}) {
1339 # Skip internal metadata keys
1340 69 ▶ next if $key =~ /^_/;
Branch: 1 branch
BranchTrueFalseTotal
if $key =~ /^_/ 2 67 69
1341  
1342 67 my $field_spec = $spec->{$key};
1343 67 ▶ next unless ref($field_spec) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $field_spec eq "HASH" 0 67 67
1344  
1345 67 ▶ my $value = ref($input) eq 'HASH' ? $input->{$key} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $input eq 'HASH' ? : 67 0 67
1346  
1347 # Required field missing is always invalid
1348 67 ▶ if(!defined($value) && !$field_spec->{optional}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $value or $field_spec->{"optional"}) 5 62 67
Condition100%3/3
defined $value or $field_spec->{"optional"}
l!l&&r!l&&!r
5755
MC/DC100%2/2
defined $value or $field_spec->{"optional"}
defined $value $field_spec->{"optional"}
Truth table100%3/3
A or B
A= defined $valueB= $field_spec->{"optional"}
ABresult
1X1
011
000
1349 5 return 0;
1350 }
1351  
1352 62 ▶ next unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 5 57 62
1353  
1354 57 ▶ return 0 unless $self->_validate_value($value, $field_spec);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_validate_value($value, $field_spec) 22 35 57
1355 }
1356  
1357 31 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 339 ▶sub _validate_value {
Subroutine _validate_value: called CC=32 SCAR=35.2
1377 339 my ($self, $value, $spec) = @_;
1378  
1379 # Undef is never valid unless optional — caller already checked optional
1380 339 ▶ return 0 unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 2 337 339
1381  
1382 337 ▶ my $type = $spec->{type} // $TYPE_STRING;
Condition66%2/3
$spec->{"type"} // $TYPE_STRING
l!l&&r!l&&!r
2261110
MC/DC0%0/2
$spec->{"type"} // $TYPE_STRING
$spec->{"type"} $TYPE_STRING
Truth table66%2/3
A // B
A= $spec->{"type"}B= $TYPE_STRING
ABresult
1X1
011
000
1383  
1384 337 ▶ if($type eq $TYPE_INTEGER) {
Branch: 6 branches
BranchTrueFalseTotal
if ($type eq $TYPE_INTEGER) { } 99 238 337
elsif ($type eq $TYPE_NUMBER) { } 5 233 238
elsif ($type eq $TYPE_STRING) { } 175 58 233
elsif ($type eq $TYPE_BOOLEAN) { } 6 52 58
elsif ($type eq $TYPE_ARRAY or $type eq 'array') { } 4 48 52
elsif ($type eq $TYPE_HASH or $type eq 'hash') { } 48 0 48
1385 99 ▶ return 0 unless $value =~ /^-?\d+$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $value =~ /^-?\d+$/ 4 95 99
1386 95 ▶ return 0 if defined($spec->{min}) && $value < $spec->{min};
Branch: 1 branch
BranchTrueFalseTotal
if defined $spec->{"min"} and $value < $spec->{"min"} 31 64 95
Condition100%3/3
defined $spec->{"min"} and $value < $spec->{"min"}
!ll&&!rl&&r
55931
MC/DC100%2/2
defined $spec->{"min"} and $value < $spec->{"min"}
defined $spec->{"min"} $value < $spec->{"min"}
Truth table100%3/3
A and B
A= defined $spec->{"min"}B= $value < $spec->{"min"}
ABresult
0X0
100
111
1387 64 ▶ return 0 if defined($spec->{max}) && $value > $spec->{max};
Branch: 1 branch
BranchTrueFalseTotal
if defined $spec->{"max"} and $value > $spec->{"max"} 13 51 64
Condition100%3/3
defined $spec->{"max"} and $value > $spec->{"max"}
!ll&&!rl&&r
84313
MC/DC100%2/2
defined $spec->{"max"} and $value > $spec->{"max"}
defined $spec->{"max"} $value > $spec->{"max"}
Truth table100%3/3
A and B
A= defined $spec->{"max"}B= $value > $spec->{"max"}
ABresult
0X0
100
111
1388 }
1389 elsif($type eq $TYPE_NUMBER) {
1390 # Accept integers, decimals, and scientific notation
1391 5 ▶ return 0 unless $value =~ /^-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $value =~ /^-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/ 1 4 5
1392 4 ▶ return 0 if defined($spec->{min}) && $value < $spec->{min};
Branch: 1 branch
BranchTrueFalseTotal
if defined $spec->{"min"} and $value < $spec->{"min"} 0 4 4
Condition33%1/3
defined $spec->{"min"} and $value < $spec->{"min"}
!ll&&!rl&&r
400
MC/DC0%0/2
defined $spec->{"min"} and $value < $spec->{"min"}
defined $spec->{"min"} $value < $spec->{"min"}
Truth table33%1/3
A and B
A= defined $spec->{"min"}B= $value < $spec->{"min"}
ABresult
0X0
100
111
1393 4 ▶ return 0 if defined($spec->{max}) && $value > $spec->{max};
Branch: 1 branch
BranchTrueFalseTotal
if defined $spec->{"max"} and $value > $spec->{"max"} 0 4 4
Condition33%1/3
defined $spec->{"max"} and $value > $spec->{"max"}
!ll&&!rl&&r
400
MC/DC0%0/2
defined $spec->{"max"} and $value > $spec->{"max"}
defined $spec->{"max"} $value > $spec->{"max"}
Truth table33%1/3
A and B
A= defined $spec->{"max"}B= $value > $spec->{"max"}
ABresult
0X0
100
111
1394 }
1395 elsif($type eq $TYPE_STRING) {
1396 175 my $len = length($value);
1397 175 ▶ return 0 if defined($spec->{min}) && $len < $spec->{min};
Branch: 1 branch
BranchTrueFalseTotal
if defined $spec->{"min"} and $len < $spec->{"min"} 2 173 175
Condition100%3/3
defined $spec->{"min"} and $len < $spec->{"min"}
!ll&&!rl&&r
146272
MC/DC100%2/2
defined $spec->{"min"} and $len < $spec->{"min"}
defined $spec->{"min"} $len < $spec->{"min"}
Truth table100%3/3
A and B
A= defined $spec->{"min"}B= $len < $spec->{"min"}
ABresult
0X0
100
111
1398 173 ▶ return 0 if defined($spec->{max}) && $len > $spec->{max};
Branch: 1 branch
BranchTrueFalseTotal
if defined $spec->{"max"} and $len > $spec->{"max"} 8 165 173
Condition100%3/3
defined $spec->{"max"} and $len > $spec->{"max"}
!ll&&!rl&&r
138278
MC/DC100%2/2
defined $spec->{"max"} and $len > $spec->{"max"}
defined $spec->{"max"} $len > $spec->{"max"}
Truth table100%3/3
A and B
A= defined $spec->{"max"}B= $len > $spec->{"max"}
ABresult
0X0
100
111
1399 165 ▶ if(defined($spec->{matches})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $spec->{"matches"}) 5 160 165
1400 5 (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 my $matched = eval {
1408 0 ▶ local $SIG{ALRM} = sub { die "matches regex timed out\n" };
Subroutine __ANON__: not called CC=1 SCAR=1.2
1409 5 alarm($MATCHES_REGEX_TIMEOUT_SECS);
1410 5 my $m = $value =~ /$pat/;
1411 5 alarm(0);
1412 5 $m;
1413 };
1414 5 alarm(0);
1415 5 ▶ return 0 unless $matched;
Branch: 1 branch
BranchTrueFalseTotal
unless $matched 3 2 5
1416 }
1417 }
1418 elsif($type eq $TYPE_BOOLEAN) {
1419 6 ▶ return 0 unless $value =~ /^[01]$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $value =~ /^[01]$/ 3 3 6
1420 }
1421 ▶ elsif($type eq $TYPE_ARRAY || $type eq 'array') {
Condition66%2/3
$type eq $TYPE_ARRAY or $type eq "array"
l!l&&r!l&&!r
4048
MC/DC50%1/2
$type eq $TYPE_ARRAY or $type eq "array"
$type eq $TYPE_ARRAY $type eq "array"
Truth table66%2/3
A or B
A= $type eq $TYPE_ARRAYB= $type eq "array"
ABresult
1X1
011
000
1422 4 ▶ return 0 unless ref($value) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "ARRAY" 2 2 4
1423 }
1424 ▶ elsif($type eq $TYPE_HASH || $type eq 'hash') {
Condition33%1/3
$type eq $TYPE_HASH or $type eq "hash"
l!l&&r!l&&!r
4800
MC/DC0%0/2
$type eq $TYPE_HASH or $type eq "hash"
$type eq $TYPE_HASH $type eq "hash"
Truth table33%1/3
A or B
A= $type eq $TYPE_HASHB= $type eq "hash"
ABresult
1X1
011
000
1425 48 ▶ return 0 unless ref($value) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "HASH" 2 46 48
1426 46 ▶ if(ref($spec->{properties}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $spec->{"properties"} eq "HASH") 44 2 46
1427 44 ▶ return 0 unless $self->_validate_hash_input($value, $spec->{properties});
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_validate_hash_input($value, $spec->{"properties"}) 20 24 44
1428 }
1429 }
1430  
1431 248 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 976 ▶sub _mutate {
Subroutine _mutate: called CC=7 SCAR=19.5
1454 976 my ($self, $input, $spec) = @_;
1455  
1456 976 my $type = ref($input);
1457  
1458 976 ▶ if(!defined $input) {
Branch: 4 branches
BranchTrueFalseTotal
if (not defined $input) { } 12 964 976
elsif (not $type) { } 916 48 964
elsif ($type eq 'ARRAY') { } 11 37 48
elsif ($type eq 'HASH') { } 35 2 37
1459 # Replace undef with a fresh random value
1460 12 return $self->_generate_random();
1461 }
1462 elsif(!$type) {
1463 # Dispatch scalar mutation based on apparent type
1464 916 ▶ if($input =~ /^-?\d+$/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($input =~ /^-?\d+$/) { } 483 433 916
elsif ($input =~ /^-?[\d.]+$/) { } 2 431 433
1465 483 return $self->_mutate_int($input, $spec);
1466 } elsif($input =~ /^-?[\d.]+$/) {
1467 2 return $self->_mutate_num($input, $spec);
1468 } else {
1469 431 return $self->_mutate_string($input);
1470 }
1471 }
1472 elsif($type eq 'ARRAY') {
1473 11 return $self->_mutate_array($input, $spec);
1474 }
1475 elsif($type eq 'HASH') {
1476 35 return $self->_mutate_hash($input, $spec);
1477 }
1478  
1479 # Blessed refs and other types pass through unchanged
1480 2 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 1093 ▶sub _outside_sampling_band {
Subroutine _outside_sampling_band: called CC=7 SCAR=19.5
1510 1093 my ($self, $value, $spec) = @_;
1511  
1512 1093 ▶ return $value unless ref($spec) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec eq "HASH" 16 1077 1093
1513  
1514 1077 my $ceiling = $spec->{sample_max};
1515 1077 my $max = $spec->{max};
1516  
1517 1077 ▶ return $value unless defined($ceiling) && defined($max);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ceiling and defined $max 77 1000 1077
Condition66%2/3
defined $ceiling and defined $max
!ll&&!rl&&r
7701000
MC/DC50%1/2
defined $ceiling and defined $max
defined $ceiling defined $max
Truth table66%2/3
A and B
A= defined $ceilingB= defined $max
ABresult
0X0
100
111
1518 1000 ▶ return $value unless defined($value) && ($value > $ceiling) && ($value <= $max);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and $value > $ceiling and $value <= $max 896 104 1000
Condition83%5/6
defined $value and $value > $ceiling and $value <= $max
!ll&&!rl&&r
754142104
defined $value and $value > $ceiling
!ll&&!rl&&r
0754246
MC/DC66%2/3
defined $value and $value > $ceiling and $value <= $max
defined $value $value > $ceiling $value <= $max
Truth table75%3/4
A and B and C
A= defined $valueB= $value > $ceilingC= $value <= $max
ABCresult
0XX0
10X0
1100
1111
1519  
1520 104 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 888 ▶sub _mutate_int {
Subroutine _mutate_int: called CC=9 SCAR=22.0
1536 888 my ($self, $n, $spec) = @_;
1537 888 my $op = int(rand(8));
1538 888 ▶ my $value
Branch: 8 branches
BranchTrueFalseTotal
$op == 0 ? : 113 775 888
$op == 1 ? : 98 677 775
$op == 2 ? : 110 567 677
$op == 3 ? : 130 437 567
$n == 0 ? : 5 125 130
$op == 4 ? : 115 322 437
$op == 5 ? : 104 218 322
$op == 6 ? : 110 108 218
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 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 205 ▶sub _mutate_num {
Subroutine _mutate_num: called CC=5 SCAR=16.1
1564 205 my ($self, $n, $spec) = @_;
1565 205 my $op = int(rand(5));
1566 205 ▶ my $value
Branch: 4 branches
BranchTrueFalseTotal
$op == 0 ? : 49 156 205
$op == 1 ? : 46 110 156
$op == 2 ? : 38 72 110
$op == 3 ? : 37 35 72
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 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 434 ▶sub _mutate_string {
Subroutine _mutate_string: called CC=1 SCAR=0.0
1589 434 my ($self, $s) = @_;
1590  
1591 434 my $len = length($s);
1592  
1593 my @ops = (
1594 # Bit flip a random character
1595 46 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1596 46 ▶ return $s unless $len;
Branch: 1 branch
BranchTrueFalseTotal
unless $len 3 43 46
1597 43 my $pos = int(rand($len));
1598 43 my $char = substr($s, $pos, 1);
1599 43 substr($s, $pos, 1) = chr(ord($char) ^ (1 << int(rand(8))));
1600 43 $s
1601 },
1602 # Insert a random byte
1603 94 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1604 94 my $pos = int(rand($len + 1));
1605 94 my $char = chr(int(rand(256)));
1606 94 substr($s, $pos, 0, $char);
1607 94 $s
1608 },
1609 # Delete a random character
1610 60 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1611 60 ▶ return $s unless $len;
Branch: 1 branch
BranchTrueFalseTotal
unless $len 5 55 60
1612 55 substr($s, int(rand($len)), 1, '');
1613 55 $s
1614 },
1615 # Truncate at a random position
1616 73 ▶ sub { substr($s, 0, int(rand($len + 1))) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1617 # Double the string
1618 92 ▶ sub { $s x 2 },
Subroutine __ANON__: called CC=1 SCAR=0.0
1619 # Replace with a known interesting string
1620 69 ▶ sub { $INTERESTING_STRINGS[ int(rand(@INTERESTING_STRINGS)) ] },
Subroutine __ANON__: called CC=1 SCAR=0.0
1621 434 );
1622  
1623 434 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 13 ▶sub _mutate_array {
Subroutine _mutate_array: called CC=2 SCAR=7.1
1638 13 my ($self, $arr, $spec) = @_;
1639  
1640 13 ▶ my $items = (ref($spec) eq 'HASH') ? $spec->{items} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $spec eq 'HASH' ? : 9 4 13
1641 13 my @copy = @{$arr};
1642  
1643 my @ops = (
1644 # Mutate a random element
1645 2 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1646 2 ▶ return [] unless @copy;
Branch: 1 branch
BranchTrueFalseTotal
unless @copy 0 2 2
1647 2 my $i = int(rand(@copy));
1648 2 $copy[$i] = $self->_mutate($copy[$i], $items);
1649 \@copy
1650 2 },
1651 # Duplicate a random element
1652 1 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=11.6
1653 1 ▶ return \@copy unless @copy;
Branch: 1 branch
BranchTrueFalseTotal
unless @copy 1 0 1
1654 0 my $i = int(rand(@copy));
1655 0 splice @copy, $i, 0, $copy[$i];
1656 \@copy
1657 0 },
1658 # Delete a random element
1659 8 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1660 8 ▶ return \@copy unless @copy;
Branch: 1 branch
BranchTrueFalseTotal
unless @copy 1 7 8
1661 7 splice @copy, int(rand(@copy)), 1;
1662 \@copy
1663 7 },
1664 # Return empty array
1665 2 ▶ sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
1666 13 );
1667  
1668 13 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 238 ▶sub _mutate_hash {
Subroutine _mutate_hash: called CC=4 SCAR=13.9
1682 238 my ($self, $h, $spec) = @_;
1683  
1684 my $properties = (ref($spec) eq 'HASH' && ref($spec->{properties}) eq 'HASH')
1685 238 ▶ ? $spec->{properties} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $spec eq 'HASH' && ref $spec->{'properties'} eq 'HASH' ? : 227 11 238
Condition100%3/3
ref $spec eq "HASH" and ref $spec->{"properties"} eq "HASH"
!ll&&!rl&&r
56227
MC/DC100%2/2
ref $spec eq "HASH" and ref $spec->{"properties"} eq "HASH"
ref $spec eq "HASH" ref $spec->{"properties"} eq "HASH"
Truth table100%3/3
A and B
A= ref $spec eq "HASH"B= ref $spec->{"properties"} eq "HASH"
ABresult
0X0
100
111
1686 238 my %copy = %{$h};
1687 238 my @keys = keys %copy;
1688  
1689 # Return unchanged if hash is empty
1690 238 ▶ return \%copy unless @keys;
Branch: 1 branch
BranchTrueFalseTotal
unless @keys 7 231 238
1691  
1692 231 my $k = $keys[ int(rand(@keys)) ];
1693 231 $copy{$k} = $self->_mutate($copy{$k}, $properties->{$k});
1694  
1695 231 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 81 ▶sub _seed_corpus {
Subroutine _seed_corpus: called CC=2 SCAR=6.9
1710 81 my $self = $_[0];
1711  
1712 81 for (1 .. $SEED_CORPUS_SIZE) {
1713 405 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 79 ▶sub _build_report {
Subroutine _build_report: called CC=1 SCAR=0.0
1731 79 my $self = $_[0];
1732  
1733 return {
1734 total_iterations => $self->{stats}{total},
1735 interesting_inputs => $self->{stats}{interesting},
1736 79 corpus_size => scalar @{ $self->{corpus} },
1737 branches_covered => $self->{stats}{coverage},
1738 bugs_found => $self->{stats}{bugs},
1739 bugs => $self->{bugs},
1740 79 };
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 19 1;
« blib/lib/Devel/App/Test/Generator/LCSAJ/Runtime.pm ↑ Summary lib/App/Test/Generator/Mutation/Feedback.pm »