cheat_engine.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. // Copyright 2018 yuzu emulator team
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <locale>
  5. #include "common/hex_util.h"
  6. #include "common/microprofile.h"
  7. #include "common/swap.h"
  8. #include "core/core.h"
  9. #include "core/core_timing.h"
  10. #include "core/hle/kernel/k_page_table.h"
  11. #include "core/hle/kernel/k_process.h"
  12. #include "core/hle/service/hid/controllers/npad.h"
  13. #include "core/hle/service/hid/hid.h"
  14. #include "core/hle/service/sm/sm.h"
  15. #include "core/memory.h"
  16. #include "core/memory/cheat_engine.h"
  17. namespace Core::Memory {
  18. namespace {
  19. constexpr auto CHEAT_ENGINE_NS = std::chrono::nanoseconds{1000000000 / 12};
  20. constexpr u32 KEYPAD_BITMASK = 0x3FFFFFF;
  21. std::string_view ExtractName(std::string_view data, 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. (end_index - start_index - 1) > sizeof(CheatDefinition::readable_name)) {
  27. return {};
  28. }
  29. }
  30. return data.substr(start_index, end_index - start_index);
  31. }
  32. } // Anonymous namespace
  33. StandardVmCallbacks::StandardVmCallbacks(System& system_, const CheatProcessMetadata& metadata_)
  34. : metadata{metadata_}, system{system_} {}
  35. StandardVmCallbacks::~StandardVmCallbacks() = default;
  36. void StandardVmCallbacks::MemoryRead(VAddr address, void* data, u64 size) {
  37. system.Memory().ReadBlock(SanitizeAddress(address), data, size);
  38. }
  39. void StandardVmCallbacks::MemoryWrite(VAddr address, const void* data, u64 size) {
  40. system.Memory().WriteBlock(SanitizeAddress(address), data, size);
  41. }
  42. u64 StandardVmCallbacks::HidKeysDown() {
  43. const auto applet_resource =
  44. system.ServiceManager().GetService<Service::HID::Hid>("hid")->GetAppletResource();
  45. if (applet_resource == nullptr) {
  46. LOG_WARNING(CheatEngine,
  47. "Attempted to read input state, but applet resource is not initialized!");
  48. return 0;
  49. }
  50. const auto press_state =
  51. applet_resource
  52. ->GetController<Service::HID::Controller_NPad>(Service::HID::HidController::NPad)
  53. .GetAndResetPressState();
  54. return press_state & KEYPAD_BITMASK;
  55. }
  56. void StandardVmCallbacks::DebugLog(u8 id, u64 value) {
  57. LOG_INFO(CheatEngine, "Cheat triggered DebugLog: ID '{:01X}' Value '{:016X}'", id, value);
  58. }
  59. void StandardVmCallbacks::CommandLog(std::string_view data) {
  60. LOG_DEBUG(CheatEngine, "[DmntCheatVm]: {}",
  61. data.back() == '\n' ? data.substr(0, data.size() - 1) : data);
  62. }
  63. VAddr StandardVmCallbacks::SanitizeAddress(VAddr in) const {
  64. if ((in < metadata.main_nso_extents.base ||
  65. in >= metadata.main_nso_extents.base + metadata.main_nso_extents.size) &&
  66. (in < metadata.heap_extents.base ||
  67. in >= metadata.heap_extents.base + metadata.heap_extents.size)) {
  68. LOG_ERROR(CheatEngine,
  69. "Cheat attempting to access memory at invalid address={:016X}, if this "
  70. "persists, "
  71. "the cheat may be incorrect. However, this may be normal early in execution if "
  72. "the game has not properly set up yet.",
  73. in);
  74. return 0; ///< Invalid addresses will hard crash
  75. }
  76. return in;
  77. }
  78. CheatParser::~CheatParser() = default;
  79. TextCheatParser::~TextCheatParser() = default;
  80. std::vector<CheatEntry> TextCheatParser::Parse(std::string_view data) const {
  81. std::vector<CheatEntry> out(1);
  82. std::optional<u64> current_entry;
  83. for (std::size_t i = 0; i < data.size(); ++i) {
  84. if (::isspace(data[i])) {
  85. continue;
  86. }
  87. if (data[i] == '{') {
  88. current_entry = 0;
  89. if (out[*current_entry].definition.num_opcodes > 0) {
  90. return {};
  91. }
  92. const auto name = ExtractName(data, i + 1, '}');
  93. if (name.empty()) {
  94. return {};
  95. }
  96. std::memcpy(out[*current_entry].definition.readable_name.data(), name.data(),
  97. std::min<std::size_t>(out[*current_entry].definition.readable_name.size(),
  98. name.size()));
  99. out[*current_entry]
  100. .definition.readable_name[out[*current_entry].definition.readable_name.size() - 1] =
  101. '\0';
  102. i += name.length() + 1;
  103. } else if (data[i] == '[') {
  104. current_entry = out.size();
  105. out.emplace_back();
  106. const auto name = ExtractName(data, i + 1, ']');
  107. if (name.empty()) {
  108. return {};
  109. }
  110. std::memcpy(out[*current_entry].definition.readable_name.data(), name.data(),
  111. std::min<std::size_t>(out[*current_entry].definition.readable_name.size(),
  112. name.size()));
  113. out[*current_entry]
  114. .definition.readable_name[out[*current_entry].definition.readable_name.size() - 1] =
  115. '\0';
  116. i += name.length() + 1;
  117. } else if (::isxdigit(data[i])) {
  118. if (!current_entry || out[*current_entry].definition.num_opcodes >=
  119. out[*current_entry].definition.opcodes.size()) {
  120. return {};
  121. }
  122. const auto hex = std::string(data.substr(i, 8));
  123. if (!std::all_of(hex.begin(), hex.end(), ::isxdigit)) {
  124. return {};
  125. }
  126. const auto value = static_cast<u32>(std::stoul(hex, nullptr, 0x10));
  127. out[*current_entry].definition.opcodes[out[*current_entry].definition.num_opcodes++] =
  128. value;
  129. i += 8;
  130. } else {
  131. return {};
  132. }
  133. }
  134. out[0].enabled = out[0].definition.num_opcodes > 0;
  135. out[0].cheat_id = 0;
  136. for (u32 i = 1; i < out.size(); ++i) {
  137. out[i].enabled = out[i].definition.num_opcodes > 0;
  138. out[i].cheat_id = i;
  139. }
  140. return out;
  141. }
  142. CheatEngine::CheatEngine(System& system_, std::vector<CheatEntry> cheats_,
  143. const std::array<u8, 0x20>& build_id_)
  144. : vm{std::make_unique<StandardVmCallbacks>(system_, metadata)},
  145. cheats(std::move(cheats_)), core_timing{system_.CoreTiming()}, system{system_} {
  146. metadata.main_nso_build_id = build_id_;
  147. }
  148. CheatEngine::~CheatEngine() {
  149. core_timing.UnscheduleEvent(event, 0);
  150. }
  151. void CheatEngine::Initialize() {
  152. event = Core::Timing::CreateEvent(
  153. "CheatEngine::FrameCallback::" + Common::HexToString(metadata.main_nso_build_id),
  154. [this](std::uintptr_t user_data, std::chrono::nanoseconds ns_late) {
  155. FrameCallback(user_data, ns_late);
  156. });
  157. core_timing.ScheduleEvent(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. core_timing.ScheduleEvent(CHEAT_ENGINE_NS - ns_late, event);
  196. }
  197. } // namespace Core::Memory