core.cpp 16 KB

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