Skip to content

Commit 8d4697f

Browse files
[mlir][Sol] Add length guard for dynamic-memory allocation during ABI decoding
Signed-off-by: Vladimir Radosavljevic <vr@matterlabs.dev>
1 parent 7a08c47 commit 8d4697f

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

mlir/include/mlir/Conversion/SolToStandard/EVMUtil.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,8 @@ class Builder {
131131

132132
/// Generates the memory allocation code for dynamic array.
133133
Value genMemAllocForDynArray(Value sizeVar, Value sizeInBytes,
134-
std::optional<Location> locArg = std::nullopt);
134+
std::optional<Location> locArg = std::nullopt,
135+
bool genLengthPanicGuard = false);
135136

136137
/// Generates the memory allocation code.
137138
Value genMemAlloc(Type ty, bool zeroInit, ValueRange initVals, Value sizeVar,

mlir/lib/Conversion/SolToStandard/EVMUtil.cpp

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -297,11 +297,19 @@ Value evm::Builder::genMemAlloc(AllocSize size,
297297
}
298298

299299
Value evm::Builder::genMemAllocForDynArray(Value sizeVar, Value sizeInBytes,
300-
std::optional<Location> locArg) {
300+
std::optional<Location> locArg,
301+
bool genLengthPanicGuard) {
301302
Location loc = locArg ? *locArg : defLoc;
302303

303304
mlir::solgen::BuilderExt bExt(b, loc);
304305

306+
if (genLengthPanicGuard) {
307+
auto panicCond = b.create<arith::CmpIOp>(
308+
loc, arith::CmpIPredicate::ugt, sizeVar,
309+
bExt.genI256Const(APInt::getLowBitsSet(256, 64)));
310+
genPanic(mlir::evm::PanicCode::ResourceError, panicCond, loc);
311+
}
312+
305313
// dynSize is size + length-slot where length-slot's size is 32 bytes.
306314
auto dynSizeInBytes =
307315
b.create<arith::AddIOp>(loc, sizeInBytes, bExt.genI256Const(32));
@@ -1694,7 +1702,8 @@ Value evm::Builder::genABITupleDecoding(Type ty, Value addr, bool fromMem,
16941702
return bExt.genLLVMStruct({srcAddr, i256Size});
16951703

16961704
dstAddr = genMemAllocForDynArray(
1697-
i256Size, b.create<arith::MulIOp>(loc, i256Size, thirtyTwo));
1705+
i256Size, b.create<arith::MulIOp>(loc, i256Size, thirtyTwo), loc,
1706+
true);
16981707
ret = dstAddr;
16991708
// Skip the size fields in both the addresses.
17001709
dstAddr = b.create<arith::AddIOp>(loc, dstAddr, thirtyTwo);
@@ -1799,7 +1808,7 @@ Value evm::Builder::genABITupleDecoding(Type ty, Value addr, bool fromMem,
17991808

18001809
// Copy the decoded string to a new memory allocation.
18011810
Value dstAddr = genMemAllocForDynArray(
1802-
sizeInBytes, bExt.genRoundUpToMultiple<32>(sizeInBytes), loc);
1811+
sizeInBytes, bExt.genRoundUpToMultiple<32>(sizeInBytes), loc, true);
18031812
Value dstDataAddr = b.create<arith::AddIOp>(loc, dstAddr, thirtyTwo);
18041813

18051814
if (fromMem)

0 commit comments

Comments
 (0)