svc.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197
  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. struct BreakReason {
  242. union {
  243. u64 raw;
  244. BitField<31, 1, u64> dont_kill_application;
  245. };
  246. };
  247. /// Break program execution
  248. static void Break(u64 reason, u64 info1, u64 info2) {
  249. BreakReason break_reason{reason};
  250. if (break_reason.dont_kill_application) {
  251. LOG_ERROR(
  252. Debug_Emulated,
  253. "Emulated program broke execution! reason=0x{:016X}, info1=0x{:016X}, info2=0x{:016X}",
  254. reason, info1, info2);
  255. } else {
  256. LOG_CRITICAL(
  257. Debug_Emulated,
  258. "Emulated program broke execution! reason=0x{:016X}, info1=0x{:016X}, info2=0x{:016X}",
  259. reason, info1, info2);
  260. ASSERT(false);
  261. }
  262. }
  263. /// Used to output a message on a debug hardware unit - does nothing on a retail unit
  264. static void OutputDebugString(VAddr address, u64 len) {
  265. if (len == 0) {
  266. return;
  267. }
  268. std::string str(len, '\0');
  269. Memory::ReadBlock(address, str.data(), str.size());
  270. LOG_DEBUG(Debug_Emulated, "{}", str);
  271. }
  272. /// Gets system/memory information for the current process
  273. static ResultCode GetInfo(u64* result, u64 info_id, u64 handle, u64 info_sub_id) {
  274. LOG_TRACE(Kernel_SVC, "called info_id=0x{:X}, info_sub_id=0x{:X}, handle=0x{:08X}", info_id,
  275. info_sub_id, handle);
  276. const auto* current_process = Core::CurrentProcess();
  277. const auto& vm_manager = current_process->VMManager();
  278. switch (static_cast<GetInfoType>(info_id)) {
  279. case GetInfoType::AllowedCpuIdBitmask:
  280. *result = current_process->GetAllowedProcessorMask();
  281. break;
  282. case GetInfoType::AllowedThreadPrioBitmask:
  283. *result = current_process->GetAllowedThreadPriorityMask();
  284. break;
  285. case GetInfoType::MapRegionBaseAddr:
  286. *result = vm_manager.GetMapRegionBaseAddress();
  287. break;
  288. case GetInfoType::MapRegionSize:
  289. *result = vm_manager.GetMapRegionSize();
  290. break;
  291. case GetInfoType::HeapRegionBaseAddr:
  292. *result = vm_manager.GetHeapRegionBaseAddress();
  293. break;
  294. case GetInfoType::HeapRegionSize:
  295. *result = vm_manager.GetHeapRegionSize();
  296. break;
  297. case GetInfoType::TotalMemoryUsage:
  298. *result = vm_manager.GetTotalMemoryUsage();
  299. break;
  300. case GetInfoType::TotalHeapUsage:
  301. *result = vm_manager.GetTotalHeapUsage();
  302. break;
  303. case GetInfoType::IsCurrentProcessBeingDebugged:
  304. *result = 0;
  305. break;
  306. case GetInfoType::RandomEntropy:
  307. *result = 0;
  308. break;
  309. case GetInfoType::AddressSpaceBaseAddr:
  310. *result = vm_manager.GetCodeRegionBaseAddress();
  311. break;
  312. case GetInfoType::AddressSpaceSize: {
  313. const u64 width = vm_manager.GetAddressSpaceWidth();
  314. switch (width) {
  315. case 32:
  316. *result = 0xFFE00000;
  317. break;
  318. case 36:
  319. *result = 0xFF8000000;
  320. break;
  321. case 39:
  322. *result = 0x7FF8000000;
  323. break;
  324. }
  325. break;
  326. }
  327. case GetInfoType::NewMapRegionBaseAddr:
  328. *result = vm_manager.GetNewMapRegionBaseAddress();
  329. break;
  330. case GetInfoType::NewMapRegionSize:
  331. *result = vm_manager.GetNewMapRegionSize();
  332. break;
  333. case GetInfoType::IsVirtualAddressMemoryEnabled:
  334. *result = current_process->IsVirtualMemoryEnabled();
  335. break;
  336. case GetInfoType::TitleId:
  337. *result = current_process->GetTitleID();
  338. break;
  339. case GetInfoType::PrivilegedProcessId:
  340. LOG_WARNING(Kernel_SVC,
  341. "(STUBBED) Attempted to query privileged process id bounds, returned 0");
  342. *result = 0;
  343. break;
  344. case GetInfoType::UserExceptionContextAddr:
  345. LOG_WARNING(Kernel_SVC,
  346. "(STUBBED) Attempted to query user exception context address, returned 0");
  347. *result = 0;
  348. break;
  349. default:
  350. UNIMPLEMENTED();
  351. }
  352. return RESULT_SUCCESS;
  353. }
  354. /// Sets the thread activity
  355. static ResultCode SetThreadActivity(Handle handle, u32 unknown) {
  356. LOG_WARNING(Kernel_SVC, "(STUBBED) called, handle=0x{:08X}, unknown=0x{:08X}", handle, unknown);
  357. return RESULT_SUCCESS;
  358. }
  359. /// Gets the thread context
  360. static ResultCode GetThreadContext(VAddr thread_context, Handle handle) {
  361. LOG_DEBUG(Kernel_SVC, "called, context=0x{:08X}, thread=0x{:X}", thread_context, handle);
  362. auto& kernel = Core::System::GetInstance().Kernel();
  363. const SharedPtr<Thread> thread = kernel.HandleTable().Get<Thread>(handle);
  364. if (!thread) {
  365. return ERR_INVALID_HANDLE;
  366. }
  367. const auto* current_process = Core::CurrentProcess();
  368. if (thread->GetOwnerProcess() != current_process) {
  369. return ERR_INVALID_HANDLE;
  370. }
  371. if (thread == GetCurrentThread()) {
  372. return ERR_ALREADY_REGISTERED;
  373. }
  374. Core::ARM_Interface::ThreadContext ctx = thread->GetContext();
  375. // Mask away mode bits, interrupt bits, IL bit, and other reserved bits.
  376. ctx.pstate &= 0xFF0FFE20;
  377. // If 64-bit, we can just write the context registers directly and we're good.
  378. // However, if 32-bit, we have to ensure some registers are zeroed out.
  379. if (!current_process->Is64BitProcess()) {
  380. std::fill(ctx.cpu_registers.begin() + 15, ctx.cpu_registers.end(), 0);
  381. std::fill(ctx.vector_registers.begin() + 16, ctx.vector_registers.end(), u128{});
  382. }
  383. Memory::WriteBlock(thread_context, &ctx, sizeof(ctx));
  384. return RESULT_SUCCESS;
  385. }
  386. /// Gets the priority for the specified thread
  387. static ResultCode GetThreadPriority(u32* priority, Handle handle) {
  388. auto& kernel = Core::System::GetInstance().Kernel();
  389. const SharedPtr<Thread> thread = kernel.HandleTable().Get<Thread>(handle);
  390. if (!thread)
  391. return ERR_INVALID_HANDLE;
  392. *priority = thread->GetPriority();
  393. return RESULT_SUCCESS;
  394. }
  395. /// Sets the priority for the specified thread
  396. static ResultCode SetThreadPriority(Handle handle, u32 priority) {
  397. if (priority > THREADPRIO_LOWEST) {
  398. return ERR_INVALID_THREAD_PRIORITY;
  399. }
  400. auto& kernel = Core::System::GetInstance().Kernel();
  401. SharedPtr<Thread> thread = kernel.HandleTable().Get<Thread>(handle);
  402. if (!thread)
  403. return ERR_INVALID_HANDLE;
  404. // Note: The kernel uses the current process's resource limit instead of
  405. // the one from the thread owner's resource limit.
  406. const ResourceLimit& resource_limit = Core::CurrentProcess()->GetResourceLimit();
  407. if (resource_limit.GetMaxResourceValue(ResourceType::Priority) > priority) {
  408. return ERR_NOT_AUTHORIZED;
  409. }
  410. thread->SetPriority(priority);
  411. Core::System::GetInstance().CpuCore(thread->GetProcessorID()).PrepareReschedule();
  412. return RESULT_SUCCESS;
  413. }
  414. /// Get which CPU core is executing the current thread
  415. static u32 GetCurrentProcessorNumber() {
  416. LOG_TRACE(Kernel_SVC, "called");
  417. return GetCurrentThread()->GetProcessorID();
  418. }
  419. static ResultCode MapSharedMemory(Handle shared_memory_handle, VAddr addr, u64 size,
  420. u32 permissions) {
  421. LOG_TRACE(Kernel_SVC,
  422. "called, shared_memory_handle=0x{:X}, addr=0x{:X}, size=0x{:X}, permissions=0x{:08X}",
  423. shared_memory_handle, addr, size, permissions);
  424. if (!Is4KBAligned(addr)) {
  425. return ERR_INVALID_ADDRESS;
  426. }
  427. if (size == 0 || !Is4KBAligned(size)) {
  428. return ERR_INVALID_SIZE;
  429. }
  430. const auto permissions_type = static_cast<MemoryPermission>(permissions);
  431. if (permissions_type != MemoryPermission::Read &&
  432. permissions_type != MemoryPermission::ReadWrite) {
  433. LOG_ERROR(Kernel_SVC, "Invalid permissions=0x{:08X}", permissions);
  434. return ERR_INVALID_MEMORY_PERMISSIONS;
  435. }
  436. auto& kernel = Core::System::GetInstance().Kernel();
  437. auto shared_memory = kernel.HandleTable().Get<SharedMemory>(shared_memory_handle);
  438. if (!shared_memory) {
  439. return ERR_INVALID_HANDLE;
  440. }
  441. return shared_memory->Map(Core::CurrentProcess(), addr, permissions_type,
  442. MemoryPermission::DontCare);
  443. }
  444. static ResultCode UnmapSharedMemory(Handle shared_memory_handle, VAddr addr, u64 size) {
  445. LOG_WARNING(Kernel_SVC, "called, shared_memory_handle=0x{:08X}, addr=0x{:X}, size=0x{:X}",
  446. shared_memory_handle, addr, size);
  447. if (!Is4KBAligned(addr)) {
  448. return ERR_INVALID_ADDRESS;
  449. }
  450. if (size == 0 || !Is4KBAligned(size)) {
  451. return ERR_INVALID_SIZE;
  452. }
  453. auto& kernel = Core::System::GetInstance().Kernel();
  454. auto shared_memory = kernel.HandleTable().Get<SharedMemory>(shared_memory_handle);
  455. return shared_memory->Unmap(Core::CurrentProcess(), addr);
  456. }
  457. /// Query process memory
  458. static ResultCode QueryProcessMemory(MemoryInfo* memory_info, PageInfo* /*page_info*/,
  459. Handle process_handle, u64 addr) {
  460. auto& kernel = Core::System::GetInstance().Kernel();
  461. SharedPtr<Process> process = kernel.HandleTable().Get<Process>(process_handle);
  462. if (!process) {
  463. return ERR_INVALID_HANDLE;
  464. }
  465. auto vma = process->VMManager().FindVMA(addr);
  466. memory_info->attributes = 0;
  467. if (vma == Core::CurrentProcess()->VMManager().vma_map.end()) {
  468. memory_info->base_address = 0;
  469. memory_info->permission = static_cast<u32>(VMAPermission::None);
  470. memory_info->size = 0;
  471. memory_info->type = static_cast<u32>(MemoryState::Unmapped);
  472. } else {
  473. memory_info->base_address = vma->second.base;
  474. memory_info->permission = static_cast<u32>(vma->second.permissions);
  475. memory_info->size = vma->second.size;
  476. memory_info->type = static_cast<u32>(vma->second.meminfo_state);
  477. }
  478. LOG_TRACE(Kernel_SVC, "called process=0x{:08X} addr={:X}", process_handle, addr);
  479. return RESULT_SUCCESS;
  480. }
  481. /// Query memory
  482. static ResultCode QueryMemory(MemoryInfo* memory_info, PageInfo* page_info, VAddr addr) {
  483. LOG_TRACE(Kernel_SVC, "called, addr={:X}", addr);
  484. return QueryProcessMemory(memory_info, page_info, CurrentProcess, addr);
  485. }
  486. /// Exits the current process
  487. static void ExitProcess() {
  488. auto* current_process = Core::CurrentProcess();
  489. LOG_INFO(Kernel_SVC, "Process {} exiting", current_process->GetProcessID());
  490. ASSERT_MSG(current_process->GetStatus() == ProcessStatus::Running,
  491. "Process has already exited");
  492. current_process->PrepareForTermination();
  493. // Kill the current thread
  494. GetCurrentThread()->Stop();
  495. Core::System::GetInstance().PrepareReschedule();
  496. }
  497. /// Creates a new thread
  498. static ResultCode CreateThread(Handle* out_handle, VAddr entry_point, u64 arg, VAddr stack_top,
  499. u32 priority, s32 processor_id) {
  500. std::string name = fmt::format("thread-{:X}", entry_point);
  501. if (priority > THREADPRIO_LOWEST) {
  502. return ERR_INVALID_THREAD_PRIORITY;
  503. }
  504. const ResourceLimit& resource_limit = Core::CurrentProcess()->GetResourceLimit();
  505. if (resource_limit.GetMaxResourceValue(ResourceType::Priority) > priority) {
  506. return ERR_NOT_AUTHORIZED;
  507. }
  508. if (processor_id == THREADPROCESSORID_DEFAULT) {
  509. // Set the target CPU to the one specified in the process' exheader.
  510. processor_id = Core::CurrentProcess()->GetDefaultProcessorID();
  511. ASSERT(processor_id != THREADPROCESSORID_DEFAULT);
  512. }
  513. switch (processor_id) {
  514. case THREADPROCESSORID_0:
  515. case THREADPROCESSORID_1:
  516. case THREADPROCESSORID_2:
  517. case THREADPROCESSORID_3:
  518. break;
  519. default:
  520. LOG_ERROR(Kernel_SVC, "Invalid thread processor ID: {}", processor_id);
  521. return ERR_INVALID_PROCESSOR_ID;
  522. }
  523. auto& kernel = Core::System::GetInstance().Kernel();
  524. CASCADE_RESULT(SharedPtr<Thread> thread,
  525. Thread::Create(kernel, name, entry_point, priority, arg, processor_id, stack_top,
  526. *Core::CurrentProcess()));
  527. const auto new_guest_handle = kernel.HandleTable().Create(thread);
  528. if (new_guest_handle.Failed()) {
  529. return new_guest_handle.Code();
  530. }
  531. thread->SetGuestHandle(*new_guest_handle);
  532. *out_handle = *new_guest_handle;
  533. Core::System::GetInstance().CpuCore(thread->GetProcessorID()).PrepareReschedule();
  534. LOG_TRACE(Kernel_SVC,
  535. "called entrypoint=0x{:08X} ({}), arg=0x{:08X}, stacktop=0x{:08X}, "
  536. "threadpriority=0x{:08X}, processorid=0x{:08X} : created handle=0x{:08X}",
  537. entry_point, name, arg, stack_top, priority, processor_id, *out_handle);
  538. return RESULT_SUCCESS;
  539. }
  540. /// Starts the thread for the provided handle
  541. static ResultCode StartThread(Handle thread_handle) {
  542. LOG_TRACE(Kernel_SVC, "called thread=0x{:08X}", thread_handle);
  543. auto& kernel = Core::System::GetInstance().Kernel();
  544. const SharedPtr<Thread> thread = kernel.HandleTable().Get<Thread>(thread_handle);
  545. if (!thread) {
  546. return ERR_INVALID_HANDLE;
  547. }
  548. ASSERT(thread->GetStatus() == ThreadStatus::Dormant);
  549. thread->ResumeFromWait();
  550. Core::System::GetInstance().CpuCore(thread->GetProcessorID()).PrepareReschedule();
  551. return RESULT_SUCCESS;
  552. }
  553. /// Called when a thread exits
  554. static void ExitThread() {
  555. LOG_TRACE(Kernel_SVC, "called, pc=0x{:08X}", Core::CurrentArmInterface().GetPC());
  556. ExitCurrentThread();
  557. Core::System::GetInstance().PrepareReschedule();
  558. }
  559. /// Sleep the current thread
  560. static void SleepThread(s64 nanoseconds) {
  561. LOG_TRACE(Kernel_SVC, "called nanoseconds={}", nanoseconds);
  562. // Don't attempt to yield execution if there are no available threads to run,
  563. // this way we avoid a useless reschedule to the idle thread.
  564. if (nanoseconds == 0 && !Core::System::GetInstance().CurrentScheduler().HaveReadyThreads())
  565. return;
  566. // Sleep current thread and check for next thread to schedule
  567. WaitCurrentThread_Sleep();
  568. // Create an event to wake the thread up after the specified nanosecond delay has passed
  569. GetCurrentThread()->WakeAfterDelay(nanoseconds);
  570. Core::System::GetInstance().PrepareReschedule();
  571. }
  572. /// Wait process wide key atomic
  573. static ResultCode WaitProcessWideKeyAtomic(VAddr mutex_addr, VAddr condition_variable_addr,
  574. Handle thread_handle, s64 nano_seconds) {
  575. LOG_TRACE(
  576. Kernel_SVC,
  577. "called mutex_addr={:X}, condition_variable_addr={:X}, thread_handle=0x{:08X}, timeout={}",
  578. mutex_addr, condition_variable_addr, thread_handle, nano_seconds);
  579. auto& kernel = Core::System::GetInstance().Kernel();
  580. SharedPtr<Thread> thread = kernel.HandleTable().Get<Thread>(thread_handle);
  581. ASSERT(thread);
  582. CASCADE_CODE(Mutex::Release(mutex_addr));
  583. SharedPtr<Thread> current_thread = GetCurrentThread();
  584. current_thread->SetCondVarWaitAddress(condition_variable_addr);
  585. current_thread->SetMutexWaitAddress(mutex_addr);
  586. current_thread->SetWaitHandle(thread_handle);
  587. current_thread->SetStatus(ThreadStatus::WaitMutex);
  588. current_thread->InvalidateWakeupCallback();
  589. current_thread->WakeAfterDelay(nano_seconds);
  590. // Note: Deliberately don't attempt to inherit the lock owner's priority.
  591. Core::System::GetInstance().CpuCore(current_thread->GetProcessorID()).PrepareReschedule();
  592. return RESULT_SUCCESS;
  593. }
  594. /// Signal process wide key
  595. static ResultCode SignalProcessWideKey(VAddr condition_variable_addr, s32 target) {
  596. LOG_TRACE(Kernel_SVC, "called, condition_variable_addr=0x{:X}, target=0x{:08X}",
  597. condition_variable_addr, target);
  598. const auto RetrieveWaitingThreads = [](std::size_t core_index,
  599. std::vector<SharedPtr<Thread>>& waiting_threads,
  600. VAddr condvar_addr) {
  601. const auto& scheduler = Core::System::GetInstance().Scheduler(core_index);
  602. const auto& thread_list = scheduler->GetThreadList();
  603. for (const auto& thread : thread_list) {
  604. if (thread->GetCondVarWaitAddress() == condvar_addr)
  605. waiting_threads.push_back(thread);
  606. }
  607. };
  608. // Retrieve a list of all threads that are waiting for this condition variable.
  609. std::vector<SharedPtr<Thread>> waiting_threads;
  610. RetrieveWaitingThreads(0, waiting_threads, condition_variable_addr);
  611. RetrieveWaitingThreads(1, waiting_threads, condition_variable_addr);
  612. RetrieveWaitingThreads(2, waiting_threads, condition_variable_addr);
  613. RetrieveWaitingThreads(3, waiting_threads, condition_variable_addr);
  614. // Sort them by priority, such that the highest priority ones come first.
  615. std::sort(waiting_threads.begin(), waiting_threads.end(),
  616. [](const SharedPtr<Thread>& lhs, const SharedPtr<Thread>& rhs) {
  617. return lhs->GetPriority() < rhs->GetPriority();
  618. });
  619. // Only process up to 'target' threads, unless 'target' is -1, in which case process
  620. // them all.
  621. std::size_t last = waiting_threads.size();
  622. if (target != -1)
  623. last = target;
  624. // If there are no threads waiting on this condition variable, just exit
  625. if (last > waiting_threads.size())
  626. return RESULT_SUCCESS;
  627. for (std::size_t index = 0; index < last; ++index) {
  628. auto& thread = waiting_threads[index];
  629. ASSERT(thread->GetCondVarWaitAddress() == condition_variable_addr);
  630. std::size_t current_core = Core::System::GetInstance().CurrentCoreIndex();
  631. auto& monitor = Core::System::GetInstance().Monitor();
  632. // Atomically read the value of the mutex.
  633. u32 mutex_val = 0;
  634. do {
  635. monitor.SetExclusive(current_core, thread->GetMutexWaitAddress());
  636. // If the mutex is not yet acquired, acquire it.
  637. mutex_val = Memory::Read32(thread->GetMutexWaitAddress());
  638. if (mutex_val != 0) {
  639. monitor.ClearExclusive();
  640. break;
  641. }
  642. } while (!monitor.ExclusiveWrite32(current_core, thread->GetMutexWaitAddress(),
  643. thread->GetWaitHandle()));
  644. if (mutex_val == 0) {
  645. // We were able to acquire the mutex, resume this thread.
  646. ASSERT(thread->GetStatus() == ThreadStatus::WaitMutex);
  647. thread->ResumeFromWait();
  648. auto* const lock_owner = thread->GetLockOwner();
  649. if (lock_owner != nullptr) {
  650. lock_owner->RemoveMutexWaiter(thread);
  651. }
  652. thread->SetLockOwner(nullptr);
  653. thread->SetMutexWaitAddress(0);
  654. thread->SetCondVarWaitAddress(0);
  655. thread->SetWaitHandle(0);
  656. } else {
  657. // Atomically signal that the mutex now has a waiting thread.
  658. do {
  659. monitor.SetExclusive(current_core, thread->GetMutexWaitAddress());
  660. // Ensure that the mutex value is still what we expect.
  661. u32 value = Memory::Read32(thread->GetMutexWaitAddress());
  662. // TODO(Subv): When this happens, the kernel just clears the exclusive state and
  663. // retries the initial read for this thread.
  664. ASSERT_MSG(mutex_val == value, "Unhandled synchronization primitive case");
  665. } while (!monitor.ExclusiveWrite32(current_core, thread->GetMutexWaitAddress(),
  666. mutex_val | Mutex::MutexHasWaitersFlag));
  667. // The mutex is already owned by some other thread, make this thread wait on it.
  668. auto& kernel = Core::System::GetInstance().Kernel();
  669. Handle owner_handle = static_cast<Handle>(mutex_val & Mutex::MutexOwnerMask);
  670. auto owner = kernel.HandleTable().Get<Thread>(owner_handle);
  671. ASSERT(owner);
  672. ASSERT(thread->GetStatus() == ThreadStatus::WaitMutex);
  673. thread->InvalidateWakeupCallback();
  674. owner->AddMutexWaiter(thread);
  675. Core::System::GetInstance().CpuCore(thread->GetProcessorID()).PrepareReschedule();
  676. }
  677. }
  678. return RESULT_SUCCESS;
  679. }
  680. // Wait for an address (via Address Arbiter)
  681. static ResultCode WaitForAddress(VAddr address, u32 type, s32 value, s64 timeout) {
  682. LOG_WARNING(Kernel_SVC, "called, address=0x{:X}, type=0x{:X}, value=0x{:X}, timeout={}",
  683. address, type, value, timeout);
  684. // If the passed address is a kernel virtual address, return invalid memory state.
  685. if (Memory::IsKernelVirtualAddress(address)) {
  686. return ERR_INVALID_ADDRESS_STATE;
  687. }
  688. // If the address is not properly aligned to 4 bytes, return invalid address.
  689. if (address % sizeof(u32) != 0) {
  690. return ERR_INVALID_ADDRESS;
  691. }
  692. switch (static_cast<AddressArbiter::ArbitrationType>(type)) {
  693. case AddressArbiter::ArbitrationType::WaitIfLessThan:
  694. return AddressArbiter::WaitForAddressIfLessThan(address, value, timeout, false);
  695. case AddressArbiter::ArbitrationType::DecrementAndWaitIfLessThan:
  696. return AddressArbiter::WaitForAddressIfLessThan(address, value, timeout, true);
  697. case AddressArbiter::ArbitrationType::WaitIfEqual:
  698. return AddressArbiter::WaitForAddressIfEqual(address, value, timeout);
  699. default:
  700. return ERR_INVALID_ENUM_VALUE;
  701. }
  702. }
  703. // Signals to an address (via Address Arbiter)
  704. static ResultCode SignalToAddress(VAddr address, u32 type, s32 value, s32 num_to_wake) {
  705. LOG_WARNING(Kernel_SVC, "called, address=0x{:X}, type=0x{:X}, value=0x{:X}, num_to_wake=0x{:X}",
  706. address, type, value, num_to_wake);
  707. // If the passed address is a kernel virtual address, return invalid memory state.
  708. if (Memory::IsKernelVirtualAddress(address)) {
  709. return ERR_INVALID_ADDRESS_STATE;
  710. }
  711. // If the address is not properly aligned to 4 bytes, return invalid address.
  712. if (address % sizeof(u32) != 0) {
  713. return ERR_INVALID_ADDRESS;
  714. }
  715. switch (static_cast<AddressArbiter::SignalType>(type)) {
  716. case AddressArbiter::SignalType::Signal:
  717. return AddressArbiter::SignalToAddress(address, num_to_wake);
  718. case AddressArbiter::SignalType::IncrementAndSignalIfEqual:
  719. return AddressArbiter::IncrementAndSignalToAddressIfEqual(address, value, num_to_wake);
  720. case AddressArbiter::SignalType::ModifyByWaitingCountAndSignalIfEqual:
  721. return AddressArbiter::ModifyByWaitingCountAndSignalToAddressIfEqual(address, value,
  722. num_to_wake);
  723. default:
  724. return ERR_INVALID_ENUM_VALUE;
  725. }
  726. }
  727. /// This returns the total CPU ticks elapsed since the CPU was powered-on
  728. static u64 GetSystemTick() {
  729. const u64 result{CoreTiming::GetTicks()};
  730. // Advance time to defeat dumb games that busy-wait for the frame to end.
  731. CoreTiming::AddTicks(400);
  732. return result;
  733. }
  734. /// Close a handle
  735. static ResultCode CloseHandle(Handle handle) {
  736. LOG_TRACE(Kernel_SVC, "Closing handle 0x{:08X}", handle);
  737. auto& kernel = Core::System::GetInstance().Kernel();
  738. return kernel.HandleTable().Close(handle);
  739. }
  740. /// Reset an event
  741. static ResultCode ResetSignal(Handle handle) {
  742. LOG_WARNING(Kernel_SVC, "(STUBBED) called handle 0x{:08X}", handle);
  743. auto& kernel = Core::System::GetInstance().Kernel();
  744. auto event = kernel.HandleTable().Get<Event>(handle);
  745. ASSERT(event != nullptr);
  746. event->Clear();
  747. return RESULT_SUCCESS;
  748. }
  749. /// Creates a TransferMemory object
  750. static ResultCode CreateTransferMemory(Handle* handle, VAddr addr, u64 size, u32 permissions) {
  751. LOG_WARNING(Kernel_SVC, "(STUBBED) called addr=0x{:X}, size=0x{:X}, perms=0x{:08X}", addr, size,
  752. permissions);
  753. *handle = 0;
  754. return RESULT_SUCCESS;
  755. }
  756. static ResultCode GetThreadCoreMask(Handle thread_handle, u32* core, u64* mask) {
  757. LOG_TRACE(Kernel_SVC, "called, handle=0x{:08X}", thread_handle);
  758. auto& kernel = Core::System::GetInstance().Kernel();
  759. const SharedPtr<Thread> thread = kernel.HandleTable().Get<Thread>(thread_handle);
  760. if (!thread) {
  761. return ERR_INVALID_HANDLE;
  762. }
  763. *core = thread->GetIdealCore();
  764. *mask = thread->GetAffinityMask();
  765. return RESULT_SUCCESS;
  766. }
  767. static ResultCode SetThreadCoreMask(Handle thread_handle, u32 core, u64 mask) {
  768. LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, mask=0x{:16X}, core=0x{:X}", thread_handle,
  769. mask, core);
  770. auto& kernel = Core::System::GetInstance().Kernel();
  771. const SharedPtr<Thread> thread = kernel.HandleTable().Get<Thread>(thread_handle);
  772. if (!thread) {
  773. return ERR_INVALID_HANDLE;
  774. }
  775. if (core == static_cast<u32>(THREADPROCESSORID_DEFAULT)) {
  776. const u8 default_processor_id = thread->GetOwnerProcess()->GetDefaultProcessorID();
  777. ASSERT(default_processor_id != static_cast<u8>(THREADPROCESSORID_DEFAULT));
  778. // Set the target CPU to the one specified in the process' exheader.
  779. core = default_processor_id;
  780. mask = 1ULL << core;
  781. }
  782. if (mask == 0) {
  783. return ResultCode(ErrorModule::Kernel, ErrCodes::InvalidCombination);
  784. }
  785. /// This value is used to only change the affinity mask without changing the current ideal core.
  786. static constexpr u32 OnlyChangeMask = static_cast<u32>(-3);
  787. if (core == OnlyChangeMask) {
  788. core = thread->GetIdealCore();
  789. } else if (core >= Core::NUM_CPU_CORES && core != static_cast<u32>(-1)) {
  790. return ResultCode(ErrorModule::Kernel, ErrCodes::InvalidProcessorId);
  791. }
  792. // Error out if the input core isn't enabled in the input mask.
  793. if (core < Core::NUM_CPU_CORES && (mask & (1ull << core)) == 0) {
  794. return ResultCode(ErrorModule::Kernel, ErrCodes::InvalidCombination);
  795. }
  796. thread->ChangeCore(core, mask);
  797. return RESULT_SUCCESS;
  798. }
  799. static ResultCode CreateSharedMemory(Handle* handle, u64 size, u32 local_permissions,
  800. u32 remote_permissions) {
  801. LOG_TRACE(Kernel_SVC, "called, size=0x{:X}, localPerms=0x{:08X}, remotePerms=0x{:08X}", size,
  802. local_permissions, remote_permissions);
  803. // Size must be a multiple of 4KB and be less than or equal to
  804. // approx. 8 GB (actually (1GB - 512B) * 8)
  805. if (size == 0 || (size & 0xFFFFFFFE00000FFF) != 0) {
  806. return ERR_INVALID_SIZE;
  807. }
  808. const auto local_perms = static_cast<MemoryPermission>(local_permissions);
  809. if (local_perms != MemoryPermission::Read && local_perms != MemoryPermission::ReadWrite) {
  810. return ERR_INVALID_MEMORY_PERMISSIONS;
  811. }
  812. const auto remote_perms = static_cast<MemoryPermission>(remote_permissions);
  813. if (remote_perms != MemoryPermission::Read && remote_perms != MemoryPermission::ReadWrite &&
  814. remote_perms != MemoryPermission::DontCare) {
  815. return ERR_INVALID_MEMORY_PERMISSIONS;
  816. }
  817. auto& kernel = Core::System::GetInstance().Kernel();
  818. auto& handle_table = kernel.HandleTable();
  819. auto shared_mem_handle =
  820. SharedMemory::Create(kernel, handle_table.Get<Process>(KernelHandle::CurrentProcess), size,
  821. local_perms, remote_perms);
  822. CASCADE_RESULT(*handle, handle_table.Create(shared_mem_handle));
  823. return RESULT_SUCCESS;
  824. }
  825. static ResultCode ClearEvent(Handle handle) {
  826. LOG_TRACE(Kernel_SVC, "called, event=0x{:08X}", handle);
  827. auto& kernel = Core::System::GetInstance().Kernel();
  828. SharedPtr<Event> evt = kernel.HandleTable().Get<Event>(handle);
  829. if (evt == nullptr)
  830. return ERR_INVALID_HANDLE;
  831. evt->Clear();
  832. return RESULT_SUCCESS;
  833. }
  834. namespace {
  835. struct FunctionDef {
  836. using Func = void();
  837. u32 id;
  838. Func* func;
  839. const char* name;
  840. };
  841. } // namespace
  842. static const FunctionDef SVC_Table[] = {
  843. {0x00, nullptr, "Unknown"},
  844. {0x01, SvcWrap<SetHeapSize>, "SetHeapSize"},
  845. {0x02, nullptr, "SetMemoryPermission"},
  846. {0x03, SvcWrap<SetMemoryAttribute>, "SetMemoryAttribute"},
  847. {0x04, SvcWrap<MapMemory>, "MapMemory"},
  848. {0x05, SvcWrap<UnmapMemory>, "UnmapMemory"},
  849. {0x06, SvcWrap<QueryMemory>, "QueryMemory"},
  850. {0x07, SvcWrap<ExitProcess>, "ExitProcess"},
  851. {0x08, SvcWrap<CreateThread>, "CreateThread"},
  852. {0x09, SvcWrap<StartThread>, "StartThread"},
  853. {0x0A, SvcWrap<ExitThread>, "ExitThread"},
  854. {0x0B, SvcWrap<SleepThread>, "SleepThread"},
  855. {0x0C, SvcWrap<GetThreadPriority>, "GetThreadPriority"},
  856. {0x0D, SvcWrap<SetThreadPriority>, "SetThreadPriority"},
  857. {0x0E, SvcWrap<GetThreadCoreMask>, "GetThreadCoreMask"},
  858. {0x0F, SvcWrap<SetThreadCoreMask>, "SetThreadCoreMask"},
  859. {0x10, SvcWrap<GetCurrentProcessorNumber>, "GetCurrentProcessorNumber"},
  860. {0x11, nullptr, "SignalEvent"},
  861. {0x12, SvcWrap<ClearEvent>, "ClearEvent"},
  862. {0x13, SvcWrap<MapSharedMemory>, "MapSharedMemory"},
  863. {0x14, SvcWrap<UnmapSharedMemory>, "UnmapSharedMemory"},
  864. {0x15, SvcWrap<CreateTransferMemory>, "CreateTransferMemory"},
  865. {0x16, SvcWrap<CloseHandle>, "CloseHandle"},
  866. {0x17, SvcWrap<ResetSignal>, "ResetSignal"},
  867. {0x18, SvcWrap<WaitSynchronization>, "WaitSynchronization"},
  868. {0x19, SvcWrap<CancelSynchronization>, "CancelSynchronization"},
  869. {0x1A, SvcWrap<ArbitrateLock>, "ArbitrateLock"},
  870. {0x1B, SvcWrap<ArbitrateUnlock>, "ArbitrateUnlock"},
  871. {0x1C, SvcWrap<WaitProcessWideKeyAtomic>, "WaitProcessWideKeyAtomic"},
  872. {0x1D, SvcWrap<SignalProcessWideKey>, "SignalProcessWideKey"},
  873. {0x1E, SvcWrap<GetSystemTick>, "GetSystemTick"},
  874. {0x1F, SvcWrap<ConnectToNamedPort>, "ConnectToNamedPort"},
  875. {0x20, nullptr, "SendSyncRequestLight"},
  876. {0x21, SvcWrap<SendSyncRequest>, "SendSyncRequest"},
  877. {0x22, nullptr, "SendSyncRequestWithUserBuffer"},
  878. {0x23, nullptr, "SendAsyncRequestWithUserBuffer"},
  879. {0x24, SvcWrap<GetProcessId>, "GetProcessId"},
  880. {0x25, SvcWrap<GetThreadId>, "GetThreadId"},
  881. {0x26, SvcWrap<Break>, "Break"},
  882. {0x27, SvcWrap<OutputDebugString>, "OutputDebugString"},
  883. {0x28, nullptr, "ReturnFromException"},
  884. {0x29, SvcWrap<GetInfo>, "GetInfo"},
  885. {0x2A, nullptr, "FlushEntireDataCache"},
  886. {0x2B, nullptr, "FlushDataCache"},
  887. {0x2C, nullptr, "MapPhysicalMemory"},
  888. {0x2D, nullptr, "UnmapPhysicalMemory"},
  889. {0x2E, nullptr, "GetFutureThreadInfo"},
  890. {0x2F, nullptr, "GetLastThreadInfo"},
  891. {0x30, nullptr, "GetResourceLimitLimitValue"},
  892. {0x31, nullptr, "GetResourceLimitCurrentValue"},
  893. {0x32, SvcWrap<SetThreadActivity>, "SetThreadActivity"},
  894. {0x33, SvcWrap<GetThreadContext>, "GetThreadContext"},
  895. {0x34, SvcWrap<WaitForAddress>, "WaitForAddress"},
  896. {0x35, SvcWrap<SignalToAddress>, "SignalToAddress"},
  897. {0x36, nullptr, "Unknown"},
  898. {0x37, nullptr, "Unknown"},
  899. {0x38, nullptr, "Unknown"},
  900. {0x39, nullptr, "Unknown"},
  901. {0x3A, nullptr, "Unknown"},
  902. {0x3B, nullptr, "Unknown"},
  903. {0x3C, nullptr, "DumpInfo"},
  904. {0x3D, nullptr, "DumpInfoNew"},
  905. {0x3E, nullptr, "Unknown"},
  906. {0x3F, nullptr, "Unknown"},
  907. {0x40, nullptr, "CreateSession"},
  908. {0x41, nullptr, "AcceptSession"},
  909. {0x42, nullptr, "ReplyAndReceiveLight"},
  910. {0x43, nullptr, "ReplyAndReceive"},
  911. {0x44, nullptr, "ReplyAndReceiveWithUserBuffer"},
  912. {0x45, nullptr, "CreateEvent"},
  913. {0x46, nullptr, "Unknown"},
  914. {0x47, nullptr, "Unknown"},
  915. {0x48, nullptr, "MapPhysicalMemoryUnsafe"},
  916. {0x49, nullptr, "UnmapPhysicalMemoryUnsafe"},
  917. {0x4A, nullptr, "SetUnsafeLimit"},
  918. {0x4B, nullptr, "CreateCodeMemory"},
  919. {0x4C, nullptr, "ControlCodeMemory"},
  920. {0x4D, nullptr, "SleepSystem"},
  921. {0x4E, nullptr, "ReadWriteRegister"},
  922. {0x4F, nullptr, "SetProcessActivity"},
  923. {0x50, SvcWrap<CreateSharedMemory>, "CreateSharedMemory"},
  924. {0x51, nullptr, "MapTransferMemory"},
  925. {0x52, nullptr, "UnmapTransferMemory"},
  926. {0x53, nullptr, "CreateInterruptEvent"},
  927. {0x54, nullptr, "QueryPhysicalAddress"},
  928. {0x55, nullptr, "QueryIoMapping"},
  929. {0x56, nullptr, "CreateDeviceAddressSpace"},
  930. {0x57, nullptr, "AttachDeviceAddressSpace"},
  931. {0x58, nullptr, "DetachDeviceAddressSpace"},
  932. {0x59, nullptr, "MapDeviceAddressSpaceByForce"},
  933. {0x5A, nullptr, "MapDeviceAddressSpaceAligned"},
  934. {0x5B, nullptr, "MapDeviceAddressSpace"},
  935. {0x5C, nullptr, "UnmapDeviceAddressSpace"},
  936. {0x5D, nullptr, "InvalidateProcessDataCache"},
  937. {0x5E, nullptr, "StoreProcessDataCache"},
  938. {0x5F, nullptr, "FlushProcessDataCache"},
  939. {0x60, nullptr, "DebugActiveProcess"},
  940. {0x61, nullptr, "BreakDebugProcess"},
  941. {0x62, nullptr, "TerminateDebugProcess"},
  942. {0x63, nullptr, "GetDebugEvent"},
  943. {0x64, nullptr, "ContinueDebugEvent"},
  944. {0x65, nullptr, "GetProcessList"},
  945. {0x66, nullptr, "GetThreadList"},
  946. {0x67, nullptr, "GetDebugThreadContext"},
  947. {0x68, nullptr, "SetDebugThreadContext"},
  948. {0x69, nullptr, "QueryDebugProcessMemory"},
  949. {0x6A, nullptr, "ReadDebugProcessMemory"},
  950. {0x6B, nullptr, "WriteDebugProcessMemory"},
  951. {0x6C, nullptr, "SetHardwareBreakPoint"},
  952. {0x6D, nullptr, "GetDebugThreadParam"},
  953. {0x6E, nullptr, "Unknown"},
  954. {0x6F, nullptr, "GetSystemInfo"},
  955. {0x70, nullptr, "CreatePort"},
  956. {0x71, nullptr, "ManageNamedPort"},
  957. {0x72, nullptr, "ConnectToPort"},
  958. {0x73, nullptr, "SetProcessMemoryPermission"},
  959. {0x74, nullptr, "MapProcessMemory"},
  960. {0x75, nullptr, "UnmapProcessMemory"},
  961. {0x76, nullptr, "QueryProcessMemory"},
  962. {0x77, nullptr, "MapProcessCodeMemory"},
  963. {0x78, nullptr, "UnmapProcessCodeMemory"},
  964. {0x79, nullptr, "CreateProcess"},
  965. {0x7A, nullptr, "StartProcess"},
  966. {0x7B, nullptr, "TerminateProcess"},
  967. {0x7C, nullptr, "GetProcessInfo"},
  968. {0x7D, nullptr, "CreateResourceLimit"},
  969. {0x7E, nullptr, "SetResourceLimitLimitValue"},
  970. {0x7F, nullptr, "CallSecureMonitor"},
  971. };
  972. static const FunctionDef* GetSVCInfo(u32 func_num) {
  973. if (func_num >= std::size(SVC_Table)) {
  974. LOG_ERROR(Kernel_SVC, "Unknown svc=0x{:02X}", func_num);
  975. return nullptr;
  976. }
  977. return &SVC_Table[func_num];
  978. }
  979. MICROPROFILE_DEFINE(Kernel_SVC, "Kernel", "SVC", MP_RGB(70, 200, 70));
  980. void CallSVC(u32 immediate) {
  981. MICROPROFILE_SCOPE(Kernel_SVC);
  982. // Lock the global kernel mutex when we enter the kernel HLE.
  983. std::lock_guard<std::recursive_mutex> lock(HLE::g_hle_lock);
  984. const FunctionDef* info = GetSVCInfo(immediate);
  985. if (info) {
  986. if (info->func) {
  987. info->func();
  988. } else {
  989. LOG_CRITICAL(Kernel_SVC, "Unimplemented SVC function {}(..)", info->name);
  990. }
  991. } else {
  992. LOG_CRITICAL(Kernel_SVC, "Unknown SVC function 0x{:X}", immediate);
  993. }
  994. }
  995. } // namespace Kernel