cheat_engine.cpp 9.2 KB

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