Fuzzer: Refactor utility methods shared by proto fuzzers.

Co-authored-by: Leonardo <leo@ethereum.org>
Co-authored-by: Daniel Kirchner <daniel@ekpyron.org>
This commit is contained in:
Bhargava Shastry 2021-02-02 15:23:02 +01:00
parent 72c6932bf5
commit febccdd96a
12 changed files with 445 additions and 436 deletions

View File

@ -14,14 +14,17 @@
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <test/tools/ossfuzz/abiV2FuzzerCommon.h>
#include <test/tools/ossfuzz/SolidityEvmoneInterface.h>
#include <test/tools/ossfuzz/protoToAbiV2.h>
#include <src/libfuzzer/libfuzzer_macro.h>
#include <abicoder.hpp>
using namespace solidity::frontend;
using namespace solidity::test::fuzzer;
using namespace solidity::test::abiv2fuzzer;
using namespace solidity::test;
using namespace solidity::util;
@ -30,8 +33,6 @@ using namespace std;
static constexpr size_t abiCoderHeapSize = 1024 * 512;
static evmc::VM evmone = evmc::VM{evmc_create_evmone()};
/// Expected output value is decimal 0
static vector<uint8_t> const expectedOutput(32, 0);
DEFINE_PROTO_FUZZER(Contract const& _contract)
{
@ -54,54 +55,27 @@ DEFINE_PROTO_FUZZER(Contract const& _contract)
auto [encodeStatus, encodedData] = coder.encode(typeString, valueString);
solAssert(encodeStatus, "Isabelle abicoder fuzzer: Encoding failed");
// Raw runtime byte code generated by solidity
bytes byteCode;
string hexEncodedInput;
try
{
// Compile contract generated by the proto fuzzer
SolidityCompilationFramework solCompilationFramework;
string contractName = ":C";
byteCode = solCompilationFramework.compileContract(contractSource, contractName);
Json::Value methodIdentifiers = solCompilationFramework.getMethodIdentifiers();
// We always call the second function from the list of alphabetically
// sorted interface functions
hexEncodedInput = (++methodIdentifiers.begin())->asString() + encodedData.substr(2, encodedData.size());
}
// Ignore stack too deep errors during compilation
catch (solidity::evmasm::StackTooDeepException const&)
{
return;
}
// We target the default EVM which is the latest
solidity::langutil::EVMVersion version;
langutil::EVMVersion version;
EVMHost hostContext(version, evmone);
// Deploy contract and signal failure if deployment failed
evmc::result createResult = AbiV2Utility::deployContract(hostContext, byteCode);
solAssert(
createResult.status_code == EVMC_SUCCESS,
"Proto ABIv2 Fuzzer: Contract creation failed"
);
// Execute test function and signal failure if EVM reverted or
// did not return expected output on successful execution.
evmc::result callResult = AbiV2Utility::executeContract(
string contractName = ":C";
CompilerInput cInput(version, contractSource, contractName, OptimiserSettings::minimal(), {}, false);
EvmoneUtility evmoneUtil(
hostContext,
fromHex(hexEncodedInput),
createResult.create_address
cInput,
contractName,
{},
{}
);
// We don't care about EVM One failures other than EVMC_REVERT
solAssert(callResult.status_code != EVMC_REVERT, "Proto ABIv2 fuzzer: EVM One reverted");
if (callResult.status_code == EVMC_SUCCESS)
solAssert(
AbiV2Utility::isOutputExpected(callResult.output_data, callResult.output_size, expectedOutput),
"Proto ABIv2 fuzzer: ABIv2 coding failure found"
);
auto result = evmoneUtil.compileDeployAndExecute(encodedData);
if (result.has_value())
{
solAssert(result->status_code != EVMC_REVERT, "Proto ABIv2 fuzzer: EVM One reverted.");
if (result->status_code == EVMC_SUCCESS)
solAssert(
EvmoneUtility::zeroWord(result->output_data, result->output_size),
"Proto ABIv2 fuzzer: ABIv2 coding failure found."
);
}
}
return;
}

View File

@ -110,7 +110,7 @@ if (OSSFUZZ)
add_executable(abiv2_proto_ossfuzz
../../EVMHost.cpp
abiV2ProtoFuzzer.cpp
abiV2FuzzerCommon.cpp
SolidityEvmoneInterface.cpp
protoToAbiV2.cpp
abiV2Proto.pb.cc
)
@ -128,9 +128,9 @@ if (OSSFUZZ)
target_compile_options(abiv2_proto_ossfuzz PUBLIC ${COMPILE_OPTIONS} -Wno-sign-conversion -Wno-suggest-destructor-override -Wno-inconsistent-missing-destructor-override)
add_executable(abiv2_isabelle_ossfuzz
../../EVMHost.cpp
AbiV2IsabelleFuzzer.cpp
abiV2FuzzerCommon.cpp
SolidityEvmoneInterface.cpp
../../EVMHost.cpp
protoToAbiV2.cpp
abiV2Proto.pb.cc
)
@ -151,9 +151,9 @@ if (OSSFUZZ)
add_executable(sol_proto_ossfuzz
solProtoFuzzer.cpp
SolidityEvmoneInterface.cpp
protoToSol.cpp
solProto.pb.cc
abiV2FuzzerCommon.cpp
../../EVMHost.cpp
)
target_include_directories(sol_proto_ossfuzz PRIVATE

View File

@ -22,7 +22,7 @@
#include <liblangutil/Exceptions.h>
using namespace std;
using namespace solidity::test::fuzzer;
using namespace solidity::test::fuzzer::mutator;
// Prototype as we can't use the FuzzerInterface.h header.
extern "C" size_t LLVMFuzzerMutate(uint8_t* _data, size_t _size, size_t _maxSize);

View File

@ -25,7 +25,7 @@
#include <memory>
namespace solidity::test::fuzzer
namespace solidity::test::fuzzer::mutator
{
struct SolidityCustomMutatorInterface
{

View File

@ -0,0 +1,197 @@
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <test/tools/ossfuzz/SolidityEvmoneInterface.h>
#include <liblangutil/Exceptions.h>
#include <liblangutil/SourceReferenceFormatter.h>
#include <range/v3/algorithm/all_of.hpp>
#include <range/v3/span.hpp>
using namespace solidity::test::fuzzer;
using namespace solidity::frontend;
using namespace solidity::langutil;
using namespace solidity::util;
using namespace std;
optional<CompilerOutput> SolidityCompilationFramework::compileContract()
{
m_compiler.setSources({{"", m_compilerInput.sourceCode}});
m_compiler.setLibraries(m_compilerInput.libraryAddresses);
m_compiler.setEVMVersion(m_compilerInput.evmVersion);
m_compiler.setOptimiserSettings(m_compilerInput.optimiserSettings);
if (!m_compiler.compile())
{
if (m_compilerInput.debugFailure)
{
SourceReferenceFormatter formatter(cerr, false, false);
cerr << "Compiling contract failed" << endl;
for (auto const& error: m_compiler.errors())
formatter.printExceptionInformation(
*error,
formatter.formatErrorInformation(*error)
);
}
return {};
}
else
{
string contractName;
if (m_compilerInput.contractName.empty())
contractName = m_compiler.lastContractName();
else
contractName = m_compilerInput.contractName;
evmasm::LinkerObject obj = m_compiler.object(contractName);
Json::Value methodIdentifiers = m_compiler.methodIdentifiers(contractName);
return CompilerOutput{obj.bytecode, methodIdentifiers};
}
}
bool EvmoneUtility::zeroWord(uint8_t const* _result, size_t _length)
{
return _length == 32 &&
ranges::all_of(
ranges::span(_result, _length),
[](uint8_t _v) { return _v == 0; });
}
evmc_message EvmoneUtility::initializeMessage(bytes const& _input)
{
// Zero initialize all message fields
evmc_message msg = {};
// Gas available (value of type int64_t) is set to its maximum
// value.
msg.gas = std::numeric_limits<int64_t>::max();
msg.input_data = _input.data();
msg.input_size = _input.size();
return msg;
}
evmc::result EvmoneUtility::executeContract(
bytes const& _functionHash,
evmc_address _deployedAddress
)
{
evmc_message message = initializeMessage(_functionHash);
message.destination = _deployedAddress;
message.kind = EVMC_CALL;
return m_evmHost.call(message);
}
evmc::result EvmoneUtility::deployContract(bytes const& _code)
{
evmc_message message = initializeMessage(_code);
message.kind = EVMC_CREATE;
return m_evmHost.call(message);
}
evmc::result EvmoneUtility::deployAndExecute(
bytes const& _byteCode,
string const& _hexEncodedInput
)
{
// Deploy contract and signal failure if deploy failed
evmc::result createResult = deployContract(_byteCode);
solAssert(
createResult.status_code == EVMC_SUCCESS,
"SolidityEvmoneInterface: Contract creation failed"
);
// Execute test function and signal failure if EVM reverted or
// did not return expected output on successful execution.
evmc::result callResult = executeContract(
util::fromHex(_hexEncodedInput),
createResult.create_address
);
// We don't care about EVM One failures other than EVMC_REVERT
solAssert(
callResult.status_code != EVMC_REVERT,
"SolidityEvmoneInterface: EVM One reverted"
);
return callResult;
}
optional<evmc::result> EvmoneUtility::compileDeployAndExecute(string _fuzzIsabelle)
{
map<string, h160> libraryAddressMap;
// Stage 1: Compile and deploy library if present.
if (!m_libraryName.empty())
{
m_compilationFramework.contractName(m_libraryName);
auto compilationOutput = m_compilationFramework.compileContract();
if (compilationOutput.has_value())
{
CompilerOutput cOutput = compilationOutput.value();
// Deploy contract and signal failure if deploy failed
evmc::result createResult = deployContract(cOutput.byteCode);
solAssert(
createResult.status_code == EVMC_SUCCESS,
"SolidityEvmoneInterface: Library deployment failed"
);
libraryAddressMap[m_libraryName] = EVMHost::convertFromEVMC(createResult.create_address);
m_compilationFramework.libraryAddresses(libraryAddressMap);
}
else
return {};
}
// Stage 2: Compile, deploy, and execute contract, optionally using library
// address map.
m_compilationFramework.contractName(m_contractName);
auto cOutput = m_compilationFramework.compileContract();
if (cOutput.has_value())
{
solAssert(
!cOutput->byteCode.empty() && !cOutput->methodIdentifiersInContract.empty(),
"SolidityEvmoneInterface: Invalid compilation output."
);
string methodName;
if (!_fuzzIsabelle.empty())
// TODO: Remove this once a cleaner solution is found for querying
// isabelle test entry point. At the moment, we are sure that the
// entry point is the second method in the contract (hence the ++)
// but not its name.
methodName = (++cOutput->methodIdentifiersInContract.begin())->asString() +
_fuzzIsabelle.substr(2, _fuzzIsabelle.size());
else
methodName = cOutput->methodIdentifiersInContract[m_methodName].asString();
return deployAndExecute(
cOutput->byteCode,
methodName
);
}
else
return {};
}
optional<CompilerOutput> EvmoneUtility::compileContract()
{
try
{
return m_compilationFramework.compileContract();
}
catch (evmasm::StackTooDeepException const&)
{
return {};
}
}

View File

@ -0,0 +1,170 @@
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <test/EVMHost.h>
#include <libsolidity/interface/CompilerStack.h>
#include <libyul/AssemblyStack.h>
#include <libsolutil/Keccak256.h>
#include <evmone/evmone.h>
namespace solidity::test::fuzzer
{
struct CompilerOutput
{
/// EVM bytecode returned by compiler
solidity::bytes byteCode;
/// Method identifiers in a contract
Json::Value methodIdentifiersInContract;
};
struct CompilerInput
{
CompilerInput(
langutil::EVMVersion _evmVersion,
std::string const& _sourceCode,
std::string const& _contractName,
frontend::OptimiserSettings _optimiserSettings,
std::map<std::string, solidity::util::h160> _libraryAddresses,
bool _debugFailure
):
evmVersion(_evmVersion),
sourceCode(_sourceCode),
contractName(_contractName),
optimiserSettings(_optimiserSettings),
libraryAddresses(_libraryAddresses),
debugFailure(_debugFailure)
{}
/// EVM target version
langutil::EVMVersion evmVersion;
/// Source code to be compiled
std::string const& sourceCode;
/// Contract name
std::string contractName;
/// Optimiser setting to be used during compilation
frontend::OptimiserSettings optimiserSettings;
/// Information on which library is deployed where
std::map<std::string, solidity::util::h160> libraryAddresses;
/// Flag used for debugging
bool debugFailure;
};
class SolidityCompilationFramework
{
public:
SolidityCompilationFramework(CompilerInput _input): m_compilerInput(_input)
{}
/// Sets contract name to @param _contractName.
void contractName(std::string const& _contractName)
{
m_compilerInput.contractName = _contractName;
}
/// Sets library addresses to @param _libraryAddresses.
void libraryAddresses(std::map<std::string, solidity::util::h160> _libraryAddresses)
{
m_compilerInput.libraryAddresses = std::move(_libraryAddresses);
}
/// @returns method identifiers in contract called @param _contractName.
Json::Value methodIdentifiers(std::string const& _contractName)
{
return m_compiler.methodIdentifiers(_contractName);
}
/// @returns Compilation output comprising EVM bytecode and list of
/// method identifiers in contract if compilation is successful,
/// null value otherwise.
std::optional<CompilerOutput> compileContract();
private:
frontend::CompilerStack m_compiler;
CompilerInput m_compilerInput;
};
class EvmoneUtility
{
public:
EvmoneUtility(
solidity::test::EVMHost& _evmHost,
CompilerInput _compilerInput,
std::string const& _contractName,
std::string const& _libraryName,
std::string const& _methodName
):
m_evmHost(_evmHost),
m_compilationFramework(_compilerInput),
m_contractName(_contractName),
m_libraryName(_libraryName),
m_methodName(_methodName)
{}
/// @returns the result returned by the EVM host on compiling, deploying,
/// and executing test configuration.
/// @param _isabelleData contains encoding data to be passed to the
/// isabelle test entry point.
std::optional<evmc::result> compileDeployAndExecute(std::string _isabelleData = {});
/// Compares the contents of the memory address pointed to
/// by `_result` of `_length` bytes to u256 zero.
/// @returns true if `_result` is zero, false
/// otherwise.
static bool zeroWord(uint8_t const* _result, size_t _length);
/// @returns an evmc_message with all of its fields zero
/// initialized except gas and input fields.
/// The gas field is set to the maximum permissible value so that we
/// don't run into out of gas errors. The input field is copied from
/// @param _input.
static evmc_message initializeMessage(bytes const& _input);
private:
/// @returns the result of the execution of the function whose
/// keccak256 hash is @param _functionHash that is deployed at
/// @param _deployedAddress in @param _hostContext.
evmc::result executeContract(
bytes const& _functionHash,
evmc_address _deployedAddress
);
/// @returns the result of deployment of @param _code on @param _hostContext.
evmc::result deployContract(bytes const& _code);
/// Deploys and executes EVM byte code in @param _byteCode on
/// EVM Host referenced by @param _hostContext. Input passed
/// to execution context is @param _hexEncodedInput.
/// @returns result returning by @param _hostContext.
evmc::result deployAndExecute(
bytes const& _byteCode,
std::string const& _hexEncodedInput
);
/// Compiles contract named @param _contractName present in
/// @param _sourceCode, optionally using a precompiled library
/// specified via a library mapping and an optimisation setting.
/// @returns a pair containing the generated byte code and method
/// identifiers for methods in @param _contractName.
std::optional<CompilerOutput> compileContract();
/// EVM Host implementation
solidity::test::EVMHost& m_evmHost;
/// Solidity compilation framework
SolidityCompilationFramework m_compilationFramework;
/// Contract name
std::string m_contractName;
/// Library name
std::string m_libraryName;
/// Method name
std::string m_methodName;
};
}

View File

@ -21,7 +21,7 @@
#include <libsolutil/Whiskers.h>
#include <libsolutil/Visitor.h>
using namespace solidity::test::fuzzer;
using namespace solidity::test::fuzzer::mutator;
using namespace solidity::util;
using namespace std;

View File

@ -31,7 +31,7 @@
#include <set>
#include <variant>
namespace solidity::test::fuzzer
namespace solidity::test::fuzzer::mutator
{
/// Forward declarations
class SolidityGenerator;

View File

@ -1,85 +0,0 @@
#include <test/tools/ossfuzz/abiV2FuzzerCommon.h>
#include <liblangutil/Exceptions.h>
#include <liblangutil/SourceReferenceFormatter.h>
using namespace solidity::test::abiv2fuzzer;
SolidityCompilationFramework::SolidityCompilationFramework(langutil::EVMVersion _evmVersion)
{
m_evmVersion = _evmVersion;
}
solidity::bytes SolidityCompilationFramework::compileContract(
std::string const& _sourceCode,
std::string const& _contractName,
std::map<std::string, solidity::util::h160> const& _libraryAddresses,
frontend::OptimiserSettings _optimization
)
{
std::string sourceCode = _sourceCode;
m_compiler.setSources({{"", sourceCode}});
m_compiler.setLibraries(_libraryAddresses);
m_compiler.setEVMVersion(m_evmVersion);
m_compiler.setOptimiserSettings(_optimization);
if (!m_compiler.compile())
{
langutil::SourceReferenceFormatter formatter(std::cerr, false, false);
for (auto const& error: m_compiler.errors())
formatter.printExceptionInformation(
*error,
formatter.formatErrorInformation(*error)
);
std::cerr << "Compiling contract failed" << std::endl;
}
evmasm::LinkerObject obj = m_compiler.object(
_contractName.empty() ?
m_compiler.lastContractName() :
_contractName
);
return obj.bytecode;
}
bool AbiV2Utility::isOutputExpected(
uint8_t const* _result,
size_t _length,
std::vector<uint8_t> const& _expectedOutput
)
{
if (_length != _expectedOutput.size())
return false;
return (memcmp(_result, _expectedOutput.data(), _length) == 0);
}
evmc_message AbiV2Utility::initializeMessage(bytes const& _input)
{
// Zero initialize all message fields
evmc_message msg = {};
// Gas available (value of type int64_t) is set to its maximum
// value.
msg.gas = std::numeric_limits<int64_t>::max();
msg.input_data = _input.data();
msg.input_size = _input.size();
return msg;
}
evmc::result AbiV2Utility::executeContract(
EVMHost& _hostContext,
bytes const& _functionHash,
evmc_address _deployedAddress
)
{
evmc_message message = initializeMessage(_functionHash);
message.destination = _deployedAddress;
message.kind = EVMC_CALL;
return _hostContext.call(message);
}
evmc::result AbiV2Utility::deployContract(EVMHost& _hostContext, bytes const& _code)
{
evmc_message message = initializeMessage(_code);
message.kind = EVMC_CREATE;
return _hostContext.call(message);
}

View File

@ -1,67 +0,0 @@
#pragma once
#include <test/EVMHost.h>
#include <libsolidity/interface/CompilerStack.h>
#include <libyul/AssemblyStack.h>
#include <libsolutil/Keccak256.h>
#include <evmone/evmone.h>
namespace solidity::test::abiv2fuzzer
{
class SolidityCompilationFramework
{
public:
explicit SolidityCompilationFramework(langutil::EVMVersion _evmVersion = {});
Json::Value getMethodIdentifiers()
{
return m_compiler.methodIdentifiers(m_compiler.lastContractName());
}
bytes compileContract(
std::string const& _sourceCode,
std::string const& _contractName,
std::map<std::string, solidity::util::h160> const& _libraryAddresses = {},
frontend::OptimiserSettings _optimization = frontend::OptimiserSettings::minimal()
);
protected:
frontend::CompilerStack m_compiler;
langutil::EVMVersion m_evmVersion;
};
struct AbiV2Utility
{
/// Compares the contents of the memory address pointed to
/// by `_result` of `_length` bytes to the expected output.
/// Returns true if `_result` matches expected output, false
/// otherwise.
static bool isOutputExpected(
uint8_t const* _result,
size_t _length,
std::vector<uint8_t> const& _expectedOutput
);
/// Accepts a reference to a user-specified input and returns an
/// evmc_message with all of its fields zero initialized except
/// gas and input fields.
/// The gas field is set to the maximum permissible value so that we
/// don't run into out of gas errors. The input field is copied from
/// user input.
static evmc_message initializeMessage(bytes const& _input);
/// Accepts host context implementation, and keccak256 hash of the function
/// to be called at a specified address in the simulated blockchain as
/// input and returns the result of the execution of the called function.
static evmc::result executeContract(
EVMHost& _hostContext,
bytes const& _functionHash,
evmc_address _deployedAddress
);
/// Accepts a reference to host context implementation and byte code
/// as input and deploys it on the simulated blockchain. Returns the
/// result of deployment.
static evmc::result deployContract(EVMHost& _hostContext, bytes const& _code);
};
}

View File

@ -16,13 +16,15 @@
*/
// SPDX-License-Identifier: GPL-3.0
#include <test/tools/ossfuzz/abiV2FuzzerCommon.h>
#include <test/tools/ossfuzz/SolidityEvmoneInterface.h>
#include <test/tools/ossfuzz/protoToAbiV2.h>
#include <src/libfuzzer/libfuzzer_macro.h>
#include <fstream>
using namespace solidity::frontend;
using namespace solidity::test::fuzzer;
using namespace solidity::test::abiv2fuzzer;
using namespace solidity::test;
using namespace solidity::util;
@ -30,11 +32,6 @@ using namespace solidity;
using namespace std;
static evmc::VM evmone = evmc::VM{evmc_create_evmone()};
/// Expected output value is decimal 0
static vector<uint8_t> const expectedOutput = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
DEFINE_PROTO_FUZZER(Contract const& _input)
{
@ -48,61 +45,29 @@ DEFINE_PROTO_FUZZER(Contract const& _input)
of << contract_source;
}
// Raw runtime byte code generated by solidity
bytes byteCode;
std::string hexEncodedInput;
try
{
// Compile contract generated by the proto fuzzer
SolidityCompilationFramework solCompilationFramework;
std::string contractName = ":C";
byteCode = solCompilationFramework.compileContract(contract_source, contractName);
Json::Value methodIdentifiers = solCompilationFramework.getMethodIdentifiers();
// We always call the function test() that is defined in proto converter template
hexEncodedInput = methodIdentifiers["test()"].asString();
}
// Ignore stack too deep errors during compilation
catch (evmasm::StackTooDeepException const&)
{
return;
}
// Do not ignore other compilation failures
catch (Exception const&)
{
throw;
}
if (const char* dump_path = getenv("PROTO_FUZZER_DUMP_CODE"))
{
ofstream of(dump_path);
of << toHex(byteCode);
}
// We target the default EVM which is the latest
langutil::EVMVersion version = {};
langutil::EVMVersion version;
EVMHost hostContext(version, evmone);
// Deploy contract and signal failure if deploy failed
evmc::result createResult = AbiV2Utility::deployContract(hostContext, byteCode);
solAssert(
createResult.status_code == EVMC_SUCCESS,
"Proto ABIv2 Fuzzer: Contract creation failed"
);
// Execute test function and signal failure if EVM reverted or
// did not return expected output on successful execution.
evmc::result callResult = AbiV2Utility::executeContract(
string contractName = ":C";
string methodName = "test()";
CompilerInput cInput(version, contract_source, contractName, OptimiserSettings::minimal(), {}, false);
EvmoneUtility evmoneUtil(
hostContext,
fromHex(hexEncodedInput),
createResult.create_address
cInput,
contractName,
{},
methodName
);
// We don't care about EVM One failures other than EVMC_REVERT
solAssert(callResult.status_code != EVMC_REVERT, "Proto ABIv2 fuzzer: EVM One reverted");
if (callResult.status_code == EVMC_SUCCESS)
solAssert(
AbiV2Utility::isOutputExpected(callResult.output_data, callResult.output_size, expectedOutput),
"Proto ABIv2 fuzzer: ABIv2 coding failure found"
);
// Invoke test function
auto result = evmoneUtil.compileDeployAndExecute();
if (result.has_value())
{
// We don't care about EVM One failures other than EVMC_REVERT
solAssert(result->status_code != EVMC_REVERT, "Proto ABIv2 fuzzer: EVM One reverted");
if (result->status_code == EVMC_SUCCESS)
solAssert(
EvmoneUtility::zeroWord(result->output_data, result->output_size),
"Proto ABIv2 fuzzer: ABIv2 coding failure found"
);
}
}

View File

@ -17,8 +17,9 @@
// SPDX-License-Identifier: GPL-3.0
#include <test/tools/ossfuzz/protoToSol.h>
#include <test/tools/ossfuzz/SolidityEvmoneInterface.h>
#include <test/tools/ossfuzz/solProto.pb.h>
#include <test/tools/ossfuzz/abiV2FuzzerCommon.h>
#include <test/EVMHost.h>
#include <evmone/evmone.h>
@ -28,171 +29,14 @@
static evmc::VM evmone = evmc::VM{evmc_create_evmone()};
using namespace solidity::test::abiv2fuzzer;
using namespace solidity::test::fuzzer;
using namespace solidity::test::solprotofuzzer;
using namespace solidity;
using namespace solidity::frontend;
using namespace solidity::test;
using namespace solidity::util;
using namespace std;
namespace
{
/// Test function returns a uint256 value
static size_t const expectedOutputLength = 32;
/// Expected output value is decimal 0
static uint8_t const expectedOutput[expectedOutputLength] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/// Compares the contents of the memory address pointed to
/// by `_result` of `_length` bytes to the expected output.
/// Returns true if `_result` matches expected output, false
/// otherwise.
bool isOutputExpected(evmc::result const& _run)
{
if (_run.output_size != expectedOutputLength)
return false;
return memcmp(_run.output_data, expectedOutput, expectedOutputLength) == 0;
}
/// Accepts a reference to a user-specified input and returns an
/// evmc_message with all of its fields zero initialized except
/// gas and input fields.
/// The gas field is set to the maximum permissible value so that we
/// don't run into out of gas errors. The input field is copied from
/// user input.
evmc_message initializeMessage(bytes const& _input)
{
// Zero initialize all message fields
evmc_message msg = {};
// Gas available (value of type int64_t) is set to its maximum
// value.
msg.gas = std::numeric_limits<int64_t>::max();
msg.input_data = _input.data();
msg.input_size = _input.size();
return msg;
}
/// Accepts host context implementation, and keccak256 hash of the function
/// to be called at a specified address in the simulated blockchain as
/// input and returns the result of the execution of the called function.
evmc::result executeContract(
EVMHost& _hostContext,
bytes const& _functionHash,
evmc_address _deployedAddress
)
{
evmc_message message = initializeMessage(_functionHash);
message.destination = _deployedAddress;
message.kind = EVMC_CALL;
return _hostContext.call(message);
}
/// Accepts a reference to host context implementation and byte code
/// as input and deploys it on the simulated blockchain. Returns the
/// result of deployment.
evmc::result deployContract(EVMHost& _hostContext, bytes const& _code)
{
evmc_message message = initializeMessage(_code);
message.kind = EVMC_CREATE;
return _hostContext.call(message);
}
std::pair<bytes, Json::Value> compileContract(
std::string _sourceCode,
std::string _contractName,
std::map<std::string, solidity::util::h160> const& _libraryAddresses = {},
frontend::OptimiserSettings _optimization = frontend::OptimiserSettings::minimal()
)
{
try
{
// Compile contract generated by the proto fuzzer
SolidityCompilationFramework solCompilationFramework;
return std::make_pair(
solCompilationFramework.compileContract(_sourceCode, _contractName, _libraryAddresses, _optimization),
solCompilationFramework.getMethodIdentifiers()
);
}
// Ignore stack too deep errors during compilation
catch (evmasm::StackTooDeepException const&)
{
return std::make_pair(bytes{}, Json::Value(0));
}
}
evmc::result deployAndExecute(EVMHost& _hostContext, bytes _byteCode, std::string _hexEncodedInput)
{
// Deploy contract and signal failure if deploy failed
evmc::result createResult = deployContract(_hostContext, _byteCode);
solAssert(
createResult.status_code == EVMC_SUCCESS,
"Proto solc fuzzer: Contract creation failed"
);
// Execute test function and signal failure if EVM reverted or
// did not return expected output on successful execution.
evmc::result callResult = executeContract(
_hostContext,
fromHex(_hexEncodedInput),
createResult.create_address
);
// We don't care about EVM One failures other than EVMC_REVERT
solAssert(callResult.status_code != EVMC_REVERT, "Proto solc fuzzer: EVM One reverted");
return callResult;
}
evmc::result compileDeployAndExecute(
std::string _sourceCode,
std::string _contractName,
std::string _methodName,
frontend::OptimiserSettings _optimization,
std::string _libraryName = {}
)
{
bytes libraryBytecode;
Json::Value libIds;
// We target the default EVM which is the latest
langutil::EVMVersion version = {};
EVMHost hostContext(version, evmone);
std::map<std::string, solidity::util::h160> _libraryAddressMap;
// First deploy library
if (!_libraryName.empty())
{
tie(libraryBytecode, libIds) = compileContract(
_sourceCode,
_libraryName,
{},
_optimization
);
// Deploy contract and signal failure if deploy failed
evmc::result createResult = deployContract(hostContext, libraryBytecode);
solAssert(
createResult.status_code == EVMC_SUCCESS,
"Proto solc fuzzer: Library deployment failed"
);
_libraryAddressMap[_libraryName] = EVMHost::convertFromEVMC(createResult.create_address);
}
auto [bytecode, ids] = compileContract(
_sourceCode,
_contractName,
_libraryAddressMap,
_optimization
);
return deployAndExecute(
hostContext,
bytecode,
ids[_methodName].asString()
);
}
}
DEFINE_PROTO_FUZZER(Program const& _input)
{
ProtoConverter converter;
@ -219,17 +63,28 @@ DEFINE_PROTO_FUZZER(Program const& _input)
std::cout << sol_source << std::endl;
}
auto minimalResult = compileDeployAndExecute(
sol_source,
":C",
"test()",
frontend::OptimiserSettings::minimal(),
converter.libraryTest() ? converter.libraryName() : ""
// We target the default EVM which is the latest
langutil::EVMVersion version;
EVMHost hostContext(version, evmone);
string contractName = ":C";
string libraryName = converter.libraryTest() ? converter.libraryName() : "";
string methodName = "test()";
CompilerInput cInput(version, sol_source, contractName, OptimiserSettings::minimal(), {}, false);
EvmoneUtility evmoneUtil(
hostContext,
cInput,
contractName,
libraryName,
methodName
);
bool successState = minimalResult.status_code == EVMC_SUCCESS;
if (successState)
auto minimalResult = evmoneUtil.compileDeployAndExecute();
if (minimalResult.has_value())
{
solAssert(minimalResult->status_code != EVMC_REVERT, "Sol proto fuzzer: Evmone reverted.");
if (minimalResult->status_code == EVMC_SUCCESS)
solAssert(
isOutputExpected(minimalResult),
EvmoneUtility::zeroWord(minimalResult->output_data, minimalResult->output_size),
"Proto solc fuzzer: Output incorrect"
);
}
}