cheat_engine.cpp 9.6 KB

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