python
import atheris import sys import numpy as np
First, we import the required modules: atheris, sys, and numpy.
python
@atheris.instrument_func def test_numpy_solve(data): fdp = atheris.FuzzedDataProvider(data)
Next, we define a function test_numpy_solve that takes in a single argument, data. This function will be called with the inputs generated by Atheris. We decorate the function with the @atheris.instrument_func decorator to indicate that it should be instrumented for coverage analysis.
We create a FuzzedDataProvider object called fdp from the data argument to allow us to read the input data.
python
n = fdp.ConsumeIntInRange(1, 5)
We generate a random integer n between 1 and 5 to determine the size of the matrices we will create. This is done using the ConsumeIntInRange method of the FuzzedDataProvider object.
python
try: A = np.array([fdp.ConsumeFloat() for _ in range(n * n)]).reshape(n, n) B = np.array([fdp.ConsumeFloat() for _ in range(n * n)]).reshape(n, n) except atheris.BufferTooSmallError: return
We generate two random matrices A and B of size n x n by consuming n * n floats from the input data. We reshape the resulting 1D arrays into 2D matrices using the reshape method of the NumPy array.
We wrap the above code in a try-except block that catches a BufferTooSmallError exception, which is raised if there is not enough data left in the input buffer to generate the matrices.
python
try: x = np.linalg.solve(A, B) except np.linalg.LinAlgError: pass
Finally, we attempt to solve the linear matrix equation Ax = B using the numpy.linalg.solve function. If the matrix A is singular, a numpy.linalg.LinAlgError exception will be raised, which we catch and ignore.
python
def main(): atheris.Setup(sys.argv, test_numpy_solve) atheris.Fuzz()
if name == "main": main()
The main function sets up the Atheris fuzzer by calling the Setup function with the command line arguments and the function to be fuzzed (test_numpy_solve). It then starts the fuzzing process by calling the Fuzz function.
That's the complete code for the NumPy fuzzer! It generates random matrices and tests the numpy.linalg.solve function with them to detect any crashes or errors that may occur.