svc.cpp 30 KB

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