Class ZestGuidance
- All Implemented Interfaces:
Guidance
- Direct Known Subclasses:
ExecutionIndexingGuidance
- Author:
- Rohan Padhye
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classA candidate or saved test input that maps objects of type K to bytes.classclass -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected FileThe directory where all generated inputs are logged in sub-directories (if enabled).protected booleanBlind fuzzing -- if true then the queue is always empty.protected longNumber of conditional jumps since last run was started.protected final ConsoleA system console, which is non-null only if STDOUT is a console.protected FileThe file contianing the coverage informationprotected ZestGuidance.Input<?>Current input that's running -- valid after getInput() and before handleResult().protected FileThe currently executing input (for debugging purposes).protected intIndex of currentInput in the savedInputs -- valid after seeds are processed (OK if this is inaccurate).protected intNumber of cycles completed (i.e.protected final booleanWhether to save inputs that only add new coverage bits (but no new responsibilities).protected final Stringsave crash to specific location (should be used with EXIT_ON_CRASH)protected final booleanWhether to stop/exit once a crash is found.protected ThreadThe first thread in the application, which usually runs the test method.protected final booleanWhether to generate EOFs when we run out of bytes in the input, instead of randomly generating new bytes.protected longTotal execs at last stats refresh.protected DateTime at last stats refresh.protected final booleanUse libFuzzer like output instead of AFL like stats screen (https://llvm.org/docs/LibFuzzer.html#output)protected final booleanWhether to store all generated inputs to disk (can get slowww!)protected final booleanControls whether to update the .cur_input file with the most recently generated input (disabling improves performance).protected FileThe file where log data is written.protected final intMax input size to generate.protected intThe maximum number of keys covered by any single input found so far.protected final longThe max amount of time to run for, in milli-secondsprotected final longThe max number of trials to runprotected final doubleMean number of mutations to perform in each round.protected final doubleMean number of contiguous bytes to mutate in each mutation.protected booleanWhether the application has more than one thread running coverage-instrumented codeprotected final doubleProbability that a standard mutation sets the byte to just zero instead of a random value.protected final intBaseline number of mutated children to produce from a given parent input.protected final intMultiplication factor for number of children to produce for favored inputs.protected intNumber of mutated inputs generated from currentInput.protected intNumber of favored inputs in the last cycle.protected intNumber of saved inputs.protected longThe number of trials completed.protected longThe number of valid inputs.protected final FileThe directory where fuzzing results are produced.protected final booleanWhether to hide fuzzing statisticsprotected RandomA pseudo-random number generator for generating fresh values.protected Map<Object,ZestGuidance.Input> A mapping of coverage keys to inputs that are responsible for them.protected ICoverageCoverage statistics for a single run.protected DateDate when last run was started.protected final booleanWhether to save only valid inputsprotected FileThe directory where interesting inputs are saved.protected FileThe directory where saved inputs are saved.protected ArrayList<ZestGuidance.Input>Set of saved inputs to fuzz.protected Deque<ZestGuidance.Input>Queue of seeds to fuzz.protected longTimeout for an individual run.protected final DateTime since this guidance instance was created.protected final longMinimum amount of time (in millis) between two stats refreshes.protected FileThe file where saved plot data is written.protected final booleanWhether to steal responsibility from old inputs (this increases computation cost).protected final StringThe name of the test for display purposes.protected ICoverageCumulative coverage statistics.The set of unique failures found so far.protected ICoverageCumulative coverage for valid inputs.protected booleanValidity fuzzing -- if true then save valid inputs that increase valid coverageprotected final booleanWhether to print log statements to stderr (debug option; manually edit). -
Constructor Summary
ConstructorsConstructorDescriptionZestGuidance(String testName, Duration duration, File outputDirectory) Creates a new Zest guidance instance with seed inputs and optional duration.ZestGuidance(String testName, Duration duration, File outputDirectory, File seedInputDir) Creates a new Zest guidance instance with seed inputs and optional duration.ZestGuidance(String testName, Duration duration, File outputDirectory, File[] seedFiles) Creates a new Zest guidance instance with seed inputs and optional duration.ZestGuidance(String testName, Duration duration, Long trials, File outputDirectory, File[] seedInputFiles, Random sourceOfRandomness) Creates a new Zest guidance instance with seed input files and optional duration, optional trial limit, an possibly deterministic PRNG.ZestGuidance(String testName, Duration duration, Long trials, File outputDirectory, File seedInputDir, Random sourceOfRandomness) Creates a new Zest guidance instance with seed input directory and optional duration, optional trial limit, an possibly deterministic PRNG.ZestGuidance(String testName, Duration duration, Long trials, File outputDirectory, Random sourceOfRandomness) Creates a new Zest guidance instance with optional duration, optional trial limit, and possibly deterministic PRNG. -
Method Summary
Modifier and TypeMethodDescriptionprotected voidappendLineToFile(File file, String line) checkSavingCriteriaSatisfied(Result result) protected voidHandles the end of fuzzing cycle (i.e., having gone through the entire queue)protected org.eclipse.collections.impl.set.mutable.primitive.IntHashSetcomputeResponsibilities(boolean valid) protected voidconditionallySynchronize(boolean cond, Runnable task) Conditionally run a method using synchronization.protected ZestGuidance.Input<?>Spawns a new input from thin air (i.e., actually random)protected InputStreamReturns an InputStream that delivers parameters to the generators.protected voiddisplayStats(boolean force) generateCallBack(Thread thread) Returns a callback generator for a thread's event trace.getInput()Returns a reference to a stream of values return from the pseudo-random number generator.protected Stringprotected intgetTargetChildrenForParent(ZestGuidance.Input parentInput) protected StringgetTitle()Returns a reference to the coverage statistics.protected voidHandles a trace event generated during test execution.voidhandleResult(Result result, Throwable error) Handles the end of a fuzzing trial.booleanhasInput()Returns whether an input is ready for a new trial to be executed.protected voidprotected StringmillisToDuration(long millis) This method is only invoked during optional observability logging to provide the type of guidance used for input generation.protected voidsaveCurrentInput(org.eclipse.collections.impl.set.mutable.primitive.IntHashSet responsibilities, String why) voidsetBlind(boolean blind) protected voidUpdates the data in the coverage fileprotected voidwriteCurrentInputToFile(File saveFile) Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface edu.berkeley.cs.jqf.fuzz.guidance.Guidance
beforeRun, observeGeneratedArgs
-
Field Details
-
MUTATION_ZERO_PROBABILITY
protected final double MUTATION_ZERO_PROBABILITYProbability that a standard mutation sets the byte to just zero instead of a random value.- See Also:
-
random
A pseudo-random number generator for generating fresh values. -
testName
The name of the test for display purposes. -
maxDurationMillis
protected final long maxDurationMillisThe max amount of time to run for, in milli-seconds -
maxTrials
protected final long maxTrialsThe max number of trials to run -
numTrials
protected long numTrialsThe number of trials completed. -
numValid
protected long numValidThe number of valid inputs. -
outputDirectory
The directory where fuzzing results are produced. -
savedCorpusDirectory
The directory where interesting inputs are saved. -
savedFailuresDirectory
The directory where saved inputs are saved. -
allInputsDirectory
The directory where all generated inputs are logged in sub-directories (if enabled). -
savedInputs
Set of saved inputs to fuzz. -
seedInputs
Queue of seeds to fuzz. -
currentInput
Current input that's running -- valid after getInput() and before handleResult(). -
currentParentInputIdx
protected int currentParentInputIdxIndex of currentInput in the savedInputs -- valid after seeds are processed (OK if this is inaccurate). -
numChildrenGeneratedForCurrentParentInput
protected int numChildrenGeneratedForCurrentParentInputNumber of mutated inputs generated from currentInput. -
cyclesCompleted
protected int cyclesCompletedNumber of cycles completed (i.e. how many times we've reset currentParentInputIdx to 0. -
numFavoredLastCycle
protected int numFavoredLastCycleNumber of favored inputs in the last cycle. -
blind
protected boolean blindBlind fuzzing -- if true then the queue is always empty. -
validityFuzzing
protected boolean validityFuzzingValidity fuzzing -- if true then save valid inputs that increase valid coverage -
numSavedInputs
protected int numSavedInputsNumber of saved inputs. This is usually the same as savedInputs.size(), but we do not really save inputs in TOTALLY_RANDOM mode. -
runCoverage
Coverage statistics for a single run. -
totalCoverage
Cumulative coverage statistics. -
validCoverage
Cumulative coverage for valid inputs. -
maxCoverage
protected int maxCoverageThe maximum number of keys covered by any single input found so far. -
responsibleInputs
A mapping of coverage keys to inputs that are responsible for them. -
uniqueFailures
The set of unique failures found so far. -
EXACT_CRASH_PATH
save crash to specific location (should be used with EXIT_ON_CRASH) -
verbose
protected final boolean verboseWhether to print log statements to stderr (debug option; manually edit).- See Also:
-
console
A system console, which is non-null only if STDOUT is a console. -
startTime
Time since this guidance instance was created. -
lastRefreshTime
Time at last stats refresh. -
lastNumTrials
protected long lastNumTrialsTotal execs at last stats refresh. -
STATS_REFRESH_TIME_PERIOD
protected final long STATS_REFRESH_TIME_PERIODMinimum amount of time (in millis) between two stats refreshes.- See Also:
-
logFile
The file where log data is written. -
statsFile
The file where saved plot data is written. -
currentInputFile
The currently executing input (for debugging purposes). -
coverageFile
The file contianing the coverage information -
LIBFUZZER_COMPAT_OUTPUT
protected final boolean LIBFUZZER_COMPAT_OUTPUTUse libFuzzer like output instead of AFL like stats screen (https://llvm.org/docs/LibFuzzer.html#output) -
QUIET_MODE
protected final boolean QUIET_MODEWhether to hide fuzzing statistics -
LOG_ALL_INPUTS
protected final boolean LOG_ALL_INPUTSWhether to store all generated inputs to disk (can get slowww!) -
LOG_CURRENT_INPUT
protected final boolean LOG_CURRENT_INPUTControls whether to update the .cur_input file with the most recently generated input (disabling improves performance). Defaults to true. -
singleRunTimeoutMillis
protected long singleRunTimeoutMillisTimeout for an individual run. -
runStart
Date when last run was started. -
branchCount
protected long branchCountNumber of conditional jumps since last run was started. -
EXIT_ON_CRASH
protected final boolean EXIT_ON_CRASHWhether to stop/exit once a crash is found. -
firstThread
The first thread in the application, which usually runs the test method. -
multiThreaded
protected boolean multiThreadedWhether the application has more than one thread running coverage-instrumented code -
SAVE_ONLY_VALID
protected final boolean SAVE_ONLY_VALIDWhether to save only valid inputs -
MAX_INPUT_SIZE
protected final int MAX_INPUT_SIZEMax input size to generate. -
GENERATE_EOF_WHEN_OUT
protected final boolean GENERATE_EOF_WHEN_OUTWhether to generate EOFs when we run out of bytes in the input, instead of randomly generating new bytes. -
NUM_CHILDREN_BASELINE
protected final int NUM_CHILDREN_BASELINEBaseline number of mutated children to produce from a given parent input.- See Also:
-
NUM_CHILDREN_MULTIPLIER_FAVORED
protected final int NUM_CHILDREN_MULTIPLIER_FAVOREDMultiplication factor for number of children to produce for favored inputs.- See Also:
-
MEAN_MUTATION_COUNT
protected final double MEAN_MUTATION_COUNTMean number of mutations to perform in each round.- See Also:
-
MEAN_MUTATION_SIZE
protected final double MEAN_MUTATION_SIZEMean number of contiguous bytes to mutate in each mutation.- See Also:
-
DISABLE_SAVE_NEW_COUNTS
protected final boolean DISABLE_SAVE_NEW_COUNTSWhether to save inputs that only add new coverage bits (but no new responsibilities). -
STEAL_RESPONSIBILITY
protected final boolean STEAL_RESPONSIBILITYWhether to steal responsibility from old inputs (this increases computation cost).
-
-
Constructor Details
-
ZestGuidance
public ZestGuidance(String testName, Duration duration, Long trials, File outputDirectory, Random sourceOfRandomness) throws IOException Creates a new Zest guidance instance with optional duration, optional trial limit, and possibly deterministic PRNG.- Parameters:
testName- the name of test to display on the status screenduration- the amount of time to run fuzzing for, wherenullindicates unlimited time.trials- the number of trials for which to run fuzzing, wherenullindicates unlimited trials.outputDirectory- the directory where fuzzing results will be writtensourceOfRandomness- a pseudo-random number generator- Throws:
IOException- if the output directory could not be prepared
-
ZestGuidance
public ZestGuidance(String testName, Duration duration, Long trials, File outputDirectory, File[] seedInputFiles, Random sourceOfRandomness) throws IOException Creates a new Zest guidance instance with seed input files and optional duration, optional trial limit, an possibly deterministic PRNG.- Parameters:
testName- the name of test to display on the status screenduration- the amount of time to run fuzzing for, wherenullindicates unlimited time.trials- the number of trials for which to run fuzzing, wherenullindicates unlimited trials.outputDirectory- the directory where fuzzing results will be writtenseedInputFiles- one or more input files to be used as initial inputssourceOfRandomness- a pseudo-random number generator- Throws:
IOException- if the output directory could not be prepared
-
ZestGuidance
public ZestGuidance(String testName, Duration duration, Long trials, File outputDirectory, File seedInputDir, Random sourceOfRandomness) throws IOException Creates a new Zest guidance instance with seed input directory and optional duration, optional trial limit, an possibly deterministic PRNG.- Parameters:
testName- the name of test to display on the status screenduration- the amount of time to run fuzzing for, wherenullindicates unlimited time.trials- the number of trials for which to run fuzzing, wherenullindicates unlimited trials.outputDirectory- the directory where fuzzing results will be writtenseedInputDir- the directory containing one or more input files to be used as initial inputssourceOfRandomness- a pseudo-random number generator- Throws:
IOException- if the output directory could not be prepared
-
ZestGuidance
public ZestGuidance(String testName, Duration duration, File outputDirectory, File seedInputDir) throws IOException Creates a new Zest guidance instance with seed inputs and optional duration.- Parameters:
testName- the name of test to display on the status screenduration- the amount of time to run fuzzing for, wherenullindicates unlimited time.outputDirectory- the directory where fuzzing results will be writtenseedInputDir- the directory containing one or more input files to be used as initial inputs- Throws:
IOException- if the output directory could not be prepared
-
ZestGuidance
Creates a new Zest guidance instance with seed inputs and optional duration.- Parameters:
testName- the name of test to display on the status screenduration- the amount of time to run fuzzing for, wherenullindicates unlimited time.outputDirectory- the directory where fuzzing results will be written- Throws:
IOException- if the output directory could not be prepared
-
ZestGuidance
public ZestGuidance(String testName, Duration duration, File outputDirectory, File[] seedFiles) throws IOException Creates a new Zest guidance instance with seed inputs and optional duration.- Parameters:
testName- the name of test to display on the status screenduration- the amount of time to run fuzzing for, wherenullindicates unlimited time.outputDirectory- the directory where fuzzing results will be written- Throws:
IOException- if the output directory could not be prepared
-
-
Method Details
-
getStatNames
-
appendLineToFile
- Throws:
GuidanceException
-
observeGuidance
Description copied from interface:GuidanceThis method is only invoked during optional observability logging to provide the type of guidance used for input generation.
- Specified by:
observeGuidancein interfaceGuidance
-
infoLog
-
millisToDuration
-
displayStats
protected void displayStats(boolean force) -
updateCoverageFile
protected void updateCoverageFile()Updates the data in the coverage file -
getTitle
-
setBlind
public void setBlind(boolean blind) -
getTargetChildrenForParent
-
completeCycle
protected void completeCycle()Handles the end of fuzzing cycle (i.e., having gone through the entire queue) -
createFreshInput
Spawns a new input from thin air (i.e., actually random)- Returns:
- a fresh input
-
createParameterStream
Returns an InputStream that delivers parameters to the generators. Note: The variable `currentInput` has been set to point to the input to mutate.- Returns:
- an InputStream that delivers parameters to the generators
-
getInput
Description copied from interface:GuidanceReturns a reference to a stream of values return from the pseudo-random number generator.This method is guaranteed to be invoked by JQF at most once after each invocation of
Guidance.hasInput()that has returnedtrue.If
Guidance.hasInput()returnsfalseor has not been invoked since the last call toGuidance.getInput(), then invoking this method may throw an IllegalStateException.- Specified by:
getInputin interfaceGuidance- Returns:
- a stream of bytes to be used by the input generator(s)
- Throws:
GuidanceException- if there was an I/O or other error in generating the input stream
-
hasInput
public boolean hasInput()Description copied from interface:GuidanceReturns whether an input is ready for a new trial to be executed.This method may block until a new input stream is made ready. If this method returns
false, then JQF stops fuzzing and this guidance will not be used further. -
handleResult
Description copied from interface:GuidanceHandles the end of a fuzzing trial.This method is guaranteed to be invoked by JQF exactly once after each invocation of
Guidance.getInput(). Therefore, it is safe to open resources such as files in a call toGuidance.getInput()and only close them inside this method.If
resultisSUCCESS, thenerroris eithernullor it is an instance of a throwable that is declared by the test method in itsthrowsclause.If
resultisINVALID, thenerroris either anAssumptionViolatedException, if the argument of anassume()statement wasfalse, or it is aGuidanceException, indicating that fuzzing was interrupted during the execution of this trial (and will not continue further).If
resultisFAILURE, thenerroris some other throwable that was thrown by the test execution but was not listed in itsthrowsclause. This is the only way to detect test errors. Assertion errors will typically fall into this category. So will other unlisted RuntimeExceptions such as NPE.- Specified by:
handleResultin interfaceGuidance- Parameters:
result- the result of the fuzzing trialerror- the error thrown during the trial, ornull- Throws:
GuidanceException- if there was an I/O or other error in handling the result
-
checkSavingCriteriaSatisfied
-
computeResponsibilities
protected org.eclipse.collections.impl.set.mutable.primitive.IntHashSet computeResponsibilities(boolean valid) -
writeCurrentInputToFile
- Throws:
IOException
-
saveCurrentInput
protected void saveCurrentInput(org.eclipse.collections.impl.set.mutable.primitive.IntHashSet responsibilities, String why) throws IOException - Throws:
IOException
-
generateCallBack
Description copied from interface:GuidanceReturns a callback generator for a thread's event trace.The application under test is instrumented such that each thread generates a sequence of
TraceEvents that may be handled by a separate callback method (though it may also be the same callback).The callback provided by this method will typically be used for collection execution information such as branch coverage, which in turn is used for constructing the next input stream.
This method is a supplier of event consumers. It is invoked once per new application thread spawned during fuzzing.
- Specified by:
generateCallBackin interfaceGuidance- Parameters:
thread- the thread whose events to handle- Returns:
- a callback that handles trace events generated by that thread
-
handleEvent
Handles a trace event generated during test execution. Not used by FastNonCollidingCoverage, which does not allocate an instance of TraceEvent at each branch probe execution.- Parameters:
e- the trace event to be handled
-
getTotalCoverage
Returns a reference to the coverage statistics.- Returns:
- a reference to the coverage statistics
-
conditionallySynchronize
Conditionally run a method using synchronization. This is used to handle multi-threaded fuzzing.
-