svc.cpp 44 KB

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