cheat_engine.cpp 8.1 KB

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