-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathevm_instance.cpp
More file actions
317 lines (277 loc) · 9.43 KB
/
evm_instance.cpp
File metadata and controls
317 lines (277 loc) · 9.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// Copyright (C) 2025 the DTVM authors. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
#include "runtime/evm_instance.h"
#include "common/errors.h"
#include "common/evm_traphandler.h"
#include "entrypoint/entrypoint.h"
#include "evm/evm.h"
#include "utils/backtrace.h"
#include <algorithm>
#include <cstring>
#include <utility>
namespace zen::runtime {
using namespace common;
namespace {
bool calcRequiredMemorySize(uint64_t Offset, uint64_t Size,
uint64_t &RequiredSize) {
if (Offset > std::numeric_limits<uint64_t>::max() - Size) {
return false;
}
RequiredSize = Offset + Size;
return true;
}
void initMemoryFrame(std::unique_ptr<uint8_t[]> &Memory, uint8_t *&Base,
uint64_t &Size) {
// Reset frame state only; backing allocation is handled lazily by
// ensureMemoryBuffer() when real memory growth happens.
Base = Memory.get();
Size = 0;
}
void ensureMemoryBuffer(std::unique_ptr<uint8_t[]> &Memory, uint8_t *&Base) {
if (!Memory) {
// Lazily allocate memory backing store on first real expansion.
Memory.reset(new uint8_t[zen::evm::MAX_REQUIRED_MEMORY_SIZE]);
}
Base = Memory.get();
}
} // namespace
EVMInstanceUniquePtr EVMInstance::newEVMInstance(Isolation &Iso,
const EVMModule &Mod,
uint64_t GasLimit) {
#ifdef ZEN_ENABLE_CPU_EXCEPTION
[[maybe_unused]] static bool _ =
common::evm_traphandler::initEVMPlatformTrapHandler();
#endif // ZEN_ENABLE_CPU_EXCEPTION
Runtime *RT = Mod.getRuntime();
void *Buf = RT->allocate(sizeof(EVMInstance), ALIGNMENT);
ZEN_ASSERT(Buf);
EVMInstanceUniquePtr Inst(new (Buf) EVMInstance(Mod, *RT));
Inst->Iso = &Iso;
Inst->setGas(GasLimit);
return Inst;
}
EVMInstance::~EVMInstance() {}
void EVMInstance::resetForNewCall(evmc_revision NewRev) {
// Reset gas accounting
Gas = 0;
GasRefund = 0;
Rev = NewRev;
InstanceExitCode = 0;
Err = common::ErrorCode::NoError;
// Reset message stack (clear but keep capacity)
CurrentMessage = nullptr;
MessageStack.clear();
GasRefundStack.clear();
// Reset memory: keep the 16MB allocation, just reset the size
MemoryBase = nullptr;
MemorySize = 0;
// Don't release Memory - reuse the allocation on next pushMessage()
MemoryStack.clear();
// Reset output
clearReturnData();
ExeResult = evmc::Result{EVMC_SUCCESS, 0, 0};
// Reset execution cache: clear() keeps allocated bucket arrays,
// avoiding repeated alloc/free of unordered_map internals.
InstanceExecutionCache.BlockHashes.clear();
InstanceExecutionCache.BlobHashes.clear();
InstanceExecutionCache.CalldataLoads.clear();
InstanceExecutionCache.ExtcodeHashes.clear();
InstanceExecutionCache.Keccak256Results.clear();
InstanceExecutionCache.TxContextCached = false;
// Reset JIT stack
EVMStackSize = 0;
}
void EVMInstance::resetForNewCall(evmc_revision NewRev, const EVMModule &M) {
resetForNewCall(NewRev);
Mod = &M;
}
void EVMInstance::setGas(uint64_t NewGas) { Gas = NewGas; }
void EVMInstance::pushMessage(evmc_message *Msg) {
if (MessageStack.empty()) {
MemoryStack.clear();
} else {
MemoryStack.push_back({std::move(Memory), MemorySize});
}
initMemoryFrame(Memory, MemoryBase, MemorySize);
MessageStack.push_back(Msg);
CurrentMessage = Msg;
GasRefundStack.push_back(GasRefund);
Gas = Msg ? Msg->gas : 0;
}
void EVMInstance::popMessage() {
if (!MessageStack.empty()) {
MessageStack.pop_back();
}
CurrentMessage = MessageStack.empty() ? nullptr : MessageStack.back();
if (!GasRefundStack.empty()) {
// Only pop the snapshot: successful subcalls keep their accumulated
// refunds. On failures, refund rollback is handled by
// restoreGasRefundSnapshot() using this stack.
GasRefundStack.pop_back();
}
if (!MemoryStack.empty()) {
Memory = std::move(MemoryStack.back().Data);
MemorySize = MemoryStack.back().Size;
MemoryStack.pop_back();
MemoryBase = Memory.get();
} else {
MemoryBase = Memory.get();
MemorySize = 0;
}
Gas = CurrentMessage ? CurrentMessage->gas : 0;
}
uint64_t EVMInstance::calculateMemoryExpansionCost(uint64_t CurrentSize,
uint64_t NewSize) {
if (NewSize <= CurrentSize) {
return 0; // No expansion needed
}
uint64_t CurrentWords = (CurrentSize + 31) / 32;
uint64_t NewWords = (NewSize + 31) / 32;
auto MemoryCost = [](uint64_t Words) -> uint64_t {
__int128 W = Words;
return static_cast<uint64_t>(W * W / 512 + 3 * W);
};
uint64_t CurrentCost = MemoryCost(CurrentWords);
uint64_t NewCost = MemoryCost(NewWords);
return NewCost - CurrentCost;
}
void EVMInstance::setExecutionError(const Error &NewErr, uint32_t IgnoredDepth,
common::evm_traphandler::EVMTrapState TS) {
ZEN_ASSERT(NewErr.getPhase() == common::ErrorPhase::Execution);
setError(NewErr);
if (NewErr.getCode() != ErrorCode::NoError &&
NewErr.getCode() != ErrorCode::InstanceExit) {
restoreGasRefundSnapshot();
}
if (NewErr.getCode() == ErrorCode::GasLimitExceeded) {
setGas(0); // gas left
}
}
void EVMInstance::exit(int32_t ExitCode) {
this->InstanceExitCode = ExitCode;
setExceptionByHostapi(common::getError(ErrorCode::InstanceExit));
}
#ifdef ZEN_ENABLE_JIT
void EVMInstance::setInstanceExceptionOnJIT(EVMInstance *Inst,
common::ErrorCode ErrCode) {
Inst->setExecutionError(common::getError(ErrCode), 1,
common::evm_traphandler::EVMTrapState{});
}
void EVMInstance::throwInstanceExceptionOnJIT(EVMInstance *Inst) {
#ifdef ZEN_ENABLE_CPU_EXCEPTION
SAVE_EVM_HOSTAPI_FRAME_POINTER_TO_TLS
utils::throwCpuIllegalInstructionTrap();
#endif // ZEN_ENABLE_CPU_EXCEPTION
}
void EVMInstance::triggerInstanceExceptionOnJIT(EVMInstance *Inst,
common::ErrorCode ErrCode) {
// Not use setInstanceExceptionOnJIT instead of the following code, because we
// need correct `ignored_depth`
Inst->setExecutionError(common::getError(ErrCode), 1,
common::evm_traphandler::EVMTrapState{});
throwInstanceExceptionOnJIT(Inst);
}
#endif // ZEN_ENABLE_JIT
void EVMInstance::expandMemory(uint64_t RequiredSize) {
auto NewSize = (RequiredSize + 31) / 32 * 32;
uint64_t ExpansionCost = calculateMemoryExpansionCost(MemorySize, NewSize);
chargeGas(ExpansionCost);
if (NewSize > MemorySize) {
if (!MemoryBase) {
ensureMemoryBuffer(Memory, MemoryBase);
}
if (NewSize > MemorySize) {
std::memset(MemoryBase + MemorySize, 0,
static_cast<size_t>(NewSize - MemorySize));
MemorySize = NewSize;
}
}
}
void EVMInstance::expandMemoryNoGas(uint64_t RequiredSize) {
auto NewSize = (RequiredSize + 31) / 32 * 32;
if (NewSize > MemorySize) {
if (!MemoryBase) {
ensureMemoryBuffer(Memory, MemoryBase);
}
if (NewSize > MemorySize) {
std::memset(MemoryBase + MemorySize, 0,
static_cast<size_t>(NewSize - MemorySize));
MemorySize = NewSize;
}
}
}
bool EVMInstance::expandMemoryChecked(uint64_t Offset, uint64_t Size) {
if (Size == 0) {
return true;
}
uint64_t RequiredSize = 0;
if (!calcRequiredMemorySize(Offset, Size, RequiredSize)) {
chargeGas(getGas() + 1);
return false;
}
if (RequiredSize > zen::evm::MAX_REQUIRED_MEMORY_SIZE) {
chargeGas(getGas() + 1);
return false;
}
expandMemory(RequiredSize);
return true;
}
bool EVMInstance::expandMemoryChecked(uint64_t OffsetA, uint64_t SizeA,
uint64_t OffsetB, uint64_t SizeB) {
const bool NeedA = SizeA > 0;
const bool NeedB = SizeB > 0;
if (!NeedA && !NeedB) {
return true;
}
if (NeedA && !NeedB) {
return expandMemoryChecked(OffsetA, SizeA);
}
if (!NeedA && NeedB) {
return expandMemoryChecked(OffsetB, SizeB);
}
uint64_t RequiredSizeA = 0;
uint64_t RequiredSizeB = 0;
if (!calcRequiredMemorySize(OffsetA, SizeA, RequiredSizeA) ||
!calcRequiredMemorySize(OffsetB, SizeB, RequiredSizeB)) {
chargeGas(getGas() + 1);
return false;
}
const uint64_t RequiredSize = std::max(RequiredSizeA, RequiredSizeB);
if (RequiredSize > zen::evm::MAX_REQUIRED_MEMORY_SIZE) {
chargeGas(getGas() + 1);
return false;
}
expandMemory(RequiredSize);
return true;
}
void EVMInstance::chargeGas(uint64_t GasCost) {
evmc_message *Msg = getCurrentMessage();
ZEN_ASSERT(Msg && "Active message required for gas accounting");
uint64_t GasLeft = getGas();
if (GasLeft < GasCost) {
#if defined(ZEN_ENABLE_JIT) && defined(ZEN_ENABLE_CPU_EXCEPTION)
triggerInstanceExceptionOnJIT(this, common::ErrorCode::GasLimitExceeded);
#else
throw common::getError(common::ErrorCode::GasLimitExceeded);
#endif
}
uint64_t NewGas = GasLeft - GasCost;
setGas(NewGas);
Msg->gas = static_cast<int64_t>(NewGas);
}
void EVMInstance::addGas(uint64_t GasAmount) {
evmc_message *Msg = getCurrentMessage();
ZEN_ASSERT(Msg && "Active message required for gas accounting");
uint64_t GasLeft = getGas();
if (GasLeft > UINT64_MAX - GasAmount) {
#if defined(ZEN_ENABLE_JIT) && defined(ZEN_ENABLE_CPU_EXCEPTION)
triggerInstanceExceptionOnJIT(this, common::ErrorCode::GasLimitExceeded);
#else
throw common::getError(common::ErrorCode::GasLimitExceeded);
#endif
}
uint64_t NewGas = GasLeft + GasAmount;
setGas(NewGas);
Msg->gas = static_cast<int64_t>(NewGas);
}
} // namespace zen::runtime