core.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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. CoreTiming::Init();
  83. kernel.Initialize();
  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, *virtual_filesystem);
  103. GDBStub::Init();
  104. renderer = VideoCore::CreateRenderer(emu_window);
  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. CoreTiming::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(CoreTiming::GetGlobalTimeUs());
  191. }
  192. Kernel::KernelCore kernel;
  193. /// RealVfsFilesystem instance
  194. FileSys::VirtualFilesystem virtual_filesystem;
  195. /// AppLoader used to load the current executing application
  196. std::unique_ptr<Loader::AppLoader> app_loader;
  197. std::unique_ptr<VideoCore::RendererBase> renderer;
  198. std::unique_ptr<Tegra::GPU> gpu_core;
  199. std::shared_ptr<Tegra::DebugContext> debug_context;
  200. CpuCoreManager cpu_core_manager;
  201. bool is_powered_on = false;
  202. /// Frontend applets
  203. std::unique_ptr<Core::Frontend::ProfileSelectApplet> profile_selector;
  204. std::unique_ptr<Core::Frontend::SoftwareKeyboardApplet> software_keyboard;
  205. std::unique_ptr<Core::Frontend::WebBrowserApplet> web_browser;
  206. /// Service manager
  207. std::shared_ptr<Service::SM::ServiceManager> service_manager;
  208. /// Telemetry session for this emulation session
  209. std::unique_ptr<Core::TelemetrySession> telemetry_session;
  210. ResultStatus status = ResultStatus::Success;
  211. std::string status_details = "";
  212. Core::PerfStats perf_stats;
  213. Core::FrameLimiter frame_limiter;
  214. };
  215. System::System() : impl{std::make_unique<Impl>()} {}
  216. System::~System() = default;
  217. Cpu& System::CurrentCpuCore() {
  218. return impl->CurrentCpuCore();
  219. }
  220. const Cpu& System::CurrentCpuCore() const {
  221. return impl->CurrentCpuCore();
  222. }
  223. System::ResultStatus System::RunLoop(bool tight_loop) {
  224. return impl->RunLoop(tight_loop);
  225. }
  226. System::ResultStatus System::SingleStep() {
  227. return RunLoop(false);
  228. }
  229. void System::InvalidateCpuInstructionCaches() {
  230. impl->cpu_core_manager.InvalidateAllInstructionCaches();
  231. }
  232. System::ResultStatus System::Load(Frontend::EmuWindow& emu_window, const std::string& filepath) {
  233. return impl->Load(*this, emu_window, filepath);
  234. }
  235. bool System::IsPoweredOn() const {
  236. return impl->is_powered_on;
  237. }
  238. void System::PrepareReschedule() {
  239. CurrentCpuCore().PrepareReschedule();
  240. }
  241. PerfStatsResults System::GetAndResetPerfStats() {
  242. return impl->GetAndResetPerfStats();
  243. }
  244. TelemetrySession& System::TelemetrySession() {
  245. return *impl->telemetry_session;
  246. }
  247. const TelemetrySession& System::TelemetrySession() const {
  248. return *impl->telemetry_session;
  249. }
  250. ARM_Interface& System::CurrentArmInterface() {
  251. return CurrentCpuCore().ArmInterface();
  252. }
  253. const ARM_Interface& System::CurrentArmInterface() const {
  254. return CurrentCpuCore().ArmInterface();
  255. }
  256. std::size_t System::CurrentCoreIndex() const {
  257. return CurrentCpuCore().CoreIndex();
  258. }
  259. Kernel::Scheduler& System::CurrentScheduler() {
  260. return CurrentCpuCore().Scheduler();
  261. }
  262. const Kernel::Scheduler& System::CurrentScheduler() const {
  263. return CurrentCpuCore().Scheduler();
  264. }
  265. Kernel::Scheduler& System::Scheduler(std::size_t core_index) {
  266. return CpuCore(core_index).Scheduler();
  267. }
  268. const Kernel::Scheduler& System::Scheduler(std::size_t core_index) const {
  269. return CpuCore(core_index).Scheduler();
  270. }
  271. Kernel::Process* System::CurrentProcess() {
  272. return impl->kernel.CurrentProcess();
  273. }
  274. const Kernel::Process* System::CurrentProcess() const {
  275. return impl->kernel.CurrentProcess();
  276. }
  277. ARM_Interface& System::ArmInterface(std::size_t core_index) {
  278. return CpuCore(core_index).ArmInterface();
  279. }
  280. const ARM_Interface& System::ArmInterface(std::size_t core_index) const {
  281. return CpuCore(core_index).ArmInterface();
  282. }
  283. Cpu& System::CpuCore(std::size_t core_index) {
  284. return impl->cpu_core_manager.GetCore(core_index);
  285. }
  286. const Cpu& System::CpuCore(std::size_t core_index) const {
  287. ASSERT(core_index < NUM_CPU_CORES);
  288. return impl->cpu_core_manager.GetCore(core_index);
  289. }
  290. ExclusiveMonitor& System::Monitor() {
  291. return impl->cpu_core_manager.GetExclusiveMonitor();
  292. }
  293. const ExclusiveMonitor& System::Monitor() const {
  294. return impl->cpu_core_manager.GetExclusiveMonitor();
  295. }
  296. Tegra::GPU& System::GPU() {
  297. return *impl->gpu_core;
  298. }
  299. const Tegra::GPU& System::GPU() const {
  300. return *impl->gpu_core;
  301. }
  302. VideoCore::RendererBase& System::Renderer() {
  303. return *impl->renderer;
  304. }
  305. const VideoCore::RendererBase& System::Renderer() const {
  306. return *impl->renderer;
  307. }
  308. Kernel::KernelCore& System::Kernel() {
  309. return impl->kernel;
  310. }
  311. const Kernel::KernelCore& System::Kernel() const {
  312. return impl->kernel;
  313. }
  314. Core::PerfStats& System::GetPerfStats() {
  315. return impl->perf_stats;
  316. }
  317. const Core::PerfStats& System::GetPerfStats() const {
  318. return impl->perf_stats;
  319. }
  320. Core::FrameLimiter& System::FrameLimiter() {
  321. return impl->frame_limiter;
  322. }
  323. const Core::FrameLimiter& System::FrameLimiter() const {
  324. return impl->frame_limiter;
  325. }
  326. Loader::ResultStatus System::GetGameName(std::string& out) const {
  327. return impl->GetGameName(out);
  328. }
  329. void System::SetStatus(ResultStatus new_status, const char* details) {
  330. impl->SetStatus(new_status, details);
  331. }
  332. const std::string& System::GetStatusDetails() const {
  333. return impl->status_details;
  334. }
  335. Loader::AppLoader& System::GetAppLoader() const {
  336. return *impl->app_loader;
  337. }
  338. void System::SetGPUDebugContext(std::shared_ptr<Tegra::DebugContext> context) {
  339. impl->debug_context = std::move(context);
  340. }
  341. Tegra::DebugContext* System::GetGPUDebugContext() const {
  342. return impl->debug_context.get();
  343. }
  344. void System::SetFilesystem(std::shared_ptr<FileSys::VfsFilesystem> vfs) {
  345. impl->virtual_filesystem = std::move(vfs);
  346. }
  347. std::shared_ptr<FileSys::VfsFilesystem> System::GetFilesystem() const {
  348. return impl->virtual_filesystem;
  349. }
  350. void System::SetProfileSelector(std::unique_ptr<Frontend::ProfileSelectApplet> applet) {
  351. impl->profile_selector = std::move(applet);
  352. }
  353. const Frontend::ProfileSelectApplet& System::GetProfileSelector() const {
  354. return *impl->profile_selector;
  355. }
  356. void System::SetSoftwareKeyboard(std::unique_ptr<Frontend::SoftwareKeyboardApplet> applet) {
  357. impl->software_keyboard = std::move(applet);
  358. }
  359. const Frontend::SoftwareKeyboardApplet& System::GetSoftwareKeyboard() const {
  360. return *impl->software_keyboard;
  361. }
  362. void System::SetWebBrowser(std::unique_ptr<Frontend::WebBrowserApplet> applet) {
  363. impl->web_browser = std::move(applet);
  364. }
  365. Frontend::WebBrowserApplet& System::GetWebBrowser() {
  366. return *impl->web_browser;
  367. }
  368. const Frontend::WebBrowserApplet& System::GetWebBrowser() const {
  369. return *impl->web_browser;
  370. }
  371. System::ResultStatus System::Init(Frontend::EmuWindow& emu_window) {
  372. return impl->Init(*this, emu_window);
  373. }
  374. void System::Shutdown() {
  375. impl->Shutdown();
  376. }
  377. Service::SM::ServiceManager& System::ServiceManager() {
  378. return *impl->service_manager;
  379. }
  380. const Service::SM::ServiceManager& System::ServiceManager() const {
  381. return *impl->service_manager;
  382. }
  383. } // namespace Core