Compare commits

...

48 Commits

Author SHA1 Message Date
alvicsam 199b6145f2 try parity runner 2024-10-25 09:51:09 +02:00
Alexander Samusev 36f9345c22 Update .github/Dockerfile-llvm
Co-authored-by: Alexander Theißen <alex.theissen@me.com>
2024-10-25 09:49:13 +02:00
Evgeny Snitko 33d589ea7f COPY build-llvm.sh 2024-10-25 06:55:30 +04:00
Evgeny Snitko fdc44db1be checkout 2024-10-25 06:51:58 +04:00
Evgeny Snitko 76f815f33b -f 2024-10-25 06:50:24 +04:00
Evgeny Snitko a293264028 docker context 2024-10-25 06:48:46 +04:00
Evgeny Snitko 7bf9d49166 stop build for tests 2024-10-25 06:47:55 +04:00
Evgeny Snitko d5b9c489ea gha test 2024-10-25 06:46:25 +04:00
Sebastian Miasojed cc38c37481 Set evm.deployedBytecode to the value of evm.bytecode (#95) 2024-10-24 14:59:50 +02:00
Cyrill Leutwiler e56feb95be standard json output: skip serializing keys instead of emitting a null object (#52)
Signed-off-by: Cyrill Leutwiler <bigcyrill@hotmail.com>
2024-10-23 15:28:28 +02:00
Cyrill Leutwiler 995b115c5f bump polkadot-sdk and polkavm (#94)
Signed-off-by: xermicus <cyrill@parity.io>
2024-10-22 19:50:58 +02:00
Ermal Kaleci ee83d28a51 Implement extcodehash (#77) 2024-10-21 10:13:50 +02:00
Cyrill Leutwiler 82ae22c163 tidy up the runtime API crate (#85)
- remove unused runtime API imports and constants
- move runtime api symbols into the revive-runtime-api crate

Signed-off-by: Cyrill Leutwiler <bigcyrill@hotmail.com>
2024-10-17 10:55:27 +02:00
Cyrill Leutwiler 20e3560398 Makefile: remove duplicate workspace tests from the test target (#90)
Signed-off-by: Cyrill Leutwiler <bigcyrill@hotmail.com>
2024-10-17 10:22:04 +02:00
Cyrill Leutwiler 5bf31db660 bump polkavm and polkadot-sdk (#87)
Signed-off-by: Cyrill Leutwiler <bigcyrill@hotmail.com>
2024-10-15 10:46:20 +02:00
Cyrill Leutwiler f0f344a139 disable sbrk and emulate EVM linear memory internally (#76)
Signed-off-by: Cyrill Leutwiler <bigcyrill@hotmail.com>
Signed-off-by: xermicus <cyrill@parity.io>
2024-10-14 15:20:00 +02:00
Cyrill Leutwiler 92a18460e4 support solc 0.8.28 (#84)
Signed-off-by: Cyrill Leutwiler <bigcyrill@hotmail.com>
2024-10-14 13:25:18 +02:00
Cyrill Leutwiler e5233fc46e revive-runner: consider non-reverted transactions as success (#82)
Signed-off-by: Cyrill Leutwiler <bigcyrill@hotmail.com>
2024-10-14 13:24:59 +02:00
Ermal Kaleci adda5a0f12 improve runtime api return value names (#81) 2024-10-14 08:56:26 +02:00
Ermal Kaleci d9842b5427 Fix implementation for balance_of (#79)
The balance_of syscall is now available in pallet-revive.
- Fix balance_of implementation to use correct runtime api
- Add build_address_argument_store helper to be used for address arguments
2024-10-12 12:35:10 +02:00
Cyrill Leutwiler 6335c34a2b remove obsolete runtime builtins
Signed-off-by: Cyrill Leutwiler <bigcyrill@hotmail.com>
2024-10-11 15:58:28 +02:00
Cyrill Leutwiler 49d2157a84 remove near calls
Signed-off-by: Cyrill Leutwiler <bigcyrill@hotmail.com>
2024-10-11 15:58:28 +02:00
Cyrill Leutwiler e131eebf50 remove system mode and request memoization
Signed-off-by: Cyrill Leutwiler <bigcyrill@hotmail.com>
2024-10-11 15:58:28 +02:00
Cyrill Leutwiler 705d1d7866 run signed_remainder test in differential mode (#75) 2024-10-10 19:26:04 +02:00
Cyrill Leutwiler d5d419cefc implement immutable variables codegen (#70) 2024-10-10 13:33:00 +02:00
Cyrill Leutwiler 8b7fe8e3d7 deny clippy warnings by default (#73) 2024-10-09 20:19:12 +02:00
xermicus b344e0cff5 Revert "implement immutable variables codegen"
This reverts commit 0e6a6d12c3.
2024-10-09 03:43:05 +02:00
xermicus 0e6a6d12c3 implement immutable variables codegen
Signed-off-by: xermicus <cyrill@parity.io>
2024-10-09 03:37:56 +02:00
Cyrill Leutwiler 77fe683f18 remove the test encoding option (#65) 2024-10-04 09:59:27 +02:00
wpt967 e8fcd6118e Merge pull request #55 from wpt967/revive-debian-x86-build
[workflows] Add workflow for building revive in a debian container.
2024-09-30 17:25:08 +01:00
wpt967 ad46e94ebd [workflows] Add workflow for building revive in a debian container.
Makefile: Add target 'install-revive' to build revive with the
installation path specified by variable REVIVE_INSTALL_DIR.

Add utils directory with scripts for building revive in a container.

Add utils/build-revive.sh taking option argument '-o <install-dir>' to
build revive with the specified install directory.

Add utils/revive-builder-debian.dockerfile to make a docker container
for building revive in a Debian environment.
2024-09-30 12:02:57 +01:00
Cyrill Leutwiler 6585973e99 Updated call semantics (#56)
- Update pallet-revive dependency
- Implement calls according to pallet-revive call semantics
- Switch to the new return data API in pallet revive and get rid of return data buffer
- Remove a bunch of resulting dead code
2024-09-28 20:03:03 +02:00
Cyrill Leutwiler 066acc4663 set chain_id in test runtime
Signed-off-by: Cyrill Leutwiler <bigcyrill@hotmail.com>
2024-09-28 19:17:41 +02:00
Cyrill Leutwiler 287272b789 sync runtime with the pallet (#54) 2024-09-24 09:14:36 +02:00
Cyrill Leutwiler f621971a13 move the repository to paritytech org (#49) 2024-09-17 14:53:17 +02:00
Cyrill Leutwiler b8bd44b62a install solc 0.8.27 on CI (#47)
Signed-off-by: xermicus <cyrill@parity.io>
2024-09-16 13:17:30 +02:00
Cyrill Leutwiler d8c708eba5 support solc 0.8.27
Signed-off-by: Cyrill Leutwiler <bigcyrill@hotmail.com>
2024-09-16 12:43:49 +02:00
Cyrill Leutwiler 72d958392b revise alloca at function entry later
Signed-off-by: Cyrill Leutwiler <bigcyrill@hotmail.com>
2024-09-16 12:42:50 +02:00
Cyrill Leutwiler 616f044633 always build alloca in the entry block (#46)
Signed-off-by: xermicus <cyrill@parity.io>
2024-09-13 21:54:42 +02:00
xermicus 7dc8e6051e enable compressed instructions extension
Signed-off-by: xermicus <cyrill@parity.io>
2024-09-13 14:55:16 +02:00
xermicus 783fa640e4 temporarily disable pvm linker optimizations
Signed-off-by: xermicus <cyrill@parity.io>
2024-09-13 14:52:47 +02:00
xermicus f086c57442 bump up runner runtime limits
Signed-off-by: xermicus <cyrill@parity.io>
2024-09-13 14:52:09 +02:00
xermicus 0f2b55f6ff fixed output size for transferred value
Signed-off-by: xermicus <cyrill@parity.io>
2024-09-13 08:41:23 +02:00
wpt967 ac9215329c [solidity] Fix wrong check on recursive-process-input CLI option. (#42) 2024-09-10 19:11:36 +02:00
Cyrill Leutwiler 6635a0b337 fixed size event topics
Signed-off-by: Cyrill Leutwiler <bigcyrill@hotmail.com>
2024-09-10 09:09:52 +02:00
Cyrill Leutwiler 77df88b3cb update dependencies
Signed-off-by: Cyrill Leutwiler <bigcyrill@hotmail.com>
2024-09-10 09:04:55 +02:00
Cyrill Leutwiler 2955f77772 implement self balance
Signed-off-by: Cyrill Leutwiler <bigcyrill@hotmail.com>
2024-09-09 09:40:24 +02:00
Cyrill Leutwiler d77ee1e0d4 runner: endow test accounts on genesis
Signed-off-by: Cyrill Leutwiler <bigcyrill@hotmail.com>
2024-09-06 13:50:01 +02:00
91 changed files with 3872 additions and 2435 deletions
+6
View File
@@ -0,0 +1,6 @@
FROM revive-llvm
WORKDIR /app
COPY . .
RUN RUSTFLAGS='-L /app/llvm18.0/lib/unknown -L /usr/lib -L /app/llvm18.0/lib' REVIVE_INSTALL_DIR='/app/release/revive/' make install-revive
+16
View File
@@ -0,0 +1,16 @@
FROM alpine:3.20.3
ARG RUST_VERSION=stable
RUN apk add bash git cmake make ninja python3 ncurses-static curl
RUN ninja --version
COPY build-llvm.sh .
RUN bash -c ./build-llvm.sh
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain ${RUST_VERSION}
ENV PATH=/root/.cargo/bin:/llvm18.0/bin:${PATH}
WORKDIR /app
RUN REVIVE_INSTALL_DIR=$(pwd)/target/release
+38
View File
@@ -0,0 +1,38 @@
name: Build revive-debian
on:
workflow_dispatch:
env:
REVIVE_DEBIAN_PACKAGE: revive-debian-x86
DEBIAN_CONTAINER: revive-builder-debian-x86
DEBIAN_CONTAINER_BUILDER: build-debian-builder.sh
DEBIAN_CONTAINER_RUNNER: run-debian-builder.sh
REVIVE_DEBIAN_INSTALL: ${{ github.workspace }}/target/release
REVIVE_DEBIAN_BINARY: resolc
RUST_VERSION: "1.80"
jobs:
build-revive-debian-x86:
name: debian-container-x86
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: build-container
run: |
(cd utils && ./${{ env.DEBIAN_CONTAINER_BUILDER}} --build-arg RUST_VERSION=${{ env.RUST_VERSION}} . )
- name: build-revive-debian
run: |
rustup show
cargo --version
rustup +nightly show
cargo +nightly --version
bash --version
utils/${{ env.DEBIAN_CONTAINER_RUNNER }} utils/build-revive.sh -o ${{ env.REVIVE_DEBIAN_INSTALL}}
- uses: actions/upload-artifact@v4
with:
name: ${{ env.REVIVE_DEBIAN_PACKAGE }}
path: ${{ env.REVIVE_DEBIAN_INSTALL }}/${{ env.REVIVE_DEBIAN_BINARY }}
retention-days: 1
+40
View File
@@ -0,0 +1,40 @@
name: Release
run-name: Release ${{ github.ref_name }}
on:
push:
tags:
- "[0-9]+.[0-9]+.[0-9]+"
- "[0-9]+.[0-9]+.[0-9]+-[a-zA-Z0-9]+"
jobs:
CreateRelease:
permissions:
contents: write
runs-on: ubuntu-20.04
steps:
- name: Release
uses: softprops/action-gh-release@v2
with:
draft: true
make_latest: true
Release:
needs: [CreateRelease]
permissions:
contents: write
runs-on: ubuntu-20.04
env:
GH_TOKEN: ${{ github.token }}
steps:
- name: build llvm
run: docker build -t revive-llvm:latest --progress=plain -f --build-arg RUST_VERSION=1.80 .github/Dockerfile-llvm
- name: build revive
run: docker build -t revive:latest --progress=plain -f .github/Dockerfile
- name: get binary
run: docker run --rm revive:latest -v output:/app/output cp /app/release/revive/resolc /app/output
# docker push revive:latest
- run: gh release upload ${{ github.ref_name }} output/resolc --clobber
+1 -3
View File
@@ -3,8 +3,6 @@ name: Build
on:
push:
branches: ["main"]
pull_request:
branches: ["main"]
env:
CARGO_TERM_COLOR: always
@@ -19,7 +17,7 @@ jobs:
- name: Install solc
run: |
mkdir -p solc
curl -sSL --output solc/solc https://github.com/ethereum/solidity/releases/download/v0.8.26/solc-static-linux
curl -sSL --output solc/solc https://github.com/ethereum/solidity/releases/download/v0.8.28/solc-static-linux
chmod +x solc/solc
echo "$(pwd)/solc/" >> $GITHUB_PATH
+30
View File
@@ -0,0 +1,30 @@
name: Test
run-name: Test ${{ github.ref_name }}
on:
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
Release:
# runs-on: ubuntu-20.04
runs-on: parity-large
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: build llvm
run: docker build -t revive-llvm:latest --progress=plain --build-arg RUST_VERSION=1.80 -f .github/Dockerfile-llvm .
- name: build revive
run: docker build -t revive:latest --progress=plain -f .github/Dockerfile
- name: get binary
run: docker run --rm revive:latest -v output:/app/output cp /app/release/revive/resolc /app/output .
# docker push revive:latest
- run: gh release upload ${{ github.ref_name }} output/resolc
Generated
+2036 -883
View File
File diff suppressed because it is too large Load Diff
+7 -6
View File
@@ -10,7 +10,8 @@ authors = [
]
license = "MIT/Apache-2.0"
edition = "2021"
repository = "https://github.com/xermicus/revive"
repository = "https://github.com/paritytech/revive"
rust-version = "1.80.0"
[workspace.dependencies]
revive-benchmarks = { version = "0.1.0", path = "crates/benchmarks" }
@@ -50,10 +51,10 @@ path-slash = "0.2"
rayon = "1.8"
clap = { version = "4", default-features = false, features = ["derive"] }
rand = "0.8"
polkavm-common = "0.10"
polkavm-linker = "0.10"
polkavm-disassembler = "0.10"
polkavm = "0.10"
polkavm-common = "0.13"
polkavm-linker = "0.13"
polkavm-disassembler = "0.13"
polkavm = "0.13"
alloy-primitives = { version = "0.8", features = ["serde"] }
alloy-sol-types = "0.8"
alloy-genesis = "0.3"
@@ -66,7 +67,7 @@ log = { version = "0.4" }
# polkadot-sdk and friends
codec = { version = "3.6.12", default-features = false, package = "parity-scale-codec" }
scale-info = { version = "2.11.1", default-features = false }
polkadot-sdk = { git = "https://github.com/paritytech/polkadot-sdk", rev = "d7b575338b2c647e04fc48bfbe00ea8f492fb580" }
polkadot-sdk = { git = "https://github.com/paritytech/polkadot-sdk", rev = "aeebf2f383390f2f86527d70212162d5dbea8b93" }
# llvm
[workspace.dependencies.inkwell]
+10 -4
View File
@@ -8,11 +8,20 @@ install-bin:
install-npm:
npm install && npm fund
# install-revive: Build and install to the directory specified in REVIVE_INSTALL_DIR
ifeq ($(origin REVIVE_INSTALL_DIR), undefined)
REVIVE_INSTALL_DIR=`pwd`/release/revive-debian
endif
install-revive:
cargo install --path crates/solidity --root $(REVIVE_INSTALL_DIR)
format:
cargo fmt --all --check
clippy:
cargo clippy --all-features --workspace --tests --benches -- --deny warnings --allow dead_code
test: format clippy test-cli test-workspace
cargo test --workspace
test-integration: install-bin
cargo test --package revive-integration
@@ -38,9 +47,6 @@ bench: install-bin
cargo criterion --all --all-features --message-format=json \
| criterion-table > crates/benchmarks/BENCHMARKS.md
clippy:
cargo clippy --all-features --workspace --tests --benches
docs: docs-build
mdbook serve --open docs/
+1 -1
View File
@@ -1,4 +1,4 @@
![CI](https://github.com/xermicus/revive/actions/workflows/rust.yml/badge.svg)
![CI](https://github.com/paritytech/revive/actions/workflows/rust.yml/badge.svg)
# revive
+1 -1
View File
@@ -20,7 +20,7 @@ pub const BIT_LENGTH_ETH_ADDRESS: usize =
pub const BIT_LENGTH_WORD: usize = crate::byte_length::BYTE_LENGTH_WORD * BIT_LENGTH_BYTE;
/// Bit length of the runtime value type.
pub const BIT_LENGTH_VALUE: usize = crate::byte_length::BYTE_LENGTH_VALUE * BIT_LENGTH_BYTE;
pub const BIT_LENGTH_VALUE: usize = BIT_LENGTH_WORD;
/// Bit length of thre runimte block number type.
pub const BIT_LENGTH_BLOCK_NUMBER: usize =
+3 -6
View File
@@ -6,15 +6,12 @@ pub const BYTE_LENGTH_BYTE: usize = 1;
/// The x86 word byte-length.
pub const BYTE_LENGTH_X32: usize = 4;
/// Native stack alignment size in bytes
#[cfg(not(feature = "riscv-64"))]
pub const BYTE_LENGTH_STACK_ALIGN: usize = 4;
#[cfg(feature = "riscv-64")]
pub const BYTE_LENGTH_STACK_ALIGN: usize = 8;
/// The x86_64 word byte-length.
pub const BYTE_LENGTH_X64: usize = 8;
/// EVM native stack alignment size in bytes
pub const BYTE_LENGTH_STACK_ALIGN: usize = 32;
/// The ETH address byte-length.
pub const BYTE_LENGTH_ETH_ADDRESS: usize = 20;
+12 -2
View File
@@ -1,6 +1,6 @@
{
"config": {
"chainId": 1,
"chainId": 420420420,
"homesteadBlock": 0,
"eip150Block": 0,
"eip155Block": 0,
@@ -26,5 +26,15 @@
"mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"timestamp": "0x00",
"alloc": {}
"alloc": {
"0101010101010101010101010101010101010101": {
"balance": "1000000000"
},
"0202020202020202020202020202020202020202": {
"balance": "1000000000"
},
"0303030303030303030303030303030303030303": {
"balance": "1000000000"
}
}
}
+3 -4
View File
@@ -40,7 +40,7 @@ const EXECUTABLE_ARGS_BENCH: [&str; 6] = [
"-",
];
const GAS_USED_MARKER: &str = "EVM gas used:";
const REVERT_MARKER: &str = "error: execution reverted";
const REVERT_MARKER: &str = " error: ";
/// The geth EVM state dump structure
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
@@ -100,10 +100,9 @@ pub struct EvmOutput {
impl EvmOutput {
/// Return if there was no error found.
///
/// Panics if the gas used is zero as this indicates nothing was run, i.e.
/// there was no receiving account but still no error is reported.
/// Panics if the gas used is zero as this indicates nothing was run.
pub fn run_success(&self) -> bool {
assert_ne!(self.gas_used, U256::ZERO, "nothing was executed");
assert_ne!(self.gas_used, U256::ZERO, "nothing was executed: {self:?}");
self.error.is_none()
}
}
+8 -8
View File
@@ -1,10 +1,10 @@
{
"Baseline": 878,
"Computation": 4305,
"DivisionArithmetics": 39774,
"ERC20": 53405,
"Events": 1693,
"FibonacciIterative": 2917,
"Flipper": 3570,
"SHA1": 32557
"Baseline": 989,
"Computation": 4153,
"DivisionArithmetics": 40614,
"ERC20": 47343,
"Events": 1781,
"FibonacciIterative": 3035,
"Flipper": 3393,
"SHA1": 33553
}
+47 -9
View File
@@ -2,19 +2,57 @@
pragma solidity ^0.8;
contract Call {
function value_transfer(address payable destination) public payable {
destination.transfer(msg.value);
}
/* runner.json
{
"differential": true,
"actions": [
{
"Upload": {
"code": {
"Solidity": {
"contract": "Callee"
}
}
}
},
{
"Instantiate": {
"code": {
"Solidity": {
"contract": "Caller"
}
},
"value": 123
}
},
{
"Call": {
"dest": {
"Instantiated": 0
},
"data": "5a6535fc00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000004cafebabe00000000000000000000000000000000000000000000000000000000"
}
}
]
}
*/
contract Callee {
function echo(bytes memory payload) public pure returns (bytes memory) {
return payload;
}
function call(
address callee,
bytes memory payload
) public pure returns (bytes memory) {
return Call(callee).echo(payload);
receive() external payable {}
}
contract Caller {
constructor() payable {
Callee callee = new Callee();
payable(address(callee)).transfer(msg.value);
}
function call(bytes memory payload) public returns (bytes memory) {
Callee callee = new Callee();
return callee.echo(payload);
}
}
+16
View File
@@ -30,6 +30,14 @@ pragma solidity ^0.8;
},
"data": "fc9c8d39"
}
},
{
"Call": {
"dest": {
"Instantiated": 0
},
"data": "3af973b1"
}
}
]
}
@@ -43,4 +51,12 @@ contract Context {
function caller() public view returns (address ret) {
ret = msg.sender;
}
function chain_id() public view returns (uint) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
}
+57 -6
View File
@@ -1,13 +1,64 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
pragma solidity ^0.8;
/* runner.json
{
"differential": true,
"actions": [
{
"Upload": {
"code": {
"Solidity": {
"contract": "CreateA"
}
}
}
},
{
"Instantiate": {
"code": {
"Solidity": {
"contract": "CreateB"
}
}
}
},
{
"Call": {
"dest": {
"Instantiated": 0
},
"value": 10000
}
},
{
"Call": {
"dest": {
"Instantiated": 0
}
}
},
{
"Call": {
"dest": {
"Instantiated": 0
}
}
},
{
"Call": {
"dest": {
"Instantiated": 0
}
}
}
]
}
*/
contract CreateA {
address creator;
constructor() payable {
creator = msg.sender;
}
constructor() payable {}
}
contract CreateB {
+13 -11
View File
@@ -4,30 +4,32 @@ pragma solidity ^0.8.24;
/* runner.json
{
"actions": [
"differential": true,
"actions": [
{
"Instantiate": {}
"Instantiate": {
"code": {
"Solidity": {
"contract": "TestSha3"
}
}
}
},
{
"Call": {
"dest": {
"Instantiated": 0
"Instantiated": 0
},
"data": "f9fbd5540000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000c68656c6c6f20776f726c64210000000000000000000000000000000000000000"
}
},
{
"VerifyCall": {
"success": true,
"output": "57caa176af1ac0433c5df30e8dabcd2ec1af1e92a26eced5f719b88458777cd6"
}
}
]
}
*/
contract TestSha3 {
function test(string memory _pre) external payable returns (bytes32 hash) {
hash = keccak256(bytes(_pre));
function test(string memory _pre) external payable returns (bytes32) {
bytes32 hash = keccak256(bytes(_pre));
return bytes32(uint(hash) + 1);
}
}
+3 -7
View File
@@ -22,12 +22,7 @@ pragma solidity ^0.8;
},
"data": "4d43bec90000000000000000000000000000000000000000000000000000000000000000"
}
}
]
}
*/
/* TODO when pallet_revive accepts Solidity event topics
},
{
"Call": {
"dest": {
@@ -36,7 +31,8 @@ pragma solidity ^0.8;
"data": "4d43bec9000000000000000000000000000000000000000000000000000000000000007b"
}
}
]
}
*/
contract Events {
+12
View File
@@ -14,4 +14,16 @@ contract ExtCode {
ret := codesize()
}
}
function ExtCodeHash(address who) public view returns (bytes32 ret) {
assembly {
ret := extcodehash(who)
}
}
function CodeHash() public view returns (bytes32 ret) {
assembly {
ret := extcodehash(address())
}
}
}
@@ -0,0 +1,63 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
/* runner.json
{
"differential": true,
"actions": [
{
"Upload": {
"code": {
"Solidity": {
"contract": "ImmutablesTester"
}
}
}
},
{
"Instantiate": {
"code": {
"Solidity": {
"contract": "Immutables"
}
}
}
},
{
"Call": {
"dest": {
"Instantiated": 0
}
}
}
]
}
*/
contract ImmutablesTester {
// Read should work in the runtime code
uint public immutable foo;
// Read should work in the runtime code
uint public immutable bar;
// Read should work in the runtime code
uint public immutable zoo;
// Assign and read should work in the constructor
constructor(uint _foo) payable {
foo = _foo;
bar = foo + 1;
zoo = bar + 2;
assert(zoo == _foo + 3);
}
}
contract Immutables {
fallback() external {
ImmutablesTester tester = new ImmutablesTester(127);
assert(tester.foo() == 127);
assert(tester.bar() == tester.foo() + 1);
assert(tester.zoo() == tester.bar() + 2);
}
}
+1 -12
View File
@@ -4,6 +4,7 @@ pragma solidity ^0.8;
/* runner.json
{
"differential": true,
"actions": [
{
"Instantiate": {
@@ -23,12 +24,6 @@ pragma solidity ^0.8;
"data": "f016832c"
}
},
{
"VerifyCall": {
"success": true,
"output": "0000000000000000000000000000000000000000000000000000000000000060"
}
},
{
"Call": {
"dest": {
@@ -36,12 +31,6 @@ pragma solidity ^0.8;
},
"data": "f4a63aa5"
}
},
{
"VerifyCall": {
"success": true,
"output": "0000000000000000000000000000000000000000000000000000000000000084"
}
}
]
}
@@ -0,0 +1,53 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
/* runner.json
{
"differential": true,
"actions": [
{
"Upload": {
"code": {
"Solidity": {
"contract": "Callee"
}
}
}
},
{
"Instantiate": {
"code": {
"Solidity": {
"contract": "ReturnDataOob"
}
}
}
},
{
"Call": {
"dest": {
"Instantiated": 0
}
}
}
]
}
*/
contract Callee {
function echo(bytes memory payload) public pure returns (bytes memory) {
return payload;
}
}
contract ReturnDataOob {
fallback() external {
new Callee().echo(hex"1234");
assembly {
let pos := mload(64)
let size := add(returndatasize(), 1)
returndatacopy(pos, 0, size)
}
}
}
+54
View File
@@ -0,0 +1,54 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
/* runner.json
{
"differential": true,
"actions": [
{
"Instantiate": {
"code": {
"Solidity": {
"contract": "Transfer"
}
},
"value": 11
}
},
{
"Call": {
"dest": {
"Instantiated": 0
},
"data": "1c8d16b30000000000000000000000000303030303030303030303030303030303030303000000000000000000000000000000000000000000000000000000000000000a"
}
},
{
"Call": {
"dest": {
"Instantiated": 0
},
"data": "fb9e8d0500000000000000000000000003030303030303030303030303030303030303030000000000000000000000000000000000000000000000000000000000000001"
}
}
]
}
*/
contract Transfer {
constructor() payable {
transfer_self(msg.value);
}
function address_self() internal view returns (address payable) {
return payable(address(this));
}
function transfer_self(uint _amount) public payable {
transfer_to(address_self(), _amount);
}
function transfer_to(address payable _dest, uint _amount) public payable {
_dest.transfer(_amount);
}
}
+33 -4
View File
@@ -5,8 +5,18 @@ pragma solidity ^0.8;
{
"differential": true,
"actions": [
{
"Upload": {
"code": {
"Solidity": {
"contract": "ValueTester"
}
}
}
},
{
"Instantiate": {
"value": 1024,
"code": {
"Solidity": {
"contract": "Value"
@@ -19,6 +29,7 @@ pragma solidity ^0.8;
"dest": {
"Instantiated": 0
},
"value": 123,
"data": "3fa4f245"
}
}
@@ -26,12 +37,30 @@ pragma solidity ^0.8;
}
*/
contract ValueTester {
constructor() payable {}
function balance_self() public view returns (uint ret) {
ret = address(this).balance;
}
}
contract Value {
constructor() payable {
ValueTester tester = new ValueTester{value: msg.value}();
// own account
assert(address(this).balance == 0);
// tester account
assert(address(tester).balance == msg.value);
assert(tester.balance_self() == msg.value);
// non-existant account
assert(address(0xdeadbeef).balance == 0);
}
function value() public payable returns (uint ret) {
ret = msg.value;
}
function balance_of(address _address) public view returns (uint ret) {
ret = _address.balance;
}
}
+8
View File
@@ -178,10 +178,16 @@ sol!(
function ExtCodeSize(address who) public view returns (uint ret);
function CodeSize() public pure returns (uint ret);
function ExtCodeHash(address who) public view returns (bytes32 ret);
function CodeHash() public view returns (bytes32 ret);
}
);
case!("ExtCode.sol", ExtCode, ExtCodeSizeCall, ext_code_size, address: Address);
case!("ExtCode.sol", ExtCode, CodeSizeCall, code_size,);
case!("ExtCode.sol", ExtCode, ExtCodeHashCall, ext_code_hash, address: Address);
case!("ExtCode.sol", ExtCode, CodeHashCall, code_hash,);
sol!(
contract MCopy {
@@ -209,9 +215,11 @@ case!("Call.sol", "Call", vec![], call_constructor);
sol!(
contract Value {
function balance_of(address _address) public view returns (uint ret);
function balance_self() public view returns (uint ret);
}
);
case!("Value.sol", Value, balance_ofCall, value_balance_of, address: Address);
case!("Value.sol", Value, balance_selfCall, value_balance_self,);
sol!(
contract Bitwise {
+99 -113
View File
@@ -6,6 +6,10 @@ use SpecsAction::*;
use crate::cases::Contract;
/// Parameters:
/// - The function name of the test
/// - The contract name to fill in empty code based on the file path
/// - The contract source file
macro_rules! test_spec {
($test_name:ident, $contract_name:literal, $source_file:literal) => {
#[test]
@@ -26,7 +30,6 @@ test_spec!(hash_keccak_256, "TestSha3", "Crypto.sol");
test_spec!(erc20, "ERC20", "ERC20.sol");
test_spec!(computation, "Computation", "Computation.sol");
test_spec!(msize, "MSize", "MSize.sol");
test_spec!(transferred_value, "Value", "Value.sol");
test_spec!(sha1, "SHA1", "SHA1.sol");
test_spec!(block, "Block", "Block.sol");
test_spec!(mcopy, "MCopy", "MCopy.sol");
@@ -34,6 +37,12 @@ test_spec!(events, "Events", "Events.sol");
test_spec!(storage, "Storage", "Storage.sol");
test_spec!(mstore8, "MStore8", "MStore8.sol");
test_spec!(address, "Context", "Context.sol");
test_spec!(balance, "Value", "Value.sol");
test_spec!(create, "CreateB", "Create.sol");
test_spec!(call, "Caller", "Call.sol");
test_spec!(transfer, "Transfer", "Transfer.sol");
test_spec!(return_data_oob, "ReturnDataOob", "ReturnDataOob.sol");
test_spec!(immutables, "Immutables", "Immutables.sol");
fn instantiate(path: &str, contract: &str) -> Vec<SpecsAction> {
vec![Instantiate {
@@ -221,66 +230,98 @@ fn signed_remainder() {
data: Contract::division_arithmetics_smod(n, d).calldata,
})
}
run_differential(actions);
}
#[test]
fn ext_code_hash() {
let mut actions = instantiate("contracts/ExtCode.sol", "ExtCode");
// First do contract instantiation to figure out address and code hash
let results = Specs {
actions: actions.clone(),
..Default::default()
}
.run();
let (addr, code_hash) = match results.first().cloned() {
Some(CallResult::Instantiate {
result, code_hash, ..
}) => (result.result.unwrap().addr, code_hash),
_ => panic!("instantiate contract failed"),
};
// code hash of itself
actions.push(Call {
origin: TestAddress::Alice,
dest: TestAddress::Instantiated(0),
value: 0,
gas_limit: None,
storage_deposit_limit: None,
data: Contract::code_hash().calldata,
});
actions.push(VerifyCall(VerifyCallExpectation {
success: true,
output: OptionalHex::from(code_hash.as_bytes().to_vec()),
gas_consumed: None,
}));
// code hash for a given contract address
actions.push(Call {
origin: TestAddress::Alice,
dest: TestAddress::Instantiated(0),
value: 0,
gas_limit: None,
storage_deposit_limit: None,
data: Contract::ext_code_hash(Address::from(addr.to_fixed_bytes())).calldata,
});
actions.push(VerifyCall(VerifyCallExpectation {
success: true,
output: OptionalHex::from(code_hash.as_bytes().to_vec()),
gas_consumed: None,
}));
// EOA returns fixed hash
actions.push(Call {
origin: TestAddress::Alice,
dest: TestAddress::Instantiated(0),
value: 0,
gas_limit: None,
storage_deposit_limit: None,
data: Contract::ext_code_hash(Address::from(CHARLIE.to_fixed_bytes())).calldata,
});
actions.push(VerifyCall(VerifyCallExpectation {
success: true,
output: OptionalHex::from(
hex!("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470").to_vec(),
),
gas_consumed: None,
}));
// non-existing account
actions.push(Call {
origin: TestAddress::Alice,
dest: TestAddress::Instantiated(0),
value: 0,
gas_limit: None,
storage_deposit_limit: None,
data: Contract::ext_code_hash(Address::from([8u8; 20])).calldata,
});
actions.push(VerifyCall(VerifyCallExpectation {
success: true,
output: OptionalHex::from([0u8; 32].to_vec()),
gas_consumed: None,
}));
Specs {
actions,
..Default::default()
}
.run();
}
/*
#[test]
fn events() {
assert_success(&Contract::event(U256::ZERO), true);
assert_success(&Contract::event(U256::from(123)), true);
}
#[test]
fn balance() {
let (_, output) = assert_success(&Contract::value_balance_of(Default::default()), false);
let expected = U256::ZERO;
let received = U256::from_be_slice(&output.data);
assert_eq!(expected, received);
let expected = U256::from(54589);
let (mut state, address) = State::new_deployed(Contract::value_balance_of(Default::default()));
state.accounts_mut().get_mut(&address).unwrap().value = expected;
let contract = Contract::value_balance_of(address);
let (_, output) = state
.transaction()
.with_default_account(&contract.pvm_runtime)
.calldata(contract.calldata)
.call();
assert_eq!(ReturnFlags::Success, output.flags);
let received = U256::from_be_slice(&output.data);
assert_eq!(expected, received)
}
#[test]
fn create2() {
let mut state = State::default();
let contract_a = Contract::create_a();
state.upload_code(&contract_a.pvm_runtime);
let contract = Contract::create_b();
let (state, output) = state
.transaction()
.with_default_account(&contract.pvm_runtime)
.calldata(contract.calldata)
.call();
assert_eq!(output.flags, ReturnFlags::Success);
assert_eq!(state.accounts().len(), 2);
for address in state.accounts().keys() {
if *address != Transaction::default_address() {
let derived_address = Transaction::default_address().create2(
B256::from(U256::from(1)),
keccak256(&contract_a.pvm_runtime).0,
);
assert_eq!(*address, derived_address);
}
}
}
// These test were implement for the mock-runtime and need to be ported yet.
#[test]
fn create2_failure() {
@@ -308,31 +349,6 @@ fn create2_failure() {
assert_eq!(output.flags, ReturnFlags::Revert);
}
#[test]
fn create_with_value() {
let mut state = State::default();
state.upload_code(&Contract::create_a().pvm_runtime);
let amount = U256::from(123);
let contract = Contract::create_b();
let (state, output) = state
.transaction()
.with_default_account(&contract.pvm_runtime)
.callvalue(amount)
.call();
assert_eq!(output.flags, ReturnFlags::Success);
assert_eq!(state.accounts().len(), 2);
for (address, account) in state.accounts() {
if *address == Transaction::default_address() {
assert_eq!(account.value, U256::ZERO);
} else {
assert_eq!(account.value, amount);
}
}
}
#[test]
fn ext_code_size() {
let contract = Contract::ext_code_size(Transaction::default_address());
@@ -356,34 +372,4 @@ fn code_size() {
let received = U256::from_be_slice(&output.data);
assert_eq!(expected, received);
}
#[test]
fn value_transfer() {
// Succeeds in remix (shanghai) but traps the interpreter
let (state, _) = assert_success(&Contract::call_value_transfer(Default::default()), false);
assert_eq!(state.accounts().len(), 2);
assert!(state.accounts().get(&Address::default()).is_some());
}
#[test]
fn echo() {
let (state, address) = State::new_deployed(Contract::call_constructor());
let expected = vec![1, 2, 3, 4, 5];
let contract = Contract::call_call(address, expected.clone());
let (_, output) = state
.transaction()
.with_default_account(&contract.pvm_runtime)
.calldata(contract.calldata)
.call();
assert_eq!(output.flags, ReturnFlags::Success);
let received = alloy_primitives::Bytes::abi_decode(&output.data, true)
.unwrap()
.to_vec();
assert_eq!(expected, received);
}
*/
+1
View File
@@ -32,6 +32,7 @@ fn invoke_lld(cmd_args: &[&str]) -> bool {
fn polkavm_linker<T: AsRef<[u8]>>(code: T) -> anyhow::Result<Vec<u8>> {
let mut config = polkavm_linker::Config::default();
config.set_strip(true);
config.set_optimize(true);
polkavm_linker::program_from_elf(config, code.as_ref())
.map_err(|reason| anyhow::anyhow!("polkavm linker failed: {}", reason))
+2
View File
@@ -27,9 +27,11 @@ pub use self::polkavm::context::function::llvm_runtime::LLVMRuntime as PolkaVMLL
pub use self::polkavm::context::function::r#return::Return as PolkaVMFunctionReturn;
pub use self::polkavm::context::function::runtime::deploy_code::DeployCode as PolkaVMDeployCodeFunction;
pub use self::polkavm::context::function::runtime::entry::Entry as PolkaVMEntryFunction;
pub use self::polkavm::context::function::runtime::immutable_data_load::ImmutableDataLoad as PolkaVMImmutableDataLoadFunction;
pub use self::polkavm::context::function::runtime::runtime_code::RuntimeCode as PolkaVMRuntimeCodeFunction;
pub use self::polkavm::context::function::runtime::FUNCTION_DEPLOY_CODE as PolkaVMFunctionDeployCode;
pub use self::polkavm::context::function::runtime::FUNCTION_ENTRY as PolkaVMFunctionEntry;
pub use self::polkavm::context::function::runtime::FUNCTION_LOAD_IMMUTABLE_DATA as PolkaVMFunctionImmutableDataLoad;
pub use self::polkavm::context::function::runtime::FUNCTION_RUNTIME_CODE as PolkaVMFunctionRuntimeCode;
pub use self::polkavm::context::function::yul_data::YulData as PolkaVMFunctionYulData;
pub use self::polkavm::context::function::Function as PolkaVMFunction;
@@ -21,8 +21,6 @@ pub struct Settings {
/// Fallback to optimizing for size if the bytecode is too large.
pub is_fallback_to_size_enabled: bool,
/// Whether the system request memoization is disabled.
pub is_system_request_memoization_disabled: bool,
/// Whether the LLVM `verify each` option is enabled.
pub is_verify_each_enabled: bool,
@@ -43,7 +41,6 @@ impl Settings {
level_back_end,
is_fallback_to_size_enabled: false,
is_system_request_memoization_disabled: false,
is_verify_each_enabled: false,
is_debug_logging_enabled: false,
@@ -65,7 +62,6 @@ impl Settings {
level_back_end,
is_fallback_to_size_enabled: false,
is_system_request_memoization_disabled: false,
is_verify_each_enabled,
is_debug_logging_enabled,
@@ -206,20 +202,10 @@ impl Settings {
self.is_fallback_to_size_enabled = true;
}
/// Disables the system request memoization.
pub fn disable_system_request_memoization(&mut self) {
self.is_system_request_memoization_disabled = true;
}
/// Whether the fallback to optimizing for size is enabled.
pub fn is_fallback_to_size_enabled(&self) -> bool {
self.is_fallback_to_size_enabled
}
/// Whether the system request memoization is disabled.
pub fn is_system_request_memoization_disabled(&self) -> bool {
self.is_system_request_memoization_disabled
}
}
impl PartialEq for Settings {
@@ -1,14 +1,8 @@
//! The LLVM context constants.
/// Runtime API methods.
pub mod runtime_api;
/// The LLVM framework version.
pub const LLVM_VERSION: semver::Version = semver::Version::new(18, 1, 4);
/// The PolkaVM version.
pub const ZKEVM_VERSION: semver::Version = semver::Version::new(1, 3, 2);
/// The register width sized type
pub static XLEN: usize = revive_common::BIT_LENGTH_X32;
@@ -21,49 +15,9 @@ pub static GLOBAL_CALLDATA_POINTER: &str = "ptr_calldata";
/// The calldata size global variable name.
pub static GLOBAL_CALLDATA_SIZE: &str = "calldatasize";
/// The return data pointer global variable name.
pub static GLOBAL_RETURN_DATA_POINTER: &str = "ptr_return_data";
/// The return data size pointer global variable name.
pub static GLOBAL_RETURN_DATA_SIZE: &str = "returndatasize";
/// The call flags global variable name.
pub static GLOBAL_CALL_FLAGS: &str = "call_flags";
/// The constant array global variable name prefix.
pub static GLOBAL_CONST_ARRAY_PREFIX: &str = "const_array_";
/// The global verbatim getter identifier prefix.
pub static GLOBAL_VERBATIM_GETTER_PREFIX: &str = "get_global::";
/// The static word size.
pub static GLOBAL_I256_SIZE: &str = "i256_size";
/// The static value size.
pub static GLOBAL_I160_SIZE: &str = "i160_size";
/// The static i64 size.
pub static GLOBAL_I64_SIZE: &str = "i64_size";
/// The external call data offset in the auxiliary heap.
pub const HEAP_AUX_OFFSET_EXTERNAL_CALL: u64 = 0;
/// The constructor return data offset in the auxiliary heap.
pub const HEAP_AUX_OFFSET_CONSTRUCTOR_RETURN_DATA: u64 =
8 * (revive_common::BYTE_LENGTH_WORD as u64);
/// The `create` method deployer signature.
pub static DEPLOYER_SIGNATURE_CREATE: &str = "create(bytes32,bytes32,bytes)";
/// The `create2` method deployer signature.
pub static DEPLOYER_SIGNATURE_CREATE2: &str = "create2(bytes32,bytes32,bytes)";
/// The absence of system call bit.
pub const NO_SYSTEM_CALL_BIT: bool = false;
/// The system call bit.
pub const SYSTEM_CALL_BIT: bool = true;
/// The deployer call header size that consists of:
/// - bytecode hash (32 bytes)
pub const DEPLOYER_CALL_HEADER_SIZE: usize = revive_common::BYTE_LENGTH_WORD;
@@ -1,71 +0,0 @@
//! Runtime API import and export symbols.
pub mod exports {
/// The contract deploy export.
pub static CALL: &str = "call";
/// The contract call export.
pub static DEPLOY: &str = "deploy";
/// All exported symbols.
/// Useful for configuring common attributes and linkage.
pub static EXPORTS: [&str; 2] = [CALL, DEPLOY];
}
pub mod imports {
pub static ADDRESS: &str = "address";
pub static BALANCE: &str = "balance";
pub static BLOCK_NUMBER: &str = "block_number";
pub static CALL: &str = "call";
pub static CALLER: &str = "caller";
pub static CODE_SIZE: &str = "code_size";
pub static DEPOSIT_EVENT: &str = "deposit_event";
pub static GET_STORAGE: &str = "get_storage";
pub static HASH_KECCAK_256: &str = "hash_keccak_256";
pub static INPUT: &str = "input";
pub static INSTANTIATE: &str = "instantiate";
pub static NOW: &str = "now";
pub static RETURN: &str = "seal_return";
pub static RETURNDATACOPY: &str = "returndatacopy";
pub static SET_STORAGE: &str = "set_storage";
pub static VALUE_TRANSFERRED: &str = "value_transferred";
/// All imported runtime API symbols.
/// Useful for configuring common attributes and linkage.
pub static IMPORTS: [&str; 16] = [
ADDRESS,
BALANCE,
BLOCK_NUMBER,
CALL,
CALLER,
CODE_SIZE,
DEPOSIT_EVENT,
GET_STORAGE,
HASH_KECCAK_256,
INPUT,
INSTANTIATE,
NOW,
RETURN,
RETURNDATACOPY,
SET_STORAGE,
VALUE_TRANSFERRED,
];
}
/// PolkaVM __sbrk API symbol to extend the heap memory.
pub static SBRK: &str = "__sbrk";
@@ -11,15 +11,6 @@ use crate::polkavm::context::function::Function;
/// The functions are automatically linked to the LLVM implementations if the signatures match.
#[derive(Debug)]
pub struct LLVMRuntime<'ctx> {
/// The corresponding LLVM runtime function.
pub shl: FunctionDeclaration<'ctx>,
/// The corresponding LLVM runtime function.
pub shr: FunctionDeclaration<'ctx>,
/// The corresponding LLVM runtime function.
pub sar: FunctionDeclaration<'ctx>,
/// The corresponding LLVM runtime function.
pub byte: FunctionDeclaration<'ctx>,
/// The corresponding LLVM runtime function.
pub add_mod: FunctionDeclaration<'ctx>,
/// The corresponding LLVM runtime function.
@@ -31,32 +22,9 @@ pub struct LLVMRuntime<'ctx> {
/// The corresponding LLVM runtime function.
pub sha3: FunctionDeclaration<'ctx>,
/// The corresponding LLVM runtime function.
pub r#return: FunctionDeclaration<'ctx>,
/// The corresponding LLVM runtime function.
pub revert: FunctionDeclaration<'ctx>,
}
impl<'ctx> LLVMRuntime<'ctx> {
/// The LLVM personality function name.
pub const FUNCTION_PERSONALITY: &'static str = "__personality";
/// The LLVM exception throwing function name.
pub const FUNCTION_CXA_THROW: &'static str = "__cxa_throw";
/// The corresponding runtime function name.
pub const FUNCTION_SHL: &'static str = "__shl";
/// The corresponding runtime function name.
pub const FUNCTION_SHR: &'static str = "__shr";
/// The corresponding runtime function name.
pub const FUNCTION_SAR: &'static str = "__sar";
/// The corresponding runtime function name.
pub const FUNCTION_BYTE: &'static str = "__byte";
/// The corresponding runtime function name.
pub const FUNCTION_ADDMOD: &'static str = "__addmod";
@@ -72,121 +40,12 @@ impl<'ctx> LLVMRuntime<'ctx> {
/// The corresponding runtime function name.
pub const FUNCTION_SHA3: &'static str = "__sha3";
/// The corresponding runtime function name.
pub const FUNCTION_SYSTEM_REQUEST: &'static str = "__system_request";
/// The corresponding runtime function name.
pub const FUNCTION_FARCALL: &'static str = "__farcall";
/// The corresponding runtime function name.
pub const FUNCTION_STATICCALL: &'static str = "__staticcall";
/// The corresponding runtime function name.
pub const FUNCTION_DELEGATECALL: &'static str = "__delegatecall";
/// The corresponding runtime function name.
pub const FUNCTION_MIMICCALL: &'static str = "__mimiccall";
/// The corresponding runtime function name.
pub const FUNCTION_FARCALL_BYREF: &'static str = "__farcall_byref";
/// The corresponding runtime function name.
pub const FUNCTION_STATICCALL_BYREF: &'static str = "__staticcall_byref";
/// The corresponding runtime function name.
pub const FUNCTION_DELEGATECALL_BYREF: &'static str = "__delegatecall_byref";
/// The corresponding runtime function name.
pub const FUNCTION_MIMICCALL_BYREF: &'static str = "__mimiccall_byref";
/// The corresponding runtime function name.
pub const FUNCTION_RETURN: &'static str = "__return";
/// The corresponding runtime function name.
pub const FUNCTION_REVERT: &'static str = "__revert";
/// A shortcut constructor.
pub fn new(
llvm: &'ctx inkwell::context::Context,
module: &inkwell::module::Module<'ctx>,
optimizer: &Optimizer,
) -> Self {
let shl = Self::declare(
module,
Self::FUNCTION_SHL,
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
.fn_type(
vec![
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
.as_basic_type_enum()
.into();
2
]
.as_slice(),
false,
),
Some(inkwell::module::Linkage::External),
);
Function::set_default_attributes(llvm, shl, optimizer);
Function::set_pure_function_attributes(llvm, shl);
let shr = Self::declare(
module,
Self::FUNCTION_SHR,
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
.fn_type(
vec![
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
.as_basic_type_enum()
.into();
2
]
.as_slice(),
false,
),
Some(inkwell::module::Linkage::External),
);
Function::set_default_attributes(llvm, shr, optimizer);
Function::set_pure_function_attributes(llvm, shr);
let sar = Self::declare(
module,
Self::FUNCTION_SAR,
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
.fn_type(
vec![
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
.as_basic_type_enum()
.into();
2
]
.as_slice(),
false,
),
Some(inkwell::module::Linkage::External),
);
Function::set_default_attributes(llvm, sar, optimizer);
Function::set_pure_function_attributes(llvm, sar);
let byte = Self::declare(
module,
Self::FUNCTION_BYTE,
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
.fn_type(
vec![
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
.as_basic_type_enum()
.into();
2
]
.as_slice(),
false,
),
Some(inkwell::module::Linkage::External),
);
Function::set_default_attributes(llvm, byte, optimizer);
Function::set_pure_function_attributes(llvm, byte);
let add_mod =
Self::define(module, Self::FUNCTION_ADDMOD).expect("should be declared in stdlib");
Function::set_default_attributes(llvm, add_mod, optimizer);
@@ -236,54 +95,13 @@ impl<'ctx> LLVMRuntime<'ctx> {
false,
);
let r#return = Self::declare(
module,
Self::FUNCTION_RETURN,
llvm.void_type().fn_type(
vec![
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
.as_basic_type_enum()
.into();
3
]
.as_slice(),
false,
),
Some(inkwell::module::Linkage::External),
);
Function::set_default_attributes(llvm, r#return, optimizer);
let revert = Self::declare(
module,
Self::FUNCTION_REVERT,
llvm.void_type().fn_type(
vec![
llvm.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
.as_basic_type_enum()
.into();
3
]
.as_slice(),
false,
),
Some(inkwell::module::Linkage::External),
);
Function::set_default_attributes(llvm, revert, optimizer);
Self {
shl,
shr,
sar,
byte,
add_mod,
mul_mod,
exp,
sign_extend,
sha3,
r#return,
revert,
}
}
@@ -48,12 +48,6 @@ pub struct Function<'ctx> {
}
impl<'ctx> Function<'ctx> {
/// The near call ABI function prefix.
pub const ZKSYNC_NEAR_CALL_ABI_PREFIX: &'static str = "ZKSYNC_NEAR_CALL";
/// The near call ABI exception handler name.
pub const ZKSYNC_NEAR_CALL_ABI_EXCEPTION_HANDLER: &'static str = "ZKSYNC_CATCH_NEAR_CALL";
/// The stack hashmap default capacity.
const STACK_HASHMAP_INITIAL_CAPACITY: usize = 64;
@@ -91,13 +85,8 @@ impl<'ctx> Function<'ctx> {
|| (name.starts_with("__")
&& name != self::runtime::FUNCTION_ENTRY
&& name != self::runtime::FUNCTION_DEPLOY_CODE
&& name != self::runtime::FUNCTION_RUNTIME_CODE)
}
/// Checks whether the function is related to the near call ABI.
pub fn is_near_call_abi(name: &str) -> bool {
name.starts_with(Self::ZKSYNC_NEAR_CALL_ABI_PREFIX)
|| name == Self::ZKSYNC_NEAR_CALL_ABI_EXCEPTION_HANDLER
&& name != self::runtime::FUNCTION_RUNTIME_CODE
&& name != self::runtime::FUNCTION_LOAD_IMMUTABLE_DATA)
}
/// Returns the LLVM function declaration.
@@ -42,8 +42,7 @@ where
D: Dependency + Clone,
{
fn declare(&mut self, context: &mut Context<D>) -> anyhow::Result<()> {
let function_type =
context.function_type::<inkwell::types::BasicTypeEnum>(vec![], 0, false);
let function_type = context.function_type::<inkwell::types::BasicTypeEnum>(vec![], 0);
context.add_function(
runtime::FUNCTION_DEPLOY_CODE,
function_type,
@@ -1,12 +1,10 @@
//! The entry function.
use inkwell::types::BasicType;
use inkwell::values::BasicValue;
use crate::polkavm::context::address_space::AddressSpace;
use crate::polkavm::context::function::runtime;
use crate::polkavm::context::Context;
use crate::polkavm::r#const::*;
use crate::polkavm::Dependency;
use crate::polkavm::WriteLLVM;
@@ -20,14 +18,8 @@ impl Entry {
/// The call flags argument index.
pub const ARGUMENT_INDEX_CALL_FLAGS: usize = 0;
/// The number of mandatory arguments.
pub const MANDATORY_ARGUMENTS_COUNT: usize = 2;
/// Reserve 1mb for calldata.
pub const MAX_CALLDATA_SIZE: usize = 1024 * 1024;
/// Reserve 1mb for returndata.
pub const MAX_RETURNDATA_SIZE: usize = 1024 * 1024;
/// Reserve 1kb for calldata.
pub const MAX_CALLDATA_SIZE: usize = 1024;
/// Initializes the global variables.
/// The pointers are not initialized, because it's not possible to create a null pointer.
@@ -35,6 +27,18 @@ impl Entry {
where
D: Dependency + Clone,
{
context.declare_global(
revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_POINTER,
context.word_type().array_type(0),
AddressSpace::Stack,
);
context.declare_global(
revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_SIZE,
context.xlen_type(),
AddressSpace::Stack,
);
let calldata_type = context.array_type(context.byte_type(), Self::MAX_CALLDATA_SIZE);
context.set_global(
crate::polkavm::GLOBAL_CALLDATA_POINTER,
@@ -43,14 +47,6 @@ impl Entry {
calldata_type.get_undef(),
);
let returndata_type = context.array_type(context.byte_type(), Self::MAX_RETURNDATA_SIZE);
context.set_global(
crate::polkavm::GLOBAL_RETURN_DATA_POINTER,
returndata_type,
AddressSpace::Stack,
returndata_type.get_undef(),
);
context.set_global(
crate::polkavm::GLOBAL_HEAP_MEMORY_POINTER,
context.llvm().ptr_type(AddressSpace::Heap.into()),
@@ -61,7 +57,10 @@ impl Entry {
context
.get_global(crate::polkavm::GLOBAL_HEAP_MEMORY_POINTER)?
.into(),
context.build_sbrk(context.integer_const(crate::polkavm::XLEN, 0))?,
context.build_sbrk(
context.xlen_type().const_zero(),
context.xlen_type().const_zero(),
)?,
)?;
context.set_global(
@@ -70,12 +69,6 @@ impl Entry {
AddressSpace::Stack,
context.word_undef(),
);
context.set_global(
crate::polkavm::GLOBAL_RETURN_DATA_SIZE,
context.xlen_type(),
AddressSpace::Stack,
context.xlen_type().const_zero().as_basic_value_enum(),
);
context.set_global(
crate::polkavm::GLOBAL_CALL_FLAGS,
@@ -84,33 +77,6 @@ impl Entry {
context.word_const(0),
);
context.set_global(
crate::polkavm::GLOBAL_I256_SIZE,
context.xlen_type(),
AddressSpace::Stack,
context.integer_const(
crate::polkavm::XLEN,
revive_common::BYTE_LENGTH_X64 as u64 * 4,
),
);
context.set_global(
crate::polkavm::GLOBAL_I160_SIZE,
context.xlen_type(),
AddressSpace::Stack,
context.integer_const(
crate::polkavm::XLEN,
revive_common::BYTE_LENGTH_X64 as u64 * 2 + revive_common::BYTE_LENGTH_X32 as u64,
),
);
context.set_global(
crate::polkavm::GLOBAL_I64_SIZE,
context.xlen_type(),
AddressSpace::Stack,
context.integer_const(crate::polkavm::XLEN, revive_common::BYTE_LENGTH_X64 as u64),
);
Ok(())
}
@@ -130,7 +96,7 @@ impl Entry {
"input_pointer_casted",
)?;
let length_pointer = context.build_alloca(context.xlen_type(), "len_ptr");
let length_pointer = context.build_alloca_at_entry(context.xlen_type(), "len_ptr");
let length_pointer_casted = context.builder.build_ptr_to_int(
length_pointer.value,
context.xlen_type(),
@@ -142,7 +108,7 @@ impl Entry {
context.integer_const(crate::polkavm::XLEN, Self::MAX_CALLDATA_SIZE as u64),
)?;
context.build_runtime_call(
runtime_api::imports::INPUT,
revive_runtime_api::polkavm_imports::INPUT,
&[input_pointer_casted.into(), length_pointer_casted.into()],
);
@@ -221,7 +187,7 @@ where
{
fn declare(&mut self, context: &mut Context<D>) -> anyhow::Result<()> {
let entry_arguments = vec![context.bool_type().as_basic_type_enum()];
let entry_function_type = context.function_type(entry_arguments, 0, false);
let entry_function_type = context.function_type(entry_arguments, 0);
context.add_function(
runtime::FUNCTION_ENTRY,
entry_function_type,
@@ -0,0 +1,116 @@
//! The immutable data runtime function.
use crate::polkavm::context::address_space::AddressSpace;
use crate::polkavm::context::function::runtime;
use crate::polkavm::context::pointer::Pointer;
use crate::polkavm::context::Context;
use crate::polkavm::Dependency;
use crate::polkavm::WriteLLVM;
/// A function for requesting the immutable data from the runtime.
/// This is a special function that is only used by the front-end generated code.
///
/// The runtime API is called lazily and subsequent calls are no-ops.
///
/// The bytes written is asserted to match the expected length.
/// This should never fail; the length is known.
/// However, this is a one time assertion, hence worth it.
#[derive(Debug)]
pub struct ImmutableDataLoad;
impl<D> WriteLLVM<D> for ImmutableDataLoad
where
D: Dependency + Clone,
{
fn declare(&mut self, context: &mut Context<D>) -> anyhow::Result<()> {
context.add_function(
runtime::FUNCTION_LOAD_IMMUTABLE_DATA,
context.void_type().fn_type(Default::default(), false),
0,
Some(inkwell::module::Linkage::Private),
)?;
Ok(())
}
fn into_llvm(self, context: &mut Context<D>) -> anyhow::Result<()> {
context.set_current_function(runtime::FUNCTION_LOAD_IMMUTABLE_DATA)?;
context.set_basic_block(context.current_function().borrow().entry_block());
let immutable_data_size_pointer = context
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_SIZE)?
.value
.as_pointer_value();
let immutable_data_size = context.build_load(
Pointer::new(
context.xlen_type(),
AddressSpace::Stack,
immutable_data_size_pointer,
),
"immutable_data_size_load",
)?;
let load_immutable_data_block = context.append_basic_block("load_immutables_block");
let return_block = context.current_function().borrow().return_block();
let immutable_data_size_is_zero = context.builder().build_int_compare(
inkwell::IntPredicate::EQ,
context.xlen_type().const_zero(),
immutable_data_size.into_int_value(),
"immutable_data_size_is_zero",
)?;
context.build_conditional_branch(
immutable_data_size_is_zero,
return_block,
load_immutable_data_block,
)?;
context.set_basic_block(load_immutable_data_block);
let output_pointer = context
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_POINTER)?
.value
.as_pointer_value();
context.build_runtime_call(
revive_runtime_api::polkavm_imports::GET_IMMUTABLE_DATA,
&[
context
.builder()
.build_ptr_to_int(output_pointer, context.xlen_type(), "ptr_to_xlen")?
.into(),
context
.builder()
.build_ptr_to_int(
immutable_data_size_pointer,
context.xlen_type(),
"ptr_to_xlen",
)?
.into(),
],
);
let bytes_written = context.builder().build_load(
context.xlen_type(),
immutable_data_size_pointer,
"bytes_written",
)?;
context.builder().build_store(
immutable_data_size_pointer,
context.xlen_type().const_zero(),
)?;
let overflow_block = context.append_basic_block("immutable_data_overflow");
let is_overflow = context.builder().build_int_compare(
inkwell::IntPredicate::UGT,
immutable_data_size.into_int_value(),
bytes_written.into_int_value(),
"is_overflow",
)?;
context.build_conditional_branch(is_overflow, overflow_block, return_block)?;
context.set_basic_block(overflow_block);
context.build_call(context.intrinsics().trap, &[], "invalid_trap");
context.build_unreachable();
context.set_basic_block(return_block);
context.build_return(None);
Ok(())
}
}
@@ -2,6 +2,7 @@
pub mod deploy_code;
pub mod entry;
pub mod immutable_data_load;
pub mod runtime_code;
/// The main entry function name.
@@ -12,3 +13,6 @@ pub const FUNCTION_DEPLOY_CODE: &str = "__deploy";
/// The runtime code function name.
pub const FUNCTION_RUNTIME_CODE: &str = "__runtime";
/// The immutable data load function name.
pub const FUNCTION_LOAD_IMMUTABLE_DATA: &str = "__immutable_data_load";
@@ -42,8 +42,7 @@ where
D: Dependency + Clone,
{
fn declare(&mut self, context: &mut Context<D>) -> anyhow::Result<()> {
let function_type =
context.function_type::<inkwell::types::BasicTypeEnum>(vec![], 0, false);
let function_type = context.function_type::<inkwell::types::BasicTypeEnum>(vec![], 0);
context.add_function(
runtime::FUNCTION_RUNTIME_CODE,
function_type,
@@ -51,4 +51,31 @@ impl<'ctx> Global<'ctx> {
global
}
/// Construct an external global.
pub fn declare<D, T>(
context: &mut Context<'ctx, D>,
r#type: T,
address_space: AddressSpace,
name: &str,
) -> Self
where
D: PolkaVMDependency + Clone,
T: BasicType<'ctx>,
{
let r#type = r#type.as_basic_type_enum();
let value = context
.module()
.add_global(r#type, Some(address_space.into()), name);
let global = Self { r#type, value };
global.value.set_linkage(inkwell::module::Linkage::External);
global
.value
.set_visibility(inkwell::GlobalVisibility::Default);
global.value.set_externally_initialized(true);
global
}
}
+121 -143
View File
@@ -26,7 +26,6 @@ use inkwell::values::BasicValue;
use crate::optimizer::settings::Settings as OptimizerSettings;
use crate::optimizer::Optimizer;
use crate::polkavm::r#const::*;
use crate::polkavm::DebugConfig;
use crate::polkavm::Dependency;
use crate::target_machine::target::Target;
@@ -136,7 +135,7 @@ where
)
.expect("the PolkaVM imports module should be linkable");
for import in runtime_api::imports::IMPORTS {
for import in revive_runtime_api::polkavm_imports::IMPORTS {
module
.get_function(import)
.expect("should be declared")
@@ -162,6 +161,18 @@ where
})
}
fn link_immutable_data(&self, contract_path: &str) -> anyhow::Result<()> {
let size = self.solidity().immutables_size() as u32;
let exports = revive_runtime_api::immutable_data::module(self.llvm(), size);
self.module.link_in_module(exports).map_err(|error| {
anyhow::anyhow!(
"The contract `{}` immutable data module linking error: {}",
contract_path,
error
)
})
}
/// Configure the PolkaVM minimum stack size.
fn set_polkavm_stack_size(
llvm: &'ctx inkwell::context::Context,
@@ -239,6 +250,7 @@ where
let module_clone = self.module.clone();
self.link_polkavm_exports(contract_path)?;
self.link_immutable_data(contract_path)?;
let target_machine = TargetMachine::new(Target::PVM, self.optimizer.settings())?;
target_machine.set_target_data(self.module());
@@ -381,6 +393,15 @@ where
}
}
/// Declare an external global.
pub fn declare_global<T>(&mut self, name: &str, r#type: T, address_space: AddressSpace)
where
T: BasicType<'ctx> + Clone + Copy,
{
let global = Global::declare(self, r#type, address_space, name);
self.globals.insert(name.to_owned(), global);
}
/// Returns the LLVM intrinsics collection reference.
pub fn intrinsics(&self) -> &Intrinsics<'ctx> {
&self.intrinsics
@@ -391,47 +412,14 @@ where
&self.llvm_runtime
}
/// Declare a function already existing in the module.
pub fn declare_extern_function(
&mut self,
name: &str,
) -> anyhow::Result<Rc<RefCell<Function<'ctx>>>> {
let function = self.module().get_function(name).ok_or_else(|| {
anyhow::anyhow!("Failed to activate an undeclared function `{}`", name)
})?;
let basic_block = self.llvm.append_basic_block(function, name);
let declaration = FunctionDeclaration::new(
self.function_type::<inkwell::types::BasicTypeEnum>(vec![], 0, false),
function,
);
let function = Function::new(
name.to_owned(),
declaration,
FunctionReturn::None,
basic_block,
basic_block,
);
Function::set_default_attributes(self.llvm, function.declaration(), &self.optimizer);
let function = Rc::new(RefCell::new(function));
self.functions.insert(name.to_string(), function.clone());
Ok(function)
}
/// Appends a function to the current module.
pub fn add_function(
&mut self,
name: &str,
r#type: inkwell::types::FunctionType<'ctx>,
return_values_length: usize,
mut linkage: Option<inkwell::module::Linkage>,
linkage: Option<inkwell::module::Linkage>,
) -> anyhow::Result<Rc<RefCell<Function<'ctx>>>> {
if Function::is_near_call_abi(name) && self.is_system_mode() {
linkage = Some(inkwell::module::Linkage::External);
}
let value = self.module().add_function(name, r#type, linkage);
let entry_block = self.llvm.append_basic_block(value, "entry");
@@ -444,12 +432,6 @@ where
let pointer = self.build_alloca(self.word_type(), "return_pointer");
FunctionReturn::primitive(pointer)
}
size if name.starts_with(Function::ZKSYNC_NEAR_CALL_ABI_PREFIX) => {
let first_argument = value.get_first_param().expect("Always exists");
let r#type = self.structure_type(vec![self.word_type(); size].as_slice());
let pointer = first_argument.into_pointer_value();
FunctionReturn::compound(Pointer::new(r#type, AddressSpace::Stack, pointer), size)
}
size => {
self.set_basic_block(entry_block);
let pointer = self.build_alloca(
@@ -470,10 +452,6 @@ where
return_block,
);
Function::set_default_attributes(self.llvm, function.declaration(), &self.optimizer);
if Function::is_near_call_abi(function.name()) && self.is_system_mode() {
Function::set_exception_handler_attributes(self.llvm, function.declaration());
}
let function = Rc::new(RefCell::new(function));
self.functions.insert(name.to_string(), function.clone());
@@ -534,10 +512,6 @@ where
manager,
name,
self.optimizer.settings().to_owned(),
self.yul_data
.as_ref()
.map(|data| data.is_system_mode())
.unwrap_or_default(),
self.include_metadata_hash,
self.debug_config.clone(),
)
@@ -595,59 +569,70 @@ where
self.builder.get_insert_block().expect("Always exists")
}
/// Builds a stack allocation instruction.
/// Sets the alignment to 128 bits.
/// Builds an aligned stack allocation at the function entry.
pub fn build_alloca_at_entry<T: BasicType<'ctx> + Clone + Copy>(
&self,
r#type: T,
name: &str,
) -> Pointer<'ctx> {
let current_block = self.basic_block();
let entry_block = self.current_function().borrow().entry_block();
match entry_block.get_first_instruction() {
Some(instruction) => self.builder().position_before(&instruction),
None => self.builder().position_at_end(entry_block),
}
let pointer = self.build_alloca(r#type, name);
self.set_basic_block(current_block);
pointer
}
/// Builds an aligned stack allocation at the current position.
/// Use this if [`build_alloca_at_entry`] might change program semantics.
/// Otherwise, alloca should always be built at the function prelude!
pub fn build_alloca<T: BasicType<'ctx> + Clone + Copy>(
&self,
r#type: T,
name: &str,
) -> Pointer<'ctx> {
let pointer = self.builder.build_alloca(r#type, name).unwrap();
self.basic_block()
.get_last_instruction()
.expect("Always exists")
pointer
.as_instruction()
.unwrap()
.set_alignment(revive_common::BYTE_LENGTH_STACK_ALIGN as u32)
.expect("Alignment is valid");
Pointer::new(r#type, AddressSpace::Stack, pointer)
}
/// Allocate an int of size `bit_length` on the stack.
/// Returns the allocation pointer and the length pointer.
///
/// Useful helper for passing runtime API parameters on the stack.
pub fn build_stack_parameter(
/// Truncate `address` to the ethereum address length and store it as bytes on the stack.
/// The stack allocation will be at the function entry. Returns the stack pointer.
/// This helper should be used when passing address arguments to the runtime, ensuring correct size and endianness.
pub fn build_address_argument_store(
&self,
bit_length: usize,
name: &str,
) -> (Pointer<'ctx>, Pointer<'ctx>) {
let buffer_pointer = self.build_alloca(self.integer_type(bit_length), name);
let symbol = match bit_length {
revive_common::BIT_LENGTH_WORD => GLOBAL_I256_SIZE,
revive_common::BIT_LENGTH_ETH_ADDRESS => GLOBAL_I160_SIZE,
revive_common::BIT_LENGTH_BLOCK_NUMBER => GLOBAL_I64_SIZE,
_ => panic!("invalid stack parameter bit width: {bit_length}"),
};
let length_pointer = self.get_global(symbol).expect("should be declared");
(buffer_pointer, length_pointer.into())
address: inkwell::values::IntValue<'ctx>,
) -> anyhow::Result<Pointer<'ctx>> {
let address_type = self.integer_type(revive_common::BIT_LENGTH_ETH_ADDRESS);
let address_pointer = self.build_alloca_at_entry(address_type, "address_pointer");
let address_truncated =
self.builder()
.build_int_truncate(address, address_type, "address_truncated")?;
let address_swapped = self.build_byte_swap(address_truncated.into())?;
self.build_store(address_pointer, address_swapped)?;
Ok(address_pointer)
}
/// Load the integer at given pointer and zero extend it to the VM word size.
pub fn build_load_word(
/// Load the address at given pointer and zero extend it to the VM word size.
pub fn build_load_address(
&self,
pointer: Pointer<'ctx>,
bit_length: usize,
name: &str,
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>> {
let value = self.build_load(
pointer.cast(self.integer_type(bit_length)),
&format!("load_{name}"),
)?;
let value_extended = self.builder().build_int_z_extend(
value.into_int_value(),
self.word_type(),
&format!("zext_{name}"),
)?;
Ok(value_extended.as_basic_value_enum())
let address = self.build_byte_swap(self.build_load(pointer, "address_pointer")?)?;
Ok(self
.builder()
.build_int_z_extend(address.into_int_value(), self.word_type(), "address_zext")?
.into())
}
/// Builds a stack load instruction.
@@ -710,7 +695,7 @@ where
let transient = pointer.address_space == AddressSpace::TransientStorage;
self.build_runtime_call(
runtime_api::imports::GET_STORAGE,
revive_runtime_api::polkavm_imports::GET_STORAGE,
&[
self.xlen_type().const_int(transient as u64, false).into(),
storage_key_pointer_casted.into(),
@@ -809,7 +794,7 @@ where
let transient = pointer.address_space == AddressSpace::TransientStorage;
self.build_runtime_call(
runtime_api::imports::SET_STORAGE,
revive_runtime_api::polkavm_imports::SET_STORAGE,
&[
self.xlen_type().const_int(transient as u64, false).into(),
storage_key_pointer_casted.into(),
@@ -921,13 +906,29 @@ where
.copied()
.map(inkwell::values::BasicMetadataValueEnum::from)
.collect::<Vec<_>>(),
&format!("runtime API call {name}"),
&format!("runtime_api_{name}_return_value"),
)
.unwrap()
.try_as_basic_value()
.left()
}
/// Builds a call to the runtime API `import`, where `import` is a "getter" API.
/// This means that the supplied API method just writes back a single word.
/// `import` is thus expect to have a single parameter, the 32 bytes output buffer,
/// and no return value.
pub fn build_runtime_call_to_getter(
&self,
import: &'static str,
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
where
D: Dependency + Clone,
{
let pointer = self.build_alloca_at_entry(self.word_type(), &format!("{import}_output"));
self.build_runtime_call(import, &[pointer.to_int(self).into()]);
self.build_load(pointer, import)
}
/// Builds a call.
pub fn build_call(
&self,
@@ -1028,7 +1029,7 @@ where
)?;
self.build_runtime_call(
runtime_api::imports::RETURN,
revive_runtime_api::polkavm_imports::RETURN,
&[flags.into(), offset_pointer.into(), length_pointer.into()],
);
self.build_unreachable();
@@ -1086,16 +1087,20 @@ where
Ok(truncated)
}
/// Build a call to PolkaVM `sbrk` for extending the heap by `size`.
/// Build a call to PolkaVM `sbrk` for extending the heap from offset by `size`.
/// The allocation is aligned to 32 bytes.
///
/// This emulates the EVM linear memory until the runtime supports metered memory.
pub fn build_sbrk(
&self,
offset: inkwell::values::IntValue<'ctx>,
size: inkwell::values::IntValue<'ctx>,
) -> anyhow::Result<inkwell::values::PointerValue<'ctx>> {
Ok(self
.builder()
.build_call(
self.runtime_api_method(runtime_api::SBRK),
&[size.into()],
self.runtime_api_method(revive_runtime_api::polkavm_imports::SBRK),
&[offset.into(), size.into()],
"call_sbrk",
)?
.try_as_basic_value()
@@ -1104,14 +1109,29 @@ where
.into_pointer_value())
}
/// Call PolkaVM `sbrk` for extending the heap by `size`,
/// Build a call to PolkaVM `msize` for querying the linear memory size.
pub fn build_msize(&self) -> anyhow::Result<inkwell::values::IntValue<'ctx>> {
Ok(self
.builder()
.build_call(
self.runtime_api_method(revive_runtime_api::polkavm_imports::MEMORY_SIZE),
&[],
"call_msize",
)?
.try_as_basic_value()
.left()
.expect("sbrk returns an int")
.into_int_value())
}
/// Call PolkaVM `sbrk` for extending the heap by `offset` + `size`,
/// trapping the contract if the call failed.
/// Returns the end of memory pointer.
pub fn build_heap_alloc(
&self,
offset: inkwell::values::IntValue<'ctx>,
size: inkwell::values::IntValue<'ctx>,
) -> anyhow::Result<inkwell::values::PointerValue<'ctx>> {
let end_of_memory = self.build_sbrk(size)?;
) -> anyhow::Result<()> {
let end_of_memory = self.build_sbrk(offset, size)?;
let return_is_nil = self.builder().build_int_compare(
inkwell::IntPredicate::EQ,
end_of_memory,
@@ -1129,7 +1149,7 @@ where
self.set_basic_block(continue_block);
Ok(end_of_memory)
Ok(())
}
/// Returns a pointer to `offset` into the heap, allocating
@@ -1144,40 +1164,12 @@ where
assert_eq!(offset.get_type(), self.xlen_type());
assert_eq!(length.get_type(), self.xlen_type());
self.build_heap_alloc(offset, length)?;
let heap_start = self
.get_global(crate::polkavm::GLOBAL_HEAP_MEMORY_POINTER)?
.value
.as_pointer_value();
let heap_end = self.build_sbrk(self.integer_const(crate::polkavm::XLEN, 0))?;
let value_end = self.build_gep(
Pointer::new(self.byte_type(), AddressSpace::Stack, heap_start),
&[self.builder().build_int_nuw_add(offset, length, "end")?],
self.byte_type(),
"heap_end_gep",
);
let is_out_of_bounds = self.builder().build_int_compare(
inkwell::IntPredicate::UGT,
value_end.value,
heap_end,
"is_value_overflowing_heap",
)?;
let out_of_bounds_block = self.append_basic_block("heap_offset_out_of_bounds");
let heap_offset_block = self.append_basic_block("build_heap_pointer");
self.build_conditional_branch(is_out_of_bounds, out_of_bounds_block, heap_offset_block)?;
self.set_basic_block(out_of_bounds_block);
let size = self.builder().build_int_nuw_sub(
self.builder()
.build_ptr_to_int(value_end.value, self.xlen_type(), "value_end")?,
self.builder()
.build_ptr_to_int(heap_end, self.xlen_type(), "heap_end")?,
"heap_alloc_size",
)?;
self.build_heap_alloc(size)?;
self.build_unconditional_branch(heap_offset_block);
self.set_basic_block(heap_offset_block);
Ok(self.build_gep(
Pointer::new(self.byte_type(), AddressSpace::Stack, heap_start),
&[offset],
@@ -1298,12 +1290,11 @@ where
&self,
argument_types: Vec<T>,
return_values_size: usize,
is_near_call_abi: bool,
) -> inkwell::types::FunctionType<'ctx>
where
T: BasicType<'ctx>,
{
let mut argument_types: Vec<inkwell::types::BasicMetadataTypeEnum> = argument_types
let argument_types: Vec<inkwell::types::BasicMetadataTypeEnum> = argument_types
.as_slice()
.iter()
.map(T::as_basic_type_enum)
@@ -1315,11 +1306,6 @@ where
.void_type()
.fn_type(argument_types.as_slice(), false),
1 => self.word_type().fn_type(argument_types.as_slice(), false),
_size if is_near_call_abi && self.is_system_mode() => {
let return_type = self.llvm().ptr_type(AddressSpace::Stack.into());
argument_types.insert(0, return_type.as_basic_type_enum().into());
return_type.fn_type(argument_types.as_slice(), false)
}
size => self
.structure_type(vec![self.word_type().as_basic_type_enum(); size].as_slice())
.fn_type(argument_types.as_slice(), false),
@@ -1512,12 +1498,4 @@ where
anyhow::bail!("The immutable size data is not available");
}
}
/// Whether the system mode is enabled.
pub fn is_system_mode(&self) -> bool {
self.yul_data
.as_ref()
.map(|data| data.is_system_mode())
.unwrap_or_default()
}
}
@@ -17,7 +17,7 @@ impl SolidityData {
Self::default()
}
/// Returns the current number of immutables values in the contract.
/// Returns the current size of immutable values in the contract.
pub fn immutables_size(&self) -> usize {
self.immutables.len() * revive_common::BYTE_LENGTH_WORD
}
@@ -8,28 +8,12 @@ use num::Zero;
/// Describes some data that is only relevant to Yul.
#[derive(Debug, Default)]
pub struct YulData {
/// The system mode flag.
/// The call simulations only work if this mode is enabled.
is_system_mode: bool,
/// The list of constant arrays in the code section.
/// It is a temporary storage used until the finalization method is called.
const_arrays: BTreeMap<u8, Vec<num::BigUint>>,
}
impl YulData {
/// A shortcut constructor.
pub fn new(is_system_mode: bool) -> Self {
Self {
is_system_mode,
const_arrays: BTreeMap::new(),
}
}
/// Whether the system mode is enabled.
pub fn is_system_mode(&self) -> bool {
self.is_system_mode
}
/// Declares a temporary constant array representation.
pub fn const_array_declare(&mut self, index: u8, size: u16) -> anyhow::Result<()> {
if self.const_arrays.contains_key(&index) {
+43 -41
View File
@@ -5,18 +5,15 @@ use inkwell::values::BasicValue;
use crate::polkavm::context::argument::Argument;
use crate::polkavm::context::Context;
use crate::polkavm::Dependency;
use crate::polkavm_const::runtime_api;
static STATIC_CALL_FLAG: u32 = 0b0001_0000;
const STATIC_CALL_FLAG: u32 = 0b0001_0000;
const REENTRANT_CALL_FLAG: u32 = 0b0000_1000;
/// Translates a contract call.
///
/// If the `simulation_address` is specified, the call is
/// substituted with another instruction according to the specification.
#[allow(clippy::too_many_arguments)]
pub fn call<'ctx, D>(
context: &mut Context<'ctx, D>,
gas: inkwell::values::IntValue<'ctx>,
_gas: inkwell::values::IntValue<'ctx>,
address: inkwell::values::IntValue<'ctx>,
value: Option<inkwell::values::IntValue<'ctx>>,
input_offset: inkwell::values::IntValue<'ctx>,
@@ -29,59 +26,64 @@ pub fn call<'ctx, D>(
where
D: Dependency + Clone,
{
let address_pointer = context.build_alloca(context.word_type(), "address_ptr");
context.build_store(address_pointer, address)?;
let address_pointer = context.build_address_argument_store(address)?;
let value_pointer = if let Some(value) = value {
let value_pointer = context.build_alloca(context.value_type(), "value");
context.build_store(value_pointer, value)?;
value_pointer
} else {
context.sentinel_pointer()
};
let value = value.unwrap_or_else(|| context.word_const(0));
let value_pointer = context.build_alloca_at_entry(context.word_type(), "value_pointer");
context.build_store(value_pointer, value)?;
let input_offset = context.safe_truncate_int_to_xlen(input_offset)?;
let input_length = context.safe_truncate_int_to_xlen(input_length)?;
let output_offset = context.safe_truncate_int_to_xlen(output_offset)?;
let output_length = context.safe_truncate_int_to_xlen(output_length)?;
let gas = context
// TODO: What to supply here? Is there a weight to gas?
let _gas = context
.builder()
.build_int_truncate(gas, context.integer_type(64), "gas")?;
let flags = if static_call { STATIC_CALL_FLAG } else { 0 };
.build_int_truncate(_gas, context.integer_type(64), "gas")?;
let input_pointer = context.build_heap_gep(input_offset, input_length)?;
let output_pointer = context.build_heap_gep(output_offset, output_length)?;
let output_length_pointer = context.get_global(crate::polkavm::GLOBAL_RETURN_DATA_SIZE)?;
context.build_store(output_length_pointer.into(), output_length)?;
let output_length_pointer = context.build_alloca_at_entry(context.xlen_type(), "output_length");
context.build_store(output_length_pointer, output_length)?;
let argument_pointer = revive_runtime_api::calling_convention::Spill::new(
let flags = if static_call {
REENTRANT_CALL_FLAG | STATIC_CALL_FLAG
} else {
REENTRANT_CALL_FLAG
};
let flags = context.xlen_type().const_int(flags as u64, false);
let argument_type = revive_runtime_api::calling_convention::call(context.llvm());
let argument_pointer = context.build_alloca_at_entry(argument_type, "call_arguments");
let arguments = &[
flags.as_basic_value_enum(),
address_pointer.value.as_basic_value_enum(),
context.integer_const(64, 0).as_basic_value_enum(),
context.integer_const(64, 0).as_basic_value_enum(),
context.sentinel_pointer().value.as_basic_value_enum(),
value_pointer.value.as_basic_value_enum(),
input_pointer.value.as_basic_value_enum(),
input_length.as_basic_value_enum(),
output_pointer.value.as_basic_value_enum(),
output_length_pointer.value.as_basic_value_enum(),
];
revive_runtime_api::calling_convention::spill(
context.builder(),
revive_runtime_api::calling_convention::call(context.llvm()),
"call_arguments",
)?
.next(context.xlen_type().const_int(flags as u64, false))?
.next(address_pointer.value)?
.next(gas)?
.skip()
.next(context.sentinel_pointer().value)?
.next(value_pointer.value)?
.next(input_pointer.value)?
.next(input_length)?
.next(output_pointer.value)?
.next(output_length_pointer.value)?
.done();
argument_pointer.value,
argument_type,
arguments,
)?;
let name = runtime_api::imports::CALL;
let arguments = context.builder().build_ptr_to_int(
argument_pointer,
let name = revive_runtime_api::polkavm_imports::CALL;
let argument_pointer = context.builder().build_ptr_to_int(
argument_pointer.value,
context.xlen_type(),
"argument_pointer",
"call_argument_pointer",
)?;
let success = context
.build_runtime_call(name, &[arguments.into()])
.build_runtime_call(name, &[argument_pointer.into()])
.unwrap_or_else(|| panic!("{name} should return a value"))
.into_int_value();
+19 -87
View File
@@ -4,7 +4,6 @@ use inkwell::values::BasicValue;
use crate::polkavm::context::Context;
use crate::polkavm::Dependency;
use crate::polkavm_const::runtime_api;
/// Translates the `gas_limit` instruction.
pub fn gas_limit<'ctx, D>(
@@ -43,7 +42,7 @@ pub fn chain_id<'ctx, D>(
where
D: Dependency + Clone,
{
Ok(context.word_const(0).as_basic_value_enum())
context.build_runtime_call_to_getter(revive_runtime_api::polkavm_imports::CHAIN_ID)
}
/// Translates the `block_number` instruction.
@@ -53,22 +52,7 @@ pub fn block_number<'ctx, D>(
where
D: Dependency + Clone,
{
let (output_pointer, output_length_pointer) = context.build_stack_parameter(
revive_common::BIT_LENGTH_BLOCK_NUMBER,
"block_timestamp_output",
);
context.build_runtime_call(
runtime_api::imports::BLOCK_NUMBER,
&[
output_pointer.to_int(context).into(),
output_length_pointer.to_int(context).into(),
],
);
context.build_load_word(
output_pointer,
revive_common::BIT_LENGTH_BLOCK_NUMBER,
"block_number",
)
context.build_runtime_call_to_getter(revive_runtime_api::polkavm_imports::BLOCK_NUMBER)
}
/// Translates the `block_timestamp` instruction.
@@ -78,22 +62,7 @@ pub fn block_timestamp<'ctx, D>(
where
D: Dependency + Clone,
{
let (output_pointer, output_length_pointer) = context.build_stack_parameter(
revive_common::BIT_LENGTH_BLOCK_TIMESTAMP,
"block_timestamp_output",
);
context.build_runtime_call(
runtime_api::imports::NOW,
&[
output_pointer.to_int(context).into(),
output_length_pointer.to_int(context).into(),
],
);
context.build_load_word(
output_pointer,
revive_common::BIT_LENGTH_BLOCK_TIMESTAMP,
"block_timestamp",
)
context.build_runtime_call_to_getter(revive_runtime_api::polkavm_imports::NOW)
}
/// Translates the `block_hash` instruction.
@@ -137,33 +106,6 @@ where
Ok(context.word_const(0).as_basic_value_enum())
}
/// Translates the `msize` instruction.
pub fn msize<'ctx, D>(
context: &mut Context<'ctx, D>,
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
where
D: Dependency + Clone,
{
let heap_end = context.build_sbrk(context.xlen_type().const_zero())?;
let heap_start = context
.get_global(crate::polkavm::GLOBAL_HEAP_MEMORY_POINTER)?
.value
.as_pointer_value();
let heap_size = context.builder().build_int_nuw_sub(
context
.builder()
.build_ptr_to_int(heap_end, context.xlen_type(), "heap_end")?,
context
.builder()
.build_ptr_to_int(heap_start, context.xlen_type(), "heap_start")?,
"heap_size",
)?;
Ok(context
.builder()
.build_int_z_extend(heap_size, context.word_type(), "heap_size_extended")?
.as_basic_value_enum())
}
/// Translates the `address` instruction.
pub fn address<'ctx, D>(
context: &mut Context<'ctx, D>,
@@ -171,20 +113,15 @@ pub fn address<'ctx, D>(
where
D: Dependency + Clone,
{
let (output_pointer, output_length_pointer) =
context.build_stack_parameter(revive_common::BIT_LENGTH_ETH_ADDRESS, "address_output");
context.build_runtime_call(
runtime_api::imports::ADDRESS,
&[
output_pointer.to_int(context).into(),
output_length_pointer.to_int(context).into(),
],
let pointer = context.build_alloca_at_entry(
context.integer_type(revive_common::BIT_LENGTH_ETH_ADDRESS),
"address_output",
);
let value = context.build_byte_swap(context.build_load(output_pointer, "address")?)?;
Ok(context
.builder()
.build_int_z_extend(value.into_int_value(), context.word_type(), "address_zext")?
.into())
context.build_runtime_call(
revive_runtime_api::polkavm_imports::ADDRESS,
&[pointer.to_int(context).into()],
);
context.build_load_address(pointer)
}
/// Translates the `caller` instruction.
@@ -194,18 +131,13 @@ pub fn caller<'ctx, D>(
where
D: Dependency + Clone,
{
let (output_pointer, output_length_pointer) =
context.build_stack_parameter(revive_common::BIT_LENGTH_ETH_ADDRESS, "caller_output");
context.build_runtime_call(
runtime_api::imports::CALLER,
&[
output_pointer.to_int(context).into(),
output_length_pointer.to_int(context).into(),
],
let pointer = context.build_alloca_at_entry(
context.integer_type(revive_common::BIT_LENGTH_ETH_ADDRESS),
"address_output",
);
let value = context.build_byte_swap(context.build_load(output_pointer, "caller")?)?;
Ok(context
.builder()
.build_int_z_extend(value.into_int_value(), context.word_type(), "caller_zext")?
.into())
context.build_runtime_call(
revive_runtime_api::polkavm_imports::CALLER,
&[pointer.to_int(context).into()],
);
context.build_load_address(pointer)
}
+55 -56
View File
@@ -7,28 +7,15 @@ use crate::polkavm::context::argument::Argument;
use crate::polkavm::context::code_type::CodeType;
use crate::polkavm::context::Context;
use crate::polkavm::Dependency;
use crate::polkavm_const::runtime_api;
/// Translates the contract `create` instruction.
/// The instruction is simulated by a call to a system contract.
/// Translates the contract `create` and `create2` instruction.
///
/// A `salt` value of `None` is equivalent to `create1`.
pub fn create<'ctx, D>(
context: &mut Context<'ctx, D>,
value: inkwell::values::IntValue<'ctx>,
input_offset: inkwell::values::IntValue<'ctx>,
input_length: inkwell::values::IntValue<'ctx>,
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
where
D: Dependency + Clone,
{
self::create2(context, value, input_offset, input_length, None)
}
/// Translates the contract `create2` instruction.
pub fn create2<'ctx, D>(
context: &mut Context<'ctx, D>,
value: inkwell::values::IntValue<'ctx>,
input_offset: inkwell::values::IntValue<'ctx>,
input_length: inkwell::values::IntValue<'ctx>,
salt: Option<inkwell::values::IntValue<'ctx>>,
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
where
@@ -37,9 +24,6 @@ where
let input_offset = context.safe_truncate_int_to_xlen(input_offset)?;
let input_length = context.safe_truncate_int_to_xlen(input_length)?;
let value_pointer = context.build_alloca(context.value_type(), "value");
context.build_store(value_pointer, value)?;
let code_hash_pointer = context.build_heap_gep(input_offset, input_length)?;
let input_data_pointer = context.build_gep(
@@ -48,53 +32,68 @@ where
.xlen_type()
.const_int(revive_common::BYTE_LENGTH_WORD as u64, false)],
context.byte_type(),
"value_ptr_parameter_offset",
"input_ptr_parameter_offset",
);
let salt_pointer = context.build_alloca(context.word_type(), "salt");
context.build_store(salt_pointer, salt.unwrap_or_else(|| context.word_const(0)))?;
let value_pointer = context.build_alloca_at_entry(context.value_type(), "transferred_value");
context.build_store(value_pointer, value)?;
let (address_pointer, address_length_pointer) =
context.build_stack_parameter(revive_common::BIT_LENGTH_ETH_ADDRESS, "address_pointer");
let salt_pointer = match salt {
Some(salt) => {
let salt_pointer = context.build_alloca_at_entry(context.word_type(), "salt_pointer");
context.build_store(salt_pointer, salt)?;
salt_pointer
}
None => context.sentinel_pointer(),
};
let address_pointer = context.build_alloca_at_entry(
context.integer_type(revive_common::BIT_LENGTH_ETH_ADDRESS),
"address_pointer",
);
context.build_store(address_pointer, context.word_const(0))?;
let argument_pointer = revive_runtime_api::calling_convention::Spill::new(
let argument_type = revive_runtime_api::calling_convention::instantiate(context.llvm());
let argument_pointer = context.build_alloca_at_entry(argument_type, "instantiate_arguments");
let arguments = &[
code_hash_pointer.value.as_basic_value_enum(),
context.integer_const(64, 0).as_basic_value_enum(),
context.integer_const(64, 0).as_basic_value_enum(),
context.sentinel_pointer().value.as_basic_value_enum(),
value_pointer.value.as_basic_value_enum(),
input_data_pointer.value.as_basic_value_enum(),
input_length.as_basic_value_enum(),
address_pointer.value.as_basic_value_enum(),
context.sentinel_pointer().value.as_basic_value_enum(),
context.sentinel_pointer().value.as_basic_value_enum(),
salt_pointer.value.as_basic_value_enum(),
];
revive_runtime_api::calling_convention::spill(
context.builder(),
revive_runtime_api::calling_convention::instantiate(context.llvm()),
"create2_arguments",
)?
.next(code_hash_pointer.value)?
.skip()
.skip()
.next(context.sentinel_pointer().value)?
.next(value_pointer.value)?
.next(input_data_pointer.value)?
.next(input_length)?
.next(address_pointer.value)?
.next(address_length_pointer.value)?
.next(context.sentinel_pointer().value)?
.next(context.sentinel_pointer().value)?
.next(salt_pointer.value)?
.next(
context
.xlen_type()
.const_int(revive_common::BYTE_LENGTH_WORD as u64, false),
)?
.done();
argument_pointer.value,
argument_type,
arguments,
)?;
let argument_pointer = context.builder().build_ptr_to_int(
argument_pointer.value,
context.xlen_type(),
"instantiate_argument_pointer",
)?;
context.build_runtime_call(
runtime_api::imports::INSTANTIATE,
&[context
.builder()
.build_ptr_to_int(argument_pointer, context.xlen_type(), "argument_pointer")?
.into()],
revive_runtime_api::polkavm_imports::INSTANTIATE,
&[argument_pointer.into()],
);
context.build_load_word(
address_pointer,
revive_common::BIT_LENGTH_ETH_ADDRESS,
"address",
)
let address = context.build_byte_swap(context.build_load(address_pointer, "address")?)?;
Ok(context
.builder()
.build_int_z_extend(
address.into_int_value(),
context.word_type(),
"address_zext",
)?
.into())
}
/// Translates the contract hash instruction, which is actually used to set the hash of the contract
@@ -2,7 +2,6 @@
use crate::polkavm::context::Context;
use crate::polkavm::Dependency;
use crate::polkavm_const::runtime_api;
/// Translates the `sha3` instruction.
pub fn sha3<'ctx, D>(
@@ -19,7 +18,7 @@ where
let output_pointer = context.build_alloca(context.word_type(), "output_pointer");
context.build_runtime_call(
runtime_api::imports::HASH_KECCAK_256,
revive_runtime_api::polkavm_imports::HASH_KECCAK_256,
&[
input_pointer.to_int(context).into(),
length_casted.into(),
@@ -4,7 +4,6 @@ use inkwell::values::BasicValue;
use crate::polkavm::context::Context;
use crate::polkavm::Dependency;
use crate::polkavm_const::runtime_api;
/// Translates the `gas` instruction.
pub fn gas<'ctx, D>(
@@ -23,20 +22,13 @@ pub fn value<'ctx, D>(
where
D: Dependency + Clone,
{
let (output_pointer, output_length_pointer) =
context.build_stack_parameter(revive_common::BIT_LENGTH_VALUE, "value_transferred_output");
let output_pointer = context.build_alloca(context.value_type(), "value_transferred");
context.build_store(output_pointer, context.word_const(0))?;
context.build_runtime_call(
runtime_api::imports::VALUE_TRANSFERRED,
&[
output_pointer.to_int(context).into(),
output_length_pointer.to_int(context).into(),
],
revive_runtime_api::polkavm_imports::VALUE_TRANSFERRED,
&[output_pointer.to_int(context).into()],
);
context.build_load_word(
output_pointer,
revive_common::BIT_LENGTH_VALUE,
"value_transferred",
)
context.build_load(output_pointer, "value_transferred")
}
/// Translates the `balance` instructions.
@@ -47,24 +39,40 @@ pub fn balance<'ctx, D>(
where
D: Dependency + Clone,
{
let balance_pointer = context.build_alloca(context.word_type(), "balance_pointer");
let address_pointer = context.build_alloca(context.word_type(), "address_pointer");
context.build_store(address_pointer, address)?;
let address_pointer = context.build_address_argument_store(address)?;
let balance_pointer = context.build_alloca(context.word_type(), "balance_pointer");
let balance = context.builder().build_ptr_to_int(
balance_pointer.value,
context.xlen_type(),
"balance",
)?;
let address = context.builder().build_ptr_to_int(
address_pointer.value,
context.xlen_type(),
"address",
)?;
context.build_runtime_call(
runtime_api::imports::BALANCE,
&[address.into(), balance.into()],
revive_runtime_api::polkavm_imports::BALANCE_OF,
&[address_pointer.to_int(context).into(), balance.into()],
);
context.build_load(balance_pointer, "balance")
}
/// Translates the `selfbalance` instructions.
pub fn self_balance<'ctx, D>(
context: &mut Context<'ctx, D>,
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
where
D: Dependency + Clone,
{
let balance_pointer = context.build_alloca(context.word_type(), "balance_pointer");
let balance = context.builder().build_ptr_to_int(
balance_pointer.value,
context.xlen_type(),
"balance",
)?;
context.build_runtime_call(
revive_runtime_api::polkavm_imports::BALANCE,
&[balance.into()],
);
context.build_load(balance_pointer, "balance")
+7 -3
View File
@@ -4,7 +4,6 @@ use inkwell::values::BasicValue;
use crate::polkavm::context::Context;
use crate::polkavm::Dependency;
use crate::polkavm_const::runtime_api;
/// Translates a log or event call.
///
@@ -43,6 +42,7 @@ where
context.byte_type().array_type(topics_buffer_size as u32),
"topics_buffer",
);
for (n, topic) in topics.iter().enumerate() {
let topic_buffer_offset = context
.xlen_type()
@@ -57,6 +57,7 @@ where
context.build_byte_swap(topic.as_basic_value_enum())?,
)?;
}
[
context
.builder()
@@ -68,14 +69,17 @@ where
.as_basic_value_enum(),
context
.xlen_type()
.const_int(topics_buffer_size as u64, false)
.const_int(topics.len() as u64, false)
.as_basic_value_enum(),
input_pointer.as_basic_value_enum(),
input_length.as_basic_value_enum(),
]
};
let _ = context.build_runtime_call(runtime_api::imports::DEPOSIT_EVENT, &arguments);
let _ = context.build_runtime_call(
revive_runtime_api::polkavm_imports::DEPOSIT_EVENT,
&arguments,
);
Ok(())
}
@@ -4,7 +4,6 @@ use inkwell::values::BasicValue;
use crate::polkavm::context::Context;
use crate::polkavm::Dependency;
use crate::polkavm_const::runtime_api;
/// Translates the `extcodesize` instruction if `address` is `Some`.
/// Otherwise, translates the `codesize` instruction.
@@ -31,10 +30,15 @@ where
)?;
let value = context
.build_runtime_call(
runtime_api::imports::CODE_SIZE,
revive_runtime_api::polkavm_imports::CODE_SIZE,
&[address_pointer_casted.into()],
)
.unwrap_or_else(|| panic!("{} should return a value", runtime_api::imports::CODE_SIZE))
.unwrap_or_else(|| {
panic!(
"{} should return a value",
revive_runtime_api::polkavm_imports::CODE_SIZE
)
})
.into_int_value();
Ok(context
@@ -45,11 +49,31 @@ where
/// Translates the `extcodehash` instruction.
pub fn hash<'ctx, D>(
_context: &mut Context<'ctx, D>,
_address: inkwell::values::IntValue<'ctx>,
context: &mut Context<'ctx, D>,
address: inkwell::values::IntValue<'ctx>,
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
where
D: Dependency + Clone,
{
todo!()
let address_type = context.integer_type(revive_common::BIT_LENGTH_ETH_ADDRESS);
let address_pointer = context.build_alloca_at_entry(address_type, "address_pointer");
let address_truncated =
context
.builder()
.build_int_truncate(address, address_type, "address_truncated")?;
let address_swapped = context.build_byte_swap(address_truncated.into())?;
context.build_store(address_pointer, address_swapped)?;
let extcodehash_pointer =
context.build_alloca_at_entry(context.word_type(), "extcodehash_pointer");
context.build_runtime_call(
revive_runtime_api::polkavm_imports::CODE_HASH,
&[
address_pointer.to_int(context).into(),
extcodehash_pointer.to_int(context).into(),
],
);
context.build_byte_swap(context.build_load(extcodehash_pointer, "extcodehash_value")?)
}
@@ -1,14 +1,19 @@
//! Translates the contract immutable operations.
use inkwell::types::BasicType;
use crate::polkavm::context::address_space::AddressSpace;
use crate::polkavm::context::code_type::CodeType;
use crate::polkavm::context::function::runtime;
use crate::polkavm::context::pointer::Pointer;
use crate::polkavm::context::Context;
use crate::polkavm::Dependency;
/// Translates the contract immutable load.
/// In the deploy code the values are read from the auxiliary heap.
/// In the runtime code they are requested from the system contract.
///
/// In deploy code the values are read from the stack.
///
/// In runtime code they are loaded lazily with the `get_immutable_data` syscall.
pub fn load<'ctx, D>(
context: &mut Context<'ctx, D>,
index: inkwell::values::IntValue<'ctx>,
@@ -20,38 +25,27 @@ where
None => {
anyhow::bail!("Immutables are not available if the contract part is undefined");
}
Some(CodeType::Deploy) => {
let index_double = context.builder().build_int_mul(
index,
context.word_const(2),
"immutable_load_index_double",
)?;
let offset_absolute = context.builder().build_int_add(
index_double,
context.word_const(
crate::polkavm::HEAP_AUX_OFFSET_CONSTRUCTOR_RETURN_DATA
+ (3 * revive_common::BYTE_LENGTH_WORD) as u64,
),
"immutable_offset_absolute",
)?;
let immutable_pointer = Pointer::new_with_offset(
context,
AddressSpace::default(),
context.word_type(),
offset_absolute,
"immutable_pointer",
);
context.build_load(immutable_pointer, "immutable_value")
}
Some(CodeType::Deploy) => load_from_memory(context, index),
Some(CodeType::Runtime) => {
todo!()
context.build_call(
context
.get_function(runtime::FUNCTION_LOAD_IMMUTABLE_DATA)
.expect("is always declared for runtime code")
.borrow()
.declaration(),
&[],
runtime::FUNCTION_LOAD_IMMUTABLE_DATA,
);
load_from_memory(context, index)
}
}
}
/// Translates the contract immutable store.
/// In the deploy code the values are written to the auxiliary heap at the predefined offset,
/// being prepared for returning to the system contract for saving.
///
/// In deploy code the values are written to the stack at the predefined offset,
/// being prepared for storing them using the `set_immutable_data` syscall.
///
/// Ignored in the runtime code.
pub fn store<'ctx, D>(
context: &mut Context<'ctx, D>,
@@ -66,46 +60,48 @@ where
anyhow::bail!("Immutables are not available if the contract part is undefined");
}
Some(CodeType::Deploy) => {
let index_double = context.builder().build_int_mul(
index,
context.word_const(2),
"immutable_load_index_double",
)?;
let index_offset_absolute = context.builder().build_int_add(
index_double,
context.word_const(
crate::polkavm::HEAP_AUX_OFFSET_CONSTRUCTOR_RETURN_DATA
+ (2 * revive_common::BYTE_LENGTH_WORD) as u64,
let immutable_data_pointer = context
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_POINTER)?
.value
.as_pointer_value();
let immutable_pointer = context.build_gep(
Pointer::new(
context.word_type(),
AddressSpace::Stack,
immutable_data_pointer,
),
"index_offset_absolute",
)?;
let index_offset_pointer = Pointer::new_with_offset(
context,
AddressSpace::default(),
context.word_type(),
index_offset_absolute,
"immutable_index_pointer",
&[index],
context.word_type().as_basic_type_enum(),
"immutable_variable_pointer",
);
context.build_store(index_offset_pointer, index)?;
let value_offset_absolute = context.builder().build_int_add(
index_offset_absolute,
context.word_const(revive_common::BYTE_LENGTH_WORD as u64),
"value_offset_absolute",
)?;
let value_offset_pointer = Pointer::new_with_offset(
context,
AddressSpace::default(),
context.word_type(),
value_offset_absolute,
"immutable_value_pointer",
);
context.build_store(value_offset_pointer, value)?;
Ok(())
context.build_store(immutable_pointer, value)
}
Some(CodeType::Runtime) => {
anyhow::bail!("Immutable writes are not available in the runtime code");
}
}
}
pub fn load_from_memory<'ctx, D>(
context: &mut Context<'ctx, D>,
index: inkwell::values::IntValue<'ctx>,
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
where
D: Dependency + Clone,
{
let immutable_data_pointer = context
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_POINTER)?
.value
.as_pointer_value();
let immutable_pointer = context.build_gep(
Pointer::new(
context.word_type(),
AddressSpace::Stack,
immutable_data_pointer,
),
&[index],
context.word_type().as_basic_type_enum(),
"immutable_variable_pointer",
);
context.build_load(immutable_pointer, "immutable_value")
}
@@ -1,10 +1,29 @@
//! Translates the heap memory operations.
use inkwell::values::BasicValue;
use crate::polkavm::context::address_space::AddressSpace;
use crate::polkavm::context::pointer::Pointer;
use crate::polkavm::context::Context;
use crate::polkavm::Dependency;
/// Translates the `msize` instruction.
pub fn msize<'ctx, D>(
context: &mut Context<'ctx, D>,
) -> anyhow::Result<inkwell::values::BasicValueEnum<'ctx>>
where
D: Dependency + Clone,
{
Ok(context
.builder()
.build_int_z_extend(
context.build_msize()?,
context.word_type(),
"heap_size_extended",
)?
.as_basic_value_enum())
}
/// Translates the `mload` instruction.
/// Uses the main heap.
pub fn load<'ctx, D>(
+57 -2
View File
@@ -1,5 +1,8 @@
//! Translates the transaction return operations.
use crate::polkavm::context::address_space::AddressSpace;
use crate::polkavm::context::code_type::CodeType;
use crate::polkavm::context::pointer::Pointer;
use crate::polkavm::context::Context;
use crate::polkavm::Dependency;
@@ -12,8 +15,60 @@ pub fn r#return<'ctx, D>(
where
D: Dependency + Clone,
{
if context.code_type().is_none() {
anyhow::bail!("Return is not available if the contract part is undefined");
match context.code_type() {
None => anyhow::bail!("Return is not available if the contract part is undefined"),
Some(CodeType::Deploy) => {
let immutable_data_size_pointer = context
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_SIZE)?
.value
.as_pointer_value();
let immutable_data_size = context.build_load(
Pointer::new(
context.xlen_type(),
AddressSpace::Stack,
immutable_data_size_pointer,
),
"immutable_data_size_load",
)?;
let write_immutable_data_block = context.append_basic_block("write_immutables_block");
let join_return_block = context.append_basic_block("join_return_block");
let immutable_data_size_is_zero = context.builder().build_int_compare(
inkwell::IntPredicate::EQ,
context.xlen_type().const_zero(),
immutable_data_size.into_int_value(),
"immutable_data_size_is_zero",
)?;
context.build_conditional_branch(
immutable_data_size_is_zero,
join_return_block,
write_immutable_data_block,
)?;
context.set_basic_block(write_immutable_data_block);
let immutable_data_pointer = context
.get_global(revive_runtime_api::immutable_data::GLOBAL_IMMUTABLE_DATA_POINTER)?
.value
.as_pointer_value();
context.build_runtime_call(
revive_runtime_api::polkavm_imports::SET_IMMUTABLE_DATA,
&[
context
.builder()
.build_ptr_to_int(
immutable_data_pointer,
context.xlen_type(),
"immutable_data_pointer_to_xlen",
)?
.into(),
immutable_data_size,
],
);
context.build_unconditional_branch(join_return_block);
context.set_basic_block(join_return_block);
}
Some(CodeType::Runtime) => {}
}
context.build_exit(
@@ -1,10 +1,7 @@
//! Translates the return data instructions.
use inkwell::values::BasicValue;
use crate::polkavm::context::Context;
use crate::polkavm::Dependency;
use crate::polkavm_const::runtime_api;
/// Translates the return data size.
pub fn size<'ctx, D>(
@@ -13,13 +10,17 @@ pub fn size<'ctx, D>(
where
D: Dependency + Clone,
{
let value = context
.get_global_value(crate::polkavm::GLOBAL_RETURN_DATA_SIZE)?
.into_int_value();
Ok(context
.builder()
.build_int_z_extend(value, context.word_type(), "calldatasize_extended")?
.as_basic_value_enum())
let output_pointer = context.build_alloca_at_entry(context.word_type(), "return_data_size");
let output_pointer_parameter = context.builder().build_ptr_to_int(
output_pointer.value,
context.xlen_type(),
"return_data_copy_output_pointer",
)?;
context.build_runtime_call(
revive_runtime_api::polkavm_imports::RETURNDATASIZE,
&[output_pointer_parameter.into()],
);
context.build_load(output_pointer, "return_data_size_load")
}
/// Translates the return data copy, trapping if
@@ -39,16 +40,49 @@ where
let destination_offset = context.safe_truncate_int_to_xlen(destination_offset)?;
let size = context.safe_truncate_int_to_xlen(size)?;
let destination_offset = context.builder().build_ptr_to_int(
let output_pointer = context.builder().build_ptr_to_int(
context.build_heap_gep(destination_offset, size)?.value,
context.xlen_type(),
"destination_offset",
"return_data_copy_output_pointer",
)?;
let output_length_pointer = context.build_alloca_at_entry(
context.xlen_type(),
"return_data_copy_output_length_pointer",
);
context.build_store(output_length_pointer, size)?;
let output_length_pointer_int = context.builder().build_ptr_to_int(
output_length_pointer.value,
context.xlen_type(),
"return_data_copy_output_length_pointer_int",
)?;
context.build_runtime_call(
runtime_api::imports::RETURNDATACOPY,
&[destination_offset.into(), source_offset.into(), size.into()],
revive_runtime_api::polkavm_imports::RETURNDATACOPY,
&[
output_pointer.into(),
output_length_pointer_int.into(),
source_offset.into(),
],
);
// Trap on OOB (will be different in EOF code)
let overflow_block = context.append_basic_block("return_data_overflow");
let non_overflow_block = context.append_basic_block("return_data_non_overflow");
let is_overflow = context.builder().build_int_compare(
inkwell::IntPredicate::UGT,
size,
context
.build_load(output_length_pointer, "bytes_written")?
.into_int_value(),
"is_overflow",
)?;
context.build_conditional_branch(is_overflow, overflow_block, non_overflow_block)?;
context.set_basic_block(overflow_block);
context.build_call(context.intrinsics().trap, &[], "invalid_trap");
context.build_unreachable();
context.set_basic_block(non_overflow_block);
Ok(())
}
-2
View File
@@ -97,7 +97,6 @@ pub trait Dependency {
dependency: Self,
path: &str,
optimizer_settings: OptimizerSettings,
is_system_mode: bool,
include_metadata_hash: bool,
debug_config: Option<DebugConfig>,
) -> anyhow::Result<String>;
@@ -118,7 +117,6 @@ impl Dependency for DummyDependency {
_dependency: Self,
_path: &str,
_optimizer_settings: OptimizerSettings,
_is_system_mode: bool,
_include_metadata_hash: bool,
_debug_config: Option<DebugConfig>,
) -> anyhow::Result<String> {
@@ -39,9 +39,9 @@ impl TargetMachine {
/// LLVM target features.
#[cfg(feature = "riscv-zbb")]
pub const VM_FEATURES: &'static str = "+zbb,+e,+m";
pub const VM_FEATURES: &'static str = "+zbb,+e,+m,+c";
#[cfg(not(feature = "riscv-zbb"))]
pub const VM_FEATURES: &'static str = "+e,+m";
pub const VM_FEATURES: &'static str = "+e,+m,+c";
/// A shortcut constructor.
/// A separate instance for every optimization level is created.
Binary file not shown.
+20 -9
View File
@@ -26,13 +26,13 @@
use std::time::Duration;
use hex::{FromHex, ToHex};
use pallet_revive::AddressMapper;
use pallet_revive::{AddressMapper, ExecReturnValue, InstantiateReturnValue};
use polkadot_sdk::*;
use polkadot_sdk::{
pallet_revive::{CollectEvents, ContractExecResult, ContractInstantiateResult, DebugInfo},
pallet_revive::{CollectEvents, ContractResult, DebugInfo},
polkadot_runtime_common::BuildStorage,
polkadot_sdk_frame::testing_prelude::*,
sp_core::H160,
sp_core::{H160, H256},
sp_keystore::{testing::MemoryKeystore, KeystoreExt},
sp_runtime::AccountId32,
};
@@ -161,7 +161,7 @@ impl VerifyCallExpectation {
fn verify(self, result: &CallResult) {
assert_eq!(
self.success,
result.is_ok(),
!result.did_revert(),
"contract execution result mismatch: {result:?}"
);
@@ -179,23 +179,33 @@ impl VerifyCallExpectation {
#[derive(Clone, Debug)]
pub enum CallResult {
Exec {
result: ContractExecResult<Balance, EventRecord>,
result: ContractResult<ExecReturnValue, Balance, EventRecord>,
wall_time: Duration,
},
Instantiate {
result: ContractInstantiateResult<Balance, EventRecord>,
result: ContractResult<InstantiateReturnValue, Balance, EventRecord>,
wall_time: Duration,
code_hash: H256,
},
}
impl CallResult {
/// Check if the call was successful
fn is_ok(&self) -> bool {
fn did_revert(&self) -> bool {
match self {
Self::Exec { result, .. } => result.result.is_ok(),
Self::Instantiate { result, .. } => result.result.is_ok(),
Self::Exec { result, .. } => result
.result
.as_ref()
.map(|r| r.did_revert())
.unwrap_or(true),
Self::Instantiate { result, .. } => result
.result
.as_ref()
.map(|r| r.result.did_revert())
.unwrap_or(true),
}
}
/// Get the output of the call
fn output(&self) -> Vec<u8> {
match self {
@@ -211,6 +221,7 @@ impl CallResult {
.unwrap_or_default(),
}
}
/// Get the gas consumed by the call
fn gas_consumed(&self) -> Weight {
match self {
+3 -1
View File
@@ -75,10 +75,12 @@ impl pallet_revive::Config for Runtime {
type DepositPerByte = DepositPerByte;
type DepositPerItem = DepositPerItem;
type AddressMapper = AccountId;
type RuntimeMemory = ConstU32<{ 512 * 1024 * 1024 }>;
type PVFMemory = ConstU32<{ 1024 * 1024 * 1024 }>;
type UnsafeUnstableInterface = UnstableInterface;
type UploadOrigin = EnsureSigned<AccountId32>;
type InstantiateOrigin = EnsureSigned<AccountId32>;
type Migrations = ();
type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
type Debug = ();
type ChainId = ConstU64<420_420_420>;
}
+65 -23
View File
@@ -4,7 +4,7 @@ use pallet_revive::AddressMapper;
use serde::{Deserialize, Serialize};
use crate::*;
use alloy_primitives::Address;
use alloy_primitives::{keccak256, Address};
#[cfg(feature = "revive-solidity")]
use revive_differential::{Evm, EvmLog};
#[cfg(feature = "revive-solidity")]
@@ -58,7 +58,6 @@ pub enum SpecsAction {
},
/// Verify the result of the last call, omitting this will simply ensure the last call was successful
VerifyCall(VerifyCallExpectation),
/// Verify the balance of an account
VerifyBalance {
origin: TestAddress,
@@ -179,7 +178,11 @@ impl Default for Specs {
fn default() -> Self {
Self {
differential: false,
balances: vec![(ALICE, 1_000_000_000)],
balances: vec![
(ALICE, 1_000_000_000),
(BOB, 1_000_000_000),
(CHARLIE, 1_000_000_000),
],
actions: Default::default(),
}
}
@@ -272,10 +275,10 @@ impl Specs {
origin,
value,
gas_limit,
storage_deposit_limit,
code,
data,
salt,
..
} => {
let Code::Solidity {
path: Some(path),
@@ -286,21 +289,37 @@ impl Specs {
else {
panic!("the differential runner requires Code::Solidity source");
};
assert_ne!(solc_optimizer, Some(false), "solc_optimizer must be enabled in differntial mode");
assert_ne!(pipeline, Some(revive_solidity::SolcPipeline::EVMLA), "yul pipeline must be enabled in differntial mode");
assert!(storage_deposit_limit.is_none(), "storage deposit limit is not supported in differential mode");
assert!(salt.0.is_none(), "salt is not supported in differential mode");
assert_eq!(origin, TestAddress::default(), "configuring the origin is not supported in differential mode");
assert_ne!(
pipeline,
Some(revive_solidity::SolcPipeline::EVMLA),
"yul pipeline must be enabled in differential mode"
);
assert!(
salt.0.is_none(),
"salt is not supported in differential mode"
);
assert_eq!(
origin,
TestAddress::default(),
"configuring the origin is not supported in differential mode"
);
let deploy_code = match std::fs::read_to_string(&path) {
Ok(solidity_source) => compile_evm_deploy_code(&contract, &solidity_source),
Ok(solidity_source) => hex::encode(compile_evm_deploy_code(
&contract,
&solidity_source,
solc_optimizer.unwrap_or(true),
)),
Err(err) => panic!(
"failed to read solidity source\n . path: '{}'\n . error: {:?}",
path.display(),
err
),
};
let deploy_code = hex::encode(deploy_code);
let mut vm = evm.code_blob(deploy_code.as_bytes().to_vec()).sender(origin.to_eth_addr(&[]).0.into()).deploy(true);
let mut vm = evm
.code_blob(deploy_code.as_bytes().to_vec())
.sender(origin.to_eth_addr(&[]).0.into())
.deploy(true);
if !data.is_empty() {
vm = vm.input(data.into());
}
@@ -315,7 +334,13 @@ impl Specs {
let deployed_account = log.account_deployed.expect("no account was created");
let account_pvm = TestAddress::Instantiated(deployed_accounts.len());
deployed_accounts.push(deployed_account);
derived_specs.actions.append(&mut SpecsAction::derive_verification(&log, deployed_account, account_pvm));
derived_specs
.actions
.append(&mut SpecsAction::derive_verification(
&log,
deployed_account,
account_pvm,
));
evm = Evm::from_genesis(log.state_dump.into());
}
Call {
@@ -323,16 +348,23 @@ impl Specs {
dest,
value,
gas_limit,
storage_deposit_limit,
data,
..
} => {
assert_eq!(origin, TestAddress::default(), "configuring the origin is not supported in differential mode");
assert!(storage_deposit_limit.is_none(), "storage deposit limit is not supported in differential mode");
assert_eq!(
origin,
TestAddress::default(),
"configuring the origin is not supported in differential mode"
);
let TestAddress::Instantiated(n) = dest else {
panic!("the differential runner requires TestAccountId::Instantiated(n) as dest");
};
let address = deployed_accounts.get(n).unwrap_or_else(|| panic!("no account at index {n} "));
let mut vm = evm.receiver(*address).sender(origin.to_eth_addr(&[]).0.into());
let address = deployed_accounts
.get(n)
.unwrap_or_else(|| panic!("no account at index {n} "));
let mut vm = evm
.receiver(*address)
.sender(origin.to_eth_addr(&[]).0.into());
if !data.is_empty() {
vm = vm.input(data.into());
}
@@ -344,10 +376,13 @@ impl Specs {
}
let log = vm.run();
derived_specs.actions.append(&mut SpecsAction::derive_verification(&log, *address, dest));
derived_specs
.actions
.append(&mut SpecsAction::derive_verification(&log, *address, dest));
evm = Evm::from_genesis(log.state_dump.into());
}
_ => panic!("only instantiate and call action allowed in differential mode, got: {action:?}"),
Upload { .. } => continue,
other => derived_specs.actions.push(other),
}
}
@@ -374,6 +409,13 @@ impl Specs {
data,
salt,
} => {
let code: pallet_revive::Code = code.into();
let code_hash = match code.clone() {
pallet_revive::Code::Existing(code_hash) => code_hash,
pallet_revive::Code::Upload(bytes) => {
H256::from_slice(keccak256(&bytes).as_slice())
}
};
let origin = RuntimeOrigin::signed(origin.to_account_id(&results));
let time_start = Instant::now();
let result = Contracts::bare_instantiate(
@@ -381,7 +423,7 @@ impl Specs {
value,
gas_limit.unwrap_or(GAS_LIMIT),
storage_deposit_limit.unwrap_or(DEPOSIT_LIMIT),
code.into(),
code,
data,
salt.0,
DebugInfo::Skip,
@@ -390,6 +432,7 @@ impl Specs {
results.push(CallResult::Instantiate {
result,
wall_time: time_start.elapsed(),
code_hash,
})
}
Upload {
@@ -402,7 +445,7 @@ impl Specs {
pallet_revive::Code::Existing(_) => continue,
pallet_revive::Code::Upload(bytes) => bytes,
},
storage_deposit_limit.unwrap_or_default(),
storage_deposit_limit.unwrap_or(DEPOSIT_LIMIT),
)
.unwrap_or_else(|error| panic!("code upload failed: {error:?}")),
Call {
@@ -442,7 +485,6 @@ impl Specs {
expected,
} => {
let address = contract.to_eth_addr(&results);
dbg!(contract.to_account_id(&results));
let Ok(value) = Contracts::get_storage(address, key) else {
panic!("error reading storage for address {address}");
};
+3 -1
View File
@@ -12,4 +12,6 @@ riscv-64 = []
[dependencies]
anyhow = { workspace = true }
inkwell = { workspace = true, features = ["target-riscv", "no-libffi-linking", "llvm18-0"] }
inkwell = { workspace = true, features = ["target-riscv", "no-libffi-linking", "llvm18-0"] }
revive-common = { workspace = true }
+21 -47
View File
@@ -3,7 +3,7 @@ use inkwell::{
context::Context,
module::Module,
types::{BasicType, StructType},
values::{BasicValue, PointerValue},
values::{BasicValueEnum, PointerValue},
};
/// Creates a module that sets the PolkaVM minimum stack size to [`size`] if linked in.
@@ -21,56 +21,33 @@ pub fn min_stack_size<'context>(
module
}
pub struct Spill<'a, 'ctx> {
/// Helper for building function calls with stack spilled arguments.
/// - `pointer`: points to a struct of the packed argument struct type
/// - `type`: the packed argument struct type
/// - `arguments`: a correctly ordered list of the struct field values
pub fn spill<'ctx>(
builder: &Builder<'ctx>,
pointer: PointerValue<'ctx>,
builder: &'a Builder<'ctx>,
r#type: StructType<'ctx>,
current_field: u32,
}
impl<'a, 'ctx> Spill<'a, 'ctx> {
pub fn new(
builder: &'a Builder<'ctx>,
r#type: StructType<'ctx>,
name: &str,
) -> anyhow::Result<Self> {
Ok(Self {
pointer: builder.build_alloca(r#type, name)?,
builder,
arguments: &[BasicValueEnum<'ctx>],
) -> anyhow::Result<()> {
for index in 0..r#type.get_field_types().len() {
let field_pointer = builder.build_struct_gep(
r#type,
current_field: 0,
})
}
pub fn next<V: BasicValue<'ctx>>(mut self, value: V) -> anyhow::Result<Self> {
let field_pointer = self.builder.build_struct_gep(
self.r#type,
self.pointer,
self.current_field,
&format!("spill_parameter_{}", self.current_field),
pointer,
index as u32,
&format!("spill_parameter_{}", index),
)?;
self.builder.build_store(field_pointer, value)?;
self.current_field += 1;
Ok(self)
let field_value = arguments
.get(index)
.ok_or_else(|| anyhow::anyhow!("invalid index {index} for struct type {}", r#type))?;
builder.build_store(field_pointer, *field_value)?;
}
pub fn skip(mut self) -> Self {
self.current_field += 1;
self
}
pub fn done(self) -> PointerValue<'ctx> {
assert!(
self.r#type
.get_field_type_at_index(self.current_field)
.is_none(),
"there must not be any missing parameters"
);
self.pointer
}
Ok(())
}
/// Returns a packed struct argument type for the `instantiate` API.
pub fn instantiate(context: &Context) -> StructType {
context.struct_type(
&[
@@ -90,21 +67,18 @@ pub fn instantiate(context: &Context) -> StructType {
context.i32_type().as_basic_type_enum(),
// address_ptr: u32,
context.ptr_type(Default::default()).as_basic_type_enum(),
// address_len_ptr: u32,
context.ptr_type(Default::default()).as_basic_type_enum(),
// output_ptr: u32,
context.ptr_type(Default::default()).as_basic_type_enum(),
// output_len_ptr: u32,
context.ptr_type(Default::default()).as_basic_type_enum(),
// salt_ptr: u32,
context.ptr_type(Default::default()).as_basic_type_enum(),
// salt_len: u32
context.i32_type().as_basic_type_enum(),
],
true,
)
}
/// Returns a packed struct argument type for the `call` API.
pub fn call(context: &Context) -> StructType {
context.struct_type(
&[
+89
View File
@@ -0,0 +1,89 @@
//! Allocates memory for the immutable data in a separate module.
//!
//! Because we only know how many immutable variables were set after
//! translating the whole contract code, we want to set the size at
//! last. However, array types need a size upon declaration.
//!
//! A simple work around is to replace it during link time.
//! To quote the [LLVM docs][0]:
//!
//! > For global variable declarations [..] the allocation size and
//! > alignment of the definition it resolves to must be greater than
//! > or equal to that of the declaration [..]
//!
//! To adhere to this we initially declare a length of 0 in
//! `revive-llvm-context`.
//!
//! [0]: https://llvm.org/docs/LangRef.html#global-variables
/// The immutable data module name.
pub static MODULE_NAME: &str = "__evm_immutables";
/// The immutable data global pointer.
pub static GLOBAL_IMMUTABLE_DATA_POINTER: &str = "__immutable_data_ptr";
/// The immutable data global size.
pub static GLOBAL_IMMUTABLE_DATA_SIZE: &str = "__immutable_data_size";
/// The immutable data maximum size in bytes.
pub static IMMUTABLE_DATA_MAX_SIZE: u32 = 4 * 1024;
/// Returns the immutable data global type.
pub fn data_type(context: &inkwell::context::Context, size: u32) -> inkwell::types::ArrayType {
context
.custom_width_int_type(revive_common::BIT_LENGTH_WORD as u32)
.array_type(size)
}
/// Returns the immutable data size global type.
pub fn size_type(context: &inkwell::context::Context) -> inkwell::types::IntType {
context.custom_width_int_type(revive_common::BIT_LENGTH_X32 as u32)
}
/// Creates a LLVM module with the immutable data and its `size` in bytes.
pub fn module(context: &inkwell::context::Context, size: u32) -> inkwell::module::Module {
let module = context.create_module(MODULE_NAME);
let length = size / revive_common::BYTE_LENGTH_WORD as u32;
let immutable_data = module.add_global(
data_type(context, length),
Default::default(),
GLOBAL_IMMUTABLE_DATA_POINTER,
);
immutable_data.set_linkage(inkwell::module::Linkage::External);
immutable_data.set_visibility(inkwell::GlobalVisibility::Default);
immutable_data.set_initializer(&data_type(context, length).get_undef());
let immutable_data_size = module.add_global(
size_type(context),
Default::default(),
GLOBAL_IMMUTABLE_DATA_SIZE,
);
immutable_data_size.set_linkage(inkwell::module::Linkage::External);
immutable_data_size.set_visibility(inkwell::GlobalVisibility::Default);
immutable_data_size.set_initializer(&size_type(context).const_int(size as u64, false));
module
}
#[cfg(test)]
mod tests {
use crate::immutable_data::*;
#[test]
fn it_works() {
inkwell::targets::Target::initialize_riscv(&Default::default());
let context = inkwell::context::Context::create();
let size = 512;
let module = crate::immutable_data::module(&context, size);
let immutable_data_pointer = module.get_global(GLOBAL_IMMUTABLE_DATA_POINTER).unwrap();
assert_eq!(
immutable_data_pointer.get_initializer().unwrap(),
data_type(&context, size / 32).get_undef()
);
let immutable_data_size = module.get_global(GLOBAL_IMMUTABLE_DATA_SIZE).unwrap();
assert_eq!(
immutable_data_size.get_initializer().unwrap(),
size_type(&context).const_int(size as u64, false)
);
}
}
+1
View File
@@ -7,5 +7,6 @@
//! [1]: [https://docs.rs/pallet-contracts/26.0.0/pallet_contracts/api_doc/index.html]
pub mod calling_convention;
pub mod immutable_data;
pub mod polkavm_exports;
pub mod polkavm_imports;
+12 -2
View File
@@ -2,6 +2,16 @@ use inkwell::{context::Context, memory_buffer::MemoryBuffer, module::Module, sup
include!(concat!(env!("OUT_DIR"), "/polkavm_exports.rs"));
/// The contract deploy export.
pub static CALL: &str = "call";
/// The contract call export.
pub static DEPLOY: &str = "deploy";
/// All exported symbols.
/// Useful for configuring common attributes and linkage.
pub static EXPORTS: [&str; 2] = [CALL, DEPLOY];
/// Creates a LLVM module from the [BITCODE].
/// The module exports `call` and `deploy` functions (which are named thereafter).
/// Returns `Error` if the bitcode fails to parse, which should never happen.
@@ -23,7 +33,7 @@ mod tests {
let context = inkwell::context::Context::create();
let module = polkavm_exports::module(&context, "polkavm_exports").unwrap();
assert!(module.get_function("call").is_some());
assert!(module.get_function("deploy").is_some());
assert!(module.get_function(polkavm_exports::CALL).is_some());
assert!(module.get_function(polkavm_exports::DEPLOY).is_some());
}
}
+46 -63
View File
@@ -3,9 +3,34 @@
#include "polkavm_guest.h"
// Missing builtins
#define EVM_WORD_SIZE 32
#define ALIGN(size) ((size + EVM_WORD_SIZE - 1) & ~(EVM_WORD_SIZE - 1))
#define MAX_MEMORY_SIZE (64 * 1024)
static char __memory[MAX_MEMORY_SIZE];
static uint32_t __memory_size = 0;
void * __sbrk_internal(uint32_t offset, uint32_t size) {
if (offset >= MAX_MEMORY_SIZE || size > MAX_MEMORY_SIZE) {
return NULL;
}
uint32_t new_size = ALIGN(offset + size);
if (new_size > MAX_MEMORY_SIZE) {
return NULL;
}
if (new_size > __memory_size) {
__memory_size = new_size;
}
return (void *)&__memory[__memory_size];
}
uint32_t __msize() {
return __memory_size;
}
void * memset(void *b, int c, size_t len) {
uint8_t *dest = b;
while (len-- > 0) *dest++ = c;
@@ -37,90 +62,48 @@ void * memmove(void *dst, const void *src, size_t n) {
return dst;
}
void * __sbrk(uint32_t size) {
uint32_t address;
__asm__ __volatile__(
".insn r 0xb, 1, 0, %[dst], %[sz], zero"
: [dst] "=r" (address)
: [sz] "ir" (size)
:
);
return (void *)address;
}
// Imports
POLKAVM_IMPORT(void, input, uint32_t, uint32_t)
POLKAVM_IMPORT(void, address, uint32_t)
POLKAVM_IMPORT(void, seal_return, uint32_t, uint32_t, uint32_t)
POLKAVM_IMPORT(void, balance, uint32_t)
POLKAVM_IMPORT(void, returndatacopy, uint32_t, uint32_t, uint32_t)
POLKAVM_IMPORT(void, balance_of, uint32_t, uint32_t)
POLKAVM_IMPORT(void, value_transferred, uint32_t, uint32_t)
POLKAVM_IMPORT(uint32_t, set_storage, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)
POLKAVM_IMPORT(uint32_t, get_storage, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)
POLKAVM_IMPORT(uint32_t, clear_storage, uint32_t, uint32_t)
POLKAVM_IMPORT(uint32_t, contains_storage, uint32_t, uint32_t)
POLKAVM_IMPORT(uint32_t, take_storage, uint32_t, uint32_t, uint32_t, uint32_t)
POLKAVM_IMPORT(void, block_number, uint32_t)
POLKAVM_IMPORT(uint32_t, call, uint32_t)
POLKAVM_IMPORT(uint32_t, delegate_call, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)
POLKAVM_IMPORT(void, caller, uint32_t)
POLKAVM_IMPORT(uint32_t, instantiate, uint32_t)
POLKAVM_IMPORT(void, terminate, uint32_t)
POLKAVM_IMPORT(void, caller, uint32_t, uint32_t)
POLKAVM_IMPORT(uint32_t, is_contract, uint32_t)
POLKAVM_IMPORT(uint32_t, code_hash, uint32_t, uint32_t, uint32_t)
POLKAVM_IMPORT(void, chain_id, uint32_t)
POLKAVM_IMPORT(uint32_t, code_size, uint32_t)
POLKAVM_IMPORT(void, own_code_hash, uint32_t, uint32_t)
POLKAVM_IMPORT(uint32_t, caller_is_origin)
POLKAVM_IMPORT(uint32_t, caller_is_root)
POLKAVM_IMPORT(void, address, uint32_t, uint32_t)
POLKAVM_IMPORT(void, weight_to_fee, uint64_t, uint32_t, uint32_t)
POLKAVM_IMPORT(void, gas_left, uint32_t, uint32_t)
POLKAVM_IMPORT(void, balance, uint32_t, uint32_t)
POLKAVM_IMPORT(void, now, uint32_t, uint32_t)
POLKAVM_IMPORT(void, minimum_balance, uint32_t, uint32_t)
POLKAVM_IMPORT(void, code_hash, uint32_t, uint32_t)
POLKAVM_IMPORT(void, deposit_event, uint32_t, uint32_t, uint32_t, uint32_t)
POLKAVM_IMPORT(void, block_number, uint32_t, uint32_t)
POLKAVM_IMPORT(void, get_immutable_data, uint32_t, uint32_t);
POLKAVM_IMPORT(void, hash_sha2_256, uint32_t, uint32_t, uint32_t)
POLKAVM_IMPORT(uint32_t, get_storage, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)
POLKAVM_IMPORT(void, hash_keccak_256, uint32_t, uint32_t, uint32_t)
POLKAVM_IMPORT(void, hash_blake2_256, uint32_t, uint32_t, uint32_t)
POLKAVM_IMPORT(void, input, uint32_t, uint32_t)
POLKAVM_IMPORT(void, hash_blake2_128, uint32_t, uint32_t, uint32_t)
POLKAVM_IMPORT(uint32_t, instantiate, uint32_t)
POLKAVM_IMPORT(uint32_t, call_chain_extension, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)
POLKAVM_IMPORT(void, now, uint32_t)
POLKAVM_IMPORT(uint32_t, debug_message, uint32_t, uint32_t)
POLKAVM_IMPORT(void, seal_return, uint32_t, uint32_t, uint32_t)
POLKAVM_IMPORT(uint32_t, set_code_hash, uint32_t)
POLKAVM_IMPORT(uint32_t, set_storage, uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)
POLKAVM_IMPORT(uint64_t, instantiation_nonce,)
POLKAVM_IMPORT(void, return_data_copy, uint32_t, uint32_t, uint32_t)
POLKAVM_IMPORT(uint32_t, transfer, uint32_t, uint32_t, uint32_t, uint32_t)
POLKAVM_IMPORT(void, return_data_size, uint32_t)
POLKAVM_IMPORT(void, set_immutable_data, uint32_t, uint32_t);
POLKAVM_IMPORT(void, value_transferred, uint32_t)
+77
View File
@@ -10,6 +10,83 @@ use inkwell::{context::Context, memory_buffer::MemoryBuffer, module::Module, sup
include!(concat!(env!("OUT_DIR"), "/polkavm_imports.rs"));
pub static SBRK: &str = "__sbrk_internal";
pub static MEMORY_SIZE: &str = "__msize";
pub static ADDRESS: &str = "address";
pub static BALANCE: &str = "balance";
pub static BALANCE_OF: &str = "balance_of";
pub static BLOCK_NUMBER: &str = "block_number";
pub static CALL: &str = "call";
pub static CALLER: &str = "caller";
pub static CHAIN_ID: &str = "chain_id";
pub static CODE_SIZE: &str = "code_size";
pub static CODE_HASH: &str = "code_hash";
pub static DEPOSIT_EVENT: &str = "deposit_event";
pub static GET_IMMUTABLE_DATA: &str = "get_immutable_data";
pub static GET_STORAGE: &str = "get_storage";
pub static HASH_KECCAK_256: &str = "hash_keccak_256";
pub static INPUT: &str = "input";
pub static INSTANTIATE: &str = "instantiate";
pub static NOW: &str = "now";
pub static RETURN: &str = "seal_return";
pub static SET_STORAGE: &str = "set_storage";
pub static RETURNDATACOPY: &str = "return_data_copy";
pub static RETURNDATASIZE: &str = "return_data_size";
pub static SET_IMMUTABLE_DATA: &str = "set_immutable_data";
pub static VALUE_TRANSFERRED: &str = "value_transferred";
/// All imported runtime API symbols.
/// Useful for configuring common attributes and linkage.
pub static IMPORTS: [&str; 24] = [
SBRK,
MEMORY_SIZE,
ADDRESS,
BALANCE,
BALANCE_OF,
BLOCK_NUMBER,
CALL,
CALLER,
CHAIN_ID,
CODE_SIZE,
CODE_HASH,
DEPOSIT_EVENT,
GET_IMMUTABLE_DATA,
GET_STORAGE,
HASH_KECCAK_256,
INPUT,
INSTANTIATE,
NOW,
RETURN,
RETURNDATACOPY,
RETURNDATASIZE,
SET_IMMUTABLE_DATA,
SET_STORAGE,
VALUE_TRANSFERRED,
];
/// Creates a LLVM module from the [BITCODE].
/// The module imports `pallet-revive` runtime API functions.
/// Returns `Error` if the bitcode fails to parse, which should never happen.
@@ -199,6 +199,7 @@ where
revive_llvm_context::PolkaVMDummyLLVMWritable::default(),
)
.declare(context)?;
revive_llvm_context::PolkaVMImmutableDataLoadFunction.declare(context)?;
entry.into_llvm(context)?;
@@ -266,6 +267,7 @@ where
revive_llvm_context::PolkaVMCodeType::Runtime,
))
.into_llvm(context)?;
revive_llvm_context::PolkaVMImmutableDataLoadFunction.into_llvm(context)?;
Ok(())
}
@@ -45,7 +45,7 @@ impl Element {
fn pop_arguments_llvm<'ctx, D>(
&mut self,
context: &mut revive_llvm_context::PolkaVMContext<'ctx, D>,
) -> Vec<inkwell::values::BasicValueEnum<'ctx>>
) -> anyhow::Result<Vec<inkwell::values::BasicValueEnum<'ctx>>>
where
D: revive_llvm_context::PolkaVMDependency + Clone,
{
@@ -57,15 +57,13 @@ impl Element {
[self.stack.elements.len() + input_size - output_size - 1 - index]
.to_llvm()
.into_pointer_value();
let value = context
.build_load(
revive_llvm_context::PolkaVMPointer::new_stack_field(context, pointer),
format!("argument_{index}").as_str(),
)
.unwrap();
let value = context.build_load(
revive_llvm_context::PolkaVMPointer::new_stack_field(context, pointer),
format!("argument_{index}").as_str(),
)?;
arguments.push(value);
}
arguments
Ok(arguments)
}
}
@@ -426,7 +424,7 @@ where
InstructionName::JUMPDEST => Ok(None),
InstructionName::ADD => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_arithmetic::addition(
context,
arguments[0].into_int_value(),
@@ -435,7 +433,7 @@ where
.map(Some)
}
InstructionName::SUB => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_arithmetic::subtraction(
context,
arguments[0].into_int_value(),
@@ -444,7 +442,7 @@ where
.map(Some)
}
InstructionName::MUL => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_arithmetic::multiplication(
context,
arguments[0].into_int_value(),
@@ -453,7 +451,7 @@ where
.map(Some)
}
InstructionName::DIV => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_arithmetic::division(
context,
arguments[0].into_int_value(),
@@ -462,7 +460,7 @@ where
.map(Some)
}
InstructionName::MOD => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_arithmetic::remainder(
context,
arguments[0].into_int_value(),
@@ -471,7 +469,7 @@ where
.map(Some)
}
InstructionName::SDIV => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_arithmetic::division_signed(
context,
arguments[0].into_int_value(),
@@ -480,7 +478,7 @@ where
.map(Some)
}
InstructionName::SMOD => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_arithmetic::remainder_signed(
context,
arguments[0].into_int_value(),
@@ -490,7 +488,7 @@ where
}
InstructionName::LT => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_comparison::compare(
context,
arguments[0].into_int_value(),
@@ -500,7 +498,7 @@ where
.map(Some)
}
InstructionName::GT => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_comparison::compare(
context,
arguments[0].into_int_value(),
@@ -510,7 +508,7 @@ where
.map(Some)
}
InstructionName::EQ => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_comparison::compare(
context,
arguments[0].into_int_value(),
@@ -520,7 +518,7 @@ where
.map(Some)
}
InstructionName::ISZERO => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_comparison::compare(
context,
arguments[0].into_int_value(),
@@ -530,7 +528,7 @@ where
.map(Some)
}
InstructionName::SLT => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_comparison::compare(
context,
arguments[0].into_int_value(),
@@ -540,7 +538,7 @@ where
.map(Some)
}
InstructionName::SGT => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_comparison::compare(
context,
arguments[0].into_int_value(),
@@ -551,7 +549,7 @@ where
}
InstructionName::OR => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::or(
context,
arguments[0].into_int_value(),
@@ -560,7 +558,7 @@ where
.map(Some)
}
InstructionName::XOR => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::xor(
context,
arguments[0].into_int_value(),
@@ -569,7 +567,7 @@ where
.map(Some)
}
InstructionName::NOT => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::xor(
context,
arguments[0].into_int_value(),
@@ -578,7 +576,7 @@ where
.map(Some)
}
InstructionName::AND => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::and(
context,
arguments[0].into_int_value(),
@@ -587,7 +585,7 @@ where
.map(Some)
}
InstructionName::SHL => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::shift_left(
context,
arguments[0].into_int_value(),
@@ -596,7 +594,7 @@ where
.map(Some)
}
InstructionName::SHR => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::shift_right(
context,
arguments[0].into_int_value(),
@@ -605,7 +603,7 @@ where
.map(Some)
}
InstructionName::SAR => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::shift_right_arithmetic(
context,
arguments[0].into_int_value(),
@@ -614,7 +612,7 @@ where
.map(Some)
}
InstructionName::BYTE => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_bitwise::byte(
context,
arguments[0].into_int_value(),
@@ -624,7 +622,7 @@ where
}
InstructionName::ADDMOD => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_math::add_mod(
context,
arguments[0].into_int_value(),
@@ -634,7 +632,7 @@ where
.map(Some)
}
InstructionName::MULMOD => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_math::mul_mod(
context,
arguments[0].into_int_value(),
@@ -644,7 +642,7 @@ where
.map(Some)
}
InstructionName::EXP => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_math::exponent(
context,
arguments[0].into_int_value(),
@@ -653,7 +651,7 @@ where
.map(Some)
}
InstructionName::SIGNEXTEND => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_math::sign_extend(
context,
arguments[0].into_int_value(),
@@ -663,7 +661,7 @@ where
}
InstructionName::SHA3 | InstructionName::KECCAK256 => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_crypto::sha3(
context,
arguments[0].into_int_value(),
@@ -673,7 +671,7 @@ where
}
InstructionName::MLOAD => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_memory::load(
context,
arguments[0].into_int_value(),
@@ -681,7 +679,7 @@ where
.map(Some)
}
InstructionName::MSTORE => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_memory::store(
context,
arguments[0].into_int_value(),
@@ -690,7 +688,7 @@ where
.map(|_| None)
}
InstructionName::MSTORE8 => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_memory::store_byte(
context,
arguments[0].into_int_value(),
@@ -699,7 +697,7 @@ where
.map(|_| None)
}
InstructionName::MCOPY => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
let destination = revive_llvm_context::PolkaVMPointer::new_with_offset(
context,
revive_llvm_context::PolkaVMAddressSpace::Heap,
@@ -725,7 +723,7 @@ where
}
InstructionName::SLOAD => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_storage::load(
context,
arguments[0].into_int_value(),
@@ -733,7 +731,7 @@ where
.map(Some)
}
InstructionName::SSTORE => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_storage::store(
context,
arguments[0].into_int_value(),
@@ -742,7 +740,7 @@ where
.map(|_| None)
}
InstructionName::TLOAD => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_storage::transient_load(
context,
arguments[0].into_int_value(),
@@ -750,7 +748,7 @@ where
.map(Some)
}
InstructionName::TSTORE => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_storage::transient_store(
context,
arguments[0].into_int_value(),
@@ -766,27 +764,28 @@ where
let offset = context
.solidity_mut()
.get_or_allocate_immutable(key.as_str());
.get_or_allocate_immutable(key.as_str())
/ revive_common::BYTE_LENGTH_WORD;
let index = context.word_const(offset as u64);
let index = context.xlen_type().const_int(offset as u64, false);
revive_llvm_context::polkavm_evm_immutable::load(context, index).map(Some)
}
InstructionName::ASSIGNIMMUTABLE => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
let key = self
.instruction
.value
.ok_or_else(|| anyhow::anyhow!("Instruction value missing"))?;
let offset = context.solidity_mut().allocate_immutable(key.as_str());
let offset = context.solidity_mut().allocate_immutable(key.as_str())
/ revive_common::BYTE_LENGTH_WORD;
let index = context.word_const(offset as u64);
let index = context.xlen_type().const_int(offset as u64, false);
let value = arguments.pop().expect("Always exists").into_int_value();
revive_llvm_context::polkavm_evm_immutable::store(context, index, value)
.map(|_| None)
}
InstructionName::CALLDATALOAD => {
match context
.code_type()
@@ -796,7 +795,7 @@ where
Ok(Some(context.word_const(0).as_basic_value_enum()))
}
revive_llvm_context::PolkaVMCodeType::Runtime => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_calldata::load(
context,
arguments[0].into_int_value(),
@@ -819,7 +818,7 @@ where
}
}
InstructionName::CALLDATACOPY => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
match context
.code_type()
@@ -862,7 +861,7 @@ where
}
}
InstructionName::CODECOPY => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
let parent = context.module().get_name().to_str().expect("Always valid");
let source = &self.stack_input.elements[1];
@@ -917,7 +916,7 @@ where
revive_llvm_context::polkavm_evm_return_data::size(context).map(Some)
}
InstructionName::RETURNDATACOPY => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_return_data::copy(
context,
arguments[0].into_int_value(),
@@ -927,7 +926,7 @@ where
.map(|_| None)
}
InstructionName::EXTCODESIZE => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_ext_code::size(
context,
Some(arguments[0].into_int_value()),
@@ -935,7 +934,7 @@ where
.map(Some)
}
InstructionName::EXTCODEHASH => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_ext_code::hash(
context,
arguments[0].into_int_value(),
@@ -944,7 +943,7 @@ where
}
InstructionName::RETURN => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_return::r#return(
context,
arguments[0].into_int_value(),
@@ -953,7 +952,7 @@ where
.map(|_| None)
}
InstructionName::REVERT => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_return::revert(
context,
arguments[0].into_int_value(),
@@ -969,7 +968,7 @@ where
}
InstructionName::LOG0 => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_event::log(
context,
arguments.remove(0).into_int_value(),
@@ -982,7 +981,7 @@ where
.map(|_| None)
}
InstructionName::LOG1 => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_event::log(
context,
arguments.remove(0).into_int_value(),
@@ -995,7 +994,7 @@ where
.map(|_| None)
}
InstructionName::LOG2 => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_event::log(
context,
arguments.remove(0).into_int_value(),
@@ -1008,7 +1007,7 @@ where
.map(|_| None)
}
InstructionName::LOG3 => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_event::log(
context,
arguments.remove(0).into_int_value(),
@@ -1021,7 +1020,7 @@ where
.map(|_| None)
}
InstructionName::LOG4 => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
revive_llvm_context::polkavm_evm_event::log(
context,
arguments.remove(0).into_int_value(),
@@ -1035,7 +1034,7 @@ where
}
InstructionName::CALL => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
let gas = arguments.remove(0).into_int_value();
let address = arguments.remove(0).into_int_value();
@@ -1060,7 +1059,7 @@ where
.map(Some)
}
InstructionName::STATICCALL => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
let gas = arguments.remove(0).into_int_value();
let address = arguments.remove(0).into_int_value();
@@ -1084,7 +1083,7 @@ where
.map(Some)
}
InstructionName::DELEGATECALL => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
let gas = arguments.remove(0).into_int_value();
let address = arguments.remove(0).into_int_value();
@@ -1108,7 +1107,7 @@ where
}
InstructionName::CREATE | InstructionName::ZK_CREATE => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
let value = arguments[0].into_int_value();
let input_offset = arguments[1].into_int_value();
@@ -1119,18 +1118,19 @@ where
value,
input_offset,
input_length,
None,
)
.map(Some)
}
InstructionName::CREATE2 | InstructionName::ZK_CREATE2 => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
let value = arguments[0].into_int_value();
let input_offset = arguments[1].into_int_value();
let input_length = arguments[2].into_int_value();
let salt = arguments[3].into_int_value();
revive_llvm_context::polkavm_evm_create::create2(
revive_llvm_context::polkavm_evm_create::create(
context,
value,
input_offset,
@@ -1154,12 +1154,14 @@ where
revive_llvm_context::polkavm_evm_ether_gas::gas(context).map(Some)
}
InstructionName::BALANCE => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
let address = arguments[0].into_int_value();
revive_llvm_context::polkavm_evm_ether_gas::balance(context, address).map(Some)
}
InstructionName::SELFBALANCE => todo!(),
InstructionName::SELFBALANCE => {
revive_llvm_context::polkavm_evm_ether_gas::self_balance(context).map(Some)
}
InstructionName::GASLIMIT => {
revive_llvm_context::polkavm_evm_contract_context::gas_limit(context).map(Some)
@@ -1181,7 +1183,7 @@ where
revive_llvm_context::polkavm_evm_contract_context::block_number(context).map(Some)
}
InstructionName::BLOCKHASH => {
let arguments = self.pop_arguments_llvm(context);
let arguments = self.pop_arguments_llvm(context)?;
let index = arguments[0].into_int_value();
revive_llvm_context::polkavm_evm_contract_context::block_hash(context, index)
@@ -1204,7 +1206,7 @@ where
anyhow::bail!("The `BLOBBASEFEE` instruction is not supported until zkVM v1.5.0");
}
InstructionName::MSIZE => {
revive_llvm_context::polkavm_evm_contract_context::msize(context).map(Some)
revive_llvm_context::polkavm_evm_memory::msize(context).map(Some)
}
InstructionName::CALLCODE => {
@@ -1219,7 +1221,7 @@ where
anyhow::bail!("The `EXTCODECOPY` instruction is not supported");
}
InstructionName::SELFDESTRUCT => {
let _arguments = self.pop_arguments_llvm(context);
let _arguments = self.pop_arguments_llvm(context)?;
anyhow::bail!("The `SELFDESTRUCT` instruction is not supported");
}
@@ -1231,7 +1233,7 @@ where
return_address,
..
} => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
arguments.pop();
arguments.reverse();
arguments.pop();
@@ -1294,7 +1296,7 @@ where
return Ok(());
}
InstructionName::RecursiveReturn { .. } => {
let mut arguments = self.pop_arguments_llvm(context);
let mut arguments = self.pop_arguments_llvm(context)?;
arguments.reverse();
arguments.pop();
@@ -1139,7 +1139,6 @@ where
.integer_type(revive_common::BIT_LENGTH_BOOLEAN)
.as_basic_type_enum()],
output_size,
false,
);
(r#type, output_size)
}
@@ -1156,7 +1155,6 @@ where
input_size
],
output_size,
false,
);
(r#type, output_size)
}
+8 -44
View File
@@ -51,7 +51,6 @@ pub fn yul(
input_files: &[PathBuf],
solc: &mut SolcCompiler,
optimizer_settings: revive_llvm_context::OptimizerSettings,
is_system_mode: bool,
include_metadata_hash: bool,
debug_config: Option<revive_llvm_context::DebugConfig>,
) -> anyhow::Result<Build> {
@@ -64,28 +63,17 @@ pub fn yul(
),
};
let solc_validator = if is_system_mode {
None
} else {
if solc.version()?.default != SolcCompiler::LAST_SUPPORTED_VERSION {
anyhow::bail!(
if solc.version()?.default != SolcCompiler::LAST_SUPPORTED_VERSION {
anyhow::bail!(
"The Yul mode is only supported with the most recent version of the Solidity compiler: {}",
SolcCompiler::LAST_SUPPORTED_VERSION,
);
}
Some(&*solc)
};
}
let solc_validator = Some(&*solc);
let project = Project::try_from_yul_path(path, solc_validator)?;
let build = project.compile(
optimizer_settings,
is_system_mode,
include_metadata_hash,
false,
debug_config,
)?;
let build = project.compile(optimizer_settings, include_metadata_hash, debug_config)?;
Ok(build)
}
@@ -94,7 +82,6 @@ pub fn yul(
pub fn llvm_ir(
input_files: &[PathBuf],
optimizer_settings: revive_llvm_context::OptimizerSettings,
is_system_mode: bool,
include_metadata_hash: bool,
debug_config: Option<revive_llvm_context::DebugConfig>,
) -> anyhow::Result<Build> {
@@ -109,13 +96,7 @@ pub fn llvm_ir(
let project = Project::try_from_llvm_ir_path(path)?;
let build = project.compile(
optimizer_settings,
is_system_mode,
include_metadata_hash,
false,
debug_config,
)?;
let build = project.compile(optimizer_settings, include_metadata_hash, debug_config)?;
Ok(build)
}
@@ -130,7 +111,6 @@ pub fn standard_output(
solc_optimizer_enabled: bool,
optimizer_settings: revive_llvm_context::OptimizerSettings,
force_evmla: bool,
is_system_mode: bool,
include_metadata_hash: bool,
base_path: Option<String>,
include_paths: Vec<String>,
@@ -154,7 +134,6 @@ pub fn standard_output(
None,
&solc_version.default,
optimizer_settings.is_fallback_to_size_enabled(),
optimizer_settings.is_system_request_memoization_disabled(),
),
None,
solc_pipeline == SolcPipeline::Yul,
@@ -200,13 +179,7 @@ pub fn standard_output(
debug_config.as_ref(),
)?;
let build = project.compile(
optimizer_settings,
is_system_mode,
include_metadata_hash,
false,
debug_config,
)?;
let build = project.compile(optimizer_settings, include_metadata_hash, debug_config)?;
Ok(build)
}
@@ -217,7 +190,6 @@ pub fn standard_json(
solc: &mut SolcCompiler,
detect_missing_libraries: bool,
force_evmla: bool,
is_system_mode: bool,
base_path: Option<String>,
include_paths: Vec<String>,
allow_paths: Option<String>,
@@ -278,13 +250,7 @@ pub fn standard_json(
&resolc_version,
)?;
} else {
let build = project.compile(
optimizer_settings,
is_system_mode,
include_metadata_hash,
false,
debug_config,
)?;
let build = project.compile(optimizer_settings, include_metadata_hash, debug_config)?;
build.write_to_standard_json(&mut solc_output, &solc_version, &resolc_version)?;
}
serde_json::to_writer(std::io::stdout(), &solc_output)?;
@@ -302,7 +268,6 @@ pub fn combined_json(
solc_optimizer_enabled: bool,
optimizer_settings: revive_llvm_context::OptimizerSettings,
force_evmla: bool,
is_system_mode: bool,
include_metadata_hash: bool,
base_path: Option<String>,
include_paths: Vec<String>,
@@ -323,7 +288,6 @@ pub fn combined_json(
solc_optimizer_enabled,
optimizer_settings,
force_evmla,
is_system_mode,
include_metadata_hash,
base_path,
include_paths,
-8
View File
@@ -14,12 +14,8 @@ pub struct Input {
pub contract: Contract,
/// The project representation.
pub project: Project,
/// The system mode flag.
pub is_system_mode: bool,
/// Whether to append the metadata hash.
pub include_metadata_hash: bool,
/// Enables the test bytecode encoding.
pub enable_test_encoding: bool,
/// The optimizer settings.
pub optimizer_settings: revive_llvm_context::OptimizerSettings,
/// The debug output config.
@@ -31,18 +27,14 @@ impl Input {
pub fn new(
contract: Contract,
project: Project,
is_system_mode: bool,
include_metadata_hash: bool,
enable_test_encoding: bool,
optimizer_settings: revive_llvm_context::OptimizerSettings,
debug_config: Option<revive_llvm_context::DebugConfig>,
) -> Self {
Self {
contract,
project,
is_system_mode,
include_metadata_hash,
enable_test_encoding,
optimizer_settings,
debug_config,
}
-4
View File
@@ -40,13 +40,9 @@ pub fn run(input_file: Option<&mut std::fs::File>) -> anyhow::Result<()> {
}
let input: Input = revive_common::deserialize_from_slice(buffer.as_slice())?;
if input.enable_test_encoding {
todo!()
}
let result = input.contract.compile(
input.project,
input.optimizer_settings,
input.is_system_mode,
input.include_metadata_hash,
input.debug_config,
);
+1 -3
View File
@@ -78,7 +78,6 @@ impl Contract {
mut self,
project: Project,
optimizer_settings: revive_llvm_context::OptimizerSettings,
is_system_mode: bool,
include_metadata_hash: bool,
debug_config: Option<revive_llvm_context::DebugConfig>,
) -> anyhow::Result<ContractBuild> {
@@ -127,8 +126,7 @@ impl Contract {
context.set_solidity_data(revive_llvm_context::PolkaVMContextSolidityData::default());
match self.ir {
IR::Yul(_) => {
let yul_data = revive_llvm_context::PolkaVMContextYulData::new(is_system_mode);
context.set_yul_data(yul_data);
context.set_yul_data(Default::default());
}
IR::EVMLA(_) => {
let evmla_data = revive_llvm_context::PolkaVMContextEVMLAData::new(version.default);
-6
View File
@@ -62,9 +62,7 @@ impl Project {
pub fn compile(
self,
optimizer_settings: revive_llvm_context::OptimizerSettings,
is_system_mode: bool,
include_metadata_hash: bool,
bytecode_encoding_testing: bool,
debug_config: Option<revive_llvm_context::DebugConfig>,
) -> anyhow::Result<Build> {
let project = self.clone();
@@ -75,9 +73,7 @@ impl Project {
let process_output = crate::process::call(ProcessInput::new(
contract,
project.clone(),
is_system_mode,
include_metadata_hash,
bytecode_encoding_testing,
optimizer_settings.clone(),
debug_config.clone(),
));
@@ -241,7 +237,6 @@ impl revive_llvm_context::PolkaVMDependency for Project {
project: Self,
identifier: &str,
optimizer_settings: revive_llvm_context::OptimizerSettings,
is_system_mode: bool,
include_metadata_hash: bool,
debug_config: Option<revive_llvm_context::DebugConfig>,
) -> anyhow::Result<String> {
@@ -261,7 +256,6 @@ impl revive_llvm_context::PolkaVMDependency for Project {
.compile(
project,
optimizer_settings,
is_system_mode,
include_metadata_hash,
debug_config,
)
+3 -25
View File
@@ -62,10 +62,6 @@ pub struct Arguments {
#[structopt(long = "fallback-Oz")]
pub fallback_to_optimizing_for_size: bool,
/// Disable the system request memoization.
#[structopt(long = "disable-system-request-memoization")]
pub disable_system_request_memoization: bool,
/// Disable the `solc` optimizer.
/// Use it if your project uses the `MSIZE` instruction, or in other cases.
/// Beware that it will prevent libraries from being inlined.
@@ -79,7 +75,7 @@ pub struct Arguments {
pub solc: Option<String>,
/// The EVM target version to generate IR for.
/// See https://github.com/xermicus/revive/blob/main/crates/common/src/evm_version.rs for reference.
/// See https://github.com/paritytech/revive/blob/main/crates/common/src/evm_version.rs for reference.
#[structopt(long = "evm-version")]
pub evm_version: Option<String>,
@@ -123,13 +119,6 @@ pub struct Arguments {
#[structopt(long = "force-evmla")]
pub force_evmla: bool,
/// Enable system contract compilation mode.
/// In this mode PolkaVM extensions are enabled. For example, calls to addresses `0xFFFF` and below
/// are substituted by special PolkaVM instructions.
/// In the Yul mode, the `verbatim_*` instruction family is available.
#[structopt(long = "system-mode")]
pub is_system_mode: bool,
/// Set metadata hash mode.
/// The only supported value is `none` that disables appending the metadata hash.
/// Is enabled by default.
@@ -196,14 +185,14 @@ impl Arguments {
}
#[cfg(debug_assertions)]
if self.recursive_process_input.is_none() && !self.recursive_process {
if self.recursive_process_input.is_some() && !self.recursive_process {
anyhow::bail!("--process-input can be only used when --recursive-process is given");
}
#[cfg(debug_assertions)]
if self.recursive_process
&& ((self.recursive_process_input.is_none() && std::env::args().count() > 2)
|| (self.recursive_process_input.is_none() && std::env::args().count() > 4))
|| (self.recursive_process_input.is_some() && std::env::args().count() > 4))
{
anyhow::bail!("No other options are allowed in recursive mode.");
}
@@ -267,12 +256,6 @@ impl Arguments {
if self.solc.is_some() {
anyhow::bail!("`solc` is not used in LLVM IR and PolkaVM assembly modes.");
}
if self.is_system_mode {
anyhow::bail!(
"System contract mode is not supported in LLVM IR and PolkaVM assembly modes."
);
}
}
if self.combined_json.is_some() {
@@ -319,11 +302,6 @@ impl Arguments {
"Falling back to -Oz must specified in standard JSON input settings."
);
}
if self.disable_system_request_memoization {
anyhow::bail!(
"Disabling the system request memoization must specified in standard JSON input settings."
);
}
if self.metadata_hash.is_some() {
anyhow::bail!("Metadata hash mode must specified in standard JSON input settings.");
}
-8
View File
@@ -101,9 +101,6 @@ fn main_inner() -> anyhow::Result<()> {
if arguments.fallback_to_optimizing_for_size {
optimizer_settings.enable_fallback_to_size();
}
if arguments.disable_system_request_memoization {
optimizer_settings.disable_system_request_memoization();
}
optimizer_settings.is_verify_each_enabled = arguments.llvm_verify_each;
optimizer_settings.is_debug_logging_enabled = arguments.llvm_debug_logging;
@@ -121,7 +118,6 @@ fn main_inner() -> anyhow::Result<()> {
input_files.as_slice(),
&mut solc,
optimizer_settings,
arguments.is_system_mode,
include_metadata_hash,
debug_config,
)
@@ -129,7 +125,6 @@ fn main_inner() -> anyhow::Result<()> {
revive_solidity::llvm_ir(
input_files.as_slice(),
optimizer_settings,
arguments.is_system_mode,
include_metadata_hash,
debug_config,
)
@@ -138,7 +133,6 @@ fn main_inner() -> anyhow::Result<()> {
&mut solc,
arguments.detect_missing_libraries,
arguments.force_evmla,
arguments.is_system_mode,
arguments.base_path,
arguments.include_paths,
arguments.allow_paths,
@@ -155,7 +149,6 @@ fn main_inner() -> anyhow::Result<()> {
!arguments.disable_solc_optimizer,
optimizer_settings,
arguments.force_evmla,
arguments.is_system_mode,
include_metadata_hash,
arguments.base_path,
arguments.include_paths,
@@ -176,7 +169,6 @@ fn main_inner() -> anyhow::Result<()> {
!arguments.disable_solc_optimizer,
optimizer_settings,
arguments.force_evmla,
arguments.is_system_mode,
include_metadata_hash,
arguments.base_path,
arguments.include_paths,
+1 -1
View File
@@ -37,7 +37,7 @@ impl Compiler {
pub const FIRST_VIA_IR_VERSION: semver::Version = semver::Version::new(0, 8, 13);
/// The last supported version of `solc`.
pub const LAST_SUPPORTED_VERSION: semver::Version = semver::Version::new(0, 8, 26);
pub const LAST_SUPPORTED_VERSION: semver::Version = semver::Version::new(0, 8, 28);
/// A shortcut constructor.
/// Different tools may use different `executable` names. For example, the integration tester
@@ -22,9 +22,6 @@ pub struct Optimizer {
/// Whether to try to recompile with -Oz if the bytecode is too large.
#[serde(skip_serializing)]
pub fallback_to_optimizing_for_size: Option<bool>,
/// Whether to disable the system request memoization.
#[serde(skip_serializing)]
pub disable_system_request_memoization: Option<bool>,
}
impl Optimizer {
@@ -34,14 +31,12 @@ impl Optimizer {
mode: Option<char>,
version: &semver::Version,
fallback_to_optimizing_for_size: bool,
disable_system_request_memoization: bool,
) -> Self {
Self {
enabled,
mode,
details: Some(Details::disabled(version)),
fallback_to_optimizing_for_size: Some(fallback_to_optimizing_for_size),
disable_system_request_memoization: Some(disable_system_request_memoization),
}
}
@@ -66,9 +61,6 @@ impl TryFrom<&Optimizer> for revive_llvm_context::OptimizerSettings {
if value.fallback_to_optimizing_for_size.unwrap_or_default() {
result.enable_fallback_to_size();
}
if value.disable_system_request_memoization.unwrap_or_default() {
result.disable_system_request_memoization();
}
Ok(result)
}
}
@@ -41,6 +41,9 @@ pub enum Flag {
EVMBC,
#[serde(rename = "evm.deployedBytecode")]
EVMDBC,
/// The assembly code
#[serde(rename = "evm.assembly")]
Assembly,
}
impl From<SolcPipeline> for Flag {
@@ -66,6 +69,7 @@ impl std::fmt::Display for Flag {
Self::EVMLA => write!(f, "evm.legacyAssembly"),
Self::EVMBC => write!(f, "evm.bytecode"),
Self::EVMDBC => write!(f, "evm.deployedBytecode"),
Self::Assembly => write!(f, "evm.assembly"),
}
}
}
@@ -20,15 +20,19 @@ use self::extra_metadata::ExtraMetadata;
#[serde(rename_all = "camelCase")]
pub struct EVM {
/// The contract EVM legacy assembly code.
#[serde(rename = "legacyAssembly")]
#[serde(rename = "legacyAssembly", skip_serializing_if = "Option::is_none")]
pub assembly: Option<Assembly>,
/// The contract PolkaVM assembly code.
#[serde(rename = "assembly")]
#[serde(rename = "assembly", skip_serializing_if = "Option::is_none")]
pub assembly_text: Option<String>,
/// The contract bytecode.
/// Is reset by that of PolkaVM before yielding the compiled project artifacts.
#[serde(skip_serializing_if = "Option::is_none")]
pub bytecode: Option<Bytecode>,
/// The contract deployed bytecode.
/// The deployed bytecode of the contract.
/// It is overwritten with the PolkaVM blob before yielding the compiled project artifacts.
/// Hence it will be the same as the runtime code but we keep both for compatibility reasons.
#[serde(skip_serializing_if = "Option::is_none")]
pub deployed_bytecode: Option<DeployedBytecode>,
/// The contract function signatures.
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -42,6 +46,7 @@ impl EVM {
/// Sets the PolkaVM assembly and bytecode.
pub fn modify(&mut self, assembly_text: String, bytecode: String) {
self.assembly_text = Some(assembly_text);
self.bytecode = Some(Bytecode::new(bytecode));
self.bytecode = Some(Bytecode::new(bytecode.clone()));
self.deployed_bytecode = Some(DeployedBytecode::new(bytecode));
}
}
+17 -23
View File
@@ -95,7 +95,6 @@ pub fn build_solidity_with_options(
None,
&solc_version.default,
false,
false,
),
None,
pipeline == SolcPipeline::Yul,
@@ -106,7 +105,7 @@ pub fn build_solidity_with_options(
let project = output.try_to_project(sources, libraries, pipeline, &solc_version, None)?;
let build: crate::Build = project.compile(optimizer_settings, false, false, false, None)?;
let build: crate::Build = project.compile(optimizer_settings, false, None)?;
build.write_to_standard_json(
&mut output,
&solc_version,
@@ -144,7 +143,6 @@ pub fn build_solidity_with_options_evm(
None,
&solc_version.default,
false,
false,
),
None,
pipeline == SolcPipeline::Yul,
@@ -193,13 +191,7 @@ pub fn build_solidity_and_detect_missing_libraries(
libraries.clone(),
None,
SolcStandardJsonInputSettingsSelection::new_required(pipeline),
SolcStandardJsonInputSettingsOptimizer::new(
true,
None,
&solc_version.default,
false,
false,
),
SolcStandardJsonInputSettingsOptimizer::new(true, None, &solc_version.default, false),
None,
pipeline == SolcPipeline::Yul,
None,
@@ -229,7 +221,7 @@ pub fn build_yul(source_code: &str) -> anyhow::Result<()> {
let project =
Project::try_from_yul_string(PathBuf::from("test.yul").as_path(), source_code, None)?;
let _build = project.compile(optimizer_settings, false, false, false, None)?;
let _build = project.compile(optimizer_settings, false, None)?;
Ok(())
}
@@ -259,13 +251,7 @@ pub fn check_solidity_warning(
libraries,
None,
SolcStandardJsonInputSettingsSelection::new_required(pipeline),
SolcStandardJsonInputSettingsOptimizer::new(
true,
None,
&solc_version.default,
false,
false,
),
SolcStandardJsonInputSettingsOptimizer::new(true, None, &solc_version.default, false),
None,
pipeline == SolcPipeline::Yul,
suppressed_warnings,
@@ -290,18 +276,26 @@ pub fn compile_blob(contract_name: &str, source_code: &str) -> Vec<u8> {
/// Compile the EVM bin-runtime of `contract_name` found in given `source_code`.
/// The `solc` optimizer will be enabled
pub fn compile_evm_bin_runtime(contract_name: &str, source_code: &str) -> Vec<u8> {
compile_evm(contract_name, source_code, true)
compile_evm(contract_name, source_code, true, true)
}
/// Compile the EVM bin of `contract_name` found in given `source_code`.
/// The `solc` optimizer will be enabled
pub fn compile_evm_deploy_code(contract_name: &str, source_code: &str) -> Vec<u8> {
compile_evm(contract_name, source_code, false)
pub fn compile_evm_deploy_code(
contract_name: &str,
source_code: &str,
solc_optimizer_enabled: bool,
) -> Vec<u8> {
compile_evm(contract_name, source_code, solc_optimizer_enabled, false)
}
fn compile_evm(contract_name: &str, source_code: &str, runtime: bool) -> Vec<u8> {
fn compile_evm(
contract_name: &str,
source_code: &str,
solc_optimizer_enabled: bool,
runtime: bool,
) -> Vec<u8> {
let pipeline = SolcPipeline::Yul;
let solc_optimizer_enabled = true;
let id = CachedBlob {
contract_name: contract_name.to_owned(),
pipeline,
@@ -3,7 +3,7 @@
"version": "1.0.0",
"title": "resolc CLI Tests",
"description": "Auto tests for verifying resolc CLI",
"repository": "https://github.com/xermicus/revive",
"repository": "https://github.com/paritytech/revive",
"main": "index.js",
"private": true,
"scripts": {
@@ -125,13 +125,6 @@ impl FunctionCall {
let location = self.location;
match self.name {
Name::UserDefined(name)
if name.starts_with(
revive_llvm_context::PolkaVMFunction::ZKSYNC_NEAR_CALL_ABI_PREFIX,
) && context.is_system_mode() =>
{
unimplemented!();
}
Name::UserDefined(name) => {
let mut values = Vec::with_capacity(self.arguments.len());
for argument in self.arguments.into_iter().rev() {
@@ -501,25 +494,30 @@ impl FunctionCall {
)
.map(|_| None)
}
Name::LoadImmutable => todo!(),
Name::LoadImmutable => {
let mut arguments = self.pop_arguments::<D, 1>(context)?;
let key = arguments[0].original.take().ok_or_else(|| {
anyhow::anyhow!("{} `load_immutable` literal is missing", location)
})?;
let offset = context
.solidity_mut()
.get_or_allocate_immutable(key.as_str())
/ revive_common::BYTE_LENGTH_WORD;
let index = context.xlen_type().const_int(offset as u64, false);
revive_llvm_context::polkavm_evm_immutable::load(context, index).map(Some)
}
Name::SetImmutable => {
let mut arguments = self.pop_arguments::<D, 3>(context)?;
let key = arguments[1].original.take().ok_or_else(|| {
anyhow::anyhow!("{} `load_immutable` literal is missing", location)
})?;
if key.as_str() == "library_deploy_address" {
return Ok(None);
}
let offset = context.solidity_mut().allocate_immutable(key.as_str());
let index = context.word_const(offset as u64);
let offset = context.solidity_mut().allocate_immutable(key.as_str())
/ revive_common::BYTE_LENGTH_WORD;
let index = context.xlen_type().const_int(offset as u64, false);
let value = arguments[2].value.into_int_value();
revive_llvm_context::polkavm_evm_immutable::store(context, index, value)
.map(|_| None)
}
Name::CallDataLoad => {
let arguments = self.pop_arguments_llvm::<D, 1>(context)?;
@@ -831,6 +829,7 @@ impl FunctionCall {
value,
input_offset,
input_length,
None,
)
.map(Some)
}
@@ -842,7 +841,7 @@ impl FunctionCall {
let input_length = arguments[2].into_int_value();
let salt = arguments[3].into_int_value();
revive_llvm_context::polkavm_evm_create::create2(
revive_llvm_context::polkavm_evm_create::create(
context,
value,
input_offset,
@@ -912,7 +911,9 @@ impl FunctionCall {
let address = arguments[0].into_int_value();
revive_llvm_context::polkavm_evm_ether_gas::balance(context, address).map(Some)
}
Name::SelfBalance => todo!(),
Name::SelfBalance => {
revive_llvm_context::polkavm_evm_ether_gas::self_balance(context).map(Some)
}
Name::GasLimit => {
revive_llvm_context::polkavm_evm_contract_context::gas_limit(context).map(Some)
@@ -962,9 +963,7 @@ impl FunctionCall {
location
);
}
Name::MSize => {
revive_llvm_context::polkavm_evm_contract_context::msize(context).map(Some)
}
Name::MSize => revive_llvm_context::polkavm_evm_memory::msize(context).map(Some),
Name::Verbatim {
input_size,
@@ -92,37 +92,7 @@ impl FunctionDefinition {
}
}
let (mut arguments, next) = Identifier::parse_typed_list(lexer, None)?;
if identifier
.inner
.contains(revive_llvm_context::PolkaVMFunction::ZKSYNC_NEAR_CALL_ABI_PREFIX)
{
if arguments.is_empty() {
return Err(ParserError::InvalidNumberOfArguments {
location,
identifier: identifier.inner,
expected: 1,
found: arguments.len(),
}
.into());
}
arguments.remove(0);
}
if identifier
.inner
.contains(revive_llvm_context::PolkaVMFunction::ZKSYNC_NEAR_CALL_ABI_EXCEPTION_HANDLER)
&& !arguments.is_empty()
{
return Err(ParserError::InvalidNumberOfArguments {
location,
identifier: identifier.inner,
expected: 0,
found: arguments.len(),
}
.into());
}
let (arguments, next) = Identifier::parse_typed_list(lexer, None)?;
match crate::yul::parser::take_or_next(next, lexer)? {
Token {
lexeme: Lexeme::Symbol(Symbol::ParenthesisRight),
@@ -234,12 +204,7 @@ where
})
.collect();
let function_type = context.function_type(
argument_types,
self.result.len(),
self.identifier
.starts_with(revive_llvm_context::PolkaVMFunction::ZKSYNC_NEAR_CALL_ABI_PREFIX),
);
let function_type = context.function_type(argument_types, self.result.len());
let function = context.add_function(
self.identifier.as_str(),
@@ -310,23 +275,12 @@ where
yul_type.into_llvm(context)
})
.collect();
for (mut index, argument) in self.arguments.iter().enumerate() {
for (index, argument) in self.arguments.iter().enumerate() {
let pointer = context.build_alloca(argument_types[index], argument.inner.as_str());
context
.current_function()
.borrow_mut()
.insert_stack_pointer(argument.inner.clone(), pointer);
if self
.identifier
.starts_with(revive_llvm_context::PolkaVMFunction::ZKSYNC_NEAR_CALL_ABI_PREFIX)
&& matches!(
context.current_function().borrow().r#return(),
revive_llvm_context::PolkaVMFunctionReturn::Compound { .. }
)
&& context.is_system_mode()
{
index += 1;
}
context.build_store(
pointer,
context.current_function().borrow().get_nth_param(index),
@@ -354,13 +308,6 @@ where
let return_value = context.build_load(pointer, "return_value")?;
context.build_return(Some(&return_value));
}
revive_llvm_context::PolkaVMFunctionReturn::Compound { pointer, .. }
if context.current_function().borrow().name().starts_with(
revive_llvm_context::PolkaVMFunction::ZKSYNC_NEAR_CALL_ABI_PREFIX,
) =>
{
context.build_return(Some(&pointer.value));
}
revive_llvm_context::PolkaVMFunctionReturn::Compound { pointer, .. } => {
let return_value = context.build_load(pointer, "return_value")?;
context.build_return(Some(&return_value));
@@ -524,80 +471,6 @@ object "Test" {
);
}
#[test]
fn error_invalid_number_of_arguments_near_call_abi() {
let input = r#"
object "Test" {
code {
{
return(0, 0)
}
}
object "Test_deployed" {
code {
{
return(0, 0)
}
function ZKSYNC_NEAR_CALL_test() -> result {
result := 42
}
}
}
}
"#;
let mut lexer = Lexer::new(input.to_owned());
let result = Object::parse(&mut lexer, None);
assert_eq!(
result,
Err(Error::InvalidNumberOfArguments {
location: Location::new(14, 22),
identifier: "ZKSYNC_NEAR_CALL_test".to_owned(),
expected: 1,
found: 0,
}
.into())
);
}
#[test]
fn error_invalid_number_of_arguments_near_call_abi_catch() {
let input = r#"
object "Test" {
code {
{
return(0, 0)
}
}
object "Test_deployed" {
code {
{
return(0, 0)
}
function ZKSYNC_CATCH_NEAR_CALL(length) {
revert(0, length)
}
}
}
}
"#;
let mut lexer = Lexer::new(input.to_owned());
let result = Object::parse(&mut lexer, None);
assert_eq!(
result,
Err(Error::InvalidNumberOfArguments {
location: Location::new(14, 22),
identifier: "ZKSYNC_CATCH_NEAR_CALL".to_owned(),
expected: 0,
found: 1,
}
.into())
);
}
#[test]
fn error_reserved_identifier() {
let input = r#"
@@ -183,6 +183,7 @@ where
&mut self,
context: &mut revive_llvm_context::PolkaVMContext<D>,
) -> anyhow::Result<()> {
revive_llvm_context::PolkaVMImmutableDataLoadFunction.declare(context)?;
let mut entry = revive_llvm_context::PolkaVMEntryFunction::default();
entry.declare(context)?;
@@ -199,6 +200,7 @@ where
revive_llvm_context::PolkaVMFunctionDeployCode,
revive_llvm_context::PolkaVMFunctionRuntimeCode,
revive_llvm_context::PolkaVMFunctionEntry,
revive_llvm_context::PolkaVMFunctionImmutableDataLoad,
]
.into_iter()
{
@@ -216,6 +218,7 @@ where
fn into_llvm(self, context: &mut revive_llvm_context::PolkaVMContext<D>) -> anyhow::Result<()> {
if self.identifier.ends_with("_deployed") {
revive_llvm_context::PolkaVMImmutableDataLoadFunction.into_llvm(context)?;
revive_llvm_context::PolkaVMRuntimeCodeFunction::new(self.code).into_llvm(context)?;
} else {
revive_llvm_context::PolkaVMDeployCodeFunction::new(self.code).into_llvm(context)?;
+7
View File
@@ -0,0 +1,7 @@
#! /usr/bin/env bash
CONTAINER=revive-builder-debian-x86
VERSION=latest
DOCKERFILE=revive-builder-debian.dockerfile
docker build --rm -t ${CONTAINER}:${VERSION} -f ${DOCKERFILE} $@
+20
View File
@@ -0,0 +1,20 @@
#! /usr/bin/env bash
set -euo pipefail
REVIVE_INSTALL_DIR=$(pwd)/target/release
while getopts "o:" option ; do
case $option in
o) # Output directory
REVIVE_INSTALL_DIR=$OPTARG
;;
\?) echo "Error: Invalid option"
exit 1;;
esac
done
echo "Installing to ${REVIVE_INSTALL_DIR}"
$(pwd)/build-llvm.sh
export PATH=$(pwd)/llvm18.0/bin:$PATH
make install-revive REVIVE_INSTALL_DIR=${REVIVE_INSTALL_DIR}
+14
View File
@@ -0,0 +1,14 @@
# syntax=docker/dockerfile:1
# Dockerfile for building revive in a Debian container.
FROM debian:12
RUN <<EOF
apt-get update
apt-get install -q -y build-essential cmake make ninja-build python3 \
libmpfr-dev libgmp-dev libmpc-dev ncurses-dev \
git curl
EOF
ARG RUST_VERSION=stable
RUN <<EOF
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain ${RUST_VERSION}
EOF
ENV PATH=/root/.cargo/bin:${PATH}
+6
View File
@@ -0,0 +1,6 @@
#! /usr/bin/env bash
CONTAINER=revive-builder-debian-x86
VERSION=latest
docker run --rm -v $(pwd):$(pwd) -w $(pwd) ${CONTAINER}:${VERSION} $@