core.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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 <map>
  6. #include <memory>
  7. #include <thread>
  8. #include <utility>
  9. #include "common/file_util.h"
  10. #include "common/logging/log.h"
  11. #include "common/string_util.h"
  12. #include "core/arm/exclusive_monitor.h"
  13. #include "core/core.h"
  14. #include "core/core_cpu.h"
  15. #include "core/core_timing.h"
  16. #include "core/cpu_core_manager.h"
  17. #include "core/file_sys/mode.h"
  18. #include "core/file_sys/vfs_concat.h"
  19. #include "core/file_sys/vfs_real.h"
  20. #include "core/gdbstub/gdbstub.h"
  21. #include "core/hle/kernel/client_port.h"
  22. #include "core/hle/kernel/kernel.h"
  23. #include "core/hle/kernel/process.h"
  24. #include "core/hle/kernel/scheduler.h"
  25. #include "core/hle/kernel/thread.h"
  26. #include "core/hle/service/am/applets/software_keyboard.h"
  27. #include "core/hle/service/service.h"
  28. #include "core/hle/service/sm/sm.h"
  29. #include "core/loader/loader.h"
  30. #include "core/perf_stats.h"
  31. #include "core/settings.h"
  32. #include "core/telemetry_session.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/gpu.h"
  38. #include "video_core/renderer_base.h"
  39. #include "video_core/video_core.h"
  40. namespace Core {
  41. /*static*/ System System::s_instance;
  42. FileSys::VirtualFile GetGameFileFromPath(const FileSys::VirtualFilesystem& vfs,
  43. const std::string& path) {
  44. // To account for split 00+01+etc files.
  45. std::string dir_name;
  46. std::string filename;
  47. Common::SplitPath(path, &dir_name, &filename, nullptr);
  48. if (filename == "00") {
  49. const auto dir = vfs->OpenDirectory(dir_name, FileSys::Mode::Read);
  50. std::vector<FileSys::VirtualFile> concat;
  51. for (u8 i = 0; i < 0x10; ++i) {
  52. auto next = dir->GetFile(fmt::format("{:02X}", i));
  53. if (next != nullptr)
  54. concat.push_back(std::move(next));
  55. else {
  56. next = dir->GetFile(fmt::format("{:02x}", i));
  57. if (next != nullptr)
  58. concat.push_back(std::move(next));
  59. else
  60. break;
  61. }
  62. }
  63. if (concat.empty())
  64. return nullptr;
  65. return FileSys::ConcatenatedVfsFile::MakeConcatenatedFile(concat, dir->GetName());
  66. }
  67. if (FileUtil::IsDirectory(path))
  68. return vfs->OpenFile(path + "/" + "main", FileSys::Mode::Read);
  69. return vfs->OpenFile(path, FileSys::Mode::Read);
  70. }
  71. struct System::Impl {
  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. kernel.Initialize(core_timing);
  84. const auto current_time = std::chrono::duration_cast<std::chrono::seconds>(
  85. std::chrono::system_clock::now().time_since_epoch());
  86. Settings::values.custom_rtc_differential =
  87. Settings::values.custom_rtc.value_or(current_time) - current_time;
  88. // Create a default fs if one doesn't already exist.
  89. if (virtual_filesystem == nullptr)
  90. virtual_filesystem = std::make_shared<FileSys::RealVfsFilesystem>();
  91. /// Create default implementations of applets if one is not provided.
  92. if (profile_selector == nullptr)
  93. profile_selector = std::make_unique<Core::Frontend::DefaultProfileSelectApplet>();
  94. if (software_keyboard == nullptr)
  95. software_keyboard = std::make_unique<Core::Frontend::DefaultSoftwareKeyboardApplet>();
  96. if (web_browser == nullptr)
  97. web_browser = std::make_unique<Core::Frontend::DefaultWebBrowserApplet>();
  98. auto main_process = Kernel::Process::Create(kernel, "main");
  99. kernel.MakeCurrentProcess(main_process.get());
  100. telemetry_session = std::make_unique<Core::TelemetrySession>();
  101. service_manager = std::make_shared<Service::SM::ServiceManager>();
  102. Service::Init(service_manager, system, *virtual_filesystem);
  103. GDBStub::Init();
  104. renderer = VideoCore::CreateRenderer(emu_window, system);
  105. if (!renderer->Init()) {
  106. return ResultStatus::ErrorVideoCore;
  107. }
  108. gpu_core = std::make_unique<Tegra::GPU>(renderer->Rasterizer());
  109. cpu_core_manager.Initialize(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. const Loader::ResultStatus load_result{app_loader->Load(*kernel.CurrentProcess())};
  139. if (load_result != Loader::ResultStatus::Success) {
  140. LOG_CRITICAL(Core, "Failed to load ROM (Error {})!", static_cast<int>(load_result));
  141. Shutdown();
  142. return static_cast<ResultStatus>(static_cast<u32>(ResultStatus::ErrorLoader) +
  143. static_cast<u32>(load_result));
  144. }
  145. status = ResultStatus::Success;
  146. return status;
  147. }
  148. void Shutdown() {
  149. // Log last frame performance stats
  150. auto perf_results = GetAndResetPerfStats();
  151. Telemetry().AddField(Telemetry::FieldType::Performance, "Shutdown_EmulationSpeed",
  152. perf_results.emulation_speed * 100.0);
  153. Telemetry().AddField(Telemetry::FieldType::Performance, "Shutdown_Framerate",
  154. perf_results.game_fps);
  155. Telemetry().AddField(Telemetry::FieldType::Performance, "Shutdown_Frametime",
  156. perf_results.frametime * 1000.0);
  157. is_powered_on = false;
  158. // Shutdown emulation session
  159. renderer.reset();
  160. GDBStub::Shutdown();
  161. Service::Shutdown();
  162. service_manager.reset();
  163. telemetry_session.reset();
  164. gpu_core.reset();
  165. // Close all CPU/threading state
  166. cpu_core_manager.Shutdown();
  167. // Shutdown kernel and core timing
  168. kernel.Shutdown();
  169. core_timing.Shutdown();
  170. // Close app loader
  171. app_loader.reset();
  172. // Clear all applets
  173. profile_selector.reset();
  174. software_keyboard.reset();
  175. web_browser.reset();
  176. LOG_DEBUG(Core, "Shutdown OK");
  177. }
  178. Loader::ResultStatus GetGameName(std::string& out) const {
  179. if (app_loader == nullptr)
  180. return Loader::ResultStatus::ErrorNotInitialized;
  181. return app_loader->ReadTitle(out);
  182. }
  183. void SetStatus(ResultStatus new_status, const char* details = nullptr) {
  184. status = new_status;
  185. if (details) {
  186. status_details = details;
  187. }
  188. }
  189. PerfStatsResults GetAndResetPerfStats() {
  190. return perf_stats.GetAndResetStats(core_timing.GetGlobalTimeUs());
  191. }
  192. Timing::CoreTiming core_timing;
  193. Kernel::KernelCore kernel;
  194. /// RealVfsFilesystem instance
  195. FileSys::VirtualFilesystem virtual_filesystem;
  196. /// AppLoader used to load the current executing application
  197. std::unique_ptr<Loader::AppLoader> app_loader;
  198. std::unique_ptr<VideoCore::RendererBase> renderer;
  199. std::unique_ptr<Tegra::GPU> gpu_core;
  200. std::shared_ptr<Tegra::DebugContext> debug_context;
  201. CpuCoreManager cpu_core_manager;
  202. bool is_powered_on = false;
  203. /// Frontend applets
  204. std::unique_ptr<Core::Frontend::ProfileSelectApplet> profile_selector;
  205. std::unique_ptr<Core::Frontend::SoftwareKeyboardApplet> software_keyboard;
  206. std::unique_ptr<Core::Frontend::WebBrowserApplet> web_browser;
  207. /// Service manager
  208. std::shared_ptr<Service::SM::ServiceManager> service_manager;
  209. /// Telemetry session for this emulation session
  210. std::unique_ptr<Core::TelemetrySession> telemetry_session;
  211. ResultStatus status = ResultStatus::Success;
  212. std::string status_details = "";
  213. Core::PerfStats perf_stats;
  214. Core::FrameLimiter frame_limiter;
  215. };
  216. System::System() : impl{std::make_unique<Impl>()} {}
  217. System::~System() = default;
  218. Cpu& System::CurrentCpuCore() {
  219. return impl->CurrentCpuCore();
  220. }
  221. const Cpu& System::CurrentCpuCore() const {
  222. return impl->CurrentCpuCore();
  223. }
  224. System::ResultStatus System::RunLoop(bool tight_loop) {
  225. return impl->RunLoop(tight_loop);
  226. }
  227. System::ResultStatus System::SingleStep() {
  228. return RunLoop(false);
  229. }
  230. void System::InvalidateCpuInstructionCaches() {
  231. impl->cpu_core_manager.InvalidateAllInstructionCaches();
  232. }
  233. System::ResultStatus System::Load(Frontend::EmuWindow& emu_window, const std::string& filepath) {
  234. return impl->Load(*this, emu_window, filepath);
  235. }
  236. bool System::IsPoweredOn() const {
  237. return impl->is_powered_on;
  238. }
  239. void System::PrepareReschedule() {
  240. CurrentCpuCore().PrepareReschedule();
  241. }
  242. PerfStatsResults System::GetAndResetPerfStats() {
  243. return impl->GetAndResetPerfStats();
  244. }
  245. TelemetrySession& System::TelemetrySession() {
  246. return *impl->telemetry_session;
  247. }
  248. const TelemetrySession& System::TelemetrySession() const {
  249. return *impl->telemetry_session;
  250. }
  251. ARM_Interface& System::CurrentArmInterface() {
  252. return CurrentCpuCore().ArmInterface();
  253. }
  254. const ARM_Interface& System::CurrentArmInterface() const {
  255. return CurrentCpuCore().ArmInterface();
  256. }
  257. std::size_t System::CurrentCoreIndex() const {
  258. return CurrentCpuCore().CoreIndex();
  259. }
  260. Kernel::Scheduler& System::CurrentScheduler() {
  261. return CurrentCpuCore().Scheduler();
  262. }
  263. const Kernel::Scheduler& System::CurrentScheduler() const {
  264. return CurrentCpuCore().Scheduler();
  265. }
  266. Kernel::Scheduler& System::Scheduler(std::size_t core_index) {
  267. return CpuCore(core_index).Scheduler();
  268. }
  269. const Kernel::Scheduler& System::Scheduler(std::size_t core_index) const {
  270. return CpuCore(core_index).Scheduler();
  271. }
  272. Kernel::Process* System::CurrentProcess() {
  273. return impl->kernel.CurrentProcess();
  274. }
  275. const Kernel::Process* System::CurrentProcess() const {
  276. return impl->kernel.CurrentProcess();
  277. }
  278. ARM_Interface& System::ArmInterface(std::size_t core_index) {
  279. return CpuCore(core_index).ArmInterface();
  280. }
  281. const ARM_Interface& System::ArmInterface(std::size_t core_index) const {
  282. return CpuCore(core_index).ArmInterface();
  283. }
  284. Cpu& System::CpuCore(std::size_t core_index) {
  285. return impl->cpu_core_manager.GetCore(core_index);
  286. }
  287. const Cpu& System::CpuCore(std::size_t core_index) const {
  288. ASSERT(core_index < NUM_CPU_CORES);
  289. return impl->cpu_core_manager.GetCore(core_index);
  290. }
  291. ExclusiveMonitor& System::Monitor() {
  292. return impl->cpu_core_manager.GetExclusiveMonitor();
  293. }
  294. const ExclusiveMonitor& System::Monitor() const {
  295. return impl->cpu_core_manager.GetExclusiveMonitor();
  296. }
  297. Tegra::GPU& System::GPU() {
  298. return *impl->gpu_core;
  299. }
  300. const Tegra::GPU& System::GPU() const {
  301. return *impl->gpu_core;
  302. }
  303. VideoCore::RendererBase& System::Renderer() {
  304. return *impl->renderer;
  305. }
  306. const VideoCore::RendererBase& System::Renderer() const {
  307. return *impl->renderer;
  308. }
  309. Kernel::KernelCore& System::Kernel() {
  310. return impl->kernel;
  311. }
  312. const Kernel::KernelCore& System::Kernel() const {
  313. return impl->kernel;
  314. }
  315. Timing::CoreTiming& System::CoreTiming() {
  316. return impl->core_timing;
  317. }
  318. const Timing::CoreTiming& System::CoreTiming() const {
  319. return impl->core_timing;
  320. }
  321. Core::PerfStats& System::GetPerfStats() {
  322. return impl->perf_stats;
  323. }
  324. const Core::PerfStats& System::GetPerfStats() const {
  325. return impl->perf_stats;
  326. }
  327. Core::FrameLimiter& System::FrameLimiter() {
  328. return impl->frame_limiter;
  329. }
  330. const Core::FrameLimiter& System::FrameLimiter() const {
  331. return impl->frame_limiter;
  332. }
  333. Loader::ResultStatus System::GetGameName(std::string& out) const {
  334. return impl->GetGameName(out);
  335. }
  336. void System::SetStatus(ResultStatus new_status, const char* details) {
  337. impl->SetStatus(new_status, details);
  338. }
  339. const std::string& System::GetStatusDetails() const {
  340. return impl->status_details;
  341. }
  342. Loader::AppLoader& System::GetAppLoader() const {
  343. return *impl->app_loader;
  344. }
  345. void System::SetGPUDebugContext(std::shared_ptr<Tegra::DebugContext> context) {
  346. impl->debug_context = std::move(context);
  347. }
  348. Tegra::DebugContext* System::GetGPUDebugContext() const {
  349. return impl->debug_context.get();
  350. }
  351. void System::SetFilesystem(std::shared_ptr<FileSys::VfsFilesystem> vfs) {
  352. impl->virtual_filesystem = std::move(vfs);
  353. }
  354. std::shared_ptr<FileSys::VfsFilesystem> System::GetFilesystem() const {
  355. return impl->virtual_filesystem;
  356. }
  357. void System::SetProfileSelector(std::unique_ptr<Frontend::ProfileSelectApplet> applet) {
  358. impl->profile_selector = std::move(applet);
  359. }
  360. const Frontend::ProfileSelectApplet& System::GetProfileSelector() const {
  361. return *impl->profile_selector;
  362. }
  363. void System::SetSoftwareKeyboard(std::unique_ptr<Frontend::SoftwareKeyboardApplet> applet) {
  364. impl->software_keyboard = std::move(applet);
  365. }
  366. const Frontend::SoftwareKeyboardApplet& System::GetSoftwareKeyboard() const {
  367. return *impl->software_keyboard;
  368. }
  369. void System::SetWebBrowser(std::unique_ptr<Frontend::WebBrowserApplet> applet) {
  370. impl->web_browser = std::move(applet);
  371. }
  372. Frontend::WebBrowserApplet& System::GetWebBrowser() {
  373. return *impl->web_browser;
  374. }
  375. const Frontend::WebBrowserApplet& System::GetWebBrowser() const {
  376. return *impl->web_browser;
  377. }
  378. System::ResultStatus System::Init(Frontend::EmuWindow& emu_window) {
  379. return impl->Init(*this, emu_window);
  380. }
  381. void System::Shutdown() {
  382. impl->Shutdown();
  383. }
  384. Service::SM::ServiceManager& System::ServiceManager() {
  385. return *impl->service_manager;
  386. }
  387. const Service::SM::ServiceManager& System::ServiceManager() const {
  388. return *impl->service_manager;
  389. }
  390. } // namespace Core