svc.cpp 35 KB

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