svc.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. // Copyright 2018 Yuzu Emulator Team
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include "common/logging/log.h"
  5. #include "common/microprofile.h"
  6. #include "common/string_util.h"
  7. #include "core/core_timing.h"
  8. #include "core/hle/kernel/client_port.h"
  9. #include "core/hle/kernel/client_session.h"
  10. #include "core/hle/kernel/condition_variable.h"
  11. #include "core/hle/kernel/handle_table.h"
  12. #include "core/hle/kernel/mutex.h"
  13. #include "core/hle/kernel/object_address_table.h"
  14. #include "core/hle/kernel/process.h"
  15. #include "core/hle/kernel/resource_limit.h"
  16. #include "core/hle/kernel/svc.h"
  17. #include "core/hle/kernel/svc_wrap.h"
  18. #include "core/hle/kernel/sync_object.h"
  19. #include "core/hle/kernel/thread.h"
  20. #include "core/hle/lock.h"
  21. #include "core/hle/result.h"
  22. #include "core/hle/service/service.h"
  23. namespace Kernel {
  24. /// Set the process heap to a given Size. It can both extend and shrink the heap.
  25. static ResultCode SetHeapSize(VAddr* heap_addr, u64 heap_size) {
  26. LOG_TRACE(Kernel_SVC, "called, heap_size=0x%llx", heap_size);
  27. auto& process = *g_current_process;
  28. CASCADE_RESULT(*heap_addr,
  29. process.HeapAllocate(Memory::HEAP_VADDR, heap_size, VMAPermission::ReadWrite));
  30. return RESULT_SUCCESS;
  31. }
  32. static ResultCode SetMemoryAttribute(VAddr addr, u64 size, u32 state0, u32 state1) {
  33. LOG_WARNING(Kernel_SVC, "(STUBBED) called, addr=0x%llx", addr);
  34. return RESULT_SUCCESS;
  35. }
  36. /// Maps a memory range into a different range.
  37. static ResultCode MapMemory(VAddr dst_addr, VAddr src_addr, u64 size) {
  38. LOG_TRACE(Kernel_SVC, "called, dst_addr=0x%llx, src_addr=0x%llx, size=0x%llx", dst_addr,
  39. src_addr, size);
  40. return g_current_process->MirrorMemory(dst_addr, src_addr, size);
  41. }
  42. /// Unmaps a region that was previously mapped with svcMapMemory
  43. static ResultCode UnmapMemory(VAddr dst_addr, VAddr src_addr, u64 size) {
  44. LOG_TRACE(Kernel_SVC, "called, dst_addr=0x%llx, src_addr=0x%llx, size=0x%llx", dst_addr,
  45. src_addr, size);
  46. return g_current_process->UnmapMemory(dst_addr, src_addr, size);
  47. }
  48. /// Connect to an OS service given the port name, returns the handle to the port to out
  49. static ResultCode ConnectToPort(Handle* out_handle, VAddr port_name_address) {
  50. if (!Memory::IsValidVirtualAddress(port_name_address))
  51. return ERR_NOT_FOUND;
  52. static constexpr std::size_t PortNameMaxLength = 11;
  53. // Read 1 char beyond the max allowed port name to detect names that are too long.
  54. std::string port_name = Memory::ReadCString(port_name_address, PortNameMaxLength + 1);
  55. if (port_name.size() > PortNameMaxLength)
  56. return ERR_PORT_NAME_TOO_LONG;
  57. LOG_TRACE(Kernel_SVC, "called port_name=%s", port_name.c_str());
  58. auto it = Service::g_kernel_named_ports.find(port_name);
  59. if (it == Service::g_kernel_named_ports.end()) {
  60. LOG_WARNING(Kernel_SVC, "tried to connect to unknown port: %s", port_name.c_str());
  61. return ERR_NOT_FOUND;
  62. }
  63. auto client_port = it->second;
  64. SharedPtr<ClientSession> client_session;
  65. CASCADE_RESULT(client_session, client_port->Connect());
  66. // Return the client session
  67. CASCADE_RESULT(*out_handle, g_handle_table.Create(client_session));
  68. return RESULT_SUCCESS;
  69. }
  70. /// Makes a blocking IPC call to an OS service.
  71. static ResultCode SendSyncRequest(Handle handle) {
  72. SharedPtr<SyncObject> session = g_handle_table.Get<SyncObject>(handle);
  73. if (!session) {
  74. LOG_ERROR(Kernel_SVC, "called with invalid handle=0x%08X", handle);
  75. return ERR_INVALID_HANDLE;
  76. }
  77. LOG_TRACE(Kernel_SVC, "called handle=0x%08X(%s)", handle, session->GetName().c_str());
  78. Core::System::GetInstance().PrepareReschedule();
  79. // TODO(Subv): svcSendSyncRequest should put the caller thread to sleep while the server
  80. // responds and cause a reschedule.
  81. return session->SendSyncRequest(GetCurrentThread());
  82. }
  83. /// Get the ID for the specified thread.
  84. static ResultCode GetThreadId(u32* thread_id, Handle thread_handle) {
  85. LOG_TRACE(Kernel_SVC, "called thread=0x%08X", thread_handle);
  86. const SharedPtr<Thread> thread = g_handle_table.Get<Thread>(thread_handle);
  87. if (!thread) {
  88. return ERR_INVALID_HANDLE;
  89. }
  90. *thread_id = thread->GetThreadId();
  91. return RESULT_SUCCESS;
  92. }
  93. /// Get the ID of the specified process
  94. static ResultCode GetProcessId(u32* process_id, Handle process_handle) {
  95. LOG_TRACE(Kernel_SVC, "called process=0x%08X", process_handle);
  96. const SharedPtr<Process> process = g_handle_table.Get<Process>(process_handle);
  97. if (!process) {
  98. return ERR_INVALID_HANDLE;
  99. }
  100. *process_id = process->process_id;
  101. return RESULT_SUCCESS;
  102. }
  103. /// Default thread wakeup callback for WaitSynchronization
  104. static bool DefaultThreadWakeupCallback(ThreadWakeupReason reason, SharedPtr<Thread> thread,
  105. SharedPtr<WaitObject> object, size_t index) {
  106. ASSERT(thread->status == THREADSTATUS_WAIT_SYNCH_ANY);
  107. if (reason == ThreadWakeupReason::Timeout) {
  108. thread->SetWaitSynchronizationResult(RESULT_TIMEOUT);
  109. return true;
  110. }
  111. ASSERT(reason == ThreadWakeupReason::Signal);
  112. thread->SetWaitSynchronizationResult(RESULT_SUCCESS);
  113. thread->SetWaitSynchronizationOutput(static_cast<u32>(index));
  114. return true;
  115. };
  116. /// Wait for a kernel object to synchronize, timeout after the specified nanoseconds
  117. static ResultCode WaitSynchronization1(
  118. SharedPtr<WaitObject> object, Thread* thread, s64 nano_seconds = -1,
  119. std::function<Thread::WakeupCallback> wakeup_callback = DefaultThreadWakeupCallback) {
  120. if (!object) {
  121. return ERR_INVALID_HANDLE;
  122. }
  123. if (object->ShouldWait(thread)) {
  124. if (nano_seconds == 0) {
  125. return RESULT_TIMEOUT;
  126. }
  127. thread->wait_objects = {object};
  128. object->AddWaitingThread(thread);
  129. thread->status = THREADSTATUS_WAIT_SYNCH_ANY;
  130. // Create an event to wake the thread up after the specified nanosecond delay has passed
  131. thread->WakeAfterDelay(nano_seconds);
  132. thread->wakeup_callback = wakeup_callback;
  133. Core::System::GetInstance().PrepareReschedule();
  134. } else {
  135. object->Acquire(thread);
  136. }
  137. return RESULT_SUCCESS;
  138. }
  139. /// Wait for the given handles to synchronize, timeout after the specified nanoseconds
  140. static ResultCode WaitSynchronization(Handle* index, VAddr handles_address, u64 handle_count,
  141. s64 nano_seconds) {
  142. LOG_TRACE(Kernel_SVC, "called handles_address=0x%llx, handle_count=%d, nano_seconds=%d",
  143. handles_address, handle_count, nano_seconds);
  144. if (!Memory::IsValidVirtualAddress(handles_address))
  145. return ERR_INVALID_POINTER;
  146. static constexpr u64 MaxHandles = 0x40;
  147. if (handle_count > MaxHandles)
  148. return ResultCode(ErrorModule::Kernel, ErrCodes::TooLarge);
  149. auto thread = GetCurrentThread();
  150. using ObjectPtr = SharedPtr<WaitObject>;
  151. std::vector<ObjectPtr> objects(handle_count);
  152. for (int i = 0; i < handle_count; ++i) {
  153. Handle handle = Memory::Read32(handles_address + i * sizeof(Handle));
  154. auto object = g_handle_table.Get<WaitObject>(handle);
  155. if (object == nullptr)
  156. return ERR_INVALID_HANDLE;
  157. objects[i] = object;
  158. }
  159. // Find the first object that is acquirable in the provided list of objects
  160. auto itr = std::find_if(objects.begin(), objects.end(), [thread](const ObjectPtr& object) {
  161. return !object->ShouldWait(thread);
  162. });
  163. if (itr != objects.end()) {
  164. // We found a ready object, acquire it and set the result value
  165. WaitObject* object = itr->get();
  166. object->Acquire(thread);
  167. *index = static_cast<s32>(std::distance(objects.begin(), itr));
  168. return RESULT_SUCCESS;
  169. }
  170. // No objects were ready to be acquired, prepare to suspend the thread.
  171. // If a timeout value of 0 was provided, just return the Timeout error code instead of
  172. // suspending the thread.
  173. if (nano_seconds == 0)
  174. return RESULT_TIMEOUT;
  175. for (auto& object : objects)
  176. object->AddWaitingThread(thread);
  177. thread->wait_objects = std::move(objects);
  178. thread->status = THREADSTATUS_WAIT_SYNCH_ANY;
  179. // Create an event to wake the thread up after the specified nanosecond delay has passed
  180. thread->WakeAfterDelay(nano_seconds);
  181. thread->wakeup_callback = DefaultThreadWakeupCallback;
  182. Core::System::GetInstance().PrepareReschedule();
  183. return RESULT_TIMEOUT;
  184. }
  185. /// Resumes a thread waiting on WaitSynchronization
  186. static ResultCode CancelSynchronization(Handle thread_handle) {
  187. LOG_TRACE(Kernel_SVC, "called thread=0x%08X", thread_handle);
  188. const SharedPtr<Thread> thread = g_handle_table.Get<Thread>(thread_handle);
  189. if (!thread) {
  190. return ERR_INVALID_HANDLE;
  191. }
  192. ASSERT(thread->status == THREADSTATUS_WAIT_SYNCH_ANY);
  193. thread->SetWaitSynchronizationResult(
  194. ResultCode(ErrorModule::Kernel, ErrCodes::SynchronizationCanceled));
  195. thread->ResumeFromWait();
  196. return RESULT_SUCCESS;
  197. }
  198. /// Attempts to locks a mutex, creating it if it does not already exist
  199. static ResultCode LockMutex(Handle holding_thread_handle, VAddr mutex_addr,
  200. Handle requesting_thread_handle) {
  201. LOG_TRACE(Kernel_SVC,
  202. "called holding_thread_handle=0x%08X, mutex_addr=0x%llx, "
  203. "requesting_current_thread_handle=0x%08X",
  204. holding_thread_handle, mutex_addr, requesting_thread_handle);
  205. SharedPtr<Thread> holding_thread = g_handle_table.Get<Thread>(holding_thread_handle);
  206. SharedPtr<Thread> requesting_thread = g_handle_table.Get<Thread>(requesting_thread_handle);
  207. ASSERT(requesting_thread);
  208. SharedPtr<Mutex> mutex = g_object_address_table.Get<Mutex>(mutex_addr);
  209. if (!mutex) {
  210. // Create a new mutex for the specified address if one does not already exist
  211. mutex = Mutex::Create(holding_thread, mutex_addr);
  212. mutex->name = Common::StringFromFormat("mutex-%llx", mutex_addr);
  213. }
  214. ASSERT(holding_thread == mutex->GetHoldingThread());
  215. return WaitSynchronization1(mutex, requesting_thread.get());
  216. }
  217. /// Unlock a mutex
  218. static ResultCode UnlockMutex(VAddr mutex_addr) {
  219. LOG_TRACE(Kernel_SVC, "called mutex_addr=0x%llx", mutex_addr);
  220. SharedPtr<Mutex> mutex = g_object_address_table.Get<Mutex>(mutex_addr);
  221. ASSERT(mutex);
  222. return mutex->Release(GetCurrentThread());
  223. }
  224. /// Break program execution
  225. static void Break(u64 unk_0, u64 unk_1, u64 unk_2) {
  226. LOG_CRITICAL(Debug_Emulated, "Emulated program broke execution!");
  227. ASSERT(false);
  228. }
  229. /// Used to output a message on a debug hardware unit - does nothing on a retail unit
  230. static void OutputDebugString(VAddr address, s32 len) {
  231. std::vector<char> string(len);
  232. Memory::ReadBlock(address, string.data(), len);
  233. LOG_DEBUG(Debug_Emulated, "%.*s", len, string.data());
  234. }
  235. /// Gets system/memory information for the current process
  236. static ResultCode GetInfo(u64* result, u64 info_id, u64 handle, u64 info_sub_id) {
  237. LOG_TRACE(Kernel_SVC, "called info_id=0x%X, info_sub_id=0x%X, handle=0x%08X", info_id,
  238. info_sub_id, handle);
  239. ASSERT(handle == 0 || handle == CurrentProcess);
  240. auto& vm_manager = g_current_process->vm_manager;
  241. switch (static_cast<GetInfoType>(info_id)) {
  242. case GetInfoType::AllowedCpuIdBitmask:
  243. *result = g_current_process->allowed_processor_mask;
  244. break;
  245. case GetInfoType::TotalMemoryUsage:
  246. *result = vm_manager.GetTotalMemoryUsage();
  247. break;
  248. case GetInfoType::TotalHeapUsage:
  249. *result = vm_manager.GetTotalHeapUsage();
  250. break;
  251. case GetInfoType::RandomEntropy:
  252. *result = 0;
  253. break;
  254. case GetInfoType::AddressSpaceBaseAddr:
  255. *result = vm_manager.GetAddressSpaceBaseAddr();
  256. break;
  257. case GetInfoType::AddressSpaceSize:
  258. *result = vm_manager.GetAddressSpaceSize();
  259. break;
  260. case GetInfoType::NewMapRegionBaseAddr:
  261. *result = vm_manager.GetNewMapRegionBaseAddr();
  262. break;
  263. case GetInfoType::NewMapRegionSize:
  264. *result = vm_manager.GetNewMapRegionSize();
  265. break;
  266. default:
  267. UNIMPLEMENTED();
  268. }
  269. return RESULT_SUCCESS;
  270. }
  271. /// Gets the priority for the specified thread
  272. static ResultCode GetThreadPriority(u32* priority, Handle handle) {
  273. const SharedPtr<Thread> thread = g_handle_table.Get<Thread>(handle);
  274. if (!thread)
  275. return ERR_INVALID_HANDLE;
  276. *priority = thread->GetPriority();
  277. return RESULT_SUCCESS;
  278. }
  279. /// Sets the priority for the specified thread
  280. static ResultCode SetThreadPriority(Handle handle, u32 priority) {
  281. if (priority > THREADPRIO_LOWEST) {
  282. return ERR_OUT_OF_RANGE;
  283. }
  284. SharedPtr<Thread> thread = g_handle_table.Get<Thread>(handle);
  285. if (!thread)
  286. return ERR_INVALID_HANDLE;
  287. // Note: The kernel uses the current process's resource limit instead of
  288. // the one from the thread owner's resource limit.
  289. SharedPtr<ResourceLimit>& resource_limit = g_current_process->resource_limit;
  290. if (resource_limit->GetMaxResourceValue(ResourceTypes::PRIORITY) > priority) {
  291. return ERR_NOT_AUTHORIZED;
  292. }
  293. thread->SetPriority(priority);
  294. thread->UpdatePriority();
  295. // Update the mutexes that this thread is waiting for
  296. for (auto& mutex : thread->pending_mutexes)
  297. mutex->UpdatePriority();
  298. Core::System::GetInstance().PrepareReschedule();
  299. return RESULT_SUCCESS;
  300. }
  301. /// Get which CPU core is executing the current thread
  302. static u32 GetCurrentProcessorNumber() {
  303. LOG_WARNING(Kernel_SVC, "(STUBBED) called, defaulting to processor 0");
  304. return 0;
  305. }
  306. /// Query process memory
  307. static ResultCode QueryProcessMemory(MemoryInfo* memory_info, PageInfo* /*page_info*/,
  308. Handle process_handle, u64 addr) {
  309. SharedPtr<Process> process = g_handle_table.Get<Process>(process_handle);
  310. if (!process) {
  311. return ERR_INVALID_HANDLE;
  312. }
  313. auto vma = process->vm_manager.FindVMA(addr);
  314. memory_info->attributes = 0;
  315. if (vma == g_current_process->vm_manager.vma_map.end()) {
  316. memory_info->base_address = 0;
  317. memory_info->permission = static_cast<u32>(VMAPermission::None);
  318. memory_info->size = 0;
  319. memory_info->type = static_cast<u32>(MemoryState::Free);
  320. } else {
  321. memory_info->base_address = vma->second.base;
  322. memory_info->permission = static_cast<u32>(vma->second.permissions);
  323. memory_info->size = vma->second.size;
  324. memory_info->type = static_cast<u32>(vma->second.meminfo_state);
  325. }
  326. LOG_TRACE(Kernel_SVC, "called process=0x%08X addr=%llx", process_handle, addr);
  327. return RESULT_SUCCESS;
  328. }
  329. /// Query memory
  330. static ResultCode QueryMemory(MemoryInfo* memory_info, PageInfo* page_info, VAddr addr) {
  331. LOG_TRACE(Kernel_SVC, "called, addr=%llx", addr);
  332. return QueryProcessMemory(memory_info, page_info, CurrentProcess, addr);
  333. }
  334. /// Exits the current process
  335. static void ExitProcess() {
  336. LOG_INFO(Kernel_SVC, "Process %u exiting", g_current_process->process_id);
  337. ASSERT_MSG(g_current_process->status == ProcessStatus::Running, "Process has already exited");
  338. g_current_process->status = ProcessStatus::Exited;
  339. // Stop all the process threads that are currently waiting for objects.
  340. auto& thread_list = GetThreadList();
  341. for (auto& thread : thread_list) {
  342. if (thread->owner_process != g_current_process)
  343. continue;
  344. if (thread == GetCurrentThread())
  345. continue;
  346. // TODO(Subv): When are the other running/ready threads terminated?
  347. ASSERT_MSG(thread->status == THREADSTATUS_WAIT_SYNCH_ANY ||
  348. thread->status == THREADSTATUS_WAIT_SYNCH_ALL,
  349. "Exiting processes with non-waiting threads is currently unimplemented");
  350. thread->Stop();
  351. }
  352. // Kill the current thread
  353. GetCurrentThread()->Stop();
  354. Core::System::GetInstance().PrepareReschedule();
  355. }
  356. /// Creates a new thread
  357. static ResultCode CreateThread(Handle* out_handle, VAddr entry_point, u64 arg, VAddr stack_top,
  358. u32 priority, s32 processor_id) {
  359. std::string name = Common::StringFromFormat("unknown-%llx", entry_point);
  360. if (priority > THREADPRIO_LOWEST) {
  361. return ERR_OUT_OF_RANGE;
  362. }
  363. SharedPtr<ResourceLimit>& resource_limit = g_current_process->resource_limit;
  364. if (resource_limit->GetMaxResourceValue(ResourceTypes::PRIORITY) > priority) {
  365. return ERR_NOT_AUTHORIZED;
  366. }
  367. if (processor_id == THREADPROCESSORID_DEFAULT) {
  368. // Set the target CPU to the one specified in the process' exheader.
  369. processor_id = g_current_process->ideal_processor;
  370. ASSERT(processor_id != THREADPROCESSORID_DEFAULT);
  371. }
  372. switch (processor_id) {
  373. case THREADPROCESSORID_0:
  374. break;
  375. case THREADPROCESSORID_1:
  376. case THREADPROCESSORID_2:
  377. case THREADPROCESSORID_3:
  378. // TODO(bunnei): Implement support for other processor IDs
  379. LOG_ERROR(Kernel_SVC,
  380. "Newly created thread must run in another thread (%u), unimplemented.",
  381. processor_id);
  382. break;
  383. default:
  384. ASSERT_MSG(false, "Unsupported thread processor ID: %d", processor_id);
  385. break;
  386. }
  387. CASCADE_RESULT(SharedPtr<Thread> thread,
  388. Thread::Create(name, entry_point, priority, arg, processor_id, stack_top,
  389. g_current_process));
  390. CASCADE_RESULT(thread->guest_handle, g_handle_table.Create(thread));
  391. *out_handle = thread->guest_handle;
  392. Core::System::GetInstance().PrepareReschedule();
  393. LOG_TRACE(Kernel_SVC,
  394. "called entrypoint=0x%08X (%s), arg=0x%08X, stacktop=0x%08X, "
  395. "threadpriority=0x%08X, processorid=0x%08X : created handle=0x%08X",
  396. entry_point, name.c_str(), arg, stack_top, priority, processor_id, *out_handle);
  397. return RESULT_SUCCESS;
  398. }
  399. /// Starts the thread for the provided handle
  400. static ResultCode StartThread(Handle thread_handle) {
  401. LOG_TRACE(Kernel_SVC, "called thread=0x%08X", thread_handle);
  402. const SharedPtr<Thread> thread = g_handle_table.Get<Thread>(thread_handle);
  403. if (!thread) {
  404. return ERR_INVALID_HANDLE;
  405. }
  406. thread->ResumeFromWait();
  407. return RESULT_SUCCESS;
  408. }
  409. /// Called when a thread exits
  410. static void ExitThread() {
  411. LOG_TRACE(Kernel_SVC, "called, pc=0x%08X", Core::CPU().GetPC());
  412. ExitCurrentThread();
  413. Core::System::GetInstance().PrepareReschedule();
  414. }
  415. /// Sleep the current thread
  416. static void SleepThread(s64 nanoseconds) {
  417. LOG_TRACE(Kernel_SVC, "called nanoseconds=%lld", nanoseconds);
  418. // Don't attempt to yield execution if there are no available threads to run,
  419. // this way we avoid a useless reschedule to the idle thread.
  420. if (nanoseconds == 0 && !HaveReadyThreads())
  421. return;
  422. // Sleep current thread and check for next thread to schedule
  423. WaitCurrentThread_Sleep();
  424. // Create an event to wake the thread up after the specified nanosecond delay has passed
  425. GetCurrentThread()->WakeAfterDelay(nanoseconds);
  426. Core::System::GetInstance().PrepareReschedule();
  427. }
  428. /// Signal process wide key atomic
  429. static ResultCode WaitProcessWideKeyAtomic(VAddr mutex_addr, VAddr condition_variable_addr,
  430. Handle thread_handle, s64 nano_seconds) {
  431. LOG_TRACE(
  432. Kernel_SVC,
  433. "called mutex_addr=%llx, condition_variable_addr=%llx, thread_handle=0x%08X, timeout=%d",
  434. mutex_addr, condition_variable_addr, thread_handle, nano_seconds);
  435. SharedPtr<Thread> thread = g_handle_table.Get<Thread>(thread_handle);
  436. ASSERT(thread);
  437. SharedPtr<Mutex> mutex = g_object_address_table.Get<Mutex>(mutex_addr);
  438. if (!mutex) {
  439. // Create a new mutex for the specified address if one does not already exist
  440. mutex = Mutex::Create(thread, mutex_addr);
  441. mutex->name = Common::StringFromFormat("mutex-%llx", mutex_addr);
  442. }
  443. ASSERT(mutex->GetOwnerHandle() == thread_handle);
  444. SharedPtr<ConditionVariable> condition_variable =
  445. g_object_address_table.Get<ConditionVariable>(condition_variable_addr);
  446. if (!condition_variable) {
  447. // Create a new condition_variable for the specified address if one does not already exist
  448. condition_variable =
  449. ConditionVariable::Create(condition_variable_addr, mutex_addr).Unwrap();
  450. condition_variable->name =
  451. Common::StringFromFormat("condition-variable-%llx", condition_variable_addr);
  452. }
  453. ASSERT(condition_variable->GetAvailableCount() == 0);
  454. ASSERT(condition_variable->mutex_addr == mutex_addr);
  455. auto wakeup_callback = [mutex, nano_seconds](ThreadWakeupReason reason,
  456. SharedPtr<Thread> thread,
  457. SharedPtr<WaitObject> object, size_t index) {
  458. ASSERT(thread->status == THREADSTATUS_WAIT_SYNCH_ANY);
  459. if (reason == ThreadWakeupReason::Timeout) {
  460. thread->SetWaitSynchronizationResult(RESULT_TIMEOUT);
  461. return true;
  462. }
  463. ASSERT(reason == ThreadWakeupReason::Signal);
  464. // Now try to acquire the mutex and don't resume if it's not available.
  465. if (!mutex->ShouldWait(thread.get())) {
  466. mutex->Acquire(thread.get());
  467. thread->SetWaitSynchronizationResult(RESULT_SUCCESS);
  468. return true;
  469. }
  470. if (nano_seconds == 0) {
  471. thread->SetWaitSynchronizationResult(RESULT_TIMEOUT);
  472. return true;
  473. }
  474. thread->wait_objects = {mutex};
  475. mutex->AddWaitingThread(thread);
  476. thread->status = THREADSTATUS_WAIT_SYNCH_ANY;
  477. // Create an event to wake the thread up after the
  478. // specified nanosecond delay has passed
  479. thread->WakeAfterDelay(nano_seconds);
  480. thread->wakeup_callback = DefaultThreadWakeupCallback;
  481. Core::System::GetInstance().PrepareReschedule();
  482. return false;
  483. };
  484. CASCADE_CODE(
  485. WaitSynchronization1(condition_variable, thread.get(), nano_seconds, wakeup_callback));
  486. mutex->Release(thread.get());
  487. return RESULT_SUCCESS;
  488. }
  489. /// Signal process wide key
  490. static ResultCode SignalProcessWideKey(VAddr condition_variable_addr, s32 target) {
  491. LOG_TRACE(Kernel_SVC, "called, condition_variable_addr=0x%llx, target=0x%08x",
  492. condition_variable_addr, target);
  493. // Wakeup all or one thread - Any other value is unimplemented
  494. ASSERT(target == -1 || target == 1);
  495. SharedPtr<ConditionVariable> condition_variable =
  496. g_object_address_table.Get<ConditionVariable>(condition_variable_addr);
  497. if (!condition_variable) {
  498. // Create a new condition_variable for the specified address if one does not already exist
  499. condition_variable = ConditionVariable::Create(condition_variable_addr).Unwrap();
  500. condition_variable->name =
  501. Common::StringFromFormat("condition-variable-%llx", condition_variable_addr);
  502. }
  503. CASCADE_CODE(condition_variable->Release(target));
  504. if (condition_variable->mutex_addr) {
  505. // If a mutex was created for this condition_variable, wait the current thread on it
  506. SharedPtr<Mutex> mutex = g_object_address_table.Get<Mutex>(condition_variable->mutex_addr);
  507. return WaitSynchronization1(mutex, GetCurrentThread());
  508. }
  509. return RESULT_SUCCESS;
  510. }
  511. /// Close a handle
  512. static ResultCode CloseHandle(Handle handle) {
  513. LOG_TRACE(Kernel_SVC, "Closing handle 0x%08X", handle);
  514. return g_handle_table.Close(handle);
  515. }
  516. namespace {
  517. struct FunctionDef {
  518. using Func = void();
  519. u32 id;
  520. Func* func;
  521. const char* name;
  522. };
  523. } // namespace
  524. static const FunctionDef SVC_Table[] = {
  525. {0x00, nullptr, "Unknown"},
  526. {0x01, SvcWrap<SetHeapSize>, "SetHeapSize"},
  527. {0x02, nullptr, "SetMemoryPermission"},
  528. {0x03, nullptr, "SetMemoryAttribute"},
  529. {0x04, SvcWrap<MapMemory>, "MapMemory"},
  530. {0x05, SvcWrap<UnmapMemory>, "UnmapMemory"},
  531. {0x06, SvcWrap<QueryMemory>, "QueryMemory"},
  532. {0x07, SvcWrap<ExitProcess>, "ExitProcess"},
  533. {0x08, SvcWrap<CreateThread>, "CreateThread"},
  534. {0x09, SvcWrap<StartThread>, "StartThread"},
  535. {0x0A, SvcWrap<ExitThread>, "ExitThread"},
  536. {0x0B, SvcWrap<SleepThread>, "SleepThread"},
  537. {0x0C, SvcWrap<GetThreadPriority>, "GetThreadPriority"},
  538. {0x0D, SvcWrap<SetThreadPriority>, "SetThreadPriority"},
  539. {0x0E, nullptr, "GetThreadCoreMask"},
  540. {0x0F, nullptr, "SetThreadCoreMask"},
  541. {0x10, SvcWrap<GetCurrentProcessorNumber>, "GetCurrentProcessorNumber"},
  542. {0x11, nullptr, "SignalEvent"},
  543. {0x12, nullptr, "ClearEvent"},
  544. {0x13, nullptr, "MapSharedMemory"},
  545. {0x14, nullptr, "UnmapSharedMemory"},
  546. {0x15, nullptr, "CreateTransferMemory"},
  547. {0x16, SvcWrap<CloseHandle>, "CloseHandle"},
  548. {0x17, nullptr, "ResetSignal"},
  549. {0x18, SvcWrap<WaitSynchronization>, "WaitSynchronization"},
  550. {0x19, SvcWrap<CancelSynchronization>, "CancelSynchronization"},
  551. {0x1A, SvcWrap<LockMutex>, "LockMutex"},
  552. {0x1B, SvcWrap<UnlockMutex>, "UnlockMutex"},
  553. {0x1C, SvcWrap<WaitProcessWideKeyAtomic>, "WaitProcessWideKeyAtomic"},
  554. {0x1D, SvcWrap<SignalProcessWideKey>, "SignalProcessWideKey"},
  555. {0x1E, nullptr, "GetSystemTick"},
  556. {0x1F, SvcWrap<ConnectToPort>, "ConnectToPort"},
  557. {0x20, nullptr, "SendSyncRequestLight"},
  558. {0x21, SvcWrap<SendSyncRequest>, "SendSyncRequest"},
  559. {0x22, nullptr, "SendSyncRequestWithUserBuffer"},
  560. {0x23, nullptr, "SendAsyncRequestWithUserBuffer"},
  561. {0x24, SvcWrap<GetProcessId>, "GetProcessId"},
  562. {0x25, SvcWrap<GetThreadId>, "GetThreadId"},
  563. {0x26, SvcWrap<Break>, "Break"},
  564. {0x27, SvcWrap<OutputDebugString>, "OutputDebugString"},
  565. {0x28, nullptr, "ReturnFromException"},
  566. {0x29, SvcWrap<GetInfo>, "GetInfo"},
  567. {0x2A, nullptr, "FlushEntireDataCache"},
  568. {0x2B, nullptr, "FlushDataCache"},
  569. {0x2C, nullptr, "MapPhysicalMemory"},
  570. {0x2D, nullptr, "UnmapPhysicalMemory"},
  571. {0x2E, nullptr, "Unknown"},
  572. {0x2F, nullptr, "GetLastThreadInfo"},
  573. {0x30, nullptr, "GetResourceLimitLimitValue"},
  574. {0x31, nullptr, "GetResourceLimitCurrentValue"},
  575. {0x32, nullptr, "SetThreadActivity"},
  576. {0x33, nullptr, "GetThreadContext"},
  577. {0x34, nullptr, "Unknown"},
  578. {0x35, nullptr, "Unknown"},
  579. {0x36, nullptr, "Unknown"},
  580. {0x37, nullptr, "Unknown"},
  581. {0x38, nullptr, "Unknown"},
  582. {0x39, nullptr, "Unknown"},
  583. {0x3A, nullptr, "Unknown"},
  584. {0x3B, nullptr, "Unknown"},
  585. {0x3C, nullptr, "DumpInfo"},
  586. {0x3D, nullptr, "Unknown"},
  587. {0x3E, nullptr, "Unknown"},
  588. {0x3F, nullptr, "Unknown"},
  589. {0x40, nullptr, "CreateSession"},
  590. {0x41, nullptr, "AcceptSession"},
  591. {0x42, nullptr, "ReplyAndReceiveLight"},
  592. {0x43, nullptr, "ReplyAndReceive"},
  593. {0x44, nullptr, "ReplyAndReceiveWithUserBuffer"},
  594. {0x45, nullptr, "CreateEvent"},
  595. {0x46, nullptr, "Unknown"},
  596. {0x47, nullptr, "Unknown"},
  597. {0x48, nullptr, "Unknown"},
  598. {0x49, nullptr, "Unknown"},
  599. {0x4A, nullptr, "Unknown"},
  600. {0x4B, nullptr, "Unknown"},
  601. {0x4C, nullptr, "Unknown"},
  602. {0x4D, nullptr, "SleepSystem"},
  603. {0x4E, nullptr, "ReadWriteRegister"},
  604. {0x4F, nullptr, "SetProcessActivity"},
  605. {0x50, nullptr, "CreateSharedMemory"},
  606. {0x51, nullptr, "MapTransferMemory"},
  607. {0x52, nullptr, "UnmapTransferMemory"},
  608. {0x53, nullptr, "CreateInterruptEvent"},
  609. {0x54, nullptr, "QueryPhysicalAddress"},
  610. {0x55, nullptr, "QueryIoMapping"},
  611. {0x56, nullptr, "CreateDeviceAddressSpace"},
  612. {0x57, nullptr, "AttachDeviceAddressSpace"},
  613. {0x58, nullptr, "DetachDeviceAddressSpace"},
  614. {0x59, nullptr, "MapDeviceAddressSpaceByForce"},
  615. {0x5A, nullptr, "MapDeviceAddressSpaceAligned"},
  616. {0x5B, nullptr, "MapDeviceAddressSpace"},
  617. {0x5C, nullptr, "UnmapDeviceAddressSpace"},
  618. {0x5D, nullptr, "InvalidateProcessDataCache"},
  619. {0x5E, nullptr, "StoreProcessDataCache"},
  620. {0x5F, nullptr, "FlushProcessDataCache"},
  621. {0x60, nullptr, "DebugActiveProcess"},
  622. {0x61, nullptr, "BreakDebugProcess"},
  623. {0x62, nullptr, "TerminateDebugProcess"},
  624. {0x63, nullptr, "GetDebugEvent"},
  625. {0x64, nullptr, "ContinueDebugEvent"},
  626. {0x65, nullptr, "GetProcessList"},
  627. {0x66, nullptr, "GetThreadList"},
  628. {0x67, nullptr, "GetDebugThreadContext"},
  629. {0x68, nullptr, "SetDebugThreadContext"},
  630. {0x69, nullptr, "QueryDebugProcessMemory"},
  631. {0x6A, nullptr, "ReadDebugProcessMemory"},
  632. {0x6B, nullptr, "WriteDebugProcessMemory"},
  633. {0x6C, nullptr, "SetHardwareBreakPoint"},
  634. {0x6D, nullptr, "GetDebugThreadParam"},
  635. {0x6E, nullptr, "Unknown"},
  636. {0x6F, nullptr, "Unknown"},
  637. {0x70, nullptr, "CreatePort"},
  638. {0x71, nullptr, "ManageNamedPort"},
  639. {0x72, nullptr, "ConnectToPort"},
  640. {0x73, nullptr, "SetProcessMemoryPermission"},
  641. {0x74, nullptr, "MapProcessMemory"},
  642. {0x75, nullptr, "UnmapProcessMemory"},
  643. {0x76, nullptr, "QueryProcessMemory"},
  644. {0x77, nullptr, "MapProcessCodeMemory"},
  645. {0x78, nullptr, "UnmapProcessCodeMemory"},
  646. {0x79, nullptr, "CreateProcess"},
  647. {0x7A, nullptr, "StartProcess"},
  648. {0x7B, nullptr, "TerminateProcess"},
  649. {0x7C, nullptr, "GetProcessInfo"},
  650. {0x7D, nullptr, "CreateResourceLimit"},
  651. {0x7E, nullptr, "SetResourceLimitLimitValue"},
  652. {0x7F, nullptr, "CallSecureMonitor"},
  653. };
  654. static const FunctionDef* GetSVCInfo(u32 func_num) {
  655. if (func_num >= ARRAY_SIZE(SVC_Table)) {
  656. LOG_ERROR(Kernel_SVC, "unknown svc=0x%02X", func_num);
  657. return nullptr;
  658. }
  659. return &SVC_Table[func_num];
  660. }
  661. MICROPROFILE_DEFINE(Kernel_SVC, "Kernel", "SVC", MP_RGB(70, 200, 70));
  662. void CallSVC(u32 immediate) {
  663. MICROPROFILE_SCOPE(Kernel_SVC);
  664. // Lock the global kernel mutex when we enter the kernel HLE.
  665. std::lock_guard<std::recursive_mutex> lock(HLE::g_hle_lock);
  666. const FunctionDef* info = GetSVCInfo(immediate);
  667. if (info) {
  668. if (info->func) {
  669. info->func();
  670. } else {
  671. LOG_CRITICAL(Kernel_SVC, "unimplemented SVC function %s(..)", info->name);
  672. }
  673. } else {
  674. LOG_CRITICAL(Kernel_SVC, "unknown SVC function 0x%x", immediate);
  675. }
  676. }
  677. } // namespace Kernel