core.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <array>
  5. #include <memory>
  6. #include <utility>
  7. #include "common/file_util.h"
  8. #include "common/logging/log.h"
  9. #include "common/string_util.h"
  10. #include "core/arm/exclusive_monitor.h"
  11. #include "core/core.h"
  12. #include "core/core_cpu.h"
  13. #include "core/core_timing.h"
  14. #include "core/cpu_core_manager.h"
  15. #include "core/file_sys/mode.h"
  16. #include "core/file_sys/registered_cache.h"
  17. #include "core/file_sys/vfs_concat.h"
  18. #include "core/file_sys/vfs_real.h"
  19. #include "core/gdbstub/gdbstub.h"
  20. #include "core/hle/kernel/client_port.h"
  21. #include "core/hle/kernel/kernel.h"
  22. #include "core/hle/kernel/process.h"
  23. #include "core/hle/kernel/scheduler.h"
  24. #include "core/hle/kernel/thread.h"
  25. #include "core/hle/service/am/applets/applets.h"
  26. #include "core/hle/service/service.h"
  27. #include "core/hle/service/sm/sm.h"
  28. #include "core/loader/loader.h"
  29. #include "core/perf_stats.h"
  30. #include "core/settings.h"
  31. #include "core/telemetry_session.h"
  32. #include "core/tools/freezer.h"
  33. #include "file_sys/cheat_engine.h"
  34. #include "video_core/debug_utils/debug_utils.h"
  35. #include "video_core/renderer_base.h"
  36. #include "video_core/video_core.h"
  37. namespace Core {
  38. /*static*/ System System::s_instance;
  39. FileSys::VirtualFile GetGameFileFromPath(const FileSys::VirtualFilesystem& vfs,
  40. const std::string& path) {
  41. // To account for split 00+01+etc files.
  42. std::string dir_name;
  43. std::string filename;
  44. Common::SplitPath(path, &dir_name, &filename, nullptr);
  45. if (filename == "00") {
  46. const auto dir = vfs->OpenDirectory(dir_name, FileSys::Mode::Read);
  47. std::vector<FileSys::VirtualFile> concat;
  48. for (u8 i = 0; i < 0x10; ++i) {
  49. auto next = dir->GetFile(fmt::format("{:02X}", i));
  50. if (next != nullptr)
  51. concat.push_back(std::move(next));
  52. else {
  53. next = dir->GetFile(fmt::format("{:02x}", i));
  54. if (next != nullptr)
  55. concat.push_back(std::move(next));
  56. else
  57. break;
  58. }
  59. }
  60. if (concat.empty())
  61. return nullptr;
  62. return FileSys::ConcatenatedVfsFile::MakeConcatenatedFile(concat, dir->GetName());
  63. }
  64. if (FileUtil::IsDirectory(path))
  65. return vfs->OpenFile(path + "/" + "main", FileSys::Mode::Read);
  66. return vfs->OpenFile(path, FileSys::Mode::Read);
  67. }
  68. struct System::Impl {
  69. explicit Impl(System& system) : kernel{system}, cpu_core_manager{system} {}
  70. Cpu& CurrentCpuCore() {
  71. return cpu_core_manager.GetCurrentCore();
  72. }
  73. ResultStatus RunLoop(bool tight_loop) {
  74. status = ResultStatus::Success;
  75. cpu_core_manager.RunLoop(tight_loop);
  76. return status;
  77. }
  78. ResultStatus Init(System& system, Frontend::EmuWindow& emu_window) {
  79. LOG_DEBUG(HW_Memory, "initialized OK");
  80. core_timing.Initialize();
  81. cpu_core_manager.Initialize();
  82. kernel.Initialize();
  83. const auto current_time = std::chrono::duration_cast<std::chrono::seconds>(
  84. std::chrono::system_clock::now().time_since_epoch());
  85. Settings::values.custom_rtc_differential =
  86. Settings::values.custom_rtc.value_or(current_time) - current_time;
  87. // Create a default fs if one doesn't already exist.
  88. if (virtual_filesystem == nullptr)
  89. virtual_filesystem = std::make_shared<FileSys::RealVfsFilesystem>();
  90. if (content_provider == nullptr)
  91. content_provider = std::make_unique<FileSys::ContentProviderUnion>();
  92. /// Create default implementations of applets if one is not provided.
  93. applet_manager.SetDefaultAppletsIfMissing();
  94. telemetry_session = std::make_unique<Core::TelemetrySession>();
  95. service_manager = std::make_shared<Service::SM::ServiceManager>();
  96. Service::Init(service_manager, system, *virtual_filesystem);
  97. GDBStub::Init();
  98. renderer = VideoCore::CreateRenderer(emu_window, system);
  99. if (!renderer->Init()) {
  100. return ResultStatus::ErrorVideoCore;
  101. }
  102. gpu_core = VideoCore::CreateGPU(system);
  103. is_powered_on = true;
  104. LOG_DEBUG(Core, "Initialized OK");
  105. // Reset counters and set time origin to current frame
  106. GetAndResetPerfStats();
  107. perf_stats.BeginSystemFrame();
  108. return ResultStatus::Success;
  109. }
  110. ResultStatus Load(System& system, Frontend::EmuWindow& emu_window,
  111. const std::string& filepath) {
  112. app_loader = Loader::GetLoader(GetGameFileFromPath(virtual_filesystem, filepath));
  113. if (!app_loader) {
  114. LOG_CRITICAL(Core, "Failed to obtain loader for {}!", filepath);
  115. return ResultStatus::ErrorGetLoader;
  116. }
  117. ResultStatus init_result{Init(system, emu_window)};
  118. if (init_result != ResultStatus::Success) {
  119. LOG_CRITICAL(Core, "Failed to initialize system (Error {})!",
  120. static_cast<int>(init_result));
  121. Shutdown();
  122. return init_result;
  123. }
  124. telemetry_session->AddInitialInfo(*app_loader);
  125. auto main_process = Kernel::Process::Create(system, "main");
  126. const auto [load_result, load_parameters] = app_loader->Load(*main_process);
  127. if (load_result != Loader::ResultStatus::Success) {
  128. LOG_CRITICAL(Core, "Failed to load ROM (Error {})!", static_cast<int>(load_result));
  129. Shutdown();
  130. return static_cast<ResultStatus>(static_cast<u32>(ResultStatus::ErrorLoader) +
  131. static_cast<u32>(load_result));
  132. }
  133. kernel.MakeCurrentProcess(main_process.get());
  134. // Main process has been loaded and been made current.
  135. // Begin GPU and CPU execution.
  136. gpu_core->Start();
  137. cpu_core_manager.StartThreads();
  138. // All threads are started, begin main process execution, now that we're in the clear.
  139. main_process->Run(load_parameters->main_thread_priority,
  140. load_parameters->main_thread_stack_size);
  141. status = ResultStatus::Success;
  142. return status;
  143. }
  144. void Shutdown() {
  145. // Log last frame performance stats
  146. const auto perf_results = GetAndResetPerfStats();
  147. telemetry_session->AddField(Telemetry::FieldType::Performance, "Shutdown_EmulationSpeed",
  148. perf_results.emulation_speed * 100.0);
  149. telemetry_session->AddField(Telemetry::FieldType::Performance, "Shutdown_Framerate",
  150. perf_results.game_fps);
  151. telemetry_session->AddField(Telemetry::FieldType::Performance, "Shutdown_Frametime",
  152. perf_results.frametime * 1000.0);
  153. is_powered_on = false;
  154. // Shutdown emulation session
  155. renderer.reset();
  156. GDBStub::Shutdown();
  157. Service::Shutdown();
  158. service_manager.reset();
  159. cheat_engine.reset();
  160. telemetry_session.reset();
  161. gpu_core.reset();
  162. // Close all CPU/threading state
  163. cpu_core_manager.Shutdown();
  164. // Shutdown kernel and core timing
  165. kernel.Shutdown();
  166. core_timing.Shutdown();
  167. // Close app loader
  168. app_loader.reset();
  169. // Clear all applets
  170. applet_manager.ClearAll();
  171. LOG_DEBUG(Core, "Shutdown OK");
  172. }
  173. Loader::ResultStatus GetGameName(std::string& out) const {
  174. if (app_loader == nullptr)
  175. return Loader::ResultStatus::ErrorNotInitialized;
  176. return app_loader->ReadTitle(out);
  177. }
  178. void SetStatus(ResultStatus new_status, const char* details = nullptr) {
  179. status = new_status;
  180. if (details) {
  181. status_details = details;
  182. }
  183. }
  184. PerfStatsResults GetAndResetPerfStats() {
  185. return perf_stats.GetAndResetStats(core_timing.GetGlobalTimeUs());
  186. }
  187. Timing::CoreTiming core_timing;
  188. Kernel::KernelCore kernel;
  189. /// RealVfsFilesystem instance
  190. FileSys::VirtualFilesystem virtual_filesystem;
  191. /// ContentProviderUnion instance
  192. std::unique_ptr<FileSys::ContentProviderUnion> content_provider;
  193. /// AppLoader used to load the current executing application
  194. std::unique_ptr<Loader::AppLoader> app_loader;
  195. std::unique_ptr<VideoCore::RendererBase> renderer;
  196. std::unique_ptr<Tegra::GPU> gpu_core;
  197. std::shared_ptr<Tegra::DebugContext> debug_context;
  198. CpuCoreManager cpu_core_manager;
  199. bool is_powered_on = false;
  200. std::unique_ptr<FileSys::CheatEngine> cheat_engine;
  201. std::unique_ptr<Tools::Freezer> memory_freezer;
  202. /// Frontend applets
  203. Service::AM::Applets::AppletManager applet_manager;
  204. /// Service manager
  205. std::shared_ptr<Service::SM::ServiceManager> service_manager;
  206. /// Telemetry session for this emulation session
  207. std::unique_ptr<Core::TelemetrySession> telemetry_session;
  208. ResultStatus status = ResultStatus::Success;
  209. std::string status_details = "";
  210. Core::PerfStats perf_stats;
  211. Core::FrameLimiter frame_limiter;
  212. };
  213. System::System() : impl{std::make_unique<Impl>(*this)} {}
  214. System::~System() = default;
  215. Cpu& System::CurrentCpuCore() {
  216. return impl->CurrentCpuCore();
  217. }
  218. const Cpu& System::CurrentCpuCore() const {
  219. return impl->CurrentCpuCore();
  220. }
  221. System::ResultStatus System::RunLoop(bool tight_loop) {
  222. return impl->RunLoop(tight_loop);
  223. }
  224. System::ResultStatus System::SingleStep() {
  225. return RunLoop(false);
  226. }
  227. void System::InvalidateCpuInstructionCaches() {
  228. impl->cpu_core_manager.InvalidateAllInstructionCaches();
  229. }
  230. System::ResultStatus System::Load(Frontend::EmuWindow& emu_window, const std::string& filepath) {
  231. return impl->Load(*this, emu_window, filepath);
  232. }
  233. bool System::IsPoweredOn() const {
  234. return impl->is_powered_on;
  235. }
  236. void System::PrepareReschedule() {
  237. CurrentCpuCore().PrepareReschedule();
  238. }
  239. PerfStatsResults System::GetAndResetPerfStats() {
  240. return impl->GetAndResetPerfStats();
  241. }
  242. TelemetrySession& System::TelemetrySession() {
  243. return *impl->telemetry_session;
  244. }
  245. const TelemetrySession& System::TelemetrySession() const {
  246. return *impl->telemetry_session;
  247. }
  248. ARM_Interface& System::CurrentArmInterface() {
  249. return CurrentCpuCore().ArmInterface();
  250. }
  251. const ARM_Interface& System::CurrentArmInterface() const {
  252. return CurrentCpuCore().ArmInterface();
  253. }
  254. std::size_t System::CurrentCoreIndex() const {
  255. return CurrentCpuCore().CoreIndex();
  256. }
  257. Kernel::Scheduler& System::CurrentScheduler() {
  258. return CurrentCpuCore().Scheduler();
  259. }
  260. const Kernel::Scheduler& System::CurrentScheduler() const {
  261. return CurrentCpuCore().Scheduler();
  262. }
  263. Kernel::Scheduler& System::Scheduler(std::size_t core_index) {
  264. return CpuCore(core_index).Scheduler();
  265. }
  266. const Kernel::Scheduler& System::Scheduler(std::size_t core_index) const {
  267. return CpuCore(core_index).Scheduler();
  268. }
  269. Kernel::Process* System::CurrentProcess() {
  270. return impl->kernel.CurrentProcess();
  271. }
  272. const Kernel::Process* System::CurrentProcess() const {
  273. return impl->kernel.CurrentProcess();
  274. }
  275. ARM_Interface& System::ArmInterface(std::size_t core_index) {
  276. return CpuCore(core_index).ArmInterface();
  277. }
  278. const ARM_Interface& System::ArmInterface(std::size_t core_index) const {
  279. return CpuCore(core_index).ArmInterface();
  280. }
  281. Cpu& System::CpuCore(std::size_t core_index) {
  282. return impl->cpu_core_manager.GetCore(core_index);
  283. }
  284. const Cpu& System::CpuCore(std::size_t core_index) const {
  285. ASSERT(core_index < NUM_CPU_CORES);
  286. return impl->cpu_core_manager.GetCore(core_index);
  287. }
  288. ExclusiveMonitor& System::Monitor() {
  289. return impl->cpu_core_manager.GetExclusiveMonitor();
  290. }
  291. const ExclusiveMonitor& System::Monitor() const {
  292. return impl->cpu_core_manager.GetExclusiveMonitor();
  293. }
  294. Tegra::GPU& System::GPU() {
  295. return *impl->gpu_core;
  296. }
  297. const Tegra::GPU& System::GPU() const {
  298. return *impl->gpu_core;
  299. }
  300. VideoCore::RendererBase& System::Renderer() {
  301. return *impl->renderer;
  302. }
  303. const VideoCore::RendererBase& System::Renderer() const {
  304. return *impl->renderer;
  305. }
  306. Kernel::KernelCore& System::Kernel() {
  307. return impl->kernel;
  308. }
  309. const Kernel::KernelCore& System::Kernel() const {
  310. return impl->kernel;
  311. }
  312. Timing::CoreTiming& System::CoreTiming() {
  313. return impl->core_timing;
  314. }
  315. const Timing::CoreTiming& System::CoreTiming() const {
  316. return impl->core_timing;
  317. }
  318. Core::PerfStats& System::GetPerfStats() {
  319. return impl->perf_stats;
  320. }
  321. const Core::PerfStats& System::GetPerfStats() const {
  322. return impl->perf_stats;
  323. }
  324. Core::FrameLimiter& System::FrameLimiter() {
  325. return impl->frame_limiter;
  326. }
  327. const Core::FrameLimiter& System::FrameLimiter() const {
  328. return impl->frame_limiter;
  329. }
  330. Loader::ResultStatus System::GetGameName(std::string& out) const {
  331. return impl->GetGameName(out);
  332. }
  333. void System::SetStatus(ResultStatus new_status, const char* details) {
  334. impl->SetStatus(new_status, details);
  335. }
  336. const std::string& System::GetStatusDetails() const {
  337. return impl->status_details;
  338. }
  339. Loader::AppLoader& System::GetAppLoader() const {
  340. return *impl->app_loader;
  341. }
  342. void System::SetGPUDebugContext(std::shared_ptr<Tegra::DebugContext> context) {
  343. impl->debug_context = std::move(context);
  344. }
  345. Tegra::DebugContext* System::GetGPUDebugContext() const {
  346. return impl->debug_context.get();
  347. }
  348. void System::RegisterCheatList(const std::vector<FileSys::CheatList>& list,
  349. const std::string& build_id, VAddr code_region_start,
  350. VAddr code_region_end) {
  351. impl->cheat_engine = std::make_unique<FileSys::CheatEngine>(*this, list, build_id,
  352. code_region_start, code_region_end);
  353. }
  354. void System::SetFilesystem(std::shared_ptr<FileSys::VfsFilesystem> vfs) {
  355. impl->virtual_filesystem = std::move(vfs);
  356. }
  357. std::shared_ptr<FileSys::VfsFilesystem> System::GetFilesystem() const {
  358. return impl->virtual_filesystem;
  359. }
  360. void System::SetAppletFrontendSet(Service::AM::Applets::AppletFrontendSet&& set) {
  361. impl->applet_manager.SetAppletFrontendSet(std::move(set));
  362. }
  363. void System::SetDefaultAppletFrontendSet() {
  364. impl->applet_manager.SetDefaultAppletFrontendSet();
  365. }
  366. Service::AM::Applets::AppletManager& System::GetAppletManager() {
  367. return impl->applet_manager;
  368. }
  369. const Service::AM::Applets::AppletManager& System::GetAppletManager() const {
  370. return impl->applet_manager;
  371. }
  372. void System::SetContentProvider(std::unique_ptr<FileSys::ContentProviderUnion> provider) {
  373. impl->content_provider = std::move(provider);
  374. }
  375. FileSys::ContentProvider& System::GetContentProvider() {
  376. return *impl->content_provider;
  377. }
  378. const FileSys::ContentProvider& System::GetContentProvider() const {
  379. return *impl->content_provider;
  380. }
  381. void System::RegisterContentProvider(FileSys::ContentProviderUnionSlot slot,
  382. FileSys::ContentProvider* provider) {
  383. impl->content_provider->SetSlot(slot, provider);
  384. }
  385. void System::ClearContentProvider(FileSys::ContentProviderUnionSlot slot) {
  386. impl->content_provider->ClearSlot(slot);
  387. }
  388. System::ResultStatus System::Init(Frontend::EmuWindow& emu_window) {
  389. return impl->Init(*this, emu_window);
  390. }
  391. void System::Shutdown() {
  392. impl->Shutdown();
  393. }
  394. Service::SM::ServiceManager& System::ServiceManager() {
  395. return *impl->service_manager;
  396. }
  397. const Service::SM::ServiceManager& System::ServiceManager() const {
  398. return *impl->service_manager;
  399. }
  400. } // namespace Core