svc.cpp 43 KB

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