svc.cpp 34 KB

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