svc.cpp 41 KB

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