svc.cpp 36 KB

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