Skip to content

Commit

Permalink
Fix RLPWriter Memory Allocation (#84)
Browse files Browse the repository at this point in the history
* add failing test case with this issue

* add _malloc which works

* malloc words not bytes
  • Loading branch information
ben-chain authored Dec 3, 2020
1 parent 8e116f2 commit 7c2a09a
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ library Lib_RLPWriter {
bytes memory _out
)
{
_malloc(0x20);
bytes memory inputBytes;
assembly {
let m := mload(0x40)
Expand Down Expand Up @@ -308,4 +309,22 @@ library Lib_RLPWriter {

return flattened;
}

/**
* Clears memory wherever the free memory is pointing.
* @param _numBytes Number of bytes to clear out (will be rounded up to nearest word).
*/
function _malloc(
uint _numBytes
)
private
pure
{
assembly {
let free_mem := mload(0x40)
for { let offset := 0x00 } lt(offset, _numBytes) { offset := add(offset, 0x20) } {
mstore(add(free_mem, offset), 0x00)
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pragma experimental ABIEncoderV2;

/* Library Imports */
import { Lib_RLPWriter } from "../../optimistic-ethereum/libraries/rlp/Lib_RLPWriter.sol";
import { TestERC20 } from "../../test-helpers/TestERC20.sol";

/**
* @title TestLib_RLPWriter
Expand Down Expand Up @@ -93,4 +94,16 @@ contract TestLib_RLPWriter {
{
return Lib_RLPWriter.writeBool(_in);
}

function writeAddressWithOtherMemory(
address _in
)
public
returns (
bytes memory _out
)
{
new TestERC20();
return Lib_RLPWriter.writeAddress(_in);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,13 @@ describe('Lib_RLPWriter', () => {
})
}
})

describe.only('Use of library with other memory-modifying operations', () => {
it('should allow creation of a contract beforehand and still work', async () => {
const randomAddress = '0x1234123412341234123412341234123412341234'
const rlpEncodedRandomAddress = '0x941234123412341234123412341234123412341234'
const encoded = await Lib_RLPWriter.callStatic.writeAddressWithOtherMemory(randomAddress)
expect(encoded).to.eq(rlpEncodedRandomAddress)
})
})
})

0 comments on commit 7c2a09a

Please sign in to comment.