Initial commit

This commit is contained in:
drof
2026-11-05 02:19:09 +01:00
commit 13f8503697
125 changed files with 17029 additions and 0 deletions
+93
View File
@@ -0,0 +1,93 @@
#include <include.h>
void c_entity_cache::initialize()
{
_entities = stl::mem_alloc<decltype(_entities)>( sizeof(cache::player_t) * cache::capacity );
if (_entities == nullptr)
{
log_info_("failed to allocate entity-cache storage space.");
return report_failure();
}
}
void c_entity_cache::on_createmove()
{
on_update();
}
void c_entity_cache::collect_entities()
{
size_t valid_count = 0;
size_t player_count = ix::global_vars->MaxClients;
const auto my_index = ix::engine_client->get_local_player();
for (auto i = 0; i < ix::entity_list->get_highest_entity_index(); i++)
{
auto entity = ix::entity_list->get_client_entity<respawn::c_entity>(i);
auto& entry = _entities[i];
if (entity == nullptr)
{
entry.valid = false;
continue;
}
entry.valid = true;
entry.index = i;
entry.entity_type = respawn::get_entity_type(entity);
if (!entry.m_pointer || entry.m_pointer != entity)
{
//
// Invalidate our cached information.
//
auto model_name = entity->model_name();
if (model_name && stl::strlen(model_name) < sizeof(entry.m_model_name))
stl::strcpy(entry.m_model_name, model_name);
entry.m_pointer = entity;
}
process_base(i, entity, entry);
++valid_count;
}
_entity_count = ix::entity_list->get_highest_entity_index();
}
void c_entity_cache::on_update()
{
if (!g::is_in_game)
return;
collect_entities();
}
void c_entity_cache::reset()
{
memset(_entities, 0, sizeof(cache::player_t) * cache::capacity);
}
void* c_entity_cache::get_pointer_internal(size_t index)
{
if (index >= _entity_count || index >= cache::capacity)
return {};
auto info = _entities[index];
if (!info.valid)
return {};
//
// check if the cached data is still valid for the given index.
//
if (info.m_pointer != ix::entity_list->get_client_entity<void*>( static_cast<int>(index) ))
return {};
return info.m_pointer;
}
+176
View File
@@ -0,0 +1,176 @@
#include <include.h>
void cache::process_player(int index, respawn::c_player* player, cache::entry_t& entry, cache::player_t& data)
{
if (ix::entity_list->get_client_entity<respawn::c_player>(index) != player)
return;
data.m_valid = true;
data.m_life_state = player->life_state();
if (data.m_life_state == LIFE_ALIVE)
{
data.m_team_number = player->team_number();
data.m_color = respawn::get_player_color(player);
data.m_health = player->health();
data.m_health_max = player->health_max();
data.m_armor = player->armor();
data.m_armor_max = player->armor_max();
data.m_visible = player->is_visible();
data.m_teammate = respawn::is_teammate(player);
//
// this data is only valid for actual players and not for dummies.
// make sure to NOT collect them, otherwise you might get bogus data and crashes.
//
if (entry.type == cache::types::player)
{
data.m_bleedout_state = player->bleed_out_state();
data.m_velocity = player->velocity();
}
else
{
data.m_bleedout_state = 0;
data.m_velocity = { 0.f, 0.f, 0.f };
}
data.m_origin = player->origin();
respawn::get_entity_center_pos(player, data.m_center);
if (data.m_name[0] == NULL)
{
if (respawn::is_player(player, true, false))
{
respawn::player_info_t pl_info{};
if (ix::engine_client->get_player_info(index, &pl_info))
memcpy(data.m_name, pl_info.pad, sizeof(data.m_name));
}
else
{
stl::strcpy(data.m_name, _XS("dummie"));
}
}
for (auto bone_id = 0; bone_id < respawn::bone_count; bone_id++)
{
if (!player->get_bone_position(bone_id, data.m_bones[bone_id]))
break;
}
}
}
void cache::process_npc(int index, respawn::c_npc* npc, cache::entry_t& entry, cache::npc_t& data)
{
if (ix::entity_list->get_client_entity<respawn::c_npc>(index) != npc)
return;
data.m_valid = true;
data.m_life_state = npc->life_state();
if (data.m_life_state == LIFE_ALIVE)
{
data.m_origin = npc->origin();
data.m_health = npc->health();
data.m_health_max = npc->health_max();
respawn::get_entity_center_pos(npc, data.m_center);
}
}
void cache::process_loot(int index, respawn::c_prop_survival* entity, cache::loot_t& data)
{
if (ix::entity_list->get_client_entity<respawn::c_prop_survival>(index) != entity)
return;
data.m_valid = true;
data.m_origin = entity->origin();
data.m_script_id = entity->custom_script_int();
respawn::get_entity_center_pos(entity, data.m_center);
}
void cache::process_dynamic_prop(int index, respawn::c_entity* entity, cache::entry_t& entry, cache::prop_dynamic_t& data)
{
if (ix::entity_list->get_client_entity<respawn::c_entity>(index) != entity)
return;
data.m_valid = true;
data.m_origin = entity->origin();
respawn::get_entity_center_pos(entity, data.m_center);
//
// Need to identify dynamic props by their model name.
//
using pd_types = cache::prop_dynamic_types;
switch (util::string_hash(entry.m_model_name, stl::strlen(entry.m_model_name)))
{
case 0x853c46d9:
data.m_type = pd_types::shooting_range_target;
break;
case 0x84a17394:
data.m_type = pd_types::trap_gas;
break;
}
}
void cache::process_base(int index, respawn::c_entity* entity, cache::entry_t& entry)
{
using type = respawn::entity_types;
switch (respawn::get_entity_type(entity))
{
case type::PLAYER:
{
entry.type = cache::types::player;
process_player(index, mem::addr(entity).As<respawn::c_player*>(), entry, entry.type_specific.plr);
break;
}
case type::DUMMIE:
{
entry.type = cache::types::dummie;
process_player(index, mem::addr(entity).As<respawn::c_player*>(), entry, entry.type_specific.plr);
break;
}
case type::PROWLER:
{
entry.type = cache::types::npc;
process_npc(index, mem::addr(entity).As<respawn::c_npc*>(), entry, entry.type_specific.npc);
break;
}
case type::PROP_SURVIVAL:
{
entry.type = cache::types::loot;
process_loot(index, mem::addr(entity).As<respawn::c_prop_survival*>(), entry.type_specific.loot);
break;
}
case type::PROP_DYNAMIC:
{
entry.type = cache::types::dynamic_prop;
process_dynamic_prop(index, entity, entry, entry.type_specific.prop_dynamic);
break;
}
case type::PROP_SCRIPT:
{
entry.type = cache::types::script_prop;
process_dynamic_prop(index, entity, entry, entry.type_specific.prop_dynamic);
break;
}
default:
entry.type = cache::types::none;
break;
}
}
+97
View File
@@ -0,0 +1,97 @@
#include <include.h>
void c_config::initialize()
{
m_parser = new (stl::mem_alloc<void*>(sizeof(c_json))) c_json();
if (m_parser == nullptr)
return;
if (!get_path(m_path, sizeof(m_path)))
return;
m_ready = true;
}
void c_config::shutdown()
{
if (!m_ready)
return;
if (m_parser)
stl::mem_free(m_parser);
}
bool c_config::validate(void* file_ptr)
{
if (m_parser->parse(reinterpret_cast<LPCSTR>(file_ptr)))
{
m_valid = true;
return true;
}
log_info_("config file is invalid.");
m_valid = false;
return false;
}
void c_config::on_start()
{
if (util::file_exists_wide(m_path))
{
//
// We found a configuration file, process it.
//
void* file_ptr = util::get_file_ptr(m_path);
if (file_ptr)
{
validate(file_ptr);
stl::mem_free(file_ptr);
}
}
else
{
log_info_("config file could not be found.");
//
// No configuration file was found.
//
//
// TODO: Implement.
//
__noop();
}
}
bool c_config::get_path(wchar_t* buffer, size_t length)
{
if (buffer && length)
{
char path_desktop[MAX_PATH];
char path_result[MAX_PATH];
ZERO_MEM(path_desktop, sizeof(path_desktop));
if (util::get_desktop_directory(path_desktop, sizeof(path_desktop)))
{
util::format_string(
path_result, length,
_XS("\\??\\%s\\%s"),
path_desktop,
_XS("hs.cfg")
);
stl::mbstowcs(buffer, path_result, 0, length);
return true;
}
}
return false;
}
+112
View File
@@ -0,0 +1,112 @@
#include <include.h>
void dyn_addr::add_dynamic_address_code(const char* name, const wchar_t* pattern, uint32_t offset)
{
auto entry = entry_t{};
memset(&entry, 0, sizeof(entry));
entry.type = entry_t::DYN_ADDR_TYPE_CODE;
entry.offset = offset;
memcpy(entry.name, name, stl::strlen(name) * sizeof(char));
memcpy(entry.pattern, pattern, stl::wcslen(pattern) * sizeof(wchar_t));
_list.insert(entry);
}
void dyn_addr::add_dynamic_address_ptr(const char* name, const wchar_t* pattern,
uint32_t offset, uint32_t offset_to_instr, uint32_t length_of_instr)
{
auto entry = entry_t{};
memset(&entry, 0, sizeof(entry));
entry.type = entry_t::DYN_ADDR_TYPE_PTR;
entry.offset = offset;
entry.ptr = { offset_to_instr, length_of_instr };
memcpy(entry.name, name, stl::strlen(name) * sizeof(char));
memcpy(entry.pattern, pattern, stl::wcslen(pattern) * sizeof(wchar_t));
_list.insert(entry);
}
bool dyn_addr::grab_all()
{
auto handled = true;
for (auto* entry_info = _list.first_entry();
entry_info != nullptr;
entry_info = entry_info->m_next)
{
if (entry_info->m_is_head)
continue;
auto& entry = entry_info->m_data;
switch (entry.type)
{
case entry_t::DYN_ADDR_TYPE_CODE:
{
entry.result = FIND_SIG(
g::p::context->m_process_info.base,
g::p::context->m_process_info.length,
entry.pattern, entry.offset);
break;
}
case entry_t::DYN_ADDR_TYPE_PTR:
{
entry.result = FIND_PTR(
g::p::context->m_process_info.base,
g::p::context->m_process_info.length,
entry.pattern,
entry.offset,
entry.ptr.offset_to_instr,
entry.ptr.length_of_instr
);
break;
}
default:
handled = false;
break;
}
if (handled)
{
log_info("found DA '%s' -> %p",
entry.name, mem::addr(entry.result).Ptr());
}
else
{
return false;
}
}
return true;
}
uintptr_t dyn_addr::get_dynamic_address(const char* name)
{
uintptr_t result = 0;
for (auto* entry_info = _list.first_entry();
entry_info != nullptr;
entry_info = entry_info->m_next)
{
if (entry_info->m_is_head)
continue;
auto& entry = entry_info->m_data;
if (!stl::strcmp(entry.name, name))
{
result = entry.result;
break;
}
}
return result;
}
+31
View File
@@ -0,0 +1,31 @@
#include <include.h>
namespace dyn_offs
{
auto retrieve(LPCWSTR sig, std::initializer_list<uint8_t> pattern, u_long offset, size_t opcode_len) noexcept
{
uintptr_t result{ };
uintptr_t game_base = g::p::context->m_process_info.base;
uintptr_t game_length = g::p::context->m_process_info.length;
if (game_base && game_length)
{
uintptr_t address = FIND_SIG(game_base, game_length, sig, offset);
if (address)
result = shared::sig::find_offset(address, pattern.begin(), pattern.size(), offset, opcode_len);
}
return result;
}
}
bool dyn_offs::initialize()
{
_::player::last_visible_time = retrieve(_XSW(L"41 B1 09 48 8D 15 ? ? ? ? 48 8D 4C 24 ? E8 ? ? ? ? 48 85 C0 74 08"), { 0x8B, 0x8B }, 0, 2);
_::player::view_offset = retrieve(_XSW(L"48 83 EC 38 8B 05 ? ? ? ? 0F 29 74 24 ? 83 F8 FF 74"), { 0xF3, 0x41, 0x0F, 0x10, 0x80 }, 0, 5);
_::player::eye_angles = retrieve(_XSW(L"75 08 4C 8B C0 0F 28 CC EB 33"), { 0xF3, 0x0F, 0x11, 0x81 }, 0, 4);
return true;
}
+283
View File
@@ -0,0 +1,283 @@
#include <include.h>
using namespace features;
bool c_aim::find_target(respawn::c_player* me, cache::entry_t* result, aim::find_context_t& ctx)
{
ctx.viable_targets = 0;
ctx.closest_distance = ctx.maximum_distance;
ctx.closest_fov = ctx.maximum_fov;
ctx.me = me;
ctx.my_position = me->origin();
ctx.my_view = me->view_offset();
ctx.my_angle = me->eye_angles();
size_t viable_targets{ };
aim::find_context_t target_ctx{ };
for (auto i = 0ull; i < g::p::ent_cache.count(); i++)
{
auto entity = g::p::ent_cache.get_neutral(i);
if (!entity.valid)
continue;
if (aim::is_target_viable(entity, ctx))
{
*result = entity;
target_ctx = ctx;
++viable_targets;
}
}
ctx = target_ctx;
return viable_targets;
}
bool c_aim::is_weapon_compatible(respawn::c_weapon* wpn) noexcept
{
auto name_idx = wpn->name_index();
if (name_idx == respawn::weapon_name_indexes::hands)
return false;
return true;
}
void c_aim::create_move(respawn::c_player* me, respawn::user_cmd_t* cmd)
{
if (!cfg::aim_enabled)
return;
if (!respawn::is_playing())
return;
if (me == nullptr)
return;
if (!respawn::is_alive(me) || respawn::is_knocked(me))
return;
auto* const my_wpn = me->get_active_weapon();
if (my_wpn == nullptr || !is_weapon_compatible(my_wpn))
return;
if (cfg::aim_bullet_time && !my_wpn->can_fire(me))
{
is_aiming = false;
return;
}
cache::entry_t target{ };
aim::find_context_t find_ctx{ };
find_ctx.maximum_distance = cfg::aim_distance;
find_ctx.maximum_fov = cfg::aim_fov;
if (cfg::aim_distance <= 0.1f)
find_ctx.maximum_distance = FLT_MAX;
if (g::p::cache.local_player.zooming)
find_ctx.maximum_fov /= 2.5f;
effective_max_fov_ = find_ctx.maximum_fov;
if (!find_target(me, &target, find_ctx))
{
is_aiming = false;
return;
}
auto bone_id = respawn::bone_id::head;
if (cfg::aim_random_hitbox)
bone_id = respawn::bone_id::torso_upper;
auto my_shoot_pos = me->view_offset();
auto hit_pos = find_ctx.aim_pos;
auto aim_ang = math::Angle3{};
if (cfg::aim_bullet_prediction)
{
auto get_distance = [](math::Vector3 target_pos, math::Vector3 our_pos)
{
float dist = math::sqrtf((our_pos.x - target_pos.x) * (our_pos.x - target_pos.x)
+ (our_pos.y - target_pos.y) * (our_pos.y - target_pos.y)
+ (our_pos.z - target_pos.z) * (our_pos.z - target_pos.z));
return dist * 0.01905f;
};
auto velocity = find_ctx.target_info.velocity;
if (velocity.Length2d() > 0.f)
{
auto world_gravity = 750.f;
auto distance = get_distance(hit_pos, my_shoot_pos) / 0.01905f;
auto bullet_speed = my_wpn->projectile_speed();
auto bullet_gravity = my_wpn->projectile_gravity();
auto travel_time = (distance / bullet_speed);
auto prediction_scale = max(cfg::aim_bullet_prediction_scale, bullet_gravity);
hit_pos.x += (velocity.x * travel_time) * prediction_scale;
hit_pos.y += (velocity.y * travel_time) * prediction_scale;
hit_pos.z += (world_gravity * travel_time * travel_time) * prediction_scale;
}
}
math::VectorAngles((hit_pos - my_shoot_pos), aim_ang);
auto my_angle = me->eye_angles();
auto my_angle_dyn = (!cfg::no_sway ? me->dyn_angles() : g::p::sway_angles);
if (cfg::aim_no_recoil > 0)
{
auto delta = (my_angle_dyn - my_angle);
auto length = delta.Length2d();
if (cfg::aim_no_recoil == 1)
{
delta.x = (delta.x / 2.f);
delta.y = (delta.y / 2.f);
}
if (length > 0.f)
{
aim_ang.x -= delta.x;
aim_ang.y -= delta.y;
}
}
if (cfg::aim_smooth_out && cfg::aim_smooth > 0.f)
{
auto vCurrentAngle = my_angle;
auto vAimDelta = (aim_ang - vCurrentAngle);
math::NormalizeAngle(vCurrentAngle);
math::NormalizeAngle(vAimDelta);
const auto flMultiplier = cfg::aim_smooth;
const auto vActualAimAngle = aim_ang; // back it up so we can compare it later.
if (vAimDelta.x >= +89.f || vAimDelta.x <= -89.f)
vAimDelta.x = 0.f;
if (flMultiplier >= 0.01f)
{
aim_ang.x = vCurrentAngle.x + ((vAimDelta.x + FLT_EPSILON) / flMultiplier);
aim_ang.y = vCurrentAngle.y + ((vAimDelta.y + FLT_EPSILON) / flMultiplier);
aim_ang.z = 0.f;
}
}
bool should_aim = false;
if (cfg::aim_ignore_key)
should_aim = true;
else if (cfg::aim_auto_fire && g::p::input_mgr.is_button_down(VK_SHIFT))
should_aim = true;
else if (cmd->buttons & IN_ATTACK)
should_aim = true;
if (cfg::aim_rapid_fire)
{
if (cmd->buttons & IN_ATTACK && my_wpn->can_fire(me))
cvar::time_scale->m_value_float = cfg::aim_rapid_fire_boost;
else
cvar::time_scale->m_value_float = 1.f;
}
if (should_aim)
{
is_aiming = true;
target_pos_ = hit_pos;
wish_angle = aim_ang;
switch (cfg::aim_silent)
{
case 0: // plain
cmd->viewangles = aim_ang;
me->eye_angles() = aim_ang;
break;
case 1: // silent (1)
case 2: // silent (2)
cmd->viewangles = aim_ang;
break;
default:
break;
}
if (cfg::aim_auto_fire)
cmd->buttons |= IN_ATTACK;
}
else
{
is_aiming = false;
writecmd_silent = false;
wish_angle = { };
}
}
void c_aim::cl_move(respawn::c_player* me)
{
//
// ...
//
}
void c_aim::paint()
{
if (!respawn::is_playing())
return;
if (!cfg::aim_enabled)
return;
if(cfg::aim_visualize_range)
draw_range();
if (is_aiming)
{
math::Vector3 target_scr{ };
if (respawn::world_to_screen(target_pos_, target_scr))
{
const float x_center = target_scr.x;
const float y_center = target_scr.y;
const float width = 5.0f;
g::p::render.draw_rect_filled(respawn::colors::red, x_center - width, y_center - 1.0f, x_center + width, y_center + 1.0f);
g::p::render.draw_rect_filled(respawn::colors::red, x_center - 1.0f, y_center - width, x_center + 1.0f, y_center + width);
g::p::render.draw_rect(respawn::colors::red, x_center - width, y_center - 1.0f, x_center + width, y_center + 1.0f);
g::p::render.draw_rect(respawn::colors::red, x_center - 1.0f, y_center - width, x_center + 1.0f, y_center + width);
}
}
}
void c_aim::draw_range()
{
auto screen = g::p::screen;
float local_fov = 110.f;
float valid_fov = effective_max_fov_ / local_fov;
float local_range = (local_fov * static_cast<float>(M_PI) / 180.f);
float valid_range = (valid_fov * static_cast<float>(M_PI) / 180.f);
float radius = (math::tanf((valid_fov / 2.f)) / math::tanf((local_fov / 2.f)) * screen.w * 25.f);
float scenter_x = (screen.w / 2);
float scenter_y = (screen.h / 2);
g::p::render.draw_circle(respawn::colors::white, scenter_x, scenter_y, radius, 100, 125);
}
+43
View File
@@ -0,0 +1,43 @@
#include <include.h>
using bone_id = respawn::bone_id;
static bone_id bone_array[] = { bone_id::head, bone_id::neck, bone_id::spine, bone_id::torso_center, bone_id::torso_lower, bone_id::torso_upper };
respawn::bone_id aim::get_optimal_bone_id(const cache::player_t& player)
{
const auto& lp_data = g::p::cache.local_player;
if (cfg::aim_random_hitbox)
return bone_id::torso_upper;
if (cfg::aim_dynamic_hitbox)
{
auto closest_bone = bone_id{ };
auto maximum_fov = FLT_MAX;
auto closest_fov = maximum_fov;
const auto& shoot_position = lp_data.shoot_pos;
for (auto i = 0; i < ARRAYSIZE(bone_array); i++)
{
auto id = bone_array[i];
auto bone_position = player.m_bones[ static_cast<int>(id) ];
auto fov = math::SE::get_fov_difference(lp_data.eye_angle, shoot_position, bone_position);
if (fov > maximum_fov)
continue;
if (fov < closest_fov)
{
closest_bone = static_cast<bone_id>(id);
closest_fov = fov;
continue;
}
}
return closest_bone;
}
return bone_id::head;
}
+28
View File
@@ -0,0 +1,28 @@
#include <include.h>
void aim::psilent(respawn::c_player* me, respawn::c_weapon* weapon)
{
const auto net_chan = respawn::net_chan();
if (net_chan == nullptr)
return;
if (!ix::engine_client->is_in_game())
return;
const auto choked_packets = net_chan->num_choked_packets();
const auto last_out_cmd_nr = respawn::last_out_cmd_nr();
if (f::aim.is_aiming)
{
g::choke_this_tick = (choked_packets <= cfg::aim_choke_cap);
auto* const silent_cmd = ix::input->get_user_cmd(last_out_cmd_nr - 1);
if (silent_cmd && silent_cmd->command_number)
{
silent_cmd->buttons |= IN_ATTACK;
silent_cmd->viewangles = f::aim.wish_angle;
}
}
}
+110
View File
@@ -0,0 +1,110 @@
#include <include.h>
bool aim::is_target_viable(cache::entry_t& entity, aim::find_context_t& ctx)
{
auto& info = ctx.target_info;
switch (entity.type)
{
case cache::types::dummie:
case cache::types::player:
{
if (cfg::aim_players)
{
auto& player = entity.type_specific.plr;
if (player.m_teammate && !cfg::aim_friendly_fire)
return false;
if (player.m_life_state != LIFE_ALIVE)
return false;
if (!player.m_visible)
return false;
ctx.aim_pos = player.m_bones[static_cast<int>(get_optimal_bone_id(player))];
info.velocity = player.m_velocity;
}
break;
}
case cache::types::npc:
{
switch (entity.entity_type)
{
case respawn::entity_types::PROWLER:
if (cfg::aim_prowler)
{
auto& npc = entity.type_specific.npc;
if (npc.m_life_state != LIFE_ALIVE)
return false;
ctx.aim_pos = npc.m_center;
info.velocity = { };
break;
}
}
break;
}
case cache::types::dynamic_prop:
case cache::types::script_prop:
{
const auto& prop = entity.type_specific.prop_dynamic;
using prop_type = cache::prop_dynamic_types;
switch (prop.m_type)
{
case prop_type::shooting_range_target:
if (cfg::aim_firing_range_targets)
{
ctx.aim_pos = prop.m_center;
info.velocity = { };
}
break;
}
break;
}
default:
return false;
}
//
// At this point the current target has been classified as viable.
// Calculate aim angles and such, and then perform some checks.
//
auto entity_pos = ctx.aim_pos;
auto arbitrary_aim_angle = math::Angle3{};
math::VectorAngles((entity_pos - ctx.my_position), arbitrary_aim_angle);
auto distance = entity_pos.DistanceTo(ctx.my_position) / 4096.f;
auto fov = math::SE::get_fov_difference(ctx.my_angle, ctx.my_view, entity_pos);
if (distance > ctx.maximum_distance)
return false;
if (fov > ctx.maximum_fov)
return false;
if (fov < ctx.closest_fov)
{
ctx.closest_fov = fov;
++ctx.viable_targets;
return true;
}
return false;
}
+477
View File
@@ -0,0 +1,477 @@
#include <include.h>
using namespace features;
void c_esp::draw_bar(respawn::color_t color, FLOAT flX, FLOAT flY, FLOAT flW, FLOAT flH, int current, const int max)
{
if (current < 0)
current = 0;
if (current > max)
current = max;
flY -= flH;
const float base = flH / static_cast<float>(max) * static_cast<float>(current);
const float delta = (flH - base);
const float bar_x = flX;
g::p::render.draw_rect_filled({ 5, 5, 5 }, bar_x, flY, bar_x + 5.0f, flY + flH, 175);
g::p::render.draw_rect_filled(color, bar_x, flY + delta, bar_x + 5.0f, flY + flH);
g::p::render.draw_rect({ 5, 5, 5 }, bar_x, flY, bar_x + 5.0f, flY + flH);
}
void c_esp::draw_outline(respawn::color_t color, int opacity, math::Vector3 scr_origin, float bw, float bh)
{
g::p::render.draw_rect_bordered(color, scr_origin.x - bw, scr_origin.y - bh, scr_origin.x + bw, scr_origin.y + 5.f, opacity);
}
void c_esp::show_debug_ents()
{
const auto& local_player_data = g::p::cache.local_player;
const auto my_origin = local_player_data.origin;
math::Vector3 screen{};
for (auto i = 0; i < ix::entity_list->get_highest_entity_index(); i++)
{
auto* const entity = ix::entity_list->get_client_entity<respawn::c_entity>(i);
if (entity == nullptr)
continue;
if (!respawn::world_to_screen(entity->origin(), screen))
continue;
if (!entity->identifier())
continue;
const auto distance = entity->origin().DistanceTo(my_origin) / 4096.f;
if (distance > 512.f)
continue;
g::p::render.draw_text_ex(
respawn::colors::white, 2, 12, screen.x,
screen.y, _XS("[%s]\n[%s]"),
entity->identifier(),
entity->model_name()
);
}
}
void c_esp::process_player(int index, const cache::entry_t& entry, const cache::player_t& player)
{
const auto& local_player_data = g::p::cache.local_player;
if (!player.m_valid)
return;
if (index == g::p::cache.local_player.index)
{
if (!cfg::esp_show_local_player)
return;
if (cvar::third_person->m_value_numeric != 1)
return;
}
else
{
if (player.m_teammate && !cfg::esp_show_team_mates)
return;
}
const auto is_ally = (player.m_team_number == local_player_data.team_number);
const auto is_knocked = (player.m_bleedout_state != 0);
math::Vector3 pos_head, pos_origin = player.m_origin;
math::Vector3 scr_head, scr_origin;
if (player.m_life_state != 0)
return;
pos_head = player.m_bones[7];
if (!respawn::world_to_screen(pos_head, scr_head) ||
!respawn::world_to_screen(pos_origin, scr_origin))
return;
const auto bounds_height = math::fabsf(scr_head.y - scr_origin.y) * 1.5f;
const auto bounds_width = (bounds_height / 2.5f);
const auto distance = pos_origin.DistanceTo(local_player_data.origin) / 4096.f;
if (distance > cfg::esp_object_render_dist)
return;
const auto render_text = (distance < cfg::esp_text_render_dist);
const auto opacity = player.m_visible ? 255 : 125;
const auto draw_pos_top_x = scr_origin.x + (bounds_width / 2.f);
const auto draw_pos_top_y = scr_origin.y - (bounds_height + 20.f);
float draw_pos_top_push = 0.f;
if (render_text)
{
if (cfg::esp_players_name)
{
g::p::render.draw_text_centered(
respawn::colors::white, 2, 14,
draw_pos_top_x, draw_pos_top_y - draw_pos_top_push,
player.m_name
);
draw_pos_top_push += 15.f;
}
if (cfg::esp_players_health > 0 && player.m_health > 0)
{
if (cfg::esp_players_health == 1)
{
g::p::render.draw_text_centered(
respawn::colors::green, 2, 14,
draw_pos_top_x, draw_pos_top_y - draw_pos_top_push,
_XS("%i HP"), player.m_health
);
}
else if (cfg::esp_players_health == 2)
{
g::p::render.draw_text_centered(
respawn::colors::green, 2, 14,
draw_pos_top_x, draw_pos_top_y - draw_pos_top_push,
_XS("%i/%i HP"), player.m_health, player.m_health_max
);
}
draw_pos_top_push += 15.f;
}
if (cfg::esp_players_armor > 0 && player.m_armor > 0)
{
if (cfg::esp_players_armor == 1)
{
g::p::render.draw_text_centered(
respawn::colors::blue, 2, 14,
draw_pos_top_x, draw_pos_top_y - draw_pos_top_push,
_XS("%i AR"), player.m_armor
);
}
else if (cfg::esp_players_armor == 2)
{
g::p::render.draw_text_centered(
respawn::colors::blue, 2, 14,
draw_pos_top_x, draw_pos_top_y - draw_pos_top_push,
_XS("%i/%i AR"), player.m_armor, player.m_armor_max
);
}
}
}
if(cfg::esp_players_outline)
draw_outline(player.m_color, opacity, scr_origin, bounds_width, bounds_height);
if(cfg::esp_players_health_bar && player.m_health_max > 0)
draw_bar({ 65, 255, 65 }, scr_origin.x - bounds_width - 6.f, scr_origin.y, bounds_width, bounds_height, player.m_health, player.m_health_max);
if(cfg::esp_players_armor_bar && player.m_armor_max > 0)
draw_bar({ 65, 65, 255 }, scr_origin.x + bounds_width + 2.f, scr_origin.y, bounds_width, bounds_height, player.m_armor, player.m_armor_max);
if (cfg::esp_player_bone_ids)
draw_bone_identifiers(player);
}
void c_esp::process_prowler(int index, const cache::entry_t& entry, const cache::npc_t& npc)
{
const auto& local_player_data = g::p::cache.local_player;
if (!npc.m_valid)
return;
math::Vector3 scr_origin, pos_origin = npc.m_origin;
if (!respawn::world_to_screen(pos_origin, scr_origin))
return;
const auto distance = pos_origin.DistanceTo(local_player_data.origin) / 4096.f;
if (distance > 4096.f)
return;
g::p::render.draw_text(respawn::colors::yellow, 2, 20, scr_origin.x, scr_origin.y, _XS("PROWLER"));
g::p::render.draw_text_ex(
respawn::colors::white, 2, 20,
scr_origin.x, scr_origin.y + 22,
_XS("%i HP"),
npc.m_health
);
}
void c_esp::process_loot(int index, const cache::entry_t& entry, const cache::loot_t& loot)
{
const auto& local_player_data = g::p::cache.local_player;
if (!loot.m_valid)
return;
math::Vector3 scr_origin, pos_origin = loot.m_origin;
if (!respawn::world_to_screen(pos_origin, scr_origin))
return;
const auto distance = pos_origin.DistanceTo(local_player_data.origin) / 4096.f;
if (distance > 1024.f)
return;
using lid = respawn::loot_ids;
bool found = true;
std::pair<const char*, respawn::color_t> ldef;
switch ( static_cast<lid>(loot.m_script_id) )
{
/*case lid::SHIELD_BLUE: ldef = std::make_pair(_XS("SH"), respawn::colors::blue); break;
case lid::SHIELD_PURP: ldef = std::make_pair(_XS("SH"), respawn::colors::purple); break;
case lid::SHIELD_GOLD: ldef = std::make_pair(_XS("SH"), respawn::colors::yellow); break;
case lid::BACKPACK_BLUE: ldef = std::make_pair(_XS("BP"), respawn::colors::blue); break;
case lid::BACKPACK_PURP: ldef = std::make_pair(_XS("BP"), respawn::colors::purple); break;
case lid::BACKPACK_GOLD: ldef = std::make_pair(_XS("BP"), respawn::colors::yellow); break;
case lid::HELMET_BLUE: ldef = std::make_pair(_XS("H"), respawn::colors::blue); break;
case lid::HELMET_PURP: ldef = std::make_pair(_XS("H"), respawn::colors::purple); break;
case lid::HELMET_GOLD: ldef = std::make_pair(_XS("H"), respawn::colors::yellow); break;*/
case lid::WEAPON_CHARGE_RIFLE: ldef = std::make_pair(_XS("CR"), respawn::colors::blue); break;
default:
found = false;
break;
}
if (found)
{
g::p::render.draw_text(ldef.second, 2, 14, scr_origin.x, scr_origin.y, ldef.first);
}
else if (cfg::esp_loot_unknown)
{
g::p::render.draw_text_ex(
respawn::colors::yellow, 2, 14,
scr_origin.x, scr_origin.y, _XS("ID: %i"),
loot.m_script_id
);
}
}
void process_generic(const math::Vector3& origin, const char* name, const respawn::color_t color)
{
const auto& local_player_data = g::p::cache.local_player;
math::Vector3 scr_origin, pos_origin = origin;
if (!respawn::world_to_screen(pos_origin, scr_origin))
return;
const auto distance = pos_origin.DistanceTo(local_player_data.origin) / 4096.f;
if (distance > 4096.f)
return;
g::p::render.draw_text(color, 2, 20, scr_origin.x, scr_origin.y, name);
}
void c_esp::overlay_hud()
{
float push = 0.f;
constexpr float start_x = 150.f, start_y = 5.f;
//
//
//
if (cfg::other_debug_overlay)
{
g::p::render.draw_text_ex(respawn::colors::white, 2, 14, start_x, start_y + push, _XS("is_ingame= %i"), g::is_in_game);
push += 15.f;
g::p::render.draw_text_ex(respawn::colors::white, 2, 14, start_x, start_y + push, _XS("engine time= %i"), (int)*gv::engine_time);
push += 15.f;
g::p::render.draw_text_ex(respawn::colors::white, 2, 14, start_x, start_y + push, _XS("current time= %i"), (int)ix::global_vars->Curtime);
push += 15.f;
g::p::render.draw_text_ex(respawn::colors::white, 2, 14, start_x, start_y + push, _XS("sway angles= (%i, %i, %i)"),
(int)g::p::sway_angles.x, (int)g::p::sway_angles.y, (int)g::p::sway_angles.z);
push += 15.f;
if (g::is_in_game)
{
g::p::render.draw_text_ex(respawn::colors::white, 2, 14, start_x, start_y + push, _XS("local_player= %p"), g::p::cache.local_player.address);
push += 15.f;
g::p::render.draw_text_ex(respawn::colors::white, 2, 14, start_x, start_y + push, _XS("local_weapon= %p"), g::p::cache.local_weapon.address);
push += 15.f;
if (g::p::cache.local_weapon.address)
{
g::p::render.draw_text_ex(respawn::colors::white, 2, 14, start_x, start_y + push, _XS(" reloading= %i"), g::p::cache.local_weapon.reloading);
push += 15.f;
g::p::render.draw_text_ex(respawn::colors::white, 2, 14, start_x, start_y + push, _XS(" next_primary_attack= %i"), (int)g::p::cache.local_weapon.next_primary_attack);
push += 15.f;
g::p::render.draw_text_ex(respawn::colors::white, 2, 14, start_x, start_y + push, _XS(" next_ready_time= %i"), (int)g::p::cache.local_weapon.next_ready_time);
push += 15.f;
g::p::render.draw_text_ex(respawn::colors::white, 2, 14, start_x, start_y + push, _XS(" can_fire= %i"), (int)g::p::cache.local_weapon.can_fire);
push += 15.f;
}
}
}
if (g::unprotected_game)
{
g::p::render.draw_text(respawn::colors::red, 2, 14, start_x, start_y + push, _XS("*UNPROTECTED GAME*"));
push += 15.f;
}
if (cfg::aim_enabled)
{
if (cfg::aim_silent == 0 || cfg::aim_silent == 1)
{
g::p::render.draw_text(respawn::colors::red, 2, 14, start_x, start_y + push, _XS("*UNSAFE AIM*"));
push += 15.f;
}
}
if (cfg::custom_crosshair_enabled)
{
if (respawn::is_playing())
{
const auto screen_size = g::p::screen;
const float x_center = static_cast<float>(screen_size.w) / 2.0f;
const float y_center = static_cast<float>(screen_size.h) / 2.0f;
const float width = cfg::custom_crosshair_size;
g::p::render.draw_rect_filled(respawn::colors::white, x_center - width, y_center - 1.0f, x_center + width, y_center + 1.0f);
g::p::render.draw_rect_filled(respawn::colors::white, x_center - 1.0f, y_center - width, x_center + 1.0f, y_center + width);
if (cfg::custom_crosshair_outline)
{
g::p::render.draw_rect(respawn::colors::black, x_center - width, y_center - 1.0f, x_center + width, y_center + 1.0f);
g::p::render.draw_rect(respawn::colors::black, x_center - 1.0f, y_center - width, x_center + 1.0f, y_center + width);
}
}
}
}
void c_esp::info_panel()
{
}
void c_esp::draw_bone_identifiers(const cache::player_t& player)
{
math::Vector3 pos, screen;
for (auto i = 0ull; i < 20; i++)
{
pos = player.m_bones[i];
if (!respawn::world_to_screen(pos, screen))
continue;
char text[64];
util::format_string(text, sizeof(text), _XS("%i"), i);
g::p::render.draw_text({ 65, 255, 65 }, 2, 15, screen.x, screen.y, text);
}
}
void c_esp::paint()
{
if (!cfg::esp_enabled)
return;
if (cfg::esp_show_debug_ents)
{
show_debug_ents();
return;
}
if (respawn::is_playing())
{
for (auto i = 0ull; i < g::p::ent_cache.count(); i++)
{
auto data = g::p::ent_cache.get_neutral(i);
if (!data.valid)
continue;
switch (data.type)
{
case cache::types::player:
case cache::types::dummie:
{
if (cfg::esp_players)
process_player(i, data, data.type_specific.plr);
break;
}
case cache::types::npc:
{
using ent_type = respawn::entity_types;
switch (data.entity_type)
{
case ent_type::PROWLER:
if(cfg::esp_prowler)
process_prowler(i, data, data.type_specific.npc);
break;
}
break;
}
case cache::types::loot:
{
if (cfg::esp_loot)
process_loot(i, data, data.type_specific.loot);
break;
}
case cache::types::dynamic_prop:
case cache::types::script_prop:
{
using pd_types = cache::prop_dynamic_types;
switch (data.type_specific.prop_dynamic.m_type)
{
case pd_types::shooting_range_target:
if(cfg::esp_firing_range_targets)
process_generic(data.type_specific.prop_dynamic.m_center, _XS("X"), respawn::colors::red);
break;
case pd_types::trap_gas:
if(cfg::esp_traps)
process_generic(data.type_specific.prop_dynamic.m_center, _XS("GAS-T"), respawn::colors::yellow);
break;
}
break;
}
default:
break;
}
}
}
overlay_hud();
info_panel();
}
+108
View File
@@ -0,0 +1,108 @@
#include <include.h>
using namespace features;
respawn::color_t c_glow::get_color(const cache::player_t& player)
{
auto result = respawn::color_t{};
const int current_shield = player.m_armor;
const int current_health = player.m_health;
const int max_shield = player.m_armor_max;
const int max_health = player.m_health_max;
const int total_health = (current_health + current_shield);
const int split_count = 3;
const auto frac_shield = ((max_shield + 1) / 3);
const auto frac_health = ((max_health + 1) / 3);
if (player.m_bleedout_state == 0)
{
if (frac_shield && frac_health)
{
const auto shield_state = ((current_shield + 1) / frac_shield);
const auto health_state = ((current_health + 1) / frac_health);
const auto total_state = (shield_state + health_state);
switch (total_state)
{
case 0:
case 1:
result = respawn::glow_colors::red;
break;
case 2:
case 3:
result = respawn::glow_colors::yellow;
break;
case 4:
case 5:
case 6:
result = respawn::glow_colors::green;
break;
default:
break;
}
}
else
result = respawn::glow_colors::green;
}
else
result = respawn::glow_colors::white;
return result;
}
void c_glow::create_move(respawn::c_player* me, respawn::user_cmd_t* cmd)
{
const auto& local_player_data = g::p::cache.local_player;
for (auto i = 0ull; i < g::p::ent_cache.count(); i++)
{
auto entry = g::p::ent_cache.get_neutral(i);
if (!entry.valid)
continue;
switch (entry.type)
{
case cache::types::player:
case cache::types::dummie:
break;
default:
continue;
}
auto data = entry.type_specific.plr;
if (entry.index == g::p::cache.local_player.index)
{
continue;
}
else
{
if (data.m_teammate && !cfg::esp_show_team_mates)
continue;
}
auto* const pointer = g::p::ent_cache.get_pointer<respawn::c_player*>(i);
if (pointer)
{
if (cfg::esp_enabled && cfg::esp_players && cfg::esp_players_glow)
{
pointer->glow_enabled() = true;
pointer->glow_type() = 0x2;
pointer->glow_config() = { 101, 102, 46, 96 };
pointer->glow_color() = get_color(data);
}
else
{
if (pointer->glow_enabled())
pointer->glow_enabled() = false;
}
}
}
}
+69
View File
@@ -0,0 +1,69 @@
#include <include.h>
using namespace features;
void c_logger::paint()
{
draw_messages();
}
void c_logger::draw_messages()
{
float push_y = 0.0f;
float start_x = 2.0f, start_y = 2.0f;
for (auto i = 0ul; i < m_fields.count(); i++)
{
field_t* entry = m_fields[i];
if (entry == nullptr)
continue;
bool requires_removal = (entry->m_time_registered && math::fabsf(entry->m_time_registered - *gv::engine_time) > entry->m_duration);
size_t text_height = 14;
size_t text_width = g::p::render.get_text_width(entry->m_text, text_height);
g::p::render.draw_rect_filled(
respawn::color_t{25, 25, 25}, start_x, start_y + push_y,
start_x + 1 + text_width,
start_y + push_y + text_height + 1.0f
);
g::p::render.draw_text(entry->m_color, 2, static_cast<int>(text_height), start_x + 1, start_y + push_y, entry->m_text);
if (requires_removal)
{
m_fields.remove(*entry);
break;
}
push_y += text_height;
}
}
void c_logger::add_message(float duration, respawn::color_t color, const char* fmt, ...)
{
stl::my_lock_guard _(&m_lock);
if (!duration || !fmt)
return;
va_list list{ };
field_t entry{ };
memset(&entry, 0, sizeof(entry));
if( stl::strlen(fmt) >= (sizeof(entry.m_text) - 1) )
return;
entry.m_duration = duration;
entry.m_color = color;
entry.m_time_registered = *gv::engine_time;
va_start(list, fmt);
LI_FN(wvsprintfA).cached()(entry.m_text, fmt, list);
va_end(list);
m_fields.insert(entry);
}
+193
View File
@@ -0,0 +1,193 @@
#include <include.h>
using namespace features;
void bunnyhop(bool& hopping, respawn::c_player* me, respawn::user_cmd_t* cmd)
{
if (!cfg::movement_bunny_hop)
return;
if (hopping)
{
if (!(cmd->buttons & IN_JUMP))
{
hopping = false;
return;
}
if (!(me->flags() & FL_ONGROUND))
cmd->buttons &= ~IN_JUMP;
}
else
{
if (cmd->buttons & IN_DUCK)
hopping = true;
}
}
void freecam(respawn::c_player* me)
{
static bool is_toggled{ };
g::in_freecam = cfg::movement_freecam && is_toggled;
if (si::create_move.was_button_down(VK_NUMPAD7))
is_toggled = !is_toggled;
me->observer_mode() = g::in_freecam ? 7 : 0;
}
void thirdperson()
{
static bool previous_enabled{ };
static bool is_toggled{ };
static int initial_value{ };
if (!initial_value)
initial_value = cvar::third_person->m_value_numeric;
const auto maintain_value = []()
{
if (cfg::movement_thirdperson && is_toggled)
cvar::third_person->m_value_numeric = 1;
else
cvar::third_person->m_value_numeric = initial_value;
};
if (previous_enabled != cfg::movement_thirdperson)
{
maintain_value();
previous_enabled = cfg::movement_thirdperson;
}
if (si::create_move.was_button_down(VK_XBUTTON1))
{
is_toggled = !is_toggled;
maintain_value();
}
}
void airstuck()
{
static bool is_toggled{ };
static int initial_value{ };
if (!initial_value)
initial_value = cvar::move_use_dt->m_value_numeric;
const auto maintain_value = []()
{
if (is_toggled)
cvar::move_use_dt->m_value_numeric = 0;
else
cvar::move_use_dt->m_value_numeric = initial_value;
};
if (si::create_move.was_button_down(VK_NUMPAD4))
{
is_toggled = !is_toggled;
maintain_value();
}
}
void fakelag(respawn::c_player* me)
{
static bool is_toggled{ };
if (!cfg::fake_lag)
return;
const auto my_index = g::p::cache.local_player.index;
const auto my_team_number = g::p::cache.local_player.team_number;
const auto choked_packets = g::p::cache.net_chan.num_choked_packets;
if (cfg::fake_lag == 1)
{
//
// adaptive, based on enemy sight.
//
size_t num_visible_opponents{};
for (auto i = 0ull; i < ix::global_vars->MaxClients; i++)
{
if (i == my_index)
continue;
auto player_data = g::p::ent_cache.get_player(i);
if (!player_data.m_valid)
continue;
if (player_data.m_team_number == my_team_number)
continue;
if (!player_data.is_alive() || !player_data.m_visible)
continue;
++num_visible_opponents;
}
if (num_visible_opponents > 0)
g::choke_this_tick = (choked_packets < cfg::fake_lag_choke_cap);
}
else if (cfg::fake_lag == 2)
{
//
// full pulled, all time.
// TODO: once we figure out xbutton keys for input handler,
// make an option like on aimbot called ignore key
// and make the default one require a key like on the external.
//
if ( (!cfg::fake_lag_ignore_key && g::p::input_mgr.is_button_down(VK_XBUTTON2)) || cfg::fake_lag_ignore_key)
{
g::choke_this_tick = (choked_packets < cfg::fake_lag_choke_cap);
}
}
}
void charge_rifle(respawn::c_player* me)
{
if (!cfg::other_infinite_charge_rifle)
return;
static bool toggled = false;
if (si::create_move.was_button_down(VK_F12))
{
toggled = !toggled;
if (!toggled)
{
cvar::time_scale->m_value_float = 1.f;
}
}
auto my_wpn = me->get_active_weapon();
if (my_wpn)
{
if (my_wpn->projectile_speed() == 1.f)
{
if (toggled)
{
cvar::time_scale->m_value_float = 0.000000000000000000000000000000001f;
}
}
}
}
void c_movement::create_move(respawn::c_player* me, respawn::user_cmd_t* cmd)
{
if (respawn::is_playing())
{
bunnyhop(m_hopping, me, cmd);
charge_rifle(me);
}
freecam(me);
fakelag(me);
thirdperson();
airstuck();
}
+165
View File
@@ -0,0 +1,165 @@
#include <include.h>
using namespace features;
void force_heirloom(respawn::c_entity* vm, int model_index)
{
if (!vm || !model_index)
return;
vm->set_model_index(model_index);
}
bool is_valid_sequence(int heirloom_idx, int sequence_nr)
{
int blacklisted_sequence_nr = 0;
switch (heirloom_idx)
{
case HEIRLOOM_IDX_WRAITH:
case HEIRLOOM_IDX_BLOODHOUND:
blacklisted_sequence_nr = 60;
break;
case HEIRLOOM_IDX_LIFELINE:
blacklisted_sequence_nr = 65;
break;
case HEIRLOOM_IDX_PATHFINDER_GLOVES:
blacklisted_sequence_nr = 64;
break;
case HEIRLOOM_IDX_OCTANE_KNIFE:
blacklisted_sequence_nr = 57;
break;
case HEIRLOOM_IDX_MIRAGE:
blacklisted_sequence_nr = 53;
break;
case HEIRLOOM_IDX_GIBRALTAR:
blacklisted_sequence_nr = 71;
break;
case HEIRLOOM_IDX_BANGALORE:
blacklisted_sequence_nr = 79;
break;
default:
//
// No validation for this specific heirloom.
//
break;
}
return (sequence_nr != blacklisted_sequence_nr);
}
void reset_sequence(int heirloom_idx, uint32_t* sequence_nr)
{
uint32_t default_sequence = 0;
switch (heirloom_idx)
{
case HEIRLOOM_IDX_WRAITH:
case HEIRLOOM_IDX_BLOODHOUND:
default_sequence = 46;
break;
case HEIRLOOM_IDX_LIFELINE:
default_sequence = 48;
break;
case HEIRLOOM_IDX_PATHFINDER_GLOVES:
default_sequence = 51;
break;
case HEIRLOOM_IDX_OCTANE_KNIFE:
default_sequence = 42;
break;
case HEIRLOOM_IDX_MIRAGE:
default_sequence = 43;
break;
case HEIRLOOM_IDX_GIBRALTAR:
default_sequence = 57;
break;
case HEIRLOOM_IDX_BANGALORE:
default_sequence = 59;
break;
default:
//
// No rule for this specific heirloom.
//
break;
}
if (default_sequence != 0)
*sequence_nr = default_sequence;
}
void c_skin_changer::create_move(respawn::c_player* me, respawn::user_cmd_t* cmd)
{
}
bool is_hands(respawn::c_entity* entity)
{
auto model_name = entity->model_name();
if (model_name)
{
if (stl::strlen(model_name) == 45)
{
if (model_name[12] == 'e' && model_name[15] == 't' && model_name[18] == 'h')
return true;
}
}
return false;
}
void c_skin_changer::frame_stage_notify(int stage, respawn::c_player* me)
{
if (!cfg::other_heirloom_changer_active || !respawn::is_playing())
return;
if (me == nullptr)
return;
switch (stage)
{
case respawn::frame_render_start:
{
if (!respawn::is_alive(me) || respawn::is_knocked(me))
return;
auto my_wpn = me->get_active_weapon();
auto my_vm = me->get_view_model();
if (my_wpn == nullptr || my_vm == nullptr)
return;
auto name_idx = my_wpn->name_index();
if (name_idx != respawn::weapon_name_indexes::hands)
return;
if (!is_hands(my_vm))
return;
auto heirloom_idx = ix::model_info->get_model_index(respawn::_heirloom_table.get(cfg::other_heirloom_index));
if (!heirloom_idx || heirloom_idx == -1)
return;
const auto cur_sequence = my_vm->anim_sequence();
const auto cur_activity = my_vm->get_sequence_activity(cur_sequence);
force_heirloom(my_vm, heirloom_idx);
auto new_sequence = my_vm->get_activity_sequence(cur_activity);
if (new_sequence != UINT32_MAX)
{
if (!is_valid_sequence(cfg::other_heirloom_index, new_sequence))
reset_sequence(cfg::other_heirloom_index, &new_sequence);
my_vm->anim_sequence() = new_sequence;
}
break;
}
default:
break;
}
}
+195
View File
@@ -0,0 +1,195 @@
#include <include.h>
using namespace hook;
namespace u
{
bool patch_stealth(uint32_t pid, void* target, uint8_t* bytes, size_t length)
{
if (target == nullptr || bytes == nullptr || pid == 0 || length <= 0)
return false;
if (!hvi::write_virt_memory(pid, mem::addr(target).Base(), bytes, length, true))
return false;
return true;
}
bool patch(void* target, void* bytes, size_t length, bool cow_page)
{
auto process = win_api::get_current_process_id();
auto prot = ulong{};
auto backup = uint8_t{};
if (cow_page)
{
if (!hvi::protect_virt_memory(
process, (uintptr_t)target,
page_size, PAGE_EXECUTE_READWRITE, &prot
))
return false;
*(uint8_t*)((uintptr_t)target + 0x8) = 0x1;
win_api::rebuilt::sleep(1000);
*(uint8_t*)((uintptr_t)target + 0x8) = 0x0;
}
if (!patch_stealth(
process, target,
(uint8_t*)bytes, length
))
return false;
return true;
}
}
bool detour::protect_virtual_memory(void* pAddress, size_t uLength, ulong uProt, ulong* uOldProt)
{
ulong uDummy{};
ulong* puProt = (uOldProt != nullptr) ? uOldProt : &uDummy;
return hvi::protect_virt_memory(
win_api::get_current_process_id(), (uintptr_t)pAddress,
uLength, uProt, puProt
);
}
bool detour::copy_virtual_memory(void* pDst, void* pSrc, size_t uLength, bool bStealth)
{
return u::patch(pDst, (uint8_t*)pSrc, uLength, true);
}
bool detour::place(void* pTarget, void* pHandler,
void** pOriginal, size_t* uBackupLength,
void* pRealTarget,
u32* pdwErrorCode,
bool bUseSafeRegister,
bool bSmallFunction
)
{
const bool is_hooking_shadow_page = !(pRealTarget == nullptr);
const auto handler = reinterpret_cast<DWORD_PTR>(pHandler);
auto redirect_shell = instr::jump_t(handler);
auto backup_length = size_t{};
// determine if the target is eligible for hooking with this particular method and
// also how many bytes we are required to back-up in order to allow smooth transition.
constexpr size_t snippet_length = 128;
auto* const snippet_buffer = stl::mem_alloc<uint8_t*>(snippet_length);
if (snippet_buffer == nullptr)
{
if (pdwErrorCode)
*pdwErrorCode = 0xE01;
return false;
}
RtlSecureZeroMemory(snippet_buffer, snippet_length);
// copy a "snippet/piece" of the target function inside a local buffer and start processing it.
// usually, we'll come to our required instruction size by the first 128 bytes, if not, then
// we'll refuse to work. TODO: maybe change this logic to allow reading for more?
if (!copy_virtual_memory(snippet_buffer, pTarget, snippet_length))
{
if (pdwErrorCode)
*pdwErrorCode = 0xE02;
return false;
}
uint32_t disasm_sc = 0;
if (!hde::is_function_hookable(snippet_buffer, snippet_length,
&backup_length, sizeof(redirect_shell), disasm_sc))
{
if (pdwErrorCode)
*pdwErrorCode = 0xE03;
return false;
}
if (uBackupLength)
*uBackupLength = backup_length;
// that is only required for determining if it's hookable and some other things.
// but after the function has returned, we generally don't need it anymore.
stl::mem_free(snippet_buffer);
{
const size_t original_length = ((sizeof(redirect_shell) * 2) + (2 * sizeof(void*)));
auto* const original_ptr =
stl::mem_alloc<void*>(original_length);
if (original_ptr == nullptr)
{
if (pdwErrorCode)
*pdwErrorCode = 0xE04;
return false;
}
if (!protect_virtual_memory(original_ptr,
original_length, PAGE_EXECUTE_READWRITE))
return false;
void* trampoline_escape_target = (is_hooking_shadow_page ? pRealTarget : pTarget);
const auto trampoline_escape_dst =
(reinterpret_cast<uintptr_t>(trampoline_escape_target) + backup_length);
auto trampoline_shell = instr::jump_safe_t(trampoline_escape_dst);
// zero the original buffer.
RtlZeroMemory(original_ptr, original_length);
if (!bSmallFunction)
{
UINT8 backup_data[256] = { 0 };
RtlCopyMemory(&backup_data[0], pTarget, backup_length);
// copy backup bytes into the original buffer.
RtlCopyMemory(original_ptr, backup_data, backup_length);
}
// append the jump away from our trampoline at the end of here.
auto* const trampoline_dst_ptr =
reinterpret_cast<void*>(
reinterpret_cast<uintptr_t>(original_ptr)
+ backup_length);
RtlCopyMemory(trampoline_dst_ptr, &trampoline_shell,
sizeof(trampoline_shell));
// pass the original to the output parameter.
// NOTE: make sure to free this memory this when un-hooking.
if (pOriginal && !(*pOriginal))
*pOriginal = original_ptr;
}
if (!copy_virtual_memory(pTarget, &redirect_shell, sizeof(redirect_shell), true))
{
if (pdwErrorCode)
*pdwErrorCode = 0xE05;
return false;
}
return true;
}
bool detour::restore(void* pTarget, void* pOriginal, size_t uBackupLength)
{
const auto uOriginalLength = uBackupLength;
if (!copy_virtual_memory(pTarget, pOriginal, static_cast<ulong>(uOriginalLength)))
return false;
stl::mem_free(pOriginal);
return true;
}
+299
View File
@@ -0,0 +1,299 @@
#include <include.h>
bool hooks::register_(hooks::data_t& data, bool resolve_jt, bool small_fn)
{
uintptr_t actual_target{};
if (resolve_jt)
{
if (!hde::resolve_jump(data.m_target, actual_target, true))
return false;
}
else
actual_target = mem::addr(data.m_target).Base();
if (!actual_target)
return false;
const auto result =
hook::detour::place(mem::addr(actual_target).Ptr(),
data.m_handler, &data.m_original,
&data.m_backup_length, nullptr,
nullptr, FALSE, small_fn
);
return result;
}
bool hooks::initialize_early()
{
log_call();
if (mh::MH_Initialize() != mh::MH_OK)
{
log_info_("failed to initialize mh.");
return false;
}
if (!setup_detours_api())
{
log_info_("failed to setup API hooks.");
return false;
}
if (!setup_detours_early())
{
log_info_("failed to setup GAME hooks (early).");
return false;
}
return true;
}
bool hooks::initialize()
{
log_call();
if (!setup_vmt() || !setup_detours())
{
log_info_("failed to setup GAME hooks.");
return false;
}
/*if (!setup_detours_ac())
{
log_info_("failed to setup AC hooks.");
return false;
}*/
constexpr auto unprotect_game = false;
if (unprotect_game)
{
const auto& process_info = g::p::context->m_process_info;
if (util::protect_virtual_memory((void*)process_info.base, process_info.length, PAGE_EXECUTE_READWRITE))
{
log_info_("deprotected the process memory for debugging.");
g::unprotected_game = true;
}
}
return true;
}
bool hooks::setup_detours_early()
{
if (!mh::stealth_patch(BASE_OF(VTABLE_FUNC(ix::file_system, HOOK_IDX_LOOKUP_FILE)), &lookup_file, &o::lookup_file))
return false;
return true;
}
bool hooks::setup_detours()
{
if (!mh::stealth_patch(dyn_addr::get_dynamic_address(_XS("fn_write_user_cmd")), &write_user_cmd, &o::write_user_cmd))
return false;
if (!mh::stealth_patch(dyn_addr::get_dynamic_address(_XS("fn_paint_end")), &paint_fn, &o::paint_fn))
return false;
if (!mh::stealth_patch(BASE_OF(VTABLE_FUNC(ix::base_client, HOOK_IDX_FRAME_STAGE_NOTIFY)), &frame_stage_notify, &o::frame_stage_notify))
return false;
if (!mh::stealth_patch(BASE_OF(VTABLE_FUNC(ix::engine_client, HOOK_IDX_GET_PLAYER_INFO)), &get_player_info, &o::get_player_info))
return false;
if (!mh::stealth_patch(BASE_OF(VTABLE_FUNC(ix::input, HOOK_IDX_INPUT_CREATE_MOVE)), &create_move, &o::create_move))
return false;
if (!mh::stealth_patch(dyn_addr::get_dynamic_address(_XS("view_render_start")), &view_render_start, &o::view_render_start))
return false;
if (!mh::stealth_patch(dyn_addr::get_dynamic_address(_XS("cl_move")), &cl_move, &o::cl_move))
return false;
uint8_t patch_silent[] = { 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90 };
if (!mh::stealth_patch_bytes(DYN_ADDR("silent1"), patch_silent, sizeof(patch_silent)) ||
!mh::stealth_patch_bytes(DYN_ADDR("silent1") + 0x12, patch_silent, sizeof(patch_silent)) ||
!mh::stealth_patch_bytes(DYN_ADDR("silent1") + 0x1A, patch_silent, sizeof(patch_silent)))
return false;
return true;
}
bool set_callback_user_exception_dispatcher(void* handler)
{
struct patch_t
{
patch_t(uintptr_t dst)
{
pad[0] = 0x90;
pad[1] = 0x90;
bytes[0] = 0x48;
bytes[1] = 0xB8;
memcpy(dest, &dst, sizeof(dest));
}
uint8_t bytes[2];
uint8_t dest[8];
uint8_t pad[2];
} patch( mem::addr(handler).Base() );
auto func_addr = util::find_export<uintptr_t>(_XS("ntdll.dll"), _XS("KiUserExceptionDispatcher"));
if (!func_addr)
return false;
func_addr += 0x1;
if (!hv::trigger_cow(func_addr))
return false;
if (!hvi::write_virt_memory(
win_api::get_current_process_id(),
func_addr, &patch, sizeof(patch),
true
))
return false;
return true;
}
bool hooks::setup_detours_api()
{
if (!set_callback_user_exception_dispatcher(&api::user_exception_dispatcher))
return false;
if (!mh::stealth_patch_api(
util::find_export<uintptr_t>(_XS("kernel32.dll"),
_XS("AddVectoredExceptionHandler")),
&api::add_veh_handler, &o::api_::add_veh_handler
))
return false;
if (!mh::stealth_patch_api(
util::find_export<uintptr_t>(_XS("kernel32.dll"),
_XS("RemoveVectoredExceptionHandler")),
&api::remove_veh_handler, &o::api_::remove_veh_handler))
return false;
if (!mh::stealth_patch_api(
util::find_export<uintptr_t>(_XS("ntdll.dll"),
_XS("NtQueryInformationThread")),
&api::query_info_thread, &o::api_::query_info_thread))
return false;
if (!mh::stealth_patch_api(
util::find_export<uintptr_t>(_XS("kernel32.dll"),
_XS("GetThreadContext")),
&api::get_thread_context, &o::api_::get_thread_context))
return false;
if (!mh::stealth_patch_api(
util::find_export<uintptr_t>(_XS("user32.dll"),
_XS("TranslateMessage")),
&api::translate_message, &o::api_::translate_message))
return false;
return true;
}
bool hooks::setup_detours_ac()
{
auto* const ctx = g::p::acc::eac;
if (ctx == nullptr || !ctx->launched || !ctx->internal_module.found)
return false;
const auto module_base = ctx->internal_module.base;
const auto module_length = ctx->internal_module.length;
if (!module_base || !module_length)
return false;
struct detour_t
{
const char* name;
const wchar_t* pattern;
void* handler;
void** original;
};
auto list = stl::vector<detour_t>();
list.push_back({
_XS("fetch_suspect_strings"),
_XSW(L"48 89 5C 24 ? 48 89 74 24 ? 48 89 7C 24 ? 55 41 56 41 57 48 8B EC 48 83 EC 70 48 8B 5A 08 48 8B"),
&ac::fetch_suspect_strings,
(void**)&o::ac_::fetch_suspect_string,
});
list.push_back({
_XS("fetch_suspect_system_calls"),
_XSW(L"48 89 54 24 ? 48 89 4C 24 ? 53 56 57 41 54 41 55 41 56 41 57 48 81 EC ? ? ? ? 48 8B DA 4C 8B F9"),
&ac::fetch_suspect_strings,
(void**)&o::ac_::fetch_suspect_system_calls
});
/*list.push_back({
_XS("detect_suspect_memory_regions"),
_XSW(L"48 8B C4 48 89 58 10 48 89 70 18 48 89 78 20 55 41 54 41 55 41 56 41 57 48 8D 68 A8 48 81 EC"),
&ac::detect_suspect_memory_regions,
(void**)&o::ac_::detect_suspect_memory_regions
});*/
for (auto i = 0ull; i < list.size(); i++)
{
const auto& info = list[i];
if (!info.pattern || !info.handler || !info.original)
{
log_info("invalid ac_detour data at index %i.", i);
return false;
}
const auto target = shared::sig::FindPattern(
module_base,
module_length,
info.pattern
);
if (!target)
{
log_info("failed ot find ac_detour data at index %i.", i);
return false;
}
log_info("found ac_detour target for index %i at %p.", i, target);
if (!mh::stealth_patch(target, info.handler, info.original))
{
log_info("failed to do ac_detour for index %i and target %p.", i, target);
return false;
}
log_info("performed ac_detour for index %i and target %p.", i, target);
}
return true;
}
bool hooks::setup_vmt()
{
return true;
}
void hooks::shutdown()
{
log_call();
//
// ..
//
}
+28
View File
@@ -0,0 +1,28 @@
#include <include.h>
bool __fastcall hooks::ac::fetch_suspect_strings(void* a1, void* a2)
{
log_mon_call("(%p, %p)", a1, a2);
g::p::on_ac_event(0xB01);
return false;
}
bool __fastcall hooks::ac::fetch_suspect_system_calls(void* a1, void* a2)
{
log_mon_call("(%p, %p)", a1, a2);
g::p::on_ac_event(0xB02);
return false;
}
char __fastcall hooks::ac::detect_suspect_memory_regions(void* a1)
{
log_mon_call("(%p)", a1);
g::p::on_ac_event(0xB03);
return false;
}
+167
View File
@@ -0,0 +1,167 @@
#include <include.h>
void* __fastcall hooks::api::add_veh_handler(ulong first, void* handler)
{
auto* const original_fn = o::api_::add_veh_handler;
log_mon_call("()");
if (r5::is_within_eac(_ReturnAddress()))
{
g::p::on_ac_event(0xF01);
log_info_("blocking EAC attempt to register VEH handler.");
return nullptr;
}
return original_fn(first, handler);
}
ulong __fastcall hooks::api::remove_veh_handler(void* handle)
{
auto* const original_fn = o::api_::remove_veh_handler;
log_mon_call("()");
return original_fn(handle);
}
ulong __fastcall hooks::api::query_info_thread(
_handle thread, THREADINFOCLASS info_class,
void* info_buffer, ulong info_length,
ulong* return_length
)
{
auto* const original_fn = o::api_::query_info_thread;
log_mon_call("()");
if (r5::is_within_eac(_ReturnAddress()))
{
g::p::on_ac_event(0xF02);
log_info_("blocking call to query info thread from EAC.");
return STATUS_ACCESS_VIOLATION;
}
return original_fn(
thread, info_class,
info_buffer, info_length,
return_length
);
}
int __fastcall hooks::api::get_thread_context(_handle thread, CONTEXT* ctx)
{
auto* const original_fn = o::api_::get_thread_context;
log_mon_call("()");
return original_fn(thread, ctx);
}
ulong __fastcall hooks::api::device_ioctl_file(
_handle file_handle, _handle event, PIO_APC_ROUTINE apc_routine, PVOID apc_ctx,
PIO_STATUS_BLOCK iosb, ulong ioctl_code, PVOID input_buffer,
ULONG input_buffer_len, PVOID output_buffer, ULONG output_buffer_len
)
{
auto* const original_fn = o::api_::device_ioctl_file;
return original_fn(
file_handle, event, apc_routine, apc_ctx, iosb,
ioctl_code, input_buffer, input_buffer_len,
output_buffer, output_buffer_len
);
}
int __fastcall hooks::api::translate_message(PMSG msg)
{
auto* const original_fn = o::api_::translate_message;
r5::on_window_proc(msg->message, msg->wParam, msg->lParam);
return original_fn(msg);
}
__forceinline bool file_header_to_info(uintptr_t address, hvi::module_info_ex* result)
{
auto my_context = g::p::context;
auto eac_context = g::p::acc::eac;
if (my_context && my_context->m_initialized)
{
auto my_begin = g::p::context->my_base;
auto my_end = my_begin + g::p::context->my_length;
if (address >= my_begin && address <= my_end)
{
result->base = my_begin;
result->length = g::p::context->my_length;
stl::wcscpy(result->name, _XSW(L"game_r5.dll"));
return true;
}
}
if (eac_context && eac_context->launched && eac_context->internal_module.found)
{
auto im_begin = eac_context->internal_module.base;
auto im_end = im_begin + eac_context->internal_module.length;
if (address >= im_begin && address <= im_end)
{
result->base = im_begin;
result->length = eac_context->internal_module.length;
stl::wcscpy(result->name, _XSW(L"eac_internal.dll"));
return true;
}
}
auto list = stl::vector<hvi::module_info_ex>();
if (hvi::get_module_list(win_api::get_current_process_id(), list))
{
for (auto i = 0ull; i < list.size(); i++)
{
const auto& mod = list[i];
auto mod_begin = mod.base;
auto mod_end = mod_begin + mod.length;
if (address >= mod_begin && address <= mod_end)
{
result->base = mod_begin;
result->length = mod.length;
stl::wcscpy(result->name, mod.name);
return true;
}
}
}
return false;
}
void __fastcall hooks::api::user_exception_dispatcher(PEXCEPTION_RECORD record, PCONTEXT context)
{
constexpr auto capture_exceptions = false;
hvi::module_info_ex exception_module{ };
bool module_found = file_header_to_info(context->Rip, &exception_module);
if (!capture_exceptions)
return;
char fmt[256];
util::format_string(
fmt, sizeof(fmt), _XS("CODE = %p | RIP_RAW = %p | MODULE = %ls | RVA = %p \n"),
record->ExceptionCode, context->Rip,
module_found ? exception_module.name : _XSW(L"N/A"),
(context->Rip - exception_module.base)
);
util::write_data(fmt, _XSW(L"C:/Users/Berkan/Desktop/EX/ed.txt"));
}
+158
View File
@@ -0,0 +1,158 @@
#include <include.h>
void __fastcall hooks::frame_stage_notify(void* this_ptr, int stage)
{
auto* const original_fn = o::frame_stage_notify;
r5::on_fsn(stage);
return original_fn(this_ptr, stage);
}
void __fastcall hooks::create_move(void* this_ptr, int seq_nr, float sample_time, bool active)
{
auto* const original_fn = o::create_move;
g::p::ent_cache.on_createmove();
original_fn(this_ptr, seq_nr, sample_time, active);
if (!seq_nr)
return;
auto* const cmd = ix::input->get_user_cmd(seq_nr);
if (!cmd || !cmd->command_number)
return;
r5::on_createmove(cmd);
}
bool __fastcall hooks::write_user_cmd_delta_to_buffer(void* this_ptr, __int64 unused_0, __int64 pBuffer2, __int64 from_, int to)
{
return false;
}
int __fastcall hooks::vgui_paint(void* this_ptr, int mode)
{
auto* const original_fn = o::vgui_paint;
return 0;
}
int64_t __fastcall hooks::unk0(void* this_ptr)
{
return 0;
}
void __fastcall hooks::write_user_cmd(void* buf, respawn::user_cmd_t* to, respawn::user_cmd_t* from)
{
auto* const original_fn = o::write_user_cmd;
return original_fn(buf, to, from);
}
void __fastcall hooks::paint_fn(void* this_ptr, uint8_t* unk0, int64_t unk1)
{
auto* const original_fn = o::paint_fn;
original_fn(this_ptr, unk0, unk1);
r5::on_paint();
}
void __fastcall hooks::view_render_start(void* this_ptr)
{
auto* const original_fn = o::view_render_start;
original_fn(this_ptr);
if (respawn::is_playing())
{
auto* const inst = mem::addr(this_ptr).As<respawn::c_view_render*>();
if (!(inst == nullptr))
{
if (cfg::custom_fov)
{
if (g::p::cache.local_player.zooming)
{
if(cfg::custom_fov_override_zoomed)
*reinterpret_cast<float*>(BASE_OF(inst) + 0xD0) = cfg::no_zoom ? cfg::custom_fov_scale : cfg::custom_fov_scale_zoomed;
}
else
*reinterpret_cast<float*>(BASE_OF(inst) + 0xD0) = cfg::custom_fov_scale;
}
if (cfg::no_sway)
{
ix::engine_client->get_view_angles(g::p::eye_angles);
g::p::sway_angles = *reinterpret_cast<math::Angle3*>(BASE_OF(inst) + 0xEC);
*reinterpret_cast<math::Angle3*>(BASE_OF(inst) + 0xEC) = g::p::eye_angles;
}
}
}
}
void __fastcall hooks::cl_move(void)
{
auto* const original_fn = o::cl_move;
r5::on_clmove();
return original_fn();
}
void __fastcall hooks::cl_move_send(__int64 a1, __int64 a2, __int64 a3)
{
auto* const original_fn = o::cl_move_send;
return original_fn(a1, a2, a3);
}
bool __fastcall hooks::lookup_file(void* this_ptr, const char* name, __int64 a3)
{
auto* const original_fn = o::lookup_file;
const auto result = original_fn(this_ptr, name, a3);
if (stl::strstr(name, _XS("nut")))
{
//
// A script file has been attempted to look up.
//
//log_info("lookup_script('%s').", name);
auto file_info = *(uintptr_t*)(a3 + 0x10);
auto file_buffer = *(char**)file_info;
auto file_primary_size = (size_t*)(*(uintptr_t*)(a3 + 0x8) + 0x20);
//dump_to_disk(name, file_buffer, *file_primary_size);
respawn::script::override_from_disk(name, file_buffer, file_primary_size);
}
return result;
}
bool __fastcall hooks::get_player_info(void* this_ptr, int index, respawn::player_info_t* buffer)
{
auto* const original_fn = o::get_player_info;
auto result = original_fn(this_ptr, index, buffer);
if (cfg::other_anonymous_mode)
{
if (result && !r5::is_within_self(_ReturnAddress()))
{
if (util::is_valid_address(buffer))
{
stl::strcpy(buffer->pad, _XS("Player1337"));
}
}
}
return result;
}
+186
View File
@@ -0,0 +1,186 @@
#pragma once
namespace cache
{
enum class types
{
none = 0,
player,
dummie,
npc,
loot,
dynamic_prop,
script_prop,
};
enum class prop_dynamic_types
{
none = 0,
shooting_range_target,
trap_gas,
trap_fence,
};
struct entity_t
{
bool m_valid;
uint64_t m_identifier;
math::Vector3 m_origin;
math::Vector3 m_center;
};
struct player_t : entity_t
{
int m_life_state;
int m_bleedout_state;
int m_team_number;
int m_health;
int m_health_max;
int m_armor;
int m_armor_max;
bool m_visible;
bool m_teammate;
respawn::color_t m_color;
math::Vector3 m_origin;
math::Vector3 m_velocity;
math::Vector3 m_bones[20];
char m_name[32];
bool is_alive() noexcept { return (m_life_state == LIFE_ALIVE); }
};
struct npc_t : entity_t
{
uint8_t m_life_state;
int m_health;
int m_health_max;
};
struct prop_dynamic_t : entity_t
{
prop_dynamic_types m_type;
};
struct loot_t : entity_t
{
int m_script_id;
};
struct entry_t
{
bool valid;
int index;
types type;
respawn::entity_types entity_type;
void* m_pointer;
char m_model_name[MAX_PATH];
struct
{
player_t plr;
npc_t npc;
loot_t loot;
prop_dynamic_t prop_dynamic;
} type_specific;
};
constexpr size_t capacity = 0x10000;
extern void process_player(int index, respawn::c_player* player, cache::entry_t& entry, cache::player_t& data);
extern void process_npc(int index, respawn::c_npc* npc, cache::entry_t& entry, cache::npc_t& data);
extern void process_loot(int index, respawn::c_prop_survival* entity, cache::loot_t& data);
extern void process_dynamic_prop(int index, respawn::c_entity* entity, cache::entry_t& entry, cache::prop_dynamic_t& data);
extern void process_base(int index, respawn::c_entity* entity, cache::entry_t& entry);
};
class c_entity_cache
{
public:
//
//
//
void initialize();
//
//
//
void on_createmove();
//
//
//
void collect_entities();
//
//
//
void on_update();
//
//
//
void reset();
//
//
//
const auto count() { return _entity_count; }
auto get_neutral(size_t index) -> cache::entry_t
{
if (index >= _entity_count || index >= cache::capacity)
return {};
auto info = _entities[index];
if (!info.valid)
return {};
return info;
}
//
//
//
auto get_player(size_t index) -> cache::player_t
{
if (index >= _entity_count || index >= cache::capacity)
return {};
auto info = _entities[index];
if (!info.valid)
return {};
if (info.type != cache::types::player &&
info.type != cache::types::dummie)
return {};
return info.type_specific.plr;
}
//
//
//
template < typename T >
T get_pointer(size_t index)
{
return (T)get_pointer_internal(index);
}
private:
void* get_pointer_internal(size_t index);
private:
size_t _entity_count;
cache::entry_t* _entities = nullptr;
};
+26
View File
@@ -0,0 +1,26 @@
#pragma once
class c_config
{
public:
void initialize();
void shutdown();
void on_start();
bool get_path(wchar_t* buffer, size_t length);
bool validate(void* file_ptr);
const auto is_ready() { return m_ready; }
const auto get_parser() { return m_parser; }
private:
bool m_ready;
bool m_valid;
c_json* m_parser;
wchar_t m_path[MAX_PATH];
};
#define conf_integer(NAME) g::p::config.get_parser()->get_value_integer(_XS(NAME))
#define conf_bool(NAME) g::p::config.get_parser()->get_value_boolean(_XS(NAME))
#define conf_double(NAME) g::p::config.get_parser()->get_value_double(_XS(NAME))
+38
View File
@@ -0,0 +1,38 @@
#pragma once
namespace dyn_addr
{
struct entry_t
{
enum
{
DYN_ADDR_TYPE_NONE = 0,
DYN_ADDR_TYPE_CODE,
DYN_ADDR_TYPE_PTR,
} type;
struct
{
uint32_t offset_to_instr;
uint32_t length_of_instr;
} ptr;
uint32_t offset;
uintptr_t result;
char name[128];
wchar_t pattern[128];
};
inline stl::c_linked_list<entry_t> _list;
extern void add_dynamic_address_code(const char* name, const wchar_t* pattern, uint32_t offset);
extern void add_dynamic_address_ptr(const char* name, const wchar_t* pattern,
uint32_t offset, uint32_t offset_to_instr, uint32_t length_of_instr);
extern bool grab_all();
extern uintptr_t get_dynamic_address(const char* name);
}
+13
View File
@@ -0,0 +1,13 @@
#pragma once
namespace dyn_offs
{
extern bool initialize();
namespace _::player
{
inline u_long last_visible_time{ };
inline u_long view_offset{ };
inline u_long eye_angles{ };
}
}
+149
View File
@@ -0,0 +1,149 @@
#pragma once
namespace aim
{
struct find_context_t
{
respawn::c_player* me;
size_t viable_targets;
float maximum_distance;
float maximum_fov;
float closest_distance;
float closest_fov;
math::Vector3 my_position;
math::Vector3 my_view;
math::Angle3 my_angle;
math::Vector3 aim_pos;
struct
{
math::Vector3 velocity;
} target_info;
};
extern respawn::bone_id get_optimal_bone_id(const cache::player_t& player);
extern bool is_target_viable(cache::entry_t& entity, aim::find_context_t& ctx);
extern void psilent(respawn::c_player* me, respawn::c_weapon* weapon);
}
namespace features
{
enum HEIRLOOM_INDEXES
{
HEIRLOOM_IDX_WRAITH = 0,
HEIRLOOM_IDX_BLOODHOUND = 1,
HEIRLOOM_IDX_LIFELINE = 2,
HEIRLOOM_IDX_PATHFINDER_GLOVES = 3,
HEIRLOOM_IDX_OCTANE_KNIFE = 4,
HEIRLOOM_IDX_MIRAGE = 5,
HEIRLOOM_IDX_GIBRALTAR = 7,
HEIRLOOM_IDX_BANGALORE = 8,
};
class c_base
{
public:
virtual void cl_move(respawn::c_player* me) { __noop(); }
virtual void create_move(respawn::c_player* me, respawn::user_cmd_t* cmd) { __noop(); }
virtual void paint() { __noop(); }
private:
};
class c_movement : public c_base
{
public:
void create_move(respawn::c_player* me, respawn::user_cmd_t* cmd) override;
bool m_hopping;
private:
};
class c_glow : public c_base
{
public:
respawn::color_t get_color(const cache::player_t& player);
void create_move(respawn::c_player* me, respawn::user_cmd_t* cmd) override;
private:
};
class c_aim : public c_base
{
public:
bool is_weapon_compatible(respawn::c_weapon* wpn) noexcept;
bool find_target(respawn::c_player* me, cache::entry_t* result, aim::find_context_t& ctx);
void create_move(respawn::c_player* me, respawn::user_cmd_t* cmd) override;
void cl_move(respawn::c_player* me) override;
void draw_range();
void paint() override;
bool is_aiming;
bool writecmd_silent;
float effective_max_fov_;
math::Vector3 target_pos_;
math::Angle3 wish_angle;
private:
};
class c_skin_changer : public c_base
{
public:
void create_move(respawn::c_player* me, respawn::user_cmd_t* cmd) override;
void frame_stage_notify(int stage, respawn::c_player* me);
private:
};
class c_esp : public c_base
{
public:
void draw_bar(respawn::color_t color, FLOAT flX, FLOAT flY, FLOAT flW, FLOAT flH, int current, const int max);
void draw_outline(respawn::color_t color, int opacity, math::Vector3 scr_origin, float bw, float bh);
void show_debug_ents();
void process_player(int index, const cache::entry_t& entry, const cache::player_t& player);
void process_prowler(int index, const cache::entry_t& entry, const cache::npc_t& npc);
void process_loot(int index, const cache::entry_t& entry, const cache::loot_t& loot);
void overlay_hud();
void info_panel();
void draw_bone_identifiers(const cache::player_t& player);
void paint() override;
private:
};
class c_logger : public c_base
{
public:
struct field_t
{
char m_text[256];
float m_duration;
float m_time_registered;
respawn::color_t m_color;
};
void draw_messages();
void paint() override;
void add_message(float duration, respawn::color_t color, const char* fmt, ...);
private:
stl::spinlock m_lock;
stl::c_linked_list<field_t> m_fields;
};
}
#define LOGGER_MSG_INTERNAL(DURATION, COLOR, FMT, ...) f::logger.add_message(DURATION, COLOR, _XS(FMT), __VA_ARGS__)
#define LOGGER_MSG_INFO(DURATION, FMT, ...) LOGGER_MSG_INTERNAL(DURATION, respawn::colors::white, FMT, __VA_ARGS__)
#define LOGGER_MSG_WARN(DURATION, FMT, ...) LOGGER_MSG_INTERNAL(DURATION, respawn::colors::yellow, FMT, __VA_ARGS__)
#define LOGGER_MSG_CRITICAL(DURATION, FMT, ...) LOGGER_MSG_INTERNAL(DURATION, respawn::colors::red, FMT, __VA_ARGS__)
+100
View File
@@ -0,0 +1,100 @@
#pragma once
namespace g
{
inline float curtime{};
inline bool is_in_game{};
inline bool is_in_game_last{};
inline bool in_freecam{};
inline bool is_playing{};
inline bool choke_this_tick{};
inline bool unprotected_game{};
inline unsigned long build_hash{};
inline uintptr_t return_address_gadget{};
}
namespace cfg
{
inline bool aim_enabled{ true };
inline bool aim_visualize_range{ false };
inline bool aim_ignore_key{};
inline bool aim_auto_fire{ true };
inline bool aim_smooth_out{};
inline bool aim_friendly_fire{};
inline bool aim_random_hitbox{};
inline bool aim_dynamic_hitbox{};
inline bool aim_bullet_time{};
inline bool aim_bullet_prediction{ true };
inline bool aim_rapid_fire{};
inline bool aim_players{ true };
inline bool aim_prowler{ true };
inline bool aim_firing_range_targets{ };
inline int aim_no_recoil{ 2 };
inline int aim_silent{ 2 };
inline float aim_fov{ 25.f };
inline float aim_smooth{ 0.f };
inline float aim_rapid_fire_boost{ 2.5f };
inline float aim_distance{ 4096.f };
inline float aim_bullet_prediction_scale{ 1.25f };
inline int aim_choke_cap{ 5 };
inline bool esp_enabled{ true };
inline bool esp_show_local_player{ false };
inline bool esp_show_team_mates{ false };
inline bool esp_show_debug_ents{};
inline bool esp_players{ true };
inline bool esp_prowler{ true };
inline bool esp_loot{ true };
inline bool esp_loot_unknown{ false };
inline bool esp_firing_range_targets{};
inline bool esp_traps{ true };
inline float esp_object_render_dist{ 8192.f };
inline float esp_text_render_dist{ 2048.f};
inline bool esp_info_panel{ false };
inline bool esp_info_panel_supress_ac_msgs{ true };
inline bool esp_players_name{ true };
inline bool esp_players_health_bar{ true };
inline bool esp_players_armor_bar{ true };
inline bool esp_players_outline{};
inline bool esp_players_glow{ true };
inline bool esp_player_bone_ids{};
inline int esp_players_health{};
inline int esp_players_armor{};
inline bool radar_enabled{};
inline float radar_radius{};
inline float radar_range{};
inline float radar_opacity{};
inline bool custom_fov{ true };
inline bool custom_fov_override_zoomed{ true };
inline bool no_zoom{ true };
inline bool no_sway{ false };
inline float custom_fov_scale{ 2.7f };
inline float custom_fov_scale_zoomed{ 2.0f };
inline bool movement_bunny_hop{ true };
inline bool movement_freecam{ true };
inline bool movement_thirdperson{ true };
inline int fake_lag{ false };
inline bool fake_lag_ignore_key{};
inline int fake_lag_choke_cap{ 4 };
inline bool other_bullet_time{ true };
inline bool other_debug_overlay{};
inline bool other_disable_default_crosshair{ true };
inline bool other_disable_view_model{ false };
inline bool other_spectator_list{ false };
inline bool other_infinite_charge_rifle{ false };
inline bool other_anonymous_mode{ false };
inline bool other_heirloom_changer_active{ false };
inline int other_heirloom_index{ };
inline bool custom_crosshair_enabled{ true };
inline bool custom_crosshair_outline{ };
inline float custom_crosshair_size{ 2.f };
}
+115
View File
@@ -0,0 +1,115 @@
#pragma once
namespace g::p
{
struct ac_scan_t
{
ulong id;
float time;
};
inline r5::context_t* context = nullptr;
namespace acc
{
inline hvi::acc::eac::Context_t* eac = nullptr;
}
inline respawn::game_modes game_mode{};
inline c_render render{};
inline math::dimension_t<int> screen{};
inline respawn::cached_data_t cache{};
inline c_input_manager input_mgr{};
inline window::c_manager window_mgr{};
inline c_entity_cache ent_cache{};
inline c_config config{};
inline math::Angle3 eye_angles{ };
inline math::Angle3 sway_angles{ };
inline stl::c_linked_list<ac_scan_t> acs_history{};
__forceinline auto on_ac_event(ulong code)
{
acs_history.insert({ 0xEAC + code, curtime });
}
}
namespace ix
{
inline respawn::c_base_client* base_client = nullptr;
inline respawn::c_shared_client* shared_client = nullptr;
inline respawn::c_engine_client* engine_client = nullptr;
inline respawn::c_engine_vgui* engine_vgui = nullptr;
inline respawn::c_engine_trace* engine_trace = nullptr;
inline respawn::c_entity_list* entity_list = nullptr;
inline respawn::c_input* input = nullptr;
inline respawn::c_input_system* input_system = nullptr;
inline respawn::c_view_render* view_render = nullptr;
inline respawn::c_model_info* model_info = nullptr;
inline respawn::c_global_vars* global_vars = nullptr;
inline respawn::c_game_movement* game_movement = nullptr;
inline respawn::c_mat_system_surface* mat_system_surface = nullptr;
inline respawn::c_convar_mgr* cvar_mgr = nullptr;
inline respawn::c_file_system* file_system = nullptr;
inline respawn::c_player** local_player_ptr = nullptr;
inline respawn::c_net_chan** net_chan = nullptr;
}
namespace gv
{
inline float* engine_time = nullptr;
inline int* crosshair_state = nullptr;
inline bool* input_disable = nullptr;
}
namespace f
{
inline features::c_movement movement{};
inline features::c_glow glow{};
inline features::c_aim aim{};
inline features::c_esp esp{};
inline features::c_logger logger{};
inline features::c_skin_changer skin_changer{};
}
namespace si
{
inline c_synced_input paint{};
inline c_synced_input create_move{};
}
namespace respawn
{
__forceinline auto net_chan() -> respawn::c_net_chan*
{
if (ix::net_chan == nullptr)
return nullptr;
return *ix::net_chan;
}
__forceinline auto last_out_cmd_nr() -> int
{
const auto address = dyn_addr::get_dynamic_address(_XS("ptr_last_out_cmd"));
return *reinterpret_cast<int*>(address);
}
}
namespace netvar
{
inline ulong life_state{};
inline ulong bleedout_state{};
}
namespace cvar
{
inline respawn::c_convar* time_scale{ };
inline respawn::c_convar* third_person{ };
inline respawn::c_convar* draw_view_model{ };
inline respawn::c_convar* move_use_dt{ };
}
+184
View File
@@ -0,0 +1,184 @@
#pragma once
#include "table64.h"
#include "hde64.h"
#pragma once
namespace hde
{
inline size_t disasm_buffer(void* data, size_t length, hde64s* list, size_t list_length)
{
size_t left = length;
size_t count = 0;
size_t offset = 0;
hde64s info{};
do
{
if (mem::addr(data).Add(offset).Base() >
mem::addr(data).Add(length).Base())
break;
if (!hde64_disasm(mem::addr(data).Add(offset).Ptr(), &info))
break;
const auto delta = left - info.len;
if (static_cast<int>(delta) <= 0)
break;
memcpy(&list[count], &info, sizeof(hde64s));
count++;
left -= info.len;
offset += info.len;
} while (left > 0 && (count + 1) < list_length);
return count;
}
inline auto disasm_buffer_ex(void* data, size_t length)
{
auto result = stl::vector<hde64s>();
size_t left = length;
size_t count = 0;
size_t offset = 0;
hde64s info{};
do
{
if (mem::addr(data).Add(offset).Base() >
mem::addr(data).Add(length).Base())
break;
if (!hde64_disasm(mem::addr(data).Add(offset).Ptr(), &info))
break;
const auto delta = left - info.len;
if (static_cast<int>(delta) <= 0)
break;
result.push_back(info);
count++;
left -= info.len;
offset += info.len;
} while (left > 0);
return result;
}
inline size_t get_code_size(void* buffer, size_t length, bool function = false)
{
auto tmp_buffer_mem = stl::c_pool_buffer(0x1000);
auto tmp_buffer = mem::addr(tmp_buffer_mem.ptr()).As<hde64s*>();
if (!tmp_buffer_mem.valid())
return 0;
const auto count = disasm_buffer(
buffer, length,
tmp_buffer,
tmp_buffer_mem.length()
);
size_t index = 0;
size_t result = 0;
hde64s* instr = tmp_buffer;
do
{
result += instr->len;
if (function && instr->opcode == 0xC3)
break;
++index;
++instr;
} while (index < count && instr != nullptr);
return result;
}
inline size_t get_function_size(void* buffer, size_t length)
{
return get_code_size(buffer, length, true);
}
inline bool is_function_hookable(UINT8* buffer, SIZE_T length,
SIZE_T* backup_size, SIZE_T minimum_length, UINT32& status_code)
{
auto tmp_buffer_mem = stl::c_pool_buffer(0x1000);
auto tmp_buffer = mem::addr(tmp_buffer_mem.ptr()).As<hde64s*>();
if (!tmp_buffer_mem.valid())
return 0;
SIZE_T instr_count = disasm_buffer(buffer, length, tmp_buffer, tmp_buffer_mem.length());
if (instr_count <= 0)
{
status_code = 0xE02;
return false;
}
auto result = false;
SIZE_T instr_total_length = 0;
for (SIZE_T index = 0; index < instr_count; index++)
{
const auto& instr = tmp_buffer[index];
instr_total_length += instr.len;
if (instr_total_length >= minimum_length)
{
result = true;
break;
}
}
if (result && backup_size)
*backup_size = instr_total_length;
status_code = 0x1;
return result;
}
inline bool resolve_jump(void* ptr, uintptr_t& dst, bool follow = false)
{
hde64s list[64];
uint8_t snippet[128] = { 0 };
memset(list, 0, sizeof(list));
memcpy(snippet, ptr, sizeof(snippet));
size_t count = disasm_buffer(snippet, sizeof(snippet), list, sizeof(list));
if (count <= 0)
return false;
const auto& jump_instr = list[0];
if (jump_instr.opcode != 0xFF)
return false;
uintptr_t jump_rip = ((uintptr_t)ptr) + jump_instr.len;
uintptr_t jump_offset_addr = ((uintptr_t)&snippet[0]) + jump_instr.len - sizeof(std::uint32_t);
uint32_t result = 0;
memcpy(&result, (void*)jump_offset_addr, sizeof(result));
dst = jump_rip + result;
if (follow)
dst = *(uintptr_t*)dst;
return true;
}
}
+94
View File
@@ -0,0 +1,94 @@
#pragma once
#ifndef _HDE64_H_
#define _HDE64_H_
#define F_MODRM 0x00000001
#define F_SIB 0x00000002
#define F_IMM8 0x00000004
#define F_IMM16 0x00000008
#define F_IMM32 0x00000010
#define F_IMM64 0x00000020
#define F_DISP8 0x00000040
#define F_DISP16 0x00000080
#define F_DISP32 0x00000100
#define F_RELATIVE 0x00000200
#define F_ERROR 0x00001000
#define F_ERROR_OPCODE 0x00002000
#define F_ERROR_LENGTH 0x00004000
#define F_ERROR_LOCK 0x00008000
#define F_ERROR_OPERAND 0x00010000
#define F_PREFIX_REPNZ 0x01000000
#define F_PREFIX_REPX 0x02000000
#define F_PREFIX_REP 0x03000000
#define F_PREFIX_66 0x04000000
#define F_PREFIX_67 0x08000000
#define F_PREFIX_LOCK 0x10000000
#define F_PREFIX_SEG 0x20000000
#define F_PREFIX_REX 0x40000000
#define F_PREFIX_ANY 0x7f000000
#define PREFIX_SEGMENT_CS 0x2e
#define PREFIX_SEGMENT_SS 0x36
#define PREFIX_SEGMENT_DS 0x3e
#define PREFIX_SEGMENT_ES 0x26
#define PREFIX_SEGMENT_FS 0x64
#define PREFIX_SEGMENT_GS 0x65
#define PREFIX_LOCK 0xf0
#define PREFIX_REPNZ 0xf2
#define PREFIX_REPX 0xf3
#define PREFIX_OPERAND_SIZE 0x66
#define PREFIX_ADDRESS_SIZE 0x67
#pragma pack(push,1)
typedef struct {
uint8_t len;
uint8_t p_rep;
uint8_t p_lock;
uint8_t p_seg;
uint8_t p_66;
uint8_t p_67;
uint8_t rex;
uint8_t rex_w;
uint8_t rex_r;
uint8_t rex_x;
uint8_t rex_b;
uint8_t opcode;
uint8_t opcode2;
uint8_t modrm;
uint8_t modrm_mod;
uint8_t modrm_reg;
uint8_t modrm_rm;
uint8_t sib;
uint8_t sib_scale;
uint8_t sib_index;
uint8_t sib_base;
union {
uint8_t imm8;
uint16_t imm16;
uint32_t imm32;
uint64_t imm64;
} imm;
union {
uint8_t disp8;
uint16_t disp16;
uint32_t disp32;
} disp;
uint32_t flags;
} hde64s;
#pragma pack(pop)
#ifdef __cplusplus
extern "C" {
#endif
/* __cdecl */
unsigned int hde64_disasm(const void* code, hde64s* hs);
#ifdef __cplusplus
}
#endif
#endif /* _HDE64_H_ */
+69
View File
@@ -0,0 +1,69 @@
#pragma once
#define C_NONE 0x00
#define C_MODRM 0x01
#define C_IMM8 0x02
#define C_IMM16 0x04
#define C_IMM_P66 0x10
#define C_REL8 0x20
#define C_REL32 0x40
#define C_GROUP 0x80
#define C_ERROR 0xff
#define PRE_ANY 0x00
#define PRE_NONE 0x01
#define PRE_F2 0x02
#define PRE_F3 0x04
#define PRE_66 0x08
#define PRE_67 0x10
#define PRE_LOCK 0x20
#define PRE_SEG 0x40
#define PRE_ALL 0xff
#define DELTA_OPCODES 0x4a
#define DELTA_FPU_REG 0xfd
#define DELTA_FPU_MODRM 0x104
#define DELTA_PREFIXES 0x13c
#define DELTA_OP_LOCK_OK 0x1ae
#define DELTA_OP2_LOCK_OK 0x1c6
#define DELTA_OP_ONLY_MEM 0x1d8
#define DELTA_OP2_ONLY_MEM 0x1e7
inline unsigned char hde64_table[] = {
0xa5,0xaa,0xa5,0xb8,0xa5,0xaa,0xa5,0xaa,0xa5,0xb8,0xa5,0xb8,0xa5,0xb8,0xa5,
0xb8,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xac,0xc0,0xcc,0xc0,0xa1,0xa1,
0xa1,0xa1,0xb1,0xa5,0xa5,0xa6,0xc0,0xc0,0xd7,0xda,0xe0,0xc0,0xe4,0xc0,0xea,
0xea,0xe0,0xe0,0x98,0xc8,0xee,0xf1,0xa5,0xd3,0xa5,0xa5,0xa1,0xea,0x9e,0xc0,
0xc0,0xc2,0xc0,0xe6,0x03,0x7f,0x11,0x7f,0x01,0x7f,0x01,0x3f,0x01,0x01,0xab,
0x8b,0x90,0x64,0x5b,0x5b,0x5b,0x5b,0x5b,0x92,0x5b,0x5b,0x76,0x90,0x92,0x92,
0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x6a,0x73,0x90,
0x5b,0x52,0x52,0x52,0x52,0x5b,0x5b,0x5b,0x5b,0x77,0x7c,0x77,0x85,0x5b,0x5b,
0x70,0x5b,0x7a,0xaf,0x76,0x76,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,
0x5b,0x5b,0x86,0x01,0x03,0x01,0x04,0x03,0xd5,0x03,0xd5,0x03,0xcc,0x01,0xbc,
0x03,0xf0,0x03,0x03,0x04,0x00,0x50,0x50,0x50,0x50,0xff,0x20,0x20,0x20,0x20,
0x01,0x01,0x01,0x01,0xc4,0x02,0x10,0xff,0xff,0xff,0x01,0x00,0x03,0x11,0xff,
0x03,0xc4,0xc6,0xc8,0x02,0x10,0x00,0xff,0xcc,0x01,0x01,0x01,0x00,0x00,0x00,
0x00,0x01,0x01,0x03,0x01,0xff,0xff,0xc0,0xc2,0x10,0x11,0x02,0x03,0x01,0x01,
0x01,0xff,0xff,0xff,0x00,0x00,0x00,0xff,0x00,0x00,0xff,0xff,0xff,0xff,0x10,
0x10,0x10,0x10,0x02,0x10,0x00,0x00,0xc6,0xc8,0x02,0x02,0x02,0x02,0x06,0x00,
0x04,0x00,0x02,0xff,0x00,0xc0,0xc2,0x01,0x01,0x03,0x03,0x03,0xca,0x40,0x00,
0x0a,0x00,0x04,0x00,0x00,0x00,0x00,0x7f,0x00,0x33,0x01,0x00,0x00,0x00,0x00,
0x00,0x00,0xff,0xbf,0xff,0xff,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0xff,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,
0x00,0x00,0x00,0xbf,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7f,0x00,0x00,
0xff,0x40,0x40,0x40,0x40,0x41,0x49,0x40,0x40,0x40,0x40,0x4c,0x42,0x40,0x40,
0x40,0x40,0x40,0x40,0x40,0x40,0x4f,0x44,0x53,0x40,0x40,0x40,0x44,0x57,0x43,
0x5c,0x40,0x60,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,
0x40,0x40,0x64,0x66,0x6e,0x6b,0x40,0x40,0x6a,0x46,0x40,0x40,0x44,0x46,0x40,
0x40,0x5b,0x44,0x40,0x40,0x00,0x00,0x00,0x00,0x06,0x06,0x06,0x06,0x01,0x06,
0x06,0x02,0x06,0x06,0x00,0x06,0x00,0x0a,0x0a,0x00,0x00,0x00,0x02,0x07,0x07,
0x06,0x02,0x0d,0x06,0x06,0x06,0x0e,0x05,0x05,0x02,0x02,0x00,0x00,0x04,0x04,
0x04,0x04,0x05,0x06,0x06,0x06,0x00,0x00,0x00,0x0e,0x00,0x00,0x08,0x00,0x10,
0x00,0x18,0x00,0x20,0x00,0x28,0x00,0x30,0x00,0x80,0x01,0x82,0x01,0x86,0x00,
0xf6,0xcf,0xfe,0x3f,0xab,0x00,0xb0,0x00,0xb1,0x00,0xb3,0x00,0xba,0xf8,0xbb,
0x00,0xc0,0x00,0xc1,0x00,0xc7,0xbf,0x62,0xff,0x00,0x8d,0xff,0x00,0xc4,0xff,
0x00,0xc5,0xff,0x00,0xff,0xff,0xeb,0x01,0xff,0x0e,0x12,0x08,0x00,0x13,0x09,
0x00,0x16,0x08,0x00,0x17,0x09,0x00,0x2b,0x09,0x00,0xae,0xff,0x07,0xb2,0xff,
0x00,0xb4,0xff,0x00,0xb5,0xff,0x00,0xc3,0x01,0x00,0xc7,0xff,0xbf,0xe7,0x08,
0x00,0xf0,0x02,0x00
};
+14
View File
@@ -0,0 +1,14 @@
#pragma once
namespace hook::detour
{
extern bool protect_virtual_memory(void* pAddress, size_t uLength, ulong uProt, ulong* uOldProt = nullptr);
extern bool copy_virtual_memory(void* pDst, void* pSrc, size_t uLength, bool bStealth = false);
extern bool place(void* pTarget, void* pHandler,
void** pOriginal, size_t* uBackupLength,
void* pRealTarget = nullptr, u32* pdwErrorCode = nullptr,
bool bUseSafeRegister = false, bool bSmallFunction = false);
extern bool restore(void* pTarget, void* pOriginal, size_t uBackupLength);
}
+128
View File
@@ -0,0 +1,128 @@
#pragma once
#define DECLARE_ORIGINAL(F) inline decltype(&F) F = nullptr;
namespace hooks
{
enum idx : uint32_t
{
HOOK_IDX_INPUT_CREATE_MOVE = 4,
HOOK_IDX_CLIENT_CREATE_MOVE = 27,
HOOK_IDX_START_TRACK_PREDICTION_ERRORS = 4,
HOOK_IDX_FINISH_TRACK_PREDICTION_ERRORS = 5,
HOOK_IDX_GET_VIEW_ANGLES = 60,
HOOK_IDX_SET_VIEW_ANGLES = 61,
HOOK_IDX_WRITE_USER_CMD_DELTA_TO_BUFFER = 6,
HOOK_IDX_VGUI_PAINT = 24,
HOOK_IDX_FRAME_STAGE_NOTIFY = 55,
HOOK_IDX_LOOKUP_FILE = 80,
HOOK_IDX_GET_PLAYER_INFO = 24,
};
struct data_t
{
size_t m_backup_length;
void* m_target;
void* m_handler;
void* m_original;
};
namespace d
{
inline data_t get_proc_addr{};
inline data_t enum_windows{};
}
namespace mgr
{
inline c_vfunc_hook base_client{};
inline c_vfunc_hook engine_client{};
inline c_vfunc_hook engine_vgui{};
inline c_vfunc_hook game_movement{};
inline c_vfunc_hook input{};
}
extern bool initialize_early();
extern bool initialize();
extern bool setup_detours_early();
extern bool setup_detours();
extern bool setup_detours_api();
extern bool setup_detours_ac();
extern bool setup_vmt();
extern void shutdown();
extern bool register_(hooks::data_t& data, bool resolve_jt = false, bool small_fn = false);
extern void __fastcall frame_stage_notify(void* this_ptr, int stage);
extern void __fastcall create_move(void* this_ptr, int seq_nr, float sample_time, bool active);
extern bool __fastcall write_user_cmd_delta_to_buffer(void* this_ptr, __int64 unused_0, __int64 pBuffer2, __int64 from_, int to);
extern int __fastcall vgui_paint(void* this_ptr, int mode);
extern int64_t __fastcall unk0(void* this_ptr);
extern void __fastcall write_user_cmd(void* buf, respawn::user_cmd_t* to, respawn::user_cmd_t* from);
extern void __fastcall paint_fn(void* this_ptr, uint8_t* unk0, int64_t unk1);
extern void __fastcall view_render_start(void* this_ptr);
extern void __fastcall cl_move(void);
extern void __fastcall cl_move_send(__int64 a1, __int64 a2, __int64 a3);
extern bool __fastcall lookup_file(void* this_ptr, const char* name, __int64 a3);
extern bool __fastcall get_player_info(void* this_ptr, int index, respawn::player_info_t* buffer);
namespace api
{
extern void* __fastcall add_veh_handler(ulong first, void* handler);
extern ulong __fastcall remove_veh_handler(void* handle);
extern ulong __fastcall query_info_thread(
_handle thread, THREADINFOCLASS info_class,
void* info_buffer, ulong info_length,
ulong* return_length
);
extern int __fastcall get_thread_context(_handle thread, CONTEXT* ctx);
extern ulong __fastcall device_ioctl_file(
_handle file_handle, _handle event, PIO_APC_ROUTINE apc_routine, PVOID apc_ctx,
PIO_STATUS_BLOCK iosb, ulong ioctl_code, PVOID input_buffer,
ULONG input_buffer_len, PVOID output_buffer, ULONG output_buffer_len
);
extern int __fastcall translate_message(PMSG msg);
extern void __fastcall user_exception_dispatcher(PEXCEPTION_RECORD record, PCONTEXT context);
}
namespace ac
{
extern bool __fastcall fetch_suspect_strings(void* a1, void* a2);
extern bool __fastcall fetch_suspect_system_calls(void* a1, void* a2);
extern char __fastcall detect_suspect_memory_regions(void* a1);
}
namespace o
{
DECLARE_ORIGINAL(frame_stage_notify);
DECLARE_ORIGINAL(create_move);
DECLARE_ORIGINAL(write_user_cmd_delta_to_buffer);
DECLARE_ORIGINAL(vgui_paint);
DECLARE_ORIGINAL(write_user_cmd);
DECLARE_ORIGINAL(paint_fn);
DECLARE_ORIGINAL(view_render_start);
DECLARE_ORIGINAL(cl_move);
DECLARE_ORIGINAL(cl_move_send);
DECLARE_ORIGINAL(lookup_file);
DECLARE_ORIGINAL(get_player_info);
namespace api_
{
inline decltype(api::add_veh_handler)* add_veh_handler = nullptr;
inline decltype(api::remove_veh_handler)* remove_veh_handler = nullptr;
inline decltype(api::query_info_thread)* query_info_thread = nullptr;
inline decltype(api::get_thread_context)* get_thread_context = nullptr;
inline decltype(api::device_ioctl_file)* device_ioctl_file = nullptr;
inline decltype(api::translate_message)* translate_message = nullptr;
}
namespace ac_
{
inline decltype(ac::fetch_suspect_strings)* fetch_suspect_string = nullptr;
inline decltype(ac::fetch_suspect_system_calls)* fetch_suspect_system_calls = nullptr;
inline decltype(ac::detect_suspect_memory_regions)* detect_suspect_memory_regions = nullptr;
}
}
}
+48
View File
@@ -0,0 +1,48 @@
#pragma once
#define _USE_MATH_DEFINES
#define _NO_CRT_STDIO_INLINE
#include <cinttypes>
#include <cmath>
#include <intrin.h>
#include <array>
#include <initializer_list>
#if !defined(WIN32_LEAN_AND_MEAN)
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <winternl.h>
#include <winioctl.h>
#include <ShlObj.h>
#endif
#include "global.h"
#include "mh/mh.h"
#include "shd/shared.h"
#include "dyn_addr.h"
#include "dyn_offs.h"
#include "rspn/respawn.h"
#include "hde/hde.h"
#include "r5.h"
#include "hook.h"
#include "hooks.h"
#include "cache.h"
#include "features.h"
#include "render.h"
#include "config.h"
#include "wnds/windows.h"
#include "global_post.h"
#include "shd/log_post.h"
int memcmp(void*, void*, size_t);
void* memset(void* str, int c, size_t n);
void* memcpy(void* dest, const void* src, size_t len);
#pragma intrinsic(memset)
#pragma intrinsic(memcpy)
#pragma intrinsic(memcmp)
#pragma function(memset)
#pragma function(memcpy)
#pragma function(memcmp)
+131
View File
@@ -0,0 +1,131 @@
#pragma once
// Size of each memory slot.
#if defined(_M_X64) || defined(__x86_64__)
#define MEMORY_SLOT_SIZE 64
#else
#define MEMORY_SLOT_SIZE 32
#endif
// Can be passed as a parameter to MH_EnableHook, MH_DisableHook,
// MH_QueueEnableHook or MH_QueueDisableHook.
#define MH_ALL_HOOKS NULL
namespace mh
{
typedef enum MH_STATUS
{
MH_UNKNOWN = -1,
MH_OK = 0,
MH_ERROR_ALREADY_INITIALIZED,
MH_ERROR_NOT_INITIALIZED,
MH_ERROR_ALREADY_CREATED,
MH_ERROR_NOT_CREATED,
MH_ERROR_ENABLED,
MH_ERROR_DISABLED,
MH_ERROR_NOT_EXECUTABLE,
MH_ERROR_UNSUPPORTED_FUNCTION,
MH_ERROR_MEMORY_ALLOC,
MH_ERROR_MEMORY_PROTECT,
MH_ERROR_MODULE_NOT_FOUND,
MH_ERROR_FUNCTION_NOT_FOUND
}
MH_STATUS;
MH_STATUS WINAPI MH_Initialize(VOID);
MH_STATUS WINAPI MH_CreateHook(LPVOID pTarget, LPVOID pDetour, LPVOID* ppOriginal, PVOID pTargetReal);
MH_STATUS WINAPI MH_CreateHookApi(
LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID* ppOriginal);
MH_STATUS WINAPI MH_CreateHookApiEx(
LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID* ppOriginal, LPVOID* ppTarget);
MH_STATUS WINAPI MH_RemoveHook(LPVOID pTarget);
MH_STATUS WINAPI MH_EnableHook(LPVOID pTarget, PVOID pSideBuffer);
MH_STATUS WINAPI MH_DisableHook(LPVOID pTarget);
MH_STATUS WINAPI MH_QueueEnableHook(LPVOID pTarget);
MH_STATUS WINAPI MH_QueueDisableHook(LPVOID pTarget);
MH_STATUS WINAPI MH_ApplyQueued(VOID);
VOID InitializeBuffer(VOID);
VOID UninitializeBuffer(VOID);
LPVOID AllocateBuffer(LPVOID pOrigin);
VOID FreeBuffer(LPVOID pBuffer);
BOOL IsExecutableAddress(LPVOID pAddress);
#pragma pack(push, 1)
// Structs for writing x86/x64 instructions.
// 8-bit relative jump.
typedef struct _JMP_REL_SHORT
{
UINT8 opcode; // EB xx: JMP +2+xx
UINT8 operand;
} JMP_REL_SHORT, * PJMP_REL_SHORT;
// 32-bit direct relative jump/call.
typedef struct _JMP_REL
{
UINT8 opcode; // E9/E8 xxxxxxxx: JMP/CALL +5+xxxxxxxx
UINT32 operand; // Relative destination address
} JMP_REL, * PJMP_REL, CALL_REL;
// 64-bit indirect absolute jump.
typedef struct _JMP_ABS
{
UINT8 opcode0; // FF25 00000000: JMP [+6]
UINT8 opcode1;
UINT32 dummy;
UINT64 address; // Absolute destination address
} JMP_ABS, * PJMP_ABS;
// 64-bit indirect absolute call.
typedef struct _CALL_ABS
{
UINT8 opcode0; // FF15 00000002: CALL [+6]
UINT8 opcode1;
UINT32 dummy0;
UINT8 dummy1; // EB 08: JMP +10
UINT8 dummy2;
UINT64 address; // Absolute destination address
} CALL_ABS;
// 32-bit direct relative conditional jumps.
typedef struct _JCC_REL
{
UINT8 opcode0; // 0F8* xxxxxxxx: J** +6+xxxxxxxx
UINT8 opcode1;
UINT32 operand; // Relative destination address
} JCC_REL;
// 64bit indirect absolute conditional jumps that x64 lacks.
typedef struct _JCC_ABS
{
UINT8 opcode; // 7* 0E: J** +16
UINT8 dummy0;
UINT8 dummy1; // FF25 00000000: JMP [+6]
UINT8 dummy2;
UINT32 dummy3;
UINT64 address; // Absolute destination address
} JCC_ABS;
#pragma pack(pop)
typedef struct _TRAMPOLINE
{
LPVOID pTarget; // [In] Address of the target function.
LPVOID pDetour; // [In] Address of the detour function.
LPVOID pTrampoline; // [In] Buffer address for the trampoline and relay function.
#if defined(_M_X64) || defined(__x86_64__)
LPVOID pRelay; // [Out] Address of the relay function.
#endif
BOOL patchAbove; // [Out] Should use the hot patch area?
UINT nIP; // [Out] Number of the instruction boundaries.
UINT8 oldIPs[8]; // [Out] Instruction boundaries of the target function.
UINT8 newIPs[8]; // [Out] Instruction boundaries of the trampoline function.
} TRAMPOLINE, * PTRAMPOLINE;
BOOL CreateTrampolineFunction(PTRAMPOLINE ct);
}
+80
View File
@@ -0,0 +1,80 @@
#pragma once
namespace r5
{
struct context_t
{
uintptr_t my_base;
uintptr_t my_length;
bool m_initialized;
struct
{
uintptr_t base;
size_t length;
} m_process_info;
} inline _ctx;
__forceinline auto en_decrypt(void* data_ptr, size_t length, uint64_t key)
{
for (size_t i = 0; i < length; i++)
reinterpret_cast<uint8_t*>(data_ptr)[i] ^= key;
}
extern bool setup_context();
extern bool setup_dyn_addrs();
extern bool setup_interfaces_early();
extern bool setup_interfaces();
extern bool setup_convars();
extern void initialize();
extern void initialize_full();
extern void shutdown();
extern bool setup_context_encrypted(uintptr_t base);
extern bool setup_context_internal(uintptr_t base, _pimage_dos_header dh, _pimage_nt_header nh);
extern bool setup_context();
extern bool is_within_eac(void* address);
extern void think();
extern void maintain_screen_size();
//
// hook handlers.
//
extern void on_game_state_change(bool current, bool previous);
extern void on_createmove(respawn::user_cmd_t* user_cmd);
extern void on_clmove();
extern void on_paint();
extern void on_render();
extern void on_fsn(int stage);
extern void on_window_proc(UINT msg, WPARAM w_param, LPARAM l_param);
__forceinline auto on_failure(ulong line, const char* file)
{
log_info("a failure inside game_r5 was reported (file='%s', line=%i).", file, line);
log_info("the return address which might contain more info is %p", _ReturnAddress());
//
// this will throw an access violation and automatically generate a crash dump.
// but only if this was configured for windows error reporting (WER).
//
*reinterpret_cast<int*>(0) = NULL;
}
__forceinline auto is_within_self(void* va)
{
auto address = mem::addr(va).Base();
if (address == 0)
return false;
return (address >= _ctx.my_base &&
address <= (_ctx.my_base + _ctx.my_length));
}
}
#define report_failure() r5::on_failure(__LINE__, _XS(__FILE__))
+16
View File
@@ -0,0 +1,16 @@
#pragma once
class c_render
{
public:
size_t get_text_width(const char* text, size_t font_size);
void draw_rect(respawn::color_t color, int x1, int y1, int x2, int y2, int opacity = 255);
void draw_rect_filled(respawn::color_t color, int x1, int y1, int x2, int y2, int opacity = 255);
void draw_line(respawn::color_t color, int x1, int y1, int x2, int y2, int opacity = 255);
void draw_rect_bordered(respawn::color_t sColor, float flX0, float flY0, float flX1, float flY1, int opacity = 255);
void draw_circle(respawn::color_t color, int x, int y, int radius, int segments = 100, int opacity = 255);
void draw_text(respawn::color_t color, ulong font, int size, int x, int y, const char* text);
void draw_text_ex(respawn::color_t color, ulong font, int size, int x, int y, const char* text, ...);
void draw_text_centered(respawn::color_t color, ulong font, int size, int x, int y, const char* text, ...);
private:
};
+14
View File
@@ -0,0 +1,14 @@
#pragma once
namespace respawn
{
class c_base_client
{
public:
client_class* get_all_classes()
{
return vfunc::call<12, client_class*>(this);
}
private:
};
}
+178
View File
@@ -0,0 +1,178 @@
#ifndef IN_BUTTONS_H
#define IN_BUTTONS_H
#ifdef _WIN32
#pragma once
#endif
#define IN_ATTACK (1 << 0)
#define IN_JUMP (1 << 1)
#define IN_DUCK (1 << 2)
#define IN_FORWARD (1 << 3)
#define IN_BACK (1 << 4)
#define IN_USE (1 << 5)
#define IN_CANCEL (1 << 6)
#define IN_LEFT (1 << 7)
#define IN_RIGHT (1 << 8)
#define IN_MOVELEFT (1 << 9)
#define IN_MOVERIGHT (1 << 10)
#define IN_ATTACK2 (1 << 11)
#define IN_RUN (1 << 12)
#define IN_RELOAD (1 << 13)
#define IN_ALT1 (1 << 14)
#define IN_ALT2 (1 << 15)
#define IN_SCORE (1 << 16) // Used by client.dll for when scoreboard is held down
#define IN_SPEED (1 << 17) // Player is holding the speed key
#define IN_WALK (1 << 18) // Player holding walk key
#define IN_ZOOM (1 << 19) // Zoom key for HUD zoom
#define IN_WEAPON1 (1 << 20) // weapon defines these bits
#define IN_WEAPON2 (1 << 21) // weapon defines these bits
#define IN_BULLRUSH (1 << 22)
#define IN_GRENADE1 (1 << 23) // grenade 1
#define IN_GRENADE2 (1 << 24) // grenade 2
#define IN_ATTACK3 (1 << 25)
#endif // IN_BUTTONS_H
enum button_code_t
{
BUTTON_CODE_INVALID = -1,
BUTTON_CODE_NONE = 0,
KEY_FIRST = 0,
KEY_NONE = KEY_FIRST,
KEY_0,
KEY_1,
KEY_2,
KEY_3,
KEY_4,
KEY_5,
KEY_6,
KEY_7,
KEY_8,
KEY_9,
KEY_A,
KEY_B,
KEY_C,
KEY_D,
KEY_E,
KEY_F,
KEY_G,
KEY_H,
KEY_I,
KEY_J,
KEY_K,
KEY_L,
KEY_M,
KEY_N,
KEY_O,
KEY_P,
KEY_Q,
KEY_R,
KEY_S,
KEY_T,
KEY_U,
KEY_V,
KEY_W,
KEY_X,
KEY_Y,
KEY_Z,
KEY_PAD_0,
KEY_PAD_1,
KEY_PAD_2,
KEY_PAD_3,
KEY_PAD_4,
KEY_PAD_5,
KEY_PAD_6,
KEY_PAD_7,
KEY_PAD_8,
KEY_PAD_9,
KEY_PAD_DIVIDE,
KEY_PAD_MULTIPLY,
KEY_PAD_MINUS,
KEY_PAD_PLUS,
KEY_PAD_ENTER,
KEY_PAD_DECIMAL,
KEY_LBRACKET,
KEY_RBRACKET,
KEY_SEMICOLON,
KEY_APOSTROPHE,
KEY_BACKQUOTE,
KEY_COMMA,
KEY_PERIOD,
KEY_SLASH,
KEY_BACKSLASH,
KEY_MINUS,
KEY_EQUAL,
KEY_ENTER,
KEY_SPACE,
KEY_BACKSPACE,
KEY_TAB,
KEY_CAPSLOCK,
KEY_NUMLOCK,
KEY_ESCAPE,
KEY_SCROLLLOCK,
KEY_INSERT,
KEY_DELETE,
KEY_HOME,
KEY_END,
KEY_PAGEUP,
KEY_PAGEDOWN,
KEY_BREAK,
KEY_LSHIFT,
KEY_RSHIFT,
KEY_LALT,
KEY_RALT,
KEY_LCONTROL,
KEY_RCONTROL,
KEY_LWIN,
KEY_RWIN,
KEY_APP,
KEY_UP,
KEY_LEFT,
KEY_DOWN,
KEY_RIGHT,
KEY_F1,
KEY_F2,
KEY_F3,
KEY_F4,
KEY_F5,
KEY_F6,
KEY_F7,
KEY_F8,
KEY_F9,
KEY_F10,
KEY_F11,
KEY_F12,
KEY_CAPSLOCKTOGGLE,
KEY_NUMLOCKTOGGLE,
KEY_SCROLLLOCKTOGGLE,
KEY_LAST = KEY_SCROLLLOCKTOGGLE,
KEY_COUNT = KEY_LAST - KEY_FIRST + 1,
// Mouse
MOUSE_FIRST = KEY_LAST + 1,
MOUSE_LEFT = MOUSE_FIRST,
MOUSE_RIGHT,
MOUSE_MIDDLE,
MOUSE_4,
MOUSE_5,
MOUSE_WHEEL_UP, // A fake button which is 'pressed' and 'released' when the wheel is moved up
MOUSE_WHEEL_DOWN, // A fake button which is 'pressed' and 'released' when the wheel is moved down
MOUSE_LAST = MOUSE_WHEEL_DOWN,
MOUSE_COUNT = MOUSE_LAST - MOUSE_FIRST + 1,
BUTTON_CODE_LAST,
BUTTON_CODE_COUNT = BUTTON_CODE_LAST - KEY_FIRST + 1,
KEY_XBUTTON_LTRIGGER, // ZAXIS POSITIVE
KEY_XBUTTON_RTRIGGER, // ZAXIS NEGATIVE
KEY_XSTICK2_RIGHT, // UAXIS POSITIVE
KEY_XSTICK2_LEFT, // UAXIS NEGATIVE
KEY_XSTICK2_DOWN, // VAXIS POSITIVE
KEY_XSTICK2_UP, // VAXIS NEGATIVE
};
+26
View File
@@ -0,0 +1,26 @@
#pragma once
namespace respawn
{
class c_convar
{
public:
char pad_0000[24]; //0x0000
char* m_name; //0x0018
char* m_description; //0x0020
char pad_0028[64]; //0x0028
float m_value_float; //0x0068
int32_t m_value_numeric; //0x006C
}; //Size: 0x0154
class c_convar_mgr
{
public:
c_convar* find(const char* name)
{
return vfunc::call<14, c_convar*>(this, name);
}
private:
};
}
+27
View File
@@ -0,0 +1,27 @@
#pragma once
#define LIFE_ALIVE 0 // alive
#define LIFE_DYING 1 // playing death animation or still falling off of a ledge waiting to hit ground
#define LIFE_DEAD 2 // dead. lying still.
#define LIFE_RESPAWNABLE 3
#define LIFE_DISCARDBODY 4
#define ENTITY_INDEX_BY_HANDLE(X) ( X & 0xFFFF )
namespace respawn
{
enum client_frame_stages
{
frame_undefined = -1,
frame_start,
frame_net_update_start,
frame_net_update_post_data_update_start,
frame_net_update_post_data_update_end,
frame_net_update_end,
frame_render_start,
frame_render_end,
frame_stage_count,
};
}
+48
View File
@@ -0,0 +1,48 @@
#pragma once
namespace respawn
{
class recv_prop
{
public:
int32_t type; //0x0000
int32_t offset; //0x0004
char pad_0008[24]; //0x0008
class recv_table* data_table; //0x0020
char* name; //0x0028
bool is_inside_array; //0x0030
char pad_0031[7]; //0x0031
class recv_prop* array_prop; //0x0038
void* proxy_fn; //0x0040
char pad_0048[12]; //0x0048
int32_t flags; //0x0054
char pad_0058[4]; //0x0058
int32_t num_elements; //0x005C
}; //Size: 0x0060
class recv_table
{
public:
char pad_0000[8]; //0x0000
recv_prop** props; //0x0008
int32_t num_props; //0x0010
char pad_0014[1196]; //0x0014
void* decoder; //0x04C0
char* name; //0x04C8
bool initialized; //0x04D0
bool in_main_list; //0x04D1
}; //Size: 0x04D2
class client_class
{
public:
void* create_fn; //0x0000
void* create_event_fn; //0x0008
char* network_name; //0x0010
recv_table* table; //0x0018
client_class* next; //0x0020
int32_t id; //0x0028
char pad_002C[4]; //0x002C
char* name; //0x0030
}; //Size: 0x0038
}
+25
View File
@@ -0,0 +1,25 @@
#pragma once
namespace respawn
{
struct player_info_t
{
char pad[512];
};
class c_engine_client
{
public:
VIRTUAL_FUNC(get_local_player, int, 40, (), this);
VIRTUAL_FUNC(is_in_game, bool, 48, (), this);
VIRTUAL_FUNC(get_screen_size, void, 19, (int& w, int& h), this, &w, &h);
VIRTUAL_FUNC(get_player_info, bool, 24, (int idx, player_info_t* buf), this, idx, buf);
VIRTUAL_FUNC(get_view_angles, void, 61, (math::Angle3& out), this, &out);
VIRTUAL_FUNC(set_view_angles, void, 62, (math::Angle3& in), this, &in);
VIRTUAL_FUNC(client_command, int64_t, 22, (const char* cmd), this, cmd);
private:
};
}
+10
View File
@@ -0,0 +1,10 @@
#pragma once
namespace respawn
{
class c_engine_trace
{
public:
private:
};
}
+10
View File
@@ -0,0 +1,10 @@
#pragma once
namespace respawn
{
class c_engine_vgui
{
public:
private:
};
}
+78
View File
@@ -0,0 +1,78 @@
#pragma once
namespace respawn
{
class c_collision_property
{
public:
NETVAR_FIELD(vec_mins, this, math::Vector3, "DT_CollisionProperty", "m_vecMins");
NETVAR_FIELD(vec_maxs, this, math::Vector3, "DT_CollisionProperty", "m_vecMaxs");
private:
};
class c_client_renderable
{
public:
bool setup_bones(math::matrix3x4* buffer, int count, int mask, float time)
{
return vfunc::call<16, bool>(this, buffer, count, mask, time);
}
private:
};
class c_client_networkable
{
public:
client_class* get_client_class()
{
return vfunc::call<3, client_class*>(this);
}
private:
};
class c_entity
{
public:
DATA_FIELD_NR(renderable, this, c_client_renderable, 0x10);
DATA_FIELD_NR(networkable, this, c_client_networkable, 0x18);
NETVAR_FIELD(identifier, this, PCHAR, "DT_BaseEntity", "m_iSignifierName");
NETVAR_FIELD(script_name_index, this, int, "DT_BaseEntity", "m_scriptNameIndex");
NETVAR_FIELD(model_index, this, int, "DT_BaseEntity", "m_nModelIndex");
NETVAR_FIELD_NR(collision, this, c_collision_property, "DT_BaseEntity", "m_Collision");
DATA_FIELD(anim_sequence, this, int, 0xF80);
DATA_FIELD(model_name, this, char*, 0x30);
DATA_FIELD(origin, this, math::Vector3, 0x14C);
void* get_model();
bool set_model(const char* name);
bool set_model_index(int index);
void set_abs_angles(math::Angle3 angle);
uint32_t get_sequence_activity(int sequence);
uint32_t get_activity_sequence(uint32_t activity);
private:
};
class c_prop_survival : public c_entity
{
public:
NETVAR_FIELD(custom_script_int, this, int, "DT_PropSurvival", "m_customScriptInt");
private:
};
class c_npc : public c_entity
{
public:
NETVAR_FIELD(life_state, this, uint8_t, "DT_AI_BaseNPC", "m_lifeState");
NETVAR_FIELD(health, this, int, "DT_AI_BaseNPC", "m_iHealth");
NETVAR_FIELD(health_max, this, int, "DT_AI_BaseNPC", "m_iMaxHealth");
private:
};
}
+20
View File
@@ -0,0 +1,20 @@
#pragma once
namespace respawn
{
class c_entity_list
{
public:
template < typename T >
auto* get_client_entity(int index)
{
return (T*)vfunc::call<4, T*>(this, index);
}
auto get_highest_entity_index()
{
return vfunc::call<8, int>(this);
}
private:
};
}
+10
View File
@@ -0,0 +1,10 @@
#pragma once
namespace respawn
{
class c_file_system
{
public:
private:
};
}
+10
View File
@@ -0,0 +1,10 @@
#pragma once
namespace respawn
{
class c_game_movement
{
public:
private:
};
}
+6
View File
@@ -0,0 +1,6 @@
#pragma once
namespace g::p
{
inline c_netvar_manager netvar_mgr{};
}
+20
View File
@@ -0,0 +1,20 @@
#pragma once
namespace respawn
{
class c_global_vars
{
public:
char pad_0000[16]; //0x0000
float Curtime; //0x0010
char pad_0014[12]; //0x0014
float Frametime; //0x0020
char pad_0024[12]; //0x0024
float IntervalPerTick; //0x0030
int32_t MaxClients; //0x0034
char pad_0038[8]; //0x0038
int32_t TickCount; //0x0040
char pad_0044[1052]; //0x0044
}; //Size: 0x0460
static_assert(sizeof(c_global_vars) == 0x460);
}
+28
View File
@@ -0,0 +1,28 @@
#pragma once
namespace respawn
{
class c_input
{
public:
auto* get_user_cmd(int seq_nr)
{
user_cmd_t* result = nullptr;
const auto list_base =
mem::addr(this).Add(0xF8)
.Retrieve_as<uintptr_t>();
constexpr size_t multiplayer_backup = 750;
constexpr size_t list_entry_length = user_cmd_t::size();
result =
mem::addr(list_base)
.Add(list_entry_length * (seq_nr % multiplayer_backup))
.As<decltype(result)>();
return result;
}
private:
};
}
+12
View File
@@ -0,0 +1,12 @@
#pragma once
namespace respawn
{
class c_input_system
{
public:
VIRTUAL_FUNC(is_button_down, bool, 13, (int kc), this, kc);
VIRTUAL_FUNC(get_cursor_pos, void, 36, (int* x, int* y), this, x, y);
private:
};
}
+44
View File
@@ -0,0 +1,44 @@
#pragma once
namespace respawn
{
class c_mat_system_surface
{
public:
void draw_set_color(int r, int g, int b, int a)
{
return vfunc::call<14, void>(this, r, g, b, a);
}
void draw_filled_rect(int x1, int y1, int x2, int y2)
{
return vfunc::call<16, void>(this, x1, y1, x2, y2);
}
void draw_outlined_rect(int x1, int y1, int x2, int y2)
{
return vfunc::call<19, void>(this, x1, y1, x2, y2);
}
void draw_line(int x1, int y1, int x2, int y2)
{
return vfunc::call<20, void>(this, x1, y1, x2, y2);
}
void draw_text(unsigned long font, int size, int x, int y, int r, int g, int b, int a, unsigned int a10, const char* str)
{
return vfunc::call<200, void>(this, font, size, x, y, r, g, b, a, a10, str);
}
void draw_outlined_circle(int x, int y, int radius, int segments)
{
return vfunc::call<125, void>(this, x, y, radius, segments);
}
void get_screen_size(int& wide, int& tall)
{
return vfunc::call<53, void>(this, &wide, &tall);
}
private:
};
}
+404
View File
@@ -0,0 +1,404 @@
#pragma once
namespace math
{
class Vector3
{
public:
Vector3 operator-(const Vector3& other) const
{
return Vector3{ this->x - other.x, this->y - other.y, this->z - other.z };
}
Vector3 operator+(const Vector3& other) const
{
return Vector3{ this->x + other.x, this->y + other.y, this->z + other.z };
}
Vector3& operator*=(const float multiplier)
{
x *= multiplier;
y *= multiplier;
z *= multiplier;
return *this;
}
Vector3 operator*(const Vector3& other) const
{
return { x * other.x, y * other.y, z * other.z };
}
Vector3 operator*(const float& other) const
{
return { x * other, y * other, z * other };
}
[[nodiscard]] FLOAT Length() CONST {
return (x + y + z);
}
[[nodiscard]] FLOAT Length2d() CONST {
return math::sqrtf(x * x + y * y + z * z);
}
[[nodiscard]] FLOAT LengthSquare() CONST {
return (x * x + y * y + z * z);
}
[[nodiscard]] BOOL Empty() CONST {
return (Length() <= 0.0f);
}
[[nodiscard]] FLOAT DistanceTo(Vector3& vOther) CONST
{
CONST AUTO delta = (vOther - *this);
return math::fabsf(delta.LengthSquare());
}
[[nodiscard]] FLOAT DistanceTo(CONST Vector3& vOther) CONST
{
CONST AUTO delta = (vOther - *this);
return math::fabsf(delta.LengthSquare());
}
[[nodiscard]] floating_point_holder3_t<FLOAT> Data() {
return { x, y, z };
}
Vector3 Normalized();
public:
float x, y, z;
protected:
private:
};
class Angle3 {
public:
Angle3 operator-(const Angle3& other) const
{
return Angle3{ this->x - other.x, this->y - other.y, this->z - other.z };
}
Angle3 operator+(const Angle3& other) const
{
return Angle3{ this->x + other.x, this->y + other.y, this->z + other.z };
}
Angle3& operator*=(const float multiplier)
{
x *= multiplier;
y *= multiplier;
z *= multiplier;
return *this;
}
Angle3 operator*(const Angle3& other) const
{
return { x * other.x, y * other.y, z * other.z };
}
Angle3 operator*(const float& other) const
{
return { x * other, y * other, z * other };
}
[[nodiscard]] floating_point_holder3_t<FLOAT> Data() {
return { x, y, z };
}
[[nodiscard]] FLOAT Length() CONST {
return (x + y + z);
}
[[nodiscard]] FLOAT Length2d() CONST {
return math::sqrtf(x * x + y * y + z * z);
}
[[nodiscard]] FLOAT LengthSquare() CONST {
return (x * x + y * y + z * z);
}
[[nodiscard]] BOOL Empty() CONST {
return (Length() <= 0.0f);
}
public:
float x, y, z;
protected:
private:
};
class Vector4 : public Vector3
{
public:
public:
float w;
protected:
private:
};
struct matrix3x4
{
float* operator[](int i)
{
return m_value[i];
}
const float* operator[](int i) const
{
return m_value[i];
}
float* Base()
{
return &m_value[0][0];
}
const float* Base() const
{
return &m_value[0][0];
}
float m_value[3][4];
};
struct matrix4x4
{
float* operator[](int i)
{
return m_value[i];
}
const float* operator[](int i) const
{
return m_value[i];
}
float* Base()
{
return &m_value[0][0];
}
const float* Base() const
{
return &m_value[0][0];
}
float m_value[4][4];
};
struct __declspec(align(16)) matrix3x4a : matrix3x4
{
};
inline constexpr float deg2rad(const float v)
{
return (v * static_cast<float>(M_PI)) / 180.0f;
}
inline constexpr float rad2deg(const float v)
{
return (v * 180.0f) / static_cast<float>(M_PI);
}
inline void sin_cos(float radians, float* sine, float* cosine)
{
*sine = sinf(radians);
*cosine = cosf(radians);
}
inline void VectorAngles(const math::Vector3& forward, math::Angle3& angles)
{
float temp, yaw, pitch;
if (forward.y == 0.0f && forward.x == 0.0f)
{
yaw = 0.0f;
if (forward.z > 0.0f)
{
pitch = 270.0f;
}
else
{
pitch = 90.0f;
}
}
else
{
yaw = math::atan2f(forward.y, forward.x) * 180.0f / static_cast<float>(M_PI);
if (yaw < 0.0f)
{
yaw += 360.0f;
}
temp = math::sqrtf(forward.x * forward.x + forward.y * forward.y);
pitch = math::atan2f(-forward.z, temp) * 180.0f / static_cast<float>(M_PI);
if (pitch < 0.0f)
{
pitch += 360.0f;
}
angles.x = pitch;
angles.y = yaw;
angles.z = 0.0f;
}
}
inline void AngleVectors(const math::Angle3& in, math::Vector3& out)
{
float sp, sy, cp, cy;
sin_cos(deg2rad(in.y), &sy, &cy);
sin_cos(deg2rad(in.x), &sp, &cp);
out.x = cp * cy;
out.y = cp * sy;
out.z = -sp;
}
inline void ClampAngle(Vector3& angle)
{
angle.x = stl::clamp(angle.x, -89.0f, +89.0f);
angle.y = stl::clamp(angle.y, -180.0f, +180.0f);
angle.z = stl::clamp(angle.z, 0.0f, 0.0f);
}
inline void ClampAngle(Angle3& angle)
{
angle.x = stl::clamp(angle.x, -89.0f, +89.0f);
angle.y = stl::clamp(angle.y, -180.0f, +180.0f);
angle.z = stl::clamp(angle.z, 0.0f, 0.0f);
}
inline void NormalizeVector(math::Vector3& in)
{
if (in.x > 89.0f)
{
in.x -= 360.0f;
}
if (in.x < -89.0f)
{
in.x += 360.0f;
}
while (in.y > 180.0f)
{
in.y -= 360.0f;
}
while (in.y < -180.0f)
{
in.y += 360.0f;
}
}
inline void NormalizeAngle(math::Angle3& angle)
{
if (angle.x > 89.0f)
{
angle.x -= 360.0f;
}
if (angle.x < -89.0f)
{
angle.x += 360.0f;
}
while (angle.y > 180.0f)
{
angle.y -= 360.0f;
}
while (angle.y < -180.0f)
{
angle.y += 360.0f;
}
}
constexpr float DotProduct(const math::Vector3& first, const math::Vector3& second)
{
return ((first.x * second.x) + (first.y * second.y) + (first.z * second.z));
}
inline Vector3 Vector3::Normalized()
{
auto temp = *this;
NormalizeVector(temp);
return temp;
}
namespace SE {
FORCEINLINE FLOAT VectorNormalize(Vector3& vec) {
FLOAT radius = math::sqrtf(vec.x * vec.x + vec.y * vec.y + vec.z * vec.z);
FLOAT iradius = 1.f / (radius + FLT_EPSILON);
vec.x *= iradius;
vec.y *= iradius;
vec.z *= iradius;
return radius;
}
FORCEINLINE FLOAT AngleNormalize(FLOAT angle)
{
angle = std::fmodf(angle, 360.0f);
if (angle > 180)
angle -= 360;
if (angle < -180)
angle += 360;
return angle;
}
FORCEINLINE FLOAT AngleNormalizePositive(FLOAT angle)
{
angle = std::fmodf(angle, 360.0f);
if (angle < 0.0f)
angle += 360.0f;
return angle;
}
FORCEINLINE VOID AngleNormalize(Angle3& vec) {
vec.x = stl::clamp(vec.x, -89.f, +89.f);
vec.y = remainderf(vec.y, 360.f);
vec.z = 0.f;
}
__forceinline auto get_fov_difference(Angle3 angle, Vector3 start, Vector3 end)
{
Angle3 aim_angle{};
Vector3 view_position{}, aim_position{};
const Vector3 delta = end - start;
VectorAngles(delta, aim_angle);
AngleVectors(angle, view_position);
AngleVectors(aim_angle, aim_position);
const float aimplsq = aim_position.Length2d();
const auto dotp = static_cast<float>(DotProduct(aim_position, view_position) / aimplsq);
const float vcos = math::acos(dotp);
const float drad = math::rad2deg(vcos);
if (!math::isnan(vcos))
return drad;
return 0.0f;
}
}
}
+25
View File
@@ -0,0 +1,25 @@
#pragma once
namespace respawn
{
class c_model : public c_entity
{
public:
private:
};
class c_model_info
{
public:
int get_model_index(const char* nm)
{
return vfunc::call<2, int>(this, nm);
}
const char* get_model_name(c_model* mdl)
{
return vfunc::call<4, const char*>(this, mdl);
}
private:
};
}
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#define FL_ONGROUND (1<<0) // At rest / on the ground
#define FL_DUCKING (1<<1) // Player flag -- Player is fully crouched
#define FL_WATERJUMP (1<<2) // player jumping out of water
#define FL_ONTRAIN (1<<3) // Player is _controlling_ a train, so movement commands should be ignored on client during prediction.
#define FL_INRAIN (1<<4) // Indicates the entity is standing in rain
#define FL_FROZEN (1<<5) // Player is frozen for 3rd person camera
#define FL_ATCONTROLS (1<<6) // Player can't move, but keeps key inputs for controlling another entity
#define FL_CLIENT (1<<7) // Is a player
#define FL_FAKECLIENT (1<<8) // Fake client, simulated server side; don't send network messages to them
// NON-PLAYER SPECIFIC (i.e., not used by GameMovement or the client .dll ) -- Can still be applied to players, though
#define FL_INWATER (1<<9) // In water
+13
View File
@@ -0,0 +1,13 @@
#pragma once
namespace respawn
{
class c_net_chan
{
public:
DATA_FIELD(out_sequence_nr, this, int, 0x4);
DATA_FIELD(num_choked_packets, this, int, 0x10);
DATA_FIELD(stop_sending, this, uint8_t, 0x1A0);
private:
};
}
+63
View File
@@ -0,0 +1,63 @@
#pragma once
struct netvar_t
{
char name[128];
ulong offset;
};
struct netvar_table_t
{
char name[128];
stl::c_linked_list<netvar_t> props;
};
class c_netvar_manager
{
public:
bool initialize();
bool is_prop_garbage(const char* name);
void process_table(respawn::recv_table* table);
void process_prop(respawn::recv_table* table, respawn::recv_prop* prop, stl::c_linked_list<netvar_t>& list);
ulong get(const char* table_name, const char* prop_name) noexcept
{
stl::c_linked_list<netvar_t>* props_head = nullptr;
for (auto i = 0ull; i < m_list.count(); i++)
{
auto* const table = m_list[i];
if (table == nullptr)
continue;
if (stl::strcmp(table_name, table->name))
continue;
props_head = &table->props;
}
if (props_head == nullptr)
return 0;
ulong result{};
for (auto i = 0ull; i < props_head->count(); i++)
{
auto* const prop = (*props_head)[i];
if (!stl::strcmp(prop_name, prop->name))
{
result = prop->offset;
break;
}
}
return result;
}
private:
stl::c_linked_list<netvar_table_t> m_list;
};
#define NETVAR(TABLE, NAME) g::p::netvar_mgr.get(_XS(TABLE), _XS(NAME))
+57
View File
@@ -0,0 +1,57 @@
#pragma once
namespace respawn
{
struct glow_config_t
{
uint8_t general_mode;
uint8_t border_mode;
uint8_t border_len;
uint8_t transp_lvl;
};
class c_player : public c_entity
{
public:
NETVAR_FIELD(flags, this, int, "DT_Player", "m_fFlags");
NETVAR_FIELD(life_state, this, uint8_t, "DT_Player", "m_lifeState");
NETVAR_FIELD(health, this, int, "DT_Player", "m_iHealth");
NETVAR_FIELD(health_max, this, int, "DT_Player", "m_iMaxHealth");
NETVAR_FIELD(view_model, this, int, "DT_Player", "m_hViewModels");
NETVAR_FIELD(armor, this, int, "DT_BaseEntity", "m_shieldHealth");
NETVAR_FIELD(armor_max, this, int, "DT_BaseEntity", "m_shieldHealthMax");
NETVAR_FIELD(team_number, this, int, "DT_BaseEntity", "m_iTeamNum");
NETVAR_FIELD(observer_mode, this, int, "DT_LocalPlayerExclusive", "m_iObserverMode");
NETVAR_FIELD(bleed_out_state, this, int, "DT_Player", "m_bleedoutState");
NETVAR_FIELD(bleed_out_start_time, this, float, "DT_Player", "m_bleedoutStartTime");
NETVAR_FIELD(is_zooming, this, bool, "DT_Player", "m_bZooming");
NETVAR_FIELD(latest_primary_weapon, this, DWORD_PTR, "DT_BaseCombatCharacter", "m_latestPrimaryWeapons");
DATA_FIELD(server_time, this, float, 0x20D8);
DATA_FIELD(last_visible_time, this, float, dyn_offs::_::player::last_visible_time);
DATA_FIELD(glow_enabled, this, int, 0x3C8);
DATA_FIELD(glow_type, this, int, 0x3D0);
DATA_FIELD(glow_config, this, glow_config_t, 0x2C4);
DATA_FIELD(glow_color, this, color_t, 0x1D0);
DATA_FIELD(glow_distance, this, float, 0x3B4);
DATA_FIELD(velocity, this, math::Vector3, 0x140);
DATA_FIELD(view_offset, this, math::Vector3, dyn_offs::_::player::view_offset); // "48 83 EC 38 8B 05 ? ? ? ? 0F 29 74 24 20 83 F8 FF 74 22 0F B7 D0 48 8D 05 ? ? ? ? 48 C1 E2 05 48 03 D0 0F B7 05 ? ? ? ? 39 42 08"
DATA_FIELD(eye_angles, this, math::Angle3, dyn_offs::_::player::eye_angles); // "48 83 EC 58 80 3D ? ? ? ? ? 48 8B 05 ? ? ? ?"
DATA_FIELD(dyn_angles, this, math::Angle3, dyn_offs::_::player::eye_angles - 0x10);
bool is_visible() noexcept;
bool get_bone_position(size_t index, math::Vector3& result) noexcept;
c_weapon* get_active_weapon() noexcept;
c_view_model* get_view_model() noexcept;
private:
};
}
+239
View File
@@ -0,0 +1,239 @@
#pragma once
namespace respawn
{
class c_entity;
struct color_t
{
float r{}, g{}, b{};
};
using create_interface_fn = void* (__fastcall*)(const char*, int*);
namespace type_hash
{
constexpr ulong player = 0x98197a65;
constexpr ulong dummie = 0xf50db101;
}
namespace colors
{
constexpr color_t black = { 0.f, 0.f, 0.f };
constexpr color_t red = { 255.f, 65.f, 65.f };
constexpr color_t green = { 65.f, 255.f, 65.f };
constexpr color_t yellow = { 255.f, 255.f, 65.f };
constexpr color_t blue = { 65.f, 65.f, 255.f };
constexpr color_t white = { 255.f, 255.f, 255.f };
constexpr color_t cyan = { 0.f, 255.f, 221.f };
constexpr color_t purple = { 202.f, 3.f, 252.f };
}
namespace glow_colors
{
constexpr float opacity = 5.f;
constexpr color_t red = { opacity, 1.f, 1.f };
constexpr color_t blue = { 1.f, 1.f, opacity };
constexpr color_t green = { 1.f, opacity, 1.f };
constexpr color_t yellow = { opacity, opacity, 1.f };
constexpr color_t white = { opacity, opacity, opacity };
}
}
#include "defs.h"
#include "math.h"
#include "buttons.h"
#include "move_flags.h"
#include "dt_recv.h"
#include "user_cmd.h"
#include "netvar.h"
#include "global.h"
#include "base_client.h"
#include "shared_client.h"
#include "engine_client.h"
#include "engine_vgui.h"
#include "engine_trace.h"
#include "entity.h"
#include "weapon.h"
#include "view_model.h"
#include "player.h"
#include "entity_list.h"
#include "input.h"
#include "input_system.h"
#include "studio.h"
#include "view_render.h"
#include "model_info.h"
#include "global_vars.h"
#include "game_movement.h"
#include "net_chan.h"
#include "mat_system_surface.h"
#include "cvar.h"
#include "file_system.h"
namespace respawn
{
struct cached_data_t
{
struct
{
int index;
int team_number;
bool zooming;
uintptr_t address;
math::Vector3 origin;
math::Vector3 shoot_pos;
math::Angle3 eye_angle;
} local_player;
struct
{
uintptr_t address;
bool reloading;
bool can_fire;
float next_primary_attack;
float next_ready_time;
} local_weapon;
struct
{
int out_sequence_nr;
int num_choked_packets;
} net_chan;
};
enum crosshair_states
{
CROSSHAIR_STATE_SHOW_ALL = 0,
CROSSHAIR_STATE_HIDE_ALL,
CROSSHAIR_STATE_HIT_INDICATORS_ONLY,
CROSSHAIR_STATE_COUNT,
};
enum class entity_types
{
UNKNOWN,
NONE,
PLAYER,
DUMMIE,
PROWLER,
PROP_SURVIVAL,
PROP_SCRIPT,
PROP_DEATH_BOX,
PROP_DYNAMIC,
};
enum class loot_ids
{
SHIELD_WHITE = 175,
SHIELD_BLUE = 176,
SHIELD_PURP = 177,
SHIELD_RED = 178,
SHIELD_GOLD = 173,
HELMET_WHITE = 166,
HELMET_BLUE = 167,
HELMET_PURP = 168,
HELMET_GOLD = 169,
BACKPACK_WHITE = 184,
BACKPACK_BLUE = 185,
BACKPACK_PURP = 186,
BACKPACK_GOLD = 187,
WEAPON_KRABER = 1,
WEAPON_G7_SCOUT = 37,
WEAPON_ALTERNATOR = 42,
WEAPON_SPITFIRE = 68,
WEAPON_CHARGE_RIFLE = 63,
AMMO_ENERGY = 121,
AMMO_SHOTGUN = 122,
AMMO_ARROW = 125,
AMMO_HEAVY = 123,
AMMO_LIGHT = 120,
AMMO_SNIPER = 124,
ATTACHMENT_BARREL_STABILIZER_BLUE = 202,
ATTACHMENT_BARREL_STABILIZER_PURP = 203,
ATTACHMENT_MAGAZINE_LIGHT_PURP = 207,
ATTACHMENT_MAGAZINE_LIGHT_GOLD = 208,
};
enum class game_modes
{
invalid = 0,
survival,
arenas,
control,
};
inline stl::c_linked_list<std::pair<uint64_t, entity_types>> _ident_table;
inline stl::c_string_table _heirloom_table;
extern bool initialize();
extern respawn::c_player* get_local_player();
extern respawn::color_t get_player_color(respawn::c_player* player);
extern void* create_interface(const char* name);
extern int get_sequence_count(void* model);
extern mstudioseqdesc_t* seq_desc(void* model, int sequence);
extern entity_types get_entity_type(c_entity* entity);
extern uint64_t get_entity_identifier(c_entity* entity);
extern bool is_player(respawn::c_entity* entity, bool player = true, bool dummy = true);
extern bool is_survival_prop(respawn::c_entity* entity);
extern bool is_script_prop(respawn::c_entity* entity);
extern bool is_of_type(respawn::c_entity* entity, const char* name);
extern bool is_alive(respawn::c_player* player);
extern bool is_knocked(respawn::c_player* player);
extern game_modes get_game_mode();
extern void start_drawing(respawn::c_mat_system_surface* mssf);
extern void finish_drawing();
extern bool world_to_screen(math::Vector3& vIn, math::Vector3& vOut);
extern void on_update_cache(respawn::c_player* me, respawn::c_weapon* my_wpn, respawn::c_net_chan* nc);
extern bool is_teammate(c_player* player);
extern bool get_entity_center_pos(respawn::c_entity* entity, math::Vector3& result);
enum class bone_id
{
head = 8,
neck = 7,
torso_upper = 5,
torso_center = 3,
torso_lower = 2,
spine = 1,
};
constexpr size_t bone_count = 13;
__forceinline auto is_dummy(respawn::c_entity* entity) noexcept
{
return is_player(entity, false, true);
}
__forceinline auto is_playing() noexcept
{
return (g::is_in_game && g::is_playing);
}
namespace script
{
extern void dump_to_disk(const char* name, char* buffer, size_t length);
extern void override_from_disk(const char* name, char* buffer, size_t* length);
}
}
+10
View File
@@ -0,0 +1,10 @@
#pragma once
namespace respawn
{
class c_shared_client
{
public:
private:
};
}
+21
View File
@@ -0,0 +1,21 @@
#pragma once
namespace respawn
{
#pragma pack( push, 1 )
struct mstudioseqdesc_t
{
int baseptr;
int szlabelindex;
inline char* const pszLabel(void) const
{
return ((char*)this) + szlabelindex;
}
int szactivitynameindex;
inline char* const pszActivityName(void) const
{
return ((char*)this) + szactivitynameindex;
}
};
#pragma pack( pop )
}
+21
View File
@@ -0,0 +1,21 @@
#pragma once
namespace respawn
{
struct user_cmd_t
{
inline static constexpr size_t size() { return 0x218; }
int command_number;
int tick_count;
float command_time;
math::Angle3 viewangles;
BYTE _pad0[0x14];
float forwardmove;
float sidemove;
float upmove;
int buttons;
BYTE impulse;
BYTE _pad1[472];
};
}
+10
View File
@@ -0,0 +1,10 @@
#pragma once
namespace respawn
{
class c_view_model : public c_entity
{
public:
private:
};
}
+14
View File
@@ -0,0 +1,14 @@
#pragma once
namespace respawn
{
class c_view_render
{
public:
d3d::D3DMATRIX* get_view_matrix()
{
return *reinterpret_cast<d3d::D3DMATRIX**>(mem::addr(this).Base() + 0x10E8D0);
}
private:
};
}
+27
View File
@@ -0,0 +1,27 @@
#pragma once
namespace respawn
{
FORWARD_DECLARE(c_player);
enum class weapon_name_indexes : int
{
hands = 18,
};
class c_weapon : public c_entity
{
public:
NETVAR_FIELD(is_reloading, this, bool, "DT_WeaponX_LocalWeaponData", "m_bInReload");
NETVAR_FIELD(next_primary_attack, this, float, "DT_WeaponX_LocalWeaponData", "m_nextPrimaryAttackTime");
NETVAR_FIELD(next_ready_time, this, float, "DT_WeaponX_LocalWeaponData", "m_nextReadyTime");
NETVAR_FIELD(name_index, this, weapon_name_indexes, "DT_WeaponX", "m_weaponNameIndex");
DATA_FIELD(projectile_speed, this, float, 0x1F18);
DATA_FIELD(projectile_gravity, this, float, 0x1F20);
bool can_fire(c_player* owner) noexcept;
void set_legendary_view_model_index(int64_t idx) noexcept;
private:
};
}
+57
View File
@@ -0,0 +1,57 @@
#pragma once
extern "C"
{
extern ulong __fastcall sc_asm_alloc_virtual_memory(
HANDLE ProcessHandle,
PVOID* BaseAddress,
ULONG_PTR ZeroBits,
PSIZE_T RegionSize,
ULONG AllocationType,
ULONG Protect
);
extern ulong __fastcall sc_asm_query_virtual_memory(
HANDLE ProcessHandle,
PVOID BaseAddress,
k::MEMORY_INFORMATION_CLASS MemoryInformationClass,
PVOID MemoryInformation,
SIZE_T MemoryInformationLength,
PSIZE_T ReturnLength
);
extern ulong __fastcall sc_asm_delay_execution(
BOOLEAN Alertable,
PLARGE_INTEGER DelayInterval
);
extern ulong __fastcall sc_asm_get_context_thread(
HANDLE Thread,
PCONTEXT Context
);
extern ulong __fastcall sc_asm_open_file(
PHANDLE FileHandle,
ACCESS_MASK DesiredAccess,
POBJECT_ATTRIBUTES ObjectAttributes,
PIO_STATUS_BLOCK IoStatusBlock,
ULONG ShareAccess,
ULONG OpenOptions
);
extern ulong __fastcall sc_asm_read_file(
HANDLE FileHandle,
HANDLE Event,
PIO_APC_ROUTINE ApcRoutine,
PVOID ApcContext,
PIO_STATUS_BLOCK IoStatusBlock,
PVOID Buffer,
ULONG Length,
PLARGE_INTEGER ByteOffset,
PULONG Key
);
extern void __fastcall asm_capture_context(
PCONTEXT Context
);
}
+1704
View File
File diff suppressed because it is too large Load Diff
+48
View File
@@ -0,0 +1,48 @@
#pragma once
enum button_states
{
button_state_invalid = -1,
button_state_unassigned = 0,
button_state_released,
button_state_busy,
button_state_count,
};
struct button_t
{
int m_state = -1;
bool m_pressed = false;
};
class c_synced_input
{
public:
void sync(std::array<button_t, 255>& buttons);
bool is_button_down(uintptr_t key_code) noexcept;
bool was_button_down(uintptr_t key_code) noexcept;
private:
std::array<button_t, 255> m_buttons;
std::array<button_t, 255> m_buttons_prev;
};
class c_input_manager
{
public:
void update();
void window_proc(UINT msg, WPARAM w_param, LPARAM l_param);
void sync(c_synced_input* si);
public:
bool is_button_down(uintptr_t key_code) noexcept;
math::position_t<int> get_cursor_pos() noexcept;
private:
void internal_handler_key_down(uintptr_t key_code);
void internal_handler_key_up(uintptr_t key_code);
private:
math::position_t<int> m_cursor_pos;
std::array<button_t, 255> m_buttons;
std::array<button_t, 255> m_buttons_prev;
};
+146
View File
@@ -0,0 +1,146 @@
#pragma once
#include <pshpack1.h>
namespace instr
{
struct jump_t
{
size_t length() const
{
return sizeof((*this));
}
void assign_data(uint8_t mov_register = 0xB8,
uint8_t jmp_register = 0xE0)
{
memset(this, 0, sizeof(jump_t));
// mov rax, qword ptr (or something?!) <address>
m_mov[0] = 0x48;
m_mov[1] = mov_register;
// jmp rax
m_jmp[0] = 0xFF;
m_jmp[1] = jmp_register;
}
jump_t()
{
assign_data();
};
~jump_t() = default;
jump_t(uintptr_t destination)
{
assign_data();
memcpy(&m_dst[0], &destination, sizeof(uintptr_t));
}
jump_t(uintptr_t destination,
uint8_t mov_register, uint8_t jmp_register)
{
assign_data(mov_register, jmp_register);
memcpy(&m_dst[0], &destination, sizeof(uintptr_t));
}
inline void set_registers(uint8_t mov_register, uint8_t jmp_register)
{
m_mov[1] = mov_register;
m_jmp[1] = jmp_register;
}
UINT8 m_mov[2];
UINT8 m_dst[8];
UINT8 m_jmp[2];
};
struct jump_safe_t
{
void assign_data()
{
memset(this, 0, sizeof(jump_safe_t));
uint8_t pre[] = { 0xFF, 0x25, 0x00, 0x00, 0x00, 0x00 };
memcpy(m_pre, pre, sizeof(pre));
}
jump_safe_t()
{
assign_data();
};
~jump_safe_t() = default;
jump_safe_t(uintptr_t destination)
{
assign_data();
memcpy(&m_dst[0], &destination, sizeof(uintptr_t));
}
uint8_t m_pre[6];
uint8_t m_dst[8];
};
struct jump6_t
{
static jump6_t build(void* dst)
{
return jump6_t
{
0x50,
{ 0x48, 0xB8 },
dst,
{ 0x48, 0x87, 0x04, 0x24 },
0xC3
};
}
uint8_t m_push;
uint8_t m_mov[2];
void* m_dst;
uint8_t m_rstor[4];
uint8_t m_ret;
};
struct system_call_t
{
system_call_t() = default;
system_call_t(uint32_t id)
{
memset(this, 0, sizeof(system_call_t));
// mov r10, rcx ;
m_mov_r10[0] = 0x49;
m_mov_r10[1] = 0x89;
m_mov_r10[2] = 0xCA;
// mov eax, <id> ;
m_mov_eax = 0xB8;
memcpy(&m_id, &id, sizeof(id));
// sycall ;
m_call[0] = 0x0F;
m_call[1] = 0x05;
// retn ;
m_return = 0xC3;
}
void* stub() noexcept;
std::uint8_t m_mov_r10[0x3];
std::uint8_t m_mov_eax;
std::uint8_t m_id[0x4];
std::uint8_t m_call[0x2];
std::uint8_t m_return;
};
}
#include <poppack.h>
+474
View File
@@ -0,0 +1,474 @@
#pragma once
#define JSMN_STATIC
/*
* MIT License
*
* Copyright (c) 2010 Serge Zaitsev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef JSMN_H
#define JSMN_H
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
#ifdef JSMN_STATIC
#define JSMN_API inline_block static
#else
#define JSMN_API extern
#endif
/**
* JSON type identifier. Basic types are:
* o Object
* o Array
* o String
* o Other primitive: number, boolean (true/false) or null
*/
typedef enum {
JSMN_UNDEFINED = 0,
JSMN_OBJECT = 1 << 0,
JSMN_ARRAY = 1 << 1,
JSMN_STRING = 1 << 2,
JSMN_PRIMITIVE = 1 << 3
} jsmntype_t;
enum jsmnerr {
/* Not enough tokens were provided */
JSMN_ERROR_NOMEM = -1,
/* Invalid character inside JSON string */
JSMN_ERROR_INVAL = -2,
/* The string is not a full JSON packet, more bytes expected */
JSMN_ERROR_PART = -3
};
/**
* JSON token description.
* type type (object, array, string etc.)
* start start position in JSON data string
* end end position in JSON data string
*/
typedef struct jsmntok {
jsmntype_t type;
int start;
int end;
int size;
#ifdef JSMN_PARENT_LINKS
int parent;
#endif
} jsmntok_t;
/**
* JSON parser. Contains an array of token blocks available. Also stores
* the string being parsed now and current position in that string.
*/
typedef struct jsmn_parser {
unsigned int pos; /* offset in the JSON string */
unsigned int toknext; /* next token to allocate */
int toksuper; /* superior token node, e.g. parent object or array */
} jsmn_parser;
/**
* Create JSON parser over an array of tokens
*/
JSMN_API void jsmn_init(jsmn_parser* parser);
/**
* Run JSON parser. It parses a JSON data string into and array of tokens, each
* describing
* a single JSON object.
*/
JSMN_API int jsmn_parse(jsmn_parser* parser, const char* js, const size_t len,
jsmntok_t* tokens, const unsigned int num_tokens);
#ifndef JSMN_HEADER
/**
* Allocates a fresh unused token from the token pool.
*/
static jsmntok_t* jsmn_alloc_token(jsmn_parser* parser, jsmntok_t* tokens,
const size_t num_tokens) {
jsmntok_t* tok;
if (parser->toknext >= num_tokens) {
return NULL;
}
tok = &tokens[parser->toknext++];
tok->start = tok->end = -1;
tok->size = 0;
#ifdef JSMN_PARENT_LINKS
tok->parent = -1;
#endif
return tok;
}
/**
* Fills token type and boundaries.
*/
static void jsmn_fill_token(jsmntok_t* token, const jsmntype_t type,
const int start, const int end) {
token->type = type;
token->start = start;
token->end = end;
token->size = 0;
}
/**
* Fills next available token with JSON primitive.
*/
static int jsmn_parse_primitive(jsmn_parser* parser, const char* js,
const size_t len, jsmntok_t* tokens,
const size_t num_tokens) {
jsmntok_t* token;
int start;
start = parser->pos;
for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
switch (js[parser->pos]) {
#ifndef JSMN_STRICT
/* In strict mode primitive must be followed by "," or "}" or "]" */
case ':':
#endif
case '\t':
case '\r':
case '\n':
case ' ':
case ',':
case ']':
case '}':
goto found;
default:
/* to quiet a warning from gcc*/
break;
}
if (js[parser->pos] < 32 || js[parser->pos] >= 127) {
parser->pos = start;
return JSMN_ERROR_INVAL;
}
}
#ifdef JSMN_STRICT
/* In strict mode primitive must be followed by a comma/object/array */
parser->pos = start;
return JSMN_ERROR_PART;
#endif
found:
if (tokens == NULL) {
parser->pos--;
return 0;
}
token = jsmn_alloc_token(parser, tokens, num_tokens);
if (token == NULL) {
parser->pos = start;
return JSMN_ERROR_NOMEM;
}
jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos);
#ifdef JSMN_PARENT_LINKS
token->parent = parser->toksuper;
#endif
parser->pos--;
return 0;
}
/**
* Fills next token with JSON string.
*/
static int jsmn_parse_string(jsmn_parser* parser, const char* js,
const size_t len, jsmntok_t* tokens,
const size_t num_tokens) {
jsmntok_t* token;
int start = parser->pos;
/* Skip starting quote */
parser->pos++;
for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
char c = js[parser->pos];
/* Quote: end of string */
if (c == '\"') {
if (tokens == NULL) {
return 0;
}
token = jsmn_alloc_token(parser, tokens, num_tokens);
if (token == NULL) {
parser->pos = start;
return JSMN_ERROR_NOMEM;
}
jsmn_fill_token(token, JSMN_STRING, start + 1, parser->pos);
#ifdef JSMN_PARENT_LINKS
token->parent = parser->toksuper;
#endif
return 0;
}
/* Backslash: Quoted symbol expected */
if (c == '\\' && parser->pos + 1 < len) {
int i;
parser->pos++;
switch (js[parser->pos]) {
/* Allowed escaped symbols */
case '\"':
case '/':
case '\\':
case 'b':
case 'f':
case 'r':
case 'n':
case 't':
break;
/* Allows escaped symbol \uXXXX */
case 'u':
parser->pos++;
for (i = 0; i < 4 && parser->pos < len && js[parser->pos] != '\0';
i++) {
/* If it isn't a hex character we have an error */
if (!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */
(js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */
(js[parser->pos] >= 97 && js[parser->pos] <= 102))) { /* a-f */
parser->pos = start;
return JSMN_ERROR_INVAL;
}
parser->pos++;
}
parser->pos--;
break;
/* Unexpected symbol */
default:
parser->pos = start;
return JSMN_ERROR_INVAL;
}
}
}
parser->pos = start;
return JSMN_ERROR_PART;
}
/**
* Parse JSON string and fill tokens.
*/
JSMN_API int jsmn_parse(jsmn_parser* parser, const char* js, const size_t len,
jsmntok_t* tokens, const unsigned int num_tokens) {
int r;
int i;
jsmntok_t* token;
int count = parser->toknext;
for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) {
char c;
jsmntype_t type;
c = js[parser->pos];
switch (c) {
case '{':
case '[':
count++;
if (tokens == NULL) {
break;
}
token = jsmn_alloc_token(parser, tokens, num_tokens);
if (token == NULL) {
return JSMN_ERROR_NOMEM;
}
if (parser->toksuper != -1) {
jsmntok_t* t = &tokens[parser->toksuper];
#ifdef JSMN_STRICT
/* In strict mode an object or array can't become a key */
if (t->type == JSMN_OBJECT) {
return JSMN_ERROR_INVAL;
}
#endif
t->size++;
#ifdef JSMN_PARENT_LINKS
token->parent = parser->toksuper;
#endif
}
token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY);
token->start = parser->pos;
parser->toksuper = parser->toknext - 1;
break;
case '}':
case ']':
if (tokens == NULL) {
break;
}
type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY);
#ifdef JSMN_PARENT_LINKS
if (parser->toknext < 1) {
return JSMN_ERROR_INVAL;
}
token = &tokens[parser->toknext - 1];
for (;;) {
if (token->start != -1 && token->end == -1) {
if (token->type != type) {
return JSMN_ERROR_INVAL;
}
token->end = parser->pos + 1;
parser->toksuper = token->parent;
break;
}
if (token->parent == -1) {
if (token->type != type || parser->toksuper == -1) {
return JSMN_ERROR_INVAL;
}
break;
}
token = &tokens[token->parent];
}
#else
for (i = parser->toknext - 1; i >= 0; i--) {
token = &tokens[i];
if (token->start != -1 && token->end == -1) {
if (token->type != type) {
return JSMN_ERROR_INVAL;
}
parser->toksuper = -1;
token->end = parser->pos + 1;
break;
}
}
/* Error if unmatched closing bracket */
if (i == -1) {
return JSMN_ERROR_INVAL;
}
for (; i >= 0; i--) {
token = &tokens[i];
if (token->start != -1 && token->end == -1) {
parser->toksuper = i;
break;
}
}
#endif
break;
case '\"':
r = jsmn_parse_string(parser, js, len, tokens, num_tokens);
if (r < 0) {
return r;
}
count++;
if (parser->toksuper != -1 && tokens != NULL) {
tokens[parser->toksuper].size++;
}
break;
case '\t':
case '\r':
case '\n':
case ' ':
break;
case ':':
parser->toksuper = parser->toknext - 1;
break;
case ',':
if (tokens != NULL && parser->toksuper != -1 &&
tokens[parser->toksuper].type != JSMN_ARRAY &&
tokens[parser->toksuper].type != JSMN_OBJECT) {
#ifdef JSMN_PARENT_LINKS
parser->toksuper = tokens[parser->toksuper].parent;
#else
for (i = parser->toknext - 1; i >= 0; i--) {
if (tokens[i].type == JSMN_ARRAY || tokens[i].type == JSMN_OBJECT) {
if (tokens[i].start != -1 && tokens[i].end == -1) {
parser->toksuper = i;
break;
}
}
}
#endif
}
break;
#ifdef JSMN_STRICT
/* In strict mode primitives are: numbers and booleans */
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 't':
case 'f':
case 'n':
/* And they must not be keys of the object */
if (tokens != NULL && parser->toksuper != -1) {
const jsmntok_t* t = &tokens[parser->toksuper];
if (t->type == JSMN_OBJECT ||
(t->type == JSMN_STRING && t->size != 0)) {
return JSMN_ERROR_INVAL;
}
}
#else
/* In non-strict mode every unquoted value is a primitive */
default:
#endif
r = jsmn_parse_primitive(parser, js, len, tokens, num_tokens);
if (r < 0) {
return r;
}
count++;
if (parser->toksuper != -1 && tokens != NULL) {
tokens[parser->toksuper].size++;
}
break;
#ifdef JSMN_STRICT
/* Unexpected char in strict mode */
default:
return JSMN_ERROR_INVAL;
#endif
}
}
if (tokens != NULL) {
for (i = parser->toknext - 1; i >= 0; i--) {
/* Unmatched opened object or array */
if (tokens[i].start != -1 && tokens[i].end == -1) {
return JSMN_ERROR_PART;
}
}
}
return count;
}
/**
* Creates a new parser based over a given buffer with an array of tokens
* available.
*/
JSMN_API void jsmn_init(jsmn_parser* parser) {
parser->pos = 0;
parser->toknext = 0;
parser->toksuper = -1;
}
#endif /* JSMN_HEADER */
#ifdef __cplusplus
}
#endif
#endif /* JSMN_H */
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#pragma warning(disable : 4996)
class c_json
{
public:
c_json() = default;
~c_json();
void reset() noexcept;
bool parse(const char* data) noexcept;
bool is_equal(int index, const char* text);
const auto count() { return m_count; }
int get_value_integer(const char* name);
bool get_value_boolean(const char* name);
double get_value_double(const char* name);
private:
void get_value_internal(int index, char* buffer, size_t length);
private:
int m_count;
char* m_json;
jsmn_parser m_parser;
jsmntok_t m_tok[1024];
};
+22
View File
@@ -0,0 +1,22 @@
#pragma once
namespace k
{
typedef struct _SYSTEM_MODULE_ENTRY
{
HANDLE Section;
PVOID MappedBase;
PVOID ImageBase;
ULONG ImageSize;
ULONG Flags;
USHORT LoadOrderIndex;
USHORT InitOrderIndex;
USHORT LoadCount;
USHORT OffsetToFileName;
UCHAR FullPathName[256];
} SYSTEM_MODULE_ENTRY, * PSYSTEM_MODULE_ENTRY;
typedef enum _MEMORY_INFORMATION_CLASS {
MemoryBasicInformation
} MEMORY_INFORMATION_CLASS;
}
+700
View File
@@ -0,0 +1,700 @@
/*
* Copyright 2018-2020 Justas Masiulis
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// documentation is available at https://github.com/JustasMasiulis/lazy_importer
#ifndef LAZY_IMPORTER_HPP
#define LAZY_IMPORTER_HPP
#define LI_FN(name) \
::li::detail::lazy_function<::li::detail::khash(#name), decltype(&name)>()
#define LI_FN_DEF(name) ::li::detail::lazy_function<::li::detail::khash(#name), name>()
#define LI_MODULE(name) ::li::detail::lazy_module<::li::detail::khash(name)>()
// NOTE only std::forward is used from this header.
// If there is a need to eliminate this dependency the function itself is very small.
#include <utility>
#include <cstddef>
#include <intrin.h>
#ifndef LAZY_IMPORTER_NO_FORCEINLINE
#if defined(_MSC_VER)
#define LAZY_IMPORTER_FORCEINLINE inline
#elif defined(__GNUC__) && __GNUC__ > 3
#define LAZY_IMPORTER_FORCEINLINE inline __attribute__((__always_inline__))
#else
#define LAZY_IMPORTER_FORCEINLINE inline
#endif
#else
#define LAZY_IMPORTER_FORCEINLINE inline
#endif
#ifdef LAZY_IMPORTER_CASE_INSENSITIVE
#define LAZY_IMPORTER_TOLOWER(c) (c >= 'A' && c <= 'Z' ? (c | (1 << 5)) : c)
#else
#define LAZY_IMPORTER_TOLOWER(c) (c)
#endif
namespace li {
namespace detail {
template<class First, class Second>
struct pair {
First first;
Second second;
};
namespace win {
struct LIST_ENTRY_T {
const char* Flink;
const char* Blink;
};
struct UNICODE_STRING_T {
unsigned short Length;
unsigned short MaximumLength;
wchar_t* Buffer;
};
struct PEB_LDR_DATA_T {
unsigned long Length;
unsigned long Initialized;
const char* SsHandle;
LIST_ENTRY_T InLoadOrderModuleList;
};
struct PEB_T {
unsigned char Reserved1[2];
unsigned char BeingDebugged;
unsigned char Reserved2[1];
const char* Reserved3[2];
PEB_LDR_DATA_T* Ldr;
};
struct LDR_DATA_TABLE_ENTRY_T {
LIST_ENTRY_T InLoadOrderLinks;
LIST_ENTRY_T InMemoryOrderLinks;
LIST_ENTRY_T InInitializationOrderLinks;
const char* DllBase;
const char* EntryPoint;
union {
unsigned long SizeOfImage;
const char* _dummy;
};
UNICODE_STRING_T FullDllName;
UNICODE_STRING_T BaseDllName;
LAZY_IMPORTER_FORCEINLINE const LDR_DATA_TABLE_ENTRY_T*
load_order_next() const noexcept
{
return reinterpret_cast<const LDR_DATA_TABLE_ENTRY_T*>(
InLoadOrderLinks.Flink);
}
};
struct IMAGE_DOS_HEADER { // DOS .EXE header
unsigned short e_magic; // Magic number
unsigned short e_cblp; // Bytes on last page of file
unsigned short e_cp; // Pages in file
unsigned short e_crlc; // Relocations
unsigned short e_cparhdr; // Size of header in paragraphs
unsigned short e_minalloc; // Minimum extra paragraphs needed
unsigned short e_maxalloc; // Maximum extra paragraphs needed
unsigned short e_ss; // Initial (relative) SS value
unsigned short e_sp; // Initial SP value
unsigned short e_csum; // Checksum
unsigned short e_ip; // Initial IP value
unsigned short e_cs; // Initial (relative) CS value
unsigned short e_lfarlc; // File address of relocation table
unsigned short e_ovno; // Overlay number
unsigned short e_res[4]; // Reserved words
unsigned short e_oemid; // OEM identifier (for e_oeminfo)
unsigned short e_oeminfo; // OEM information; e_oemid specific
unsigned short e_res2[10]; // Reserved words
long e_lfanew; // File address of new exe header
};
struct IMAGE_FILE_HEADER {
unsigned short Machine;
unsigned short NumberOfSections;
unsigned long TimeDateStamp;
unsigned long PointerToSymbolTable;
unsigned long NumberOfSymbols;
unsigned short SizeOfOptionalHeader;
unsigned short Characteristics;
};
struct IMAGE_EXPORT_DIRECTORY {
unsigned long Characteristics;
unsigned long TimeDateStamp;
unsigned short MajorVersion;
unsigned short MinorVersion;
unsigned long Name;
unsigned long Base;
unsigned long NumberOfFunctions;
unsigned long NumberOfNames;
unsigned long AddressOfFunctions; // RVA from base of image
unsigned long AddressOfNames; // RVA from base of image
unsigned long AddressOfNameOrdinals; // RVA from base of image
};
struct IMAGE_DATA_DIRECTORY {
unsigned long VirtualAddress;
unsigned long Size;
};
struct IMAGE_OPTIONAL_HEADER64 {
unsigned short Magic;
unsigned char MajorLinkerVersion;
unsigned char MinorLinkerVersion;
unsigned long SizeOfCode;
unsigned long SizeOfInitializedData;
unsigned long SizeOfUninitializedData;
unsigned long AddressOfEntryPoint;
unsigned long BaseOfCode;
unsigned long long ImageBase;
unsigned long SectionAlignment;
unsigned long FileAlignment;
unsigned short MajorOperatingSystemVersion;
unsigned short MinorOperatingSystemVersion;
unsigned short MajorImageVersion;
unsigned short MinorImageVersion;
unsigned short MajorSubsystemVersion;
unsigned short MinorSubsystemVersion;
unsigned long Win32VersionValue;
unsigned long SizeOfImage;
unsigned long SizeOfHeaders;
unsigned long CheckSum;
unsigned short Subsystem;
unsigned short DllCharacteristics;
unsigned long long SizeOfStackReserve;
unsigned long long SizeOfStackCommit;
unsigned long long SizeOfHeapReserve;
unsigned long long SizeOfHeapCommit;
unsigned long LoaderFlags;
unsigned long NumberOfRvaAndSizes;
IMAGE_DATA_DIRECTORY DataDirectory[16];
};
struct IMAGE_OPTIONAL_HEADER32 {
unsigned short Magic;
unsigned char MajorLinkerVersion;
unsigned char MinorLinkerVersion;
unsigned long SizeOfCode;
unsigned long SizeOfInitializedData;
unsigned long SizeOfUninitializedData;
unsigned long AddressOfEntryPoint;
unsigned long BaseOfCode;
unsigned long BaseOfData;
unsigned long ImageBase;
unsigned long SectionAlignment;
unsigned long FileAlignment;
unsigned short MajorOperatingSystemVersion;
unsigned short MinorOperatingSystemVersion;
unsigned short MajorImageVersion;
unsigned short MinorImageVersion;
unsigned short MajorSubsystemVersion;
unsigned short MinorSubsystemVersion;
unsigned long Win32VersionValue;
unsigned long SizeOfImage;
unsigned long SizeOfHeaders;
unsigned long CheckSum;
unsigned short Subsystem;
unsigned short DllCharacteristics;
unsigned long SizeOfStackReserve;
unsigned long SizeOfStackCommit;
unsigned long SizeOfHeapReserve;
unsigned long SizeOfHeapCommit;
unsigned long LoaderFlags;
unsigned long NumberOfRvaAndSizes;
IMAGE_DATA_DIRECTORY DataDirectory[16];
};
struct IMAGE_NT_HEADERS {
unsigned long Signature;
IMAGE_FILE_HEADER FileHeader;
#ifdef _WIN64
IMAGE_OPTIONAL_HEADER64 OptionalHeader;
#else
IMAGE_OPTIONAL_HEADER32 OptionalHeader;
#endif
};
} // namespace win
// hashing stuff
struct hash_t {
using value_type = unsigned long;
constexpr static value_type offset = 2166136261;
constexpr static value_type prime = 16777619;
constexpr static unsigned long long prime64 = prime;
LAZY_IMPORTER_FORCEINLINE constexpr static value_type single(value_type value,
char c) noexcept
{
return static_cast<hash_t::value_type>(
(value ^ LAZY_IMPORTER_TOLOWER(c)) *
static_cast<unsigned long long>(prime));
}
};
template<class CharT = char>
LAZY_IMPORTER_FORCEINLINE constexpr hash_t::value_type
khash(const CharT* str, hash_t::value_type value = hash_t::offset) noexcept
{
return (*str ? khash(str + 1, hash_t::single(value, *str)) : value);
}
template<class CharT = char>
LAZY_IMPORTER_FORCEINLINE hash_t::value_type hash(const CharT* str) noexcept
{
hash_t::value_type value = hash_t::offset;
for (;;) {
char c = *str++;
if (!c)
return value;
value = hash_t::single(value, c);
}
}
LAZY_IMPORTER_FORCEINLINE hash_t::value_type hash(
const win::UNICODE_STRING_T& str) noexcept
{
auto first = str.Buffer;
const auto last = first + (str.Length / sizeof(wchar_t));
auto value = hash_t::offset;
for (; first != last; ++first)
value = hash_t::single(value, static_cast<char>(*first));
return value;
}
LAZY_IMPORTER_FORCEINLINE pair<hash_t::value_type, hash_t::value_type> hash_forwarded(
const char* str) noexcept
{
pair<hash_t::value_type, hash_t::value_type> module_and_function{
hash_t::offset, hash_t::offset
};
for (; *str != '.'; ++str)
module_and_function.first = hash_t::single(module_and_function.first, *str);
++str;
for (; *str; ++str)
module_and_function.second = hash_t::single(module_and_function.second, *str);
return module_and_function;
}
// some helper functions
LAZY_IMPORTER_FORCEINLINE const win::PEB_T* peb() noexcept
{
#if defined(_M_X64) || defined(__amd64__)
return reinterpret_cast<const win::PEB_T*>(__readgsqword(0x60));
#elif defined(_M_IX86) || defined(__i386__)
return reinterpret_cast<const win::PEB_T*>(__readfsdword(0x30));
#elif defined(_M_ARM) || defined(__arm__)
return *reinterpret_cast<const win::PEB_T**>(_MoveFromCoprocessor(15, 0, 13, 0, 2) + 0x30);
#elif defined(_M_ARM64) || defined(__aarch64__)
return *reinterpret_cast<const win::PEB_T**>(__getReg(18) + 0x60);
#elif defined(_M_IA64) || defined(__ia64__)
return *reinterpret_cast<const win::PEB_T**>(static_cast<char*>(_rdteb()) + 0x60);
#else
#error Unsupported platform. Open an issue and I'll probably add support.
#endif
}
LAZY_IMPORTER_FORCEINLINE const win::PEB_LDR_DATA_T* ldr()
{
return reinterpret_cast<const win::PEB_LDR_DATA_T*>(peb()->Ldr);
}
LAZY_IMPORTER_FORCEINLINE const win::IMAGE_NT_HEADERS* nt_headers(
const char* base) noexcept
{
return reinterpret_cast<const win::IMAGE_NT_HEADERS*>(
base + reinterpret_cast<const win::IMAGE_DOS_HEADER*>(base)->e_lfanew);
}
LAZY_IMPORTER_FORCEINLINE const win::IMAGE_EXPORT_DIRECTORY* image_export_dir(
const char* base) noexcept
{
return reinterpret_cast<const win::IMAGE_EXPORT_DIRECTORY*>(
base + nt_headers(base)->OptionalHeader.DataDirectory->VirtualAddress);
}
LAZY_IMPORTER_FORCEINLINE const win::LDR_DATA_TABLE_ENTRY_T* ldr_data_entry() noexcept
{
return reinterpret_cast<const win::LDR_DATA_TABLE_ENTRY_T*>(
ldr()->InLoadOrderModuleList.Flink);
}
struct exports_directory {
const char* _base;
const win::IMAGE_EXPORT_DIRECTORY* _ied;
unsigned long _ied_size;
public:
using size_type = unsigned long;
LAZY_IMPORTER_FORCEINLINE
exports_directory(const char* base) noexcept : _base(base)
{
const auto ied_data_dir = nt_headers(base)->OptionalHeader.DataDirectory[0];
_ied = reinterpret_cast<const win::IMAGE_EXPORT_DIRECTORY*>(
base + ied_data_dir.VirtualAddress);
_ied_size = ied_data_dir.Size;
}
LAZY_IMPORTER_FORCEINLINE explicit operator bool() const noexcept
{
return reinterpret_cast<const char*>(_ied) != _base;
}
LAZY_IMPORTER_FORCEINLINE size_type size() const noexcept
{
return _ied->NumberOfNames;
}
LAZY_IMPORTER_FORCEINLINE const char* base() const noexcept { return _base; }
LAZY_IMPORTER_FORCEINLINE const win::IMAGE_EXPORT_DIRECTORY* ied() const noexcept
{
return _ied;
}
LAZY_IMPORTER_FORCEINLINE const char* name(size_type index) const noexcept
{
return reinterpret_cast<const char*>(
_base + reinterpret_cast<const unsigned long*>(
_base + _ied->AddressOfNames)[index]);
}
LAZY_IMPORTER_FORCEINLINE const char* address(size_type index) const noexcept
{
const auto* const rva_table =
reinterpret_cast<const unsigned long*>(_base + _ied->AddressOfFunctions);
const auto* const ord_table = reinterpret_cast<const unsigned short*>(
_base + _ied->AddressOfNameOrdinals);
return _base + rva_table[ord_table[index]];
}
LAZY_IMPORTER_FORCEINLINE bool is_forwarded(
const char* export_address) const noexcept
{
const auto ui_ied = reinterpret_cast<const char*>(_ied);
return (export_address > ui_ied && export_address < ui_ied + _ied_size);
}
};
struct safe_module_enumerator {
using value_type = const detail::win::LDR_DATA_TABLE_ENTRY_T;
value_type* value;
value_type* head;
LAZY_IMPORTER_FORCEINLINE safe_module_enumerator() noexcept
: safe_module_enumerator(ldr_data_entry())
{}
LAZY_IMPORTER_FORCEINLINE
safe_module_enumerator(const detail::win::LDR_DATA_TABLE_ENTRY_T* ldr) noexcept
: value(ldr->load_order_next()), head(value)
{}
LAZY_IMPORTER_FORCEINLINE void reset() noexcept
{
value = head->load_order_next();
}
LAZY_IMPORTER_FORCEINLINE bool next() noexcept
{
value = value->load_order_next();
return value != head && value->DllBase;
}
};
struct unsafe_module_enumerator {
using value_type = const detail::win::LDR_DATA_TABLE_ENTRY_T*;
value_type value;
LAZY_IMPORTER_FORCEINLINE unsafe_module_enumerator() noexcept
: value(ldr_data_entry())
{}
LAZY_IMPORTER_FORCEINLINE void reset() noexcept { value = ldr_data_entry(); }
LAZY_IMPORTER_FORCEINLINE bool next() noexcept
{
value = value->load_order_next();
return true;
}
};
// provides the cached functions which use Derive classes methods
template<class Derived, class DefaultType = void*>
class lazy_base {
protected:
// This function is needed because every templated function
// with different args has its own static buffer
LAZY_IMPORTER_FORCEINLINE static void*& _cache() noexcept
{
static void* value = nullptr;
return value;
}
public:
template<class T = DefaultType>
LAZY_IMPORTER_FORCEINLINE static T safe() noexcept
{
return Derived::template get<T, safe_module_enumerator>();
}
template<class T = DefaultType, class Enum = unsafe_module_enumerator>
LAZY_IMPORTER_FORCEINLINE static T cached() noexcept
{
auto& cached = _cache();
if (!cached)
cached = Derived::template get<void*, Enum>();
return (T)(cached);
}
template<class T = DefaultType>
LAZY_IMPORTER_FORCEINLINE static T safe_cached() noexcept
{
return cached<T, safe_module_enumerator>();
}
};
template<hash_t::value_type Hash>
struct lazy_module : lazy_base<lazy_module<Hash>> {
template<class T = void*, class Enum = unsafe_module_enumerator>
LAZY_IMPORTER_FORCEINLINE static T get() noexcept
{
Enum e;
do {
if (hash(e.value->BaseDllName) == Hash)
return (T)(e.value->DllBase);
} while (e.next());
return {};
}
template<class T = void*, class Ldr>
LAZY_IMPORTER_FORCEINLINE static T in(Ldr ldr) noexcept
{
safe_module_enumerator e((const detail::win::LDR_DATA_TABLE_ENTRY_T*)(ldr));
do {
if (hash(e.value->BaseDllName) == Hash)
return (T)(e.value->DllBase);
} while (e.next());
return {};
}
template<class T = void*, class Ldr>
LAZY_IMPORTER_FORCEINLINE static T in_cached(Ldr ldr) noexcept
{
auto& cached = lazy_base<lazy_module<Hash>>::_cache();
if (!cached)
cached = in(ldr);
return (T)(cached);
}
};
template<hash_t::value_type Hash, class T>
struct lazy_function : lazy_base<lazy_function<Hash, T>, T> {
using base_type = lazy_base<lazy_function<Hash, T>, T>;
template<class... Args>
LAZY_IMPORTER_FORCEINLINE decltype(auto) operator()(Args&&... args) const
{
#ifndef LAZY_IMPORTER_CACHE_OPERATOR_PARENS
return get()(std::forward<Args>(args)...);
#else
return this->cached()(std::forward<Args>(args)...);
#endif
}
template<class F = T, class Enum = unsafe_module_enumerator>
LAZY_IMPORTER_FORCEINLINE static F get() noexcept
{
// for backwards compatability.
// Before 2.0 it was only possible to resolve forwarded exports when
// this macro was enabled
#ifdef LAZY_IMPORTER_RESOLVE_FORWARDED_EXPORTS
return forwarded<F, Enum>();
#else
Enum e;
do {
#ifdef LAZY_IMPORTER_HARDENED_MODULE_CHECKS
if (!e.value->DllBase || !e.value->FullDllName.Length)
continue;
#endif
const exports_directory exports(e.value->DllBase);
if (exports) {
auto export_index = exports.size();
while (export_index--)
if (hash(exports.name(export_index)) == Hash)
return (F)(exports.address(export_index));
}
} while (e.next());
return {};
#endif
}
template<class F = T, class Enum = unsafe_module_enumerator>
LAZY_IMPORTER_FORCEINLINE static F forwarded() noexcept
{
detail::win::UNICODE_STRING_T name;
hash_t::value_type module_hash = 0;
auto function_hash = Hash;
Enum e;
do {
name = e.value->BaseDllName;
name.Length -= 8; // get rid of .dll extension
if (!module_hash || hash(name) == module_hash) {
const exports_directory exports(e.value->DllBase);
if (exports) {
auto export_index = exports.size();
while (export_index--)
if (hash(exports.name(export_index)) == function_hash) {
const auto addr = exports.address(export_index);
if (exports.is_forwarded(addr)) {
auto hashes = hash_forwarded(
reinterpret_cast<const char*>(addr));
function_hash = hashes.second;
module_hash = hashes.first;
e.reset();
break;
}
return (F)(addr);
}
}
}
} while (e.next());
return {};
}
template<class F = T>
LAZY_IMPORTER_FORCEINLINE static F forwarded_safe() noexcept
{
return forwarded<F, safe_module_enumerator>();
}
template<class F = T, class Enum = unsafe_module_enumerator>
LAZY_IMPORTER_FORCEINLINE static F forwarded_cached() noexcept
{
auto& value = base_type::_cache();
if (!value)
value = forwarded<void*, Enum>();
return (F)(value);
}
template<class F = T>
LAZY_IMPORTER_FORCEINLINE static F forwarded_safe_cached() noexcept
{
return forwarded_cached<F, safe_module_enumerator>();
}
template<class F = T, bool IsSafe = false, class Module>
LAZY_IMPORTER_FORCEINLINE static F in(Module m) noexcept
{
if (IsSafe && !m)
return {};
const exports_directory exports((const char*)(m));
if (IsSafe && !exports)
return {};
for (unsigned long i{};; ++i) {
if (IsSafe && i == exports.size())
break;
if (hash(exports.name(i)) == Hash)
return (F)(exports.address(i));
}
return {};
}
template<class F = T, class Module>
LAZY_IMPORTER_FORCEINLINE static F in_safe(Module m) noexcept
{
return in<F, true>(m);
}
template<class F = T, bool IsSafe = false, class Module>
LAZY_IMPORTER_FORCEINLINE static F in_cached(Module m) noexcept
{
auto& value = base_type::_cache();
if (!value)
value = in<void*, IsSafe>(m);
return (F)(value);
}
template<class F = T, class Module>
LAZY_IMPORTER_FORCEINLINE static F in_safe_cached(Module m) noexcept
{
return in_cached<F, true>(m);
}
template<class F = T>
LAZY_IMPORTER_FORCEINLINE static F nt() noexcept
{
return in<F>(ldr_data_entry()->load_order_next()->DllBase);
}
template<class F = T>
LAZY_IMPORTER_FORCEINLINE static F nt_safe() noexcept
{
return in_safe<F>(ldr_data_entry()->load_order_next()->DllBase);
}
template<class F = T>
LAZY_IMPORTER_FORCEINLINE static F nt_cached() noexcept
{
return in_cached<F>(ldr_data_entry()->load_order_next()->DllBase);
}
template<class F = T>
LAZY_IMPORTER_FORCEINLINE static F nt_safe_cached() noexcept
{
return in_safe_cached<F>(ldr_data_entry()->load_order_next()->DllBase);
}
};
}
} // namespace li::detail
#endif // include guard
+38
View File
@@ -0,0 +1,38 @@
#pragma once
inline_block void log_internal(const char* fmt, ...)
{
#if !defined(HS_DISABLE_LOGS)
char cad[512];
va_list list{ };
ZERO_MEM(cad, sizeof(cad));
va_start(list, fmt);
LI_FN(wvsprintfA).cached()(cad, fmt, list);
va_end(list);
win_api::output_debug_string(cad);
#else
__noop();
#endif
}
template <typename... T>
extern void __log_monitor_call(void* ret_addr, const char* funcname, const char* format, T&&... arguments);
template <typename... T>
extern void __log_monitor_call_nofilter(void* ret_addr, const char* funcname, const char* format, T&&... arguments);
#define log_mon_call(X, ...) __log_monitor_call(_ReturnAddress(), _XS(__FUNCTION__), _XS(X), __VA_ARGS__)
#define log_mon_call_nf(X, ...) __log_monitor_call_nofilter(_ReturnAddress(), _XS(__FUNCTION__), _XS(X), __VA_ARGS__)
#define log_legacy(...) log_internal(__VA_ARGS__)
#define log_info_(X, ...) log_legacy(_XS(X))
#define log_info(...) log_legacy(__VA_ARGS__)
#define log_call() log_info("LOG_CALL '%s'", _XS(__FUNCTION__))
+51
View File
@@ -0,0 +1,51 @@
#pragma once
template <typename... T>
void __log_monitor_call(void* ret_addr, const char* funcname, const char* format, T&&... arguments)
{
//
// ignore calls from within our own image.
//
if (r5::is_within_self(ret_addr))
return;
//
// only log API calls outside of valid images.
//
if (util::file_header(ret_addr) != nullptr)
return;
size_t length = 0;
char cad[512];
length += LI_FN(wsprintfA).cached()(cad + length, _XS("MON_CALL @ #%p '%s' "), ret_addr, funcname);
length += LI_FN(wsprintfA).cached()(cad + length, format, arguments...);
length += LI_FN(wsprintfA).cached()(cad + length, _XS("\n"));
win_api::output_debug_string(cad);
}
template <typename... T>
void __log_monitor_call_nofilter(void* ret_addr, const char* funcname, const char* format, T&&... arguments)
{
//
// ignore calls from within our own image.
//
if (r5::is_within_self(ret_addr))
return;
//
// only log API calls outside of valid images.
//
if (util::file_header(ret_addr) != nullptr)
return;
size_t length = 0;
char cad[512];
length += LI_FN(wsprintfA).cached()(cad + length, _XS("MON_CALL @ #%p '%s' "), ret_addr, funcname);
length += LI_FN(wsprintfA).cached()(cad + length, format, arguments...);
length += LI_FN(wsprintfA).cached()(cad + length, _XS("\n"));
win_api::output_debug_string(cad);
}
+812
View File
@@ -0,0 +1,812 @@
#pragma once
#pragma warning(push, 0)
#define __HI(x) *(1+(int*)&x)
#define __LO(x) *(int*)&x
#define __HIp(x) *(1+(int*)x)
#define __LOp(x) *(int*)x
#define POLYNOM1(x, a) ((a)[1]*(x)+(a)[0])
#define POLYNOM2(x, a) (POLYNOM1((x),(a)+1)*(x)+(a)[0])
#define POLYNOM3(x, a) (POLYNOM2((x),(a)+1)*(x)+(a)[0])
#define POLYNOM4(x, a) (POLYNOM3((x),(a)+1)*(x)+(a)[0])
#define POLYNOM5(x, a) (POLYNOM4((x),(a)+1)*(x)+(a)[0])
#define POLYNOM6(x, a) (POLYNOM5((x),(a)+1)*(x)+(a)[0])
#define POLYNOM7(x, a) (POLYNOM6((x),(a)+1)*(x)+(a)[0])
#define POLYNOM8(x, a) (POLYNOM7((x),(a)+1)*(x)+(a)[0])
#define POLYNOM9(x, a) (POLYNOM8((x),(a)+1)*(x)+(a)[0])
#define POLYNOM10(x, a) (POLYNOM9((x),(a)+1)*(x)+(a)[0])
#define POLYNOM11(x, a) (POLYNOM10((x),(a)+1)*(x)+(a)[0])
#define POLYNOM12(x, a) (POLYNOM11((x),(a)+1)*(x)+(a)[0])
#define POLYNOM13(x, a) (POLYNOM12((x),(a)+1)*(x)+(a)[0])
#define M_LN_MAX_D (M_LN2 * DBL_MAX_EXP)
#define M_LN_MIN_D (M_LN2 * (DBL_MIN_EXP - 1))
struct f64
{
uint32_t low_word;
uint32_t high_word;
};
#define F64_SIGN_SHIFT 31
#define F64_SIGN_MASK 1
#define F64_EXP_SHIFT 20
#define F64_EXP_MASK 0x7ff
#define F64_EXP_BIAS 1023
#define F64_EXP_MAX 2047
#define F64_MANT_SHIFT 0
#define F64_MANT_MASK 0xfffff
#define F64_GET_SIGN(fp) (((fp)->high_word >> F64_SIGN_SHIFT) & \
F64_SIGN_MASK)
#define F64_GET_EXP(fp) (((fp)->high_word >> F64_EXP_SHIFT) & \
F64_EXP_MASK)
#define F64_SET_EXP(fp, val) ((fp)->high_word= ((fp)->high_word & \
~(F64_EXP_MASK << F64_EXP_SHIFT)) | \
(((val) & F64_EXP_MASK) << F64_EXP_SHIFT))
#define F64_GET_MANT_LOW(fp) ((fp)->low_word)
#define F64_SET_MANT_LOW(fp, val) ((fp)->low_word= (val))
#define F64_GET_MANT_HIGH(fp) (((fp)->high_word >> F64_MANT_SHIFT) & \
F64_MANT_MASK)
#define F64_SET_MANT_HIGH(fp, val) ((fp)->high_word= ((fp)->high_word & \
~(F64_MANT_MASK << F64_MANT_SHIFT)) | \
(((val) & F64_MANT_MASK) << F64_MANT_SHIFT))
namespace math
{
static const double huge = 1.0e300;
template <typename _t>
struct position_t
{
_t x;
_t y;
_t length()
{
return x + y;
}
_t distance_to(const position_t<_t>& other)
{
return length() - other.length();
}
template <typename _n>
_n static_type_convert()
{
return position_t<_n>{static_cast<_n>(x), static_cast<_n>(y)};
}
};
template <typename _t>
struct dimension_t
{
_t w;
_t h;
};
constexpr double calculate_percentage(const double current, const double max)
{
if (max == 0.0) {
return 0.0;
}
if (current > max) {
return 100.0;
}
// G = max
// W = value
return ((current * 100.0) / max);
}
template < typename _t >
struct range_t {
_t min;
_t max;
};
template < typename _t >
struct floating_point_holder2_t {
_t x;
_t y;
};
template < typename _t >
struct floating_point_holder3_t {
_t x;
_t y;
_t z;
};
template < typename _t >
struct floating_point_holder4_t {
_t x;
_t y;
_t z;
_t h;
};
inline float sqrtf(float _X) { return _mm_cvtss_f32(_mm_sqrt_ss(_mm_set_ss(_X))); }
inline float expf(float _X) { return _mm_cvtss_f32(_mm_exp_ps(_mm_set_ss(_X))); }
inline float asinf(float _X) { return _mm_cvtss_f32(_mm_asin_ps(_mm_set_ss(_X))); }
inline float fabsf(float x)
{
union
{
float f;
uint32_t i;
} u = { x };
u.i &= 0x7fffffff;
return u.f;
}
inline int isinf(double x)
{
union { uint64_t u; double f; } ieee754;
ieee754.f = x;
return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) == 0x7ff00000 &&
((unsigned)ieee754.u == 0);
}
inline int isnan(double x)
{
union { uint64_t u; double f; } ieee754;
ieee754.f = x;
return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) +
((unsigned)ieee754.u != 0) > 0x7ff00000;
}
inline int signbit(double x)
{
union {
double d;
uint64_t i;
} y = { x };
return y.i >> 63;
}
inline float fminf(float x, float y)
{
if (isnan(x))
return y;
if (isnan(y))
return x;
if (signbit(x) != signbit(y))
return signbit(x) ? x : y;
return x < y ? x : y;
}
inline float fmaxf(float x, float y)
{
if (isnan(x))
return y;
if (isnan(y))
return x;
if (signbit(x) != signbit(y))
return signbit(x) ? y : x;
return x < y ? y : x;
}
inline float atan2f(float y, float x)
{
float a, r, s, t, c, q, ax, ay, mx, mn;
ax = fabsf(x);
ay = fabsf(y);
mx = fmaxf(ay, ax);
mn = fminf(ay, ax);
a = mn / mx;
s = a * a;
c = s * a;
q = s * s;
r = 0.024840285f * q + 0.18681418f;
t = -0.094097948f * q - 0.33213072f;
r = r * s + t;
r = r * c + a;
if (ay > ax) r = 1.57079637f - r;
if (x < 0) r = 3.14159274f - r;
if (y < 0) r = -r;
return r;
}
inline static float FOPI = (float)1.27323954473516;
inline static float DP1 = (float)0.78515625;
inline static float DP2 = (float)2.4187564849853515625e-4;
inline static float DP3 = (float)3.77489497744594108e-8;
inline static float lossth = (float)8192.;
inline static float T24M1 = (float)16777215.;
inline static float sincof[] = {
(float)-1.9515295891E-4,
(float)8.3321608736E-3,
(float)-1.6666654611E-1
};
inline static float coscof[] = {
(float)2.443315711809948E-005,
(float)-1.388731625493765E-003,
(float)4.166664568298827E-002
};
inline float acos(float x) {
float negate = float(x < 0);
x = abs(x);
float ret = -0.0187293;
ret = ret * x;
ret = ret + 0.0742610;
ret = ret * x;
ret = ret - 0.2121144;
ret = ret * x;
ret = ret + 1.5707288;
ret = ret * sqrtf(1.0 - x);
ret = ret - 2 * negate * ret;
return negate * 3.14159265358979 + ret;
}
inline float sinf(float xx)
{
float* p;
float x, y, z;
unsigned long j;
int sign;
sign = 1;
x = xx;
if (xx < 0)
{
sign = -1;
x = -xx;
}
if (x > T24M1)
{
return(0.0);
}
j = FOPI * x;
y = j;
if (j & 1)
{
j += 1;
y += 1.0;
}
j &= 7;
if (j > 3)
{
sign = -sign;
j -= 4;
}
if (x > lossth)
{
x = x - y * M_PI_4;
}
else
{
x = ((x - y * DP1) - y * DP2) - y * DP3;
}
z = x * x;
if ((j == 1) || (j == 2))
{
p = coscof;
y = *p++;
y = y * z + *p++;
y = y * z + *p++;
y *= z * z;
y -= 0.5 * z;
y += 1.0;
}
else
{
p = sincof;
y = *p++;
y = y * z + *p++;
y = y * z + *p++;
y *= z * x;
y += x;
}
if (sign < 0)
y = -y;
return(y);
}
inline float cosf(float xx)
{
float x, y, z;
int j, sign;
sign = 1;
x = xx;
if (x < 0)
x = -x;
if (x > T24M1)
{
return(0.0);
}
j = FOPI * x;
y = j;
if (j & 1)
{
j += 1;
y += 1.0;
}
j &= 7;
if (j > 3)
{
j -= 4;
sign = -sign;
}
if (j > 1)
sign = -sign;
if (x > lossth)
{
x = x - y * M_PI_4;
}
else
x = ((x - y * DP1) - y * DP2) - y * DP3;
z = x * x;
if ((j == 1) || (j == 2))
{
y = (((-1.9515295891E-4 * z
+ 8.3321608736E-3) * z
- 1.6666654611E-1) * z * x)
+ x;
}
else
{
y = ((2.443315711809948E-005 * z
- 1.388731625493765E-003) * z
+ 4.166664568298827E-002) * z * z;
y -= 0.5 * z;
y += 1.0;
}
if (sign < 0)
y = -y;
return(y);
}
inline double floor(double x)
{
int i0, i1, j0;
unsigned i, j;
i0 = __HI(x);
i1 = __LO(x);
j0 = ((i0 >> 20) & 0x7ff) - 0x3ff;
if (j0 < 20) {
if (j0 < 0) { /* raise inexact if x != 0 */
if (huge + x > 0.0) {/* return 0*sign(x) if |x|<1 */
if (i0 >= 0) { i0 = i1 = 0; }
else if (((i0 & 0x7fffffff) | i1) != 0)
{
i0 = 0xbff00000; i1 = 0;
}
}
}
else {
i = (0x000fffff) >> j0;
if (((i0 & i) | i1) == 0) return x; /* x is integral */
if (huge + x > 0.0) { /* raise inexact flag */
if (i0 < 0) i0 += (0x00100000) >> j0;
i0 &= (~i); i1 = 0;
}
}
}
else if (j0 > 51) {
if (j0 == 0x400) return x + x; /* inf or NaN */
else return x; /* x is integral */
}
else {
i = ((unsigned)(0xffffffff)) >> (j0 - 20);
if ((i1 & i) == 0) return x; /* x is integral */
if (huge + x > 0.0) { /* raise inexact flag */
if (i0 < 0) {
if (j0 == 20) i0 += 1;
else {
j = i1 + (1 << (52 - j0));
if (j < i1) i0 += 1; /* got a carry */
i1 = j;
}
}
i1 &= (~i);
}
}
__HI(x) = i0;
__LO(x) = i1;
return x;
}
inline float floorf(float f)
{
return (float)floor((double)f);
}
inline float roundf(float x)
{
float t;
if (x >= 0.0) {
t = floorf(x);
if (t - x <= -0.5)
t += 1.0;
return t;
}
else {
t = floorf(-x);
if (t + x <= -0.5)
t += 1.0;
return -t;
}
}
inline double modf(double value, double* iptr)
{
struct f64* f64p;
double tmp;
int exp;
int mask_bits;
uint32_t mant;
f64p = (struct f64*)&value;
exp = F64_GET_EXP(f64p);
exp -= F64_EXP_BIAS;
if (exp < 0)
{
*iptr = 0;
return value;
}
mask_bits = 52 - exp;
if (mask_bits <= 0)
{
*iptr = value;
return 0;
}
tmp = value;
if (mask_bits >= 32)
{
F64_SET_MANT_LOW(f64p, 0);
mask_bits -= 32;
mant = F64_GET_MANT_HIGH(f64p);
mant &= ~((1 << mask_bits) - 1);
F64_SET_MANT_HIGH(f64p, mant);
}
else
{
mant = F64_GET_MANT_LOW(f64p);
mant &= ~((1 << mask_bits) - 1);
F64_SET_MANT_LOW(f64p, mant);
}
*iptr = value;
return tmp - value;
}
inline double
tan(double x)
{
/* Algorithm and coefficients from:
"Software manual for the elementary functions"
by W.J. Cody and W. Waite, Prentice-Hall, 1980
*/
int negative = x < 0;
int invert = 0;
double y;
static double p[] = {
1.0,
-0.13338350006421960681e+0,
0.34248878235890589960e-2,
-0.17861707342254426711e-4
};
static double q[] = {
1.0,
-0.46671683339755294240e+0,
0.25663832289440112864e-1,
-0.31181531907010027307e-3,
0.49819433993786512270e-6
};
if (math::isnan(x)) {
return x;
}
if (negative) x = -x;
/* ??? avoid loss of significance, error if x is too large ??? */
y = x * M_2_PI + 0.5;
if (y >= DBL_MAX / M_PI_2) return 0.0;
/* Use extended precision to calculate reduced argument.
Here we used 12 bits of the mantissa for a1.
Also split x in integer part x1 and fraction part x2.
*/
#define A1 1.57080078125
#define A2 -4.454455103380768678308e-6
{
double x1, x2;
modf(y, &y);
if (modf(0.5 * y, &x1)) invert = 1;
x2 = modf(x, &x1);
x = x1 - y * A1;
x += x2;
x -= y * A2;
#undef A1
#undef A2
}
/* ??? avoid underflow ??? */
y = x * x;
x += x * y * POLYNOM2(y, p + 1);
y = POLYNOM4(y, q);
if (negative) x = -x;
return invert ? -y / x : x / y;
}
inline float tanf(float x)
{
return tan(x);
}
static int maxExponent = 511; /* Largest possible base 10 exponent. Any
* exponent larger than this will already
* produce underflow or overflow, so there's
* no need to worry about additional digits.
*/
static double powersOf10[] = { /* Table giving binary powers of 10. Entry */
10., /* is 10^2^i. Used to convert decimal */
100., /* exponents into floating-point numbers. */
1.0e4,
1.0e8,
1.0e16,
1.0e32,
1.0e64,
1.0e128,
1.0e256
};
inline int isspace(int c)
{
return (c == '\t' || c == '\n' ||
c == '\v' || c == '\f' || c == '\r' || c == ' ' ? 1 : 0);
}
inline char isdigit(unsigned char c)
{
if (c >= '0' && c <= '9')
return 1;
return 0;
}
inline int isalpha(int c)
{
/*
* Depends on ASCII-like character ordering.
*/
return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ? 1 : 0);
}
inline char isupper(unsigned char c)
{
if (c >= UC('A') && c <= UC('Z'))
return 1;
return 0;
}
inline double atof(char* string) /* A decimal ASCII floating-point number,
* optionally preceded by white space.
* Must have form "-I.FE-X", where I is the
* integer part of the mantissa, F is the
* fractional part of the mantissa, and X
* is the exponent. Either of the signs
* may be "+", "-", or omitted. Either I
* or F may be omitted, or both. The decimal
* point isn't necessary unless F is present.
* The "E" may actually be an "e". E and X
* may both be omitted (but not just one).
*/
{
int sign, expSign = FALSE;
double fraction, dblExp, * d;
register char* p, c;
int exp = 0; /* Exponent read from "EX" field. */
int fracExp = 0; /* Exponent that derives from the fractional
* part. Under normal circumstatnces, it is
* the negative of the number of digits in F.
* However, if I is very long, the last digits
* of I get dropped (otherwise a long I with a
* large negative exponent could cause an
* unnecessary overflow on I alone). In this
* case, fracExp is incremented one for each
* dropped digit.
*/
int mantSize; /* Number of digits in mantissa. */
int decPt; /* Number of mantissa digits BEFORE decimal
* point.
*/
char* pExp; /* Temporarily holds location of exponent
* in string.
*/
/*
* Strip off leading blanks and check for a sign.
*/
p = string;
while (isspace(*p)) {
p += 1;
}
if (*p == '-') {
sign = TRUE;
p += 1;
}
else {
if (*p == '+') {
p += 1;
}
sign = FALSE;
}
/*
* Count the number of digits in the mantissa (including the decimal
* point), and also locate the decimal point.
*/
decPt = -1;
for (mantSize = 0; ; mantSize += 1)
{
c = *p;
if (!isdigit(c)) {
if ((c != '.') || (decPt >= 0)) {
break;
}
decPt = mantSize;
}
p += 1;
}
/*
* Now suck up the digits in the mantissa. Use two integers to
* collect 9 digits each (this is faster than using floating-point).
* If the mantissa has more than 18 digits, ignore the extras, since
* they can't affect the value anyway.
*/
pExp = p;
p -= mantSize;
if (decPt < 0) {
decPt = mantSize;
}
else {
mantSize -= 1; /* One of the digits was the point. */
}
if (mantSize > 18) {
fracExp = decPt - 18;
mantSize = 18;
}
else {
fracExp = decPt - mantSize;
}
if (mantSize == 0) {
return 0.0;
}
else {
int frac1, frac2;
frac1 = 0;
for (; mantSize > 9; mantSize -= 1)
{
c = *p;
p += 1;
if (c == '.') {
c = *p;
p += 1;
}
frac1 = 10 * frac1 + (c - '0');
}
frac2 = 0;
for (; mantSize > 0; mantSize -= 1)
{
c = *p;
p += 1;
if (c == '.') {
c = *p;
p += 1;
}
frac2 = 10 * frac2 + (c - '0');
}
fraction = (1.0e9 * frac1) + frac2;
}
/*
* Skim off the exponent.
*/
p = pExp;
if ((*p == 'E') || (*p == 'e')) {
p += 1;
if (*p == '-') {
expSign = TRUE;
p += 1;
}
else {
if (*p == '+') {
p += 1;
}
expSign = FALSE;
}
while (isdigit(*p)) {
exp = exp * 10 + (*p - '0');
p += 1;
}
}
if (expSign) {
exp = fracExp - exp;
}
else {
exp = fracExp + exp;
}
/*
* Generate a floating-point number that represents the exponent.
* Do this by processing the exponent one bit at a time to combine
* many powers of 2 of 10. Then combine the exponent with the
* fraction.
*/
if (exp < 0) {
expSign = TRUE;
exp = -exp;
}
else {
expSign = FALSE;
}
if (exp > maxExponent) {
exp = maxExponent;
}
dblExp = 1.0;
for (d = powersOf10; exp != 0; exp >>= 1, d += 1) {
if (exp & 01) {
dblExp *= *d;
}
}
if (expSign) {
fraction /= dblExp;
}
else {
fraction *= dblExp;
}
if (sign) {
return -fraction;
}
return fraction;
}
}
#pragma warning(pop)
+130
View File
@@ -0,0 +1,130 @@
#pragma once
namespace mem
{
struct range {
uintptr_t m_begin{};
uintptr_t m_end{};
uintptr_t m_size{};
};
class addr
{
public:
addr() = default;
~addr() = default;
bool operator==(const DWORD_PTR& other) const
{
return (m_base == other);
}
bool operator==(const DWORD_PTR& lhs)
{
return (lhs == m_base);
}
addr(const DWORD_PTR base)
{
m_base = base;
}
addr(void* const ptr)
{
m_base = reinterpret_cast<DWORD_PTR>(ptr);
}
[[nodiscard]] auto Get() const
{
return addr(m_base);
}
[[nodiscard]] auto Base() const
{
return m_base;
}
[[nodiscard]] auto Valid() const
{
return !(m_base == 0);
}
[[nodiscard]] auto Add(const DWORD_PTR t) const
{
return addr(m_base + t);
}
[[nodiscard]] auto Sub(const DWORD_PTR t) const
{
return addr(m_base - t);
}
[[nodiscard]] auto Deref() const
{
return addr(*reinterpret_cast<DWORD_PTR*>(m_base));
}
[[nodiscard]] auto Ptr() const
{
return reinterpret_cast<PVOID>(m_base);
}
template < class T >
[[nodiscard]] auto As()
{
return reinterpret_cast<T>(m_base);
}
template < class T >
[[nodiscard]] auto Retrieve_as()
{
return *reinterpret_cast<T*>(m_base);
}
template < class T >
void Set(const T& value)
{
*As<T*>() = value;
}
private:
DWORD_PTR m_base;
};
class bare_pointer
{
public:
bare_pointer(void* const ptr)
{
m_instance = ptr;
}
[[nodiscard]] addr base() const
{
return addr(m_instance);
}
[[nodiscard]] auto deref() const
{
return *static_cast<void**>(m_instance);
}
private:
void* m_instance;
};
INLINE DWORD_PTR ResolveAddressToRelative(DWORD_PTR dwInitial, DWORD_PTR dwInstructionOffset, DWORD_PTR dwPostOffset)
{
if (dwInitial == NULL)
return NULL;
CONST AUTO dwRelativeAddyOffset = (dwInitial + dwInstructionOffset);
CONST AUTO dwRelativeAddy = *reinterpret_cast<LONG*>(dwRelativeAddyOffset);
CONST AUTO dwRelativeResult = dwInitial + dwRelativeAddy;
if (dwPostOffset != NULL)
return dwRelativeResult + dwPostOffset;
return dwRelativeResult;
}
}
#define RESOLVE_ADDRESS_TO_RELATIVE(INITIAL, INSTR_OFFS, OPCODE_LENGTH) mem::ResolveAddressToRelative(INITIAL, INSTR_OFFS, OPCODE_LENGTH)
+98
View File
@@ -0,0 +1,98 @@
#pragma once
namespace mh
{
__forceinline auto get_minhook_data_for_hook(void* target, void* handler, void** original, uint8_t* buffer)
{
MH_STATUS status;
if ((status = MH_CreateHook(target, handler, original, 0)) != MH_OK)
{
log_info("failed to create minhook request => %i", status);
return false;
}
if ((status = MH_EnableHook(target, buffer)) != MH_OK)
{
log_info("failed to enable minhook request => %i", status);
return false;
}
return true;
}
__forceinline auto stealth_patch_bytes(uintptr_t target, uint8_t* patch, size_t size)
{
if (!hvi::write_virt_memory(win_api::get_current_process_id(), target, patch, size, true))
{
log_info_("stealth_patch_bytes() -> failed to write memory. \n");
return false;
}
return true;
}
//
// just a regular stealth patch.
//
template < typename T >
__forceinline auto stealth_patch(uintptr_t target, void* handler, T* original)
{
uint8_t patch[64];
memset(patch, 0, sizeof(patch));
if (!target)
return false;
if (!get_minhook_data_for_hook(mem::addr(target).Ptr(), handler, (void**)original, patch))
{
log_info_("stealth_patch_api() -> failed to get data from MH engine. \n");
return false;
}
if (!hvi::write_virt_memory(win_api::get_current_process_id(), target, patch, 5, true))
{
log_info_("stealth_patch_api() -> failed to write memory. \n");
return false;
}
return true;
}
//
// this in addition triggers CoW (copy-on-write) so the page gets it's unique physical address.
// that's necessary and very handy for shared DLLs which are mapped to the same physical memory,
// like system DLLs kernel32.dll ntdll.dll etc. we don't want a system wide hook, that'd be fatal.
// access violations, undefined behavior and insane performance loss as well so yeah no don't try that.
//
template < typename T >
__forceinline auto stealth_patch_api(uintptr_t target, void* handler, T* original)
{
uint8_t patch[64];
memset(patch, 0, sizeof(patch));
if (!target)
return false;
if (!hv::trigger_cow(target))
{
//return false;
}
if (!get_minhook_data_for_hook(mem::addr(target).Ptr(), handler, (void**)original, patch))
{
log_info_("stealth_patch_api() -> failed to get data from MH engine. \n");
return false;
}
if (!hvi::write_virt_memory(win_api::get_current_process_id(), target, patch, 5, true))
{
log_info_("stealth_patch_api() -> failed to write memory. \n");
return false;
}
return true;
}
}
+38
View File
@@ -0,0 +1,38 @@
#pragma once
namespace pe
{
template < typename _pt, typename _nth >
__forceinline _pt* get_data_directory_ptr(uintptr_t base, _nth nt_hdr, int index)
{
const auto offset =
nt_hdr->OptionalHeader.DataDirectory[index].VirtualAddress;
return reinterpret_cast<_pt*>((base + offset));
}
template < typename _nth >
__forceinline bool get_data_directory_info(uintptr_t base, _nth nt_hdr, int index, IMAGE_DATA_DIRECTORY& out)
{
out = nt_hdr->OptionalHeader.DataDirectory[index];
return true;
}
extern bool get_headers(void* image, _pimage_dos_header* out_dh, _pimage_nt_header* out_nh);
extern uintptr_t find_export_address(uintptr_t base, _pimage_dos_header dos_hdr, _pimage_nt_header nt_hdr, const char* exp_name);
template < typename T >
__forceinline auto find_export(void* image, const char* name)
{
const auto base = mem::addr(image).Base();
_pimage_dos_header dh = nullptr;
_pimage_nt_header nh = nullptr;
if (!get_headers(image, &dh, &nh))
return T();
return reinterpret_cast<T>(find_export_address(base, dh, nh, name));
}
}
+119
View File
@@ -0,0 +1,119 @@
#include <type_traits>
namespace detail
{
extern "C" void* _spoofer_stub();
template <typename Ret, typename... Args>
static inline auto shellcode_stub_helper(
const void* shell,
Args... args
) -> Ret
{
auto fn = (Ret(*)(Args...))(shell);
return fn(args...);
}
template <std::size_t Argc, typename>
struct argument_remapper
{
// At least 5 params
template<
typename Ret,
typename First,
typename Second,
typename Third,
typename Fourth,
typename... Pack
>
static auto do_call(
const void* shell,
void* shell_param,
First first,
Second second,
Third third,
Fourth fourth,
Pack... pack
) -> Ret
{
return shellcode_stub_helper<
Ret,
First,
Second,
Third,
Fourth,
void*,
void*,
Pack...
>(
shell,
first,
second,
third,
fourth,
shell_param,
nullptr,
pack...
);
}
};
template <std::size_t Argc>
struct argument_remapper<Argc, std::enable_if_t<Argc <= 4>>
{
// 4 or less params
template<
typename Ret,
typename First = void*,
typename Second = void*,
typename Third = void*,
typename Fourth = void*
>
static auto do_call(
const void* shell,
void* shell_param,
First first = First{},
Second second = Second{},
Third third = Third{},
Fourth fourth = Fourth{}
) -> Ret
{
return shellcode_stub_helper<
Ret,
First,
Second,
Third,
Fourth,
void*,
void*
>(
shell,
first,
second,
third,
fourth,
shell_param,
nullptr
);
}
};
}
template <typename Ret, typename... Args>
static inline auto spoof_call(
Ret(*fn)(Args...),
Args... args
) -> Ret
{
struct shell_params
{
const void* trampoline;
void* function;
void* rbx;
};
shell_params p{ (void*)g::return_address_gadget, reinterpret_cast<void*>(fn) };
using mapper = detail::argument_remapper<sizeof...(Args), void>;
return mapper::template do_call<Ret, Args...>((const void*)&detail::_spoofer_stub, &p, args...);
}
+29
View File
@@ -0,0 +1,29 @@
#pragma once
#include "defs.h"
#include "ia32.h"
#include "kernel.h"
#include "lazy_importer.h"
#include "math.h"
#include "xor.h"
#include "assembly.h"
#include "memory.h"
#include "pe.h"
#include "crc.hpp"
#include "winapi.h"
#include "instr.h"
#include "return_spoofer.h"
#include "vfunc.h"
#include "stl.h"
#include "stl_uni.h"
#include "util.h"
#include "syscall.h"
#include "hvi.h"
#include "signature.h"
#include "log.h"
#include "vmt.h"
#include "hv.h"
#include "min_hook.h"
#include "input.h"
#include "jsmn.h"
#include "json.h"
+117
View File
@@ -0,0 +1,117 @@
#pragma once
#define IN_RANGE(x,a,b) (x >= a && x <= b)
#define GET_BITS( x ) (IN_RANGE(x,'0','9') ? (x - '0') : ((x&(~0x20)) - 'A' + 0xa))
#define GET_BYTE( x ) (GET_BITS(x[0]) << 4 | GET_BITS(x[1]))
namespace shared::sig {
inline BYTE GetBits(BYTE x) {
if (IN_RANGE(x, '0', '9'))
{
return x - '0';
}
return ((x & (~0x20)) - 'A' + 0xA);
}
inline BYTE GetByte(PCWSTR x) {
return (GetBits((BYTE)x[0]) << 4 | GetBits((BYTE)x[1]));
}
extern DWORD_PTR FindPattern(const DWORD_PTR baseAddress, const DWORD_PTR length, const PCWSTR pattern);
inline DWORD_PTR FindInImage(const DWORD_PTR imageBaseAddress, const SIZE_T imageSize, const PCWSTR pattern, const DWORD offset = NULL)
{
auto dwResult = FindPattern(imageBaseAddress, imageSize, pattern);
if (offset)
dwResult += offset;
return dwResult;
}
inline DWORD_PTR FindInImageEx(const DWORD_PTR imageBaseAddress, const SIZE_T imageSize, const PCWSTR section, const PCWSTR pattern, const DWORD offset = NULL)
{
auto* const pDosHdr = (PIMAGE_DOS_HEADER)imageBaseAddress;
auto* const pNtHdr = (PIMAGE_NT_HEADERS)(imageBaseAddress + pDosHdr->e_lfanew);
if (pDosHdr->e_magic != IMAGE_DOS_SIGNATURE || pNtHdr->Signature != IMAGE_NT_SIGNATURE)
return 0;
auto* pSecHdr = IMAGE_FIRST_SECTION(pNtHdr);
auto nSecCnt = pNtHdr->FileHeader.NumberOfSections;
for (size_t i = 0; i < nSecCnt; i++)
{
}
auto dwResult = FindPattern(imageBaseAddress, imageSize, pattern);
if (offset)
dwResult += offset;
return dwResult;
}
inline DWORD_PTR FindInImagePtr(const DWORD_PTR imageBaseAddress, const SIZE_T imageSize, const PCWSTR pattern, const DWORD offset,
const DWORD offsetToInstr, const DWORD instrLength)
{
const auto dwInitialAddr = FindInImage(imageBaseAddress, imageSize, pattern, offset);
if (!dwInitialAddr)
return NULL;
return RESOLVE_ADDRESS_TO_RELATIVE(dwInitialAddr, offsetToInstr, instrLength);
}
inline BOOLEAN FindSection(PIMAGE_DOS_HEADER pDosHdr, PIMAGE_NT_HEADERS pNtHdr, IMAGE_SECTION_HEADER* pBuffer, LPCSTR pszName)
{
auto* pSecHdr = IMAGE_FIRST_SECTION(pNtHdr);
const auto nSecCnt = pNtHdr->FileHeader.NumberOfSections;
for (size_t i = 0; i < nSecCnt; i++)
{
const auto& sEntry = pSecHdr[i];
if (!stl::strcmp((PCSTR)sEntry.Name, pszName))
{
memcpy(pBuffer, &sEntry, sizeof(sEntry));
return TRUE;
}
}
return FALSE;
}
inline DWORD_PTR FindInImageEx(const DWORD_PTR imageBaseAddress, const PCSTR section, const PCWSTR pattern, const DWORD offset = NULL)
{
auto* const pDosHdr = (PIMAGE_DOS_HEADER)imageBaseAddress;
auto* const pNtHdr = (PIMAGE_NT_HEADERS)(imageBaseAddress + pDosHdr->e_lfanew);
if (pDosHdr->e_magic != IMAGE_DOS_SIGNATURE || pNtHdr->Signature != IMAGE_NT_SIGNATURE)
return 0;
auto sTargetSection = IMAGE_SECTION_HEADER{};
if (!FindSection(pDosHdr, pNtHdr, &sTargetSection, section))
return 0;
auto dwResult = FindPattern(
imageBaseAddress + sTargetSection.VirtualAddress,
sTargetSection.Misc.VirtualSize,
pattern
);
if (offset)
dwResult += offset;
return dwResult;
}
extern uintptr_t find_offset(uintptr_t start_addr, const uint8_t* pattern_buf, size_t pattern_len, size_t offset, size_t opcode_len) noexcept;
extern DWORD_PTR FindPatternSafe(const DWORD_PTR baseAddress, const DWORD_PTR length, const PCWSTR pattern);
}
+1118
View File
File diff suppressed because it is too large Load Diff
+413
View File
@@ -0,0 +1,413 @@
#pragma once
namespace stl
{
struct out_of_range
{
};
template<class T> class vector
{
public:
/* ----- Constructors ----- */
// Default constructor
vector();
explicit vector(int s);
// Copy constructor
vector(const vector& arg);
// Copy Assingment
vector<T>& operator=(const vector<T>& arg);
// Destructor
~vector();
/*----------------------------*/
/* -------- ITERATORS --------*/
class iterator;
iterator begin();
const iterator begin() const;
iterator end();
const iterator end() const;
const iterator cbegin() const;
const iterator cend() const;
/*----------------------------*/
/* -------- CAPACITY -------- */
bool empty() const;
// Returns size of allocated storate capacity
size_t capacity() const;
// Requests a change in capacity
// reserve() will never decrase the capacity.
void reserve(size_t newmalloc);
// Changes the Vector's size.
// If the newsize is smaller, the last elements will be lost.
// Has a default value param for custom values when resizing.
void resize(size_t newsize, T val = T());
// Returns the size of the Vector (number of elements).
size_t size() const;
// Returns the maximum number of elements the Vector can hold
size_t max_size() const;
// Reduces capcity to fit the size
void shrink_to_fit();
/*----------------------------*/
/* -------- MODIFIERS --------*/
// Removes all elements from the Vector
// Capacity is not changed.
void clear();
// Inserts element at the back
void push_back(const T& d);
// Removes the last element from the Vector
void pop_back();
/*----------------------------*/
/* ----- ELEMENT ACCESS ----- */
// Access elements with bounds checking
T& at(int n);
// Access elements with bounds checking for constant Vectors.
const T& at(int n) const;
// Access elements, no bounds checking
T& operator[](int i);
// Access elements, no bounds checking
const T& operator[](int i) const;
// Returns a reference to the first element
T& front();
// Returns a reference to the first element
const T& front() const;
// Returns a reference to the last element
T& back();
// Returns a reference to the last element
const T& back() const;
// Returns a pointer to the array used by Vector
T* data();
// Returns a pointer to the array used by Vector
const T* data() const;
/*----------------------------*/
private:
size_t _size; // Number of elements in Vector
T* _elements; // Pointer to first element of Vector
size_t _space; // Total space used by Vector including
// elements and free space.
};
template<class T> class vector<T>::iterator
{
public:
iterator(T* p)
:_curr(p)
{}
iterator& operator++()
{
_curr++;
return *this;
}
iterator& operator--()
{
_curr--;
return *this;
}
T& operator*()
{
return *_curr;
}
bool operator==(const iterator& b) const
{
return *_curr == *b._curr;
}
bool operator!=(const iterator& b) const
{
return *_curr != *b._curr;
}
private:
T* _curr;
};
// Constructors/Destructor
template<class T>
vector<T>::vector()
:_size(0), _elements(0), _space(0)
{}
template<class T>
inline vector<T>::vector(int s)
: _size(s), _elements(new T[s]), _space(s)
{
for (int index = 0; index < _size; ++index)
_elements[index] = T();
}
template<class T>
inline vector<T>::vector(const vector& arg)
:_size(arg._size), _elements(new T[arg._size])
{
for (int index = 0; index < arg._size; ++index)
_elements[index] = arg._elements[index];
}
template<class T>
inline vector<T>& vector<T>::operator=(const vector<T>& a)
{
if (this == &a) return *this; // Self-assingment not work needed
// Current Vector has enough space, so there is no need for new allocation
if (a._size <= _space)
{
for (int index = 0; index < a._size; ++index)
{
_elements[index] = a._elements[index];
_size = a._size;
return *this;
}
}
T* p = new T[a._size];
for (int index = 0; index < a._size; ++index)
p[index] = a._elements[index];
delete[] _elements;
_size = a._size;
_space = a._size;
_elements = p;
return *this;
}
template<class T>
vector<T>::~vector()
{
delete[] _elements;
}
// Iterators
template<class T>
inline typename vector<T>::iterator vector<T>::begin()
{
return vector<T>::iterator(&_elements[0]);
}
template<class T>
inline typename const vector<T>::iterator vector<T>::begin() const
{
return vector<T>::iterator(&_elements[0]);
}
template<class T>
inline typename vector<T>::iterator vector<T>::end()
{
return vector<T>::iterator(&_elements[_size]);
}
template<class T>
inline typename const vector<T>::iterator vector<T>::end() const
{
return vector<T>::iterator(&_elements[_size]);
}
template<class T>
inline typename const vector<T>::iterator vector<T>::cbegin() const
{
return vector<T>::iterator(&_elements[0]);
}
template<class T>
inline typename const vector<T>::iterator vector<T>::cend() const
{
return vector<T>::iterator(&_elements[_size]);
}
// Capacity
template<class T>
inline bool vector<T>::empty() const
{
return (_size == 0);
}
template<class T>
inline size_t vector<T>::capacity() const
{
return _space;
}
template<class T>
inline void vector<T>::reserve(size_t newalloc)
{
if (newalloc <= _space) return;
T* p = new T[newalloc];
for (int i = 0; i < _size; ++i)
p[i] = _elements[i];
delete[] _elements;
_elements = p;
_space = newalloc;
}
template<class T>
inline void vector<T>::resize(size_t newsize, T val)
{
reserve(newsize);
for (auto index = _size; index < newsize; ++index)
_elements[index] = T();
_size = newsize;
}
template<class T>
inline size_t vector<T>::size() const
{
return _size;
}
// Modifiers
template<class T>
inline void vector<T>::push_back(const T& d)
{
if (_space == 0)
reserve(8);
else if (_size == _space)
reserve(2 * _space);
_elements[_size] = d;
++_size;
}
// Accessors
template<class T>
inline T& vector<T>::at(int n)
{
if (n < 0 || _size <= n) throw out_of_range();
return _elements[n];
}
template<class T>
inline const T& vector<T>::at(int n) const
{
if (n < 0 || _size <= n) throw out_of_range();
return _elements[n];
}
template<class T>
inline T& vector<T>::operator[](int i)
{
return _elements[i];
}
template<class T>
inline const T& vector<T>::operator[](int i) const
{
return _elements[i];
}
template<class T>
inline T& vector<T>::front()
{
return _elements[0];
}
template<class T>
inline const T& vector<T>::front() const
{
return _elements[0];
}
template<class T>
inline T& vector<T>::back()
{
return _elements[_size - 1];
}
template<class T>
inline const T& vector<T>::back() const
{
return _elements[_size - 1];
}
template<class T>
inline T* vector<T>::data()
{
return _elements;
}
template<class T>
inline const T* vector<T>::data() const
{
return _elements;
}
}
+58
View File
@@ -0,0 +1,58 @@
#pragma once
#pragma warning(push)
#pragma warning(disable : 4244 4066 4309 4305 4244)
namespace stl
{
inline_block char wtoc(wchar_t w)
{
if (w == L'Ё') return 'Ё';
if (w == L'ё') return 'ё';
if (w >= L'А' && w <= L'Я') return w - L'А' + 'А';
if (w >= L'а' && w <= L'я') return w - L'а' + 'а';
return (char)w;
}
inline_block wchar_t ctow(char w)
{
if (w == 'Ё') return L'Ё';
if (w == 'ё') return L'ё';
if (w >= 'А' && w <= 'Я') return w - 'А' + L'А';
if (w >= 'а' && w <= 'я') return w - 'а' + L'а';
return w;
}
inline_block int mbstowcs(wchar_t* Dest, const char* Source, unsigned __int64 Length, unsigned __int64 MaxCount)
{
int result = -1;
if (!Dest)
return 0;
if (Dest && !MaxCount)
return 0;
if (MaxCount > 0x7FFFFFFF)
return -1;
if (!Length)
{
Length = strlen(Source);
if (!Length)
return -1;
}
for (result = 0; (result < Length && result < MaxCount); result++)
{
Dest[result] = ctow(Source[result]);
}
return result;
}
}
#pragma warning(pop)
+6
View File
@@ -0,0 +1,6 @@
#pragma once
namespace sc
{
extern UINT32 find_id_by_name(LPCSTR pszName);
}
+296
View File
@@ -0,0 +1,296 @@
#pragma once
namespace util
{
inline unsigned int mmh_32(const void* key, int len, unsigned int seed)
{
const unsigned int m = 0x5bd1e995;
const int r = 24;
unsigned int h = seed ^ len;
const unsigned char* data = (const unsigned char*)key;
while (len >= 4)
{
unsigned int k = *(unsigned int*)data;
k *= m;
k ^= k >> r;
k *= m;
h *= m;
h ^= k;
data += 4;
len -= 4;
}
switch (len)
{
case 3: h ^= data[2] << 16;
case 2: h ^= data[1] << 8;
case 1: h ^= data[0];
h *= m;
};
h ^= h >> 13;
h *= m;
h ^= h >> 15;
return h;
}
inline int string_hash(const char* text, size_t length)
{
return mmh_32((void*)text, static_cast<int>(length), 6);
}
template < typename T >
inline auto find_export(const char* mod, const char* proc)
{
auto handle = LI_FN(GetModuleHandleA)(mod);
return (T)LI_FN(GetProcAddress)(handle, proc);
}
template < typename T >
inline auto find_export(_hmodule mod, const char* proc)
{
return (T)LI_FN(GetProcAddress)(mod, proc);
}
__forceinline void* get_vtable_func(void* class_base, size_t index)
{
if (!class_base || index < 0)
return nullptr;
auto** const class_vtable = *(void***)class_base;
if (class_vtable == nullptr)
return nullptr;
return class_vtable[index];
}
__forceinline auto protect_virtual_memory(void* address, size_t length, u_long prot, u_long* prot_old = nullptr)
{
u_long unused_0{};
u_long* prot_old_act = (!(prot_old == nullptr) ? prot_old : &unused_0);
return win_api::virtual_protect(address, length, prot, prot_old_act);
}
__forceinline auto file_header(void* pc) -> void*
{
void* result = nullptr;
if (!win_api::pc_to_file_header(pc, &result))
return nullptr;
return result;
}
template <typename... T>
__forceinline void format_string(char* buffer, size_t length, const char* fmt, T&&... args)
{
LI_FN(wsprintfA).cached()(buffer, fmt, args...);
}
template <typename... T>
__forceinline void format_wstring(wchar_t* buffer, size_t length, const wchar_t* fmt, T&&... args)
{
LI_FN(wsprintfW).cached()(buffer, fmt, args...);
}
__forceinline bool is_valid_address(void* p)
{
auto region_info = MEMORY_BASIC_INFORMATION{};
if (!win_api::rebuilt::virtual_query(p, &region_info, sizeof(region_info)))
return false;
if (region_info.Protect == PAGE_GUARD)
return false;
return true;
}
__forceinline bool read_memory(void* dst, uintptr_t src, size_t len)
{
size_t processed = 0;
const auto result = win_api::read_process_memory(
win_api::get_current_process(),
(LPCVOID)src,
dst,
len,
&processed
);
if (!result && win_api::get_last_error() != ERROR_PARTIAL_COPY)
return false;
return true;
}
__forceinline bool write_data(const char* data, const wchar_t* filename)
{
HANDLE hFile;
SIZE_T dwBytesToWrite = stl::strlen(data);
DWORD dwBytesWritten;
BOOL bErrorFlag = FALSE;
hFile = LI_FN(CreateFileW).cached()(filename, // name of the write
FILE_APPEND_DATA, // open for appending
FILE_SHARE_READ, // share for reading only
NULL, // default security
OPEN_ALWAYS, // open existing file or create new file
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. template
if (hFile == INVALID_HANDLE_VALUE)
return false;
while (dwBytesToWrite > 0)
{
bErrorFlag = LI_FN(WriteFile).cached()(
hFile, // open file handle
data, // start of data to write
dwBytesToWrite, // number of bytes to write
&dwBytesWritten, // number of bytes that were written
NULL); // no overlapped structure
if (!bErrorFlag)
break;
data += dwBytesWritten;
dwBytesToWrite -= dwBytesWritten;
}
LI_FN(CloseHandle).cached()(hFile);
return true;
}
__forceinline bool write_data_reg(const char* data, size_t length, const char* filename)
{
HANDLE hFile;
SIZE_T dwBytesToWrite = length;
DWORD dwBytesWritten;
BOOL bErrorFlag = FALSE;
hFile = LI_FN(CreateFileA).cached()(filename, // name of the write
FILE_APPEND_DATA, // open for appending
FILE_SHARE_READ, // share for reading only
NULL, // default security
OPEN_ALWAYS, // open existing file or create new file
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. template
if (hFile == INVALID_HANDLE_VALUE)
return false;
while (dwBytesToWrite > 0)
{
bErrorFlag = LI_FN(WriteFile).cached()(
hFile, // open file handle
data, // start of data to write
dwBytesToWrite, // number of bytes to write
&dwBytesWritten, // number of bytes that were written
NULL); // no overlapped structure
if (!bErrorFlag)
break;
data += dwBytesWritten;
dwBytesToWrite -= dwBytesWritten;
}
LI_FN(CloseHandle).cached()(hFile);
return true;
}
inline BOOL file_exists(LPCSTR szPath)
{
DWORD dwAttrib = LI_FN(GetFileAttributesA).cached()(szPath);
return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
!(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}
inline BOOL file_exists_wide(LPCWSTR szPath)
{
DWORD dwAttrib = LI_FN(GetFileAttributesW).cached()(szPath);
return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
!(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}
inline BOOL read_file(LPCSTR pszPath, PVOID pBuffer, DWORD uLength)
{
HANDLE hFile = LI_FN(CreateFileA).cached()(pszPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile)
{
BOOL bResult = LI_FN(ReadFile).cached()(hFile, pBuffer, uLength, &uLength, nullptr);
LI_FN(CloseHandle).cached()(hFile);
if (bResult)
{
((PCHAR)pBuffer)[uLength] = '\0';
}
return bResult;
}
return FALSE;
}
extern BOOL read_file_ex(LPCWSTR pszPath, PVOID pBuffer, DWORD uLength);
extern PVOID get_file_ptr(LPCWSTR pszPath);
inline DWORD get_file_size(LPCSTR pszPath)
{
HANDLE hFile = LI_FN(CreateFileA).cached()(pszPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile)
{
DWORD dwResult = LI_FN(GetFileSize).cached()(hFile, nullptr);
LI_FN(CloseHandle).cached()(hFile);
return dwResult;
}
return 0;
}
inline DWORD get_file_size_wide(LPCWSTR pszPath)
{
HANDLE hFile = LI_FN(CreateFileW).cached()(pszPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile)
{
DWORD dwResult = LI_FN(GetFileSize).cached()(hFile, nullptr);
LI_FN(CloseHandle).cached()(hFile);
return dwResult;
}
return 0;
}
inline bool get_desktop_directory(char* buffer, size_t length)
{
if (!buffer || !length)
return false;
if (!LI_FN(SHGetSpecialFolderPathA).cached()(HWND_DESKTOP, buffer, CSIDL_DESKTOP, FALSE))
return false;
return true;
}
}
+16
View File
@@ -0,0 +1,16 @@
#pragma once
namespace vfunc
{
template <size_t Index, typename ReturnType, typename... Args>
__forceinline ReturnType call(void* instance, Args... args)
{
using Fn = ReturnType(__thiscall*)(void*, Args...);
auto function = (*reinterpret_cast<Fn**>(instance))[Index];
return spoof_call(function, instance, args...);
}
}
#define VIRTUAL_FUNC(NAME, RETURN_VALUE, INDEX, ARGS, ...) RETURN_VALUE NAME ARGS { return vfunc::call<INDEX, RETURN_VALUE>(__VA_ARGS__); }
+69
View File
@@ -0,0 +1,69 @@
#pragma once
namespace detail
{
class protect_guard
{
public:
protect_guard(void* base, size_t len, uint32_t flags)
{
_base = base;
_length = len;
if (!win_api::virtual_protect(base, len, flags, reinterpret_cast<PDWORD>(&_old)))
{
log_info_("failed to protect virtual memory.");
EXIT_PROCESS(NULL);
}
}
~protect_guard()
{
win_api::virtual_protect(_base, _length, _old, reinterpret_cast<PDWORD>(&_old));
}
private:
void* _base;
size_t _length;
uint32_t _old{};
};
}
class c_vfunc_hook
{
public:
bool setup(void* base);
size_t estimate_vftbl_length(std::uintptr_t* vftbl_start);
template<typename T>
void hook_index(const int index, T fun)
{
new_vftb1[index + 1] = reinterpret_cast<std::uintptr_t>(fun);
}
void unhook_index(const int index) const
{
new_vftb1[index] = old_vftbl[index];
}
void unhook_all()
{
if (old_vftbl != nullptr) {
auto guard = detail::protect_guard{ class_base, sizeof(uintptr_t), PAGE_READWRITE };
*static_cast<uintptr_t**>(class_base) = old_vftbl;
old_vftbl = nullptr;
}
}
template<typename T>
T get_original(const int index)
{
return reinterpret_cast<T>(old_vftbl[index]);
}
private:
void* class_base;
size_t vftbl_len;
uintptr_t* new_vftb1;
uintptr_t* old_vftbl;
LPCVOID search_base = nullptr;
bool wasAllocated = false;
};
+179
View File
@@ -0,0 +1,179 @@
#pragma once
#define FIND_EXPORT(MOD, EXP, TYPE) win_api::find_export<TYPE>(_XS(MOD), _XS(EXP))
#define DECLARE_FUNC(MOD, EXP, TYPE, ID) if(!table[ID]) table[ID] = FIND_EXPORT(MOD, EXP, TYPE); \
auto* const fn = (TYPE*)table[ID]
namespace win_api
{
#pragma data_seg("data")
__declspec(allocate("data")) inline void* table[8192];
#pragma data_seg()
template < typename T >
T* find_export(const char* mod_name, const char* exp_name)
{
auto mod_handle = LI_FN(GetModuleHandleA)(mod_name);
if (mod_handle == nullptr)
return nullptr;
return pe::find_export<T*>(mod_handle, exp_name);
}
inline_block auto get_last_error() -> DWORD
{
return *(DWORD*)(__readgsqword(0x30u) + 104);
}
inline_block auto get_current_process() -> HANDLE
{
return (HANDLE)-1;
}
inline_block auto get_current_thread() -> HANDLE
{
return (HANDLE)-2;
}
inline_block auto get_current_process_id() -> u_long
{
return *(DWORD*)(__readgsqword(0x30u) + 64);
}
inline_block auto get_process_heap() -> HANDLE
{
return *(HANDLE*)(__readgsqword(0x60u) + 48);
}
inline_block auto get_module_handle(const char* name) -> HMODULE
{
DECLARE_FUNC("kernel32.dll", "GetModuleHandleA", decltype(get_module_handle), __COUNTER__);
return fn(name);
}
inline_block auto get_module_handle_wide(const wchar_t* name) -> HMODULE
{
DECLARE_FUNC("kernel32.dll", "GetModuleHandleA", decltype(get_module_handle_wide), __COUNTER__);
return fn(name);
}
inline_block auto virtual_alloc(
void* address, size_t size,
u_long alloc_type, u_long protect
) -> void*
{
DECLARE_FUNC("kernel32.dll", "VirtualAlloc", decltype(virtual_alloc), __COUNTER__);
return fn(
address, size,
alloc_type, protect
);
}
inline_block auto virtual_query(const void* address, PMEMORY_BASIC_INFORMATION buffer, size_t size) -> size_t
{
DECLARE_FUNC("kernel32.dll", "VirtualQuery", decltype(virtual_query), __COUNTER__);
return fn(address, buffer, size);
}
inline_block auto virtual_free(void* address, size_t size, u_long free_type) -> int
{
DECLARE_FUNC("kernel32.dll", "VirtualFree", decltype(virtual_free), __COUNTER__);
return fn(address, size, free_type);
}
inline_block auto read_process_memory(_handle process, const void* base_address, void* buffer, size_t size, size_t* cnt) -> BOOL
{
DECLARE_FUNC("kernel32.dll", "ReadProcessMemory", decltype(read_process_memory), __COUNTER__);
return fn(process, base_address, buffer, size, cnt);
}
inline_block auto output_debug_string(const char* text) -> void
{
DECLARE_FUNC("kernel32.dll", "OutputDebugStringA", decltype(output_debug_string), __COUNTER__);
return fn(text);
}
inline_block auto suspend_thread(HANDLE handle) -> DWORD
{
DECLARE_FUNC("kernel32.dll", "SuspendThread", decltype(suspend_thread), __COUNTER__);
return fn(handle);
}
inline_block auto heap_create(DWORD options, SIZE_T initial_size, SIZE_T maximum_size) -> HANDLE
{
DECLARE_FUNC("kernel32.dll", "HeapCreate", decltype(heap_create), __COUNTER__);
return fn(options, initial_size, maximum_size);
}
inline_block auto heap_destroy(HANDLE handle) -> BOOL
{
DECLARE_FUNC("kernel32.dll", "HeapDestroy", decltype(heap_destroy), __COUNTER__);
return fn(handle);
}
inline_block auto pc_to_file_header(PVOID value, PVOID* base_of_image) -> PVOID
{
DECLARE_FUNC("kernel32.dll", "RtlPcToFileHeader", decltype(pc_to_file_header), __COUNTER__);
return fn(value, base_of_image);
}
inline_block auto heap_alloc(HANDLE handle, DWORD flags, SIZE_T size) -> PVOID
{
DECLARE_FUNC("ntdll.dll", "RtlAllocateHeap", decltype(heap_alloc), __COUNTER__);
return fn(handle, flags, size);
}
inline_block auto heap_re_alloc(HANDLE handle, DWORD flags, PVOID ptr, SIZE_T size) -> PVOID
{
DECLARE_FUNC("ntdll.dll", "RtlReAllocateHeap", decltype(heap_re_alloc), __COUNTER__);
return fn(handle, flags, ptr, size);
}
extern bool virtual_protect(void* address, size_t size, u_long new_protect, u_long* old_protect);
namespace rebuilt
{
inline_block auto virtual_alloc(void* address, size_t size, u_long alloc_type, u_long protect) -> void*
{
if (!NT_SUCCESS(sc_asm_alloc_virtual_memory(get_current_process(), &address, 0, &size, alloc_type, protect)))
return nullptr;
return address;
}
inline_block auto virtual_query(const void* address, PMEMORY_BASIC_INFORMATION info_buffer, size_t length) -> size_t
{
if (!NT_SUCCESS(sc_asm_query_virtual_memory(get_current_process(), (void*)address, k::MemoryBasicInformation, info_buffer, length, &length)))
return 0;
return length;
}
inline_block auto get_thread_context(_handle thread, PCONTEXT context) -> bool
{
return NT_SUCCESS(sc_asm_get_context_thread(thread, context));
}
inline_block auto sleep(int miliseconds)
{
LARGE_INTEGER delay;
delay.QuadPart = -(miliseconds * 10000);
sc_asm_delay_execution(FALSE, &delay);
}
}
}
+120
View File
@@ -0,0 +1,120 @@
#pragma once
#pragma warning(disable : 4244)
// =============================================================================
namespace crypt
{
// =============================================================================
// convert __TIME__ == "hh:mm:ss" to a sum of seconds this gives us a compile-time seed
// Note: in some weird cases I've seen the seed being different from encryption
// to decryption so it's safer to not use time and set the seed manually
#if 0
#define TBX_XSTR_SEED ((__TIME__[7] - '0') * 1ull + (__TIME__[6] - '0') * 10ull + \
(__TIME__[4] - '0') * 60ull + (__TIME__[3] - '0') * 600ull + \
(__TIME__[1] - '0') * 3600ull + (__TIME__[0] - '0') * 36000ull)
#else
#define TBX_XSTR_SEED (3600ull)
#endif
// -----------------------------------------------------------------------------
// @return a pseudo random number clamped at 0xFFFFFFFF
constexpr unsigned long long linear_congruent_generator(unsigned rounds)
{
return 1013904223ull + (1664525ull * ((rounds > 0) ? linear_congruent_generator(rounds - 1) : (TBX_XSTR_SEED)))
% 0xFFFFFFFF;
}
// -----------------------------------------------------------------------------
#define Random() linear_congruent_generator(10)
#define XSTR_RANDOM_NUMBER(Min, Max) (Min + (Random() % (Max - Min + 1)))
// -----------------------------------------------------------------------------
constexpr const unsigned long long XORKEY = XSTR_RANDOM_NUMBER(0, 0xFF);
// -----------------------------------------------------------------------------
template <typename Char>
constexpr Char encrypt_character(const Char character, int index)
{
return character ^ (static_cast<Char>(XORKEY) + index);
}
// -----------------------------------------------------------------------------
template <unsigned size, typename Char>
class Xor_string
{
public:
const unsigned _nb_chars = (size - 1);
Char _string[size];
// if every goes alright this constructor should be executed at compile time
constexpr Xor_string(const Char* string)
: _string{}
{
for (unsigned i = 0u; i < size; ++i)
_string[i] = encrypt_character<Char>(string[i], i);
}
// This is executed at runtime.
// HACK: although decrypt() is const we modify '_string' in place
const Char* decrypt() const
{
Char* string = const_cast<Char*>(_string);
for (unsigned t = 0; t < _nb_chars; t++)
{
string[t] = string[t] ^ (static_cast<Char>(XORKEY) + t);
}
string[_nb_chars] = '\0';
return string;
}
};
template <unsigned size, typename uint64_t>
class Xor_Addr
{
public:
const unsigned _nb_chars = (size - 1);
uint64_t _addr;
// if every goes alright this constructor should be executed at compile time
constexpr Xor_Addr(const uint64_t addr)
: _addr{}
{
_addr = (addr ^ XORKEY);
}
// This is executed at runtime.
// HACK: although decrypt() is const we modify '_string' in place
const uint64_t decrypt() const
{
return (_addr ^ XORKEY);
}
};
} // END crypt NAMESPACE ========================================================
#define XOR_S(name, my_string) constexpr crypt::Xor_string<(sizeof(my_string)/sizeof(char)), char> name(my_string)
// Because of a limitation/bug in msvc 2017 we need to declare crypt::Xor_string() as a constexpr
// otherwise the constructor is not evaluated at compile time. The lambda function is here to allow this declaration inside the macro
// because there is no such thing as casting to 'constexpr' (and casting to const does not solve this bug).
#define _XS(my_string) []()[[msvc::forceinline]]{ constexpr crypt::Xor_string<(sizeof(my_string)/sizeof(char)), char> expr(my_string); return expr; }().decrypt()
#define _XA(my_addr)[]{ constexpr crypt::Xor_Addr<(sizeof(my_addr)/sizeof(uint64_t)), uint64_t> expr(my_addr); return expr; }().decrypt()
// Crypt normal string char*
#define XOR_C( string ) XorString( string )
#define XOR_WS(name, my_string) constexpr crypt::Xor_string<(sizeof(my_string)/sizeof(wchar_t)), wchar_t> name(my_string)
#define _XSW(my_string) []()[[msvc::forceinline]]{ constexpr crypt::Xor_string<(sizeof(my_string)/sizeof(wchar_t)), wchar_t> expr(my_string); return expr; }().decrypt()
// crypt wide characters
#define XOR_W( string ) XorWideString( string )
#define XOR_STD_STRING(X) XOR_STRING(X)
constexpr uint64_t __xor_constant_key = 0xF2E1062D448B;
#define _XC(X) (X ^ __xor_constant_key)
+11
View File
@@ -0,0 +1,11 @@
#pragma once
namespace window
{
class c_info_panel : public c_base
{
public:
void paint() override;
private:
};
}
+53
View File
@@ -0,0 +1,53 @@
#pragma once
#define SECTION_START() __noop();
#define SECTION_END() __nop();
#define SECTION_INIT(NAME) float section_push = 0.0f; \
const float section_start_x = position.x + 5.0f, section_start_y = position.y + 55.0f + yaw_push; \
static float section_height = 0.0f; \
ui::section({ section_start_x, section_start_y }, { (dimension.w / 2.f) - 10.f, section_height + 10.0f }, { 65, 65, 65 }, _XS(NAME)); \
const float section_rstart_x = section_start_x + 5.0f, \
section_rstart_y = section_start_y + 10.0f; \
#define SECTION_INIT_EX(NAME, WIDTH) float section_push = 0.0f; \
const float section_start_x = start_x, section_start_y = start_y + yaw_push; \
static float section_height = 0.0f; \
ui::section({ section_start_x, section_start_y }, { WIDTH, section_height + 10.0f }, { 65, 65, 65 }, _XS(NAME)); \
const float section_rstart_x = section_start_x + 5.0f, \
section_rstart_y = section_start_y + 10.0f; \
#define MENU_TAB_ARGS const math::position_t<int>& position, const math::dimension_t<int>& dimension, const float& start_x, const float& start_y, float& yaw_push
namespace window
{
namespace menu::tabs
{
extern void other_left(MENU_TAB_ARGS);
extern void other_right(MENU_TAB_ARGS);
extern void config_left(MENU_TAB_ARGS);
extern void config_right(MENU_TAB_ARGS);
extern void aim_left(MENU_TAB_ARGS);
extern void aim_right(MENU_TAB_ARGS);
extern void visual_left(MENU_TAB_ARGS);
extern void visual_right(MENU_TAB_ARGS);
}
class c_menu : public c_base
{
public:
void paint() override;
void draw_base();
void draw_tab_selection();
void draw_tab_right();
void render();
private:
int m_tab;
bool m_visible;
};
}
+16
View File
@@ -0,0 +1,16 @@
#pragma once
namespace window
{
class c_radar : public c_base
{
public:
void draw_base();
void draw_objects();
void paint() override;
private:
float m_radius;
float m_range;
};
}
+11
View File
@@ -0,0 +1,11 @@
#pragma once
namespace window
{
class c_spectator_list : public c_base
{
public:
void paint() override;
private:
};
}
+15
View File
@@ -0,0 +1,15 @@
#pragma once
namespace ui
{
extern bool in_range(const math::position_t<float>& _position, const math::dimension_t<float>& _dimension);
extern void section(const math::position_t<float>& _position, const math::dimension_t<float>& _dimension, respawn::color_t color, const char* name);
extern void checkbox(const math::position_t<float> _position, const char* text, bool* variable);
extern void checkbox_triple(const math::position_t<float> _position, const char* text, int* variable);
extern void slider(math::position_t<float> _position, math::dimension_t<float> _dimension, const char* text, int* variable, int min, int max);
extern void slider_float(math::position_t<float> _position, math::dimension_t<float> _dimension, const char* text, float* variable, float min, float max);
extern bool button(
const math::position_t<float>& _position, const math::dimension_t<float>& _dimension,
respawn::color_t background_color, respawn::color_t text_color, const char* text
);
}
+95
View File
@@ -0,0 +1,95 @@
#pragma once
namespace window
{
namespace fl
{
constexpr char invalid = 1 << 0;
constexpr char none = 1 << 1;
constexpr char draggable = 1 << 3;
constexpr char dragging = 1 << 4;
}
class c_base
{
public:
void declare(const math::position_t<int>& pos, const math::dimension_t<int>& dim)
{
m_position = pos;
m_dimension = dim;
}
virtual void paint() { __noop(); };
auto& _position() { return m_position; }
auto& _dimension() { return m_dimension; }
const auto has_flag(int f) noexcept { return (m_flags & f); }
auto set_flag(int f, bool s) noexcept
{
if (s == true)
m_flags |= f;
else
m_flags &= ~f;
}
protected:
int32_t m_flags;
math::position_t<int> m_position;
math::dimension_t<int> m_dimension;
private:
};
class c_manager
{
public:
template <typename _t>
[[nodiscard]] bool in_range(const math::position_t<int> cursor_position,
const std::pair<math::position_t<_t>, math::dimension_t<_t>> target_position) const
{
const auto x0 = static_cast<int>(target_position.first.x), y0 = static_cast<int>(target_position.first.y);
const auto x1 = x0 + static_cast<int>(target_position.second.w), y1 = y0 + static_cast<int>(target_position
.second.h);
if (cursor_position.x < x0 || cursor_position.x > x1)
{
return false;
}
if (cursor_position.y < y0 || cursor_position.y > y1)
{
return false;
}
return true;
}
void paint();
template < typename T >
void add(const math::position_t<int>& pos, const math::dimension_t<int>& dim)
{
T* wnd = new T();
if (wnd == nullptr)
{
log_info_("failed to allocate/construct a window.");
return;
}
wnd->declare(pos, dim);
m_list.insert(wnd);
}
private:
stl::c_linked_list<c_base*> m_list;
};
}
#include "ui.h"
#include "menu.h"
#include "info_panel.h"
#include "radar.h"
#include "spectator_list.h"
+24
View File
@@ -0,0 +1,24 @@
#include <include.h>
extern "C"
{
LONG first_call = FALSE;
void entry_point()
{
//
// Due to the design of our mapper, this part of the code
// Can be called several times instead of just once.
//
// It's our job to ensure we only ever execute this once.
// Because initializing, as the name suggests, only needs to be done one time.
//
if (InterlockedCompareExchange(&first_call, TRUE, 0))
return;
log_info_("received initialization request.");
r5::initialize();
}
}
+313
View File
@@ -0,0 +1,313 @@
/*
* MinHook - The Minimalistic API Hooking Library for x64/x86
* Copyright (C) 2009-2017 Tsuda Kageyu.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <include.h>
// Size of each memory block. (= page size of VirtualAlloc)
namespace mh
{
#define MEMORY_BLOCK_SIZE 0x1000
// Max range for seeking a memory block. (= 1024MB)
#define MAX_MEMORY_RANGE 0x40000000
// Memory protection flags to check the executable address.
#define PAGE_EXECUTE_FLAGS \
(PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY)
// Memory slot.
typedef struct _MEMORY_SLOT
{
union
{
struct _MEMORY_SLOT* pNext;
UINT8 buffer[MEMORY_SLOT_SIZE];
};
} MEMORY_SLOT, * PMEMORY_SLOT;
// Memory block info. Placed at the head of each block.
typedef struct _MEMORY_BLOCK
{
struct _MEMORY_BLOCK* pNext;
PMEMORY_SLOT pFree; // First element of the free slot list.
UINT usedCount;
} MEMORY_BLOCK, * PMEMORY_BLOCK;
//-------------------------------------------------------------------------
// Global Variables:
//-------------------------------------------------------------------------
// First element of the memory block list.
PMEMORY_BLOCK g_pMemoryBlocks;
//-------------------------------------------------------------------------
VOID InitializeBuffer(VOID)
{
// Nothing to do for now.
}
//-------------------------------------------------------------------------
VOID UninitializeBuffer(VOID)
{
PMEMORY_BLOCK pBlock = g_pMemoryBlocks;
g_pMemoryBlocks = NULL;
while (pBlock)
{
PMEMORY_BLOCK pNext = pBlock->pNext;
win_api::virtual_free(pBlock, 0, MEM_RELEASE);
pBlock = pNext;
}
}
//-------------------------------------------------------------------------
#if defined(_M_X64) || defined(__x86_64__)
static LPVOID FindPrevFreeRegion(LPVOID pAddress, LPVOID pMinAddr, DWORD dwAllocationGranularity)
{
ULONG_PTR tryAddr = (ULONG_PTR)pAddress;
// Round down to the allocation granularity.
tryAddr -= tryAddr % dwAllocationGranularity;
// Start from the previous allocation granularity multiply.
tryAddr -= dwAllocationGranularity;
while (tryAddr >= (ULONG_PTR)pMinAddr)
{
MEMORY_BASIC_INFORMATION mbi;
if (win_api::rebuilt::virtual_query((LPVOID)tryAddr, &mbi, sizeof(mbi)) == 0)
break;
if (mbi.State == MEM_FREE)
return (LPVOID)tryAddr;
if ((ULONG_PTR)mbi.AllocationBase < dwAllocationGranularity)
break;
tryAddr = (ULONG_PTR)mbi.AllocationBase - dwAllocationGranularity;
}
return NULL;
}
#endif
//-------------------------------------------------------------------------
#if defined(_M_X64) || defined(__x86_64__)
static LPVOID FindNextFreeRegion(LPVOID pAddress, LPVOID pMaxAddr, DWORD dwAllocationGranularity)
{
ULONG_PTR tryAddr = (ULONG_PTR)pAddress;
// Round down to the allocation granularity.
tryAddr -= tryAddr % dwAllocationGranularity;
// Start from the next allocation granularity multiply.
tryAddr += dwAllocationGranularity;
while (tryAddr <= (ULONG_PTR)pMaxAddr)
{
MEMORY_BASIC_INFORMATION mbi;
if (win_api::rebuilt::virtual_query((LPVOID)tryAddr, &mbi, sizeof(mbi)) == 0)
break;
if (mbi.State == MEM_FREE)
return (LPVOID)tryAddr;
tryAddr = (ULONG_PTR)mbi.BaseAddress + mbi.RegionSize;
// Round up to the next allocation granularity.
tryAddr += dwAllocationGranularity - 1;
tryAddr -= tryAddr % dwAllocationGranularity;
}
return NULL;
}
#endif
//-------------------------------------------------------------------------
static PMEMORY_BLOCK GetMemoryBlock(LPVOID pOrigin)
{
PMEMORY_BLOCK pBlock;
#if defined(_M_X64) || defined(__x86_64__)
ULONG_PTR minAddr;
ULONG_PTR maxAddr;
SYSTEM_INFO si;
LI_FN(GetSystemInfo)(&si);
minAddr = (ULONG_PTR)si.lpMinimumApplicationAddress;
maxAddr = (ULONG_PTR)si.lpMaximumApplicationAddress;
// pOrigin ± 512MB
if ((ULONG_PTR)pOrigin > MAX_MEMORY_RANGE && minAddr < (ULONG_PTR)pOrigin - MAX_MEMORY_RANGE)
minAddr = (ULONG_PTR)pOrigin - MAX_MEMORY_RANGE;
if (maxAddr > (ULONG_PTR)pOrigin + MAX_MEMORY_RANGE)
maxAddr = (ULONG_PTR)pOrigin + MAX_MEMORY_RANGE;
// Make room for MEMORY_BLOCK_SIZE bytes.
maxAddr -= MEMORY_BLOCK_SIZE - 1;
#endif
// Look the registered blocks for a reachable one.
for (pBlock = g_pMemoryBlocks; pBlock != NULL; pBlock = pBlock->pNext)
{
#if defined(_M_X64) || defined(__x86_64__)
// Ignore the blocks too far.
if ((ULONG_PTR)pBlock < minAddr || (ULONG_PTR)pBlock >= maxAddr)
continue;
#endif
// The block has at least one unused slot.
if (pBlock->pFree != NULL)
return pBlock;
}
#if defined(_M_X64) || defined(__x86_64__)
// Alloc a new block above if not found.
{
LPVOID pAlloc = pOrigin;
while ((ULONG_PTR)pAlloc >= minAddr)
{
pAlloc = FindPrevFreeRegion(pAlloc, (LPVOID)minAddr, si.dwAllocationGranularity);
if (pAlloc == NULL)
break;
pBlock = (PMEMORY_BLOCK)win_api::rebuilt::virtual_alloc(
pAlloc, MEMORY_BLOCK_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (pBlock != NULL)
break;
}
}
// Alloc a new block below if not found.
if (pBlock == NULL)
{
LPVOID pAlloc = pOrigin;
while ((ULONG_PTR)pAlloc <= maxAddr)
{
pAlloc = FindNextFreeRegion(pAlloc, (LPVOID)maxAddr, si.dwAllocationGranularity);
if (pAlloc == NULL)
break;
pBlock = (PMEMORY_BLOCK)win_api::rebuilt::virtual_alloc(
pAlloc, MEMORY_BLOCK_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if (pBlock != NULL)
break;
}
}
#else
// In x86 mode, a memory block can be placed anywhere.
pBlock = (PMEMORY_BLOCK)VirtualAlloc(
NULL, MEMORY_BLOCK_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
#endif
if (pBlock != NULL)
{
// Build a linked list of all the slots.
PMEMORY_SLOT pSlot = (PMEMORY_SLOT)pBlock + 1;
pBlock->pFree = NULL;
pBlock->usedCount = 0;
do
{
pSlot->pNext = pBlock->pFree;
pBlock->pFree = pSlot;
pSlot++;
} while ((ULONG_PTR)pSlot - (ULONG_PTR)pBlock <= MEMORY_BLOCK_SIZE - MEMORY_SLOT_SIZE);
pBlock->pNext = g_pMemoryBlocks;
g_pMemoryBlocks = pBlock;
}
return pBlock;
}
//-------------------------------------------------------------------------
LPVOID AllocateBuffer(LPVOID pOrigin)
{
PMEMORY_SLOT pSlot;
PMEMORY_BLOCK pBlock = GetMemoryBlock(pOrigin);
if (pBlock == NULL)
return NULL;
// Remove an unused slot from the list.
pSlot = pBlock->pFree;
pBlock->pFree = pSlot->pNext;
pBlock->usedCount++;
#ifdef _DEBUG
// Fill the slot with INT3 for debugging.
memset(pSlot, 0xCC, sizeof(MEMORY_SLOT));
#endif
return pSlot;
}
//-------------------------------------------------------------------------
VOID FreeBuffer(LPVOID pBuffer)
{
PMEMORY_BLOCK pBlock = g_pMemoryBlocks;
PMEMORY_BLOCK pPrev = NULL;
ULONG_PTR pTargetBlock = ((ULONG_PTR)pBuffer / MEMORY_BLOCK_SIZE) * MEMORY_BLOCK_SIZE;
while (pBlock != NULL)
{
if ((ULONG_PTR)pBlock == pTargetBlock)
{
PMEMORY_SLOT pSlot = (PMEMORY_SLOT)pBuffer;
#ifdef _DEBUG
// Clear the released slot for debugging.
memset(pSlot, 0x00, sizeof(MEMORY_SLOT));
#endif
// Restore the released slot to the list.
pSlot->pNext = pBlock->pFree;
pBlock->pFree = pSlot;
pBlock->usedCount--;
// Free if unused.
if (pBlock->usedCount == 0)
{
if (pPrev)
pPrev->pNext = pBlock->pNext;
else
g_pMemoryBlocks = pBlock->pNext;
win_api::virtual_free(pBlock, 0, MEM_RELEASE);
}
break;
}
pPrev = pBlock;
pBlock = pBlock->pNext;
}
}
//-------------------------------------------------------------------------
BOOL IsExecutableAddress(LPVOID pAddress)
{
MEMORY_BASIC_INFORMATION mi;
win_api::rebuilt::virtual_query(pAddress, &mi, sizeof(mi));
return (mi.State == MEM_COMMIT && (mi.Protect & PAGE_EXECUTE_FLAGS));
}
}
+848
View File
@@ -0,0 +1,848 @@
#include <include.h>
/*
* MinHook - The Minimalistic API Hooking Library for x64/x86
* Copyright (C) 2009-2017 Tsuda Kageyu.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <include.h>
#include <tlhelp32.h>
#include <limits.h>
namespace mh
{
#ifndef ARRAYSIZE
#define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0]))
#endif
// Initial capacity of the HOOK_ENTRY buffer.
#define INITIAL_HOOK_CAPACITY 32
// Initial capacity of the thread IDs buffer.
#define INITIAL_THREAD_CAPACITY 128
// Special hook position values.
#define INVALID_HOOK_POS UINT_MAX
#define ALL_HOOKS_POS UINT_MAX
// Freeze() action argument defines.
#define ACTION_DISABLE 0
#define ACTION_ENABLE 1
#define ACTION_APPLY_QUEUED 2
// Thread access rights for suspending/resuming threads.
#define THREAD_ACCESS \
(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION | THREAD_SET_CONTEXT)
// Hook information.
typedef struct _HOOK_ENTRY
{
LPVOID pTarget; // Address of the target function.
LPVOID pDetour; // Address of the detour or relay function.
LPVOID pTrampoline; // Address of the trampoline function.
UINT8 backup[8]; // Original prologue of the target function.
UINT8 patchAbove : 1; // Uses the hot patch area.
UINT8 isEnabled : 1; // Enabled.
UINT8 queueEnable : 1; // Queued for enabling/disabling when != isEnabled.
UINT nIP : 4; // Count of the instruction boundaries.
UINT8 oldIPs[8]; // Instruction boundaries of the target function.
UINT8 newIPs[8]; // Instruction boundaries of the trampoline function.
} HOOK_ENTRY, * PHOOK_ENTRY;
// Suspended threads for Freeze()/Unfreeze().
typedef struct _FROZEN_THREADS
{
LPDWORD pItems; // Data heap
UINT capacity; // Size of allocated data heap, items
UINT size; // Actual number of data items
} FROZEN_THREADS, * PFROZEN_THREADS;
//-------------------------------------------------------------------------
// Global Variables:
//-------------------------------------------------------------------------
// Spin lock flag for EnterSpinLock()/LeaveSpinLock().
volatile LONG g_isLocked = FALSE;
// Private heap handle. If not NULL, this library is initialized.
HANDLE g_hHeap = NULL;
// Hook entries.
struct
{
PHOOK_ENTRY pItems; // Data heap
UINT capacity; // Size of allocated data heap, items
UINT size; // Actual number of data items
} g_hooks;
//-------------------------------------------------------------------------
// Returns INVALID_HOOK_POS if not found.
static UINT FindHookEntry(LPVOID pTarget)
{
UINT i;
for (i = 0; i < g_hooks.size; ++i)
{
if ((ULONG_PTR)pTarget == (ULONG_PTR)g_hooks.pItems[i].pTarget)
return i;
}
return INVALID_HOOK_POS;
}
//-------------------------------------------------------------------------
static PHOOK_ENTRY AddHookEntry()
{
if (g_hooks.pItems == NULL)
{
g_hooks.capacity = INITIAL_HOOK_CAPACITY;
g_hooks.pItems = (PHOOK_ENTRY)win_api::heap_alloc(
g_hHeap, 0, g_hooks.capacity * sizeof(HOOK_ENTRY));
if (g_hooks.pItems == NULL)
return NULL;
}
else if (g_hooks.size >= g_hooks.capacity)
{
PHOOK_ENTRY p = (PHOOK_ENTRY)win_api::heap_re_alloc(
g_hHeap, 0, g_hooks.pItems, ( static_cast<uint64_t>(g_hooks.capacity) * 2) * sizeof(HOOK_ENTRY));
if (p == NULL)
return NULL;
g_hooks.capacity *= 2;
g_hooks.pItems = p;
}
return &g_hooks.pItems[g_hooks.size++];
}
//-------------------------------------------------------------------------
static VOID DeleteHookEntry(UINT pos)
{
if (pos < g_hooks.size - 1)
g_hooks.pItems[pos] = g_hooks.pItems[g_hooks.size - 1];
g_hooks.size--;
if (g_hooks.capacity / 2 >= INITIAL_HOOK_CAPACITY && g_hooks.capacity / 2 >= g_hooks.size)
{
PHOOK_ENTRY p = (PHOOK_ENTRY)win_api::heap_re_alloc(
g_hHeap, 0, g_hooks.pItems, (g_hooks.capacity / 2) * sizeof(HOOK_ENTRY));
if (p == NULL)
return;
g_hooks.capacity /= 2;
g_hooks.pItems = p;
}
}
//-------------------------------------------------------------------------
static DWORD_PTR FindOldIP(PHOOK_ENTRY pHook, DWORD_PTR ip)
{
UINT i;
if (pHook->patchAbove && ip == ((DWORD_PTR)pHook->pTarget - sizeof(JMP_REL)))
return (DWORD_PTR)pHook->pTarget;
for (i = 0; i < pHook->nIP; ++i)
{
if (ip == ((DWORD_PTR)pHook->pTrampoline + pHook->newIPs[i]))
return (DWORD_PTR)pHook->pTarget + pHook->oldIPs[i];
}
#if defined(_M_X64) || defined(__x86_64__)
// Check relay function.
if (ip == (DWORD_PTR)pHook->pDetour)
return (DWORD_PTR)pHook->pTarget;
#endif
return 0;
}
//-------------------------------------------------------------------------
static DWORD_PTR FindNewIP(PHOOK_ENTRY pHook, DWORD_PTR ip)
{
UINT i;
for (i = 0; i < pHook->nIP; ++i)
{
if (ip == ((DWORD_PTR)pHook->pTarget + pHook->oldIPs[i]))
return (DWORD_PTR)pHook->pTrampoline + pHook->newIPs[i];
}
return 0;
}
//-------------------------------------------------------------------------
static VOID ProcessThreadIPs(HANDLE hThread, UINT pos, UINT action)
{
// If the thread suspended in the overwritten area,
// move IP to the proper address.
CONTEXT c;
#if defined(_M_X64) || defined(__x86_64__)
DWORD64* pIP = &c.Rip;
#else
DWORD* pIP = &c.Eip;
#endif
UINT count;
c.ContextFlags = CONTEXT_CONTROL;
if (!GetThreadContext(hThread, &c))
return;
if (pos == ALL_HOOKS_POS)
{
pos = 0;
count = g_hooks.size;
}
else
{
count = pos + 1;
}
for (; pos < count; ++pos)
{
PHOOK_ENTRY pHook = &g_hooks.pItems[pos];
BOOL enable;
DWORD_PTR ip;
switch (action)
{
case ACTION_DISABLE:
enable = FALSE;
break;
case ACTION_ENABLE:
enable = TRUE;
break;
default: // ACTION_APPLY_QUEUED
enable = pHook->queueEnable;
break;
}
if (pHook->isEnabled == enable)
continue;
if (enable)
ip = FindNewIP(pHook, *pIP);
else
ip = FindOldIP(pHook, *pIP);
if (ip != 0)
{
*pIP = ip;
SetThreadContext(hThread, &c);
}
}
}
//-------------------------------------------------------------------------
static MH_STATUS Freeze(PFROZEN_THREADS pThreads, UINT pos, UINT action)
{
/*MH_STATUS status = MH_OK;
pThreads->pItems = NULL;
pThreads->capacity = 0;
pThreads->size = 0;
if (!EnumerateThreads(pThreads))
{
status = MH_ERROR_MEMORY_ALLOC;
}
else if (pThreads->pItems != NULL)
{
UINT i;
for (i = 0; i < pThreads->size; ++i)
{
HANDLE hThread = OpenThread(THREAD_ACCESS, FALSE, pThreads->pItems[i]);
if (hThread != NULL)
{
SuspendThread(hThread);
ProcessThreadIPs(hThread, pos, action);
CloseHandle(hThread);
}
}
}*/
return MH_OK;
}
//-------------------------------------------------------------------------
static VOID Unfreeze(PFROZEN_THREADS pThreads)
{
/*if (pThreads->pItems != NULL)
{
UINT i;
for (i = 0; i < pThreads->size; ++i)
{
HANDLE hThread = OpenThread(THREAD_ACCESS, FALSE, pThreads->pItems[i]);
if (hThread != NULL)
{
ResumeThread(hThread);
CloseHandle(hThread);
}
}
HeapFree(g_hHeap, 0, pThreads->pItems);
}*/
}
//-------------------------------------------------------------------------
static MH_STATUS EnableHookLL(UINT pos, BOOL enable, PVOID side_buffer)
{
PHOOK_ENTRY pHook = &g_hooks.pItems[pos];
DWORD oldProtect;
SIZE_T patchSize = sizeof(JMP_REL);
LPBYTE pPatchTarget = (LPBYTE)pHook->pTarget;
if (pHook->patchAbove)
{
pPatchTarget -= sizeof(JMP_REL);
patchSize += sizeof(JMP_REL_SHORT);
}
if (!side_buffer && !win_api::virtual_protect(pPatchTarget, patchSize, PAGE_EXECUTE_READWRITE, &oldProtect))
return MH_ERROR_MEMORY_PROTECT;
if (enable)
{
PVOID pOriginalTarget = 0;
if (side_buffer)
{
memcpy(side_buffer, pPatchTarget, 64);
pOriginalTarget = pPatchTarget;
pPatchTarget = (LPBYTE)side_buffer;
}
PJMP_REL pJmp = (PJMP_REL)pPatchTarget;
pJmp->opcode = 0xE9;
pJmp->operand = (UINT32)((LPBYTE)pHook->pDetour - ((LPBYTE)pOriginalTarget + sizeof(JMP_REL)));
if (pHook->patchAbove)
{
PJMP_REL_SHORT pShortJmp = (PJMP_REL_SHORT)pHook->pTarget;
pShortJmp->opcode = 0xEB;
pShortJmp->operand = (UINT8)(0 - (sizeof(JMP_REL_SHORT) + sizeof(JMP_REL)));
}
if (pOriginalTarget != 0)
pPatchTarget = (LPBYTE)pOriginalTarget;
}
else
{
if (pHook->patchAbove)
memcpy(pPatchTarget, pHook->backup, sizeof(JMP_REL) + sizeof(JMP_REL_SHORT));
else
memcpy(pPatchTarget, pHook->backup, sizeof(JMP_REL));
}
if (!side_buffer)
win_api::virtual_protect(pPatchTarget, patchSize, oldProtect, &oldProtect);
// Just-in-case measure.
//FlushInstructionCache(GetCurrentProcess(), pPatchTarget, patchSize);
pHook->isEnabled = enable;
pHook->queueEnable = enable;
return MH_OK;
}
//-------------------------------------------------------------------------
static MH_STATUS EnableAllHooksLL(BOOL enable)
{
MH_STATUS status = MH_OK;
UINT i, first = INVALID_HOOK_POS;
for (i = 0; i < g_hooks.size; ++i)
{
if (g_hooks.pItems[i].isEnabled != enable)
{
first = i;
break;
}
}
if (first != INVALID_HOOK_POS)
{
FROZEN_THREADS threads;
status = Freeze(&threads, ALL_HOOKS_POS, enable ? ACTION_ENABLE : ACTION_DISABLE);
if (status == MH_OK)
{
for (i = first; i < g_hooks.size; ++i)
{
if (g_hooks.pItems[i].isEnabled != enable)
{
status = EnableHookLL(i, enable, 0);
if (status != MH_OK)
break;
}
}
Unfreeze(&threads);
}
}
return status;
}
//-------------------------------------------------------------------------
static VOID EnterSpinLock(VOID)
{
SIZE_T spinCount = 0;
// Wait until the flag is FALSE.
while (InterlockedCompareExchange(&g_isLocked, TRUE, FALSE) != FALSE)
{
// No need to generate a memory barrier here, since InterlockedCompareExchange()
// generates a full memory barrier itself.
// Prevent the loop from being too busy.
if (spinCount < 32)
win_api::rebuilt::sleep(0);
else
win_api::rebuilt::sleep(1);
spinCount++;
}
}
//-------------------------------------------------------------------------
static VOID LeaveSpinLock(VOID)
{
// No need to generate a memory barrier here, since InterlockedExchange()
// generates a full memory barrier itself.
InterlockedExchange(&g_isLocked, FALSE);
}
//-------------------------------------------------------------------------
MH_STATUS WINAPI MH_Initialize(VOID)
{
MH_STATUS status = MH_OK;
EnterSpinLock();
if (g_hHeap == NULL)
{
g_hHeap = win_api::heap_create(0, 0, 0);
if (g_hHeap != NULL)
{
// Initialize the internal function buffer.
InitializeBuffer();
}
else
{
status = MH_ERROR_MEMORY_ALLOC;
}
}
else
{
status = MH_ERROR_ALREADY_INITIALIZED;
}
LeaveSpinLock();
return status;
}
//-------------------------------------------------------------------------
MH_STATUS WINAPI MH_Uninitialize(VOID)
{
MH_STATUS status = MH_OK;
EnterSpinLock();
if (g_hHeap != NULL)
{
status = EnableAllHooksLL(FALSE);
if (status == MH_OK)
{
// Free the internal function buffer.
// HeapFree is actually not required, but some tools detect a false
// memory leak without HeapFree.
UninitializeBuffer();
LI_FN(HeapFree)(g_hHeap, 0, g_hooks.pItems);
win_api::heap_destroy(g_hHeap);
g_hHeap = NULL;
g_hooks.pItems = NULL;
g_hooks.capacity = 0;
g_hooks.size = 0;
}
}
else
{
status = MH_ERROR_NOT_INITIALIZED;
}
LeaveSpinLock();
return status;
}
//-------------------------------------------------------------------------
MH_STATUS WINAPI MH_CreateHook(LPVOID pTarget, LPVOID pDetour, LPVOID* ppOriginal, LPVOID pTargetReal)
{
MH_STATUS status = MH_OK;
EnterSpinLock();
if (g_hHeap != NULL)
{
if (IsExecutableAddress(pTarget) && IsExecutableAddress(pDetour))
{
UINT pos = FindHookEntry(pTarget);
if (pos == INVALID_HOOK_POS)
{
LPVOID pBuffer = AllocateBuffer(pTarget);
if (pBuffer != NULL)
{
TRAMPOLINE ct;
ct.pTarget = pTarget;
ct.pDetour = pDetour;
ct.pTrampoline = pBuffer;
if (CreateTrampolineFunction(&ct))
{
PHOOK_ENTRY pHook = AddHookEntry();
if (pHook != NULL)
{
pHook->pTarget = ct.pTarget;
#if defined(_M_X64) || defined(__x86_64__)
pHook->pDetour = ct.pRelay;
#else
pHook->pDetour = ct.pDetour;
#endif
pHook->pTrampoline = ct.pTrampoline;
pHook->patchAbove = ct.patchAbove;
pHook->isEnabled = FALSE;
pHook->queueEnable = FALSE;
pHook->nIP = ct.nIP;
memcpy(pHook->oldIPs, ct.oldIPs, ARRAYSIZE(ct.oldIPs));
memcpy(pHook->newIPs, ct.newIPs, ARRAYSIZE(ct.newIPs));
// Back up the target function.
if (ct.patchAbove)
{
memcpy(
pHook->backup,
(LPBYTE)pTarget - sizeof(JMP_REL),
sizeof(JMP_REL) + sizeof(JMP_REL_SHORT));
}
else
{
memcpy(pHook->backup, pTarget, sizeof(JMP_REL));
}
if (ppOriginal != NULL)
*ppOriginal = pHook->pTrampoline;
}
else
{
status = MH_ERROR_MEMORY_ALLOC;
}
}
else
{
status = MH_ERROR_UNSUPPORTED_FUNCTION;
}
if (status != MH_OK)
{
FreeBuffer(pBuffer);
}
}
else
{
status = MH_ERROR_MEMORY_ALLOC;
}
}
else
{
status = MH_ERROR_ALREADY_CREATED;
}
}
else
{
status = MH_ERROR_NOT_EXECUTABLE;
}
}
else
{
status = MH_ERROR_NOT_INITIALIZED;
}
LeaveSpinLock();
return status;
}
//-------------------------------------------------------------------------
MH_STATUS WINAPI MH_RemoveHook(LPVOID pTarget)
{
MH_STATUS status = MH_OK;
EnterSpinLock();
if (g_hHeap != NULL)
{
UINT pos = FindHookEntry(pTarget);
if (pos != INVALID_HOOK_POS)
{
if (g_hooks.pItems[pos].isEnabled)
{
FROZEN_THREADS threads;
status = Freeze(&threads, pos, ACTION_DISABLE);
if (status == MH_OK)
{
status = EnableHookLL(pos, FALSE, 0);
Unfreeze(&threads);
}
}
if (status == MH_OK)
{
FreeBuffer(g_hooks.pItems[pos].pTrampoline);
DeleteHookEntry(pos);
}
}
else
{
status = MH_ERROR_NOT_CREATED;
}
}
else
{
status = MH_ERROR_NOT_INITIALIZED;
}
LeaveSpinLock();
return status;
}
//-------------------------------------------------------------------------
static MH_STATUS EnableHook(LPVOID pTarget, BOOL enable, PVOID side_buffer)
{
MH_STATUS status = MH_OK;
EnterSpinLock();
if (g_hHeap != NULL)
{
if (pTarget == MH_ALL_HOOKS)
{
status = EnableAllHooksLL(enable);
}
else
{
UINT pos = FindHookEntry(pTarget);
if (pos != INVALID_HOOK_POS)
{
if (g_hooks.pItems[pos].isEnabled != enable)
{
FROZEN_THREADS threads;
status = Freeze(&threads, pos, ACTION_ENABLE);
if (status == MH_OK)
{
status = EnableHookLL(pos, enable, side_buffer);
Unfreeze(&threads);
}
}
else
{
status = enable ? MH_ERROR_ENABLED : MH_ERROR_DISABLED;
}
}
else
{
status = MH_ERROR_NOT_CREATED;
}
}
}
else
{
status = MH_ERROR_NOT_INITIALIZED;
}
LeaveSpinLock();
return status;
}
//-------------------------------------------------------------------------
MH_STATUS WINAPI MH_EnableHook(LPVOID pTarget, LPVOID pSideBuffer)
{
return EnableHook(pTarget, TRUE, pSideBuffer);
}
//-------------------------------------------------------------------------
MH_STATUS WINAPI MH_DisableHook(LPVOID pTarget)
{
return EnableHook(pTarget, FALSE, 0);
}
//-------------------------------------------------------------------------
static MH_STATUS QueueHook(LPVOID pTarget, BOOL queueEnable)
{
MH_STATUS status = MH_OK;
EnterSpinLock();
if (g_hHeap != NULL)
{
if (pTarget == MH_ALL_HOOKS)
{
UINT i;
for (i = 0; i < g_hooks.size; ++i)
g_hooks.pItems[i].queueEnable = queueEnable;
}
else
{
UINT pos = FindHookEntry(pTarget);
if (pos != INVALID_HOOK_POS)
{
g_hooks.pItems[pos].queueEnable = queueEnable;
}
else
{
status = MH_ERROR_NOT_CREATED;
}
}
}
else
{
status = MH_ERROR_NOT_INITIALIZED;
}
LeaveSpinLock();
return status;
}
//-------------------------------------------------------------------------
MH_STATUS WINAPI MH_QueueEnableHook(LPVOID pTarget)
{
return QueueHook(pTarget, TRUE);
}
//-------------------------------------------------------------------------
MH_STATUS WINAPI MH_QueueDisableHook(LPVOID pTarget)
{
return QueueHook(pTarget, FALSE);
}
//-------------------------------------------------------------------------
MH_STATUS WINAPI MH_ApplyQueued(VOID)
{
MH_STATUS status = MH_OK;
UINT i, first = INVALID_HOOK_POS;
EnterSpinLock();
if (g_hHeap != NULL)
{
for (i = 0; i < g_hooks.size; ++i)
{
if (g_hooks.pItems[i].isEnabled != g_hooks.pItems[i].queueEnable)
{
first = i;
break;
}
}
if (first != INVALID_HOOK_POS)
{
FROZEN_THREADS threads;
status = Freeze(&threads, ALL_HOOKS_POS, ACTION_APPLY_QUEUED);
if (status == MH_OK)
{
for (i = first; i < g_hooks.size; ++i)
{
PHOOK_ENTRY pHook = &g_hooks.pItems[i];
if (pHook->isEnabled != pHook->queueEnable)
{
status = EnableHookLL(i, pHook->queueEnable, 0);
if (status != MH_OK)
break;
}
}
Unfreeze(&threads);
}
}
}
else
{
status = MH_ERROR_NOT_INITIALIZED;
}
LeaveSpinLock();
return status;
}
//-------------------------------------------------------------------------
MH_STATUS WINAPI MH_CreateHookApiEx(
LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour,
LPVOID* ppOriginal, LPVOID* ppTarget)
{
HMODULE hModule;
LPVOID pTarget;
hModule = win_api::get_module_handle_wide(pszModule);
if (hModule == NULL)
return MH_ERROR_MODULE_NOT_FOUND;
pTarget = util::find_export<LPVOID>(hModule, pszProcName);
if (pTarget == NULL)
return MH_ERROR_FUNCTION_NOT_FOUND;
if (ppTarget != NULL)
*ppTarget = pTarget;
return MH_CreateHook(pTarget, pDetour, ppOriginal, 0);
}
//-------------------------------------------------------------------------
MH_STATUS WINAPI MH_CreateHookApi(
LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID* ppOriginal)
{
return MH_CreateHookApiEx(pszModule, pszProcName, pDetour, ppOriginal, NULL);
}
}

Some files were not shown because too many files have changed in this diff Show More