From 2cf5e510299744ae59d8910237d01acfa9352c5d Mon Sep 17 00:00:00 2001 From: momgaro ganuchi Date: Sat, 21 Nov 2026 13:09:56 +0300 Subject: [PATCH 1/5] feat(relinker): record the host CPU features --to-avx output needs Linux and Windows output now carries a 16-byte AnyPS5 record (magic and an eight-byte mask) in a PT_OS_HOSTCPU program header or a .hostcpu PE section. The classifier maps every kept instruction to LZCNT, BMI1, BMI2, MOVBE, AVX2, FMA or F16C, the converter unions the mask for the executable and every bundled module converted in the same run, and libkernel requires the baseline plus the recorded bits, keeping the old all-extensions check when no record is present. This lets --to-avx output start on a host with AVX but without AVX2, so the option no longer requires --macos. A retained extension the lowering does not cover is recorded and refuses start-up instead of raising an illegal instruction later. The classifier is conservative: a 256-bit VEX opcode outside the AVX1 list counts as AVX2, and every byte of an executable segment is decoded. Unit tests cover the classifier, the converter mask and the recorded-mask checks in libkernel; an end-to-end test converts a fixture with --to-avx and validates both output records. --- .../libs/prx/libc/include/ApplicationHeap.hpp | 3 + .../libs/prx/libc/include/HostCpuFeatures.hpp | 22 +++ .../libc/src/ApplicationProcessParameters.cpp | 106 ++++++++++-- .../prx/libkernel/System/include/HostCpu.hpp | 7 +- .../libs/prx/libkernel/System/src/HostCpu.cpp | 96 ++++++----- core/libs/tests/HostCpu.cpp | 34 ++++ core/relinker/CMakeLists.txt | 16 +- core/relinker/cli/src/CliArgs.cpp | 5 +- core/relinker/cli/tests/CliArgsTests.cpp | 6 +- .../codegen/include/codegen/CodegenTypes.hpp | 1 + .../codegen/x86/HostCpuFeatureClassifier.hpp | 13 ++ .../codegen/src/Amd64OnlyConverter.cpp | 16 ++ .../src/x86/HostCpuFeatureClassifier.cpp | 162 ++++++++++++++++++ .../codegen/tests/Amd64OnlyConverterTests.cpp | 17 ++ .../tests/HostCpuFeatureClassifierTests.cpp | 105 ++++++++++++ .../elfpatcher/general/ElfConstants.hpp | 1 + .../elfpatcher/general/IElfPatcher.hpp | 4 +- .../general/ProgramHeaderLayoutRequest.hpp | 2 + .../elfpatcher/linux/LinuxElfPatcher.hpp | 3 +- .../elfpatcher/macos/MacOsMachOPatcher.hpp | 3 +- .../elfpatcher/windows/WindowsElfPatcher.hpp | 2 +- .../general/ProgramHeaderLayoutBuilder.cpp | 24 ++- .../elfpatcher/src/linux/LinuxElfPatcher.cpp | 20 ++- .../src/macos/MacOsMachOPatcher.cpp | 2 +- .../src/windows/WindowsPePatcher.cpp | 10 +- .../include/relinker/guest/GuestImage.hpp | 7 +- .../relinker/src/guest/GuestModuleBuilder.cpp | 6 +- .../relinker/src/pipeline/Conversion.cpp | 11 +- .../relinker/tests/test_hostcpu_record.py | 82 +++++++++ .../changes/feat-relinker-to-avx-host-cpu.md | 9 + docs/user/USAGE.md | 2 +- 31 files changed, 715 insertions(+), 82 deletions(-) create mode 100644 core/libs/prx/libc/include/HostCpuFeatures.hpp create mode 100644 core/relinker/codegen/include/codegen/x86/HostCpuFeatureClassifier.hpp create mode 100644 core/relinker/codegen/src/x86/HostCpuFeatureClassifier.cpp create mode 100644 core/relinker/codegen/tests/HostCpuFeatureClassifierTests.cpp create mode 100644 core/relinker/relinker/tests/test_hostcpu_record.py create mode 100644 docs/dev/debt/changes/feat-relinker-to-avx-host-cpu.md diff --git a/core/libs/prx/libc/include/ApplicationHeap.hpp b/core/libs/prx/libc/include/ApplicationHeap.hpp index cef34a2b319b..e383db087c61 100644 --- a/core/libs/prx/libc/include/ApplicationHeap.hpp +++ b/core/libs/prx/libc/include/ApplicationHeap.hpp @@ -2,11 +2,14 @@ #define CORE_LIBS_PRX_LIBC_INCLUDE_APPLICATIONHEAP_HPP #include +#include +#include extern "C" { const void* ApplicationProcessParameters_nid_no_patch(); const void* ApplicationEmptyProcessParameters_nid_no_patch(); +std::optional ApplicationHostCpuFeatures_nid_no_patch(); bool ApplicationGuestHeapApi_nid_no_patch(void** api); void ApplicationHeapInitialize_nid_no_patch(const void* processParameters); void ApplicationHeapEnsureInitialized_nid_no_patch(); diff --git a/core/libs/prx/libc/include/HostCpuFeatures.hpp b/core/libs/prx/libc/include/HostCpuFeatures.hpp new file mode 100644 index 000000000000..8031b4befc5f --- /dev/null +++ b/core/libs/prx/libc/include/HostCpuFeatures.hpp @@ -0,0 +1,22 @@ +#ifndef CORE_LIBS_PRX_LIBC_INCLUDE_HOSTCPUFEATURES_HPP +#define CORE_LIBS_PRX_LIBC_INCLUDE_HOSTCPUFEATURES_HPP + +#include + +namespace HostCpuFeatureBits { + +inline constexpr std::uint64_t Lzcnt = 1ull << 0u; +inline constexpr std::uint64_t Bmi1 = 1ull << 1u; +inline constexpr std::uint64_t Bmi2 = 1ull << 2u; +inline constexpr std::uint64_t Movbe = 1ull << 3u; +inline constexpr std::uint64_t Avx2 = 1ull << 4u; +inline constexpr std::uint64_t Fma = 1ull << 5u; +inline constexpr std::uint64_t F16c = 1ull << 6u; +inline constexpr std::uint64_t All = Lzcnt | Bmi1 | Bmi2 | Movbe | Avx2 | Fma | F16c; + +inline constexpr std::uint64_t RecordMagic = 0x3150434835535041ull; +inline constexpr std::uint64_t RecordSize = 16; + +} + +#endif diff --git a/core/libs/prx/libc/src/ApplicationProcessParameters.cpp b/core/libs/prx/libc/src/ApplicationProcessParameters.cpp index ed5f1fb309f4..ae52f5e14ef1 100644 --- a/core/libs/prx/libc/src/ApplicationProcessParameters.cpp +++ b/core/libs/prx/libc/src/ApplicationProcessParameters.cpp @@ -1,7 +1,9 @@ #include "prx/libc/include/ApplicationHeap.hpp" +#include "prx/libc/include/HostCpuFeatures.hpp" #include #include #include +#include #include #include @@ -15,6 +17,28 @@ #include #endif +#ifdef _WIN32 +namespace { + +struct WindowsImage { + const std::byte* Bytes; + const IMAGE_NT_HEADERS64* Nt; +}; + +WindowsImage ReadWindowsImage() { + const auto* bytes = reinterpret_cast(GetModuleHandleW(nullptr)); + if (bytes == nullptr) throw std::runtime_error("application heap: main image is unavailable"); + const auto* dos = reinterpret_cast(bytes); + if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew < 0) throw std::runtime_error("application heap: invalid DOS header"); + const auto* nt = reinterpret_cast(bytes + dos->e_lfanew); + if (nt->Signature != IMAGE_NT_SIGNATURE || nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) throw std::runtime_error("application heap: invalid PE header"); + return {bytes, nt}; +} + +} + +#endif + bool ApplicationGuestHeapApi_nid_no_patch(void** api) { #ifdef __linux__ static const auto guest = [] { @@ -59,17 +83,12 @@ const void* ApplicationEmptyProcessParameters_nid_no_patch() { const void* ApplicationProcessParameters_nid_no_patch() { #ifdef _WIN32 - const auto* image = reinterpret_cast(GetModuleHandleW(nullptr)); - if (image == nullptr) throw std::runtime_error("application heap: main image is unavailable"); - const auto* dos = reinterpret_cast(image); - if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew < 0) throw std::runtime_error("application heap: invalid DOS header"); - const auto* nt = reinterpret_cast(image + dos->e_lfanew); - if (nt->Signature != IMAGE_NT_SIGNATURE || nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) throw std::runtime_error("application heap: invalid PE header"); - const auto* sections = IMAGE_FIRST_SECTION(nt); - const auto imageSize = nt->OptionalHeader.SizeOfImage; + const auto image = ReadWindowsImage(); + const auto* sections = IMAGE_FIRST_SECTION(image.Nt); + const auto imageSize = image.Nt->OptionalHeader.SizeOfImage; const void* result = nullptr; bool found = false; - for (unsigned index = 0; index < nt->FileHeader.NumberOfSections; ++index) { + for (unsigned index = 0; index < image.Nt->FileHeader.NumberOfSections; ++index) { const auto& section = sections[index]; if (std::memcmp(section.Name, ".procpar", 8) != 0) continue; if (found) throw std::runtime_error("application heap: duplicate process metadata"); @@ -77,14 +96,14 @@ const void* ApplicationProcessParameters_nid_no_patch() { if (section.Misc.VirtualSize != 8 || section.VirtualAddress > imageSize || 8 > imageSize - section.VirtualAddress) throw std::runtime_error("application heap: invalid process metadata section"); std::uint32_t address; std::uint32_t size; - std::memcpy(&address, image + section.VirtualAddress, sizeof(address)); - std::memcpy(&size, image + section.VirtualAddress + 4, sizeof(size)); + std::memcpy(&address, image.Bytes + section.VirtualAddress, sizeof(address)); + std::memcpy(&size, image.Bytes + section.VirtualAddress + 4, sizeof(size)); if (address == 0 && size == 0) { result = ApplicationEmptyProcessParameters_nid_no_patch(); continue; } if (size < 0x40 || address > imageSize || size > imageSize - address) throw std::runtime_error("application heap: process parameters exceed the image"); - result = image + address; + result = image.Bytes + address; } if (!found) throw std::runtime_error("application heap: process metadata is missing; relink the executable"); return result; @@ -122,3 +141,66 @@ const void* ApplicationProcessParameters_nid_no_patch() { throw std::runtime_error("application heap: unsupported executable format"); #endif } + +std::optional ApplicationHostCpuFeatures_nid_no_patch() { +#ifdef _WIN32 + const auto image = ReadWindowsImage(); + const auto* sections = IMAGE_FIRST_SECTION(image.Nt); + const auto imageSize = image.Nt->OptionalHeader.SizeOfImage; + std::optional result; + for (unsigned index = 0; index < image.Nt->FileHeader.NumberOfSections; ++index) { + const auto& section = sections[index]; + if (std::memcmp(section.Name, ".hostcpu", 8) != 0) continue; + if (result || section.Misc.VirtualSize != HostCpuFeatureBits::RecordSize || section.VirtualAddress > imageSize || HostCpuFeatureBits::RecordSize > imageSize - section.VirtualAddress) + throw std::runtime_error("application heap: invalid host CPU record section"); + std::uint64_t magic; + std::uint64_t features; + std::memcpy(&magic, image.Bytes + section.VirtualAddress, sizeof(magic)); + std::memcpy(&features, image.Bytes + section.VirtualAddress + 8, sizeof(features)); + if (magic != HostCpuFeatureBits::RecordMagic || (features & ~HostCpuFeatureBits::All) != 0) + throw std::runtime_error("application heap: invalid host CPU record"); + result = features; + } + return result; +#elif defined(__linux__) || defined(__APPLE__) || defined(__EMSCRIPTEN__) + struct Search { + std::optional features; + bool invalid = false; + } search; + dl_iterate_phdr([](dl_phdr_info* image, std::size_t, void* data) { + auto& result = *static_cast(data); + if (image->dlpi_name != nullptr && image->dlpi_name[0] != '\0') return 0; + for (std::uint16_t index = 0; index < image->dlpi_phnum; ++index) { + const auto& header = image->dlpi_phdr[index]; + if (header.p_type != 0x61000002) continue; + if (result.features || header.p_filesz != HostCpuFeatureBits::RecordSize) { + result.invalid = true; + return 1; + } + bool mapped = false; + for (std::uint16_t loadIndex = 0; loadIndex < image->dlpi_phnum; ++loadIndex) { + const auto& load = image->dlpi_phdr[loadIndex]; + if (load.p_type == PT_LOAD && header.p_vaddr >= load.p_vaddr && header.p_vaddr - load.p_vaddr <= load.p_memsz && header.p_filesz <= load.p_memsz - (header.p_vaddr - load.p_vaddr)) mapped = true; + } + if (!mapped) { + result.invalid = true; + return 1; + } + std::uint64_t magic; + std::uint64_t features; + std::memcpy(&magic, reinterpret_cast(image->dlpi_addr + header.p_vaddr), sizeof(magic)); + std::memcpy(&features, reinterpret_cast(image->dlpi_addr + header.p_vaddr + 8), sizeof(features)); + if (magic != HostCpuFeatureBits::RecordMagic || (features & ~HostCpuFeatureBits::All) != 0) { + result.invalid = true; + return 1; + } + result.features = features; + } + return 1; + }, &search); + if (search.invalid) throw std::runtime_error("application heap: invalid host CPU record"); + return search.features; +#else + return std::nullopt; +#endif +} diff --git a/core/libs/prx/libkernel/System/include/HostCpu.hpp b/core/libs/prx/libkernel/System/include/HostCpu.hpp index 149136c48359..df8bbdbd72a6 100644 --- a/core/libs/prx/libkernel/System/include/HostCpu.hpp +++ b/core/libs/prx/libkernel/System/include/HostCpu.hpp @@ -2,6 +2,7 @@ #define CORE_LIBS_PRX_LIBKERNEL_SYSTEM_HOSTCPU_HPP #include +#include #include #include @@ -36,8 +37,8 @@ HostCpuText MissingHostCpuFeatures_nid_no_patch(const HostCpuRegisters* register HostCpuRegisters ReadHostCpuRegisters(); std::string HostCpuModel(); -std::vector HostCpuFeatures(const HostCpuRegisters& registers); -std::vector MissingHostCpuFeatures(const HostCpuRegisters& registers); -void CheckHostCpu(const HostCpuRegisters& registers, const std::string& model); +std::vector HostCpuFeatures(const HostCpuRegisters& registers, std::optional recorded = std::nullopt); +std::vector MissingHostCpuFeatures(const HostCpuRegisters& registers, std::optional recorded = std::nullopt); +void CheckHostCpu(const HostCpuRegisters& registers, const std::string& model, std::optional recorded = std::nullopt); #endif diff --git a/core/libs/prx/libkernel/System/src/HostCpu.cpp b/core/libs/prx/libkernel/System/src/HostCpu.cpp index 50ca4798ec26..a3f6b76f98d6 100644 --- a/core/libs/prx/libkernel/System/src/HostCpu.cpp +++ b/core/libs/prx/libkernel/System/src/HostCpu.cpp @@ -1,4 +1,6 @@ #include "prx/libkernel/System/include/HostCpu.hpp" +#include "prx/libc/include/ApplicationHeap.hpp" +#include "prx/libc/include/HostCpuFeatures.hpp" #include "prx/libc/include/general/LogMacros.hpp" #if defined(__x86_64__) || defined(__i386__) #include @@ -28,40 +30,41 @@ struct FeatureBit { Register Source; unsigned Bit; bool Required; + std::uint64_t RecordMask; }; constexpr FeatureBit kFeatures[] = { - {"SSE", Register::Leaf1Edx, 25, true}, - {"SSE2", Register::Leaf1Edx, 26, true}, - {"SSE3", Register::Leaf1Ecx, 0, true}, - {"SSSE3", Register::Leaf1Ecx, 9, true}, - {"SSE4.1", Register::Leaf1Ecx, 19, true}, - {"SSE4.2", Register::Leaf1Ecx, 20, true}, - {"POPCNT", Register::Leaf1Ecx, 23, true}, - {"LZCNT", Register::Leaf80000001Ecx, 5, true}, - {"BMI1", Register::Leaf7Ebx, 3, true}, - {"BMI2", Register::Leaf7Ebx, 8, true}, - {"MOVBE", Register::Leaf1Ecx, 22, true}, - {"CMPXCHG16B", Register::Leaf1Ecx, 13, true}, - {"LAHF/SAHF", Register::Leaf80000001Ecx, 0, true}, - {"AVX", Register::Leaf1Ecx, 28, true}, - {"AVX2", Register::Leaf7Ebx, 5, true}, - {"FMA", Register::Leaf1Ecx, 12, true}, - {"F16C", Register::Leaf1Ecx, 29, true}, - {"AES", Register::Leaf1Ecx, 25, false}, - {"PCLMULQDQ", Register::Leaf1Ecx, 1, false}, - {"RDRAND", Register::Leaf1Ecx, 30, false}, - {"RDSEED", Register::Leaf7Ebx, 18, false}, - {"ADX", Register::Leaf7Ebx, 19, false}, - {"SHA", Register::Leaf7Ebx, 29, false}, - {"CLFLUSHOPT", Register::Leaf7Ebx, 23, false}, - {"CLWB", Register::Leaf7Ebx, 24, false}, - {"RDPID", Register::Leaf7Ecx, 22, false}, - {"XSAVEOPT", Register::LeafDSub1Eax, 0, false}, - {"XSAVEC", Register::LeafDSub1Eax, 1, false}, - {"SSE4A", Register::Leaf80000001Ecx, 6, false}, - {"PREFETCHW", Register::Leaf80000001Ecx, 8, false}, - {"CLZERO", Register::Leaf80000008Ebx, 0, false}, + {"SSE", Register::Leaf1Edx, 25, true, 0}, + {"SSE2", Register::Leaf1Edx, 26, true, 0}, + {"SSE3", Register::Leaf1Ecx, 0, true, 0}, + {"SSSE3", Register::Leaf1Ecx, 9, true, 0}, + {"SSE4.1", Register::Leaf1Ecx, 19, true, 0}, + {"SSE4.2", Register::Leaf1Ecx, 20, true, 0}, + {"POPCNT", Register::Leaf1Ecx, 23, true, 0}, + {"LZCNT", Register::Leaf80000001Ecx, 5, true, HostCpuFeatureBits::Lzcnt}, + {"BMI1", Register::Leaf7Ebx, 3, true, HostCpuFeatureBits::Bmi1}, + {"BMI2", Register::Leaf7Ebx, 8, true, HostCpuFeatureBits::Bmi2}, + {"MOVBE", Register::Leaf1Ecx, 22, true, HostCpuFeatureBits::Movbe}, + {"CMPXCHG16B", Register::Leaf1Ecx, 13, true, 0}, + {"LAHF/SAHF", Register::Leaf80000001Ecx, 0, true, 0}, + {"AVX", Register::Leaf1Ecx, 28, true, 0}, + {"AVX2", Register::Leaf7Ebx, 5, true, HostCpuFeatureBits::Avx2}, + {"FMA", Register::Leaf1Ecx, 12, true, HostCpuFeatureBits::Fma}, + {"F16C", Register::Leaf1Ecx, 29, true, HostCpuFeatureBits::F16c}, + {"AES", Register::Leaf1Ecx, 25, false, 0}, + {"PCLMULQDQ", Register::Leaf1Ecx, 1, false, 0}, + {"RDRAND", Register::Leaf1Ecx, 30, false, 0}, + {"RDSEED", Register::Leaf7Ebx, 18, false, 0}, + {"ADX", Register::Leaf7Ebx, 19, false, 0}, + {"SHA", Register::Leaf7Ebx, 29, false, 0}, + {"CLFLUSHOPT", Register::Leaf7Ebx, 23, false, 0}, + {"CLWB", Register::Leaf7Ebx, 24, false, 0}, + {"RDPID", Register::Leaf7Ecx, 22, false, 0}, + {"XSAVEOPT", Register::LeafDSub1Eax, 0, false, 0}, + {"XSAVEC", Register::LeafDSub1Eax, 1, false, 0}, + {"SSE4A", Register::Leaf80000001Ecx, 6, false, 0}, + {"PREFETCHW", Register::Leaf80000001Ecx, 8, false, 0}, + {"CLZERO", Register::Leaf80000008Ebx, 0, false, 0}, }; constexpr unsigned kOsxsaveBit = 27; @@ -158,18 +161,20 @@ std::string HostCpuModel() { #endif } -std::vector HostCpuFeatures(const HostCpuRegisters& registers) { +std::vector HostCpuFeatures(const HostCpuRegisters& registers, const std::optional recorded) { std::vector features; features.reserve(std::size(kFeatures) + 1); - for (const auto& feature : kFeatures) - features.push_back({feature.Name, feature.Required, (Value(registers, feature.Source) >> feature.Bit & 1) != 0}); + for (const auto& feature : kFeatures) { + const bool required = recorded && feature.RecordMask != 0 ? (*recorded & feature.RecordMask) != 0 : feature.Required; + features.push_back({feature.Name, required, (Value(registers, feature.Source) >> feature.Bit & 1) != 0}); + } features.push_back({"OS AVX state (XCR0)", true, AvxStateEnabled(registers)}); return features; } -std::vector MissingHostCpuFeatures(const HostCpuRegisters& registers) { +std::vector MissingHostCpuFeatures(const HostCpuRegisters& registers, const std::optional recorded) { std::vector missing; - for (const auto& feature : HostCpuFeatures(registers)) + for (const auto& feature : HostCpuFeatures(registers, recorded)) if (feature.Required && !feature.Present) missing.emplace_back(feature.Name); return missing; } @@ -195,16 +200,20 @@ HostCpuText HostCpuModel_nid_no_patch() { } HostCpuText MissingHostCpuFeatures_nid_no_patch(const HostCpuRegisters* registers) { - return PackText(Join(MissingHostCpuFeatures(*registers))); + return PackText(Join(MissingHostCpuFeatures(*registers, ApplicationHostCpuFeatures_nid_no_patch()))); } } -void CheckHostCpu(const HostCpuRegisters& registers, const std::string& model) { - const auto missing = MissingHostCpuFeatures(registers); +void CheckHostCpu(const HostCpuRegisters& registers, const std::string& model, const std::optional recorded) { + const auto missing = MissingHostCpuFeatures(registers, recorded); if (missing.empty()) return; - throw std::runtime_error("The host CPU (" + DisplayModel(model) + ") lacks " + Join(missing) + - ". The PS5's Zen 2 CPU has these extensions and titles run their instructions natively, so this CPU cannot run them."); + std::string message = "The host CPU (" + DisplayModel(model) + ") lacks " + Join(missing) + "."; + if (recorded) + message += " The converted executable records that it still uses these extensions."; + else + message += " The PS5's Zen 2 CPU has these extensions and titles run their instructions natively, so this CPU cannot run them; relink with --to-avx to lower the extensions it can."; + throw std::runtime_error(message); } #if (defined(__x86_64__) || defined(__i386__)) && !defined(__APPLE__) @@ -213,12 +222,13 @@ namespace { const bool HostCpuChecked = [] { const auto registers = ReadHostCpuRegisters(); const auto model = HostCpuModel(); + const auto recorded = ApplicationHostCpuFeatures_nid_no_patch(); std::vector present; std::vector absent; - for (const auto& feature : HostCpuFeatures(registers)) + for (const auto& feature : HostCpuFeatures(registers, recorded)) (feature.Present ? present : absent).emplace_back(feature.Name); APS5_LOG_OUT("host CPU %s: has %s; lacks %s", DisplayModel(model).c_str(), Join(present).c_str(), absent.empty() ? "none" : Join(absent).c_str()); - CheckHostCpu(registers, model); + CheckHostCpu(registers, model, recorded); return true; }(); diff --git a/core/libs/tests/HostCpu.cpp b/core/libs/tests/HostCpu.cpp index 0f52676ca67a..e0f0fafeb4c0 100644 --- a/core/libs/tests/HostCpu.cpp +++ b/core/libs/tests/HostCpu.cpp @@ -1,6 +1,8 @@ #include "prx/libkernel/System/include/HostCpu.hpp" +#include "prx/libc/include/HostCpuFeatures.hpp" #include #include +#include #include #include #include @@ -37,6 +39,11 @@ static void CheckMissing(const HostCpuRegisters& registers, const std::vector& expected, const std::string& label, const std::optional recorded) { + const auto missing = MissingHostCpuFeatures(registers, recorded); + Require(missing == expected, label + ": expected [" + Text(expected) + "], got [" + Text(missing) + "]"); +} + static void CheckZen2() { CheckMissing(Zen2(), {}, "Zen 2"); for (const auto& feature : HostCpuFeatures(Zen2())) @@ -96,6 +103,32 @@ static void CheckPreHaswell() { CheckMissing(registers, {"LZCNT", "BMI1", "BMI2", "MOVBE", "AVX2", "FMA"}, "AVX host without AVX2"); } +static void CheckRecordedFeatures() { + auto preHaswell = Zen2(); + preHaswell.Leaf1Ecx &= ~(Bit(12) | Bit(22)); + preHaswell.Leaf7Ebx = 0; + preHaswell.Leaf80000001Ecx &= ~Bit(5); + CheckMissing(preHaswell, {}, "empty record", std::uint64_t{0}); + CheckMissing(preHaswell, {"FMA"}, "recorded FMA", HostCpuFeatureBits::Fma); + CheckMissing(preHaswell, {"BMI1", "FMA"}, "recorded BMI1 and FMA", HostCpuFeatureBits::Bmi1 | HostCpuFeatureBits::Fma); + CheckMissing(Zen2(), {}, "recorded extensions the host has", HostCpuFeatureBits::All); + auto noSse2 = Zen2(); + noSse2.Leaf1Edx &= ~Bit(26); + CheckMissing(noSse2, {"SSE2"}, "empty record keeps the baseline", std::uint64_t{0}); + auto noAvx = Zen2(); + noAvx.Leaf1Ecx &= ~Bit(28); + CheckMissing(noAvx, {"AVX"}, "empty record keeps AVX", std::uint64_t{0}); + CheckHostCpu(preHaswell, "Pre-Haswell", std::uint64_t{0}); + try { + CheckHostCpu(preHaswell, "Pre-Haswell", HostCpuFeatureBits::Fma); + throw std::logic_error("a recorded missing FMA did not throw"); + } catch (const std::runtime_error& error) { + const std::string message = error.what(); + Require(message.find("(Pre-Haswell) lacks FMA.") != std::string::npos, "unexpected recorded message: " + message); + Require(message.find("BMI1") == std::string::npos, "the recorded message names an extension the record does not require: " + message); + } +} + static void CheckError() { auto registers = Zen2(); registers.Leaf7Ebx &= ~Bit(8); @@ -145,6 +178,7 @@ int main() { CheckSingleMissingExtension(); CheckAvxWithoutOsState(); CheckPreHaswell(); + CheckRecordedFeatures(); CheckError(); } catch (const std::exception& error) { std::cerr << error.what() << '\n'; diff --git a/core/relinker/CMakeLists.txt b/core/relinker/CMakeLists.txt index 5c017921437c..d11688fa752c 100644 --- a/core/relinker/CMakeLists.txt +++ b/core/relinker/CMakeLists.txt @@ -65,6 +65,7 @@ add_library(relinker_core STATIC ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/LaneSplitLowering.cpp ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/PermuteLowering.cpp ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/WidenBroadcastLowering.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/HostCpuFeatureClassifier.cpp ${CMAKE_CURRENT_SOURCE_DIR}/relinker/src/parsing/ElfReader.cpp ${CMAKE_CURRENT_SOURCE_DIR}/relinker/src/parsing/RelrRelocations.cpp ${CMAKE_CURRENT_SOURCE_DIR}/relinker/src/analysis/SyscallScanner.cpp @@ -98,6 +99,7 @@ target_include_directories(relinker_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/io/include ${CMAKE_CURRENT_SOURCE_DIR}/codegen/include ${CMAKE_CURRENT_SOURCE_DIR}/relinker/include + ${CMAKE_CURRENT_SOURCE_DIR}/../libs/prx/libc/include ) target_compile_features(relinker_core PUBLIC cxx_std_20) @@ -182,6 +184,11 @@ if(BUILD_TESTING) add_test(NAME mulx_lowering COMMAND mulx_lowering_tests) set_tests_properties(mulx_lowering PROPERTIES TIMEOUT 20) + add_test_executable(host_cpu_feature_classifier_tests ${CMAKE_CURRENT_SOURCE_DIR}/codegen/tests/HostCpuFeatureClassifierTests.cpp) + target_link_libraries(host_cpu_feature_classifier_tests PRIVATE relinker_core) + add_test(NAME host_cpu_feature_classifier COMMAND host_cpu_feature_classifier_tests) + set_tests_properties(host_cpu_feature_classifier PROPERTIES TIMEOUT 20) + add_test_executable(relinker_conversion_tests ${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/ConversionTests.cpp) target_link_libraries(relinker_conversion_tests PRIVATE relinker_core) add_test(NAME relinker_conversion COMMAND relinker_conversion_tests) @@ -340,8 +347,9 @@ if(WIN32) ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/LaneSplitLowering.cpp ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/PermuteLowering.cpp ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/WidenBroadcastLowering.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/HostCpuFeatureClassifier.cpp ) - target_include_directories(amd64_only_windows_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/elfpatcher/include ${CMAKE_CURRENT_SOURCE_DIR}/domain/include ${CMAKE_CURRENT_SOURCE_DIR}/io/include ${CMAKE_CURRENT_SOURCE_DIR}/codegen/include ${CMAKE_CURRENT_SOURCE_DIR}/../libs/prx/libc/src/specifics/windows) + target_include_directories(amd64_only_windows_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/elfpatcher/include ${CMAKE_CURRENT_SOURCE_DIR}/domain/include ${CMAKE_CURRENT_SOURCE_DIR}/io/include ${CMAKE_CURRENT_SOURCE_DIR}/codegen/include ${CMAKE_CURRENT_SOURCE_DIR}/../libs/prx/libc/include ${CMAKE_CURRENT_SOURCE_DIR}/../libs/prx/libc/src/specifics/windows) if(BUILD_TESTING) set_target_properties(amd64_only_windows_tests PROPERTIES EXCLUDE_FROM_ALL FALSE) add_test(NAME amd64_only_windows COMMAND amd64_only_windows_tests) @@ -478,6 +486,7 @@ if(BUILD_TESTING) ${CMAKE_CURRENT_SOURCE_DIR}/elfpatcher/include ${CMAKE_CURRENT_SOURCE_DIR}/codegen/include ${CMAKE_CURRENT_SOURCE_DIR}/io/include + ${CMAKE_CURRENT_SOURCE_DIR}/../libs/prx/libc/include ) add_test(NAME program_layout_ranges COMMAND program_layout_ranges_tests) add_test_executable(windows_load_image_relocation_tests @@ -626,6 +635,7 @@ if(BUILD_TESTING) ${CMAKE_CURRENT_SOURCE_DIR}/elfpatcher/include ${CMAKE_CURRENT_SOURCE_DIR}/io/include ${CMAKE_CURRENT_SOURCE_DIR}/../libs/nid/include + ${CMAKE_CURRENT_SOURCE_DIR}/../libs/prx/libc/include ) add_test(NAME linux_load_pages COMMAND linux_load_pages_tests) set_tests_properties(linux_load_pages PROPERTIES TIMEOUT 20) @@ -664,6 +674,7 @@ if(BUILD_TESTING) ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/LaneSplitLowering.cpp ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/PermuteLowering.cpp ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/WidenBroadcastLowering.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/codegen/src/x86/HostCpuFeatureClassifier.cpp ${CMAKE_CURRENT_SOURCE_DIR}/elfpatcher/src/linux/LinuxElfPatcher.cpp ${CMAKE_CURRENT_SOURCE_DIR}/elfpatcher/src/general/SegmentFilter.cpp ${CMAKE_CURRENT_SOURCE_DIR}/elfpatcher/src/general/EntryStubBuilder.cpp @@ -680,6 +691,7 @@ if(BUILD_TESTING) ${CMAKE_CURRENT_SOURCE_DIR}/elfpatcher/include ${CMAKE_CURRENT_SOURCE_DIR}/io/include ${CMAKE_CURRENT_SOURCE_DIR}/../libs/nid/include + ${CMAKE_CURRENT_SOURCE_DIR}/../libs/prx/libc/include ) if(APPLE AND (CMAKE_OSX_ARCHITECTURES STREQUAL "x86_64" OR (NOT CMAKE_OSX_ARCHITECTURES AND CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64"))) target_link_options(amd64_only_converter_tests PRIVATE "LINKER:-pagezero_size,0x10000") @@ -1073,6 +1085,8 @@ if(BUILD_TESTING) ${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_elf_header.py $) add_test(NAME windows_process_parameters COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_windows_process_parameters.py $) + add_test(NAME host_cpu_record COMMAND ${Python3_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_hostcpu_record.py $) add_test(NAME weak_imports COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/relinker/tests/test_weak_imports.py $) add_test(NAME windows_guest_weak_imports COMMAND ${Python3_EXECUTABLE} diff --git a/core/relinker/cli/src/CliArgs.cpp b/core/relinker/cli/src/CliArgs.cpp index 9be4a054490d..10ed82638763 100644 --- a/core/relinker/cli/src/CliArgs.cpp +++ b/core/relinker/cli/src/CliArgs.cpp @@ -24,7 +24,8 @@ const char* Usage() { " --to-intel Convert supported AMD-only instructions for Intel CPUs.\n" " --to-rosetta Convert as --to-intel and lower what Rosetta lacks too. Implies --to-intel.\n" " --to-avx Convert as --to-intel and lower BMI1, BMI2, LZCNT, MOVBE, CLWB and RDPID for\n" - " CPUs with AVX but without AVX2. Implies --to-intel. Requires --macos.\n" + " CPUs with AVX but without AVX2. Implies --to-intel. Linux and Windows\n" + " output record the extensions it still needs.\n" " --frame-red-zone Windows: give leaf functions a frame so an exception on a guest thread can unwind.\n" " --rpath System library search path. Default: $ORIGIN/libs.\n" " --omit-unavailable-dependencies Linux: leave out a module dependency that no module provides, no import uses\n" @@ -260,8 +261,6 @@ Args ParseArgs(int argc, char* argv[]) { throw std::runtime_error("--windows conflicts with --macos"); if (args.toRosetta && args.toWindows) throw std::runtime_error("--to-rosetta conflicts with --windows"); - if (args.toAvx && !args.toMacos) - throw std::runtime_error("--to-avx requires --macos"); if (args.windowsDiagnostics && !args.toWindows) throw std::runtime_error("--windows-diagnostics requires --windows"); if (args.frameRedZone && !args.toWindows) diff --git a/core/relinker/cli/tests/CliArgsTests.cpp b/core/relinker/cli/tests/CliArgsTests.cpp index 9272097a195e..095a413211f5 100644 --- a/core/relinker/cli/tests/CliArgsTests.cpp +++ b/core/relinker/cli/tests/CliArgsTests.cpp @@ -341,8 +341,10 @@ void targetSelection() { expectThrows({"--to-rosetta", "--windows", "input.elf", "output.elf"}, rosettaConflict); const auto avx = parse({"--macos", "--to-avx", "input.elf", "output.elf"}); require(avx.toMacos && avx.toAvx && avx.toIntel && !avx.toRosetta, "--to-avx did not imply --to-intel on macOS"); - expectThrows({"--to-avx", "input.elf", "output.elf"}, "--to-avx requires --macos"); - expectThrows({"--windows", "--to-avx", "input.elf", "output.elf"}, "--to-avx requires --macos"); + const auto avxLinux = parse({"--to-avx", "input.elf", "output.elf"}); + require(avxLinux.toAvx && avxLinux.toIntel && !avxLinux.toMacos && !avxLinux.toWindows, "--to-avx did not select Linux output"); + const auto avxWindows = parse({"--windows", "--to-avx", "input.elf", "output.elf"}); + require(avxWindows.toWindows && avxWindows.toAvx && avxWindows.toIntel, "--to-avx was rejected with --windows"); } void patchOptions() { diff --git a/core/relinker/codegen/include/codegen/CodegenTypes.hpp b/core/relinker/codegen/include/codegen/CodegenTypes.hpp index 9b116f3657ef..55e8cc33142d 100644 --- a/core/relinker/codegen/include/codegen/CodegenTypes.hpp +++ b/core/relinker/codegen/include/codegen/CodegenTypes.hpp @@ -45,6 +45,7 @@ struct ConvertResult { std::vector Trampolines; std::vector Reports; std::size_t KeptCount = 0; + std::uint64_t RequiredHostCpuFeatures = 0; }; enum class ControlFlowKind : std::uint8_t { diff --git a/core/relinker/codegen/include/codegen/x86/HostCpuFeatureClassifier.hpp b/core/relinker/codegen/include/codegen/x86/HostCpuFeatureClassifier.hpp new file mode 100644 index 000000000000..9fb98f0528db --- /dev/null +++ b/core/relinker/codegen/include/codegen/x86/HostCpuFeatureClassifier.hpp @@ -0,0 +1,13 @@ +#ifndef CODEGEN_X86_HOSTCPUFEATURECLASSIFIER_HPP +#define CODEGEN_X86_HOSTCPUFEATURECLASSIFIER_HPP + +#include +#include + +namespace Codegen { + +[[nodiscard]] std::uint64_t RequiredHostCpuFeatures(const std::uint8_t* data, std::size_t length); + +} + +#endif diff --git a/core/relinker/codegen/src/Amd64OnlyConverter.cpp b/core/relinker/codegen/src/Amd64OnlyConverter.cpp index 5c96d1c4113c..6734851f3aeb 100644 --- a/core/relinker/codegen/src/Amd64OnlyConverter.cpp +++ b/core/relinker/codegen/src/Amd64OnlyConverter.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -379,6 +380,9 @@ void Amd64OnlyConverter::_convertSegment( const auto scanner = MakeInstructionScanner([&](auto offset, auto) { if (progress) progress(completed + offset, total); }); const auto matches = _atFileOffset(ph.Offset, [&] { return scanner->ScanCodeSection(seg, 0, seg.size()); }); + std::vector instructionFeatures(matches.size(), 0); + for (std::size_t index = 0; index < matches.size(); ++index) + instructionFeatures[index] = RequiredHostCpuFeatures(seg.data() + matches[index].Offset, matches[index].Length); if (progress) progress(completed + segSize, total); std::vector pending; @@ -394,6 +398,8 @@ void Amd64OnlyConverter::_convertSegment( if (progress) progress(completed + std::uint64_t{2} * segSize, total); if (pending.empty()) { if (progress) progress(completed + std::uint64_t{3} * segSize, total); + for (const auto features : instructionFeatures) + result.RequiredHostCpuFeatures |= features; return; } @@ -407,6 +413,7 @@ void Amd64OnlyConverter::_convertSegment( pendingIndices.insert(item.Index); std::set claimed; std::set consumed; + std::set lowered; std::size_t processed = 0; for (const auto& item : pending) { @@ -426,6 +433,7 @@ void Amd64OnlyConverter::_convertSegment( throw CodegenException("Intel substitution changes the instruction length", fileOffset); std::copy(substitution.ReplacementBytes.begin(), substitution.ReplacementBytes.end(), seg.begin() + static_cast(match.Offset)); replacementLength = substitution.ReplacementBytes.size(); + lowered.insert(item.Index); ++result.ReplacedCount; break; } @@ -441,6 +449,8 @@ void Amd64OnlyConverter::_convertSegment( result.Trampolines.push_back(std::move(site)); claimed.insert(placement->Claimed.begin(), placement->Claimed.end()); consumed.insert(placement->Consumed.begin(), placement->Consumed.end()); + lowered.insert(item.Index); + lowered.insert(placement->Consumed.begin(), placement->Consumed.end()); replacementLength = placement->ReplacementLength; break; } @@ -492,6 +502,8 @@ void Amd64OnlyConverter::_convertSegment( }); replacementLength = stub.StubBody.size(); consumed.insert(taken.begin(), taken.end()); + lowered.insert(item.Index); + lowered.insert(taken.begin(), taken.end()); for (auto k = item.Index; k < matches.size() && matches[k].Offset < match.Offset + siteLength; ++k) claimed.insert(k); } catch (const CodegenException&) { @@ -513,6 +525,10 @@ void Amd64OnlyConverter::_convertSegment( if (seg.size() != segSize) throw CodegenException("Code segment size changed during Intel conversion", ph.Offset); + for (std::size_t index = 0; index < matches.size(); ++index) { + if (lowered.contains(index)) continue; + result.RequiredHostCpuFeatures |= instructionFeatures[index]; + } std::copy(seg.begin(), seg.end(), fileBytes.begin() + static_cast(segOffset)); if (progress) progress(completed + std::uint64_t{3} * segSize, total); } diff --git a/core/relinker/codegen/src/x86/HostCpuFeatureClassifier.cpp b/core/relinker/codegen/src/x86/HostCpuFeatureClassifier.cpp new file mode 100644 index 000000000000..6c05eeee0d07 --- /dev/null +++ b/core/relinker/codegen/src/x86/HostCpuFeatureClassifier.cpp @@ -0,0 +1,162 @@ +#include +#include +#include + +namespace Codegen { + +namespace { + +using namespace VexEncoding; + +bool isLegacyPrefix(const std::uint8_t byte) { + return byte == 0xF0 || byte == 0xF2 || byte == 0xF3 || byte == 0x2E || byte == 0x36 || byte == 0x3E || + byte == 0x26 || byte == 0x64 || byte == 0x65 || byte == 0x66 || byte == 0x67; +} + +bool isAvx1Vector256(const std::uint8_t map, const std::uint8_t prefix, const std::uint8_t opcode) { + if (map == Map0F) { + if (prefix == 0) { + if (opcode >= 0x10 && opcode <= 0x17) return true; + if (opcode >= 0x28 && opcode <= 0x2F) return true; + if (opcode >= 0x50 && opcode <= 0x5F) return true; + return opcode == 0x77 || opcode == 0xC2 || opcode == 0xC6; + } + if (prefix == Prefix66) { + if (opcode >= 0x10 && opcode <= 0x17) return true; + if (opcode >= 0x28 && opcode <= 0x2F) return true; + if (opcode >= 0x50 && opcode <= 0x5F) return true; + if (opcode == 0x6F || opcode == 0x7F || opcode == 0xE7) return true; + if (opcode == 0x77 || opcode == 0x7C || opcode == 0x7D) return true; + return opcode == 0xC2 || opcode == 0xC6 || opcode == 0xD0; + } + if (prefix == PrefixF3) { + if (opcode == 0x10 || opcode == 0x11 || opcode == 0x12 || opcode == 0x16) return true; + if (opcode >= 0x2A && opcode <= 0x2F) return true; + if (opcode >= 0x51 && opcode <= 0x5F) return true; + if (opcode == 0x6F || opcode == 0x7E || opcode == 0x7F) return true; + return opcode == 0xC2; + } + if (prefix == PrefixF2) { + if (opcode == 0x10 || opcode == 0x11 || opcode == 0x12) return true; + if (opcode >= 0x2A && opcode <= 0x2F) return true; + if (opcode >= 0x51 && opcode <= 0x5F) return true; + if (opcode == 0x7C || opcode == 0x7D) return true; + return opcode == 0xC2 || opcode == 0xD0 || opcode == 0xF0; + } + return false; + } + if (map == Map0F38 && prefix == Prefix66) { + switch (opcode) { + case 0x0C: case 0x0D: case 0x0E: case 0x0F: case 0x17: + case 0x18: case 0x19: case 0x1A: + case 0x2C: case 0x2D: case 0x2E: case 0x2F: + case 0x41: + case 0xDC: case 0xDD: case 0xDE: case 0xDF: + return true; + default: + return false; + } + } + if (map == Map0F3A && prefix == Prefix66) { + switch (opcode) { + case 0x04: case 0x05: case 0x06: + case 0x08: case 0x09: case 0x0A: case 0x0B: + case 0x0C: case 0x0D: + case 0x18: case 0x19: + case 0x40: case 0x41: + case 0x4A: case 0x4B: + case 0x60: case 0x61: case 0x62: case 0x63: + case 0xDF: + return true; + default: + return false; + } + } + return false; +} + +bool isAvx2Vector128(const std::uint8_t map, const std::uint8_t prefix, const std::uint8_t opcode) { + if (prefix != Prefix66) return false; + if (map == Map0F38) { + switch (opcode) { + case 0x45: case 0x46: case 0x47: + case 0x58: case 0x59: + case 0x78: case 0x79: + case 0x8C: case 0x8D: case 0x8E: case 0x8F: + case 0x90: case 0x91: case 0x92: case 0x93: + return true; + default: + return false; + } + } + return map == Map0F3A && opcode == 0x02; +} + +std::uint64_t classifyVex(const Instruction& instruction) { + if (instruction.Map == Map0F38 && instruction.Prefix == Prefix66) { + if ((instruction.Opcode >= 0x96 && instruction.Opcode <= 0x9F) || + (instruction.Opcode >= 0xA6 && instruction.Opcode <= 0xAF) || + (instruction.Opcode >= 0xB6 && instruction.Opcode <= 0xBF)) + return HostCpuFeatureBits::Fma; + if (instruction.Opcode == 0x13) return HostCpuFeatureBits::F16c; + } + if (instruction.Map == Map0F3A && instruction.Prefix == Prefix66 && instruction.Opcode == 0x1D) + return HostCpuFeatureBits::F16c; + + if (instruction.Map == Map0F38) { + if (instruction.Prefix == 0) { + if (instruction.Opcode == 0xF2 || instruction.Opcode == 0xF3 || instruction.Opcode == 0xF7) + return HostCpuFeatureBits::Bmi1; + if (instruction.Opcode == 0xF5 || instruction.Opcode == 0xF6) + return HostCpuFeatureBits::Bmi2; + } + if (instruction.Prefix != 0) { + if (instruction.Opcode == 0xF5 || instruction.Opcode == 0xF6 || instruction.Opcode == 0xF7) + return HostCpuFeatureBits::Bmi2; + } + } + if (instruction.Map == Map0F3A && instruction.Prefix == PrefixF2 && instruction.Opcode == 0xF0) + return HostCpuFeatureBits::Bmi2; + + if (instruction.Vector256) { + if (!isAvx1Vector256(instruction.Map, instruction.Prefix, instruction.Opcode)) + return HostCpuFeatureBits::Avx2; + return 0; + } + if (isAvx2Vector128(instruction.Map, instruction.Prefix, instruction.Opcode)) + return HostCpuFeatureBits::Avx2; + return 0; +} + +} + +std::uint64_t RequiredHostCpuFeatures(const std::uint8_t* data, const std::size_t length) { + if (data == nullptr || length == 0) return 0; + + if (const auto instruction = Decode(data, length)) { + if (instruction->End > length) return 0; + return classifyVex(*instruction); + } + + std::size_t position = 0; + bool repeat = false; + bool repeatNot = false; + while (position < length) { + const std::uint8_t byte = data[position]; + if (byte == 0xF3) repeat = true; + if (byte == 0xF2) repeatNot = true; + if (!isLegacyPrefix(byte) && (byte < 0x40 || byte > 0x4F)) break; + ++position; + } + if (position + 1 >= length || data[position] != 0x0F) return 0; + const std::uint8_t first = data[position + 1]; + if (repeat && first == 0xBC) return HostCpuFeatureBits::Bmi1; + if (repeat && first == 0xBD) return HostCpuFeatureBits::Lzcnt; + if (first == 0x38 && !repeat && !repeatNot && position + 2 < length) { + const std::uint8_t second = data[position + 2]; + if (second == 0xF0 || second == 0xF1) return HostCpuFeatureBits::Movbe; + } + return 0; +} + +} diff --git a/core/relinker/codegen/tests/Amd64OnlyConverterTests.cpp b/core/relinker/codegen/tests/Amd64OnlyConverterTests.cpp index 04d361ae8e8d..cb8c1c82bf71 100644 --- a/core/relinker/codegen/tests/Amd64OnlyConverterTests.cpp +++ b/core/relinker/codegen/tests/Amd64OnlyConverterTests.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -585,6 +586,21 @@ void converterSegment() { requireFailure([&] { (void)converter->Convert(file, {segmentHeader(0x200)}); }, "Segment exceeding the file was accepted"); } +void converterHostCpuFeatures() { + const Bytes text = {0xF3, 0x0F, 0xBD, 0xC1, 0xC5, 0xF5, 0xFE, 0xC2, 0xC4, 0xE2, 0x71, 0x98, 0xC1, 0xC3}; + Bytes file(0x300, 0xCC); + std::copy(text.begin(), text.end(), file.begin() + 0x200); + const auto intel = Codegen::MakeAmd64OnlyConverter(Codegen::Amd64OnlyTarget::Intel)->Convert(file, {segmentHeader(text.size())}); + require(intel.RequiredHostCpuFeatures == (HostCpuFeatureBits::Lzcnt | HostCpuFeatureBits::Avx2 | HostCpuFeatureBits::Fma), "An Intel conversion did not record every retained extension"); + const Bytes avxText = {0xC5, 0xF5, 0xFE, 0xC2, 0xC4, 0xE2, 0x71, 0x98, 0xC1, 0xC3}; + Bytes avxFile(0x300, 0xCC); + std::copy(avxText.begin(), avxText.end(), avxFile.begin() + 0x200); + const auto avx = Codegen::MakeAmd64OnlyConverter(Codegen::Amd64OnlyTarget::Avx)->Convert(avxFile, {segmentHeader(avxText.size())}); + require(avx.RequiredHostCpuFeatures == HostCpuFeatureBits::Fma, "An AVX conversion kept a lowered extension or dropped a retained one"); + const auto untouched = Codegen::MakeAmd64OnlyConverter(Codegen::Amd64OnlyTarget::Avx)->Convert(Bytes(0x300, 0x90), {segmentHeader(0x100)}); + require(untouched.RequiredHostCpuFeatures == 0, "A segment without extensions recorded one"); +} + void converterSegmentMappedAtInt64Max() { const auto converter = Codegen::MakeAmd64OnlyConverter(); const auto file = segmentFixture(); @@ -2605,6 +2621,7 @@ int main() { rdpruExecution(); mcommitExecution(); converterSegment(); + converterHostCpuFeatures(); converterSegmentMappedAtInt64Max(); converterRipRelativeFollower(); converterSha256(); diff --git a/core/relinker/codegen/tests/HostCpuFeatureClassifierTests.cpp b/core/relinker/codegen/tests/HostCpuFeatureClassifierTests.cpp new file mode 100644 index 000000000000..27169f29db7c --- /dev/null +++ b/core/relinker/codegen/tests/HostCpuFeatureClassifierTests.cpp @@ -0,0 +1,105 @@ +#include +#include "HostCpuFeatures.hpp" +#include +#include +#include +#include +#include + +using namespace Codegen; + +namespace { + +void Require(const bool condition, const char* message) { + if (!condition) { + std::fprintf(stderr, "Requirement failed: %s\n", message); + std::abort(); + } +} + +void Expect(const std::initializer_list bytes, const std::uint64_t expected, const char* label) { + const std::vector instruction(bytes); + const auto actual = RequiredHostCpuFeatures(instruction.data(), instruction.size()); + if (actual != expected) { + std::fprintf(stderr, "%s: got 0x%llx, expected 0x%llx\n", label, + static_cast(actual), static_cast(expected)); + std::abort(); + } +} + +void TestLegacy() { + Expect({0x0F, 0xBD, 0xC1}, 0, "BSR"); + Expect({0xF3, 0x0F, 0xBD, 0xC1}, HostCpuFeatureBits::Lzcnt, "LZCNT"); + Expect({0xF3, 0x48, 0x0F, 0xBD, 0xC1}, HostCpuFeatureBits::Lzcnt, "LZCNT with REX.W"); + Expect({0x0F, 0xBC, 0xC1}, 0, "BSF"); + Expect({0xF3, 0x0F, 0xBC, 0xC1}, HostCpuFeatureBits::Bmi1, "TZCNT"); + Expect({0x0F, 0x38, 0xF0, 0x01}, HostCpuFeatureBits::Movbe, "MOVBE load"); + Expect({0x0F, 0x38, 0xF1, 0x01}, HostCpuFeatureBits::Movbe, "MOVBE store"); + Expect({0xF2, 0x0F, 0x38, 0xF0, 0xC1}, 0, "CRC32 is not MOVBE"); + Expect({0x66, 0x0F, 0x70, 0xC1, 0x1B}, 0, "PSHUFD"); + Expect({0x90}, 0, "NOP"); + Expect({0x62, 0xF1, 0x7C, 0x48, 0x58, 0xC1}, 0, "EVEX"); +} + +void TestBmi() { + Expect({0xC4, 0xE2, 0x70, 0xF2, 0xC2}, HostCpuFeatureBits::Bmi1, "ANDN"); + Expect({0xC4, 0xE2, 0x70, 0xF3, 0xC2}, HostCpuFeatureBits::Bmi1, "BLSR"); + Expect({0xC4, 0xE2, 0x70, 0xF7, 0xC2}, HostCpuFeatureBits::Bmi1, "BEXTR"); + Expect({0xC4, 0xE2, 0x70, 0xF5, 0xC2}, HostCpuFeatureBits::Bmi2, "BZHI"); + Expect({0xC4, 0xE2, 0x73, 0xF6, 0xC2}, HostCpuFeatureBits::Bmi2, "MULX"); + Expect({0xC4, 0xE2, 0x71, 0xF7, 0xC2}, HostCpuFeatureBits::Bmi2, "SHLX"); + Expect({0xC4, 0xE2, 0x72, 0xF7, 0xC2}, HostCpuFeatureBits::Bmi2, "SARX"); + Expect({0xC4, 0xE2, 0x73, 0xF7, 0xC2}, HostCpuFeatureBits::Bmi2, "SHRX"); + Expect({0xC4, 0xE3, 0x7B, 0xF0, 0xC2, 0x01}, HostCpuFeatureBits::Bmi2, "RORX"); +} + +void TestFmaAndF16c() { + Expect({0xC4, 0xE2, 0x71, 0x98, 0xC1}, HostCpuFeatureBits::Fma, "VFMADD132PS"); + Expect({0xC4, 0xE2, 0xF1, 0x9B, 0xC1}, HostCpuFeatureBits::Fma, "VFMSUB132SD"); + Expect({0xC4, 0xE2, 0x71, 0xA6, 0xC1}, HostCpuFeatureBits::Fma, "VFMADDSUB213PS"); + Expect({0xC4, 0xE2, 0x71, 0xBF, 0xC1}, HostCpuFeatureBits::Fma, "VFNMSUB231PS"); + Expect({0xC4, 0xE2, 0x79, 0x13, 0xC1}, HostCpuFeatureBits::F16c, "VCVTPH2PS"); + Expect({0xC4, 0xE3, 0x79, 0x1D, 0xC1, 0x00}, HostCpuFeatureBits::F16c, "VCVTPS2PH"); +} + +void TestAvx() { + Expect({0xC5, 0xFC, 0x58, 0xC2}, 0, "VADDPS ymm"); + Expect({0xC5, 0xF5, 0x58, 0xC2}, 0, "VADDPD ymm"); + Expect({0xC5, 0xFD, 0x5A, 0xC1}, 0, "VCVTPD2PS ymm"); + Expect({0xC5, 0xFD, 0x6F, 0xC1}, 0, "VMOVDQA ymm"); + Expect({0xC5, 0xFD, 0xE7, 0x01}, 0, "VMOVNTDQ ymm"); + Expect({0xC5, 0xFF, 0xF0, 0x01}, 0, "VLDDQU ymm"); + Expect({0xC5, 0xFA, 0x10, 0xC1}, 0, "VMOVSS"); + Expect({0xC5, 0xF8, 0x77}, 0, "VZEROUPPER"); + Expect({0xC4, 0xE3, 0x6D, 0x06, 0xC1, 0x00}, 0, "VPERM2F128"); + Expect({0xC4, 0xE3, 0x6D, 0x40, 0xC1, 0x01}, 0, "VDPPS ymm"); + Expect({0xC4, 0xE2, 0x7D, 0x1A, 0x01}, 0, "VBROADCASTF128"); + Expect({0xC4, 0xE2, 0x7D, 0x18, 0x01}, 0, "VBROADCASTSS ymm"); + Expect({0xC4, 0xE3, 0x69, 0x4C, 0xC1, 0x00}, 0, "VPBLENDVB xmm"); + Expect({0xC5, 0xF1, 0xFE, 0xC2}, 0, "VPADDD xmm"); + Expect({0xC4, 0xE2, 0x71, 0x20, 0xC1}, 0, "VPMOVSXBW xmm"); +} + +void TestAvx2() { + Expect({0xC5, 0xF5, 0xFE, 0xC2}, HostCpuFeatureBits::Avx2, "VPADDD ymm"); + Expect({0xC5, 0xF5, 0xEF, 0xC2}, HostCpuFeatureBits::Avx2, "VPXOR ymm"); + Expect({0xC4, 0xE2, 0x75, 0x36, 0xC2}, HostCpuFeatureBits::Avx2, "VPERMD ymm"); + Expect({0xC4, 0xE3, 0xED, 0x00, 0xC1, 0x01}, HostCpuFeatureBits::Avx2, "VPERMQ ymm"); + Expect({0xC4, 0xE2, 0x79, 0x58, 0xC1}, HostCpuFeatureBits::Avx2, "VPBROADCASTD xmm"); + Expect({0xC4, 0xE2, 0x69, 0x47, 0xC1}, HostCpuFeatureBits::Avx2, "VPSLLVD xmm"); + Expect({0xC4, 0xE2, 0x69, 0x90, 0xC1}, HostCpuFeatureBits::Avx2, "VPGATHERDD xmm"); + Expect({0xC4, 0xE3, 0x69, 0x02, 0xC1, 0x00}, HostCpuFeatureBits::Avx2, "VPBLENDD xmm"); + Expect({0xC4, 0xE3, 0x6D, 0x0E, 0xC1, 0x00}, HostCpuFeatureBits::Avx2, "VPBLENDW ymm"); + Expect({0xC4, 0xE2, 0x7D, 0x25, 0xC1}, HostCpuFeatureBits::Avx2, "VPMOVSXDQ ymm"); +} + +} + +int main() { + TestLegacy(); + TestBmi(); + TestFmaAndF16c(); + TestAvx(); + TestAvx2(); + return 0; +} diff --git a/core/relinker/elfpatcher/include/elfpatcher/general/ElfConstants.hpp b/core/relinker/elfpatcher/include/elfpatcher/general/ElfConstants.hpp index bd7e4f3b1aca..b2017626721f 100644 --- a/core/relinker/elfpatcher/include/elfpatcher/general/ElfConstants.hpp +++ b/core/relinker/elfpatcher/include/elfpatcher/general/ElfConstants.hpp @@ -76,6 +76,7 @@ inline constexpr std::uint32_t ET_EXEC = 2; inline constexpr std::uint32_t ET_DYN = 3; inline constexpr std::uint32_t PT_SCE_DYNLIBDATA = 0x61000000; inline constexpr std::uint32_t PT_OS_PROCPARAM = 0x61000001; +inline constexpr std::uint32_t PT_OS_HOSTCPU = 0x61000002; inline constexpr std::uint32_t PT_OS_RELRO = 0x61000010; inline constexpr std::uint32_t PT_LOOS = 0x61000000; diff --git a/core/relinker/elfpatcher/include/elfpatcher/general/IElfPatcher.hpp b/core/relinker/elfpatcher/include/elfpatcher/general/IElfPatcher.hpp index 5b1e8dbb621e..3489edf59a20 100644 --- a/core/relinker/elfpatcher/include/elfpatcher/general/IElfPatcher.hpp +++ b/core/relinker/elfpatcher/include/elfpatcher/general/IElfPatcher.hpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -21,7 +22,8 @@ class IElfPatcher { const std::string& runPath, bool lazyBinding, bool dependencyDiagnostics, - const std::vector& trampolines + const std::vector& trampolines, + std::optional hostCpuFeatures = std::nullopt ) = 0; }; diff --git a/core/relinker/elfpatcher/include/elfpatcher/general/ProgramHeaderLayoutRequest.hpp b/core/relinker/elfpatcher/include/elfpatcher/general/ProgramHeaderLayoutRequest.hpp index ec0da1750a7b..cd2315c52890 100644 --- a/core/relinker/elfpatcher/include/elfpatcher/general/ProgramHeaderLayoutRequest.hpp +++ b/core/relinker/elfpatcher/include/elfpatcher/general/ProgramHeaderLayoutRequest.hpp @@ -3,6 +3,7 @@ #include #include +#include #include namespace Elfpatcher { @@ -20,6 +21,7 @@ namespace Elfpatcher { std::uint64_t InterpOffset; std::uint64_t InterpSize; std::uint64_t MovedLoadAlignment; + std::optional HostCpuRecordVaddr; }; } diff --git a/core/relinker/elfpatcher/include/elfpatcher/linux/LinuxElfPatcher.hpp b/core/relinker/elfpatcher/include/elfpatcher/linux/LinuxElfPatcher.hpp index 58aebbcd6785..b40b8736998b 100644 --- a/core/relinker/elfpatcher/include/elfpatcher/linux/LinuxElfPatcher.hpp +++ b/core/relinker/elfpatcher/include/elfpatcher/linux/LinuxElfPatcher.hpp @@ -35,7 +35,8 @@ class LinuxElfPatcher : public IElfPatcher { const std::string& runPath, bool lazyBinding, bool dependencyDiagnostics, - const std::vector& trampolines + const std::vector& trampolines, + std::optional hostCpuFeatures = std::nullopt ) override; private: diff --git a/core/relinker/elfpatcher/include/elfpatcher/macos/MacOsMachOPatcher.hpp b/core/relinker/elfpatcher/include/elfpatcher/macos/MacOsMachOPatcher.hpp index 0acc388273fb..e84127750980 100644 --- a/core/relinker/elfpatcher/include/elfpatcher/macos/MacOsMachOPatcher.hpp +++ b/core/relinker/elfpatcher/include/elfpatcher/macos/MacOsMachOPatcher.hpp @@ -22,7 +22,8 @@ class MacOsMachOPatcher final : public IElfPatcher { const std::string& runPath, bool lazyBinding, bool dependencyDiagnostics, - const std::vector& trampolines + const std::vector& trampolines, + std::optional hostCpuFeatures = std::nullopt ) override; private: diff --git a/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsElfPatcher.hpp b/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsElfPatcher.hpp index 2443228d5647..5e6d1663c029 100644 --- a/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsElfPatcher.hpp +++ b/core/relinker/elfpatcher/include/elfpatcher/windows/WindowsElfPatcher.hpp @@ -15,7 +15,7 @@ class WindowsPePatcher : public IElfPatcher { explicit WindowsPePatcher(bool windowsGui = false, std::optional> icon = std::nullopt, std::filesystem::path iconName = "icon0.png", std::function progress = {}, std::optional fixedBase = std::nullopt, bool traceImports = false, std::function message = {}, std::string outputName = "app.exe", bool functionSymbolRoots = false); const std::string& GetDiagnostics() const; - std::vector Patch(std::vector sourceElf, const std::vector& originalHeaders, const Domain::SysVDynamicSection& dynamicSection, std::uint64_t originalPltGotVaddr, const std::string& runPath, bool lazyBinding, bool dependencyDiagnostics, const std::vector& trampolines) override; + std::vector Patch(std::vector sourceElf, const std::vector& originalHeaders, const Domain::SysVDynamicSection& dynamicSection, std::uint64_t originalPltGotVaddr, const std::string& runPath, bool lazyBinding, bool dependencyDiagnostics, const std::vector& trampolines, std::optional hostCpuFeatures = std::nullopt) override; private: std::function progress; diff --git a/core/relinker/elfpatcher/src/general/ProgramHeaderLayoutBuilder.cpp b/core/relinker/elfpatcher/src/general/ProgramHeaderLayoutBuilder.cpp index 7f366fcaf823..8cb47072b948 100644 --- a/core/relinker/elfpatcher/src/general/ProgramHeaderLayoutBuilder.cpp +++ b/core/relinker/elfpatcher/src/general/ProgramHeaderLayoutBuilder.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include @@ -201,13 +202,16 @@ std::uint16_t ProgramHeaderLayoutBuilder::WriteLayout( auto kept = _outputHeaders(request.OriginalHeaders); const auto frameCount = std::count_if(kept.begin(), kept.end(), [](const Domain::ProgramHeader& ph) { return ph.Type == PT_GNU_EH_FRAME; }); - const bool keepFrames = kept.size() + kSyntheticProgramHeaderCount <= request.PhNum; + const std::size_t syntheticCount = kSyntheticProgramHeaderCount + (request.HostCpuRecordVaddr ? 1u : 0u); + const bool keepFrames = kept.size() + syntheticCount <= request.PhNum; if (!keepFrames && frameCount > 0) { throw Domain::RelinkerException("No free program header slot for PT_GNU_EH_FRAME"); } _sortLoadHeaders(kept); - const std::size_t neededPh = kept.size() + kSyntheticProgramHeaderCount; + const std::size_t neededPh = kept.size() + syntheticCount; + if (neededPh >= kExtendedProgramHeaderCount) + throw Domain::RelinkerException("Extended program header counts are not supported"); if (neededPh > request.PhNum) throw Domain::RelinkerException( "Not enough program header slots: need " + std::to_string(neededPh) + @@ -279,6 +283,22 @@ std::uint16_t ProgramHeaderLayoutBuilder::WriteLayout( layout.push_back(_makeLoadHeader(request.ExtraBlockOffset, extraBlockVaddr, request.ExtraBlockSize, kDefaultLoadAlignment, extraBlockPageEnd - extraBlockVaddr, PF_R | PF_W | PF_X)); layout.push_back(_makeLoadHeader(0, headerBlockVaddr, headerBlockSize, headerBlockAlign, headerBlockSize, PF_R)); layout.push_back(_makeDynamicHeader(request.DynamicSegmentOffset, dynamicSegmentVaddr, request.DynamicSegmentSize)); + if (request.HostCpuRecordVaddr) { + const std::uint64_t recordVaddr = *request.HostCpuRecordVaddr; + if (recordVaddr < extraBlockVaddr || recordVaddr - extraBlockVaddr > request.ExtraBlockSize || + HostCpuFeatureBits::RecordSize > request.ExtraBlockSize - (recordVaddr - extraBlockVaddr)) + throw Domain::RelinkerException("Host CPU feature record does not fit within the extra block"); + Domain::ProgramHeader hostCpu{}; + hostCpu.Type = PT_OS_HOSTCPU; + hostCpu.Flags = PF_R; + hostCpu.Offset = request.ExtraBlockOffset + (recordVaddr - extraBlockVaddr); + hostCpu.MappedAddress = recordVaddr; + hostCpu.PhysicalAddress = recordVaddr; + hostCpu.FileSize = HostCpuFeatureBits::RecordSize; + hostCpu.MemorySize = HostCpuFeatureBits::RecordSize; + hostCpu.Alignment = 8; + layout.push_back(hostCpu); + } for (std::size_t index = 0; index < layout.size(); ++index) _writeProgramHeader(buf, static_cast(request.PhOff) + index * request.PhEntSize, layout[index]); diff --git a/core/relinker/elfpatcher/src/linux/LinuxElfPatcher.cpp b/core/relinker/elfpatcher/src/linux/LinuxElfPatcher.cpp index 8e68052f66a5..f16317984ab2 100644 --- a/core/relinker/elfpatcher/src/linux/LinuxElfPatcher.cpp +++ b/core/relinker/elfpatcher/src/linux/LinuxElfPatcher.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -430,7 +431,8 @@ std::vector LinuxElfPatcher::Patch( const std::string& runPath, const bool lazyBinding, const bool dependencyDiagnostics, - const std::vector& trampolines) + const std::vector& trampolines, + const std::optional hostCpuFeatures) { const auto dynSection = ImportsByNid(sourceDynSection); if (runPath.empty() || runPath.front() == ':' || runPath.back() == ':' || runPath.find("::") != std::string::npos) @@ -491,6 +493,14 @@ std::vector LinuxElfPatcher::Patch( return extraBlockVaddr + (fileOffset - extraBlockOff); }; + std::optional hostCpuRecordVaddr; + if (hostCpuFeatures) { + alignBuf(buf, 8); + hostCpuRecordVaddr = vaddrOfExtraBlockOffset(static_cast(buf.size())); + Io::AppendU64(buf, HostCpuFeatureBits::RecordMagic); + Io::AppendU64(buf, *hostCpuFeatures); + } + const auto& neededLibraries = dynSection.NeededLibraries; const bool mainStackEntry = std::find(neededLibraries.begin(), neededLibraries.end(), kGuestMainStackEntryLibrary) != neededLibraries.end(); std::optional mainStackSlotOff; @@ -787,10 +797,13 @@ std::vector LinuxElfPatcher::Patch( std::uint64_t tableOff = phOff; std::uint16_t tableSlots = phNum; - if (const auto required = _programHeaderLayoutBuilder->RequiredProgramHeaderCount(originalHeaders); required > phNum && required <= std::numeric_limits::max()) { + const auto requiredHeaders = _programHeaderLayoutBuilder->RequiredProgramHeaderCount(originalHeaders) + (hostCpuRecordVaddr ? 1u : 0u); + if (requiredHeaders > std::numeric_limits::max()) + throw Domain::RelinkerException("Not enough program header slots for the host CPU feature record"); + if (const auto required = static_cast(requiredHeaders); required > phNum) { alignBuf(buf, kPhdrHeaderAlignment); tableOff = static_cast(buf.size()); - tableSlots = static_cast(required); + tableSlots = required; buf.resize(buf.size() + required * phEntSize); _byteWriter->WriteU64(buf, kEhdrPhOffOffset, tableOff); } @@ -817,6 +830,7 @@ std::vector LinuxElfPatcher::Patch( layoutRequest.InterpOffset = interpOff; layoutRequest.InterpSize = interpSize; layoutRequest.MovedLoadAlignment = movedLoadAlignment; + layoutRequest.HostCpuRecordVaddr = hostCpuRecordVaddr; const std::uint16_t writtenPh = _programHeaderLayoutBuilder->WriteLayout(buf, layoutRequest); _byteWriter->WriteU16(buf, kEhdrPhNumOffset, writtenPh); diff --git a/core/relinker/elfpatcher/src/macos/MacOsMachOPatcher.cpp b/core/relinker/elfpatcher/src/macos/MacOsMachOPatcher.cpp index 1acef7ff4bba..8190dc9c28f7 100644 --- a/core/relinker/elfpatcher/src/macos/MacOsMachOPatcher.cpp +++ b/core/relinker/elfpatcher/src/macos/MacOsMachOPatcher.cpp @@ -57,7 +57,7 @@ MacOsMachOPatcher::MacOsMachOPatcher(const std::optional fixedBas throw Domain::RelinkerException("Invalid fixed macOS guest image base"); } -std::vector MacOsMachOPatcher::Patch(std::vector sourceElf, const std::vector& originalHeaders, const Domain::SysVDynamicSection& dynamicSection, const std::uint64_t originalPltGotVaddr, const std::string& runPath, const bool lazyBinding, const bool dependencyDiagnostics, const std::vector& trampolines) { +std::vector MacOsMachOPatcher::Patch(std::vector sourceElf, const std::vector& originalHeaders, const Domain::SysVDynamicSection& dynamicSection, const std::uint64_t originalPltGotVaddr, const std::string& runPath, const bool lazyBinding, const bool dependencyDiagnostics, const std::vector& trampolines, const std::optional) { if (dependencyDiagnostics) throw Domain::RelinkerException("macOS target does not support --windows-diagnostics"); if (lazyBinding) diff --git a/core/relinker/elfpatcher/src/windows/WindowsPePatcher.cpp b/core/relinker/elfpatcher/src/windows/WindowsPePatcher.cpp index bdd8327495d7..23f1ff8c506e 100644 --- a/core/relinker/elfpatcher/src/windows/WindowsPePatcher.cpp +++ b/core/relinker/elfpatcher/src/windows/WindowsPePatcher.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -36,7 +37,7 @@ WindowsPePatcher::WindowsPePatcher(const bool windowsGui, std::optional WindowsPePatcher::Patch(std::vector sourceElf, const std::vector& originalHeaders, const Domain::SysVDynamicSection& dynamicSection, const std::uint64_t originalPltGotVaddr, const std::string& runPath, const bool lazyBinding, const bool dependencyDiagnostics, const std::vector& trampolines) { +std::vector WindowsPePatcher::Patch(std::vector sourceElf, const std::vector& originalHeaders, const Domain::SysVDynamicSection& dynamicSection, const std::uint64_t originalPltGotVaddr, const std::string& runPath, const bool lazyBinding, const bool dependencyDiagnostics, const std::vector& trampolines, const std::optional hostCpuFeatures) { const auto report = [&](std::uint64_t completed) { if (progress) progress(completed, 10000); }; report(0); diagnostics.clear(); @@ -73,6 +74,13 @@ std::vector WindowsPePatcher::Patch(std::vector sour sections.push_back({".procpar", nextRva, SectionRead | 0x40u, std::vector(8)}); nextRva = AlignRva(nextRva + sections.back().Data.size()); } + if (hostCpuFeatures) { + std::vector record(HostCpuFeatureBits::RecordSize); + Io::WriteU64(record, 0, HostCpuFeatureBits::RecordMagic); + Io::WriteU64(record, 8, *hostCpuFeatures); + sections.push_back({".hostcpu", nextRva, SectionRead | 0x40u, std::move(record)}); + nextRva = AlignRva(nextRva + sections.back().Data.size()); + } for (const auto& header : originalHeaders) { if (header.Type != 0x6474e550) continue; std::vector metadata(4); diff --git a/core/relinker/relinker/include/relinker/guest/GuestImage.hpp b/core/relinker/relinker/include/relinker/guest/GuestImage.hpp index a8b633c8aa59..6f45ce571111 100644 --- a/core/relinker/relinker/include/relinker/guest/GuestImage.hpp +++ b/core/relinker/relinker/include/relinker/guest/GuestImage.hpp @@ -80,6 +80,11 @@ struct GuestArtifact { std::vector NeededLibraries; }; +struct GuestModuleBuild { + std::vector Artifacts; + std::uint64_t RequiredHostCpuFeatures = 0; +}; + struct GuestModuleInput { std::filesystem::path Path; std::vector Bytes; @@ -96,7 +101,7 @@ std::vector RemoveBackupCopies(std::vector& module class GuestModuleBuilder { public: - std::vector Build(const std::filesystem::path& inputPath, const std::filesystem::path& outputPath, Domain::SysVDynamicSection& dynamic, bool windows, bool macos, bool toIntel, Codegen::Amd64OnlyTarget target, ISyscallScanner& syscallScanner, bool lazyBinding, bool omitUnavailableDependencies, const std::string& runPath, const std::set& excludedModules, const std::filesystem::path& root, const std::vector& runtimeDirectories, std::vector modules, Domain::IProgress& progress, bool functionSymbolRoots = false) const; + GuestModuleBuild Build(const std::filesystem::path& inputPath, const std::filesystem::path& outputPath, Domain::SysVDynamicSection& dynamic, bool windows, bool macos, bool toIntel, Codegen::Amd64OnlyTarget target, ISyscallScanner& syscallScanner, bool lazyBinding, bool omitUnavailableDependencies, const std::string& runPath, const std::set& excludedModules, const std::filesystem::path& root, const std::vector& runtimeDirectories, std::vector modules, Domain::IProgress& progress, bool functionSymbolRoots = false) const; }; } diff --git a/core/relinker/relinker/src/guest/GuestModuleBuilder.cpp b/core/relinker/relinker/src/guest/GuestModuleBuilder.cpp index 46399de4cd50..75b6909ff5b9 100644 --- a/core/relinker/relinker/src/guest/GuestModuleBuilder.cpp +++ b/core/relinker/relinker/src/guest/GuestModuleBuilder.cpp @@ -91,7 +91,7 @@ std::string ModuleStem(std::string name, const bool windows) { } -std::vector GuestModuleBuilder::Build(const std::filesystem::path& inputPath, const std::filesystem::path& outputPath, Domain::SysVDynamicSection& dynamic, const bool windows, const bool macos, const bool toIntel, const Codegen::Amd64OnlyTarget target, ISyscallScanner& syscallScanner, const bool lazyBinding, const bool omitUnavailableDependencies, const std::string& runPath, const std::set& excludedModules, const std::filesystem::path& root, const std::vector& runtimeDirectories, std::vector modules, Domain::IProgress& progress, const bool functionSymbolRoots) const { +GuestModuleBuild GuestModuleBuilder::Build(const std::filesystem::path& inputPath, const std::filesystem::path& outputPath, Domain::SysVDynamicSection& dynamic, const bool windows, const bool macos, const bool toIntel, const Codegen::Amd64OnlyTarget target, ISyscallScanner& syscallScanner, const bool lazyBinding, const bool omitUnavailableDependencies, const std::string& runPath, const std::set& excludedModules, const std::filesystem::path& root, const std::vector& runtimeDirectories, std::vector modules, Domain::IProgress& progress, const bool functionSymbolRoots) const { std::vector paths; std::map discovered; progress.Report({Domain::ProgressStage::Modules, {}, 0, modules.size()}); @@ -478,6 +478,7 @@ std::vector GuestModuleBuilder::Build(const std::filesystem::path } const auto outputDirectory = outputPath.parent_path().lexically_normal(); std::vector artifacts; + std::uint64_t requiredHostCpuFeatures = 0; for (const auto index : order) { auto& image = images[index]; progress.Report({Domain::ProgressStage::Modules, Io::Utf8Path(image.SourcePath), artifacts.size(), order.size()}); @@ -485,6 +486,7 @@ std::vector GuestModuleBuilder::Build(const std::filesystem::path for (const auto& header : image.Headers) if (header.Type == 1 && (header.Flags & 1) != 0) codeHeaders.push_back(header); if (toIntel) { auto converted = Codegen::MakeAmd64OnlyConverter(target, [&](auto completed, auto total) { progress.Report({Domain::ProgressStage::Lowering, Io::Utf8Path(image.SourcePath), completed, total}); })->Convert(std::move(image.Bytes), image.Headers); + requiredHostCpuFeatures |= converted.RequiredHostCpuFeatures; image.Trampolines = std::move(converted.Trampolines); image.Bytes = std::move(converted.Bytes); if (!image.PatchedRanges.empty()) GamePatch::CheckOverlaps(Io::Utf8Path(image.SourcePath), image.PatchedRanges, {.Reports = converted.Reports, .Trampolines = image.Trampolines}); @@ -595,7 +597,7 @@ std::vector GuestModuleBuilder::Build(const std::filesystem::path artifacts.push_back({target, std::move(output), std::move(imports), image.SourcePath, std::move(neededLibraries)}); progress.Report({Domain::ProgressStage::Modules, Io::Utf8Path(image.SourcePath), artifacts.size(), order.size()}); } - return artifacts; + return {std::move(artifacts), requiredHostCpuFeatures}; } diff --git a/core/relinker/relinker/src/pipeline/Conversion.cpp b/core/relinker/relinker/src/pipeline/Conversion.cpp index 94dd9bd8519b..cca6ac8a2179 100644 --- a/core/relinker/relinker/src/pipeline/Conversion.cpp +++ b/core/relinker/relinker/src/pipeline/Conversion.cpp @@ -43,7 +43,7 @@ ConversionOutput Conversion::Convert(ConversionInput input, const ConversionOpti static_assert(std::endian::native == std::endian::little); if (options.Target != TargetSystem::Linux && options.Target != TargetSystem::Windows && options.Target != TargetSystem::MacOs) throw Domain::RelinkerException("Unknown target system"); if (options.ToRosetta && (!options.ToIntel || options.Target == TargetSystem::Windows)) throw Domain::RelinkerException("Rosetta conversion requires Intel lowering and a non-Windows target"); - if (options.ToAvx && (!options.ToIntel || options.Target != TargetSystem::MacOs)) throw Domain::RelinkerException("AVX conversion requires Intel lowering and a macOS target: only the macOS runtime skips the host CPU check"); + if (options.ToAvx && !options.ToIntel) throw Domain::RelinkerException("AVX conversion requires Intel lowering"); if (options.UnusedFilterLevel > 2) throw Domain::RelinkerException("Unused NID filter level must be 0, 1 or 2"); if (options.FrameRedZone && options.Target != TargetSystem::Windows) throw Domain::RelinkerException("Red-zone framing requires a Windows target: only Windows exception dispatch writes below RSP"); if (input.InputPath.empty() || input.OutputPath.empty()) throw Domain::RelinkerException("Input and output names are required"); @@ -70,9 +70,11 @@ ConversionOutput Conversion::Convert(ConversionInput input, const ConversionOpti } } std::vector trampolines; + std::uint64_t executableHostCpuFeatures = 0; if (options.ToIntel) { const auto segments = Relinker::ElfReader(sourceBytes).ReadProgramHeaders(); auto converted = Codegen::MakeAmd64OnlyConverter(Codegen::Amd64OnlyTargetFor(options.ToRosetta, options.ToAvx), [&](auto completed, auto total) { inputProgress.Report({Domain::ProgressStage::Lowering, {}, completed, total}); })->Convert(std::move(sourceBytes), segments); + executableHostCpuFeatures = converted.RequiredHostCpuFeatures; sourceBytes = std::move(converted.Bytes); trampolines = std::move(converted.Trampolines); GamePatch::CheckOverlaps(options.TargetName, patchedRanges, {.Reports = converted.Reports, .Trampolines = trampolines}); @@ -148,8 +150,11 @@ ConversionOutput Conversion::Convert(ConversionInput input, const ConversionOpti } std::vector guestArtifacts; + std::uint64_t requiredHostCpuFeatures = executableHostCpuFeatures; if (!input.Modules.empty()) { - guestArtifacts = Relinker::GuestModuleBuilder().Build(input.InputPath, input.OutputPath, result.DynamicSection, windows, macos, options.ToIntel, Codegen::Amd64OnlyTargetFor(options.ToRosetta, options.ToAvx), *syscallScanner, options.LazyBinding, options.OmitUnavailableDependencies, options.RunPath, options.ExcludedModules, input.ModuleRoot, input.RuntimeDirectories, std::move(input.Modules), inputProgress, options.FunctionSymbolRoots); + auto moduleBuild = Relinker::GuestModuleBuilder().Build(input.InputPath, input.OutputPath, result.DynamicSection, windows, macos, options.ToIntel, Codegen::Amd64OnlyTargetFor(options.ToRosetta, options.ToAvx), *syscallScanner, options.LazyBinding, options.OmitUnavailableDependencies, options.RunPath, options.ExcludedModules, input.ModuleRoot, input.RuntimeDirectories, std::move(input.Modules), inputProgress, options.FunctionSymbolRoots); + guestArtifacts = std::move(moduleBuild.Artifacts); + requiredHostCpuFeatures |= moduleBuild.RequiredHostCpuFeatures; } auto byteWriter = std::make_shared(); @@ -186,7 +191,7 @@ ConversionOutput Conversion::Convert(ConversionInput input, const ConversionOpti for (auto& patch : appliedPatches) if (patch.Target == options.TargetName) patch.OutputRva = image.GetRva(patch.VirtualAddress); } - executableBytes = patcher->Patch(std::move(sourceBytes), result.OriginalHeaders, result.DynamicSection, result.OriginalPltGotVaddr, options.RunPath, options.LazyBinding, options.WindowsDiagnostics, trampolines); + executableBytes = patcher->Patch(std::move(sourceBytes), result.OriginalHeaders, result.DynamicSection, result.OriginalPltGotVaddr, options.RunPath, options.LazyBinding, options.WindowsDiagnostics, trampolines, options.ToAvx && !macos ? std::optional(requiredHostCpuFeatures) : std::nullopt); } catch (Domain::RelinkerException& error) { if (error.InputPath.empty()) error.InputPath = Io::Utf8Path(input.InputPath); throw; diff --git a/core/relinker/relinker/tests/test_hostcpu_record.py b/core/relinker/relinker/tests/test_hostcpu_record.py new file mode 100644 index 000000000000..75e08f3b8895 --- /dev/null +++ b/core/relinker/relinker/tests/test_hostcpu_record.py @@ -0,0 +1,82 @@ +"""Check that --to-avx records the host CPU extensions its output still needs.""" + +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +from test_guest_intel_trampolines import main_fixture, pe_sections + +PT_OS_HOSTCPU = 0x61000002 +FMA = bytes.fromhex("c4 e2 71 98 c1") +AVX2 = bytes.fromhex("c5 f5 fe c2") +TEXT = FMA + AVX2 + b"\x90\xc3" +MAGIC = b"APS5HCP1" +FMA_BIT = 1 << 5 + + +def program_headers(elf): + offset, = struct.unpack_from("` | Map the lowest ELF load page of the macOS executable at this fixed address, given in decimal or hexadecimal (`0x`). Requires `--macos`, a 64 KiB-aligned address from `0x20000` through `0x7fffffff0000`, and an image that ends in the macOS user address space. `__PAGEZERO` ends 64 KiB below the address and the Mach-O header occupies those 64 KiB. The executable has no ASLR; an address the process cannot map fails to load. Bundled modules keep their normal placement. | | `--to-intel` | Convert supported AMD-only instructions in the executable and bundled modules. Unsupported instructions or unreachable conversion stubs cause an error. | | `--to-rosetta` | Convert as `--to-intel` does and also lower what Rosetta lacks: ANDN becomes scalar NOT/AND, BLSI, BLSMSK and BLSR become scalar LEA/AND/XOR/NEG sequences, SHLX, SHRX, SARX and RORX become flag-preserving scalar shifts and rotates, BZHI and BEXTR become scalar shift-and-mask sequences, RDSEED becomes RDRAND, CLWB a NOP, XSAVEOPT becomes XSAVE, and RDPID and the ECX of RDTSCP return processor 0. Implies `--to-intel`. Independent of `--macos`: `--macos` alone leaves these instructions as they are. Conflicts with `--windows`. | -| `--to-avx` | Convert as `--to-intel` does and also lower what a CPU with AVX but without AVX2 lacks: ANDN, BLSI, BLSMSK, BLSR, SHLX, SHRX, SARX, RORX, BZHI, BEXTR, MULX, CLWB and RDPID as `--to-rosetta` lowers them, TZCNT and LZCNT become BSF and BSR with a CMOV for a zero source, and MOVBE becomes MOV and BSWAP. VINSERTI128, VEXTRACTI128, VPERM2I128, VPBLENDD, VBROADCASTI128 and the memory forms of VPBROADCASTD and VPBROADCASTQ become their AVX equivalents VINSERTF128, VEXTRACTF128, VPERM2F128, VBLENDPS, VBROADCASTF128, VBROADCASTSS and VBROADCASTSD or VMOVDDUP in place, and 256-bit lane-local integer instructions (additions, logic, compares, packs, unpacks, shuffles within a lane, shifts by an immediate or by an XMM count, VPBLENDVB, VMPSADBW and VPMOVMSKB) run as two 128-bit halves in a stub, and the cross-lane permutes VPERMQ, VPERMPD, VPERMD and VPERMPS, the 256-bit widening moves VPMOVZX and VPMOVSX and the register-source and byte or word broadcasts run in AVX stubs. The Rosetta workarounds for 256-bit stores, scalar compares, masked stores, RDTSCP, XSAVEOPT and RDSEED are not applied. Other AVX2 instructions, F16C, PDEP and PEXT are not lowered yet ([list](../dev/debt/relinker.md)). Implies `--to-intel`. Requires `--macos`, because only the macOS runtime starts without checking the host CPU. | +| `--to-avx` | Convert as `--to-intel` does and also lower what a CPU with AVX but without AVX2 lacks: ANDN, BLSI, BLSMSK, BLSR, SHLX, SHRX, SARX, RORX, BZHI, BEXTR, MULX, CLWB and RDPID as `--to-rosetta` lowers them, TZCNT and LZCNT become BSF and BSR with a CMOV for a zero source, and MOVBE becomes MOV and BSWAP. VINSERTI128, VEXTRACTI128, VPERM2I128, VPBLENDD, VBROADCASTI128 and the memory forms of VPBROADCASTD and VPBROADCASTQ become their AVX equivalents VINSERTF128, VEXTRACTF128, VPERM2F128, VBLENDPS, VBROADCASTF128, VBROADCASTSS and VBROADCASTSD or VMOVDDUP in place, and 256-bit lane-local integer instructions (additions, logic, compares, packs, unpacks, shuffles within a lane, shifts by an immediate or by an XMM count, VPBLENDVB, VMPSADBW and VPMOVMSKB) run as two 128-bit halves in a stub, and the cross-lane permutes VPERMQ, VPERMPD, VPERMD and VPERMPS, the 256-bit widening moves VPMOVZX and VPMOVSX and the register-source and byte or word broadcasts run in AVX stubs. The Rosetta workarounds for 256-bit stores, scalar compares, masked stores, RDTSCP, XSAVEOPT and RDSEED are not applied. Other AVX2 instructions, F16C, PDEP and PEXT are not lowered yet ([list](../dev/debt/relinker.md)). Implies `--to-intel`. Linux and Windows output record the extensions it still needs and start only when the host has the baseline plus those recorded extensions; macOS output keeps its existing start-up behaviour. | | `unused-filter=0` | Keep all imported NID references. | | `unused-filter=1` | Filter unused non-PLT imports using control-flow and GOT access analysis, treating address-taken code as reachable; preserve PLT imports. | | `unused-filter=2` | Apply strict unused-import analysis and compact the PLT. Unsupported analysis cases cause an error. | From 5aaef93431ed3027c1f9ea5312a039f66ab8099f Mon Sep 17 00:00:00 2001 From: momgaro ganuchi Date: Sat, 21 Nov 2026 19:31:49 +0300 Subject: [PATCH 2/5] fix(relinker): correct AVX1 and AVX2 classification VEX.128 VPACKUSDW is AVX and only its 256-bit form is AVX2; VCVTDQ2PD, VCVTPD2DQ and VCVTTPD2DQ are AVX in their 256-bit forms. Removes 0x2B from the 128-bit AVX2 list, adds 0xE6 to the AVX1 256-bit lists and covers the encodings. --- core/relinker/codegen/src/x86/HostCpuFeatureClassifier.cpp | 6 +++--- .../codegen/tests/HostCpuFeatureClassifierTests.cpp | 5 +++++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/core/relinker/codegen/src/x86/HostCpuFeatureClassifier.cpp b/core/relinker/codegen/src/x86/HostCpuFeatureClassifier.cpp index 6c05eeee0d07..62f4b6be0920 100644 --- a/core/relinker/codegen/src/x86/HostCpuFeatureClassifier.cpp +++ b/core/relinker/codegen/src/x86/HostCpuFeatureClassifier.cpp @@ -25,7 +25,7 @@ bool isAvx1Vector256(const std::uint8_t map, const std::uint8_t prefix, const st if (opcode >= 0x10 && opcode <= 0x17) return true; if (opcode >= 0x28 && opcode <= 0x2F) return true; if (opcode >= 0x50 && opcode <= 0x5F) return true; - if (opcode == 0x6F || opcode == 0x7F || opcode == 0xE7) return true; + if (opcode == 0x6F || opcode == 0x7F || opcode == 0xE6 || opcode == 0xE7) return true; if (opcode == 0x77 || opcode == 0x7C || opcode == 0x7D) return true; return opcode == 0xC2 || opcode == 0xC6 || opcode == 0xD0; } @@ -33,14 +33,14 @@ bool isAvx1Vector256(const std::uint8_t map, const std::uint8_t prefix, const st if (opcode == 0x10 || opcode == 0x11 || opcode == 0x12 || opcode == 0x16) return true; if (opcode >= 0x2A && opcode <= 0x2F) return true; if (opcode >= 0x51 && opcode <= 0x5F) return true; - if (opcode == 0x6F || opcode == 0x7E || opcode == 0x7F) return true; + if (opcode == 0x6F || opcode == 0x7E || opcode == 0x7F || opcode == 0xE6) return true; return opcode == 0xC2; } if (prefix == PrefixF2) { if (opcode == 0x10 || opcode == 0x11 || opcode == 0x12) return true; if (opcode >= 0x2A && opcode <= 0x2F) return true; if (opcode >= 0x51 && opcode <= 0x5F) return true; - if (opcode == 0x7C || opcode == 0x7D) return true; + if (opcode == 0x7C || opcode == 0x7D || opcode == 0xE6) return true; return opcode == 0xC2 || opcode == 0xD0 || opcode == 0xF0; } return false; diff --git a/core/relinker/codegen/tests/HostCpuFeatureClassifierTests.cpp b/core/relinker/codegen/tests/HostCpuFeatureClassifierTests.cpp index 27169f29db7c..b200af074ee0 100644 --- a/core/relinker/codegen/tests/HostCpuFeatureClassifierTests.cpp +++ b/core/relinker/codegen/tests/HostCpuFeatureClassifierTests.cpp @@ -78,6 +78,9 @@ void TestAvx() { Expect({0xC4, 0xE3, 0x69, 0x4C, 0xC1, 0x00}, 0, "VPBLENDVB xmm"); Expect({0xC5, 0xF1, 0xFE, 0xC2}, 0, "VPADDD xmm"); Expect({0xC4, 0xE2, 0x71, 0x20, 0xC1}, 0, "VPMOVSXBW xmm"); + Expect({0xC5, 0xFD, 0xE6, 0xC1}, 0, "VCVTDQ2PD ymm"); + Expect({0xC5, 0xFE, 0xE6, 0xC1}, 0, "VCVTPD2DQ ymm"); + Expect({0xC5, 0xFF, 0xE6, 0xC1}, 0, "VCVTTPD2DQ ymm"); } void TestAvx2() { @@ -91,6 +94,8 @@ void TestAvx2() { Expect({0xC4, 0xE3, 0x69, 0x02, 0xC1, 0x00}, HostCpuFeatureBits::Avx2, "VPBLENDD xmm"); Expect({0xC4, 0xE3, 0x6D, 0x0E, 0xC1, 0x00}, HostCpuFeatureBits::Avx2, "VPBLENDW ymm"); Expect({0xC4, 0xE2, 0x7D, 0x25, 0xC1}, HostCpuFeatureBits::Avx2, "VPMOVSXDQ ymm"); + Expect({0xC4, 0xE2, 0x71, 0x2B, 0xD0}, 0, "VPACKUSDW xmm is AVX"); + Expect({0xC4, 0xE2, 0x7D, 0x2B, 0xC1}, HostCpuFeatureBits::Avx2, "VPACKUSDW ymm"); } } From 93c0122d7583669c8673719fb4957b7c62de8c44 Mon Sep 17 00:00:00 2001 From: momgaro ganuchi Date: Sun, 22 Nov 2026 16:44:41 +0300 Subject: [PATCH 3/5] fix(relinker): validate legacy encodings and broadcast forms Requires the full legacy instruction length before recording TZCNT, LZCNT or MOVBE, so truncated encodings add no requirement. Classifies register-source VBROADCASTSS and VBROADCASTSD as AVX2 while their memory forms stay AVX1, and covers the forms in the classifier tests. --- .../src/x86/HostCpuFeatureClassifier.cpp | 22 ++++++++++++++----- .../tests/HostCpuFeatureClassifierTests.cpp | 9 +++++++- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/core/relinker/codegen/src/x86/HostCpuFeatureClassifier.cpp b/core/relinker/codegen/src/x86/HostCpuFeatureClassifier.cpp index 62f4b6be0920..a37c0ee2d0df 100644 --- a/core/relinker/codegen/src/x86/HostCpuFeatureClassifier.cpp +++ b/core/relinker/codegen/src/x86/HostCpuFeatureClassifier.cpp @@ -1,5 +1,7 @@ #include #include +#include +#include #include namespace Codegen { @@ -13,7 +15,7 @@ bool isLegacyPrefix(const std::uint8_t byte) { byte == 0x26 || byte == 0x64 || byte == 0x65 || byte == 0x66 || byte == 0x67; } -bool isAvx1Vector256(const std::uint8_t map, const std::uint8_t prefix, const std::uint8_t opcode) { +bool isAvx1Vector256(const std::uint8_t map, const std::uint8_t prefix, const std::uint8_t opcode, const bool registerForm) { if (map == Map0F) { if (prefix == 0) { if (opcode >= 0x10 && opcode <= 0x17) return true; @@ -48,7 +50,9 @@ bool isAvx1Vector256(const std::uint8_t map, const std::uint8_t prefix, const st if (map == Map0F38 && prefix == Prefix66) { switch (opcode) { case 0x0C: case 0x0D: case 0x0E: case 0x0F: case 0x17: - case 0x18: case 0x19: case 0x1A: + case 0x18: case 0x19: + return !registerForm; + case 0x1A: case 0x2C: case 0x2D: case 0x2E: case 0x2F: case 0x41: case 0xDC: case 0xDD: case 0xDE: case 0xDF: @@ -75,9 +79,10 @@ bool isAvx1Vector256(const std::uint8_t map, const std::uint8_t prefix, const st return false; } -bool isAvx2Vector128(const std::uint8_t map, const std::uint8_t prefix, const std::uint8_t opcode) { +bool isAvx2Vector128(const std::uint8_t map, const std::uint8_t prefix, const std::uint8_t opcode, const bool registerForm) { if (prefix != Prefix66) return false; if (map == Map0F38) { + if (registerForm && (opcode == 0x18 || opcode == 0x19)) return true; switch (opcode) { case 0x45: case 0x46: case 0x47: case 0x58: case 0x59: @@ -119,11 +124,11 @@ std::uint64_t classifyVex(const Instruction& instruction) { return HostCpuFeatureBits::Bmi2; if (instruction.Vector256) { - if (!isAvx1Vector256(instruction.Map, instruction.Prefix, instruction.Opcode)) + if (!isAvx1Vector256(instruction.Map, instruction.Prefix, instruction.Opcode, !instruction.Memory.has_value())) return HostCpuFeatureBits::Avx2; return 0; } - if (isAvx2Vector128(instruction.Map, instruction.Prefix, instruction.Opcode)) + if (isAvx2Vector128(instruction.Map, instruction.Prefix, instruction.Opcode, !instruction.Memory.has_value())) return HostCpuFeatureBits::Avx2; return 0; } @@ -138,6 +143,13 @@ std::uint64_t RequiredHostCpuFeatures(const std::uint8_t* data, const std::size_ return classifyVex(*instruction); } + const X64InstructionDecoder decoder; + try { + if (decoder.Decode(data, length) != length) return 0; + } catch (const CodegenException&) { + return 0; + } + std::size_t position = 0; bool repeat = false; bool repeatNot = false; diff --git a/core/relinker/codegen/tests/HostCpuFeatureClassifierTests.cpp b/core/relinker/codegen/tests/HostCpuFeatureClassifierTests.cpp index b200af074ee0..ba91615701cf 100644 --- a/core/relinker/codegen/tests/HostCpuFeatureClassifierTests.cpp +++ b/core/relinker/codegen/tests/HostCpuFeatureClassifierTests.cpp @@ -39,6 +39,9 @@ void TestLegacy() { Expect({0x66, 0x0F, 0x70, 0xC1, 0x1B}, 0, "PSHUFD"); Expect({0x90}, 0, "NOP"); Expect({0x62, 0xF1, 0x7C, 0x48, 0x58, 0xC1}, 0, "EVEX"); + Expect({0xF3, 0x0F, 0xBC}, 0, "truncated TZCNT"); + Expect({0xF3, 0x0F, 0xBD}, 0, "truncated LZCNT"); + Expect({0x0F, 0x38, 0xF0}, 0, "truncated MOVBE"); } void TestBmi() { @@ -74,7 +77,8 @@ void TestAvx() { Expect({0xC4, 0xE3, 0x6D, 0x06, 0xC1, 0x00}, 0, "VPERM2F128"); Expect({0xC4, 0xE3, 0x6D, 0x40, 0xC1, 0x01}, 0, "VDPPS ymm"); Expect({0xC4, 0xE2, 0x7D, 0x1A, 0x01}, 0, "VBROADCASTF128"); - Expect({0xC4, 0xE2, 0x7D, 0x18, 0x01}, 0, "VBROADCASTSS ymm"); + Expect({0xC4, 0xE2, 0x7D, 0x18, 0x01}, 0, "VBROADCASTSS ymm, m32"); + Expect({0xC4, 0xE2, 0x7D, 0x19, 0x01}, 0, "VBROADCASTSD ymm, m64"); Expect({0xC4, 0xE3, 0x69, 0x4C, 0xC1, 0x00}, 0, "VPBLENDVB xmm"); Expect({0xC5, 0xF1, 0xFE, 0xC2}, 0, "VPADDD xmm"); Expect({0xC4, 0xE2, 0x71, 0x20, 0xC1}, 0, "VPMOVSXBW xmm"); @@ -95,6 +99,9 @@ void TestAvx2() { Expect({0xC4, 0xE3, 0x6D, 0x0E, 0xC1, 0x00}, HostCpuFeatureBits::Avx2, "VPBLENDW ymm"); Expect({0xC4, 0xE2, 0x7D, 0x25, 0xC1}, HostCpuFeatureBits::Avx2, "VPMOVSXDQ ymm"); Expect({0xC4, 0xE2, 0x71, 0x2B, 0xD0}, 0, "VPACKUSDW xmm is AVX"); + Expect({0xC4, 0xE2, 0x7D, 0x18, 0xC1}, HostCpuFeatureBits::Avx2, "VBROADCASTSS ymm, xmm"); + Expect({0xC4, 0xE2, 0x7D, 0x19, 0xC1}, HostCpuFeatureBits::Avx2, "VBROADCASTSD ymm, xmm"); + Expect({0xC4, 0xE2, 0x79, 0x18, 0xC1}, HostCpuFeatureBits::Avx2, "VBROADCASTSS xmm, xmm"); Expect({0xC4, 0xE2, 0x7D, 0x2B, 0xC1}, HostCpuFeatureBits::Avx2, "VPACKUSDW ymm"); } From b903995898003f34f30164555b361d49ef16fdc7 Mon Sep 17 00:00:00 2001 From: momgaro ganuchi Date: Mon, 23 Nov 2026 11:59:30 +0300 Subject: [PATCH 4/5] fix(relinker): keep register-form 0F38 66 instructions AVX1 Only VBROADCASTSS and VBROADCASTSD depend on the ModRM register form; VPERMILPS, VPERMILPD, VTESTPS, VTESTPD and VPTEST are AVX1 in both forms. Adds classifier tests for the five register forms. --- core/relinker/codegen/src/x86/HostCpuFeatureClassifier.cpp | 1 + .../relinker/codegen/tests/HostCpuFeatureClassifierTests.cpp | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/core/relinker/codegen/src/x86/HostCpuFeatureClassifier.cpp b/core/relinker/codegen/src/x86/HostCpuFeatureClassifier.cpp index a37c0ee2d0df..70debc99d32d 100644 --- a/core/relinker/codegen/src/x86/HostCpuFeatureClassifier.cpp +++ b/core/relinker/codegen/src/x86/HostCpuFeatureClassifier.cpp @@ -50,6 +50,7 @@ bool isAvx1Vector256(const std::uint8_t map, const std::uint8_t prefix, const st if (map == Map0F38 && prefix == Prefix66) { switch (opcode) { case 0x0C: case 0x0D: case 0x0E: case 0x0F: case 0x17: + return true; case 0x18: case 0x19: return !registerForm; case 0x1A: diff --git a/core/relinker/codegen/tests/HostCpuFeatureClassifierTests.cpp b/core/relinker/codegen/tests/HostCpuFeatureClassifierTests.cpp index ba91615701cf..a49eb94ba1d5 100644 --- a/core/relinker/codegen/tests/HostCpuFeatureClassifierTests.cpp +++ b/core/relinker/codegen/tests/HostCpuFeatureClassifierTests.cpp @@ -79,6 +79,11 @@ void TestAvx() { Expect({0xC4, 0xE2, 0x7D, 0x1A, 0x01}, 0, "VBROADCASTF128"); Expect({0xC4, 0xE2, 0x7D, 0x18, 0x01}, 0, "VBROADCASTSS ymm, m32"); Expect({0xC4, 0xE2, 0x7D, 0x19, 0x01}, 0, "VBROADCASTSD ymm, m64"); + Expect({0xC4, 0xE2, 0x7D, 0x0C, 0xC1}, 0, "VPERMILPS ymm, ymm, ymm"); + Expect({0xC4, 0xE2, 0x7D, 0x0D, 0xC1}, 0, "VPERMILPD ymm, ymm, ymm"); + Expect({0xC4, 0xE2, 0x7D, 0x0E, 0xC1}, 0, "VTESTPS ymm, ymm"); + Expect({0xC4, 0xE2, 0x7D, 0x0F, 0xC1}, 0, "VTESTPD ymm, ymm"); + Expect({0xC4, 0xE2, 0x7D, 0x17, 0xC1}, 0, "VPTEST ymm, ymm"); Expect({0xC4, 0xE3, 0x69, 0x4C, 0xC1, 0x00}, 0, "VPBLENDVB xmm"); Expect({0xC5, 0xF1, 0xFE, 0xC2}, 0, "VPADDD xmm"); Expect({0xC4, 0xE2, 0x71, 0x20, 0xC1}, 0, "VPMOVSXBW xmm"); From 4afb5db7993a3e0611771fcf45252ff074ac8046 Mon Sep 17 00:00:00 2001 From: momgaro ganuchi Date: Wed, 25 Nov 2026 19:13:32 +0300 Subject: [PATCH 5/5] feat(relinker): record every retained host CPU extension Record AES, PCLMULQDQ, RDRAND, RDSEED, ADX, SHA, CLFLUSHOPT, CLWB, RDPID, XSAVEOPT, XSAVEC, XSAVES, SSE4A, CLZERO, RDTSCP and FSGSBASE in the host CPU record, detect the legacy encodings that carry them in the classifier, and read CPUID leaf 80000001 EDX for RDTSCP. Extend the record, classifier and runtime tests and the debt note. --- .../libs/prx/libc/include/HostCpuFeatures.hpp | 24 +++- .../prx/libkernel/System/include/HostCpu.hpp | 3 + .../libs/prx/libkernel/System/src/HostCpu.cpp | 46 ++++++-- core/libs/tests/HostCpu.cpp | 75 ++++++++++-- .../src/x86/HostCpuFeatureClassifier.cpp | 111 +++++++++++++++--- .../tests/HostCpuFeatureClassifierTests.cpp | 50 ++++++++ .../relinker/tests/test_hostcpu_record.py | 8 +- .../changes/feat-relinker-to-avx-host-cpu.md | 4 +- 8 files changed, 275 insertions(+), 46 deletions(-) diff --git a/core/libs/prx/libc/include/HostCpuFeatures.hpp b/core/libs/prx/libc/include/HostCpuFeatures.hpp index 8031b4befc5f..b278cdff157d 100644 --- a/core/libs/prx/libc/include/HostCpuFeatures.hpp +++ b/core/libs/prx/libc/include/HostCpuFeatures.hpp @@ -12,7 +12,29 @@ inline constexpr std::uint64_t Movbe = 1ull << 3u; inline constexpr std::uint64_t Avx2 = 1ull << 4u; inline constexpr std::uint64_t Fma = 1ull << 5u; inline constexpr std::uint64_t F16c = 1ull << 6u; -inline constexpr std::uint64_t All = Lzcnt | Bmi1 | Bmi2 | Movbe | Avx2 | Fma | F16c; +inline constexpr std::uint64_t Rdrand = 1ull << 7u; +inline constexpr std::uint64_t Rdseed = 1ull << 8u; +inline constexpr std::uint64_t Adx = 1ull << 9u; +inline constexpr std::uint64_t Sha = 1ull << 10u; +inline constexpr std::uint64_t Clflushopt = 1ull << 11u; +inline constexpr std::uint64_t Clwb = 1ull << 12u; +inline constexpr std::uint64_t Rdpid = 1ull << 13u; +inline constexpr std::uint64_t Xsaveopt = 1ull << 14u; +inline constexpr std::uint64_t Xsavec = 1ull << 15u; +inline constexpr std::uint64_t Xsaves = 1ull << 16u; +inline constexpr std::uint64_t Aes = 1ull << 17u; +inline constexpr std::uint64_t Pclmul = 1ull << 18u; +inline constexpr std::uint64_t Sse4a = 1ull << 19u; +inline constexpr std::uint64_t Clzero = 1ull << 20u; +inline constexpr std::uint64_t Rdtscp = 1ull << 21u; +inline constexpr std::uint64_t Fsgsbase = 1ull << 22u; +inline constexpr std::uint64_t AvxVnni = 1ull << 23u; +inline constexpr std::uint64_t AvxIfma = 1ull << 24u; +inline constexpr std::uint64_t AvxVnniInt8 = 1ull << 25u; +inline constexpr std::uint64_t AvxNeConvert = 1ull << 26u; +inline constexpr std::uint64_t All = Lzcnt | Bmi1 | Bmi2 | Movbe | Avx2 | Fma | F16c | Rdrand | Rdseed | Adx | Sha | + Clflushopt | Clwb | Rdpid | Xsaveopt | Xsavec | Xsaves | Aes | Pclmul | Sse4a | + Clzero | Rdtscp | Fsgsbase | AvxVnni | AvxIfma | AvxVnniInt8 | AvxNeConvert; inline constexpr std::uint64_t RecordMagic = 0x3150434835535041ull; inline constexpr std::uint64_t RecordSize = 16; diff --git a/core/libs/prx/libkernel/System/include/HostCpu.hpp b/core/libs/prx/libkernel/System/include/HostCpu.hpp index df8bbdbd72a6..97f9f61e6b07 100644 --- a/core/libs/prx/libkernel/System/include/HostCpu.hpp +++ b/core/libs/prx/libkernel/System/include/HostCpu.hpp @@ -11,8 +11,11 @@ struct HostCpuRegisters { std::uint32_t Leaf1Edx = 0; std::uint32_t Leaf7Ebx = 0; std::uint32_t Leaf7Ecx = 0; + std::uint32_t Leaf7Sub1Eax = 0; + std::uint32_t Leaf7Sub1Edx = 0; std::uint32_t LeafDSub1Eax = 0; std::uint32_t Leaf80000001Ecx = 0; + std::uint32_t Leaf80000001Edx = 0; std::uint32_t Leaf80000008Ebx = 0; std::uint64_t Xcr0 = 0; }; diff --git a/core/libs/prx/libkernel/System/src/HostCpu.cpp b/core/libs/prx/libkernel/System/src/HostCpu.cpp index a3f6b76f98d6..556be903b641 100644 --- a/core/libs/prx/libkernel/System/src/HostCpu.cpp +++ b/core/libs/prx/libkernel/System/src/HostCpu.cpp @@ -20,8 +20,11 @@ enum class Register : std::uint8_t { Leaf1Edx, Leaf7Ebx, Leaf7Ecx, + Leaf7Sub1Eax, + Leaf7Sub1Edx, LeafDSub1Eax, Leaf80000001Ecx, + Leaf80000001Edx, Leaf80000008Ebx }; @@ -51,20 +54,27 @@ constexpr FeatureBit kFeatures[] = { {"AVX2", Register::Leaf7Ebx, 5, true, HostCpuFeatureBits::Avx2}, {"FMA", Register::Leaf1Ecx, 12, true, HostCpuFeatureBits::Fma}, {"F16C", Register::Leaf1Ecx, 29, true, HostCpuFeatureBits::F16c}, - {"AES", Register::Leaf1Ecx, 25, false, 0}, - {"PCLMULQDQ", Register::Leaf1Ecx, 1, false, 0}, - {"RDRAND", Register::Leaf1Ecx, 30, false, 0}, - {"RDSEED", Register::Leaf7Ebx, 18, false, 0}, - {"ADX", Register::Leaf7Ebx, 19, false, 0}, - {"SHA", Register::Leaf7Ebx, 29, false, 0}, - {"CLFLUSHOPT", Register::Leaf7Ebx, 23, false, 0}, - {"CLWB", Register::Leaf7Ebx, 24, false, 0}, - {"RDPID", Register::Leaf7Ecx, 22, false, 0}, - {"XSAVEOPT", Register::LeafDSub1Eax, 0, false, 0}, - {"XSAVEC", Register::LeafDSub1Eax, 1, false, 0}, - {"SSE4A", Register::Leaf80000001Ecx, 6, false, 0}, + {"AES", Register::Leaf1Ecx, 25, false, HostCpuFeatureBits::Aes}, + {"PCLMULQDQ", Register::Leaf1Ecx, 1, false, HostCpuFeatureBits::Pclmul}, + {"RDRAND", Register::Leaf1Ecx, 30, false, HostCpuFeatureBits::Rdrand}, + {"FSGSBASE", Register::Leaf7Ebx, 0, false, HostCpuFeatureBits::Fsgsbase}, + {"RDSEED", Register::Leaf7Ebx, 18, false, HostCpuFeatureBits::Rdseed}, + {"ADX", Register::Leaf7Ebx, 19, false, HostCpuFeatureBits::Adx}, + {"SHA", Register::Leaf7Ebx, 29, false, HostCpuFeatureBits::Sha}, + {"CLFLUSHOPT", Register::Leaf7Ebx, 23, false, HostCpuFeatureBits::Clflushopt}, + {"CLWB", Register::Leaf7Ebx, 24, false, HostCpuFeatureBits::Clwb}, + {"RDPID", Register::Leaf7Ecx, 22, false, HostCpuFeatureBits::Rdpid}, + {"AVX-VNNI", Register::Leaf7Sub1Eax, 4, false, HostCpuFeatureBits::AvxVnni}, + {"AVX-IFMA", Register::Leaf7Sub1Eax, 23, false, HostCpuFeatureBits::AvxIfma}, + {"AVX-VNNI-INT8", Register::Leaf7Sub1Edx, 4, false, HostCpuFeatureBits::AvxVnniInt8}, + {"AVX-NE-CONVERT", Register::Leaf7Sub1Edx, 5, false, HostCpuFeatureBits::AvxNeConvert}, + {"XSAVEOPT", Register::LeafDSub1Eax, 0, false, HostCpuFeatureBits::Xsaveopt}, + {"XSAVEC", Register::LeafDSub1Eax, 1, false, HostCpuFeatureBits::Xsavec}, + {"XSAVES", Register::LeafDSub1Eax, 3, false, HostCpuFeatureBits::Xsaves}, + {"SSE4A", Register::Leaf80000001Ecx, 6, false, HostCpuFeatureBits::Sse4a}, {"PREFETCHW", Register::Leaf80000001Ecx, 8, false, 0}, - {"CLZERO", Register::Leaf80000008Ebx, 0, false, 0}, + {"RDTSCP", Register::Leaf80000001Edx, 27, false, HostCpuFeatureBits::Rdtscp}, + {"CLZERO", Register::Leaf80000008Ebx, 0, false, HostCpuFeatureBits::Clzero}, }; constexpr unsigned kOsxsaveBit = 27; @@ -80,10 +90,16 @@ std::uint32_t Value(const HostCpuRegisters& registers, const Register source) { return registers.Leaf7Ebx; case Register::Leaf7Ecx: return registers.Leaf7Ecx; + case Register::Leaf7Sub1Eax: + return registers.Leaf7Sub1Eax; + case Register::Leaf7Sub1Edx: + return registers.Leaf7Sub1Edx; case Register::LeafDSub1Eax: return registers.LeafDSub1Eax; case Register::Leaf80000001Ecx: return registers.Leaf80000001Ecx; + case Register::Leaf80000001Edx: + return registers.Leaf80000001Edx; case Register::Leaf80000008Ebx: return registers.Leaf80000008Ebx; } @@ -124,6 +140,9 @@ HostCpuRegisters ReadHostCpuRegisters() { __cpuid_count(7, 0, eax, ebx, ecx, edx); registers.Leaf7Ebx = ebx; registers.Leaf7Ecx = ecx; + __cpuid_count(7, 1, eax, ebx, ecx, edx); + registers.Leaf7Sub1Eax = eax; + registers.Leaf7Sub1Edx = edx; } if (basic >= 0xD) { __cpuid_count(0xD, 1, eax, ebx, ecx, edx); @@ -133,6 +152,7 @@ HostCpuRegisters ReadHostCpuRegisters() { if (extended >= 0x80000001) { __cpuid(0x80000001, eax, ebx, ecx, edx); registers.Leaf80000001Ecx = ecx; + registers.Leaf80000001Edx = edx; } if (extended >= 0x80000008) { __cpuid(0x80000008, eax, ebx, ecx, edx); diff --git a/core/libs/tests/HostCpu.cpp b/core/libs/tests/HostCpu.cpp index e0f0fafeb4c0..61b50c0f7afc 100644 --- a/core/libs/tests/HostCpu.cpp +++ b/core/libs/tests/HostCpu.cpp @@ -19,10 +19,11 @@ static HostCpuRegisters Zen2() { HostCpuRegisters registers; registers.Leaf1Ecx = Bit(0) | Bit(1) | Bit(9) | Bit(12) | Bit(13) | Bit(19) | Bit(20) | Bit(22) | Bit(23) | Bit(25) | Bit(26) | Bit(27) | Bit(28) | Bit(29) | Bit(30); registers.Leaf1Edx = Bit(25) | Bit(26); - registers.Leaf7Ebx = Bit(3) | Bit(5) | Bit(8) | Bit(18) | Bit(19) | Bit(23) | Bit(24) | Bit(29); + registers.Leaf7Ebx = Bit(0) | Bit(3) | Bit(5) | Bit(8) | Bit(18) | Bit(19) | Bit(23) | Bit(24) | Bit(29); registers.Leaf7Ecx = Bit(22); - registers.LeafDSub1Eax = Bit(0) | Bit(1); + registers.LeafDSub1Eax = Bit(0) | Bit(1) | Bit(3); registers.Leaf80000001Ecx = Bit(0) | Bit(5) | Bit(6) | Bit(8); + registers.Leaf80000001Edx = Bit(27); registers.Leaf80000008Ebx = Bit(0); registers.Xcr0 = 0x7; return registers; @@ -46,18 +47,22 @@ static void CheckMissing(const HostCpuRegisters& registers, const std::vector= 0x50 && instruction.Opcode <= 0x53) + return HostCpuFeatureBits::AvxVnni; + if (instruction.Prefix != Prefix66 && instruction.Opcode >= 0x50 && instruction.Opcode <= 0x51) + return HostCpuFeatureBits::AvxVnniInt8; + if (instruction.Prefix == Prefix66 && instruction.Wide && (instruction.Opcode == 0xB4 || instruction.Opcode == 0xB5)) + return HostCpuFeatureBits::AvxIfma; + if (instruction.Opcode == 0xB0) return HostCpuFeatureBits::AvxNeConvert; + if (instruction.Opcode == 0xB1 && (instruction.Prefix == Prefix66 || instruction.Prefix == PrefixF3)) + return HostCpuFeatureBits::AvxNeConvert; + if (instruction.Opcode == 0x72 && instruction.Prefix == PrefixF3) + return HostCpuFeatureBits::AvxNeConvert; + } if (instruction.Map == Map0F38 && instruction.Prefix == Prefix66) { if ((instruction.Opcode >= 0x96 && instruction.Opcode <= 0x9F) || (instruction.Opcode >= 0xA6 && instruction.Opcode <= 0xAF) || @@ -134,6 +147,84 @@ std::uint64_t classifyVex(const Instruction& instruction) { return 0; } +std::uint64_t classifyLegacy(const std::uint8_t* data, const std::size_t length) { + std::size_t position = 0; + bool operandSize = false; + bool repeat = false; + bool repeatNot = false; + while (position < length) { + const std::uint8_t byte = data[position]; + if (byte == 0xF3) repeat = true; + if (byte == 0xF2) repeatNot = true; + if (byte == 0x66) operandSize = true; + if (!isLegacyPrefix(byte) && (byte < 0x40 || byte > 0x4F)) break; + ++position; + } + if (position + 1 >= length || data[position] != 0x0F) return 0; + const std::uint8_t first = data[position + 1]; + if (repeat && first == 0xBC) return HostCpuFeatureBits::Bmi1; + if (repeat && first == 0xBD) return HostCpuFeatureBits::Lzcnt; + + const bool plain = !operandSize && !repeat && !repeatNot; + if (first == 0x38 || first == 0x3A) { + if (position + 2 >= length) return 0; + const std::uint8_t opcode = data[position + 2]; + if (first == 0x38) { + if (!repeat && !repeatNot && (opcode == 0xF0 || opcode == 0xF1)) return HostCpuFeatureBits::Movbe; + if (plain && opcode >= 0xC8 && opcode <= 0xCD) return HostCpuFeatureBits::Sha; + if (operandSize && !repeat && !repeatNot) { + if (opcode >= 0xDB && opcode <= 0xDF) return HostCpuFeatureBits::Aes; + if (opcode == 0xF6) return HostCpuFeatureBits::Adx; + } + if (repeat && !repeatNot && opcode == 0xF6) return HostCpuFeatureBits::Adx; + return 0; + } + if (operandSize && !repeat && !repeatNot) { + if (opcode == 0x44) return HostCpuFeatureBits::Pclmul; + if (opcode == 0xDF) return HostCpuFeatureBits::Aes; + } + if (plain && opcode == 0xCC) return HostCpuFeatureBits::Sha; + return 0; + } + + if (position + 2 >= length) return 0; + const std::uint8_t modrm = data[position + 2]; + const unsigned reg = (modrm >> 3) & 7u; + const bool registerForm = (modrm >> 6) == 3; + if (first == 0xAE) { + if (operandSize && !repeat && !repeatNot) { + if (registerForm) return 0; + if (reg == 6) return HostCpuFeatureBits::Clwb; + if (reg == 7) return HostCpuFeatureBits::Clflushopt; + return 0; + } + if (plain) { + if (registerForm) return 0; + return reg == 6 ? HostCpuFeatureBits::Xsaveopt : 0; + } + if (repeat && !repeatNot && registerForm && reg <= 3) return HostCpuFeatureBits::Fsgsbase; + return 0; + } + if (first == 0xC7 && !repeatNot) { + if (registerForm) { + if (reg == 6) return HostCpuFeatureBits::Rdrand; + if (reg == 7) return repeat ? HostCpuFeatureBits::Rdpid : HostCpuFeatureBits::Rdseed; + return 0; + } + if (reg == 3 || reg == 5) return HostCpuFeatureBits::Xsaves; + return reg == 4 ? HostCpuFeatureBits::Xsavec : 0; + } + if (first == 0x01 && plain) { + if (modrm == 0xF9) return HostCpuFeatureBits::Rdtscp; + return modrm == 0xFC ? HostCpuFeatureBits::Clzero : 0; + } + if ((first == 0x78 || first == 0x79) && !repeat && (operandSize != repeatNot)) + return HostCpuFeatureBits::Sse4a; + if (first == 0x2B && !operandSize && (repeat != repeatNot)) + return HostCpuFeatureBits::Sse4a; + return 0; +} + } std::uint64_t RequiredHostCpuFeatures(const std::uint8_t* data, const std::size_t length) { @@ -151,25 +242,7 @@ std::uint64_t RequiredHostCpuFeatures(const std::uint8_t* data, const std::size_ return 0; } - std::size_t position = 0; - bool repeat = false; - bool repeatNot = false; - while (position < length) { - const std::uint8_t byte = data[position]; - if (byte == 0xF3) repeat = true; - if (byte == 0xF2) repeatNot = true; - if (!isLegacyPrefix(byte) && (byte < 0x40 || byte > 0x4F)) break; - ++position; - } - if (position + 1 >= length || data[position] != 0x0F) return 0; - const std::uint8_t first = data[position + 1]; - if (repeat && first == 0xBC) return HostCpuFeatureBits::Bmi1; - if (repeat && first == 0xBD) return HostCpuFeatureBits::Lzcnt; - if (first == 0x38 && !repeat && !repeatNot && position + 2 < length) { - const std::uint8_t second = data[position + 2]; - if (second == 0xF0 || second == 0xF1) return HostCpuFeatureBits::Movbe; - } - return 0; + return classifyLegacy(data, length); } } diff --git a/core/relinker/codegen/tests/HostCpuFeatureClassifierTests.cpp b/core/relinker/codegen/tests/HostCpuFeatureClassifierTests.cpp index a49eb94ba1d5..240c1387cafd 100644 --- a/core/relinker/codegen/tests/HostCpuFeatureClassifierTests.cpp +++ b/core/relinker/codegen/tests/HostCpuFeatureClassifierTests.cpp @@ -35,6 +35,7 @@ void TestLegacy() { Expect({0xF3, 0x0F, 0xBC, 0xC1}, HostCpuFeatureBits::Bmi1, "TZCNT"); Expect({0x0F, 0x38, 0xF0, 0x01}, HostCpuFeatureBits::Movbe, "MOVBE load"); Expect({0x0F, 0x38, 0xF1, 0x01}, HostCpuFeatureBits::Movbe, "MOVBE store"); + Expect({0x66, 0x0F, 0x38, 0xF0, 0x01}, HostCpuFeatureBits::Movbe, "MOVBE r16"); Expect({0xF2, 0x0F, 0x38, 0xF0, 0xC1}, 0, "CRC32 is not MOVBE"); Expect({0x66, 0x0F, 0x70, 0xC1, 0x1B}, 0, "PSHUFD"); Expect({0x90}, 0, "NOP"); @@ -110,10 +111,59 @@ void TestAvx2() { Expect({0xC4, 0xE2, 0x7D, 0x2B, 0xC1}, HostCpuFeatureBits::Avx2, "VPACKUSDW ymm"); } +void TestRetainedExtensions() { + Expect({0x66, 0x0F, 0x38, 0xDC, 0xC1}, HostCpuFeatureBits::Aes, "AESENC"); + Expect({0x66, 0x0F, 0x3A, 0xDF, 0xC1, 0x00}, HostCpuFeatureBits::Aes, "AESKEYGENASSIST"); + Expect({0x66, 0x0F, 0x3A, 0x44, 0xC1, 0x00}, HostCpuFeatureBits::Pclmul, "PCLMULQDQ"); + Expect({0x0F, 0x38, 0xC8, 0xC1}, HostCpuFeatureBits::Sha, "SHA1NEXTE"); + Expect({0x0F, 0x38, 0xCD, 0xC1}, HostCpuFeatureBits::Sha, "SHA256MSG2"); + Expect({0x0F, 0x3A, 0xCC, 0xC1, 0x00}, HostCpuFeatureBits::Sha, "SHA1RNDS4"); + Expect({0x66, 0x0F, 0x38, 0xF6, 0xC1}, HostCpuFeatureBits::Adx, "ADCX"); + Expect({0xF3, 0x0F, 0x38, 0xF6, 0xC1}, HostCpuFeatureBits::Adx, "ADOX"); + Expect({0x66, 0xF3, 0x0F, 0x38, 0xF6, 0xC1}, HostCpuFeatureBits::Adx, "ADOX r16"); + Expect({0x0F, 0xC7, 0xF0}, HostCpuFeatureBits::Rdrand, "RDRAND"); + Expect({0x66, 0x0F, 0xC7, 0xF0}, HostCpuFeatureBits::Rdrand, "RDRAND r16"); + Expect({0x0F, 0xC7, 0xF8}, HostCpuFeatureBits::Rdseed, "RDSEED"); + Expect({0x66, 0x0F, 0xC7, 0xF8}, HostCpuFeatureBits::Rdseed, "RDSEED r16"); + Expect({0xF3, 0x0F, 0xC7, 0xF8}, HostCpuFeatureBits::Rdpid, "RDPID"); + Expect({0x66, 0x0F, 0xAE, 0x38}, HostCpuFeatureBits::Clflushopt, "CLFLUSHOPT"); + Expect({0x66, 0x0F, 0xAE, 0x30}, HostCpuFeatureBits::Clwb, "CLWB"); + Expect({0x0F, 0xAE, 0x38}, 0, "CLFLUSH"); + Expect({0x0F, 0xAE, 0x30}, HostCpuFeatureBits::Xsaveopt, "XSAVEOPT"); + Expect({0x0F, 0xAE, 0xF0}, 0, "MFENCE"); + Expect({0x66, 0x0F, 0xAE, 0xF0}, 0, "MFENCE with an operand-size prefix"); + Expect({0x0F, 0xAE, 0xE8}, 0, "LFENCE"); + Expect({0x0F, 0xAE, 0xF8}, 0, "SFENCE"); + Expect({0x0F, 0xC7, 0x20}, HostCpuFeatureBits::Xsavec, "XSAVEC"); + Expect({0x66, 0x0F, 0xC7, 0x20}, HostCpuFeatureBits::Xsavec, "XSAVEC with an operand-size prefix"); + Expect({0x0F, 0xC7, 0x28}, HostCpuFeatureBits::Xsaves, "XSAVES"); + Expect({0xF3, 0x0F, 0xC7, 0x28}, HostCpuFeatureBits::Xsaves, "XSAVES with a rep prefix"); + Expect({0x0F, 0xC7, 0x18}, HostCpuFeatureBits::Xsaves, "XRSTORS"); + Expect({0xF3, 0x0F, 0xC7, 0x18}, HostCpuFeatureBits::Xsaves, "XRSTORS with a rep prefix"); + Expect({0x0F, 0xC7, 0x30}, 0, "VMPTRLD is not RDRAND"); + Expect({0x0F, 0xC7, 0x38}, 0, "VMPTRST is not RDSEED"); + Expect({0x0F, 0x01, 0xF9}, HostCpuFeatureBits::Rdtscp, "RDTSCP"); + Expect({0x0F, 0x01, 0xFC}, HostCpuFeatureBits::Clzero, "CLZERO"); + Expect({0xF3, 0x0F, 0xAE, 0xC0}, HostCpuFeatureBits::Fsgsbase, "RDFSBASE"); + Expect({0xF3, 0x0F, 0xAE, 0xD8}, HostCpuFeatureBits::Fsgsbase, "WRGSBASE"); + Expect({0x66, 0x0F, 0x78, 0xC0, 0x00, 0x00}, HostCpuFeatureBits::Sse4a, "EXTRQ"); + Expect({0xF2, 0x0F, 0x79, 0xC0}, HostCpuFeatureBits::Sse4a, "INSERTQ"); + Expect({0xF3, 0x0F, 0x2B, 0x00}, HostCpuFeatureBits::Sse4a, "MOVNTSS"); + Expect({0xF2, 0x0F, 0x2B, 0x00}, HostCpuFeatureBits::Sse4a, "MOVNTSD"); + Expect({0xF2, 0x0F, 0x38, 0xF0, 0xC1}, 0, "CRC32"); + Expect({0xC4, 0xE2, 0x71, 0x50, 0xC2}, HostCpuFeatureBits::AvxVnni, "VPDPBUSD xmm"); + Expect({0xC4, 0xE2, 0x75, 0x50, 0xC2}, HostCpuFeatureBits::AvxVnni, "VPDPBUSD ymm"); + Expect({0xC4, 0xE2, 0x73, 0x50, 0xC2}, HostCpuFeatureBits::AvxVnniInt8, "VPDPBSSD xmm"); + Expect({0xC4, 0xE2, 0xF1, 0xB4, 0xC2}, HostCpuFeatureBits::AvxIfma, "VPMADD52LUQ xmm"); + Expect({0xC4, 0xE2, 0x7A, 0x72, 0xC2}, HostCpuFeatureBits::AvxNeConvert, "VCVTNEPS2BF16 xmm"); + Expect({0xC4, 0xE2, 0x02, 0xB1, 0x00}, HostCpuFeatureBits::AvxNeConvert, "VBCSTNEBF162PS"); +} + } int main() { TestLegacy(); + TestRetainedExtensions(); TestBmi(); TestFmaAndF16c(); TestAvx(); diff --git a/core/relinker/relinker/tests/test_hostcpu_record.py b/core/relinker/relinker/tests/test_hostcpu_record.py index 75e08f3b8895..ab02ab33834c 100644 --- a/core/relinker/relinker/tests/test_hostcpu_record.py +++ b/core/relinker/relinker/tests/test_hostcpu_record.py @@ -11,9 +11,11 @@ PT_OS_HOSTCPU = 0x61000002 FMA = bytes.fromhex("c4 e2 71 98 c1") AVX2 = bytes.fromhex("c5 f5 fe c2") -TEXT = FMA + AVX2 + b"\x90\xc3" +RDSEED = bytes.fromhex("0f c7 f8") +TEXT = FMA + AVX2 + RDSEED + b"\x90\xc3" MAGIC = b"APS5HCP1" FMA_BIT = 1 << 5 +RDSEED_BIT = 1 << 8 def program_headers(elf): @@ -45,7 +47,7 @@ def check_linux(relinker, work): stored = linux[offset:offset + 16] assert stored[:8] == MAGIC, stored mask, = struct.unpack_from("