svc.cpp 60 KB

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