core.cpp 16 KB

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