Skip to content

Commit

Permalink
Add error handling for too large rip relative displacements
Browse files Browse the repository at this point in the history
  • Loading branch information
ZehMatt committed May 1, 2024
1 parent f04bc83 commit 0cb0e70
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/tests/tests/tests.serialization.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1240,4 +1240,21 @@ namespace zasm::tests
ASSERT_EQ(res, ErrorCode::None);
}

TEST(SerializationTests, TestBadMemoryDisplacement)
{
Program program(MachineMode::AMD64);

x86::Assembler a(program);
ASSERT_EQ(a.mov(x86::rax, x86::qword_ptr(x86::rip, 0xF23456789)), ErrorCode::None);

Serializer serializer;
auto res = serializer.serialize(program, 0x140015000);
ASSERT_EQ(res, ErrorCode::AddressOutOfRange);

ASSERT_EQ(
res.getErrorMessage(),
std::string("Error at node \"mov rax, qword ptr ds:[rel 0xf23456789]\" with id 0: Displacement out of range for "
"operand 1"));
}

} // namespace zasm::tests
7 changes: 7 additions & 0 deletions src/zasm/src/encoder/encoder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,13 @@ namespace zasm
if (isDisplacementValid)
{
displacement = displacement - (address + instrSize);
if (std::abs(displacement) > std::numeric_limits<std::int32_t>::max())
{
char msg[128];
std::snprintf(msg, sizeof(msg), "Displacement out of range for operand %zu", state.operandIndex);

return Error(ErrorCode::AddressOutOfRange, msg);
}
}
}

Expand Down

0 comments on commit 0cb0e70

Please sign in to comment.