Merge pull request #211 from ljkx/fix/decoder-rex-prefix-order

fix(relinker): ignore a REX prefix that is followed by another prefix
This commit is contained in:
boykopovar
2026-10-01 21:21:44 +03:00
committed by GitHub
9 changed files with 87 additions and 81 deletions
@@ -4,7 +4,6 @@
#include <codegen/x86/Amd64OnlySubstitutionTable.hpp>
#include <codegen/x86/X64InstructionDecoder.hpp>
#include <codegen/x86/X64InstructionRewriter.hpp>
#include <codegen/x86/X64OpcodeConstants.hpp>
#include <codegen/x86/IAmd64OnlyInstructionMatcher.hpp>
#include <algorithm>
#include <memory>
@@ -17,15 +16,6 @@ namespace Codegen {
namespace {
bool _isPrefixRun(const std::uint8_t* data, const std::size_t length) {
using namespace X64OpcodeConstants;
return std::all_of(data, data + length, [](const std::uint8_t b) {
return (b >= RexMin && b <= RexMax) || b == PrefixLock || b == PrefixRepne || b == PrefixRep ||
b == PrefixSegCs || b == PrefixSegSs || b == PrefixSegDs || b == PrefixSegEs ||
b == PrefixSegFs || b == PrefixSegGs || b == PrefixOperandSize || b == PrefixAddressSize;
});
}
template<typename TOperation>
auto _atFileOffset(const Domain::FileByteOffset base, const TOperation& operation) {
try {
@@ -120,11 +110,6 @@ void Amd64OnlyConverter::_convertSegment(
for (const auto& item : pending) {
if (consumed.contains(item.Index))
continue;
if (item.Index > 0) {
const auto& previous = matches[item.Index - 1];
if (previous.Offset + previous.Length == item.Instruction.Offset && _isPrefixRun(seg.data() + previous.Offset, previous.Length))
throw CodegenException("AMD-only instruction follows prefixes the decoder split from it", ph.Offset + previous.Offset);
}
const auto& match = item.Instruction;
const auto& substitution = item.Substitution;
const auto fileOffset = static_cast<Domain::FileByteOffset>(ph.Offset + match.Offset);
@@ -157,7 +142,7 @@ void Amd64OnlyConverter::_convertSegment(
if (amdOnly && trailingBytes == 0) {
sequence.push_back(bytes);
consumed.insert(next);
} else if (amdOnly || info.FlowKind != ControlFlowKind::Sequential || info.HasRipRelativeDisp || info.HasBranchTarget || _isPrefixRun(bytes.data(), bytes.size())) {
} else if (amdOnly || info.FlowKind != ControlFlowKind::Sequential || info.HasRipRelativeDisp || info.HasBranchTarget) {
throw CodegenException("AMD-only instruction too short for a jump is followed by an instruction that cannot move", ph.Offset + following.Offset);
} else {
trailingBytes += following.Length;
@@ -22,6 +22,10 @@ ClzeroOperands DecodeClzero(const std::uint8_t* data, const std::size_t length)
while (pos < length) {
const std::uint8_t b = data[pos];
if (b >= RexMin && b <= RexMax) {
pos += 1;
continue;
}
if (b == PrefixLock) {
throw CodegenException("CLZERO with a LOCK prefix");
}
@@ -39,10 +43,6 @@ ClzeroOperands DecodeClzero(const std::uint8_t* data, const std::size_t length)
pos += 1;
}
if (pos < length && data[pos] >= RexMin && data[pos] <= RexMax) {
pos += 1;
}
if (pos + 3 != length || data[pos] != TwoByteOpcodeEscape || data[pos + 1] != TwoByteGrp7 || data[pos + 2] != 0xFC) {
throw CodegenException("Not a CLZERO instruction");
}
@@ -18,6 +18,11 @@ std::size_t DecodedInstruction::_skipPrefixesAndRex(
while (pos < Length) {
const std::uint8_t b = Data[pos];
if (b >= RexMin && b <= RexMax) {
pos += 1;
continue;
}
if (b == PrefixRepne) {
*outHasRepnePrefix = true;
pos += 1;
@@ -51,10 +56,6 @@ std::size_t DecodedInstruction::_skipPrefixesAndRex(
break;
}
if (pos < Length && Data[pos] >= RexMin && Data[pos] <= RexMax) {
pos += 1;
}
return pos;
}
@@ -8,9 +8,15 @@ using namespace X64OpcodeConstants;
Sha256Operands DecodeSha256(const std::uint8_t* data, const std::size_t length) {
std::size_t pos = 0;
std::uint8_t rex = 0;
while (pos < length) {
const std::uint8_t b = data[pos];
if (b >= RexMin && b <= RexMax) {
rex = b;
pos += 1;
continue;
}
if (b == PrefixOperandSize || b == PrefixRepne || b == PrefixRep) {
throw CodegenException("Not a SHA-256 instruction");
}
@@ -19,12 +25,7 @@ Sha256Operands DecodeSha256(const std::uint8_t* data, const std::size_t length)
b != PrefixSegEs && b != PrefixSegFs && b != PrefixSegGs) {
break;
}
pos += 1;
}
std::uint8_t rex = 0;
if (pos < length && data[pos] >= RexMin && data[pos] <= RexMax) {
rex = data[pos];
rex = 0;
pos += 1;
}
@@ -10,9 +10,15 @@ Sse4aOperands DecodeSse4a(const std::uint8_t* data, const std::size_t length) {
std::size_t pos = 0;
bool operandSizeOverride = false;
bool repnePrefix = false;
std::uint8_t rex = 0;
while (pos < length) {
const std::uint8_t b = data[pos];
if (b >= RexMin && b <= RexMax) {
rex = b;
pos += 1;
continue;
}
if (b == PrefixOperandSize) {
operandSizeOverride = true;
} else if (b == PrefixRepne) {
@@ -22,12 +28,7 @@ Sse4aOperands DecodeSse4a(const std::uint8_t* data, const std::size_t length) {
b != PrefixSegEs && b != PrefixSegFs && b != PrefixSegGs) {
break;
}
pos += 1;
}
std::uint8_t rex = 0;
if (pos < length && data[pos] >= RexMin && data[pos] <= RexMax) {
rex = data[pos];
rex = 0;
pos += 1;
}
@@ -17,36 +17,25 @@ std::size_t X64InstructionDecoder::Decode(const std::uint8_t* data, std::size_t
while (pos < available) {
const std::uint8_t b = data[pos];
if (b >= RexMin && b <= RexMax) {
rexPresent = true;
rex = b;
pos += 1;
continue;
}
if (b == PrefixRepne) {
repnePrefix = true;
pos += 1;
continue;
}
if (b == PrefixLock || b == PrefixRep ||
b == PrefixSegCs || b == PrefixSegSs || b == PrefixSegDs || b == PrefixSegEs ||
b == PrefixSegFs || b == PrefixSegGs) {
pos += 1;
continue;
}
if (b == PrefixOperandSize) {
} else if (b == PrefixOperandSize) {
operandSizeOverride = true;
pos += 1;
continue;
} else if (b != PrefixLock && b != PrefixRep && b != PrefixAddressSize &&
b != PrefixSegCs && b != PrefixSegSs && b != PrefixSegDs &&
b != PrefixSegEs && b != PrefixSegFs && b != PrefixSegGs) {
break;
}
if (b == PrefixAddressSize) {
pos += 1;
continue;
}
break;
}
if (pos < available && data[pos] >= RexMin && data[pos] <= RexMax) {
rexPresent = true;
rex = data[pos];
rexPresent = false;
rex = 0;
pos += 1;
}
@@ -340,21 +329,24 @@ DecodedInstructionInfo X64InstructionDecoder::DecodeInstruction(
while (pos < info.Length) {
std::uint8_t b = data[pos];
if (b >= RexMin && b <= RexMax) {
info.RexPrefix = b;
++pos;
continue;
}
if (b == PrefixLock || b == PrefixRepne || b == PrefixRep ||
b == PrefixSegCs || b == PrefixSegSs || b == PrefixSegDs ||
b == PrefixSegEs || b == PrefixSegFs || b == PrefixSegGs ||
b == PrefixOperandSize || b == PrefixAddressSize) {
if (b >= PrefixSegFs && b <= PrefixSegGs)
info.SegmentPrefix = b;
info.RexPrefix = 0;
++pos;
continue;
}
break;
}
if (pos < info.Length && data[pos] >= RexMin && data[pos] <= RexMax)
info.RexPrefix = data[pos++];
info.OpcodeOffset = pos;
if (pos >= info.Length)
@@ -18,7 +18,8 @@ X64InstructionRewriter::ReferenceSite X64InstructionRewriter::ClassifyInstructio
while (pos < length) {
const std::uint8_t b = data[pos];
if (b == PrefixLock || b == PrefixRepne || b == PrefixRep ||
if ((b >= RexMin && b <= RexMax) ||
b == PrefixLock || b == PrefixRepne || b == PrefixRep ||
b == PrefixSegCs || b == PrefixSegSs || b == PrefixSegDs ||
b == PrefixSegEs || b == PrefixSegFs || b == PrefixSegGs ||
b == PrefixOperandSize || b == PrefixAddressSize) {
@@ -28,10 +29,6 @@ X64InstructionRewriter::ReferenceSite X64InstructionRewriter::ClassifyInstructio
break;
}
if (pos < length && data[pos] >= RexMin && data[pos] <= RexMax) {
pos += 1;
}
if (pos >= length) {
return {ReferenceKind::None, 0};
}
@@ -8,6 +8,7 @@
#include <codegen/x86/ClzeroLowering.hpp>
#include <codegen/x86/DecodedInstruction.hpp>
#include <codegen/x86/X64InstructionDecoder.hpp>
#include <codegen/x86/X64InstructionRewriter.hpp>
#include <codegen/IInstructionScanner.hpp>
#include <elfpatcher/general/EntryStubBuilder.hpp>
#include <elfpatcher/general/ProgramHeaderLayoutBuilder.hpp>
@@ -119,7 +120,9 @@ void decoderLengths() {
{0x66, 0x0F, 0xC4, 0xC0, 0x01}, {0xC2, 0x08, 0x00}, {0xC8, 0x10, 0x00, 0x00}, {0xF3, 0x0F, 0x2B, 0x07},
{0xF2, 0x44, 0x0F, 0x2B, 0x4C, 0x24, 0x10}, {0x0F, 0x01, 0xFA}, {0x0F, 0xB9, 0x00},
{0x41, 0x0F, 0xBB, 0xF7}, {0x0F, 0xBB, 0x47, 0x08},
{0x0F, 0x38, 0xCB, 0xCA}, {0x45, 0x0F, 0x38, 0xCC, 0xE1}, {0x0F, 0x38, 0xCD, 0x08}, {0x0F, 0x38, 0xCB, 0x0D, 0x10, 0x00, 0x00, 0x00}};
{0x0F, 0x38, 0xCB, 0xCA}, {0x45, 0x0F, 0x38, 0xCC, 0xE1}, {0x0F, 0x38, 0xCD, 0x08}, {0x0F, 0x38, 0xCB, 0x0D, 0x10, 0x00, 0x00, 0x00},
{0x48, 0x66, 0xB8, 0x34, 0x12}, {0x66, 0x48, 0xB8, 1, 2, 3, 4, 5, 6, 7, 8}, {0x41, 0x48, 0xB8, 1, 2, 3, 4, 5, 6, 7, 8},
{0x48, 0x64, 0x8B, 0x00}, {0x48, 0xF3, 0x0F, 0x2B, 0x00}, {0x48, 0x67, 0x0F, 0x01, 0xFC}, {0x48, 0x48, 0x0F, 0x01, 0xFC}};
Bytes padded;
for (const auto& instruction : instructions) {
padded = instruction;
@@ -127,6 +130,12 @@ void decoderLengths() {
require(decoder.Decode(padded.data(), padded.size()) == instruction.size(), "AMD-only or repaired two-byte opcode was decoded with the wrong length");
}
requireFailure([&] { const Bytes bare = {0x0F, 0x78, 0xC3, 0x08, 0x28}; (void)decoder.Decode(bare.data(), bare.size()); }, "0F 78 without an SSE4a prefix was accepted");
const Bytes strayRex = {0x48, 0x64, 0x8B, 0x00, 0x90};
const auto stray = decoder.DecodeInstruction(strayRex.data(), strayRex.size());
require(stray.Length == 4 && stray.OpcodeOffset == 2 && stray.RexPrefix == 0 && stray.SegmentPrefix == 0x64, "A REX before a legacy prefix was kept");
const Bytes lastRex = {0x41, 0x48, 0x8B, 0x00, 0x90};
const auto last = decoder.DecodeInstruction(lastRex.data(), lastRex.size());
require(last.Length == 4 && last.OpcodeOffset == 2 && last.RexPrefix == 0x48, "The REX before the opcode was not the one kept");
}
void sse4aOperands() {
@@ -144,6 +153,9 @@ void sse4aOperands() {
const Bytes registerForm = {0x66, 0x45, 0x0F, 0x79, 0xCA};
const auto decoded = Codegen::DecodeSse4a(registerForm.data(), registerForm.size());
require(decoded.RegisterForm && !decoded.Insertq && decoded.Destination == 9 && decoded.Source == 10, "Register form operands were decoded incorrectly");
const Bytes strayRex = {0x41, 0xF2, 0x0F, 0x79, 0xCA};
const auto ignored = Codegen::DecodeSse4a(strayRex.data(), strayRex.size());
require(ignored.RegisterForm && ignored.Insertq && ignored.Destination == 1 && ignored.Source == 2, "A REX before a legacy prefix was applied");
requireFailure([] { const Bytes bytes = {0x66, 0x0F, 0x78, 0xCB, 0x08, 0x28}; (void)Codegen::DecodeSse4a(bytes.data(), bytes.size()); }, "EXTRQ with a non-zero reg field was accepted");
requireFailure([] { const Bytes bytes = {0xF2, 0x0F, 0x78, 0x1B, 0x08, 0x08}; (void)Codegen::DecodeSse4a(bytes.data(), bytes.size()); }, "SSE4a memory operand was accepted");
requireFailure([] { const Bytes bytes = {0xF2, 0x0F, 0x78, 0xC8, 0x20, 0x30}; (void)Codegen::DecodeSse4a(bytes.data(), bytes.size()); }, "Field beyond bit 64 was accepted");
@@ -160,6 +172,8 @@ void sha256Operands() {
requireFailure([] { const Bytes bytes = {0x0F, 0x38, 0xCC, 0x08}; (void)Codegen::DecodeSha256(bytes.data(), bytes.size()); }, "SHA-256 memory operand was accepted");
requireFailure([] { const Bytes bytes = {0x66, 0x0F, 0x38, 0xCB, 0xCA}; (void)Codegen::DecodeSha256(bytes.data(), bytes.size()); }, "Prefixed 0F 38 CB was decoded as SHA-256");
requireFailure([] { const Bytes bytes = {0x0F, 0x38, 0xC9, 0xCA}; (void)Codegen::DecodeSha256(bytes.data(), bytes.size()); }, "SHA-1 was decoded as SHA-256");
check({0x41, 0x2E, 0x0F, 0x38, 0xCC, 0xCA}, Codegen::Sha256Operation::Msg1, 1, 2);
check({0x2E, 0x41, 0x0F, 0x38, 0xCC, 0xCA}, Codegen::Sha256Operation::Msg1, 1, 10);
const Bytes rounds = {0x0F, 0x38, 0xCB, 0xCA};
require(Codegen::DecodedInstruction{rounds.data(), rounds.size()}.IsShaNi(), "SHA256RNDS2 is not recognised as SHA-NI");
}
@@ -388,25 +402,40 @@ void converterClzero() {
require(failureOffset([&] { (void)converter->Convert(segmentRelative, {segmentHeader(text.size())}); }, "FS-relative CLZERO was accepted") == 0x20A, "CLZERO operand failure does not carry the file offset");
}
void converterSplitPrefixes() {
void converterStrayRex() {
const auto converter = Codegen::MakeAmd64OnlyConverter();
for (const Bytes& instruction : {Bytes{0x48, 0x64, 0x0F, 0x01, 0xFC}, Bytes{0x48, 0x67, 0x0F, 0x01, 0xFC}, Bytes{0x48, 0xF0, 0x0F, 0x01, 0xFC}, Bytes{0x48, 0xF0, 0x0F, 0x38, 0xCB, 0xCA}}) {
const auto convert = [&](const Bytes& text) {
Bytes file(0x300, 0xCC);
Bytes text = instruction;
text.insert(text.end(), {0x90, 0x90, 0xC3});
std::copy(text.begin(), text.end(), file.begin() + 0x200);
require(failureOffset([&] { (void)converter->Convert(file, {segmentHeader(text.size())}); }, "AMD-only instruction after a split REX and prefix was accepted") == 0x200, "Split prefix failure does not carry the file offset");
}
return std::pair{file, converter->Convert(file, {segmentHeader(text.size())})};
};
for (const Bytes& instruction : {Bytes{0x48, 0x64, 0x0F, 0x01, 0xFC, 0x90, 0x90, 0xC3}, Bytes{0x48, 0xF0, 0x0F, 0x01, 0xFC, 0x90, 0x90, 0xC3}})
require(failureOffset([&] { (void)convert(instruction); }, "CLZERO with a FS or LOCK prefix after a stray REX was accepted") == 0x200, "Stray REX failure does not carry the file offset");
const auto [addressFile, addressSize32] = convert({0x48, 0x67, 0x0F, 0x01, 0xFC, 0xC3});
require(addressSize32.Trampolines.size() == 1 && addressSize32.Trampolines[0].Length == 5 && addressSize32.Reports[0].InstructionName == "CLZERO", "67h CLZERO after a stray REX was not lowered as one instruction");
const auto [movntsFile, movnts] = convert({0x48, 0xF3, 0x0F, 0x2B, 0x00, 0xC3});
auto expected = movntsFile;
expected[0x203] = 0x11;
require(movnts.ReplacedCount == 1 && movnts.Reports[0].InstructionName == "MOVNTSS" && movnts.Bytes == expected, "MOVNTSS after a stray REX was not rewritten");
for (const Bytes& following : {Bytes{0x48, 0x64, 0x8B, 0x00}, Bytes{0x48, 0x67, 0x8B, 0x00}, Bytes{0x48, 0xF0, 0x01, 0x00}}) {
Bytes file(0x300, 0xCC);
Bytes text = {0x0F, 0x01, 0xFC};
text.insert(text.end(), following.begin(), following.end());
text.push_back(0xC3);
std::copy(text.begin(), text.end(), file.begin() + 0x200);
require(failureOffset([&] { (void)converter->Convert(file, {segmentHeader(text.size())}); }, "Split REX and prefix were moved into a stub") == 0x203, "Split prefix failure after a short site does not carry the file offset");
const auto [file, result] = convert(text);
require(result.Trampolines.size() == 1 && result.Trampolines[0].Length == 7, "Instruction with a stray REX was not absorbed whole");
const auto& body = result.Trampolines[0].Body;
const auto returnBranch = result.Trampolines[0].ReturnBranchOffset;
require(Bytes(body.begin() + static_cast<std::ptrdiff_t>(returnBranch - following.size()), body.begin() + static_cast<std::ptrdiff_t>(returnBranch)) == following, "Absorbed instruction lost its prefixes");
}
}
void rewriterStrayRex() {
const Bytes code = {0x48, 0x2E, 0xE9, 0x01, 0x00, 0x00, 0x00, 0x90, 0xC3};
const auto rewritten = Codegen::X64InstructionRewriter{}.Rewrite(code, {7, {0x66, 0x90}});
const Bytes expected = {0x48, 0x2E, 0xE9, 0x02, 0x00, 0x00, 0x00, 0x66, 0x90, 0xC3};
require(rewritten.Bytes == expected, "Branch with a stray REX was not adjusted by a length-changing rewrite");
}
void converterFailureOffsets() {
const auto converter = Codegen::MakeAmd64OnlyConverter();
const auto file = segmentFixture();
@@ -763,7 +792,8 @@ int main() {
converterSha256();
converterMonitorWait();
converterClzero();
converterSplitPrefixes();
converterStrayRex();
rewriterStrayRex();
converterFailureOffsets();
linuxPlacement();
scannerZeroTail();
-1
View File
@@ -37,7 +37,6 @@ Throughout the project, every function at every stage either **does exactly what
- [libSceJpegEnc](../../core/libs/prx/libSceJpegEnc/Export.cpp) encodes 4:2:2 sampling requests with 4:2:0 chroma subsampling, and grayscale requests as a 3-component JPEG with neutral chroma instead of a single-component one: the [JPEG encoder](../../core/Decoder/Jpeg/src/Jpeg.cpp) (stb) only produces 3-component 4:2:0 and 4:4:4 images.
- [Relinker](../../core/relinker/elfpatcher/src) doesn't add an icon to the generated executable. This should be done without adding dependencies (only standard).
- `--to-intel` does not lower RDPRU/MCOMMIT; the [matcher](../../core/relinker/codegen/src/x86/Amd64OnlyInstructionMatcher.cpp) fails the relink instead. The SHA-1 instructions of SHA-NI (SHA1RNDS4, SHA1NEXTE, SHA1MSG1, SHA1MSG2) are not substituted, and SHA-256 instructions with a memory operand fail the relink.
- The [instruction decoder](../../core/relinker/codegen/src/x86/X64InstructionDecoder.cpp) takes the byte after a REX prefix as the opcode, so a REX followed by a legacy or another REX prefix is split off as a separate instruction, while the CPU ignores that REX and applies the following prefixes to the next instruction. `--to-intel` fails the relink when such a fragment directly precedes an AMD-only instruction or would be moved into a stub. A split F2/F3 prefix that makes the next instruction MOVNTSS/MOVNTSD is not recognised: `48 F3 0F 2B 00` is scanned as `[48 F3][0F 2B 00]` and kept unchanged (split SSE4a forms already fail in the scanner).
- The length-changing path of the [instruction rewriter](../../core/relinker/codegen/src/x86/X64InstructionRewriter.cpp) is not used by the [converter](../../core/relinker/codegen/src/Amd64OnlyConverter.cpp): it does not adjust VEX/0F38/0F3A RIP-relative operands, data-to-code references (relocations, FDEs, jump tables) or segment sizes, so every substitution keeps the instruction length.
- The Linux placement of the `--to-intel` stubs in the [ELF patcher](../../core/relinker/elfpatcher/src/linux/LinuxElfPatcher.cpp) is covered only by a synthetic test.
- The libc [SSE4a trap emulation](../../core/libs/prx/libc/src/specifics/windows/Sse4aEmulation.hpp) on Windows is superseded by `--to-intel` and remains only until the relinked title has been verified without it.