svc.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  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/assert.h"
  10. #include "common/logging/log.h"
  11. #include "common/microprofile.h"
  12. #include "common/string_util.h"
  13. #include "core/arm/exclusive_monitor.h"
  14. #include "core/core.h"
  15. #include "core/core_cpu.h"
  16. #include "core/core_timing.h"
  17. #include "core/hle/kernel/address_arbiter.h"
  18. #include "core/hle/kernel/client_port.h"
  19. #include "core/hle/kernel/client_session.h"
  20. #include "core/hle/kernel/event.h"
  21. #include "core/hle/kernel/handle_table.h"
  22. #include "core/hle/kernel/kernel.h"
  23. #include "core/hle/kernel/mutex.h"
  24. #include "core/hle/kernel/process.h"
  25. #include "core/hle/kernel/resource_limit.h"
  26. #include "core/hle/kernel/scheduler.h"
  27. #include "core/hle/kernel/shared_memory.h"
  28. #include "core/hle/kernel/svc.h"
  29. #include "core/hle/kernel/svc_wrap.h"
  30. #include "core/hle/kernel/thread.h"
  31. #include "core/hle/lock.h"
  32. #include "core/hle/result.h"
  33. #include "core/hle/service/service.h"
  34. namespace Kernel {
  35. namespace {
  36. constexpr bool Is4KBAligned(VAddr address) {
  37. return (address & 0xFFF) == 0;
  38. }
  39. } // Anonymous namespace
  40. /// Set the process heap to a given Size. It can both extend and shrink the heap.
  41. static ResultCode SetHeapSize(VAddr* heap_addr, u64 heap_size) {
  42. LOG_TRACE(Kernel_SVC, "called, heap_size=0x{:X}", heap_size);
  43. // Size must be a multiple of 0x200000 (2MB) and be equal to or less than 4GB.
  44. if ((heap_size & 0xFFFFFFFE001FFFFF) != 0) {
  45. return ERR_INVALID_SIZE;
  46. }
  47. auto& process = *Core::CurrentProcess();
  48. CASCADE_RESULT(*heap_addr,
  49. process.HeapAllocate(Memory::HEAP_VADDR, heap_size, VMAPermission::ReadWrite));
  50. return RESULT_SUCCESS;
  51. }
  52. static ResultCode SetMemoryAttribute(VAddr addr, u64 size, u32 state0, u32 state1) {
  53. LOG_WARNING(Kernel_SVC,
  54. "(STUBBED) called, addr=0x{:X}, size=0x{:X}, state0=0x{:X}, state1=0x{:X}", addr,
  55. size, state0, state1);
  56. return RESULT_SUCCESS;
  57. }
  58. /// Maps a memory range into a different range.
  59. static ResultCode MapMemory(VAddr dst_addr, VAddr src_addr, u64 size) {
  60. LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr,
  61. src_addr, size);
  62. if (!Is4KBAligned(dst_addr) || !Is4KBAligned(src_addr)) {
  63. return ERR_INVALID_ADDRESS;
  64. }
  65. if (size == 0 || !Is4KBAligned(size)) {
  66. return ERR_INVALID_SIZE;
  67. }
  68. return Core::CurrentProcess()->MirrorMemory(dst_addr, src_addr, size);
  69. }
  70. /// Unmaps a region that was previously mapped with svcMapMemory
  71. static ResultCode UnmapMemory(VAddr dst_addr, VAddr src_addr, u64 size) {
  72. LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr,
  73. src_addr, size);
  74. if (!Is4KBAligned(dst_addr) || !Is4KBAligned(src_addr)) {
  75. return ERR_INVALID_ADDRESS;
  76. }
  77. if (size == 0 || !Is4KBAligned(size)) {
  78. return ERR_INVALID_SIZE;
  79. }
  80. return Core::CurrentProcess()->UnmapMemory(dst_addr, src_addr, size);
  81. }
  82. /// Connect to an OS service given the port name, returns the handle to the port to out
  83. static ResultCode ConnectToNamedPort(Handle* out_handle, VAddr port_name_address) {
  84. if (!Memory::IsValidVirtualAddress(port_name_address)) {
  85. return ERR_NOT_FOUND;
  86. }
  87. static constexpr std::size_t PortNameMaxLength = 11;
  88. // Read 1 char beyond the max allowed port name to detect names that are too long.
  89. std::string port_name = Memory::ReadCString(port_name_address, PortNameMaxLength + 1);
  90. if (port_name.size() > PortNameMaxLength) {
  91. return ERR_PORT_NAME_TOO_LONG;
  92. }
  93. LOG_TRACE(Kernel_SVC, "called port_name={}", port_name);
  94. auto& kernel = Core::System::GetInstance().Kernel();
  95. auto it = kernel.FindNamedPort(port_name);
  96. if (!kernel.IsValidNamedPort(it)) {
  97. LOG_WARNING(Kernel_SVC, "tried to connect to unknown port: {}", port_name);
  98. return ERR_NOT_FOUND;
  99. }
  100. auto client_port = it->second;
  101. SharedPtr<ClientSession> client_session;
  102. CASCADE_RESULT(client_session, client_port->Connect());
  103. // Return the client session
  104. CASCADE_RESULT(*out_handle, kernel.HandleTable().Create(client_session));
  105. return RESULT_SUCCESS;
  106. }
  107. /// Makes a blocking IPC call to an OS service.
  108. static ResultCode SendSyncRequest(Handle handle) {
  109. auto& kernel = Core::System::GetInstance().Kernel();
  110. SharedPtr<ClientSession> session = kernel.HandleTable().Get<ClientSession>(handle);
  111. if (!session) {
  112. LOG_ERROR(Kernel_SVC, "called with invalid handle=0x{:08X}", handle);
  113. return ERR_INVALID_HANDLE;
  114. }
  115. LOG_TRACE(Kernel_SVC, "called handle=0x{:08X}({})", handle, session->GetName());
  116. Core::System::GetInstance().PrepareReschedule();
  117. // TODO(Subv): svcSendSyncRequest should put the caller thread to sleep while the server
  118. // responds and cause a reschedule.
  119. return session->SendSyncRequest(GetCurrentThread());
  120. }
  121. /// Get the ID for the specified thread.
  122. static ResultCode GetThreadId(u32* thread_id, Handle thread_handle) {
  123. LOG_TRACE(Kernel_SVC, "called thread=0x{:08X}", thread_handle);
  124. auto& kernel = Core::System::GetInstance().Kernel();
  125. const SharedPtr<Thread> thread = kernel.HandleTable().Get<Thread>(thread_handle);
  126. if (!thread) {
  127. return ERR_INVALID_HANDLE;
  128. }
  129. *thread_id = thread->GetThreadId();
  130. return RESULT_SUCCESS;
  131. }
  132. /// Get the ID of the specified process
  133. static ResultCode GetProcessId(u32* process_id, Handle process_handle) {
  134. LOG_TRACE(Kernel_SVC, "called process=0x{:08X}", process_handle);
  135. auto& kernel = Core::System::GetInstance().Kernel();
  136. const SharedPtr<Process> process = kernel.HandleTable().Get<Process>(process_handle);
  137. if (!process) {
  138. return ERR_INVALID_HANDLE;
  139. }
  140. *process_id = process->process_id;
  141. return RESULT_SUCCESS;
  142. }
  143. /// Default thread wakeup callback for WaitSynchronization
  144. static bool DefaultThreadWakeupCallback(ThreadWakeupReason reason, SharedPtr<Thread> thread,
  145. SharedPtr<WaitObject> object, size_t index) {
  146. ASSERT(thread->status == ThreadStatus::WaitSynchAny);
  147. if (reason == ThreadWakeupReason::Timeout) {
  148. thread->SetWaitSynchronizationResult(RESULT_TIMEOUT);
  149. return true;
  150. }
  151. ASSERT(reason == ThreadWakeupReason::Signal);
  152. thread->SetWaitSynchronizationResult(RESULT_SUCCESS);
  153. thread->SetWaitSynchronizationOutput(static_cast<u32>(index));
  154. return true;
  155. };
  156. /// Wait for the given handles to synchronize, timeout after the specified nanoseconds
  157. static ResultCode WaitSynchronization(Handle* index, VAddr handles_address, u64 handle_count,
  158. s64 nano_seconds) {
  159. LOG_TRACE(Kernel_SVC, "called handles_address=0x{:X}, handle_count={}, nano_seconds={}",
  160. handles_address, handle_count, nano_seconds);
  161. if (!Memory::IsValidVirtualAddress(handles_address))
  162. return ERR_INVALID_POINTER;
  163. static constexpr u64 MaxHandles = 0x40;
  164. if (handle_count > MaxHandles)
  165. return ResultCode(ErrorModule::Kernel, ErrCodes::TooLarge);
  166. auto thread = GetCurrentThread();
  167. using ObjectPtr = SharedPtr<WaitObject>;
  168. std::vector<ObjectPtr> objects(handle_count);
  169. auto& kernel = Core::System::GetInstance().Kernel();
  170. for (u64 i = 0; i < handle_count; ++i) {
  171. const Handle handle = Memory::Read32(handles_address + i * sizeof(Handle));
  172. const auto object = kernel.HandleTable().Get<WaitObject>(handle);
  173. if (object == nullptr) {
  174. return ERR_INVALID_HANDLE;
  175. }
  176. objects[i] = object;
  177. }
  178. // Find the first object that is acquirable in the provided list of objects
  179. auto itr = std::find_if(objects.begin(), objects.end(), [thread](const ObjectPtr& object) {
  180. return !object->ShouldWait(thread);
  181. });
  182. if (itr != objects.end()) {
  183. // We found a ready object, acquire it and set the result value
  184. WaitObject* object = itr->get();
  185. object->Acquire(thread);
  186. *index = static_cast<s32>(std::distance(objects.begin(), itr));
  187. return RESULT_SUCCESS;
  188. }
  189. // No objects were ready to be acquired, prepare to suspend the thread.
  190. // If a timeout value of 0 was provided, just return the Timeout error code instead of
  191. // suspending the thread.
  192. if (nano_seconds == 0)
  193. return RESULT_TIMEOUT;
  194. for (auto& object : objects)
  195. object->AddWaitingThread(thread);
  196. thread->wait_objects = std::move(objects);
  197. thread->status = ThreadStatus::WaitSynchAny;
  198. // Create an event to wake the thread up after the specified nanosecond delay has passed
  199. thread->WakeAfterDelay(nano_seconds);
  200. thread->wakeup_callback = DefaultThreadWakeupCallback;
  201. Core::System::GetInstance().CpuCore(thread->processor_id).PrepareReschedule();
  202. return RESULT_TIMEOUT;
  203. }
  204. /// Resumes a thread waiting on WaitSynchronization
  205. static ResultCode CancelSynchronization(Handle thread_handle) {
  206. LOG_TRACE(Kernel_SVC, "called thread=0x{:X}", thread_handle);
  207. auto& kernel = Core::System::GetInstance().Kernel();
  208. const SharedPtr<Thread> thread = kernel.HandleTable().Get<Thread>(thread_handle);
  209. if (!thread) {
  210. return ERR_INVALID_HANDLE;
  211. }
  212. ASSERT(thread->status == ThreadStatus::WaitSynchAny);
  213. thread->SetWaitSynchronizationResult(
  214. ResultCode(ErrorModule::Kernel, ErrCodes::SynchronizationCanceled));
  215. thread->ResumeFromWait();
  216. return RESULT_SUCCESS;
  217. }
  218. /// Attempts to locks a mutex, creating it if it does not already exist
  219. static ResultCode ArbitrateLock(Handle holding_thread_handle, VAddr mutex_addr,
  220. Handle requesting_thread_handle) {
  221. LOG_TRACE(Kernel_SVC,
  222. "called holding_thread_handle=0x{:08X}, mutex_addr=0x{:X}, "
  223. "requesting_current_thread_handle=0x{:08X}",
  224. holding_thread_handle, mutex_addr, requesting_thread_handle);
  225. auto& handle_table = Core::System::GetInstance().Kernel().HandleTable();
  226. return Mutex::TryAcquire(handle_table, mutex_addr, holding_thread_handle,
  227. requesting_thread_handle);
  228. }
  229. /// Unlock a mutex
  230. static ResultCode ArbitrateUnlock(VAddr mutex_addr) {
  231. LOG_TRACE(Kernel_SVC, "called mutex_addr=0x{:X}", mutex_addr);
  232. return Mutex::Release(mutex_addr);
  233. }
  234. /// Break program execution
  235. static void Break(u64 reason, u64 info1, u64 info2) {
  236. LOG_CRITICAL(
  237. Debug_Emulated,
  238. "Emulated program broke execution! reason=0x{:016X}, info1=0x{:016X}, info2=0x{:016X}",
  239. reason, info1, info2);
  240. ASSERT(false);
  241. }
  242. /// Used to output a message on a debug hardware unit - does nothing on a retail unit
  243. static void OutputDebugString(VAddr address, u64 len) {
  244. if (len == 0) {
  245. return;
  246. }
  247. std::string str(len, '\0');
  248. Memory::ReadBlock(address, str.data(), str.size());
  249. LOG_DEBUG(Debug_Emulated, "{}", str);
  250. }
  251. /// Gets system/memory information for the current process
  252. static ResultCode GetInfo(u64* result, u64 info_id, u64 handle, u64 info_sub_id) {
  253. LOG_TRACE(Kernel_SVC, "called info_id=0x{:X}, info_sub_id=0x{:X}, handle=0x{:08X}", info_id,
  254. info_sub_id, handle);
  255. const auto& vm_manager = Core::CurrentProcess()->vm_manager;
  256. switch (static_cast<GetInfoType>(info_id)) {
  257. case GetInfoType::AllowedCpuIdBitmask:
  258. *result = Core::CurrentProcess()->allowed_processor_mask;
  259. break;
  260. case GetInfoType::AllowedThreadPrioBitmask:
  261. *result = Core::CurrentProcess()->allowed_thread_priority_mask;
  262. break;
  263. case GetInfoType::MapRegionBaseAddr:
  264. *result = Memory::MAP_REGION_VADDR;
  265. break;
  266. case GetInfoType::MapRegionSize:
  267. *result = Memory::MAP_REGION_SIZE;
  268. break;
  269. case GetInfoType::HeapRegionBaseAddr:
  270. *result = Memory::HEAP_VADDR;
  271. break;
  272. case GetInfoType::HeapRegionSize:
  273. *result = Memory::HEAP_SIZE;
  274. break;
  275. case GetInfoType::TotalMemoryUsage:
  276. *result = vm_manager.GetTotalMemoryUsage();
  277. break;
  278. case GetInfoType::TotalHeapUsage:
  279. *result = vm_manager.GetTotalHeapUsage();
  280. break;
  281. case GetInfoType::IsCurrentProcessBeingDebugged:
  282. *result = 0;
  283. break;
  284. case GetInfoType::RandomEntropy:
  285. *result = 0;
  286. break;
  287. case GetInfoType::AddressSpaceBaseAddr:
  288. *result = vm_manager.GetAddressSpaceBaseAddr();
  289. break;
  290. case GetInfoType::AddressSpaceSize:
  291. *result = vm_manager.GetAddressSpaceSize();
  292. break;
  293. case GetInfoType::NewMapRegionBaseAddr:
  294. *result = Memory::NEW_MAP_REGION_VADDR;
  295. break;
  296. case GetInfoType::NewMapRegionSize:
  297. *result = Memory::NEW_MAP_REGION_SIZE;
  298. break;
  299. case GetInfoType::IsVirtualAddressMemoryEnabled:
  300. *result = Core::CurrentProcess()->is_virtual_address_memory_enabled;
  301. break;
  302. case GetInfoType::TitleId:
  303. *result = Core::CurrentProcess()->program_id;
  304. break;
  305. case GetInfoType::PrivilegedProcessId:
  306. LOG_WARNING(Kernel_SVC,
  307. "(STUBBED) Attempted to query privileged process id bounds, returned 0");
  308. *result = 0;
  309. break;
  310. case GetInfoType::UserExceptionContextAddr:
  311. LOG_WARNING(Kernel_SVC,
  312. "(STUBBED) Attempted to query user exception context address, returned 0");
  313. *result = 0;
  314. break;
  315. default:
  316. UNIMPLEMENTED();
  317. }
  318. return RESULT_SUCCESS;
  319. }
  320. /// Sets the thread activity
  321. static ResultCode SetThreadActivity(Handle handle, u32 unknown) {
  322. LOG_WARNING(Kernel_SVC, "(STUBBED) called, handle=0x{:08X}, unknown=0x{:08X}", handle, unknown);
  323. return RESULT_SUCCESS;
  324. }
  325. /// Gets the thread context
  326. static ResultCode GetThreadContext(Handle handle, VAddr addr) {
  327. LOG_WARNING(Kernel_SVC, "(STUBBED) called, handle=0x{:08X}, addr=0x{:X}", handle, addr);
  328. return RESULT_SUCCESS;
  329. }
  330. /// Gets the priority for the specified thread
  331. static ResultCode GetThreadPriority(u32* priority, Handle handle) {
  332. auto& kernel = Core::System::GetInstance().Kernel();
  333. const SharedPtr<Thread> thread = kernel.HandleTable().Get<Thread>(handle);
  334. if (!thread)
  335. return ERR_INVALID_HANDLE;
  336. *priority = thread->GetPriority();
  337. return RESULT_SUCCESS;
  338. }
  339. /// Sets the priority for the specified thread
  340. static ResultCode SetThreadPriority(Handle handle, u32 priority) {
  341. if (priority > THREADPRIO_LOWEST) {
  342. return ERR_INVALID_THREAD_PRIORITY;
  343. }
  344. auto& kernel = Core::System::GetInstance().Kernel();
  345. SharedPtr<Thread> thread = kernel.HandleTable().Get<Thread>(handle);
  346. if (!thread)
  347. return ERR_INVALID_HANDLE;
  348. // Note: The kernel uses the current process's resource limit instead of
  349. // the one from the thread owner's resource limit.
  350. SharedPtr<ResourceLimit>& resource_limit = Core::CurrentProcess()->resource_limit;
  351. if (resource_limit->GetMaxResourceValue(ResourceType::Priority) > priority) {
  352. return ERR_NOT_AUTHORIZED;
  353. }
  354. thread->SetPriority(priority);
  355. Core::System::GetInstance().CpuCore(thread->processor_id).PrepareReschedule();
  356. return RESULT_SUCCESS;
  357. }
  358. /// Get which CPU core is executing the current thread
  359. static u32 GetCurrentProcessorNumber() {
  360. LOG_TRACE(Kernel_SVC, "called");
  361. return GetCurrentThread()->processor_id;
  362. }
  363. static ResultCode MapSharedMemory(Handle shared_memory_handle, VAddr addr, u64 size,
  364. u32 permissions) {
  365. LOG_TRACE(Kernel_SVC,
  366. "called, shared_memory_handle=0x{:X}, addr=0x{:X}, size=0x{:X}, permissions=0x{:08X}",
  367. shared_memory_handle, addr, size, permissions);
  368. auto& kernel = Core::System::GetInstance().Kernel();
  369. auto shared_memory = kernel.HandleTable().Get<SharedMemory>(shared_memory_handle);
  370. if (!shared_memory) {
  371. return ERR_INVALID_HANDLE;
  372. }
  373. MemoryPermission permissions_type = static_cast<MemoryPermission>(permissions);
  374. switch (permissions_type) {
  375. case MemoryPermission::Read:
  376. case MemoryPermission::Write:
  377. case MemoryPermission::ReadWrite:
  378. case MemoryPermission::Execute:
  379. case MemoryPermission::ReadExecute:
  380. case MemoryPermission::WriteExecute:
  381. case MemoryPermission::ReadWriteExecute:
  382. case MemoryPermission::DontCare:
  383. return shared_memory->Map(Core::CurrentProcess().get(), addr, permissions_type,
  384. MemoryPermission::DontCare);
  385. default:
  386. LOG_ERROR(Kernel_SVC, "unknown permissions=0x{:08X}", permissions);
  387. }
  388. return RESULT_SUCCESS;
  389. }
  390. static ResultCode UnmapSharedMemory(Handle shared_memory_handle, VAddr addr, u64 size) {
  391. LOG_WARNING(Kernel_SVC, "called, shared_memory_handle=0x{:08X}, addr=0x{:X}, size=0x{:X}",
  392. shared_memory_handle, addr, size);
  393. auto& kernel = Core::System::GetInstance().Kernel();
  394. auto shared_memory = kernel.HandleTable().Get<SharedMemory>(shared_memory_handle);
  395. return shared_memory->Unmap(Core::CurrentProcess().get(), addr);
  396. }
  397. /// Query process memory
  398. static ResultCode QueryProcessMemory(MemoryInfo* memory_info, PageInfo* /*page_info*/,
  399. Handle process_handle, u64 addr) {
  400. auto& kernel = Core::System::GetInstance().Kernel();
  401. SharedPtr<Process> process = kernel.HandleTable().Get<Process>(process_handle);
  402. if (!process) {
  403. return ERR_INVALID_HANDLE;
  404. }
  405. auto vma = process->vm_manager.FindVMA(addr);
  406. memory_info->attributes = 0;
  407. if (vma == Core::CurrentProcess()->vm_manager.vma_map.end()) {
  408. memory_info->base_address = 0;
  409. memory_info->permission = static_cast<u32>(VMAPermission::None);
  410. memory_info->size = 0;
  411. memory_info->type = static_cast<u32>(MemoryState::Unmapped);
  412. } else {
  413. memory_info->base_address = vma->second.base;
  414. memory_info->permission = static_cast<u32>(vma->second.permissions);
  415. memory_info->size = vma->second.size;
  416. memory_info->type = static_cast<u32>(vma->second.meminfo_state);
  417. }
  418. LOG_TRACE(Kernel_SVC, "called process=0x{:08X} addr={:X}", process_handle, addr);
  419. return RESULT_SUCCESS;
  420. }
  421. /// Query memory
  422. static ResultCode QueryMemory(MemoryInfo* memory_info, PageInfo* page_info, VAddr addr) {
  423. LOG_TRACE(Kernel_SVC, "called, addr={:X}", addr);
  424. return QueryProcessMemory(memory_info, page_info, CurrentProcess, addr);
  425. }
  426. /// Exits the current process
  427. static void ExitProcess() {
  428. LOG_INFO(Kernel_SVC, "Process {} exiting", Core::CurrentProcess()->process_id);
  429. ASSERT_MSG(Core::CurrentProcess()->status == ProcessStatus::Running,
  430. "Process has already exited");
  431. Core::CurrentProcess()->status = ProcessStatus::Exited;
  432. auto stop_threads = [](const std::vector<SharedPtr<Thread>>& thread_list) {
  433. for (auto& thread : thread_list) {
  434. if (thread->owner_process != Core::CurrentProcess())
  435. continue;
  436. if (thread == GetCurrentThread())
  437. continue;
  438. // TODO(Subv): When are the other running/ready threads terminated?
  439. ASSERT_MSG(thread->status == ThreadStatus::WaitSynchAny ||
  440. thread->status == ThreadStatus::WaitSynchAll,
  441. "Exiting processes with non-waiting threads is currently unimplemented");
  442. thread->Stop();
  443. }
  444. };
  445. auto& system = Core::System::GetInstance();
  446. stop_threads(system.Scheduler(0)->GetThreadList());
  447. stop_threads(system.Scheduler(1)->GetThreadList());
  448. stop_threads(system.Scheduler(2)->GetThreadList());
  449. stop_threads(system.Scheduler(3)->GetThreadList());
  450. // Kill the current thread
  451. GetCurrentThread()->Stop();
  452. Core::System::GetInstance().PrepareReschedule();
  453. }
  454. /// Creates a new thread
  455. static ResultCode CreateThread(Handle* out_handle, VAddr entry_point, u64 arg, VAddr stack_top,
  456. u32 priority, s32 processor_id) {
  457. std::string name = fmt::format("unknown-{:X}", entry_point);
  458. if (priority > THREADPRIO_LOWEST) {
  459. return ERR_INVALID_THREAD_PRIORITY;
  460. }
  461. SharedPtr<ResourceLimit>& resource_limit = Core::CurrentProcess()->resource_limit;
  462. if (resource_limit->GetMaxResourceValue(ResourceType::Priority) > priority) {
  463. return ERR_NOT_AUTHORIZED;
  464. }
  465. if (processor_id == THREADPROCESSORID_DEFAULT) {
  466. // Set the target CPU to the one specified in the process' exheader.
  467. processor_id = Core::CurrentProcess()->ideal_processor;
  468. ASSERT(processor_id != THREADPROCESSORID_DEFAULT);
  469. }
  470. switch (processor_id) {
  471. case THREADPROCESSORID_0:
  472. case THREADPROCESSORID_1:
  473. case THREADPROCESSORID_2:
  474. case THREADPROCESSORID_3:
  475. break;
  476. default:
  477. LOG_ERROR(Kernel_SVC, "Invalid thread processor ID: {}", processor_id);
  478. return ERR_INVALID_PROCESSOR_ID;
  479. }
  480. auto& kernel = Core::System::GetInstance().Kernel();
  481. CASCADE_RESULT(SharedPtr<Thread> thread,
  482. Thread::Create(kernel, name, entry_point, priority, arg, processor_id, stack_top,
  483. Core::CurrentProcess()));
  484. CASCADE_RESULT(thread->guest_handle, kernel.HandleTable().Create(thread));
  485. *out_handle = thread->guest_handle;
  486. Core::System::GetInstance().CpuCore(thread->processor_id).PrepareReschedule();
  487. LOG_TRACE(Kernel_SVC,
  488. "called entrypoint=0x{:08X} ({}), arg=0x{:08X}, stacktop=0x{:08X}, "
  489. "threadpriority=0x{:08X}, processorid=0x{:08X} : created handle=0x{:08X}",
  490. entry_point, name, arg, stack_top, priority, processor_id, *out_handle);
  491. return RESULT_SUCCESS;
  492. }
  493. /// Starts the thread for the provided handle
  494. static ResultCode StartThread(Handle thread_handle) {
  495. LOG_TRACE(Kernel_SVC, "called thread=0x{:08X}", thread_handle);
  496. auto& kernel = Core::System::GetInstance().Kernel();
  497. const SharedPtr<Thread> thread = kernel.HandleTable().Get<Thread>(thread_handle);
  498. if (!thread) {
  499. return ERR_INVALID_HANDLE;
  500. }
  501. ASSERT(thread->status == ThreadStatus::Dormant);
  502. thread->ResumeFromWait();
  503. Core::System::GetInstance().CpuCore(thread->processor_id).PrepareReschedule();
  504. return RESULT_SUCCESS;
  505. }
  506. /// Called when a thread exits
  507. static void ExitThread() {
  508. LOG_TRACE(Kernel_SVC, "called, pc=0x{:08X}", Core::CurrentArmInterface().GetPC());
  509. ExitCurrentThread();
  510. Core::System::GetInstance().PrepareReschedule();
  511. }
  512. /// Sleep the current thread
  513. static void SleepThread(s64 nanoseconds) {
  514. LOG_TRACE(Kernel_SVC, "called nanoseconds={}", nanoseconds);
  515. // Don't attempt to yield execution if there are no available threads to run,
  516. // this way we avoid a useless reschedule to the idle thread.
  517. if (nanoseconds == 0 && !Core::System::GetInstance().CurrentScheduler().HaveReadyThreads())
  518. return;
  519. // Sleep current thread and check for next thread to schedule
  520. WaitCurrentThread_Sleep();
  521. // Create an event to wake the thread up after the specified nanosecond delay has passed
  522. GetCurrentThread()->WakeAfterDelay(nanoseconds);
  523. Core::System::GetInstance().PrepareReschedule();
  524. }
  525. /// Wait process wide key atomic
  526. static ResultCode WaitProcessWideKeyAtomic(VAddr mutex_addr, VAddr condition_variable_addr,
  527. Handle thread_handle, s64 nano_seconds) {
  528. LOG_TRACE(
  529. Kernel_SVC,
  530. "called mutex_addr={:X}, condition_variable_addr={:X}, thread_handle=0x{:08X}, timeout={}",
  531. mutex_addr, condition_variable_addr, thread_handle, nano_seconds);
  532. auto& kernel = Core::System::GetInstance().Kernel();
  533. SharedPtr<Thread> thread = kernel.HandleTable().Get<Thread>(thread_handle);
  534. ASSERT(thread);
  535. CASCADE_CODE(Mutex::Release(mutex_addr));
  536. SharedPtr<Thread> current_thread = GetCurrentThread();
  537. current_thread->condvar_wait_address = condition_variable_addr;
  538. current_thread->mutex_wait_address = mutex_addr;
  539. current_thread->wait_handle = thread_handle;
  540. current_thread->status = ThreadStatus::WaitMutex;
  541. current_thread->wakeup_callback = nullptr;
  542. current_thread->WakeAfterDelay(nano_seconds);
  543. // Note: Deliberately don't attempt to inherit the lock owner's priority.
  544. Core::System::GetInstance().CpuCore(current_thread->processor_id).PrepareReschedule();
  545. return RESULT_SUCCESS;
  546. }
  547. /// Signal process wide key
  548. static ResultCode SignalProcessWideKey(VAddr condition_variable_addr, s32 target) {
  549. LOG_TRACE(Kernel_SVC, "called, condition_variable_addr=0x{:X}, target=0x{:08X}",
  550. condition_variable_addr, target);
  551. auto RetrieveWaitingThreads =
  552. [](size_t core_index, std::vector<SharedPtr<Thread>>& waiting_threads, VAddr condvar_addr) {
  553. const auto& scheduler = Core::System::GetInstance().Scheduler(core_index);
  554. auto& thread_list = scheduler->GetThreadList();
  555. for (auto& thread : thread_list) {
  556. if (thread->condvar_wait_address == condvar_addr)
  557. waiting_threads.push_back(thread);
  558. }
  559. };
  560. // Retrieve a list of all threads that are waiting for this condition variable.
  561. std::vector<SharedPtr<Thread>> waiting_threads;
  562. RetrieveWaitingThreads(0, waiting_threads, condition_variable_addr);
  563. RetrieveWaitingThreads(1, waiting_threads, condition_variable_addr);
  564. RetrieveWaitingThreads(2, waiting_threads, condition_variable_addr);
  565. RetrieveWaitingThreads(3, waiting_threads, condition_variable_addr);
  566. // Sort them by priority, such that the highest priority ones come first.
  567. std::sort(waiting_threads.begin(), waiting_threads.end(),
  568. [](const SharedPtr<Thread>& lhs, const SharedPtr<Thread>& rhs) {
  569. return lhs->current_priority < rhs->current_priority;
  570. });
  571. // Only process up to 'target' threads, unless 'target' is -1, in which case process
  572. // them all.
  573. size_t last = waiting_threads.size();
  574. if (target != -1)
  575. last = target;
  576. // If there are no threads waiting on this condition variable, just exit
  577. if (last > waiting_threads.size())
  578. return RESULT_SUCCESS;
  579. for (size_t index = 0; index < last; ++index) {
  580. auto& thread = waiting_threads[index];
  581. ASSERT(thread->condvar_wait_address == condition_variable_addr);
  582. size_t current_core = Core::System::GetInstance().CurrentCoreIndex();
  583. auto& monitor = Core::System::GetInstance().Monitor();
  584. // Atomically read the value of the mutex.
  585. u32 mutex_val = 0;
  586. do {
  587. monitor.SetExclusive(current_core, thread->mutex_wait_address);
  588. // If the mutex is not yet acquired, acquire it.
  589. mutex_val = Memory::Read32(thread->mutex_wait_address);
  590. if (mutex_val != 0) {
  591. monitor.ClearExclusive();
  592. break;
  593. }
  594. } while (!monitor.ExclusiveWrite32(current_core, thread->mutex_wait_address,
  595. thread->wait_handle));
  596. if (mutex_val == 0) {
  597. // We were able to acquire the mutex, resume this thread.
  598. ASSERT(thread->status == ThreadStatus::WaitMutex);
  599. thread->ResumeFromWait();
  600. auto lock_owner = thread->lock_owner;
  601. if (lock_owner)
  602. lock_owner->RemoveMutexWaiter(thread);
  603. thread->lock_owner = nullptr;
  604. thread->mutex_wait_address = 0;
  605. thread->condvar_wait_address = 0;
  606. thread->wait_handle = 0;
  607. } else {
  608. // Atomically signal that the mutex now has a waiting thread.
  609. do {
  610. monitor.SetExclusive(current_core, thread->mutex_wait_address);
  611. // Ensure that the mutex value is still what we expect.
  612. u32 value = Memory::Read32(thread->mutex_wait_address);
  613. // TODO(Subv): When this happens, the kernel just clears the exclusive state and
  614. // retries the initial read for this thread.
  615. ASSERT_MSG(mutex_val == value, "Unhandled synchronization primitive case");
  616. } while (!monitor.ExclusiveWrite32(current_core, thread->mutex_wait_address,
  617. mutex_val | Mutex::MutexHasWaitersFlag));
  618. // The mutex is already owned by some other thread, make this thread wait on it.
  619. auto& kernel = Core::System::GetInstance().Kernel();
  620. Handle owner_handle = static_cast<Handle>(mutex_val & Mutex::MutexOwnerMask);
  621. auto owner = kernel.HandleTable().Get<Thread>(owner_handle);
  622. ASSERT(owner);
  623. ASSERT(thread->status == ThreadStatus::WaitMutex);
  624. thread->wakeup_callback = nullptr;
  625. owner->AddMutexWaiter(thread);
  626. Core::System::GetInstance().CpuCore(thread->processor_id).PrepareReschedule();
  627. }
  628. }
  629. return RESULT_SUCCESS;
  630. }
  631. // Wait for an address (via Address Arbiter)
  632. static ResultCode WaitForAddress(VAddr address, u32 type, s32 value, s64 timeout) {
  633. LOG_WARNING(Kernel_SVC, "called, address=0x{:X}, type=0x{:X}, value=0x{:X}, timeout={}",
  634. address, type, value, timeout);
  635. // If the passed address is a kernel virtual address, return invalid memory state.
  636. if (Memory::IsKernelVirtualAddress(address)) {
  637. return ERR_INVALID_ADDRESS_STATE;
  638. }
  639. // If the address is not properly aligned to 4 bytes, return invalid address.
  640. if (address % sizeof(u32) != 0) {
  641. return ERR_INVALID_ADDRESS;
  642. }
  643. switch (static_cast<AddressArbiter::ArbitrationType>(type)) {
  644. case AddressArbiter::ArbitrationType::WaitIfLessThan:
  645. return AddressArbiter::WaitForAddressIfLessThan(address, value, timeout, false);
  646. case AddressArbiter::ArbitrationType::DecrementAndWaitIfLessThan:
  647. return AddressArbiter::WaitForAddressIfLessThan(address, value, timeout, true);
  648. case AddressArbiter::ArbitrationType::WaitIfEqual:
  649. return AddressArbiter::WaitForAddressIfEqual(address, value, timeout);
  650. default:
  651. return ERR_INVALID_ENUM_VALUE;
  652. }
  653. }
  654. // Signals to an address (via Address Arbiter)
  655. static ResultCode SignalToAddress(VAddr address, u32 type, s32 value, s32 num_to_wake) {
  656. LOG_WARNING(Kernel_SVC, "called, address=0x{:X}, type=0x{:X}, value=0x{:X}, num_to_wake=0x{:X}",
  657. address, type, value, num_to_wake);
  658. // If the passed address is a kernel virtual address, return invalid memory state.
  659. if (Memory::IsKernelVirtualAddress(address)) {
  660. return ERR_INVALID_ADDRESS_STATE;
  661. }
  662. // If the address is not properly aligned to 4 bytes, return invalid address.
  663. if (address % sizeof(u32) != 0) {
  664. return ERR_INVALID_ADDRESS;
  665. }
  666. switch (static_cast<AddressArbiter::SignalType>(type)) {
  667. case AddressArbiter::SignalType::Signal:
  668. return AddressArbiter::SignalToAddress(address, num_to_wake);
  669. case AddressArbiter::SignalType::IncrementAndSignalIfEqual:
  670. return AddressArbiter::IncrementAndSignalToAddressIfEqual(address, value, num_to_wake);
  671. case AddressArbiter::SignalType::ModifyByWaitingCountAndSignalIfEqual:
  672. return AddressArbiter::ModifyByWaitingCountAndSignalToAddressIfEqual(address, value,
  673. num_to_wake);
  674. default:
  675. return ERR_INVALID_ENUM_VALUE;
  676. }
  677. }
  678. /// This returns the total CPU ticks elapsed since the CPU was powered-on
  679. static u64 GetSystemTick() {
  680. const u64 result{CoreTiming::GetTicks()};
  681. // Advance time to defeat dumb games that busy-wait for the frame to end.
  682. CoreTiming::AddTicks(400);
  683. return result;
  684. }
  685. /// Close a handle
  686. static ResultCode CloseHandle(Handle handle) {
  687. LOG_TRACE(Kernel_SVC, "Closing handle 0x{:08X}", handle);
  688. auto& kernel = Core::System::GetInstance().Kernel();
  689. return kernel.HandleTable().Close(handle);
  690. }
  691. /// Reset an event
  692. static ResultCode ResetSignal(Handle handle) {
  693. LOG_WARNING(Kernel_SVC, "(STUBBED) called handle 0x{:08X}", handle);
  694. auto& kernel = Core::System::GetInstance().Kernel();
  695. auto event = kernel.HandleTable().Get<Event>(handle);
  696. ASSERT(event != nullptr);
  697. event->Clear();
  698. return RESULT_SUCCESS;
  699. }
  700. /// Creates a TransferMemory object
  701. static ResultCode CreateTransferMemory(Handle* handle, VAddr addr, u64 size, u32 permissions) {
  702. LOG_WARNING(Kernel_SVC, "(STUBBED) called addr=0x{:X}, size=0x{:X}, perms=0x{:08X}", addr, size,
  703. permissions);
  704. *handle = 0;
  705. return RESULT_SUCCESS;
  706. }
  707. static ResultCode GetThreadCoreMask(Handle thread_handle, u32* core, u64* mask) {
  708. LOG_TRACE(Kernel_SVC, "called, handle=0x{:08X}", thread_handle);
  709. auto& kernel = Core::System::GetInstance().Kernel();
  710. const SharedPtr<Thread> thread = kernel.HandleTable().Get<Thread>(thread_handle);
  711. if (!thread) {
  712. return ERR_INVALID_HANDLE;
  713. }
  714. *core = thread->ideal_core;
  715. *mask = thread->affinity_mask;
  716. return RESULT_SUCCESS;
  717. }
  718. static ResultCode SetThreadCoreMask(Handle thread_handle, u32 core, u64 mask) {
  719. LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, mask=0x{:16X}, core=0x{:X}", thread_handle,
  720. mask, core);
  721. auto& kernel = Core::System::GetInstance().Kernel();
  722. const SharedPtr<Thread> thread = kernel.HandleTable().Get<Thread>(thread_handle);
  723. if (!thread) {
  724. return ERR_INVALID_HANDLE;
  725. }
  726. if (core == static_cast<u32>(THREADPROCESSORID_DEFAULT)) {
  727. ASSERT(thread->owner_process->ideal_processor !=
  728. static_cast<u8>(THREADPROCESSORID_DEFAULT));
  729. // Set the target CPU to the one specified in the process' exheader.
  730. core = thread->owner_process->ideal_processor;
  731. mask = 1ull << core;
  732. }
  733. if (mask == 0) {
  734. return ResultCode(ErrorModule::Kernel, ErrCodes::InvalidCombination);
  735. }
  736. /// This value is used to only change the affinity mask without changing the current ideal core.
  737. static constexpr u32 OnlyChangeMask = static_cast<u32>(-3);
  738. if (core == OnlyChangeMask) {
  739. core = thread->ideal_core;
  740. } else if (core >= Core::NUM_CPU_CORES && core != static_cast<u32>(-1)) {
  741. return ResultCode(ErrorModule::Kernel, ErrCodes::InvalidProcessorId);
  742. }
  743. // Error out if the input core isn't enabled in the input mask.
  744. if (core < Core::NUM_CPU_CORES && (mask & (1ull << core)) == 0) {
  745. return ResultCode(ErrorModule::Kernel, ErrCodes::InvalidCombination);
  746. }
  747. thread->ChangeCore(core, mask);
  748. return RESULT_SUCCESS;
  749. }
  750. static ResultCode CreateSharedMemory(Handle* handle, u64 size, u32 local_permissions,
  751. u32 remote_permissions) {
  752. LOG_TRACE(Kernel_SVC, "called, size=0x{:X}, localPerms=0x{:08X}, remotePerms=0x{:08X}", size,
  753. local_permissions, remote_permissions);
  754. auto& kernel = Core::System::GetInstance().Kernel();
  755. auto& handle_table = kernel.HandleTable();
  756. auto shared_mem_handle =
  757. SharedMemory::Create(kernel, handle_table.Get<Process>(KernelHandle::CurrentProcess), size,
  758. static_cast<MemoryPermission>(local_permissions),
  759. static_cast<MemoryPermission>(remote_permissions));
  760. CASCADE_RESULT(*handle, handle_table.Create(shared_mem_handle));
  761. return RESULT_SUCCESS;
  762. }
  763. static ResultCode ClearEvent(Handle handle) {
  764. LOG_TRACE(Kernel_SVC, "called, event=0x{:08X}", handle);
  765. auto& kernel = Core::System::GetInstance().Kernel();
  766. SharedPtr<Event> evt = kernel.HandleTable().Get<Event>(handle);
  767. if (evt == nullptr)
  768. return ERR_INVALID_HANDLE;
  769. evt->Clear();
  770. return RESULT_SUCCESS;
  771. }
  772. namespace {
  773. struct FunctionDef {
  774. using Func = void();
  775. u32 id;
  776. Func* func;
  777. const char* name;
  778. };
  779. } // namespace
  780. static const FunctionDef SVC_Table[] = {
  781. {0x00, nullptr, "Unknown"},
  782. {0x01, SvcWrap<SetHeapSize>, "SetHeapSize"},
  783. {0x02, nullptr, "SetMemoryPermission"},
  784. {0x03, SvcWrap<SetMemoryAttribute>, "SetMemoryAttribute"},
  785. {0x04, SvcWrap<MapMemory>, "MapMemory"},
  786. {0x05, SvcWrap<UnmapMemory>, "UnmapMemory"},
  787. {0x06, SvcWrap<QueryMemory>, "QueryMemory"},
  788. {0x07, SvcWrap<ExitProcess>, "ExitProcess"},
  789. {0x08, SvcWrap<CreateThread>, "CreateThread"},
  790. {0x09, SvcWrap<StartThread>, "StartThread"},
  791. {0x0A, SvcWrap<ExitThread>, "ExitThread"},
  792. {0x0B, SvcWrap<SleepThread>, "SleepThread"},
  793. {0x0C, SvcWrap<GetThreadPriority>, "GetThreadPriority"},
  794. {0x0D, SvcWrap<SetThreadPriority>, "SetThreadPriority"},
  795. {0x0E, SvcWrap<GetThreadCoreMask>, "GetThreadCoreMask"},
  796. {0x0F, SvcWrap<SetThreadCoreMask>, "SetThreadCoreMask"},
  797. {0x10, SvcWrap<GetCurrentProcessorNumber>, "GetCurrentProcessorNumber"},
  798. {0x11, nullptr, "SignalEvent"},
  799. {0x12, SvcWrap<ClearEvent>, "ClearEvent"},
  800. {0x13, SvcWrap<MapSharedMemory>, "MapSharedMemory"},
  801. {0x14, SvcWrap<UnmapSharedMemory>, "UnmapSharedMemory"},
  802. {0x15, SvcWrap<CreateTransferMemory>, "CreateTransferMemory"},
  803. {0x16, SvcWrap<CloseHandle>, "CloseHandle"},
  804. {0x17, SvcWrap<ResetSignal>, "ResetSignal"},
  805. {0x18, SvcWrap<WaitSynchronization>, "WaitSynchronization"},
  806. {0x19, SvcWrap<CancelSynchronization>, "CancelSynchronization"},
  807. {0x1A, SvcWrap<ArbitrateLock>, "ArbitrateLock"},
  808. {0x1B, SvcWrap<ArbitrateUnlock>, "ArbitrateUnlock"},
  809. {0x1C, SvcWrap<WaitProcessWideKeyAtomic>, "WaitProcessWideKeyAtomic"},
  810. {0x1D, SvcWrap<SignalProcessWideKey>, "SignalProcessWideKey"},
  811. {0x1E, SvcWrap<GetSystemTick>, "GetSystemTick"},
  812. {0x1F, SvcWrap<ConnectToNamedPort>, "ConnectToNamedPort"},
  813. {0x20, nullptr, "SendSyncRequestLight"},
  814. {0x21, SvcWrap<SendSyncRequest>, "SendSyncRequest"},
  815. {0x22, nullptr, "SendSyncRequestWithUserBuffer"},
  816. {0x23, nullptr, "SendAsyncRequestWithUserBuffer"},
  817. {0x24, SvcWrap<GetProcessId>, "GetProcessId"},
  818. {0x25, SvcWrap<GetThreadId>, "GetThreadId"},
  819. {0x26, SvcWrap<Break>, "Break"},
  820. {0x27, SvcWrap<OutputDebugString>, "OutputDebugString"},
  821. {0x28, nullptr, "ReturnFromException"},
  822. {0x29, SvcWrap<GetInfo>, "GetInfo"},
  823. {0x2A, nullptr, "FlushEntireDataCache"},
  824. {0x2B, nullptr, "FlushDataCache"},
  825. {0x2C, nullptr, "MapPhysicalMemory"},
  826. {0x2D, nullptr, "UnmapPhysicalMemory"},
  827. {0x2E, nullptr, "GetNextThreadInfo"},
  828. {0x2F, nullptr, "GetLastThreadInfo"},
  829. {0x30, nullptr, "GetResourceLimitLimitValue"},
  830. {0x31, nullptr, "GetResourceLimitCurrentValue"},
  831. {0x32, SvcWrap<SetThreadActivity>, "SetThreadActivity"},
  832. {0x33, SvcWrap<GetThreadContext>, "GetThreadContext"},
  833. {0x34, SvcWrap<WaitForAddress>, "WaitForAddress"},
  834. {0x35, SvcWrap<SignalToAddress>, "SignalToAddress"},
  835. {0x36, nullptr, "Unknown"},
  836. {0x37, nullptr, "Unknown"},
  837. {0x38, nullptr, "Unknown"},
  838. {0x39, nullptr, "Unknown"},
  839. {0x3A, nullptr, "Unknown"},
  840. {0x3B, nullptr, "Unknown"},
  841. {0x3C, nullptr, "DumpInfo"},
  842. {0x3D, nullptr, "DumpInfoNew"},
  843. {0x3E, nullptr, "Unknown"},
  844. {0x3F, nullptr, "Unknown"},
  845. {0x40, nullptr, "CreateSession"},
  846. {0x41, nullptr, "AcceptSession"},
  847. {0x42, nullptr, "ReplyAndReceiveLight"},
  848. {0x43, nullptr, "ReplyAndReceive"},
  849. {0x44, nullptr, "ReplyAndReceiveWithUserBuffer"},
  850. {0x45, nullptr, "CreateEvent"},
  851. {0x46, nullptr, "Unknown"},
  852. {0x47, nullptr, "Unknown"},
  853. {0x48, nullptr, "AllocateUnsafeMemory"},
  854. {0x49, nullptr, "FreeUnsafeMemory"},
  855. {0x4A, nullptr, "SetUnsafeAllocationLimit"},
  856. {0x4B, nullptr, "CreateJitMemory"},
  857. {0x4C, nullptr, "MapJitMemory"},
  858. {0x4D, nullptr, "SleepSystem"},
  859. {0x4E, nullptr, "ReadWriteRegister"},
  860. {0x4F, nullptr, "SetProcessActivity"},
  861. {0x50, SvcWrap<CreateSharedMemory>, "CreateSharedMemory"},
  862. {0x51, nullptr, "MapTransferMemory"},
  863. {0x52, nullptr, "UnmapTransferMemory"},
  864. {0x53, nullptr, "CreateInterruptEvent"},
  865. {0x54, nullptr, "QueryPhysicalAddress"},
  866. {0x55, nullptr, "QueryIoMapping"},
  867. {0x56, nullptr, "CreateDeviceAddressSpace"},
  868. {0x57, nullptr, "AttachDeviceAddressSpace"},
  869. {0x58, nullptr, "DetachDeviceAddressSpace"},
  870. {0x59, nullptr, "MapDeviceAddressSpaceByForce"},
  871. {0x5A, nullptr, "MapDeviceAddressSpaceAligned"},
  872. {0x5B, nullptr, "MapDeviceAddressSpace"},
  873. {0x5C, nullptr, "UnmapDeviceAddressSpace"},
  874. {0x5D, nullptr, "InvalidateProcessDataCache"},
  875. {0x5E, nullptr, "StoreProcessDataCache"},
  876. {0x5F, nullptr, "FlushProcessDataCache"},
  877. {0x60, nullptr, "DebugActiveProcess"},
  878. {0x61, nullptr, "BreakDebugProcess"},
  879. {0x62, nullptr, "TerminateDebugProcess"},
  880. {0x63, nullptr, "GetDebugEvent"},
  881. {0x64, nullptr, "ContinueDebugEvent"},
  882. {0x65, nullptr, "GetProcessList"},
  883. {0x66, nullptr, "GetThreadList"},
  884. {0x67, nullptr, "GetDebugThreadContext"},
  885. {0x68, nullptr, "SetDebugThreadContext"},
  886. {0x69, nullptr, "QueryDebugProcessMemory"},
  887. {0x6A, nullptr, "ReadDebugProcessMemory"},
  888. {0x6B, nullptr, "WriteDebugProcessMemory"},
  889. {0x6C, nullptr, "SetHardwareBreakPoint"},
  890. {0x6D, nullptr, "GetDebugThreadParam"},
  891. {0x6E, nullptr, "Unknown"},
  892. {0x6F, nullptr, "GetMemoryInfo"},
  893. {0x70, nullptr, "CreatePort"},
  894. {0x71, nullptr, "ManageNamedPort"},
  895. {0x72, nullptr, "ConnectToPort"},
  896. {0x73, nullptr, "SetProcessMemoryPermission"},
  897. {0x74, nullptr, "MapProcessMemory"},
  898. {0x75, nullptr, "UnmapProcessMemory"},
  899. {0x76, nullptr, "QueryProcessMemory"},
  900. {0x77, nullptr, "MapProcessCodeMemory"},
  901. {0x78, nullptr, "UnmapProcessCodeMemory"},
  902. {0x79, nullptr, "CreateProcess"},
  903. {0x7A, nullptr, "StartProcess"},
  904. {0x7B, nullptr, "TerminateProcess"},
  905. {0x7C, nullptr, "GetProcessInfo"},
  906. {0x7D, nullptr, "CreateResourceLimit"},
  907. {0x7E, nullptr, "SetResourceLimitLimitValue"},
  908. {0x7F, nullptr, "CallSecureMonitor"},
  909. };
  910. static const FunctionDef* GetSVCInfo(u32 func_num) {
  911. if (func_num >= std::size(SVC_Table)) {
  912. LOG_ERROR(Kernel_SVC, "Unknown svc=0x{:02X}", func_num);
  913. return nullptr;
  914. }
  915. return &SVC_Table[func_num];
  916. }
  917. MICROPROFILE_DEFINE(Kernel_SVC, "Kernel", "SVC", MP_RGB(70, 200, 70));
  918. void CallSVC(u32 immediate) {
  919. MICROPROFILE_SCOPE(Kernel_SVC);
  920. // Lock the global kernel mutex when we enter the kernel HLE.
  921. std::lock_guard<std::recursive_mutex> lock(HLE::g_hle_lock);
  922. const FunctionDef* info = GetSVCInfo(immediate);
  923. if (info) {
  924. if (info->func) {
  925. info->func();
  926. } else {
  927. LOG_CRITICAL(Kernel_SVC, "Unimplemented SVC function {}(..)", info->name);
  928. }
  929. } else {
  930. LOG_CRITICAL(Kernel_SVC, "Unknown SVC function 0x{:X}", immediate);
  931. }
  932. }
  933. } // namespace Kernel