core.cpp 14 KB

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