Horizon.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  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. }
  175. public void LoadXci(string xciFile)
  176. {
  177. FileStream file = new FileStream(xciFile, FileMode.Open, FileAccess.Read);
  178. Xci xci = new Xci(KeySet, file.AsStorage());
  179. (Nca mainNca, Nca patchNca, Nca controlNca) = GetXciGameData(xci);
  180. if (mainNca == null)
  181. {
  182. Logger.PrintError(LogClass.Loader, "Unable to load XCI");
  183. return;
  184. }
  185. ContentManager.LoadEntries(Device);
  186. LoadNca(mainNca, patchNca, controlNca);
  187. }
  188. public void LoadKip(string kipFile)
  189. {
  190. using (IStorage fs = new LocalStorage(kipFile, FileAccess.Read))
  191. {
  192. ProgramLoader.LoadKernelInitalProcess(this, new KipExecutable(fs));
  193. }
  194. }
  195. private (Nca Main, Nca patch, Nca Control) GetXciGameData(Xci xci)
  196. {
  197. if (!xci.HasPartition(XciPartitionType.Secure))
  198. {
  199. throw new InvalidDataException("Could not find XCI secure partition");
  200. }
  201. Nca mainNca = null;
  202. Nca patchNca = null;
  203. Nca controlNca = null;
  204. XciPartition securePartition = xci.OpenPartition(XciPartitionType.Secure);
  205. foreach (DirectoryEntryEx ticketEntry in securePartition.EnumerateEntries("/", "*.tik"))
  206. {
  207. Result result = securePartition.OpenFile(out IFile ticketFile, ticketEntry.FullPath.ToU8Span(), OpenMode.Read);
  208. if (result.IsSuccess())
  209. {
  210. Ticket ticket = new Ticket(ticketFile.AsStream());
  211. KeySet.ExternalKeySet.Add(new RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(KeySet)));
  212. }
  213. }
  214. foreach (DirectoryEntryEx fileEntry in securePartition.EnumerateEntries("/", "*.nca"))
  215. {
  216. Result result = securePartition.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read);
  217. if (result.IsFailure())
  218. {
  219. continue;
  220. }
  221. Nca nca = new Nca(KeySet, ncaFile.AsStorage());
  222. if (nca.Header.ContentType == NcaContentType.Program)
  223. {
  224. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  225. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  226. {
  227. patchNca = nca;
  228. }
  229. else
  230. {
  231. mainNca = nca;
  232. }
  233. }
  234. else if (nca.Header.ContentType == NcaContentType.Control)
  235. {
  236. controlNca = nca;
  237. }
  238. }
  239. if (mainNca == null)
  240. {
  241. Logger.PrintError(LogClass.Loader, "Could not find an Application NCA in the provided XCI file");
  242. }
  243. if (controlNca != null)
  244. {
  245. ReadControlData(controlNca);
  246. }
  247. else
  248. {
  249. ControlData.ByteSpan.Clear();
  250. }
  251. return (mainNca, patchNca, controlNca);
  252. }
  253. public void ReadControlData(Nca controlNca)
  254. {
  255. IFileSystem controlFs = controlNca.OpenFileSystem(NcaSectionType.Data, FsIntegrityCheckLevel);
  256. Result result = controlFs.OpenFile(out IFile controlFile, "/control.nacp".ToU8Span(), OpenMode.Read);
  257. if (result.IsSuccess())
  258. {
  259. result = controlFile.Read(out long bytesRead, 0, ControlData.ByteSpan, ReadOption.None);
  260. if (result.IsSuccess() && bytesRead == ControlData.ByteSpan.Length)
  261. {
  262. TitleName = ControlData.Value
  263. .Titles[(int) State.DesiredTitleLanguage].Name.ToString();
  264. if (string.IsNullOrWhiteSpace(TitleName))
  265. {
  266. TitleName = ControlData.Value.Titles.ToArray()
  267. .FirstOrDefault(x => x.Name[0] != 0).Name.ToString();
  268. }
  269. TitleVersionString = ControlData.Value.DisplayVersion.ToString();
  270. }
  271. }
  272. else
  273. {
  274. ControlData.ByteSpan.Clear();
  275. }
  276. }
  277. public void LoadNca(string ncaFile)
  278. {
  279. FileStream file = new FileStream(ncaFile, FileMode.Open, FileAccess.Read);
  280. Nca nca = new Nca(KeySet, file.AsStorage(false));
  281. LoadNca(nca, null, null);
  282. }
  283. public void LoadNsp(string nspFile)
  284. {
  285. FileStream file = new FileStream(nspFile, FileMode.Open, FileAccess.Read);
  286. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  287. foreach (DirectoryEntryEx ticketEntry in nsp.EnumerateEntries("/", "*.tik"))
  288. {
  289. Result result = nsp.OpenFile(out IFile ticketFile, ticketEntry.FullPath.ToU8Span(), OpenMode.Read);
  290. if (result.IsSuccess())
  291. {
  292. Ticket ticket = new Ticket(ticketFile.AsStream());
  293. KeySet.ExternalKeySet.Add(new RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(KeySet)));
  294. }
  295. }
  296. Nca mainNca = null;
  297. Nca patchNca = null;
  298. Nca controlNca = null;
  299. foreach (DirectoryEntryEx fileEntry in nsp.EnumerateEntries("/", "*.nca"))
  300. {
  301. nsp.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  302. Nca nca = new Nca(KeySet, ncaFile.AsStorage());
  303. if (nca.Header.ContentType == NcaContentType.Program)
  304. {
  305. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  306. if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  307. {
  308. patchNca = nca;
  309. }
  310. else
  311. {
  312. mainNca = nca;
  313. }
  314. }
  315. else if (nca.Header.ContentType == NcaContentType.Control)
  316. {
  317. controlNca = nca;
  318. }
  319. }
  320. if (mainNca != null)
  321. {
  322. LoadNca(mainNca, patchNca, controlNca);
  323. return;
  324. }
  325. // This is not a normal NSP, it's actually a ExeFS as a NSP
  326. LoadExeFs(nsp, out _);
  327. }
  328. public void LoadNca(Nca mainNca, Nca patchNca, Nca controlNca)
  329. {
  330. if (mainNca.Header.ContentType != NcaContentType.Program)
  331. {
  332. Logger.PrintError(LogClass.Loader, "Selected NCA is not a \"Program\" NCA");
  333. return;
  334. }
  335. IStorage dataStorage = null;
  336. IFileSystem codeFs = null;
  337. if (File.Exists(Path.Combine(Device.FileSystem.GetBasePath(), "games", mainNca.Header.TitleId.ToString("x16"), "updates.json")))
  338. {
  339. using (Stream stream = File.OpenRead(Path.Combine(Device.FileSystem.GetBasePath(), "games", mainNca.Header.TitleId.ToString("x16"), "updates.json")))
  340. {
  341. IJsonFormatterResolver resolver = CompositeResolver.Create(StandardResolver.AllowPrivateSnakeCase);
  342. string updatePath = JsonSerializer.Deserialize<TitleUpdateMetadata>(stream, resolver).Selected;
  343. if (File.Exists(updatePath))
  344. {
  345. FileStream file = new FileStream(updatePath, FileMode.Open, FileAccess.Read);
  346. PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());
  347. foreach (DirectoryEntryEx ticketEntry in nsp.EnumerateEntries("/", "*.tik"))
  348. {
  349. Result result = nsp.OpenFile(out IFile ticketFile, ticketEntry.FullPath.ToU8Span(), OpenMode.Read);
  350. if (result.IsSuccess())
  351. {
  352. Ticket ticket = new Ticket(ticketFile.AsStream());
  353. KeySet.ExternalKeySet.Add(new RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(KeySet)));
  354. }
  355. }
  356. foreach (DirectoryEntryEx fileEntry in nsp.EnumerateEntries("/", "*.nca"))
  357. {
  358. nsp.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  359. Nca nca = new Nca(KeySet, ncaFile.AsStorage());
  360. if ($"{nca.Header.TitleId.ToString("x16")[..^3]}000" != mainNca.Header.TitleId.ToString("x16"))
  361. {
  362. break;
  363. }
  364. if (nca.Header.ContentType == NcaContentType.Program)
  365. {
  366. patchNca = nca;
  367. }
  368. else if (nca.Header.ContentType == NcaContentType.Control)
  369. {
  370. controlNca = nca;
  371. }
  372. }
  373. }
  374. }
  375. }
  376. if (patchNca == null)
  377. {
  378. if (mainNca.CanOpenSection(NcaSectionType.Data))
  379. {
  380. dataStorage = mainNca.OpenStorage(NcaSectionType.Data, FsIntegrityCheckLevel);
  381. }
  382. if (mainNca.CanOpenSection(NcaSectionType.Code))
  383. {
  384. codeFs = mainNca.OpenFileSystem(NcaSectionType.Code, FsIntegrityCheckLevel);
  385. }
  386. }
  387. else
  388. {
  389. if (patchNca.CanOpenSection(NcaSectionType.Data))
  390. {
  391. dataStorage = mainNca.OpenStorageWithPatch(patchNca, NcaSectionType.Data, FsIntegrityCheckLevel);
  392. }
  393. if (patchNca.CanOpenSection(NcaSectionType.Code))
  394. {
  395. codeFs = mainNca.OpenFileSystemWithPatch(patchNca, NcaSectionType.Code, FsIntegrityCheckLevel);
  396. }
  397. }
  398. if (codeFs == null)
  399. {
  400. Logger.PrintError(LogClass.Loader, "No ExeFS found in NCA");
  401. return;
  402. }
  403. if (dataStorage == null)
  404. {
  405. Logger.PrintWarning(LogClass.Loader, "No RomFS found in NCA");
  406. }
  407. else
  408. {
  409. Device.FileSystem.SetRomFs(dataStorage.AsStream(FileAccess.Read));
  410. }
  411. LoadExeFs(codeFs, out Npdm metaData);
  412. TitleId = metaData.Aci0.TitleId;
  413. TitleIs64Bit = metaData.Is64Bit;
  414. if (controlNca != null)
  415. {
  416. ReadControlData(controlNca);
  417. }
  418. else
  419. {
  420. ControlData.ByteSpan.Clear();
  421. }
  422. if (TitleId != 0)
  423. {
  424. EnsureSaveData(new TitleId(TitleId));
  425. }
  426. Logger.PrintInfo(LogClass.Loader, $"Application Loaded: {TitleName} v{TitleVersionString} [{TitleIdText}] [{(TitleIs64Bit ? "64-bit" : "32-bit")}]");
  427. }
  428. private void LoadExeFs(IFileSystem codeFs, out Npdm metaData)
  429. {
  430. Result result = codeFs.OpenFile(out IFile npdmFile, "/main.npdm".ToU8Span(), OpenMode.Read);
  431. if (ResultFs.PathNotFound.Includes(result))
  432. {
  433. Logger.PrintWarning(LogClass.Loader, "NPDM file not found, using default values!");
  434. metaData = GetDefaultNpdm();
  435. }
  436. else
  437. {
  438. metaData = new Npdm(npdmFile.AsStream());
  439. }
  440. List<IExecutable> staticObjects = new List<IExecutable>();
  441. void LoadNso(string filename)
  442. {
  443. foreach (DirectoryEntryEx file in codeFs.EnumerateEntries("/", $"{filename}*"))
  444. {
  445. if (Path.GetExtension(file.Name) != string.Empty)
  446. {
  447. continue;
  448. }
  449. Logger.PrintInfo(LogClass.Loader, $"Loading {file.Name}...");
  450. codeFs.OpenFile(out IFile nsoFile, file.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  451. NsoExecutable staticObject = new NsoExecutable(nsoFile.AsStorage());
  452. staticObjects.Add(staticObject);
  453. }
  454. }
  455. TitleId = metaData.Aci0.TitleId;
  456. TitleIs64Bit = metaData.Is64Bit;
  457. LoadNso("rtld");
  458. LoadNso("main");
  459. LoadNso("subsdk");
  460. LoadNso("sdk");
  461. ContentManager.LoadEntries(Device);
  462. ProgramLoader.LoadStaticObjects(this, metaData, staticObjects.ToArray());
  463. }
  464. public void LoadProgram(string filePath)
  465. {
  466. Npdm metaData = GetDefaultNpdm();
  467. bool isNro = Path.GetExtension(filePath).ToLower() == ".nro";
  468. IExecutable staticObject;
  469. if (isNro)
  470. {
  471. FileStream input = new FileStream(filePath, FileMode.Open);
  472. NroExecutable obj = new NroExecutable(input);
  473. staticObject = obj;
  474. // homebrew NRO can actually have some data after the actual NRO
  475. if (input.Length > obj.FileSize)
  476. {
  477. input.Position = obj.FileSize;
  478. BinaryReader reader = new BinaryReader(input);
  479. uint asetMagic = reader.ReadUInt32();
  480. if (asetMagic == 0x54455341)
  481. {
  482. uint asetVersion = reader.ReadUInt32();
  483. if (asetVersion == 0)
  484. {
  485. ulong iconOffset = reader.ReadUInt64();
  486. ulong iconSize = reader.ReadUInt64();
  487. ulong nacpOffset = reader.ReadUInt64();
  488. ulong nacpSize = reader.ReadUInt64();
  489. ulong romfsOffset = reader.ReadUInt64();
  490. ulong romfsSize = reader.ReadUInt64();
  491. if (romfsSize != 0)
  492. {
  493. Device.FileSystem.SetRomFs(new HomebrewRomFsStream(input, obj.FileSize + (long)romfsOffset));
  494. }
  495. if (nacpSize != 0)
  496. {
  497. input.Seek(obj.FileSize + (long)nacpOffset, SeekOrigin.Begin);
  498. reader.Read(ControlData.ByteSpan);
  499. ref ApplicationControlProperty nacp = ref ControlData.Value;
  500. metaData.TitleName = nacp.Titles[(int)State.DesiredTitleLanguage].Name.ToString();
  501. if (string.IsNullOrWhiteSpace(metaData.TitleName))
  502. {
  503. metaData.TitleName = nacp.Titles.ToArray().FirstOrDefault(x => x.Name[0] != 0).Name.ToString();
  504. }
  505. if (nacp.PresenceGroupId != 0)
  506. {
  507. metaData.Aci0.TitleId = nacp.PresenceGroupId;
  508. }
  509. else if (nacp.SaveDataOwnerId.Value != 0)
  510. {
  511. metaData.Aci0.TitleId = nacp.SaveDataOwnerId.Value;
  512. }
  513. else if (nacp.AddOnContentBaseId != 0)
  514. {
  515. metaData.Aci0.TitleId = nacp.AddOnContentBaseId - 0x1000;
  516. }
  517. else
  518. {
  519. metaData.Aci0.TitleId = 0000000000000000;
  520. }
  521. }
  522. }
  523. else
  524. {
  525. Logger.PrintWarning(LogClass.Loader, $"Unsupported ASET header version found \"{asetVersion}\"");
  526. }
  527. }
  528. }
  529. }
  530. else
  531. {
  532. staticObject = new NsoExecutable(new LocalStorage(filePath, FileAccess.Read));
  533. }
  534. ContentManager.LoadEntries(Device);
  535. TitleName = metaData.TitleName;
  536. TitleId = metaData.Aci0.TitleId;
  537. TitleIs64Bit = metaData.Is64Bit;
  538. ProgramLoader.LoadStaticObjects(this, metaData, new IExecutable[] { staticObject });
  539. }
  540. private Npdm GetDefaultNpdm()
  541. {
  542. Assembly asm = Assembly.GetCallingAssembly();
  543. using (Stream npdmStream = asm.GetManifestResourceStream("Ryujinx.HLE.Homebrew.npdm"))
  544. {
  545. return new Npdm(npdmStream);
  546. }
  547. }
  548. private Result EnsureSaveData(TitleId titleId)
  549. {
  550. Logger.PrintInfo(LogClass.Application, "Ensuring required savedata exists.");
  551. Uid user = State.Account.LastOpenedUser.UserId.ToLibHacUid();
  552. ref ApplicationControlProperty control = ref ControlData.Value;
  553. if (LibHac.Util.IsEmpty(ControlData.ByteSpan))
  554. {
  555. // If the current application doesn't have a loaded control property, create a dummy one
  556. // and set the savedata sizes so a user savedata will be created.
  557. control = ref new BlitStruct<ApplicationControlProperty>(1).Value;
  558. // The set sizes don't actually matter as long as they're non-zero because we use directory savedata.
  559. control.UserAccountSaveDataSize = 0x4000;
  560. control.UserAccountSaveDataJournalSize = 0x4000;
  561. Logger.PrintWarning(LogClass.Application,
  562. "No control file was found for this game. Using a dummy one instead. This may cause inaccuracies in some games.");
  563. }
  564. FileSystemClient fs = Device.FileSystem.FsClient;
  565. Result rc = fs.EnsureApplicationCacheStorage(out _, titleId, ref ControlData.Value);
  566. if (rc.IsFailure())
  567. {
  568. Logger.PrintError(LogClass.Application, $"Error calling EnsureApplicationCacheStorage. Result code {rc.ToStringWithName()}");
  569. }
  570. rc = EnsureApplicationSaveData(fs, out _, titleId, ref ControlData.Value, ref user);
  571. if (rc.IsFailure())
  572. {
  573. Logger.PrintError(LogClass.Application, $"Error calling EnsureApplicationSaveData. Result code {rc.ToStringWithName()}");
  574. }
  575. return rc;
  576. }
  577. public void SignalVsync()
  578. {
  579. VsyncEvent.ReadableEvent.Signal();
  580. }
  581. internal long GetThreadUid()
  582. {
  583. return Interlocked.Increment(ref _threadUid) - 1;
  584. }
  585. internal long GetKipId()
  586. {
  587. return Interlocked.Increment(ref _kipId) - 1;
  588. }
  589. internal long GetProcessId()
  590. {
  591. return Interlocked.Increment(ref _processId) - 1;
  592. }
  593. public void EnableMultiCoreScheduling()
  594. {
  595. if (!_hasStarted)
  596. {
  597. Scheduler.MultiCoreScheduling = true;
  598. }
  599. }
  600. public void DisableMultiCoreScheduling()
  601. {
  602. if (!_hasStarted)
  603. {
  604. Scheduler.MultiCoreScheduling = false;
  605. }
  606. }
  607. public void Dispose()
  608. {
  609. Dispose(true);
  610. }
  611. protected virtual void Dispose(bool disposing)
  612. {
  613. if (!_isDisposed && disposing)
  614. {
  615. _isDisposed = true;
  616. KProcess terminationProcess = new KProcess(this);
  617. KThread terminationThread = new KThread(this);
  618. terminationThread.Initialize(0, 0, 0, 3, 0, terminationProcess, ThreadType.Kernel, () =>
  619. {
  620. // Force all threads to exit.
  621. lock (Processes)
  622. {
  623. foreach (KProcess process in Processes.Values)
  624. {
  625. process.Terminate();
  626. }
  627. }
  628. // Exit ourself now!
  629. Scheduler.ExitThread(terminationThread);
  630. Scheduler.GetCurrentThread().Exit();
  631. Scheduler.RemoveThread(terminationThread);
  632. });
  633. terminationThread.Start();
  634. // Signal the vsync event to avoid issues of KThread waiting on it.
  635. if (Device.EnableDeviceVsync)
  636. {
  637. Device.VsyncEvent.Set();
  638. }
  639. // This is needed as the IPC Dummy KThread is also counted in the ThreadCounter.
  640. ThreadCounter.Signal();
  641. // It's only safe to release resources once all threads
  642. // have exited.
  643. ThreadCounter.Signal();
  644. ThreadCounter.Wait();
  645. Scheduler.Dispose();
  646. TimeManager.Dispose();
  647. Device.Unload();
  648. }
  649. }
  650. }
  651. }