-
Notifications
You must be signed in to change notification settings - Fork 12.1k
Add extra memory manipulation functions #5792
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ernestognw
wants to merge
23
commits into
OpenZeppelin:master
Choose a base branch
from
ernestognw:utils/memory-extra-functions
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
9eb5f1c
Add memory utils
ernestognw 2d397f4
Fix tests upgradeable
ernestognw 2a0fb7e
Add docs
ernestognw a7e61c3
Make use of the library
ernestognw 1aae8bb
Update docs/modules/ROOT/pages/utilities.adoc
ernestognw 1b2679a
Merge branch 'master' into utils/memory
Amxx d514606
fix tests
Amxx 14fa04e
Update contracts/utils/Memory.sol
ernestognw d0d55fc
Update contracts/utils/Memory.sol
arr00 608e3cd
Merge branch 'master' into utils/memory
ernestognw ac92bb4
up
ernestognw 6094bb7
Merge branch 'master' into utils/memory
ernestognw 6bb96d5
WIP: Add more Memory functions
ernestognw 860e5a8
up
ernestognw ecdb768
revert
ernestognw 95907aa
Update docs
ernestognw 124ccee
Nit
ernestognw c3237df
Finish fuzz tests and FV
ernestognw 27f0a9b
up
ernestognw e67e8b4
up
ernestognw 3847050
Remove extra functions
ernestognw 59f0aef
Revert "Remove extra functions"
ernestognw 7158817
Merge branch 'master' into utils/memory-extra-functions
ernestognw File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
'openzeppelin-solidity': minor | ||
--- | ||
|
||
`Memory`: Add library with utilities to manipulate memory |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
// SPDX-License-Identifier: MIT | ||
|
||
pragma solidity ^0.8.20; | ||
|
||
/** | ||
* @dev Utilities to manipulate memory. | ||
* | ||
* Memory is a contiguous and dynamic byte array in which Solidity stores non-primitive types. | ||
* This library provides functions to manipulate pointers to this dynamic array. | ||
* | ||
* WARNING: When manipulating memory, make sure to follow the Solidity documentation | ||
* guidelines for https://docs.soliditylang.org/en/v0.8.20/assembly.html#memory-safety[Memory Safety]. | ||
*/ | ||
library Memory { | ||
type Pointer is bytes32; | ||
|
||
/// @dev Returns a `Pointer` to the current free `Pointer`. | ||
function getFreeMemoryPointer() internal pure returns (Pointer ptr) { | ||
assembly ("memory-safe") { | ||
ptr := mload(0x40) | ||
} | ||
} | ||
|
||
/// @dev Sets the free `Pointer` to a specific value. | ||
/// | ||
/// WARNING: Everything after the pointer may be overwritten. | ||
function setFreeMemoryPointer(Pointer ptr) internal pure { | ||
assembly ("memory-safe") { | ||
mstore(0x40, ptr) | ||
} | ||
} | ||
|
||
/// @dev Returns a `Pointer` to the content of a `bytes` buffer. Skips the length word. | ||
function contentPointer(bytes memory buffer) internal pure returns (Pointer) { | ||
return addOffset(asPointer(buffer), 32); | ||
} | ||
|
||
/** | ||
* @dev Copies `length` bytes from `srcPtr` to `destPtr`. Equivalent to https://www.evm.codes/?fork=cancun#5e[`mcopy`]. | ||
* | ||
* WARNING: Reading or writing beyond the allocated memory bounds of either pointer | ||
* will result in undefined behavior and potential memory corruption. | ||
*/ | ||
function copy(Pointer destPtr, Pointer srcPtr, uint256 length) internal pure { | ||
assembly ("memory-safe") { | ||
mcopy(destPtr, srcPtr, length) | ||
} | ||
} | ||
|
||
/** | ||
* @dev Extracts a `bytes1` from a `Pointer`. `offset` starts from the most significant byte. | ||
* | ||
* NOTE: Will return `0x00` if `offset` is larger or equal to `32`. | ||
*/ | ||
function loadByte(Pointer ptr, uint256 offset) internal pure returns (bytes1 v) { | ||
bytes32 word = load(ptr); | ||
assembly ("memory-safe") { | ||
v := byte(offset, word) | ||
} | ||
} | ||
|
||
/// @dev Extracts a `bytes32` from a `Pointer`. | ||
function load(Pointer ptr) internal pure returns (bytes32 v) { | ||
assembly ("memory-safe") { | ||
v := mload(ptr) | ||
} | ||
} | ||
|
||
/// @dev Adds an offset to a `Pointer`. | ||
function addOffset(Pointer ptr, uint256 offset) internal pure returns (Pointer) { | ||
return asPointer(bytes32(asUint256(ptr) + offset)); | ||
} | ||
|
||
/// @dev `Pointer` to `bytes32`. Expects a pointer to a properly ABI-encoded `bytes` object. | ||
function asBytes32(Pointer ptr) internal pure returns (bytes32) { | ||
return Pointer.unwrap(ptr); | ||
} | ||
|
||
/// @dev `Pointer` to `uint256`. Expects a pointer to a properly ABI-encoded `bytes` object. | ||
function asUint256(Pointer ptr) internal pure returns (uint256) { | ||
return uint256(asBytes32(ptr)); | ||
} | ||
|
||
/// @dev `bytes32` to `Pointer`. Expects a pointer to a properly ABI-encoded `bytes` object. | ||
function asPointer(bytes32 value) internal pure returns (Pointer) { | ||
return Pointer.wrap(value); | ||
} | ||
|
||
/// @dev Returns a `Pointer` to the `value`'s header (i.e. includes the length word). | ||
function asPointer(bytes memory value) internal pure returns (Pointer) { | ||
bytes32 ptr; | ||
assembly ("memory-safe") { | ||
ptr := value | ||
} | ||
return asPointer(ptr); | ||
} | ||
|
||
/// @dev `Pointer` to `bytes`. Expects a pointer to a properly ABI-encoded `bytes` object. | ||
function asBytes(Pointer ptr) internal pure returns (bytes memory b) { | ||
assembly ("memory-safe") { | ||
b := ptr | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
// SPDX-License-Identifier: MIT | ||
|
||
pragma solidity ^0.8.20; | ||
|
||
import {Test} from "forge-std/Test.sol"; | ||
import {Memory} from "@openzeppelin/contracts/utils/Memory.sol"; | ||
|
||
contract MemoryTest is Test { | ||
using Memory for *; | ||
|
||
// - first 0x80 bytes are reserved (scratch + FMP + zero) | ||
uint256 constant START_PTR = 0x80; | ||
// - moving the free memory pointer to far causes OOG errors | ||
uint256 constant END_PTR = type(uint24).max; | ||
|
||
function testGetsetFreeMemoryPointer(uint256 seed) public pure { | ||
bytes32 ptr = bytes32(bound(seed, START_PTR, END_PTR)); | ||
ptr.asPointer().setFreeMemoryPointer(); | ||
assertEq(Memory.getFreeMemoryPointer().asBytes32(), ptr); | ||
} | ||
|
||
function testSymbolicContentPointer(uint256 seed) public pure { | ||
Memory.Pointer ptr = bytes32(bound(seed, START_PTR, END_PTR)).asPointer(); | ||
assertEq(ptr.asBytes().contentPointer().asBytes32(), ptr.addOffset(32).asBytes32()); | ||
} | ||
|
||
function testCopy(bytes memory data, uint256 destSeed) public pure { | ||
uint256 minDestPtr = Memory.getFreeMemoryPointer().asUint256(); | ||
Memory.Pointer destPtr = bytes32(bound(destSeed, minDestPtr, minDestPtr + END_PTR)).asPointer(); | ||
destPtr.addOffset(data.length + 32).setFreeMemoryPointer(); | ||
destPtr.copy(data.asPointer(), data.length + 32); | ||
bytes memory copiedData = destPtr.asBytes(); | ||
assertEq(data.length, copiedData.length); | ||
for (uint256 i = 0; i < data.length; i++) { | ||
assertEq(data[i], copiedData[i]); | ||
} | ||
} | ||
|
||
function testLoadByte(uint256 seed, uint256 index, bytes32 value) public pure { | ||
index = bound(index, 0, 31); | ||
Memory.Pointer ptr = bytes32(bound(seed, START_PTR, END_PTR)).asPointer(); | ||
|
||
assembly ("memory-safe") { | ||
mstore(ptr, value) | ||
} | ||
|
||
bytes1 expected; | ||
assembly ("memory-safe") { | ||
expected := byte(index, value) | ||
} | ||
assertEq(ptr.loadByte(index), expected); | ||
} | ||
|
||
function testLoad(uint256 seed, bytes32 value) public pure { | ||
Memory.Pointer ptr = bytes32(bound(seed, START_PTR, END_PTR)).asPointer(); | ||
assembly ("memory-safe") { | ||
mstore(ptr, value) | ||
} | ||
assertEq(ptr.load(), value); | ||
} | ||
|
||
function testSymbolicAddOffset(uint256 seed, uint256 offset) public pure { | ||
offset = bound(offset, 0, type(uint256).max - END_PTR); | ||
Memory.Pointer ptr = bytes32(bound(seed, START_PTR, END_PTR)).asPointer(); | ||
assertEq(ptr.addOffset(offset).asUint256(), ptr.asUint256() + offset); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
const { ethers } = require('hardhat'); | ||
const { expect } = require('chai'); | ||
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers'); | ||
|
||
async function fixture() { | ||
const mock = await ethers.deployContract('$Memory'); | ||
|
||
return { mock }; | ||
} | ||
|
||
describe('Memory', function () { | ||
beforeEach(async function () { | ||
Object.assign(this, await loadFixture(fixture)); | ||
}); | ||
|
||
describe('free pointer', function () { | ||
it('sets free memory pointer', async function () { | ||
const ptr = ethers.toBeHex(0xa0, 32); | ||
await expect(this.mock.$setFreeMemoryPointer(ptr)).to.not.be.reverted; | ||
}); | ||
|
||
it('gets free memory pointer', async function () { | ||
await expect(this.mock.$getFreeMemoryPointer()).to.eventually.equal( | ||
ethers.toBeHex(0x80, 32), // Default pointer | ||
); | ||
}); | ||
}); | ||
|
||
it('load extracts a word', async function () { | ||
const ptr = await this.mock.$getFreeMemoryPointer(); | ||
await expect(this.mock.$load(ptr)).to.eventually.equal(ethers.toBeHex(0, 32)); | ||
}); | ||
|
||
it('loadByte extracts a byte', async function () { | ||
const ptr = await this.mock.$getFreeMemoryPointer(); | ||
await expect(this.mock.$loadByte(ptr, 0)).to.eventually.equal(ethers.toBeHex(0, 1)); | ||
}); | ||
|
||
it('contentPointer', async function () { | ||
const data = ethers.toUtf8Bytes('hello world'); | ||
const result = await this.mock.$contentPointer(data); | ||
expect(result).to.equal(ethers.toBeHex(0xa0, 32)); // 0x80 is the default free pointer (length) | ||
}); | ||
|
||
describe('addOffset', function () { | ||
it('addOffset', async function () { | ||
const basePtr = ethers.toBeHex(0x80, 32); | ||
const offset = 32; | ||
const expectedPtr = ethers.toBeHex(0xa0, 32); | ||
|
||
await expect(this.mock.$addOffset(basePtr, offset)).to.eventually.equal(expectedPtr); | ||
}); | ||
|
||
it('addOffsetwraps around', async function () { | ||
const basePtr = ethers.toBeHex(0x80, 32); | ||
const offset = 256; | ||
const expectedPtr = ethers.toBeHex(0x180, 32); | ||
await expect(this.mock.$addOffset(basePtr, offset)).to.eventually.equal(expectedPtr); | ||
}); | ||
}); | ||
|
||
describe('pointer conversions', function () { | ||
it('asBytes32 / asPointer', async function () { | ||
const ptr = ethers.toBeHex('0x1234', 32); | ||
await expect(this.mock.$asBytes32(ptr)).to.eventually.equal(ptr); | ||
await expect(this.mock.$asPointer(ethers.Typed.bytes32(ptr))).to.eventually.equal(ptr); | ||
}); | ||
|
||
it('asBytes / asPointer', async function () { | ||
const ptr = await this.mock.$asPointer(ethers.Typed.bytes(ethers.toUtf8Bytes('hello world'))); | ||
expect(ptr).to.equal(ethers.toBeHex(0x80, 32)); // Default free pointer | ||
await expect(this.mock.$asBytes(ptr)).to.eventually.equal(ethers.toBeHex(0x20, 32)); | ||
}); | ||
|
||
it('asUint256', async function () { | ||
const value = 0x1234; | ||
const ptr = ethers.toBeHex(value, 32); | ||
await expect(this.mock.$asUint256(ptr)).to.eventually.equal(value); | ||
}); | ||
}); | ||
|
||
describe('memory operations', function () { | ||
it('copy', async function () { | ||
await expect(this.mock.$copy(ethers.toBeHex(0x80, 32), ethers.toBeHex(0xc0, 32), 32)).to.not.be.reverted; | ||
}); | ||
|
||
it('copy with zero length', async function () { | ||
await expect(this.mock.$copy(ethers.toBeHex(0x80, 32), ethers.toBeHex(0xc0, 32), 0)).to.not.be.reverted; | ||
}); | ||
}); | ||
}); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.