Horizon.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. using LibHac;
  2. using LibHac.Account;
  3. using LibHac.Common;
  4. using LibHac.Fs;
  5. using LibHac.FsService;
  6. using LibHac.FsSystem;
  7. using LibHac.FsSystem.NcaUtils;
  8. using LibHac.Ncm;
  9. using LibHac.Ns;
  10. using LibHac.Spl;
  11. using Ryujinx.Common.Logging;
  12. using Ryujinx.HLE.FileSystem.Content;
  13. using Ryujinx.HLE.HOS.Font;
  14. using Ryujinx.HLE.HOS.Kernel.Common;
  15. using Ryujinx.HLE.HOS.Kernel.Memory;
  16. using Ryujinx.HLE.HOS.Kernel.Process;
  17. using Ryujinx.HLE.HOS.Kernel.Threading;
  18. using Ryujinx.HLE.HOS.Services.Pcv.Bpc;
  19. using Ryujinx.HLE.HOS.Services.Settings;
  20. using Ryujinx.HLE.HOS.Services.Sm;
  21. using Ryujinx.HLE.HOS.Services.Time.Clock;
  22. using Ryujinx.HLE.HOS.SystemState;
  23. using Ryujinx.HLE.Loaders.Executables;
  24. using Ryujinx.HLE.Loaders.Npdm;
  25. using Ryujinx.HLE.Utilities;
  26. using System;
  27. using System.Collections.Concurrent;
  28. using System.Collections.Generic;
  29. using System.IO;
  30. using System.Linq;
  31. using System.Reflection;
  32. using System.Threading;
  33. using TimeServiceManager = Ryujinx.HLE.HOS.Services.Time.TimeManager;
  34. using NxStaticObject = Ryujinx.HLE.Loaders.Executables.NxStaticObject;
  35. using static LibHac.Fs.ApplicationSaveDataManagement;
  36. namespace Ryujinx.HLE.HOS
  37. {
  38. public class Horizon : IDisposable
  39. {
  40. internal const int InitialKipId = 1;
  41. internal const int InitialProcessId = 0x51;
  42. internal const int HidSize = 0x40000;
  43. internal const int FontSize = 0x1100000;
  44. internal const int IirsSize = 0x8000;
  45. internal const int TimeSize = 0x1000;
  46. private const int MemoryBlockAllocatorSize = 0x2710;
  47. private const ulong UserSlabHeapBase = DramMemoryMap.SlabHeapBase;
  48. private const ulong UserSlabHeapItemSize = KMemoryManager.PageSize;
  49. private const ulong UserSlabHeapSize = 0x3de000;
  50. internal long PrivilegedProcessLowestId { get; set; } = 1;
  51. internal long PrivilegedProcessHighestId { get; set; } = 8;
  52. internal Switch Device { get; private set; }
  53. public SystemStateMgr State { get; private set; }
  54. internal bool KernelInitialized { get; private set; }
  55. internal KResourceLimit ResourceLimit { get; private set; }
  56. internal KMemoryRegionManager[] MemoryRegions { get; private set; }
  57. internal KMemoryBlockAllocator LargeMemoryBlockAllocator { get; private set; }
  58. internal KMemoryBlockAllocator SmallMemoryBlockAllocator { get; private set; }
  59. internal KSlabHeap UserSlabHeapPages { get; private set; }
  60. internal KCriticalSection CriticalSection { get; private set; }
  61. internal KScheduler Scheduler { get; private set; }
  62. internal KTimeManager TimeManager { get; private set; }
  63. internal KSynchronization Synchronization { get; private set; }
  64. internal KContextIdManager ContextIdManager { get; private set; }
  65. private long _kipId;
  66. private long _processId;
  67. private long _threadUid;
  68. internal CountdownEvent ThreadCounter;
  69. internal SortedDictionary<long, KProcess> Processes;
  70. internal ConcurrentDictionary<string, KAutoObject> AutoObjectNames;
  71. internal bool EnableVersionChecks { get; private set; }
  72. internal AppletStateMgr AppletState { get; private set; }
  73. internal KSharedMemory HidSharedMem { get; private set; }
  74. internal KSharedMemory FontSharedMem { get; private set; }
  75. internal KSharedMemory IirsSharedMem { get; private set; }
  76. internal SharedFontManager Font { get; private set; }
  77. internal ContentManager ContentManager { get; private set; }
  78. internal KEvent VsyncEvent { get; private set; }
  79. public Keyset KeySet { get; private set; }
  80. private bool _hasStarted;
  81. public BlitStruct<ApplicationControlProperty> ControlData { get; set; }
  82. public string TitleName { get; private set; }
  83. public ulong TitleId { get; private set; }
  84. public string TitleIdText => TitleId.ToString("x16");
  85. public IntegrityCheckLevel FsIntegrityCheckLevel { get; set; }
  86. public int GlobalAccessLogMode { get; set; }
  87. internal long HidBaseAddress { get; private set; }
  88. internal FileSystemServer FsServer { get; private set; }
  89. public FileSystemClient FsClient { get; private set; }
  90. internal EmulatedGameCard GameCard { get; private set; }
  91. public Horizon(Switch device)
  92. {
  93. ControlData = new BlitStruct<ApplicationControlProperty>(1);
  94. Device = device;
  95. State = new SystemStateMgr();
  96. ResourceLimit = new KResourceLimit(this);
  97. KernelInit.InitializeResourceLimit(ResourceLimit);
  98. MemoryRegions = KernelInit.GetMemoryRegions();
  99. LargeMemoryBlockAllocator = new KMemoryBlockAllocator(MemoryBlockAllocatorSize * 2);
  100. SmallMemoryBlockAllocator = new KMemoryBlockAllocator(MemoryBlockAllocatorSize);
  101. UserSlabHeapPages = new KSlabHeap(
  102. UserSlabHeapBase,
  103. UserSlabHeapItemSize,
  104. UserSlabHeapSize);
  105. CriticalSection = new KCriticalSection(this);
  106. Scheduler = new KScheduler(this);
  107. TimeManager = new KTimeManager();
  108. Synchronization = new KSynchronization(this);
  109. ContextIdManager = new KContextIdManager();
  110. _kipId = InitialKipId;
  111. _processId = InitialProcessId;
  112. Scheduler.StartAutoPreemptionThread();
  113. KernelInitialized = true;
  114. ThreadCounter = new CountdownEvent(1);
  115. Processes = new SortedDictionary<long, KProcess>();
  116. AutoObjectNames = new ConcurrentDictionary<string, KAutoObject>();
  117. // Note: This is not really correct, but with HLE of services, the only memory
  118. // region used that is used is Application, so we can use the other ones for anything.
  119. KMemoryRegionManager region = MemoryRegions[(int)MemoryRegion.NvServices];
  120. ulong hidPa = region.Address;
  121. ulong fontPa = region.Address + HidSize;
  122. ulong iirsPa = region.Address + HidSize + FontSize;
  123. ulong timePa = region.Address + HidSize + FontSize + IirsSize;
  124. HidBaseAddress = (long)(hidPa - DramMemoryMap.DramBase);
  125. KPageList hidPageList = new KPageList();
  126. KPageList fontPageList = new KPageList();
  127. KPageList iirsPageList = new KPageList();
  128. KPageList timePageList = new KPageList();
  129. hidPageList .AddRange(hidPa, HidSize / KMemoryManager.PageSize);
  130. fontPageList.AddRange(fontPa, FontSize / KMemoryManager.PageSize);
  131. iirsPageList.AddRange(iirsPa, IirsSize / KMemoryManager.PageSize);
  132. timePageList.AddRange(timePa, TimeSize / KMemoryManager.PageSize);
  133. HidSharedMem = new KSharedMemory(this, hidPageList, 0, 0, MemoryPermission.Read);
  134. FontSharedMem = new KSharedMemory(this, fontPageList, 0, 0, MemoryPermission.Read);
  135. IirsSharedMem = new KSharedMemory(this, iirsPageList, 0, 0, MemoryPermission.Read);
  136. KSharedMemory timeSharedMemory = new KSharedMemory(this, timePageList, 0, 0, MemoryPermission.Read);
  137. TimeServiceManager.Instance.Initialize(device, this, timeSharedMemory, (long)(timePa - DramMemoryMap.DramBase), TimeSize);
  138. AppletState = new AppletStateMgr(this);
  139. AppletState.SetFocus(true);
  140. Font = new SharedFontManager(device, (long)(fontPa - DramMemoryMap.DramBase));
  141. IUserInterface.InitializePort(this);
  142. VsyncEvent = new KEvent(this);
  143. LoadKeySet();
  144. ContentManager = new ContentManager(device);
  145. // TODO: use set:sys (and get external clock source id from settings)
  146. // TODO: use "time!standard_steady_clock_rtc_update_interval_minutes" and implement a worker thread to be accurate.
  147. UInt128 clockSourceId = new UInt128(Guid.NewGuid().ToByteArray());
  148. IRtcManager.GetExternalRtcValue(out ulong rtcValue);
  149. // We assume the rtc is system time.
  150. TimeSpanType systemTime = TimeSpanType.FromSeconds((long)rtcValue);
  151. // First init the standard steady clock
  152. TimeServiceManager.Instance.SetupStandardSteadyClock(null, clockSourceId, systemTime, TimeSpanType.Zero, TimeSpanType.Zero, false);
  153. TimeServiceManager.Instance.SetupStandardLocalSystemClock(null, new SystemClockContext(), systemTime.ToSeconds());
  154. if (NxSettings.Settings.TryGetValue("time!standard_network_clock_sufficient_accuracy_minutes", out object standardNetworkClockSufficientAccuracyMinutes))
  155. {
  156. TimeSpanType standardNetworkClockSufficientAccuracy = new TimeSpanType((int)standardNetworkClockSufficientAccuracyMinutes * 60000000000);
  157. TimeServiceManager.Instance.SetupStandardNetworkSystemClock(new SystemClockContext(), standardNetworkClockSufficientAccuracy);
  158. }
  159. TimeServiceManager.Instance.SetupStandardUserSystemClock(null, false, SteadyClockTimePoint.GetRandom());
  160. // FIXME: TimeZone shoud be init here but it's actually done in ContentManager
  161. TimeServiceManager.Instance.SetupEphemeralNetworkSystemClock();
  162. LocalFileSystem serverBaseFs = new LocalFileSystem(device.FileSystem.GetBasePath());
  163. DefaultFsServerObjects fsServerObjects = DefaultFsServerObjects.GetDefaultEmulatedCreators(serverBaseFs, KeySet);
  164. GameCard = fsServerObjects.GameCard;
  165. FileSystemServerConfig fsServerConfig = new FileSystemServerConfig
  166. {
  167. FsCreators = fsServerObjects.FsCreators,
  168. DeviceOperator = fsServerObjects.DeviceOperator,
  169. ExternalKeySet = KeySet.ExternalKeySet
  170. };
  171. FsServer = new FileSystemServer(fsServerConfig);
  172. FsClient = FsServer.CreateFileSystemClient();
  173. }
  174. public void LoadCart(string exeFsDir, string romFsFile = null)
  175. {
  176. if (romFsFile != null)
  177. {
  178. Device.FileSystem.LoadRomFs(romFsFile);
  179. }
  180. LocalFileSystem codeFs = new LocalFileSystem(exeFsDir);
  181. LoadExeFs(codeFs, out _);
  182. }
  183. public void LoadXci(string xciFile)
  184. {
  185. FileStream file = new FileStream(xciFile, FileMode.Open, FileAccess.Read);
  186. Xci xci = new Xci(KeySet, file.AsStorage());
  187. (Nca mainNca, Nca patchNca, Nca controlNca) = GetXciGameData(xci);
  188. if (mainNca == null)
  189. {
  190. Logger.PrintError(LogClass.Loader, "Unable to load XCI");
  191. return;
  192. }
  193. ContentManager.LoadEntries();
  194. LoadNca(mainNca, patchNca, controlNca);
  195. }
  196. public void LoadKip(string kipFile)
  197. {
  198. using (FileStream fs = new FileStream(kipFile, FileMode.Open))
  199. {
  200. ProgramLoader.LoadKernelInitalProcess(this, new KernelInitialProcess(fs));
  201. }
  202. }
  203. private (Nca Main, Nca patch, Nca Control) GetXciGameData(Xci xci)
  204. {
  205. if (!xci.HasPartition(XciPartitionType.Secure))
  206. {
  207. throw new InvalidDataException("Could not find XCI secure partition");
  208. }
  209. Nca mainNca = null;
  210. Nca patchNca = null;
  211. Nca controlNca = null;
  212. XciPartition securePartition = xci.OpenPartition(XciPartitionType.Secure);
  213. foreach (DirectoryEntryEx ticketEntry in securePartition.EnumerateEntries("/", "*.tik"))
  214. {
  215. Result result = securePartition.OpenFile(out IFile ticketFile, ticketEntry.FullPath, OpenMode.Read);
  216. if (result.IsSuccess())
  217. {
  218. Ticket ticket = new Ticket(ticketFile.AsStream());
  219. KeySet.ExternalKeySet.Add(new RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(KeySet)));
  220. }
  221. }
  222. foreach (DirectoryEntryEx fileEntry in securePartition.EnumerateEntries("/", "*.nca"))
  223. {
  224. Result result = securePartition.OpenFile(out IFile ncaFile, fileEntry.FullPath, OpenMode.Read);
  225. if (result.IsFailure())
  226. {
  227. continue;
  228. }
  229. Nca nca = new Nca(KeySet, ncaFile.AsStorage());
  230. if (nca.Header.ContentType == NcaContentType.Program)
  231. {
  232. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  233. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  234. {
  235. patchNca = nca;
  236. }
  237. else
  238. {
  239. mainNca = nca;
  240. }
  241. }
  242. else if (nca.Header.ContentType == NcaContentType.Control)
  243. {
  244. controlNca = nca;
  245. }
  246. }
  247. if (mainNca == null)
  248. {
  249. Logger.PrintError(LogClass.Loader, "Could not find an Application NCA in the provided XCI file");
  250. }
  251. if (controlNca != null)
  252. {
  253. ReadControlData(controlNca);
  254. }
  255. else
  256. {
  257. ControlData.ByteSpan.Clear();
  258. }
  259. return (mainNca, patchNca, controlNca);
  260. }
  261. public void ReadControlData(Nca controlNca)
  262. {
  263. IFileSystem controlFs = controlNca.OpenFileSystem(NcaSectionType.Data, FsIntegrityCheckLevel);
  264. Result result = controlFs.OpenFile(out IFile controlFile, "/control.nacp", OpenMode.Read);
  265. if (result.IsSuccess())
  266. {
  267. result = controlFile.Read(out long bytesRead, 0, ControlData.ByteSpan, ReadOption.None);
  268. if (result.IsSuccess() && bytesRead == ControlData.ByteSpan.Length)
  269. {
  270. TitleName = ControlData.Value
  271. .Titles[(int) State.DesiredTitleLanguage].Name.ToString();
  272. if (string.IsNullOrWhiteSpace(TitleName))
  273. {
  274. TitleName = ControlData.Value.Titles.ToArray()
  275. .FirstOrDefault(x => x.Name[0] != 0).Name.ToString();
  276. }
  277. }
  278. }
  279. else
  280. {
  281. ControlData.ByteSpan.Clear();
  282. }
  283. }
  284. public void LoadNca(string ncaFile)
  285. {
  286. FileStream file = new FileStream(ncaFile, FileMode.Open, FileAccess.Read);
  287. Nca nca = new Nca(KeySet, file.AsStorage(false));
  288. LoadNca(nca, null, null);
  289. }
  290. public void LoadNsp(string nspFile)
  291. {
  292. FileStream file = new FileStream(nspFile, FileMode.Open, FileAccess.Read);
  293. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  294. foreach (DirectoryEntryEx ticketEntry in nsp.EnumerateEntries("/", "*.tik"))
  295. {
  296. Result result = nsp.OpenFile(out IFile ticketFile, ticketEntry.FullPath, OpenMode.Read);
  297. if (result.IsSuccess())
  298. {
  299. Ticket ticket = new Ticket(ticketFile.AsStream());
  300. KeySet.ExternalKeySet.Add(new RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(KeySet)));
  301. }
  302. }
  303. Nca mainNca = null;
  304. Nca patchNca = null;
  305. Nca controlNca = null;
  306. foreach (DirectoryEntryEx fileEntry in nsp.EnumerateEntries("/", "*.nca"))
  307. {
  308. nsp.OpenFile(out IFile ncaFile, fileEntry.FullPath, OpenMode.Read).ThrowIfFailure();
  309. Nca nca = new Nca(KeySet, ncaFile.AsStorage());
  310. if (nca.Header.ContentType == NcaContentType.Program)
  311. {
  312. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  313. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  314. {
  315. patchNca = nca;
  316. }
  317. else
  318. {
  319. mainNca = nca;
  320. }
  321. }
  322. else if (nca.Header.ContentType == NcaContentType.Control)
  323. {
  324. controlNca = nca;
  325. }
  326. }
  327. if (mainNca != null)
  328. {
  329. LoadNca(mainNca, patchNca, controlNca);
  330. return;
  331. }
  332. // This is not a normal NSP, it's actually a ExeFS as a NSP
  333. LoadExeFs(nsp, out _);
  334. }
  335. public void LoadNca(Nca mainNca, Nca patchNca, Nca controlNca)
  336. {
  337. if (mainNca.Header.ContentType != NcaContentType.Program)
  338. {
  339. Logger.PrintError(LogClass.Loader, "Selected NCA is not a \"Program\" NCA");
  340. return;
  341. }
  342. IStorage dataStorage = null;
  343. IFileSystem codeFs = null;
  344. if (patchNca == null)
  345. {
  346. if (mainNca.CanOpenSection(NcaSectionType.Data))
  347. {
  348. dataStorage = mainNca.OpenStorage(NcaSectionType.Data, FsIntegrityCheckLevel);
  349. }
  350. if (mainNca.CanOpenSection(NcaSectionType.Code))
  351. {
  352. codeFs = mainNca.OpenFileSystem(NcaSectionType.Code, FsIntegrityCheckLevel);
  353. }
  354. }
  355. else
  356. {
  357. if (patchNca.CanOpenSection(NcaSectionType.Data))
  358. {
  359. dataStorage = mainNca.OpenStorageWithPatch(patchNca, NcaSectionType.Data, FsIntegrityCheckLevel);
  360. }
  361. if (patchNca.CanOpenSection(NcaSectionType.Code))
  362. {
  363. codeFs = mainNca.OpenFileSystemWithPatch(patchNca, NcaSectionType.Code, FsIntegrityCheckLevel);
  364. }
  365. }
  366. if (codeFs == null)
  367. {
  368. Logger.PrintError(LogClass.Loader, "No ExeFS found in NCA");
  369. return;
  370. }
  371. if (dataStorage == null)
  372. {
  373. Logger.PrintWarning(LogClass.Loader, "No RomFS found in NCA");
  374. }
  375. else
  376. {
  377. Device.FileSystem.SetRomFs(dataStorage.AsStream(FileAccess.Read));
  378. }
  379. LoadExeFs(codeFs, out Npdm metaData);
  380. TitleId = metaData.Aci0.TitleId;
  381. if (controlNca != null)
  382. {
  383. ReadControlData(controlNca);
  384. }
  385. else
  386. {
  387. ControlData.ByteSpan.Clear();
  388. }
  389. if (TitleId != 0)
  390. {
  391. EnsureSaveData(new TitleId(TitleId));
  392. }
  393. }
  394. private void LoadExeFs(IFileSystem codeFs, out Npdm metaData)
  395. {
  396. Result result = codeFs.OpenFile(out IFile npdmFile, "/main.npdm", OpenMode.Read);
  397. if (result == ResultFs.PathNotFound)
  398. {
  399. Logger.PrintWarning(LogClass.Loader, "NPDM file not found, using default values!");
  400. metaData = GetDefaultNpdm();
  401. }
  402. else
  403. {
  404. metaData = new Npdm(npdmFile.AsStream());
  405. }
  406. List<IExecutable> staticObjects = new List<IExecutable>();
  407. void LoadNso(string filename)
  408. {
  409. foreach (DirectoryEntryEx file in codeFs.EnumerateEntries("/", $"{filename}*"))
  410. {
  411. if (Path.GetExtension(file.Name) != string.Empty)
  412. {
  413. continue;
  414. }
  415. Logger.PrintInfo(LogClass.Loader, $"Loading {file.Name}...");
  416. codeFs.OpenFile(out IFile nsoFile, file.FullPath, OpenMode.Read).ThrowIfFailure();
  417. NxStaticObject staticObject = new NxStaticObject(nsoFile.AsStream());
  418. staticObjects.Add(staticObject);
  419. }
  420. }
  421. TitleId = metaData.Aci0.TitleId;
  422. LoadNso("rtld");
  423. LoadNso("main");
  424. LoadNso("subsdk");
  425. LoadNso("sdk");
  426. ContentManager.LoadEntries();
  427. ProgramLoader.LoadStaticObjects(this, metaData, staticObjects.ToArray());
  428. }
  429. public void LoadProgram(string filePath)
  430. {
  431. Npdm metaData = GetDefaultNpdm();
  432. bool isNro = Path.GetExtension(filePath).ToLower() == ".nro";
  433. FileStream input = new FileStream(filePath, FileMode.Open);
  434. IExecutable staticObject;
  435. if (isNro)
  436. {
  437. NxRelocatableObject obj = new NxRelocatableObject(input);
  438. staticObject = obj;
  439. // homebrew NRO can actually have some data after the actual NRO
  440. if (input.Length > obj.FileSize)
  441. {
  442. input.Position = obj.FileSize;
  443. BinaryReader reader = new BinaryReader(input);
  444. uint asetMagic = reader.ReadUInt32();
  445. if (asetMagic == 0x54455341)
  446. {
  447. uint asetVersion = reader.ReadUInt32();
  448. if (asetVersion == 0)
  449. {
  450. ulong iconOffset = reader.ReadUInt64();
  451. ulong iconSize = reader.ReadUInt64();
  452. ulong nacpOffset = reader.ReadUInt64();
  453. ulong nacpSize = reader.ReadUInt64();
  454. ulong romfsOffset = reader.ReadUInt64();
  455. ulong romfsSize = reader.ReadUInt64();
  456. if (romfsSize != 0)
  457. {
  458. Device.FileSystem.SetRomFs(new HomebrewRomFsStream(input, obj.FileSize + (long)romfsOffset));
  459. }
  460. if (nacpSize != 0)
  461. {
  462. input.Seek(obj.FileSize + (long)nacpOffset, SeekOrigin.Begin);
  463. reader.Read(ControlData.ByteSpan);
  464. ref ApplicationControlProperty nacp = ref ControlData.Value;
  465. metaData.TitleName = nacp.Titles[(int)State.DesiredTitleLanguage].Name.ToString();
  466. if (string.IsNullOrWhiteSpace(metaData.TitleName))
  467. {
  468. metaData.TitleName = nacp.Titles.ToArray().FirstOrDefault(x => x.Name[0] != 0).Name.ToString();
  469. }
  470. metaData.Aci0.TitleId = nacp.PresenceGroupId;
  471. if (metaData.Aci0.TitleId == 0)
  472. {
  473. metaData.Aci0.TitleId = nacp.SaveDataOwnerId.Value;
  474. }
  475. if (metaData.Aci0.TitleId == 0)
  476. {
  477. metaData.Aci0.TitleId = nacp.AddOnContentBaseId - 0x1000;
  478. }
  479. if (metaData.Aci0.TitleId.ToString("x16") == "fffffffffffff000")
  480. {
  481. metaData.Aci0.TitleId = 0000000000000000;
  482. }
  483. }
  484. }
  485. else
  486. {
  487. Logger.PrintWarning(LogClass.Loader, $"Unsupported ASET header version found \"{asetVersion}\"");
  488. }
  489. }
  490. }
  491. }
  492. else
  493. {
  494. staticObject = new NxStaticObject(input);
  495. }
  496. ContentManager.LoadEntries();
  497. TitleName = metaData.TitleName;
  498. TitleId = metaData.Aci0.TitleId;
  499. ProgramLoader.LoadStaticObjects(this, metaData, new IExecutable[] { staticObject });
  500. }
  501. private Npdm GetDefaultNpdm()
  502. {
  503. Assembly asm = Assembly.GetCallingAssembly();
  504. using (Stream npdmStream = asm.GetManifestResourceStream("Ryujinx.HLE.Homebrew.npdm"))
  505. {
  506. return new Npdm(npdmStream);
  507. }
  508. }
  509. private Result EnsureSaveData(TitleId titleId)
  510. {
  511. Logger.PrintInfo(LogClass.Application, "Ensuring required savedata exists.");
  512. UInt128 lastOpenedUser = State.Account.LastOpenedUser.UserId;
  513. Uid user = new Uid((ulong)lastOpenedUser.Low, (ulong)lastOpenedUser.High);
  514. ref ApplicationControlProperty control = ref ControlData.Value;
  515. if (LibHac.Util.IsEmpty(ControlData.ByteSpan))
  516. {
  517. // If the current application doesn't have a loaded control property, create a dummy one
  518. // and set the savedata sizes so a user savedata will be created.
  519. control = ref new BlitStruct<ApplicationControlProperty>(1).Value;
  520. // The set sizes don't actually matter as long as they're non-zero because we use directory savedata.
  521. control.UserAccountSaveDataSize = 0x4000;
  522. control.UserAccountSaveDataJournalSize = 0x4000;
  523. Logger.PrintWarning(LogClass.Application,
  524. "No control file was found for this game. Using a dummy one instead. This may cause inaccuracies in some games.");
  525. }
  526. Result rc = EnsureApplicationSaveData(FsClient, out _, titleId, ref ControlData.Value, ref user);
  527. if (rc.IsFailure())
  528. {
  529. Logger.PrintError(LogClass.Application, $"Error calling EnsureApplicationSaveData. Result code {rc.ToStringWithName()}");
  530. }
  531. return rc;
  532. }
  533. public void LoadKeySet()
  534. {
  535. string keyFile = null;
  536. string titleKeyFile = null;
  537. string consoleKeyFile = null;
  538. string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
  539. LoadSetAtPath(Path.Combine(home, ".switch"));
  540. LoadSetAtPath(Device.FileSystem.GetSystemPath());
  541. KeySet = ExternalKeyReader.ReadKeyFile(keyFile, titleKeyFile, consoleKeyFile);
  542. void LoadSetAtPath(string basePath)
  543. {
  544. string localKeyFile = Path.Combine(basePath, "prod.keys");
  545. string localTitleKeyFile = Path.Combine(basePath, "title.keys");
  546. string localConsoleKeyFile = Path.Combine(basePath, "console.keys");
  547. if (File.Exists(localKeyFile))
  548. {
  549. keyFile = localKeyFile;
  550. }
  551. if (File.Exists(localTitleKeyFile))
  552. {
  553. titleKeyFile = localTitleKeyFile;
  554. }
  555. if (File.Exists(localConsoleKeyFile))
  556. {
  557. consoleKeyFile = localConsoleKeyFile;
  558. }
  559. }
  560. }
  561. public SystemVersion VerifyFirmwarePackage(string firmwarePackage)
  562. {
  563. return ContentManager.VerifyFirmwarePackage(firmwarePackage);
  564. }
  565. public SystemVersion GetCurrentFirmwareVersion()
  566. {
  567. return ContentManager.GetCurrentFirmwareVersion();
  568. }
  569. public void InstallFirmware(string firmwarePackage)
  570. {
  571. ContentManager.InstallFirmware(firmwarePackage);
  572. }
  573. public void SignalVsync()
  574. {
  575. VsyncEvent.ReadableEvent.Signal();
  576. }
  577. internal long GetThreadUid()
  578. {
  579. return Interlocked.Increment(ref _threadUid) - 1;
  580. }
  581. internal long GetKipId()
  582. {
  583. return Interlocked.Increment(ref _kipId) - 1;
  584. }
  585. internal long GetProcessId()
  586. {
  587. return Interlocked.Increment(ref _processId) - 1;
  588. }
  589. public void EnableMultiCoreScheduling()
  590. {
  591. if (!_hasStarted)
  592. {
  593. Scheduler.MultiCoreScheduling = true;
  594. }
  595. }
  596. public void DisableMultiCoreScheduling()
  597. {
  598. if (!_hasStarted)
  599. {
  600. Scheduler.MultiCoreScheduling = false;
  601. }
  602. }
  603. public void Dispose()
  604. {
  605. Dispose(true);
  606. }
  607. protected virtual void Dispose(bool disposing)
  608. {
  609. if (disposing)
  610. {
  611. KProcess terminationProcess = new KProcess(this);
  612. KThread terminationThread = new KThread(this);
  613. terminationThread.Initialize(0, 0, 0, 3, 0, terminationProcess, ThreadType.Kernel, () =>
  614. {
  615. // Force all threads to exit.
  616. lock (Processes)
  617. {
  618. foreach (KProcess process in Processes.Values)
  619. {
  620. process.Terminate();
  621. }
  622. }
  623. // Exit ourself now!
  624. Scheduler.ExitThread(terminationThread);
  625. Scheduler.GetCurrentThread().Exit();
  626. Scheduler.RemoveThread(terminationThread);
  627. });
  628. terminationThread.Start();
  629. // Signal the vsync event to avoid issues of KThread waiting on it.
  630. if (Device.EnableDeviceVsync)
  631. {
  632. Device.VsyncEvent.Set();
  633. }
  634. // This is needed as the IPC Dummy KThread is also counted in the ThreadCounter.
  635. ThreadCounter.Signal();
  636. // It's only safe to release resources once all threads
  637. // have exited.
  638. ThreadCounter.Signal();
  639. ThreadCounter.Wait();
  640. Scheduler.Dispose();
  641. TimeManager.Dispose();
  642. Device.Unload();
  643. }
  644. }
  645. }
  646. }