Horizon.cs 31 KB

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