core.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. // SPDX-FileCopyrightText: 2014 Citra Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <array>
  4. #include <atomic>
  5. #include <exception>
  6. #include <memory>
  7. #include <utility>
  8. #include "audio_core/audio_core.h"
  9. #include "common/fs/fs.h"
  10. #include "common/logging/log.h"
  11. #include "common/microprofile.h"
  12. #include "common/settings.h"
  13. #include "common/string_util.h"
  14. #include "core/arm/exclusive_monitor.h"
  15. #include "core/core.h"
  16. #include "core/core_timing.h"
  17. #include "core/cpu_manager.h"
  18. #include "core/debugger/debugger.h"
  19. #include "core/device_memory.h"
  20. #include "core/file_sys/bis_factory.h"
  21. #include "core/file_sys/mode.h"
  22. #include "core/file_sys/patch_manager.h"
  23. #include "core/file_sys/registered_cache.h"
  24. #include "core/file_sys/romfs_factory.h"
  25. #include "core/file_sys/savedata_factory.h"
  26. #include "core/file_sys/vfs_concat.h"
  27. #include "core/file_sys/vfs_real.h"
  28. #include "core/hid/hid_core.h"
  29. #include "core/hle/kernel/k_memory_manager.h"
  30. #include "core/hle/kernel/k_process.h"
  31. #include "core/hle/kernel/k_resource_limit.h"
  32. #include "core/hle/kernel/k_scheduler.h"
  33. #include "core/hle/kernel/kernel.h"
  34. #include "core/hle/kernel/physical_core.h"
  35. #include "core/hle/service/am/applets/applets.h"
  36. #include "core/hle/service/apm/apm_controller.h"
  37. #include "core/hle/service/filesystem/filesystem.h"
  38. #include "core/hle/service/glue/glue_manager.h"
  39. #include "core/hle/service/service.h"
  40. #include "core/hle/service/sm/sm.h"
  41. #include "core/hle/service/time/time_manager.h"
  42. #include "core/internal_network/network.h"
  43. #include "core/loader/loader.h"
  44. #include "core/memory.h"
  45. #include "core/memory/cheat_engine.h"
  46. #include "core/perf_stats.h"
  47. #include "core/reporter.h"
  48. #include "core/telemetry_session.h"
  49. #include "core/tools/freezer.h"
  50. #include "network/network.h"
  51. #include "video_core/host1x/host1x.h"
  52. #include "video_core/renderer_base.h"
  53. #include "video_core/video_core.h"
  54. MICROPROFILE_DEFINE(ARM_Jit_Dynarmic_CPU0, "ARM JIT", "Dynarmic CPU 0", MP_RGB(255, 64, 64));
  55. MICROPROFILE_DEFINE(ARM_Jit_Dynarmic_CPU1, "ARM JIT", "Dynarmic CPU 1", MP_RGB(255, 64, 64));
  56. MICROPROFILE_DEFINE(ARM_Jit_Dynarmic_CPU2, "ARM JIT", "Dynarmic CPU 2", MP_RGB(255, 64, 64));
  57. MICROPROFILE_DEFINE(ARM_Jit_Dynarmic_CPU3, "ARM JIT", "Dynarmic CPU 3", MP_RGB(255, 64, 64));
  58. namespace Core {
  59. namespace {
  60. FileSys::StorageId GetStorageIdForFrontendSlot(
  61. std::optional<FileSys::ContentProviderUnionSlot> slot) {
  62. if (!slot.has_value()) {
  63. return FileSys::StorageId::None;
  64. }
  65. switch (*slot) {
  66. case FileSys::ContentProviderUnionSlot::UserNAND:
  67. return FileSys::StorageId::NandUser;
  68. case FileSys::ContentProviderUnionSlot::SysNAND:
  69. return FileSys::StorageId::NandSystem;
  70. case FileSys::ContentProviderUnionSlot::SDMC:
  71. return FileSys::StorageId::SdCard;
  72. case FileSys::ContentProviderUnionSlot::FrontendManual:
  73. return FileSys::StorageId::Host;
  74. default:
  75. return FileSys::StorageId::None;
  76. }
  77. }
  78. } // Anonymous namespace
  79. FileSys::VirtualFile GetGameFileFromPath(const FileSys::VirtualFilesystem& vfs,
  80. const std::string& path) {
  81. // To account for split 00+01+etc files.
  82. std::string dir_name;
  83. std::string filename;
  84. Common::SplitPath(path, &dir_name, &filename, nullptr);
  85. if (filename == "00") {
  86. const auto dir = vfs->OpenDirectory(dir_name, FileSys::Mode::Read);
  87. std::vector<FileSys::VirtualFile> concat;
  88. for (u32 i = 0; i < 0x10; ++i) {
  89. const auto file_name = fmt::format("{:02X}", i);
  90. auto next = dir->GetFile(file_name);
  91. if (next != nullptr) {
  92. concat.push_back(std::move(next));
  93. } else {
  94. next = dir->GetFile(file_name);
  95. if (next == nullptr) {
  96. break;
  97. }
  98. concat.push_back(std::move(next));
  99. }
  100. }
  101. if (concat.empty()) {
  102. return nullptr;
  103. }
  104. return FileSys::ConcatenatedVfsFile::MakeConcatenatedFile(concat, dir->GetName());
  105. }
  106. if (Common::FS::IsDir(path)) {
  107. return vfs->OpenFile(path + "/main", FileSys::Mode::Read);
  108. }
  109. return vfs->OpenFile(path, FileSys::Mode::Read);
  110. }
  111. struct System::Impl {
  112. explicit Impl(System& system)
  113. : kernel{system}, fs_controller{system}, memory{system}, hid_core{}, room_network{},
  114. cpu_manager{system}, reporter{system}, applet_manager{system}, time_manager{system} {}
  115. void Initialize(System& system) {
  116. device_memory = std::make_unique<Core::DeviceMemory>();
  117. is_multicore = Settings::values.use_multi_core.GetValue();
  118. extended_memory_layout = Settings::values.use_unsafe_extended_memory_layout.GetValue();
  119. core_timing.SetMulticore(is_multicore);
  120. core_timing.Initialize([&system]() { system.RegisterHostThread(); });
  121. const auto posix_time = std::chrono::system_clock::now().time_since_epoch();
  122. const auto current_time =
  123. std::chrono::duration_cast<std::chrono::seconds>(posix_time).count();
  124. Settings::values.custom_rtc_differential =
  125. Settings::values.custom_rtc.value_or(current_time) - current_time;
  126. // Create a default fs if one doesn't already exist.
  127. if (virtual_filesystem == nullptr) {
  128. virtual_filesystem = std::make_shared<FileSys::RealVfsFilesystem>();
  129. }
  130. if (content_provider == nullptr) {
  131. content_provider = std::make_unique<FileSys::ContentProviderUnion>();
  132. }
  133. // Create default implementations of applets if one is not provided.
  134. applet_manager.SetDefaultAppletsIfMissing();
  135. is_async_gpu = Settings::values.use_asynchronous_gpu_emulation.GetValue();
  136. kernel.SetMulticore(is_multicore);
  137. cpu_manager.SetMulticore(is_multicore);
  138. cpu_manager.SetAsyncGpu(is_async_gpu);
  139. }
  140. void ReinitializeIfNecessary(System& system) {
  141. const bool must_reinitialize =
  142. is_multicore != Settings::values.use_multi_core.GetValue() ||
  143. extended_memory_layout != Settings::values.use_unsafe_extended_memory_layout.GetValue();
  144. if (!must_reinitialize) {
  145. return;
  146. }
  147. LOG_DEBUG(Kernel, "Re-initializing");
  148. is_multicore = Settings::values.use_multi_core.GetValue();
  149. extended_memory_layout = Settings::values.use_unsafe_extended_memory_layout.GetValue();
  150. Initialize(system);
  151. }
  152. void Run() {
  153. std::unique_lock<std::mutex> lk(suspend_guard);
  154. kernel.SuspendApplication(false);
  155. core_timing.SyncPause(false);
  156. is_paused.store(false, std::memory_order_relaxed);
  157. }
  158. void Pause() {
  159. std::unique_lock<std::mutex> lk(suspend_guard);
  160. core_timing.SyncPause(true);
  161. kernel.SuspendApplication(true);
  162. is_paused.store(true, std::memory_order_relaxed);
  163. }
  164. bool IsPaused() const {
  165. return is_paused.load(std::memory_order_relaxed);
  166. }
  167. std::unique_lock<std::mutex> StallApplication() {
  168. std::unique_lock<std::mutex> lk(suspend_guard);
  169. kernel.SuspendApplication(true);
  170. core_timing.SyncPause(true);
  171. return lk;
  172. }
  173. void UnstallApplication() {
  174. if (!IsPaused()) {
  175. core_timing.SyncPause(false);
  176. kernel.SuspendApplication(false);
  177. }
  178. }
  179. void SetNVDECActive(bool is_nvdec_active) {
  180. nvdec_active = is_nvdec_active;
  181. }
  182. bool GetNVDECActive() {
  183. return nvdec_active;
  184. }
  185. void InitializeDebugger(System& system, u16 port) {
  186. debugger = std::make_unique<Debugger>(system, port);
  187. }
  188. SystemResultStatus SetupForApplicationProcess(System& system, Frontend::EmuWindow& emu_window) {
  189. LOG_DEBUG(Core, "initialized OK");
  190. // Setting changes may require a full system reinitialization (e.g., disabling multicore).
  191. ReinitializeIfNecessary(system);
  192. kernel.Initialize();
  193. cpu_manager.Initialize();
  194. /// Reset all glue registrations
  195. arp_manager.ResetAll();
  196. telemetry_session = std::make_unique<Core::TelemetrySession>();
  197. host1x_core = std::make_unique<Tegra::Host1x::Host1x>(system);
  198. gpu_core = VideoCore::CreateGPU(emu_window, system);
  199. if (!gpu_core) {
  200. return SystemResultStatus::ErrorVideoCore;
  201. }
  202. audio_core = std::make_unique<AudioCore::AudioCore>(system);
  203. service_manager = std::make_shared<Service::SM::ServiceManager>(kernel);
  204. services = std::make_unique<Service::Services>(service_manager, system);
  205. // Initialize time manager, which must happen after kernel is created
  206. time_manager.Initialize();
  207. is_powered_on = true;
  208. exit_lock = false;
  209. microprofile_dynarmic[0] = MICROPROFILE_TOKEN(ARM_Jit_Dynarmic_CPU0);
  210. microprofile_dynarmic[1] = MICROPROFILE_TOKEN(ARM_Jit_Dynarmic_CPU1);
  211. microprofile_dynarmic[2] = MICROPROFILE_TOKEN(ARM_Jit_Dynarmic_CPU2);
  212. microprofile_dynarmic[3] = MICROPROFILE_TOKEN(ARM_Jit_Dynarmic_CPU3);
  213. LOG_DEBUG(Core, "Initialized OK");
  214. return SystemResultStatus::Success;
  215. }
  216. SystemResultStatus Load(System& system, Frontend::EmuWindow& emu_window,
  217. const std::string& filepath, u64 program_id,
  218. std::size_t program_index) {
  219. app_loader = Loader::GetLoader(system, GetGameFileFromPath(virtual_filesystem, filepath),
  220. program_id, program_index);
  221. if (!app_loader) {
  222. LOG_CRITICAL(Core, "Failed to obtain loader for {}!", filepath);
  223. return SystemResultStatus::ErrorGetLoader;
  224. }
  225. SystemResultStatus init_result{SetupForApplicationProcess(system, emu_window)};
  226. if (init_result != SystemResultStatus::Success) {
  227. LOG_CRITICAL(Core, "Failed to initialize system (Error {})!",
  228. static_cast<int>(init_result));
  229. ShutdownMainProcess();
  230. return init_result;
  231. }
  232. telemetry_session->AddInitialInfo(*app_loader, fs_controller, *content_provider);
  233. // Create a resource limit for the process.
  234. const auto physical_memory_size =
  235. kernel.MemoryManager().GetSize(Kernel::KMemoryManager::Pool::Application);
  236. auto* resource_limit = Kernel::CreateResourceLimitForProcess(system, physical_memory_size);
  237. // Create the process.
  238. auto main_process = Kernel::KProcess::Create(system.Kernel());
  239. ASSERT(Kernel::KProcess::Initialize(main_process, system, "main",
  240. Kernel::KProcess::ProcessType::Userland, resource_limit)
  241. .IsSuccess());
  242. Kernel::KProcess::Register(system.Kernel(), main_process);
  243. kernel.MakeApplicationProcess(main_process);
  244. const auto [load_result, load_parameters] = app_loader->Load(*main_process, system);
  245. if (load_result != Loader::ResultStatus::Success) {
  246. LOG_CRITICAL(Core, "Failed to load ROM (Error {})!", load_result);
  247. ShutdownMainProcess();
  248. return static_cast<SystemResultStatus>(
  249. static_cast<u32>(SystemResultStatus::ErrorLoader) + static_cast<u32>(load_result));
  250. }
  251. AddGlueRegistrationForProcess(*app_loader, *main_process);
  252. kernel.InitializeCores();
  253. // Initialize cheat engine
  254. if (cheat_engine) {
  255. cheat_engine->Initialize();
  256. }
  257. // All threads are started, begin main process execution, now that we're in the clear.
  258. main_process->Run(load_parameters->main_thread_priority,
  259. load_parameters->main_thread_stack_size);
  260. if (Settings::values.gamecard_inserted) {
  261. if (Settings::values.gamecard_current_game) {
  262. fs_controller.SetGameCard(GetGameFileFromPath(virtual_filesystem, filepath));
  263. } else if (!Settings::values.gamecard_path.GetValue().empty()) {
  264. const auto& gamecard_path = Settings::values.gamecard_path.GetValue();
  265. fs_controller.SetGameCard(GetGameFileFromPath(virtual_filesystem, gamecard_path));
  266. }
  267. }
  268. if (app_loader->ReadProgramId(program_id) != Loader::ResultStatus::Success) {
  269. LOG_ERROR(Core, "Failed to find title id for ROM (Error {})", load_result);
  270. }
  271. perf_stats = std::make_unique<PerfStats>(program_id);
  272. // Reset counters and set time origin to current frame
  273. GetAndResetPerfStats();
  274. perf_stats->BeginSystemFrame();
  275. std::string name = "Unknown Game";
  276. if (app_loader->ReadTitle(name) != Loader::ResultStatus::Success) {
  277. LOG_ERROR(Core, "Failed to read title for ROM (Error {})", load_result);
  278. }
  279. std::string title_version;
  280. const FileSys::PatchManager pm(program_id, system.GetFileSystemController(),
  281. system.GetContentProvider());
  282. const auto metadata = pm.GetControlMetadata();
  283. if (metadata.first != nullptr) {
  284. title_version = metadata.first->GetVersionString();
  285. }
  286. if (auto room_member = room_network.GetRoomMember().lock()) {
  287. Network::GameInfo game_info;
  288. game_info.name = name;
  289. game_info.id = program_id;
  290. game_info.version = title_version;
  291. room_member->SendGameInfo(game_info);
  292. }
  293. status = SystemResultStatus::Success;
  294. return status;
  295. }
  296. void ShutdownMainProcess() {
  297. SetShuttingDown(true);
  298. // Log last frame performance stats if game was loaded
  299. if (perf_stats) {
  300. const auto perf_results = GetAndResetPerfStats();
  301. constexpr auto performance = Common::Telemetry::FieldType::Performance;
  302. telemetry_session->AddField(performance, "Shutdown_EmulationSpeed",
  303. perf_results.emulation_speed * 100.0);
  304. telemetry_session->AddField(performance, "Shutdown_Framerate",
  305. perf_results.average_game_fps);
  306. telemetry_session->AddField(performance, "Shutdown_Frametime",
  307. perf_results.frametime * 1000.0);
  308. telemetry_session->AddField(performance, "Mean_Frametime_MS",
  309. perf_stats->GetMeanFrametime());
  310. }
  311. is_powered_on = false;
  312. exit_lock = false;
  313. if (gpu_core != nullptr) {
  314. gpu_core->NotifyShutdown();
  315. }
  316. kernel.SuspendApplication(true);
  317. if (services) {
  318. services->KillNVNFlinger();
  319. }
  320. kernel.CloseServices();
  321. services.reset();
  322. service_manager.reset();
  323. cheat_engine.reset();
  324. telemetry_session.reset();
  325. time_manager.Shutdown();
  326. core_timing.ClearPendingEvents();
  327. app_loader.reset();
  328. audio_core.reset();
  329. gpu_core.reset();
  330. host1x_core.reset();
  331. perf_stats.reset();
  332. kernel.ShutdownCores();
  333. cpu_manager.Shutdown();
  334. debugger.reset();
  335. kernel.Shutdown();
  336. memory.Reset();
  337. if (auto room_member = room_network.GetRoomMember().lock()) {
  338. Network::GameInfo game_info{};
  339. room_member->SendGameInfo(game_info);
  340. }
  341. LOG_DEBUG(Core, "Shutdown OK");
  342. }
  343. bool IsShuttingDown() const {
  344. return is_shutting_down;
  345. }
  346. void SetShuttingDown(bool shutting_down) {
  347. is_shutting_down = shutting_down;
  348. }
  349. Loader::ResultStatus GetGameName(std::string& out) const {
  350. if (app_loader == nullptr)
  351. return Loader::ResultStatus::ErrorNotInitialized;
  352. return app_loader->ReadTitle(out);
  353. }
  354. void AddGlueRegistrationForProcess(Loader::AppLoader& loader, Kernel::KProcess& process) {
  355. std::vector<u8> nacp_data;
  356. FileSys::NACP nacp;
  357. if (loader.ReadControlData(nacp) == Loader::ResultStatus::Success) {
  358. nacp_data = nacp.GetRawBytes();
  359. } else {
  360. nacp_data.resize(sizeof(FileSys::RawNACP));
  361. }
  362. Service::Glue::ApplicationLaunchProperty launch{};
  363. launch.title_id = process.GetProgramId();
  364. FileSys::PatchManager pm{launch.title_id, fs_controller, *content_provider};
  365. launch.version = pm.GetGameVersion().value_or(0);
  366. // TODO(DarkLordZach): When FSController/Game Card Support is added, if
  367. // current_process_game_card use correct StorageId
  368. launch.base_game_storage_id = GetStorageIdForFrontendSlot(content_provider->GetSlotForEntry(
  369. launch.title_id, FileSys::ContentRecordType::Program));
  370. launch.update_storage_id = GetStorageIdForFrontendSlot(content_provider->GetSlotForEntry(
  371. FileSys::GetUpdateTitleID(launch.title_id), FileSys::ContentRecordType::Program));
  372. arp_manager.Register(launch.title_id, launch, std::move(nacp_data));
  373. }
  374. void SetStatus(SystemResultStatus new_status, const char* details = nullptr) {
  375. status = new_status;
  376. if (details) {
  377. status_details = details;
  378. }
  379. }
  380. PerfStatsResults GetAndResetPerfStats() {
  381. return perf_stats->GetAndResetStats(core_timing.GetGlobalTimeUs());
  382. }
  383. mutable std::mutex suspend_guard;
  384. std::atomic_bool is_paused{};
  385. std::atomic<bool> is_shutting_down{};
  386. Timing::CoreTiming core_timing;
  387. Kernel::KernelCore kernel;
  388. /// RealVfsFilesystem instance
  389. FileSys::VirtualFilesystem virtual_filesystem;
  390. /// ContentProviderUnion instance
  391. std::unique_ptr<FileSys::ContentProviderUnion> content_provider;
  392. Service::FileSystem::FileSystemController fs_controller;
  393. /// AppLoader used to load the current executing application
  394. std::unique_ptr<Loader::AppLoader> app_loader;
  395. std::unique_ptr<Tegra::GPU> gpu_core;
  396. std::unique_ptr<Tegra::Host1x::Host1x> host1x_core;
  397. std::unique_ptr<Core::DeviceMemory> device_memory;
  398. std::unique_ptr<AudioCore::AudioCore> audio_core;
  399. Core::Memory::Memory memory;
  400. Core::HID::HIDCore hid_core;
  401. Network::RoomNetwork room_network;
  402. CpuManager cpu_manager;
  403. std::atomic_bool is_powered_on{};
  404. bool exit_lock = false;
  405. bool nvdec_active{};
  406. Reporter reporter;
  407. std::unique_ptr<Memory::CheatEngine> cheat_engine;
  408. std::unique_ptr<Tools::Freezer> memory_freezer;
  409. std::array<u8, 0x20> build_id{};
  410. /// Frontend applets
  411. Service::AM::Applets::AppletManager applet_manager;
  412. /// APM (Performance) services
  413. Service::APM::Controller apm_controller{core_timing};
  414. /// Service State
  415. Service::Glue::ARPManager arp_manager;
  416. Service::Time::TimeManager time_manager;
  417. /// Service manager
  418. std::shared_ptr<Service::SM::ServiceManager> service_manager;
  419. /// Services
  420. std::unique_ptr<Service::Services> services;
  421. /// Telemetry session for this emulation session
  422. std::unique_ptr<Core::TelemetrySession> telemetry_session;
  423. /// Network instance
  424. Network::NetworkInstance network_instance;
  425. /// Debugger
  426. std::unique_ptr<Core::Debugger> debugger;
  427. SystemResultStatus status = SystemResultStatus::Success;
  428. std::string status_details = "";
  429. std::unique_ptr<Core::PerfStats> perf_stats;
  430. Core::SpeedLimiter speed_limiter;
  431. bool is_multicore{};
  432. bool is_async_gpu{};
  433. bool extended_memory_layout{};
  434. ExecuteProgramCallback execute_program_callback;
  435. ExitCallback exit_callback;
  436. std::array<u64, Core::Hardware::NUM_CPU_CORES> dynarmic_ticks{};
  437. std::array<MicroProfileToken, Core::Hardware::NUM_CPU_CORES> microprofile_dynarmic{};
  438. };
  439. System::System() : impl{std::make_unique<Impl>(*this)} {}
  440. System::~System() = default;
  441. CpuManager& System::GetCpuManager() {
  442. return impl->cpu_manager;
  443. }
  444. const CpuManager& System::GetCpuManager() const {
  445. return impl->cpu_manager;
  446. }
  447. void System::Initialize() {
  448. impl->Initialize(*this);
  449. }
  450. void System::Run() {
  451. impl->Run();
  452. }
  453. void System::Pause() {
  454. impl->Pause();
  455. }
  456. bool System::IsPaused() const {
  457. return impl->IsPaused();
  458. }
  459. void System::InvalidateCpuInstructionCaches() {
  460. impl->kernel.InvalidateAllInstructionCaches();
  461. }
  462. void System::InvalidateCpuInstructionCacheRange(u64 addr, std::size_t size) {
  463. impl->kernel.InvalidateCpuInstructionCacheRange(addr, size);
  464. }
  465. void System::ShutdownMainProcess() {
  466. impl->ShutdownMainProcess();
  467. }
  468. bool System::IsShuttingDown() const {
  469. return impl->IsShuttingDown();
  470. }
  471. void System::SetShuttingDown(bool shutting_down) {
  472. impl->SetShuttingDown(shutting_down);
  473. }
  474. void System::DetachDebugger() {
  475. if (impl->debugger) {
  476. impl->debugger->NotifyShutdown();
  477. }
  478. }
  479. std::unique_lock<std::mutex> System::StallApplication() {
  480. return impl->StallApplication();
  481. }
  482. void System::UnstallApplication() {
  483. impl->UnstallApplication();
  484. }
  485. void System::SetNVDECActive(bool is_nvdec_active) {
  486. impl->SetNVDECActive(is_nvdec_active);
  487. }
  488. bool System::GetNVDECActive() {
  489. return impl->GetNVDECActive();
  490. }
  491. void System::InitializeDebugger() {
  492. impl->InitializeDebugger(*this, Settings::values.gdbstub_port.GetValue());
  493. }
  494. SystemResultStatus System::Load(Frontend::EmuWindow& emu_window, const std::string& filepath,
  495. u64 program_id, std::size_t program_index) {
  496. return impl->Load(*this, emu_window, filepath, program_id, program_index);
  497. }
  498. bool System::IsPoweredOn() const {
  499. return impl->is_powered_on.load(std::memory_order::relaxed);
  500. }
  501. void System::PrepareReschedule(const u32 core_index) {
  502. impl->kernel.PrepareReschedule(core_index);
  503. }
  504. size_t System::GetCurrentHostThreadID() const {
  505. return impl->kernel.GetCurrentHostThreadID();
  506. }
  507. PerfStatsResults System::GetAndResetPerfStats() {
  508. return impl->GetAndResetPerfStats();
  509. }
  510. TelemetrySession& System::TelemetrySession() {
  511. return *impl->telemetry_session;
  512. }
  513. const TelemetrySession& System::TelemetrySession() const {
  514. return *impl->telemetry_session;
  515. }
  516. ARM_Interface& System::CurrentArmInterface() {
  517. return impl->kernel.CurrentPhysicalCore().ArmInterface();
  518. }
  519. const ARM_Interface& System::CurrentArmInterface() const {
  520. return impl->kernel.CurrentPhysicalCore().ArmInterface();
  521. }
  522. Kernel::PhysicalCore& System::CurrentPhysicalCore() {
  523. return impl->kernel.CurrentPhysicalCore();
  524. }
  525. const Kernel::PhysicalCore& System::CurrentPhysicalCore() const {
  526. return impl->kernel.CurrentPhysicalCore();
  527. }
  528. /// Gets the global scheduler
  529. Kernel::GlobalSchedulerContext& System::GlobalSchedulerContext() {
  530. return impl->kernel.GlobalSchedulerContext();
  531. }
  532. /// Gets the global scheduler
  533. const Kernel::GlobalSchedulerContext& System::GlobalSchedulerContext() const {
  534. return impl->kernel.GlobalSchedulerContext();
  535. }
  536. Kernel::KProcess* System::ApplicationProcess() {
  537. return impl->kernel.ApplicationProcess();
  538. }
  539. Core::DeviceMemory& System::DeviceMemory() {
  540. return *impl->device_memory;
  541. }
  542. const Core::DeviceMemory& System::DeviceMemory() const {
  543. return *impl->device_memory;
  544. }
  545. const Kernel::KProcess* System::ApplicationProcess() const {
  546. return impl->kernel.ApplicationProcess();
  547. }
  548. ARM_Interface& System::ArmInterface(std::size_t core_index) {
  549. return impl->kernel.PhysicalCore(core_index).ArmInterface();
  550. }
  551. const ARM_Interface& System::ArmInterface(std::size_t core_index) const {
  552. return impl->kernel.PhysicalCore(core_index).ArmInterface();
  553. }
  554. ExclusiveMonitor& System::Monitor() {
  555. return impl->kernel.GetExclusiveMonitor();
  556. }
  557. const ExclusiveMonitor& System::Monitor() const {
  558. return impl->kernel.GetExclusiveMonitor();
  559. }
  560. Memory::Memory& System::ApplicationMemory() {
  561. return impl->memory;
  562. }
  563. const Core::Memory::Memory& System::ApplicationMemory() const {
  564. return impl->memory;
  565. }
  566. Tegra::GPU& System::GPU() {
  567. return *impl->gpu_core;
  568. }
  569. const Tegra::GPU& System::GPU() const {
  570. return *impl->gpu_core;
  571. }
  572. Tegra::Host1x::Host1x& System::Host1x() {
  573. return *impl->host1x_core;
  574. }
  575. const Tegra::Host1x::Host1x& System::Host1x() const {
  576. return *impl->host1x_core;
  577. }
  578. VideoCore::RendererBase& System::Renderer() {
  579. return impl->gpu_core->Renderer();
  580. }
  581. const VideoCore::RendererBase& System::Renderer() const {
  582. return impl->gpu_core->Renderer();
  583. }
  584. Kernel::KernelCore& System::Kernel() {
  585. return impl->kernel;
  586. }
  587. const Kernel::KernelCore& System::Kernel() const {
  588. return impl->kernel;
  589. }
  590. HID::HIDCore& System::HIDCore() {
  591. return impl->hid_core;
  592. }
  593. const HID::HIDCore& System::HIDCore() const {
  594. return impl->hid_core;
  595. }
  596. AudioCore::AudioCore& System::AudioCore() {
  597. return *impl->audio_core;
  598. }
  599. const AudioCore::AudioCore& System::AudioCore() const {
  600. return *impl->audio_core;
  601. }
  602. Timing::CoreTiming& System::CoreTiming() {
  603. return impl->core_timing;
  604. }
  605. const Timing::CoreTiming& System::CoreTiming() const {
  606. return impl->core_timing;
  607. }
  608. Core::PerfStats& System::GetPerfStats() {
  609. return *impl->perf_stats;
  610. }
  611. const Core::PerfStats& System::GetPerfStats() const {
  612. return *impl->perf_stats;
  613. }
  614. Core::SpeedLimiter& System::SpeedLimiter() {
  615. return impl->speed_limiter;
  616. }
  617. const Core::SpeedLimiter& System::SpeedLimiter() const {
  618. return impl->speed_limiter;
  619. }
  620. u64 System::GetApplicationProcessProgramID() const {
  621. return impl->kernel.ApplicationProcess()->GetProgramId();
  622. }
  623. Loader::ResultStatus System::GetGameName(std::string& out) const {
  624. return impl->GetGameName(out);
  625. }
  626. void System::SetStatus(SystemResultStatus new_status, const char* details) {
  627. impl->SetStatus(new_status, details);
  628. }
  629. const std::string& System::GetStatusDetails() const {
  630. return impl->status_details;
  631. }
  632. Loader::AppLoader& System::GetAppLoader() {
  633. return *impl->app_loader;
  634. }
  635. const Loader::AppLoader& System::GetAppLoader() const {
  636. return *impl->app_loader;
  637. }
  638. void System::SetFilesystem(FileSys::VirtualFilesystem vfs) {
  639. impl->virtual_filesystem = std::move(vfs);
  640. }
  641. FileSys::VirtualFilesystem System::GetFilesystem() const {
  642. return impl->virtual_filesystem;
  643. }
  644. void System::RegisterCheatList(const std::vector<Memory::CheatEntry>& list,
  645. const std::array<u8, 32>& build_id, u64 main_region_begin,
  646. u64 main_region_size) {
  647. impl->cheat_engine = std::make_unique<Memory::CheatEngine>(*this, list, build_id);
  648. impl->cheat_engine->SetMainMemoryParameters(main_region_begin, main_region_size);
  649. }
  650. void System::SetAppletFrontendSet(Service::AM::Applets::AppletFrontendSet&& set) {
  651. impl->applet_manager.SetAppletFrontendSet(std::move(set));
  652. }
  653. void System::SetDefaultAppletFrontendSet() {
  654. impl->applet_manager.SetDefaultAppletFrontendSet();
  655. }
  656. Service::AM::Applets::AppletManager& System::GetAppletManager() {
  657. return impl->applet_manager;
  658. }
  659. const Service::AM::Applets::AppletManager& System::GetAppletManager() const {
  660. return impl->applet_manager;
  661. }
  662. void System::SetContentProvider(std::unique_ptr<FileSys::ContentProviderUnion> provider) {
  663. impl->content_provider = std::move(provider);
  664. }
  665. FileSys::ContentProvider& System::GetContentProvider() {
  666. return *impl->content_provider;
  667. }
  668. const FileSys::ContentProvider& System::GetContentProvider() const {
  669. return *impl->content_provider;
  670. }
  671. Service::FileSystem::FileSystemController& System::GetFileSystemController() {
  672. return impl->fs_controller;
  673. }
  674. const Service::FileSystem::FileSystemController& System::GetFileSystemController() const {
  675. return impl->fs_controller;
  676. }
  677. void System::RegisterContentProvider(FileSys::ContentProviderUnionSlot slot,
  678. FileSys::ContentProvider* provider) {
  679. impl->content_provider->SetSlot(slot, provider);
  680. }
  681. void System::ClearContentProvider(FileSys::ContentProviderUnionSlot slot) {
  682. impl->content_provider->ClearSlot(slot);
  683. }
  684. const Reporter& System::GetReporter() const {
  685. return impl->reporter;
  686. }
  687. Service::Glue::ARPManager& System::GetARPManager() {
  688. return impl->arp_manager;
  689. }
  690. const Service::Glue::ARPManager& System::GetARPManager() const {
  691. return impl->arp_manager;
  692. }
  693. Service::APM::Controller& System::GetAPMController() {
  694. return impl->apm_controller;
  695. }
  696. const Service::APM::Controller& System::GetAPMController() const {
  697. return impl->apm_controller;
  698. }
  699. Service::Time::TimeManager& System::GetTimeManager() {
  700. return impl->time_manager;
  701. }
  702. const Service::Time::TimeManager& System::GetTimeManager() const {
  703. return impl->time_manager;
  704. }
  705. void System::SetExitLock(bool locked) {
  706. impl->exit_lock = locked;
  707. }
  708. bool System::GetExitLock() const {
  709. return impl->exit_lock;
  710. }
  711. void System::SetApplicationProcessBuildID(const CurrentBuildProcessID& id) {
  712. impl->build_id = id;
  713. }
  714. const System::CurrentBuildProcessID& System::GetApplicationProcessBuildID() const {
  715. return impl->build_id;
  716. }
  717. Service::SM::ServiceManager& System::ServiceManager() {
  718. return *impl->service_manager;
  719. }
  720. const Service::SM::ServiceManager& System::ServiceManager() const {
  721. return *impl->service_manager;
  722. }
  723. void System::RegisterCoreThread(std::size_t id) {
  724. impl->kernel.RegisterCoreThread(id);
  725. }
  726. void System::RegisterHostThread() {
  727. impl->kernel.RegisterHostThread();
  728. }
  729. void System::EnterDynarmicProfile() {
  730. std::size_t core = impl->kernel.GetCurrentHostThreadID();
  731. impl->dynarmic_ticks[core] = MicroProfileEnter(impl->microprofile_dynarmic[core]);
  732. }
  733. void System::ExitDynarmicProfile() {
  734. std::size_t core = impl->kernel.GetCurrentHostThreadID();
  735. MicroProfileLeave(impl->microprofile_dynarmic[core], impl->dynarmic_ticks[core]);
  736. }
  737. bool System::IsMulticore() const {
  738. return impl->is_multicore;
  739. }
  740. bool System::DebuggerEnabled() const {
  741. return Settings::values.use_gdbstub.GetValue();
  742. }
  743. Core::Debugger& System::GetDebugger() {
  744. return *impl->debugger;
  745. }
  746. const Core::Debugger& System::GetDebugger() const {
  747. return *impl->debugger;
  748. }
  749. Network::RoomNetwork& System::GetRoomNetwork() {
  750. return impl->room_network;
  751. }
  752. const Network::RoomNetwork& System::GetRoomNetwork() const {
  753. return impl->room_network;
  754. }
  755. void System::RunServer(std::unique_ptr<Service::ServerManager>&& server_manager) {
  756. return impl->kernel.RunServer(std::move(server_manager));
  757. }
  758. void System::RegisterExecuteProgramCallback(ExecuteProgramCallback&& callback) {
  759. impl->execute_program_callback = std::move(callback);
  760. }
  761. void System::ExecuteProgram(std::size_t program_index) {
  762. if (impl->execute_program_callback) {
  763. impl->execute_program_callback(program_index);
  764. } else {
  765. LOG_CRITICAL(Core, "execute_program_callback must be initialized by the frontend");
  766. }
  767. }
  768. void System::RegisterExitCallback(ExitCallback&& callback) {
  769. impl->exit_callback = std::move(callback);
  770. }
  771. void System::Exit() {
  772. if (impl->exit_callback) {
  773. impl->exit_callback();
  774. } else {
  775. LOG_CRITICAL(Core, "exit_callback must be initialized by the frontend");
  776. }
  777. }
  778. void System::ApplySettings() {
  779. if (IsPoweredOn()) {
  780. Renderer().RefreshBaseSettings();
  781. }
  782. }
  783. } // namespace Core