├── .gitignore ├── tests ├── lib │ ├── main.cpp │ └── CMakeLists.txt ├── main.cpp ├── signature.test.cpp ├── module.test.cpp ├── page.test.cpp ├── address.test.cpp ├── CMakeLists.txt ├── hook.test.cpp └── instruction.test.cpp ├── include └── lime │ ├── address.inl │ ├── hooks │ ├── convention.hpp │ ├── hook.inl │ ├── convention.inl │ └── hook.hpp │ ├── entrypoint.hpp │ ├── utils │ └── signature.hpp │ ├── address.hpp │ ├── module.hpp │ ├── page.hpp │ └── instruction.hpp ├── cmake ├── mingw-x86.cmake ├── mingw-x64.cmake ├── proxy.cpp.in ├── proxy.cmake └── cpm.cmake ├── private ├── module.linux.impl.hpp ├── constants.hpp └── disasm.hpp ├── LICENSE ├── .clang-tidy ├── .github └── workflows │ └── test.yml ├── README.md ├── src ├── address.cpp ├── module.linux.impl.cpp ├── module.linux.cpp ├── instruction.cpp ├── disasm.cpp ├── utils.signature.cpp ├── module.win.cpp ├── page.linux.cpp ├── page.win.cpp └── hooks.hook.cpp ├── .clang-format └── CMakeLists.txt /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | build 3 | -------------------------------------------------------------------------------- /tests/lib/main.cpp: -------------------------------------------------------------------------------- 1 | extern "C" 2 | { 3 | int lime_demo_export(int num) 4 | { 5 | return num + 10; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /tests/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | return boost::ut::cfg.run(); 6 | } 7 | -------------------------------------------------------------------------------- /include/lime/address.inl: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "address.hpp" 4 | 5 | namespace lime 6 | { 7 | template 8 | bool address::write(const T &value) 9 | { 10 | return write(reinterpret_cast(&value), sizeof(T)); 11 | } 12 | 13 | template 14 | [[nodiscard]] T address::read() 15 | { 16 | return *reinterpret_cast(ptr()); 17 | } 18 | } // namespace lime 19 | -------------------------------------------------------------------------------- /include/lime/hooks/convention.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace lime 4 | { 5 | enum class convention 6 | { 7 | automatic, 8 | c_cdecl, 9 | c_stdcall, 10 | c_fastcall, 11 | c_thiscall, 12 | }; 13 | 14 | namespace detail 15 | { 16 | template 17 | struct calling_convention; 18 | }; 19 | } // namespace lime 20 | 21 | #include "convention.inl" 22 | -------------------------------------------------------------------------------- /cmake/mingw-x86.cmake: -------------------------------------------------------------------------------- 1 | set(CMAKE_SYSTEM_NAME Windows) 2 | 3 | add_compile_definitions(-DNTDDI_VERSION=0x0A000005) 4 | 5 | set(CMAKE_C_COMPILER i686-w64-mingw32-gcc) 6 | set(CMAKE_CXX_COMPILER i686-w64-mingw32-c++) 7 | 8 | set(CMAKE_CXX_FLAGS "-static") 9 | set(CMAKE_FIND_ROOT_PATH "/usr/i686-w64-mingw32/") 10 | 11 | set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) 12 | 13 | set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) 14 | set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) 15 | -------------------------------------------------------------------------------- /cmake/mingw-x64.cmake: -------------------------------------------------------------------------------- 1 | set(CMAKE_SYSTEM_NAME Windows) 2 | 3 | add_compile_definitions(-DNTDDI_VERSION=0x0A000005) 4 | 5 | set(CMAKE_C_COMPILER x86_64-w64-mingw32-gcc) 6 | set(CMAKE_CXX_COMPILER x86_64-w64-mingw32-c++) 7 | 8 | set(CMAKE_CXX_FLAGS "-static") 9 | set(CMAKE_FIND_ROOT_PATH "/usr/x86_64-w64-mingw32/") 10 | 11 | set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) 12 | 13 | set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) 14 | set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) 15 | -------------------------------------------------------------------------------- /private/module.linux.impl.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "module.hpp" 4 | 5 | #include 6 | #include 7 | 8 | #include 9 | #include 10 | 11 | namespace lime 12 | { 13 | struct module::impl 14 | { 15 | void *handle; 16 | dl_phdr_info info; 17 | 18 | public: 19 | void iterate_symbols(const std::function &) const; 20 | 21 | public: 22 | static std::uint32_t gnu_symbol_count(ElfW(Addr)); 23 | }; 24 | } // namespace lime 25 | -------------------------------------------------------------------------------- /private/constants.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | namespace lime 7 | { 8 | enum class architecture 9 | { 10 | x86, 11 | x64, 12 | }; 13 | 14 | static constexpr inline architecture arch = (sizeof(std::uintptr_t)) == 8 ? architecture::x64 : architecture::x86; 15 | static constexpr inline auto max_instruction_size = 0x15; 16 | 17 | enum size : std::size_t 18 | { 19 | jmp_near = sizeof(std::int32_t) + 1, 20 | jmp_far = arch == architecture::x86 ? jmp_near : sizeof(std::uintptr_t) + 6, 21 | }; 22 | } // namespace lime 23 | -------------------------------------------------------------------------------- /private/disasm.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | namespace lime 8 | { 9 | struct imm; 10 | struct disp; 11 | } // namespace lime 12 | 13 | namespace lime::disasm 14 | { 15 | bool valid(std::uintptr_t); 16 | bool relative(std::uintptr_t); 17 | bool branching(std::uintptr_t); 18 | 19 | std::size_t size(std::uintptr_t); 20 | std::size_t mnemonic(std::uintptr_t); 21 | 22 | disp displacement(std::uintptr_t); 23 | std::vector immediates(std::uintptr_t); 24 | std::optional follow(std::uintptr_t address, std::optional = std::nullopt); 25 | } // namespace lime::disasm 26 | -------------------------------------------------------------------------------- /tests/signature.test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace boost::ut; 5 | using namespace boost::ut::literals; 6 | 7 | struct impl 8 | { 9 | std::string mask; 10 | std::string pattern; 11 | }; 12 | 13 | suite<"Signature"> signature_suite = [] 14 | { 15 | const auto *ida_signature = "0F 2F 05 D8 20 ?? 03 72 41"; 16 | const auto *code_pattern = "\x0F\x2F\x05\xD8\x20\x00\x03\x72\x41"; 17 | const auto *code_mask = "xxxxx?xxx"; 18 | 19 | auto ida_sig = lime::signature::from(ida_signature); 20 | auto code_sig = lime::signature::from(code_pattern, code_mask); 21 | 22 | auto &ida_impl = *reinterpret_cast *>(&ida_sig); 23 | auto &code_impl = *reinterpret_cast *>(&code_sig); 24 | 25 | expect(eq(ida_impl->mask, code_impl->mask)); 26 | expect(eq(ida_impl->pattern, code_impl->pattern)); 27 | }; 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Curve 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /tests/lib/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.16) 2 | project(lime-shared-lib LANGUAGES CXX) 3 | 4 | # -------------------------------------------------------------------------------------------------------- 5 | # Create executable 6 | # -------------------------------------------------------------------------------------------------------- 7 | 8 | add_library(${PROJECT_NAME} SHARED) 9 | target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_20) 10 | 11 | set_target_properties(${PROJECT_NAME} PROPERTIES PREFIX "") 12 | set_target_properties(${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/tests") 13 | set_target_properties(${PROJECT_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/tests") 14 | set_target_properties(${PROJECT_NAME} PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS ON CXX_VISIBILITY_PRESET default) 15 | set_target_properties(${PROJECT_NAME} PROPERTIES CXX_STANDARD 20 CXX_EXTENSIONS OFF CXX_STANDARD_REQUIRED ON) 16 | 17 | # -------------------------------------------------------------------------------------------------------- 18 | # Add Sources 19 | # -------------------------------------------------------------------------------------------------------- 20 | 21 | target_sources(${PROJECT_NAME} PRIVATE "main.cpp") 22 | -------------------------------------------------------------------------------- /cmake/proxy.cpp.in: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define LIME_MAP_EXPORTS(TRANSFORMER) @MAP_EXPORTS@ 4 | 5 | namespace lime::proxy 6 | { 7 | namespace detail 8 | { 9 | inline std::uintptr_t originals[@EXPORT_COUNT@] = {}; 10 | } // namespace detail 11 | 12 | inline bool setup(std::string_view path) 13 | { 14 | auto original = lime::module::load(path); 15 | 16 | if (!original) 17 | { 18 | return false; 19 | } 20 | 21 | #define LIME_LOAD_ORIGINAL(index, name) detail::originals[(index)-1] = original->symbol(name); 22 | LIME_MAP_EXPORTS(LIME_LOAD_ORIGINAL) 23 | #undef LIME_LOAD_ORIGINAL 24 | 25 | return true; 26 | } 27 | } // namespace lime::proxy 28 | 29 | #define LIME_EXPORT_FUNC(index, name) \ 30 | extern "C" __attribute__((naked, stdcall)) void LIME_PROXY_EXPORT_##index() \ 31 | { \ 32 | asm volatile("jmp *%0" : : "r"(lime::proxy::detail::originals[(index)-1])); \ 33 | } 34 | 35 | LIME_MAP_EXPORTS(LIME_EXPORT_FUNC) 36 | 37 | #undef LIME_EXPORT_FUNC 38 | #undef LIME_MAP_EXPORTS 39 | -------------------------------------------------------------------------------- /include/lime/entrypoint.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace lime 4 | { 5 | extern void load(); 6 | extern void unload(); 7 | } // namespace lime 8 | 9 | #if LIME_STATIC_ENTRYPOINT 10 | #include 11 | 12 | // NOLINTNEXTLINE(cert-err58-cpp, *-namespace) 13 | [[maybe_unused]] static auto constructor = []() 14 | { 15 | lime::load(); 16 | return 1; 17 | }(); 18 | 19 | // NOLINTNEXTLINE(cert-err58-cpp, *-namespace) 20 | [[maybe_unused]] static auto destructor = []() 21 | { 22 | return std::shared_ptr(new char, 23 | [](auto *data) 24 | { 25 | lime::unload(); 26 | delete data; 27 | }); 28 | }(); 29 | #elif defined(WIN32) || defined(_WIN32) 30 | #include 31 | 32 | BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID reserved) 33 | { 34 | if (reason == DLL_PROCESS_ATTACH) 35 | { 36 | lime::load(); 37 | } 38 | 39 | if (reason == DLL_PROCESS_DETACH) 40 | { 41 | if (reserved) 42 | { 43 | return TRUE; 44 | } 45 | 46 | lime::unload(); 47 | } 48 | 49 | return TRUE; 50 | } 51 | #else 52 | void __attribute__((constructor)) constructor() 53 | { 54 | lime::load(); 55 | } 56 | 57 | void __attribute__((destructor)) destructor() 58 | { 59 | lime::unload(); 60 | } 61 | #endif 62 | -------------------------------------------------------------------------------- /include/lime/utils/signature.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "../page.hpp" 4 | #include "../module.hpp" 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | #include 11 | #include 12 | 13 | namespace lime 14 | { 15 | enum class find_policy 16 | { 17 | all, 18 | one, 19 | }; 20 | 21 | class signature 22 | { 23 | struct impl; 24 | 25 | private: 26 | std::unique_ptr m_impl; 27 | 28 | private: 29 | signature(); 30 | 31 | public: 32 | ~signature(); 33 | 34 | public: 35 | signature(const signature &); 36 | signature(signature &&) noexcept; 37 | 38 | public: 39 | [[nodiscard]] std::optional find() const; 40 | [[nodiscard]] std::optional find(const page &) const; 41 | [[nodiscard]] std::optional find(const module &) const; 42 | 43 | public: 44 | [[nodiscard]] std::vector find_all() const; 45 | [[nodiscard]] std::vector find_all(const page &) const; 46 | [[nodiscard]] std::vector find_all(const module &) const; 47 | 48 | public: 49 | static signature from(std::string_view ida_pattern, protection required = protection::read); 50 | static signature from(const char *pattern, std::string mask, protection required = protection::read); 51 | }; 52 | } // namespace lime 53 | -------------------------------------------------------------------------------- /include/lime/address.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | #include 7 | #include 8 | 9 | namespace lime 10 | { 11 | class address 12 | { 13 | struct impl; 14 | 15 | private: 16 | std::unique_ptr m_impl; 17 | 18 | private: 19 | address(); 20 | 21 | public: 22 | ~address(); 23 | 24 | public: 25 | address(const address &); 26 | address(address &&) noexcept; 27 | 28 | public: 29 | bool write(const void *data, std::size_t size); 30 | [[nodiscard]] std::vector copy(std::size_t size); 31 | 32 | public: 33 | template 34 | bool write(const T &value); 35 | 36 | public: 37 | template 38 | [[nodiscard]] T read(); 39 | 40 | public: 41 | [[nodiscard]] void *ptr() const; 42 | [[nodiscard]] std::uintptr_t addr() const; 43 | 44 | public: 45 | [[nodiscard]] std::optional
operator-(std::size_t) const; 46 | [[nodiscard]] std::optional
operator+(std::size_t) const; 47 | 48 | public: 49 | [[nodiscard]] std::strong_ordering operator<=>(const address &) const; 50 | 51 | public: 52 | [[nodiscard]] static address unsafe(std::uintptr_t address); 53 | [[nodiscard]] static std::optional
at(std::uintptr_t address); 54 | }; 55 | } // namespace lime 56 | 57 | #include "address.inl" 58 | -------------------------------------------------------------------------------- /include/lime/module.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | #include 7 | #include 8 | 9 | #include 10 | #include 11 | 12 | namespace lime 13 | { 14 | struct symbol 15 | { 16 | std::string name; 17 | std::uintptr_t address; 18 | }; 19 | 20 | class module 21 | { 22 | struct impl; 23 | 24 | private: 25 | std::unique_ptr m_impl; 26 | 27 | private: 28 | module(); 29 | 30 | public: 31 | ~module(); 32 | 33 | public: 34 | module(const module &); 35 | module(module &&) noexcept; 36 | 37 | public: 38 | [[nodiscard]] std::string_view name() const; 39 | 40 | public: 41 | [[nodiscard]] std::size_t size() const; 42 | 43 | public: 44 | [[nodiscard]] std::uintptr_t end() const; 45 | [[nodiscard]] std::uintptr_t start() const; 46 | 47 | public: 48 | [[nodiscard]] std::vector symbols() const; 49 | 50 | public: 51 | [[nodiscard]] std::uintptr_t symbol(std::string_view name) const; 52 | [[nodiscard]] std::optional find_symbol(std::string_view name) const; 53 | 54 | public: 55 | [[nodiscard]] static std::vector modules(); 56 | 57 | public: 58 | [[nodiscard]] static std::optional get(std::string_view name); 59 | [[nodiscard]] static std::optional load(std::string_view name); 60 | 61 | public: 62 | [[nodiscard]] static std::optional find(std::string_view name); 63 | }; 64 | } // namespace lime 65 | -------------------------------------------------------------------------------- /cmake/proxy.cmake: -------------------------------------------------------------------------------- 1 | function(lime_mingw_generate_proxy TARGET DEFINITIONS) 2 | message(STATUS "[lime] Generating Proxy for \"${TARGET}\"") 3 | 4 | if (NOT WIN32) 5 | message(WARNING "[lime] Proxy-Generation is only supported on windows!") 6 | message(WARNING "[lime] You might be interested in ld preload for unix") 7 | endif() 8 | 9 | file(STRINGS ${DEFINITIONS} DEFS) 10 | set(MAP_EXPORTS "") 11 | 12 | set(SOURCE_DIR "${CMAKE_BINARY_DIR}/lime") 13 | file(MAKE_DIRECTORY ${SOURCE_DIR}) 14 | 15 | set(DEF_FILE "${SOURCE_DIR}/exports.def") 16 | set(SRC_FILE "${SOURCE_DIR}/exports.hpp") 17 | 18 | file(REMOVE ${DEF_FILE}) 19 | file(REMOVE ${SRC_FILE}) 20 | 21 | file(APPEND ${DEF_FILE} "EXPORTS\n") 22 | 23 | foreach(entry ${DEFS}) 24 | string(REGEX MATCH "=([0-9]+)$" ORDINAL_MATCH ${entry}) 25 | 26 | list(FIND DEFS "${entry}" CURRENT_INDEX) 27 | MATH(EXPR CURRENT_INDEX "${CURRENT_INDEX}+1") 28 | 29 | string(REGEX REPLACE "=([0-9]+)$" "" entry ${entry}) 30 | 31 | if (NOT CMAKE_MATCH_1) 32 | set(CURRENT_ORDINAL ${CURRENT_INDEX}) 33 | else() 34 | set(CURRENT_ORDINAL ${CMAKE_MATCH_1}) 35 | endif() 36 | 37 | file(APPEND ${DEF_FILE} "\t${entry} = LIME_PROXY_EXPORT_${CURRENT_INDEX} @${CURRENT_ORDINAL}\n") 38 | string(APPEND MAP_EXPORTS " \\\n\tTRANSFORMER(${CURRENT_INDEX}, \"${entry}\")") 39 | endforeach() 40 | 41 | list(LENGTH DEFS EXPORT_COUNT) 42 | configure_file("${CMAKE_CURRENT_FUNCTION_LIST_DIR}/proxy.cpp.in" ${SRC_FILE}) 43 | 44 | target_sources(${TARGET} PUBLIC ${DEF_FILE}) 45 | target_include_directories(${TARGET} PUBLIC ${SOURCE_DIR}) 46 | endfunction() 47 | -------------------------------------------------------------------------------- /tests/module.test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #if defined(WIN32) || defined(_WIN32) 6 | #include 7 | #endif 8 | 9 | using namespace boost::ut; 10 | using namespace boost::ut::literals; 11 | 12 | namespace fs = std::filesystem; 13 | 14 | fs::path find_library() 15 | { 16 | #if defined(WIN32) || defined(_WIN32) 17 | char path[MAX_PATH]; 18 | GetModuleFileNameA(nullptr, path, sizeof(path)); 19 | 20 | return fs::path{path}.parent_path() / "lime-shared-lib.dll"; 21 | #else 22 | const auto self = fs::canonical("/proc/self/exe").parent_path(); 23 | return self / "lime-shared-lib.so"; 24 | #endif 25 | } 26 | 27 | suite<"Module"> module_suite = [] 28 | { 29 | expect(eq(lime::module::find("lime-shared-lib").has_value(), false)); 30 | 31 | const auto path = find_library().string(); 32 | 33 | auto loaded = lime::module::load(path); 34 | expect(eq(loaded.has_value(), true)); 35 | 36 | auto test = lime::module::find("lime-shared-lib"); 37 | expect(eq(test.has_value(), true)); 38 | 39 | #if defined(WIN32) || defined(_WIN32) 40 | auto case_test = lime::module::find("LIME-SHARED-LIB"); 41 | expect(eq(case_test.has_value(), true)); 42 | #endif 43 | 44 | expect(test->name().find("lime-shared") != std::string_view::npos); 45 | 46 | expect(test->symbols().size() >= 1); 47 | expect(test->size() > 0); 48 | 49 | expect(eq(test->find_symbol("lime_demo").has_value(), true)); 50 | expect(test->symbol("lime_demo_export") > 0); 51 | 52 | expect(test->start() > 0); 53 | expect(test->end() > 0); 54 | 55 | using demo_export_t = int (*)(int); 56 | auto demo_export = reinterpret_cast(test->symbol("lime_demo_export")); 57 | 58 | expect(eq(demo_export(10), 20)); 59 | }; 60 | -------------------------------------------------------------------------------- /tests/page.test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace boost::ut; 5 | using namespace boost::ut::literals; 6 | 7 | int example(int arg) 8 | { 9 | return arg + 20; 10 | } 11 | 12 | suite<"Page"> page_suite = [] 13 | { 14 | using prot = lime::protection; 15 | 16 | expect(gt(lime::page::pages().size(), 0)); 17 | 18 | auto addr = reinterpret_cast(example); 19 | { 20 | auto page = lime::page::at(addr); 21 | 22 | expect(eq(page.has_value(), true)); 23 | 24 | expect(page->prot() & prot::read); 25 | expect(page->prot() & prot::execute); 26 | 27 | expect(ge(addr, page->start())); 28 | expect(le(addr, page->end())); 29 | } 30 | 31 | auto allocated = lime::page::allocate(100, prot::read | prot::write | prot::execute); 32 | { 33 | expect(neq(allocated, nullptr)); 34 | 35 | auto page = lime::page::at(allocated->start()); 36 | 37 | expect(eq(page.has_value(), true)); 38 | 39 | expect(page->prot() & prot::read); 40 | expect(page->prot() & prot::write); 41 | expect(page->prot() & prot::execute); 42 | } 43 | 44 | auto near = lime::page::allocate(addr, 10, prot::read); 45 | { 46 | expect(neq(near, nullptr)); 47 | 48 | auto page = lime::page::at(near->start()); 49 | 50 | expect(eq(page.has_value(), true)); 51 | 52 | expect(page->prot() & prot::read); 53 | expect(not(page->prot() & prot::write)); 54 | expect(not(page->prot() & prot::execute)); 55 | 56 | const auto diff = std::abs(static_cast(near->start()) - static_cast(addr)); 57 | 58 | expect(gt(diff, 0)); 59 | expect(lt(diff, std::numeric_limits::max())); 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /tests/address.test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | #include 6 | 7 | using namespace boost::ut; 8 | using namespace boost::ut::literals; 9 | 10 | suite<"Address"> address_suite = [] 11 | { 12 | auto seed = std::seed_seq{std::random_device{}()}; 13 | std::mt19937 random{seed}; 14 | 15 | static constexpr auto n = 50; 16 | static constexpr auto offset = sizeof(int); 17 | 18 | std::vector data; 19 | data.reserve(n); 20 | 21 | for (auto i = 0u; n > i; i++) 22 | { 23 | data.emplace_back(random()); 24 | } 25 | 26 | auto address = lime::address::at(reinterpret_cast(data.data())); 27 | { 28 | expect(eq(address.has_value(), true)); 29 | expect(eq(address->addr(), reinterpret_cast(data.data()))); 30 | 31 | for (const auto &value : data) 32 | { 33 | auto ¤t = address.value(); 34 | expect(eq(current.read(), value)); 35 | 36 | auto next = current + offset; 37 | expect(eq(next.has_value(), true)); 38 | 39 | address.emplace(std::move(next.value())); 40 | } 41 | } 42 | 43 | auto back_address = lime::address::at(address->addr() - offset); 44 | { 45 | expect(eq(back_address.has_value(), true)); 46 | 47 | for (const auto &value : std::views::reverse(data)) 48 | { 49 | auto ¤t = back_address.value(); 50 | 51 | expect(eq(current.read(), value)); 52 | current.write(1337); 53 | 54 | auto next = current - offset; 55 | expect(eq(next.has_value(), true)); 56 | 57 | back_address.emplace(std::move(next.value())); 58 | } 59 | } 60 | 61 | for (const auto &value : data) 62 | { 63 | expect(eq(value, 1337)); 64 | } 65 | }; 66 | -------------------------------------------------------------------------------- /.clang-tidy: -------------------------------------------------------------------------------- 1 | --- 2 | Checks: "*, 3 | -abseil-*, 4 | -altera-*, 5 | -android-*, 6 | -fuchsia-*, 7 | -google-*, 8 | -llvm*, 9 | -modernize-use-trailing-return-type, 10 | -zircon-*, 11 | -readability-else-after-return, 12 | -readability-static-accessed-through-instance, 13 | -readability-avoid-const-params-in-decls, 14 | -cppcoreguidelines-non-private-member-variables-in-classes, 15 | -misc-non-private-member-variables-in-classes, 16 | -readability-redundant-access-specifiers, 17 | -cppcoreguidelines-special-member-functions, 18 | -hicpp-special-member-functions, 19 | -readability-implicit-bool-conversion, 20 | -hicpp-explicit-conversions, 21 | -*-magic-numbers, 22 | -readability-named-parameter, 23 | -hicpp-named-parameter, 24 | -readability-identifier-length, 25 | -cppcoreguidelines-owning-memory, 26 | -cppcoreguidelines-pro-type-reinterpret-cast, 27 | -cppcoreguidelines-avoid-non-const-global-variables, 28 | -hicpp-signed-bitwise, 29 | -*-uppercase-literal-suffix, 30 | -*-cognitive-complexity, 31 | -*-multiway-paths-covered, 32 | -*-switch-missing-default-case, 33 | -*-avoid-endl, 34 | -cppcoreguidelines-pro-type-static-cast-downcast, 35 | -misc-header-include-cycle, 36 | -cppcoreguidelines-pro-type-vararg, 37 | -*-member-init, 38 | -bugprone-easily-swappable-parameters, 39 | -hicpp-vararg, 40 | -cppcoreguidelines-pro-bounds-pointer-arithmetic, 41 | -*-dcl21-cpp, 42 | -cert-err58-cpp, 43 | -performance-no-int-to-ptr, 44 | -cppcoreguidelines-interfaces-global-init, 45 | -*-avoid-c-arrays, 46 | -hicpp-no-array-decay 47 | -*-array-to-pointer-decay, 48 | -*-pro-type-union-access, 49 | -*-array-to-pointer-decay, 50 | -*-no-array-decay, 51 | -*-pro-bounds-constant-array-index, 52 | " 53 | WarningsAsErrors: '' 54 | HeaderFilterRegex: '' 55 | FormatStyle: none 56 | -------------------------------------------------------------------------------- /tests/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.16) 2 | project(lime-tests LANGUAGES CXX) 3 | 4 | # -------------------------------------------------------------------------------------------------------- 5 | # Create executable 6 | # -------------------------------------------------------------------------------------------------------- 7 | 8 | add_executable(${PROJECT_NAME}) 9 | add_executable(lime::tests ALIAS ${PROJECT_NAME}) 10 | 11 | target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_20) 12 | set_target_properties(${PROJECT_NAME} PROPERTIES CXX_STANDARD 20 CXX_EXTENSIONS OFF CXX_STANDARD_REQUIRED ON) 13 | 14 | # -------------------------------------------------------------------------------------------------------- 15 | # Add Sources 16 | # -------------------------------------------------------------------------------------------------------- 17 | 18 | file(GLOB src "*.test.cpp" "main.cpp") 19 | target_sources(${PROJECT_NAME} PRIVATE ${src}) 20 | 21 | # -------------------------------------------------------------------------------------------------------- 22 | # Link Dependencies 23 | # -------------------------------------------------------------------------------------------------------- 24 | 25 | include("../cmake/cpm.cmake") 26 | 27 | CPMFindPackage( 28 | NAME ut 29 | VERSION 2.0.0 30 | GIT_REPOSITORY "https://github.com/boost-ext/ut" 31 | OPTIONS "BOOST_UT_DISABLE_MODULE ON" 32 | ) 33 | 34 | target_link_libraries(${PROJECT_NAME} PRIVATE Boost::ut cr::lime) 35 | 36 | # -------------------------------------------------------------------------------------------------------- 37 | # Shared Library 38 | # -------------------------------------------------------------------------------------------------------- 39 | 40 | add_subdirectory(lib) 41 | 42 | # -------------------------------------------------------------------------------------------------------- 43 | # Add Test-Target 44 | # -------------------------------------------------------------------------------------------------------- 45 | 46 | include(CTest) 47 | 48 | add_test(NAME lime-tests COMMAND $) 49 | -------------------------------------------------------------------------------- /include/lime/page.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | #include 7 | #include 8 | 9 | #include 10 | 11 | namespace lime 12 | { 13 | enum class protection 14 | { 15 | none, 16 | read = 1 << 0, 17 | write = 1 << 1, 18 | execute = 1 << 2, 19 | }; 20 | 21 | enum class alloc_policy 22 | { 23 | exact, 24 | nearby, 25 | }; 26 | 27 | class page 28 | { 29 | struct impl; 30 | 31 | private: 32 | std::unique_ptr m_impl; 33 | 34 | private: 35 | page(); 36 | 37 | public: 38 | ~page(); 39 | 40 | public: 41 | page(const page &); 42 | page(page &&) noexcept; 43 | 44 | public: 45 | page &operator=(page &&) noexcept; 46 | 47 | public: 48 | [[nodiscard]] protection prot() const; 49 | 50 | public: 51 | [[nodiscard]] std::size_t size() const; 52 | 53 | public: 54 | [[nodiscard]] std::uintptr_t end() const; 55 | [[nodiscard]] std::uintptr_t start() const; 56 | 57 | public: 58 | bool restore(); 59 | bool protect(protection prot); 60 | 61 | public: 62 | [[nodiscard]] static std::vector pages(); 63 | 64 | public: 65 | [[nodiscard]] static page unsafe(std::uintptr_t address); 66 | [[nodiscard]] static std::optional at(std::uintptr_t address); 67 | 68 | public: 69 | [[nodiscard]] static std::shared_ptr allocate(std::size_t size, protection prot); 70 | 71 | public: 72 | template 73 | [[nodiscard]] static std::shared_ptr allocate(std::uintptr_t where, std::size_t size, protection prot); 74 | }; 75 | 76 | template <> 77 | std::shared_ptr page::allocate(std::uintptr_t, std::size_t, protection); 78 | 79 | template <> 80 | std::shared_ptr page::allocate(std::uintptr_t, std::size_t, protection); 81 | } // namespace lime 82 | 83 | template <> 84 | constexpr inline bool flagpp::enabled = true; 85 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | on: 2 | workflow_dispatch: 3 | push: 4 | branches: ["**"] 5 | paths-ignore: 6 | - "**/*.md" 7 | 8 | name: 🧪 Run Tests 9 | jobs: 10 | test: 11 | strategy: 12 | fail-fast: false 13 | 14 | matrix: 15 | arch: [x86, x64] 16 | config: [Release, Debug] 17 | type: [linux, mingw, windows, windows-clang] 18 | 19 | include: 20 | - type: linux 21 | container: fedora:38 # g++ on ubuntu latest does not include P2210R2 22 | deps: sudo dnf install -y git cmake gcc gcc-c++ ninja-build 23 | 24 | - type: mingw 25 | container: archlinux:multilib-devel 26 | deps: pacman --noconfirm -Syyu cmake gcc git make mingw-w64 wine 27 | 28 | - type: mingw 29 | arch: x86 30 | cmake_args: -DCMAKE_TOOLCHAIN_FILE=cmake/mingw-x86.cmake 31 | - type: mingw 32 | arch: x64 33 | cmake_args: -DCMAKE_TOOLCHAIN_FILE=cmake/mingw-x64.cmake 34 | 35 | - type: windows 36 | arch: x86 37 | cmake_args: -A Win32 38 | - type: windows 39 | arch: x64 40 | cmake_args: -A x64 41 | 42 | - type: windows-clang 43 | arch: x86 44 | cmake_args: -T ClangCL -A Win32 45 | - type: windows-clang 46 | arch: x64 47 | cmake_args: -T ClangCL -A x64 48 | 49 | exclude: 50 | - type: linux 51 | arch: x86 52 | 53 | runs-on: ${{ contains(matrix.type, 'windows') && 'windows-latest' || 'ubuntu-latest' }} 54 | container: ${{ matrix.container }} 55 | 56 | name: "${{ matrix.type }} (💾: ${{ matrix.arch }}, ⚙️: ${{ matrix.config }})" 57 | 58 | steps: 59 | - name: 📦 Checkout 60 | uses: actions/checkout@v4 61 | 62 | - name: 🧰 Dependencies 63 | run: ${{ matrix.deps }} 64 | 65 | - name: 🔧 Compile 66 | run: | 67 | cmake -B build -Dlime_tests=ON ${{ matrix.cmake_args }} 68 | cmake --build build --config ${{ matrix.config }} 69 | 70 | - name: 🔬 Run Tests 71 | if: ${{ matrix.type != 'mingw' }} 72 | run: | 73 | ctest --test-dir build/tests -C ${{ matrix.config }} --verbose 74 | 75 | - name: 🔬 Run Tests (Wine) 76 | if: ${{ matrix.type == 'mingw' }} 77 | run: | 78 | mkdir prefix 79 | WINEPREFIX="$(pwd)/prefix" wine ./build/tests/lime-tests.exe 80 | -------------------------------------------------------------------------------- /include/lime/instruction.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | namespace lime 11 | { 12 | struct imm 13 | { 14 | using amount_t = std::variant; 15 | 16 | public: 17 | bool relative; 18 | amount_t amount; 19 | 20 | public: 21 | std::size_t size; 22 | std::size_t offset; 23 | }; 24 | 25 | struct disp 26 | { 27 | std::int64_t amount; 28 | 29 | public: 30 | std::size_t size; 31 | std::size_t offset; 32 | }; 33 | 34 | class instruction 35 | { 36 | struct impl; 37 | 38 | private: 39 | std::unique_ptr m_impl; 40 | 41 | private: 42 | instruction(); 43 | 44 | public: 45 | ~instruction(); 46 | 47 | public: 48 | instruction(const instruction &); 49 | instruction(instruction &&) noexcept; 50 | 51 | public: 52 | instruction &operator=(instruction &&) noexcept; 53 | 54 | public: 55 | [[nodiscard]] std::uintptr_t addr() const; 56 | 57 | public: 58 | [[nodiscard]] std::size_t size() const; 59 | [[nodiscard]] std::size_t mnemonic() const; 60 | 61 | public: 62 | [[nodiscard]] bool relative() const; 63 | [[nodiscard]] bool branching() const; 64 | 65 | public: 66 | [[nodiscard]] disp displacement() const; 67 | [[nodiscard]] std::vector immediates() const; 68 | 69 | public: 70 | [[nodiscard]] std::optional next() const; 71 | [[lime::inaccurate]] [[nodiscard]] std::optional prev() const; 72 | 73 | public: 74 | [[nodiscard]] std::optional follow() const; 75 | [[nodiscard]] std::optional next(std::size_t mnemonic) const; 76 | 77 | public: 78 | [[nodiscard]] std::optional absolute() const; 79 | [[nodiscard]] std::optional absolute(std::uintptr_t rip) const; 80 | 81 | public: 82 | [[nodiscard]] std::optional operator-(std::size_t) const; 83 | [[nodiscard]] std::optional operator+(std::size_t) const; 84 | 85 | public: 86 | [[nodiscard]] std::strong_ordering operator<=>(const instruction &) const; 87 | 88 | public: 89 | [[nodiscard]] static instruction unsafe(std::uintptr_t address); 90 | [[nodiscard]] static std::optional at(std::uintptr_t address); 91 | }; 92 | } // namespace lime 93 | -------------------------------------------------------------------------------- /include/lime/hooks/hook.inl: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "hook.hpp" 4 | 5 | #include 6 | 7 | namespace lime 8 | { 9 | template 10 | typename hook::signature_t hook::original() const 11 | { 12 | return reinterpret_cast(hook_base::original()); 13 | } 14 | 15 | template 16 | template 17 | hook::rtn_t hook::create(Source source, 18 | Target target) 19 | { 20 | auto source_address = std::bit_cast(source); 21 | auto target_address = std::bit_cast(target); 22 | 23 | auto rtn = hook_base::create(source_address, target_address); 24 | 25 | if (!rtn) 26 | { 27 | return tl::make_unexpected(rtn.error()); 28 | } 29 | 30 | auto *ptr = rtn->release(); 31 | return std::unique_ptr{static_cast(ptr)}; 32 | } 33 | 34 | template 35 | template 36 | hook::rtn_t hook::create(Source source, 37 | Callable &&target) 38 | { 39 | static hook *rtn; 40 | [[maybe_unused]] static auto lambda = std::forward(target); 41 | 42 | static constexpr auto dispatch = [](T &&...args) 43 | { 44 | return lambda(rtn, std::forward(args)...); 45 | }; 46 | 47 | auto wrapper = detail::calling_convention::template wrapper; 48 | auto result = create(source, wrapper); 49 | 50 | if (!result) 51 | { 52 | return tl::make_unexpected(result.error()); 53 | } 54 | 55 | rtn = result->release(); 56 | 57 | return rtn; 58 | } 59 | 60 | template 61 | auto make_hook(Signature source, Callable &&target) 62 | { 63 | return hook, Convention>::create(source, std::forward(target)); 64 | } 65 | 66 | template 67 | auto make_hook(detail::address auto source, Callable &&target) 68 | { 69 | return hook::create(source, std::forward(target)); 70 | } 71 | } // namespace lime 72 | -------------------------------------------------------------------------------- /include/lime/hooks/convention.inl: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "convention.hpp" 4 | 5 | #include 6 | #include 7 | 8 | namespace lime::detail 9 | { 10 | template 11 | struct calling_convention 12 | { 13 | using add = Ret(Args...); 14 | 15 | template 16 | static Ret wrapper(Args... args) 17 | { 18 | return Function(std::forward(args)...); 19 | } 20 | }; 21 | 22 | #if INTPTR_MAX == INT32_MAX 23 | 24 | #ifdef _MSC_VER 25 | #define LIME_CDECL __cdecl 26 | #define LIME_STDCALL __stdcall 27 | #define LIME_FASTCALL __fastcall 28 | #define LIME_THISCALL __thiscall 29 | #else 30 | #define LIME_CDECL __attribute__((cdecl)) 31 | #define LIME_STDCALL __attribute__((stdcall)) 32 | #define LIME_FASTCALL __attribute__((fastcall)) 33 | #define LIME_THISCALL __attribute__((thiscall)) 34 | #endif 35 | 36 | #ifdef __GNUC__ 37 | #pragma GCC diagnostic push 38 | #pragma GCC diagnostic ignored "-Wattributes" 39 | #endif 40 | 41 | template 42 | struct calling_convention 43 | { 44 | using add = Ret LIME_CDECL(Args...); 45 | 46 | template 47 | static Ret LIME_CDECL wrapper(Args... args) 48 | { 49 | return Function(std::forward(args)...); 50 | } 51 | }; 52 | 53 | template 54 | struct calling_convention 55 | { 56 | using add = Ret LIME_STDCALL(Args...); 57 | 58 | template 59 | static Ret LIME_STDCALL wrapper(Args... args) 60 | { 61 | return Function(std::forward(args)...); 62 | } 63 | }; 64 | 65 | template 66 | struct calling_convention 67 | { 68 | using add = Ret LIME_FASTCALL(Args...); 69 | 70 | template 71 | static Ret LIME_FASTCALL wrapper(Args... args) 72 | { 73 | return Function(std::forward(args)...); 74 | } 75 | }; 76 | 77 | template 78 | struct calling_convention 79 | { 80 | using add = Ret LIME_THISCALL(Args...); 81 | 82 | template 83 | static Ret LIME_THISCALL wrapper(Args... args) 84 | { 85 | return Function(std::forward(args)...); 86 | } 87 | }; 88 | 89 | #ifdef __GNUC__ 90 | #pragma GCC diagnostic pop 91 | #endif 92 | 93 | #endif 94 | 95 | #undef LIME_CDECL 96 | #undef LIME_STDCALL 97 | #undef LIME_FASTCALL 98 | #undef LIME_THISCALL 99 | } // namespace lime::detail 100 | -------------------------------------------------------------------------------- /tests/hook.test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | #include 5 | 6 | using namespace boost::ut; 7 | using namespace boost::ut::literals; 8 | 9 | int test_fn(int param) 10 | { 11 | std::cout << std::format("test_fn({}): called", param) << std::endl; 12 | 13 | if (param == 1337) 14 | { 15 | return 0; 16 | } 17 | 18 | return param; 19 | } 20 | 21 | std::unique_ptr> original_test; 22 | 23 | int test_hook(int param) 24 | { 25 | return original_test->original()(param + 5); 26 | } 27 | 28 | suite<"Hooks"> hook_suite = [] 29 | { 30 | expect(eq(test_fn(10), 10)); 31 | expect(eq(test_fn(1337), 0)); 32 | 33 | original_test = std::move(lime::hook::create(test_fn, test_hook).value()); 34 | expect(eq(test_fn(10), 15)); 35 | expect(eq(test_fn(1337), 1342)); 36 | 37 | original_test.reset(); 38 | expect(eq(test_fn(10), 10)); 39 | 40 | original_test = std::move(lime::make_hook(test_fn, test_hook).value()); 41 | expect(eq(test_fn(10), 15)); 42 | 43 | original_test.reset(); 44 | expect(eq(test_fn(10), 10)); 45 | 46 | lime::hook::create(test_fn, 47 | [](auto *hook, int param) -> int 48 | { 49 | auto rtn = hook->original()(param + 10); 50 | delete hook; 51 | return rtn; 52 | }); 53 | 54 | #if INTPTR_MAX == INT32_MAX 55 | using hook_t = lime::hook; 56 | 57 | hook_t::create(0xDEADBEEF, 58 | [&](auto *hook, void *thiz, int param) -> int 59 | { 60 | auto ret = hook->original()(thiz, param); 61 | delete hook; 62 | return ret; 63 | }); 64 | 65 | lime::make_hook(0xDEADBEEF, 66 | [&](auto *hook, void *thiz, int param) -> int 67 | { 68 | auto ret = hook->original()(thiz, param); 69 | delete hook; 70 | return ret; 71 | }); 72 | #endif 73 | 74 | expect(eq(test_fn(10), 20)); 75 | expect(eq(test_fn(10), 10)); 76 | 77 | lime::make_hook(test_fn, 78 | [](auto *hook, int param) -> int 79 | { 80 | auto rtn = hook->original()(param + 10); 81 | delete hook; 82 | return rtn; 83 | }); 84 | 85 | expect(eq(test_fn(10), 20)); 86 | expect(eq(test_fn(10), 10)); 87 | }; 88 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 | ## 👋 Introduction 6 | Lime is a *cross-platform* library that is focused on game modding and tries to provide you with useful features for your journey. 7 | 8 | ## 🗒️ Features 9 | - Detours 10 | - x86/x86-64 11 | - Lambda support 12 | - (Cross-Platform) Calling Convention support _(for lambdas!)_ 13 | - Instruction 14 | - Get next / prev instruction 15 | - Get immediates, displacement, size, mnemonic 16 | - Calculate absolute target _(follow relative instructions...)_ 17 | - Memory Pages 18 | - Allocate pages 19 | - Anywhere 20 | - Exactly at specified address 21 | - In ±2GB range of specified address 22 | - Read / Write / Restore protection 23 | - Module 24 | - Iterate Loaded Modules 25 | - Iterate Symbols 26 | - Load Modules 27 | - Address 28 | - Read / Write Data 29 | - Signature Scanner 30 | - Supports Traditional & IDA Signatures 31 | - Cross-Platform Entrypoint 32 | - _[MinGW]_ Proxy-DLL Generation 33 | 34 | > [!NOTE] 35 | > Lime follows `RAII` so you won't have to care about manually cleaning anything up (i.e. when allocating a page). 36 | 37 | ## ⚙️ Configuration 38 | 39 | ### Static Entrypoint 40 | ```cmake 41 | set(lime_static_entrypoint ON) 42 | ``` 43 | 44 | > Default is: `OFF` 45 | 46 | Use a platform-independent method for the entrypoint implementation. 47 | You do not need to enable this to make use of the cross-platform entrypoint! 48 | 49 | ### VirtualAlloc2 50 | ```cmake 51 | set(lime_no_alloc2 ON) 52 | ``` 53 | 54 | > Default is: `OFF` 55 | 56 | Can be used to disable the usage of `VirtualAlloc2`. 57 | 58 | ~~This should be used for compatibility with wine as it currently does not support the `LowestStartingAddress` requirement.~~ 59 | Should work since wine 8.11 🎉 60 | 61 | # 📦 Installation 62 | 63 | * Using [CPM](https://github.com/cpm-cmake/CPM.cmake) 64 | ```cmake 65 | CPMFindPackage( 66 | NAME lime 67 | VERSION 5.0 68 | GIT_REPOSITORY "https://github.com/Curve/lime" 69 | ) 70 | ``` 71 | 72 | * Using FetchContent 73 | ```cmake 74 | include(FetchContent) 75 | 76 | FetchContent_Declare(lime GIT_REPOSITORY "https://github.com/Curve/lime" GIT_TAG v5.0) 77 | FetchContent_MakeAvailable(lime) 78 | 79 | target_link_libraries( cr::lime) 80 | ``` 81 | 82 | ## 📖 Examples 83 | 84 | https://github.com/Curve/lime/blob/7de073bd4736900193f6af5c543a3cf62e6f1a73/tests/hook.test.cpp#L46-L52 85 | https://github.com/Curve/lime/blob/9ee66d3cc9e8976d5d8a40856d7ee5a09d32c415/tests/hook.test.cpp#L44-L52 86 | 87 | > For more examples see [tests](tests/) 88 | 89 | ## 🌐 Who's using Lime 90 | 91 |
92 |
93 | 94 | 95 | 96 | [profuis-patch](https://github.com/simplytest/profuis-patch) 97 | 98 |
99 | 100 | > [Extend the list!](https://github.com/Curve/lime/issues/new) 101 | -------------------------------------------------------------------------------- /src/address.cpp: -------------------------------------------------------------------------------- 1 | #include "address.hpp" 2 | 3 | #include "page.hpp" 4 | 5 | #include 6 | #include 7 | 8 | #include 9 | 10 | namespace lime 11 | { 12 | struct address::impl 13 | { 14 | std::uintptr_t address; 15 | }; 16 | 17 | address::address() : m_impl(std::make_unique()) {} 18 | 19 | address::~address() = default; 20 | 21 | address::address(const address &other) : m_impl(std::make_unique()) 22 | { 23 | *m_impl = *other.m_impl; 24 | } 25 | 26 | address::address(address &&other) noexcept : m_impl(std::move(other.m_impl)) {} 27 | 28 | bool address::write(const void *data, std::size_t size) 29 | { 30 | auto page = lime::page::at(m_impl->address); 31 | 32 | if (!page) 33 | { 34 | return false; 35 | } 36 | 37 | auto writable = page->prot() & protection::write; 38 | 39 | if (!writable && !page->protect(page->prot() | protection::write)) 40 | { 41 | return false; 42 | } 43 | 44 | auto *dest = reinterpret_cast(m_impl->address); 45 | std::memcpy(dest, data, size); 46 | 47 | if (!writable) 48 | { 49 | page->restore(); 50 | } 51 | 52 | return true; 53 | } 54 | 55 | std::vector address::copy(std::size_t size) 56 | { 57 | const auto *src = reinterpret_cast(m_impl->address); 58 | 59 | std::vector rtn; 60 | std::ranges::copy(src, src + size, std::back_inserter(rtn)); 61 | 62 | return rtn; 63 | } 64 | 65 | void *address::ptr() const 66 | { 67 | return reinterpret_cast(m_impl->address); 68 | } 69 | 70 | std::uintptr_t address::addr() const 71 | { 72 | return m_impl->address; 73 | } 74 | 75 | std::optional
address::operator+(const std::size_t amount) const 76 | { 77 | return at(m_impl->address + amount); 78 | } 79 | 80 | std::optional
address::operator-(const std::size_t amount) const 81 | { 82 | return at(m_impl->address - amount); 83 | } 84 | 85 | std::strong_ordering address::operator<=>(const address &other) const 86 | { 87 | const auto address = other.addr(); 88 | 89 | if (address > m_impl->address) 90 | { 91 | return std::strong_ordering::less; 92 | } 93 | 94 | if (address < m_impl->address) 95 | { 96 | return std::strong_ordering::greater; 97 | } 98 | 99 | return std::strong_ordering::equal; 100 | } 101 | 102 | address address::unsafe(std::uintptr_t address) 103 | { 104 | lime::address rtn; 105 | 106 | rtn.m_impl->address = address; 107 | 108 | return rtn; 109 | } 110 | 111 | std::optional
address::at(std::uintptr_t address) 112 | { 113 | const auto page = page::at(address); 114 | 115 | if (!page || !(page->prot() & protection::read)) 116 | { 117 | return std::nullopt; 118 | } 119 | 120 | return unsafe(address); 121 | } 122 | } // namespace lime 123 | -------------------------------------------------------------------------------- /.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Cpp 3 | InsertNewlineAtEOF: true 4 | AccessModifierOffset: -2 5 | AlignAfterOpenBracket: Align 6 | AlignConsecutiveMacros: true 7 | AlignConsecutiveAssignments: 8 | Enabled: true 9 | AcrossComments: false 10 | AcrossEmptyLines: false 11 | AlignConsecutiveDeclarations: false 12 | AlignEscapedNewlines: Right 13 | AlignOperands: true 14 | AlignTrailingComments: true 15 | AllowAllArgumentsOnNextLine: true 16 | AllowAllConstructorInitializersOnNextLine: true 17 | AllowAllParametersOfDeclarationOnNextLine: true 18 | AllowShortBlocksOnASingleLine: Never 19 | AllowShortCaseLabelsOnASingleLine: false 20 | AllowShortFunctionsOnASingleLine: Empty 21 | AllowShortLambdasOnASingleLine: Inline 22 | AllowShortIfStatementsOnASingleLine: Never 23 | AllowShortLoopsOnASingleLine: false 24 | AlwaysBreakAfterDefinitionReturnType: None 25 | AlwaysBreakAfterReturnType: None 26 | AlwaysBreakBeforeMultilineStrings: false 27 | AlwaysBreakTemplateDeclarations: Yes 28 | BinPackArguments: true 29 | BinPackParameters: true 30 | BraceWrapping: 31 | BeforeLambdaBody: true 32 | AfterCaseLabel: false 33 | AfterClass: true 34 | AfterControlStatement: true 35 | AfterEnum: true 36 | AfterFunction: true 37 | AfterNamespace: true 38 | AfterObjCDeclaration: true 39 | AfterStruct: true 40 | AfterUnion: false 41 | AfterExternBlock: true 42 | BeforeCatch: true 43 | BeforeElse: true 44 | IndentBraces: false 45 | SplitEmptyFunction: true 46 | SplitEmptyRecord: true 47 | SplitEmptyNamespace: true 48 | BreakBeforeBinaryOperators: None 49 | BreakBeforeBraces: Custom 50 | BreakBeforeInheritanceComma: false 51 | BreakInheritanceList: BeforeColon 52 | BreakBeforeTernaryOperators: true 53 | BreakConstructorInitializersBeforeComma: false 54 | BreakConstructorInitializers: BeforeColon 55 | BreakAfterJavaFieldAnnotations: false 56 | BreakStringLiterals: true 57 | BreakBeforeConceptDeclarations: Always 58 | RequiresClausePosition: SingleLine 59 | ColumnLimit: 120 60 | CompactNamespaces: false 61 | ConstructorInitializerAllOnOneLineOrOnePerLine: false 62 | ConstructorInitializerIndentWidth: 4 63 | ContinuationIndentWidth: 4 64 | Cpp11BracedListStyle: true 65 | DeriveLineEnding: true 66 | DerivePointerAlignment: false 67 | FixNamespaceComments: true 68 | IndentCaseLabels: false 69 | IndentGotoLabels: true 70 | IndentPPDirectives: None 71 | IndentWidth: 4 72 | IndentWrappedFunctionNames: false 73 | KeepEmptyLinesAtTheStartOfBlocks: true 74 | NamespaceIndentation: All 75 | PointerAlignment: Right 76 | ReflowComments: true 77 | SortIncludes: false 78 | SortUsingDeclarations: true 79 | SpaceAfterCStyleCast: false 80 | SpaceAfterLogicalNot: false 81 | SpaceAfterTemplateKeyword: true 82 | SpaceBeforeAssignmentOperators: true 83 | SpaceBeforeCpp11BracedList: false 84 | SpaceBeforeCtorInitializerColon: true 85 | SpaceBeforeInheritanceColon: true 86 | SpaceBeforeParens: ControlStatements 87 | SpaceBeforeRangeBasedForLoopColon: true 88 | SpaceInEmptyBlock: false 89 | SpaceInEmptyParentheses: false 90 | SpacesBeforeTrailingComments: 1 91 | SpacesInAngles: false 92 | SpacesInConditionalStatement: false 93 | SpacesInContainerLiterals: true 94 | SpacesInCStyleCastParentheses: false 95 | SpacesInParentheses: false 96 | SpacesInSquareBrackets: false 97 | SpaceBeforeSquareBrackets: false 98 | Standard: Latest 99 | TabWidth: 4 100 | UseCRLF: false 101 | UseTab: Never 102 | -------------------------------------------------------------------------------- /include/lime/hooks/hook.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "convention.hpp" 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #include 11 | 12 | namespace lime 13 | { 14 | namespace detail 15 | { 16 | template 17 | concept is_std_function = requires(T value) { 18 | [](std::function &) { 19 | }(value); 20 | }; 21 | 22 | template 23 | concept function_signature = requires() { 24 | requires not std::is_pointer_v; 25 | requires std::is_function_v; 26 | }; 27 | 28 | template 29 | concept function_pointer = requires() { 30 | requires std::is_pointer_v or std::is_reference_v; 31 | requires std::is_function_v>>; 32 | }; 33 | 34 | template 35 | concept address = requires() { requires std::integral or function_pointer; }; 36 | 37 | template 38 | concept lambda_like = requires() { 39 | requires not address; 40 | requires not is_std_function; 41 | }; 42 | } // namespace detail 43 | 44 | enum class hook_error 45 | { 46 | protect, 47 | relocate, 48 | bad_page, 49 | bad_prot, 50 | bad_func, 51 | }; 52 | 53 | class hook_base 54 | { 55 | struct impl; 56 | 57 | protected: 58 | using rtn_t = tl::expected, hook_error>; 59 | 60 | protected: 61 | std::unique_ptr m_impl; 62 | 63 | protected: 64 | hook_base(); 65 | 66 | public: 67 | ~hook_base(); 68 | 69 | public: 70 | hook_base(hook_base &&) noexcept; 71 | 72 | protected: 73 | [[nodiscard]] std::uintptr_t original() const; 74 | 75 | protected: 76 | [[nodiscard]] static rtn_t create(std::uintptr_t, std::uintptr_t); 77 | }; 78 | 79 | template 80 | class hook : public hook_base 81 | { 82 | template