Fixed build errors

This commit is contained in:
acidicoala
2025-08-19 00:40:42 +05:00
parent b170fd2276
commit 3978006e12
17 changed files with 257 additions and 183 deletions

View File

@@ -5,6 +5,7 @@
<w>indicies</w> <w>indicies</w>
<w>koalabox</w> <w>koalabox</w>
<w>koaloader</w> <w>koaloader</w>
<w>wstr</w>
</words> </words>
</dictionary> </dictionary>
</component> </component>

View File

@@ -93,6 +93,11 @@ endif ()
add_library(SmokeAPI SHARED ${SMOKE_API_SOURCES} ${VERSION_RESOURCE}) add_library(SmokeAPI SHARED ${SMOKE_API_SOURCES} ${VERSION_RESOURCE})
# There is a weird bug where c++23 features are not enabled in x64 builds,
# while they are available in x86. I've no idea what causes this discrepancy,
# but manually setting the MSVC compiler option fixes this issue.
target_compile_options(SmokeAPI PRIVATE /std:c++latest)
configure_linker_exports( configure_linker_exports(
TARGET SmokeAPI TARGET SmokeAPI
FORWARDED_DLL "${STEAMAPI_DLL}_o" FORWARDED_DLL "${STEAMAPI_DLL}_o"

View File

@@ -1,9 +1,10 @@
#include <core/types.hpp>
#include <common/steamclient_exports.hpp> #include <common/steamclient_exports.hpp>
#include <steam_impl/steam_client.hpp> #include <steam_impl/steam_client.hpp>
DLL_EXPORT(void*) CreateInterface(const char* interface_string, int* out_result) { DLL_EXPORT(void*) CreateInterface(const char* interface_string, int* out_result) {
return steam_client::GetGenericInterface( return steam_client::GetGenericInterface(
__func__, interface_string, [&]() { __func__, interface_string, [&] {
GET_ORIGINAL_HOOKED_FUNCTION(CreateInterface) GET_ORIGINAL_HOOKED_FUNCTION(CreateInterface)
return CreateInterface_o(interface_string, out_result); return CreateInterface_o(interface_string, out_result);

View File

@@ -1,8 +1,8 @@
#pragma once #pragma once
#include <core/globals.hpp>
#include <koalabox/core.hpp> #include <koalabox/core.hpp>
#include <koalabox/hook.hpp> // ReSharper disable once CppUnusedIncludeDirective
#include <koalabox/hook.hpp> // Used by several macros
#include <koalabox/logger.hpp> #include <koalabox/logger.hpp>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>

View File

@@ -1,17 +1,5 @@
#include <smoke_api/config.hpp> #include <smoke_api/config.hpp>
#include <core/globals.hpp>
// DLL_EXPORT(void) SteamAPI_Shutdown1() {
// LOG_INFO("{} -> Game requested shutdown", __func__);
//
// ORIGINAL_FUNCTION_STEAMAPI(SteamAPI_Shutdown)();
// }
/*DLL_EXPORT(void) SteamAPI_Shutdown2() {
LOG_INFO("{} -> Game requested shutdown", __func__);
ORIGINAL_FUNCTION_STEAMAPI(SteamAPI_Shutdown)();
}*/
// TODO: Detour in hook mode // TODO: Detour in hook mode
DLL_EXPORT(bool) SteamAPI_RestartAppIfNecessary( DLL_EXPORT(bool) SteamAPI_RestartAppIfNecessary(

View File

@@ -1,9 +1,11 @@
#include <koalabox/logger.hpp>
#include <core/globals.hpp>
#include <steam_impl/steam_apps.hpp> #include <steam_impl/steam_apps.hpp>
#include <steam_impl/steam_client.hpp> #include <steam_impl/steam_client.hpp>
#include <steam_impl/steam_inventory.hpp> #include <steam_impl/steam_inventory.hpp>
#include <steam_impl/steam_user.hpp> #include <steam_impl/steam_user.hpp>
#include <steam_impl/steam_impl.hpp> #include <steam_impl/steam_impl.hpp>
#include <koalabox/logger.hpp>
// ISteamApps // ISteamApps

View File

@@ -1,3 +1,4 @@
#include <core/globals.hpp>
#include <steam_impl/steam_client.hpp> #include <steam_impl/steam_client.hpp>
DLL_EXPORT(void*) SteamInternal_FindOrCreateUserInterface(HSteamUser hSteamUser, const char* version) { DLL_EXPORT(void*) SteamInternal_FindOrCreateUserInterface(HSteamUser hSteamUser, const char* version) {

View File

@@ -1,8 +1,11 @@
#include <steam_impl/steam_client.hpp> #include <regex>
#include <koalabox/logger.hpp> #include <koalabox/logger.hpp>
#include <koalabox/win_util.hpp> #include <koalabox/win_util.hpp>
#include <koalabox/util.hpp> #include <koalabox/util.hpp>
#include <regex>
#include <core/globals.hpp>
#include <steam_impl/steam_client.hpp>
/** /**
* Searches the `.rdata` section of the original dll for the full interface version string * Searches the `.rdata` section of the original dll for the full interface version string
@@ -40,7 +43,7 @@ DLL_EXPORT(void*) SteamClient() {
static auto version = get_versioned_interface(STEAM_CLIENT, "006"); static auto version = get_versioned_interface(STEAM_CLIENT, "006");
return steam_client::GetGenericInterface( return steam_client::GetGenericInterface(
__func__, version, [&]() { __func__, version, [&] {
GET_ORIGINAL_FUNCTION_STEAMAPI(SteamClient) GET_ORIGINAL_FUNCTION_STEAMAPI(SteamClient)
return SteamClient_o(); return SteamClient_o();
@@ -64,7 +67,7 @@ DLL_EXPORT(void*) SteamUser() {
static auto version = get_versioned_interface(STEAM_USER, "012"); static auto version = get_versioned_interface(STEAM_USER, "012");
return steam_client::GetGenericInterface( return steam_client::GetGenericInterface(
__func__, version, [&]() { __func__, version, [&] {
GET_ORIGINAL_FUNCTION_STEAMAPI(SteamUser) GET_ORIGINAL_FUNCTION_STEAMAPI(SteamUser)
return SteamUser_o(); return SteamUser_o();
@@ -76,7 +79,7 @@ DLL_EXPORT(void*) SteamInventory() {
static auto version = get_versioned_interface(STEAM_INVENTORY, "001"); static auto version = get_versioned_interface(STEAM_INVENTORY, "001");
return steam_client::GetGenericInterface( return steam_client::GetGenericInterface(
__func__, version, [&]() { __func__, version, [&] {
GET_ORIGINAL_FUNCTION_STEAMAPI(SteamInventory) GET_ORIGINAL_FUNCTION_STEAMAPI(SteamInventory)
return SteamInventory_o(); return SteamInventory_o();

View File

@@ -80,8 +80,8 @@ namespace {
return false; return false;
} }
// Verify that it's steam from valve, and not some other executable coincidentally named // Verify that it's steam from valve,
// steam // and not some other executable coincidentally named steam
const HMODULE steam_handle = koalabox::win_util::get_module_handle_or_throw(nullptr); const HMODULE steam_handle = koalabox::win_util::get_module_handle_or_throw(nullptr);
const auto manifest = koalabox::win_util::get_module_manifest(steam_handle); const auto manifest = koalabox::win_util::get_module_manifest(steam_handle);

View File

@@ -6,7 +6,7 @@
#include <core/types.hpp> #include <core/types.hpp>
#include <core/api.hpp> #include <core/api.hpp>
namespace steam_apps { namespace {
/// Steamworks may max GetDLCCount value at 64, depending on how much unowned DLCs the user has. /// Steamworks may max GetDLCCount value at 64, depending on how much unowned DLCs the user has.
/// Despite this limit, some games with more than 64 DLCs still keep using this method. /// Despite this limit, some games with more than 64 DLCs still keep using this method.
/// This means we have to get extra DLC IDs from local config, remote config, or cache. /// This means we have to get extra DLC IDs from local config, remote config, or cache.
@@ -43,9 +43,10 @@ namespace steam_apps {
// by aggregating results from all the sources into a single set. // by aggregating results from all the sources into a single set.
Vector<DLC> aggregated_dlcs; Vector<DLC> aggregated_dlcs;
const auto append_dlcs = [&](const Vector<DLC>& source, const String& source_name) { const auto append_dlcs = [&](const Vector<DLC>& dlc_list, const String& source_name) {
LOG_DEBUG("App ID {} has {} DLCs defined in {}", app_id, source.size(), source_name); LOG_DEBUG("App ID {} has {} DLCs defined in {}", app_id, dlc_list.size(), source_name);
aggregated_dlcs < append > source; // Append DLCs to aggregated DLCs
std::ranges::copy(dlc_list, std::back_inserter(aggregated_dlcs));
}; };
append_dlcs(smoke_api::config::get_extra_dlcs(app_id), "local config"); append_dlcs(smoke_api::config::get_extra_dlcs(app_id), "local config");
@@ -71,6 +72,9 @@ namespace steam_apps {
smoke_api::app_cache::save_dlcs(app_id, aggregated_dlcs); smoke_api::app_cache::save_dlcs(app_id, aggregated_dlcs);
} }
}
namespace steam_apps {
bool IsDlcUnlocked( bool IsDlcUnlocked(
const String& function_name, const String& function_name,
@@ -114,7 +118,7 @@ namespace steam_apps {
return total_count(static_cast<int>(app_dlcs[app_id].size())); return total_count(static_cast<int>(app_dlcs[app_id].size()));
} catch (const Exception& e) { } catch (const Exception& e) {
LOG_ERROR(" Uncaught exception: {}", function_name, e.what()); LOG_ERROR("Uncaught exception: {}", function_name, e.what());
return 0; return 0;
} }
} }

View File

@@ -13,7 +13,7 @@ VIRTUAL(bool) IClientUser_BIsSubscribedApp(PARAMS(AppId_t dlc_id)) {
return IClientUser_BIsSubscribedApp_o(ARGS(dlc_id)); return IClientUser_BIsSubscribedApp_o(ARGS(dlc_id));
}); });
} catch (const Exception& e) { } catch (const Exception& e) {
LOG_ERROR("{} -> Error: {}", __func__, e.what()) LOG_ERROR("{} -> Error: {}", __func__, e.what());
return false; return false;
} }
} }

View File

@@ -1,11 +1,11 @@
#include <store_mode/steamclient/steamclient.hpp>
#include <store_mode/store.hpp>
#include <koalabox/hook.hpp> #include <koalabox/hook.hpp>
#include <koalabox/logger.hpp> #include <koalabox/logger.hpp>
#include <koalabox/util.hpp> #include <koalabox/util.hpp>
#include <store_mode/steamclient/steamclient.hpp>
#include <store_mode/store.hpp>
#include <Zydis/Zydis.h>
#include <Zydis/DecoderTypes.h> #include <Zydis/DecoderTypes.h>
#include <Zydis/Zydis.h>
namespace store::steamclient { namespace store::steamclient {
using namespace koalabox; using namespace koalabox;
@@ -31,6 +31,7 @@ namespace store::steamclient {
uintptr_t start_address uintptr_t start_address
); );
// clang-format off
#define CONSTRUCT_ORDINAL_MAP(INTERFACE) \ #define CONSTRUCT_ORDINAL_MAP(INTERFACE) \
construct_ordinal_map(#INTERFACE, ordinal_map[#INTERFACE], function_selector_address); construct_ordinal_map(#INTERFACE, ordinal_map[#INTERFACE], function_selector_address);
@@ -38,11 +39,11 @@ namespace store::steamclient {
interface, \ interface, \
#INTERFACE"_"#FUNC, \ #INTERFACE"_"#FUNC, \
ordinal_map[#INTERFACE][#FUNC], \ ordinal_map[#INTERFACE][#FUNC], \
reinterpret_cast<uintptr_t>(INTERFACE##_##FUNC) \ reinterpret_cast<uintptr_t>(INTERFACE## _## FUNC) \
); );
#define SELECTOR_IMPLEMENTATION(INTERFACE, FUNC_BODY) \ #define SELECTOR_IMPLEMENTATION(INTERFACE, FUNC_BODY) \
DLL_EXPORT(void) INTERFACE##_Selector( \ DLL_EXPORT(void) INTERFACE## _Selector( \
void* interface, \ void* interface, \
void* arg2, \ void* arg2, \
void* arg3, \ void* arg3, \
@@ -52,8 +53,8 @@ namespace store::steamclient {
interface_name_to_address_map[#INTERFACE] = interface; \ interface_name_to_address_map[#INTERFACE] = interface; \
[&]()FUNC_BODY(); \ [&]()FUNC_BODY(); \
}) \ }) \
GET_ORIGINAL_HOOKED_FUNCTION(INTERFACE##_Selector) \ GET_ORIGINAL_HOOKED_FUNCTION(INTERFACE## _Selector) \
INTERFACE##_Selector_o(interface, arg2, arg3, arg4); \ INTERFACE## _Selector_o(interface, arg2, arg3, arg4); \
} }
SELECTOR_IMPLEMENTATION(IClientAppManager, { SELECTOR_IMPLEMENTATION(IClientAppManager, {
@@ -87,10 +88,12 @@ namespace store::steamclient {
#define DETOUR_SELECTOR(INTERFACE) \ #define DETOUR_SELECTOR(INTERFACE) \
if(interface_name == #INTERFACE){ \ if(interface_name == #INTERFACE){ \
CONSTRUCT_ORDINAL_MAP(INTERFACE) \ CONSTRUCT_ORDINAL_MAP(INTERFACE) \
DETOUR_ADDRESS(INTERFACE##_Selector, function_selector_address) \ DETOUR_ADDRESS(INTERFACE## _Selector, function_selector_address) \
} }
// clang-format on
void detour_interface_selector(const String& interface_name, uintptr_t function_selector_address) { void
detour_interface_selector(const String& interface_name, uintptr_t function_selector_address) {
LOG_DEBUG("Detected interface: '{}'", interface_name); LOG_DEBUG("Detected interface: '{}'", interface_name);
DETOUR_SELECTOR(IClientAppManager) DETOUR_SELECTOR(IClientAppManager)
@@ -100,8 +103,12 @@ namespace store::steamclient {
DETOUR_SELECTOR(IClientUtils) DETOUR_SELECTOR(IClientUtils)
} }
uintptr_t get_absolute_address(ZydisDecodedInstruction instruction, uintptr_t address) { uintptr_t get_absolute_address(
const auto operand = instruction.operands[0]; const ZydisDecodedInstruction instruction, //
const ZydisDecodedOperand operands[], //
const uintptr_t address
) {
const auto operand = operands[0];
if (operand.imm.is_relative) { if (operand.imm.is_relative) {
ZyanU64 absolute_address; ZyanU64 absolute_address;
@@ -110,11 +117,14 @@ namespace store::steamclient {
return absolute_address; return absolute_address;
} }
return (uintptr_t) operand.imm.value.u; return (uintptr_t)operand.imm.value.u;
} }
bool is_push_immediate(const ZydisDecodedInstruction& instruction) { bool is_push_immediate(
const auto& operand = instruction.operands[0]; const ZydisDecodedInstruction& instruction, //
const ZydisDecodedOperand operands[]
) {
const auto& operand = operands[0];
return instruction.mnemonic == ZYDIS_MNEMONIC_PUSH && return instruction.mnemonic == ZYDIS_MNEMONIC_PUSH &&
operand.type == ZYDIS_OPERAND_TYPE_IMMEDIATE && operand.type == ZYDIS_OPERAND_TYPE_IMMEDIATE &&
@@ -122,8 +132,11 @@ namespace store::steamclient {
operand.encoding == ZYDIS_OPERAND_ENCODING_SIMM16_32_32; operand.encoding == ZYDIS_OPERAND_ENCODING_SIMM16_32_32;
} }
std::optional<String> get_string_argument(const ZydisDecodedInstruction& instruction) { std::optional<String> get_string_argument(
const auto* name_address = reinterpret_cast<char*>(instruction.operands[0].imm.value.u); const ZydisDecodedInstruction& instruction, //
const ZydisDecodedOperand operands[]
) {
const auto* name_address = reinterpret_cast<char*>(operands[0].imm.value.u);
if (util::is_valid_pointer(name_address)) { if (util::is_valid_pointer(name_address)) {
return name_address; return name_address;
} }
@@ -132,20 +145,22 @@ namespace store::steamclient {
std::optional<String> get_instruction_string( std::optional<String> get_instruction_string(
const ZydisDecodedInstruction& instruction, const ZydisDecodedInstruction& instruction,
const ZydisDecodedOperand operands[],
const uintptr_t address const uintptr_t address
) { ) {
const auto buffer_size = 64; const auto buffer_size = 64;
char buffer[buffer_size] = {}; char buffer[buffer_size] = {};
if (ZYAN_SUCCESS( if (ZYAN_SUCCESS(ZydisFormatterFormatInstruction(
ZydisFormatterFormatInstruction(
&formatter, &formatter,
&instruction, &instruction,
operands,
instruction.operand_count,
buffer, buffer,
buffer_size, buffer_size,
address address,
) ZYAN_NULL
)) { ))) {
return buffer; return buffer;
} }
@@ -155,16 +170,18 @@ namespace store::steamclient {
std::optional<String> find_interface_name(uintptr_t selector_address) { std::optional<String> find_interface_name(uintptr_t selector_address) {
auto current_address = selector_address; auto current_address = selector_address;
ZydisDecodedInstruction instruction{}; ZydisDecodedInstruction instruction{};
while (ZYAN_SUCCESS(ZydisDecoderDecodeBuffer( ZydisDecodedOperand operands[ZYDIS_MAX_OPERAND_COUNT];
&decoder, while (ZYAN_SUCCESS(ZydisDecoderDecodeFull(
(void*) current_address, &decoder, // decoder
MAX_INSTRUCTION_SIZE, reinterpret_cast<void*>(current_address), // buffer
&instruction MAX_INSTRUCTION_SIZE, // length
&instruction, // instruction
operands // operands
))) { ))) {
const auto debug_str = get_instruction_string(instruction, current_address); // const auto debug_str = get_instruction_string(instruction, current_address);
if (is_push_immediate(instruction)) { if (is_push_immediate(instruction, operands)) {
auto string_opt = get_string_argument(instruction); auto string_opt = get_string_argument(instruction, operands);
if (string_opt && string_opt->starts_with("IClient")) { if (string_opt && string_opt->starts_with("IClient")) {
return string_opt; return string_opt;
@@ -181,24 +198,29 @@ namespace store::steamclient {
return std::nullopt; return std::nullopt;
} }
struct full_instruction {
const ZydisDecodedInstruction instruction;
const std::vector<ZydisDecodedOperand> operands;
};
/** /**
* Recursively walks through the code, until a return instruction is reached. * Recursively walks through the code, until a return instruction is reached.
* Recursion occurs whenever a jump/branch is encountered. * Recursion occurs whenever a jump/branch is encountered.
*/ */
template<typename T> template<typename T>
void visit_code( // NOLINT(misc-no-recursion) void visit_code( // NOLINT(misc-no-recursion)
Set<uintptr_t>& visited_addresses, std::set<uintptr_t>& visited_addresses,
uintptr_t start_address, uintptr_t start_address,
T context, T context,
const Function<bool( const std::function<bool(
const ZydisDecodedInstruction& instruction, const ZydisDecodedInstruction& instruction,
const ZydisDecodedOperand& operand, const ZydisDecodedOperand operand[],
const uintptr_t& current_address, const uintptr_t& current_address,
T& context, T& context,
const std::list<ZydisDecodedInstruction>& instruction_list const std::list<full_instruction>& instruction_list
)>& callback )>& callback
) { ) {
LOG_TRACE("{} -> start_address: {}", __func__, (void*) start_address); LOG_TRACE("{} -> start_address: {}", __func__, reinterpret_cast<void*>(start_address));
if (visited_addresses.contains(start_address)) { if (visited_addresses.contains(start_address)) {
LOG_TRACE("Breaking recursion due to visited address"); LOG_TRACE("Breaking recursion due to visited address");
@@ -206,34 +228,36 @@ namespace store::steamclient {
} }
auto current_address = start_address; auto current_address = start_address;
std::list instruction_list{ZydisDecodedInstruction{}}; std::list<full_instruction> instruction_list;
ZydisDecodedInstruction instruction{}; ZydisDecodedInstruction instruction{};
while ( ZydisDecodedOperand operands[ZYDIS_MAX_OPERAND_COUNT];
ZYAN_SUCCESS( while (ZYAN_SUCCESS(ZydisDecoderDecodeFull(
ZydisDecoderDecodeBuffer( &decoder, // decoder
&decoder, (void*)current_address, // buffer
(void*) current_address, MAX_INSTRUCTION_SIZE, // length
MAX_INSTRUCTION_SIZE, &instruction, // instructions
&instruction operands // operands
) ))) {
)) {
visited_addresses.insert(current_address); visited_addresses.insert(current_address);
LOG_TRACE( LOG_TRACE(
"{} -> visiting {} │ {}", "{} -> visiting {} │ {}",
__func__, (void*) current_address, *get_instruction_string(instruction, current_address) __func__,
reinterpret_cast<void*>(current_address),
*get_instruction_string(instruction, operands, current_address)
); );
const auto operand = instruction.operands[0]; const auto should_return =
callback(instruction, operands, current_address, context, instruction_list);
const auto should_return = callback(instruction, operand, current_address, context, instruction_list);
if (should_return) { if (should_return) {
return; return;
} }
if (instruction.meta.category == ZYDIS_CATEGORY_COND_BR) { if (instruction.meta.category == ZYDIS_CATEGORY_COND_BR) {
const auto jump_taken_destination = get_absolute_address(instruction, current_address); const auto jump_taken_destination =
get_absolute_address(instruction, operands, current_address);
const auto jump_not_taken_destination = current_address + instruction.length; const auto jump_not_taken_destination = current_address + instruction.length;
visit_code(visited_addresses, jump_taken_destination, context, callback); visit_code(visited_addresses, jump_taken_destination, context, callback);
@@ -243,24 +267,28 @@ namespace store::steamclient {
return; return;
} }
if (instruction.mnemonic == ZYDIS_MNEMONIC_JMP && operand.type == ZYDIS_OPERAND_TYPE_IMMEDIATE) { const auto& operand = operands[0];
const auto jump_destination = get_absolute_address(instruction, current_address);
if (instruction.mnemonic == ZYDIS_MNEMONIC_JMP &&
operand.type == ZYDIS_OPERAND_TYPE_IMMEDIATE) {
const auto jump_destination =
get_absolute_address(instruction, operands, current_address);
visit_code(visited_addresses, jump_destination, context, callback); visit_code(visited_addresses, jump_destination, context, callback);
LOG_TRACE("{} -> Breaking recursion due to an unconditional jump", __func__) LOG_TRACE("{} -> Breaking recursion due to an unconditional jump", __func__);
return; return;
} }
if (instruction.mnemonic == ZYDIS_MNEMONIC_JMP && if (instruction.mnemonic == ZYDIS_MNEMONIC_JMP &&
operand.type == ZYDIS_OPERAND_TYPE_MEMORY && operand.type == ZYDIS_OPERAND_TYPE_MEMORY &&
operand.mem.scale == sizeof(uintptr_t) && operand.mem.scale == sizeof(uintptr_t) && operand.mem.disp.has_displacement) {
operand.mem.disp.has_displacement) { // Special handling for jump tables. Guaranteed to be present in the interface
// Special handling for jump tables. Guaranteed to be present in the interface selector. // selector.
const auto* table = (uintptr_t*) operand.mem.disp.value; const auto* table = (uintptr_t*)operand.mem.disp.value;
const auto* table_entry = table; const auto* table_entry = table;
while (util::is_valid_pointer((void*) *table_entry)) { while (util::is_valid_pointer((void*)*table_entry)) {
visit_code(visited_addresses, *table_entry, context, callback); visit_code(visited_addresses, *table_entry, context, callback);
table_entry++; table_entry++;
@@ -275,10 +303,16 @@ namespace store::steamclient {
return; return;
} }
// We push items to the front so that it becomes easy to iterate over instructions // We push items to the front so that it becomes easy to iterate over instructions
// in reverse order of addition. // in reverse order of addition.
instruction_list.push_front(instruction);
std::vector<ZydisDecodedOperand> operand_list;
for (auto i = 0U; i < instruction.operand_count; i++) {
operand_list.emplace_back(operands[i]);
}
instruction_list.push_front(
{.instruction = instruction, .operands = std::move(operand_list)}
);
current_address += instruction.length; current_address += instruction.length;
} }
} }
@@ -289,35 +323,39 @@ namespace store::steamclient {
uintptr_t start_address uintptr_t start_address
) { ) {
Set<uintptr_t> visited_addresses; Set<uintptr_t> visited_addresses;
visit_code<InstructionContext>(visited_addresses, start_address, {}, [&]( visit_code<InstructionContext>(
const ZydisDecodedInstruction& instruction, visited_addresses,
const ZydisDecodedOperand& operand, start_address,
{},
[&](const ZydisDecodedInstruction& instruction,
const ZydisDecodedOperand operands[],
const auto&, const auto&,
InstructionContext& context, InstructionContext& context,
const std::list<ZydisDecodedInstruction>& instruction_list const std::list<full_instruction>& instruction_list) {
) { if (context.function_name &&
if (context.function_name && function_name_to_ordinal_map.contains(*context.function_name)) { function_name_to_ordinal_map.contains(*context.function_name)) {
// Avoid duplicate work // Avoid duplicate work
return true; return true;
} }
const auto& last_instruction = instruction_list.front(); const auto& last = instruction_list.front();
const auto is_mov_base_esp = instruction.mnemonic == ZYDIS_MNEMONIC_MOV && const auto is_mov_base_esp = instruction.mnemonic == ZYDIS_MNEMONIC_MOV &&
instruction.operand_count == 2 && instruction.operand_count == 2 &&
instruction.operands[0].type == ZYDIS_OPERAND_TYPE_REGISTER && operands[0].type == ZYDIS_OPERAND_TYPE_REGISTER &&
instruction.operands[1].reg.value == ZYDIS_REGISTER_ESP; operands[1].reg.value == ZYDIS_REGISTER_ESP;
if (!context.base_register && is_mov_base_esp) { if (!context.base_register && is_mov_base_esp) {
// Save base register // Save base register
context.base_register = instruction.operands[0].reg.value; context.base_register = operands[0].reg.value;
} else if (is_push_immediate(last_instruction) && } else if ( //
is_push_immediate(instruction) && is_push_immediate( last.instruction, last.operands.data() ) &&
!context.function_name) { is_push_immediate(instruction, operands) && !context.function_name) {
// The very first 2 consecutive pushes indicate interface and function names. // The very first 2 consecutive pushes indicate interface and function names.
// However, subsequent pushes may contain irrelevant strings. // However, subsequent pushes may contain irrelevant strings.
const auto push_string_1 = get_string_argument(last_instruction); const auto push_string_1 =
const auto push_string_2 = get_string_argument(instruction); get_string_argument(last.instruction, last.operands.data());
const auto push_string_2 = get_string_argument(instruction, operands);
if (push_string_1 && push_string_2) { if (push_string_1 && push_string_2) {
if (*push_string_1 == target_interface) { if (*push_string_1 == target_interface) {
@@ -326,7 +364,8 @@ namespace store::steamclient {
context.function_name = push_string_1; context.function_name = push_string_1;
} }
if (context.function_name && function_name_to_ordinal_map.contains(*context.function_name)) { if (context.function_name &&
function_name_to_ordinal_map.contains(*context.function_name)) {
// Bail early to avoid duplicate work // Bail early to avoid duplicate work
return true; return true;
} }
@@ -338,28 +377,30 @@ namespace store::steamclient {
const auto& base_register = *(context.base_register); const auto& base_register = *(context.base_register);
const auto& function_name = *(context.function_name); const auto& function_name = *(context.function_name);
std::optional<uint32_t> offset; std::optional<uint32_t> offset;
auto last_destination_reg = ZYDIS_REGISTER_NONE; auto last_destination_reg = ZYDIS_REGISTER_NONE;
bool is_derived_from_base_reg = false; bool is_derived_from_base_reg = false;
const auto& operand = operands[0];
// Sometimes the offset is present in the call instruction itself, // Sometimes the offset is present in the call instruction itself,
// hence we can immediately obtain it. // hence we can immediately obtain it.
if (operand.type == ZYDIS_OPERAND_TYPE_MEMORY && operand.mem.base != ZYDIS_REGISTER_NONE) { if (operand.type == ZYDIS_OPERAND_TYPE_MEMORY &&
operand.mem.base != ZYDIS_REGISTER_NONE) {
offset = static_cast<uint32_t>(operand.mem.disp.value); offset = static_cast<uint32_t>(operand.mem.disp.value);
last_destination_reg = operand.mem.base; last_destination_reg = operand.mem.base;
} else if (operand.type == ZYDIS_OPERAND_TYPE_REGISTER) { } else if (operand.type == ZYDIS_OPERAND_TYPE_REGISTER) {
last_destination_reg = operand.reg.value; last_destination_reg = operand.reg.value;
} }
for (const auto& previous_instruction: instruction_list) { for (const auto& previous : instruction_list) {
const auto& destination_operand = previous_instruction.operands[0]; const auto& destination_operand = previous.operands[0];
const auto& source_operand = previous_instruction.operands[1]; const auto& source_operand = previous.operands[1];
// Extract offset if necessary // Extract offset if necessary
if (previous_instruction.mnemonic == ZYDIS_MNEMONIC_MOV && if (previous.instruction.mnemonic == ZYDIS_MNEMONIC_MOV &&
previous_instruction.operand_count == 2 && previous.instruction.operand_count == 2 &&
destination_operand.reg.value == last_destination_reg && destination_operand.reg.value == last_destination_reg &&
source_operand.type == ZYDIS_OPERAND_TYPE_MEMORY) { source_operand.type == ZYDIS_OPERAND_TYPE_MEMORY) {
@@ -367,8 +408,9 @@ namespace store::steamclient {
if (source_mem.base == base_register && if (source_mem.base == base_register &&
source_mem.disp.has_displacement && source_mem.disp.has_displacement &&
source_mem.disp.value == 8) { source_mem.disp.value == 8) {
// We have verified that the chain eventually leads up to the base register. // We have verified that the chain eventually leads up to the
// Hence, we can conclude that the offset is valid. // base register. Hence, we can conclude that the offset is
// valid.
is_derived_from_base_reg = true; is_derived_from_base_reg = true;
break; break;
} }
@@ -385,7 +427,12 @@ namespace store::steamclient {
if (offset && is_derived_from_base_reg) { if (offset && is_derived_from_base_reg) {
const auto ordinal = *offset / sizeof(uintptr_t); const auto ordinal = *offset / sizeof(uintptr_t);
LOG_DEBUG("Found function ordinal {}::{}@{}", target_interface, function_name, ordinal); LOG_DEBUG(
"Found function ordinal {}::{}@{}",
target_interface,
function_name,
ordinal
);
function_name_to_ordinal_map[function_name] = ordinal; function_name_to_ordinal_map[function_name] = ordinal;
return true; return true;
@@ -402,17 +449,21 @@ namespace store::steamclient {
const uintptr_t start_address, const uintptr_t start_address,
Set<uintptr_t>& visited_addresses Set<uintptr_t>& visited_addresses
) { ) {
visit_code<nullptr_t>(visited_addresses, start_address, nullptr, []( visit_code<nullptr_t>(
const ZydisDecodedInstruction& instruction, visited_addresses,
const ZydisDecodedOperand& operand, start_address,
const auto& current_address, nullptr,
auto, [](const ZydisDecodedInstruction& instruction,
const auto& const ZydisDecodedOperand operands[],
) { const auto& current_address,
if (instruction.mnemonic == ZYDIS_MNEMONIC_CALL && operand.type == ZYDIS_OPERAND_TYPE_IMMEDIATE) { auto,
LOG_TRACE("Found call instruction at {}", (void*) current_address); const auto&) {
if (instruction.mnemonic == ZYDIS_MNEMONIC_CALL &&
operands[0].type == ZYDIS_OPERAND_TYPE_IMMEDIATE) {
LOG_TRACE("Found call instruction at {}", (void*)current_address);
const auto function_selector_address = get_absolute_address(instruction, current_address); const auto function_selector_address =
get_absolute_address(instruction, operands, current_address);
const auto interface_name_opt = find_interface_name(function_selector_address); const auto interface_name_opt = find_interface_name(function_selector_address);
@@ -429,16 +480,16 @@ namespace store::steamclient {
} }
void process_client_engine(uintptr_t interface) { void process_client_engine(uintptr_t interface) {
const auto* steam_client_internal = ((uintptr_t***) interface)[ const auto* steam_client_internal =
store::config.client_engine_steam_client_internal_ordinal ((uintptr_t***)interface)[store::config.client_engine_steam_client_internal_ordinal];
]; const auto interface_selector_address = (*steam_client_internal
const auto interface_selector_address = (*steam_client_internal)[ )[store::config.steam_client_internal_interface_selector_ordinal];
store::config.steam_client_internal_interface_selector_ordinal
];
LOG_DEBUG("Found interface selector at: {}", (void*) interface_selector_address); LOG_DEBUG("Found interface selector at: {}", (void*)interface_selector_address);
if (ZYAN_FAILED(ZydisDecoderInit(&decoder, ZYDIS_MACHINE_MODE_LEGACY_32, ZYDIS_STACK_WIDTH_32))) { if (ZYAN_FAILED(
ZydisDecoderInit(&decoder, ZYDIS_MACHINE_MODE_LEGACY_32, ZYDIS_STACK_WIDTH_32)
)) {
LOG_ERROR("Failed to initialize zydis decoder"); LOG_ERROR("Failed to initialize zydis decoder");
return; return;
} }

View File

@@ -10,14 +10,14 @@
#include <store_mode/store_api.hpp> #include <store_mode/store_api.hpp>
#include <store_mode/store_cache.hpp> #include <store_mode/store_cache.hpp>
#include <store_mode/vstdlib/vstdlib.hpp> #include <store_mode/vstdlib/vstdlib.hpp>
#include <core/globals.hpp>
namespace store { namespace {
using namespace store;
StoreConfig config; // NOLINT(cert-err58-cpp)
/** /**
* @return A string representing the source of the config. * @return A string representing the source of the config.
*/ */
void init_store_config() { void init_store_config() {
const auto print_source = [](const String& source) { const auto print_source = [](const String& source) {
LOG_INFO("Loaded Store config from the {}", source); LOG_INFO("Loaded Store config from the {}", source);
@@ -50,47 +50,62 @@ namespace store {
config = {}; config = {};
} }
// Finally, fetch the remote config from GitHub, and inform user about the need to restart Steam, // Finally, fetch the remote config from GitHub, and inform user about the need to restart
// if a new config has been fetched // Steam, if a new config has been fetched
NEW_THREAD({ std::thread([] {
try { try {
const auto github_config_opt = api::fetch_store_config(); const auto github_config_opt = api::fetch_store_config();
if (!github_config_opt) { if (!github_config_opt) {
return; return;
} }
const auto github_config = *github_config_opt; const auto github_config = *github_config_opt;
store_cache::save_store_config(github_config); store_cache::save_store_config(github_config);
if (github_config == config) { if (github_config == config) {
LOG_DEBUG("Fetched Store config is equal to existing config"); (spdlog::default_logger_raw())
->log(
spdlog::source_loc{
"store.cpp", 66, static_cast<const char*>(__FUNCTION__)
},
spdlog::level::debug,
"Fetched Store config is equal to existing config"
);
return; return;
} }
(spdlog::default_logger_raw())
LOG_DEBUG("Fetched a new Store config") ->log(
spdlog::source_loc{"store.cpp", 66, static_cast<const char*>(__FUNCTION__)},
::MessageBox( spdlog::level::debug,
"Fetched a new Store config"
);
MessageBoxW(
nullptr, nullptr,
TEXT( L"SmokeAPI has downloaded an updated config for Store mode. "
"SmokeAPI has downloaded an updated config for Store mode. " "Please restart Steam in order to apply the new Store config. ",
"Please restart Steam in order to apply the new Store config. " L"SmokeAPI - Store",
), 0x00010000L | 0x00000040L | 0x00000000L
TEXT("SmokeAPI - Store"),
MB_SETFOREGROUND | MB_ICONINFORMATION | MB_OK
); );
} catch (const Exception& ex) { } catch (const Exception& ex) {
LOG_ERROR("Failed to get remote store_mode config: {}", ex.what()); (spdlog::default_logger_raw())
->log(
spdlog::source_loc{"store.cpp", 66, static_cast<const char*>(__FUNCTION__)},
spdlog::level::err,
"Failed to get remote store_mode config: {}",
ex.what()
);
} }
}) }).detach();
} }
}
namespace store {
StoreConfig config; // NOLINT(cert-err58-cpp)
void init_store_mode() { void init_store_mode() {
init_store_config(); init_store_config();
koalabox::dll_monitor::init_listener( koalabox::dll_monitor::init_listener(
{VSTDLIB_DLL, STEAMCLIENT_DLL}, [](const HMODULE& module_handle, const String& name) { {VSTDLIB_DLL, STEAMCLIENT_DLL},
[](const HMODULE& module_handle, const String& name) {
try { try {
if (koalabox::str::eq(name, VSTDLIB_DLL)) { if (koalabox::str::eq(name, VSTDLIB_DLL)) {
// VStdLib DLL handles Family Sharing functions // VStdLib DLL handles Family Sharing functions
@@ -108,32 +123,35 @@ namespace store {
DETOUR_STEAMCLIENT(CreateInterface) DETOUR_STEAMCLIENT(CreateInterface)
} }
if (globals::vstdlib_module != nullptr && globals::steamclient_module != nullptr) { if (globals::vstdlib_module != nullptr &&
globals::steamclient_module != nullptr) {
koalabox::dll_monitor::shutdown_listener(); koalabox::dll_monitor::shutdown_listener();
} }
} catch (const Exception& ex) { } catch (const Exception& ex) {
LOG_ERROR( LOG_ERROR(
"Error listening to DLL load events. Module: '{}', Message: {}", "Error listening to DLL load events. Module: '{}', Message: {}",
name, ex.what() name,
ex.what()
); );
} }
} }
); );
NEW_THREAD({ std::thread([=] {
koalabox::ipc::init_pipe_server("smokeapi.store.steam", [](const koalabox::ipc::Request& request) { koalabox::ipc::init_pipe_server(
koalabox::ipc::Response response; "smokeapi.store.steam",
[](const koalabox::ipc::Request& request) {
if (request.name < equals > "config::reload") { koalabox::ipc::Response response;
smoke_api::config::ReloadConfig(); if (koalabox::str::eq(request.name, "config::reload")) {
response.success = true; smoke_api::config::ReloadConfig();
} else { response.success = true;
response.success = false; } else {
response.data["error_message"] = "Invalid request name: " + request.name; response.success = false;
response.data["error_message"] = "Invalid request name: " + request.name;
}
return response;
} }
);
return response; }).detach();
});
})
} }
} }

View File

@@ -11,7 +11,7 @@ namespace store::api {
return kg_config_json.get<StoreConfig>(); return kg_config_json.get<StoreConfig>();
} catch (const Exception& e) { } catch (const Exception& e) {
LOG_ERROR("Failed to fetch Store config from GitHub: {}", e.what()) LOG_ERROR("Failed to fetch Store config from GitHub: {}", e.what());
return std::nullopt; return std::nullopt;
} }
} }

View File

@@ -9,7 +9,7 @@ namespace store::store_cache {
try { try {
return koalabox::cache::get(KEY_KG_CONFIG, Json(nullptr)).get<StoreConfig>(); return koalabox::cache::get(KEY_KG_CONFIG, Json(nullptr)).get<StoreConfig>();
} catch (const Exception& e) { } catch (const Exception& e) {
LOG_ERROR("Failed to get cached store_mode config: {}", e.what()) LOG_ERROR("Failed to get cached store_mode config: {}", e.what());
return std::nullopt; return std::nullopt;
} }
@@ -17,11 +17,11 @@ namespace store::store_cache {
bool save_store_config(const StoreConfig& config) { bool save_store_config(const StoreConfig& config) {
try { try {
LOG_DEBUG("Caching store_mode config") LOG_DEBUG("Caching store_mode config");
return koalabox::cache::put(KEY_KG_CONFIG, Json(config)); return koalabox::cache::put(KEY_KG_CONFIG, Json(config));
} catch (const Exception& e) { } catch (const Exception& e) {
LOG_ERROR("Failed to cache store_mode config: {}", e.what()) LOG_ERROR("Failed to cache store_mode config: {}", e.what());
return false; return false;
} }

View File

@@ -2,13 +2,13 @@
namespace store::vstdlib { namespace store::vstdlib {
VIRTUAL(bool) SharedLicensesLockStatus(PARAMS(void* arg)) { VIRTUAL(bool) SharedLicensesLockStatus(PARAMS(void* arg)) {
LOG_DEBUG("{}(this={}, arg={})", __func__, THIS, arg) LOG_DEBUG("{}(this={}, arg={})", __func__, THIS, arg);
ARGS(); ARGS();
return true; return true;
} }
VIRTUAL(bool) SharedLibraryStopPlaying(PARAMS(void* arg)) { VIRTUAL(bool) SharedLibraryStopPlaying(PARAMS(void* arg)) {
LOG_DEBUG("{}(this={}, arg={})", __func__, THIS, arg) LOG_DEBUG("{}(this={}, arg={})", __func__, THIS, arg);
ARGS(); ARGS();
return true; return true;
} }
@@ -28,7 +28,7 @@ namespace store::vstdlib {
if (data && data->get_callback_name()) { if (data && data->get_callback_name()) {
const auto name = String(data->get_callback_name()); const auto name = String(data->get_callback_name());
LOG_TRACE("{}(ecx={}, edx={}, name='{}')", __func__, ARGS(), name) LOG_TRACE("{}(ecx={}, edx={}, name='{}')", __func__, ARGS(), name);
if (name == "SharedLicensesLockStatus" && !lock_status_hooked) { if (name == "SharedLicensesLockStatus" && !lock_status_hooked) {
DETOUR_ADDRESS(SharedLicensesLockStatus, data->get_callback_data()->get_callback_address()) DETOUR_ADDRESS(SharedLicensesLockStatus, data->get_callback_data()->get_callback_address())
lock_status_hooked = true; lock_status_hooked = true;