diff --git a/core/relinker/CMakeLists.txt b/core/relinker/CMakeLists.txt index f3c4461a9..a01c7cd0e 100644 --- a/core/relinker/CMakeLists.txt +++ b/core/relinker/CMakeLists.txt @@ -40,6 +40,8 @@ add_executable(relinker ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/StubBodyBuilder.cpp ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/Sha256Operands.cpp ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/Sha256Lowering.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/Sha1Operands.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/Sha1Lowering.cpp ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/ClzeroOperands.cpp ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/ClzeroLowering.cpp ${CMAKE_CURRENT_SOURCE_DIR}/relinker/src/parsing/ElfReader.cpp @@ -104,6 +106,8 @@ if(WIN32) ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/StubBodyBuilder.cpp ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/Sha256Operands.cpp ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/Sha256Lowering.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/Sha1Operands.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/Sha1Lowering.cpp ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/ClzeroOperands.cpp ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/ClzeroLowering.cpp ) @@ -150,6 +154,8 @@ if(BUILD_TESTING) ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/StubBodyBuilder.cpp ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/Sha256Operands.cpp ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/Sha256Lowering.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/Sha1Operands.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/Sha1Lowering.cpp ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/ClzeroOperands.cpp ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/ClzeroLowering.cpp ${CMAKE_CURRENT_SOURCE_DIR}/elfpatcher/src/linux/LinuxElfPatcher.cpp diff --git a/core/relinker/codegen/include/codegen/x86/Amd64OnlySubstitutionTable.hpp b/core/relinker/codegen/include/codegen/x86/Amd64OnlySubstitutionTable.hpp index 2928c46af..b87b6a6bf 100644 --- a/core/relinker/codegen/include/codegen/x86/Amd64OnlySubstitutionTable.hpp +++ b/core/relinker/codegen/include/codegen/x86/Amd64OnlySubstitutionTable.hpp @@ -47,6 +47,10 @@ inline constexpr Entry kMovntsd = {"MOVNTSD", nullptr, 0}; inline constexpr Entry kSha256rnds2 = {"SHA256RNDS2", nullptr, 0}; inline constexpr Entry kSha256msg1 = {"SHA256MSG1", nullptr, 0}; inline constexpr Entry kSha256msg2 = {"SHA256MSG2", nullptr, 0}; +inline constexpr Entry kSha1rnds4 = {"SHA1RNDS4", nullptr, 0}; +inline constexpr Entry kSha1nexte = {"SHA1NEXTE", nullptr, 0}; +inline constexpr Entry kSha1msg1 = {"SHA1MSG1", nullptr, 0}; +inline constexpr Entry kSha1msg2 = {"SHA1MSG2", nullptr, 0}; inline constexpr std::uint8_t kMovsStoreOpcode = 0x11; inline constexpr std::uint8_t kPshufbZero = 0x80; diff --git a/core/relinker/codegen/include/codegen/x86/DecodedInstruction.hpp b/core/relinker/codegen/include/codegen/x86/DecodedInstruction.hpp index c8488e2dd..dc85cbcd4 100644 --- a/core/relinker/codegen/include/codegen/x86/DecodedInstruction.hpp +++ b/core/relinker/codegen/include/codegen/x86/DecodedInstruction.hpp @@ -13,6 +13,7 @@ struct DecodedInstruction { [[nodiscard]] std::size_t OpcodeOffset() const; [[nodiscard]] bool IsShaNi() const; [[nodiscard]] bool IsSha256() const; + [[nodiscard]] bool IsSha1() const; [[nodiscard]] bool IsExtrq() const; [[nodiscard]] bool IsInsertq() const; [[nodiscard]] bool IsMonitorx() const; diff --git a/core/relinker/codegen/include/codegen/x86/Sha1Lowering.hpp b/core/relinker/codegen/include/codegen/x86/Sha1Lowering.hpp new file mode 100644 index 000000000..1eabbd720 --- /dev/null +++ b/core/relinker/codegen/include/codegen/x86/Sha1Lowering.hpp @@ -0,0 +1,19 @@ +#ifndef CODEGEN_X86_SHA1LOWERING_HPP +#define CODEGEN_X86_SHA1LOWERING_HPP + +#include +#include +#include +#include + +namespace Codegen { + +class Sha1Lowering { +public: + void EmitOutOfLine(StubBodyBuilder& body, const Sha1Operands& operands) const; + [[nodiscard]] LoweredBody LowerOutOfLine(const Sha1Operands& operands, std::span trailing = {}) const; +}; + +} + +#endif diff --git a/core/relinker/codegen/include/codegen/x86/Sha1Operands.hpp b/core/relinker/codegen/include/codegen/x86/Sha1Operands.hpp new file mode 100644 index 000000000..6f00e1d92 --- /dev/null +++ b/core/relinker/codegen/include/codegen/x86/Sha1Operands.hpp @@ -0,0 +1,27 @@ +#ifndef CODEGEN_X86_SHA1OPERANDS_HPP +#define CODEGEN_X86_SHA1OPERANDS_HPP + +#include +#include + +namespace Codegen { + +enum class Sha1Operation : std::uint8_t { + Rnds4, + Nexte, + Msg1, + Msg2 +}; + +struct Sha1Operands { + Sha1Operation Operation; + std::uint8_t Destination; + std::uint8_t Source; + std::uint8_t Function; +}; + +[[nodiscard]] Sha1Operands DecodeSha1(const std::uint8_t* data, std::size_t length); + +} + +#endif diff --git a/core/relinker/codegen/src/x86/Amd64OnlyInstructionMatcher.cpp b/core/relinker/codegen/src/x86/Amd64OnlyInstructionMatcher.cpp index 273444fa8..a0732af9c 100644 --- a/core/relinker/codegen/src/x86/Amd64OnlyInstructionMatcher.cpp +++ b/core/relinker/codegen/src/x86/Amd64OnlyInstructionMatcher.cpp @@ -7,6 +7,8 @@ #include #include #include +#include +#include #include #include #include @@ -45,6 +47,20 @@ const Entry& _sha256Entry(const Sha256Operands& operands) { return kSha256rnds2; } +const Entry& _sha1Entry(const Sha1Operands& operands) { + switch (operands.Operation) { + case Sha1Operation::Rnds4: + return kSha1rnds4; + case Sha1Operation::Nexte: + return kSha1nexte; + case Sha1Operation::Msg1: + return kSha1msg1; + case Sha1Operation::Msg2: + return kSha1msg2; + } + return kSha1rnds4; +} + Amd64OnlyMatch _inPlace(const Entry& entry, const std::size_t length, std::vector replacement) { while (replacement.size() < length) { const auto& nop = kNops[std::min(length - replacement.size(), std::size(kNops)) - 1]; @@ -79,11 +95,13 @@ public: private: Sse4aLowering _lowering; Sha256Lowering _sha256Lowering; + Sha1Lowering _sha1Lowering; ClzeroLowering _clzeroLowering; [[nodiscard]] Amd64OnlyMatch _matchMovnts(const DecodedInstruction& instr, const Entry& entry) const; [[nodiscard]] Amd64OnlyMatch _matchSse4a(const DecodedInstruction& instr, const Entry& entry, const Entry& registerFormEntry, std::span trailing) const; [[nodiscard]] Amd64OnlyMatch _matchSha256(const DecodedInstruction& instr, std::span trailing) const; + [[nodiscard]] Amd64OnlyMatch _matchSha1(const DecodedInstruction& instr, std::span trailing) const; [[nodiscard]] Amd64OnlyMatch _matchClzero(const DecodedInstruction& instr, std::span trailing) const; }; @@ -117,6 +135,12 @@ Amd64OnlyMatch Amd64OnlyInstructionMatcher::_matchSha256(const DecodedInstructio return Amd64OnlyMatch{_sha256Entry(operands).Name, instr.Length, Amd64OnlyLowering::Trampoline, {}, std::move(body.Bytes), body.ReturnBranchOffset}; } +Amd64OnlyMatch Amd64OnlyInstructionMatcher::_matchSha1(const DecodedInstruction& instr, std::span trailing) const { + const auto operands = DecodeSha1(instr.Data, instr.Length); + auto body = _sha1Lowering.LowerOutOfLine(operands, trailing); + return Amd64OnlyMatch{_sha1Entry(operands).Name, instr.Length, Amd64OnlyLowering::Trampoline, {}, std::move(body.Bytes), body.ReturnBranchOffset}; +} + Amd64OnlyMatch Amd64OnlyInstructionMatcher::_matchClzero(const DecodedInstruction& instr, std::span trailing) const { auto body = _clzeroLowering.LowerOutOfLine(DecodeClzero(instr.Data, instr.Length), trailing); return Amd64OnlyMatch{kClzero.Name, instr.Length, Amd64OnlyLowering::Trampoline, {}, std::move(body.Bytes), body.ReturnBranchOffset}; @@ -142,6 +166,11 @@ std::optional Amd64OnlyInstructionMatcher::MatchSequence( if (name == nullptr) name = _sha256Entry(operands).Name; _sha256Lowering.EmitOutOfLine(body, operands); + } else if (instr.IsSha1()) { + const auto operands = DecodeSha1(instr.Data, instr.Length); + if (name == nullptr) + name = _sha1Entry(operands).Name; + _sha1Lowering.EmitOutOfLine(body, operands); } else if (instr.IsClzero()) { const auto operands = DecodeClzero(instr.Data, instr.Length); if (name == nullptr) @@ -178,6 +207,9 @@ std::optional Amd64OnlyInstructionMatcher::Match( if (instr.IsSha256()) return _matchSha256(instr, trailing); + if (instr.IsSha1()) + return _matchSha1(instr, trailing); + if (instr.IsMonitorx()) return _validWait(instr) ? _inPlace(kMonitorx, length, {}) : _unsupported(kMonitorx, length); diff --git a/core/relinker/codegen/src/x86/DecodedInstruction.cpp b/core/relinker/codegen/src/x86/DecodedInstruction.cpp index 1361d8a18..0c91e49ac 100644 --- a/core/relinker/codegen/src/x86/DecodedInstruction.cpp +++ b/core/relinker/codegen/src/x86/DecodedInstruction.cpp @@ -120,6 +120,27 @@ bool DecodedInstruction::IsSha256() const { return opcode == 0xCB || opcode == 0xCC || opcode == 0xCD; } +bool DecodedInstruction::IsSha1() const { + bool operandSizeOverride = false; + bool repnePrefix = false; + bool repPrefix = false; + const std::size_t pos = _skipPrefixesAndRex(&operandSizeOverride, &repnePrefix, &repPrefix); + + if (operandSizeOverride || repnePrefix || repPrefix) { + return false; + } + + if (pos + 2 >= Length || Data[pos] != TwoByteOpcodeEscape) { + return false; + } + + const std::uint8_t opcode = Data[pos + 2]; + if (Data[pos + 1] == ThreeByteEscape38) { + return opcode == 0xC8 || opcode == 0xC9 || opcode == 0xCA; + } + return Data[pos + 1] == ThreeByteEscape3A && opcode == 0xCC; +} + bool DecodedInstruction::IsExtrq() const { bool operandSizeOverride = false; bool repnePrefix = false; diff --git a/core/relinker/codegen/src/x86/Sha1Lowering.cpp b/core/relinker/codegen/src/x86/Sha1Lowering.cpp new file mode 100644 index 000000000..0c5253747 --- /dev/null +++ b/core/relinker/codegen/src/x86/Sha1Lowering.cpp @@ -0,0 +1,182 @@ +#include +#include + +namespace Codegen { + +namespace { + +constexpr std::uint8_t kPrefixPacked = 0x66; +constexpr std::uint8_t kShiftRightDwords = 2; +constexpr std::uint8_t kShiftLeftDwords = 6; +constexpr std::uint8_t kShiftRightBytes = 3; +constexpr std::uint8_t kShiftLeftBytes = 7; +constexpr std::uint8_t kWordBits = 32; +constexpr std::uint8_t kPunpckldq = 0x62; +constexpr std::uint8_t kPunpcklqdq = 0x6C; +constexpr std::uint8_t kMovdqa = 0x6F; +constexpr std::uint8_t kPshufd = 0x70; +constexpr std::uint8_t kShufpd = 0xC6; +constexpr std::uint8_t kPand = 0xDB; +constexpr std::uint8_t kPor = 0xEB; +constexpr std::uint8_t kPxor = 0xEF; +constexpr std::uint8_t kPaddd = 0xFE; +constexpr std::array kRoundConstants = {0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6}; + +template +std::array _scratch(const Sha1Operands& operands) { + std::array scratch{}; + for (std::uint8_t reg = 0, found = 0; found < TCount; ++reg) + if (reg != operands.Destination && reg != operands.Source) scratch[found++] = reg; + return scratch; +} + +void _op(StubBodyBuilder& body, const std::uint8_t opcode, const std::uint8_t dst, const std::uint8_t src) { + body.Sse(kPrefixPacked, {0x0F, opcode}, dst, src); +} + +void _lane(StubBodyBuilder& body, const std::uint8_t dst, const std::uint8_t src, const std::uint8_t lane) { + body.SseImm(kPrefixPacked, {0x0F, kPshufd}, dst, src, lane); +} + +void _rotate(StubBodyBuilder& body, const std::uint8_t reg, const std::uint8_t tmp, const std::uint8_t count) { + _op(body, kMovdqa, tmp, reg); + body.ShiftDwordImm(kShiftLeftDwords, tmp, count); + body.ShiftDwordImm(kShiftRightDwords, reg, static_cast(kWordBits - count)); + _op(body, kPor, reg, tmp); +} + +void _function(StubBodyBuilder& body, const std::uint8_t function, const std::uint8_t out, const std::uint8_t b, const std::uint8_t c, const std::uint8_t d, const std::uint8_t tmp) { + switch (function) { + case 0: + _op(body, kMovdqa, out, c); + _op(body, kPxor, out, d); + _op(body, kPand, out, b); + _op(body, kPxor, out, d); + return; + case 2: + _op(body, kMovdqa, out, b); + _op(body, kPand, out, c); + _op(body, kMovdqa, tmp, b); + _op(body, kPor, tmp, c); + _op(body, kPand, tmp, d); + _op(body, kPor, out, tmp); + return; + default: + _op(body, kMovdqa, out, b); + _op(body, kPxor, out, c); + _op(body, kPxor, out, d); + return; + } +} + +StubConstant _roundConstant(const std::uint8_t function) { + StubConstant constant{}; + for (std::size_t index = 0; index < constant.size(); ++index) + constant[index] = static_cast(kRoundConstants[function] >> ((index % 4) * 8)); + return constant; +} + +void _emitRounds(StubBodyBuilder& body, const Sha1Operands& operands) { + const auto scratch = _scratch<7>(operands); + std::array state = {scratch[0], scratch[1], scratch[2], scratch[3], scratch[4]}; + const auto t = scratch[5]; + const auto u = scratch[6]; + for (const auto reg : scratch) + body.Spill(reg); + for (std::uint8_t index = 0; index < 4; ++index) + _lane(body, state[index], operands.Destination, static_cast(3 - index)); + _op(body, kPxor, state[4], state[4]); + for (std::uint8_t round = 0; round < 4; ++round) { + const auto [a, b, c, d, e] = state; + _function(body, operands.Function, t, b, c, d, u); + _op(body, kPaddd, e, t); + _op(body, kMovdqa, t, a); + _rotate(body, t, u, 5); + _op(body, kPaddd, e, t); + _lane(body, t, operands.Source, static_cast(3 - round)); + _op(body, kPaddd, e, t); + body.RipOperand({0x0F, kPaddd}, e, _roundConstant(operands.Function)); + _rotate(body, b, u, 30); + state = {e, a, b, c, d}; + } + const auto [a, b, c, d, e] = state; + _op(body, kPunpckldq, d, c); + _op(body, kPunpckldq, b, a); + _op(body, kPunpcklqdq, d, b); + _op(body, kMovdqa, operands.Destination, d); + for (auto reg = scratch.rbegin(); reg != scratch.rend(); ++reg) + body.Restore(*reg); +} + +void _emitNext(StubBodyBuilder& body, const Sha1Operands& operands) { + const auto scratch = _scratch<2>(operands); + const auto rotated = scratch[0]; + const auto tmp = scratch[1]; + for (const auto reg : scratch) + body.Spill(reg); + _op(body, kMovdqa, rotated, operands.Destination); + _rotate(body, rotated, tmp, 30); + body.ShiftImm(kShiftRightBytes, rotated, 12); + body.ShiftImm(kShiftLeftBytes, rotated, 12); + _op(body, kMovdqa, operands.Destination, operands.Source); + _op(body, kPaddd, operands.Destination, rotated); + for (auto reg = scratch.rbegin(); reg != scratch.rend(); ++reg) + body.Restore(*reg); +} + +void _emitMessage1(StubBodyBuilder& body, const Sha1Operands& operands) { + const auto scratch = _scratch<1>(operands); + const auto words = scratch[0]; + body.Spill(words); + _op(body, kMovdqa, words, operands.Source); + body.SseImm(kPrefixPacked, {0x0F, kShufpd}, words, operands.Destination, 1); + _op(body, kPxor, operands.Destination, words); + body.Restore(words); +} + +void _emitMessage2(StubBodyBuilder& body, const Sha1Operands& operands) { + const auto dst = operands.Destination; + const auto scratch = _scratch<2>(operands); + const auto words = scratch[0]; + const auto tmp = scratch[1]; + for (const auto reg : scratch) + body.Spill(reg); + _op(body, kMovdqa, words, operands.Source); + body.ShiftImm(kShiftLeftBytes, words, 4); + _op(body, kPxor, dst, words); + _rotate(body, dst, tmp, 1); + _op(body, kMovdqa, words, dst); + body.ShiftImm(kShiftRightBytes, words, 12); + _rotate(body, words, tmp, 1); + _op(body, kPxor, dst, words); + for (auto reg = scratch.rbegin(); reg != scratch.rend(); ++reg) + body.Restore(*reg); +} + +} + +void Sha1Lowering::EmitOutOfLine(StubBodyBuilder& body, const Sha1Operands& operands) const { + switch (operands.Operation) { + case Sha1Operation::Rnds4: + _emitRounds(body, operands); + return; + case Sha1Operation::Nexte: + _emitNext(body, operands); + return; + case Sha1Operation::Msg1: + _emitMessage1(body, operands); + return; + case Sha1Operation::Msg2: + _emitMessage2(body, operands); + return; + } +} + +LoweredBody Sha1Lowering::LowerOutOfLine(const Sha1Operands& operands, std::span trailing) const { + StubBodyBuilder body; + EmitOutOfLine(body, operands); + body.Raw(trailing); + return body.Finish(); +} + +} diff --git a/core/relinker/codegen/src/x86/Sha1Operands.cpp b/core/relinker/codegen/src/x86/Sha1Operands.cpp new file mode 100644 index 000000000..ffcb25b82 --- /dev/null +++ b/core/relinker/codegen/src/x86/Sha1Operands.cpp @@ -0,0 +1,65 @@ +#include +#include +#include + +namespace Codegen { + +using namespace X64OpcodeConstants; + +Sha1Operands DecodeSha1(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-1 instruction"); + } + if (b != PrefixLock && b != PrefixAddressSize && + b != PrefixSegCs && b != PrefixSegSs && b != PrefixSegDs && + b != PrefixSegEs && b != PrefixSegFs && b != PrefixSegGs) { + break; + } + rex = 0; + pos += 1; + } + + if (pos + 4 > length || data[pos] != TwoByteOpcodeEscape) { + throw CodegenException("Not a SHA-1 instruction"); + } + + Sha1Operands operands{}; + if (data[pos + 1] == ThreeByteEscape3A && data[pos + 2] == 0xCC) { + operands.Operation = Sha1Operation::Rnds4; + } else if (data[pos + 1] == ThreeByteEscape38 && data[pos + 2] == 0xC8) { + operands.Operation = Sha1Operation::Nexte; + } else if (data[pos + 1] == ThreeByteEscape38 && data[pos + 2] == 0xC9) { + operands.Operation = Sha1Operation::Msg1; + } else if (data[pos + 1] == ThreeByteEscape38 && data[pos + 2] == 0xCA) { + operands.Operation = Sha1Operation::Msg2; + } else { + throw CodegenException("Not a SHA-1 instruction"); + } + + const std::uint8_t modrm = data[pos + 3]; + if (((modrm >> ModRmModShift) & ModRmModMask) != ModRmModRegister) { + throw CodegenException("SHA-1 instruction with a memory operand"); + } + if (operands.Operation == Sha1Operation::Rnds4) { + if (pos + 5 > length) { + throw CodegenException("SHA1RNDS4 truncated before its immediate"); + } + operands.Function = static_cast(data[pos + 4] & 3); + } + + operands.Destination = static_cast(((modrm >> ModRmRegShift) & ModRmRegMask) | (((rex & 0x4) != 0) ? 8 : 0)); + operands.Source = static_cast((modrm & ModRmRmMask) | (((rex & 0x1) != 0) ? 8 : 0)); + return operands; +} + +} diff --git a/core/relinker/codegen/tests/Amd64OnlyConverterTests.cpp b/core/relinker/codegen/tests/Amd64OnlyConverterTests.cpp index 5e1442dd3..92590fa0b 100644 --- a/core/relinker/codegen/tests/Amd64OnlyConverterTests.cpp +++ b/core/relinker/codegen/tests/Amd64OnlyConverterTests.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -122,6 +123,7 @@ void decoderLengths() { {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, 0x3A, 0xCC, 0xD5, 0x03}, {0x45, 0x0F, 0x3A, 0xCC, 0xE1, 0x00}, {0x0F, 0x3A, 0xCC, 0x08, 0x01}, {0x0F, 0x38, 0xC8, 0xCA}, {0x0F, 0x38, 0xC9, 0xCA}, {0x0F, 0x38, 0xCA, 0x08}, {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; @@ -198,6 +200,25 @@ void sha256Operands() { require(Codegen::DecodedInstruction{rounds.data(), rounds.size()}.IsShaNi(), "SHA256RNDS2 is not recognised as SHA-NI"); } +void sha1Operands() { + const auto check = [](const Bytes& site, const Codegen::Sha1Operation operation, const int dst, const int src, const int function) { + const auto operands = Codegen::DecodeSha1(site.data(), site.size()); + require(operands.Operation == operation && operands.Destination == dst && operands.Source == src && operands.Function == function, "SHA-1 operands were decoded incorrectly"); + }; + check({0x0F, 0x3A, 0xCC, 0xCA, 0x02}, Codegen::Sha1Operation::Rnds4, 1, 2, 2); + check({0x45, 0x0F, 0x3A, 0xCC, 0xE1, 0xFF}, Codegen::Sha1Operation::Rnds4, 12, 9, 3); + check({0x44, 0x0F, 0x38, 0xC8, 0xC0}, Codegen::Sha1Operation::Nexte, 8, 0, 0); + check({0x0F, 0x38, 0xC9, 0xD5}, Codegen::Sha1Operation::Msg1, 2, 5, 0); + check({0x2E, 0x41, 0x0F, 0x38, 0xCA, 0xCA}, Codegen::Sha1Operation::Msg2, 1, 10, 0); + requireFailure([] { const Bytes bytes = {0x0F, 0x38, 0xC9, 0x08}; (void)Codegen::DecodeSha1(bytes.data(), bytes.size()); }, "SHA-1 memory operand was accepted"); + requireFailure([] { const Bytes bytes = {0x0F, 0x3A, 0xCC, 0x08, 0x00}; (void)Codegen::DecodeSha1(bytes.data(), bytes.size()); }, "SHA1RNDS4 memory operand was accepted"); + requireFailure([] { const Bytes bytes = {0x0F, 0x3A, 0xCC, 0xCA}; (void)Codegen::DecodeSha1(bytes.data(), bytes.size()); }, "SHA1RNDS4 without its immediate was accepted"); + requireFailure([] { const Bytes bytes = {0x66, 0x0F, 0x38, 0xC8, 0xCA}; (void)Codegen::DecodeSha1(bytes.data(), bytes.size()); }, "Prefixed 0F 38 C8 was decoded as SHA-1"); + requireFailure([] { const Bytes bytes = {0x0F, 0x38, 0xCC, 0xCA}; (void)Codegen::DecodeSha1(bytes.data(), bytes.size()); }, "SHA-256 was decoded as SHA-1"); + const Bytes prefixedRounds = {0x66, 0x0F, 0x3A, 0xCC, 0xCA, 0x00}; + require(!Codegen::DecodedInstruction{prefixedRounds.data(), prefixedRounds.size()}.IsSha1(), "66-prefixed 0F 3A CC was recognised as SHA-1"); +} + void clzeroOperands() { const auto decode = [](const Bytes& bytes) { return Codegen::DecodeClzero(bytes.data(), bytes.size()); }; require(!decode({0x0F, 0x01, 0xFC}).AddressSize32 && decode({0x67, 0x0F, 0x01, 0xFC}).AddressSize32, "CLZERO address size was decoded incorrectly"); @@ -257,7 +278,10 @@ void matcherSubstitutions() { const auto sha256 = match(bytes); require(sha256 && sha256->Lowering == Codegen::Amd64OnlyLowering::Trampoline && sha256->InstructionName == name, "SHA-256 instruction was not lowered through a stub"); } - require(!match({0x0F, 0x38, 0xC9, 0xCA}), "SHA-1 instruction was matched"); + for (const auto& [bytes, name] : {std::pair{Bytes{0x0F, 0x3A, 0xCC, 0xCA, 0x01}, "SHA1RNDS4"}, {Bytes{0x0F, 0x38, 0xC8, 0xCA}, "SHA1NEXTE"}, {Bytes{0x0F, 0x38, 0xC9, 0xCA}, "SHA1MSG1"}, {Bytes{0x45, 0x0F, 0x38, 0xCA, 0xE1}, "SHA1MSG2"}}) { + const auto sha1 = match(bytes); + require(sha1 && sha1->Lowering == Codegen::Amd64OnlyLowering::Trampoline && sha1->InstructionName == name, "SHA-1 instruction was not lowered through a stub"); + } const auto stub = match(kInsertqHighSite); require(stub && stub->Lowering == Codegen::Amd64OnlyLowering::Trampoline && stub->StubBody == kInsertqHighBody && stub->ReturnBranchOffset == 15 && stub->InstructionName == "INSERTQ", "INSERTQ was not lowered through a stub"); const auto topAligned = match({0x66, 0x0F, 0x78, 0xC3, 0x18, 0x28}); @@ -402,6 +426,33 @@ void converterSha256() { require(failureOffset([&] { (void)converter->Convert(memoryForm, {segmentHeader(text.size())}); }, "SHA-256 memory form was accepted") == 0x20C, "SHA-256 operand failure does not carry the file offset"); } +void converterSha1() { + const auto converter = Codegen::MakeAmd64OnlyConverter(); + Bytes file(0x300, 0xCC); + const Bytes text = { + 0x0F, 0x3A, 0xCC, 0xCA, 0x00, + 0x0F, 0x38, 0xC8, 0xD3, + 0x0F, 0x38, 0xC9, 0xE5, + 0x66, 0x0F, 0xFE, 0xC1, + 0x0F, 0x38, 0xCA, 0xE5, + 0x90, + 0xC3}; + std::copy(text.begin(), text.end(), file.begin() + 0x200); + const auto result = converter->Convert(file, {segmentHeader(text.size())}); + require(result.Trampolines.size() == 3 && result.Reports.size() == 3 && result.Bytes == file, "SHA-1 sites were not lowered through stubs"); + require(result.Trampolines[0].Offset == 0x200 && result.Trampolines[0].Length == 5 && result.Reports[0].InstructionName == "SHA1RNDS4", "SHA1RNDS4 was not lowered as one site"); + require(result.Trampolines[1].Offset == 0x205 && result.Trampolines[1].Length == 8 && result.Reports[1].InstructionName == "SHA1NEXTE", "SHA1NEXTE did not absorb the following SHA1MSG1"); + const auto& message = result.Trampolines[2]; + require(message.Offset == 0x211 && message.Length == 5 && result.Reports[2].InstructionName == "SHA1MSG2", "SHA1MSG2 did not absorb the following instruction"); + require(message.Body[message.ReturnBranchOffset - 1] == 0x90 && message.Body[message.ReturnBranchOffset] == 0xE9, "Absorbed instruction does not run before the return jump"); + auto beforeReturn = file; + beforeReturn[0x215] = 0xC3; + requireFailure([&] { (void)converter->Convert(beforeReturn, {segmentHeader(text.size())}); }, "Short SHA-1 instruction followed by a return was relocated"); + auto memoryForm = file; + memoryForm[0x214] = 0x28; + require(failureOffset([&] { (void)converter->Convert(memoryForm, {segmentHeader(text.size())}); }, "SHA-1 memory form was accepted") == 0x211, "SHA-1 operand failure does not carry the file offset"); +} + void converterMonitorWait() { const auto converter = Codegen::MakeAmd64OnlyConverter(); Bytes file(0x300, 0xCC); @@ -709,15 +760,15 @@ void sha256Execution() { } } -struct ClzeroRun { +struct StubRun { std::uint64_t Rax; std::uint64_t Rcx; std::uint64_t Flags; std::uint64_t Xmm[16][2]; }; -ClzeroRun runClzeroBody(const Codegen::Amd64OnlyMatch& match, const std::uint64_t rax, const std::uint64_t (&xmmIn)[16][2]) { - require(match.Lowering == Codegen::Amd64OnlyLowering::Trampoline, "CLZERO stub was not produced"); +StubRun runStubBody(const Codegen::Amd64OnlyMatch& match, const std::uint64_t rax, const std::uint64_t (&xmmIn)[16][2]) { + require(match.Lowering == Codegen::Amd64OnlyLowering::Trampoline, "Stub was not produced"); auto body = match.StubBody; const auto ret = body.size(); body.push_back(0xC3); @@ -726,7 +777,7 @@ ClzeroRun runClzeroBody(const Codegen::Amd64OnlyMatch& match, const std::uint64_ void* code = mmap(nullptr, 4096, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); require(code != MAP_FAILED, "cannot map executable memory for the stub"); std::memcpy(code, body.data(), body.size()); - ClzeroRun run{}; + StubRun run{}; asm volatile( "movdqu 0x00(%[xmmIn]), %%xmm0\n\t" "movdqu 0x10(%[xmmIn]), %%xmm1\n\t" @@ -808,7 +859,7 @@ void clzeroExecution() { for (const std::size_t offset : {std::size_t{0x80}, std::size_t{0xAD}, std::size_t{0xFF}}) { std::memset(buffer, 0xA5, 4096); const auto address = reinterpret_cast(buffer + offset); - const auto run = runClzeroBody(*item.Match, address | item.Junk, xmmIn); + const auto run = runStubBody(*item.Match, address | item.Junk, xmmIn); const auto line = offset & ~std::size_t{63}; for (std::size_t index = 0; index < 4096; ++index) require(buffer[index] == (index >= line && index < line + 64 ? 0x00 : 0xA5), "CLZERO stub did not clear exactly the addressed line"); @@ -821,8 +872,75 @@ void clzeroExecution() { munmap(buffer, 4096); } } + +std::uint32_t rotl(const std::uint32_t value, const unsigned count) { + return (value << count) | (value >> (32 - count)); +} + +std::array sha1Reference(const Codegen::Sha1Operands& operands, const std::uint32_t (&x)[4], const std::uint32_t (&y)[4]) { + switch (operands.Operation) { + case Codegen::Sha1Operation::Nexte: + return {y[0], y[1], y[2], y[3] + rotl(x[3], 30)}; + case Codegen::Sha1Operation::Msg1: + return {x[0] ^ y[2], x[1] ^ y[3], x[2] ^ x[0], x[3] ^ x[1]}; + case Codegen::Sha1Operation::Msg2: { + const auto w16 = rotl(x[3] ^ y[2], 1); + return {rotl(x[0] ^ w16, 1), rotl(x[1] ^ y[0], 1), rotl(x[2] ^ y[1], 1), w16}; + } + case Codegen::Sha1Operation::Rnds4: + break; + } + constexpr std::uint32_t keys[4] = {0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6}; + std::uint32_t a = x[3], b = x[2], c = x[1], d = x[0], e = 0; + for (int round = 0; round < 4; ++round) { + std::uint32_t f = b ^ c ^ d; + if (operands.Function == 0) f = (b & c) ^ (~b & d); + if (operands.Function == 2) f = (b & c) ^ (b & d) ^ (c & d); + const auto next = f + rotl(a, 5) + y[3 - round] + e + keys[operands.Function]; + e = d; d = c; c = rotl(b, 30); b = a; a = next; + } + return {d, c, b, a}; +} + +void sha1Execution() { + const auto matcher = Codegen::MakeAmd64OnlyInstructionMatcher(); + std::uint64_t seed = 0x9e3779b97f4a7c15ull; + const auto random = [&] { seed ^= seed << 13; seed ^= seed >> 7; seed ^= seed << 17; return seed; }; + const std::vector sites = { + {0x0F, 0x3A, 0xCC, 0xD5, 0x00}, {0x0F, 0x3A, 0xCC, 0xD5, 0x01}, {0x0F, 0x3A, 0xCC, 0xD5, 0x02}, {0x0F, 0x3A, 0xCC, 0xD5, 0xFF}, + {0x0F, 0x3A, 0xCC, 0xD2, 0x02}, {0x45, 0x0F, 0x3A, 0xCC, 0xCE, 0x00}, {0x41, 0x0F, 0x3A, 0xCC, 0xC0, 0x01}, + {0x0F, 0x38, 0xC8, 0xD5}, {0x0F, 0x38, 0xC8, 0xD2}, {0x44, 0x0F, 0x38, 0xC8, 0xC7}, + {0x0F, 0x38, 0xC9, 0xD5}, {0x0F, 0x38, 0xC9, 0xD2}, {0x41, 0x0F, 0x38, 0xC9, 0xC7}, + {0x0F, 0x38, 0xCA, 0xD5}, {0x0F, 0x38, 0xCA, 0xD2}, {0x45, 0x0F, 0x38, 0xCA, 0xFF}}; + for (const auto& site : sites) { + const auto operands = Codegen::DecodeSha1(site.data(), site.size()); + const auto match = matcher->Match(site.data(), site.size()); + require(match.has_value(), "SHA-1 stub was not produced"); + for (int sample = 0; sample < 64; ++sample) { + std::uint64_t xmmIn[16][2]; + for (auto& reg : xmmIn) { + reg[0] = random(); + reg[1] = random(); + } + std::uint32_t x[4]; + std::uint32_t y[4]; + std::memcpy(x, xmmIn[operands.Destination], sizeof(x)); + std::memcpy(y, xmmIn[operands.Source], sizeof(y)); + const auto expected = sha1Reference(operands, x, y); + const auto run = runStubBody(*match, 0x5A5A5A5A5A5A5A5Aull, xmmIn); + for (unsigned reg = 0; reg < 16; ++reg) { + if (reg == operands.Destination) + require(std::memcmp(run.Xmm[reg], expected.data(), 16) == 0, "SHA-1 stub computed the wrong result"); + else + require(run.Xmm[reg][0] == xmmIn[reg][0] && run.Xmm[reg][1] == xmmIn[reg][1], "SHA-1 stub clobbered an xmm register"); + } + require(run.Rax == 0x5A5A5A5A5A5A5A5Aull && run.Rcx == 0x1122334455667788ull && (run.Flags & 0x8D5) == (0x8D7 & 0x8D5), "SHA-1 stub changed a general register or RFLAGS"); + } + } +} #else void registerFormExecution() {} +void sha1Execution() {} void sha256Execution() {} void clzeroExecution() {} void immediateFormExecution() {} @@ -842,16 +960,19 @@ int main() { decoderRipRelative(); sse4aOperands(); sha256Operands(); + sha1Operands(); clzeroOperands(); matcherSubstitutions(); goldenBodies(); registerFormExecution(); immediateFormExecution(); sha256Execution(); + sha1Execution(); clzeroExecution(); converterSegment(); converterRipRelativeFollower(); converterSha256(); + converterSha1(); converterMonitorWait(); converterClzero(); converterStrayRex(); diff --git a/docs/dev/TechnicalDebt.md b/docs/dev/TechnicalDebt.md index fa678defe..7b044a5a4 100644 --- a/docs/dev/TechnicalDebt.md +++ b/docs/dev/TechnicalDebt.md @@ -55,7 +55,7 @@ Throughout the project, every function at every stage either **does exactly what - The executable file that [relinker](../../core/relinker/elfpatcher/src/windows/WindowsPeWriter.cpp) generates opens the console when launched, which is inconvenient for playability. - [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. +- `--to-intel` does not lower RDPRU/MCOMMIT; the [matcher](../../core/relinker/codegen/src/x86/Amd64OnlyInstructionMatcher.cpp) fails the relink instead. SHA-1 and SHA-256 instructions with a memory operand fail the relink. - 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.