Horizon.cs 32 KB

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