cheat_engine.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. // SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <locale>
  4. #include "common/hex_util.h"
  5. #include "common/microprofile.h"
  6. #include "common/swap.h"
  7. #include "core/core.h"
  8. #include "core/core_timing.h"
  9. #include "core/hle/kernel/k_page_table.h"
  10. #include "core/hle/kernel/k_process.h"
  11. #include "core/hle/service/hid/hid_server.h"
  12. #include "core/hle/service/sm/sm.h"
  13. #include "core/memory.h"
  14. #include "core/memory/cheat_engine.h"
  15. #include "hid_core/resource_manager.h"
  16. #include "hid_core/resources/npad/npad.h"
  17. namespace Core::Memory {
  18. namespace {
  19. constexpr auto CHEAT_ENGINE_NS = std::chrono::nanoseconds{1000000000 / 12};
  20. std::string_view ExtractName(std::size_t& out_name_size, std::string_view data,
  21. std::size_t start_index, char match) {
  22. auto end_index = start_index;
  23. while (data[end_index] != match) {
  24. ++end_index;
  25. if (end_index > data.size()) {
  26. return {};
  27. }
  28. }
  29. out_name_size = end_index - start_index;
  30. // Clamp name if it's too big
  31. if (out_name_size > sizeof(CheatDefinition::readable_name)) {
  32. end_index = start_index + sizeof(CheatDefinition::readable_name);
  33. }
  34. return data.substr(start_index, end_index - start_index);
  35. }
  36. } // Anonymous namespace
  37. StandardVmCallbacks::StandardVmCallbacks(System& system_, const CheatProcessMetadata& metadata_)
  38. : metadata{metadata_}, system{system_} {}
  39. StandardVmCallbacks::~StandardVmCallbacks() = default;
  40. void StandardVmCallbacks::MemoryRead(VAddr address, void* data, u64 size) {
  41. system.ApplicationMemory().ReadBlock(SanitizeAddress(address), data, size);
  42. }
  43. void StandardVmCallbacks::MemoryWrite(VAddr address, const void* data, u64 size) {
  44. system.ApplicationMemory().WriteBlock(SanitizeAddress(address), data, size);
  45. }
  46. u64 StandardVmCallbacks::HidKeysDown() {
  47. const auto hid = system.ServiceManager().GetService<Service::HID::IHidServer>("hid");
  48. if (hid == nullptr) {
  49. LOG_WARNING(CheatEngine, "Attempted to read input state, but hid is not initialized!");
  50. return 0;
  51. }
  52. const auto applet_resource = hid->GetResourceManager();
  53. if (applet_resource == nullptr || applet_resource->GetNpad() == nullptr) {
  54. LOG_WARNING(CheatEngine,
  55. "Attempted to read input state, but applet resource is not initialized!");
  56. return 0;
  57. }
  58. const auto press_state = applet_resource->GetNpad()->GetAndResetPressState();
  59. return static_cast<u64>(press_state & HID::NpadButton::All);
  60. }
  61. void StandardVmCallbacks::DebugLog(u8 id, u64 value) {
  62. LOG_INFO(CheatEngine, "Cheat triggered DebugLog: ID '{:01X}' Value '{:016X}'", id, value);
  63. }
  64. void StandardVmCallbacks::CommandLog(std::string_view data) {
  65. LOG_DEBUG(CheatEngine, "[DmntCheatVm]: {}",
  66. data.back() == '\n' ? data.substr(0, data.size() - 1) : data);
  67. }
  68. VAddr StandardVmCallbacks::SanitizeAddress(VAddr in) const {
  69. if ((in < metadata.main_nso_extents.base ||
  70. in >= metadata.main_nso_extents.base + metadata.main_nso_extents.size) &&
  71. (in < metadata.heap_extents.base ||
  72. in >= metadata.heap_extents.base + metadata.heap_extents.size)) {
  73. LOG_ERROR(CheatEngine,
  74. "Cheat attempting to access memory at invalid address={:016X}, if this "
  75. "persists, "
  76. "the cheat may be incorrect. However, this may be normal early in execution if "
  77. "the game has not properly set up yet.",
  78. in);
  79. return 0; ///< Invalid addresses will hard crash
  80. }
  81. return in;
  82. }
  83. CheatParser::~CheatParser() = default;
  84. TextCheatParser::~TextCheatParser() = default;
  85. std::vector<CheatEntry> TextCheatParser::Parse(std::string_view data) const {
  86. std::vector<CheatEntry> out(1);
  87. std::optional<u64> current_entry;
  88. for (std::size_t i = 0; i < data.size(); ++i) {
  89. if (::isspace(data[i])) {
  90. continue;
  91. }
  92. if (data[i] == '{') {
  93. current_entry = 0;
  94. if (out[*current_entry].definition.num_opcodes > 0) {
  95. return {};
  96. }
  97. std::size_t name_size{};
  98. const auto name = ExtractName(name_size, data, i + 1, '}');
  99. if (name.empty()) {
  100. return {};
  101. }
  102. std::memcpy(out[*current_entry].definition.readable_name.data(), name.data(),
  103. std::min<std::size_t>(out[*current_entry].definition.readable_name.size(),
  104. name.size()));
  105. out[*current_entry]
  106. .definition.readable_name[out[*current_entry].definition.readable_name.size() - 1] =
  107. '\0';
  108. i += name_size + 1;
  109. } else if (data[i] == '[') {
  110. current_entry = out.size();
  111. out.emplace_back();
  112. std::size_t name_size{};
  113. const auto name = ExtractName(name_size, data, i + 1, ']');
  114. if (name.empty()) {
  115. return {};
  116. }
  117. std::memcpy(out[*current_entry].definition.readable_name.data(), name.data(),
  118. std::min<std::size_t>(out[*current_entry].definition.readable_name.size(),
  119. name.size()));
  120. out[*current_entry]
  121. .definition.readable_name[out[*current_entry].definition.readable_name.size() - 1] =
  122. '\0';
  123. i += name_size + 1;
  124. } else if (::isxdigit(data[i])) {
  125. if (!current_entry || out[*current_entry].definition.num_opcodes >=
  126. out[*current_entry].definition.opcodes.size()) {
  127. return {};
  128. }
  129. const auto hex = std::string(data.substr(i, 8));
  130. if (!std::all_of(hex.begin(), hex.end(), ::isxdigit)) {
  131. return {};
  132. }
  133. const auto value = static_cast<u32>(std::strtoul(hex.c_str(), nullptr, 0x10));
  134. out[*current_entry].definition.opcodes[out[*current_entry].definition.num_opcodes++] =
  135. value;
  136. i += 8;
  137. } else {
  138. return {};
  139. }
  140. }
  141. out[0].enabled = out[0].definition.num_opcodes > 0;
  142. out[0].cheat_id = 0;
  143. for (u32 i = 1; i < out.size(); ++i) {
  144. out[i].enabled = out[i].definition.num_opcodes > 0;
  145. out[i].cheat_id = i;
  146. }
  147. return out;
  148. }
  149. CheatEngine::CheatEngine(System& system_, std::vector<CheatEntry> cheats_,
  150. const std::array<u8, 0x20>& build_id_)
  151. : vm{std::make_unique<StandardVmCallbacks>(system_, metadata)},
  152. cheats(std::move(cheats_)), core_timing{system_.CoreTiming()}, system{system_} {
  153. metadata.main_nso_build_id = build_id_;
  154. }
  155. CheatEngine::~CheatEngine() {
  156. core_timing.UnscheduleEvent(event);
  157. }
  158. void CheatEngine::Initialize() {
  159. event = Core::Timing::CreateEvent(
  160. "CheatEngine::FrameCallback::" + Common::HexToString(metadata.main_nso_build_id),
  161. [this](s64 time,
  162. std::chrono::nanoseconds ns_late) -> std::optional<std::chrono::nanoseconds> {
  163. FrameCallback(ns_late);
  164. return std::nullopt;
  165. });
  166. core_timing.ScheduleLoopingEvent(CHEAT_ENGINE_NS, CHEAT_ENGINE_NS, event);
  167. metadata.process_id = system.ApplicationProcess()->GetProcessId();
  168. metadata.title_id = system.GetApplicationProcessProgramID();
  169. const auto& page_table = system.ApplicationProcess()->GetPageTable();
  170. metadata.heap_extents = {
  171. .base = GetInteger(page_table.GetHeapRegionStart()),
  172. .size = page_table.GetHeapRegionSize(),
  173. };
  174. metadata.address_space_extents = {
  175. .base = GetInteger(page_table.GetAddressSpaceStart()),
  176. .size = page_table.GetAddressSpaceSize(),
  177. };
  178. metadata.alias_extents = {
  179. .base = GetInteger(page_table.GetAliasCodeRegionStart()),
  180. .size = page_table.GetAliasCodeRegionSize(),
  181. };
  182. is_pending_reload.exchange(true);
  183. }
  184. void CheatEngine::SetMainMemoryParameters(VAddr main_region_begin, u64 main_region_size) {
  185. metadata.main_nso_extents = {
  186. .base = main_region_begin,
  187. .size = main_region_size,
  188. };
  189. }
  190. void CheatEngine::Reload(std::vector<CheatEntry> reload_cheats) {
  191. cheats = std::move(reload_cheats);
  192. is_pending_reload.exchange(true);
  193. }
  194. MICROPROFILE_DEFINE(Cheat_Engine, "Add-Ons", "Cheat Engine", MP_RGB(70, 200, 70));
  195. void CheatEngine::FrameCallback(std::chrono::nanoseconds ns_late) {
  196. if (is_pending_reload.exchange(false)) {
  197. vm.LoadProgram(cheats);
  198. }
  199. if (vm.GetProgramSize() == 0) {
  200. return;
  201. }
  202. MICROPROFILE_SCOPE(Cheat_Engine);
  203. vm.Execute(metadata);
  204. }
  205. } // namespace Core::Memory