core.cpp 17 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/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/software_keyboard.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 "file_sys/cheat_engine.h"
  33. #include "frontend/applets/profile_select.h"
  34. #include "frontend/applets/software_keyboard.h"
  35. #include "frontend/applets/web_browser.h"
  36. #include "video_core/debug_utils/debug_utils.h"
  37. #include "video_core/renderer_base.h"
  38. #include "video_core/video_core.h"
  39. namespace Core {
  40. /*static*/ System System::s_instance;
  41. FileSys::VirtualFile GetGameFileFromPath(const FileSys::VirtualFilesystem& vfs,
  42. const std::string& path) {
  43. // To account for split 00+01+etc files.
  44. std::string dir_name;
  45. std::string filename;
  46. Common::SplitPath(path, &dir_name, &filename, nullptr);
  47. if (filename == "00") {
  48. const auto dir = vfs->OpenDirectory(dir_name, FileSys::Mode::Read);
  49. std::vector<FileSys::VirtualFile> concat;
  50. for (u8 i = 0; i < 0x10; ++i) {
  51. auto next = dir->GetFile(fmt::format("{:02X}", i));
  52. if (next != nullptr)
  53. concat.push_back(std::move(next));
  54. else {
  55. next = dir->GetFile(fmt::format("{:02x}", i));
  56. if (next != nullptr)
  57. concat.push_back(std::move(next));
  58. else
  59. break;
  60. }
  61. }
  62. if (concat.empty())
  63. return nullptr;
  64. return FileSys::ConcatenatedVfsFile::MakeConcatenatedFile(concat, dir->GetName());
  65. }
  66. if (FileUtil::IsDirectory(path))
  67. return vfs->OpenFile(path + "/" + "main", FileSys::Mode::Read);
  68. return vfs->OpenFile(path, FileSys::Mode::Read);
  69. }
  70. struct System::Impl {
  71. explicit Impl(System& system) : kernel{system}, cpu_core_manager{system} {}
  72. Cpu& CurrentCpuCore() {
  73. return cpu_core_manager.GetCurrentCore();
  74. }
  75. ResultStatus RunLoop(bool tight_loop) {
  76. status = ResultStatus::Success;
  77. cpu_core_manager.RunLoop(tight_loop);
  78. return status;
  79. }
  80. ResultStatus Init(System& system, Frontend::EmuWindow& emu_window) {
  81. LOG_DEBUG(HW_Memory, "initialized OK");
  82. core_timing.Initialize();
  83. cpu_core_manager.Initialize();
  84. kernel.Initialize();
  85. const auto current_time = std::chrono::duration_cast<std::chrono::seconds>(
  86. std::chrono::system_clock::now().time_since_epoch());
  87. Settings::values.custom_rtc_differential =
  88. Settings::values.custom_rtc.value_or(current_time) - current_time;
  89. // Create a default fs if one doesn't already exist.
  90. if (virtual_filesystem == nullptr)
  91. virtual_filesystem = std::make_shared<FileSys::RealVfsFilesystem>();
  92. if (content_provider == nullptr)
  93. content_provider = std::make_unique<FileSys::ContentProviderUnion>();
  94. /// Create default implementations of applets if one is not provided.
  95. if (profile_selector == nullptr)
  96. profile_selector = std::make_unique<Core::Frontend::DefaultProfileSelectApplet>();
  97. if (software_keyboard == nullptr)
  98. software_keyboard = std::make_unique<Core::Frontend::DefaultSoftwareKeyboardApplet>();
  99. if (web_browser == nullptr)
  100. web_browser = std::make_unique<Core::Frontend::DefaultWebBrowserApplet>();
  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. profile_selector.reset();
  184. software_keyboard.reset();
  185. web_browser.reset();
  186. LOG_DEBUG(Core, "Shutdown OK");
  187. }
  188. Loader::ResultStatus GetGameName(std::string& out) const {
  189. if (app_loader == nullptr)
  190. return Loader::ResultStatus::ErrorNotInitialized;
  191. return app_loader->ReadTitle(out);
  192. }
  193. void SetStatus(ResultStatus new_status, const char* details = nullptr) {
  194. status = new_status;
  195. if (details) {
  196. status_details = details;
  197. }
  198. }
  199. PerfStatsResults GetAndResetPerfStats() {
  200. return perf_stats.GetAndResetStats(core_timing.GetGlobalTimeUs());
  201. }
  202. Timing::CoreTiming core_timing;
  203. Kernel::KernelCore kernel;
  204. /// RealVfsFilesystem instance
  205. FileSys::VirtualFilesystem virtual_filesystem;
  206. /// ContentProviderUnion instance
  207. std::unique_ptr<FileSys::ContentProviderUnion> content_provider;
  208. /// AppLoader used to load the current executing application
  209. std::unique_ptr<Loader::AppLoader> app_loader;
  210. std::unique_ptr<VideoCore::RendererBase> renderer;
  211. std::unique_ptr<Tegra::GPU> gpu_core;
  212. std::shared_ptr<Tegra::DebugContext> debug_context;
  213. CpuCoreManager cpu_core_manager;
  214. bool is_powered_on = false;
  215. std::unique_ptr<FileSys::CheatEngine> cheat_engine;
  216. /// Frontend applets
  217. std::unique_ptr<Core::Frontend::ProfileSelectApplet> profile_selector;
  218. std::unique_ptr<Core::Frontend::SoftwareKeyboardApplet> software_keyboard;
  219. std::unique_ptr<Core::Frontend::WebBrowserApplet> web_browser;
  220. /// Service manager
  221. std::shared_ptr<Service::SM::ServiceManager> service_manager;
  222. /// Telemetry session for this emulation session
  223. std::unique_ptr<Core::TelemetrySession> telemetry_session;
  224. ResultStatus status = ResultStatus::Success;
  225. std::string status_details = "";
  226. Core::PerfStats perf_stats;
  227. Core::FrameLimiter frame_limiter;
  228. };
  229. System::System() : impl{std::make_unique<Impl>(*this)} {}
  230. System::~System() = default;
  231. Cpu& System::CurrentCpuCore() {
  232. return impl->CurrentCpuCore();
  233. }
  234. const Cpu& System::CurrentCpuCore() const {
  235. return impl->CurrentCpuCore();
  236. }
  237. System::ResultStatus System::RunLoop(bool tight_loop) {
  238. return impl->RunLoop(tight_loop);
  239. }
  240. System::ResultStatus System::SingleStep() {
  241. return RunLoop(false);
  242. }
  243. void System::InvalidateCpuInstructionCaches() {
  244. impl->cpu_core_manager.InvalidateAllInstructionCaches();
  245. }
  246. System::ResultStatus System::Load(Frontend::EmuWindow& emu_window, const std::string& filepath) {
  247. return impl->Load(*this, emu_window, filepath);
  248. }
  249. bool System::IsPoweredOn() const {
  250. return impl->is_powered_on;
  251. }
  252. void System::PrepareReschedule() {
  253. CurrentCpuCore().PrepareReschedule();
  254. }
  255. PerfStatsResults System::GetAndResetPerfStats() {
  256. return impl->GetAndResetPerfStats();
  257. }
  258. TelemetrySession& System::TelemetrySession() {
  259. return *impl->telemetry_session;
  260. }
  261. const TelemetrySession& System::TelemetrySession() const {
  262. return *impl->telemetry_session;
  263. }
  264. ARM_Interface& System::CurrentArmInterface() {
  265. return CurrentCpuCore().ArmInterface();
  266. }
  267. const ARM_Interface& System::CurrentArmInterface() const {
  268. return CurrentCpuCore().ArmInterface();
  269. }
  270. std::size_t System::CurrentCoreIndex() const {
  271. return CurrentCpuCore().CoreIndex();
  272. }
  273. Kernel::Scheduler& System::CurrentScheduler() {
  274. return CurrentCpuCore().Scheduler();
  275. }
  276. const Kernel::Scheduler& System::CurrentScheduler() const {
  277. return CurrentCpuCore().Scheduler();
  278. }
  279. Kernel::Scheduler& System::Scheduler(std::size_t core_index) {
  280. return CpuCore(core_index).Scheduler();
  281. }
  282. const Kernel::Scheduler& System::Scheduler(std::size_t core_index) const {
  283. return CpuCore(core_index).Scheduler();
  284. }
  285. Kernel::Process* System::CurrentProcess() {
  286. return impl->kernel.CurrentProcess();
  287. }
  288. const Kernel::Process* System::CurrentProcess() const {
  289. return impl->kernel.CurrentProcess();
  290. }
  291. ARM_Interface& System::ArmInterface(std::size_t core_index) {
  292. return CpuCore(core_index).ArmInterface();
  293. }
  294. const ARM_Interface& System::ArmInterface(std::size_t core_index) const {
  295. return CpuCore(core_index).ArmInterface();
  296. }
  297. Cpu& System::CpuCore(std::size_t core_index) {
  298. return impl->cpu_core_manager.GetCore(core_index);
  299. }
  300. const Cpu& System::CpuCore(std::size_t core_index) const {
  301. ASSERT(core_index < NUM_CPU_CORES);
  302. return impl->cpu_core_manager.GetCore(core_index);
  303. }
  304. ExclusiveMonitor& System::Monitor() {
  305. return impl->cpu_core_manager.GetExclusiveMonitor();
  306. }
  307. const ExclusiveMonitor& System::Monitor() const {
  308. return impl->cpu_core_manager.GetExclusiveMonitor();
  309. }
  310. Tegra::GPU& System::GPU() {
  311. return *impl->gpu_core;
  312. }
  313. const Tegra::GPU& System::GPU() const {
  314. return *impl->gpu_core;
  315. }
  316. VideoCore::RendererBase& System::Renderer() {
  317. return *impl->renderer;
  318. }
  319. const VideoCore::RendererBase& System::Renderer() const {
  320. return *impl->renderer;
  321. }
  322. Kernel::KernelCore& System::Kernel() {
  323. return impl->kernel;
  324. }
  325. const Kernel::KernelCore& System::Kernel() const {
  326. return impl->kernel;
  327. }
  328. Timing::CoreTiming& System::CoreTiming() {
  329. return impl->core_timing;
  330. }
  331. const Timing::CoreTiming& System::CoreTiming() const {
  332. return impl->core_timing;
  333. }
  334. Core::PerfStats& System::GetPerfStats() {
  335. return impl->perf_stats;
  336. }
  337. const Core::PerfStats& System::GetPerfStats() const {
  338. return impl->perf_stats;
  339. }
  340. Core::FrameLimiter& System::FrameLimiter() {
  341. return impl->frame_limiter;
  342. }
  343. const Core::FrameLimiter& System::FrameLimiter() const {
  344. return impl->frame_limiter;
  345. }
  346. Loader::ResultStatus System::GetGameName(std::string& out) const {
  347. return impl->GetGameName(out);
  348. }
  349. void System::SetStatus(ResultStatus new_status, const char* details) {
  350. impl->SetStatus(new_status, details);
  351. }
  352. const std::string& System::GetStatusDetails() const {
  353. return impl->status_details;
  354. }
  355. Loader::AppLoader& System::GetAppLoader() const {
  356. return *impl->app_loader;
  357. }
  358. void System::SetGPUDebugContext(std::shared_ptr<Tegra::DebugContext> context) {
  359. impl->debug_context = std::move(context);
  360. }
  361. Tegra::DebugContext* System::GetGPUDebugContext() const {
  362. return impl->debug_context.get();
  363. }
  364. void System::RegisterCheatList(const std::vector<FileSys::CheatList>& list,
  365. const std::string& build_id, VAddr code_region_start,
  366. VAddr code_region_end) {
  367. impl->cheat_engine = std::make_unique<FileSys::CheatEngine>(*this, list, build_id,
  368. code_region_start, code_region_end);
  369. }
  370. void System::SetFilesystem(std::shared_ptr<FileSys::VfsFilesystem> vfs) {
  371. impl->virtual_filesystem = std::move(vfs);
  372. }
  373. std::shared_ptr<FileSys::VfsFilesystem> System::GetFilesystem() const {
  374. return impl->virtual_filesystem;
  375. }
  376. void System::SetProfileSelector(std::unique_ptr<Frontend::ProfileSelectApplet> applet) {
  377. impl->profile_selector = std::move(applet);
  378. }
  379. const Frontend::ProfileSelectApplet& System::GetProfileSelector() const {
  380. return *impl->profile_selector;
  381. }
  382. void System::SetSoftwareKeyboard(std::unique_ptr<Frontend::SoftwareKeyboardApplet> applet) {
  383. impl->software_keyboard = std::move(applet);
  384. }
  385. const Frontend::SoftwareKeyboardApplet& System::GetSoftwareKeyboard() const {
  386. return *impl->software_keyboard;
  387. }
  388. void System::SetContentProvider(std::unique_ptr<FileSys::ContentProviderUnion> provider) {
  389. impl->content_provider = std::move(provider);
  390. }
  391. FileSys::ContentProvider& System::GetContentProvider() {
  392. return *impl->content_provider;
  393. }
  394. const FileSys::ContentProvider& System::GetContentProvider() const {
  395. return *impl->content_provider;
  396. }
  397. void System::RegisterContentProvider(FileSys::ContentProviderUnionSlot slot,
  398. FileSys::ContentProvider* provider) {
  399. impl->content_provider->SetSlot(slot, provider);
  400. }
  401. void System::ClearContentProvider(FileSys::ContentProviderUnionSlot slot) {
  402. impl->content_provider->ClearSlot(slot);
  403. }
  404. void System::SetWebBrowser(std::unique_ptr<Frontend::WebBrowserApplet> applet) {
  405. impl->web_browser = std::move(applet);
  406. }
  407. Frontend::WebBrowserApplet& System::GetWebBrowser() {
  408. return *impl->web_browser;
  409. }
  410. const Frontend::WebBrowserApplet& System::GetWebBrowser() const {
  411. return *impl->web_browser;
  412. }
  413. System::ResultStatus System::Init(Frontend::EmuWindow& emu_window) {
  414. return impl->Init(*this, emu_window);
  415. }
  416. void System::Shutdown() {
  417. impl->Shutdown();
  418. }
  419. Service::SM::ServiceManager& System::ServiceManager() {
  420. return *impl->service_manager;
  421. }
  422. const Service::SM::ServiceManager& System::ServiceManager() const {
  423. return *impl->service_manager;
  424. }
  425. } // namespace Core