svc.cpp 41 KB

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