svc.cpp 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045
  1. // Copyright 2018 yuzu emulator team
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <cinttypes>
  6. #include <iterator>
  7. #include <mutex>
  8. #include <vector>
  9. #include "common/alignment.h"
  10. #include "common/assert.h"
  11. #include "common/logging/log.h"
  12. #include "common/microprofile.h"
  13. #include "common/string_util.h"
  14. #include "core/arm/exclusive_monitor.h"
  15. #include "core/core.h"
  16. #include "core/core_cpu.h"
  17. #include "core/core_timing.h"
  18. #include "core/hle/kernel/address_arbiter.h"
  19. #include "core/hle/kernel/client_port.h"
  20. #include "core/hle/kernel/client_session.h"
  21. #include "core/hle/kernel/errors.h"
  22. #include "core/hle/kernel/handle_table.h"
  23. #include "core/hle/kernel/kernel.h"
  24. #include "core/hle/kernel/mutex.h"
  25. #include "core/hle/kernel/process.h"
  26. #include "core/hle/kernel/readable_event.h"
  27. #include "core/hle/kernel/resource_limit.h"
  28. #include "core/hle/kernel/scheduler.h"
  29. #include "core/hle/kernel/shared_memory.h"
  30. #include "core/hle/kernel/svc.h"
  31. #include "core/hle/kernel/svc_wrap.h"
  32. #include "core/hle/kernel/thread.h"
  33. #include "core/hle/kernel/writable_event.h"
  34. #include "core/hle/lock.h"
  35. #include "core/hle/result.h"
  36. #include "core/hle/service/service.h"
  37. #include "core/memory.h"
  38. namespace Kernel {
  39. namespace {
  40. // Checks if address + size is greater than the given address
  41. // This can return false if the size causes an overflow of a 64-bit type
  42. // or if the given size is zero.
  43. constexpr bool IsValidAddressRange(VAddr address, u64 size) {
  44. return address + size > address;
  45. }
  46. // 8 GiB
  47. constexpr u64 MAIN_MEMORY_SIZE = 0x200000000;
  48. // Helper function that performs the common sanity checks for svcMapMemory
  49. // and svcUnmapMemory. This is doable, as both functions perform their sanitizing
  50. // in the same order.
  51. ResultCode MapUnmapMemorySanityChecks(const VMManager& vm_manager, VAddr dst_addr, VAddr src_addr,
  52. u64 size) {
  53. if (!Common::Is4KBAligned(dst_addr)) {
  54. LOG_ERROR(Kernel_SVC, "Destination address is not aligned to 4KB, 0x{:016X}", dst_addr);
  55. return ERR_INVALID_ADDRESS;
  56. }
  57. if (!Common::Is4KBAligned(src_addr)) {
  58. LOG_ERROR(Kernel_SVC, "Source address is not aligned to 4KB, 0x{:016X}", src_addr);
  59. return ERR_INVALID_SIZE;
  60. }
  61. if (size == 0) {
  62. LOG_ERROR(Kernel_SVC, "Size is 0");
  63. return ERR_INVALID_SIZE;
  64. }
  65. if (!Common::Is4KBAligned(size)) {
  66. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, 0x{:016X}", size);
  67. return ERR_INVALID_SIZE;
  68. }
  69. if (!IsValidAddressRange(dst_addr, size)) {
  70. LOG_ERROR(Kernel_SVC,
  71. "Destination is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
  72. dst_addr, size);
  73. return ERR_INVALID_ADDRESS_STATE;
  74. }
  75. if (!IsValidAddressRange(src_addr, size)) {
  76. LOG_ERROR(Kernel_SVC, "Source is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
  77. src_addr, size);
  78. return ERR_INVALID_ADDRESS_STATE;
  79. }
  80. if (!vm_manager.IsWithinAddressSpace(src_addr, size)) {
  81. LOG_ERROR(Kernel_SVC,
  82. "Source is not within the address space, addr=0x{:016X}, size=0x{:016X}",
  83. src_addr, size);
  84. return ERR_INVALID_ADDRESS_STATE;
  85. }
  86. if (!vm_manager.IsWithinNewMapRegion(dst_addr, size)) {
  87. LOG_ERROR(Kernel_SVC,
  88. "Destination is not within the new map region, addr=0x{:016X}, size=0x{:016X}",
  89. dst_addr, size);
  90. return ERR_INVALID_MEMORY_RANGE;
  91. }
  92. const VAddr dst_end_address = dst_addr + size;
  93. if (dst_end_address > vm_manager.GetHeapRegionBaseAddress() &&
  94. vm_manager.GetHeapRegionEndAddress() > dst_addr) {
  95. LOG_ERROR(Kernel_SVC,
  96. "Destination does not fit within the heap region, addr=0x{:016X}, "
  97. "size=0x{:016X}, end_addr=0x{:016X}",
  98. dst_addr, size, dst_end_address);
  99. return ERR_INVALID_MEMORY_RANGE;
  100. }
  101. if (dst_end_address > vm_manager.GetMapRegionBaseAddress() &&
  102. vm_manager.GetMapRegionEndAddress() > dst_addr) {
  103. LOG_ERROR(Kernel_SVC,
  104. "Destination does not fit within the map region, addr=0x{:016X}, "
  105. "size=0x{:016X}, end_addr=0x{:016X}",
  106. dst_addr, size, dst_end_address);
  107. return ERR_INVALID_MEMORY_RANGE;
  108. }
  109. return RESULT_SUCCESS;
  110. }
  111. enum class ResourceLimitValueType {
  112. CurrentValue,
  113. LimitValue,
  114. };
  115. ResultVal<s64> RetrieveResourceLimitValue(Handle resource_limit, u32 resource_type,
  116. ResourceLimitValueType value_type) {
  117. const auto type = static_cast<ResourceType>(resource_type);
  118. if (!IsValidResourceType(type)) {
  119. LOG_ERROR(Kernel_SVC, "Invalid resource limit type: '{}'", resource_type);
  120. return ERR_INVALID_ENUM_VALUE;
  121. }
  122. const auto& kernel = Core::System::GetInstance().Kernel();
  123. const auto* const current_process = kernel.CurrentProcess();
  124. ASSERT(current_process != nullptr);
  125. const auto resource_limit_object =
  126. current_process->GetHandleTable().Get<ResourceLimit>(resource_limit);
  127. if (!resource_limit_object) {
  128. LOG_ERROR(Kernel_SVC, "Handle to non-existent resource limit instance used. Handle={:08X}",
  129. resource_limit);
  130. return ERR_INVALID_HANDLE;
  131. }
  132. if (value_type == ResourceLimitValueType::CurrentValue) {
  133. return MakeResult(resource_limit_object->GetCurrentResourceValue(type));
  134. }
  135. return MakeResult(resource_limit_object->GetMaxResourceValue(type));
  136. }
  137. } // Anonymous namespace
  138. /// Set the process heap to a given Size. It can both extend and shrink the heap.
  139. static ResultCode SetHeapSize(VAddr* heap_addr, u64 heap_size) {
  140. LOG_TRACE(Kernel_SVC, "called, heap_size=0x{:X}", heap_size);
  141. // Size must be a multiple of 0x200000 (2MB) and be equal to or less than 8GB.
  142. if ((heap_size % 0x200000) != 0) {
  143. LOG_ERROR(Kernel_SVC, "The heap size is not a multiple of 2MB, heap_size=0x{:016X}",
  144. heap_size);
  145. return ERR_INVALID_SIZE;
  146. }
  147. if (heap_size >= 0x200000000) {
  148. LOG_ERROR(Kernel_SVC, "The heap size is not less than 8GB, heap_size=0x{:016X}", heap_size);
  149. return ERR_INVALID_SIZE;
  150. }
  151. auto& vm_manager = Core::CurrentProcess()->VMManager();
  152. const VAddr heap_base = vm_manager.GetHeapRegionBaseAddress();
  153. const auto alloc_result =
  154. vm_manager.HeapAllocate(heap_base, heap_size, VMAPermission::ReadWrite);
  155. if (alloc_result.Failed()) {
  156. return alloc_result.Code();
  157. }
  158. *heap_addr = *alloc_result;
  159. return RESULT_SUCCESS;
  160. }
  161. static ResultCode SetMemoryPermission(VAddr addr, u64 size, u32 prot) {
  162. LOG_TRACE(Kernel_SVC, "called, addr=0x{:X}, size=0x{:X}, prot=0x{:X}", addr, size, prot);
  163. if (!Common::Is4KBAligned(addr)) {
  164. LOG_ERROR(Kernel_SVC, "Address is not aligned to 4KB, addr=0x{:016X}", addr);
  165. return ERR_INVALID_ADDRESS;
  166. }
  167. if (size == 0) {
  168. LOG_ERROR(Kernel_SVC, "Size is 0");
  169. return ERR_INVALID_SIZE;
  170. }
  171. if (!Common::Is4KBAligned(size)) {
  172. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, size=0x{:016X}", size);
  173. return ERR_INVALID_SIZE;
  174. }
  175. if (!IsValidAddressRange(addr, size)) {
  176. LOG_ERROR(Kernel_SVC, "Region is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
  177. addr, size);
  178. return ERR_INVALID_ADDRESS_STATE;
  179. }
  180. const auto permission = static_cast<MemoryPermission>(prot);
  181. if (permission != MemoryPermission::None && permission != MemoryPermission::Read &&
  182. permission != MemoryPermission::ReadWrite) {
  183. LOG_ERROR(Kernel_SVC, "Invalid memory permission specified, Got memory permission=0x{:08X}",
  184. static_cast<u32>(permission));
  185. return ERR_INVALID_MEMORY_PERMISSIONS;
  186. }
  187. auto* const current_process = Core::CurrentProcess();
  188. auto& vm_manager = current_process->VMManager();
  189. if (!vm_manager.IsWithinAddressSpace(addr, size)) {
  190. LOG_ERROR(Kernel_SVC,
  191. "Source is not within the address space, addr=0x{:016X}, size=0x{:016X}", addr,
  192. size);
  193. return ERR_INVALID_ADDRESS_STATE;
  194. }
  195. const VMManager::VMAHandle iter = vm_manager.FindVMA(addr);
  196. if (!vm_manager.IsValidHandle(iter)) {
  197. LOG_ERROR(Kernel_SVC, "Unable to find VMA for address=0x{:016X}", addr);
  198. return ERR_INVALID_ADDRESS_STATE;
  199. }
  200. LOG_WARNING(Kernel_SVC, "Uniformity check on protected memory is not implemented.");
  201. // TODO: Performs a uniformity check to make sure only protected memory is changed (it doesn't
  202. // make sense to allow changing permissions on kernel memory itself, etc).
  203. const auto converted_permissions = SharedMemory::ConvertPermissions(permission);
  204. return vm_manager.ReprotectRange(addr, size, converted_permissions);
  205. }
  206. static ResultCode SetMemoryAttribute(VAddr address, u64 size, u32 mask, u32 attribute) {
  207. LOG_DEBUG(Kernel_SVC,
  208. "called, address=0x{:016X}, size=0x{:X}, mask=0x{:08X}, attribute=0x{:08X}", address,
  209. size, mask, attribute);
  210. if (!Common::Is4KBAligned(address)) {
  211. LOG_ERROR(Kernel_SVC, "Address not page aligned (0x{:016X})", address);
  212. return ERR_INVALID_ADDRESS;
  213. }
  214. if (size == 0 || !Common::Is4KBAligned(size)) {
  215. LOG_ERROR(Kernel_SVC, "Invalid size (0x{:X}). Size must be non-zero and page aligned.",
  216. size);
  217. return ERR_INVALID_ADDRESS;
  218. }
  219. if (!IsValidAddressRange(address, size)) {
  220. LOG_ERROR(Kernel_SVC, "Address range overflowed (Address: 0x{:016X}, Size: 0x{:016X})",
  221. address, size);
  222. return ERR_INVALID_ADDRESS_STATE;
  223. }
  224. const auto mem_attribute = static_cast<MemoryAttribute>(attribute);
  225. const auto mem_mask = static_cast<MemoryAttribute>(mask);
  226. const auto attribute_with_mask = mem_attribute | mem_mask;
  227. if (attribute_with_mask != mem_mask) {
  228. LOG_ERROR(Kernel_SVC,
  229. "Memory attribute doesn't match the given mask (Attribute: 0x{:X}, Mask: {:X}",
  230. attribute, mask);
  231. return ERR_INVALID_COMBINATION;
  232. }
  233. if ((attribute_with_mask | MemoryAttribute::Uncached) != MemoryAttribute::Uncached) {
  234. LOG_ERROR(Kernel_SVC, "Specified attribute isn't equal to MemoryAttributeUncached (8).");
  235. return ERR_INVALID_COMBINATION;
  236. }
  237. auto& vm_manager = Core::CurrentProcess()->VMManager();
  238. if (!vm_manager.IsWithinAddressSpace(address, size)) {
  239. LOG_ERROR(Kernel_SVC,
  240. "Given address (0x{:016X}) is outside the bounds of the address space.", address);
  241. return ERR_INVALID_ADDRESS_STATE;
  242. }
  243. return vm_manager.SetMemoryAttribute(address, size, mem_mask, mem_attribute);
  244. }
  245. /// Maps a memory range into a different range.
  246. static ResultCode MapMemory(VAddr dst_addr, VAddr src_addr, u64 size) {
  247. LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr,
  248. src_addr, size);
  249. auto& vm_manager = Core::CurrentProcess()->VMManager();
  250. const auto result = MapUnmapMemorySanityChecks(vm_manager, dst_addr, src_addr, size);
  251. if (result.IsError()) {
  252. return result;
  253. }
  254. return vm_manager.MirrorMemory(dst_addr, src_addr, size, MemoryState::Stack);
  255. }
  256. /// Unmaps a region that was previously mapped with svcMapMemory
  257. static ResultCode UnmapMemory(VAddr dst_addr, VAddr src_addr, u64 size) {
  258. LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr,
  259. src_addr, size);
  260. auto& vm_manager = Core::CurrentProcess()->VMManager();
  261. const auto result = MapUnmapMemorySanityChecks(vm_manager, dst_addr, src_addr, size);
  262. if (result.IsError()) {
  263. return result;
  264. }
  265. return vm_manager.UnmapRange(dst_addr, size);
  266. }
  267. /// Connect to an OS service given the port name, returns the handle to the port to out
  268. static ResultCode ConnectToNamedPort(Handle* out_handle, VAddr port_name_address) {
  269. if (!Memory::IsValidVirtualAddress(port_name_address)) {
  270. LOG_ERROR(Kernel_SVC,
  271. "Port Name Address is not a valid virtual address, port_name_address=0x{:016X}",
  272. port_name_address);
  273. return ERR_NOT_FOUND;
  274. }
  275. static constexpr std::size_t PortNameMaxLength = 11;
  276. // Read 1 char beyond the max allowed port name to detect names that are too long.
  277. std::string port_name = Memory::ReadCString(port_name_address, PortNameMaxLength + 1);
  278. if (port_name.size() > PortNameMaxLength) {
  279. LOG_ERROR(Kernel_SVC, "Port name is too long, expected {} but got {}", PortNameMaxLength,
  280. port_name.size());
  281. return ERR_OUT_OF_RANGE;
  282. }
  283. LOG_TRACE(Kernel_SVC, "called port_name={}", port_name);
  284. auto& kernel = Core::System::GetInstance().Kernel();
  285. auto it = kernel.FindNamedPort(port_name);
  286. if (!kernel.IsValidNamedPort(it)) {
  287. LOG_WARNING(Kernel_SVC, "tried to connect to unknown port: {}", port_name);
  288. return ERR_NOT_FOUND;
  289. }
  290. auto client_port = it->second;
  291. SharedPtr<ClientSession> client_session;
  292. CASCADE_RESULT(client_session, client_port->Connect());
  293. // Return the client session
  294. auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  295. CASCADE_RESULT(*out_handle, handle_table.Create(client_session));
  296. return RESULT_SUCCESS;
  297. }
  298. /// Makes a blocking IPC call to an OS service.
  299. static ResultCode SendSyncRequest(Handle handle) {
  300. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  301. SharedPtr<ClientSession> session = handle_table.Get<ClientSession>(handle);
  302. if (!session) {
  303. LOG_ERROR(Kernel_SVC, "called with invalid handle=0x{:08X}", handle);
  304. return ERR_INVALID_HANDLE;
  305. }
  306. LOG_TRACE(Kernel_SVC, "called handle=0x{:08X}({})", handle, session->GetName());
  307. Core::System::GetInstance().PrepareReschedule();
  308. // TODO(Subv): svcSendSyncRequest should put the caller thread to sleep while the server
  309. // responds and cause a reschedule.
  310. return session->SendSyncRequest(GetCurrentThread());
  311. }
  312. /// Get the ID for the specified thread.
  313. static ResultCode GetThreadId(u64* thread_id, Handle thread_handle) {
  314. LOG_TRACE(Kernel_SVC, "called thread=0x{:08X}", thread_handle);
  315. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  316. const SharedPtr<Thread> thread = handle_table.Get<Thread>(thread_handle);
  317. if (!thread) {
  318. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}", thread_handle);
  319. return ERR_INVALID_HANDLE;
  320. }
  321. *thread_id = thread->GetThreadID();
  322. return RESULT_SUCCESS;
  323. }
  324. /// Gets the ID of the specified process or a specified thread's owning process.
  325. static ResultCode GetProcessId(u64* process_id, Handle handle) {
  326. LOG_DEBUG(Kernel_SVC, "called handle=0x{:08X}", handle);
  327. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  328. const SharedPtr<Process> process = handle_table.Get<Process>(handle);
  329. if (process) {
  330. *process_id = process->GetProcessID();
  331. return RESULT_SUCCESS;
  332. }
  333. const SharedPtr<Thread> thread = handle_table.Get<Thread>(handle);
  334. if (thread) {
  335. const Process* const owner_process = thread->GetOwnerProcess();
  336. if (!owner_process) {
  337. LOG_ERROR(Kernel_SVC, "Non-existent owning process encountered.");
  338. return ERR_INVALID_HANDLE;
  339. }
  340. *process_id = owner_process->GetProcessID();
  341. return RESULT_SUCCESS;
  342. }
  343. // NOTE: This should also handle debug objects before returning.
  344. LOG_ERROR(Kernel_SVC, "Handle does not exist, handle=0x{:08X}", handle);
  345. return ERR_INVALID_HANDLE;
  346. }
  347. /// Default thread wakeup callback for WaitSynchronization
  348. static bool DefaultThreadWakeupCallback(ThreadWakeupReason reason, SharedPtr<Thread> thread,
  349. SharedPtr<WaitObject> object, std::size_t index) {
  350. ASSERT(thread->GetStatus() == ThreadStatus::WaitSynchAny);
  351. if (reason == ThreadWakeupReason::Timeout) {
  352. thread->SetWaitSynchronizationResult(RESULT_TIMEOUT);
  353. return true;
  354. }
  355. ASSERT(reason == ThreadWakeupReason::Signal);
  356. thread->SetWaitSynchronizationResult(RESULT_SUCCESS);
  357. thread->SetWaitSynchronizationOutput(static_cast<u32>(index));
  358. return true;
  359. };
  360. /// Wait for the given handles to synchronize, timeout after the specified nanoseconds
  361. static ResultCode WaitSynchronization(Handle* index, VAddr handles_address, u64 handle_count,
  362. s64 nano_seconds) {
  363. LOG_TRACE(Kernel_SVC, "called handles_address=0x{:X}, handle_count={}, nano_seconds={}",
  364. handles_address, handle_count, nano_seconds);
  365. if (!Memory::IsValidVirtualAddress(handles_address)) {
  366. LOG_ERROR(Kernel_SVC,
  367. "Handle address is not a valid virtual address, handle_address=0x{:016X}",
  368. handles_address);
  369. return ERR_INVALID_POINTER;
  370. }
  371. static constexpr u64 MaxHandles = 0x40;
  372. if (handle_count > MaxHandles) {
  373. LOG_ERROR(Kernel_SVC, "Handle count specified is too large, expected {} but got {}",
  374. MaxHandles, handle_count);
  375. return ERR_OUT_OF_RANGE;
  376. }
  377. auto* const thread = GetCurrentThread();
  378. using ObjectPtr = Thread::ThreadWaitObjects::value_type;
  379. Thread::ThreadWaitObjects objects(handle_count);
  380. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  381. for (u64 i = 0; i < handle_count; ++i) {
  382. const Handle handle = Memory::Read32(handles_address + i * sizeof(Handle));
  383. const auto object = handle_table.Get<WaitObject>(handle);
  384. if (object == nullptr) {
  385. LOG_ERROR(Kernel_SVC, "Object is a nullptr");
  386. return ERR_INVALID_HANDLE;
  387. }
  388. objects[i] = object;
  389. }
  390. // Find the first object that is acquirable in the provided list of objects
  391. auto itr = std::find_if(objects.begin(), objects.end(), [thread](const ObjectPtr& object) {
  392. return !object->ShouldWait(thread);
  393. });
  394. if (itr != objects.end()) {
  395. // We found a ready object, acquire it and set the result value
  396. WaitObject* object = itr->get();
  397. object->Acquire(thread);
  398. *index = static_cast<s32>(std::distance(objects.begin(), itr));
  399. return RESULT_SUCCESS;
  400. }
  401. // No objects were ready to be acquired, prepare to suspend the thread.
  402. // If a timeout value of 0 was provided, just return the Timeout error code instead of
  403. // suspending the thread.
  404. if (nano_seconds == 0) {
  405. return RESULT_TIMEOUT;
  406. }
  407. for (auto& object : objects) {
  408. object->AddWaitingThread(thread);
  409. }
  410. thread->SetWaitObjects(std::move(objects));
  411. thread->SetStatus(ThreadStatus::WaitSynchAny);
  412. // Create an event to wake the thread up after the specified nanosecond delay has passed
  413. thread->WakeAfterDelay(nano_seconds);
  414. thread->SetWakeupCallback(DefaultThreadWakeupCallback);
  415. Core::System::GetInstance().CpuCore(thread->GetProcessorID()).PrepareReschedule();
  416. return RESULT_TIMEOUT;
  417. }
  418. /// Resumes a thread waiting on WaitSynchronization
  419. static ResultCode CancelSynchronization(Handle thread_handle) {
  420. LOG_TRACE(Kernel_SVC, "called thread=0x{:X}", thread_handle);
  421. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  422. const SharedPtr<Thread> thread = handle_table.Get<Thread>(thread_handle);
  423. if (!thread) {
  424. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, thread_handle=0x{:08X}",
  425. thread_handle);
  426. return ERR_INVALID_HANDLE;
  427. }
  428. ASSERT(thread->GetStatus() == ThreadStatus::WaitSynchAny);
  429. thread->SetWaitSynchronizationResult(ERR_SYNCHRONIZATION_CANCELED);
  430. thread->ResumeFromWait();
  431. return RESULT_SUCCESS;
  432. }
  433. /// Attempts to locks a mutex, creating it if it does not already exist
  434. static ResultCode ArbitrateLock(Handle holding_thread_handle, VAddr mutex_addr,
  435. Handle requesting_thread_handle) {
  436. LOG_TRACE(Kernel_SVC,
  437. "called holding_thread_handle=0x{:08X}, mutex_addr=0x{:X}, "
  438. "requesting_current_thread_handle=0x{:08X}",
  439. holding_thread_handle, mutex_addr, requesting_thread_handle);
  440. if (Memory::IsKernelVirtualAddress(mutex_addr)) {
  441. LOG_ERROR(Kernel_SVC, "Mutex Address is a kernel virtual address, mutex_addr={:016X}",
  442. mutex_addr);
  443. return ERR_INVALID_ADDRESS_STATE;
  444. }
  445. if (!Common::IsWordAligned(mutex_addr)) {
  446. LOG_ERROR(Kernel_SVC, "Mutex Address is not word aligned, mutex_addr={:016X}", mutex_addr);
  447. return ERR_INVALID_ADDRESS;
  448. }
  449. auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  450. return Mutex::TryAcquire(handle_table, mutex_addr, holding_thread_handle,
  451. requesting_thread_handle);
  452. }
  453. /// Unlock a mutex
  454. static ResultCode ArbitrateUnlock(VAddr mutex_addr) {
  455. LOG_TRACE(Kernel_SVC, "called mutex_addr=0x{:X}", mutex_addr);
  456. if (Memory::IsKernelVirtualAddress(mutex_addr)) {
  457. LOG_ERROR(Kernel_SVC, "Mutex Address is a kernel virtual address, mutex_addr={:016X}",
  458. mutex_addr);
  459. return ERR_INVALID_ADDRESS_STATE;
  460. }
  461. if (!Common::IsWordAligned(mutex_addr)) {
  462. LOG_ERROR(Kernel_SVC, "Mutex Address is not word aligned, mutex_addr={:016X}", mutex_addr);
  463. return ERR_INVALID_ADDRESS;
  464. }
  465. return Mutex::Release(mutex_addr);
  466. }
  467. enum class BreakType : u32 {
  468. Panic = 0,
  469. AssertionFailed = 1,
  470. PreNROLoad = 3,
  471. PostNROLoad = 4,
  472. PreNROUnload = 5,
  473. PostNROUnload = 6,
  474. CppException = 7,
  475. };
  476. struct BreakReason {
  477. union {
  478. u32 raw;
  479. BitField<0, 30, BreakType> break_type;
  480. BitField<31, 1, u32> signal_debugger;
  481. };
  482. };
  483. /// Break program execution
  484. static void Break(u32 reason, u64 info1, u64 info2) {
  485. BreakReason break_reason{reason};
  486. bool has_dumped_buffer{};
  487. const auto handle_debug_buffer = [&](VAddr addr, u64 sz) {
  488. if (sz == 0 || addr == 0 || has_dumped_buffer) {
  489. return;
  490. }
  491. // This typically is an error code so we're going to assume this is the case
  492. if (sz == sizeof(u32)) {
  493. LOG_CRITICAL(Debug_Emulated, "debug_buffer_err_code={:X}", Memory::Read32(addr));
  494. } else {
  495. // We don't know what's in here so we'll hexdump it
  496. std::vector<u8> debug_buffer(sz);
  497. Memory::ReadBlock(addr, debug_buffer.data(), sz);
  498. std::string hexdump;
  499. for (std::size_t i = 0; i < debug_buffer.size(); i++) {
  500. hexdump += fmt::format("{:02X} ", debug_buffer[i]);
  501. if (i != 0 && i % 16 == 0) {
  502. hexdump += '\n';
  503. }
  504. }
  505. LOG_CRITICAL(Debug_Emulated, "debug_buffer=\n{}", hexdump);
  506. }
  507. has_dumped_buffer = true;
  508. };
  509. switch (break_reason.break_type) {
  510. case BreakType::Panic:
  511. LOG_CRITICAL(Debug_Emulated, "Signalling debugger, PANIC! info1=0x{:016X}, info2=0x{:016X}",
  512. info1, info2);
  513. handle_debug_buffer(info1, info2);
  514. break;
  515. case BreakType::AssertionFailed:
  516. LOG_CRITICAL(Debug_Emulated,
  517. "Signalling debugger, Assertion failed! info1=0x{:016X}, info2=0x{:016X}",
  518. info1, info2);
  519. handle_debug_buffer(info1, info2);
  520. break;
  521. case BreakType::PreNROLoad:
  522. LOG_WARNING(
  523. Debug_Emulated,
  524. "Signalling debugger, Attempting to load an NRO at 0x{:016X} with size 0x{:016X}",
  525. info1, info2);
  526. break;
  527. case BreakType::PostNROLoad:
  528. LOG_WARNING(Debug_Emulated,
  529. "Signalling debugger, Loaded an NRO at 0x{:016X} with size 0x{:016X}", info1,
  530. info2);
  531. break;
  532. case BreakType::PreNROUnload:
  533. LOG_WARNING(
  534. Debug_Emulated,
  535. "Signalling debugger, Attempting to unload an NRO at 0x{:016X} with size 0x{:016X}",
  536. info1, info2);
  537. break;
  538. case BreakType::PostNROUnload:
  539. LOG_WARNING(Debug_Emulated,
  540. "Signalling debugger, Unloaded an NRO at 0x{:016X} with size 0x{:016X}", info1,
  541. info2);
  542. break;
  543. case BreakType::CppException:
  544. LOG_CRITICAL(Debug_Emulated, "Signalling debugger. Uncaught C++ exception encountered.");
  545. break;
  546. default:
  547. LOG_WARNING(
  548. Debug_Emulated,
  549. "Signalling debugger, Unknown break reason {}, info1=0x{:016X}, info2=0x{:016X}",
  550. static_cast<u32>(break_reason.break_type.Value()), info1, info2);
  551. handle_debug_buffer(info1, info2);
  552. break;
  553. }
  554. if (!break_reason.signal_debugger) {
  555. LOG_CRITICAL(
  556. Debug_Emulated,
  557. "Emulated program broke execution! reason=0x{:016X}, info1=0x{:016X}, info2=0x{:016X}",
  558. reason, info1, info2);
  559. handle_debug_buffer(info1, info2);
  560. Core::System::GetInstance()
  561. .ArmInterface(static_cast<std::size_t>(GetCurrentThread()->GetProcessorID()))
  562. .LogBacktrace();
  563. ASSERT(false);
  564. Core::CurrentProcess()->PrepareForTermination();
  565. // Kill the current thread
  566. GetCurrentThread()->Stop();
  567. Core::System::GetInstance().PrepareReschedule();
  568. }
  569. }
  570. /// Used to output a message on a debug hardware unit - does nothing on a retail unit
  571. static void OutputDebugString(VAddr address, u64 len) {
  572. if (len == 0) {
  573. return;
  574. }
  575. std::string str(len, '\0');
  576. Memory::ReadBlock(address, str.data(), str.size());
  577. LOG_DEBUG(Debug_Emulated, "{}", str);
  578. }
  579. /// Gets system/memory information for the current process
  580. static ResultCode GetInfo(u64* result, u64 info_id, u64 handle, u64 info_sub_id) {
  581. LOG_TRACE(Kernel_SVC, "called info_id=0x{:X}, info_sub_id=0x{:X}, handle=0x{:08X}", info_id,
  582. info_sub_id, handle);
  583. enum class GetInfoType : u64 {
  584. // 1.0.0+
  585. AllowedCPUCoreMask = 0,
  586. AllowedThreadPriorityMask = 1,
  587. MapRegionBaseAddr = 2,
  588. MapRegionSize = 3,
  589. HeapRegionBaseAddr = 4,
  590. HeapRegionSize = 5,
  591. TotalMemoryUsage = 6,
  592. TotalHeapUsage = 7,
  593. IsCurrentProcessBeingDebugged = 8,
  594. RegisterResourceLimit = 9,
  595. IdleTickCount = 10,
  596. RandomEntropy = 11,
  597. PerformanceCounter = 0xF0000002,
  598. // 2.0.0+
  599. ASLRRegionBaseAddr = 12,
  600. ASLRRegionSize = 13,
  601. NewMapRegionBaseAddr = 14,
  602. NewMapRegionSize = 15,
  603. // 3.0.0+
  604. IsVirtualAddressMemoryEnabled = 16,
  605. PersonalMmHeapUsage = 17,
  606. TitleId = 18,
  607. // 4.0.0+
  608. PrivilegedProcessId = 19,
  609. // 5.0.0+
  610. UserExceptionContextAddr = 20,
  611. ThreadTickCount = 0xF0000002,
  612. };
  613. const auto info_id_type = static_cast<GetInfoType>(info_id);
  614. switch (info_id_type) {
  615. case GetInfoType::AllowedCPUCoreMask:
  616. case GetInfoType::AllowedThreadPriorityMask:
  617. case GetInfoType::MapRegionBaseAddr:
  618. case GetInfoType::MapRegionSize:
  619. case GetInfoType::HeapRegionBaseAddr:
  620. case GetInfoType::HeapRegionSize:
  621. case GetInfoType::ASLRRegionBaseAddr:
  622. case GetInfoType::ASLRRegionSize:
  623. case GetInfoType::NewMapRegionBaseAddr:
  624. case GetInfoType::NewMapRegionSize:
  625. case GetInfoType::TotalMemoryUsage:
  626. case GetInfoType::TotalHeapUsage:
  627. case GetInfoType::IsVirtualAddressMemoryEnabled:
  628. case GetInfoType::PersonalMmHeapUsage:
  629. case GetInfoType::TitleId:
  630. case GetInfoType::UserExceptionContextAddr: {
  631. if (info_sub_id != 0) {
  632. return ERR_INVALID_ENUM_VALUE;
  633. }
  634. const auto& current_process_handle_table = Core::CurrentProcess()->GetHandleTable();
  635. const auto process = current_process_handle_table.Get<Process>(static_cast<Handle>(handle));
  636. if (!process) {
  637. return ERR_INVALID_HANDLE;
  638. }
  639. switch (info_id_type) {
  640. case GetInfoType::AllowedCPUCoreMask:
  641. *result = process->GetCoreMask();
  642. return RESULT_SUCCESS;
  643. case GetInfoType::AllowedThreadPriorityMask:
  644. *result = process->GetPriorityMask();
  645. return RESULT_SUCCESS;
  646. case GetInfoType::MapRegionBaseAddr:
  647. *result = process->VMManager().GetMapRegionBaseAddress();
  648. return RESULT_SUCCESS;
  649. case GetInfoType::MapRegionSize:
  650. *result = process->VMManager().GetMapRegionSize();
  651. return RESULT_SUCCESS;
  652. case GetInfoType::HeapRegionBaseAddr:
  653. *result = process->VMManager().GetHeapRegionBaseAddress();
  654. return RESULT_SUCCESS;
  655. case GetInfoType::HeapRegionSize:
  656. *result = process->VMManager().GetHeapRegionSize();
  657. return RESULT_SUCCESS;
  658. case GetInfoType::ASLRRegionBaseAddr:
  659. *result = process->VMManager().GetASLRRegionBaseAddress();
  660. return RESULT_SUCCESS;
  661. case GetInfoType::ASLRRegionSize:
  662. *result = process->VMManager().GetASLRRegionSize();
  663. return RESULT_SUCCESS;
  664. case GetInfoType::NewMapRegionBaseAddr:
  665. *result = process->VMManager().GetNewMapRegionBaseAddress();
  666. return RESULT_SUCCESS;
  667. case GetInfoType::NewMapRegionSize:
  668. *result = process->VMManager().GetNewMapRegionSize();
  669. return RESULT_SUCCESS;
  670. case GetInfoType::TotalMemoryUsage:
  671. *result = process->VMManager().GetTotalMemoryUsage();
  672. return RESULT_SUCCESS;
  673. case GetInfoType::TotalHeapUsage:
  674. *result = process->VMManager().GetTotalHeapUsage();
  675. return RESULT_SUCCESS;
  676. case GetInfoType::IsVirtualAddressMemoryEnabled:
  677. *result = process->IsVirtualMemoryEnabled();
  678. return RESULT_SUCCESS;
  679. case GetInfoType::TitleId:
  680. *result = process->GetTitleID();
  681. return RESULT_SUCCESS;
  682. case GetInfoType::UserExceptionContextAddr:
  683. LOG_WARNING(Kernel_SVC,
  684. "(STUBBED) Attempted to query user exception context address, returned 0");
  685. *result = 0;
  686. return RESULT_SUCCESS;
  687. default:
  688. break;
  689. }
  690. LOG_WARNING(Kernel_SVC, "(STUBBED) Unimplemented svcGetInfo id=0x{:016X}", info_id);
  691. return ERR_INVALID_ENUM_VALUE;
  692. }
  693. case GetInfoType::IsCurrentProcessBeingDebugged:
  694. *result = 0;
  695. return RESULT_SUCCESS;
  696. case GetInfoType::RegisterResourceLimit: {
  697. if (handle != 0) {
  698. return ERR_INVALID_HANDLE;
  699. }
  700. if (info_sub_id != 0) {
  701. return ERR_INVALID_COMBINATION;
  702. }
  703. Process* const current_process = Core::CurrentProcess();
  704. HandleTable& handle_table = current_process->GetHandleTable();
  705. const auto resource_limit = current_process->GetResourceLimit();
  706. if (!resource_limit) {
  707. *result = KernelHandle::InvalidHandle;
  708. // Yes, the kernel considers this a successful operation.
  709. return RESULT_SUCCESS;
  710. }
  711. const auto table_result = handle_table.Create(resource_limit);
  712. if (table_result.Failed()) {
  713. return table_result.Code();
  714. }
  715. *result = *table_result;
  716. return RESULT_SUCCESS;
  717. }
  718. case GetInfoType::RandomEntropy:
  719. if (handle != 0) {
  720. LOG_ERROR(Kernel_SVC, "Process Handle is non zero, expected 0 result but got {:016X}",
  721. handle);
  722. return ERR_INVALID_HANDLE;
  723. }
  724. if (info_sub_id >= Process::RANDOM_ENTROPY_SIZE) {
  725. LOG_ERROR(Kernel_SVC, "Entropy size is out of range, expected {} but got {}",
  726. Process::RANDOM_ENTROPY_SIZE, info_sub_id);
  727. return ERR_INVALID_COMBINATION;
  728. }
  729. *result = Core::CurrentProcess()->GetRandomEntropy(info_sub_id);
  730. return RESULT_SUCCESS;
  731. case GetInfoType::PrivilegedProcessId:
  732. LOG_WARNING(Kernel_SVC,
  733. "(STUBBED) Attempted to query privileged process id bounds, returned 0");
  734. *result = 0;
  735. return RESULT_SUCCESS;
  736. case GetInfoType::ThreadTickCount: {
  737. constexpr u64 num_cpus = 4;
  738. if (info_sub_id != 0xFFFFFFFFFFFFFFFF && info_sub_id >= num_cpus) {
  739. LOG_ERROR(Kernel_SVC, "Core count is out of range, expected {} but got {}", num_cpus,
  740. info_sub_id);
  741. return ERR_INVALID_COMBINATION;
  742. }
  743. const auto thread =
  744. Core::CurrentProcess()->GetHandleTable().Get<Thread>(static_cast<Handle>(handle));
  745. if (!thread) {
  746. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}",
  747. static_cast<Handle>(handle));
  748. return ERR_INVALID_HANDLE;
  749. }
  750. const auto& system = Core::System::GetInstance();
  751. const auto& core_timing = system.CoreTiming();
  752. const auto& scheduler = system.CurrentScheduler();
  753. const auto* const current_thread = scheduler.GetCurrentThread();
  754. const bool same_thread = current_thread == thread;
  755. const u64 prev_ctx_ticks = scheduler.GetLastContextSwitchTicks();
  756. u64 out_ticks = 0;
  757. if (same_thread && info_sub_id == 0xFFFFFFFFFFFFFFFF) {
  758. const u64 thread_ticks = current_thread->GetTotalCPUTimeTicks();
  759. out_ticks = thread_ticks + (core_timing.GetTicks() - prev_ctx_ticks);
  760. } else if (same_thread && info_sub_id == system.CurrentCoreIndex()) {
  761. out_ticks = core_timing.GetTicks() - prev_ctx_ticks;
  762. }
  763. *result = out_ticks;
  764. return RESULT_SUCCESS;
  765. }
  766. default:
  767. LOG_WARNING(Kernel_SVC, "(STUBBED) Unimplemented svcGetInfo id=0x{:016X}", info_id);
  768. return ERR_INVALID_ENUM_VALUE;
  769. }
  770. }
  771. /// Sets the thread activity
  772. static ResultCode SetThreadActivity(Handle handle, u32 activity) {
  773. LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, activity=0x{:08X}", handle, activity);
  774. if (activity > static_cast<u32>(ThreadActivity::Paused)) {
  775. return ERR_INVALID_ENUM_VALUE;
  776. }
  777. const auto* current_process = Core::CurrentProcess();
  778. const SharedPtr<Thread> thread = current_process->GetHandleTable().Get<Thread>(handle);
  779. if (!thread) {
  780. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}", handle);
  781. return ERR_INVALID_HANDLE;
  782. }
  783. if (thread->GetOwnerProcess() != current_process) {
  784. LOG_ERROR(Kernel_SVC,
  785. "The current process does not own the current thread, thread_handle={:08X} "
  786. "thread_pid={}, "
  787. "current_process_pid={}",
  788. handle, thread->GetOwnerProcess()->GetProcessID(),
  789. current_process->GetProcessID());
  790. return ERR_INVALID_HANDLE;
  791. }
  792. if (thread == GetCurrentThread()) {
  793. LOG_ERROR(Kernel_SVC, "The thread handle specified is the current running thread");
  794. return ERR_BUSY;
  795. }
  796. thread->SetActivity(static_cast<ThreadActivity>(activity));
  797. return RESULT_SUCCESS;
  798. }
  799. /// Gets the thread context
  800. static ResultCode GetThreadContext(VAddr thread_context, Handle handle) {
  801. LOG_DEBUG(Kernel_SVC, "called, context=0x{:08X}, thread=0x{:X}", thread_context, handle);
  802. const auto* current_process = Core::CurrentProcess();
  803. const SharedPtr<Thread> thread = current_process->GetHandleTable().Get<Thread>(handle);
  804. if (!thread) {
  805. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}", handle);
  806. return ERR_INVALID_HANDLE;
  807. }
  808. if (thread->GetOwnerProcess() != current_process) {
  809. LOG_ERROR(Kernel_SVC,
  810. "The current process does not own the current thread, thread_handle={:08X} "
  811. "thread_pid={}, "
  812. "current_process_pid={}",
  813. handle, thread->GetOwnerProcess()->GetProcessID(),
  814. current_process->GetProcessID());
  815. return ERR_INVALID_HANDLE;
  816. }
  817. if (thread == GetCurrentThread()) {
  818. LOG_ERROR(Kernel_SVC, "The thread handle specified is the current running thread");
  819. return ERR_BUSY;
  820. }
  821. Core::ARM_Interface::ThreadContext ctx = thread->GetContext();
  822. // Mask away mode bits, interrupt bits, IL bit, and other reserved bits.
  823. ctx.pstate &= 0xFF0FFE20;
  824. // If 64-bit, we can just write the context registers directly and we're good.
  825. // However, if 32-bit, we have to ensure some registers are zeroed out.
  826. if (!current_process->Is64BitProcess()) {
  827. std::fill(ctx.cpu_registers.begin() + 15, ctx.cpu_registers.end(), 0);
  828. std::fill(ctx.vector_registers.begin() + 16, ctx.vector_registers.end(), u128{});
  829. }
  830. Memory::WriteBlock(thread_context, &ctx, sizeof(ctx));
  831. return RESULT_SUCCESS;
  832. }
  833. /// Gets the priority for the specified thread
  834. static ResultCode GetThreadPriority(u32* priority, Handle handle) {
  835. LOG_TRACE(Kernel_SVC, "called");
  836. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  837. const SharedPtr<Thread> thread = handle_table.Get<Thread>(handle);
  838. if (!thread) {
  839. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}", handle);
  840. return ERR_INVALID_HANDLE;
  841. }
  842. *priority = thread->GetPriority();
  843. return RESULT_SUCCESS;
  844. }
  845. /// Sets the priority for the specified thread
  846. static ResultCode SetThreadPriority(Handle handle, u32 priority) {
  847. LOG_TRACE(Kernel_SVC, "called");
  848. if (priority > THREADPRIO_LOWEST) {
  849. LOG_ERROR(
  850. Kernel_SVC,
  851. "An invalid priority was specified, expected {} but got {} for thread_handle={:08X}",
  852. THREADPRIO_LOWEST, priority, handle);
  853. return ERR_INVALID_THREAD_PRIORITY;
  854. }
  855. const auto* const current_process = Core::CurrentProcess();
  856. SharedPtr<Thread> thread = current_process->GetHandleTable().Get<Thread>(handle);
  857. if (!thread) {
  858. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}", handle);
  859. return ERR_INVALID_HANDLE;
  860. }
  861. thread->SetPriority(priority);
  862. Core::System::GetInstance().CpuCore(thread->GetProcessorID()).PrepareReschedule();
  863. return RESULT_SUCCESS;
  864. }
  865. /// Get which CPU core is executing the current thread
  866. static u32 GetCurrentProcessorNumber() {
  867. LOG_TRACE(Kernel_SVC, "called");
  868. return GetCurrentThread()->GetProcessorID();
  869. }
  870. static ResultCode MapSharedMemory(Handle shared_memory_handle, VAddr addr, u64 size,
  871. u32 permissions) {
  872. LOG_TRACE(Kernel_SVC,
  873. "called, shared_memory_handle=0x{:X}, addr=0x{:X}, size=0x{:X}, permissions=0x{:08X}",
  874. shared_memory_handle, addr, size, permissions);
  875. if (!Common::Is4KBAligned(addr)) {
  876. LOG_ERROR(Kernel_SVC, "Address is not aligned to 4KB, addr=0x{:016X}", addr);
  877. return ERR_INVALID_ADDRESS;
  878. }
  879. if (size == 0) {
  880. LOG_ERROR(Kernel_SVC, "Size is 0");
  881. return ERR_INVALID_SIZE;
  882. }
  883. if (!Common::Is4KBAligned(size)) {
  884. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, size=0x{:016X}", size);
  885. return ERR_INVALID_SIZE;
  886. }
  887. if (!IsValidAddressRange(addr, size)) {
  888. LOG_ERROR(Kernel_SVC, "Region is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
  889. addr, size);
  890. return ERR_INVALID_ADDRESS_STATE;
  891. }
  892. const auto permissions_type = static_cast<MemoryPermission>(permissions);
  893. if (permissions_type != MemoryPermission::Read &&
  894. permissions_type != MemoryPermission::ReadWrite) {
  895. LOG_ERROR(Kernel_SVC, "Expected Read or ReadWrite permission but got permissions=0x{:08X}",
  896. permissions);
  897. return ERR_INVALID_MEMORY_PERMISSIONS;
  898. }
  899. auto* const current_process = Core::CurrentProcess();
  900. auto shared_memory = current_process->GetHandleTable().Get<SharedMemory>(shared_memory_handle);
  901. if (!shared_memory) {
  902. LOG_ERROR(Kernel_SVC, "Shared memory does not exist, shared_memory_handle=0x{:08X}",
  903. shared_memory_handle);
  904. return ERR_INVALID_HANDLE;
  905. }
  906. const auto& vm_manager = current_process->VMManager();
  907. if (!vm_manager.IsWithinASLRRegion(addr, size)) {
  908. LOG_ERROR(Kernel_SVC, "Region is not within the ASLR region. addr=0x{:016X}, size={:016X}",
  909. addr, size);
  910. return ERR_INVALID_MEMORY_RANGE;
  911. }
  912. return shared_memory->Map(*current_process, addr, permissions_type, MemoryPermission::DontCare);
  913. }
  914. static ResultCode UnmapSharedMemory(Handle shared_memory_handle, VAddr addr, u64 size) {
  915. LOG_WARNING(Kernel_SVC, "called, shared_memory_handle=0x{:08X}, addr=0x{:X}, size=0x{:X}",
  916. shared_memory_handle, addr, size);
  917. if (!Common::Is4KBAligned(addr)) {
  918. LOG_ERROR(Kernel_SVC, "Address is not aligned to 4KB, addr=0x{:016X}", addr);
  919. return ERR_INVALID_ADDRESS;
  920. }
  921. if (size == 0) {
  922. LOG_ERROR(Kernel_SVC, "Size is 0");
  923. return ERR_INVALID_SIZE;
  924. }
  925. if (!Common::Is4KBAligned(size)) {
  926. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, size=0x{:016X}", size);
  927. return ERR_INVALID_SIZE;
  928. }
  929. if (!IsValidAddressRange(addr, size)) {
  930. LOG_ERROR(Kernel_SVC, "Region is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
  931. addr, size);
  932. return ERR_INVALID_ADDRESS_STATE;
  933. }
  934. auto* const current_process = Core::CurrentProcess();
  935. auto shared_memory = current_process->GetHandleTable().Get<SharedMemory>(shared_memory_handle);
  936. if (!shared_memory) {
  937. LOG_ERROR(Kernel_SVC, "Shared memory does not exist, shared_memory_handle=0x{:08X}",
  938. shared_memory_handle);
  939. return ERR_INVALID_HANDLE;
  940. }
  941. const auto& vm_manager = current_process->VMManager();
  942. if (!vm_manager.IsWithinASLRRegion(addr, size)) {
  943. LOG_ERROR(Kernel_SVC, "Region is not within the ASLR region. addr=0x{:016X}, size={:016X}",
  944. addr, size);
  945. return ERR_INVALID_MEMORY_RANGE;
  946. }
  947. return shared_memory->Unmap(*current_process, addr);
  948. }
  949. static ResultCode QueryProcessMemory(VAddr memory_info_address, VAddr page_info_address,
  950. Handle process_handle, VAddr address) {
  951. LOG_TRACE(Kernel_SVC, "called process=0x{:08X} address={:X}", process_handle, address);
  952. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  953. SharedPtr<Process> process = handle_table.Get<Process>(process_handle);
  954. if (!process) {
  955. LOG_ERROR(Kernel_SVC, "Process handle does not exist, process_handle=0x{:08X}",
  956. process_handle);
  957. return ERR_INVALID_HANDLE;
  958. }
  959. const auto& vm_manager = process->VMManager();
  960. const MemoryInfo memory_info = vm_manager.QueryMemory(address);
  961. Memory::Write64(memory_info_address, memory_info.base_address);
  962. Memory::Write64(memory_info_address + 8, memory_info.size);
  963. Memory::Write32(memory_info_address + 16, memory_info.state);
  964. Memory::Write32(memory_info_address + 20, memory_info.attributes);
  965. Memory::Write32(memory_info_address + 24, memory_info.permission);
  966. Memory::Write32(memory_info_address + 32, memory_info.ipc_ref_count);
  967. Memory::Write32(memory_info_address + 28, memory_info.device_ref_count);
  968. Memory::Write32(memory_info_address + 36, 0);
  969. // Page info appears to be currently unused by the kernel and is always set to zero.
  970. Memory::Write32(page_info_address, 0);
  971. return RESULT_SUCCESS;
  972. }
  973. static ResultCode QueryMemory(VAddr memory_info_address, VAddr page_info_address,
  974. VAddr query_address) {
  975. LOG_TRACE(Kernel_SVC,
  976. "called, memory_info_address=0x{:016X}, page_info_address=0x{:016X}, "
  977. "query_address=0x{:016X}",
  978. memory_info_address, page_info_address, query_address);
  979. return QueryProcessMemory(memory_info_address, page_info_address, CurrentProcess,
  980. query_address);
  981. }
  982. /// Exits the current process
  983. static void ExitProcess() {
  984. auto* current_process = Core::CurrentProcess();
  985. LOG_INFO(Kernel_SVC, "Process {} exiting", current_process->GetProcessID());
  986. ASSERT_MSG(current_process->GetStatus() == ProcessStatus::Running,
  987. "Process has already exited");
  988. current_process->PrepareForTermination();
  989. // Kill the current thread
  990. GetCurrentThread()->Stop();
  991. Core::System::GetInstance().PrepareReschedule();
  992. }
  993. /// Creates a new thread
  994. static ResultCode CreateThread(Handle* out_handle, VAddr entry_point, u64 arg, VAddr stack_top,
  995. u32 priority, s32 processor_id) {
  996. LOG_TRACE(Kernel_SVC,
  997. "called entrypoint=0x{:08X}, arg=0x{:08X}, stacktop=0x{:08X}, "
  998. "threadpriority=0x{:08X}, processorid=0x{:08X} : created handle=0x{:08X}",
  999. entry_point, arg, stack_top, priority, processor_id, *out_handle);
  1000. auto* const current_process = Core::CurrentProcess();
  1001. if (processor_id == THREADPROCESSORID_IDEAL) {
  1002. // Set the target CPU to the one specified by the process.
  1003. processor_id = current_process->GetIdealCore();
  1004. ASSERT(processor_id != THREADPROCESSORID_IDEAL);
  1005. }
  1006. if (processor_id < THREADPROCESSORID_0 || processor_id > THREADPROCESSORID_3) {
  1007. LOG_ERROR(Kernel_SVC, "Invalid thread processor ID: {}", processor_id);
  1008. return ERR_INVALID_PROCESSOR_ID;
  1009. }
  1010. const u64 core_mask = current_process->GetCoreMask();
  1011. if ((core_mask | (1ULL << processor_id)) != core_mask) {
  1012. LOG_ERROR(Kernel_SVC, "Invalid thread core specified ({})", processor_id);
  1013. return ERR_INVALID_PROCESSOR_ID;
  1014. }
  1015. if (priority > THREADPRIO_LOWEST) {
  1016. LOG_ERROR(Kernel_SVC,
  1017. "Invalid thread priority specified ({}). Must be within the range 0-64",
  1018. priority);
  1019. return ERR_INVALID_THREAD_PRIORITY;
  1020. }
  1021. if (((1ULL << priority) & current_process->GetPriorityMask()) == 0) {
  1022. LOG_ERROR(Kernel_SVC, "Invalid thread priority specified ({})", priority);
  1023. return ERR_INVALID_THREAD_PRIORITY;
  1024. }
  1025. const std::string name = fmt::format("thread-{:X}", entry_point);
  1026. auto& kernel = Core::System::GetInstance().Kernel();
  1027. CASCADE_RESULT(SharedPtr<Thread> thread,
  1028. Thread::Create(kernel, name, entry_point, priority, arg, processor_id, stack_top,
  1029. *current_process));
  1030. const auto new_guest_handle = current_process->GetHandleTable().Create(thread);
  1031. if (new_guest_handle.Failed()) {
  1032. LOG_ERROR(Kernel_SVC, "Failed to create handle with error=0x{:X}",
  1033. new_guest_handle.Code().raw);
  1034. return new_guest_handle.Code();
  1035. }
  1036. thread->SetGuestHandle(*new_guest_handle);
  1037. *out_handle = *new_guest_handle;
  1038. Core::System::GetInstance().CpuCore(thread->GetProcessorID()).PrepareReschedule();
  1039. return RESULT_SUCCESS;
  1040. }
  1041. /// Starts the thread for the provided handle
  1042. static ResultCode StartThread(Handle thread_handle) {
  1043. LOG_TRACE(Kernel_SVC, "called thread=0x{:08X}", thread_handle);
  1044. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  1045. const SharedPtr<Thread> thread = handle_table.Get<Thread>(thread_handle);
  1046. if (!thread) {
  1047. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, thread_handle=0x{:08X}",
  1048. thread_handle);
  1049. return ERR_INVALID_HANDLE;
  1050. }
  1051. ASSERT(thread->GetStatus() == ThreadStatus::Dormant);
  1052. thread->ResumeFromWait();
  1053. if (thread->GetStatus() == ThreadStatus::Ready) {
  1054. Core::System::GetInstance().CpuCore(thread->GetProcessorID()).PrepareReschedule();
  1055. }
  1056. return RESULT_SUCCESS;
  1057. }
  1058. /// Called when a thread exits
  1059. static void ExitThread() {
  1060. auto& system = Core::System::GetInstance();
  1061. LOG_TRACE(Kernel_SVC, "called, pc=0x{:08X}", system.CurrentArmInterface().GetPC());
  1062. auto* const current_thread = system.CurrentScheduler().GetCurrentThread();
  1063. current_thread->Stop();
  1064. system.CurrentScheduler().RemoveThread(current_thread);
  1065. system.PrepareReschedule();
  1066. }
  1067. /// Sleep the current thread
  1068. static void SleepThread(s64 nanoseconds) {
  1069. LOG_TRACE(Kernel_SVC, "called nanoseconds={}", nanoseconds);
  1070. enum class SleepType : s64 {
  1071. YieldWithoutLoadBalancing = 0,
  1072. YieldWithLoadBalancing = -1,
  1073. YieldAndWaitForLoadBalancing = -2,
  1074. };
  1075. auto& system = Core::System::GetInstance();
  1076. auto& scheduler = system.CurrentScheduler();
  1077. auto* const current_thread = scheduler.GetCurrentThread();
  1078. if (nanoseconds <= 0) {
  1079. switch (static_cast<SleepType>(nanoseconds)) {
  1080. case SleepType::YieldWithoutLoadBalancing:
  1081. scheduler.YieldWithoutLoadBalancing(current_thread);
  1082. break;
  1083. case SleepType::YieldWithLoadBalancing:
  1084. scheduler.YieldWithLoadBalancing(current_thread);
  1085. break;
  1086. case SleepType::YieldAndWaitForLoadBalancing:
  1087. scheduler.YieldAndWaitForLoadBalancing(current_thread);
  1088. break;
  1089. default:
  1090. UNREACHABLE_MSG("Unimplemented sleep yield type '{:016X}'!", nanoseconds);
  1091. }
  1092. } else {
  1093. current_thread->Sleep(nanoseconds);
  1094. }
  1095. // Reschedule all CPU cores
  1096. for (std::size_t i = 0; i < Core::NUM_CPU_CORES; ++i) {
  1097. system.CpuCore(i).PrepareReschedule();
  1098. }
  1099. }
  1100. /// Wait process wide key atomic
  1101. static ResultCode WaitProcessWideKeyAtomic(VAddr mutex_addr, VAddr condition_variable_addr,
  1102. Handle thread_handle, s64 nano_seconds) {
  1103. LOG_TRACE(
  1104. Kernel_SVC,
  1105. "called mutex_addr={:X}, condition_variable_addr={:X}, thread_handle=0x{:08X}, timeout={}",
  1106. mutex_addr, condition_variable_addr, thread_handle, nano_seconds);
  1107. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  1108. SharedPtr<Thread> thread = handle_table.Get<Thread>(thread_handle);
  1109. ASSERT(thread);
  1110. CASCADE_CODE(Mutex::Release(mutex_addr));
  1111. SharedPtr<Thread> current_thread = GetCurrentThread();
  1112. current_thread->SetCondVarWaitAddress(condition_variable_addr);
  1113. current_thread->SetMutexWaitAddress(mutex_addr);
  1114. current_thread->SetWaitHandle(thread_handle);
  1115. current_thread->SetStatus(ThreadStatus::WaitCondVar);
  1116. current_thread->InvalidateWakeupCallback();
  1117. current_thread->WakeAfterDelay(nano_seconds);
  1118. // Note: Deliberately don't attempt to inherit the lock owner's priority.
  1119. Core::System::GetInstance().CpuCore(current_thread->GetProcessorID()).PrepareReschedule();
  1120. return RESULT_SUCCESS;
  1121. }
  1122. /// Signal process wide key
  1123. static ResultCode SignalProcessWideKey(VAddr condition_variable_addr, s32 target) {
  1124. LOG_TRACE(Kernel_SVC, "called, condition_variable_addr=0x{:X}, target=0x{:08X}",
  1125. condition_variable_addr, target);
  1126. const auto RetrieveWaitingThreads = [](std::size_t core_index,
  1127. std::vector<SharedPtr<Thread>>& waiting_threads,
  1128. VAddr condvar_addr) {
  1129. const auto& scheduler = Core::System::GetInstance().Scheduler(core_index);
  1130. const auto& thread_list = scheduler.GetThreadList();
  1131. for (const auto& thread : thread_list) {
  1132. if (thread->GetCondVarWaitAddress() == condvar_addr)
  1133. waiting_threads.push_back(thread);
  1134. }
  1135. };
  1136. // Retrieve a list of all threads that are waiting for this condition variable.
  1137. std::vector<SharedPtr<Thread>> waiting_threads;
  1138. RetrieveWaitingThreads(0, waiting_threads, condition_variable_addr);
  1139. RetrieveWaitingThreads(1, waiting_threads, condition_variable_addr);
  1140. RetrieveWaitingThreads(2, waiting_threads, condition_variable_addr);
  1141. RetrieveWaitingThreads(3, waiting_threads, condition_variable_addr);
  1142. // Sort them by priority, such that the highest priority ones come first.
  1143. std::sort(waiting_threads.begin(), waiting_threads.end(),
  1144. [](const SharedPtr<Thread>& lhs, const SharedPtr<Thread>& rhs) {
  1145. return lhs->GetPriority() < rhs->GetPriority();
  1146. });
  1147. // Only process up to 'target' threads, unless 'target' is -1, in which case process
  1148. // them all.
  1149. std::size_t last = waiting_threads.size();
  1150. if (target != -1)
  1151. last = std::min(waiting_threads.size(), static_cast<std::size_t>(target));
  1152. // If there are no threads waiting on this condition variable, just exit
  1153. if (last == 0)
  1154. return RESULT_SUCCESS;
  1155. for (std::size_t index = 0; index < last; ++index) {
  1156. auto& thread = waiting_threads[index];
  1157. ASSERT(thread->GetCondVarWaitAddress() == condition_variable_addr);
  1158. // liberate Cond Var Thread.
  1159. thread->SetCondVarWaitAddress(0);
  1160. std::size_t current_core = Core::System::GetInstance().CurrentCoreIndex();
  1161. auto& monitor = Core::System::GetInstance().Monitor();
  1162. // Atomically read the value of the mutex.
  1163. u32 mutex_val = 0;
  1164. do {
  1165. monitor.SetExclusive(current_core, thread->GetMutexWaitAddress());
  1166. // If the mutex is not yet acquired, acquire it.
  1167. mutex_val = Memory::Read32(thread->GetMutexWaitAddress());
  1168. if (mutex_val != 0) {
  1169. monitor.ClearExclusive();
  1170. break;
  1171. }
  1172. } while (!monitor.ExclusiveWrite32(current_core, thread->GetMutexWaitAddress(),
  1173. thread->GetWaitHandle()));
  1174. if (mutex_val == 0) {
  1175. // We were able to acquire the mutex, resume this thread.
  1176. ASSERT(thread->GetStatus() == ThreadStatus::WaitCondVar);
  1177. thread->ResumeFromWait();
  1178. auto* const lock_owner = thread->GetLockOwner();
  1179. if (lock_owner != nullptr) {
  1180. lock_owner->RemoveMutexWaiter(thread);
  1181. }
  1182. thread->SetLockOwner(nullptr);
  1183. thread->SetMutexWaitAddress(0);
  1184. thread->SetWaitHandle(0);
  1185. Core::System::GetInstance().CpuCore(thread->GetProcessorID()).PrepareReschedule();
  1186. } else {
  1187. // Atomically signal that the mutex now has a waiting thread.
  1188. do {
  1189. monitor.SetExclusive(current_core, thread->GetMutexWaitAddress());
  1190. // Ensure that the mutex value is still what we expect.
  1191. u32 value = Memory::Read32(thread->GetMutexWaitAddress());
  1192. // TODO(Subv): When this happens, the kernel just clears the exclusive state and
  1193. // retries the initial read for this thread.
  1194. ASSERT_MSG(mutex_val == value, "Unhandled synchronization primitive case");
  1195. } while (!monitor.ExclusiveWrite32(current_core, thread->GetMutexWaitAddress(),
  1196. mutex_val | Mutex::MutexHasWaitersFlag));
  1197. // The mutex is already owned by some other thread, make this thread wait on it.
  1198. const Handle owner_handle = static_cast<Handle>(mutex_val & Mutex::MutexOwnerMask);
  1199. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  1200. auto owner = handle_table.Get<Thread>(owner_handle);
  1201. ASSERT(owner);
  1202. ASSERT(thread->GetStatus() == ThreadStatus::WaitCondVar);
  1203. thread->InvalidateWakeupCallback();
  1204. thread->SetStatus(ThreadStatus::WaitMutex);
  1205. owner->AddMutexWaiter(thread);
  1206. }
  1207. }
  1208. return RESULT_SUCCESS;
  1209. }
  1210. // Wait for an address (via Address Arbiter)
  1211. static ResultCode WaitForAddress(VAddr address, u32 type, s32 value, s64 timeout) {
  1212. LOG_WARNING(Kernel_SVC, "called, address=0x{:X}, type=0x{:X}, value=0x{:X}, timeout={}",
  1213. address, type, value, timeout);
  1214. // If the passed address is a kernel virtual address, return invalid memory state.
  1215. if (Memory::IsKernelVirtualAddress(address)) {
  1216. LOG_ERROR(Kernel_SVC, "Address is a kernel virtual address, address={:016X}", address);
  1217. return ERR_INVALID_ADDRESS_STATE;
  1218. }
  1219. // If the address is not properly aligned to 4 bytes, return invalid address.
  1220. if (!Common::IsWordAligned(address)) {
  1221. LOG_ERROR(Kernel_SVC, "Address is not word aligned, address={:016X}", address);
  1222. return ERR_INVALID_ADDRESS;
  1223. }
  1224. const auto arbitration_type = static_cast<AddressArbiter::ArbitrationType>(type);
  1225. auto& address_arbiter =
  1226. Core::System::GetInstance().Kernel().CurrentProcess()->GetAddressArbiter();
  1227. return address_arbiter.WaitForAddress(address, arbitration_type, value, timeout);
  1228. }
  1229. // Signals to an address (via Address Arbiter)
  1230. static ResultCode SignalToAddress(VAddr address, u32 type, s32 value, s32 num_to_wake) {
  1231. LOG_WARNING(Kernel_SVC, "called, address=0x{:X}, type=0x{:X}, value=0x{:X}, num_to_wake=0x{:X}",
  1232. address, type, value, num_to_wake);
  1233. // If the passed address is a kernel virtual address, return invalid memory state.
  1234. if (Memory::IsKernelVirtualAddress(address)) {
  1235. LOG_ERROR(Kernel_SVC, "Address is a kernel virtual address, address={:016X}", address);
  1236. return ERR_INVALID_ADDRESS_STATE;
  1237. }
  1238. // If the address is not properly aligned to 4 bytes, return invalid address.
  1239. if (!Common::IsWordAligned(address)) {
  1240. LOG_ERROR(Kernel_SVC, "Address is not word aligned, address={:016X}", address);
  1241. return ERR_INVALID_ADDRESS;
  1242. }
  1243. const auto signal_type = static_cast<AddressArbiter::SignalType>(type);
  1244. auto& address_arbiter =
  1245. Core::System::GetInstance().Kernel().CurrentProcess()->GetAddressArbiter();
  1246. return address_arbiter.SignalToAddress(address, signal_type, value, num_to_wake);
  1247. }
  1248. /// This returns the total CPU ticks elapsed since the CPU was powered-on
  1249. static u64 GetSystemTick() {
  1250. LOG_TRACE(Kernel_SVC, "called");
  1251. auto& core_timing = Core::System::GetInstance().CoreTiming();
  1252. const u64 result{core_timing.GetTicks()};
  1253. // Advance time to defeat dumb games that busy-wait for the frame to end.
  1254. core_timing.AddTicks(400);
  1255. return result;
  1256. }
  1257. /// Close a handle
  1258. static ResultCode CloseHandle(Handle handle) {
  1259. LOG_TRACE(Kernel_SVC, "Closing handle 0x{:08X}", handle);
  1260. auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  1261. return handle_table.Close(handle);
  1262. }
  1263. /// Clears the signaled state of an event or process.
  1264. static ResultCode ResetSignal(Handle handle) {
  1265. LOG_DEBUG(Kernel_SVC, "called handle 0x{:08X}", handle);
  1266. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  1267. auto event = handle_table.Get<ReadableEvent>(handle);
  1268. if (event) {
  1269. return event->Reset();
  1270. }
  1271. auto process = handle_table.Get<Process>(handle);
  1272. if (process) {
  1273. return process->ClearSignalState();
  1274. }
  1275. LOG_ERROR(Kernel_SVC, "Invalid handle (0x{:08X})", handle);
  1276. return ERR_INVALID_HANDLE;
  1277. }
  1278. /// Creates a TransferMemory object
  1279. static ResultCode CreateTransferMemory(Handle* handle, VAddr addr, u64 size, u32 permissions) {
  1280. LOG_DEBUG(Kernel_SVC, "called addr=0x{:X}, size=0x{:X}, perms=0x{:08X}", addr, size,
  1281. permissions);
  1282. if (!Common::Is4KBAligned(addr)) {
  1283. LOG_ERROR(Kernel_SVC, "Address ({:016X}) is not page aligned!", addr);
  1284. return ERR_INVALID_ADDRESS;
  1285. }
  1286. if (!Common::Is4KBAligned(size) || size == 0) {
  1287. LOG_ERROR(Kernel_SVC, "Size ({:016X}) is not page aligned or equal to zero!", size);
  1288. return ERR_INVALID_ADDRESS;
  1289. }
  1290. if (!IsValidAddressRange(addr, size)) {
  1291. LOG_ERROR(Kernel_SVC, "Address and size cause overflow! (address={:016X}, size={:016X})",
  1292. addr, size);
  1293. return ERR_INVALID_ADDRESS_STATE;
  1294. }
  1295. const auto perms = static_cast<MemoryPermission>(permissions);
  1296. if (perms != MemoryPermission::None && perms != MemoryPermission::Read &&
  1297. perms != MemoryPermission::ReadWrite) {
  1298. LOG_ERROR(Kernel_SVC, "Invalid memory permissions for transfer memory! (perms={:08X})",
  1299. permissions);
  1300. return ERR_INVALID_MEMORY_PERMISSIONS;
  1301. }
  1302. auto& kernel = Core::System::GetInstance().Kernel();
  1303. auto process = kernel.CurrentProcess();
  1304. auto& handle_table = process->GetHandleTable();
  1305. const auto shared_mem_handle = SharedMemory::Create(kernel, process, size, perms, perms, addr);
  1306. CASCADE_RESULT(*handle, handle_table.Create(shared_mem_handle));
  1307. return RESULT_SUCCESS;
  1308. }
  1309. static ResultCode GetThreadCoreMask(Handle thread_handle, u32* core, u64* mask) {
  1310. LOG_TRACE(Kernel_SVC, "called, handle=0x{:08X}", thread_handle);
  1311. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  1312. const SharedPtr<Thread> thread = handle_table.Get<Thread>(thread_handle);
  1313. if (!thread) {
  1314. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, thread_handle=0x{:08X}",
  1315. thread_handle);
  1316. return ERR_INVALID_HANDLE;
  1317. }
  1318. *core = thread->GetIdealCore();
  1319. *mask = thread->GetAffinityMask();
  1320. return RESULT_SUCCESS;
  1321. }
  1322. static ResultCode SetThreadCoreMask(Handle thread_handle, u32 core, u64 mask) {
  1323. LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, mask=0x{:016X}, core=0x{:X}", thread_handle,
  1324. mask, core);
  1325. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  1326. const SharedPtr<Thread> thread = handle_table.Get<Thread>(thread_handle);
  1327. if (!thread) {
  1328. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, thread_handle=0x{:08X}",
  1329. thread_handle);
  1330. return ERR_INVALID_HANDLE;
  1331. }
  1332. if (core == static_cast<u32>(THREADPROCESSORID_IDEAL)) {
  1333. const u8 ideal_cpu_core = thread->GetOwnerProcess()->GetIdealCore();
  1334. ASSERT(ideal_cpu_core != static_cast<u8>(THREADPROCESSORID_IDEAL));
  1335. // Set the target CPU to the ideal core specified by the process.
  1336. core = ideal_cpu_core;
  1337. mask = 1ULL << core;
  1338. }
  1339. if (mask == 0) {
  1340. LOG_ERROR(Kernel_SVC, "Mask is 0");
  1341. return ERR_INVALID_COMBINATION;
  1342. }
  1343. /// This value is used to only change the affinity mask without changing the current ideal core.
  1344. static constexpr u32 OnlyChangeMask = static_cast<u32>(-3);
  1345. if (core == OnlyChangeMask) {
  1346. core = thread->GetIdealCore();
  1347. } else if (core >= Core::NUM_CPU_CORES && core != static_cast<u32>(-1)) {
  1348. LOG_ERROR(Kernel_SVC, "Invalid core specified, got {}", core);
  1349. return ERR_INVALID_PROCESSOR_ID;
  1350. }
  1351. // Error out if the input core isn't enabled in the input mask.
  1352. if (core < Core::NUM_CPU_CORES && (mask & (1ull << core)) == 0) {
  1353. LOG_ERROR(Kernel_SVC, "Core is not enabled for the current mask, core={}, mask={:016X}",
  1354. core, mask);
  1355. return ERR_INVALID_COMBINATION;
  1356. }
  1357. thread->ChangeCore(core, mask);
  1358. return RESULT_SUCCESS;
  1359. }
  1360. static ResultCode CreateSharedMemory(Handle* handle, u64 size, u32 local_permissions,
  1361. u32 remote_permissions) {
  1362. LOG_TRACE(Kernel_SVC, "called, size=0x{:X}, localPerms=0x{:08X}, remotePerms=0x{:08X}", size,
  1363. local_permissions, remote_permissions);
  1364. if (size == 0) {
  1365. LOG_ERROR(Kernel_SVC, "Size is 0");
  1366. return ERR_INVALID_SIZE;
  1367. }
  1368. if (!Common::Is4KBAligned(size)) {
  1369. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, 0x{:016X}", size);
  1370. return ERR_INVALID_SIZE;
  1371. }
  1372. if (size >= MAIN_MEMORY_SIZE) {
  1373. LOG_ERROR(Kernel_SVC, "Size is not less than 8GB, 0x{:016X}", size);
  1374. return ERR_INVALID_SIZE;
  1375. }
  1376. const auto local_perms = static_cast<MemoryPermission>(local_permissions);
  1377. if (local_perms != MemoryPermission::Read && local_perms != MemoryPermission::ReadWrite) {
  1378. LOG_ERROR(Kernel_SVC,
  1379. "Invalid local memory permissions, expected Read or ReadWrite but got "
  1380. "local_permissions={}",
  1381. static_cast<u32>(local_permissions));
  1382. return ERR_INVALID_MEMORY_PERMISSIONS;
  1383. }
  1384. const auto remote_perms = static_cast<MemoryPermission>(remote_permissions);
  1385. if (remote_perms != MemoryPermission::Read && remote_perms != MemoryPermission::ReadWrite &&
  1386. remote_perms != MemoryPermission::DontCare) {
  1387. LOG_ERROR(Kernel_SVC,
  1388. "Invalid remote memory permissions, expected Read, ReadWrite or DontCare but got "
  1389. "remote_permissions={}",
  1390. static_cast<u32>(remote_permissions));
  1391. return ERR_INVALID_MEMORY_PERMISSIONS;
  1392. }
  1393. auto& kernel = Core::System::GetInstance().Kernel();
  1394. auto process = kernel.CurrentProcess();
  1395. auto& handle_table = process->GetHandleTable();
  1396. auto shared_mem_handle = SharedMemory::Create(kernel, process, size, local_perms, remote_perms);
  1397. CASCADE_RESULT(*handle, handle_table.Create(shared_mem_handle));
  1398. return RESULT_SUCCESS;
  1399. }
  1400. static ResultCode CreateEvent(Handle* write_handle, Handle* read_handle) {
  1401. LOG_DEBUG(Kernel_SVC, "called");
  1402. auto& kernel = Core::System::GetInstance().Kernel();
  1403. const auto [readable_event, writable_event] =
  1404. WritableEvent::CreateEventPair(kernel, ResetType::Sticky, "CreateEvent");
  1405. HandleTable& handle_table = kernel.CurrentProcess()->GetHandleTable();
  1406. const auto write_create_result = handle_table.Create(writable_event);
  1407. if (write_create_result.Failed()) {
  1408. return write_create_result.Code();
  1409. }
  1410. *write_handle = *write_create_result;
  1411. const auto read_create_result = handle_table.Create(readable_event);
  1412. if (read_create_result.Failed()) {
  1413. handle_table.Close(*write_create_result);
  1414. return read_create_result.Code();
  1415. }
  1416. *read_handle = *read_create_result;
  1417. LOG_DEBUG(Kernel_SVC,
  1418. "successful. Writable event handle=0x{:08X}, Readable event handle=0x{:08X}",
  1419. *write_create_result, *read_create_result);
  1420. return RESULT_SUCCESS;
  1421. }
  1422. static ResultCode ClearEvent(Handle handle) {
  1423. LOG_TRACE(Kernel_SVC, "called, event=0x{:08X}", handle);
  1424. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  1425. auto writable_event = handle_table.Get<WritableEvent>(handle);
  1426. if (writable_event) {
  1427. writable_event->Clear();
  1428. return RESULT_SUCCESS;
  1429. }
  1430. auto readable_event = handle_table.Get<ReadableEvent>(handle);
  1431. if (readable_event) {
  1432. readable_event->Clear();
  1433. return RESULT_SUCCESS;
  1434. }
  1435. LOG_ERROR(Kernel_SVC, "Event handle does not exist, handle=0x{:08X}", handle);
  1436. return ERR_INVALID_HANDLE;
  1437. }
  1438. static ResultCode SignalEvent(Handle handle) {
  1439. LOG_DEBUG(Kernel_SVC, "called. Handle=0x{:08X}", handle);
  1440. HandleTable& handle_table = Core::CurrentProcess()->GetHandleTable();
  1441. auto writable_event = handle_table.Get<WritableEvent>(handle);
  1442. if (!writable_event) {
  1443. LOG_ERROR(Kernel_SVC, "Non-existent writable event handle used (0x{:08X})", handle);
  1444. return ERR_INVALID_HANDLE;
  1445. }
  1446. writable_event->Signal();
  1447. return RESULT_SUCCESS;
  1448. }
  1449. static ResultCode GetProcessInfo(u64* out, Handle process_handle, u32 type) {
  1450. LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, type=0x{:X}", process_handle, type);
  1451. // This function currently only allows retrieving a process' status.
  1452. enum class InfoType {
  1453. Status,
  1454. };
  1455. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  1456. const auto process = handle_table.Get<Process>(process_handle);
  1457. if (!process) {
  1458. LOG_ERROR(Kernel_SVC, "Process handle does not exist, process_handle=0x{:08X}",
  1459. process_handle);
  1460. return ERR_INVALID_HANDLE;
  1461. }
  1462. const auto info_type = static_cast<InfoType>(type);
  1463. if (info_type != InfoType::Status) {
  1464. LOG_ERROR(Kernel_SVC, "Expected info_type to be Status but got {} instead", type);
  1465. return ERR_INVALID_ENUM_VALUE;
  1466. }
  1467. *out = static_cast<u64>(process->GetStatus());
  1468. return RESULT_SUCCESS;
  1469. }
  1470. static ResultCode CreateResourceLimit(Handle* out_handle) {
  1471. LOG_DEBUG(Kernel_SVC, "called");
  1472. auto& kernel = Core::System::GetInstance().Kernel();
  1473. auto resource_limit = ResourceLimit::Create(kernel);
  1474. auto* const current_process = kernel.CurrentProcess();
  1475. ASSERT(current_process != nullptr);
  1476. const auto handle = current_process->GetHandleTable().Create(std::move(resource_limit));
  1477. if (handle.Failed()) {
  1478. return handle.Code();
  1479. }
  1480. *out_handle = *handle;
  1481. return RESULT_SUCCESS;
  1482. }
  1483. static ResultCode GetResourceLimitLimitValue(u64* out_value, Handle resource_limit,
  1484. u32 resource_type) {
  1485. LOG_DEBUG(Kernel_SVC, "called. Handle={:08X}, Resource type={}", resource_limit, resource_type);
  1486. const auto limit_value = RetrieveResourceLimitValue(resource_limit, resource_type,
  1487. ResourceLimitValueType::LimitValue);
  1488. if (limit_value.Failed()) {
  1489. return limit_value.Code();
  1490. }
  1491. *out_value = static_cast<u64>(*limit_value);
  1492. return RESULT_SUCCESS;
  1493. }
  1494. static ResultCode GetResourceLimitCurrentValue(u64* out_value, Handle resource_limit,
  1495. u32 resource_type) {
  1496. LOG_DEBUG(Kernel_SVC, "called. Handle={:08X}, Resource type={}", resource_limit, resource_type);
  1497. const auto current_value = RetrieveResourceLimitValue(resource_limit, resource_type,
  1498. ResourceLimitValueType::CurrentValue);
  1499. if (current_value.Failed()) {
  1500. return current_value.Code();
  1501. }
  1502. *out_value = static_cast<u64>(*current_value);
  1503. return RESULT_SUCCESS;
  1504. }
  1505. static ResultCode SetResourceLimitLimitValue(Handle resource_limit, u32 resource_type, u64 value) {
  1506. LOG_DEBUG(Kernel_SVC, "called. Handle={:08X}, Resource type={}, Value={}", resource_limit,
  1507. resource_type, value);
  1508. const auto type = static_cast<ResourceType>(resource_type);
  1509. if (!IsValidResourceType(type)) {
  1510. LOG_ERROR(Kernel_SVC, "Invalid resource limit type: '{}'", resource_type);
  1511. return ERR_INVALID_ENUM_VALUE;
  1512. }
  1513. auto& kernel = Core::System::GetInstance().Kernel();
  1514. auto* const current_process = kernel.CurrentProcess();
  1515. ASSERT(current_process != nullptr);
  1516. auto resource_limit_object =
  1517. current_process->GetHandleTable().Get<ResourceLimit>(resource_limit);
  1518. if (!resource_limit_object) {
  1519. LOG_ERROR(Kernel_SVC, "Handle to non-existent resource limit instance used. Handle={:08X}",
  1520. resource_limit);
  1521. return ERR_INVALID_HANDLE;
  1522. }
  1523. const auto set_result = resource_limit_object->SetLimitValue(type, static_cast<s64>(value));
  1524. if (set_result.IsError()) {
  1525. LOG_ERROR(
  1526. Kernel_SVC,
  1527. "Attempted to lower resource limit ({}) for category '{}' below its current value ({})",
  1528. resource_limit_object->GetMaxResourceValue(type), resource_type,
  1529. resource_limit_object->GetCurrentResourceValue(type));
  1530. return set_result;
  1531. }
  1532. return RESULT_SUCCESS;
  1533. }
  1534. namespace {
  1535. struct FunctionDef {
  1536. using Func = void();
  1537. u32 id;
  1538. Func* func;
  1539. const char* name;
  1540. };
  1541. } // namespace
  1542. static const FunctionDef SVC_Table[] = {
  1543. {0x00, nullptr, "Unknown"},
  1544. {0x01, SvcWrap<SetHeapSize>, "SetHeapSize"},
  1545. {0x02, SvcWrap<SetMemoryPermission>, "SetMemoryPermission"},
  1546. {0x03, SvcWrap<SetMemoryAttribute>, "SetMemoryAttribute"},
  1547. {0x04, SvcWrap<MapMemory>, "MapMemory"},
  1548. {0x05, SvcWrap<UnmapMemory>, "UnmapMemory"},
  1549. {0x06, SvcWrap<QueryMemory>, "QueryMemory"},
  1550. {0x07, SvcWrap<ExitProcess>, "ExitProcess"},
  1551. {0x08, SvcWrap<CreateThread>, "CreateThread"},
  1552. {0x09, SvcWrap<StartThread>, "StartThread"},
  1553. {0x0A, SvcWrap<ExitThread>, "ExitThread"},
  1554. {0x0B, SvcWrap<SleepThread>, "SleepThread"},
  1555. {0x0C, SvcWrap<GetThreadPriority>, "GetThreadPriority"},
  1556. {0x0D, SvcWrap<SetThreadPriority>, "SetThreadPriority"},
  1557. {0x0E, SvcWrap<GetThreadCoreMask>, "GetThreadCoreMask"},
  1558. {0x0F, SvcWrap<SetThreadCoreMask>, "SetThreadCoreMask"},
  1559. {0x10, SvcWrap<GetCurrentProcessorNumber>, "GetCurrentProcessorNumber"},
  1560. {0x11, SvcWrap<SignalEvent>, "SignalEvent"},
  1561. {0x12, SvcWrap<ClearEvent>, "ClearEvent"},
  1562. {0x13, SvcWrap<MapSharedMemory>, "MapSharedMemory"},
  1563. {0x14, SvcWrap<UnmapSharedMemory>, "UnmapSharedMemory"},
  1564. {0x15, SvcWrap<CreateTransferMemory>, "CreateTransferMemory"},
  1565. {0x16, SvcWrap<CloseHandle>, "CloseHandle"},
  1566. {0x17, SvcWrap<ResetSignal>, "ResetSignal"},
  1567. {0x18, SvcWrap<WaitSynchronization>, "WaitSynchronization"},
  1568. {0x19, SvcWrap<CancelSynchronization>, "CancelSynchronization"},
  1569. {0x1A, SvcWrap<ArbitrateLock>, "ArbitrateLock"},
  1570. {0x1B, SvcWrap<ArbitrateUnlock>, "ArbitrateUnlock"},
  1571. {0x1C, SvcWrap<WaitProcessWideKeyAtomic>, "WaitProcessWideKeyAtomic"},
  1572. {0x1D, SvcWrap<SignalProcessWideKey>, "SignalProcessWideKey"},
  1573. {0x1E, SvcWrap<GetSystemTick>, "GetSystemTick"},
  1574. {0x1F, SvcWrap<ConnectToNamedPort>, "ConnectToNamedPort"},
  1575. {0x20, nullptr, "SendSyncRequestLight"},
  1576. {0x21, SvcWrap<SendSyncRequest>, "SendSyncRequest"},
  1577. {0x22, nullptr, "SendSyncRequestWithUserBuffer"},
  1578. {0x23, nullptr, "SendAsyncRequestWithUserBuffer"},
  1579. {0x24, SvcWrap<GetProcessId>, "GetProcessId"},
  1580. {0x25, SvcWrap<GetThreadId>, "GetThreadId"},
  1581. {0x26, SvcWrap<Break>, "Break"},
  1582. {0x27, SvcWrap<OutputDebugString>, "OutputDebugString"},
  1583. {0x28, nullptr, "ReturnFromException"},
  1584. {0x29, SvcWrap<GetInfo>, "GetInfo"},
  1585. {0x2A, nullptr, "FlushEntireDataCache"},
  1586. {0x2B, nullptr, "FlushDataCache"},
  1587. {0x2C, nullptr, "MapPhysicalMemory"},
  1588. {0x2D, nullptr, "UnmapPhysicalMemory"},
  1589. {0x2E, nullptr, "GetFutureThreadInfo"},
  1590. {0x2F, nullptr, "GetLastThreadInfo"},
  1591. {0x30, SvcWrap<GetResourceLimitLimitValue>, "GetResourceLimitLimitValue"},
  1592. {0x31, SvcWrap<GetResourceLimitCurrentValue>, "GetResourceLimitCurrentValue"},
  1593. {0x32, SvcWrap<SetThreadActivity>, "SetThreadActivity"},
  1594. {0x33, SvcWrap<GetThreadContext>, "GetThreadContext"},
  1595. {0x34, SvcWrap<WaitForAddress>, "WaitForAddress"},
  1596. {0x35, SvcWrap<SignalToAddress>, "SignalToAddress"},
  1597. {0x36, nullptr, "Unknown"},
  1598. {0x37, nullptr, "Unknown"},
  1599. {0x38, nullptr, "Unknown"},
  1600. {0x39, nullptr, "Unknown"},
  1601. {0x3A, nullptr, "Unknown"},
  1602. {0x3B, nullptr, "Unknown"},
  1603. {0x3C, nullptr, "DumpInfo"},
  1604. {0x3D, nullptr, "DumpInfoNew"},
  1605. {0x3E, nullptr, "Unknown"},
  1606. {0x3F, nullptr, "Unknown"},
  1607. {0x40, nullptr, "CreateSession"},
  1608. {0x41, nullptr, "AcceptSession"},
  1609. {0x42, nullptr, "ReplyAndReceiveLight"},
  1610. {0x43, nullptr, "ReplyAndReceive"},
  1611. {0x44, nullptr, "ReplyAndReceiveWithUserBuffer"},
  1612. {0x45, SvcWrap<CreateEvent>, "CreateEvent"},
  1613. {0x46, nullptr, "Unknown"},
  1614. {0x47, nullptr, "Unknown"},
  1615. {0x48, nullptr, "MapPhysicalMemoryUnsafe"},
  1616. {0x49, nullptr, "UnmapPhysicalMemoryUnsafe"},
  1617. {0x4A, nullptr, "SetUnsafeLimit"},
  1618. {0x4B, nullptr, "CreateCodeMemory"},
  1619. {0x4C, nullptr, "ControlCodeMemory"},
  1620. {0x4D, nullptr, "SleepSystem"},
  1621. {0x4E, nullptr, "ReadWriteRegister"},
  1622. {0x4F, nullptr, "SetProcessActivity"},
  1623. {0x50, SvcWrap<CreateSharedMemory>, "CreateSharedMemory"},
  1624. {0x51, nullptr, "MapTransferMemory"},
  1625. {0x52, nullptr, "UnmapTransferMemory"},
  1626. {0x53, nullptr, "CreateInterruptEvent"},
  1627. {0x54, nullptr, "QueryPhysicalAddress"},
  1628. {0x55, nullptr, "QueryIoMapping"},
  1629. {0x56, nullptr, "CreateDeviceAddressSpace"},
  1630. {0x57, nullptr, "AttachDeviceAddressSpace"},
  1631. {0x58, nullptr, "DetachDeviceAddressSpace"},
  1632. {0x59, nullptr, "MapDeviceAddressSpaceByForce"},
  1633. {0x5A, nullptr, "MapDeviceAddressSpaceAligned"},
  1634. {0x5B, nullptr, "MapDeviceAddressSpace"},
  1635. {0x5C, nullptr, "UnmapDeviceAddressSpace"},
  1636. {0x5D, nullptr, "InvalidateProcessDataCache"},
  1637. {0x5E, nullptr, "StoreProcessDataCache"},
  1638. {0x5F, nullptr, "FlushProcessDataCache"},
  1639. {0x60, nullptr, "DebugActiveProcess"},
  1640. {0x61, nullptr, "BreakDebugProcess"},
  1641. {0x62, nullptr, "TerminateDebugProcess"},
  1642. {0x63, nullptr, "GetDebugEvent"},
  1643. {0x64, nullptr, "ContinueDebugEvent"},
  1644. {0x65, nullptr, "GetProcessList"},
  1645. {0x66, nullptr, "GetThreadList"},
  1646. {0x67, nullptr, "GetDebugThreadContext"},
  1647. {0x68, nullptr, "SetDebugThreadContext"},
  1648. {0x69, nullptr, "QueryDebugProcessMemory"},
  1649. {0x6A, nullptr, "ReadDebugProcessMemory"},
  1650. {0x6B, nullptr, "WriteDebugProcessMemory"},
  1651. {0x6C, nullptr, "SetHardwareBreakPoint"},
  1652. {0x6D, nullptr, "GetDebugThreadParam"},
  1653. {0x6E, nullptr, "Unknown"},
  1654. {0x6F, nullptr, "GetSystemInfo"},
  1655. {0x70, nullptr, "CreatePort"},
  1656. {0x71, nullptr, "ManageNamedPort"},
  1657. {0x72, nullptr, "ConnectToPort"},
  1658. {0x73, nullptr, "SetProcessMemoryPermission"},
  1659. {0x74, nullptr, "MapProcessMemory"},
  1660. {0x75, nullptr, "UnmapProcessMemory"},
  1661. {0x76, SvcWrap<QueryProcessMemory>, "QueryProcessMemory"},
  1662. {0x77, nullptr, "MapProcessCodeMemory"},
  1663. {0x78, nullptr, "UnmapProcessCodeMemory"},
  1664. {0x79, nullptr, "CreateProcess"},
  1665. {0x7A, nullptr, "StartProcess"},
  1666. {0x7B, nullptr, "TerminateProcess"},
  1667. {0x7C, SvcWrap<GetProcessInfo>, "GetProcessInfo"},
  1668. {0x7D, SvcWrap<CreateResourceLimit>, "CreateResourceLimit"},
  1669. {0x7E, SvcWrap<SetResourceLimitLimitValue>, "SetResourceLimitLimitValue"},
  1670. {0x7F, nullptr, "CallSecureMonitor"},
  1671. };
  1672. static const FunctionDef* GetSVCInfo(u32 func_num) {
  1673. if (func_num >= std::size(SVC_Table)) {
  1674. LOG_ERROR(Kernel_SVC, "Unknown svc=0x{:02X}", func_num);
  1675. return nullptr;
  1676. }
  1677. return &SVC_Table[func_num];
  1678. }
  1679. MICROPROFILE_DEFINE(Kernel_SVC, "Kernel", "SVC", MP_RGB(70, 200, 70));
  1680. void CallSVC(u32 immediate) {
  1681. MICROPROFILE_SCOPE(Kernel_SVC);
  1682. // Lock the global kernel mutex when we enter the kernel HLE.
  1683. std::lock_guard<std::recursive_mutex> lock(HLE::g_hle_lock);
  1684. const FunctionDef* info = GetSVCInfo(immediate);
  1685. if (info) {
  1686. if (info->func) {
  1687. info->func();
  1688. } else {
  1689. LOG_CRITICAL(Kernel_SVC, "Unimplemented SVC function {}(..)", info->name);
  1690. }
  1691. } else {
  1692. LOG_CRITICAL(Kernel_SVC, "Unknown SVC function 0x{:X}", immediate);
  1693. }
  1694. }
  1695. } // namespace Kernel