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

View file

@ -621,27 +621,26 @@ public:
class EntityLinkage : public Singleton <EntityLinkage> {
private:
#if defined (CR_WINDOWS)
# define HOOK_FUNCTION GetProcAddress
# define HOOK_CAST HMODULE
# define DETOUR_FUNCTION GetProcAddress
# define DETOUR_RETURN FARPROC
# define DETOUR_HANDLE HMODULE
#else
# define HOOK_FUNCTION dlsym
# define HOOK_CAST SharedLibrary::Handle
# define DETOUR_FUNCTION dlsym
# define DETOUR_RETURN SharedLibrary::Handle
# define DETOUR_HANDLE SharedLibrary::Handle
#endif
private:
SharedLibrary m_self;
SimpleHook m_dlsym;
HashMap <StringRef, SharedLibrary::Handle> m_exports;
Detour <decltype (DETOUR_FUNCTION)> m_dlsym { "kernel32.dll", "GetProcAddress", DETOUR_FUNCTION };
HashMap <StringRef, DETOUR_RETURN> m_exports;
public:
EntityLinkage () = default;
~EntityLinkage () {
m_dlsym.disable ();
}
public:
void initialize ();
SharedLibrary::Handle lookup (SharedLibrary::Handle module, const char *function);
DETOUR_RETURN lookup (SharedLibrary::Handle module, const char *function);
public:
void callPlayerFunction (edict_t *ent) {
@ -653,7 +652,7 @@ public:
}
public:
static SharedLibrary::Handle CR_STDCALL CR_STDCALL replacement (SharedLibrary::Handle module, const char *function) {
static DETOUR_RETURN CR_STDCALL replacement (SharedLibrary::Handle module, const char *function) {
return EntityLinkage::instance ().lookup (module, function);
}
};

View file

@ -38,7 +38,7 @@ private:
HashMap <int32, String> m_weaponAlias;
HashMap <String, int32> m_noiseCache;
SimpleHook m_sendToHook;
Detour <decltype (sendto)> m_sendToDetour { "ws2_32.dll", "sendto", sendto };
public:
BotSupport ();
@ -134,12 +134,7 @@ public:
// disables send hook
bool disableSendTo () {
return m_sendToHook.disable ();
}
// enables send hook
bool enableSendTo () {
return m_sendToHook.enable ();
return m_sendToDetour.restore ();
}
// gets the shooting cone deviation

View file

@ -1144,12 +1144,12 @@ float LightMeasure::getSkyColor () {
return static_cast <float> (Color (sv_skycolor_r.int_ (), sv_skycolor_g.int_ (), sv_skycolor_b.int_ ()).avg ());
}
SharedLibrary::Handle EntityLinkage::lookup (SharedLibrary::Handle module, const char *function) {
DETOUR_RETURN EntityLinkage::lookup (SharedLibrary::Handle module, const char *function) {
static const auto &gamedll = game.lib ().handle ();
static const auto &self = m_self.handle ();
const auto resolve = [&] (SharedLibrary::Handle handle) {
return reinterpret_cast <SharedLibrary::Handle> (m_dlsym.call <decltype (HOOK_FUNCTION)> (static_cast <HOOK_CAST> (handle), function));
return reinterpret_cast <DETOUR_RETURN> (m_dlsym (static_cast <DETOUR_HANDLE> (handle), function));
};
// if requested module is yapb module, put in cache the looked up symbol
@ -1180,6 +1180,6 @@ void EntityLinkage::initialize () {
return;
}
m_dlsym.patch (reinterpret_cast <SharedLibrary::Handle> (&HOOK_FUNCTION), reinterpret_cast <SharedLibrary::Handle> (&EntityLinkage::replacement));
m_dlsym.install (reinterpret_cast <void *> (EntityLinkage::replacement), true);
m_self.locate (&engfuncs);
}

View file

@ -305,7 +305,7 @@ void BotSupport::checkWelcome () {
.writeShort (MessageWriter::fu16 (2.0f, 8.0f))
.writeShort (MessageWriter::fu16 (6.0f, 8.0f))
.writeShort (MessageWriter::fu16 (0.1f, 8.0f))
.writeString (strings.format ("\nHello! You are playing with %s v%s (Build: %s)\nDevised by %s\n\n%s", product.name, product.version, product.build.count, product.author, graph.getAuthor ()));
.writeString (strings.format ("\nHello! You are playing with %s v%s (Revision: %s)\nDevised by %s\n\n%s", product.name, product.version, product.build.count, product.author, graph.getAuthor ()));
m_welcomeReceiveTime = 0.0f;
m_needToSendWelcome = false;
@ -634,7 +634,7 @@ void BotSupport::sendPings (edict_t *to) {
void BotSupport::installSendTo () {
// if previously requested to disable?
if (!cv_enable_query_hook.bool_ ()) {
if (m_sendToHook.enabled ()) {
if (m_sendToDetour.detoured ()) {
disableSendTo ();
}
return;
@ -646,8 +646,8 @@ void BotSupport::installSendTo () {
}
// enable only on modern games
if (game.is (GameFlags::Modern) && (plat.linux || plat.win32) && !plat.arm && !m_sendToHook.enabled ()) {
m_sendToHook.patch (reinterpret_cast <void *> (&sendto), reinterpret_cast <void *> (&BotSupport::sendTo));
if (game.is (GameFlags::Modern) && (plat.linux || plat.win32) && !plat.arm && !m_sendToDetour.detoured ()) {
m_sendToDetour.install (reinterpret_cast <void *> (BotSupport::sendTo), true);
}
}

View file

@ -17,9 +17,9 @@
<ClInclude Include="..\ext\crlib\cr-binheap.h" />
<ClInclude Include="..\ext\crlib\cr-color.h" />
<ClInclude Include="..\ext\crlib\cr-complete.h" />
<ClInclude Include="..\ext\crlib\cr-dict.h" />
<ClInclude Include="..\ext\crlib\cr-hashmap.h" />
<ClInclude Include="..\ext\crlib\cr-files.h" />
<ClInclude Include="..\ext\crlib\cr-hook.h" />
<ClInclude Include="..\ext\crlib\cr-detour.h" />
<ClInclude Include="..\ext\crlib\cr-http.h" />
<ClInclude Include="..\ext\crlib\cr-lambda.h" />
<ClInclude Include="..\ext\crlib\cr-library.h" />
@ -88,12 +88,14 @@
<PlatformToolset>v142</PlatformToolset>
<UseOfMfc>false</UseOfMfc>
<WholeProgramOptimization>true</WholeProgramOptimization>
<EnableASAN>false</EnableASAN>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseOfMfc>false</UseOfMfc>
<PlatformToolset>v142</PlatformToolset>
<EnableASAN>false</EnableASAN>
<UseDebugLibraries>false</UseDebugLibraries>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
@ -159,7 +161,7 @@
<SuppressStartupBanner>true</SuppressStartupBanner>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<CompileAs>Default</CompileAs>
<BufferSecurityCheck>false</BufferSecurityCheck>
<BufferSecurityCheck>true</BufferSecurityCheck>
<StringPooling>false</StringPooling>
<InlineFunctionExpansion>Default</InlineFunctionExpansion>
<MultiProcessorCompilation>true</MultiProcessorCompilation>

View file

@ -93,15 +93,9 @@
<ClInclude Include="..\ext\crlib\cr-complete.h">
<Filter>inc\ext\crlib</Filter>
</ClInclude>
<ClInclude Include="..\ext\crlib\cr-dict.h">
<Filter>inc\ext\crlib</Filter>
</ClInclude>
<ClInclude Include="..\ext\crlib\cr-files.h">
<Filter>inc\ext\crlib</Filter>
</ClInclude>
<ClInclude Include="..\ext\crlib\cr-hook.h">
<Filter>inc\ext\crlib</Filter>
</ClInclude>
<ClInclude Include="..\ext\crlib\cr-http.h">
<Filter>inc\ext\crlib</Filter>
</ClInclude>
@ -141,6 +135,12 @@
<ClInclude Include="..\ext\crlib\cr-vector.h">
<Filter>inc\ext\crlib</Filter>
</ClInclude>
<ClInclude Include="..\ext\crlib\cr-detour.h">
<Filter>inc\ext\crlib</Filter>
</ClInclude>
<ClInclude Include="..\ext\crlib\cr-hashmap.h">
<Filter>inc\ext\crlib</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\src\android.cpp">