crlib: reworked detours.

This commit is contained in:
dmitry 2020-06-21 09:45:09 +03:00
commit 419626df0e
13 changed files with 274 additions and 205 deletions

View file

@ -21,6 +21,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stddef.h>
#include <limits.h>

View file

@ -17,7 +17,6 @@
#include <stdio.h>
#include <crlib/cr-platform.h>
#include <crlib/cr-basic.h>
#include <crlib/cr-alloc.h>
#include <crlib/cr-array.h>
@ -26,14 +25,14 @@
#include <crlib/cr-lambda.h>
#include <crlib/cr-http.h>
#include <crlib/cr-library.h>
#include <crlib/cr-dict.h>
#include <crlib/cr-hashmap.h>
#include <crlib/cr-logger.h>
#include <crlib/cr-math.h>
#include <crlib/cr-vector.h>
#include <crlib/cr-random.h>
#include <crlib/cr-ulz.h>
#include <crlib/cr-color.h>
#include <crlib/cr-hook.h>
#include <crlib/cr-detour.h>
CR_NAMESPACE_BEGIN

239
ext/crlib/cr-detour.h Normal file
View file

@ -0,0 +1,239 @@
//
// CRLib - Simple library for STL replacement in private projects.
// Copyright © 2020 YaPB Development Team <team@yapb.ru>.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
#pragma once
#include <crlib/cr-basic.h>
#if !defined (CR_WINDOWS)
# include <sys/mman.h>
# include <pthread.h>
#endif
CR_NAMESPACE_BEGIN
// simple wrapper for critical sections
class CriticalSection final : public DenyCopying {
private:
#if defined (CR_WINDOWS)
CRITICAL_SECTION cs_;
#else
pthread_mutex_t mutex_;
#endif
public:
CriticalSection () {
#if defined (CR_WINDOWS)
InitializeCriticalSection (&cs_);
#else
pthread_mutex_init (&mutex_, nullptr);
#endif
}
~CriticalSection () {
#if defined (CR_WINDOWS)
DeleteCriticalSection (&cs_);
#else
pthread_mutex_destroy (&mutex_);
#endif
}
void lock () {
#if defined (CR_WINDOWS)
EnterCriticalSection (&cs_);
#else
pthread_mutex_lock (&mutex_);
#endif
}
void unlock () {
#if defined (CR_WINDOWS)
LeaveCriticalSection (&cs_);
#else
pthread_mutex_unlock (&mutex_);
#endif
}
};
// simple autolock wrapper
class AutoLock final : public DenyCopying {
private:
CriticalSection *cs_;
public:
AutoLock (CriticalSection *cs) : cs_ (cs) {
cs_->lock ();
}
~AutoLock () {
cs_->unlock ();
}
};
// simple detour class for x86/x64
template <typename T> class Detour final : public DenyCopying {
private:
enum : uint32 {
PtrSize = sizeof (void *),
#if defined (CR_ARCH_X64)
Offset = 2
#else
Offset = 1
#endif
};
#if defined (CR_ARCH_X64)
using uintptr = uint64;
#else
using uintptr = uint32;
#endif
private:
CriticalSection cs_;
void *original_ = nullptr;
void *detour_ = nullptr;
Array <uint8> savedBytes_ { };
Array <uint8> jmpBuffer_
#ifdef CR_ARCH_X64
{ 0x48, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xe0 };
#else
{ 0xb8, 0x00, 0x00, 0x00, 0x00, 0xff, 0xe0 };
#endif
#if !defined (CR_WINDOWS)
unsigned long pageSize_ { 0 };
uintptr pageStart_ { 0 };
#endif
bool overwritten_ { false };
private:
bool overwriteMemory (const Array <uint8> &to, const bool overwritten) noexcept {
overwritten_ = overwritten;
AutoLock lock (&cs_);
#if defined (CR_WINDOWS)
unsigned long oldProtect {};
if (VirtualProtect (original_, to.length (), PAGE_EXECUTE_READWRITE, &oldProtect)) {
memcpy (original_, to.data (), to.length ());
// restore protection
return VirtualProtect (original_, to.length (), oldProtect, &oldProtect);
}
#else
if (mprotect (reinterpret_cast <void *> (pageStart_), pageSize_, PROT_READ | PROT_WRITE | PROT_EXEC) != -1) {
memcpy (original_, to.data (), to.length ());
// restore protection
return mprotect (reinterpret_cast <void *> (pageStart_), pageSize_, PROT_READ | PROT_EXEC) != -1;
}
#endif
return false;
}
public:
Detour (StringRef module, StringRef name, T *address) {
savedBytes_.resize (jmpBuffer_.length ());
#if !defined (CR_WINDOWS)
(void) module;
(void) name;
auto search = reinterpret_cast <uint8 *> (address);
while (*reinterpret_cast <uint16 *> (search) == 0x25ff) {
search = **reinterpret_cast <uint8 ***> (search + 2);
}
original_ = search;
pageSize_ = static_cast <unsigned long> (sysconf (_SC_PAGE_SIZE));
#else
auto handle = GetModuleHandleA (module.chars ());
if (!handle) {
original_ = reinterpret_cast <void *> (address);
return;
}
original_ = reinterpret_cast <void *> (GetProcAddress (handle, name.chars ()));
if (!original_) {
original_ = reinterpret_cast <void *> (address);
return;
}
#endif
}
~Detour () {
restore ();
original_ = nullptr;
detour_ = nullptr;
}
public:
void install (void *detour, const bool enable = false) {
if (!original_) {
return;
}
detour_ = detour;
#if !defined (CR_WINDOWS)
pageStart_ = reinterpret_cast <uintptr> (original_) & -pageSize_;
#endif
memcpy (savedBytes_.data (), original_, savedBytes_.length ());
memcpy (reinterpret_cast <void *> (reinterpret_cast <uintptr> (jmpBuffer_.data ()) + Offset), &detour_, PtrSize);
if (enable) {
this->detour ();
}
}
bool valid () const {
return original_ && detour_;
}
bool detoured () const {
return overwritten_;
}
bool detour () {
if (!valid ()) {
return false;
}
return overwriteMemory (jmpBuffer_, true);
}
bool restore () {
if (!valid ()) {
return false;
}
return overwriteMemory (savedBytes_, false);
}
template <typename... Args > decltype (auto) operator () (Args &&...args) {
restore ();
auto res = reinterpret_cast <T *> (original_) (args...);
detour ();
return res;
}
};
CR_NAMESPACE_END

View file

@ -1,166 +0,0 @@
//
// CRLib - Simple library for STL replacement in private projects.
// Copyright © 2020 YaPB Development Team <team@yapb.ru>.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
#pragma once
#include <crlib/cr-basic.h>
#if !defined (CR_WINDOWS)
# include <sys/mman.h>
#endif
CR_NAMESPACE_BEGIN
class SimpleHook : DenyCopying {
private:
#if defined (CR_ARCH_X64)
using uint = uint64;
#else
using uint = uint32;
#endif
private:
enum : uint32 {
#if defined (CR_ARCH_X64)
CodeLength = 5 + sizeof (uint)
#else
CodeLength = 1 + sizeof (uint)
#endif
};
private:
bool patched_;
uint pageSize_;
uint originalFun_;
uint hookedFun_;
UniquePtr <uint8 []> originalBytes_;
UniquePtr <uint8 []> hookedBytes_;
private:
void setPageSize () {
#if defined (CR_WINDOWS)
SYSTEM_INFO sysinfo;
GetSystemInfo (&sysinfo);
pageSize_ = sysinfo.dwPageSize;
#else
pageSize_ = sysconf (_SC_PAGESIZE);
#endif
}
#if !defined (CR_WINDOWS)
void *align (void *address) {
return reinterpret_cast <void *> ((reinterpret_cast <long> (address) & ~(pageSize_ - 1)));
}
#endif
bool unprotect () {
auto orig = reinterpret_cast <void *> (originalFun_);
#if defined (CR_WINDOWS)
DWORD oldProt;
FlushInstructionCache (GetCurrentProcess (), orig, CodeLength);
return VirtualProtect (orig, CodeLength, PAGE_EXECUTE_READWRITE, &oldProt);
#else
auto aligned = align (orig);
return !mprotect (aligned, pageSize_, PROT_READ | PROT_WRITE | PROT_EXEC);
#endif
}
public:
SimpleHook () : patched_ (false), pageSize_ (0), originalFun_ (0), hookedFun_ (0) {
setPageSize ();
originalBytes_ = makeUnique <uint8 []> (CodeLength);
hookedBytes_ = makeUnique <uint8 []> (CodeLength);
}
public:
bool patch (void *address, void *replacement) {
constexpr uint16 jmp = 0x25ff;
if (plat.arm) {
return false;
}
auto ptr = reinterpret_cast <uint8 *> (address);
while (*reinterpret_cast <uint16 *> (ptr) == jmp) {
ptr = **reinterpret_cast <uint8 ***> (ptr + 2);
}
originalFun_ = reinterpret_cast <uint> (ptr);
hookedFun_ = reinterpret_cast <uint> (replacement);
memcpy (originalBytes_.get (), reinterpret_cast <void *> (originalFun_), CodeLength);
if (plat.x64) {
const uint16 nop = 0x00000000;
memcpy (&hookedBytes_[0], &jmp, sizeof (uint16));
memcpy (&hookedBytes_[2], &nop, sizeof (uint16));
memcpy (&hookedBytes_[6], &replacement, sizeof (uint));
}
else {
hookedBytes_[0] = 0xe9;
auto rel = hookedFun_ - originalFun_ - CodeLength;
memcpy (&hookedBytes_[0] + 1, &rel, sizeof (rel));
}
return enable ();
}
bool enable () {
if (patched_) {
return false;
}
patched_ = true;
if (unprotect ()) {
memcpy (reinterpret_cast <void *> (originalFun_), hookedBytes_.get (), CodeLength);
return true;
}
return false;
}
bool disable () {
if (!patched_) {
return false;
}
patched_ = false;
if (unprotect ()) {
memcpy (reinterpret_cast <void *> (originalFun_), originalBytes_.get (), CodeLength);
return true;
}
return false;
}
bool enabled () const {
return patched_;
}
public:
template <typename T, typename... Args > decltype (auto) call (Args &&...args) {
disable ();
auto res = reinterpret_cast <T *> (originalFun_) (args...);
enable ();
return res;
}
};
CR_NAMESPACE_END

View file

@ -118,7 +118,7 @@ public:
}
public:
template <typename R> static inline R CR_STDCALL getSymbol (Handle module, const char *function) {
template <typename R> static inline R CR_STDCALL getSymbol (Handle module, const char *function) {
return reinterpret_cast <R> (
#if defined (CR_WINDOWS)
GetProcAddress (static_cast <HMODULE> (module), function)

View file

@ -24,7 +24,7 @@
#include <math.h>
// avoid linking to GLIBC_2.27
#if defined (CR_LINUX) && !defined (CR_CXX_INTEL) && defined (CR_ARCH_X86)
#if defined (CR_LINUX) && !defined (CR_CXX_INTEL)
__asm__ (".symver powf,powf@GLIBC_2.0");
#endif