svc.cpp 33 KB

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