KProcess.cs 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  1. using ChocolArm64;
  2. using ChocolArm64.Events;
  3. using ChocolArm64.Memory;
  4. using Ryujinx.Common;
  5. using Ryujinx.Common.Logging;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Threading;
  10. namespace Ryujinx.HLE.HOS.Kernel
  11. {
  12. class KProcess : KSynchronizationObject
  13. {
  14. public const int KernelVersionMajor = 10;
  15. public const int KernelVersionMinor = 4;
  16. public const int KernelVersionRevision = 0;
  17. public const int KernelVersionPacked =
  18. (KernelVersionMajor << 19) |
  19. (KernelVersionMinor << 15) |
  20. (KernelVersionRevision << 0);
  21. public KMemoryManager MemoryManager { get; private set; }
  22. private SortedDictionary<ulong, KTlsPageInfo> _fullTlsPages;
  23. private SortedDictionary<ulong, KTlsPageInfo> _freeTlsPages;
  24. public int DefaultCpuCore { get; private set; }
  25. public bool Debug { get; private set; }
  26. public KResourceLimit ResourceLimit { get; private set; }
  27. public ulong PersonalMmHeapPagesCount { get; private set; }
  28. private ProcessState _state;
  29. private object _processLock;
  30. private object _threadingLock;
  31. public KAddressArbiter AddressArbiter { get; private set; }
  32. public long[] RandomEntropy { get; private set; }
  33. private bool _signaled;
  34. private bool _useSystemMemBlocks;
  35. public string Name { get; private set; }
  36. private int _threadCount;
  37. public int MmuFlags { get; private set; }
  38. private MemoryRegion _memRegion;
  39. public KProcessCapabilities Capabilities { get; private set; }
  40. public long TitleId { get; private set; }
  41. public long Pid { get; private set; }
  42. private long _creationTimestamp;
  43. private ulong _entrypoint;
  44. private ulong _imageSize;
  45. private ulong _mainThreadStackSize;
  46. private ulong _memoryUsageCapacity;
  47. private int _category;
  48. public KHandleTable HandleTable { get; private set; }
  49. public ulong UserExceptionContextAddress { get; private set; }
  50. private LinkedList<KThread> _threads;
  51. public bool IsPaused { get; private set; }
  52. public Translator Translator { get; private set; }
  53. public MemoryManager CpuMemory { get; private set; }
  54. private SvcHandler _svcHandler;
  55. public HleProcessDebugger Debugger { get; private set; }
  56. public KProcess(Horizon system) : base(system)
  57. {
  58. _processLock = new object();
  59. _threadingLock = new object();
  60. CpuMemory = new MemoryManager(system.Device.Memory.RamPointer);
  61. CpuMemory.InvalidAccess += InvalidAccessHandler;
  62. AddressArbiter = new KAddressArbiter(system);
  63. MemoryManager = new KMemoryManager(system, CpuMemory);
  64. _fullTlsPages = new SortedDictionary<ulong, KTlsPageInfo>();
  65. _freeTlsPages = new SortedDictionary<ulong, KTlsPageInfo>();
  66. Capabilities = new KProcessCapabilities();
  67. RandomEntropy = new long[KScheduler.CpuCoresCount];
  68. _threads = new LinkedList<KThread>();
  69. Translator = new Translator();
  70. Translator.CpuTrace += CpuTraceHandler;
  71. _svcHandler = new SvcHandler(system.Device, this);
  72. Debugger = new HleProcessDebugger(this);
  73. }
  74. public KernelResult InitializeKip(
  75. ProcessCreationInfo creationInfo,
  76. int[] caps,
  77. KPageList pageList,
  78. KResourceLimit resourceLimit,
  79. MemoryRegion memRegion)
  80. {
  81. ResourceLimit = resourceLimit;
  82. _memRegion = memRegion;
  83. AddressSpaceType addrSpaceType = (AddressSpaceType)((creationInfo.MmuFlags >> 1) & 7);
  84. bool aslrEnabled = ((creationInfo.MmuFlags >> 5) & 1) != 0;
  85. ulong codeAddress = creationInfo.CodeAddress;
  86. ulong codeSize = (ulong)creationInfo.CodePagesCount * KMemoryManager.PageSize;
  87. KMemoryBlockAllocator memoryBlockAllocator = (MmuFlags & 0x40) != 0
  88. ? System.LargeMemoryBlockAllocator
  89. : System.SmallMemoryBlockAllocator;
  90. KernelResult result = MemoryManager.InitializeForProcess(
  91. addrSpaceType,
  92. aslrEnabled,
  93. !aslrEnabled,
  94. memRegion,
  95. codeAddress,
  96. codeSize,
  97. memoryBlockAllocator);
  98. if (result != KernelResult.Success)
  99. {
  100. return result;
  101. }
  102. if (!ValidateCodeAddressAndSize(codeAddress, codeSize))
  103. {
  104. return KernelResult.InvalidMemRange;
  105. }
  106. result = MemoryManager.MapPages(
  107. codeAddress,
  108. pageList,
  109. MemoryState.CodeStatic,
  110. MemoryPermission.None);
  111. if (result != KernelResult.Success)
  112. {
  113. return result;
  114. }
  115. result = Capabilities.InitializeForKernel(caps, MemoryManager);
  116. if (result != KernelResult.Success)
  117. {
  118. return result;
  119. }
  120. Pid = System.GetKipId();
  121. if (Pid == 0 || (ulong)Pid >= Horizon.InitialProcessId)
  122. {
  123. throw new InvalidOperationException($"Invalid KIP Id {Pid}.");
  124. }
  125. result = ParseProcessInfo(creationInfo);
  126. return result;
  127. }
  128. public KernelResult Initialize(
  129. ProcessCreationInfo creationInfo,
  130. int[] caps,
  131. KResourceLimit resourceLimit,
  132. MemoryRegion memRegion)
  133. {
  134. ResourceLimit = resourceLimit;
  135. _memRegion = memRegion;
  136. ulong personalMmHeapSize = GetPersonalMmHeapSize((ulong)creationInfo.PersonalMmHeapPagesCount, memRegion);
  137. ulong codePagesCount = (ulong)creationInfo.CodePagesCount;
  138. ulong neededSizeForProcess = personalMmHeapSize + codePagesCount * KMemoryManager.PageSize;
  139. if (neededSizeForProcess != 0 && resourceLimit != null)
  140. {
  141. if (!resourceLimit.Reserve(LimitableResource.Memory, neededSizeForProcess))
  142. {
  143. return KernelResult.ResLimitExceeded;
  144. }
  145. }
  146. void CleanUpForError()
  147. {
  148. if (neededSizeForProcess != 0 && resourceLimit != null)
  149. {
  150. resourceLimit.Release(LimitableResource.Memory, neededSizeForProcess);
  151. }
  152. }
  153. PersonalMmHeapPagesCount = (ulong)creationInfo.PersonalMmHeapPagesCount;
  154. KMemoryBlockAllocator memoryBlockAllocator;
  155. if (PersonalMmHeapPagesCount != 0)
  156. {
  157. memoryBlockAllocator = new KMemoryBlockAllocator(PersonalMmHeapPagesCount * KMemoryManager.PageSize);
  158. }
  159. else
  160. {
  161. memoryBlockAllocator = (MmuFlags & 0x40) != 0
  162. ? System.LargeMemoryBlockAllocator
  163. : System.SmallMemoryBlockAllocator;
  164. }
  165. AddressSpaceType addrSpaceType = (AddressSpaceType)((creationInfo.MmuFlags >> 1) & 7);
  166. bool aslrEnabled = ((creationInfo.MmuFlags >> 5) & 1) != 0;
  167. ulong codeAddress = creationInfo.CodeAddress;
  168. ulong codeSize = codePagesCount * KMemoryManager.PageSize;
  169. KernelResult result = MemoryManager.InitializeForProcess(
  170. addrSpaceType,
  171. aslrEnabled,
  172. !aslrEnabled,
  173. memRegion,
  174. codeAddress,
  175. codeSize,
  176. memoryBlockAllocator);
  177. if (result != KernelResult.Success)
  178. {
  179. CleanUpForError();
  180. return result;
  181. }
  182. if (!ValidateCodeAddressAndSize(codeAddress, codeSize))
  183. {
  184. CleanUpForError();
  185. return KernelResult.InvalidMemRange;
  186. }
  187. result = MemoryManager.MapNewProcessCode(
  188. codeAddress,
  189. codePagesCount,
  190. MemoryState.CodeStatic,
  191. MemoryPermission.None);
  192. if (result != KernelResult.Success)
  193. {
  194. CleanUpForError();
  195. return result;
  196. }
  197. result = Capabilities.InitializeForUser(caps, MemoryManager);
  198. if (result != KernelResult.Success)
  199. {
  200. CleanUpForError();
  201. return result;
  202. }
  203. Pid = System.GetProcessId();
  204. if (Pid == -1 || (ulong)Pid < Horizon.InitialProcessId)
  205. {
  206. throw new InvalidOperationException($"Invalid Process Id {Pid}.");
  207. }
  208. result = ParseProcessInfo(creationInfo);
  209. if (result != KernelResult.Success)
  210. {
  211. CleanUpForError();
  212. }
  213. return result;
  214. }
  215. private bool ValidateCodeAddressAndSize(ulong address, ulong size)
  216. {
  217. ulong codeRegionStart;
  218. ulong codeRegionSize;
  219. switch (MemoryManager.AddrSpaceWidth)
  220. {
  221. case 32:
  222. codeRegionStart = 0x200000;
  223. codeRegionSize = 0x3fe00000;
  224. break;
  225. case 36:
  226. codeRegionStart = 0x8000000;
  227. codeRegionSize = 0x78000000;
  228. break;
  229. case 39:
  230. codeRegionStart = 0x8000000;
  231. codeRegionSize = 0x7ff8000000;
  232. break;
  233. default: throw new InvalidOperationException("Invalid address space width on memory manager.");
  234. }
  235. ulong endAddr = address + size;
  236. ulong codeRegionEnd = codeRegionStart + codeRegionSize;
  237. if (endAddr <= address ||
  238. endAddr - 1 > codeRegionEnd - 1)
  239. {
  240. return false;
  241. }
  242. if (MemoryManager.InsideHeapRegion (address, size) ||
  243. MemoryManager.InsideAliasRegion(address, size))
  244. {
  245. return false;
  246. }
  247. return true;
  248. }
  249. private KernelResult ParseProcessInfo(ProcessCreationInfo creationInfo)
  250. {
  251. //Ensure that the current kernel version is equal or above to the minimum required.
  252. uint requiredKernelVersionMajor = (uint)Capabilities.KernelReleaseVersion >> 19;
  253. uint requiredKernelVersionMinor = ((uint)Capabilities.KernelReleaseVersion >> 15) & 0xf;
  254. if (System.EnableVersionChecks)
  255. {
  256. if (requiredKernelVersionMajor > KernelVersionMajor)
  257. {
  258. return KernelResult.InvalidCombination;
  259. }
  260. if (requiredKernelVersionMajor != KernelVersionMajor && requiredKernelVersionMajor < 3)
  261. {
  262. return KernelResult.InvalidCombination;
  263. }
  264. if (requiredKernelVersionMinor > KernelVersionMinor)
  265. {
  266. return KernelResult.InvalidCombination;
  267. }
  268. }
  269. KernelResult result = AllocateThreadLocalStorage(out ulong userExceptionContextAddress);
  270. if (result != KernelResult.Success)
  271. {
  272. return result;
  273. }
  274. UserExceptionContextAddress = userExceptionContextAddress;
  275. MemoryHelper.FillWithZeros(CpuMemory, (long)userExceptionContextAddress, KTlsPageInfo.TlsEntrySize);
  276. Name = creationInfo.Name;
  277. _state = ProcessState.Created;
  278. _creationTimestamp = PerformanceCounter.ElapsedMilliseconds;
  279. MmuFlags = creationInfo.MmuFlags;
  280. _category = creationInfo.Category;
  281. TitleId = creationInfo.TitleId;
  282. _entrypoint = creationInfo.CodeAddress;
  283. _imageSize = (ulong)creationInfo.CodePagesCount * KMemoryManager.PageSize;
  284. _useSystemMemBlocks = ((MmuFlags >> 6) & 1) != 0;
  285. switch ((AddressSpaceType)((MmuFlags >> 1) & 7))
  286. {
  287. case AddressSpaceType.Addr32Bits:
  288. case AddressSpaceType.Addr36Bits:
  289. case AddressSpaceType.Addr39Bits:
  290. _memoryUsageCapacity = MemoryManager.HeapRegionEnd -
  291. MemoryManager.HeapRegionStart;
  292. break;
  293. case AddressSpaceType.Addr32BitsNoMap:
  294. _memoryUsageCapacity = MemoryManager.HeapRegionEnd -
  295. MemoryManager.HeapRegionStart +
  296. MemoryManager.AliasRegionEnd -
  297. MemoryManager.AliasRegionStart;
  298. break;
  299. default: throw new InvalidOperationException($"Invalid MMU flags value 0x{MmuFlags:x2}.");
  300. }
  301. GenerateRandomEntropy();
  302. return KernelResult.Success;
  303. }
  304. public KernelResult AllocateThreadLocalStorage(out ulong address)
  305. {
  306. System.CriticalSection.Enter();
  307. KernelResult result;
  308. if (_freeTlsPages.Count > 0)
  309. {
  310. //If we have free TLS pages available, just use the first one.
  311. KTlsPageInfo pageInfo = _freeTlsPages.Values.First();
  312. if (!pageInfo.TryGetFreePage(out address))
  313. {
  314. throw new InvalidOperationException("Unexpected failure getting free TLS page!");
  315. }
  316. if (pageInfo.IsFull())
  317. {
  318. _freeTlsPages.Remove(pageInfo.PageAddr);
  319. _fullTlsPages.Add(pageInfo.PageAddr, pageInfo);
  320. }
  321. result = KernelResult.Success;
  322. }
  323. else
  324. {
  325. //Otherwise, we need to create a new one.
  326. result = AllocateTlsPage(out KTlsPageInfo pageInfo);
  327. if (result == KernelResult.Success)
  328. {
  329. if (!pageInfo.TryGetFreePage(out address))
  330. {
  331. throw new InvalidOperationException("Unexpected failure getting free TLS page!");
  332. }
  333. _freeTlsPages.Add(pageInfo.PageAddr, pageInfo);
  334. }
  335. else
  336. {
  337. address = 0;
  338. }
  339. }
  340. System.CriticalSection.Leave();
  341. return result;
  342. }
  343. private KernelResult AllocateTlsPage(out KTlsPageInfo pageInfo)
  344. {
  345. pageInfo = default(KTlsPageInfo);
  346. if (!System.UserSlabHeapPages.TryGetItem(out ulong tlsPagePa))
  347. {
  348. return KernelResult.OutOfMemory;
  349. }
  350. ulong regionStart = MemoryManager.TlsIoRegionStart;
  351. ulong regionSize = MemoryManager.TlsIoRegionEnd - regionStart;
  352. ulong regionPagesCount = regionSize / KMemoryManager.PageSize;
  353. KernelResult result = MemoryManager.AllocateOrMapPa(
  354. 1,
  355. KMemoryManager.PageSize,
  356. tlsPagePa,
  357. true,
  358. regionStart,
  359. regionPagesCount,
  360. MemoryState.ThreadLocal,
  361. MemoryPermission.ReadAndWrite,
  362. out ulong tlsPageVa);
  363. if (result != KernelResult.Success)
  364. {
  365. System.UserSlabHeapPages.Free(tlsPagePa);
  366. }
  367. else
  368. {
  369. pageInfo = new KTlsPageInfo(tlsPageVa);
  370. MemoryHelper.FillWithZeros(CpuMemory, (long)tlsPageVa, KMemoryManager.PageSize);
  371. }
  372. return result;
  373. }
  374. public KernelResult FreeThreadLocalStorage(ulong tlsSlotAddr)
  375. {
  376. ulong tlsPageAddr = BitUtils.AlignDown(tlsSlotAddr, KMemoryManager.PageSize);
  377. System.CriticalSection.Enter();
  378. KernelResult result = KernelResult.Success;
  379. KTlsPageInfo pageInfo = null;
  380. if (_fullTlsPages.TryGetValue(tlsPageAddr, out pageInfo))
  381. {
  382. //TLS page was full, free slot and move to free pages tree.
  383. _fullTlsPages.Remove(tlsPageAddr);
  384. _freeTlsPages.Add(tlsPageAddr, pageInfo);
  385. }
  386. else if (!_freeTlsPages.TryGetValue(tlsPageAddr, out pageInfo))
  387. {
  388. result = KernelResult.InvalidAddress;
  389. }
  390. if (pageInfo != null)
  391. {
  392. pageInfo.FreeTlsSlot(tlsSlotAddr);
  393. if (pageInfo.IsEmpty())
  394. {
  395. //TLS page is now empty, we should ensure it is removed
  396. //from all trees, and free the memory it was using.
  397. _freeTlsPages.Remove(tlsPageAddr);
  398. System.CriticalSection.Leave();
  399. FreeTlsPage(pageInfo);
  400. return KernelResult.Success;
  401. }
  402. }
  403. System.CriticalSection.Leave();
  404. return result;
  405. }
  406. private KernelResult FreeTlsPage(KTlsPageInfo pageInfo)
  407. {
  408. KernelResult result = MemoryManager.ConvertVaToPa(pageInfo.PageAddr, out ulong tlsPagePa);
  409. if (result != KernelResult.Success)
  410. {
  411. throw new InvalidOperationException("Unexpected failure translating virtual address to physical.");
  412. }
  413. result = MemoryManager.UnmapForKernel(pageInfo.PageAddr, 1, MemoryState.ThreadLocal);
  414. if (result == KernelResult.Success)
  415. {
  416. System.UserSlabHeapPages.Free(tlsPagePa);
  417. }
  418. return result;
  419. }
  420. private void GenerateRandomEntropy()
  421. {
  422. //TODO.
  423. }
  424. public KernelResult Start(int mainThreadPriority, ulong stackSize)
  425. {
  426. lock (_processLock)
  427. {
  428. if (_state > ProcessState.CreatedAttached)
  429. {
  430. return KernelResult.InvalidState;
  431. }
  432. if (ResourceLimit != null && !ResourceLimit.Reserve(LimitableResource.Thread, 1))
  433. {
  434. return KernelResult.ResLimitExceeded;
  435. }
  436. KResourceLimit threadResourceLimit = ResourceLimit;
  437. KResourceLimit memoryResourceLimit = null;
  438. if (_mainThreadStackSize != 0)
  439. {
  440. throw new InvalidOperationException("Trying to start a process with a invalid state!");
  441. }
  442. ulong stackSizeRounded = BitUtils.AlignUp(stackSize, KMemoryManager.PageSize);
  443. ulong neededSize = stackSizeRounded + _imageSize;
  444. //Check if the needed size for the code and the stack will fit on the
  445. //memory usage capacity of this Process. Also check for possible overflow
  446. //on the above addition.
  447. if (neededSize > _memoryUsageCapacity ||
  448. neededSize < stackSizeRounded)
  449. {
  450. threadResourceLimit?.Release(LimitableResource.Thread, 1);
  451. return KernelResult.OutOfMemory;
  452. }
  453. if (stackSizeRounded != 0 && ResourceLimit != null)
  454. {
  455. memoryResourceLimit = ResourceLimit;
  456. if (!memoryResourceLimit.Reserve(LimitableResource.Memory, stackSizeRounded))
  457. {
  458. threadResourceLimit?.Release(LimitableResource.Thread, 1);
  459. return KernelResult.ResLimitExceeded;
  460. }
  461. }
  462. KernelResult result;
  463. KThread mainThread = null;
  464. ulong stackTop = 0;
  465. void CleanUpForError()
  466. {
  467. mainThread?.Terminate();
  468. HandleTable.Destroy();
  469. if (_mainThreadStackSize != 0)
  470. {
  471. ulong stackBottom = stackTop - _mainThreadStackSize;
  472. ulong stackPagesCount = _mainThreadStackSize / KMemoryManager.PageSize;
  473. MemoryManager.UnmapForKernel(stackBottom, stackPagesCount, MemoryState.Stack);
  474. }
  475. memoryResourceLimit?.Release(LimitableResource.Memory, stackSizeRounded);
  476. threadResourceLimit?.Release(LimitableResource.Thread, 1);
  477. }
  478. if (stackSizeRounded != 0)
  479. {
  480. ulong stackPagesCount = stackSizeRounded / KMemoryManager.PageSize;
  481. ulong regionStart = MemoryManager.StackRegionStart;
  482. ulong regionSize = MemoryManager.StackRegionEnd - regionStart;
  483. ulong regionPagesCount = regionSize / KMemoryManager.PageSize;
  484. result = MemoryManager.AllocateOrMapPa(
  485. stackPagesCount,
  486. KMemoryManager.PageSize,
  487. 0,
  488. false,
  489. regionStart,
  490. regionPagesCount,
  491. MemoryState.Stack,
  492. MemoryPermission.ReadAndWrite,
  493. out ulong stackBottom);
  494. if (result != KernelResult.Success)
  495. {
  496. CleanUpForError();
  497. return result;
  498. }
  499. _mainThreadStackSize += stackSizeRounded;
  500. stackTop = stackBottom + stackSizeRounded;
  501. }
  502. ulong heapCapacity = _memoryUsageCapacity - _mainThreadStackSize - _imageSize;
  503. result = MemoryManager.SetHeapCapacity(heapCapacity);
  504. if (result != KernelResult.Success)
  505. {
  506. CleanUpForError();
  507. return result;
  508. }
  509. HandleTable = new KHandleTable(System);
  510. result = HandleTable.Initialize(Capabilities.HandleTableSize);
  511. if (result != KernelResult.Success)
  512. {
  513. CleanUpForError();
  514. return result;
  515. }
  516. mainThread = new KThread(System);
  517. result = mainThread.Initialize(
  518. _entrypoint,
  519. 0,
  520. stackTop,
  521. mainThreadPriority,
  522. DefaultCpuCore,
  523. this);
  524. if (result != KernelResult.Success)
  525. {
  526. CleanUpForError();
  527. return result;
  528. }
  529. result = HandleTable.GenerateHandle(mainThread, out int mainThreadHandle);
  530. if (result != KernelResult.Success)
  531. {
  532. CleanUpForError();
  533. return result;
  534. }
  535. mainThread.SetEntryArguments(0, mainThreadHandle);
  536. ProcessState oldState = _state;
  537. ProcessState newState = _state != ProcessState.Created
  538. ? ProcessState.Attached
  539. : ProcessState.Started;
  540. SetState(newState);
  541. //TODO: We can't call KThread.Start from a non-guest thread.
  542. //We will need to make some changes to allow the creation of
  543. //dummy threads that will be used to initialize the current
  544. //thread on KCoreContext so that GetCurrentThread doesn't fail.
  545. /* Result = MainThread.Start();
  546. if (Result != KernelResult.Success)
  547. {
  548. SetState(OldState);
  549. CleanUpForError();
  550. } */
  551. mainThread.Reschedule(ThreadSchedState.Running);
  552. return result;
  553. }
  554. }
  555. private void SetState(ProcessState newState)
  556. {
  557. if (_state != newState)
  558. {
  559. _state = newState;
  560. _signaled = true;
  561. Signal();
  562. }
  563. }
  564. public KernelResult InitializeThread(
  565. KThread thread,
  566. ulong entrypoint,
  567. ulong argsPtr,
  568. ulong stackTop,
  569. int priority,
  570. int cpuCore)
  571. {
  572. lock (_processLock)
  573. {
  574. return thread.Initialize(entrypoint, argsPtr, stackTop, priority, cpuCore, this);
  575. }
  576. }
  577. public void SubscribeThreadEventHandlers(CpuThread context)
  578. {
  579. context.ThreadState.Interrupt += InterruptHandler;
  580. context.ThreadState.SvcCall += _svcHandler.SvcCall;
  581. }
  582. private void InterruptHandler(object sender, EventArgs e)
  583. {
  584. System.Scheduler.ContextSwitch();
  585. }
  586. public void IncrementThreadCount()
  587. {
  588. Interlocked.Increment(ref _threadCount);
  589. System.ThreadCounter.AddCount();
  590. }
  591. public void DecrementThreadCountAndTerminateIfZero()
  592. {
  593. System.ThreadCounter.Signal();
  594. if (Interlocked.Decrement(ref _threadCount) == 0)
  595. {
  596. Terminate();
  597. }
  598. }
  599. public ulong GetMemoryCapacity()
  600. {
  601. ulong totalCapacity = (ulong)ResourceLimit.GetRemainingValue(LimitableResource.Memory);
  602. totalCapacity += MemoryManager.GetTotalHeapSize();
  603. totalCapacity += GetPersonalMmHeapSize();
  604. totalCapacity += _imageSize + _mainThreadStackSize;
  605. if (totalCapacity <= _memoryUsageCapacity)
  606. {
  607. return totalCapacity;
  608. }
  609. return _memoryUsageCapacity;
  610. }
  611. public ulong GetMemoryUsage()
  612. {
  613. return _imageSize + _mainThreadStackSize + MemoryManager.GetTotalHeapSize() + GetPersonalMmHeapSize();
  614. }
  615. public ulong GetMemoryCapacityWithoutPersonalMmHeap()
  616. {
  617. return GetMemoryCapacity() - GetPersonalMmHeapSize();
  618. }
  619. public ulong GetMemoryUsageWithoutPersonalMmHeap()
  620. {
  621. return GetMemoryUsage() - GetPersonalMmHeapSize();
  622. }
  623. private ulong GetPersonalMmHeapSize()
  624. {
  625. return GetPersonalMmHeapSize(PersonalMmHeapPagesCount, _memRegion);
  626. }
  627. private static ulong GetPersonalMmHeapSize(ulong personalMmHeapPagesCount, MemoryRegion memRegion)
  628. {
  629. if (memRegion == MemoryRegion.Applet)
  630. {
  631. return 0;
  632. }
  633. return personalMmHeapPagesCount * KMemoryManager.PageSize;
  634. }
  635. public void AddThread(KThread thread)
  636. {
  637. lock (_threadingLock)
  638. {
  639. thread.ProcessListNode = _threads.AddLast(thread);
  640. }
  641. }
  642. public void RemoveThread(KThread thread)
  643. {
  644. lock (_threadingLock)
  645. {
  646. _threads.Remove(thread.ProcessListNode);
  647. }
  648. }
  649. public bool IsCpuCoreAllowed(int core)
  650. {
  651. return (Capabilities.AllowedCpuCoresMask & (1L << core)) != 0;
  652. }
  653. public bool IsPriorityAllowed(int priority)
  654. {
  655. return (Capabilities.AllowedThreadPriosMask & (1L << priority)) != 0;
  656. }
  657. public override bool IsSignaled()
  658. {
  659. return _signaled;
  660. }
  661. public KernelResult Terminate()
  662. {
  663. KernelResult result;
  664. bool shallTerminate = false;
  665. System.CriticalSection.Enter();
  666. lock (_processLock)
  667. {
  668. if (_state >= ProcessState.Started)
  669. {
  670. if (_state == ProcessState.Started ||
  671. _state == ProcessState.Crashed ||
  672. _state == ProcessState.Attached ||
  673. _state == ProcessState.DebugSuspended)
  674. {
  675. SetState(ProcessState.Exiting);
  676. shallTerminate = true;
  677. }
  678. result = KernelResult.Success;
  679. }
  680. else
  681. {
  682. result = KernelResult.InvalidState;
  683. }
  684. }
  685. System.CriticalSection.Leave();
  686. if (shallTerminate)
  687. {
  688. //UnpauseAndTerminateAllThreadsExcept(System.Scheduler.GetCurrentThread());
  689. HandleTable.Destroy();
  690. SignalExitForDebugEvent();
  691. SignalExit();
  692. }
  693. return result;
  694. }
  695. private void UnpauseAndTerminateAllThreadsExcept(KThread thread)
  696. {
  697. //TODO.
  698. }
  699. private void SignalExitForDebugEvent()
  700. {
  701. //TODO: Debug events.
  702. }
  703. private void SignalExit()
  704. {
  705. if (ResourceLimit != null)
  706. {
  707. ResourceLimit.Release(LimitableResource.Memory, GetMemoryUsage());
  708. }
  709. System.CriticalSection.Enter();
  710. SetState(ProcessState.Exited);
  711. System.CriticalSection.Leave();
  712. }
  713. public KernelResult ClearIfNotExited()
  714. {
  715. KernelResult result;
  716. System.CriticalSection.Enter();
  717. lock (_processLock)
  718. {
  719. if (_state != ProcessState.Exited && _signaled)
  720. {
  721. _signaled = false;
  722. result = KernelResult.Success;
  723. }
  724. else
  725. {
  726. result = KernelResult.InvalidState;
  727. }
  728. }
  729. System.CriticalSection.Leave();
  730. return result;
  731. }
  732. public void StopAllThreads()
  733. {
  734. lock (_threadingLock)
  735. {
  736. foreach (KThread thread in _threads)
  737. {
  738. thread.Context.StopExecution();
  739. System.Scheduler.CoreManager.Set(thread.Context.Work);
  740. }
  741. }
  742. }
  743. private void InvalidAccessHandler(object sender, MemoryAccessEventArgs e)
  744. {
  745. PrintCurrentThreadStackTrace();
  746. }
  747. public void PrintCurrentThreadStackTrace()
  748. {
  749. System.Scheduler.GetCurrentThread().PrintGuestStackTrace();
  750. }
  751. private void CpuTraceHandler(object sender, CpuTraceEventArgs e)
  752. {
  753. Logger.PrintInfo(LogClass.Cpu, $"Executing at 0x{e.Position:X16}.");
  754. }
  755. }
  756. }