svc.cpp 40 KB

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