commit 13f8503697d71dfe48bdd553029a8f03edf4942d Author: drof Date: Thu Nov 5 02:19:09 2026 +0100 Initial commit diff --git a/cache.cpp b/cache.cpp new file mode 100644 index 0000000..cef90af --- /dev/null +++ b/cache.cpp @@ -0,0 +1,93 @@ +#include + +void c_entity_cache::initialize() +{ + _entities = stl::mem_alloc( 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(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( static_cast(index) )) + return {}; + + return info.m_pointer; +} diff --git a/cache_handlers.cpp b/cache_handlers.cpp new file mode 100644 index 0000000..a9b7306 --- /dev/null +++ b/cache_handlers.cpp @@ -0,0 +1,176 @@ +#include + +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(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(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(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(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(), entry, entry.type_specific.plr); + + break; + } + case type::DUMMIE: + { + entry.type = cache::types::dummie; + process_player(index, mem::addr(entity).As(), entry, entry.type_specific.plr); + + break; + } + case type::PROWLER: + { + entry.type = cache::types::npc; + process_npc(index, mem::addr(entity).As(), entry, entry.type_specific.npc); + + break; + } + case type::PROP_SURVIVAL: + { + entry.type = cache::types::loot; + process_loot(index, mem::addr(entity).As(), 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; + } +} diff --git a/config.cpp b/config.cpp new file mode 100644 index 0000000..875e30f --- /dev/null +++ b/config.cpp @@ -0,0 +1,97 @@ +#include + +void c_config::initialize() +{ + m_parser = new (stl::mem_alloc(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(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; +} diff --git a/dyn_addr.cpp b/dyn_addr.cpp new file mode 100644 index 0000000..06060ce --- /dev/null +++ b/dyn_addr.cpp @@ -0,0 +1,112 @@ +#include + +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; +} diff --git a/dyn_offs.cpp b/dyn_offs.cpp new file mode 100644 index 0000000..b66c229 --- /dev/null +++ b/dyn_offs.cpp @@ -0,0 +1,31 @@ +#include + +namespace dyn_offs +{ + auto retrieve(LPCWSTR sig, std::initializer_list 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; +} diff --git a/ftrs/aim/aim.cpp b/ftrs/aim/aim.cpp new file mode 100644 index 0000000..39afaa7 --- /dev/null +++ b/ftrs/aim/aim.cpp @@ -0,0 +1,283 @@ +#include + +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(M_PI) / 180.f); + float valid_range = (valid_fov * static_cast(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); +} diff --git a/ftrs/aim/helper.cpp b/ftrs/aim/helper.cpp new file mode 100644 index 0000000..bed8b4d --- /dev/null +++ b/ftrs/aim/helper.cpp @@ -0,0 +1,43 @@ +#include + +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(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(id); + closest_fov = fov; + + continue; + } + } + + return closest_bone; + } + + return bone_id::head; +} diff --git a/ftrs/aim/misc.cpp b/ftrs/aim/misc.cpp new file mode 100644 index 0000000..848dff3 --- /dev/null +++ b/ftrs/aim/misc.cpp @@ -0,0 +1,28 @@ +#include + +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; + } + } +} diff --git a/ftrs/aim/target_selection.cpp b/ftrs/aim/target_selection.cpp new file mode 100644 index 0000000..3511c0b --- /dev/null +++ b/ftrs/aim/target_selection.cpp @@ -0,0 +1,110 @@ +#include + +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(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; +} diff --git a/ftrs/esp.cpp b/ftrs/esp.cpp new file mode 100644 index 0000000..aeeed9b --- /dev/null +++ b/ftrs/esp.cpp @@ -0,0 +1,477 @@ +#include + +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(max) * static_cast(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(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 ldef; + + switch ( static_cast(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(screen_size.w) / 2.0f; + const float y_center = static_cast(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(); +} diff --git a/ftrs/glow.cpp b/ftrs/glow.cpp new file mode 100644 index 0000000..053788d --- /dev/null +++ b/ftrs/glow.cpp @@ -0,0 +1,108 @@ +#include + +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(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; + } + } + } +} diff --git a/ftrs/logger.cpp b/ftrs/logger.cpp new file mode 100644 index 0000000..ce1e96b --- /dev/null +++ b/ftrs/logger.cpp @@ -0,0 +1,69 @@ +#include + +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(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); +} diff --git a/ftrs/movement.cpp b/ftrs/movement.cpp new file mode 100644 index 0000000..6148fd2 --- /dev/null +++ b/ftrs/movement.cpp @@ -0,0 +1,193 @@ +#include + +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(); +} diff --git a/ftrs/skin_changer.cpp b/ftrs/skin_changer.cpp new file mode 100644 index 0000000..c3b6869 --- /dev/null +++ b/ftrs/skin_changer.cpp @@ -0,0 +1,165 @@ +#include + +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; + } +} diff --git a/hook.cpp b/hook.cpp new file mode 100644 index 0000000..92dc2e4 --- /dev/null +++ b/hook.cpp @@ -0,0 +1,195 @@ +#include + +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(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(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(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(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( + reinterpret_cast(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(uOriginalLength))) + return false; + + stl::mem_free(pOriginal); + + return true; +} diff --git a/hooks.cpp b/hooks.cpp new file mode 100644 index 0000000..3bbe187 --- /dev/null +++ b/hooks.cpp @@ -0,0 +1,299 @@ +#include + +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(_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(_XS("kernel32.dll"), + _XS("AddVectoredExceptionHandler")), + &api::add_veh_handler, &o::api_::add_veh_handler + )) + return false; + + if (!mh::stealth_patch_api( + util::find_export(_XS("kernel32.dll"), + _XS("RemoveVectoredExceptionHandler")), + &api::remove_veh_handler, &o::api_::remove_veh_handler)) + return false; + + if (!mh::stealth_patch_api( + util::find_export(_XS("ntdll.dll"), + _XS("NtQueryInformationThread")), + &api::query_info_thread, &o::api_::query_info_thread)) + return false; + + + if (!mh::stealth_patch_api( + util::find_export(_XS("kernel32.dll"), + _XS("GetThreadContext")), + &api::get_thread_context, &o::api_::get_thread_context)) + return false; + + if (!mh::stealth_patch_api( + util::find_export(_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(); + + 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(); + + // + // .. + // +} diff --git a/hooks_ac.cpp b/hooks_ac.cpp new file mode 100644 index 0000000..f5299a8 --- /dev/null +++ b/hooks_ac.cpp @@ -0,0 +1,28 @@ +#include + +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; +} diff --git a/hooks_api.cpp b/hooks_api.cpp new file mode 100644 index 0000000..811b5c5 --- /dev/null +++ b/hooks_api.cpp @@ -0,0 +1,167 @@ +#include + +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(); + + 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")); +} diff --git a/hooks_r5.cpp b/hooks_r5.cpp new file mode 100644 index 0000000..5a214ce --- /dev/null +++ b/hooks_r5.cpp @@ -0,0 +1,158 @@ +#include + +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(); + + if (!(inst == nullptr)) + { + if (cfg::custom_fov) + { + if (g::p::cache.local_player.zooming) + { + if(cfg::custom_fov_override_zoomed) + *reinterpret_cast(BASE_OF(inst) + 0xD0) = cfg::no_zoom ? cfg::custom_fov_scale : cfg::custom_fov_scale_zoomed; + } + else + *reinterpret_cast(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(BASE_OF(inst) + 0xEC); + + *reinterpret_cast(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; +} diff --git a/inc/cache.h b/inc/cache.h new file mode 100644 index 0000000..018f3e0 --- /dev/null +++ b/inc/cache.h @@ -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; +}; diff --git a/inc/config.h b/inc/config.h new file mode 100644 index 0000000..ce2a943 --- /dev/null +++ b/inc/config.h @@ -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)) diff --git a/inc/dyn_addr.h b/inc/dyn_addr.h new file mode 100644 index 0000000..aed0cae --- /dev/null +++ b/inc/dyn_addr.h @@ -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 _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); +} diff --git a/inc/dyn_offs.h b/inc/dyn_offs.h new file mode 100644 index 0000000..7be4430 --- /dev/null +++ b/inc/dyn_offs.h @@ -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{ }; + } +} diff --git a/inc/features.h b/inc/features.h new file mode 100644 index 0000000..f395e21 --- /dev/null +++ b/inc/features.h @@ -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 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__) diff --git a/inc/global.h b/inc/global.h new file mode 100644 index 0000000..d2ab102 --- /dev/null +++ b/inc/global.h @@ -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 }; +} diff --git a/inc/global_post.h b/inc/global_post.h new file mode 100644 index 0000000..c097b96 --- /dev/null +++ b/inc/global_post.h @@ -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 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 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(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{ }; +} diff --git a/inc/hde/hde.h b/inc/hde/hde.h new file mode 100644 index 0000000..6322739 --- /dev/null +++ b/inc/hde/hde.h @@ -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(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(); + + 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(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(); + + 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(); + + 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; + } +} + diff --git a/inc/hde/hde64.h b/inc/hde/hde64.h new file mode 100644 index 0000000..93f3e00 --- /dev/null +++ b/inc/hde/hde64.h @@ -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_ */ diff --git a/inc/hde/table64.h b/inc/hde/table64.h new file mode 100644 index 0000000..0556315 --- /dev/null +++ b/inc/hde/table64.h @@ -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 +}; diff --git a/inc/hook.h b/inc/hook.h new file mode 100644 index 0000000..a1a50d0 --- /dev/null +++ b/inc/hook.h @@ -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); +} diff --git a/inc/hooks.h b/inc/hooks.h new file mode 100644 index 0000000..63ee5b1 --- /dev/null +++ b/inc/hooks.h @@ -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; + } + } +} diff --git a/inc/include.h b/inc/include.h new file mode 100644 index 0000000..be4d1b9 --- /dev/null +++ b/inc/include.h @@ -0,0 +1,48 @@ +#pragma once + +#define _USE_MATH_DEFINES +#define _NO_CRT_STDIO_INLINE + +#include +#include +#include +#include +#include + +#if !defined(WIN32_LEAN_AND_MEAN) +#define WIN32_LEAN_AND_MEAN +#include +#include +#include +#include +#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) diff --git a/inc/mh/mh.h b/inc/mh/mh.h new file mode 100644 index 0000000..2bf79fc --- /dev/null +++ b/inc/mh/mh.h @@ -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); + + +} diff --git a/inc/r5.h b/inc/r5.h new file mode 100644 index 0000000..4f7609b --- /dev/null +++ b/inc/r5.h @@ -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(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(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__)) diff --git a/inc/render.h b/inc/render.h new file mode 100644 index 0000000..0f9c488 --- /dev/null +++ b/inc/render.h @@ -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: +}; diff --git a/inc/rspn/base_client.h b/inc/rspn/base_client.h new file mode 100644 index 0000000..d714fcc --- /dev/null +++ b/inc/rspn/base_client.h @@ -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: + }; +} diff --git a/inc/rspn/buttons.h b/inc/rspn/buttons.h new file mode 100644 index 0000000..547c8da --- /dev/null +++ b/inc/rspn/buttons.h @@ -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 +}; + diff --git a/inc/rspn/cvar.h b/inc/rspn/cvar.h new file mode 100644 index 0000000..095495a --- /dev/null +++ b/inc/rspn/cvar.h @@ -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: + }; +} diff --git a/inc/rspn/defs.h b/inc/rspn/defs.h new file mode 100644 index 0000000..26e187c --- /dev/null +++ b/inc/rspn/defs.h @@ -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, + }; +} diff --git a/inc/rspn/dt_recv.h b/inc/rspn/dt_recv.h new file mode 100644 index 0000000..03c0de1 --- /dev/null +++ b/inc/rspn/dt_recv.h @@ -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 +} diff --git a/inc/rspn/engine_client.h b/inc/rspn/engine_client.h new file mode 100644 index 0000000..58e9958 --- /dev/null +++ b/inc/rspn/engine_client.h @@ -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: + }; +} diff --git a/inc/rspn/engine_trace.h b/inc/rspn/engine_trace.h new file mode 100644 index 0000000..94b9c87 --- /dev/null +++ b/inc/rspn/engine_trace.h @@ -0,0 +1,10 @@ +#pragma once + +namespace respawn +{ + class c_engine_trace + { + public: + private: + }; +} diff --git a/inc/rspn/engine_vgui.h b/inc/rspn/engine_vgui.h new file mode 100644 index 0000000..27eb38b --- /dev/null +++ b/inc/rspn/engine_vgui.h @@ -0,0 +1,10 @@ +#pragma once + +namespace respawn +{ + class c_engine_vgui + { + public: + private: + }; +} diff --git a/inc/rspn/entity.h b/inc/rspn/entity.h new file mode 100644 index 0000000..6a524a1 --- /dev/null +++ b/inc/rspn/entity.h @@ -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: + }; +} diff --git a/inc/rspn/entity_list.h b/inc/rspn/entity_list.h new file mode 100644 index 0000000..e7ca4e1 --- /dev/null +++ b/inc/rspn/entity_list.h @@ -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: + }; +} diff --git a/inc/rspn/file_system.h b/inc/rspn/file_system.h new file mode 100644 index 0000000..d3b469a --- /dev/null +++ b/inc/rspn/file_system.h @@ -0,0 +1,10 @@ +#pragma once + +namespace respawn +{ + class c_file_system + { + public: + private: + }; +} diff --git a/inc/rspn/game_movement.h b/inc/rspn/game_movement.h new file mode 100644 index 0000000..0848cb0 --- /dev/null +++ b/inc/rspn/game_movement.h @@ -0,0 +1,10 @@ +#pragma once + +namespace respawn +{ + class c_game_movement + { + public: + private: + }; +} diff --git a/inc/rspn/global.h b/inc/rspn/global.h new file mode 100644 index 0000000..20a35b7 --- /dev/null +++ b/inc/rspn/global.h @@ -0,0 +1,6 @@ +#pragma once + +namespace g::p +{ + inline c_netvar_manager netvar_mgr{}; +} diff --git a/inc/rspn/global_vars.h b/inc/rspn/global_vars.h new file mode 100644 index 0000000..c7e7b79 --- /dev/null +++ b/inc/rspn/global_vars.h @@ -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); +} diff --git a/inc/rspn/input.h b/inc/rspn/input.h new file mode 100644 index 0000000..40ac302 --- /dev/null +++ b/inc/rspn/input.h @@ -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(); + + 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(); + + return result; + } + private: + }; +} diff --git a/inc/rspn/input_system.h b/inc/rspn/input_system.h new file mode 100644 index 0000000..1ea3b1d --- /dev/null +++ b/inc/rspn/input_system.h @@ -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: + }; +} diff --git a/inc/rspn/mat_system_surface.h b/inc/rspn/mat_system_surface.h new file mode 100644 index 0000000..f2d29fd --- /dev/null +++ b/inc/rspn/mat_system_surface.h @@ -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: + }; +} diff --git a/inc/rspn/math.h b/inc/rspn/math.h new file mode 100644 index 0000000..4a95bfe --- /dev/null +++ b/inc/rspn/math.h @@ -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 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 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(M_PI)) / 180.0f; + } + + inline constexpr float rad2deg(const float v) + { + return (v * 180.0f) / static_cast(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(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(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(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; + } + } +} + diff --git a/inc/rspn/model_info.h b/inc/rspn/model_info.h new file mode 100644 index 0000000..6ce8ab9 --- /dev/null +++ b/inc/rspn/model_info.h @@ -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: + }; +} diff --git a/inc/rspn/move_flags.h b/inc/rspn/move_flags.h new file mode 100644 index 0000000..fb9efd6 --- /dev/null +++ b/inc/rspn/move_flags.h @@ -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 diff --git a/inc/rspn/net_chan.h b/inc/rspn/net_chan.h new file mode 100644 index 0000000..540175f --- /dev/null +++ b/inc/rspn/net_chan.h @@ -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: + }; +} diff --git a/inc/rspn/netvar.h b/inc/rspn/netvar.h new file mode 100644 index 0000000..c0df716 --- /dev/null +++ b/inc/rspn/netvar.h @@ -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 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& list); + + ulong get(const char* table_name, const char* prop_name) noexcept + { + stl::c_linked_list* 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 m_list; +}; + +#define NETVAR(TABLE, NAME) g::p::netvar_mgr.get(_XS(TABLE), _XS(NAME)) diff --git a/inc/rspn/player.h b/inc/rspn/player.h new file mode 100644 index 0000000..5ddeaf7 --- /dev/null +++ b/inc/rspn/player.h @@ -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: + }; +} diff --git a/inc/rspn/respawn.h b/inc/rspn/respawn.h new file mode 100644 index 0000000..895add1 --- /dev/null +++ b/inc/rspn/respawn.h @@ -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> _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); + } +} diff --git a/inc/rspn/shared_client.h b/inc/rspn/shared_client.h new file mode 100644 index 0000000..94c0170 --- /dev/null +++ b/inc/rspn/shared_client.h @@ -0,0 +1,10 @@ +#pragma once + +namespace respawn +{ + class c_shared_client + { + public: + private: + }; +} diff --git a/inc/rspn/studio.h b/inc/rspn/studio.h new file mode 100644 index 0000000..e255385 --- /dev/null +++ b/inc/rspn/studio.h @@ -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 ) +} diff --git a/inc/rspn/user_cmd.h b/inc/rspn/user_cmd.h new file mode 100644 index 0000000..8ee3a40 --- /dev/null +++ b/inc/rspn/user_cmd.h @@ -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]; + }; +} diff --git a/inc/rspn/view_model.h b/inc/rspn/view_model.h new file mode 100644 index 0000000..ad83159 --- /dev/null +++ b/inc/rspn/view_model.h @@ -0,0 +1,10 @@ +#pragma once + +namespace respawn +{ + class c_view_model : public c_entity + { + public: + private: + }; +} diff --git a/inc/rspn/view_render.h b/inc/rspn/view_render.h new file mode 100644 index 0000000..140f70e --- /dev/null +++ b/inc/rspn/view_render.h @@ -0,0 +1,14 @@ +#pragma once + +namespace respawn +{ + class c_view_render + { + public: + d3d::D3DMATRIX* get_view_matrix() + { + return *reinterpret_cast(mem::addr(this).Base() + 0x10E8D0); + } + private: + }; +} diff --git a/inc/rspn/weapon.h b/inc/rspn/weapon.h new file mode 100644 index 0000000..d385bd1 --- /dev/null +++ b/inc/rspn/weapon.h @@ -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: + }; +} diff --git a/inc/shd/assembly.h b/inc/shd/assembly.h new file mode 100644 index 0000000..a9b70f2 --- /dev/null +++ b/inc/shd/assembly.h @@ -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 + ); +} diff --git a/inc/shd/crc.hpp b/inc/shd/crc.hpp new file mode 100644 index 0000000..d3bff37 --- /dev/null +++ b/inc/shd/crc.hpp @@ -0,0 +1,1704 @@ +/** + @file CRC.h + @author Daniel Bahr + @version 1.0.1.0 + @copyright + @parblock + CRC++ + Copyright (c) 2020, Daniel Bahr + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * 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. + + * Neither the name of CRC++ nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + 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. + @endparblock +*/ + +/* + CRC++ can be configured by setting various #defines before #including this header file: + + #define crcpp_uint8 - Specifies the type used to store CRCs that have a width of 8 bits or less. + This type is not used in CRC calculations. Defaults to ::std::uint8_t. + #define crcpp_uint16 - Specifies the type used to store CRCs that have a width between 9 and 16 bits (inclusive). + This type is not used in CRC calculations. Defaults to ::std::uint16_t. + #define crcpp_uint32 - Specifies the type used to store CRCs that have a width between 17 and 32 bits (inclusive). + This type is not used in CRC calculations. Defaults to ::std::uint32_t. + #define crcpp_uint64 - Specifies the type used to store CRCs that have a width between 33 and 64 bits (inclusive). + This type is not used in CRC calculations. Defaults to ::std::uint64_t. + #define crcpp_size - This type is used for loop iteration and function signatures only. Defaults to ::std::size_t. + #define CRCPP_USE_NAMESPACE - Define to place all CRC++ code within the ::CRCPP namespace. + #define CRCPP_BRANCHLESS - Define to enable a branchless CRC implementation. The branchless implementation uses a single integer + multiplication in the bit-by-bit calculation instead of a small conditional. The branchless implementation + may be faster on processor architectures which support single-instruction integer multiplication. + #define CRCPP_USE_CPP11 - Define to enables C++11 features (move semantics, constexpr, static_assert, etc.). + #define CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS - Define to include definitions for little-used CRCs. +*/ + +#ifndef CRCPP_CRC_H_ +#define CRCPP_CRC_H_ + +#include // Includes CHAR_BIT +#ifdef CRCPP_USE_CPP11 +#include // Includes ::std::size_t +#include // Includes ::std::uint8_t, ::std::uint16_t, ::std::uint32_t, ::std::uint64_t +#else +#include // Includes size_t +#include // Includes uint8_t, uint16_t, uint32_t, uint64_t +#endif +#include // Includes ::std::numeric_limits +#include // Includes ::std::move + +#ifndef crcpp_uint8 +# ifdef CRCPP_USE_CPP11 +/// @brief Unsigned 8-bit integer definition, used primarily for parameter definitions. +# define crcpp_uint8 ::std::uint8_t +# else +/// @brief Unsigned 8-bit integer definition, used primarily for parameter definitions. +# define crcpp_uint8 uint8_t +# endif +#endif + +#ifndef crcpp_uint16 +# ifdef CRCPP_USE_CPP11 + /// @brief Unsigned 16-bit integer definition, used primarily for parameter definitions. +# define crcpp_uint16 ::std::uint16_t +# else + /// @brief Unsigned 16-bit integer definition, used primarily for parameter definitions. +# define crcpp_uint16 uint16_t +# endif +#endif + +#ifndef crcpp_uint32 +# ifdef CRCPP_USE_CPP11 + /// @brief Unsigned 32-bit integer definition, used primarily for parameter definitions. +# define crcpp_uint32 ::std::uint32_t +# else + /// @brief Unsigned 32-bit integer definition, used primarily for parameter definitions. +# define crcpp_uint32 uint32_t +# endif +#endif + +#ifndef crcpp_uint64 +# ifdef CRCPP_USE_CPP11 + /// @brief Unsigned 64-bit integer definition, used primarily for parameter definitions. +# define crcpp_uint64 ::std::uint64_t +# else + /// @brief Unsigned 64-bit integer definition, used primarily for parameter definitions. +# define crcpp_uint64 uint64_t +# endif +#endif + +#ifndef crcpp_size +# ifdef CRCPP_USE_CPP11 + /// @brief Unsigned size definition, used for specifying data sizes. +# define crcpp_size ::std::size_t +# else + /// @brief Unsigned size definition, used for specifying data sizes. +# define crcpp_size size_t +# endif +#endif + +#ifdef CRCPP_USE_CPP11 + /// @brief Compile-time expression definition. +# define crcpp_constexpr constexpr +#else + /// @brief Compile-time expression definition. +# define crcpp_constexpr const +#endif + +#ifdef CRCPP_USE_NAMESPACE +namespace CRCPP +{ +#endif + + /** + @brief Static class for computing CRCs. + @note This class supports computation of full and multi-part CRCs, using a bit-by-bit algorithm or a + byte-by-byte lookup table. The CRCs are calculated using as many optimizations as is reasonable. + If compiling with C++11, the constexpr keyword is used liberally so that many calculations are + performed at compile-time instead of at runtime. + */ + class CRC + { + public: + // Forward declaration + template + struct Table; + + /** + @brief CRC parameters. + */ + template + struct Parameters + { + CRCType polynomial; ///< CRC polynomial + CRCType initialValue; ///< Initial CRC value + CRCType finalXOR; ///< Value to XOR with the final CRC + bool reflectInput; ///< true to reflect all input bytes + bool reflectOutput; ///< true to reflect the output CRC (reflection occurs before the final XOR) + + Table MakeTable() const; + }; + + /** + @brief CRC lookup table. After construction, the CRC parameters are fixed. + @note A CRC table can be used for multiple CRC calculations. + */ + template + struct Table + { + // Constructors are intentionally NOT marked explicit. + Table(const Parameters& parameters); + +#ifdef CRCPP_USE_CPP11 + Table(Parameters&& parameters); +#endif + + const Parameters& GetParameters() const; + + const CRCType* GetTable() const; + + CRCType operator[](unsigned char index) const; + + private: + void InitTable(); + + Parameters parameters; ///< CRC parameters used to construct the table + CRCType table[1 << CHAR_BIT]; ///< CRC lookup table + }; + + // The number of bits in CRCType must be at least as large as CRCWidth. + // CRCType must be an unsigned integer type or a custom type with operator overloads. + template + static CRCType Calculate(const void* data, crcpp_size size, const Parameters& parameters); + + template + static CRCType Calculate(const void* data, crcpp_size size, const Parameters& parameters, CRCType crc); + + template + static CRCType Calculate(const void* data, crcpp_size size, const Table& lookupTable); + + template + static CRCType Calculate(const void* data, crcpp_size size, const Table& lookupTable, CRCType crc); + + // Common CRCs up to 64 bits. + // Note: Check values are the computed CRCs when given an ASCII input of "123456789" (without null terminator) +#ifdef CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS + static const Parameters< crcpp_uint8, 4>& CRC_4_ITU(); + static const Parameters< crcpp_uint8, 5>& CRC_5_EPC(); + static const Parameters< crcpp_uint8, 5>& CRC_5_ITU(); + static const Parameters< crcpp_uint8, 5>& CRC_5_USB(); + static const Parameters< crcpp_uint8, 6>& CRC_6_CDMA2000A(); + static const Parameters< crcpp_uint8, 6>& CRC_6_CDMA2000B(); + static const Parameters< crcpp_uint8, 6>& CRC_6_ITU(); + static const Parameters< crcpp_uint8, 7>& CRC_7(); +#endif + static const Parameters< crcpp_uint8, 8>& CRC_8(); +#ifdef CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS + static const Parameters< crcpp_uint8, 8>& CRC_8_EBU(); + static const Parameters< crcpp_uint8, 8>& CRC_8_MAXIM(); + static const Parameters< crcpp_uint8, 8>& CRC_8_WCDMA(); + static const Parameters& CRC_10(); + static const Parameters& CRC_10_CDMA2000(); + static const Parameters& CRC_11(); + static const Parameters& CRC_12_CDMA2000(); + static const Parameters& CRC_12_DECT(); + static const Parameters& CRC_12_UMTS(); + static const Parameters& CRC_13_BBC(); + static const Parameters& CRC_15(); + static const Parameters& CRC_15_MPT1327(); +#endif + static const Parameters& CRC_16_ARC(); + static const Parameters& CRC_16_BUYPASS(); + static const Parameters& CRC_16_CCITTFALSE(); +#ifdef CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS + static const Parameters& CRC_16_CDMA2000(); + static const Parameters& CRC_16_CMS(); + static const Parameters& CRC_16_DECTR(); + static const Parameters& CRC_16_DECTX(); + static const Parameters& CRC_16_DNP(); +#endif + static const Parameters& CRC_16_GENIBUS(); + static const Parameters& CRC_16_KERMIT(); +#ifdef CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS + static const Parameters& CRC_16_MAXIM(); + static const Parameters& CRC_16_MODBUS(); + static const Parameters& CRC_16_T10DIF(); + static const Parameters& CRC_16_USB(); +#endif + static const Parameters& CRC_16_X25(); + static const Parameters& CRC_16_XMODEM(); +#ifdef CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS + static const Parameters& CRC_17_CAN(); + static const Parameters& CRC_21_CAN(); + static const Parameters& CRC_24(); + static const Parameters& CRC_24_FLEXRAYA(); + static const Parameters& CRC_24_FLEXRAYB(); + static const Parameters& CRC_30(); +#endif + static const Parameters& CRC_32(); + static const Parameters& CRC_32_BZIP2(); +#ifdef CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS + static const Parameters& CRC_32_C(); +#endif + static const Parameters& CRC_32_MPEG2(); + static const Parameters& CRC_32_POSIX(); +#ifdef CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS + static const Parameters& CRC_32_Q(); + static const Parameters& CRC_40_GSM(); + static const Parameters& CRC_64(); +#endif + +#ifdef CRCPP_USE_CPP11 + CRC() = delete; + CRC(const CRC& other) = delete; + CRC& operator=(const CRC& other) = delete; + CRC(CRC&& other) = delete; + CRC& operator=(CRC&& other) = delete; +#endif + + private: +#ifndef CRCPP_USE_CPP11 + CRC(); + CRC(const CRC& other); + CRC& operator=(const CRC& other); +#endif + + template + static IntegerType Reflect(IntegerType value, crcpp_uint16 numBits); + + template + static CRCType Finalize(CRCType remainder, CRCType finalXOR, bool reflectOutput); + + template + static CRCType UndoFinalize(CRCType remainder, CRCType finalXOR, bool reflectOutput); + + template + static CRCType CalculateRemainder(const void* data, crcpp_size size, const Parameters& parameters, CRCType remainder); + + template + static CRCType CalculateRemainder(const void* data, crcpp_size size, const Table& lookupTable, CRCType remainder); + }; + + /** + @brief Returns a CRC lookup table construct using these CRC parameters. + @note This function primarily exists to allow use of the auto keyword instead of instantiating + a table directly, since template parameters are not inferred in constructors. + @tparam CRCType Integer type for storing the CRC result + @tparam CRCWidth Number of bits in the CRC + @return CRC lookup table + */ + template + inline CRC::Table CRC::Parameters::MakeTable() const + { + // This should take advantage of RVO and optimize out the copy. + return CRC::Table(*this); + } + + /** + @brief Constructs a CRC table from a set of CRC parameters + @param[in] params CRC parameters + @tparam CRCType Integer type for storing the CRC result + @tparam CRCWidth Number of bits in the CRC + */ + template + inline CRC::Table::Table(const Parameters& params) : + parameters(params) + { + InitTable(); + } + +#ifdef CRCPP_USE_CPP11 + /** + @brief Constructs a CRC table from a set of CRC parameters + @param[in] params CRC parameters + @tparam CRCType Integer type for storing the CRC result + @tparam CRCWidth Number of bits in the CRC + */ + template + inline CRC::Table::Table(Parameters&& params) : + parameters(::std::move(params)) + { + InitTable(); + } +#endif + + /** + @brief Gets the CRC parameters used to construct the CRC table + @tparam CRCType Integer type for storing the CRC result + @tparam CRCWidth Number of bits in the CRC + @return CRC parameters + */ + template + inline const CRC::Parameters& CRC::Table::GetParameters() const + { + return parameters; + } + + /** + @brief Gets the CRC table + @tparam CRCType Integer type for storing the CRC result + @tparam CRCWidth Number of bits in the CRC + @return CRC table + */ + template + inline const CRCType* CRC::Table::GetTable() const + { + return table; + } + + /** + @brief Gets an entry in the CRC table + @param[in] index Index into the CRC table + @tparam CRCType Integer type for storing the CRC result + @tparam CRCWidth Number of bits in the CRC + @return CRC table entry + */ + template + inline CRCType CRC::Table::operator[](unsigned char index) const + { + return table[index]; + } + + /** + @brief Initializes a CRC table. + @tparam CRCType Integer type for storing the CRC result + @tparam CRCWidth Number of bits in the CRC + */ + template + inline void CRC::Table::InitTable() + { + // For masking off the bits for the CRC (in the event that the number of bits in CRCType is larger than CRCWidth) + static crcpp_constexpr CRCType BIT_MASK((CRCType(1) << (CRCWidth - CRCType(1))) | + ((CRCType(1) << (CRCWidth - CRCType(1))) - CRCType(1))); + + // The conditional expression is used to avoid a -Wshift-count-overflow warning. + static crcpp_constexpr CRCType SHIFT((CHAR_BIT >= CRCWidth) ? static_cast(CHAR_BIT - CRCWidth) : 0); + + CRCType crc; + unsigned char byte = 0; + + // Loop over each dividend (each possible number storable in an unsigned char) + do + { + crc = CRC::CalculateRemainder(&byte, sizeof(byte), parameters, CRCType(0)); + + // This mask might not be necessary; all unit tests pass with this line commented out, + // but that might just be a coincidence based on the CRC parameters used for testing. + // In any case, this is harmless to leave in and only adds a single machine instruction per loop iteration. + crc &= BIT_MASK; + + if (!parameters.reflectInput && CRCWidth < CHAR_BIT) + { + // Undo the special operation at the end of the CalculateRemainder() + // function for non-reflected CRCs < CHAR_BIT. + crc = static_cast(crc << SHIFT); + } + + table[byte] = crc; + } while (++byte); + } + + /** + @brief Computes a CRC. + @param[in] data Data over which CRC will be computed + @param[in] size Size of the data + @param[in] parameters CRC parameters + @tparam CRCType Integer type for storing the CRC result + @tparam CRCWidth Number of bits in the CRC + @return CRC + */ + template + inline CRCType CRC::Calculate(const void* data, crcpp_size size, const Parameters& parameters) + { + CRCType remainder = CalculateRemainder(data, size, parameters, parameters.initialValue); + + // No need to mask the remainder here; the mask will be applied in the Finalize() function. + + return Finalize(remainder, parameters.finalXOR, parameters.reflectInput != parameters.reflectOutput); + } + /** + @brief Appends additional data to a previous CRC calculation. + @note This function can be used to compute multi-part CRCs. + @param[in] data Data over which CRC will be computed + @param[in] size Size of the data + @param[in] parameters CRC parameters + @param[in] crc CRC from a previous calculation + @tparam CRCType Integer type for storing the CRC result + @tparam CRCWidth Number of bits in the CRC + @return CRC + */ + template + inline CRCType CRC::Calculate(const void* data, crcpp_size size, const Parameters& parameters, CRCType crc) + { + CRCType remainder = UndoFinalize(crc, parameters.finalXOR, parameters.reflectInput != parameters.reflectOutput); + + remainder = CalculateRemainder(data, size, parameters, remainder); + + // No need to mask the remainder here; the mask will be applied in the Finalize() function. + + return Finalize(remainder, parameters.finalXOR, parameters.reflectInput != parameters.reflectOutput); + } + + /** + @brief Computes a CRC via a lookup table. + @param[in] data Data over which CRC will be computed + @param[in] size Size of the data + @param[in] lookupTable CRC lookup table + @tparam CRCType Integer type for storing the CRC result + @tparam CRCWidth Number of bits in the CRC + @return CRC + */ + template + inline CRCType CRC::Calculate(const void* data, crcpp_size size, const Table& lookupTable) + { + const Parameters& parameters = lookupTable.GetParameters(); + + CRCType remainder = CalculateRemainder(data, size, lookupTable, parameters.initialValue); + + // No need to mask the remainder here; the mask will be applied in the Finalize() function. + + return Finalize(remainder, parameters.finalXOR, parameters.reflectInput != parameters.reflectOutput); + } + + /** + @brief Appends additional data to a previous CRC calculation using a lookup table. + @note This function can be used to compute multi-part CRCs. + @param[in] data Data over which CRC will be computed + @param[in] size Size of the data + @param[in] lookupTable CRC lookup table + @param[in] crc CRC from a previous calculation + @tparam CRCType Integer type for storing the CRC result + @tparam CRCWidth Number of bits in the CRC + @return CRC + */ + template + inline CRCType CRC::Calculate(const void* data, crcpp_size size, const Table& lookupTable, CRCType crc) + { + const Parameters& parameters = lookupTable.GetParameters(); + + CRCType remainder = UndoFinalize(crc, parameters.finalXOR, parameters.reflectInput != parameters.reflectOutput); + + remainder = CalculateRemainder(data, size, lookupTable, remainder); + + // No need to mask the remainder here; the mask will be applied in the Finalize() function. + + return Finalize(remainder, parameters.finalXOR, parameters.reflectInput != parameters.reflectOutput); + } + + /** + @brief Reflects (i.e. reverses the bits within) an integer value. + @param[in] value Value to reflect + @param[in] numBits Number of bits in the integer which will be reflected + @tparam IntegerType Integer type of the value being reflected + @return Reflected value + */ + template + inline IntegerType CRC::Reflect(IntegerType value, crcpp_uint16 numBits) + { + IntegerType reversedValue(0); + + for (crcpp_uint16 i = 0; i < numBits; ++i) + { + reversedValue = static_cast((reversedValue << 1) | (value & 1)); + value = static_cast(value >> 1); + } + + return reversedValue; + } + + /** + @brief Computes the final reflection and XOR of a CRC remainder. + @param[in] remainder CRC remainder to reflect and XOR + @param[in] finalXOR Final value to XOR with the remainder + @param[in] reflectOutput true to reflect each byte of the remainder before the XOR + @tparam CRCType Integer type for storing the CRC result + @tparam CRCWidth Number of bits in the CRC + @return Final CRC + */ + template + inline CRCType CRC::Finalize(CRCType remainder, CRCType finalXOR, bool reflectOutput) + { + // For masking off the bits for the CRC (in the event that the number of bits in CRCType is larger than CRCWidth) + static crcpp_constexpr CRCType BIT_MASK = (CRCType(1) << (CRCWidth - CRCType(1))) | + ((CRCType(1) << (CRCWidth - CRCType(1))) - CRCType(1)); + + if (reflectOutput) + { + remainder = Reflect(remainder, CRCWidth); + } + + return (remainder ^ finalXOR) & BIT_MASK; + } + + /** + @brief Undoes the process of computing the final reflection and XOR of a CRC remainder. + @note This function allows for computation of multi-part CRCs + @note Calling UndoFinalize() followed by Finalize() (or vice versa) will always return the original remainder value: + + CRCType x = ...; + CRCType y = Finalize(x, finalXOR, reflectOutput); + CRCType z = UndoFinalize(y, finalXOR, reflectOutput); + assert(x == z); + + @param[in] crc Reflected and XORed CRC + @param[in] finalXOR Final value XORed with the remainder + @param[in] reflectOutput true if the remainder is to be reflected + @tparam CRCType Integer type for storing the CRC result + @tparam CRCWidth Number of bits in the CRC + @return Un-finalized CRC remainder + */ + template + inline CRCType CRC::UndoFinalize(CRCType crc, CRCType finalXOR, bool reflectOutput) + { + // For masking off the bits for the CRC (in the event that the number of bits in CRCType is larger than CRCWidth) + static crcpp_constexpr CRCType BIT_MASK = (CRCType(1) << (CRCWidth - CRCType(1))) | + ((CRCType(1) << (CRCWidth - CRCType(1))) - CRCType(1)); + + crc = (crc & BIT_MASK) ^ finalXOR; + + if (reflectOutput) + { + crc = Reflect(crc, CRCWidth); + } + + return crc; + } + + /** + @brief Computes a CRC remainder. + @param[in] data Data over which the remainder will be computed + @param[in] size Size of the data + @param[in] parameters CRC parameters + @param[in] remainder Running CRC remainder. Can be an initial value or the result of a previous CRC remainder calculation. + @tparam CRCType Integer type for storing the CRC result + @tparam CRCWidth Number of bits in the CRC + @return CRC remainder + */ + template + inline CRCType CRC::CalculateRemainder(const void* data, crcpp_size size, const Parameters& parameters, CRCType remainder) + { +#ifdef CRCPP_USE_CPP11 + // This static_assert is put here because this function will always be compiled in no matter what + // the template parameters are and whether or not a table lookup or bit-by-bit algorithm is used. + static_assert(::std::numeric_limits::digits >= CRCWidth, "CRCType is too small to contain a CRC of width CRCWidth."); +#else + // Catching this compile-time error is very important. Sadly, the compiler error will be very cryptic, but it's + // better than nothing. + enum { static_assert_failed_CRCType_is_too_small_to_contain_a_CRC_of_width_CRCWidth = 1 / (::std::numeric_limits::digits >= CRCWidth ? 1 : 0) }; +#endif + + const unsigned char* current = reinterpret_cast(data); + + // Slightly different implementations based on the parameters. The current implementations try to eliminate as much + // computation from the inner loop (looping over each bit) as possible. + if (parameters.reflectInput) + { + CRCType polynomial = CRC::Reflect(parameters.polynomial, CRCWidth); + while (size--) + { + remainder = static_cast(remainder ^ *current++); + + // An optimizing compiler might choose to unroll this loop. + for (crcpp_size i = 0; i < CHAR_BIT; ++i) + { +#ifdef CRCPP_BRANCHLESS + // Clever way to avoid a branch at the expense of a multiplication. This code is equivalent to the following: + // if (remainder & 1) + // remainder = (remainder >> 1) ^ polynomial; + // else + // remainder >>= 1; + remainder = static_cast((remainder >> 1) ^ ((remainder & 1) * polynomial)); +#else + remainder = static_cast((remainder & 1) ? ((remainder >> 1) ^ polynomial) : (remainder >> 1)); +#endif + } + } + } + else if (CRCWidth >= CHAR_BIT) + { + static crcpp_constexpr CRCType CRC_WIDTH_MINUS_ONE(CRCWidth - CRCType(1)); +#ifndef CRCPP_BRANCHLESS + static crcpp_constexpr CRCType CRC_HIGHEST_BIT_MASK(CRCType(1) << CRC_WIDTH_MINUS_ONE); +#endif + // The conditional expression is used to avoid a -Wshift-count-overflow warning. + static crcpp_constexpr CRCType SHIFT((CRCWidth >= CHAR_BIT) ? static_cast(CRCWidth - CHAR_BIT) : 0); + + while (size--) + { + remainder = static_cast(remainder ^ (static_cast(*current++) << SHIFT)); + + // An optimizing compiler might choose to unroll this loop. + for (crcpp_size i = 0; i < CHAR_BIT; ++i) + { +#ifdef CRCPP_BRANCHLESS + // Clever way to avoid a branch at the expense of a multiplication. This code is equivalent to the following: + // if (remainder & CRC_HIGHEST_BIT_MASK) + // remainder = (remainder << 1) ^ parameters.polynomial; + // else + // remainder <<= 1; + remainder = static_cast((remainder << 1) ^ (((remainder >> CRC_WIDTH_MINUS_ONE) & 1) * parameters.polynomial)); +#else + remainder = static_cast((remainder & CRC_HIGHEST_BIT_MASK) ? ((remainder << 1) ^ parameters.polynomial) : (remainder << 1)); +#endif + } + } + } + else + { + static crcpp_constexpr CRCType CHAR_BIT_MINUS_ONE(CHAR_BIT - 1); +#ifndef CRCPP_BRANCHLESS + static crcpp_constexpr CRCType CHAR_BIT_HIGHEST_BIT_MASK(CRCType(1) << CHAR_BIT_MINUS_ONE); +#endif + // The conditional expression is used to avoid a -Wshift-count-overflow warning. + static crcpp_constexpr CRCType SHIFT((CHAR_BIT >= CRCWidth) ? static_cast(CHAR_BIT - CRCWidth) : 0); + + CRCType polynomial = static_cast(parameters.polynomial << SHIFT); + remainder = static_cast(remainder << SHIFT); + + while (size--) + { + remainder = static_cast(remainder ^ *current++); + + // An optimizing compiler might choose to unroll this loop. + for (crcpp_size i = 0; i < CHAR_BIT; ++i) + { +#ifdef CRCPP_BRANCHLESS + // Clever way to avoid a branch at the expense of a multiplication. This code is equivalent to the following: + // if (remainder & CHAR_BIT_HIGHEST_BIT_MASK) + // remainder = (remainder << 1) ^ polynomial; + // else + // remainder <<= 1; + remainder = static_cast((remainder << 1) ^ (((remainder >> CHAR_BIT_MINUS_ONE) & 1) * polynomial)); +#else + remainder = static_cast((remainder & CHAR_BIT_HIGHEST_BIT_MASK) ? ((remainder << 1) ^ polynomial) : (remainder << 1)); +#endif + } + } + + remainder = static_cast(remainder >> SHIFT); + } + + return remainder; + } + + /** + @brief Computes a CRC remainder using lookup table. + @param[in] data Data over which the remainder will be computed + @param[in] size Size of the data + @param[in] lookupTable CRC lookup table + @param[in] remainder Running CRC remainder. Can be an initial value or the result of a previous CRC remainder calculation. + @tparam CRCType Integer type for storing the CRC result + @tparam CRCWidth Number of bits in the CRC + @return CRC remainder + */ + template + inline CRCType CRC::CalculateRemainder(const void* data, crcpp_size size, const Table& lookupTable, CRCType remainder) + { + const unsigned char* current = reinterpret_cast(data); + + if (lookupTable.GetParameters().reflectInput) + { + while (size--) + { +#if defined(WIN32) || defined(_WIN32) || defined(WINCE) + // Disable warning about data loss when doing (remainder >> CHAR_BIT) when + // remainder is one byte long. The algorithm is still correct in this case, + // though it's possible that one additional machine instruction will be executed. +# pragma warning (push) +# pragma warning (disable : 4333) +#endif + remainder = static_cast((remainder >> CHAR_BIT) ^ lookupTable[static_cast(remainder ^ *current++)]); +#if defined(WIN32) || defined(_WIN32) || defined(WINCE) +# pragma warning (pop) +#endif + } + } + else if (CRCWidth >= CHAR_BIT) + { + // The conditional expression is used to avoid a -Wshift-count-overflow warning. + static crcpp_constexpr CRCType SHIFT((CRCWidth >= CHAR_BIT) ? static_cast(CRCWidth - CHAR_BIT) : 0); + + while (size--) + { + remainder = static_cast((remainder << CHAR_BIT) ^ lookupTable[static_cast((remainder >> SHIFT) ^ *current++)]); + } + } + else + { + // The conditional expression is used to avoid a -Wshift-count-overflow warning. + static crcpp_constexpr CRCType SHIFT((CHAR_BIT >= CRCWidth) ? static_cast(CHAR_BIT - CRCWidth) : 0); + + remainder = static_cast(remainder << SHIFT); + + while (size--) + { + // Note: no need to mask here since remainder is guaranteed to fit in a single byte. + remainder = lookupTable[static_cast(remainder ^ *current++)]; + } + + remainder = static_cast(remainder >> SHIFT); + } + + return remainder; + } + +#ifdef CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS + /** + @brief Returns a set of parameters for CRC-4 ITU. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-4 ITU has the following parameters and check value: + - polynomial = 0x3 + - initial value = 0x0 + - final XOR = 0x0 + - reflect input = true + - reflect output = true + - check value = 0x7 + @return CRC-4 ITU parameters + */ + inline const CRC::Parameters& CRC::CRC_4_ITU() + { + static const Parameters parameters = { 0x3, 0x0, 0x0, true, true }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-5 EPC. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-5 EPC has the following parameters and check value: + - polynomial = 0x09 + - initial value = 0x09 + - final XOR = 0x00 + - reflect input = false + - reflect output = false + - check value = 0x00 + @return CRC-5 EPC parameters + */ + inline const CRC::Parameters& CRC::CRC_5_EPC() + { + static const Parameters parameters = { 0x09, 0x09, 0x00, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-5 ITU. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-5 ITU has the following parameters and check value: + - polynomial = 0x15 + - initial value = 0x00 + - final XOR = 0x00 + - reflect input = true + - reflect output = true + - check value = 0x07 + @return CRC-5 ITU parameters + */ + inline const CRC::Parameters& CRC::CRC_5_ITU() + { + static const Parameters parameters = { 0x15, 0x00, 0x00, true, true }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-5 USB. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-5 USB has the following parameters and check value: + - polynomial = 0x05 + - initial value = 0x1F + - final XOR = 0x1F + - reflect input = true + - reflect output = true + - check value = 0x19 + @return CRC-5 USB parameters + */ + inline const CRC::Parameters& CRC::CRC_5_USB() + { + static const Parameters parameters = { 0x05, 0x1F, 0x1F, true, true }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-6 CDMA2000-A. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-6 CDMA2000-A has the following parameters and check value: + - polynomial = 0x27 + - initial value = 0x3F + - final XOR = 0x00 + - reflect input = false + - reflect output = false + - check value = 0x0D + @return CRC-6 CDMA2000-A parameters + */ + inline const CRC::Parameters& CRC::CRC_6_CDMA2000A() + { + static const Parameters parameters = { 0x27, 0x3F, 0x00, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-6 CDMA2000-B. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-6 CDMA2000-A has the following parameters and check value: + - polynomial = 0x07 + - initial value = 0x3F + - final XOR = 0x00 + - reflect input = false + - reflect output = false + - check value = 0x3B + @return CRC-6 CDMA2000-B parameters + */ + inline const CRC::Parameters& CRC::CRC_6_CDMA2000B() + { + static const Parameters parameters = { 0x07, 0x3F, 0x00, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-6 ITU. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-6 ITU has the following parameters and check value: + - polynomial = 0x03 + - initial value = 0x00 + - final XOR = 0x00 + - reflect input = true + - reflect output = true + - check value = 0x06 + @return CRC-6 ITU parameters + */ + inline const CRC::Parameters& CRC::CRC_6_ITU() + { + static const Parameters parameters = { 0x03, 0x00, 0x00, true, true }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-7 JEDEC. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-7 JEDEC has the following parameters and check value: + - polynomial = 0x09 + - initial value = 0x00 + - final XOR = 0x00 + - reflect input = false + - reflect output = false + - check value = 0x75 + @return CRC-7 JEDEC parameters + */ + inline const CRC::Parameters& CRC::CRC_7() + { + static const Parameters parameters = { 0x09, 0x00, 0x00, false, false }; + return parameters; + } +#endif // CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS + + /** + @brief Returns a set of parameters for CRC-8 SMBus. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-8 SMBus has the following parameters and check value: + - polynomial = 0x07 + - initial value = 0x00 + - final XOR = 0x00 + - reflect input = false + - reflect output = false + - check value = 0xF4 + @return CRC-8 SMBus parameters + */ + inline const CRC::Parameters& CRC::CRC_8() + { + static const Parameters parameters = { 0x07, 0x00, 0x00, false, false }; + return parameters; + } + +#ifdef CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS + /** + @brief Returns a set of parameters for CRC-8 EBU (aka CRC-8 AES). + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-8 EBU has the following parameters and check value: + - polynomial = 0x1D + - initial value = 0xFF + - final XOR = 0x00 + - reflect input = true + - reflect output = true + - check value = 0x97 + @return CRC-8 EBU parameters + */ + inline const CRC::Parameters& CRC::CRC_8_EBU() + { + static const Parameters parameters = { 0x1D, 0xFF, 0x00, true, true }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-8 MAXIM (aka CRC-8 DOW-CRC). + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-8 MAXIM has the following parameters and check value: + - polynomial = 0x31 + - initial value = 0x00 + - final XOR = 0x00 + - reflect input = true + - reflect output = true + - check value = 0xA1 + @return CRC-8 MAXIM parameters + */ + inline const CRC::Parameters& CRC::CRC_8_MAXIM() + { + static const Parameters parameters = { 0x31, 0x00, 0x00, true, true }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-8 WCDMA. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-8 WCDMA has the following parameters and check value: + - polynomial = 0x9B + - initial value = 0x00 + - final XOR = 0x00 + - reflect input = true + - reflect output = true + - check value = 0x25 + @return CRC-8 WCDMA parameters + */ + inline const CRC::Parameters& CRC::CRC_8_WCDMA() + { + static const Parameters parameters = { 0x9B, 0x00, 0x00, true, true }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-10 ITU. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-10 ITU has the following parameters and check value: + - polynomial = 0x233 + - initial value = 0x000 + - final XOR = 0x000 + - reflect input = false + - reflect output = false + - check value = 0x199 + @return CRC-10 ITU parameters + */ + inline const CRC::Parameters& CRC::CRC_10() + { + static const Parameters parameters = { 0x233, 0x000, 0x000, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-10 CDMA2000. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-10 CDMA2000 has the following parameters and check value: + - polynomial = 0x3D9 + - initial value = 0x3FF + - final XOR = 0x000 + - reflect input = false + - reflect output = false + - check value = 0x233 + @return CRC-10 CDMA2000 parameters + */ + inline const CRC::Parameters& CRC::CRC_10_CDMA2000() + { + static const Parameters parameters = { 0x3D9, 0x3FF, 0x000, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-11 FlexRay. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-11 FlexRay has the following parameters and check value: + - polynomial = 0x385 + - initial value = 0x01A + - final XOR = 0x000 + - reflect input = false + - reflect output = false + - check value = 0x5A3 + @return CRC-11 FlexRay parameters + */ + inline const CRC::Parameters& CRC::CRC_11() + { + static const Parameters parameters = { 0x385, 0x01A, 0x000, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-12 CDMA2000. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-12 CDMA2000 has the following parameters and check value: + - polynomial = 0xF13 + - initial value = 0xFFF + - final XOR = 0x000 + - reflect input = false + - reflect output = false + - check value = 0xD4D + @return CRC-12 CDMA2000 parameters + */ + inline const CRC::Parameters& CRC::CRC_12_CDMA2000() + { + static const Parameters parameters = { 0xF13, 0xFFF, 0x000, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-12 DECT (aka CRC-12 X-CRC). + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-12 DECT has the following parameters and check value: + - polynomial = 0x80F + - initial value = 0x000 + - final XOR = 0x000 + - reflect input = false + - reflect output = false + - check value = 0xF5B + @return CRC-12 DECT parameters + */ + inline const CRC::Parameters& CRC::CRC_12_DECT() + { + static const Parameters parameters = { 0x80F, 0x000, 0x000, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-12 UMTS (aka CRC-12 3GPP). + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-12 UMTS has the following parameters and check value: + - polynomial = 0x80F + - initial value = 0x000 + - final XOR = 0x000 + - reflect input = false + - reflect output = true + - check value = 0xDAF + @return CRC-12 UMTS parameters + */ + inline const CRC::Parameters& CRC::CRC_12_UMTS() + { + static const Parameters parameters = { 0x80F, 0x000, 0x000, false, true }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-13 BBC. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-13 BBC has the following parameters and check value: + - polynomial = 0x1CF5 + - initial value = 0x0000 + - final XOR = 0x0000 + - reflect input = false + - reflect output = false + - check value = 0x04FA + @return CRC-13 BBC parameters + */ + inline const CRC::Parameters& CRC::CRC_13_BBC() + { + static const Parameters parameters = { 0x1CF5, 0x0000, 0x0000, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-15 CAN. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-15 CAN has the following parameters and check value: + - polynomial = 0x4599 + - initial value = 0x0000 + - final XOR = 0x0000 + - reflect input = false + - reflect output = false + - check value = 0x059E + @return CRC-15 CAN parameters + */ + inline const CRC::Parameters& CRC::CRC_15() + { + static const Parameters parameters = { 0x4599, 0x0000, 0x0000, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-15 MPT1327. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-15 MPT1327 has the following parameters and check value: + - polynomial = 0x6815 + - initial value = 0x0000 + - final XOR = 0x0001 + - reflect input = false + - reflect output = false + - check value = 0x2566 + @return CRC-15 MPT1327 parameters + */ + inline const CRC::Parameters& CRC::CRC_15_MPT1327() + { + static const Parameters parameters = { 0x6815, 0x0000, 0x0001, false, false }; + return parameters; + } +#endif // CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS + + /** + @brief Returns a set of parameters for CRC-16 ARC (aka CRC-16 IBM, CRC-16 LHA). + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-16 ARC has the following parameters and check value: + - polynomial = 0x8005 + - initial value = 0x0000 + - final XOR = 0x0000 + - reflect input = true + - reflect output = true + - check value = 0xBB3D + @return CRC-16 ARC parameters + */ + inline const CRC::Parameters& CRC::CRC_16_ARC() + { + static const Parameters parameters = { 0x8005, 0x0000, 0x0000, true, true }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-16 BUYPASS (aka CRC-16 VERIFONE, CRC-16 UMTS). + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-16 BUYPASS has the following parameters and check value: + - polynomial = 0x8005 + - initial value = 0x0000 + - final XOR = 0x0000 + - reflect input = false + - reflect output = false + - check value = 0xFEE8 + @return CRC-16 BUYPASS parameters + */ + inline const CRC::Parameters& CRC::CRC_16_BUYPASS() + { + static const Parameters parameters = { 0x8005, 0x0000, 0x0000, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-16 CCITT FALSE. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-16 CCITT FALSE has the following parameters and check value: + - polynomial = 0x1021 + - initial value = 0xFFFF + - final XOR = 0x0000 + - reflect input = false + - reflect output = false + - check value = 0x29B1 + @return CRC-16 CCITT FALSE parameters + */ + inline const CRC::Parameters& CRC::CRC_16_CCITTFALSE() + { + static const Parameters parameters = { 0x1021, 0xFFFF, 0x0000, false, false }; + return parameters; + } + +#ifdef CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS + /** + @brief Returns a set of parameters for CRC-16 CDMA2000. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-16 CDMA2000 has the following parameters and check value: + - polynomial = 0xC867 + - initial value = 0xFFFF + - final XOR = 0x0000 + - reflect input = false + - reflect output = false + - check value = 0x4C06 + @return CRC-16 CDMA2000 parameters + */ + inline const CRC::Parameters& CRC::CRC_16_CDMA2000() + { + static const Parameters parameters = { 0xC867, 0xFFFF, 0x0000, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-16 CMS. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-16 CMS has the following parameters and check value: + - polynomial = 0x8005 + - initial value = 0xFFFF + - final XOR = 0x0000 + - reflect input = false + - reflect output = false + - check value = 0xAEE7 + @return CRC-16 CMS parameters + */ + inline const CRC::Parameters& CRC::CRC_16_CMS() + { + static const Parameters parameters = { 0x8005, 0xFFFF, 0x0000, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-16 DECT-R (aka CRC-16 R-CRC). + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-16 DECT-R has the following parameters and check value: + - polynomial = 0x0589 + - initial value = 0x0000 + - final XOR = 0x0001 + - reflect input = false + - reflect output = false + - check value = 0x007E + @return CRC-16 DECT-R parameters + */ + inline const CRC::Parameters& CRC::CRC_16_DECTR() + { + static const Parameters parameters = { 0x0589, 0x0000, 0x0001, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-16 DECT-X (aka CRC-16 X-CRC). + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-16 DECT-X has the following parameters and check value: + - polynomial = 0x0589 + - initial value = 0x0000 + - final XOR = 0x0000 + - reflect input = false + - reflect output = false + - check value = 0x007F + @return CRC-16 DECT-X parameters + */ + inline const CRC::Parameters& CRC::CRC_16_DECTX() + { + static const Parameters parameters = { 0x0589, 0x0000, 0x0000, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-16 DNP. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-16 DNP has the following parameters and check value: + - polynomial = 0x3D65 + - initial value = 0x0000 + - final XOR = 0xFFFF + - reflect input = true + - reflect output = true + - check value = 0xEA82 + @return CRC-16 DNP parameters + */ + inline const CRC::Parameters& CRC::CRC_16_DNP() + { + static const Parameters parameters = { 0x3D65, 0x0000, 0xFFFF, true, true }; + return parameters; + } +#endif // CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS + + /** + @brief Returns a set of parameters for CRC-16 GENIBUS (aka CRC-16 EPC, CRC-16 I-CODE, CRC-16 DARC). + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-16 GENIBUS has the following parameters and check value: + - polynomial = 0x1021 + - initial value = 0xFFFF + - final XOR = 0xFFFF + - reflect input = false + - reflect output = false + - check value = 0xD64E + @return CRC-16 GENIBUS parameters + */ + inline const CRC::Parameters& CRC::CRC_16_GENIBUS() + { + static const Parameters parameters = { 0x1021, 0xFFFF, 0xFFFF, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-16 KERMIT (aka CRC-16 CCITT, CRC-16 CCITT-TRUE). + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-16 KERMIT has the following parameters and check value: + - polynomial = 0x1021 + - initial value = 0x0000 + - final XOR = 0x0000 + - reflect input = true + - reflect output = true + - check value = 0x2189 + @return CRC-16 KERMIT parameters + */ + inline const CRC::Parameters& CRC::CRC_16_KERMIT() + { + static const Parameters parameters = { 0x1021, 0x0000, 0x0000, true, true }; + return parameters; + } + +#ifdef CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS + /** + @brief Returns a set of parameters for CRC-16 MAXIM. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-16 MAXIM has the following parameters and check value: + - polynomial = 0x8005 + - initial value = 0x0000 + - final XOR = 0xFFFF + - reflect input = true + - reflect output = true + - check value = 0x44C2 + @return CRC-16 MAXIM parameters + */ + inline const CRC::Parameters& CRC::CRC_16_MAXIM() + { + static const Parameters parameters = { 0x8005, 0x0000, 0xFFFF, true, true }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-16 MODBUS. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-16 MODBUS has the following parameters and check value: + - polynomial = 0x8005 + - initial value = 0xFFFF + - final XOR = 0x0000 + - reflect input = true + - reflect output = true + - check value = 0x4B37 + @return CRC-16 MODBUS parameters + */ + inline const CRC::Parameters& CRC::CRC_16_MODBUS() + { + static const Parameters parameters = { 0x8005, 0xFFFF, 0x0000, true, true }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-16 T10-DIF. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-16 T10-DIF has the following parameters and check value: + - polynomial = 0x8BB7 + - initial value = 0x0000 + - final XOR = 0x0000 + - reflect input = false + - reflect output = false + - check value = 0xD0DB + @return CRC-16 T10-DIF parameters + */ + inline const CRC::Parameters& CRC::CRC_16_T10DIF() + { + static const Parameters parameters = { 0x8BB7, 0x0000, 0x0000, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-16 USB. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-16 USB has the following parameters and check value: + - polynomial = 0x8005 + - initial value = 0xFFFF + - final XOR = 0xFFFF + - reflect input = true + - reflect output = true + - check value = 0xB4C8 + @return CRC-16 USB parameters + */ + inline const CRC::Parameters& CRC::CRC_16_USB() + { + static const Parameters parameters = { 0x8005, 0xFFFF, 0xFFFF, true, true }; + return parameters; + } + +#endif // CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS + + /** + @brief Returns a set of parameters for CRC-16 X-25 (aka CRC-16 IBM-SDLC, CRC-16 ISO-HDLC, CRC-16 B). + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-16 X-25 has the following parameters and check value: + - polynomial = 0x1021 + - initial value = 0xFFFF + - final XOR = 0xFFFF + - reflect input = true + - reflect output = true + - check value = 0x906E + @return CRC-16 X-25 parameters + */ + inline const CRC::Parameters& CRC::CRC_16_X25() + { + static const Parameters parameters = { 0x1021, 0xFFFF, 0xFFFF, true, true }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-16 XMODEM (aka CRC-16 ZMODEM, CRC-16 ACORN, CRC-16 LTE). + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-16 XMODEM has the following parameters and check value: + - polynomial = 0x1021 + - initial value = 0x0000 + - final XOR = 0x0000 + - reflect input = false + - reflect output = false + - check value = 0x31C3 + @return CRC-16 XMODEM parameters + */ + inline const CRC::Parameters& CRC::CRC_16_XMODEM() + { + static const Parameters parameters = { 0x1021, 0x0000, 0x0000, false, false }; + return parameters; + } + +#ifdef CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS + /** + @brief Returns a set of parameters for CRC-17 CAN. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-17 CAN has the following parameters and check value: + - polynomial = 0x1685B + - initial value = 0x00000 + - final XOR = 0x00000 + - reflect input = false + - reflect output = false + - check value = 0x04F03 + @return CRC-17 CAN parameters + */ + inline const CRC::Parameters& CRC::CRC_17_CAN() + { + static const Parameters parameters = { 0x1685B, 0x00000, 0x00000, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-21 CAN. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-21 CAN has the following parameters and check value: + - polynomial = 0x102899 + - initial value = 0x000000 + - final XOR = 0x000000 + - reflect input = false + - reflect output = false + - check value = 0x0ED841 + @return CRC-21 CAN parameters + */ + inline const CRC::Parameters& CRC::CRC_21_CAN() + { + static const Parameters parameters = { 0x102899, 0x000000, 0x000000, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-24 OPENPGP. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-24 OPENPGP has the following parameters and check value: + - polynomial = 0x864CFB + - initial value = 0xB704CE + - final XOR = 0x000000 + - reflect input = false + - reflect output = false + - check value = 0x21CF02 + @return CRC-24 OPENPGP parameters + */ + inline const CRC::Parameters& CRC::CRC_24() + { + static const Parameters parameters = { 0x864CFB, 0xB704CE, 0x000000, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-24 FlexRay-A. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-24 FlexRay-A has the following parameters and check value: + - polynomial = 0x5D6DCB + - initial value = 0xFEDCBA + - final XOR = 0x000000 + - reflect input = false + - reflect output = false + - check value = 0x7979BD + @return CRC-24 FlexRay-A parameters + */ + inline const CRC::Parameters& CRC::CRC_24_FLEXRAYA() + { + static const Parameters parameters = { 0x5D6DCB, 0xFEDCBA, 0x000000, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-24 FlexRay-B. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-24 FlexRay-B has the following parameters and check value: + - polynomial = 0x5D6DCB + - initial value = 0xABCDEF + - final XOR = 0x000000 + - reflect input = false + - reflect output = false + - check value = 0x1F23B8 + @return CRC-24 FlexRay-B parameters + */ + inline const CRC::Parameters& CRC::CRC_24_FLEXRAYB() + { + static const Parameters parameters = { 0x5D6DCB, 0xABCDEF, 0x000000, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-30 CDMA. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-30 CDMA has the following parameters and check value: + - polynomial = 0x2030B9C7 + - initial value = 0x3FFFFFFF + - final XOR = 0x00000000 + - reflect input = false + - reflect output = false + - check value = 0x3B3CB540 + @return CRC-30 CDMA parameters + */ + inline const CRC::Parameters& CRC::CRC_30() + { + static const Parameters parameters = { 0x2030B9C7, 0x3FFFFFFF, 0x00000000, false, false }; + return parameters; + } +#endif // CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS + + /** + @brief Returns a set of parameters for CRC-32 (aka CRC-32 ADCCP, CRC-32 PKZip). + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-32 has the following parameters and check value: + - polynomial = 0x04C11DB7 + - initial value = 0xFFFFFFFF + - final XOR = 0xFFFFFFFF + - reflect input = true + - reflect output = true + - check value = 0xCBF43926 + @return CRC-32 parameters + */ + inline const CRC::Parameters& CRC::CRC_32() + { + static const Parameters parameters = { 0x04C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, true, true }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-32 BZIP2 (aka CRC-32 AAL5, CRC-32 DECT-B, CRC-32 B-CRC). + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-32 BZIP2 has the following parameters and check value: + - polynomial = 0x04C11DB7 + - initial value = 0xFFFFFFFF + - final XOR = 0xFFFFFFFF + - reflect input = false + - reflect output = false + - check value = 0xFC891918 + @return CRC-32 BZIP2 parameters + */ + inline const CRC::Parameters& CRC::CRC_32_BZIP2() + { + static const Parameters parameters = { 0x04C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, false, false }; + return parameters; + } + +#ifdef CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS + /** + @brief Returns a set of parameters for CRC-32 C (aka CRC-32 ISCSI, CRC-32 Castagnoli, CRC-32 Interlaken). + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-32 C has the following parameters and check value: + - polynomial = 0x1EDC6F41 + - initial value = 0xFFFFFFFF + - final XOR = 0xFFFFFFFF + - reflect input = true + - reflect output = true + - check value = 0xE3069283 + @return CRC-32 C parameters + */ + inline const CRC::Parameters& CRC::CRC_32_C() + { + static const Parameters parameters = { 0x1EDC6F41, 0xFFFFFFFF, 0xFFFFFFFF, true, true }; + return parameters; + } +#endif + + /** + @brief Returns a set of parameters for CRC-32 MPEG-2. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-32 MPEG-2 has the following parameters and check value: + - polynomial = 0x04C11DB7 + - initial value = 0xFFFFFFFF + - final XOR = 0x00000000 + - reflect input = false + - reflect output = false + - check value = 0x0376E6E7 + @return CRC-32 MPEG-2 parameters + */ + inline const CRC::Parameters& CRC::CRC_32_MPEG2() + { + static const Parameters parameters = { 0x04C11DB7, 0xFFFFFFFF, 0x00000000, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-32 POSIX. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-32 POSIX has the following parameters and check value: + - polynomial = 0x04C11DB7 + - initial value = 0x00000000 + - final XOR = 0xFFFFFFFF + - reflect input = false + - reflect output = false + - check value = 0x765E7680 + @return CRC-32 POSIX parameters + */ + inline const CRC::Parameters& CRC::CRC_32_POSIX() + { + static const Parameters parameters = { 0x04C11DB7, 0x00000000, 0xFFFFFFFF, false, false }; + return parameters; + } + +#ifdef CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS + /** + @brief Returns a set of parameters for CRC-32 Q. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-32 Q has the following parameters and check value: + - polynomial = 0x814141AB + - initial value = 0x00000000 + - final XOR = 0x00000000 + - reflect input = false + - reflect output = false + - check value = 0x3010BF7F + @return CRC-32 Q parameters + */ + inline const CRC::Parameters& CRC::CRC_32_Q() + { + static const Parameters parameters = { 0x814141AB, 0x00000000, 0x00000000, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-40 GSM. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-40 GSM has the following parameters and check value: + - polynomial = 0x0004820009 + - initial value = 0x0000000000 + - final XOR = 0xFFFFFFFFFF + - reflect input = false + - reflect output = false + - check value = 0xD4164FC646 + @return CRC-40 GSM parameters + */ + inline const CRC::Parameters& CRC::CRC_40_GSM() + { + static const Parameters parameters = { 0x0004820009, 0x0000000000, 0xFFFFFFFFFF, false, false }; + return parameters; + } + + /** + @brief Returns a set of parameters for CRC-64 ECMA. + @note The parameters are static and are delayed-constructed to reduce memory footprint. + @note CRC-64 ECMA has the following parameters and check value: + - polynomial = 0x42F0E1EBA9EA3693 + - initial value = 0x0000000000000000 + - final XOR = 0x0000000000000000 + - reflect input = false + - reflect output = false + - check value = 0x6C40DF5F0B497347 + @return CRC-64 ECMA parameters + */ + inline const CRC::Parameters& CRC::CRC_64() + { + static const Parameters parameters = { 0x42F0E1EBA9EA3693, 0x0000000000000000, 0x0000000000000000, false, false }; + return parameters; + } +#endif // CRCPP_INCLUDE_ESOTERIC_CRC_DEFINITIONS + +#ifdef CRCPP_USE_NAMESPACE +} +#endif + +#endif // CRCPP_CRC_H_ diff --git a/inc/shd/input.h b/inc/shd/input.h new file mode 100644 index 0000000..e2ed9df --- /dev/null +++ b/inc/shd/input.h @@ -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& buttons); + bool is_button_down(uintptr_t key_code) noexcept; + bool was_button_down(uintptr_t key_code) noexcept; +private: + std::array m_buttons; + std::array 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 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 m_cursor_pos; + + std::array m_buttons; + std::array m_buttons_prev; +}; diff --git a/inc/shd/instr.h b/inc/shd/instr.h new file mode 100644 index 0000000..61fb33a --- /dev/null +++ b/inc/shd/instr.h @@ -0,0 +1,146 @@ +#pragma once + +#include + +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?!)
+ 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, ; + 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 diff --git a/inc/shd/jsmn.h b/inc/shd/jsmn.h new file mode 100644 index 0000000..c8e836f --- /dev/null +++ b/inc/shd/jsmn.h @@ -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 + +#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 */ \ No newline at end of file diff --git a/inc/shd/json.h b/inc/shd/json.h new file mode 100644 index 0000000..4e04246 --- /dev/null +++ b/inc/shd/json.h @@ -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]; +}; diff --git a/inc/shd/kernel.h b/inc/shd/kernel.h new file mode 100644 index 0000000..6ec1c09 --- /dev/null +++ b/inc/shd/kernel.h @@ -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; +} diff --git a/inc/shd/lazy_importer.h b/inc/shd/lazy_importer.h new file mode 100644 index 0000000..91dbca3 --- /dev/null +++ b/inc/shd/lazy_importer.h @@ -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 +#include +#include + +#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 + 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( + 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( + (value ^ LAZY_IMPORTER_TOLOWER(c)) * + static_cast(prime)); + } + }; + + template + 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 + 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(*first)); + + return value; + } + + LAZY_IMPORTER_FORCEINLINE pair hash_forwarded( + const char* str) noexcept + { + pair 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(__readgsqword(0x60)); +#elif defined(_M_IX86) || defined(__i386__) + return reinterpret_cast(__readfsdword(0x30)); +#elif defined(_M_ARM) || defined(__arm__) + return *reinterpret_cast(_MoveFromCoprocessor(15, 0, 13, 0, 2) + 0x30); +#elif defined(_M_ARM64) || defined(__aarch64__) + return *reinterpret_cast(__getReg(18) + 0x60); +#elif defined(_M_IA64) || defined(__ia64__) + return *reinterpret_cast(static_cast(_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(peb()->Ldr); + } + + LAZY_IMPORTER_FORCEINLINE const win::IMAGE_NT_HEADERS* nt_headers( + const char* base) noexcept + { + return reinterpret_cast( + base + reinterpret_cast(base)->e_lfanew); + } + + LAZY_IMPORTER_FORCEINLINE const win::IMAGE_EXPORT_DIRECTORY* image_export_dir( + const char* base) noexcept + { + return reinterpret_cast( + base + nt_headers(base)->OptionalHeader.DataDirectory->VirtualAddress); + } + + LAZY_IMPORTER_FORCEINLINE const win::LDR_DATA_TABLE_ENTRY_T* ldr_data_entry() noexcept + { + return reinterpret_cast( + 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( + base + ied_data_dir.VirtualAddress); + _ied_size = ied_data_dir.Size; + } + + LAZY_IMPORTER_FORCEINLINE explicit operator bool() const noexcept + { + return reinterpret_cast(_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( + _base + reinterpret_cast( + _base + _ied->AddressOfNames)[index]); + } + + LAZY_IMPORTER_FORCEINLINE const char* address(size_type index) const noexcept + { + const auto* const rva_table = + reinterpret_cast(_base + _ied->AddressOfFunctions); + + const auto* const ord_table = reinterpret_cast( + _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(_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 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 + LAZY_IMPORTER_FORCEINLINE static T safe() noexcept + { + return Derived::template get(); + } + + template + LAZY_IMPORTER_FORCEINLINE static T cached() noexcept + { + auto& cached = _cache(); + if (!cached) + cached = Derived::template get(); + + return (T)(cached); + } + + template + LAZY_IMPORTER_FORCEINLINE static T safe_cached() noexcept + { + return cached(); + } + }; + + template + struct lazy_module : lazy_base> { + template + 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 + 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 + LAZY_IMPORTER_FORCEINLINE static T in_cached(Ldr ldr) noexcept + { + auto& cached = lazy_base>::_cache(); + if (!cached) + cached = in(ldr); + + return (T)(cached); + } + }; + + template + struct lazy_function : lazy_base, T> { + using base_type = lazy_base, T>; + + template + LAZY_IMPORTER_FORCEINLINE decltype(auto) operator()(Args&&... args) const + { +#ifndef LAZY_IMPORTER_CACHE_OPERATOR_PARENS + return get()(std::forward(args)...); +#else + return this->cached()(std::forward(args)...); +#endif + } + + template + 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(); +#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 + 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(addr)); + + function_hash = hashes.second; + module_hash = hashes.first; + + e.reset(); + break; + } + return (F)(addr); + } + } + } + } while (e.next()); + return {}; + } + + template + LAZY_IMPORTER_FORCEINLINE static F forwarded_safe() noexcept + { + return forwarded(); + } + + template + LAZY_IMPORTER_FORCEINLINE static F forwarded_cached() noexcept + { + auto& value = base_type::_cache(); + if (!value) + value = forwarded(); + return (F)(value); + } + + template + LAZY_IMPORTER_FORCEINLINE static F forwarded_safe_cached() noexcept + { + return forwarded_cached(); + } + + template + 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 + LAZY_IMPORTER_FORCEINLINE static F in_safe(Module m) noexcept + { + return in(m); + } + + template + LAZY_IMPORTER_FORCEINLINE static F in_cached(Module m) noexcept + { + auto& value = base_type::_cache(); + if (!value) + value = in(m); + return (F)(value); + } + + template + LAZY_IMPORTER_FORCEINLINE static F in_safe_cached(Module m) noexcept + { + return in_cached(m); + } + + template + LAZY_IMPORTER_FORCEINLINE static F nt() noexcept + { + return in(ldr_data_entry()->load_order_next()->DllBase); + } + + template + LAZY_IMPORTER_FORCEINLINE static F nt_safe() noexcept + { + return in_safe(ldr_data_entry()->load_order_next()->DllBase); + } + + template + LAZY_IMPORTER_FORCEINLINE static F nt_cached() noexcept + { + return in_cached(ldr_data_entry()->load_order_next()->DllBase); + } + + template + LAZY_IMPORTER_FORCEINLINE static F nt_safe_cached() noexcept + { + return in_safe_cached(ldr_data_entry()->load_order_next()->DllBase); + } + }; + + } +} // namespace li::detail + +#endif // include guard \ No newline at end of file diff --git a/inc/shd/log.h b/inc/shd/log.h new file mode 100644 index 0000000..e4421a9 --- /dev/null +++ b/inc/shd/log.h @@ -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 +extern void __log_monitor_call(void* ret_addr, const char* funcname, const char* format, T&&... arguments); + +template +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__)) diff --git a/inc/shd/log_post.h b/inc/shd/log_post.h new file mode 100644 index 0000000..523c283 --- /dev/null +++ b/inc/shd/log_post.h @@ -0,0 +1,51 @@ +#pragma once + +template +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 +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); +} diff --git a/inc/shd/math.h b/inc/shd/math.h new file mode 100644 index 0000000..e067a87 --- /dev/null +++ b/inc/shd/math.h @@ -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 + 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 + _n static_type_convert() + { + return position_t<_n>{static_cast<_n>(x), static_cast<_n>(y)}; + } + }; + + template + 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) diff --git a/inc/shd/memory.h b/inc/shd/memory.h new file mode 100644 index 0000000..beb7394 --- /dev/null +++ b/inc/shd/memory.h @@ -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(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(m_base)); + } + + [[nodiscard]] auto Ptr() const + { + return reinterpret_cast(m_base); + } + + template < class T > + [[nodiscard]] auto As() + { + return reinterpret_cast(m_base); + } + + template < class T > + [[nodiscard]] auto Retrieve_as() + { + return *reinterpret_cast(m_base); + } + + template < class T > + void Set(const T& value) + { + *As() = 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(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(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) diff --git a/inc/shd/min_hook.h b/inc/shd/min_hook.h new file mode 100644 index 0000000..2592eca --- /dev/null +++ b/inc/shd/min_hook.h @@ -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; + } +} diff --git a/inc/shd/pe.h b/inc/shd/pe.h new file mode 100644 index 0000000..3db0f55 --- /dev/null +++ b/inc/shd/pe.h @@ -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(find_export_address(base, dh, nh, name)); + } +} diff --git a/inc/shd/return_spoofer.h b/inc/shd/return_spoofer.h new file mode 100644 index 0000000..918b5da --- /dev/null +++ b/inc/shd/return_spoofer.h @@ -0,0 +1,119 @@ +#include + +namespace detail +{ + extern "C" void* _spoofer_stub(); + + template + static inline auto shellcode_stub_helper( + const void* shell, + Args... args + ) -> Ret + { + auto fn = (Ret(*)(Args...))(shell); + return fn(args...); + } + + template + 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 + struct argument_remapper> + { + // 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 +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(fn) }; + using mapper = detail::argument_remapper; + return mapper::template do_call((const void*)&detail::_spoofer_stub, &p, args...); +} \ No newline at end of file diff --git a/inc/shd/shared.h b/inc/shd/shared.h new file mode 100644 index 0000000..c661e53 --- /dev/null +++ b/inc/shd/shared.h @@ -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" diff --git a/inc/shd/signature.h b/inc/shd/signature.h new file mode 100644 index 0000000..873aa53 --- /dev/null +++ b/inc/shd/signature.h @@ -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); +} + diff --git a/inc/shd/stl.h b/inc/shd/stl.h new file mode 100644 index 0000000..976b7dc --- /dev/null +++ b/inc/shd/stl.h @@ -0,0 +1,1118 @@ +#pragma once + +#include + +#pragma warning(push) +#pragma warning(disable : 4311 4302 4146) + +namespace stl::preserved +{ + inline void* memcpy(void* dest, const void* src, size_t len) + { + char* d = (char*)dest; + const char* s = (const char*)src; + + while (len--) + *d++ = *s++; + + return dest; + } + + inline void* memset2(void* dest, int val, size_t len) + { + __stosb((unsigned char*)dest, val, len); + + return dest; + } + + inline int memcmp(void* s1, void* s2, size_t n) + { + + if (n == 0 || (s1 == s2)) { + return 0; + } + + __m128i* ptr1 = reinterpret_cast<__m128i*>(s1); + __m128i* ptr2 = reinterpret_cast<__m128i*>(s2); + + const uint8_t mode = + _SIDD_UBYTE_OPS | + _SIDD_CMP_EQUAL_EACH | + _SIDD_NEGATIVE_POLARITY | + _SIDD_LEAST_SIGNIFICANT; + + for (/**/; n != 0; ptr1++, ptr2++) { + + const __m128i a = _mm_loadu_si128(ptr1); + const __m128i b = _mm_loadu_si128(ptr2); + + if (_mm_cmpestrc(a, (int)n, b, (int)n, mode)) { + + const auto idx = _mm_cmpestri(a, (int)n, b, (int)n, mode); + + const uint8_t b1 = (reinterpret_cast(ptr1))[idx]; + const uint8_t b2 = (reinterpret_cast(ptr2))[idx]; + + if (b1 < b2) { + return -1; + } + else if (b1 > b2) { + return +1; + } + else { + return 0; + } + } + + if (n > 16) { + n -= 16; + } + else { + n = 0; + } + } + + return 0; + } +} + +namespace stl +{ + inline size_t strnlen(const char* s, size_t maxlen) + { + size_t len; + + for (len = 0; len < maxlen; len++, s++) { + if (!*s) + break; + } + return (len); + } + + inline size_t strlen(const char* s) { + + size_t result = 0; + + __m128i* mem = reinterpret_cast<__m128i*>(const_cast(s)); + const __m128i zeros = _mm_setzero_si128(); + + for (/**/; /**/; mem++, result += 16) { + + const __m128i data = _mm_loadu_si128(mem); + + const uint8_t mode = + _SIDD_UBYTE_OPS | + _SIDD_CMP_EQUAL_EACH | + _SIDD_LEAST_SIGNIFICANT; + + if (_mm_cmpistrc(data, zeros, mode)) { + const auto idx = _mm_cmpistri(data, zeros, mode); + + return result + idx; + } + } + } + + inline bool is_xdigit(const char* s) { + + if (s == nullptr) { + return false; + } + + // 3 ranges + const __m128i ranges = _mm_setr_epi8( + '0', '9', 'a', 'f', 'A', 'F', 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0 + ); + + __m128i* mem = reinterpret_cast<__m128i*>(const_cast(s)); + + const uint8_t mode = + _SIDD_UBYTE_OPS | + _SIDD_CMP_RANGES | + _SIDD_MASKED_NEGATIVE_POLARITY | + _SIDD_LEAST_SIGNIFICANT | + _SIDD_BIT_MASK; + + for (/**/; /**/; mem++) { + + const __m128i chunk = _mm_loadu_si128(mem); + + if (_mm_cmpistrc(ranges, chunk, mode)) { + // there are some characters outside the given ranges in a chunk + return false; + } + else if (_mm_cmpistrz(ranges, chunk, mode)) { + // there is zero byte in a chunk + if (*s == 0) { + // empty string + return false; + } + else { + return true; + } + } + } + + return false; + } + + inline int strcmp(const char* s1, const char* s2) + { + while (*s1 == *s2++) + if (*s1++ == 0) + return (0); + return (*(unsigned char*)s1 - *(unsigned char*)--s2); + } + + inline int strncmp(const char* s1, const char* s2, size_t n) + { + if (n == 0) + return (0); + do { + if (*s1 != *s2++) + return (*(unsigned char*)s1 - *(unsigned char*)--s2); + if (*s1++ == 0) + break; + } while (--n != 0); + + return (0); + } + + inline char* strstr(const char* s, const char* find) + { + char c, sc; + size_t len; + if ((c = *find++) != 0) { + len = strlen(find); + do { + do { + if ((sc = *s++) == 0) + return (NULL); + } while (sc != c); + } while (strncmp(s, find, len) != 0); + s--; + } + return ((char*)s); + } + + inline char* strcpy(char* d, const char* s) + { + char* saved = d; + + while (*s) + { + *d++ = *s++; + } + + *d = 0; + + return saved; + } + + inline size_t + wcslen(const wchar_t* s) + { + size_t len = 0; + while (s[len] != L'\0') + { + if (s[++len] == L'\0') + return len; + if (s[++len] == L'\0') + return len; + if (s[++len] == L'\0') + return len; + ++len; + } + return len; + } + + inline void init_unicode_string(PUNICODE_STRING DestinationString, PCWSTR SourceString) + { + __int64 v2; // rax + unsigned __int64 v3; // rax + + DestinationString->Buffer = (wchar_t*)SourceString; + *(DWORD*)&DestinationString->Length = 0; + + if (SourceString) + { + v2 = -1i64; + + do + ++v2; + while (SourceString[v2]); + + v3 = 2 * v2; + + if (v3 >= 0xFFFE) + LOWORD(v3) = -4; + + DestinationString->Length = v3; + DestinationString->MaximumLength = v3 + 2; + } + } + + inline wchar_t* wcscpy(wchar_t* __restrict s1, const wchar_t* __restrict s2) + { + wchar_t* cp; + + cp = s1; + + while ((*cp++ = *s2++) != L'\0') + ; + + return (s1); + } + + inline bool memeq(const void* first, const void* second, size_t length) + { + return !memcmp( (void*)first, (void*)second, length ); + } + + inline auto strcmp_partial(const char* first, const char* second, size_t accuracy = 0) + { + if (first == nullptr || second == nullptr) + return false; + + if (first[0] != second[0]) + return false; + + const auto length_first = stl::strlen(first); + const auto length_second = stl::strlen(second); + + if (length_first != length_second) + return false; + + for (auto i = 0ull; i < length_first; i += (accuracy + 1)) + { + if (first[i] != second[i]) + return false; + } + + return true; + } + + inline char* __strchr(const char* s, int c_in) + { + const unsigned char* char_ptr; + const unsigned long int* longword_ptr; + unsigned long int longword, magic_bits, charmask; + unsigned char c; + c = (unsigned char)c_in; + /* Handle the first few characters by reading one character at a time. + Do this until CHAR_PTR is aligned on a longword boundary. */ + for (char_ptr = (const unsigned char*)s; + ((unsigned long int) char_ptr & (sizeof(longword) - 1)) != 0; + ++char_ptr) + + if (*char_ptr == c) + return (char*)char_ptr; + + else if (*char_ptr == '\0') + return NULL; + /* All these elucidatory comments refer to 4-byte longwords, + but the theory applies equally well to 8-byte longwords. */ + longword_ptr = (unsigned long int*) char_ptr; + /* Bits 31, 24, 16, and 8 of this number are zero. Call these bits + the "holes." Note that there is a hole just to the left of + each byte, with an extra at the end: + bits: 01111110 11111110 11111110 11111111 + bytes: AAAAAAAA BBBBBBBB CCCCCCCC DDDDDDDD + The 1-bits make sure that carries propagate to the next 0-bit. + The 0-bits provide holes for carries to fall into. */ + magic_bits = -1; + magic_bits = magic_bits / 0xff * 0xfe << 1 >> 1 | 1; + /* Set up a longword, each of whose bytes is C. */ + charmask = c | (c << 8); + charmask |= charmask << 16; + if (sizeof(longword) > 4) + /* Do the shift in two steps to avoid a warning if long has 32 bits. */ + charmask |= (charmask << 16) << 16; + if (sizeof(longword) > 8) + abort(); + /* Instead of the traditional loop which tests each character, + we will test a longword at a time. The tricky part is testing + if *any of the four* bytes in the longword in question are zero. */ + for (;;) + { + /* We tentatively exit the loop if adding MAGIC_BITS to + LONGWORD fails to change any of the hole bits of LONGWORD. + 1) Is this safe? Will it catch all the zero bytes? + Suppose there is a byte with all zeros. Any carry bits + propagating from its left will fall into the hole at its + least significant bit and stop. Since there will be no + carry from its most significant bit, the LSB of the + byte to the left will be unchanged, and the zero will be + detected. + 2) Is this worthwhile? Will it ignore everything except + zero bytes? Suppose every byte of LONGWORD has a bit set + somewhere. There will be a carry into bit 8. If bit 8 + is set, this will carry into bit 16. If bit 8 is clear, + one of bits 9-15 must be set, so there will be a carry + into bit 16. Similarly, there will be a carry into bit + 24. If one of bits 24-30 is set, there will be a carry + into bit 31, so all of the hole bits will be changed. + The one misfire occurs when bits 24-30 are clear and bit + 31 is set; in this case, the hole at bit 31 is not + changed. If we had access to the processor carry flag, + we could close this loophole by putting the fourth hole + at bit 32! + So it ignores everything except 128's, when they're aligned + properly. + 3) But wait! Aren't we looking for C as well as zero? + Good point. So what we do is XOR LONGWORD with a longword, + each of whose bytes is C. This turns each byte that is C + into a zero. */ + longword = *longword_ptr++; + /* Add MAGIC_BITS to LONGWORD. */ + if ((((longword + magic_bits) + /* Set those bits that were unchanged by the addition. */ + ^ ~longword) + /* Look at only the hole bits. If any of the hole bits + are unchanged, most likely one of the bytes was a + zero. */ + & ~magic_bits) != 0 + /* That caught zeroes. Now test for C. */ + || ((((longword ^ charmask) + magic_bits) ^ ~(longword ^ charmask)) + & ~magic_bits) != 0) + { + /* Which of the bytes was C or zero? + If none of them were, it was a misfire; continue the search. */ + const unsigned char* cp = (const unsigned char*)(longword_ptr - 1); + if (*cp == c) + return (char*)cp; + else if (*cp == '\0') + return NULL; + if (*++cp == c) + return (char*)cp; + else if (*cp == '\0') + return NULL; + if (*++cp == c) + return (char*)cp; + else if (*cp == '\0') + return NULL; + if (*++cp == c) + return (char*)cp; + else if (*cp == '\0') + return NULL; + if (sizeof(longword) > 4) + { + if (*++cp == c) + return (char*)cp; + else if (*cp == '\0') + return NULL; + if (*++cp == c) + return (char*)cp; + else if (*cp == '\0') + return NULL; + if (*++cp == c) + return (char*)cp; + else if (*cp == '\0') + return NULL; + if (*++cp == c) + return (char*)cp; + else if (*cp == '\0') + return NULL; + } + } + } + return NULL; + } + + inline char* __strrchr(const char* s, int c) + { + const char* found, * p; + c = (unsigned char)c; + /* Since strchr is fast, we use it rather than the obvious loop. */ + if (c == '\0') + return __strchr(s, '\0'); + found = NULL; + while ((p = __strchr(s, c)) != NULL) + { + found = p; + s = p + 1; + } + return (char*)found; + } + + inline char* basename(const char* filename) + { + char* p = __strrchr(filename, '/'); + return p ? p + 1 : (char*)filename; + } + + template + t clamp(t x, t min, t max) + { + if (x < min) x = min; + if (x > max) x = max; + + return x; + } + + template < typename T > + inline T mem_alloc(size_t length, ulong protect = PAGE_READWRITE) + { + auto result = win_api::heap_alloc( + win_api::get_process_heap(), 0, length + ); + + if (result != nullptr) + return (T)result; + + return T{}; + } + + inline auto mem_free(void* p) + { + return LI_FN(HeapFree)(win_api::get_process_heap(), 0, p); + } + + inline char* strndup(const char* s, size_t n) + { + size_t len = strnlen(s, n); + char* _new = mem_alloc(len + 1); + + if (_new == NULL) + return NULL; + + _new[len] = '\0'; + + return (char*)memcpy(_new, s, len); + } + +#ifndef ULONG_MAX +#define ULONG_MAX ((unsigned long)(~0L)) /* 0xFFFFFFFF */ +#endif +#ifndef LONG_MAX +#define LONG_MAX ((long)(ULONG_MAX >> 1)) /* 0x7FFFFFFF */ +#endif +#ifndef LONG_MIN +#define LONG_MIN ((long)(~LONG_MAX)) /* 0x80000000 */ +#endif + + inline long strtol(const char* nptr, char** endptr, int base) + { + const char* s = nptr; + unsigned long acc; + int c; + unsigned long cutoff; + int neg = 0, any, cutlim; + + do { + c = *s++; + } while (math::isspace(c)); + if (c == '-') { + neg = 1; + c = *s++; + } + else if (c == '+') + c = *s++; + if ((base == 0 || base == 16) && + c == '0' && (*s == 'x' || *s == 'X')) { + c = s[1]; + s += 2; + base = 16; + } + if (base == 0) + base = c == '0' ? 8 : 10; + + cutoff = neg ? -(unsigned long)LONG_MIN : LONG_MAX; + cutlim = cutoff % (unsigned long)base; + cutoff /= (unsigned long)base; + for (acc = 0, any = 0;; c = *s++) { + if (math::isdigit(c)) + c -= '0'; + else if (math::isalpha(c)) + c -= math::isupper(c) ? 'A' - 10 : 'a' - 10; + else + break; + if (c >= base) + break; + if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) + any = -1; + else { + any = 1; + acc *= base; + acc += c; + } + } + if (any < 0) { + acc = neg ? LONG_MIN : LONG_MAX; + } + else if (neg) + acc = -acc; + if (endptr != 0) + *endptr = (char*)(any ? s - 1 : nptr); + return (acc); + } + + inline double strtod(char* str, char** ptr) + { + char* p; + if (ptr == (char**)0) + return math::atof(str); + + p = str; + + while (math::isspace(*p)) + ++p; + + if (*p == '+' || *p == '-') + ++p; + /* INF or INFINITY. */ + if ((p[0] == 'i' || p[0] == 'I') + && (p[1] == 'n' || p[1] == 'N') + && (p[2] == 'f' || p[2] == 'F')) + { + if ((p[3] == 'i' || p[3] == 'I') + && (p[4] == 'n' || p[4] == 'N') + && (p[5] == 'i' || p[5] == 'I') + && (p[6] == 't' || p[6] == 'T') + && (p[7] == 'y' || p[7] == 'Y')) + { + *ptr = p + 8; + return math::atof(str); + } + else + { + *ptr = p + 3; + return math::atof(str); + } + } + /* NAN or NAN(foo). */ + if ((p[0] == 'n' || p[0] == 'N') + && (p[1] == 'a' || p[1] == 'A') + && (p[2] == 'n' || p[2] == 'N')) + { + p += 3; + if (*p == '(') + { + ++p; + while (*p != '\0' && *p != ')') + ++p; + if (*p == ')') + ++p; + } + *ptr = p; + return math::atof(str); + } + /* digits, with 0 or 1 periods in it. */ + if (math::isdigit(*p) || *p == '.') + { + int got_dot = 0; + while (math::isdigit(*p) || (!got_dot && *p == '.')) + { + if (*p == '.') + got_dot = 1; + ++p; + } + /* Exponent. */ + if (*p == 'e' || *p == 'E') + { + int i; + i = 1; + if (p[i] == '+' || p[i] == '-') + ++i; + if (math::isdigit(p[i])) + { + while (math::isdigit(p[i])) + ++i; + *ptr = p + i; + return math::atof(str); + } + } + *ptr = p; + return math::atof(str); + } + /* Didn't find any digits. Doesn't look like a number. */ + *ptr = str; + return 0.0; + } + + class c_pool_buffer + { + public: + c_pool_buffer() = delete; + ~c_pool_buffer() + { + if (m_data) + mem_free(m_data); + } + + c_pool_buffer(size_t length, bool zero = true) + { + m_length = length; + m_data = mem_alloc(m_length); + + if (m_data && zero) + RtlSecureZeroMemory(m_data, length); + } + + auto length() const { return m_length; } + auto valid() const { return !(m_data == nullptr); } + auto ptr() const { return m_data; } + private: + size_t m_length{}; + void* m_data{}; + }; + + template < typename T > + struct entry_t + { + bool m_is_head; + T m_data; + entry_t* m_next; + }; + + template < typename T > + class c_linked_list + { + public: + const auto count() const { return m_count; } + size_t index_of(T& value); + + void insert(const T& value); + void remove(const T& value); + bool remove_ex(const T& value); + void remove_all_occurrences(const T& value); + + T* first(); + T* last(); + entry_t* first_entry(); + entry_t* last_entry(); + + T* operator[](size_t index) + { + size_t current = 0; + + for (auto* data = first_entry(); data != nullptr; data = data->m_next) + { + if (data->m_is_head) + continue; + + auto& entry = data->m_data; + + if (current == index) + return &entry; + + ++current; + } + + return nullptr; + } + private: + size_t m_count; + entry_t* m_head; + }; + + template < typename T > + size_t c_linked_list::index_of(T& value) + { + size_t index = 0; + size_t result = 0; + + for (auto* entry = first_entry(); entry != nullptr; entry = entry->m_next) + { + if (entry->m_is_head) + continue; + + if (memeq(&entry->m_data, &value, sizeof(value))) + { + result = index; + break; + } + + ++index; + } + + return result; + } + + template < typename T > + void c_linked_list::insert(const T& value) + { + auto* le = last_entry(); + + if (le == nullptr) + { + m_head = mem_alloc< entry_t* >(sizeof(entry_t)); + + if (m_head == nullptr) + return; + + memset(m_head, 0, sizeof(entry_t)); + + m_head->m_is_head = true; + + le = last_entry(); + + if (le == nullptr) + return; + } + + auto*& new_entry = le->m_next; + + new_entry = mem_alloc< entry_t* >(sizeof(entry_t)); + + if (new_entry == nullptr) + return; + + memset(new_entry, 0, sizeof(entry_t)); + memcpy(&new_entry->m_data, &value, sizeof(value)); + + ++m_count; + } + + template < typename T > + void c_linked_list::remove(const T& value) + { + entry_t* previous = nullptr; + entry_t* current = nullptr; + entry_t* next = nullptr; + + for (auto* entry = first_entry(); entry != nullptr; entry = entry->m_next) + { + next = entry->m_next; + current = entry; + + if (memeq(&entry->m_data, &value, sizeof(value))) + { + mem_free(entry); + previous->m_next = next; + + --m_count; + break; + } + + previous = entry; + } + } + + template < typename T > + bool c_linked_list::remove_ex(const T& value) + { + auto result = false; + + entry_t* previous = nullptr; + entry_t* current = nullptr; + entry_t* next = nullptr; + + for (auto* entry = first_entry(); entry != nullptr; entry = entry->m_next) + { + next = entry->m_next; + current = entry; + + if (!memcmp(&entry->m_data, &value, sizeof(value))) + { + mem_free(entry); + previous->m_next = next; + + result = true; + --m_count; + break; + } + + previous = entry; + } + + return result; + } + + template < typename T > + void c_linked_list::remove_all_occurrences(const T& value) + { + do + { + if (!remove_ex(value)) + break; + } while (true); + } + + template < typename T > + T* c_linked_list::first() + { + return m_head->m_data; + } + + template < typename T > + T* c_linked_list::last() + { + auto* result = m_head; + + if (result == nullptr) + return nullptr; + + while (result != nullptr && result->next != nullptr) + result = result->next; + + return result->m_data; + } + + template < typename T > + entry_t* c_linked_list::first_entry() + { + return m_head; + } + + template < typename T > + entry_t* c_linked_list::last_entry() + { + auto* result = m_head; + + if (result == nullptr) + return nullptr; + + while (result != nullptr && result->m_next != nullptr) + result = result->m_next; + + return result; + } + + class spinlock + { + public: + // + // Manually fine-tuned. + // + static constexpr unsigned max_wait = 65536; + + bool try_lock() noexcept + { + return !lock_.test_and_set(std::memory_order_acquire); + } + + void lock() noexcept + { + unsigned wait = 1; + + while (!try_lock()) + { + for (unsigned i = 0; i < wait; ++i) + { + YieldProcessor(); + } + + // + // Don't call "pause" too many times. If the wait becomes too big, + // clamp it to the max_wait. + // + wait = min(wait * 2, max_wait); + } + } + + void unlock() noexcept + { + lock_.clear(std::memory_order_release); + } + + private: + std::atomic_flag lock_ = ATOMIC_FLAG_INIT; + }; + + class my_lock_guard + { + public: + my_lock_guard() = delete; + my_lock_guard(spinlock* lock) + { + m_lock = lock; + + if (m_lock) + m_lock->lock(); + } + + ~my_lock_guard() + { + if (m_lock) + m_lock->unlock(); + } + private: + spinlock* m_lock; + }; + + class c_handle_guard + { + public: + c_handle_guard() = delete; + c_handle_guard(HANDLE handle) + { + m_handle = handle; + } + + ~c_handle_guard() + { + if (m_handle != nullptr) + { + LI_FN(CloseHandle).cached()(m_handle); + } + } + private: + HANDLE m_handle = nullptr; + }; + + template < typename T, size_t S > + class c_fixed_list + { + public: + void initialize() + { + memset(m_data, 0, sizeof(m_data)); + + m_ready = 1; + } + + const auto capacity() { return S; } + const auto count() { return m_count; } + + void insert(const T& element) noexcept + { + if (!m_ready) + return; + + if ((m_count + 1) > S) + return; + + m_data[m_count] = element; + ++m_count; + } + + T* at(size_t i) noexcept + { + if (!m_ready) + return nullptr; + + if (i < 0 || i >= capacity() || i >= count()) + return nullptr; + + return &m_data[i]; + } + private: + uint8_t m_ready{}; + size_t m_count{}; + T m_data[S]{ 0 }; + }; + + template < typename T> + class c_heap_list + { + public: + bool initialize(size_t count) + { + const auto length = (count * sizeof(T)); + + m_capacity = count; + m_data = mem_alloc(length); + + if (m_data == nullptr) + return false; + + memset(m_data, 0, length); + + m_ready = 1; + + return true; + } + + const auto capacity() { return m_capacity; } + const auto count() { return m_count; } + + void insert(const T& element) noexcept + { + if (!m_ready) + return; + + if ((m_count + 1) > m_capacity) + return; + + m_data[m_count] = element; + ++m_count; + } + + T* at(size_t i) noexcept + { + if (!m_ready) + return nullptr; + + if (i < 0 || i >= capacity() || i >= count()) + return nullptr; + + return &m_data[i]; + } + private: + uint8_t m_ready{}; + size_t m_capacity{}; + size_t m_count{}; + T* m_data{}; + }; + + class c_string_table + { + public: + void insert(const char* text); + const char* get(int i); + + auto count() { return m_data.count(); } + private: + using entry = char[MAX_PATH]; + private: + c_linked_list m_data{ }; + }; + + inline void c_string_table::insert(const char* text) + { + if (text == nullptr) + return; + + auto length = stl::strlen(text); + + if (length > sizeof(entry)) + return; + + char data[sizeof(entry)]; + + memset(data, 0, sizeof(data)); + stl::strcpy(data, text); + + m_data.insert(data); + } + + inline const char* c_string_table::get(int i) + { + if (i > (m_data.count() - 1)) + return nullptr; + + auto entry = m_data[i]; + + if (entry == nullptr) + return nullptr; + + return *entry; + } + + class c_string + { + public: + c_string(const char* contents) + { + memset(m_buffer, 0, sizeof(m_buffer)); + strcpy(m_buffer, contents); + } + + const char* c_str() noexcept { return m_buffer; } + char* data() noexcept { return m_buffer; } + private: + char m_buffer[256]; + }; +} + +#pragma warning(pop) + +extern void* operator new(size_t size); +extern void* operator new[](size_t size); + +extern void operator delete(void* ptr); +extern void operator delete[](void* ptr); + +#include "stl/vector.h" diff --git a/inc/shd/stl/vector.h b/inc/shd/stl/vector.h new file mode 100644 index 0000000..0daa9ca --- /dev/null +++ b/inc/shd/stl/vector.h @@ -0,0 +1,413 @@ +#pragma once + +namespace stl +{ + struct out_of_range + { + + }; + + template class vector + { + public: + /* ----- Constructors ----- */ + + // Default constructor + vector(); + + explicit vector(int s); + + // Copy constructor + vector(const vector& arg); + + // Copy Assingment + vector& operator=(const vector& 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 vector::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 + vector::vector() + :_size(0), _elements(0), _space(0) + {} + + template + inline vector::vector(int s) + : _size(s), _elements(new T[s]), _space(s) + { + for (int index = 0; index < _size; ++index) + _elements[index] = T(); + } + + template + inline vector::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 + inline vector& vector::operator=(const vector& 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 + vector::~vector() + { + delete[] _elements; + } + + + + // Iterators + template + inline typename vector::iterator vector::begin() + { + return vector::iterator(&_elements[0]); + } + + template + inline typename const vector::iterator vector::begin() const + { + return vector::iterator(&_elements[0]); + } + + template + inline typename vector::iterator vector::end() + { + return vector::iterator(&_elements[_size]); + } + + template + inline typename const vector::iterator vector::end() const + { + return vector::iterator(&_elements[_size]); + } + + template + inline typename const vector::iterator vector::cbegin() const + { + return vector::iterator(&_elements[0]); + } + + template + inline typename const vector::iterator vector::cend() const + { + return vector::iterator(&_elements[_size]); + } + + + + // Capacity + template + inline bool vector::empty() const + { + return (_size == 0); + } + + template + inline size_t vector::capacity() const + { + return _space; + } + + template + inline void vector::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 + inline void vector::resize(size_t newsize, T val) + { + reserve(newsize); + + for (auto index = _size; index < newsize; ++index) + _elements[index] = T(); + + _size = newsize; + } + + template + inline size_t vector::size() const + { + return _size; + } + + + + // Modifiers + template + inline void vector::push_back(const T& d) + { + if (_space == 0) + reserve(8); + else if (_size == _space) + reserve(2 * _space); + + _elements[_size] = d; + + ++_size; + } + + + + // Accessors + template + inline T& vector::at(int n) + { + if (n < 0 || _size <= n) throw out_of_range(); + return _elements[n]; + } + + template + inline const T& vector::at(int n) const + { + if (n < 0 || _size <= n) throw out_of_range(); + return _elements[n]; + } + + template + inline T& vector::operator[](int i) + { + return _elements[i]; + } + + template + inline const T& vector::operator[](int i) const + { + return _elements[i]; + } + + template + inline T& vector::front() + { + return _elements[0]; + } + + template + inline const T& vector::front() const + { + return _elements[0]; + } + + template + inline T& vector::back() + { + return _elements[_size - 1]; + } + + template + inline const T& vector::back() const + { + return _elements[_size - 1]; + } + + template + inline T* vector::data() + { + return _elements; + } + + template + inline const T* vector::data() const + { + return _elements; + } +} diff --git a/inc/shd/stl_uni.h b/inc/shd/stl_uni.h new file mode 100644 index 0000000..3191fa7 --- /dev/null +++ b/inc/shd/stl_uni.h @@ -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) diff --git a/inc/shd/syscall.h b/inc/shd/syscall.h new file mode 100644 index 0000000..b3fee7f --- /dev/null +++ b/inc/shd/syscall.h @@ -0,0 +1,6 @@ +#pragma once + +namespace sc +{ + extern UINT32 find_id_by_name(LPCSTR pszName); +} diff --git a/inc/shd/util.h b/inc/shd/util.h new file mode 100644 index 0000000..0bfb615 --- /dev/null +++ b/inc/shd/util.h @@ -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(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 + __forceinline void format_string(char* buffer, size_t length, const char* fmt, T&&... args) + { + LI_FN(wsprintfA).cached()(buffer, fmt, args...); + } + + template + __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, ®ion_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; + } +} diff --git a/inc/shd/vfunc.h b/inc/shd/vfunc.h new file mode 100644 index 0000000..4e03a1c --- /dev/null +++ b/inc/shd/vfunc.h @@ -0,0 +1,16 @@ +#pragma once + +namespace vfunc +{ + template + __forceinline ReturnType call(void* instance, Args... args) + { + using Fn = ReturnType(__thiscall*)(void*, Args...); + + auto function = (*reinterpret_cast(instance))[Index]; + + return spoof_call(function, instance, args...); + } +} + +#define VIRTUAL_FUNC(NAME, RETURN_VALUE, INDEX, ARGS, ...) RETURN_VALUE NAME ARGS { return vfunc::call(__VA_ARGS__); } diff --git a/inc/shd/vmt.h b/inc/shd/vmt.h new file mode 100644 index 0000000..0ccec57 --- /dev/null +++ b/inc/shd/vmt.h @@ -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(&_old))) + { + log_info_("failed to protect virtual memory."); + EXIT_PROCESS(NULL); + } + } + ~protect_guard() + { + win_api::virtual_protect(_base, _length, _old, reinterpret_cast(&_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 + void hook_index(const int index, T fun) + { + new_vftb1[index + 1] = reinterpret_cast(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(class_base) = old_vftbl; + old_vftbl = nullptr; + } + } + + template + T get_original(const int index) + { + return reinterpret_cast(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; +}; \ No newline at end of file diff --git a/inc/shd/winapi.h b/inc/shd/winapi.h new file mode 100644 index 0000000..8ddfe6d --- /dev/null +++ b/inc/shd/winapi.h @@ -0,0 +1,179 @@ +#pragma once + +#define FIND_EXPORT(MOD, EXP, TYPE) win_api::find_export(_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(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); + } + } +} diff --git a/inc/shd/xor.h b/inc/shd/xor.h new file mode 100644 index 0000000..960d9f7 --- /dev/null +++ b/inc/shd/xor.h @@ -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 + constexpr Char encrypt_character(const Char character, int index) + { + return character ^ (static_cast(XORKEY) + index); + } + + // ----------------------------------------------------------------------------- + + template + 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(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(_string); + for (unsigned t = 0; t < _nb_chars; t++) + { + string[t] = string[t] ^ (static_cast(XORKEY) + t); + } + string[_nb_chars] = '\0'; + return string; + } + }; + + template + 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) + diff --git a/inc/wnds/info_panel.h b/inc/wnds/info_panel.h new file mode 100644 index 0000000..2bab69b --- /dev/null +++ b/inc/wnds/info_panel.h @@ -0,0 +1,11 @@ +#pragma once + +namespace window +{ + class c_info_panel : public c_base + { + public: + void paint() override; + private: + }; +} diff --git a/inc/wnds/menu.h b/inc/wnds/menu.h new file mode 100644 index 0000000..23c5c05 --- /dev/null +++ b/inc/wnds/menu.h @@ -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& position, const math::dimension_t& 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; + }; +} diff --git a/inc/wnds/radar.h b/inc/wnds/radar.h new file mode 100644 index 0000000..05e4850 --- /dev/null +++ b/inc/wnds/radar.h @@ -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; + }; +} diff --git a/inc/wnds/spectator_list.h b/inc/wnds/spectator_list.h new file mode 100644 index 0000000..f41f8be --- /dev/null +++ b/inc/wnds/spectator_list.h @@ -0,0 +1,11 @@ +#pragma once + +namespace window +{ + class c_spectator_list : public c_base + { + public: + void paint() override; + private: + }; +} diff --git a/inc/wnds/ui.h b/inc/wnds/ui.h new file mode 100644 index 0000000..356c1c0 --- /dev/null +++ b/inc/wnds/ui.h @@ -0,0 +1,15 @@ +#pragma once + +namespace ui +{ + extern bool in_range(const math::position_t& _position, const math::dimension_t& _dimension); + extern void section(const math::position_t& _position, const math::dimension_t& _dimension, respawn::color_t color, const char* name); + extern void checkbox(const math::position_t _position, const char* text, bool* variable); + extern void checkbox_triple(const math::position_t _position, const char* text, int* variable); + extern void slider(math::position_t _position, math::dimension_t _dimension, const char* text, int* variable, int min, int max); + extern void slider_float(math::position_t _position, math::dimension_t _dimension, const char* text, float* variable, float min, float max); + extern bool button( + const math::position_t& _position, const math::dimension_t& _dimension, + respawn::color_t background_color, respawn::color_t text_color, const char* text + ); +} diff --git a/inc/wnds/windows.h b/inc/wnds/windows.h new file mode 100644 index 0000000..1f244dd --- /dev/null +++ b/inc/wnds/windows.h @@ -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& pos, const math::dimension_t& 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 m_position; + math::dimension_t m_dimension; + private: + }; + + class c_manager + { + public: + template + [[nodiscard]] bool in_range(const math::position_t cursor_position, + const std::pair, math::dimension_t<_t>> target_position) const + { + const auto x0 = static_cast(target_position.first.x), y0 = static_cast(target_position.first.y); + const auto x1 = x0 + static_cast(target_position.second.w), y1 = y0 + static_cast(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& pos, const math::dimension_t& 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 m_list; + }; +} + +#include "ui.h" + +#include "menu.h" +#include "info_panel.h" +#include "radar.h" +#include "spectator_list.h" diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..4b33919 --- /dev/null +++ b/main.cpp @@ -0,0 +1,24 @@ +#include + +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(); + } +} diff --git a/mh/buffer.cpp b/mh/buffer.cpp new file mode 100644 index 0000000..824152f --- /dev/null +++ b/mh/buffer.cpp @@ -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 + + // 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)); + } +} diff --git a/mh/hook_.cpp b/mh/hook_.cpp new file mode 100644 index 0000000..c1f8cb0 --- /dev/null +++ b/mh/hook_.cpp @@ -0,0 +1,848 @@ +#include + +/* + * 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 +#include + +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(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(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); + } +} + diff --git a/mh/mh.cpp b/mh/mh.cpp new file mode 100644 index 0000000..78aa130 --- /dev/null +++ b/mh/mh.cpp @@ -0,0 +1,3 @@ +#include + + diff --git a/mh/trampoline.cpp b/mh/trampoline.cpp new file mode 100644 index 0000000..3267c89 --- /dev/null +++ b/mh/trampoline.cpp @@ -0,0 +1,321 @@ +/* + * 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 + +using namespace mh; + +#ifdef _MSC_VER +#include +#endif + +#ifndef ARRAYSIZE +#define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0])) +#endif + +#if defined(_M_X64) || defined(__x86_64__) +#include "./hde/hde64.h" +typedef hde64s HDE; +#define HDE_DISASM(code, hs) hde64_disasm(code, hs) +#else +#include "./hde/hde32.h" +typedef hde32s HDE; +#define HDE_DISASM(code, hs) hde32_disasm(code, hs) +#endif + +// Maximum size of a trampoline function. +#if defined(_M_X64) || defined(__x86_64__) +#define TRAMPOLINE_MAX_SIZE (MEMORY_SLOT_SIZE - sizeof(JMP_ABS)) +#else +#define TRAMPOLINE_MAX_SIZE MEMORY_SLOT_SIZE +#endif + +namespace mh +{ + //------------------------------------------------------------------------- + static BOOL IsCodePadding(LPBYTE pInst, UINT size) + { + UINT i; + + if (pInst[0] != 0x00 && pInst[0] != 0x90 && pInst[0] != 0xCC) + return FALSE; + + for (i = 1; i < size; ++i) + { + if (pInst[i] != pInst[0]) + return FALSE; + } + return TRUE; + } + + //------------------------------------------------------------------------- + BOOL CreateTrampolineFunction(PTRAMPOLINE ct) + { +#if defined(_M_X64) || defined(__x86_64__) + CALL_ABS call = { + 0xFF, 0x15, 0x00000002, // FF15 00000002: CALL [RIP+8] + 0xEB, 0x08, // EB 08: JMP +10 + 0x0000000000000000ULL // Absolute destination address + }; + JMP_ABS jmp = { + 0xFF, 0x25, 0x00000000, // FF25 00000000: JMP [RIP+6] + 0x0000000000000000ULL // Absolute destination address + }; + JCC_ABS jcc = { + 0x70, 0x0E, // 7* 0E: J** +16 + 0xFF, 0x25, 0x00000000, // FF25 00000000: JMP [RIP+6] + 0x0000000000000000ULL // Absolute destination address + }; +#else + CALL_REL call = { + 0xE8, // E8 xxxxxxxx: CALL +5+xxxxxxxx + 0x00000000 // Relative destination address + }; + JMP_REL jmp = { + 0xE9, // E9 xxxxxxxx: JMP +5+xxxxxxxx + 0x00000000 // Relative destination address + }; + JCC_REL jcc = { + 0x0F, 0x80, // 0F8* xxxxxxxx: J** +6+xxxxxxxx + 0x00000000 // Relative destination address + }; +#endif + + UINT8 oldPos = 0; + UINT8 newPos = 0; + ULONG_PTR jmpDest = 0; // Destination address of an internal jump. + BOOL finished = FALSE; // Is the function completed? +#if defined(_M_X64) || defined(__x86_64__) + UINT8 instBuf[16]; +#endif + + ct->patchAbove = FALSE; + ct->nIP = 0; + + do + { + HDE hs; + UINT copySize; + LPVOID pCopySrc; + ULONG_PTR pOldInst = (ULONG_PTR)ct->pTarget + oldPos; + ULONG_PTR pNewInst = (ULONG_PTR)ct->pTrampoline + newPos; + + copySize = HDE_DISASM((LPVOID)pOldInst, &hs); + if (hs.flags & F_ERROR) + return FALSE; + + pCopySrc = (LPVOID)pOldInst; + if (oldPos >= sizeof(JMP_REL)) + { + // The trampoline function is long enough. + // Complete the function with the jump to the target function. +#if defined(_M_X64) || defined(__x86_64__) + jmp.address = pOldInst; +#else + jmp.operand = (UINT32)(pOldInst - (pNewInst + sizeof(jmp))); +#endif + pCopySrc = &jmp; + copySize = sizeof(jmp); + + finished = TRUE; + } +#if defined(_M_X64) || defined(__x86_64__) + else if ((hs.modrm & 0xC7) == 0x05) + { + // Instructions using RIP relative addressing. (ModR/M = 00???101B) + + // Modify the RIP relative address. + PUINT32 pRelAddr; + + // Avoid using memcpy to reduce the footprint. +#ifndef _MSC_VER + memcpy(instBuf, (LPBYTE)pOldInst, copySize); +#else + __movsb(instBuf, (LPBYTE)pOldInst, copySize); +#endif + pCopySrc = instBuf; + + // Relative address is stored at (instruction length - immediate value length - 4). + pRelAddr = (PUINT32)(instBuf + hs.len - ((hs.flags & 0x3C) >> 2) - 4); + *pRelAddr + = (UINT32)((pOldInst + hs.len + (INT32)hs.disp.disp32) - (pNewInst + hs.len)); + + // Complete the function if JMP (FF /4). + if (hs.opcode == 0xFF && hs.modrm_reg == 4) + finished = TRUE; + } +#endif + else if (hs.opcode == 0xE8) + { + // Direct relative CALL + ULONG_PTR dest = pOldInst + hs.len + (INT32)hs.imm.imm32; +#if defined(_M_X64) || defined(__x86_64__) + call.address = dest; +#else + call.operand = (UINT32)(dest - (pNewInst + sizeof(call))); +#endif + pCopySrc = &call; + copySize = sizeof(call); + } + else if ((hs.opcode & 0xFD) == 0xE9) + { + // Direct relative JMP (EB or E9) + ULONG_PTR dest = pOldInst + hs.len; + + if (hs.opcode == 0xEB) // isShort jmp + dest += (INT8)hs.imm.imm8; + else + dest += (INT32)hs.imm.imm32; + + // Simply copy an internal jump. + if ((ULONG_PTR)ct->pTarget <= dest + && dest < ((ULONG_PTR)ct->pTarget + sizeof(JMP_REL))) + { + if (jmpDest < dest) + jmpDest = dest; + } + else + { +#if defined(_M_X64) || defined(__x86_64__) + jmp.address = dest; +#else + jmp.operand = (UINT32)(dest - (pNewInst + sizeof(jmp))); +#endif + pCopySrc = &jmp; + copySize = sizeof(jmp); + + // Exit the function if it is not in the branch. + finished = (pOldInst >= jmpDest); + } + } + else if ((hs.opcode & 0xF0) == 0x70 + || (hs.opcode & 0xFC) == 0xE0 + || (hs.opcode2 & 0xF0) == 0x80) + { + // Direct relative Jcc + ULONG_PTR dest = pOldInst + hs.len; + + if ((hs.opcode & 0xF0) == 0x70 // Jcc + || (hs.opcode & 0xFC) == 0xE0) // LOOPNZ/LOOPZ/LOOP/JECXZ + dest += (INT8)hs.imm.imm8; + else + dest += (INT32)hs.imm.imm32; + + // Simply copy an internal jump. + if ((ULONG_PTR)ct->pTarget <= dest + && dest < ((ULONG_PTR)ct->pTarget + sizeof(JMP_REL))) + { + if (jmpDest < dest) + jmpDest = dest; + } + else if ((hs.opcode & 0xFC) == 0xE0) + { + // LOOPNZ/LOOPZ/LOOP/JCXZ/JECXZ to the outside are not supported. + return FALSE; + } + else + { + UINT8 cond = ((hs.opcode != 0x0F ? hs.opcode : hs.opcode2) & 0x0F); +#if defined(_M_X64) || defined(__x86_64__) + // Invert the condition in x64 mode to simplify the conditional jump logic. + jcc.opcode = 0x71 ^ cond; + jcc.address = dest; +#else + jcc.opcode1 = 0x80 | cond; + jcc.operand = (UINT32)(dest - (pNewInst + sizeof(jcc))); +#endif + pCopySrc = &jcc; + copySize = sizeof(jcc); + } + } + else if ((hs.opcode & 0xFE) == 0xC2) + { + // RET (C2 or C3) + + // Complete the function if not in a branch. + finished = (pOldInst >= jmpDest); + } + + // Can't alter the instruction length in a branch. + if (pOldInst < jmpDest && copySize != hs.len) + return FALSE; + + // Trampoline function is too large. + if ((newPos + copySize) > TRAMPOLINE_MAX_SIZE) + return FALSE; + + // Trampoline function has too many instructions. + if (ct->nIP >= ARRAYSIZE(ct->oldIPs)) + return FALSE; + + ct->oldIPs[ct->nIP] = oldPos; + ct->newIPs[ct->nIP] = newPos; + ct->nIP++; + + // Avoid using memcpy to reduce the footprint. +#ifndef _MSC_VER + memcpy((LPBYTE)ct->pTrampoline + newPos, pCopySrc, copySize); +#else + __movsb((LPBYTE)ct->pTrampoline + newPos, (LPBYTE)pCopySrc, copySize); +#endif + newPos += copySize; + oldPos += hs.len; + } while (!finished); + + // Is there enough place for a long jump? + if (oldPos < sizeof(JMP_REL) + && !IsCodePadding((LPBYTE)ct->pTarget + oldPos, sizeof(JMP_REL) - oldPos)) + { + // Is there enough place for a short jump? + if (oldPos < sizeof(JMP_REL_SHORT) + && !IsCodePadding((LPBYTE)ct->pTarget + oldPos, sizeof(JMP_REL_SHORT) - oldPos)) + { + return FALSE; + } + + // Can we place the long jump above the function? + if (!IsExecutableAddress((LPBYTE)ct->pTarget - sizeof(JMP_REL))) + return FALSE; + + if (!IsCodePadding((LPBYTE)ct->pTarget - sizeof(JMP_REL), sizeof(JMP_REL))) + return FALSE; + + ct->patchAbove = TRUE; + } + +#if defined(_M_X64) || defined(__x86_64__) + // Create a relay function. + jmp.address = (ULONG_PTR)ct->pDetour; + + ct->pRelay = (LPBYTE)ct->pTrampoline + newPos; + memcpy(ct->pRelay, &jmp, sizeof(jmp)); +#endif + + return TRUE; + } +} diff --git a/r5.cpp b/r5.cpp new file mode 100644 index 0000000..f0ccebb --- /dev/null +++ b/r5.cpp @@ -0,0 +1,536 @@ +#include + +#define DA_CODE(NAME, PAT, OFFS) dyn_addr::add_dynamic_address_code(_XS(NAME), _XSW(PAT), OFFS) +#define DA_PTR(NAME, PAT, OFFS, INSTR_OFFS, INSTR_LEN) dyn_addr::add_dynamic_address_ptr(_XS(NAME), _XSW(PAT), OFFS, INSTR_OFFS, INSTR_LEN) + +bool r5::setup_context() +{ + const auto get_process_info = []() -> bool + { + auto& process_info = g::p::context->m_process_info; + auto process_handle = win_api::get_module_handle(nullptr); + + if (process_handle == nullptr) + return false; + + process_info.base = mem::addr(process_handle).Base(); + + auto* process_dh = PIMAGE_DOS_HEADER{}; + auto* process_nth = PIMAGE_NT_HEADERS{}; + + process_dh = mem::addr(process_info.base).As(); + + if (process_dh->e_magic != IMAGE_DOS_SIGNATURE) + return false; + + process_nth = mem::addr(process_info.base).Add(process_dh->e_lfanew).As(); + + if (process_nth->Signature != IMAGE_NT_SIGNATURE) + return false; + + process_info.length = process_nth->OptionalHeader.SizeOfCode; + + return true; + }; + + const auto get_self_info = []() + { + auto decrypt = [](void* data, size_t length) + { + constexpr uint64_t header_encryption_key = 0xDE9644521; + + for (size_t i = 0; i < length; i++) + reinterpret_cast(data)[i] ^= header_encryption_key; + }; + + g::p::context->my_base = mem::addr(&__ImageBase).Base(); + + auto decrypted_dh = IMAGE_DOS_HEADER{ }; + auto decrypted_nth = IMAGE_NT_HEADERS{ }; + + memset(&decrypted_dh, 0, sizeof(decrypted_dh)); + memset(&decrypted_nth, 0, sizeof(decrypted_nth)); + + if (!util::read_memory(&decrypted_dh, g::p::context->my_base, sizeof(decrypted_dh))) + return false; + + decrypt(&decrypted_dh, sizeof(decrypted_dh)); + + if (decrypted_dh.e_magic != IMAGE_DOS_SIGNATURE) + return false; + + auto nth_address = g::p::context->my_base + decrypted_dh.e_lfanew; + + if(!util::read_memory(&decrypted_nth, nth_address, sizeof(decrypted_nth))) + return false; + + decrypt(&decrypted_nth, sizeof(decrypted_nth)); + + if (decrypted_nth.Signature != IMAGE_NT_SIGNATURE) + return false; + + g::p::context->my_length = decrypted_nth.OptionalHeader.SizeOfImage; + + return true; + }; + + g::p::context = stl::mem_alloc( sizeof(context_t) ); + + if (g::p::context == nullptr) + return false; + + memset(g::p::context, 0, sizeof(context_t)); + + if (!get_process_info()) + return false; + + if (!get_self_info()) + return false; + + g::build_hash = crc_calculate32(reinterpret_cast(g::p::context->my_base), g::p::context->my_length); + + return true; +} + +bool r5::setup_dyn_addrs() +{ + DA_PTR("ptr_local_player", L"48 8B 05 ? ? ? ? 48 0F 44 C7", 0, 0x3, 0x7); + DA_PTR("ptr_input", L"48 8B 05 ? ? ? ? 48 8D 0D ? ? ? ? 4C 8B 80 B8 00 00 00", 0, 0x3, 0x7); + DA_PTR("ptr_input_system", L"48 8B 05 ? ? ? ? 48 8D 15 ? ? ? ? 48 8B 08 4C 8B 81", 0, 0x3, 0x7); + DA_PTR("ptr_global_vars", L"4C 8B 05 ? ? ? ? 0F 57 C9", 0, 0x3, 0x7); + DA_PTR("ptr_engine_vgui", L"48 8B 0D ? ? ? ? 48 83 C4 40", 0, 0x3, 0x7); + DA_PTR("ptr_game_movement", L"48 89 05 ? ? ? ? 48 85 C9 74 3C", 0, 0x3, 0x7); + DA_PTR("ptr_engine_client", L"48 8B 05 ? ? ? ? 4C 8D 25 ? ? ? ? 48 8D 15", 0, 0x3, 0x7); + DA_PTR("ptr_convar_mgr", L"48 8B 3D ? ? ? ? 48 8B D9 48 8D 0D ? ? ? ? 48 8B 07 4C 8B 80 ? ? ? ? 48 3B C1", 0, 0x3, 0x7); + DA_PTR("ptr_engine_time", L"F3 0F 11 05 ? ? ? ? 83 F8 FF 74 29", 0, 0x4, 0x8); + DA_PTR("ptr_mat_system_surface", L"4C 8B 1D ? ? ? ? 49 8B 03 49 3B C7", 0, 0x3, 0x7); + DA_PTR("ptr_net_chan", L"48 8B 0D ? ? ? ? 0F 57 F6 0F 2F B1 ? ? ? ? 77 21", 0, 0x3, 0x7); + DA_PTR("ptr_view_render", L"48 8B 3D ? ? ? ? 48 8D 0D ? ? ? ? 4C 89 3D", 0, 0x3, 0x7); + DA_PTR("ptr_last_out_cmd", L"44 8B 2D ? ? ? ? 44 8B 25 ? ? ? ? 48 85 C0 74 05 8B 50 40 EB 03", 0, 0x3, 0x7); + DA_PTR("ptr_engine_trace", L"48 8B 0D ? ? ? ? 48 8D 55 10 48 8B 01 4D 85 F6 74 18", 0, 0x3, 0x7); + DA_PTR("ptr_game_instance_data", L"48 8B 0D ? ? ? ? 48 C1 E2 08 48 0B D0 48 03 15 ? ? ? ? 48 8B 01 48 8B 5C 24 ? 48 83 C4 28 48 FF 60 70 48 8B 0D", 0, 0x3, 0x7); + DA_PTR("ptr_model_info", L"48 8B 0D ? ? ? ? 44 8B C3 44 8B C8 48 89 74 24 ? 49 8B D6 E8", 0, 0x3, 0x7); + DA_PTR("ptr_client_mode", L"48 8B 05 ? ? ? ? 48 85 C0 74 0A F3 0F 11 48 ? 48 83 C4 28 C3", 0, 0x3, 0x7); + DA_PTR("ptr_file_system", L"48 8B 1D ? ? ? ? 4C 8D 0D ? ? ? ? 4C 8D 05", 0, 0x3, 0x7); + + DA_PTR("cursor_enable", L"0F B6 05 ? ? ? ? 84 C0 0F 85 ? ? ? ? 48 8B 01 48 3B C3", 0, 0x3, 0x7); + DA_PTR("crosshair_state", L"83 3D ? ? ? ? ? 0F 85 ? ? ? ? 49 8B CD E8 ? ? ? ? A9 ? ? ? ? 0F 85 ? ? ? ? 83 F8 01 0F 84 ? ? ? ? 41 80 BD", 0, 0x2, 0x7); + + DA_PTR("fn_cl_move_send", L"E8 ? ? ? ? EB 21 0F 57 C0 F3 0F 5A C6", 0, 0x1, 0x5); + DA_PTR("fn_create_interface", L"E8 ? ? ? ? 48 89 05 ? ? ? ? 48 83 3D ? ? ? ? ? 0F 84 ? ? ? ? 33 D2", 0, 0x1, 0x5); + DA_PTR("fn_write_user_cmd", L"E8 ? ? ? ? 80 7D B4 00 0F 94 C0", 0, 0x1, 0x5); + DA_PTR("fn_paint_end", L"E8 ? ? ? ? 49 8B 8E ? ? ? ? 48 85 C9 0F 84 ? ? ? ? 40 F6 C5 01", 0, 0x1, 0x5); + DA_PTR("fn_set_model_index", L"E8 ? ? ? ? 48 8B 8B ? ? ? ? 8B 91 ? ? ? ? 33 ED 83 FA FF", 0, 0x1, 0x5); + DA_PTR("fn_set_abs_angles", L"E8 ? ? ? ? 48 8B 83 ? ? ? ? 48 8D 8B ? ? ? ? F3 0F 10 A8", 0, 0x1, 0x5); + + DA_CODE("fn_seq_desc", L"4C 8B 41 ? 4D 85 C0 75 ? 4C 8B 41 ? 33 C0 41 3B 90 ? ? ? ? 0F 42 C2 48 98", 0); + DA_CODE("fn_set_legendary_view_model", L"40 53 48 83 EC 20 48 8B D9 83 FA 10 7C 17 41 B8", 0); + DA_CODE("fn_get_model", L"40 53 48 83 EC ? 48 83 B9 ? ? ? ? ? 48 8B D9 75 ? 48 8B 41 ?", 0); + DA_CODE("fn_set_model", L"48 89 5C 24 ? 48 89 6C 24 ? 48 89 74 24 ? 57 48 81 EC ? ? ? ? 48 8B EA 48 8B F1 48 85 C9 75 0E 48 8D 0D", 0); + + DA_CODE("paint_start_drawing", L"48 8B C4 53 56 57 48 81 EC ? ? ? ? 0F 29 70 D8 48 8D", 0); + DA_CODE("paint_finish_drawing", L"40 53 48 83 EC 20 48 8B 0D ? ? ? ? C6 05 ? ? ? ? ? 48 8B", 0); + DA_CODE("view_render_start", L"48 8B C4 48 89 48 08 53 55 56 57 41 55 48 81 EC ? ? ? ? 0F 29 70 B8 4C 8B E9", 0); + DA_CODE("cl_move", L"48 81 EC ? ? ? ? 83 3D ? ? ? ? ? 44 0F 29 54 24", 0); + + DA_CODE("silent1", L"F3 0F 11 87 ? ? ? ? 89 44 24 38 F3 0F 10 44 24 ? F3 0F 11 87", 0); + + if (!dyn_addr::grab_all()) + return false; + + if (!dyn_offs::initialize()) + return false; + + return true; +} + +bool r5::setup_interfaces_early() +{ + ix::file_system = *reinterpret_cast(DYN_ADDR("ptr_file_system")); + + log_info("file_system_ptr => %p", ix::file_system); + + return true; +} + +bool r5::setup_interfaces() +{ + const auto grab_interface = [](const char* name, void** result) + { + *result = respawn::create_interface(name); + + if ((*result)) + { + log_info("grabbed interface '%s' at address '%p'.", name, *result); + } + else + { + log_info("failed to grab interface '%s'.", name); + } + + return !( (*result) == nullptr ); + }; + + if (!grab_interface(_XS("VClient018"), (void**)&ix::base_client)) + return false; + + if (!grab_interface(_XS("VClientEntityList003"), (void**)&ix::entity_list)) + return false; + + ix::input = reinterpret_cast(DYN_ADDR("ptr_input")); + ix::input_system = *reinterpret_cast(DYN_ADDR("ptr_input_system")); + ix::global_vars = *reinterpret_cast(DYN_ADDR("ptr_global_vars")); + ix::local_player_ptr = reinterpret_cast(DYN_ADDR("ptr_local_player")); + ix::engine_vgui = *reinterpret_cast(DYN_ADDR("ptr_engine_vgui")); + ix::game_movement = reinterpret_cast(DYN_ADDR("ptr_game_movement")); + ix::shared_client = *reinterpret_cast(DYN_ADDR("ptr_client_mode")); + ix::engine_client = reinterpret_cast(DYN_ADDR("ptr_engine_client")); + ix::engine_trace = *reinterpret_cast(DYN_ADDR("ptr_engine_trace")); + ix::mat_system_surface = *reinterpret_cast(DYN_ADDR("ptr_mat_system_surface")); + ix::view_render = *reinterpret_cast(DYN_ADDR("ptr_view_render")); + ix::model_info = *reinterpret_cast(DYN_ADDR("ptr_model_info")); + ix::net_chan = reinterpret_cast(DYN_ADDR("ptr_net_chan")); + ix::cvar_mgr = *reinterpret_cast(DYN_ADDR("ptr_convar_mgr")); + + gv::engine_time = reinterpret_cast(DYN_ADDR("ptr_engine_time")); + gv::input_disable = reinterpret_cast(DYN_ADDR("cursor_enable")); + gv::crosshair_state = reinterpret_cast(DYN_ADDR("crosshair_state")); + + return true; +} + +bool r5::setup_convars() +{ + if ((cvar::time_scale = ix::cvar_mgr->find(_XS("host_timescale"))) == nullptr) return false; + if ((cvar::third_person = ix::cvar_mgr->find(_XS("thirdperson_override"))) == nullptr) return false; + if ((cvar::draw_view_model = ix::cvar_mgr->find(_XS("r_drawviewmodel"))) == nullptr) return false; + if ((cvar::move_use_dt = ix::cvar_mgr->find(_XS("cl_move_use_dt"))) == nullptr) return false; + + return true; +} + +void r5::initialize_full() +{ + if (!setup_interfaces()) + return report_failure(); + + if (!g::p::netvar_mgr.initialize()) + { + log_info_("failed to initialize networked variables.\n"); + return report_failure(); + } + + g::p::ent_cache.initialize(); + + g::p::window_mgr.add({ 5, 250 }, { 450, 500 }); + g::p::window_mgr.add({ 250, 15 }, { 110, 5 }); + g::p::window_mgr.add({ 275, 500 }, { 250, 0 }); + g::p::window_mgr.add({5, 750}, { 210, 5 }); + + if (!setup_convars()) + return report_failure(); + + if (!respawn::initialize()) + return report_failure(); + + if (!hooks::initialize()) + return report_failure(); + + log_info_("r5trainer has been initialized successfully."); + + g::p::context->m_initialized = true; +} + +void r5::initialize() +{ + log_call(); + + if (!setup_context()) + return report_failure(); + + log_info("context is located at %p.", g::p::context); + log_info("process_base= %p, process_len= %p.", + mem::addr(g::p::context->m_process_info.base).Ptr(), + mem::addr(g::p::context->m_process_info.length).Ptr() + ); + + g::return_address_gadget = shared::sig::FindInImageEx( + g::p::context->m_process_info.base, + _XS(".text"), + _XSW(L"FF 26") + ); + + if (!g::return_address_gadget) + { + log_info_("failed to find ret_addr gadget inside target process."); + return report_failure(); + } + + log_info_("the ret_addr gadget is located at %p.", + (void*)g::return_address_gadget); + + if (!setup_dyn_addrs() || !setup_interfaces_early()) + return report_failure(); + + if (!hvi::query_info(hvi::HVI_AC_CONTEXT_EAC, (void**)&g::p::acc::eac)) + { + log_info_("failed to query AC_CONTEXT for EAC.\n"); + return report_failure(); + } + + if (g::p::acc::eac->launched && g::p::acc::eac->internal_module.found) + { + log_info("internal EAC module base= %p, length=%p.\n", + g::p::acc::eac->internal_module.base, g::p::acc::eac->internal_module.length); + } + else + { + log_info_("failed to find EAC internal module."); + return report_failure(); + } + + if (!hooks::initialize_early()) + { + log_info_("failed to initialize hooks (early)."); + return report_failure(); + } + + // + // Wait for the game to initialize fully. + // TODO: Find a better way to determine this desired state has been reached! + // + + win_api::rebuilt::sleep( SECONDS_IN_MS(12) ); + + initialize_full(); +} + +void r5::shutdown() +{ + log_call(); + + // + // ... + // +} + +bool r5::is_within_eac(void* address) +{ + const auto base = mem::addr(address).Base(); + const auto ctx = g::p::acc::eac; + + if (!base || !ctx->launched || !ctx->internal_module.found) + return false; + + const auto im_begin = ctx->internal_module.base; + const auto im_end = mem::addr(im_begin).Add(ctx->internal_module.length).Base(); + + return (base >= im_begin && base <= im_end); +} + +void r5::think() +{ + const auto maintain_crosshair_visibility = []() + { + using ch_state = respawn::crosshair_states; + *gv::crosshair_state = cfg::other_disable_default_crosshair ? ch_state::CROSSHAIR_STATE_HIDE_ALL : ch_state::CROSSHAIR_STATE_SHOW_ALL; + }; + + const auto maintain_view_model_visibility = []() + { + static bool previous{ }; + + if (previous != cfg::other_disable_view_model) + { + cvar::draw_view_model->m_value_numeric = !cfg::other_disable_view_model; + + previous = cfg::other_disable_view_model; + } + }; + + maintain_crosshair_visibility(); + maintain_view_model_visibility(); +} + +void r5::maintain_screen_size() +{ + int temp_w{ }, temp_h{ }; + ix::mat_system_surface->get_screen_size(temp_w, temp_h); + + if (temp_w != g::p::screen.w || temp_h != g::p::screen.h) + { + g::p::screen.w = temp_w; + g::p::screen.h = temp_h; + + LOGGER_MSG_WARN(10.f, "game resolution has changed."); + } +} + +void r5::on_game_state_change(bool current, bool previous) +{ + LOGGER_MSG_INFO(5.f, "game state has changed from %i to %i.", previous, current); + + maintain_screen_size(); + + if (current) + { + g::p::game_mode = respawn::get_game_mode(); + } + + memset(&g::p::cache, 0, sizeof(g::p::cache)); + g::p::ent_cache.reset(); +} + +bool build_in_game_context(respawn::user_cmd_t* cmd, respawn::c_net_chan** out_nc, respawn::c_player** out_lp, respawn::c_weapon** out_lw) noexcept +{ + if (cmd == nullptr || !cmd->command_number) + return false; + + if (!ix::engine_client->is_in_game()) + return false; + + auto net_chan = respawn::net_chan(); + + if (net_chan == nullptr) + return false; + + if(out_nc) *out_nc = net_chan; + + auto local_player = respawn::get_local_player(); + + if (local_player == nullptr || !respawn::is_player(local_player)) + return false; + + if (out_lp) *out_lp = local_player; + + if (respawn::is_alive(local_player) && !respawn::is_knocked(local_player)) + { + auto local_weapon = local_player->get_active_weapon(); + + if (local_weapon) + { + if (out_lw) *out_lw = local_weapon; + + g::is_playing = true; + } + } + else + g::is_playing = false; + + return true; +} + +void r5::on_createmove(respawn::user_cmd_t* user_cmd) +{ + g::p::input_mgr.sync(&si::create_move); + + if (g::is_in_game_last != respawn::is_playing()) + { + on_game_state_change(respawn::is_playing(), g::is_in_game_last); + + g::is_in_game_last = respawn::is_playing(); + } + + respawn::c_net_chan* net_chan{ }; + respawn::c_player* me{ }; + respawn::c_weapon* my_wpn{ }; + + g::is_in_game = build_in_game_context(user_cmd, &net_chan, &me, &my_wpn); + + auto is_choked = net_chan->stop_sending(); + + net_chan->stop_sending() = false; + + math::Angle3 old_angles = user_cmd->viewangles; + float old_move_forward = user_cmd->forwardmove, old_move_side = user_cmd->sidemove; + + respawn::on_update_cache(me, my_wpn, net_chan); + + f::aim.create_move(me, user_cmd); + f::movement.create_move(me, user_cmd); + f::glow.create_move(me, user_cmd); + f::skin_changer.create_move(me, user_cmd); + + if (respawn::is_playing() && my_wpn) + { + if (cfg::aim_silent == 2 && f::aim.is_weapon_compatible(my_wpn)) + { + bool wants_attack{ }; + + if (!is_choked) + { + user_cmd->viewangles = old_angles; + user_cmd->forwardmove = old_move_forward; + user_cmd->sidemove = old_move_side; + + if (user_cmd->buttons & IN_ATTACK) + { + wants_attack = true; + user_cmd->buttons &= ~IN_ATTACK; + } + } + + if ((user_cmd->buttons & IN_ATTACK || wants_attack) && my_wpn->can_fire(me)) + net_chan->stop_sending() = true; + } + + if (cfg::other_bullet_time && (user_cmd->buttons & IN_ATTACK && !my_wpn->can_fire(me))) + user_cmd->buttons &= ~IN_ATTACK; + } +} + +void r5::on_clmove() +{ + if (!respawn::is_playing()) + return; + + // + // ... + // + + think(); +} + +void r5::on_paint() +{ + g::p::input_mgr.update(); + + respawn::start_drawing(ix::mat_system_surface); + + on_render(); + + respawn::finish_drawing(); +} + +void r5::on_render() +{ + g::curtime = ix::global_vars->Curtime; + + g::p::input_mgr.sync(&si::paint); + + if (!g::p::screen.w && !g::p::screen.h) + ix::mat_system_surface->get_screen_size(g::p::screen.w, g::p::screen.h); + + f::logger.paint(); + f::esp.paint(); + f::aim.paint(); + g::p::window_mgr.paint(); +} + +void r5::on_fsn(int stage) +{ + if (!respawn::is_playing()) + return; + + auto* const me = respawn::get_local_player(); + + if (me == nullptr) + return; + + f::skin_changer.frame_stage_notify(stage, me); +} + +void r5::on_window_proc(UINT msg, WPARAM w_param, LPARAM l_param) +{ + g::p::input_mgr.window_proc(msg, w_param, l_param); +} diff --git a/render.cpp b/render.cpp new file mode 100644 index 0000000..2cfeac3 --- /dev/null +++ b/render.cpp @@ -0,0 +1,70 @@ +#include + +size_t c_render::get_text_width(const char* text, size_t font_size) +{ + const auto count = stl::strlen(text); + + return (count * font_size) / 2; +} + +void c_render::draw_rect(respawn::color_t color, int x1, int y1, int x2, int y2, int opacity) +{ + ix::mat_system_surface->draw_set_color(color.r, color.g, color.b, opacity); + ix::mat_system_surface->draw_outlined_rect(x1, y1, x2, y2); +} + +void c_render::draw_rect_filled(respawn::color_t color, int x1, int y1, int x2, int y2, int opacity) +{ + ix::mat_system_surface->draw_set_color(color.r, color.g, color.b, opacity); + ix::mat_system_surface->draw_filled_rect(x1, y1, x2, y2); +} + +void c_render::draw_line(respawn::color_t color, int x1, int y1, int x2, int y2, int opacity) +{ + ix::mat_system_surface->draw_set_color(color.r, color.g, color.b, opacity); + ix::mat_system_surface->draw_line(x1, y1, x2, y2); +} + +void c_render::draw_rect_bordered(respawn::color_t sColor, float flX0, float flY0, float flX1, float flY1, int opacity) +{ + draw_rect({ 5, 5, 5 }, flX0 - 1.0f, flY0 - 1.0f, flX1 + 1.0f, flY1 + 1.0f, opacity); + draw_rect(sColor, flX0, flY0, flX1, flY1, opacity); + draw_rect({ 5, 5, 5 }, flX0 + 1.0f, flY0 + 1.0f, flX1 - 1.0f, flY1 - 1.0f, opacity); +} + +void c_render::draw_circle(respawn::color_t color, int x, int y, int radius, int segments, int opacity) +{ + ix::mat_system_surface->draw_set_color(color.r, color.g, color.b, opacity); + ix::mat_system_surface->draw_outlined_circle(x, y, radius, segments); +} + +void c_render::draw_text(respawn::color_t color, ulong font, int size, int x, int y, const char* text) +{ + ix::mat_system_surface->draw_text(font, size, x, y, color.r, color.g, color.b, 255, 0, text); +} + +void c_render::draw_text_ex(respawn::color_t color, ulong font, int size, int x, int y, const char* text, ...) +{ + va_list list; + char buffer[512]; + + va_start(list, text); + LI_FN(wvsprintfA).cached()(buffer, text, list); + va_end(list); + + draw_text(color, font, size, x, y, buffer); +} + +void c_render::draw_text_centered(respawn::color_t color, ulong font, int size, int x, int y, const char* text, ...) +{ + const auto width = get_text_width(text, size); + + va_list list; + char buffer[512]; + + va_start(list, text); + LI_FN(wvsprintfA).cached()(buffer, text, list); + va_end(list); + + return draw_text_ex(color, font, size, x - (width / 2.f), y, buffer); +} diff --git a/rspn/entity.cpp b/rspn/entity.cpp new file mode 100644 index 0000000..6e2cbea --- /dev/null +++ b/rspn/entity.cpp @@ -0,0 +1,83 @@ +#include + +using namespace respawn; + +void* c_entity::get_model() +{ + auto address = DYN_ADDR("fn_get_model"); + using type = void* (__thiscall*)(void*); + + return reinterpret_cast(address)(this); +} + +bool c_entity::set_model(const char* name) +{ + auto address = DYN_ADDR("fn_set_model"); + using type = bool(__thiscall*)(void*, const char*); + + return reinterpret_cast(address)(this, name); +} + +bool c_entity::set_model_index(int index) +{ + auto address = DYN_ADDR("fn_set_model_index"); + using type = bool(__thiscall*)(void*, int); + + return reinterpret_cast(address)(this, index); +} + +void c_entity::set_abs_angles(math::Angle3 angle) +{ + auto address = DYN_ADDR("fn_set_abs_angles"); + using type = void(__thiscall*)(void*, math::Angle3); + + return reinterpret_cast(address)(this, angle); +} + +uint32_t c_entity::get_sequence_activity(int sequence) +{ + auto model = get_model(); + + if (model) + { + auto desc = respawn::seq_desc(model, sequence); + + if (desc) + { + auto name = desc->pszActivityName(); + + if (name && *name) + return util::string_hash(name, stl::strlen(name)); + } + } + + return UINT32_MAX; +} + +uint32_t c_entity::get_activity_sequence(uint32_t activity) +{ + if (activity != UINT32_MAX) + { + auto model = get_model(); + + if (model) + { + auto seqcount = get_sequence_count(model); + + for (int sequence = 0; sequence < seqcount; sequence++) + { + auto desc = respawn::seq_desc(model, sequence); + + if (desc) + { + auto name = desc->pszActivityName(); + + if (name && *name && util::string_hash(name, stl::strlen(name)) == activity) + return sequence; + } + } + } + } + + return UINT32_MAX; +} diff --git a/rspn/netvar.cpp b/rspn/netvar.cpp new file mode 100644 index 0000000..7fa16ae --- /dev/null +++ b/rspn/netvar.cpp @@ -0,0 +1,88 @@ +#include + +bool c_netvar_manager::initialize() +{ + auto* const head = ix::base_client->get_all_classes(); + + if (head == nullptr) + return false; + + log_info_("initializing the netvar table."); + + for (auto* client_class = head; client_class != nullptr; client_class = client_class->next) + { + auto* const table = client_class->table; + + if (table == nullptr) + continue; + + process_table(table); + } + + log_info("netvar table was set up, there is a total of %i tables.", m_list.count()); + + return true; +} + +bool c_netvar_manager::is_prop_garbage(const char* name) +{ + if (stl::strstr(name, _XS("baseclass")) || + stl::strstr(name, _XS("0")) || + stl::strstr(name, _XS("1")) || + stl::strstr(name, _XS("2"))) + return true; + + return false; +} + +void c_netvar_manager::process_table(respawn::recv_table* table) +{ + auto** const head = table->props; + + if (head == nullptr) + return; + + netvar_table_t table_entry{}; + + stl::strcpy(table_entry.name, table->name); + + for (auto i = 0ull; i < table->num_props; i++) + { + auto* const prop = head[i]; + + // + // validate the prop pointer, at first. + // + if (prop == nullptr) + continue; + + // + // validate that the prop is not garbage data. + // + if (is_prop_garbage(prop->name)) + continue; + + // + // process the actual prop here. + // + process_prop(table, prop, table_entry.props); + + // + // if this prop has a table, then recursively process it. + // + if (prop->data_table != nullptr) + process_table(prop->data_table); + } + + m_list.insert(table_entry); +} + +void c_netvar_manager::process_prop(respawn::recv_table* table, respawn::recv_prop* prop, stl::c_linked_list& list) +{ + netvar_t entry{}; + + stl::strcpy(entry.name, prop->name); + entry.offset = prop->offset; + + list.insert(entry); +} diff --git a/rspn/player.cpp b/rspn/player.cpp new file mode 100644 index 0000000..3a583e4 --- /dev/null +++ b/rspn/player.cpp @@ -0,0 +1,68 @@ +#include + +using namespace respawn; + +bool c_player::is_visible() noexcept +{ + const auto curr_time = *gv::engine_time; + const auto visible_time = last_visible_time(); + const auto visible_time_cp = visible_time + 1.f; + + if (visible_time_cp >= curr_time) + { + return true; + } + + return false; +} + +bool c_player::get_bone_position(size_t index, math::Vector3& result) noexcept +{ + auto my_origin = origin(); + auto bone_cache_base = *(uintptr_t*)(BASE_OF(this) + 0xF38); + auto bone_cache_offs = (index * 0x30); + + if (!bone_cache_base) + return false; + + result = + { + my_origin.x + *(float*)(bone_cache_base + bone_cache_offs + 0xCC), + my_origin.y + *(float*)(bone_cache_base + bone_cache_offs + 0xDC), + my_origin.z + *(float*)(bone_cache_base + bone_cache_offs + 0xEC), + }; + + return true; +} + +c_weapon* c_player::get_active_weapon() noexcept +{ + int wpn_index{ }; + ulong wpn_handle = latest_primary_weapon(); + + if (!wpn_handle) + return nullptr; + + wpn_index = ENTITY_INDEX_BY_HANDLE(wpn_handle); + + if (!wpn_index) + return nullptr; + + return ix::entity_list->get_client_entity(wpn_index); +} + +c_view_model* c_player::get_view_model() noexcept +{ + int vm_index{ }; + ulong vm_handle = view_model(); + + if (!vm_handle) + return nullptr; + + vm_index = ENTITY_INDEX_BY_HANDLE(vm_handle); + + if (!vm_index) + return nullptr; + + return ix::entity_list->get_client_entity(vm_index); +} diff --git a/rspn/respawn.cpp b/rspn/respawn.cpp new file mode 100644 index 0000000..2734916 --- /dev/null +++ b/rspn/respawn.cpp @@ -0,0 +1,434 @@ +#include + +bool respawn::initialize() +{ + _ident_table.insert({ _XC(0x726579616c70), entity_types::PLAYER }); + _ident_table.insert({ _XC(0x6d6d75645f63706e), entity_types::DUMMIE }); + _ident_table.insert({ _XC(0x776f72705f63706e), entity_types::PROWLER }); + _ident_table.insert({ _XC(0x7275735f706f7270), entity_types::PROP_SURVIVAL }); + _ident_table.insert({ _XC(0x6e79645f706f7270), entity_types::PROP_DYNAMIC }); + _ident_table.insert({ _XC(0x7263735f706f7270), entity_types::PROP_SCRIPT }); + _ident_table.insert({ _XC(0x6165645f706f7270), entity_types::PROP_DEATH_BOX }); + + _heirloom_table.insert(_XS("mdl/weapons/kunai/ptpov_kunai_wraith.rmdl")); + _heirloom_table.insert(_XS("mdl/weapons/bloodhound_axe/ptpov_bloodhound_axe.rmdl")); + _heirloom_table.insert(_XS("mdl/weapons/drumstick/ptpov_baton_lifeline.rmdl")); + _heirloom_table.insert(_XS("mdl/weapons/pathfinder_gloves/ptpov_pathfinder_gloves.rmdl")); + _heirloom_table.insert(_XS("mdl/weapons/octane_knife/ptpov_octane_knife.rmdl")); + _heirloom_table.insert(_XS("mdl/weapons/mirage_heirloom/ptpov_mirage_heirloom.rmdl")); + _heirloom_table.insert(_XS("mdl/weapons/caustic_heirloom/ptpov_caustic_heirloom.rmdl")); + _heirloom_table.insert(_XS("mdl/weapons/gibraltar_heirloom/gibraltar_heirloom_v.rmdl")); + _heirloom_table.insert(_XS("mdl/weapons/bangalore_heirloom/ptpov_bangalore_heirloom.rmdl")); + _heirloom_table.insert(_XS("mdl/weapons/revenant_heirloom/revenant_heirloom_v21_base_v.rmdl")); + _heirloom_table.insert(_XS("mdl/weapons/rampart_heirloom/ptpov_rampart_heirloom.rmdl")); + _heirloom_table.insert(_XS("mdl/weapons/wattson_heirloom/wattson_heirloom_v21_base_v.rmdl")); + + return true; +} + +respawn::c_player* respawn::get_local_player() +{ + if (!ix::engine_client->is_in_game()) + return nullptr; + + const auto index = ix::engine_client->get_local_player(); + const auto result = ix::entity_list->get_client_entity(index); + + if (result == nullptr || !respawn::is_player(result)) + return nullptr; + + return result; +} + +respawn::color_t respawn::get_player_color(respawn::c_player* player) +{ + const auto& local_player = g::p::cache.local_player; + + if (player == nullptr || player->life_state() != 0) + return colors::white; + + // + // dummy + // skip do bleed out checks and such. + // + if (respawn::is_dummy(player)) + return colors::yellow; + + // + // bleeding out + // + if (player->bleed_out_state() != 0) + return colors::red; + + // + // team mate + // + if (is_teammate(player)) + return colors::cyan; + + // + // opponent + // + return colors::yellow; +} + +void* get_create_interface() +{ + using fn = void* (__fastcall)(); + + const auto fn_address = dyn_addr::get_dynamic_address(_XS("fn_create_interface")); + auto* const fn_ptr = mem::addr(fn_address).As(); + + return fn_ptr(); +} + +void* respawn::create_interface(const char* name) +{ + auto* const fn_ptr = mem::addr(get_create_interface()).As(); + + if (fn_ptr == nullptr) + return nullptr; + + return fn_ptr(name, 0); +} + +int respawn::get_sequence_count(void* model) +{ + auto v6 = *(uint64_t*)(BASE_OF(model) + 16); + + int numseq = v6 ? *(uint32_t*)(v6 + 32) : *(uint32_t*)(*(uint64_t*)(BASE_OF(model) + 8) + 192i64); + + return numseq; +} + +respawn::mstudioseqdesc_t* respawn::seq_desc(void* model, int sequence) +{ + using fn = mstudioseqdesc_t* (__fastcall*)(void*, int); + + const auto fn_address = dyn_addr::get_dynamic_address(_XS("fn_seq_desc")); + auto* const fn_ptr = mem::addr(fn_address).As(); + + return fn_ptr(model, sequence); +} + +respawn::entity_types respawn::get_entity_type(c_entity* entity) +{ + auto identifier = entity->identifier(); + + if (!identifier) + return entity_types::NONE; + + auto hash = *(uint64_t*)( identifier ); + auto result = respawn::entity_types{}; + + for (auto i = 0ull; i < _ident_table.count(); i++) + { + auto* const entry = _ident_table[i]; + + if (entry == nullptr) + continue; + + if (hash == _XC(entry->first)) + return entry->second; + } + + return entity_types::UNKNOWN; +} + +uint64_t respawn::get_entity_identifier(c_entity* entity) +{ + auto identifier = entity->identifier(); + + if (!identifier) + return 0; + + auto hash = *(uint64_t*)(identifier); + + return hash; +} + +bool respawn::is_player(respawn::c_entity* entity, bool player, bool dummy) +{ + auto type = get_entity_type(entity); + + if ((player && type == entity_types::PLAYER) || + (dummy && type == entity_types::DUMMIE) + ) + return true; + + return false; +} + +bool respawn::is_survival_prop(respawn::c_entity* entity) +{ + return get_entity_type(entity) == entity_types::PROP_SURVIVAL; +} + +bool respawn::is_of_type(respawn::c_entity* entity, const char* name) +{ + return false; +} + +bool respawn::is_alive(respawn::c_player* player) +{ + return (player->life_state() == LIFE_ALIVE); +} + +bool respawn::is_knocked(respawn::c_player* player) +{ + return (player->bleed_out_state() != NULL); +} + +respawn::game_modes respawn::get_game_mode() +{ + const auto address = DYN_ADDR("ptr_game_instance_data"); + + if (address) + { + auto base = *(uintptr_t*)address; + + if (base) + { + auto name = *(const char**)(base + 0x58); + auto length = stl::strlen(name); + + if (length) + { + auto hash = crc_calculate32(name, length); + + switch (hash) + { + case 0xe765d4cd: return game_modes::survival; + case 0xeddb2c4b: return game_modes::control; + case 0x0a235588: return game_modes::arenas; + } + } + } + } + + return game_modes::invalid; +} + +void respawn::start_drawing(respawn::c_mat_system_surface* mssf) +{ + if (mssf == nullptr) + return; + + using fn = void(__fastcall*)(void*); + + const auto address = dyn_addr::get_dynamic_address(_XS("paint_start_drawing")); + const auto function = reinterpret_cast(address); + + if (!address || !function) + return; + + return function(mssf); +} + +void respawn::finish_drawing() +{ + using fn = void(__fastcall*)(); + + const auto address = dyn_addr::get_dynamic_address(_XS("paint_finish_drawing")); + const auto function = reinterpret_cast(address); + + if (!address || !function) + return; + + return function(); +} + +bool respawn::world_to_screen(math::Vector3& vIn, math::Vector3& vOut) +{ + auto pvMatrix = ix::view_render->get_view_matrix(); + + if (pvMatrix == nullptr) + return false; + + auto vMatrix = *pvMatrix; + + vOut.x = vMatrix.m[0][0] * vIn.x + vMatrix.m[0][1] * vIn.y + vMatrix.m[0][2] * vIn.z + vMatrix.m[0][3]; + vOut.y = vMatrix.m[1][0] * vIn.x + vMatrix.m[1][1] * vIn.y + vMatrix.m[1][2] * vIn.z + vMatrix.m[1][3]; + + float w = vMatrix.m[3][0] * vIn.x + vMatrix.m[3][1] * vIn.y + vMatrix.m[3][2] * vIn.z + vMatrix.m[3][3]; + + if (w < 0.01) + return false; + + float invw = 1.0f / w; + + vOut.x *= invw; + vOut.y *= invw; + + const auto Cl_width = g::p::screen.w; + const auto Cl_height = g::p::screen.h; + + auto x = static_cast(Cl_width) / 2.f; + auto y = static_cast(Cl_height) / 2.f; + + x += 0.5f * vOut.x * Cl_width + 0.5f; + y -= 0.5f * vOut.y * Cl_height + 0.5f; + + vOut.x = x; + vOut.y = y; + + return true; +} + +void respawn::on_update_cache(respawn::c_player* me, respawn::c_weapon* my_wpn, respawn::c_net_chan* nc) +{ + auto& cache = g::p::cache; + + auto& local_player_data = cache.local_player; + auto& local_weapon_data = cache.local_weapon; + + auto& net_chan_data = cache.net_chan; + + local_player_data.index = ix::engine_client->get_local_player(); + local_player_data.address = mem::addr(me).Base(); + local_player_data.team_number = me->team_number(); + local_player_data.origin = me->origin(); + local_player_data.eye_angle = me->eye_angles(); + local_player_data.zooming = me->is_zooming(); + local_player_data.shoot_pos = me->view_offset(); + + if ( !(my_wpn == nullptr) ) + { + local_weapon_data.address = mem::addr(my_wpn).Base(); + local_weapon_data.reloading = my_wpn->is_reloading(); + local_weapon_data.next_primary_attack = my_wpn->next_primary_attack(); + local_weapon_data.next_ready_time = my_wpn->next_ready_time(); + local_weapon_data.can_fire = my_wpn->can_fire(me); + } + + net_chan_data.out_sequence_nr = nc->out_sequence_nr(); + net_chan_data.num_choked_packets = nc->num_choked_packets(); +} + +bool respawn::is_teammate(c_player* player) +{ + if (player == nullptr) + return false; + + const auto& lp_data = g::p::cache.local_player; + const auto is_control = (g::p::game_mode == game_modes::control); + + if (is_control) + { + auto convert_team = [](int num) + { + return ( (num % 2) ? 1: 2 ); + }; + + return (convert_team(player->team_number()) == convert_team(lp_data.team_number)); + } + + return (player->team_number() == lp_data.team_number); +} + +bool respawn::get_entity_center_pos(respawn::c_entity* entity, math::Vector3& result) +{ + if (entity == nullptr) + return false; + + auto collision = entity->collision(); + + if (collision == nullptr) + return false; + + auto mins = collision->vec_mins(); + auto maxs = collision->vec_maxs(); + + result = entity->origin(); + result.z += (mins.z + maxs.z) * 0.5f; + + return true; +} + +void respawn::script::dump_to_disk(const char* name, char* buffer, size_t length) +{ + if (!name || !buffer || !length) + { + log_info_("invalid params!"); + return; + } + + char path_fmt[MAX_PATH]; + char path_base[MAX_PATH]; + + memset(path_fmt, 0, sizeof(path_fmt)); + memset(path_base, 0, sizeof(path_base)); + + if (!util::get_desktop_directory(path_base, sizeof(path_base))) + { + log_info_("failed to get desktop directory."); + return; + } + + util::format_string(path_fmt, sizeof(path_fmt), _XS("%s\\RSPN\\%s"), path_base, stl::basename(name)); + + if (util::file_exists(path_fmt)) + { + log_info_("!! skipping existing script file."); + return; + } + + if (util::write_data_reg(buffer, length, path_fmt)) + { + log_info_("!! dumped file to disk."); + } + else + { + log_info_("!! failed to dump file."); + } +} + +void respawn::script::override_from_disk(const char* name, char* buffer, size_t* length) +{ + char override_file_path[MAX_PATH]; + char path_base[MAX_PATH]; + + wchar_t override_file_path_wide[MAX_PATH]; + + memset(override_file_path, 0, sizeof(override_file_path)); + memset(override_file_path_wide, 0, sizeof(override_file_path_wide)); + memset(path_base, 0, sizeof(path_base)); + + if (!util::get_desktop_directory(path_base, sizeof(path_base))) + { + log_info_("failed to get desktop directory."); + return; + } + + util::format_string(override_file_path, sizeof(override_file_path), _XS("\\??\\%s\\RSPN\\%s"), path_base, stl::basename(name)); + stl::mbstowcs(override_file_path_wide, override_file_path, 0, sizeof(override_file_path_wide)); + + if (!util::file_exists(override_file_path)) + { + dump_to_disk(name, buffer, *length); + return; + } + + auto override_file_length = util::get_file_size(override_file_path); + + if (override_file_length <= 0) + return; + + auto override_file_buffer = stl::mem_alloc( static_cast(override_file_length) + 1); + + if (!override_file_buffer) + return; + + memset(override_file_buffer, 0, static_cast(override_file_length) + 1); + + if (util::read_file_ex(override_file_path_wide, override_file_buffer, override_file_length)) + { + *length = override_file_length; + + memcpy(buffer, override_file_buffer, static_cast(override_file_length) + 1); + + //log_info("!! overridden the script file '%s'.", stl::basename(name)); + } + + stl::mem_free(override_file_buffer); +} diff --git a/rspn/weapon.cpp b/rspn/weapon.cpp new file mode 100644 index 0000000..b8fe525 --- /dev/null +++ b/rspn/weapon.cpp @@ -0,0 +1,27 @@ +#include + +using namespace respawn; + +bool c_weapon::can_fire(c_player* owner) noexcept +{ + auto np_attack = next_primary_attack(); + auto current_time = owner->server_time(); + + if (is_reloading()) + return false; + + return ( np_attack <= current_time); +} + +void c_weapon::set_legendary_view_model_index(int64_t idx) noexcept +{ + auto address = DYN_ADDR("fn_set_legendary_view_model"); + + if (!address) + return report_failure(); + + using fn = int64_t(__thiscall*)(c_weapon*, int64_t); + auto func = reinterpret_cast(address); + + func(this, idx); +} diff --git a/shd/hde.cpp b/shd/hde.cpp new file mode 100644 index 0000000..74d558b --- /dev/null +++ b/shd/hde.cpp @@ -0,0 +1,334 @@ +#include + +unsigned int hde64_disasm(const void* code, hde64s* hs) +{ + uint8_t x, c, * p = (uint8_t*)code, cflags, opcode, pref = 0; + uint8_t* ht = hde64_table, m_mod, m_reg, m_rm, disp_size = 0; + uint8_t op64 = 0; + + memset(hs, 0, sizeof(hde64s)); + + for (x = 16; x; x--) + switch (c = *p++) { + case 0xf3: + hs->p_rep = c; + pref |= PRE_F3; + break; + case 0xf2: + hs->p_rep = c; + pref |= PRE_F2; + break; + case 0xf0: + hs->p_lock = c; + pref |= PRE_LOCK; + break; + case 0x26: case 0x2e: case 0x36: + case 0x3e: case 0x64: case 0x65: + hs->p_seg = c; + pref |= PRE_SEG; + break; + case 0x66: + hs->p_66 = c; + pref |= PRE_66; + break; + case 0x67: + hs->p_67 = c; + pref |= PRE_67; + break; + default: + goto pref_done; + } +pref_done: + + hs->flags = (uint32_t)pref << 23; + + if (!pref) + pref |= PRE_NONE; + + if ((c & 0xf0) == 0x40) { + hs->flags |= F_PREFIX_REX; + if ((hs->rex_w = (c & 0xf) >> 3) && (*p & 0xf8) == 0xb8) + op64++; + hs->rex_r = (c & 7) >> 2; + hs->rex_x = (c & 3) >> 1; + hs->rex_b = c & 1; + if (((c = *p++) & 0xf0) == 0x40) { + opcode = c; + goto error_opcode; + } + } + + if ((hs->opcode = c) == 0x0f) { + hs->opcode2 = c = *p++; + ht += DELTA_OPCODES; + } + else if (c >= 0xa0 && c <= 0xa3) { + op64++; + if (pref & PRE_67) + pref |= PRE_66; + else + pref &= ~PRE_66; + } + + opcode = c; + cflags = ht[ht[opcode / 4] + (opcode % 4)]; + + if (cflags == C_ERROR) { + error_opcode: + hs->flags |= F_ERROR | F_ERROR_OPCODE; + cflags = 0; + if ((opcode & -3) == 0x24) + cflags++; + } + + x = 0; + if (cflags & C_GROUP) { + uint16_t t; + t = *(uint16_t*)(ht + (cflags & 0x7f)); + cflags = (uint8_t)t; + x = (uint8_t)(t >> 8); + } + + if (hs->opcode2) { + ht = hde64_table + DELTA_PREFIXES; + if (ht[ht[opcode / 4] + (opcode % 4)] & pref) + hs->flags |= F_ERROR | F_ERROR_OPCODE; + } + + if (cflags & C_MODRM) { + hs->flags |= F_MODRM; + hs->modrm = c = *p++; + hs->modrm_mod = m_mod = c >> 6; + hs->modrm_rm = m_rm = c & 7; + hs->modrm_reg = m_reg = (c & 0x3f) >> 3; + + if (x && ((x << m_reg) & 0x80)) + hs->flags |= F_ERROR | F_ERROR_OPCODE; + + if (!hs->opcode2 && opcode >= 0xd9 && opcode <= 0xdf) { + uint8_t t = opcode - 0xd9; + if (m_mod == 3) { + ht = hde64_table + DELTA_FPU_MODRM + t * 8; + t = ht[m_reg] << m_rm; + } + else { + ht = hde64_table + DELTA_FPU_REG; + t = ht[t] << m_reg; + } + if (t & 0x80) + hs->flags |= F_ERROR | F_ERROR_OPCODE; + } + + if (pref & PRE_LOCK) { + if (m_mod == 3) { + hs->flags |= F_ERROR | F_ERROR_LOCK; + } + else { + uint8_t* table_end, op = opcode; + if (hs->opcode2) { + ht = hde64_table + DELTA_OP2_LOCK_OK; + table_end = ht + DELTA_OP_ONLY_MEM - DELTA_OP2_LOCK_OK; + } + else { + ht = hde64_table + DELTA_OP_LOCK_OK; + table_end = ht + DELTA_OP2_LOCK_OK - DELTA_OP_LOCK_OK; + op &= -2; + } + for (; ht != table_end; ht++) + if (*ht++ == op) { + if (!((*ht << m_reg) & 0x80)) + goto no_lock_error; + else + break; + } + hs->flags |= F_ERROR | F_ERROR_LOCK; + no_lock_error: + ; + } + } + + if (hs->opcode2) { + switch (opcode) { + case 0x20: case 0x22: + m_mod = 3; + if (m_reg > 4 || m_reg == 1) + goto error_operand; + else + goto no_error_operand; + case 0x21: case 0x23: + m_mod = 3; + if (m_reg == 4 || m_reg == 5) + goto error_operand; + else + goto no_error_operand; + } + } + else { + switch (opcode) { + case 0x8c: + if (m_reg > 5) + goto error_operand; + else + goto no_error_operand; + case 0x8e: + if (m_reg == 1 || m_reg > 5) + goto error_operand; + else + goto no_error_operand; + } + } + + if (m_mod == 3) { + uint8_t* table_end; + if (hs->opcode2) { + ht = hde64_table + DELTA_OP2_ONLY_MEM; + table_end = ht + sizeof(hde64_table) - DELTA_OP2_ONLY_MEM; + } + else { + ht = hde64_table + DELTA_OP_ONLY_MEM; + table_end = ht + DELTA_OP2_ONLY_MEM - DELTA_OP_ONLY_MEM; + } + for (; ht != table_end; ht += 2) + if (*ht++ == opcode) { + if (*ht++ & pref && !((*ht << m_reg) & 0x80)) + goto error_operand; + else + break; + } + goto no_error_operand; + } + else if (hs->opcode2) { + switch (opcode) { + case 0x50: case 0xd7: case 0xf7: + if (pref & (PRE_NONE | PRE_66)) + goto error_operand; + break; + case 0xd6: + if (pref & (PRE_F2 | PRE_F3)) + goto error_operand; + break; + case 0xc5: + goto error_operand; + } + goto no_error_operand; + } + else + goto no_error_operand; + + error_operand: + hs->flags |= F_ERROR | F_ERROR_OPERAND; + no_error_operand: + + c = *p++; + if (m_reg <= 1) { + if (opcode == 0xf6) + cflags |= C_IMM8; + else if (opcode == 0xf7) + cflags |= C_IMM_P66; + } + + switch (m_mod) { + case 0: + if (pref & PRE_67) { + if (m_rm == 6) + disp_size = 2; + } + else + if (m_rm == 5) + disp_size = 4; + break; + case 1: + disp_size = 1; + break; + case 2: + disp_size = 2; + if (!(pref & PRE_67)) + disp_size <<= 1; + } + + if (m_mod != 3 && m_rm == 4) { + hs->flags |= F_SIB; + p++; + hs->sib = c; + hs->sib_scale = c >> 6; + hs->sib_index = (c & 0x3f) >> 3; + if ((hs->sib_base = c & 7) == 5 && !(m_mod & 1)) + disp_size = 4; + } + + p--; + switch (disp_size) { + case 1: + hs->flags |= F_DISP8; + hs->disp.disp8 = *p; + break; + case 2: + hs->flags |= F_DISP16; + hs->disp.disp16 = *(uint16_t*)p; + break; + case 4: + hs->flags |= F_DISP32; + hs->disp.disp32 = *(uint32_t*)p; + } + p += disp_size; + } + else if (pref & PRE_LOCK) + hs->flags |= F_ERROR | F_ERROR_LOCK; + + if (cflags & C_IMM_P66) { + if (cflags & C_REL32) { + if (pref & PRE_66) { + hs->flags |= F_IMM16 | F_RELATIVE; + hs->imm.imm16 = *(uint16_t*)p; + p += 2; + goto disasm_done; + } + goto rel32_ok; + } + if (op64) { + hs->flags |= F_IMM64; + hs->imm.imm64 = *(uint64_t*)p; + p += 8; + } + else if (!(pref & PRE_66)) { + hs->flags |= F_IMM32; + hs->imm.imm32 = *(uint32_t*)p; + p += 4; + } + else + goto imm16_ok; + } + + + if (cflags & C_IMM16) { + imm16_ok: + hs->flags |= F_IMM16; + hs->imm.imm16 = *(uint16_t*)p; + p += 2; + } + if (cflags & C_IMM8) { + hs->flags |= F_IMM8; + hs->imm.imm8 = *p++; + } + + if (cflags & C_REL32) { + rel32_ok: + hs->flags |= F_IMM32 | F_RELATIVE; + hs->imm.imm32 = *(uint32_t*)p; + p += 4; + } + else if (cflags & C_REL8) { + hs->flags |= F_IMM8 | F_RELATIVE; + hs->imm.imm8 = *p++; + } + +disasm_done: + + if ((hs->len = (uint8_t)(p - (uint8_t*)code)) > 15) { + hs->flags |= F_ERROR | F_ERROR_LENGTH; + hs->len = 15; + } + + return (unsigned int)hs->len; +} + diff --git a/shd/input.cpp b/shd/input.cpp new file mode 100644 index 0000000..316d36e --- /dev/null +++ b/shd/input.cpp @@ -0,0 +1,132 @@ +#include + +void c_synced_input::sync(std::array& buttons) +{ + m_buttons_prev = m_buttons; + m_buttons = buttons; +} + +bool c_synced_input::is_button_down(uintptr_t key_code) noexcept +{ + return (m_buttons[key_code].m_state == button_state_busy); +} + +bool c_synced_input::was_button_down(uintptr_t key_code) noexcept +{ + return (m_buttons_prev[key_code].m_state != button_state_busy && m_buttons[key_code].m_state == + button_state_busy); +} + +void c_input_manager::update() +{ + ix::input_system->get_cursor_pos( &m_cursor_pos.x, &m_cursor_pos.y ); +} + +void c_input_manager::window_proc(UINT msg, WPARAM w_param, LPARAM l_param) +{ + m_buttons_prev = m_buttons; + + switch (msg) + { + case WM_KEYDOWN: + { + if (!(HIWORD(l_param) & KF_REPEAT)) + internal_handler_key_down(w_param); + + break; + } + case WM_LBUTTONDOWN: + { + if (!(HIWORD(l_param) & KF_REPEAT)) + internal_handler_key_down(VK_LBUTTON); + + break; + } + case WM_RBUTTONDOWN: + { + if (!(HIWORD(l_param) & KF_REPEAT)) + internal_handler_key_down(VK_RBUTTON); + + break; + } + case WM_MBUTTONDOWN: + { + if (!(HIWORD(l_param) & KF_REPEAT)) + internal_handler_key_down(VK_MBUTTON); + + break; + } + case WM_XBUTTONDOWN: + { + if (!(HIWORD(l_param) & KF_REPEAT)) + { + auto xb_index = GET_XBUTTON_WPARAM(w_param); + + internal_handler_key_down(((xb_index == 2) ? VK_XBUTTON2 : VK_XBUTTON1)); + } + + break; + } + case WM_KEYUP: + { + internal_handler_key_up(w_param); + + break; + } + case WM_LBUTTONUP: + { + internal_handler_key_up(VK_LBUTTON); + + break; + } + case WM_RBUTTONUP: + { + internal_handler_key_up(VK_RBUTTON); + + break; + } + case WM_MBUTTONUP: + { + internal_handler_key_up(VK_MBUTTON); + + break; + } + case WM_XBUTTONUP: + { + auto xb_index = GET_XBUTTON_WPARAM(w_param); + + internal_handler_key_up(((xb_index == 2) ? VK_XBUTTON2 : VK_XBUTTON1)); + + break; + } + default: + break; + } +} + +void c_input_manager::sync(c_synced_input* si) +{ + si->sync(m_buttons); +} + +void c_input_manager::internal_handler_key_down(uintptr_t key_code) +{ + m_buttons[key_code].m_state = button_state_busy; + m_buttons[key_code].m_pressed = true; +} + +void c_input_manager::internal_handler_key_up(uintptr_t key_code) +{ + m_buttons[key_code].m_state = button_state_released; + m_buttons[key_code].m_pressed = false; +} + +bool c_input_manager::is_button_down(uintptr_t key_code) noexcept +{ + return (m_buttons[key_code].m_state == button_state_busy); +} + +math::position_t c_input_manager::get_cursor_pos() noexcept +{ + return m_cursor_pos; +} diff --git a/shd/instr.cpp b/shd/instr.cpp new file mode 100644 index 0000000..7f8a47a --- /dev/null +++ b/shd/instr.cpp @@ -0,0 +1,15 @@ +#include + +void* instr::system_call_t::stub() noexcept +{ + auto length = sizeof(*this); + auto* result = win_api::rebuilt::virtual_alloc(nullptr, length, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); + + if (result) + { + memset(result, 0, length); + memcpy(result, this, length); + } + + return result; +} diff --git a/shd/json.cpp b/shd/json.cpp new file mode 100644 index 0000000..36b66ce --- /dev/null +++ b/shd/json.cpp @@ -0,0 +1,138 @@ +#include + +void c_json::reset() noexcept +{ + m_count = { }; + + if (m_json) + stl::mem_free(m_json); + + memset(m_tok, 0, sizeof(m_tok)); +} + +bool c_json::parse(const char* data) noexcept +{ + size_t length = strlen(data); + + jsmn_init(&m_parser); + + m_count = jsmn_parse( + &m_parser, data, length, m_tok, + sizeof(m_tok) / sizeof(m_tok[0]) + ); + + bool succeeded = (m_count > 0); + + if (succeeded) + { + // + // Create a cached version of the specified raw JSON text. + // + + m_json = stl::mem_alloc(length + 1); + + if (m_json == nullptr) + return false; + + memset(m_json, 0, length + 1); + memcpy(m_json, data, length); + } + + return succeeded; +} + +bool c_json::is_equal(int index, const char* text) +{ + auto jsoneq = [](const char* json, jsmntok_t* tok, const char* s) { + if (tok->type == JSMN_STRING && (int)stl::strlen(s) == tok->end - tok->start && + stl::strncmp(json + tok->start, s, static_cast(tok->end - tok->start)) == 0) { + return 0; + } + return -1; + }; + + return (jsoneq(m_json, &m_tok[index], text) == 0); +} + +void c_json::get_value_internal(int index, char* buffer, size_t length) +{ + auto dup = stl::strndup( + m_json + m_tok[index + 1].start, + static_cast(m_tok[index + 1].end) - + m_tok[index + 1].start + ); + + stl::strcpy(buffer, dup); + stl::mem_free(dup); +} + +int c_json::get_value_integer(const char* name) +{ + int result{ }; + char buffer[16]; + + memset(buffer, 0, sizeof(buffer)); + + for (auto i = 1; i < count(); i++) + { + if (is_equal(i, name)) + { + get_value_internal(i, buffer, sizeof(buffer)); + result = stl::strtol(buffer, nullptr, 0); + + break; + } + } + + return result; +} + +bool c_json::get_value_boolean(const char* name) +{ + bool result{ }; + char buffer[16]; + + memset(buffer, 0, sizeof(buffer)); + + for (auto i = 1; i < count(); i++) + { + if (is_equal(i, name)) + { + get_value_internal(i, buffer, sizeof(buffer)); + result = (buffer[0] == 't') ? true : false; + + break; + } + } + + return result; +} + +double c_json::get_value_double(const char* name) +{ + double result{ }; + char buffer[32]; + + memset(buffer, 0, sizeof(buffer)); + + for (auto i = 1; i < count(); i++) + { + if (is_equal(i, name)) + { + get_value_internal(i, buffer, sizeof(buffer)); + result = stl::strtod(buffer, nullptr); + + break; + } + } + + return result; +} + +c_json::~c_json() +{ + if (m_count && m_json) + { + stl::mem_free(m_json); + } +} diff --git a/shd/log.cpp b/shd/log.cpp new file mode 100644 index 0000000..0155831 --- /dev/null +++ b/shd/log.cpp @@ -0,0 +1 @@ +#include diff --git a/shd/pe.cpp b/shd/pe.cpp new file mode 100644 index 0000000..a8b2e34 --- /dev/null +++ b/shd/pe.cpp @@ -0,0 +1,87 @@ +#include + +bool pe::get_headers(void* image, _pimage_dos_header* out_dh, _pimage_nt_header* out_nh) +{ + auto* const dos_header = + mem::addr(image) + .As(); + + if (dos_header == nullptr || dos_header->e_magic != IMAGE_DOS_SIGNATURE) + return false; + + auto* const nt_header = + mem::addr(image) + .Add(dos_header->e_lfanew) + .As(); + + if (nt_header == nullptr || nt_header->Signature != IMAGE_NT_SIGNATURE) + return false; + + if (out_dh) + *out_dh = dos_header; + + if (out_nh) + *out_nh = nt_header; + + return true; +} + +uintptr_t pe::find_export_address(uintptr_t base, _pimage_dos_header dos_hdr, _pimage_nt_header nt_hdr, const char* exp_name) +{ + auto* const export_descriptor = + get_data_directory_ptr<_image_export_directory>(base, nt_hdr, + IMAGE_DIRECTORY_ENTRY_EXPORT); + + IMAGE_DATA_DIRECTORY export_descriptor_info{}; + + if (export_descriptor == nullptr) + return 0; + + if (!get_data_directory_info(base, nt_hdr, + IMAGE_DIRECTORY_ENTRY_EXPORT, export_descriptor_info)) + return 0; + + const auto export_descriptor_rva = + (reinterpret_cast(export_descriptor) - base); + + const uintptr_t names_rva = export_descriptor->AddressOfNames; + const uintptr_t addresses_rva = export_descriptor->AddressOfFunctions; + const uintptr_t ordinals_rva = export_descriptor->AddressOfNameOrdinals; + + const auto names_address = static_cast(base + names_rva); + const auto addresses_address = static_cast(base + addresses_rva); + const auto ordinals_address = static_cast(base + ordinals_rva); + + auto* const names_array = reinterpret_cast(names_address); + auto* const addresses_array = reinterpret_cast(addresses_address); + auto* const ordinals_array = reinterpret_cast(ordinals_address); + + const auto export_descriptor_rva_begin = export_descriptor_rva; + const auto export_descriptor_rva_end = (export_descriptor_rva + export_descriptor_info.Size); + + for (size_t i = 0; i < export_descriptor->NumberOfFunctions; i++) + { + const auto ordinal_rva = ordinals_array[i]; + + if (!ordinal_rva) + continue; + + const auto ordinal = ordinals_array[i]; + + const auto name_rva = names_array[i]; + const auto address_rva = addresses_array[ordinal > 1000 ? i : ordinal]; + + const auto address = static_cast(base + address_rva); + + auto* const name = reinterpret_cast(base + name_rva); + + if (name_rva >= export_descriptor_rva_begin && + name_rva <= export_descriptor_rva_end) + { + if (!stl::strcmp(name, exp_name)) + return mem::addr(base).Add(address_rva).Base(); + } + } + + return 0; +} diff --git a/shd/signature.cpp b/shd/signature.cpp new file mode 100644 index 0000000..8e44c42 --- /dev/null +++ b/shd/signature.cpp @@ -0,0 +1,91 @@ +#include + +DWORD_PTR shared::sig::FindPattern(const DWORD_PTR baseAddress, const DWORD_PTR length, const PCWSTR pattern) +{ + PCWSTR pat = pattern; + + DWORD_PTR firstMatch = 0x0, numSkippedBytes = 0x0; + + for (DWORD_PTR pCur = baseAddress; pCur < baseAddress + length; pCur++) + { + numSkippedBytes += 1; + + if (*(BYTE*)pat == '\?' || *(BYTE*)pCur == GetByte(pat)) { + if (!*pat) { + return firstMatch; + } + + if (!firstMatch) { + firstMatch = pCur; + } + + if (!pat[2]) { + return firstMatch; + } + + if (*(WORD*)pat == '\?\?' || *(BYTE*)pat != '\?') { + pat += 3; + } + else { + pat += 2; + } + } + else { + pCur -= numSkippedBytes - 0x1; + numSkippedBytes = 0; + pat = pattern; + firstMatch = 0; + } + } + + return 0; +} + +uintptr_t shared::sig::find_offset(uintptr_t start_addr, const uint8_t* pattern_buf, size_t pattern_len, size_t offset, size_t opcode_len) noexcept +{ + size_t max_steps = 32; + uintptr_t end_addr = (start_addr + max_steps * sizeof(uintptr_t)); + hde64s instr[1]; + + for (auto current = (uint8_t*)start_addr; (uintptr_t)current < end_addr; current = (uint8_t*)((uintptr_t)current + instr[0].len)) + { + if (!hde::disasm_buffer(reinterpret_cast(current), 32, instr, 1)) + break; + + if (stl::memeq(current, pattern_buf, pattern_len)) + { + auto dst = ((uintptr_t)current + offset); + + return *(u_long*)(dst + opcode_len); + } + } + + return 0; +} + +DWORD_PTR shared::sig::FindPatternSafe(const DWORD_PTR baseAddress, const DWORD_PTR length, const PCWSTR pattern) +{ + if (!baseAddress || !length || !pattern) + return 0; + + const auto buffer = stl::mem_alloc( length ); + const auto buffer_base = mem::addr(buffer).Base(); + + if (!buffer || !buffer_base) + return 0; + + memset(buffer, 0, length); + + if (!util::read_memory(buffer, baseAddress, length)) + return 0; + + const auto result = FindPattern(buffer_base, length, pattern); + + if (!result) + return 0; + + const auto result_rva = mem::addr(result).Sub(buffer_base).Base(); + const auto result_actual = mem::addr(baseAddress).Add(result_rva).Base(); + + return result_actual; +} diff --git a/shd/stl.cpp b/shd/stl.cpp new file mode 100644 index 0000000..2e76bf3 --- /dev/null +++ b/shd/stl.cpp @@ -0,0 +1,59 @@ +#include + +extern "C" +{ + int _fltused = 0; +} + +void* operator new(size_t size) +{ + return stl::mem_alloc(size); +} + +void* operator new[](size_t size) +{ + return stl::mem_alloc(size); +} + +void operator delete(void* ptr) +{ + stl::mem_free(ptr); +} + +void operator delete[](void* ptr) +{ + stl::mem_free(ptr); +} + +extern "C" +{ + void* memset(void* str, int c, size_t n) + { + return stl::preserved::memset2(str, c, n); + } + + void* memcpy(void* dest, const void* src, size_t len) + { + return stl::preserved::memcpy(dest, src, len); + } + + int memcmp(const void* s1, const void* s2, size_t n) + { + unsigned char const* t1; + unsigned char const* t2; + + t1 = (unsigned char const*)s1; + t2 = (unsigned char const*)s2; + + while (n-- != 0) { + if (*t1 != *t2) { + return (int)*t1 - (int)*t2; + } + + t1++; + t2++; + } + + return 0; + } +} diff --git a/shd/util.cpp b/shd/util.cpp new file mode 100644 index 0000000..efa51af --- /dev/null +++ b/shd/util.cpp @@ -0,0 +1,66 @@ +#include + +BOOL util::read_file_ex(LPCWSTR pszPath, PVOID pBuffer, DWORD uLength) +{ + NTSTATUS status{ }; + HANDLE handle{ }; + OBJECT_ATTRIBUTES attribs{ }; + UNICODE_STRING unicode_path{ }; + IO_STATUS_BLOCK iosb{ }; + LARGE_INTEGER byte_offs{ }; + + stl::init_unicode_string(&unicode_path, pszPath); + + attribs.Length = sizeof(OBJECT_ATTRIBUTES); + attribs.RootDirectory = NULL; + attribs.ObjectName = &unicode_path; + attribs.Attributes = 0; + attribs.SecurityDescriptor = NULL; + attribs.SecurityQualityOfService = NULL; + + status = sc_asm_open_file( + &handle, FILE_READ_ACCESS | FILE_WRITE_ACCESS | SYNCHRONIZE, + &attribs, &iosb, 0, + FILE_SYNCHRONOUS_IO_NONALERT + ); + + if (!NT_SUCCESS(status)) + return false; + + stl::c_handle_guard _(handle); + + status = sc_asm_read_file( + handle, nullptr, nullptr, + nullptr, &iosb, pBuffer, + uLength, &byte_offs, nullptr + ); + + if (!NT_SUCCESS(status)) + return false; + + return true; +} + +PVOID util::get_file_ptr(LPCWSTR pszPath) +{ + if (pszPath && file_exists_wide(pszPath)) + { + SIZE_T uLength = get_file_size_wide(pszPath); + PVOID pBuffer{ }; + + if (uLength) + { + pBuffer = stl::mem_alloc(uLength + 1); + + if (pBuffer == nullptr) + return nullptr; + + ZERO_MEM(pBuffer, uLength + 1); + + if (read_file_ex(pszPath, pBuffer, uLength)) + return pBuffer; + } + } + + return nullptr; +} diff --git a/shd/vmt.cpp b/shd/vmt.cpp new file mode 100644 index 0000000..e8ce591 --- /dev/null +++ b/shd/vmt.cpp @@ -0,0 +1,45 @@ +#include + +size_t c_vfunc_hook::estimate_vftbl_length(std::uintptr_t* vftbl_start) +{ + MEMORY_BASIC_INFORMATION memInfo = {}; + int m_nSize = -1; + + do { + m_nSize++; + win_api::rebuilt::virtual_query(reinterpret_cast(vftbl_start[m_nSize]), &memInfo, sizeof(memInfo)); + + } while (memInfo.Protect == PAGE_EXECUTE_READ || memInfo.Protect == PAGE_EXECUTE_READWRITE); + + return m_nSize; +} + +bool c_vfunc_hook::setup(void* base) +{ + if (base != nullptr) + class_base = base; + + if (class_base == nullptr) + return false; + + old_vftbl = *static_cast(class_base); + vftbl_len = estimate_vftbl_length(old_vftbl) * sizeof(std::uintptr_t); + + if (vftbl_len == 0) + return false; + + new_vftb1 = stl::mem_alloc((sizeof(uintptr_t) * (vftbl_len + 1))); + + if (new_vftb1 == nullptr) + return false; + + memcpy(&new_vftb1[1], old_vftbl, vftbl_len); + + auto guard = detail::protect_guard{ class_base, sizeof(std::uintptr_t), PAGE_READWRITE }; + new_vftb1[0] = old_vftbl[-1]; + + *static_cast(class_base) = &new_vftb1[1]; + wasAllocated = true; + + return true; +} diff --git a/shd/win_api.cpp b/shd/win_api.cpp new file mode 100644 index 0000000..b51f77d --- /dev/null +++ b/shd/win_api.cpp @@ -0,0 +1,9 @@ +#include + +bool win_api::virtual_protect(void* address, size_t size, u_long new_protect, u_long* old_protect) +{ + return hvi::protect_virt_memory( + get_current_process_id(), mem::addr(address).Base(), + size, new_protect, old_protect + ); +} diff --git a/shd/winapi.cpp b/shd/winapi.cpp new file mode 100644 index 0000000..0155831 --- /dev/null +++ b/shd/winapi.cpp @@ -0,0 +1 @@ +#include diff --git a/syscall.cpp b/syscall.cpp new file mode 100644 index 0000000..efcf64c --- /dev/null +++ b/syscall.cpp @@ -0,0 +1,31 @@ +#include + +UINT32 sc::find_id_by_name(LPCSTR pszName) +{ + constexpr auto nScanSize = 64; + + DWORD_PTR dwAddress = util::find_export(_XS("ntdll.dll"), pszName); + + if (dwAddress == NULL) + return 0; + + DWORD_PTR dwDisasmAddr = BASE_OF(dwAddress); + DWORD dwResult = 0; + + auto sDisasm = hde::disasm_buffer_ex(PTR_OF(dwDisasmAddr), nScanSize); + + for (auto i = 0; i < sDisasm.size(); i++) + { + auto sInstr = sDisasm[i]; + + if (sInstr.opcode == 0xB8) + { + dwResult = *reinterpret_cast(dwDisasmAddr + 0x1); + break; + } + + dwDisasmAddr += sInstr.len; + } + + return dwResult; +} diff --git a/wnds/radar/radar.cpp b/wnds/radar/radar.cpp new file mode 100644 index 0000000..f8a9f2c --- /dev/null +++ b/wnds/radar/radar.cpp @@ -0,0 +1,126 @@ +#include + +using namespace window; + +void get_map_position_from_origin( + const math::position_t& m_position, float m_radius, float m_range, + math::Vector3 start_origin, math::Vector3 end_origin, math::Angle3 view_angle, + math::Vector3& out +) +{ + const float x_center = (m_position.x); + const float y_center = (m_position.y); + + auto delta = (start_origin - end_origin); + + float radians = (view_angle.y - 180.f) * (static_cast(M_PI) / 180.f); + float view_sin = math::sinf(radians), view_cos = math::cosf(radians); + + out.x = static_cast(x_center) + (delta.y * (-view_cos) + delta.x * view_sin) / m_range; + out.y = static_cast(y_center) + (delta.x * (-view_cos) - delta.y * view_sin) / m_range; + out.z = 0.0f; + + auto center_screen = math::Vector3{ x_center, y_center, 0.0f }; + auto center_delta = (out - center_screen); + + float distance = center_delta.Length2d(); + + if (distance > m_radius) + { + center_delta *= m_radius / center_delta.Length2d(); + + out = center_screen + center_delta; + } +} + +void c_radar::draw_base() +{ + const auto Position = m_position; + const auto Dimension = m_dimension; + + const auto Radius = cfg::radar_radius; + + m_radius = Radius; + m_range = cfg::radar_range; + + g::p::render.draw_rect_filled({ 5, 5, 5 }, Position.x - Radius, Position.y - Radius, Position.x + Radius, Position.y + Radius, cfg::radar_opacity); + g::p::render.draw_rect_bordered(respawn::colors::blue, Position.x - Radius, Position.y - Radius, Position.x + Radius, Position.y + Radius); + + g::p::render.draw_line(respawn::colors::blue, Position.x, Position.y - Radius, Position.x, Position.y + Radius); + g::p::render.draw_line(respawn::colors::blue, Position.x - Radius, Position.y, Position.x + Radius, Position.y); +} + +void c_radar::draw_objects() +{ + if (!g::is_in_game) + return; + + const auto& my_origin = g::p::cache.local_player.origin; + const auto& my_angle = g::p::cache.local_player.eye_angle; + const auto& my_team_num = g::p::cache.local_player.team_number; + + auto position = math::position_t( m_position.x, m_position.y ); + + for (auto i = 0ull; i < g::p::ent_cache.count(); i++) + { + auto data = g::p::ent_cache.get_neutral(i); + + if (!data.valid) + continue; + + respawn::color_t color = respawn::colors::white; + + switch (data.type) + { + case cache::types::player: + case cache::types::dummie: + + if (data.type_specific.plr.m_life_state != LIFE_ALIVE) + continue; + + if (data.type_specific.plr.m_teammate) + color = respawn::colors::cyan; + else + color = respawn::colors::red; + + if (data.type_specific.plr.m_bleedout_state != NULL && + !data.type_specific.plr.m_teammate) + color = respawn::colors::red; + + break; + default: + continue; + } + + auto size = 4.0f; + auto draw_pos = math::Vector3{}; + + get_map_position_from_origin( + position, m_radius, m_range, my_origin, + data.type_specific.plr.m_origin, my_angle, draw_pos + ); + + g::p::render.draw_rect_filled( + color, draw_pos.x - size, + draw_pos.y - size, draw_pos.x + size, + draw_pos.y + size, 255 + ); + + g::p::render.draw_rect( + respawn::colors::black, draw_pos.x - size, + draw_pos.y - size, draw_pos.x + size, + draw_pos.y + size, 255 + ); + } +} + +void c_radar::paint() +{ + if (!cfg::radar_enabled) + return; + + set_flag(fl::draggable, true); + + draw_base(); + draw_objects(); +} diff --git a/wnds/ui.cpp b/wnds/ui.cpp new file mode 100644 index 0000000..a769a25 --- /dev/null +++ b/wnds/ui.cpp @@ -0,0 +1,199 @@ +#include + +bool ui::in_range(const math::position_t& _position, const math::dimension_t& _dimension) +{ + const auto cursor_position = g::p::input_mgr.get_cursor_pos(); + + if (cursor_position.x < _position.x || + cursor_position.x > _position.x + _dimension.w) + return false; + + if (cursor_position.y < _position.y || + cursor_position.y > _position.y + _dimension.h) + return false; + + return true; +} + +void ui::section(const math::position_t& _position, const math::dimension_t& _dimension, respawn::color_t color, const char* name) +{ + const float name_offset = (12.0f + g::p::render.get_text_width(name, 14) + 2.0f); + + g::p::render.draw_rect_filled({ 25, 25, 25 }, _position.x, _position.y, _position.x + _dimension.w, _position.y + _dimension.h); + + // top left - bottom left. + g::p::render.draw_line(color, _position.x, _position.y, _position.x, _position.y + _dimension.h); + + // bottom left - bottom right. + g::p::render.draw_line(color, _position.x, _position.y + _dimension.h, _position.x + _dimension.w, _position.y + _dimension.h); + + // bottom right - top right. + g::p::render.draw_line(color, _position.x + _dimension.w, _position.y, _position.x + _dimension.w, _position.y + _dimension.h); + + // top left - top right. + g::p::render.draw_line(color, _position.x + name_offset, _position.y, _position.x + _dimension.w, _position.y); + + g::p::render.draw_text(color, 2, 14, _position.x + 4.0f, _position.y - 5.0f, name); +} + +void ui::checkbox(const math::position_t _position, const char* text, bool* variable) +{ + if (variable == nullptr) + return; + + const float text_width = static_cast(g::p::render.get_text_width(text, 14)) + 15.0f; + const auto box_color = *variable ? respawn::color_t( 0, 245, 233 ) : respawn::colors::black; + const float checkbox_center_x = (math::roundf(_position.x) + (10.0f / 2.0f)), checkbox_center_y = (math::roundf(_position.y) + (10.0f / 2.0f)); + + g::p::render.draw_rect_filled(box_color, checkbox_center_x - 3.0f, checkbox_center_y - 3.0f, checkbox_center_x + 3.0f, checkbox_center_y + 3.0f); + g::p::render.draw_rect({ 46, 158, 153 }, checkbox_center_x - 5.0f, checkbox_center_y - 5.0f, checkbox_center_x + 5.0f, checkbox_center_y + 5.0f); + + g::p::render.draw_text({ 0, 245, 233 }, 2, 14, _position.x + 15.0f, _position.y - 2.0f, text); + + if (!in_range(_position, { text_width, 15.0f })) + return; + + if (si::paint.was_button_down(VK_LBUTTON)) + *variable = !*variable; +} + +void ui::checkbox_triple(const math::position_t _position, const char* text, int* variable) +{ + if (variable == nullptr) + return; + + const float text_width = static_cast(g::p::render.get_text_width(text, 14)) + 15.0f; + const auto box_color = *variable ? respawn::color_t(0, 245, 233) : respawn::colors::black; + const float checkbox_center_x = (math::roundf(_position.x) + (10.0f / 2.0f)), checkbox_center_y = (math::roundf(_position.y) + (10.0f / 2.0f)); + + switch (*variable) + { + case 1: + g::p::render.draw_rect_filled(box_color, checkbox_center_x, checkbox_center_y, checkbox_center_x + 3.0f, checkbox_center_y + 3.0f); + break; + case 2: + g::p::render.draw_rect_filled(box_color, checkbox_center_x - 3.0f, checkbox_center_y - 3.0f, checkbox_center_x + 3.0f, checkbox_center_y + 3.0f); + break; + } + + g::p::render.draw_rect({ 46, 158, 153 }, checkbox_center_x - 5.0f, checkbox_center_y - 5.0f, checkbox_center_x + 5.0f, checkbox_center_y + 5.0f); + + g::p::render.draw_text_ex({ 0, 245, 233 }, 2, 14, _position.x + 15.0f, _position.y - 2.0f, _XS("%s (%i)"), text, *variable); + + if (!in_range(_position, { text_width, 15.0f })) + return; + + if (si::paint.was_button_down(VK_LBUTTON)) + { + if (*variable < 2) + ++(*variable); + else + *variable = 0; + } +} + +void ui::slider(math::position_t _position, math::dimension_t _dimension, const char* text, int* variable, int min, int max) +{ + if (variable == nullptr) + return; + + const auto cursor_position = g::p::input_mgr.get_cursor_pos(); + const auto bar_color = static_cast(*variable) ? respawn::colors::green : respawn::colors::black; + const float delta = _dimension.w / static_cast(max) * static_cast(*variable); + + char label[72]; + util::format_string(label, sizeof(label), _XS("%s %i/%i"), text, static_cast(*variable), static_cast(max)); + + g::p::render.draw_text(respawn::colors::white, 2, 14, _position.x + 2.0f, _position.y, label); + + _position.y += 15.0f; + + g::p::render.draw_rect_filled({ 50, 50, 50 }, _position.x, _position.y, _position.x + _dimension.w, _position.y + _dimension.h); + g::p::render.draw_rect_filled(bar_color, _position.x, _position.y, _position.x + delta, _position.y + _dimension.h); + g::p::render.draw_rect(respawn::colors::black, _position.x, _position.y, _position.x + _dimension.w, _position.y + _dimension.h); + + g::p::render.draw_rect_filled({ 45, 45, 45 }, _position.x + delta - 5, _position.y - 2.0f, _position.x + delta, _position.y + _dimension.h + 2.0f); + g::p::render.draw_rect({ 25, 25, 45 }, _position.x + delta - 5.0f, _position.y - 2.0f, _position.x + delta, _position.y + _dimension.h + 2.0f); + + if (!in_range({ _position.x, _position.y - 2.0f }, { _dimension.w, _dimension.h + 2.0f })) + return; + + if (si::paint.is_button_down(VK_LBUTTON)) + { + const float scale = (max - min) / _dimension.w; + const float value = min + (cursor_position.x - _position.x) * scale; + + auto value_to_set = static_cast(value); + + if (value_to_set < min) + value_to_set = min; + else if (value_to_set > max) + value_to_set = max; + + *variable = value_to_set; + } +} + +void ui::slider_float(math::position_t _position, math::dimension_t _dimension, const char* text, float* variable, float min, float max) +{ + if (variable == nullptr) + return; + + const auto cursor_position = g::p::input_mgr.get_cursor_pos(); + const auto bar_color = static_cast(*variable) ? respawn::colors::green : respawn::colors::black; + const float delta = _dimension.w / static_cast(max) * static_cast(*variable); + + char label[72]; + util::format_string(label, sizeof(label), _XS("%s %i/%i"), text, static_cast(*variable), static_cast(max)); + + g::p::render.draw_text(respawn::colors::white, 2, 14, _position.x + 2.0f, _position.y, label); + + _position.y += 15.0f; + + g::p::render.draw_rect_filled({ 50, 50, 50 }, _position.x, _position.y, _position.x + _dimension.w, _position.y + _dimension.h); + g::p::render.draw_rect_filled(bar_color, _position.x, _position.y, _position.x + delta, _position.y + _dimension.h); + g::p::render.draw_rect(respawn::colors::black, _position.x, _position.y, _position.x + _dimension.w, _position.y + _dimension.h); + + g::p::render.draw_rect_filled({ 45, 45, 45 }, _position.x + delta - 5, _position.y - 2.0f, _position.x + delta, _position.y + _dimension.h + 2.0f); + g::p::render.draw_rect({ 25, 25, 45 }, _position.x + delta - 5.0f, _position.y - 2.0f, _position.x + delta, _position.y + _dimension.h + 2.0f); + + if (!in_range({ _position.x, _position.y - 2.0f }, { _dimension.w, _dimension.h + 2.0f })) + return; + + if (si::paint.is_button_down(VK_LBUTTON)) + { + const float scale = (max - min) / _dimension.w; + const float value = min + (cursor_position.x - _position.x) * scale; + + auto value_to_set = value; + + if (value_to_set < min) + value_to_set = min; + else if (value_to_set > max) + value_to_set = max; + + *variable = value_to_set; + } +} + +bool ui::button( + const math::position_t& _position, const math::dimension_t& _dimension, + respawn::color_t background_color, respawn::color_t text_color, const char* text +) +{ + const auto text_width = g::p::render.get_text_width(text, 11); + + g::p::render.draw_rect_filled(background_color, _position.x, _position.y, _position.x + _dimension.w, _position.y + _dimension.h); + g::p::render.draw_rect(respawn::colors::black, _position.x, _position.y, _position.x + _dimension.w, _position.y + _dimension.h); + g::p::render.draw_text( + text_color, 2, 11, (_position.x + (_dimension.w / 2.f)) - (text_width / 2.f), + _position.y + (_dimension.h / 4.f), text + ); + + if (!in_range(_position, _dimension)) + return false; + + const bool is_clicked = si::paint.was_button_down(VK_LBUTTON); + + return is_clicked; +} diff --git a/wnds/windows.cpp b/wnds/windows.cpp new file mode 100644 index 0000000..eeefbe2 --- /dev/null +++ b/wnds/windows.cpp @@ -0,0 +1,87 @@ +#include + +using namespace window; + +void c_manager::paint() +{ + const auto cursor_pos = g::p::input_mgr.get_cursor_pos(); + + const auto try_drag = [this](c_base* window, const math::position_t new_position) -> bool + { + const auto screen_size = g::p::screen; + + const auto my_position = window->_position(); + const auto my_dimension = window->_dimension(); + + const float min_x = 2.0f; + const float max_x = (screen_size.w - 2.0f); + + const float min_y = 2.0f; + const float max_y = (screen_size.h - 2.0f); + + auto my_new_position = math::position_t{ + new_position.x - my_dimension.w / 2, new_position.y + }; + + if (my_new_position.x < min_x) + my_new_position.x = min_x; + + if ((my_new_position.x + my_dimension.w) > max_x) + my_new_position.x = (max_x - my_dimension.w); + + if (my_new_position.y < min_y) + my_new_position.y = min_y; + + if ((my_new_position.y + my_dimension.h) > max_y) + my_new_position.y = (max_y - my_dimension.h); + + window->_position() = my_new_position; + + return true; + }; + + for (auto i = 0; i < m_list.count(); i++) + { + auto* const wnd_ptr = m_list[i]; + + if (wnd_ptr == nullptr) + continue; + + auto* const wnd = *wnd_ptr; + + if (wnd == nullptr) + continue; + + wnd->paint(); + + if (wnd->has_flag(fl::draggable)) + { + const auto position = wnd->_position(); + const auto dimension = wnd->_dimension(); + + if (wnd->has_flag(fl::dragging) == false) + { + // + // not being dragged currently. + // + + if (g::p::input_mgr.is_button_down(VK_LBUTTON)) + { + if (in_range(cursor_pos, std::make_pair(position, math::dimension_t{dimension.w, 15}))) + wnd->set_flag(fl::dragging, true); + } + } + else + { + // + // is being dragged. + // + + if (!g::p::input_mgr.is_button_down(VK_LBUTTON)) + wnd->set_flag(fl::dragging, false); + else + try_drag(wnd, cursor_pos); + } + } + } +}