Browse Source

Merge pull request #1975 from LianaHus/sol_EVMExceptions

"error jump" instead of STOP instraction in case of exception
cl-refactor
chriseth 10 years ago
parent
commit
6a4632f258
  1. 32
      libevmasm/Assembly.cpp
  2. 6
      libevmasm/Assembly.h
  3. 2
      libevmasm/AssemblyItem.h
  4. 8
      libevmasm/ControlFlowGraph.cpp
  5. 8
      libsolidity/ArrayUtils.cpp
  6. 1
      libsolidity/Compiler.cpp
  7. 2
      libsolidity/CompilerContext.h
  8. 7
      libsolidity/ExpressionCompiler.cpp
  9. 5
      libsolidity/ExpressionCompiler.h
  10. 192
      test/libsolidity/SolidityCompiler.cpp
  11. 66
      test/libsolidity/SolidityEndToEndTest.cpp
  12. 41
      test/libsolidity/solidityExecutionFramework.h

32
libevmasm/Assembly.cpp

@ -127,7 +127,10 @@ ostream& Assembly::streamAsm(ostream& _out, string const& _prefix, StringMap con
_out << " PUSH \"" << m_strings.at((h256)i.data()) << "\"";
break;
case PushTag:
_out << " PUSH [tag" << dec << i.data() << "]";
if (i.data() == 0)
_out << " PUSH [ErrorTag]";
else
_out << " PUSH [tag" << dec << i.data() << "]";
break;
case PushSub:
_out << " PUSH [$" << h256(i.data()).abridged() << "]";
@ -207,8 +210,12 @@ Json::Value Assembly::streamAsmJson(ostream& _out, StringMap const& _sourceCodes
createJsonValue("PUSH tag", i.getLocation().start, i.getLocation().end, m_strings.at((h256)i.data())));
break;
case PushTag:
collection.append(
createJsonValue("PUSH [tag]", i.getLocation().start, i.getLocation().end, string(i.data())));
if (i.data() == 0)
collection.append(
createJsonValue("PUSH [ErrorTag]", i.getLocation().start, i.getLocation().end, ""));
else
collection.append(
createJsonValue("PUSH [tag]", i.getLocation().start, i.getLocation().end, string(i.data())));
break;
case PushSub:
collection.append(
@ -226,7 +233,7 @@ Json::Value Assembly::streamAsmJson(ostream& _out, StringMap const& _sourceCodes
collection.append(
createJsonValue("tag", i.getLocation().start, i.getLocation().end, string(i.data())));
collection.append(
createJsonValue("JUMDEST", i.getLocation().start, i.getLocation().end));
createJsonValue("JUMPDEST", i.getLocation().start, i.getLocation().end));
break;
case PushData:
collection.append(createJsonValue("PUSH data", i.getLocation().start, i.getLocation().end, toStringInHex(i.data())));
@ -387,6 +394,11 @@ bytes Assembly::assemble() const
// m_data must not change from here on
for (AssemblyItem const& i: m_items)
{
// store position of the invalid jump destination
if (i.type() != Tag && tagPos[0] == 0)
tagPos[0] = ret.size();
switch (i.type())
{
case Operation:
@ -448,17 +460,23 @@ bytes Assembly::assemble() const
}
case Tag:
tagPos[(unsigned)i.data()] = ret.size();
assertThrow(i.data() != 0, AssemblyException, "");
ret.push_back((byte)Instruction::JUMPDEST);
break;
default:
BOOST_THROW_EXCEPTION(InvalidOpcode());
}
}
for (auto const& i: tagRef)
{
bytesRef r(ret.data() + i.first, bytesPerTag);
//@todo in the failure case, we could use the position of the invalid jumpdest
toBigEndian(i.second < tagPos.size() ? tagPos[i.second] : (1 << (8 * bytesPerTag)) - 1, r);
auto tag = i.second;
if (tag >= tagPos.size())
tag = 0;
if (tag == 0)
assertThrow(tagPos[tag] != 0, AssemblyException, "");
toBigEndian(tagPos[tag], r);
}
if (!m_data.empty())

6
libevmasm/Assembly.h

@ -67,6 +67,8 @@ public:
AssemblyItem appendJumpI() { auto ret = append(newPushTag()); append(Instruction::JUMPI); return ret; }
AssemblyItem appendJump(AssemblyItem const& _tag) { auto ret = append(_tag.pushTag()); append(Instruction::JUMP); return ret; }
AssemblyItem appendJumpI(AssemblyItem const& _tag) { auto ret = append(_tag.pushTag()); append(Instruction::JUMPI); return ret; }
AssemblyItem errorTag() { return AssemblyItem(PushTag, 0); }
template <class T> Assembly& operator<<(T const& _d) { append(_d); return *this; }
AssemblyItems const& getItems() const { return m_items; }
AssemblyItem const& back() const { return m_items.back(); }
@ -97,7 +99,6 @@ public:
const StringMap &_sourceCodes = StringMap(),
bool _inJsonFormat = false
) const;
protected:
std::string getLocationFromSources(StringMap const& _sourceCodes, SourceLocation const& _location) const;
void donePath() { if (m_totalDeposit != INT_MAX && m_totalDeposit != m_deposit) BOOST_THROW_EXCEPTION(InvalidDeposit()); }
@ -109,7 +110,8 @@ private:
Json::Value createJsonValue(std::string _name, int _begin, int _end, std::string _value = std::string(), std::string _jumpType = std::string()) const;
protected:
unsigned m_usedTags = 0;
// 0 is reserved for exception
unsigned m_usedTags = 1;
AssemblyItems m_items;
mutable std::map<h256, bytes> m_data;
std::vector<Assembly> m_subs;

2
libevmasm/AssemblyItem.h

@ -65,7 +65,7 @@ public:
/// @returns the instruction of this item (only valid if type() == Operation)
Instruction instruction() const { return Instruction(byte(m_data)); }
/// @returns true iff the type and data of the items are equal.
/// @returns true if the type and data of the items are equal.
bool operator==(AssemblyItem const& _other) const { return m_type == _other.m_type && m_data == _other.m_data; }
bool operator!=(AssemblyItem const& _other) const { return !operator==(_other); }
/// Less-than operator compatible with operator==.

8
libevmasm/ControlFlowGraph.cpp

@ -226,7 +226,10 @@ void ControlFlowGraph::gatherKnowledge()
//@todo we might have to do something like incrementing the sequence number for each JUMPDEST
assertThrow(!!workQueue.back().first, OptimizerException, "");
if (!m_blocks.count(workQueue.back().first))
{
workQueue.pop_back();
continue; // too bad, we do not know the tag, probably an invalid jump
}
BasicBlock& block = m_blocks.at(workQueue.back().first);
KnownStatePointer state = workQueue.back().second;
workQueue.pop_back();
@ -257,10 +260,7 @@ void ControlFlowGraph::gatherKnowledge()
);
state->feedItem(m_items.at(pc++));
if (tags.empty() || std::any_of(tags.begin(), tags.end(), [&](u256 const& _tag)
{
return !m_blocks.count(BlockId(_tag));
}))
if (tags.empty())
{
if (!unknownJumpEncountered)
{

8
libsolidity/ArrayUtils.cpp

@ -465,12 +465,10 @@ void ArrayUtils::accessIndex(ArrayType const& _arrayType) const
m_context << eth::Instruction::DUP2 << load;
// stack: <base_ref> <index> <length>
// check out-of-bounds access
m_context << eth::Instruction::DUP2 << eth::Instruction::LT;
eth::AssemblyItem legalAccess = m_context.appendConditionalJump();
// out-of-bounds access throws exception (just STOP for now)
m_context << eth::Instruction::STOP;
m_context << eth::Instruction::DUP2 << eth::Instruction::LT << eth::Instruction::ISZERO;
// out-of-bounds access throws exception
m_context.appendConditionalJumpTo(m_context.errorTag());
m_context << legalAccess;
// stack: <base_ref> <index>
m_context << eth::Instruction::SWAP1;
if (_arrayType.isDynamicallySized())

1
libsolidity/Compiler.cpp

@ -194,7 +194,6 @@ void Compiler::appendFunctionSelector(ContractDefinition const& _contract)
}
else
m_context << eth::Instruction::STOP; // function not found
for (auto const& it: interfaceFunctions)
{
FunctionTypePointer const& functionType = it.second;

2
libsolidity/CompilerContext.h

@ -98,6 +98,8 @@ public:
eth::AssemblyItem appendJumpToNew() { return m_asm.appendJump().tag(); }
/// Appends a JUMP to a tag already on the stack
CompilerContext& appendJump(eth::AssemblyItem::JumpType _jumpType = eth::AssemblyItem::JumpType::Ordinary);
/// Returns an "ErrorTag"
eth::AssemblyItem errorTag() { return m_asm.errorTag(); }
/// Appends a JUMP to a specific tag
CompilerContext& appendJumpTo(eth::AssemblyItem const& _tag) { m_asm.appendJump(_tag); return *this; }
/// Appends pushing of a new tag and @returns the new tag.

7
libsolidity/ExpressionCompiler.cpp

@ -1106,8 +1106,11 @@ void ExpressionCompiler::appendExternalFunctionCall(
m_context << eth::Instruction::CALLCODE;
else
m_context << eth::Instruction::CALL;
auto tag = m_context.appendConditionalJump();
m_context << eth::Instruction::STOP << tag; // STOP if CALL leaves 0.
//Propagate error condition (if CALL pushes 0 on stack).
m_context << eth::Instruction::ISZERO;
m_context.appendConditionalJumpTo(m_context.errorTag());
if (_functionType.valueSet())
m_context << eth::Instruction::POP;
if (_functionType.gasSet())

5
libsolidity/ExpressionCompiler.h

@ -98,10 +98,7 @@ private:
void appendHighBitsCleanup(IntegerType const& _typeOnStack);
/// Appends code to call a function of the given type with the given arguments.
void appendExternalFunctionCall(
FunctionType const& _functionType,
std::vector<ASTPointer<Expression const>> const& _arguments
);
void appendExternalFunctionCall(FunctionType const& _functionType, std::vector<ASTPointer<Expression const>> const& _arguments);
/// Appends code that evaluates the given arguments and moves the result to memory encoded as
/// specified by the ABI. The memory offset is expected to be on the stack and is updated by
/// this call. If @a _padToWordBoundaries is set to false, all values are concatenated without

192
test/libsolidity/SolidityCompiler.cpp

@ -1,192 +0,0 @@
/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <c@ethdev.com>
* @date 2014
* Unit tests for the solidity compiler.
*/
#include <string>
#include <iostream>
#include <boost/test/unit_test.hpp>
#include <libdevcore/Log.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Compiler.h>
#include <libsolidity/AST.h>
using namespace std;
using namespace dev::eth;
namespace dev
{
namespace solidity
{
namespace test
{
namespace
{
bytes compileContract(const string& _sourceCode)
{
Parser parser;
ASTPointer<SourceUnit> sourceUnit;
BOOST_REQUIRE_NO_THROW(sourceUnit = parser.parse(make_shared<Scanner>(CharStream(_sourceCode))));
NameAndTypeResolver resolver({});
resolver.registerDeclarations(*sourceUnit);
for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{
BOOST_REQUIRE_NO_THROW(resolver.resolveNamesAndTypes(*contract));
}
for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{
BOOST_REQUIRE_NO_THROW(resolver.checkTypeRequirements(*contract));
}
for (ASTPointer<ASTNode> const& node: sourceUnit->getNodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{
Compiler compiler;
compiler.compileContract(*contract, map<ContractDefinition const*, bytes const*>{});
// debug
//compiler.streamAssembly(cout);
return compiler.getAssembledBytecode();
}
BOOST_FAIL("No contract found in source.");
return bytes();
}
/// Checks that @a _compiledCode is present starting from offset @a _offset in @a _expectation.
/// This is necessary since the compiler will add boilerplate add the beginning that is not
/// tested here.
void checkCodePresentAt(bytes const& _compiledCode, bytes const& _expectation, unsigned _offset)
{
BOOST_REQUIRE(_compiledCode.size() >= _offset + _expectation.size());
auto checkStart = _compiledCode.begin() + _offset;
BOOST_CHECK_EQUAL_COLLECTIONS(checkStart, checkStart + _expectation.size(),
_expectation.begin(), _expectation.end());
}
} // end anonymous namespace
BOOST_AUTO_TEST_SUITE(SolidityCompiler)
BOOST_AUTO_TEST_CASE(smoke_test)
{
char const* sourceCode = "contract test {\n"
" function f() { var x = 2; }\n"
"}\n";
bytes code = compileContract(sourceCode);
unsigned boilerplateSize = 73;
bytes expectation({byte(Instruction::JUMPDEST),
byte(Instruction::PUSH1), 0x0, // initialize local variable x
byte(Instruction::PUSH1), 0x2,
byte(Instruction::SWAP1),
byte(Instruction::POP),
byte(Instruction::JUMPDEST),
byte(Instruction::POP),
byte(Instruction::JUMP)});
checkCodePresentAt(code, expectation, boilerplateSize);
}
BOOST_AUTO_TEST_CASE(ifStatement)
{
char const* sourceCode = "contract test {\n"
" function f() { bool x; if (x) 77; else if (!x) 78; else 79; }"
"}\n";
bytes code = compileContract(sourceCode);
unsigned shift = 60;
unsigned boilerplateSize = 73;
bytes expectation({
byte(Instruction::JUMPDEST),
byte(Instruction::PUSH1), 0x0,
byte(Instruction::DUP1),
byte(Instruction::ISZERO),
byte(Instruction::PUSH1), byte(0x0f + shift), // "false" target
byte(Instruction::JUMPI),
// "if" body
byte(Instruction::PUSH1), 0x4d,
byte(Instruction::POP),
byte(Instruction::PUSH1), byte(0x21 + shift),
byte(Instruction::JUMP),
// new check "else if" condition
byte(Instruction::JUMPDEST),
byte(Instruction::DUP1),
byte(Instruction::ISZERO),
byte(Instruction::ISZERO),
byte(Instruction::PUSH1), byte(0x1c + shift),
byte(Instruction::JUMPI),
// "else if" body
byte(Instruction::PUSH1), 0x4e,
byte(Instruction::POP),
byte(Instruction::PUSH1), byte(0x20 + shift),
byte(Instruction::JUMP),
// "else" body
byte(Instruction::JUMPDEST),
byte(Instruction::PUSH1), 0x4f,
byte(Instruction::POP),
});
checkCodePresentAt(code, expectation, boilerplateSize);
}
BOOST_AUTO_TEST_CASE(loops)
{
char const* sourceCode = "contract test {\n"
" function f() { while(true){1;break;2;continue;3;return;4;} }"
"}\n";
bytes code = compileContract(sourceCode);
unsigned shift = 60;
unsigned boilerplateSize = 73;
bytes expectation({byte(Instruction::JUMPDEST),
byte(Instruction::JUMPDEST),
byte(Instruction::PUSH1), 0x1,
byte(Instruction::ISZERO),
byte(Instruction::PUSH1), byte(0x21 + shift),
byte(Instruction::JUMPI),
byte(Instruction::PUSH1), 0x1,
byte(Instruction::POP),
byte(Instruction::PUSH1), byte(0x21 + shift),
byte(Instruction::JUMP), // break
byte(Instruction::PUSH1), 0x2,
byte(Instruction::POP),
byte(Instruction::PUSH1), byte(0x2 + shift),
byte(Instruction::JUMP), // continue
byte(Instruction::PUSH1), 0x3,
byte(Instruction::POP),
byte(Instruction::PUSH1), byte(0x22 + shift),
byte(Instruction::JUMP), // return
byte(Instruction::PUSH1), 0x4,
byte(Instruction::POP),
byte(Instruction::PUSH1), byte(0x2 + shift),
byte(Instruction::JUMP),
byte(Instruction::JUMPDEST),
byte(Instruction::JUMPDEST),
byte(Instruction::JUMP)});
checkCodePresentAt(code, expectation, boilerplateSize);
}
BOOST_AUTO_TEST_SUITE_END()
}
}
} // end namespaces

66
test/libsolidity/SolidityEndToEndTest.cpp

@ -4080,7 +4080,6 @@ BOOST_AUTO_TEST_CASE(struct_delete_member)
}
)";
compileAndRun(sourceCode, 0, "test");
auto res = callContractFunction("deleteMember()");
BOOST_CHECK(callContractFunction("deleteMember()") == encodeArgs(0));
}
@ -4106,10 +4105,73 @@ BOOST_AUTO_TEST_CASE(struct_delete_struct_in_mapping)
}
)";
compileAndRun(sourceCode, 0, "test");
auto res = callContractFunction("deleteIt()");
BOOST_CHECK(callContractFunction("deleteIt()") == encodeArgs(0));
}
BOOST_AUTO_TEST_CASE(evm_exceptions_out_of_band_access)
{
char const* sourceCode = R"(
contract A {
uint[3] arr;
bool public test = false;
function getElement(uint i) returns (uint)
{
return arr[i];
}
function testIt() returns (bool)
{
uint i = this.getElement(5);
test = true;
return true;
}
}
)";
compileAndRun(sourceCode, 0, "A");
BOOST_CHECK(callContractFunction("test()") == encodeArgs(false));
BOOST_CHECK(callContractFunction("testIt()") == encodeArgs());
BOOST_CHECK(callContractFunction("test()") == encodeArgs(false));
}
BOOST_AUTO_TEST_CASE(evm_exceptions_in_constructor_call_fail)
{
char const* sourceCode = R"(
contract A {
function A()
{
this.call("123");
}
}
contract B {
uint public test = 1;
function testIt()
{
A a = new A();
++test;
}
}
)";
compileAndRun(sourceCode, 0, "B");
BOOST_CHECK(callContractFunction("testIt()") == encodeArgs());
BOOST_CHECK(callContractFunction("test()") == encodeArgs(2));
}
BOOST_AUTO_TEST_CASE(evm_exceptions_in_constructor_out_of_baund)
{
char const* sourceCode = R"(
contract A {
uint public test = 1;
uint[3] arr;
function A()
{
test = arr[5];
++test;
}
}
)";
BOOST_CHECK(compileAndRunWthoutCheck(sourceCode, 0, "A").empty());
}
BOOST_AUTO_TEST_SUITE_END()
}

41
test/libsolidity/solidityExecutionFramework.h

@ -42,21 +42,25 @@ class ExecutionFramework
public:
ExecutionFramework() { g_logVerbosity = 0; }
bytes const& compileAndRun(std::string const& _sourceCode, u256 const& _value = 0, std::string const& _contractName = "")
bytes const& compileAndRunWthoutCheck(std::string const& _sourceCode, u256 const& _value = 0, std::string const& _contractName = "")
{
m_compiler.reset(false, m_addStandardSources);
m_compiler.addSource("", _sourceCode);
ETH_TEST_REQUIRE_NO_THROW(m_compiler.compile(m_optimize), "Compiling contract failed");
bytes code = m_compiler.getBytecode(_contractName);
sendMessage(code, true, _value);
return m_output;
}
bytes const& compileAndRun(std::string const& _sourceCode, u256 const& _value = 0, std::string const& _contractName = "")
{
compileAndRunWthoutCheck(_sourceCode, _value, _contractName);
BOOST_REQUIRE(!m_output.empty());
return m_output;
}
template <class... Args>
bytes const& callContractFunctionWithValue(std::string _sig, u256 const& _value,
Args const&... _arguments)
bytes const& callContractFunctionWithValue(std::string _sig, u256 const& _value, Args const&... _arguments)
{
FixedHash<4> hash(dev::sha3(_sig));
sendMessage(hash.asBytes() + encodeArgs(_arguments...), false, _value);
@ -74,21 +78,30 @@ public:
{
bytes solidityResult = callContractFunction(_sig, _arguments...);
bytes cppResult = callCppAndEncodeResult(_cppFunction, _arguments...);
BOOST_CHECK_MESSAGE(solidityResult == cppResult, "Computed values do not match."
"\nSolidity: " + toHex(solidityResult) + "\nC++: " + toHex(cppResult));
BOOST_CHECK_MESSAGE(
solidityResult == cppResult,
"Computed values do not match.\nSolidity: " +
toHex(solidityResult) +
"\nC++: " +
toHex(cppResult));
}
template <class CppFunction, class... Args>
void testSolidityAgainstCppOnRange(std::string _sig, CppFunction const& _cppFunction,
u256 const& _rangeStart, u256 const& _rangeEnd)
void testSolidityAgainstCppOnRange(std::string _sig, CppFunction const& _cppFunction, u256 const& _rangeStart, u256 const& _rangeEnd)
{
for (u256 argument = _rangeStart; argument < _rangeEnd; ++argument)
{
bytes solidityResult = callContractFunction(_sig, argument);
bytes cppResult = callCppAndEncodeResult(_cppFunction, argument);
BOOST_CHECK_MESSAGE(solidityResult == cppResult, "Computed values do not match."
"\nSolidity: " + toHex(solidityResult) + "\nC++: " + toHex(cppResult) +
"\nArgument: " + toHex(encode(argument)));
BOOST_CHECK_MESSAGE(
solidityResult == cppResult,
"Computed values do not match.\nSolidity: " +
toHex(solidityResult) +
"\nC++: " +
toHex(cppResult) +
"\nArgument: " +
toHex(encode(argument))
);
}
}
@ -135,8 +148,10 @@ protected:
{
m_state.addBalance(m_sender, _value); // just in case
eth::Executive executive(m_state, eth::LastHashes(), 0);
eth::Transaction t = _isCreation ? eth::Transaction(_value, m_gasPrice, m_gas, _data, 0, KeyPair::create().sec())
: eth::Transaction(_value, m_gasPrice, m_gas, m_contractAddress, _data, 0, KeyPair::create().sec());
eth::Transaction t =
_isCreation ?
eth::Transaction(_value, m_gasPrice, m_gas, _data, 0, KeyPair::create().sec()) :
eth::Transaction(_value, m_gasPrice, m_gas, m_contractAddress, _data, 0, KeyPair::create().sec());
bytes transactionRLP = t.rlp();
try
{

Loading…
Cancel
Save