/*
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 .
*/
// SPDX-License-Identifier: GPL-3.0
/**
* @author Christian
* @date 2015
* Code generation utils that handle arrays.
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
using namespace solidity;
using namespace solidity::evmasm;
using namespace solidity::frontend;
using namespace solidity::langutil;
void ArrayUtils::copyArrayToStorage(ArrayType const& _targetType, ArrayType const& _sourceType) const
{
// this copies source to target and also clears target if it was larger
// need to leave "target_ref target_byte_off" on the stack at the end
// stack layout: [source_ref] [source length] target_ref (top)
solAssert(_targetType.location() == DataLocation::Storage, "");
Type const* targetBaseType = _targetType.baseType();
Type const* sourceBaseType = _sourceType.baseType();
// TODO unroll loop for small sizes
bool sourceIsStorage = _sourceType.location() == DataLocation::Storage;
bool fromCalldata = _sourceType.location() == DataLocation::CallData;
bool directCopy = sourceIsStorage && sourceBaseType->isValueType() && *sourceBaseType == *targetBaseType;
bool haveByteOffsetSource = !directCopy && sourceIsStorage && sourceBaseType->storageBytes() <= 16;
bool haveByteOffsetTarget = !directCopy && targetBaseType->storageBytes() <= 16;
unsigned byteOffsetSize = (haveByteOffsetSource ? 1u : 0u) + (haveByteOffsetTarget ? 1u : 0u);
// stack: source_ref [source_length] target_ref
// store target_ref
for (unsigned i = _sourceType.sizeOnStack(); i > 0; --i)
m_context << swapInstruction(i);
// stack: target_ref source_ref [source_length]
if (_targetType.isByteArrayOrString())
{
// stack: target_ref source_ref [source_length]
if (fromCalldata && _sourceType.isDynamicallySized())
{
// stack: target_ref source_ref source_length
m_context << Instruction::SWAP1;
// stack: target_ref source_length source_ref
m_context << Instruction::DUP3;
// stack: target_ref source_length source_ref target_ref
m_context.callYulFunction(
m_context.utilFunctions().copyByteArrayToStorageFunction(_sourceType, _targetType),
3,
0
);
}
else
{
// stack: target_ref source_ref
m_context << Instruction::DUP2;
// stack: target_ref source_ref target_ref
m_context.callYulFunction(
m_context.utilFunctions().copyByteArrayToStorageFunction(_sourceType, _targetType),
2,
0
);
}
// stack: target_ref
return;
}
// retrieve source length
if (_sourceType.location() != DataLocation::CallData || !_sourceType.isDynamicallySized())
retrieveLength(_sourceType); // otherwise, length is already there
if (_sourceType.location() == DataLocation::Memory && _sourceType.isDynamicallySized())
{
// increment source pointer to point to data
m_context << Instruction::SWAP1 << u256(0x20);
m_context << Instruction::ADD << Instruction::SWAP1;
}
// stack: target_ref source_ref source_length
Type const* targetType = &_targetType;
Type const* sourceType = &_sourceType;
m_context.callLowLevelFunction(
"$copyArrayToStorage_" + sourceType->identifier() + "_to_" + targetType->identifier(),
3,
1,
[=](CompilerContext& _context)
{
ArrayUtils utils(_context);
ArrayType const& _sourceType = dynamic_cast(*sourceType);
ArrayType const& _targetType = dynamic_cast(*targetType);
// stack: target_ref source_ref source_length
_context << Instruction::DUP3;
// stack: target_ref source_ref source_length target_ref
utils.retrieveLength(_targetType);
// stack: target_ref source_ref source_length target_ref target_length
if (_targetType.isDynamicallySized())
{
// store new target length
solAssert(!_targetType.isByteArrayOrString());
_context << Instruction::DUP3 << Instruction::DUP3 << Instruction::SSTORE;
}
if (sourceBaseType->category() == Type::Category::Mapping)
{
solAssert(targetBaseType->category() == Type::Category::Mapping, "");
solAssert(_sourceType.location() == DataLocation::Storage, "");
// nothing to copy
_context
<< Instruction::POP << Instruction::POP
<< Instruction::POP << Instruction::POP;
return;
}
// stack: target_ref source_ref source_length target_ref target_length
// compute hashes (data positions)
_context << Instruction::SWAP1;
if (_targetType.isDynamicallySized())
CompilerUtils(_context).computeHashStatic();
// stack: target_ref source_ref source_length target_length target_data_pos
_context << Instruction::SWAP1;
utils.convertLengthToSize(_targetType);
_context << Instruction::DUP2 << Instruction::ADD;
// stack: target_ref source_ref source_length target_data_pos target_data_end
_context << Instruction::SWAP3;
// stack: target_ref target_data_end source_length target_data_pos source_ref
evmasm::AssemblyItem copyLoopEndWithoutByteOffset = _context.newTag();
solAssert(!_targetType.isByteArrayOrString());
// skip copying if source length is zero
_context << Instruction::DUP3 << Instruction::ISZERO;
_context.appendConditionalJumpTo(copyLoopEndWithoutByteOffset);
if (_sourceType.location() == DataLocation::Storage && _sourceType.isDynamicallySized())
CompilerUtils(_context).computeHashStatic();
// stack: target_ref target_data_end source_length target_data_pos source_data_pos
_context << Instruction::SWAP2;
utils.convertLengthToSize(_sourceType);
_context << Instruction::DUP3 << Instruction::ADD;
// stack: target_ref target_data_end source_data_pos target_data_pos source_data_end
if (haveByteOffsetTarget)
_context << u256(0);
if (haveByteOffsetSource)
_context << u256(0);
// stack: target_ref target_data_end source_data_pos target_data_pos source_data_end [target_byte_offset] [source_byte_offset]
evmasm::AssemblyItem copyLoopStart = _context.newTag();
_context << copyLoopStart;
// check for loop condition
_context
<< dupInstruction(3 + byteOffsetSize) << dupInstruction(2 + byteOffsetSize)
<< Instruction::GT << Instruction::ISZERO;
evmasm::AssemblyItem copyLoopEnd = _context.appendConditionalJump();
// stack: target_ref target_data_end source_data_pos target_data_pos source_data_end [target_byte_offset] [source_byte_offset]
// copy
if (sourceBaseType->category() == Type::Category::Array)
{
solAssert(byteOffsetSize == 0, "Byte offset for array as base type.");
auto const& sourceBaseArrayType = dynamic_cast(*sourceBaseType);
solUnimplementedAssert(
_sourceType.location() != DataLocation::CallData ||
!_sourceType.isDynamicallyEncoded() ||
!sourceBaseArrayType.isDynamicallySized(),
"Copying nested calldata dynamic arrays to storage is not implemented in the old code generator."
);
_context << Instruction::DUP3;
if (sourceBaseArrayType.location() == DataLocation::Memory)
_context << Instruction::MLOAD;
_context << Instruction::DUP3;
utils.copyArrayToStorage(dynamic_cast(*targetBaseType), sourceBaseArrayType);
_context << Instruction::POP;
}
else if (directCopy)
{
solAssert(byteOffsetSize == 0, "Byte offset for direct copy.");
_context
<< Instruction::DUP3 << Instruction::SLOAD
<< Instruction::DUP3 << Instruction::SSTORE;
}
else
{
// Note that we have to copy each element on its own in case conversion is involved.
// We might copy too much if there is padding at the last element, but this way end
// checking is easier.
// stack: target_ref target_data_end source_data_pos target_data_pos source_data_end [target_byte_offset] [source_byte_offset]
_context << dupInstruction(3 + byteOffsetSize);
if (_sourceType.location() == DataLocation::Storage)
{
if (haveByteOffsetSource)
_context << Instruction::DUP2;
else
_context << u256(0);
StorageItem(_context, *sourceBaseType).retrieveValue(SourceLocation(), true);
}
else if (sourceBaseType->isValueType())
CompilerUtils(_context).loadFromMemoryDynamic(*sourceBaseType, fromCalldata, true, false);
else
solUnimplemented("Copying of type " + _sourceType.toString(false) + " to storage not yet supported.");
// stack: target_ref target_data_end source_data_pos target_data_pos source_data_end [target_byte_offset] [source_byte_offset] ...
assertThrow(
2 + byteOffsetSize + sourceBaseType->sizeOnStack() <= 16,
StackTooDeepError,
util::stackTooDeepString
);
// fetch target storage reference
_context << dupInstruction(2 + byteOffsetSize + sourceBaseType->sizeOnStack());
if (haveByteOffsetTarget)
_context << dupInstruction(1 + byteOffsetSize + sourceBaseType->sizeOnStack());
else
_context << u256(0);
StorageItem(_context, *targetBaseType).storeValue(*sourceBaseType, SourceLocation(), true);
}
// stack: target_ref target_data_end source_data_pos target_data_pos source_data_end [target_byte_offset] [source_byte_offset]
// increment source
if (haveByteOffsetSource)
utils.incrementByteOffset(sourceBaseType->storageBytes(), 1, haveByteOffsetTarget ? 5 : 4);
else
{
_context << swapInstruction(2 + byteOffsetSize);
if (sourceIsStorage)
_context << sourceBaseType->storageSize();
else if (_sourceType.location() == DataLocation::Memory)
_context << sourceBaseType->memoryHeadSize();
else
_context << sourceBaseType->calldataHeadSize();
_context
<< Instruction::ADD
<< swapInstruction(2 + byteOffsetSize);
}
// increment target
if (haveByteOffsetTarget)
utils.incrementByteOffset(targetBaseType->storageBytes(), byteOffsetSize, byteOffsetSize + 2);
else
_context
<< swapInstruction(1 + byteOffsetSize)
<< targetBaseType->storageSize()
<< Instruction::ADD
<< swapInstruction(1 + byteOffsetSize);
_context.appendJumpTo(copyLoopStart);
_context << copyLoopEnd;
if (haveByteOffsetTarget)
{
// clear elements that might be left over in the current slot in target
// stack: target_ref target_data_end source_data_pos target_data_pos source_data_end target_byte_offset [source_byte_offset]
_context << dupInstruction(byteOffsetSize) << Instruction::ISZERO;
evmasm::AssemblyItem copyCleanupLoopEnd = _context.appendConditionalJump();
_context << dupInstruction(2 + byteOffsetSize) << dupInstruction(1 + byteOffsetSize);
StorageItem(_context, *targetBaseType).setToZero(SourceLocation(), true);
utils.incrementByteOffset(targetBaseType->storageBytes(), byteOffsetSize, byteOffsetSize + 2);
_context.appendJumpTo(copyLoopEnd);
_context << copyCleanupLoopEnd;
_context << Instruction::POP; // might pop the source, but then target is popped next
}
if (haveByteOffsetSource)
_context << Instruction::POP;
_context << copyLoopEndWithoutByteOffset;
// zero-out leftovers in target
// stack: target_ref target_data_end source_data_pos target_data_pos_updated source_data_end
_context << Instruction::POP << Instruction::SWAP1 << Instruction::POP;
// stack: target_ref target_data_end target_data_pos_updated
if (targetBaseType->storageBytes() < 32)
utils.clearStorageLoop(TypeProvider::uint256());
else
utils.clearStorageLoop(targetBaseType);
_context << Instruction::POP;
}
);
}
void ArrayUtils::copyArrayToMemory(ArrayType const& _sourceType, bool _padToWordBoundaries) const
{
solUnimplementedAssert(
!_sourceType.baseType()->isDynamicallySized(),
"Nested dynamic arrays not implemented here."
);
CompilerUtils utils(m_context);
if (_sourceType.location() == DataLocation::CallData)
{
if (!_sourceType.isDynamicallySized())
m_context << _sourceType.length();
if (!_sourceType.isByteArrayOrString())
convertLengthToSize(_sourceType);
string routine = "calldatacopy(target, source, len)\n";
if (_padToWordBoundaries)
routine += R"(
// Set padding suffix to zero
mstore(add(target, len), 0)
len := and(add(len, 0x1f), not(0x1f))
)";
routine += "target := add(target, len)\n";
m_context.appendInlineAssembly("{" + routine + "}", {"target", "source", "len"});
m_context << Instruction::POP << Instruction::POP;
}
else if (_sourceType.location() == DataLocation::Memory)
{
retrieveLength(_sourceType);
// stack: target source length
if (!_sourceType.baseType()->isValueType())
{
// copy using a loop
m_context << u256(0) << Instruction::SWAP3;
// stack: counter source length target
auto repeat = m_context.newTag();
m_context << repeat;
m_context << Instruction::DUP2 << Instruction::DUP5;
m_context << Instruction::LT << Instruction::ISZERO;
auto loopEnd = m_context.appendConditionalJump();
m_context << Instruction::DUP3 << Instruction::DUP5;
accessIndex(_sourceType, false);
MemoryItem(m_context, *_sourceType.baseType(), true).retrieveValue(SourceLocation(), true);
if (auto baseArray = dynamic_cast(_sourceType.baseType()))
copyArrayToMemory(*baseArray, _padToWordBoundaries);
else
utils.storeInMemoryDynamic(*_sourceType.baseType());
m_context << Instruction::SWAP3 << u256(1) << Instruction::ADD;
m_context << Instruction::SWAP3;
m_context.appendJumpTo(repeat);
m_context << loopEnd;
m_context << Instruction::SWAP3;
utils.popStackSlots(3);
// stack: updated_target_pos
return;
}
// memcpy using the built-in contract
if (_sourceType.isDynamicallySized())
{
// change pointer to data part
m_context << Instruction::SWAP1 << u256(32) << Instruction::ADD;
m_context << Instruction::SWAP1;
}
if (!_sourceType.isByteArrayOrString())
convertLengthToSize(_sourceType);
// stack: