core.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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/telemetry_session.h"
  32. #include "frontend/applets/software_keyboard.h"
  33. #include "video_core/debug_utils/debug_utils.h"
  34. #include "video_core/gpu.h"
  35. #include "video_core/renderer_base.h"
  36. #include "video_core/video_core.h"
  37. namespace Core {
  38. /*static*/ System System::s_instance;
  39. FileSys::VirtualFile GetGameFileFromPath(const FileSys::VirtualFilesystem& vfs,
  40. const std::string& path) {
  41. // To account for split 00+01+etc files.
  42. std::string dir_name;
  43. std::string filename;
  44. Common::SplitPath(path, &dir_name, &filename, nullptr);
  45. if (filename == "00") {
  46. const auto dir = vfs->OpenDirectory(dir_name, FileSys::Mode::Read);
  47. std::vector<FileSys::VirtualFile> concat;
  48. for (u8 i = 0; i < 0x10; ++i) {
  49. auto next = dir->GetFile(fmt::format("{:02X}", i));
  50. if (next != nullptr)
  51. concat.push_back(std::move(next));
  52. else {
  53. next = dir->GetFile(fmt::format("{:02x}", i));
  54. if (next != nullptr)
  55. concat.push_back(std::move(next));
  56. else
  57. break;
  58. }
  59. }
  60. if (concat.empty())
  61. return nullptr;
  62. return FileSys::ConcatenatedVfsFile::MakeConcatenatedFile(concat, dir->GetName());
  63. }
  64. if (FileUtil::IsDirectory(path))
  65. return vfs->OpenFile(path + "/" + "main", FileSys::Mode::Read);
  66. return vfs->OpenFile(path, FileSys::Mode::Read);
  67. }
  68. struct System::Impl {
  69. Cpu& CurrentCpuCore() {
  70. return cpu_core_manager.GetCurrentCore();
  71. }
  72. ResultStatus RunLoop(bool tight_loop) {
  73. status = ResultStatus::Success;
  74. cpu_core_manager.RunLoop(tight_loop);
  75. return status;
  76. }
  77. ResultStatus Init(System& system, Frontend::EmuWindow& emu_window) {
  78. LOG_DEBUG(HW_Memory, "initialized OK");
  79. CoreTiming::Init();
  80. kernel.Initialize();
  81. // Create a default fs if one doesn't already exist.
  82. if (virtual_filesystem == nullptr)
  83. virtual_filesystem = std::make_shared<FileSys::RealVfsFilesystem>();
  84. /// Create default implementations of applets if one is not provided.
  85. if (software_keyboard == nullptr)
  86. software_keyboard = std::make_unique<Core::Frontend::DefaultSoftwareKeyboardApplet>();
  87. auto main_process = Kernel::Process::Create(kernel, "main");
  88. kernel.MakeCurrentProcess(main_process.get());
  89. telemetry_session = std::make_unique<Core::TelemetrySession>();
  90. service_manager = std::make_shared<Service::SM::ServiceManager>();
  91. Service::Init(service_manager, *virtual_filesystem);
  92. GDBStub::Init();
  93. renderer = VideoCore::CreateRenderer(emu_window);
  94. if (!renderer->Init()) {
  95. return ResultStatus::ErrorVideoCore;
  96. }
  97. gpu_core = std::make_unique<Tegra::GPU>(renderer->Rasterizer());
  98. cpu_core_manager.Initialize(system);
  99. is_powered_on = true;
  100. LOG_DEBUG(Core, "Initialized OK");
  101. // Reset counters and set time origin to current frame
  102. GetAndResetPerfStats();
  103. perf_stats.BeginSystemFrame();
  104. return ResultStatus::Success;
  105. }
  106. ResultStatus Load(System& system, Frontend::EmuWindow& emu_window,
  107. const std::string& filepath) {
  108. app_loader = Loader::GetLoader(GetGameFileFromPath(virtual_filesystem, filepath));
  109. if (!app_loader) {
  110. LOG_CRITICAL(Core, "Failed to obtain loader for {}!", filepath);
  111. return ResultStatus::ErrorGetLoader;
  112. }
  113. std::pair<std::optional<u32>, Loader::ResultStatus> system_mode =
  114. app_loader->LoadKernelSystemMode();
  115. if (system_mode.second != Loader::ResultStatus::Success) {
  116. LOG_CRITICAL(Core, "Failed to determine system mode (Error {})!",
  117. static_cast<int>(system_mode.second));
  118. return ResultStatus::ErrorSystemMode;
  119. }
  120. ResultStatus init_result{Init(system, emu_window)};
  121. if (init_result != ResultStatus::Success) {
  122. LOG_CRITICAL(Core, "Failed to initialize system (Error {})!",
  123. static_cast<int>(init_result));
  124. Shutdown();
  125. return init_result;
  126. }
  127. const Loader::ResultStatus load_result{app_loader->Load(*kernel.CurrentProcess())};
  128. if (load_result != Loader::ResultStatus::Success) {
  129. LOG_CRITICAL(Core, "Failed to load ROM (Error {})!", static_cast<int>(load_result));
  130. Shutdown();
  131. return static_cast<ResultStatus>(static_cast<u32>(ResultStatus::ErrorLoader) +
  132. static_cast<u32>(load_result));
  133. }
  134. status = ResultStatus::Success;
  135. return status;
  136. }
  137. void Shutdown() {
  138. // Log last frame performance stats
  139. auto perf_results = GetAndResetPerfStats();
  140. Telemetry().AddField(Telemetry::FieldType::Performance, "Shutdown_EmulationSpeed",
  141. perf_results.emulation_speed * 100.0);
  142. Telemetry().AddField(Telemetry::FieldType::Performance, "Shutdown_Framerate",
  143. perf_results.game_fps);
  144. Telemetry().AddField(Telemetry::FieldType::Performance, "Shutdown_Frametime",
  145. perf_results.frametime * 1000.0);
  146. is_powered_on = false;
  147. // Shutdown emulation session
  148. renderer.reset();
  149. GDBStub::Shutdown();
  150. Service::Shutdown();
  151. service_manager.reset();
  152. telemetry_session.reset();
  153. gpu_core.reset();
  154. // Close all CPU/threading state
  155. cpu_core_manager.Shutdown();
  156. // Shutdown kernel and core timing
  157. kernel.Shutdown();
  158. CoreTiming::Shutdown();
  159. // Close app loader
  160. app_loader.reset();
  161. LOG_DEBUG(Core, "Shutdown OK");
  162. }
  163. Loader::ResultStatus GetGameName(std::string& out) const {
  164. if (app_loader == nullptr)
  165. return Loader::ResultStatus::ErrorNotInitialized;
  166. return app_loader->ReadTitle(out);
  167. }
  168. void SetStatus(ResultStatus new_status, const char* details = nullptr) {
  169. status = new_status;
  170. if (details) {
  171. status_details = details;
  172. }
  173. }
  174. PerfStatsResults GetAndResetPerfStats() {
  175. return perf_stats.GetAndResetStats(CoreTiming::GetGlobalTimeUs());
  176. }
  177. Kernel::KernelCore kernel;
  178. /// RealVfsFilesystem instance
  179. FileSys::VirtualFilesystem virtual_filesystem;
  180. /// AppLoader used to load the current executing application
  181. std::unique_ptr<Loader::AppLoader> app_loader;
  182. std::unique_ptr<VideoCore::RendererBase> renderer;
  183. std::unique_ptr<Tegra::GPU> gpu_core;
  184. std::shared_ptr<Tegra::DebugContext> debug_context;
  185. CpuCoreManager cpu_core_manager;
  186. bool is_powered_on = false;
  187. /// Frontend applets
  188. std::unique_ptr<Core::Frontend::SoftwareKeyboardApplet> software_keyboard;
  189. /// Service manager
  190. std::shared_ptr<Service::SM::ServiceManager> service_manager;
  191. /// Telemetry session for this emulation session
  192. std::unique_ptr<Core::TelemetrySession> telemetry_session;
  193. ResultStatus status = ResultStatus::Success;
  194. std::string status_details = "";
  195. Core::PerfStats perf_stats;
  196. Core::FrameLimiter frame_limiter;
  197. };
  198. System::System() : impl{std::make_unique<Impl>()} {}
  199. System::~System() = default;
  200. Cpu& System::CurrentCpuCore() {
  201. return impl->CurrentCpuCore();
  202. }
  203. const Cpu& System::CurrentCpuCore() const {
  204. return impl->CurrentCpuCore();
  205. }
  206. System::ResultStatus System::RunLoop(bool tight_loop) {
  207. return impl->RunLoop(tight_loop);
  208. }
  209. System::ResultStatus System::SingleStep() {
  210. return RunLoop(false);
  211. }
  212. void System::InvalidateCpuInstructionCaches() {
  213. impl->cpu_core_manager.InvalidateAllInstructionCaches();
  214. }
  215. System::ResultStatus System::Load(Frontend::EmuWindow& emu_window, const std::string& filepath) {
  216. return impl->Load(*this, emu_window, filepath);
  217. }
  218. bool System::IsPoweredOn() const {
  219. return impl->is_powered_on;
  220. }
  221. void System::PrepareReschedule() {
  222. CurrentCpuCore().PrepareReschedule();
  223. }
  224. PerfStatsResults System::GetAndResetPerfStats() {
  225. return impl->GetAndResetPerfStats();
  226. }
  227. TelemetrySession& System::TelemetrySession() {
  228. return *impl->telemetry_session;
  229. }
  230. const TelemetrySession& System::TelemetrySession() const {
  231. return *impl->telemetry_session;
  232. }
  233. ARM_Interface& System::CurrentArmInterface() {
  234. return CurrentCpuCore().ArmInterface();
  235. }
  236. const ARM_Interface& System::CurrentArmInterface() const {
  237. return CurrentCpuCore().ArmInterface();
  238. }
  239. std::size_t System::CurrentCoreIndex() const {
  240. return CurrentCpuCore().CoreIndex();
  241. }
  242. Kernel::Scheduler& System::CurrentScheduler() {
  243. return CurrentCpuCore().Scheduler();
  244. }
  245. const Kernel::Scheduler& System::CurrentScheduler() const {
  246. return CurrentCpuCore().Scheduler();
  247. }
  248. Kernel::Scheduler& System::Scheduler(std::size_t core_index) {
  249. return CpuCore(core_index).Scheduler();
  250. }
  251. const Kernel::Scheduler& System::Scheduler(std::size_t core_index) const {
  252. return CpuCore(core_index).Scheduler();
  253. }
  254. Kernel::Process* System::CurrentProcess() {
  255. return impl->kernel.CurrentProcess();
  256. }
  257. const Kernel::Process* System::CurrentProcess() const {
  258. return impl->kernel.CurrentProcess();
  259. }
  260. ARM_Interface& System::ArmInterface(std::size_t core_index) {
  261. return CpuCore(core_index).ArmInterface();
  262. }
  263. const ARM_Interface& System::ArmInterface(std::size_t core_index) const {
  264. return CpuCore(core_index).ArmInterface();
  265. }
  266. Cpu& System::CpuCore(std::size_t core_index) {
  267. return impl->cpu_core_manager.GetCore(core_index);
  268. }
  269. const Cpu& System::CpuCore(std::size_t core_index) const {
  270. ASSERT(core_index < NUM_CPU_CORES);
  271. return impl->cpu_core_manager.GetCore(core_index);
  272. }
  273. ExclusiveMonitor& System::Monitor() {
  274. return impl->cpu_core_manager.GetExclusiveMonitor();
  275. }
  276. const ExclusiveMonitor& System::Monitor() const {
  277. return impl->cpu_core_manager.GetExclusiveMonitor();
  278. }
  279. Tegra::GPU& System::GPU() {
  280. return *impl->gpu_core;
  281. }
  282. const Tegra::GPU& System::GPU() const {
  283. return *impl->gpu_core;
  284. }
  285. VideoCore::RendererBase& System::Renderer() {
  286. return *impl->renderer;
  287. }
  288. const VideoCore::RendererBase& System::Renderer() const {
  289. return *impl->renderer;
  290. }
  291. Kernel::KernelCore& System::Kernel() {
  292. return impl->kernel;
  293. }
  294. const Kernel::KernelCore& System::Kernel() const {
  295. return impl->kernel;
  296. }
  297. Core::PerfStats& System::GetPerfStats() {
  298. return impl->perf_stats;
  299. }
  300. const Core::PerfStats& System::GetPerfStats() const {
  301. return impl->perf_stats;
  302. }
  303. Core::FrameLimiter& System::FrameLimiter() {
  304. return impl->frame_limiter;
  305. }
  306. const Core::FrameLimiter& System::FrameLimiter() const {
  307. return impl->frame_limiter;
  308. }
  309. Loader::ResultStatus System::GetGameName(std::string& out) const {
  310. return impl->GetGameName(out);
  311. }
  312. void System::SetStatus(ResultStatus new_status, const char* details) {
  313. impl->SetStatus(new_status, details);
  314. }
  315. const std::string& System::GetStatusDetails() const {
  316. return impl->status_details;
  317. }
  318. Loader::AppLoader& System::GetAppLoader() const {
  319. return *impl->app_loader;
  320. }
  321. void System::SetGPUDebugContext(std::shared_ptr<Tegra::DebugContext> context) {
  322. impl->debug_context = std::move(context);
  323. }
  324. Tegra::DebugContext* System::GetGPUDebugContext() const {
  325. return impl->debug_context.get();
  326. }
  327. void System::SetFilesystem(std::shared_ptr<FileSys::VfsFilesystem> vfs) {
  328. impl->virtual_filesystem = std::move(vfs);
  329. }
  330. std::shared_ptr<FileSys::VfsFilesystem> System::GetFilesystem() const {
  331. return impl->virtual_filesystem;
  332. }
  333. void System::SetSoftwareKeyboard(std::unique_ptr<Core::Frontend::SoftwareKeyboardApplet> applet) {
  334. impl->software_keyboard = std::move(applet);
  335. }
  336. const Core::Frontend::SoftwareKeyboardApplet& System::GetSoftwareKeyboard() const {
  337. return *impl->software_keyboard;
  338. }
  339. System::ResultStatus System::Init(Frontend::EmuWindow& emu_window) {
  340. return impl->Init(*this, emu_window);
  341. }
  342. void System::Shutdown() {
  343. impl->Shutdown();
  344. }
  345. Service::SM::ServiceManager& System::ServiceManager() {
  346. return *impl->service_manager;
  347. }
  348. const Service::SM::ServiceManager& System::ServiceManager() const {
  349. return *impl->service_manager;
  350. }
  351. } // namespace Core