svc.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  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, std::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. if (Memory::IsKernelVirtualAddress(mutex_addr)) {
  226. return ERR_INVALID_ADDRESS_STATE;
  227. }
  228. auto& handle_table = Core::System::GetInstance().Kernel().HandleTable();
  229. return Mutex::TryAcquire(handle_table, mutex_addr, holding_thread_handle,
  230. requesting_thread_handle);
  231. }
  232. /// Unlock a mutex
  233. static ResultCode ArbitrateUnlock(VAddr mutex_addr) {
  234. LOG_TRACE(Kernel_SVC, "called mutex_addr=0x{:X}", mutex_addr);
  235. if (Memory::IsKernelVirtualAddress(mutex_addr)) {
  236. return ERR_INVALID_ADDRESS_STATE;
  237. }
  238. return Mutex::Release(mutex_addr);
  239. }
  240. /// Break program execution
  241. static void Break(u64 reason, u64 info1, u64 info2) {
  242. LOG_CRITICAL(
  243. Debug_Emulated,
  244. "Emulated program broke execution! reason=0x{:016X}, info1=0x{:016X}, info2=0x{:016X}",
  245. reason, info1, info2);
  246. ASSERT(false);
  247. }
  248. /// Used to output a message on a debug hardware unit - does nothing on a retail unit
  249. static void OutputDebugString(VAddr address, u64 len) {
  250. if (len == 0) {
  251. return;
  252. }
  253. std::string str(len, '\0');
  254. Memory::ReadBlock(address, str.data(), str.size());
  255. LOG_DEBUG(Debug_Emulated, "{}", str);
  256. }
  257. /// Gets system/memory information for the current process
  258. static ResultCode GetInfo(u64* result, u64 info_id, u64 handle, u64 info_sub_id) {
  259. LOG_TRACE(Kernel_SVC, "called info_id=0x{:X}, info_sub_id=0x{:X}, handle=0x{:08X}", info_id,
  260. info_sub_id, handle);
  261. const auto& vm_manager = Core::CurrentProcess()->vm_manager;
  262. switch (static_cast<GetInfoType>(info_id)) {
  263. case GetInfoType::AllowedCpuIdBitmask:
  264. *result = Core::CurrentProcess()->allowed_processor_mask;
  265. break;
  266. case GetInfoType::AllowedThreadPrioBitmask:
  267. *result = Core::CurrentProcess()->allowed_thread_priority_mask;
  268. break;
  269. case GetInfoType::MapRegionBaseAddr:
  270. *result = Memory::MAP_REGION_VADDR;
  271. break;
  272. case GetInfoType::MapRegionSize:
  273. *result = Memory::MAP_REGION_SIZE;
  274. break;
  275. case GetInfoType::HeapRegionBaseAddr:
  276. *result = Memory::HEAP_VADDR;
  277. break;
  278. case GetInfoType::HeapRegionSize:
  279. *result = Memory::HEAP_SIZE;
  280. break;
  281. case GetInfoType::TotalMemoryUsage:
  282. *result = vm_manager.GetTotalMemoryUsage();
  283. break;
  284. case GetInfoType::TotalHeapUsage:
  285. *result = vm_manager.GetTotalHeapUsage();
  286. break;
  287. case GetInfoType::IsCurrentProcessBeingDebugged:
  288. *result = 0;
  289. break;
  290. case GetInfoType::RandomEntropy:
  291. *result = 0;
  292. break;
  293. case GetInfoType::AddressSpaceBaseAddr:
  294. *result = vm_manager.GetAddressSpaceBaseAddr();
  295. break;
  296. case GetInfoType::AddressSpaceSize:
  297. *result = vm_manager.GetAddressSpaceSize();
  298. break;
  299. case GetInfoType::NewMapRegionBaseAddr:
  300. *result = Memory::NEW_MAP_REGION_VADDR;
  301. break;
  302. case GetInfoType::NewMapRegionSize:
  303. *result = Memory::NEW_MAP_REGION_SIZE;
  304. break;
  305. case GetInfoType::IsVirtualAddressMemoryEnabled:
  306. *result = Core::CurrentProcess()->is_virtual_address_memory_enabled;
  307. break;
  308. case GetInfoType::TitleId:
  309. *result = Core::CurrentProcess()->program_id;
  310. break;
  311. case GetInfoType::PrivilegedProcessId:
  312. LOG_WARNING(Kernel_SVC,
  313. "(STUBBED) Attempted to query privileged process id bounds, returned 0");
  314. *result = 0;
  315. break;
  316. case GetInfoType::UserExceptionContextAddr:
  317. LOG_WARNING(Kernel_SVC,
  318. "(STUBBED) Attempted to query user exception context address, returned 0");
  319. *result = 0;
  320. break;
  321. default:
  322. UNIMPLEMENTED();
  323. }
  324. return RESULT_SUCCESS;
  325. }
  326. /// Sets the thread activity
  327. static ResultCode SetThreadActivity(Handle handle, u32 unknown) {
  328. LOG_WARNING(Kernel_SVC, "(STUBBED) called, handle=0x{:08X}, unknown=0x{:08X}", handle, unknown);
  329. return RESULT_SUCCESS;
  330. }
  331. /// Gets the thread context
  332. static ResultCode GetThreadContext(Handle handle, VAddr addr) {
  333. LOG_WARNING(Kernel_SVC, "(STUBBED) called, handle=0x{:08X}, addr=0x{:X}", handle, addr);
  334. return RESULT_SUCCESS;
  335. }
  336. /// Gets the priority for the specified thread
  337. static ResultCode GetThreadPriority(u32* priority, Handle handle) {
  338. auto& kernel = Core::System::GetInstance().Kernel();
  339. const SharedPtr<Thread> thread = kernel.HandleTable().Get<Thread>(handle);
  340. if (!thread)
  341. return ERR_INVALID_HANDLE;
  342. *priority = thread->GetPriority();
  343. return RESULT_SUCCESS;
  344. }
  345. /// Sets the priority for the specified thread
  346. static ResultCode SetThreadPriority(Handle handle, u32 priority) {
  347. if (priority > THREADPRIO_LOWEST) {
  348. return ERR_INVALID_THREAD_PRIORITY;
  349. }
  350. auto& kernel = Core::System::GetInstance().Kernel();
  351. SharedPtr<Thread> thread = kernel.HandleTable().Get<Thread>(handle);
  352. if (!thread)
  353. return ERR_INVALID_HANDLE;
  354. // Note: The kernel uses the current process's resource limit instead of
  355. // the one from the thread owner's resource limit.
  356. SharedPtr<ResourceLimit>& resource_limit = Core::CurrentProcess()->resource_limit;
  357. if (resource_limit->GetMaxResourceValue(ResourceType::Priority) > priority) {
  358. return ERR_NOT_AUTHORIZED;
  359. }
  360. thread->SetPriority(priority);
  361. Core::System::GetInstance().CpuCore(thread->processor_id).PrepareReschedule();
  362. return RESULT_SUCCESS;
  363. }
  364. /// Get which CPU core is executing the current thread
  365. static u32 GetCurrentProcessorNumber() {
  366. LOG_TRACE(Kernel_SVC, "called");
  367. return GetCurrentThread()->processor_id;
  368. }
  369. static ResultCode MapSharedMemory(Handle shared_memory_handle, VAddr addr, u64 size,
  370. u32 permissions) {
  371. LOG_TRACE(Kernel_SVC,
  372. "called, shared_memory_handle=0x{:X}, addr=0x{:X}, size=0x{:X}, permissions=0x{:08X}",
  373. shared_memory_handle, addr, size, permissions);
  374. if (!Is4KBAligned(addr)) {
  375. return ERR_INVALID_ADDRESS;
  376. }
  377. if (size == 0 || !Is4KBAligned(size)) {
  378. return ERR_INVALID_SIZE;
  379. }
  380. const auto permissions_type = static_cast<MemoryPermission>(permissions);
  381. if (permissions_type != MemoryPermission::Read &&
  382. permissions_type != MemoryPermission::ReadWrite) {
  383. LOG_ERROR(Kernel_SVC, "Invalid permissions=0x{:08X}", permissions);
  384. return ERR_INVALID_MEMORY_PERMISSIONS;
  385. }
  386. auto& kernel = Core::System::GetInstance().Kernel();
  387. auto shared_memory = kernel.HandleTable().Get<SharedMemory>(shared_memory_handle);
  388. if (!shared_memory) {
  389. return ERR_INVALID_HANDLE;
  390. }
  391. return shared_memory->Map(Core::CurrentProcess().get(), addr, permissions_type,
  392. MemoryPermission::DontCare);
  393. }
  394. static ResultCode UnmapSharedMemory(Handle shared_memory_handle, VAddr addr, u64 size) {
  395. LOG_WARNING(Kernel_SVC, "called, shared_memory_handle=0x{:08X}, addr=0x{:X}, size=0x{:X}",
  396. shared_memory_handle, addr, size);
  397. if (!Is4KBAligned(addr)) {
  398. return ERR_INVALID_ADDRESS;
  399. }
  400. if (size == 0 || !Is4KBAligned(size)) {
  401. return ERR_INVALID_SIZE;
  402. }
  403. auto& kernel = Core::System::GetInstance().Kernel();
  404. auto shared_memory = kernel.HandleTable().Get<SharedMemory>(shared_memory_handle);
  405. return shared_memory->Unmap(Core::CurrentProcess().get(), addr);
  406. }
  407. /// Query process memory
  408. static ResultCode QueryProcessMemory(MemoryInfo* memory_info, PageInfo* /*page_info*/,
  409. Handle process_handle, u64 addr) {
  410. auto& kernel = Core::System::GetInstance().Kernel();
  411. SharedPtr<Process> process = kernel.HandleTable().Get<Process>(process_handle);
  412. if (!process) {
  413. return ERR_INVALID_HANDLE;
  414. }
  415. auto vma = process->vm_manager.FindVMA(addr);
  416. memory_info->attributes = 0;
  417. if (vma == Core::CurrentProcess()->vm_manager.vma_map.end()) {
  418. memory_info->base_address = 0;
  419. memory_info->permission = static_cast<u32>(VMAPermission::None);
  420. memory_info->size = 0;
  421. memory_info->type = static_cast<u32>(MemoryState::Unmapped);
  422. } else {
  423. memory_info->base_address = vma->second.base;
  424. memory_info->permission = static_cast<u32>(vma->second.permissions);
  425. memory_info->size = vma->second.size;
  426. memory_info->type = static_cast<u32>(vma->second.meminfo_state);
  427. }
  428. LOG_TRACE(Kernel_SVC, "called process=0x{:08X} addr={:X}", process_handle, addr);
  429. return RESULT_SUCCESS;
  430. }
  431. /// Query memory
  432. static ResultCode QueryMemory(MemoryInfo* memory_info, PageInfo* page_info, VAddr addr) {
  433. LOG_TRACE(Kernel_SVC, "called, addr={:X}", addr);
  434. return QueryProcessMemory(memory_info, page_info, CurrentProcess, addr);
  435. }
  436. /// Exits the current process
  437. static void ExitProcess() {
  438. LOG_INFO(Kernel_SVC, "Process {} exiting", Core::CurrentProcess()->process_id);
  439. ASSERT_MSG(Core::CurrentProcess()->status == ProcessStatus::Running,
  440. "Process has already exited");
  441. Core::CurrentProcess()->status = ProcessStatus::Exited;
  442. auto stop_threads = [](const std::vector<SharedPtr<Thread>>& thread_list) {
  443. for (auto& thread : thread_list) {
  444. if (thread->owner_process != Core::CurrentProcess())
  445. continue;
  446. if (thread == GetCurrentThread())
  447. continue;
  448. // TODO(Subv): When are the other running/ready threads terminated?
  449. ASSERT_MSG(thread->status == ThreadStatus::WaitSynchAny ||
  450. thread->status == ThreadStatus::WaitSynchAll,
  451. "Exiting processes with non-waiting threads is currently unimplemented");
  452. thread->Stop();
  453. }
  454. };
  455. auto& system = Core::System::GetInstance();
  456. stop_threads(system.Scheduler(0)->GetThreadList());
  457. stop_threads(system.Scheduler(1)->GetThreadList());
  458. stop_threads(system.Scheduler(2)->GetThreadList());
  459. stop_threads(system.Scheduler(3)->GetThreadList());
  460. // Kill the current thread
  461. GetCurrentThread()->Stop();
  462. Core::System::GetInstance().PrepareReschedule();
  463. }
  464. /// Creates a new thread
  465. static ResultCode CreateThread(Handle* out_handle, VAddr entry_point, u64 arg, VAddr stack_top,
  466. u32 priority, s32 processor_id) {
  467. std::string name = fmt::format("thread-{:X}", entry_point);
  468. if (priority > THREADPRIO_LOWEST) {
  469. return ERR_INVALID_THREAD_PRIORITY;
  470. }
  471. SharedPtr<ResourceLimit>& resource_limit = Core::CurrentProcess()->resource_limit;
  472. if (resource_limit->GetMaxResourceValue(ResourceType::Priority) > priority) {
  473. return ERR_NOT_AUTHORIZED;
  474. }
  475. if (processor_id == THREADPROCESSORID_DEFAULT) {
  476. // Set the target CPU to the one specified in the process' exheader.
  477. processor_id = Core::CurrentProcess()->ideal_processor;
  478. ASSERT(processor_id != THREADPROCESSORID_DEFAULT);
  479. }
  480. switch (processor_id) {
  481. case THREADPROCESSORID_0:
  482. case THREADPROCESSORID_1:
  483. case THREADPROCESSORID_2:
  484. case THREADPROCESSORID_3:
  485. break;
  486. default:
  487. LOG_ERROR(Kernel_SVC, "Invalid thread processor ID: {}", processor_id);
  488. return ERR_INVALID_PROCESSOR_ID;
  489. }
  490. auto& kernel = Core::System::GetInstance().Kernel();
  491. CASCADE_RESULT(SharedPtr<Thread> thread,
  492. Thread::Create(kernel, name, entry_point, priority, arg, processor_id, stack_top,
  493. Core::CurrentProcess()));
  494. CASCADE_RESULT(thread->guest_handle, kernel.HandleTable().Create(thread));
  495. *out_handle = thread->guest_handle;
  496. Core::System::GetInstance().CpuCore(thread->processor_id).PrepareReschedule();
  497. LOG_TRACE(Kernel_SVC,
  498. "called entrypoint=0x{:08X} ({}), arg=0x{:08X}, stacktop=0x{:08X}, "
  499. "threadpriority=0x{:08X}, processorid=0x{:08X} : created handle=0x{:08X}",
  500. entry_point, name, arg, stack_top, priority, processor_id, *out_handle);
  501. return RESULT_SUCCESS;
  502. }
  503. /// Starts the thread for the provided handle
  504. static ResultCode StartThread(Handle thread_handle) {
  505. LOG_TRACE(Kernel_SVC, "called thread=0x{:08X}", thread_handle);
  506. auto& kernel = Core::System::GetInstance().Kernel();
  507. const SharedPtr<Thread> thread = kernel.HandleTable().Get<Thread>(thread_handle);
  508. if (!thread) {
  509. return ERR_INVALID_HANDLE;
  510. }
  511. ASSERT(thread->status == ThreadStatus::Dormant);
  512. thread->ResumeFromWait();
  513. Core::System::GetInstance().CpuCore(thread->processor_id).PrepareReschedule();
  514. return RESULT_SUCCESS;
  515. }
  516. /// Called when a thread exits
  517. static void ExitThread() {
  518. LOG_TRACE(Kernel_SVC, "called, pc=0x{:08X}", Core::CurrentArmInterface().GetPC());
  519. ExitCurrentThread();
  520. Core::System::GetInstance().PrepareReschedule();
  521. }
  522. /// Sleep the current thread
  523. static void SleepThread(s64 nanoseconds) {
  524. LOG_TRACE(Kernel_SVC, "called nanoseconds={}", nanoseconds);
  525. // Don't attempt to yield execution if there are no available threads to run,
  526. // this way we avoid a useless reschedule to the idle thread.
  527. if (nanoseconds == 0 && !Core::System::GetInstance().CurrentScheduler().HaveReadyThreads())
  528. return;
  529. // Sleep current thread and check for next thread to schedule
  530. WaitCurrentThread_Sleep();
  531. // Create an event to wake the thread up after the specified nanosecond delay has passed
  532. GetCurrentThread()->WakeAfterDelay(nanoseconds);
  533. Core::System::GetInstance().PrepareReschedule();
  534. }
  535. /// Wait process wide key atomic
  536. static ResultCode WaitProcessWideKeyAtomic(VAddr mutex_addr, VAddr condition_variable_addr,
  537. Handle thread_handle, s64 nano_seconds) {
  538. LOG_TRACE(
  539. Kernel_SVC,
  540. "called mutex_addr={:X}, condition_variable_addr={:X}, thread_handle=0x{:08X}, timeout={}",
  541. mutex_addr, condition_variable_addr, thread_handle, nano_seconds);
  542. auto& kernel = Core::System::GetInstance().Kernel();
  543. SharedPtr<Thread> thread = kernel.HandleTable().Get<Thread>(thread_handle);
  544. ASSERT(thread);
  545. CASCADE_CODE(Mutex::Release(mutex_addr));
  546. SharedPtr<Thread> current_thread = GetCurrentThread();
  547. current_thread->condvar_wait_address = condition_variable_addr;
  548. current_thread->mutex_wait_address = mutex_addr;
  549. current_thread->wait_handle = thread_handle;
  550. current_thread->status = ThreadStatus::WaitMutex;
  551. current_thread->wakeup_callback = nullptr;
  552. current_thread->WakeAfterDelay(nano_seconds);
  553. // Note: Deliberately don't attempt to inherit the lock owner's priority.
  554. Core::System::GetInstance().CpuCore(current_thread->processor_id).PrepareReschedule();
  555. return RESULT_SUCCESS;
  556. }
  557. /// Signal process wide key
  558. static ResultCode SignalProcessWideKey(VAddr condition_variable_addr, s32 target) {
  559. LOG_TRACE(Kernel_SVC, "called, condition_variable_addr=0x{:X}, target=0x{:08X}",
  560. condition_variable_addr, target);
  561. auto RetrieveWaitingThreads = [](std::size_t core_index,
  562. std::vector<SharedPtr<Thread>>& waiting_threads,
  563. VAddr condvar_addr) {
  564. const auto& scheduler = Core::System::GetInstance().Scheduler(core_index);
  565. auto& thread_list = scheduler->GetThreadList();
  566. for (auto& thread : thread_list) {
  567. if (thread->condvar_wait_address == condvar_addr)
  568. waiting_threads.push_back(thread);
  569. }
  570. };
  571. // Retrieve a list of all threads that are waiting for this condition variable.
  572. std::vector<SharedPtr<Thread>> waiting_threads;
  573. RetrieveWaitingThreads(0, waiting_threads, condition_variable_addr);
  574. RetrieveWaitingThreads(1, waiting_threads, condition_variable_addr);
  575. RetrieveWaitingThreads(2, waiting_threads, condition_variable_addr);
  576. RetrieveWaitingThreads(3, waiting_threads, condition_variable_addr);
  577. // Sort them by priority, such that the highest priority ones come first.
  578. std::sort(waiting_threads.begin(), waiting_threads.end(),
  579. [](const SharedPtr<Thread>& lhs, const SharedPtr<Thread>& rhs) {
  580. return lhs->current_priority < rhs->current_priority;
  581. });
  582. // Only process up to 'target' threads, unless 'target' is -1, in which case process
  583. // them all.
  584. std::size_t last = waiting_threads.size();
  585. if (target != -1)
  586. last = target;
  587. // If there are no threads waiting on this condition variable, just exit
  588. if (last > waiting_threads.size())
  589. return RESULT_SUCCESS;
  590. for (std::size_t index = 0; index < last; ++index) {
  591. auto& thread = waiting_threads[index];
  592. ASSERT(thread->condvar_wait_address == condition_variable_addr);
  593. std::size_t current_core = Core::System::GetInstance().CurrentCoreIndex();
  594. auto& monitor = Core::System::GetInstance().Monitor();
  595. // Atomically read the value of the mutex.
  596. u32 mutex_val = 0;
  597. do {
  598. monitor.SetExclusive(current_core, thread->mutex_wait_address);
  599. // If the mutex is not yet acquired, acquire it.
  600. mutex_val = Memory::Read32(thread->mutex_wait_address);
  601. if (mutex_val != 0) {
  602. monitor.ClearExclusive();
  603. break;
  604. }
  605. } while (!monitor.ExclusiveWrite32(current_core, thread->mutex_wait_address,
  606. thread->wait_handle));
  607. if (mutex_val == 0) {
  608. // We were able to acquire the mutex, resume this thread.
  609. ASSERT(thread->status == ThreadStatus::WaitMutex);
  610. thread->ResumeFromWait();
  611. auto lock_owner = thread->lock_owner;
  612. if (lock_owner)
  613. lock_owner->RemoveMutexWaiter(thread);
  614. thread->lock_owner = nullptr;
  615. thread->mutex_wait_address = 0;
  616. thread->condvar_wait_address = 0;
  617. thread->wait_handle = 0;
  618. } else {
  619. // Atomically signal that the mutex now has a waiting thread.
  620. do {
  621. monitor.SetExclusive(current_core, thread->mutex_wait_address);
  622. // Ensure that the mutex value is still what we expect.
  623. u32 value = Memory::Read32(thread->mutex_wait_address);
  624. // TODO(Subv): When this happens, the kernel just clears the exclusive state and
  625. // retries the initial read for this thread.
  626. ASSERT_MSG(mutex_val == value, "Unhandled synchronization primitive case");
  627. } while (!monitor.ExclusiveWrite32(current_core, thread->mutex_wait_address,
  628. mutex_val | Mutex::MutexHasWaitersFlag));
  629. // The mutex is already owned by some other thread, make this thread wait on it.
  630. auto& kernel = Core::System::GetInstance().Kernel();
  631. Handle owner_handle = static_cast<Handle>(mutex_val & Mutex::MutexOwnerMask);
  632. auto owner = kernel.HandleTable().Get<Thread>(owner_handle);
  633. ASSERT(owner);
  634. ASSERT(thread->status == ThreadStatus::WaitMutex);
  635. thread->wakeup_callback = nullptr;
  636. owner->AddMutexWaiter(thread);
  637. Core::System::GetInstance().CpuCore(thread->processor_id).PrepareReschedule();
  638. }
  639. }
  640. return RESULT_SUCCESS;
  641. }
  642. // Wait for an address (via Address Arbiter)
  643. static ResultCode WaitForAddress(VAddr address, u32 type, s32 value, s64 timeout) {
  644. LOG_WARNING(Kernel_SVC, "called, address=0x{:X}, type=0x{:X}, value=0x{:X}, timeout={}",
  645. address, type, value, timeout);
  646. // If the passed address is a kernel virtual address, return invalid memory state.
  647. if (Memory::IsKernelVirtualAddress(address)) {
  648. return ERR_INVALID_ADDRESS_STATE;
  649. }
  650. // If the address is not properly aligned to 4 bytes, return invalid address.
  651. if (address % sizeof(u32) != 0) {
  652. return ERR_INVALID_ADDRESS;
  653. }
  654. switch (static_cast<AddressArbiter::ArbitrationType>(type)) {
  655. case AddressArbiter::ArbitrationType::WaitIfLessThan:
  656. return AddressArbiter::WaitForAddressIfLessThan(address, value, timeout, false);
  657. case AddressArbiter::ArbitrationType::DecrementAndWaitIfLessThan:
  658. return AddressArbiter::WaitForAddressIfLessThan(address, value, timeout, true);
  659. case AddressArbiter::ArbitrationType::WaitIfEqual:
  660. return AddressArbiter::WaitForAddressIfEqual(address, value, timeout);
  661. default:
  662. return ERR_INVALID_ENUM_VALUE;
  663. }
  664. }
  665. // Signals to an address (via Address Arbiter)
  666. static ResultCode SignalToAddress(VAddr address, u32 type, s32 value, s32 num_to_wake) {
  667. LOG_WARNING(Kernel_SVC, "called, address=0x{:X}, type=0x{:X}, value=0x{:X}, num_to_wake=0x{:X}",
  668. address, type, value, num_to_wake);
  669. // If the passed address is a kernel virtual address, return invalid memory state.
  670. if (Memory::IsKernelVirtualAddress(address)) {
  671. return ERR_INVALID_ADDRESS_STATE;
  672. }
  673. // If the address is not properly aligned to 4 bytes, return invalid address.
  674. if (address % sizeof(u32) != 0) {
  675. return ERR_INVALID_ADDRESS;
  676. }
  677. switch (static_cast<AddressArbiter::SignalType>(type)) {
  678. case AddressArbiter::SignalType::Signal:
  679. return AddressArbiter::SignalToAddress(address, num_to_wake);
  680. case AddressArbiter::SignalType::IncrementAndSignalIfEqual:
  681. return AddressArbiter::IncrementAndSignalToAddressIfEqual(address, value, num_to_wake);
  682. case AddressArbiter::SignalType::ModifyByWaitingCountAndSignalIfEqual:
  683. return AddressArbiter::ModifyByWaitingCountAndSignalToAddressIfEqual(address, value,
  684. num_to_wake);
  685. default:
  686. return ERR_INVALID_ENUM_VALUE;
  687. }
  688. }
  689. /// This returns the total CPU ticks elapsed since the CPU was powered-on
  690. static u64 GetSystemTick() {
  691. const u64 result{CoreTiming::GetTicks()};
  692. // Advance time to defeat dumb games that busy-wait for the frame to end.
  693. CoreTiming::AddTicks(400);
  694. return result;
  695. }
  696. /// Close a handle
  697. static ResultCode CloseHandle(Handle handle) {
  698. LOG_TRACE(Kernel_SVC, "Closing handle 0x{:08X}", handle);
  699. auto& kernel = Core::System::GetInstance().Kernel();
  700. return kernel.HandleTable().Close(handle);
  701. }
  702. /// Reset an event
  703. static ResultCode ResetSignal(Handle handle) {
  704. LOG_WARNING(Kernel_SVC, "(STUBBED) called handle 0x{:08X}", handle);
  705. auto& kernel = Core::System::GetInstance().Kernel();
  706. auto event = kernel.HandleTable().Get<Event>(handle);
  707. ASSERT(event != nullptr);
  708. event->Clear();
  709. return RESULT_SUCCESS;
  710. }
  711. /// Creates a TransferMemory object
  712. static ResultCode CreateTransferMemory(Handle* handle, VAddr addr, u64 size, u32 permissions) {
  713. LOG_WARNING(Kernel_SVC, "(STUBBED) called addr=0x{:X}, size=0x{:X}, perms=0x{:08X}", addr, size,
  714. permissions);
  715. *handle = 0;
  716. return RESULT_SUCCESS;
  717. }
  718. static ResultCode GetThreadCoreMask(Handle thread_handle, u32* core, u64* mask) {
  719. LOG_TRACE(Kernel_SVC, "called, handle=0x{:08X}", thread_handle);
  720. auto& kernel = Core::System::GetInstance().Kernel();
  721. const SharedPtr<Thread> thread = kernel.HandleTable().Get<Thread>(thread_handle);
  722. if (!thread) {
  723. return ERR_INVALID_HANDLE;
  724. }
  725. *core = thread->ideal_core;
  726. *mask = thread->affinity_mask;
  727. return RESULT_SUCCESS;
  728. }
  729. static ResultCode SetThreadCoreMask(Handle thread_handle, u32 core, u64 mask) {
  730. LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, mask=0x{:16X}, core=0x{:X}", thread_handle,
  731. mask, core);
  732. auto& kernel = Core::System::GetInstance().Kernel();
  733. const SharedPtr<Thread> thread = kernel.HandleTable().Get<Thread>(thread_handle);
  734. if (!thread) {
  735. return ERR_INVALID_HANDLE;
  736. }
  737. if (core == static_cast<u32>(THREADPROCESSORID_DEFAULT)) {
  738. ASSERT(thread->owner_process->ideal_processor !=
  739. static_cast<u8>(THREADPROCESSORID_DEFAULT));
  740. // Set the target CPU to the one specified in the process' exheader.
  741. core = thread->owner_process->ideal_processor;
  742. mask = 1ull << core;
  743. }
  744. if (mask == 0) {
  745. return ResultCode(ErrorModule::Kernel, ErrCodes::InvalidCombination);
  746. }
  747. /// This value is used to only change the affinity mask without changing the current ideal core.
  748. static constexpr u32 OnlyChangeMask = static_cast<u32>(-3);
  749. if (core == OnlyChangeMask) {
  750. core = thread->ideal_core;
  751. } else if (core >= Core::NUM_CPU_CORES && core != static_cast<u32>(-1)) {
  752. return ResultCode(ErrorModule::Kernel, ErrCodes::InvalidProcessorId);
  753. }
  754. // Error out if the input core isn't enabled in the input mask.
  755. if (core < Core::NUM_CPU_CORES && (mask & (1ull << core)) == 0) {
  756. return ResultCode(ErrorModule::Kernel, ErrCodes::InvalidCombination);
  757. }
  758. thread->ChangeCore(core, mask);
  759. return RESULT_SUCCESS;
  760. }
  761. static ResultCode CreateSharedMemory(Handle* handle, u64 size, u32 local_permissions,
  762. u32 remote_permissions) {
  763. LOG_TRACE(Kernel_SVC, "called, size=0x{:X}, localPerms=0x{:08X}, remotePerms=0x{:08X}", size,
  764. local_permissions, remote_permissions);
  765. // Size must be a multiple of 4KB and be less than or equal to
  766. // approx. 8 GB (actually (1GB - 512B) * 8)
  767. if (size == 0 || (size & 0xFFFFFFFE00000FFF) != 0) {
  768. return ERR_INVALID_SIZE;
  769. }
  770. const auto local_perms = static_cast<MemoryPermission>(local_permissions);
  771. if (local_perms != MemoryPermission::Read && local_perms != MemoryPermission::ReadWrite) {
  772. return ERR_INVALID_MEMORY_PERMISSIONS;
  773. }
  774. const auto remote_perms = static_cast<MemoryPermission>(remote_permissions);
  775. if (remote_perms != MemoryPermission::Read && remote_perms != MemoryPermission::ReadWrite &&
  776. remote_perms != MemoryPermission::DontCare) {
  777. return ERR_INVALID_MEMORY_PERMISSIONS;
  778. }
  779. auto& kernel = Core::System::GetInstance().Kernel();
  780. auto& handle_table = kernel.HandleTable();
  781. auto shared_mem_handle =
  782. SharedMemory::Create(kernel, handle_table.Get<Process>(KernelHandle::CurrentProcess), size,
  783. local_perms, remote_perms);
  784. CASCADE_RESULT(*handle, handle_table.Create(shared_mem_handle));
  785. return RESULT_SUCCESS;
  786. }
  787. static ResultCode ClearEvent(Handle handle) {
  788. LOG_TRACE(Kernel_SVC, "called, event=0x{:08X}", handle);
  789. auto& kernel = Core::System::GetInstance().Kernel();
  790. SharedPtr<Event> evt = kernel.HandleTable().Get<Event>(handle);
  791. if (evt == nullptr)
  792. return ERR_INVALID_HANDLE;
  793. evt->Clear();
  794. return RESULT_SUCCESS;
  795. }
  796. namespace {
  797. struct FunctionDef {
  798. using Func = void();
  799. u32 id;
  800. Func* func;
  801. const char* name;
  802. };
  803. } // namespace
  804. static const FunctionDef SVC_Table[] = {
  805. {0x00, nullptr, "Unknown"},
  806. {0x01, SvcWrap<SetHeapSize>, "SetHeapSize"},
  807. {0x02, nullptr, "SetMemoryPermission"},
  808. {0x03, SvcWrap<SetMemoryAttribute>, "SetMemoryAttribute"},
  809. {0x04, SvcWrap<MapMemory>, "MapMemory"},
  810. {0x05, SvcWrap<UnmapMemory>, "UnmapMemory"},
  811. {0x06, SvcWrap<QueryMemory>, "QueryMemory"},
  812. {0x07, SvcWrap<ExitProcess>, "ExitProcess"},
  813. {0x08, SvcWrap<CreateThread>, "CreateThread"},
  814. {0x09, SvcWrap<StartThread>, "StartThread"},
  815. {0x0A, SvcWrap<ExitThread>, "ExitThread"},
  816. {0x0B, SvcWrap<SleepThread>, "SleepThread"},
  817. {0x0C, SvcWrap<GetThreadPriority>, "GetThreadPriority"},
  818. {0x0D, SvcWrap<SetThreadPriority>, "SetThreadPriority"},
  819. {0x0E, SvcWrap<GetThreadCoreMask>, "GetThreadCoreMask"},
  820. {0x0F, SvcWrap<SetThreadCoreMask>, "SetThreadCoreMask"},
  821. {0x10, SvcWrap<GetCurrentProcessorNumber>, "GetCurrentProcessorNumber"},
  822. {0x11, nullptr, "SignalEvent"},
  823. {0x12, SvcWrap<ClearEvent>, "ClearEvent"},
  824. {0x13, SvcWrap<MapSharedMemory>, "MapSharedMemory"},
  825. {0x14, SvcWrap<UnmapSharedMemory>, "UnmapSharedMemory"},
  826. {0x15, SvcWrap<CreateTransferMemory>, "CreateTransferMemory"},
  827. {0x16, SvcWrap<CloseHandle>, "CloseHandle"},
  828. {0x17, SvcWrap<ResetSignal>, "ResetSignal"},
  829. {0x18, SvcWrap<WaitSynchronization>, "WaitSynchronization"},
  830. {0x19, SvcWrap<CancelSynchronization>, "CancelSynchronization"},
  831. {0x1A, SvcWrap<ArbitrateLock>, "ArbitrateLock"},
  832. {0x1B, SvcWrap<ArbitrateUnlock>, "ArbitrateUnlock"},
  833. {0x1C, SvcWrap<WaitProcessWideKeyAtomic>, "WaitProcessWideKeyAtomic"},
  834. {0x1D, SvcWrap<SignalProcessWideKey>, "SignalProcessWideKey"},
  835. {0x1E, SvcWrap<GetSystemTick>, "GetSystemTick"},
  836. {0x1F, SvcWrap<ConnectToNamedPort>, "ConnectToNamedPort"},
  837. {0x20, nullptr, "SendSyncRequestLight"},
  838. {0x21, SvcWrap<SendSyncRequest>, "SendSyncRequest"},
  839. {0x22, nullptr, "SendSyncRequestWithUserBuffer"},
  840. {0x23, nullptr, "SendAsyncRequestWithUserBuffer"},
  841. {0x24, SvcWrap<GetProcessId>, "GetProcessId"},
  842. {0x25, SvcWrap<GetThreadId>, "GetThreadId"},
  843. {0x26, SvcWrap<Break>, "Break"},
  844. {0x27, SvcWrap<OutputDebugString>, "OutputDebugString"},
  845. {0x28, nullptr, "ReturnFromException"},
  846. {0x29, SvcWrap<GetInfo>, "GetInfo"},
  847. {0x2A, nullptr, "FlushEntireDataCache"},
  848. {0x2B, nullptr, "FlushDataCache"},
  849. {0x2C, nullptr, "MapPhysicalMemory"},
  850. {0x2D, nullptr, "UnmapPhysicalMemory"},
  851. {0x2E, nullptr, "GetNextThreadInfo"},
  852. {0x2F, nullptr, "GetLastThreadInfo"},
  853. {0x30, nullptr, "GetResourceLimitLimitValue"},
  854. {0x31, nullptr, "GetResourceLimitCurrentValue"},
  855. {0x32, SvcWrap<SetThreadActivity>, "SetThreadActivity"},
  856. {0x33, SvcWrap<GetThreadContext>, "GetThreadContext"},
  857. {0x34, SvcWrap<WaitForAddress>, "WaitForAddress"},
  858. {0x35, SvcWrap<SignalToAddress>, "SignalToAddress"},
  859. {0x36, nullptr, "Unknown"},
  860. {0x37, nullptr, "Unknown"},
  861. {0x38, nullptr, "Unknown"},
  862. {0x39, nullptr, "Unknown"},
  863. {0x3A, nullptr, "Unknown"},
  864. {0x3B, nullptr, "Unknown"},
  865. {0x3C, nullptr, "DumpInfo"},
  866. {0x3D, nullptr, "DumpInfoNew"},
  867. {0x3E, nullptr, "Unknown"},
  868. {0x3F, nullptr, "Unknown"},
  869. {0x40, nullptr, "CreateSession"},
  870. {0x41, nullptr, "AcceptSession"},
  871. {0x42, nullptr, "ReplyAndReceiveLight"},
  872. {0x43, nullptr, "ReplyAndReceive"},
  873. {0x44, nullptr, "ReplyAndReceiveWithUserBuffer"},
  874. {0x45, nullptr, "CreateEvent"},
  875. {0x46, nullptr, "Unknown"},
  876. {0x47, nullptr, "Unknown"},
  877. {0x48, nullptr, "AllocateUnsafeMemory"},
  878. {0x49, nullptr, "FreeUnsafeMemory"},
  879. {0x4A, nullptr, "SetUnsafeAllocationLimit"},
  880. {0x4B, nullptr, "CreateJitMemory"},
  881. {0x4C, nullptr, "MapJitMemory"},
  882. {0x4D, nullptr, "SleepSystem"},
  883. {0x4E, nullptr, "ReadWriteRegister"},
  884. {0x4F, nullptr, "SetProcessActivity"},
  885. {0x50, SvcWrap<CreateSharedMemory>, "CreateSharedMemory"},
  886. {0x51, nullptr, "MapTransferMemory"},
  887. {0x52, nullptr, "UnmapTransferMemory"},
  888. {0x53, nullptr, "CreateInterruptEvent"},
  889. {0x54, nullptr, "QueryPhysicalAddress"},
  890. {0x55, nullptr, "QueryIoMapping"},
  891. {0x56, nullptr, "CreateDeviceAddressSpace"},
  892. {0x57, nullptr, "AttachDeviceAddressSpace"},
  893. {0x58, nullptr, "DetachDeviceAddressSpace"},
  894. {0x59, nullptr, "MapDeviceAddressSpaceByForce"},
  895. {0x5A, nullptr, "MapDeviceAddressSpaceAligned"},
  896. {0x5B, nullptr, "MapDeviceAddressSpace"},
  897. {0x5C, nullptr, "UnmapDeviceAddressSpace"},
  898. {0x5D, nullptr, "InvalidateProcessDataCache"},
  899. {0x5E, nullptr, "StoreProcessDataCache"},
  900. {0x5F, nullptr, "FlushProcessDataCache"},
  901. {0x60, nullptr, "DebugActiveProcess"},
  902. {0x61, nullptr, "BreakDebugProcess"},
  903. {0x62, nullptr, "TerminateDebugProcess"},
  904. {0x63, nullptr, "GetDebugEvent"},
  905. {0x64, nullptr, "ContinueDebugEvent"},
  906. {0x65, nullptr, "GetProcessList"},
  907. {0x66, nullptr, "GetThreadList"},
  908. {0x67, nullptr, "GetDebugThreadContext"},
  909. {0x68, nullptr, "SetDebugThreadContext"},
  910. {0x69, nullptr, "QueryDebugProcessMemory"},
  911. {0x6A, nullptr, "ReadDebugProcessMemory"},
  912. {0x6B, nullptr, "WriteDebugProcessMemory"},
  913. {0x6C, nullptr, "SetHardwareBreakPoint"},
  914. {0x6D, nullptr, "GetDebugThreadParam"},
  915. {0x6E, nullptr, "Unknown"},
  916. {0x6F, nullptr, "GetMemoryInfo"},
  917. {0x70, nullptr, "CreatePort"},
  918. {0x71, nullptr, "ManageNamedPort"},
  919. {0x72, nullptr, "ConnectToPort"},
  920. {0x73, nullptr, "SetProcessMemoryPermission"},
  921. {0x74, nullptr, "MapProcessMemory"},
  922. {0x75, nullptr, "UnmapProcessMemory"},
  923. {0x76, nullptr, "QueryProcessMemory"},
  924. {0x77, nullptr, "MapProcessCodeMemory"},
  925. {0x78, nullptr, "UnmapProcessCodeMemory"},
  926. {0x79, nullptr, "CreateProcess"},
  927. {0x7A, nullptr, "StartProcess"},
  928. {0x7B, nullptr, "TerminateProcess"},
  929. {0x7C, nullptr, "GetProcessInfo"},
  930. {0x7D, nullptr, "CreateResourceLimit"},
  931. {0x7E, nullptr, "SetResourceLimitLimitValue"},
  932. {0x7F, nullptr, "CallSecureMonitor"},
  933. };
  934. static const FunctionDef* GetSVCInfo(u32 func_num) {
  935. if (func_num >= std::size(SVC_Table)) {
  936. LOG_ERROR(Kernel_SVC, "Unknown svc=0x{:02X}", func_num);
  937. return nullptr;
  938. }
  939. return &SVC_Table[func_num];
  940. }
  941. MICROPROFILE_DEFINE(Kernel_SVC, "Kernel", "SVC", MP_RGB(70, 200, 70));
  942. void CallSVC(u32 immediate) {
  943. MICROPROFILE_SCOPE(Kernel_SVC);
  944. // Lock the global kernel mutex when we enter the kernel HLE.
  945. std::lock_guard<std::recursive_mutex> lock(HLE::g_hle_lock);
  946. const FunctionDef* info = GetSVCInfo(immediate);
  947. if (info) {
  948. if (info->func) {
  949. info->func();
  950. } else {
  951. LOG_CRITICAL(Kernel_SVC, "Unimplemented SVC function {}(..)", info->name);
  952. }
  953. } else {
  954. LOG_CRITICAL(Kernel_SVC, "Unknown SVC function 0x{:X}", immediate);
  955. }
  956. }
  957. } // namespace Kernel