From 5078a609b6fbbc606cd64f1dd264b830dec3849b Mon Sep 17 00:00:00 2001 From: HugeFrog24 <62775760+HugeFrog24@users.noreply.github.com> Date: Sat, 17 Oct 2026 14:39:01 +0200 Subject: [PATCH] Find the chat flag mask by decoding instead of a fixed 0.34.5 offset The chat fix hooked libBootloader + 0x13f23b8, the chat-record builder on Sky 0.34.5 only. From 0.35.0 the builder moved to 0x1466d60 and that offset lands mid-function, where the hook was still installed. The builder assembles the record's flag byte (+0x14) bit by bit and never writes bits 5-7, and its callers pass an uninitialised stack record, so those bits carry stack garbage. ChatFlagFix finds the builder's mask `and wA, wA, #0xffffffe3` by data flow (the "chat" call, the flag byte read-modify-writes) and rewrites it to `and wA, wA, #0x3`, which gives the same bits 0-4 and clears 5-7, as the hook did. Registers and the flag offset are decoded, not pinned; anything but exactly one site, or an instruction that is no longer the expected one, is left unpatched. Found on 0.33.5 (Huawei) and 0.33.7 through 0.35.1; refused on 0.33.0 and 0.33.2, whose flag layout differs. Host tests: cmake -S app/src/test/cpp -B && cmake --build && ctest --test-dir . Set CHAT_FLAG_FIX_IMAGES to a ;-separated list of libBootloader.so paths to also scan real images. --- .../main/cpp/Core/ChatFlagFix/ChatFlagFix.h | 184 ++++++++++ .../Core/ChatFlagFix/ChatFlagFixInstall.cpp | 133 +++++++ .../cpp/Core/ChatFlagFix/ChatFlagFixInstall.h | 7 + app/src/main/cpp/main.cpp | 52 +-- app/src/test/cpp/CMakeLists.txt | 16 + app/src/test/cpp/ChatFlagFixFixtures.h | 63 ++++ app/src/test/cpp/ChatFlagFixTest.cpp | 342 ++++++++++++++++++ 7 files changed, 747 insertions(+), 50 deletions(-) create mode 100644 app/src/main/cpp/Core/ChatFlagFix/ChatFlagFix.h create mode 100644 app/src/main/cpp/Core/ChatFlagFix/ChatFlagFixInstall.cpp create mode 100644 app/src/main/cpp/Core/ChatFlagFix/ChatFlagFixInstall.h create mode 100644 app/src/test/cpp/CMakeLists.txt create mode 100644 app/src/test/cpp/ChatFlagFixFixtures.h create mode 100644 app/src/test/cpp/ChatFlagFixTest.cpp diff --git a/app/src/main/cpp/Core/ChatFlagFix/ChatFlagFix.h b/app/src/main/cpp/Core/ChatFlagFix/ChatFlagFix.h new file mode 100644 index 0000000..d631414 --- /dev/null +++ b/app/src/main/cpp/Core/ChatFlagFix/ChatFlagFix.h @@ -0,0 +1,184 @@ +#pragma once + +#include +#include +#include + +namespace ChatFlagFix { + +struct Site { + std::uintptr_t address = 0; + std::uint32_t original = 0; + std::uint32_t replacement = 0; + std::uint32_t flagOffset = 0; +}; + +enum class Decision { Write, AlreadyApplied, Foreign }; + +inline Decision Decide(std::uint32_t current, const Site &site) { + if (current == site.original) + return Decision::Write; + if (current == site.replacement) + return Decision::AlreadyApplied; + return Decision::Foreign; +} + +namespace Detail { + +constexpr std::uint32_t kAndClearBit1 = 0x121e7800u; +constexpr std::uint32_t kAndKeepBits5To7 = 0x121b7000u; +constexpr std::uint32_t kAndKeepBits0To1 = 0x12000400u; +constexpr int kLoadWindow = 4; +constexpr int kStepWindow = 4; +constexpr int kCallWindow = 6; +constexpr int kAddWindow = 12; +constexpr int kAdrpWindow = 5; + +inline std::uint32_t Rd(std::uint32_t w) { return w & 0x1fu; } +inline std::uint32_t Rn(std::uint32_t w) { return (w >> 5) & 0x1fu; } + +inline bool AndImmediate(std::uint32_t w, std::uint32_t base, std::uint32_t reg) { + return (w & 0xfffffc00u) == base && Rd(w) == reg && Rn(w) == reg; +} + +inline bool OrrShifted(std::uint32_t w, std::uint32_t reg, std::uint32_t shift) { + return (w & 0xffe0fc00u) == (0x2a000000u | (shift << 10)) && Rd(w) == reg && Rn(w) == reg; +} + +inline bool ByteAccess(std::uint32_t w, bool load, std::uint32_t ®, std::uint32_t &base, + std::uint32_t &offset) { + if ((w & 0xffc00000u) != (load ? 0x39400000u : 0x39000000u)) + return false; + reg = Rd(w); + base = Rn(w); + offset = (w >> 10) & 0xfffu; + return true; +} + +inline bool IsCall(std::uint32_t w) { return (w >> 26) == 0x25u; } + +inline std::uintptr_t AdrpTarget(std::uint32_t w, std::uintptr_t pc) { + std::int64_t page = (static_cast((w >> 5) & 0x7ffffu) << 2) | ((w >> 29) & 3u); + if (page & (std::int64_t{1} << 20)) + page -= std::int64_t{1} << 21; + return (pc & ~static_cast(0xfffu)) + static_cast(page * 4096); +} + +template +bool Word(Read &read, std::uintptr_t at, std::uint32_t &w) { + return read(at, &w, sizeof(w)); +} + +template +bool PassesChat(Read &read, std::uintptr_t call) { + for (int k = 1; k <= kAddWindow; ++k) { + std::uint32_t add = 0; + if (!Word(read, call - 4u * k, add)) + return false; + if ((add & 0xffc003ffu) != 0x91000021u) + continue; + for (int j = 1; j <= kAdrpWindow; ++j) { + const std::uintptr_t at = call - 4u * (k + j); + std::uint32_t adrp = 0; + if (!Word(read, at, adrp)) + return false; + if ((adrp & 0x9f00001fu) != 0x90000001u) + continue; + char text[5] = {}; + const std::uintptr_t string = AdrpTarget(adrp, at) + ((add >> 10) & 0xfffu); + return read(string, text, sizeof(text)) && std::memcmp(text, "chat", sizeof(text)) == 0; + } + return false; + } + return false; +} + +template +bool Candidate(Read &read, std::uintptr_t at, Site &out) { + std::uint32_t w = 0; + if (!Word(read, at, w) || (w & 0xfffffc00u) != kAndClearBit1 || Rd(w) != Rn(w)) + return false; + const std::uint32_t reg = Rd(w); + + std::uintptr_t load = 0; + std::uint32_t record = 0, offset = 0; + for (int k = 1; k <= kLoadWindow && load == 0; ++k) { + std::uint32_t x = 0, t = 0, n = 0, imm = 0; + if (!Word(read, at - 4u * k, x)) + return false; + if (ByteAccess(x, true, t, n, imm) && t == reg) { + load = at - 4u * k; + record = n; + offset = imm; + } + } + if (load == 0) + return false; + + std::uintptr_t cursor = at, site = 0; + for (int step = 0; step < 5; ++step) { + bool matched = false; + for (int k = 1; k <= kStepWindow && !matched; ++k) { + std::uint32_t x = 0, t = 0, n = 0, imm = 0; + if (!Word(read, cursor + 4u * k, x)) + return false; + switch (step) { + case 0: + matched = OrrShifted(x, reg, 1); + break; + case 1: + case 4: + matched = ByteAccess(x, false, t, n, imm) && t == reg && n == record && imm == offset; + break; + case 2: + matched = AndImmediate(x, kAndKeepBits5To7, reg); + break; + case 3: + matched = OrrShifted(x, reg, 2); + break; + } + if (matched) { + cursor += 4u * k; + if (step == 2) + site = cursor; + } + } + if (!matched) + return false; + } + + for (int k = 1; k <= kCallWindow; ++k) { + std::uint32_t x = 0; + if (!Word(read, load - 4u * k, x)) + return false; + if (!IsCall(x)) + continue; + std::uint32_t original = 0; + if (!PassesChat(read, load - 4u * k) || !Word(read, site, original)) + return false; + out.address = site; + out.original = original; + out.replacement = kAndKeepBits0To1 | (reg << 5) | reg; + out.flagOffset = offset; + return true; + } + return false; +} + +} + +template +int Find(Read &&read, std::uintptr_t begin, std::size_t size, Site &out) { + int found = 0; + for (std::size_t i = 0; i + 4 <= size; i += 4) { + std::uint32_t w = 0; + if (!Detail::Word(read, begin + i, w) || (w & 0xfffffc00u) != Detail::kAndClearBit1) + continue; + Site site; + if (Detail::Candidate(read, begin + i, site) && ++found == 1) + out = site; + } + return found; +} + +} diff --git a/app/src/main/cpp/Core/ChatFlagFix/ChatFlagFixInstall.cpp b/app/src/main/cpp/Core/ChatFlagFix/ChatFlagFixInstall.cpp new file mode 100644 index 0000000..f550288 --- /dev/null +++ b/app/src/main/cpp/Core/ChatFlagFix/ChatFlagFixInstall.cpp @@ -0,0 +1,133 @@ +#include "ChatFlagFixInstall.h" + +#include "ChatFlagFix.h" + +#include + +#include +#include +#include +#include + +#include "../Cipher/Cipher.h" +#include "../../include/misc/Logger.h" + +namespace { + +struct Range { + std::uintptr_t begin; + std::size_t size; + bool executable; +}; + +struct Search { + const char *libName; + std::uintptr_t base; + std::vector ranges; +}; + +bool EndsWith(const char *text, const char *suffix) { + const std::size_t a = std::strlen(text), b = std::strlen(suffix); + return a >= b && std::strcmp(text + a - b, suffix) == 0; +} + +int CollectRanges(dl_phdr_info *info, std::size_t, void *data) { + auto *search = static_cast(data); + if (info->dlpi_name == nullptr || !EndsWith(info->dlpi_name, search->libName)) + return 0; + search->base = info->dlpi_addr; + for (int i = 0; i < info->dlpi_phnum; ++i) { + const ElfW(Phdr) &ph = info->dlpi_phdr[i]; + if (ph.p_type != PT_LOAD || (ph.p_flags & PF_R) == 0) + continue; + search->ranges.push_back({info->dlpi_addr + ph.p_vaddr, static_cast(ph.p_filesz), + (ph.p_flags & PF_X) != 0}); + } + return 1; +} + +std::mutex g_installMutex; +bool g_finished = false; + +} + +namespace ChatFlagFix { + +bool Install(const char *libName) { + std::lock_guard lock(g_installMutex); + if (g_finished) + return true; + + Search search{libName, 0, {}}; + dl_iterate_phdr(CollectRanges, &search); + if (search.ranges.empty()) { + LOGD("Chat fix: %s not loaded yet", libName); + return false; + } + + auto read = [&search](std::uintptr_t at, void *out, std::size_t size) { + for (const Range &range : search.ranges) { + if (at >= range.begin && size <= range.size && at - range.begin <= range.size - size) { + std::memcpy(out, reinterpret_cast(at), size); + return true; + } + } + return false; + }; + + int found = 0; + Site site; + for (const Range &range : search.ranges) { + if (!range.executable) + continue; + Site candidate; + const int count = Find(read, range.begin, range.size, candidate); + if (count > 0 && found == 0) + site = candidate; + found += count; + } + + g_finished = true; + if (found != 1) { + LOGW("Chat fix: %d candidate sites in %s, not patching", found, libName); + return false; + } + + std::uint32_t current = 0; + if (!read(site.address, ¤t, sizeof(current))) { + LOGW("Chat fix: site %p unreadable, not patching", reinterpret_cast(site.address)); + return false; + } + + switch (Decide(current, site)) { + case Decision::AlreadyApplied: + LOGI("Chat fix: already applied at %p", reinterpret_cast(site.address)); + return true; + case Decision::Foreign: + LOGW("Chat fix: %p holds %08x, expected %08x, not patching", + reinterpret_cast(site.address), current, site.original); + return false; + case Decision::Write: + break; + } + + char hex[9] = {}; + const auto *bytes = reinterpret_cast(&site.replacement); + std::snprintf(hex, sizeof(hex), "%02x%02x%02x%02x", bytes[0], bytes[1], bytes[2], bytes[3]); + auto *patch = new CipherPatch(); + patch->set_Address(site.address, false); + patch->set_Opcode(hex); + patch->Fire(); + __builtin___clear_cache(reinterpret_cast(site.address), reinterpret_cast(site.address + 4)); + + std::uint32_t written = 0; + if (!read(site.address, &written, sizeof(written)) || written != site.replacement) { + LOGW("Chat fix: patch at %p did not take (%08x)", reinterpret_cast(site.address), written); + return false; + } + LOGI("Chat fix: flag mask patched at %p (RVA 0x%lx, flag byte +0x%x)", reinterpret_cast(site.address), + static_cast(site.address - search.base), site.flagOffset); + return true; +} + +} diff --git a/app/src/main/cpp/Core/ChatFlagFix/ChatFlagFixInstall.h b/app/src/main/cpp/Core/ChatFlagFix/ChatFlagFixInstall.h new file mode 100644 index 0000000..e97a3fd --- /dev/null +++ b/app/src/main/cpp/Core/ChatFlagFix/ChatFlagFixInstall.h @@ -0,0 +1,7 @@ +#pragma once + +namespace ChatFlagFix { + +bool Install(const char *libName); + +} diff --git a/app/src/main/cpp/main.cpp b/app/src/main/cpp/main.cpp index 16f1e36..0e28ffe 100644 --- a/app/src/main/cpp/main.cpp +++ b/app/src/main/cpp/main.cpp @@ -23,6 +23,7 @@ #include "fileselector/fileselector.h" #include #include "shadowhook.h" +#include "ChatFlagFix/ChatFlagFixInstall.h" extern "C" { #include "Core/ceserver/ceserver.h" @@ -217,57 +218,8 @@ PRIVATE_API void Canvas::CanvasMenu() { //SystemsTest(); } -// Chat Record Constructor Hook (Sky 0.34.5) to fix blue messages bug without breaking permissions -static void* (*orig_ChatRecordConstructor)(void*, void*, void*, void*, void*, void*, void*, void*) = nullptr; -static void* g_chatRecordStub = nullptr; - -static void* hooked_ChatRecordConstructor(void* self, void* a2, void* a3, void* a4, void* a5, void* a6, void* a7, void* a8) { - if (self != nullptr) { - // Strip only the broadcast/pending bits (0xE0) - // Preserve lower permission/channel bits (0x1F) - uint8_t* pFlags = (uint8_t*)self + 20; - *pFlags &= ~0xe0; - } - void* ret = orig_ChatRecordConstructor ? orig_ChatRecordConstructor(self, a2, a3, a4, a5, a6, a7, a8) : self; - if (self != nullptr) { - uint8_t* pFlags = (uint8_t*)self + 20; - *pFlags &= ~0xe0; - } - return ret; -} - static void install_chat_fix() { - if (g_chatRecordStub != nullptr) return; - - uintptr_t base = Canvas::findLib(Canvas::libName ? Canvas::libName : "libBootloader.so"); - if (base == 0) { - LOGD("libBootloader.so not loaded yet for chat fix"); - return; - } - - uintptr_t targetAddr = 0; - - // Try known version RVA (Sky 0.34.5) - const uintptr_t CHAT_RECORD_CONSTRUCTOR_RVA = 0x13f23b8; - targetAddr = base + CHAT_RECORD_CONSTRUCTOR_RVA; - - // Safety check: Ensure target address is 4-byte aligned (ARM64 requirement) - if ((targetAddr & 3) != 0) { - LOGW("Chat fix: Target address %p is misaligned, safely skipping hook", (void*)targetAddr); - return; - } - - g_chatRecordStub = shadowhook_hook_func_addr( - (void*)targetAddr, - (void*)hooked_ChatRecordConstructor, - (void**)&orig_ChatRecordConstructor - ); - if (g_chatRecordStub != nullptr) { - LOGI("Chat record constructor hook installed at %p (RVA 0x%lx)", (void*)targetAddr, targetAddr - base); - } else { - int err = shadowhook_get_errno(); - LOGW("Chat record constructor hook skipped (err %d: %s)", err, shadowhook_to_errmsg(err)); - } + ChatFlagFix::Install(Canvas::libName ? Canvas::libName : "libBootloader.so"); } __unused __attribute__((constructor)) diff --git a/app/src/test/cpp/CMakeLists.txt b/app/src/test/cpp/CMakeLists.txt new file mode 100644 index 0000000..a59f742 --- /dev/null +++ b/app/src/test/cpp/CMakeLists.txt @@ -0,0 +1,16 @@ +cmake_minimum_required(VERSION 3.18) + +project(canvas_native_tests CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +enable_testing() + +add_executable(chat_flag_fix_test ChatFlagFixTest.cpp) +target_include_directories(chat_flag_fix_test PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/../../main/cpp/Core) +target_compile_options(chat_flag_fix_test PRIVATE -Wall -Wextra -Werror) + +add_test(NAME chat_flag_fix_test COMMAND chat_flag_fix_test) diff --git a/app/src/test/cpp/ChatFlagFixFixtures.h b/app/src/test/cpp/ChatFlagFixFixtures.h new file mode 100644 index 0000000..d733c08 --- /dev/null +++ b/app/src/test/cpp/ChatFlagFixFixtures.h @@ -0,0 +1,63 @@ +#pragma once + +#include +#include + +namespace ChatFlagFixFixtures { + +struct Window { + std::uintptr_t codeBase; + const std::uint32_t *words; + std::size_t count; + std::uintptr_t stringAddress; + const char *string; +}; + +inline constexpr std::uint32_t k0_35_1Words[] = { + 0xd10203ffu, 0xa9027bfdu, 0xf9001bfbu, 0xa90467fau, 0xa9055ff8u, 0xa90657f6u, + 0xa9074ff4u, 0x910083fdu, 0x6f00e400u, 0xa9007c1fu, 0x9000e7dbu, 0xd10023a8u, + 0xb94a6369u, 0xaa0103f6u, 0xf9000fa8u, 0x910063a8u, 0xaa0003f3u, 0xf81f83a8u, + 0xaa0003f5u, 0x52970c08u, 0xb9001009u, 0x5281419au, 0x90ff87c1u, 0x910e2421u, + 0x3c825000u, 0xaa0403f4u, 0x3c835000u, 0xaa0303f8u, 0x72a0003au, 0x3c845000u, + 0x8b080079u, 0x3901541fu, 0xaa0203e0u, 0xaa0303e2u, 0x3c815ea0u, 0x942415feu, + 0x39405268u, 0x39404329u, 0x2a0003f7u, 0x121e7908u, 0x2a090508u, 0x39005268u, + 0x121b7108u, 0x39404329u, 0x390002bfu, 0x2a090908u, 0x39005268u, 0x78fa6b09u, +}; +inline const Window k0_35_1{0x1466d60u, k0_35_1Words, sizeof(k0_35_1Words) / sizeof(k0_35_1Words[0]), 0x55e389u, "chat"}; + +inline constexpr std::uint32_t k0_34_5Words[] = { + 0xd10203ffu, 0xa9027bfdu, 0xf9001bfbu, 0xa90467fau, 0xa9055ff8u, 0xa90657f6u, + 0xa9074ff4u, 0x910083fdu, 0x6f00e400u, 0xa9007c1fu, 0x9000e33bu, 0xd10023a8u, + 0xb94a8369u, 0xaa0103f6u, 0xf9000fa8u, 0x910063a8u, 0xaa0003f3u, 0xf81f83a8u, + 0xaa0003f5u, 0x52970808u, 0xb9001009u, 0x52813d9au, 0xb0ff8a21u, 0x91279421u, + 0x3c825000u, 0xaa0403f4u, 0x3c835000u, 0xaa0303f8u, 0x72a0003au, 0x3c845000u, + 0x8b080079u, 0x3901541fu, 0xaa0203e0u, 0xaa0303e2u, 0x3c815ea0u, 0x9422faa9u, + 0x39405268u, 0x39404329u, 0x2a0003f7u, 0x121e7908u, 0x2a090508u, 0x39005268u, + 0x121b7108u, 0x39404329u, 0x390002bfu, 0x2a090908u, 0x39005268u, 0x78fa6b09u, +}; +inline const Window k0_34_5{0x13f23b8u, k0_34_5Words, sizeof(k0_34_5Words) / sizeof(k0_34_5Words[0]), 0x5379e5u, "chat"}; + +inline constexpr std::uint32_t k0_34_3Words[] = { + 0xd10203ffu, 0xa9027bfdu, 0xf9001bfbu, 0xa90467fau, 0xa9055ff8u, 0xa90657f6u, + 0xa9074ff4u, 0x910083fdu, 0xa9007c1fu, 0xb000e09bu, 0xd10023a8u, 0xb94cf369u, + 0xaa0003f3u, 0xaa0103f5u, 0xf9000fa8u, 0x910063a8u, 0x5297080au, 0x52813d9au, + 0xb9001009u, 0xd0ff8ba1u, 0x9132e421u, 0xaa0203e0u, 0xaa0303e2u, 0xaa0403f4u, + 0xaa0303f8u, 0xf81f83a8u, 0x72a0003au, 0x8b0a0079u, 0x94228264u, 0x39405268u, + 0x39404329u, 0xaa1303f6u, 0x2a0003f7u, 0x121e7908u, 0x2a090508u, 0x39005268u, + 0x121b7108u, 0x39404329u, 0x38015edfu, 0x2a090908u, 0x39005268u, 0x78fa6b09u, + 0x37f80189u, +}; +inline const Window k0_34_3{0x13c1974u, k0_34_3Words, sizeof(k0_34_3Words) / sizeof(k0_34_3Words[0]), 0x537cb9u, "chat"}; + +inline constexpr std::uint32_t k0_33_0Words[] = { + 0xd101c3ffu, 0xa9027bfdu, 0xa90367fau, 0xa9045ff8u, 0xa90557f6u, 0xa9064ff4u, + 0x910083fdu, 0xa9007c1fu, 0xd000d7bau, 0x910043e8u, 0xb947b349u, 0xaa0103f4u, + 0xaa0003f3u, 0xf81f83a8u, 0xd10023a8u, 0x5296f80au, 0x52812b99u, 0xb9001009u, + 0xd0ff94c1u, 0x912d1c21u, 0xaa0203e0u, 0xaa0303e2u, 0xaa0303f7u, 0xf9000be8u, + 0x72a00039u, 0x8b0a0078u, 0x94212e2cu, 0x39405268u, 0x39404309u, 0xaa1303f6u, + 0x2a0003f5u, 0x121e7908u, 0x2a090508u, 0x39005268u, 0x121c7508u, 0x39404309u, + 0x38015edfu, 0x2a090908u, 0x39005268u, 0x78f96ae9u, +}; +inline const Window k0_33_0{0x123d530u, k0_33_0Words, sizeof(k0_33_0Words) / sizeof(k0_33_0Words[0]), 0x4d7b47u, "chat"}; + +} diff --git a/app/src/test/cpp/ChatFlagFixTest.cpp b/app/src/test/cpp/ChatFlagFixTest.cpp new file mode 100644 index 0000000..ecb1c9e --- /dev/null +++ b/app/src/test/cpp/ChatFlagFixTest.cpp @@ -0,0 +1,342 @@ +#include "ChatFlagFix/ChatFlagFix.h" +#include "ChatFlagFixFixtures.h" + +#include +#include +#include +#include +#include + +namespace { + +int g_failures = 0; + +void Check(bool condition, const char *what, int line) { + if (!condition) { + std::printf(" FAIL line %d: %s\n", line, what); + ++g_failures; + } +} + +#define CHECK(x) Check((x), #x, __LINE__) + +struct Region { + std::uintptr_t base; + std::vector bytes; +}; + +struct Memory { + std::vector regions; + + bool operator()(std::uintptr_t at, void *out, std::size_t size) const { + for (const Region &r : regions) { + if (at >= r.base && size <= r.bytes.size() && at - r.base <= r.bytes.size() - size) { + std::memcpy(out, r.bytes.data() + (at - r.base), size); + return true; + } + } + return false; + } + + void Put(std::uintptr_t base, const void *data, std::size_t size) { + Region r{base, {}}; + r.bytes.assign(static_cast(data), static_cast(data) + size); + regions.push_back(std::move(r)); + } + + void SetWord(std::uintptr_t at, std::uint32_t w) { + for (Region &r : regions) { + if (at >= r.base && at + 4 <= r.base + r.bytes.size()) { + std::memcpy(r.bytes.data() + (at - r.base), &w, 4); + return; + } + } + std::printf(" SetWord outside fixture at %#zx\n", static_cast(at)); + std::abort(); + } +}; + +Memory FromWindow(const ChatFlagFixFixtures::Window &w, std::uintptr_t shift = 0) { + Memory m; + m.Put(w.codeBase + shift, w.words, w.count * 4); + m.Put(w.stringAddress + shift, w.string, 5); + return m; +} + +int FindIn(const Memory &m, std::uintptr_t begin, std::size_t size, ChatFlagFix::Site &site) { + return ChatFlagFix::Find(m, begin, size, site); +} + +int FindInWindow(const Memory &m, const ChatFlagFixFixtures::Window &w, ChatFlagFix::Site &site) { + return FindIn(m, w.codeBase, w.count * 4, site); +} + +std::uint32_t Adrp(std::uint32_t rd, std::uintptr_t pc, std::uintptr_t target) { + const std::int64_t pages = static_cast(target >> 12) - static_cast(pc >> 12); + const std::uint32_t imm = static_cast(pages) & 0x1fffffu; + return 0x90000000u | ((imm & 3u) << 29) | ((imm >> 2) << 5) | rd; +} +std::uint32_t AddImm(std::uint32_t rd, std::uint32_t rn, std::uint32_t imm) { + return 0x91000000u | (imm << 10) | (rn << 5) | rd; +} +std::uint32_t Bl(std::int32_t words) { return 0x94000000u | (static_cast(words) & 0x3ffffffu); } +std::uint32_t Ldrb(std::uint32_t rt, std::uint32_t rn, std::uint32_t off) { + return 0x39400000u | (off << 10) | (rn << 5) | rt; +} +std::uint32_t Strb(std::uint32_t rt, std::uint32_t rn, std::uint32_t off) { + return 0x39000000u | (off << 10) | (rn << 5) | rt; +} +std::uint32_t AndFd(std::uint32_t r) { return 0x121e7800u | (r << 5) | r; } +std::uint32_t AndE3(std::uint32_t r) { return 0x121b7000u | (r << 5) | r; } +std::uint32_t OrrLsl(std::uint32_t rd, std::uint32_t rm, std::uint32_t shift) { + return 0x2a000000u | (rm << 16) | (shift << 10) | (rd << 5) | rd; +} +constexpr std::uint32_t kNop = 0xd503201fu; + +unsigned Builder(unsigned b, unsigned local, unsigned bit15, bool type5, int branch, bool check, unsigned flag, + unsigned secondMask) { + unsigned v = (b & 0xfdu) | (local << 1); + v = (v & secondMask) | (local << 2); + v = (v & 0xe6u) | bit15; + if (type5) + v |= 4u; + if (branch == 1) { + v |= 2u; + v = (v & 0xfbu) | (check ? 4u : 0u); + v = (v & 0xf7u) | (flag << 3); + } else if (branch == 2) { + v |= 0x10u; + } + return v & 0xffu; +} + +void FindsTheSiteInEveryAuditedBuild() { + struct Expect { + const ChatFlagFixFixtures::Window *window; + std::uintptr_t site; + }; + const Expect expects[] = { + {&ChatFlagFixFixtures::k0_35_1, 0x1466e08u}, + {&ChatFlagFixFixtures::k0_34_5, 0x13f2460u}, + {&ChatFlagFixFixtures::k0_34_3, 0x13c1a04u}, + }; + for (const Expect &e : expects) { + const Memory m = FromWindow(*e.window); + ChatFlagFix::Site site; + CHECK(FindInWindow(m, *e.window, site) == 1); + CHECK(site.address == e.site); + CHECK(site.original == 0x121b7108u); + CHECK(site.replacement == 0x12000508u); + CHECK(site.flagOffset == 0x14u); + } +} + +void RefusesTheOlderFlagLayout() { + const Memory m = FromWindow(ChatFlagFixFixtures::k0_33_0); + ChatFlagFix::Site site; + CHECK(FindInWindow(m, ChatFlagFixFixtures::k0_33_0, site) == 0); +} + +void RefusesWhenTheCallIsNotPassedChat() { + const auto &w = ChatFlagFixFixtures::k0_35_1; + Memory m; + m.Put(w.codeBase, w.words, w.count * 4); + m.Put(w.stringAddress, "chaX", 5); + ChatFlagFix::Site site; + CHECK(FindInWindow(m, w, site) == 0); +} + +void RefusesWhenTheStringIsUnreadable() { + const auto &w = ChatFlagFixFixtures::k0_35_1; + Memory m; + m.Put(w.codeBase, w.words, w.count * 4); + ChatFlagFix::Site site; + CHECK(FindInWindow(m, w, site) == 0); +} + +void RefusesWhenAStoreTargetsAnotherByte() { + const auto &w = ChatFlagFixFixtures::k0_35_1; + Memory m = FromWindow(w); + m.SetWord(0x1466e18u, Strb(8, 19, 0x15)); + ChatFlagFix::Site site; + CHECK(FindInWindow(m, w, site) == 0); +} + +void RefusesWhenTheSecondMaskDiffers() { + const auto &w = ChatFlagFixFixtures::k0_35_1; + Memory m = FromWindow(w); + m.SetWord(0x1466e08u, 0x121c7508u); + ChatFlagFix::Site site; + CHECK(FindInWindow(m, w, site) == 0); +} + +void CountsEverySiteSoTheCallerCanRefuseTwo() { + const auto &w = ChatFlagFixFixtures::k0_35_1; + const std::uintptr_t shift = 0x1000u; + Memory m; + std::vector code(shift + w.count * 4, 0); + std::memcpy(code.data(), w.words, w.count * 4); + std::memcpy(code.data() + shift, w.words, w.count * 4); + m.Put(w.codeBase, code.data(), code.size()); + m.Put(w.stringAddress, w.string, 5); + m.Put(w.stringAddress + shift, w.string, 5); + ChatFlagFix::Site site; + CHECK(FindIn(m, w.codeBase, code.size(), site) == 2); + CHECK(site.address == 0x1466e08u); +} + +void DecodesRegistersAndOffsetInsteadOfPinningThem() { + const std::uintptr_t base = 0x400000u, string = 0x123456u; + const std::uint32_t a = 10, b = 21, c = 9, off = 0x18; + std::vector words = { + Adrp(1, base + 0, string), + AddImm(1, 1, static_cast(string & 0xfffu)), + kNop, + Bl(0x100), + Ldrb(a, b, off), + kNop, + AndFd(a), + OrrLsl(a, c, 1), + Strb(a, b, off), + AndE3(a), + kNop, + OrrLsl(a, c, 2), + Strb(a, b, off), + }; + Memory m; + m.Put(base, words.data(), words.size() * 4); + m.Put(string, "chat", 5); + ChatFlagFix::Site site; + CHECK(FindIn(m, base, words.size() * 4, site) == 1); + CHECK(site.address == base + 9 * 4); + CHECK(site.original == AndE3(a)); + CHECK(site.replacement == (0x12000400u | (a << 5) | a)); + CHECK(site.flagOffset == off); +} + +void DecidesWhetherToWrite() { + ChatFlagFix::Site site; + site.original = 0x121b7108u; + site.replacement = 0x12000508u; + CHECK(ChatFlagFix::Decide(0x121b7108u, site) == ChatFlagFix::Decision::Write); + CHECK(ChatFlagFix::Decide(0x12000508u, site) == ChatFlagFix::Decision::AlreadyApplied); + CHECK(ChatFlagFix::Decide(0xd503201fu, site) == ChatFlagFix::Decision::Foreign); +} + +void PatchMatchesClearingBits5To7AroundTheBuilder() { + int mismatches = 0, dirty = 0; + for (unsigned b = 0; b < 256; ++b) + for (unsigned local = 0; local < 2; ++local) + for (unsigned bit15 = 0; bit15 < 2; ++bit15) + for (int type5 = 0; type5 < 2; ++type5) + for (int branch = 0; branch < 3; ++branch) + for (int check = 0; check < 2; ++check) + for (unsigned flag = 0; flag < 2; ++flag) { + const unsigned shipped = Builder(b, local, bit15, type5, branch, check, flag, 0xe3u); + const unsigned hooked = + Builder(b & 0x1fu, local, bit15, type5, branch, check, flag, 0xe3u) & 0x1fu; + const unsigned patched = Builder(b, local, bit15, type5, branch, check, flag, 0x03u); + dirty += (shipped & 0xe0u) != 0; + mismatches += patched != hooked || patched != (shipped & 0x1fu); + } + CHECK(dirty > 0); + CHECK(mismatches == 0); +} + +bool LoadImage(const std::string &path, Memory &m, std::vector> &code) { + FILE *f = std::fopen(path.c_str(), "rb"); + if (!f) + return false; + std::fseek(f, 0, SEEK_END); + const long length = std::ftell(f); + std::fseek(f, 0, SEEK_SET); + std::vector data(static_cast(length)); + const bool ok = std::fread(data.data(), 1, data.size(), f) == data.size(); + std::fclose(f); + if (!ok || data.size() < 64) + return false; + std::uint64_t phoff = 0; + std::uint16_t phentsize = 0, phnum = 0; + std::memcpy(&phoff, &data[0x20], 8); + std::memcpy(&phentsize, &data[0x36], 2); + std::memcpy(&phnum, &data[0x38], 2); + for (unsigned i = 0; i < phnum; ++i) { + const unsigned char *p = &data[phoff + i * phentsize]; + std::uint32_t type = 0, flags = 0; + std::uint64_t offset = 0, vaddr = 0, filesz = 0; + std::memcpy(&type, p, 4); + std::memcpy(&flags, p + 4, 4); + std::memcpy(&offset, p + 8, 8); + std::memcpy(&vaddr, p + 16, 8); + std::memcpy(&filesz, p + 32, 8); + if (type != 1) + continue; + m.Put(static_cast(vaddr), data.data() + offset, static_cast(filesz)); + if (flags & 1u) + code.emplace_back(static_cast(vaddr), static_cast(filesz)); + } + return true; +} + +void FindsExactlyOneSiteInListedImages() { + const char *list = std::getenv("CHAT_FLAG_FIX_IMAGES"); + if (!list || !*list) { + std::printf(" (CHAT_FLAG_FIX_IMAGES not set, image check skipped)\n"); + return; + } + std::string paths(list); + std::size_t start = 0; + while (start <= paths.size()) { + const std::size_t end = paths.find(';', start); + const std::string path = paths.substr(start, end == std::string::npos ? std::string::npos : end - start); + start = end == std::string::npos ? paths.size() + 1 : end + 1; + if (path.empty()) + continue; + Memory m; + std::vector> code; + const bool loaded = LoadImage(path, m, code); + CHECK(loaded); + int found = 0; + ChatFlagFix::Site first; + for (const auto &range : code) { + ChatFlagFix::Site site; + const int n = FindIn(m, range.first, range.second, site); + if (n > 0 && found == 0) + first = site; + found += n; + } + std::printf(" %s: %d site(s), first at %#zx\n", path.c_str(), found, static_cast(first.address)); + CHECK(found == 1); + CHECK(first.flagOffset == 0x14u); + } +} + +} + +int main() { + std::setvbuf(stdout, nullptr, _IONBF, 0); + struct Case { + const char *name; + void (*run)(); + }; + const Case cases[] = { + {"finds_the_site_in_every_audited_build", FindsTheSiteInEveryAuditedBuild}, + {"refuses_the_older_flag_layout", RefusesTheOlderFlagLayout}, + {"refuses_when_the_call_is_not_passed_chat", RefusesWhenTheCallIsNotPassedChat}, + {"refuses_when_the_string_is_unreadable", RefusesWhenTheStringIsUnreadable}, + {"refuses_when_a_store_targets_another_byte", RefusesWhenAStoreTargetsAnotherByte}, + {"refuses_when_the_second_mask_differs", RefusesWhenTheSecondMaskDiffers}, + {"counts_every_site_so_the_caller_can_refuse_two", CountsEverySiteSoTheCallerCanRefuseTwo}, + {"decodes_registers_and_offset_instead_of_pinning_them", DecodesRegistersAndOffsetInsteadOfPinningThem}, + {"decides_whether_to_write", DecidesWhetherToWrite}, + {"patch_matches_clearing_bits_5_to_7_around_the_builder", PatchMatchesClearingBits5To7AroundTheBuilder}, + {"finds_exactly_one_site_in_listed_images", FindsExactlyOneSiteInListedImages}, + }; + for (const Case &c : cases) { + const int before = g_failures; + c.run(); + std::printf("%s %s\n", g_failures == before ? "ok " : "FAIL", c.name); + } + std::printf("%d failure(s)\n", g_failures); + return g_failures == 0 ? 0 : 1; +}