svc.cpp 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456
  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 <mutex>
  8. #include <vector>
  9. #include "common/alignment.h"
  10. #include "common/assert.h"
  11. #include "common/logging/log.h"
  12. #include "common/microprofile.h"
  13. #include "common/string_util.h"
  14. #include "core/arm/exclusive_monitor.h"
  15. #include "core/core.h"
  16. #include "core/core_cpu.h"
  17. #include "core/core_timing.h"
  18. #include "core/hle/kernel/address_arbiter.h"
  19. #include "core/hle/kernel/client_port.h"
  20. #include "core/hle/kernel/client_session.h"
  21. #include "core/hle/kernel/event.h"
  22. #include "core/hle/kernel/handle_table.h"
  23. #include "core/hle/kernel/kernel.h"
  24. #include "core/hle/kernel/mutex.h"
  25. #include "core/hle/kernel/process.h"
  26. #include "core/hle/kernel/resource_limit.h"
  27. #include "core/hle/kernel/scheduler.h"
  28. #include "core/hle/kernel/shared_memory.h"
  29. #include "core/hle/kernel/svc.h"
  30. #include "core/hle/kernel/svc_wrap.h"
  31. #include "core/hle/kernel/thread.h"
  32. #include "core/hle/lock.h"
  33. #include "core/hle/result.h"
  34. #include "core/hle/service/service.h"
  35. #include "core/settings.h"
  36. namespace Kernel {
  37. namespace {
  38. // Checks if address + size is greater than the given address
  39. // This can return false if the size causes an overflow of a 64-bit type
  40. // or if the given size is zero.
  41. constexpr bool IsValidAddressRange(VAddr address, u64 size) {
  42. return address + size > address;
  43. }
  44. // Checks if a given address range lies within a larger address range.
  45. constexpr bool IsInsideAddressRange(VAddr address, u64 size, VAddr address_range_begin,
  46. VAddr address_range_end) {
  47. const VAddr end_address = address + size - 1;
  48. return address_range_begin <= address && end_address <= address_range_end - 1;
  49. }
  50. bool IsInsideAddressSpace(const VMManager& vm, VAddr address, u64 size) {
  51. return IsInsideAddressRange(address, size, vm.GetAddressSpaceBaseAddress(),
  52. vm.GetAddressSpaceEndAddress());
  53. }
  54. bool IsInsideNewMapRegion(const VMManager& vm, VAddr address, u64 size) {
  55. return IsInsideAddressRange(address, size, vm.GetNewMapRegionBaseAddress(),
  56. vm.GetNewMapRegionEndAddress());
  57. }
  58. // Helper function that performs the common sanity checks for svcMapMemory
  59. // and svcUnmapMemory. This is doable, as both functions perform their sanitizing
  60. // in the same order.
  61. ResultCode MapUnmapMemorySanityChecks(const VMManager& vm_manager, VAddr dst_addr, VAddr src_addr,
  62. u64 size) {
  63. if (!Common::Is4KBAligned(dst_addr) || !Common::Is4KBAligned(src_addr)) {
  64. return ERR_INVALID_ADDRESS;
  65. }
  66. if (size == 0 || !Common::Is4KBAligned(size)) {
  67. return ERR_INVALID_SIZE;
  68. }
  69. if (!IsValidAddressRange(dst_addr, size)) {
  70. return ERR_INVALID_ADDRESS_STATE;
  71. }
  72. if (!IsValidAddressRange(src_addr, size)) {
  73. return ERR_INVALID_ADDRESS_STATE;
  74. }
  75. if (!IsInsideAddressSpace(vm_manager, src_addr, size)) {
  76. return ERR_INVALID_ADDRESS_STATE;
  77. }
  78. if (!IsInsideNewMapRegion(vm_manager, dst_addr, size)) {
  79. return ERR_INVALID_MEMORY_RANGE;
  80. }
  81. const VAddr dst_end_address = dst_addr + size;
  82. if (dst_end_address > vm_manager.GetHeapRegionBaseAddress() &&
  83. vm_manager.GetHeapRegionEndAddress() > dst_addr) {
  84. return ERR_INVALID_MEMORY_RANGE;
  85. }
  86. if (dst_end_address > vm_manager.GetMapRegionBaseAddress() &&
  87. vm_manager.GetMapRegionEndAddress() > dst_addr) {
  88. return ERR_INVALID_MEMORY_RANGE;
  89. }
  90. return RESULT_SUCCESS;
  91. }
  92. } // Anonymous namespace
  93. /// Set the process heap to a given Size. It can both extend and shrink the heap.
  94. static ResultCode SetHeapSize(VAddr* heap_addr, u64 heap_size) {
  95. LOG_TRACE(Kernel_SVC, "called, heap_size=0x{:X}", heap_size);
  96. // Size must be a multiple of 0x200000 (2MB) and be equal to or less than 4GB.
  97. if ((heap_size & 0xFFFFFFFE001FFFFF) != 0) {
  98. return ERR_INVALID_SIZE;
  99. }
  100. auto& process = *Core::CurrentProcess();
  101. const VAddr heap_base = process.VMManager().GetHeapRegionBaseAddress();
  102. CASCADE_RESULT(*heap_addr,
  103. process.HeapAllocate(heap_base, heap_size, VMAPermission::ReadWrite));
  104. return RESULT_SUCCESS;
  105. }
  106. static ResultCode SetMemoryAttribute(VAddr addr, u64 size, u32 state0, u32 state1) {
  107. LOG_WARNING(Kernel_SVC,
  108. "(STUBBED) called, addr=0x{:X}, size=0x{:X}, state0=0x{:X}, state1=0x{:X}", addr,
  109. size, state0, state1);
  110. return RESULT_SUCCESS;
  111. }
  112. /// Maps a memory range into a different range.
  113. static ResultCode MapMemory(VAddr dst_addr, VAddr src_addr, u64 size) {
  114. LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr,
  115. src_addr, size);
  116. auto* const current_process = Core::CurrentProcess();
  117. const auto& vm_manager = current_process->VMManager();
  118. const auto result = MapUnmapMemorySanityChecks(vm_manager, dst_addr, src_addr, size);
  119. if (result != RESULT_SUCCESS) {
  120. return result;
  121. }
  122. return current_process->MirrorMemory(dst_addr, src_addr, size);
  123. }
  124. /// Unmaps a region that was previously mapped with svcMapMemory
  125. static ResultCode UnmapMemory(VAddr dst_addr, VAddr src_addr, u64 size) {
  126. LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr,
  127. src_addr, size);
  128. auto* const current_process = Core::CurrentProcess();
  129. const auto& vm_manager = current_process->VMManager();
  130. const auto result = MapUnmapMemorySanityChecks(vm_manager, dst_addr, src_addr, size);
  131. if (result != RESULT_SUCCESS) {
  132. return result;
  133. }
  134. return current_process->UnmapMemory(dst_addr, src_addr, size);
  135. }
  136. /// Connect to an OS service given the port name, returns the handle to the port to out
  137. static ResultCode ConnectToNamedPort(Handle* out_handle, VAddr port_name_address) {
  138. if (!Memory::IsValidVirtualAddress(port_name_address)) {
  139. return ERR_NOT_FOUND;
  140. }
  141. static constexpr std::size_t PortNameMaxLength = 11;
  142. // Read 1 char beyond the max allowed port name to detect names that are too long.
  143. std::string port_name = Memory::ReadCString(port_name_address, PortNameMaxLength + 1);
  144. if (port_name.size() > PortNameMaxLength) {
  145. return ERR_PORT_NAME_TOO_LONG;
  146. }
  147. LOG_TRACE(Kernel_SVC, "called port_name={}", port_name);
  148. auto& kernel = Core::System::GetInstance().Kernel();
  149. auto it = kernel.FindNamedPort(port_name);
  150. if (!kernel.IsValidNamedPort(it)) {
  151. LOG_WARNING(Kernel_SVC, "tried to connect to unknown port: {}", port_name);
  152. return ERR_NOT_FOUND;
  153. }
  154. auto client_port = it->second;
  155. SharedPtr<ClientSession> client_session;
  156. CASCADE_RESULT(client_session, client_port->Connect());
  157. // Return the client session
  158. auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  159. CASCADE_RESULT(*out_handle, handle_table.Create(client_session));
  160. return RESULT_SUCCESS;
  161. }
  162. /// Makes a blocking IPC call to an OS service.
  163. static ResultCode SendSyncRequest(Handle handle) {
  164. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  165. SharedPtr<ClientSession> session = handle_table.Get<ClientSession>(handle);
  166. if (!session) {
  167. LOG_ERROR(Kernel_SVC, "called with invalid handle=0x{:08X}", handle);
  168. return ERR_INVALID_HANDLE;
  169. }
  170. LOG_TRACE(Kernel_SVC, "called handle=0x{:08X}({})", handle, session->GetName());
  171. Core::System::GetInstance().PrepareReschedule();
  172. // TODO(Subv): svcSendSyncRequest should put the caller thread to sleep while the server
  173. // responds and cause a reschedule.
  174. return session->SendSyncRequest(GetCurrentThread());
  175. }
  176. /// Get the ID for the specified thread.
  177. static ResultCode GetThreadId(u32* thread_id, Handle thread_handle) {
  178. LOG_TRACE(Kernel_SVC, "called thread=0x{:08X}", thread_handle);
  179. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  180. const SharedPtr<Thread> thread = handle_table.Get<Thread>(thread_handle);
  181. if (!thread) {
  182. return ERR_INVALID_HANDLE;
  183. }
  184. *thread_id = thread->GetThreadID();
  185. return RESULT_SUCCESS;
  186. }
  187. /// Get the ID of the specified process
  188. static ResultCode GetProcessId(u32* process_id, Handle process_handle) {
  189. LOG_TRACE(Kernel_SVC, "called process=0x{:08X}", process_handle);
  190. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  191. const SharedPtr<Process> process = handle_table.Get<Process>(process_handle);
  192. if (!process) {
  193. return ERR_INVALID_HANDLE;
  194. }
  195. *process_id = process->GetProcessID();
  196. return RESULT_SUCCESS;
  197. }
  198. /// Default thread wakeup callback for WaitSynchronization
  199. static bool DefaultThreadWakeupCallback(ThreadWakeupReason reason, SharedPtr<Thread> thread,
  200. SharedPtr<WaitObject> object, std::size_t index) {
  201. ASSERT(thread->GetStatus() == ThreadStatus::WaitSynchAny);
  202. if (reason == ThreadWakeupReason::Timeout) {
  203. thread->SetWaitSynchronizationResult(RESULT_TIMEOUT);
  204. return true;
  205. }
  206. ASSERT(reason == ThreadWakeupReason::Signal);
  207. thread->SetWaitSynchronizationResult(RESULT_SUCCESS);
  208. thread->SetWaitSynchronizationOutput(static_cast<u32>(index));
  209. return true;
  210. };
  211. /// Wait for the given handles to synchronize, timeout after the specified nanoseconds
  212. static ResultCode WaitSynchronization(Handle* index, VAddr handles_address, u64 handle_count,
  213. s64 nano_seconds) {
  214. LOG_TRACE(Kernel_SVC, "called handles_address=0x{:X}, handle_count={}, nano_seconds={}",
  215. handles_address, handle_count, nano_seconds);
  216. if (!Memory::IsValidVirtualAddress(handles_address))
  217. return ERR_INVALID_POINTER;
  218. static constexpr u64 MaxHandles = 0x40;
  219. if (handle_count > MaxHandles)
  220. return ResultCode(ErrorModule::Kernel, ErrCodes::TooLarge);
  221. auto* const thread = GetCurrentThread();
  222. using ObjectPtr = Thread::ThreadWaitObjects::value_type;
  223. Thread::ThreadWaitObjects objects(handle_count);
  224. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  225. for (u64 i = 0; i < handle_count; ++i) {
  226. const Handle handle = Memory::Read32(handles_address + i * sizeof(Handle));
  227. const auto object = handle_table.Get<WaitObject>(handle);
  228. if (object == nullptr) {
  229. return ERR_INVALID_HANDLE;
  230. }
  231. objects[i] = object;
  232. }
  233. // Find the first object that is acquirable in the provided list of objects
  234. auto itr = std::find_if(objects.begin(), objects.end(), [thread](const ObjectPtr& object) {
  235. return !object->ShouldWait(thread);
  236. });
  237. if (itr != objects.end()) {
  238. // We found a ready object, acquire it and set the result value
  239. WaitObject* object = itr->get();
  240. object->Acquire(thread);
  241. *index = static_cast<s32>(std::distance(objects.begin(), itr));
  242. return RESULT_SUCCESS;
  243. }
  244. // No objects were ready to be acquired, prepare to suspend the thread.
  245. // If a timeout value of 0 was provided, just return the Timeout error code instead of
  246. // suspending the thread.
  247. if (nano_seconds == 0)
  248. return RESULT_TIMEOUT;
  249. for (auto& object : objects)
  250. object->AddWaitingThread(thread);
  251. thread->SetWaitObjects(std::move(objects));
  252. thread->SetStatus(ThreadStatus::WaitSynchAny);
  253. // Create an event to wake the thread up after the specified nanosecond delay has passed
  254. thread->WakeAfterDelay(nano_seconds);
  255. thread->SetWakeupCallback(DefaultThreadWakeupCallback);
  256. Core::System::GetInstance().CpuCore(thread->GetProcessorID()).PrepareReschedule();
  257. return RESULT_TIMEOUT;
  258. }
  259. /// Resumes a thread waiting on WaitSynchronization
  260. static ResultCode CancelSynchronization(Handle thread_handle) {
  261. LOG_TRACE(Kernel_SVC, "called thread=0x{:X}", thread_handle);
  262. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  263. const SharedPtr<Thread> thread = handle_table.Get<Thread>(thread_handle);
  264. if (!thread) {
  265. return ERR_INVALID_HANDLE;
  266. }
  267. ASSERT(thread->GetStatus() == ThreadStatus::WaitSynchAny);
  268. thread->SetWaitSynchronizationResult(
  269. ResultCode(ErrorModule::Kernel, ErrCodes::SynchronizationCanceled));
  270. thread->ResumeFromWait();
  271. return RESULT_SUCCESS;
  272. }
  273. /// Attempts to locks a mutex, creating it if it does not already exist
  274. static ResultCode ArbitrateLock(Handle holding_thread_handle, VAddr mutex_addr,
  275. Handle requesting_thread_handle) {
  276. LOG_TRACE(Kernel_SVC,
  277. "called holding_thread_handle=0x{:08X}, mutex_addr=0x{:X}, "
  278. "requesting_current_thread_handle=0x{:08X}",
  279. holding_thread_handle, mutex_addr, requesting_thread_handle);
  280. if (Memory::IsKernelVirtualAddress(mutex_addr)) {
  281. return ERR_INVALID_ADDRESS_STATE;
  282. }
  283. if (!Common::IsWordAligned(mutex_addr)) {
  284. return ERR_INVALID_ADDRESS;
  285. }
  286. auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  287. return Mutex::TryAcquire(handle_table, mutex_addr, holding_thread_handle,
  288. requesting_thread_handle);
  289. }
  290. /// Unlock a mutex
  291. static ResultCode ArbitrateUnlock(VAddr mutex_addr) {
  292. LOG_TRACE(Kernel_SVC, "called mutex_addr=0x{:X}", mutex_addr);
  293. if (Memory::IsKernelVirtualAddress(mutex_addr)) {
  294. return ERR_INVALID_ADDRESS_STATE;
  295. }
  296. if (!Common::IsWordAligned(mutex_addr)) {
  297. return ERR_INVALID_ADDRESS;
  298. }
  299. return Mutex::Release(mutex_addr);
  300. }
  301. enum class BreakType : u32 {
  302. Panic = 0,
  303. AssertionFailed = 1,
  304. PreNROLoad = 3,
  305. PostNROLoad = 4,
  306. PreNROUnload = 5,
  307. PostNROUnload = 6,
  308. };
  309. struct BreakReason {
  310. union {
  311. u32 raw;
  312. BitField<0, 30, BreakType> break_type;
  313. BitField<31, 1, u32> signal_debugger;
  314. };
  315. };
  316. /// Break program execution
  317. static void Break(u32 reason, u64 info1, u64 info2) {
  318. BreakReason break_reason{reason};
  319. bool has_dumped_buffer{};
  320. const auto handle_debug_buffer = [&](VAddr addr, u64 sz) {
  321. if (sz == 0 || addr == 0 || has_dumped_buffer) {
  322. return;
  323. }
  324. // This typically is an error code so we're going to assume this is the case
  325. if (sz == sizeof(u32)) {
  326. LOG_CRITICAL(Debug_Emulated, "debug_buffer_err_code={:X}", Memory::Read32(addr));
  327. } else {
  328. // We don't know what's in here so we'll hexdump it
  329. std::vector<u8> debug_buffer(sz);
  330. Memory::ReadBlock(addr, debug_buffer.data(), sz);
  331. std::string hexdump;
  332. for (std::size_t i = 0; i < debug_buffer.size(); i++) {
  333. hexdump += fmt::format("{:02X} ", debug_buffer[i]);
  334. if (i != 0 && i % 16 == 0) {
  335. hexdump += '\n';
  336. }
  337. }
  338. LOG_CRITICAL(Debug_Emulated, "debug_buffer=\n{}", hexdump);
  339. }
  340. has_dumped_buffer = true;
  341. };
  342. switch (break_reason.break_type) {
  343. case BreakType::Panic:
  344. LOG_CRITICAL(Debug_Emulated, "Signalling debugger, PANIC! info1=0x{:016X}, info2=0x{:016X}",
  345. info1, info2);
  346. handle_debug_buffer(info1, info2);
  347. break;
  348. case BreakType::AssertionFailed:
  349. LOG_CRITICAL(Debug_Emulated,
  350. "Signalling debugger, Assertion failed! info1=0x{:016X}, info2=0x{:016X}",
  351. info1, info2);
  352. handle_debug_buffer(info1, info2);
  353. break;
  354. case BreakType::PreNROLoad:
  355. LOG_WARNING(
  356. Debug_Emulated,
  357. "Signalling debugger, Attempting to load an NRO at 0x{:016X} with size 0x{:016X}",
  358. info1, info2);
  359. break;
  360. case BreakType::PostNROLoad:
  361. LOG_WARNING(Debug_Emulated,
  362. "Signalling debugger, Loaded an NRO at 0x{:016X} with size 0x{:016X}", info1,
  363. info2);
  364. break;
  365. case BreakType::PreNROUnload:
  366. LOG_WARNING(
  367. Debug_Emulated,
  368. "Signalling debugger, Attempting to unload an NRO at 0x{:016X} with size 0x{:016X}",
  369. info1, info2);
  370. break;
  371. case BreakType::PostNROUnload:
  372. LOG_WARNING(Debug_Emulated,
  373. "Signalling debugger, Unloaded an NRO at 0x{:016X} with size 0x{:016X}", info1,
  374. info2);
  375. break;
  376. default:
  377. LOG_WARNING(
  378. Debug_Emulated,
  379. "Signalling debugger, Unknown break reason {}, info1=0x{:016X}, info2=0x{:016X}",
  380. static_cast<u32>(break_reason.break_type.Value()), info1, info2);
  381. handle_debug_buffer(info1, info2);
  382. break;
  383. }
  384. if (!break_reason.signal_debugger) {
  385. LOG_CRITICAL(
  386. Debug_Emulated,
  387. "Emulated program broke execution! reason=0x{:016X}, info1=0x{:016X}, info2=0x{:016X}",
  388. reason, info1, info2);
  389. handle_debug_buffer(info1, info2);
  390. ASSERT(false);
  391. Core::CurrentProcess()->PrepareForTermination();
  392. // Kill the current thread
  393. GetCurrentThread()->Stop();
  394. Core::System::GetInstance().PrepareReschedule();
  395. }
  396. }
  397. /// Used to output a message on a debug hardware unit - does nothing on a retail unit
  398. static void OutputDebugString(VAddr address, u64 len) {
  399. if (len == 0) {
  400. return;
  401. }
  402. std::string str(len, '\0');
  403. Memory::ReadBlock(address, str.data(), str.size());
  404. LOG_DEBUG(Debug_Emulated, "{}", str);
  405. }
  406. /// Gets system/memory information for the current process
  407. static ResultCode GetInfo(u64* result, u64 info_id, u64 handle, u64 info_sub_id) {
  408. LOG_TRACE(Kernel_SVC, "called info_id=0x{:X}, info_sub_id=0x{:X}, handle=0x{:08X}", info_id,
  409. info_sub_id, handle);
  410. enum class GetInfoType : u64 {
  411. // 1.0.0+
  412. AllowedCpuIdBitmask = 0,
  413. AllowedThreadPrioBitmask = 1,
  414. MapRegionBaseAddr = 2,
  415. MapRegionSize = 3,
  416. HeapRegionBaseAddr = 4,
  417. HeapRegionSize = 5,
  418. TotalMemoryUsage = 6,
  419. TotalHeapUsage = 7,
  420. IsCurrentProcessBeingDebugged = 8,
  421. ResourceHandleLimit = 9,
  422. IdleTickCount = 10,
  423. RandomEntropy = 11,
  424. PerformanceCounter = 0xF0000002,
  425. // 2.0.0+
  426. ASLRRegionBaseAddr = 12,
  427. ASLRRegionSize = 13,
  428. NewMapRegionBaseAddr = 14,
  429. NewMapRegionSize = 15,
  430. // 3.0.0+
  431. IsVirtualAddressMemoryEnabled = 16,
  432. PersonalMmHeapUsage = 17,
  433. TitleId = 18,
  434. // 4.0.0+
  435. PrivilegedProcessId = 19,
  436. // 5.0.0+
  437. UserExceptionContextAddr = 20,
  438. ThreadTickCount = 0xF0000002,
  439. };
  440. const auto* current_process = Core::CurrentProcess();
  441. const auto& vm_manager = current_process->VMManager();
  442. switch (static_cast<GetInfoType>(info_id)) {
  443. case GetInfoType::AllowedCpuIdBitmask:
  444. *result = current_process->GetAllowedProcessorMask();
  445. break;
  446. case GetInfoType::AllowedThreadPrioBitmask:
  447. *result = current_process->GetAllowedThreadPriorityMask();
  448. break;
  449. case GetInfoType::MapRegionBaseAddr:
  450. *result = vm_manager.GetMapRegionBaseAddress();
  451. break;
  452. case GetInfoType::MapRegionSize:
  453. *result = vm_manager.GetMapRegionSize();
  454. break;
  455. case GetInfoType::HeapRegionBaseAddr:
  456. *result = vm_manager.GetHeapRegionBaseAddress();
  457. break;
  458. case GetInfoType::HeapRegionSize:
  459. *result = vm_manager.GetHeapRegionSize();
  460. break;
  461. case GetInfoType::TotalMemoryUsage:
  462. *result = vm_manager.GetTotalMemoryUsage();
  463. break;
  464. case GetInfoType::TotalHeapUsage:
  465. *result = vm_manager.GetTotalHeapUsage();
  466. break;
  467. case GetInfoType::IsCurrentProcessBeingDebugged:
  468. *result = 0;
  469. break;
  470. case GetInfoType::RandomEntropy:
  471. if (handle != 0) {
  472. return ERR_INVALID_HANDLE;
  473. }
  474. if (info_sub_id >= Process::RANDOM_ENTROPY_SIZE) {
  475. return ERR_INVALID_COMBINATION_KERNEL;
  476. }
  477. *result = current_process->GetRandomEntropy(info_sub_id);
  478. return RESULT_SUCCESS;
  479. break;
  480. case GetInfoType::ASLRRegionBaseAddr:
  481. *result = vm_manager.GetASLRRegionBaseAddress();
  482. break;
  483. case GetInfoType::ASLRRegionSize:
  484. *result = vm_manager.GetASLRRegionSize();
  485. break;
  486. case GetInfoType::NewMapRegionBaseAddr:
  487. *result = vm_manager.GetNewMapRegionBaseAddress();
  488. break;
  489. case GetInfoType::NewMapRegionSize:
  490. *result = vm_manager.GetNewMapRegionSize();
  491. break;
  492. case GetInfoType::IsVirtualAddressMemoryEnabled:
  493. *result = current_process->IsVirtualMemoryEnabled();
  494. break;
  495. case GetInfoType::TitleId:
  496. *result = current_process->GetTitleID();
  497. break;
  498. case GetInfoType::PrivilegedProcessId:
  499. LOG_WARNING(Kernel_SVC,
  500. "(STUBBED) Attempted to query privileged process id bounds, returned 0");
  501. *result = 0;
  502. break;
  503. case GetInfoType::UserExceptionContextAddr:
  504. LOG_WARNING(Kernel_SVC,
  505. "(STUBBED) Attempted to query user exception context address, returned 0");
  506. *result = 0;
  507. break;
  508. case GetInfoType::ThreadTickCount: {
  509. constexpr u64 num_cpus = 4;
  510. if (info_sub_id != 0xFFFFFFFFFFFFFFFF && info_sub_id >= num_cpus) {
  511. return ERR_INVALID_COMBINATION_KERNEL;
  512. }
  513. const auto thread =
  514. current_process->GetHandleTable().Get<Thread>(static_cast<Handle>(handle));
  515. if (!thread) {
  516. return ERR_INVALID_HANDLE;
  517. }
  518. const auto& system = Core::System::GetInstance();
  519. const auto& scheduler = system.CurrentScheduler();
  520. const auto* const current_thread = scheduler.GetCurrentThread();
  521. const bool same_thread = current_thread == thread;
  522. const u64 prev_ctx_ticks = scheduler.GetLastContextSwitchTicks();
  523. u64 out_ticks = 0;
  524. if (same_thread && info_sub_id == 0xFFFFFFFFFFFFFFFF) {
  525. const u64 thread_ticks = current_thread->GetTotalCPUTimeTicks();
  526. out_ticks = thread_ticks + (CoreTiming::GetTicks() - prev_ctx_ticks);
  527. } else if (same_thread && info_sub_id == system.CurrentCoreIndex()) {
  528. out_ticks = CoreTiming::GetTicks() - prev_ctx_ticks;
  529. }
  530. *result = out_ticks;
  531. break;
  532. }
  533. default:
  534. UNIMPLEMENTED();
  535. }
  536. return RESULT_SUCCESS;
  537. }
  538. /// Sets the thread activity
  539. static ResultCode SetThreadActivity(Handle handle, u32 unknown) {
  540. LOG_WARNING(Kernel_SVC, "(STUBBED) called, handle=0x{:08X}, unknown=0x{:08X}", handle, unknown);
  541. return RESULT_SUCCESS;
  542. }
  543. /// Gets the thread context
  544. static ResultCode GetThreadContext(VAddr thread_context, Handle handle) {
  545. LOG_DEBUG(Kernel_SVC, "called, context=0x{:08X}, thread=0x{:X}", thread_context, handle);
  546. const auto* current_process = Core::CurrentProcess();
  547. const SharedPtr<Thread> thread = current_process->GetHandleTable().Get<Thread>(handle);
  548. if (!thread) {
  549. return ERR_INVALID_HANDLE;
  550. }
  551. if (thread->GetOwnerProcess() != current_process) {
  552. return ERR_INVALID_HANDLE;
  553. }
  554. if (thread == GetCurrentThread()) {
  555. return ERR_ALREADY_REGISTERED;
  556. }
  557. Core::ARM_Interface::ThreadContext ctx = thread->GetContext();
  558. // Mask away mode bits, interrupt bits, IL bit, and other reserved bits.
  559. ctx.pstate &= 0xFF0FFE20;
  560. // If 64-bit, we can just write the context registers directly and we're good.
  561. // However, if 32-bit, we have to ensure some registers are zeroed out.
  562. if (!current_process->Is64BitProcess()) {
  563. std::fill(ctx.cpu_registers.begin() + 15, ctx.cpu_registers.end(), 0);
  564. std::fill(ctx.vector_registers.begin() + 16, ctx.vector_registers.end(), u128{});
  565. }
  566. Memory::WriteBlock(thread_context, &ctx, sizeof(ctx));
  567. return RESULT_SUCCESS;
  568. }
  569. /// Gets the priority for the specified thread
  570. static ResultCode GetThreadPriority(u32* priority, Handle handle) {
  571. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  572. const SharedPtr<Thread> thread = handle_table.Get<Thread>(handle);
  573. if (!thread) {
  574. return ERR_INVALID_HANDLE;
  575. }
  576. *priority = thread->GetPriority();
  577. return RESULT_SUCCESS;
  578. }
  579. /// Sets the priority for the specified thread
  580. static ResultCode SetThreadPriority(Handle handle, u32 priority) {
  581. if (priority > THREADPRIO_LOWEST) {
  582. return ERR_INVALID_THREAD_PRIORITY;
  583. }
  584. const auto* const current_process = Core::CurrentProcess();
  585. // Note: The kernel uses the current process's resource limit instead of
  586. // the one from the thread owner's resource limit.
  587. const ResourceLimit& resource_limit = current_process->GetResourceLimit();
  588. if (resource_limit.GetMaxResourceValue(ResourceType::Priority) > priority) {
  589. return ERR_INVALID_THREAD_PRIORITY;
  590. }
  591. SharedPtr<Thread> thread = current_process->GetHandleTable().Get<Thread>(handle);
  592. if (!thread) {
  593. return ERR_INVALID_HANDLE;
  594. }
  595. thread->SetPriority(priority);
  596. Core::System::GetInstance().CpuCore(thread->GetProcessorID()).PrepareReschedule();
  597. return RESULT_SUCCESS;
  598. }
  599. /// Get which CPU core is executing the current thread
  600. static u32 GetCurrentProcessorNumber() {
  601. LOG_TRACE(Kernel_SVC, "called");
  602. return GetCurrentThread()->GetProcessorID();
  603. }
  604. static ResultCode MapSharedMemory(Handle shared_memory_handle, VAddr addr, u64 size,
  605. u32 permissions) {
  606. LOG_TRACE(Kernel_SVC,
  607. "called, shared_memory_handle=0x{:X}, addr=0x{:X}, size=0x{:X}, permissions=0x{:08X}",
  608. shared_memory_handle, addr, size, permissions);
  609. if (!Common::Is4KBAligned(addr)) {
  610. return ERR_INVALID_ADDRESS;
  611. }
  612. if (size == 0 || !Common::Is4KBAligned(size)) {
  613. return ERR_INVALID_SIZE;
  614. }
  615. if (!IsValidAddressRange(addr, size)) {
  616. return ERR_INVALID_ADDRESS_STATE;
  617. }
  618. const auto permissions_type = static_cast<MemoryPermission>(permissions);
  619. if (permissions_type != MemoryPermission::Read &&
  620. permissions_type != MemoryPermission::ReadWrite) {
  621. LOG_ERROR(Kernel_SVC, "Invalid permissions=0x{:08X}", permissions);
  622. return ERR_INVALID_MEMORY_PERMISSIONS;
  623. }
  624. auto* const current_process = Core::CurrentProcess();
  625. auto shared_memory = current_process->GetHandleTable().Get<SharedMemory>(shared_memory_handle);
  626. if (!shared_memory) {
  627. return ERR_INVALID_HANDLE;
  628. }
  629. const auto& vm_manager = current_process->VMManager();
  630. if (!vm_manager.IsWithinASLRRegion(addr, size)) {
  631. return ERR_INVALID_MEMORY_RANGE;
  632. }
  633. return shared_memory->Map(current_process, addr, permissions_type, MemoryPermission::DontCare);
  634. }
  635. static ResultCode UnmapSharedMemory(Handle shared_memory_handle, VAddr addr, u64 size) {
  636. LOG_WARNING(Kernel_SVC, "called, shared_memory_handle=0x{:08X}, addr=0x{:X}, size=0x{:X}",
  637. shared_memory_handle, addr, size);
  638. if (!Common::Is4KBAligned(addr)) {
  639. return ERR_INVALID_ADDRESS;
  640. }
  641. if (size == 0 || !Common::Is4KBAligned(size)) {
  642. return ERR_INVALID_SIZE;
  643. }
  644. if (!IsValidAddressRange(addr, size)) {
  645. return ERR_INVALID_ADDRESS_STATE;
  646. }
  647. auto* const current_process = Core::CurrentProcess();
  648. auto shared_memory = current_process->GetHandleTable().Get<SharedMemory>(shared_memory_handle);
  649. if (!shared_memory) {
  650. return ERR_INVALID_HANDLE;
  651. }
  652. const auto& vm_manager = current_process->VMManager();
  653. if (!vm_manager.IsWithinASLRRegion(addr, size)) {
  654. return ERR_INVALID_MEMORY_RANGE;
  655. }
  656. return shared_memory->Unmap(current_process, addr);
  657. }
  658. /// Query process memory
  659. static ResultCode QueryProcessMemory(MemoryInfo* memory_info, PageInfo* /*page_info*/,
  660. Handle process_handle, u64 addr) {
  661. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  662. SharedPtr<Process> process = handle_table.Get<Process>(process_handle);
  663. if (!process) {
  664. return ERR_INVALID_HANDLE;
  665. }
  666. auto vma = process->VMManager().FindVMA(addr);
  667. memory_info->attributes = 0;
  668. if (vma == process->VMManager().vma_map.end()) {
  669. memory_info->base_address = 0;
  670. memory_info->permission = static_cast<u32>(VMAPermission::None);
  671. memory_info->size = 0;
  672. memory_info->type = static_cast<u32>(MemoryState::Unmapped);
  673. } else {
  674. memory_info->base_address = vma->second.base;
  675. memory_info->permission = static_cast<u32>(vma->second.permissions);
  676. memory_info->size = vma->second.size;
  677. memory_info->type = static_cast<u32>(vma->second.meminfo_state);
  678. }
  679. LOG_TRACE(Kernel_SVC, "called process=0x{:08X} addr={:X}", process_handle, addr);
  680. return RESULT_SUCCESS;
  681. }
  682. /// Query memory
  683. static ResultCode QueryMemory(MemoryInfo* memory_info, PageInfo* page_info, VAddr addr) {
  684. LOG_TRACE(Kernel_SVC, "called, addr={:X}", addr);
  685. return QueryProcessMemory(memory_info, page_info, CurrentProcess, addr);
  686. }
  687. /// Exits the current process
  688. static void ExitProcess() {
  689. auto* current_process = Core::CurrentProcess();
  690. LOG_INFO(Kernel_SVC, "Process {} exiting", current_process->GetProcessID());
  691. ASSERT_MSG(current_process->GetStatus() == ProcessStatus::Running,
  692. "Process has already exited");
  693. current_process->PrepareForTermination();
  694. // Kill the current thread
  695. GetCurrentThread()->Stop();
  696. Core::System::GetInstance().PrepareReschedule();
  697. }
  698. /// Creates a new thread
  699. static ResultCode CreateThread(Handle* out_handle, VAddr entry_point, u64 arg, VAddr stack_top,
  700. u32 priority, s32 processor_id) {
  701. if (priority > THREADPRIO_LOWEST) {
  702. return ERR_INVALID_THREAD_PRIORITY;
  703. }
  704. auto* const current_process = Core::CurrentProcess();
  705. const ResourceLimit& resource_limit = current_process->GetResourceLimit();
  706. if (resource_limit.GetMaxResourceValue(ResourceType::Priority) > priority) {
  707. return ERR_INVALID_THREAD_PRIORITY;
  708. }
  709. if (processor_id == THREADPROCESSORID_DEFAULT) {
  710. // Set the target CPU to the one specified in the process' exheader.
  711. processor_id = current_process->GetDefaultProcessorID();
  712. ASSERT(processor_id != THREADPROCESSORID_DEFAULT);
  713. }
  714. switch (processor_id) {
  715. case THREADPROCESSORID_0:
  716. case THREADPROCESSORID_1:
  717. case THREADPROCESSORID_2:
  718. case THREADPROCESSORID_3:
  719. break;
  720. default:
  721. LOG_ERROR(Kernel_SVC, "Invalid thread processor ID: {}", processor_id);
  722. return ERR_INVALID_PROCESSOR_ID;
  723. }
  724. const std::string name = fmt::format("thread-{:X}", entry_point);
  725. auto& kernel = Core::System::GetInstance().Kernel();
  726. CASCADE_RESULT(SharedPtr<Thread> thread,
  727. Thread::Create(kernel, name, entry_point, priority, arg, processor_id, stack_top,
  728. *current_process));
  729. const auto new_guest_handle = current_process->GetHandleTable().Create(thread);
  730. if (new_guest_handle.Failed()) {
  731. return new_guest_handle.Code();
  732. }
  733. thread->SetGuestHandle(*new_guest_handle);
  734. *out_handle = *new_guest_handle;
  735. Core::System::GetInstance().CpuCore(thread->GetProcessorID()).PrepareReschedule();
  736. LOG_TRACE(Kernel_SVC,
  737. "called entrypoint=0x{:08X} ({}), arg=0x{:08X}, stacktop=0x{:08X}, "
  738. "threadpriority=0x{:08X}, processorid=0x{:08X} : created handle=0x{:08X}",
  739. entry_point, name, arg, stack_top, priority, processor_id, *out_handle);
  740. return RESULT_SUCCESS;
  741. }
  742. /// Starts the thread for the provided handle
  743. static ResultCode StartThread(Handle thread_handle) {
  744. LOG_TRACE(Kernel_SVC, "called thread=0x{:08X}", thread_handle);
  745. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  746. const SharedPtr<Thread> thread = handle_table.Get<Thread>(thread_handle);
  747. if (!thread) {
  748. return ERR_INVALID_HANDLE;
  749. }
  750. ASSERT(thread->GetStatus() == ThreadStatus::Dormant);
  751. thread->ResumeFromWait();
  752. Core::System::GetInstance().CpuCore(thread->GetProcessorID()).PrepareReschedule();
  753. return RESULT_SUCCESS;
  754. }
  755. /// Called when a thread exits
  756. static void ExitThread() {
  757. LOG_TRACE(Kernel_SVC, "called, pc=0x{:08X}", Core::CurrentArmInterface().GetPC());
  758. ExitCurrentThread();
  759. Core::System::GetInstance().PrepareReschedule();
  760. }
  761. /// Sleep the current thread
  762. static void SleepThread(s64 nanoseconds) {
  763. LOG_TRACE(Kernel_SVC, "called nanoseconds={}", nanoseconds);
  764. // Don't attempt to yield execution if there are no available threads to run,
  765. // this way we avoid a useless reschedule to the idle thread.
  766. if (nanoseconds == 0 && !Core::System::GetInstance().CurrentScheduler().HaveReadyThreads())
  767. return;
  768. // Sleep current thread and check for next thread to schedule
  769. WaitCurrentThread_Sleep();
  770. // Create an event to wake the thread up after the specified nanosecond delay has passed
  771. GetCurrentThread()->WakeAfterDelay(nanoseconds);
  772. Core::System::GetInstance().PrepareReschedule();
  773. }
  774. /// Wait process wide key atomic
  775. static ResultCode WaitProcessWideKeyAtomic(VAddr mutex_addr, VAddr condition_variable_addr,
  776. Handle thread_handle, s64 nano_seconds) {
  777. LOG_TRACE(
  778. Kernel_SVC,
  779. "called mutex_addr={:X}, condition_variable_addr={:X}, thread_handle=0x{:08X}, timeout={}",
  780. mutex_addr, condition_variable_addr, thread_handle, nano_seconds);
  781. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  782. SharedPtr<Thread> thread = handle_table.Get<Thread>(thread_handle);
  783. ASSERT(thread);
  784. CASCADE_CODE(Mutex::Release(mutex_addr));
  785. SharedPtr<Thread> current_thread = GetCurrentThread();
  786. current_thread->SetCondVarWaitAddress(condition_variable_addr);
  787. current_thread->SetMutexWaitAddress(mutex_addr);
  788. current_thread->SetWaitHandle(thread_handle);
  789. current_thread->SetStatus(ThreadStatus::WaitMutex);
  790. current_thread->InvalidateWakeupCallback();
  791. current_thread->WakeAfterDelay(nano_seconds);
  792. // Note: Deliberately don't attempt to inherit the lock owner's priority.
  793. Core::System::GetInstance().CpuCore(current_thread->GetProcessorID()).PrepareReschedule();
  794. return RESULT_SUCCESS;
  795. }
  796. /// Signal process wide key
  797. static ResultCode SignalProcessWideKey(VAddr condition_variable_addr, s32 target) {
  798. LOG_TRACE(Kernel_SVC, "called, condition_variable_addr=0x{:X}, target=0x{:08X}",
  799. condition_variable_addr, target);
  800. const auto RetrieveWaitingThreads = [](std::size_t core_index,
  801. std::vector<SharedPtr<Thread>>& waiting_threads,
  802. VAddr condvar_addr) {
  803. const auto& scheduler = Core::System::GetInstance().Scheduler(core_index);
  804. const auto& thread_list = scheduler.GetThreadList();
  805. for (const auto& thread : thread_list) {
  806. if (thread->GetCondVarWaitAddress() == condvar_addr)
  807. waiting_threads.push_back(thread);
  808. }
  809. };
  810. // Retrieve a list of all threads that are waiting for this condition variable.
  811. std::vector<SharedPtr<Thread>> waiting_threads;
  812. RetrieveWaitingThreads(0, waiting_threads, condition_variable_addr);
  813. RetrieveWaitingThreads(1, waiting_threads, condition_variable_addr);
  814. RetrieveWaitingThreads(2, waiting_threads, condition_variable_addr);
  815. RetrieveWaitingThreads(3, waiting_threads, condition_variable_addr);
  816. // Sort them by priority, such that the highest priority ones come first.
  817. std::sort(waiting_threads.begin(), waiting_threads.end(),
  818. [](const SharedPtr<Thread>& lhs, const SharedPtr<Thread>& rhs) {
  819. return lhs->GetPriority() < rhs->GetPriority();
  820. });
  821. // Only process up to 'target' threads, unless 'target' is -1, in which case process
  822. // them all.
  823. std::size_t last = waiting_threads.size();
  824. if (target != -1)
  825. last = target;
  826. // If there are no threads waiting on this condition variable, just exit
  827. if (last > waiting_threads.size())
  828. return RESULT_SUCCESS;
  829. for (std::size_t index = 0; index < last; ++index) {
  830. auto& thread = waiting_threads[index];
  831. ASSERT(thread->GetCondVarWaitAddress() == condition_variable_addr);
  832. std::size_t current_core = Core::System::GetInstance().CurrentCoreIndex();
  833. auto& monitor = Core::System::GetInstance().Monitor();
  834. // Atomically read the value of the mutex.
  835. u32 mutex_val = 0;
  836. do {
  837. monitor.SetExclusive(current_core, thread->GetMutexWaitAddress());
  838. // If the mutex is not yet acquired, acquire it.
  839. mutex_val = Memory::Read32(thread->GetMutexWaitAddress());
  840. if (mutex_val != 0) {
  841. monitor.ClearExclusive();
  842. break;
  843. }
  844. } while (!monitor.ExclusiveWrite32(current_core, thread->GetMutexWaitAddress(),
  845. thread->GetWaitHandle()));
  846. if (mutex_val == 0) {
  847. // We were able to acquire the mutex, resume this thread.
  848. ASSERT(thread->GetStatus() == ThreadStatus::WaitMutex);
  849. thread->ResumeFromWait();
  850. auto* const lock_owner = thread->GetLockOwner();
  851. if (lock_owner != nullptr) {
  852. lock_owner->RemoveMutexWaiter(thread);
  853. }
  854. thread->SetLockOwner(nullptr);
  855. thread->SetMutexWaitAddress(0);
  856. thread->SetCondVarWaitAddress(0);
  857. thread->SetWaitHandle(0);
  858. } else {
  859. // Atomically signal that the mutex now has a waiting thread.
  860. do {
  861. monitor.SetExclusive(current_core, thread->GetMutexWaitAddress());
  862. // Ensure that the mutex value is still what we expect.
  863. u32 value = Memory::Read32(thread->GetMutexWaitAddress());
  864. // TODO(Subv): When this happens, the kernel just clears the exclusive state and
  865. // retries the initial read for this thread.
  866. ASSERT_MSG(mutex_val == value, "Unhandled synchronization primitive case");
  867. } while (!monitor.ExclusiveWrite32(current_core, thread->GetMutexWaitAddress(),
  868. mutex_val | Mutex::MutexHasWaitersFlag));
  869. // The mutex is already owned by some other thread, make this thread wait on it.
  870. const Handle owner_handle = static_cast<Handle>(mutex_val & Mutex::MutexOwnerMask);
  871. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  872. auto owner = handle_table.Get<Thread>(owner_handle);
  873. ASSERT(owner);
  874. ASSERT(thread->GetStatus() == ThreadStatus::WaitMutex);
  875. thread->InvalidateWakeupCallback();
  876. owner->AddMutexWaiter(thread);
  877. Core::System::GetInstance().CpuCore(thread->GetProcessorID()).PrepareReschedule();
  878. }
  879. }
  880. return RESULT_SUCCESS;
  881. }
  882. // Wait for an address (via Address Arbiter)
  883. static ResultCode WaitForAddress(VAddr address, u32 type, s32 value, s64 timeout) {
  884. LOG_WARNING(Kernel_SVC, "called, address=0x{:X}, type=0x{:X}, value=0x{:X}, timeout={}",
  885. address, type, value, timeout);
  886. // If the passed address is a kernel virtual address, return invalid memory state.
  887. if (Memory::IsKernelVirtualAddress(address)) {
  888. return ERR_INVALID_ADDRESS_STATE;
  889. }
  890. // If the address is not properly aligned to 4 bytes, return invalid address.
  891. if (address % sizeof(u32) != 0) {
  892. return ERR_INVALID_ADDRESS;
  893. }
  894. switch (static_cast<AddressArbiter::ArbitrationType>(type)) {
  895. case AddressArbiter::ArbitrationType::WaitIfLessThan:
  896. return AddressArbiter::WaitForAddressIfLessThan(address, value, timeout, false);
  897. case AddressArbiter::ArbitrationType::DecrementAndWaitIfLessThan:
  898. return AddressArbiter::WaitForAddressIfLessThan(address, value, timeout, true);
  899. case AddressArbiter::ArbitrationType::WaitIfEqual:
  900. return AddressArbiter::WaitForAddressIfEqual(address, value, timeout);
  901. default:
  902. return ERR_INVALID_ENUM_VALUE;
  903. }
  904. }
  905. // Signals to an address (via Address Arbiter)
  906. static ResultCode SignalToAddress(VAddr address, u32 type, s32 value, s32 num_to_wake) {
  907. LOG_WARNING(Kernel_SVC, "called, address=0x{:X}, type=0x{:X}, value=0x{:X}, num_to_wake=0x{:X}",
  908. address, type, value, num_to_wake);
  909. // If the passed address is a kernel virtual address, return invalid memory state.
  910. if (Memory::IsKernelVirtualAddress(address)) {
  911. return ERR_INVALID_ADDRESS_STATE;
  912. }
  913. // If the address is not properly aligned to 4 bytes, return invalid address.
  914. if (address % sizeof(u32) != 0) {
  915. return ERR_INVALID_ADDRESS;
  916. }
  917. switch (static_cast<AddressArbiter::SignalType>(type)) {
  918. case AddressArbiter::SignalType::Signal:
  919. return AddressArbiter::SignalToAddress(address, num_to_wake);
  920. case AddressArbiter::SignalType::IncrementAndSignalIfEqual:
  921. return AddressArbiter::IncrementAndSignalToAddressIfEqual(address, value, num_to_wake);
  922. case AddressArbiter::SignalType::ModifyByWaitingCountAndSignalIfEqual:
  923. return AddressArbiter::ModifyByWaitingCountAndSignalToAddressIfEqual(address, value,
  924. num_to_wake);
  925. default:
  926. return ERR_INVALID_ENUM_VALUE;
  927. }
  928. }
  929. /// This returns the total CPU ticks elapsed since the CPU was powered-on
  930. static u64 GetSystemTick() {
  931. const u64 result{CoreTiming::GetTicks()};
  932. // Advance time to defeat dumb games that busy-wait for the frame to end.
  933. CoreTiming::AddTicks(400);
  934. return result;
  935. }
  936. /// Close a handle
  937. static ResultCode CloseHandle(Handle handle) {
  938. LOG_TRACE(Kernel_SVC, "Closing handle 0x{:08X}", handle);
  939. auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  940. return handle_table.Close(handle);
  941. }
  942. /// Reset an event
  943. static ResultCode ResetSignal(Handle handle) {
  944. LOG_WARNING(Kernel_SVC, "(STUBBED) called handle 0x{:08X}", handle);
  945. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  946. auto event = handle_table.Get<Event>(handle);
  947. ASSERT(event != nullptr);
  948. event->Clear();
  949. return RESULT_SUCCESS;
  950. }
  951. /// Creates a TransferMemory object
  952. static ResultCode CreateTransferMemory(Handle* handle, VAddr addr, u64 size, u32 permissions) {
  953. LOG_WARNING(Kernel_SVC, "(STUBBED) called addr=0x{:X}, size=0x{:X}, perms=0x{:08X}", addr, size,
  954. permissions);
  955. *handle = 0;
  956. return RESULT_SUCCESS;
  957. }
  958. static ResultCode GetThreadCoreMask(Handle thread_handle, u32* core, u64* mask) {
  959. LOG_TRACE(Kernel_SVC, "called, handle=0x{:08X}", thread_handle);
  960. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  961. const SharedPtr<Thread> thread = handle_table.Get<Thread>(thread_handle);
  962. if (!thread) {
  963. return ERR_INVALID_HANDLE;
  964. }
  965. *core = thread->GetIdealCore();
  966. *mask = thread->GetAffinityMask();
  967. return RESULT_SUCCESS;
  968. }
  969. static ResultCode SetThreadCoreMask(Handle thread_handle, u32 core, u64 mask) {
  970. LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, mask=0x{:16X}, core=0x{:X}", thread_handle,
  971. mask, core);
  972. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  973. const SharedPtr<Thread> thread = handle_table.Get<Thread>(thread_handle);
  974. if (!thread) {
  975. return ERR_INVALID_HANDLE;
  976. }
  977. if (core == static_cast<u32>(THREADPROCESSORID_DEFAULT)) {
  978. const u8 default_processor_id = thread->GetOwnerProcess()->GetDefaultProcessorID();
  979. ASSERT(default_processor_id != static_cast<u8>(THREADPROCESSORID_DEFAULT));
  980. // Set the target CPU to the one specified in the process' exheader.
  981. core = default_processor_id;
  982. mask = 1ULL << core;
  983. }
  984. if (mask == 0) {
  985. return ResultCode(ErrorModule::Kernel, ErrCodes::InvalidCombination);
  986. }
  987. /// This value is used to only change the affinity mask without changing the current ideal core.
  988. static constexpr u32 OnlyChangeMask = static_cast<u32>(-3);
  989. if (core == OnlyChangeMask) {
  990. core = thread->GetIdealCore();
  991. } else if (core >= Core::NUM_CPU_CORES && core != static_cast<u32>(-1)) {
  992. return ResultCode(ErrorModule::Kernel, ErrCodes::InvalidProcessorId);
  993. }
  994. // Error out if the input core isn't enabled in the input mask.
  995. if (core < Core::NUM_CPU_CORES && (mask & (1ull << core)) == 0) {
  996. return ResultCode(ErrorModule::Kernel, ErrCodes::InvalidCombination);
  997. }
  998. thread->ChangeCore(core, mask);
  999. return RESULT_SUCCESS;
  1000. }
  1001. static ResultCode CreateSharedMemory(Handle* handle, u64 size, u32 local_permissions,
  1002. u32 remote_permissions) {
  1003. LOG_TRACE(Kernel_SVC, "called, size=0x{:X}, localPerms=0x{:08X}, remotePerms=0x{:08X}", size,
  1004. local_permissions, remote_permissions);
  1005. // Size must be a multiple of 4KB and be less than or equal to
  1006. // approx. 8 GB (actually (1GB - 512B) * 8)
  1007. if (size == 0 || (size & 0xFFFFFFFE00000FFF) != 0) {
  1008. return ERR_INVALID_SIZE;
  1009. }
  1010. const auto local_perms = static_cast<MemoryPermission>(local_permissions);
  1011. if (local_perms != MemoryPermission::Read && local_perms != MemoryPermission::ReadWrite) {
  1012. return ERR_INVALID_MEMORY_PERMISSIONS;
  1013. }
  1014. const auto remote_perms = static_cast<MemoryPermission>(remote_permissions);
  1015. if (remote_perms != MemoryPermission::Read && remote_perms != MemoryPermission::ReadWrite &&
  1016. remote_perms != MemoryPermission::DontCare) {
  1017. return ERR_INVALID_MEMORY_PERMISSIONS;
  1018. }
  1019. auto& kernel = Core::System::GetInstance().Kernel();
  1020. auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  1021. auto shared_mem_handle =
  1022. SharedMemory::Create(kernel, handle_table.Get<Process>(KernelHandle::CurrentProcess), size,
  1023. local_perms, remote_perms);
  1024. CASCADE_RESULT(*handle, handle_table.Create(shared_mem_handle));
  1025. return RESULT_SUCCESS;
  1026. }
  1027. static ResultCode ClearEvent(Handle handle) {
  1028. LOG_TRACE(Kernel_SVC, "called, event=0x{:08X}", handle);
  1029. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  1030. SharedPtr<Event> evt = handle_table.Get<Event>(handle);
  1031. if (evt == nullptr) {
  1032. return ERR_INVALID_HANDLE;
  1033. }
  1034. evt->Clear();
  1035. return RESULT_SUCCESS;
  1036. }
  1037. static ResultCode GetProcessInfo(u64* out, Handle process_handle, u32 type) {
  1038. LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, type=0x{:X}", process_handle, type);
  1039. // This function currently only allows retrieving a process' status.
  1040. enum class InfoType {
  1041. Status,
  1042. };
  1043. const auto& handle_table = Core::CurrentProcess()->GetHandleTable();
  1044. const auto process = handle_table.Get<Process>(process_handle);
  1045. if (!process) {
  1046. return ERR_INVALID_HANDLE;
  1047. }
  1048. const auto info_type = static_cast<InfoType>(type);
  1049. if (info_type != InfoType::Status) {
  1050. return ERR_INVALID_ENUM_VALUE;
  1051. }
  1052. *out = static_cast<u64>(process->GetStatus());
  1053. return RESULT_SUCCESS;
  1054. }
  1055. namespace {
  1056. struct FunctionDef {
  1057. using Func = void();
  1058. u32 id;
  1059. Func* func;
  1060. const char* name;
  1061. };
  1062. } // namespace
  1063. static const FunctionDef SVC_Table[] = {
  1064. {0x00, nullptr, "Unknown"},
  1065. {0x01, SvcWrap<SetHeapSize>, "SetHeapSize"},
  1066. {0x02, nullptr, "SetMemoryPermission"},
  1067. {0x03, SvcWrap<SetMemoryAttribute>, "SetMemoryAttribute"},
  1068. {0x04, SvcWrap<MapMemory>, "MapMemory"},
  1069. {0x05, SvcWrap<UnmapMemory>, "UnmapMemory"},
  1070. {0x06, SvcWrap<QueryMemory>, "QueryMemory"},
  1071. {0x07, SvcWrap<ExitProcess>, "ExitProcess"},
  1072. {0x08, SvcWrap<CreateThread>, "CreateThread"},
  1073. {0x09, SvcWrap<StartThread>, "StartThread"},
  1074. {0x0A, SvcWrap<ExitThread>, "ExitThread"},
  1075. {0x0B, SvcWrap<SleepThread>, "SleepThread"},
  1076. {0x0C, SvcWrap<GetThreadPriority>, "GetThreadPriority"},
  1077. {0x0D, SvcWrap<SetThreadPriority>, "SetThreadPriority"},
  1078. {0x0E, SvcWrap<GetThreadCoreMask>, "GetThreadCoreMask"},
  1079. {0x0F, SvcWrap<SetThreadCoreMask>, "SetThreadCoreMask"},
  1080. {0x10, SvcWrap<GetCurrentProcessorNumber>, "GetCurrentProcessorNumber"},
  1081. {0x11, nullptr, "SignalEvent"},
  1082. {0x12, SvcWrap<ClearEvent>, "ClearEvent"},
  1083. {0x13, SvcWrap<MapSharedMemory>, "MapSharedMemory"},
  1084. {0x14, SvcWrap<UnmapSharedMemory>, "UnmapSharedMemory"},
  1085. {0x15, SvcWrap<CreateTransferMemory>, "CreateTransferMemory"},
  1086. {0x16, SvcWrap<CloseHandle>, "CloseHandle"},
  1087. {0x17, SvcWrap<ResetSignal>, "ResetSignal"},
  1088. {0x18, SvcWrap<WaitSynchronization>, "WaitSynchronization"},
  1089. {0x19, SvcWrap<CancelSynchronization>, "CancelSynchronization"},
  1090. {0x1A, SvcWrap<ArbitrateLock>, "ArbitrateLock"},
  1091. {0x1B, SvcWrap<ArbitrateUnlock>, "ArbitrateUnlock"},
  1092. {0x1C, SvcWrap<WaitProcessWideKeyAtomic>, "WaitProcessWideKeyAtomic"},
  1093. {0x1D, SvcWrap<SignalProcessWideKey>, "SignalProcessWideKey"},
  1094. {0x1E, SvcWrap<GetSystemTick>, "GetSystemTick"},
  1095. {0x1F, SvcWrap<ConnectToNamedPort>, "ConnectToNamedPort"},
  1096. {0x20, nullptr, "SendSyncRequestLight"},
  1097. {0x21, SvcWrap<SendSyncRequest>, "SendSyncRequest"},
  1098. {0x22, nullptr, "SendSyncRequestWithUserBuffer"},
  1099. {0x23, nullptr, "SendAsyncRequestWithUserBuffer"},
  1100. {0x24, SvcWrap<GetProcessId>, "GetProcessId"},
  1101. {0x25, SvcWrap<GetThreadId>, "GetThreadId"},
  1102. {0x26, SvcWrap<Break>, "Break"},
  1103. {0x27, SvcWrap<OutputDebugString>, "OutputDebugString"},
  1104. {0x28, nullptr, "ReturnFromException"},
  1105. {0x29, SvcWrap<GetInfo>, "GetInfo"},
  1106. {0x2A, nullptr, "FlushEntireDataCache"},
  1107. {0x2B, nullptr, "FlushDataCache"},
  1108. {0x2C, nullptr, "MapPhysicalMemory"},
  1109. {0x2D, nullptr, "UnmapPhysicalMemory"},
  1110. {0x2E, nullptr, "GetFutureThreadInfo"},
  1111. {0x2F, nullptr, "GetLastThreadInfo"},
  1112. {0x30, nullptr, "GetResourceLimitLimitValue"},
  1113. {0x31, nullptr, "GetResourceLimitCurrentValue"},
  1114. {0x32, SvcWrap<SetThreadActivity>, "SetThreadActivity"},
  1115. {0x33, SvcWrap<GetThreadContext>, "GetThreadContext"},
  1116. {0x34, SvcWrap<WaitForAddress>, "WaitForAddress"},
  1117. {0x35, SvcWrap<SignalToAddress>, "SignalToAddress"},
  1118. {0x36, nullptr, "Unknown"},
  1119. {0x37, nullptr, "Unknown"},
  1120. {0x38, nullptr, "Unknown"},
  1121. {0x39, nullptr, "Unknown"},
  1122. {0x3A, nullptr, "Unknown"},
  1123. {0x3B, nullptr, "Unknown"},
  1124. {0x3C, nullptr, "DumpInfo"},
  1125. {0x3D, nullptr, "DumpInfoNew"},
  1126. {0x3E, nullptr, "Unknown"},
  1127. {0x3F, nullptr, "Unknown"},
  1128. {0x40, nullptr, "CreateSession"},
  1129. {0x41, nullptr, "AcceptSession"},
  1130. {0x42, nullptr, "ReplyAndReceiveLight"},
  1131. {0x43, nullptr, "ReplyAndReceive"},
  1132. {0x44, nullptr, "ReplyAndReceiveWithUserBuffer"},
  1133. {0x45, nullptr, "CreateEvent"},
  1134. {0x46, nullptr, "Unknown"},
  1135. {0x47, nullptr, "Unknown"},
  1136. {0x48, nullptr, "MapPhysicalMemoryUnsafe"},
  1137. {0x49, nullptr, "UnmapPhysicalMemoryUnsafe"},
  1138. {0x4A, nullptr, "SetUnsafeLimit"},
  1139. {0x4B, nullptr, "CreateCodeMemory"},
  1140. {0x4C, nullptr, "ControlCodeMemory"},
  1141. {0x4D, nullptr, "SleepSystem"},
  1142. {0x4E, nullptr, "ReadWriteRegister"},
  1143. {0x4F, nullptr, "SetProcessActivity"},
  1144. {0x50, SvcWrap<CreateSharedMemory>, "CreateSharedMemory"},
  1145. {0x51, nullptr, "MapTransferMemory"},
  1146. {0x52, nullptr, "UnmapTransferMemory"},
  1147. {0x53, nullptr, "CreateInterruptEvent"},
  1148. {0x54, nullptr, "QueryPhysicalAddress"},
  1149. {0x55, nullptr, "QueryIoMapping"},
  1150. {0x56, nullptr, "CreateDeviceAddressSpace"},
  1151. {0x57, nullptr, "AttachDeviceAddressSpace"},
  1152. {0x58, nullptr, "DetachDeviceAddressSpace"},
  1153. {0x59, nullptr, "MapDeviceAddressSpaceByForce"},
  1154. {0x5A, nullptr, "MapDeviceAddressSpaceAligned"},
  1155. {0x5B, nullptr, "MapDeviceAddressSpace"},
  1156. {0x5C, nullptr, "UnmapDeviceAddressSpace"},
  1157. {0x5D, nullptr, "InvalidateProcessDataCache"},
  1158. {0x5E, nullptr, "StoreProcessDataCache"},
  1159. {0x5F, nullptr, "FlushProcessDataCache"},
  1160. {0x60, nullptr, "DebugActiveProcess"},
  1161. {0x61, nullptr, "BreakDebugProcess"},
  1162. {0x62, nullptr, "TerminateDebugProcess"},
  1163. {0x63, nullptr, "GetDebugEvent"},
  1164. {0x64, nullptr, "ContinueDebugEvent"},
  1165. {0x65, nullptr, "GetProcessList"},
  1166. {0x66, nullptr, "GetThreadList"},
  1167. {0x67, nullptr, "GetDebugThreadContext"},
  1168. {0x68, nullptr, "SetDebugThreadContext"},
  1169. {0x69, nullptr, "QueryDebugProcessMemory"},
  1170. {0x6A, nullptr, "ReadDebugProcessMemory"},
  1171. {0x6B, nullptr, "WriteDebugProcessMemory"},
  1172. {0x6C, nullptr, "SetHardwareBreakPoint"},
  1173. {0x6D, nullptr, "GetDebugThreadParam"},
  1174. {0x6E, nullptr, "Unknown"},
  1175. {0x6F, nullptr, "GetSystemInfo"},
  1176. {0x70, nullptr, "CreatePort"},
  1177. {0x71, nullptr, "ManageNamedPort"},
  1178. {0x72, nullptr, "ConnectToPort"},
  1179. {0x73, nullptr, "SetProcessMemoryPermission"},
  1180. {0x74, nullptr, "MapProcessMemory"},
  1181. {0x75, nullptr, "UnmapProcessMemory"},
  1182. {0x76, nullptr, "QueryProcessMemory"},
  1183. {0x77, nullptr, "MapProcessCodeMemory"},
  1184. {0x78, nullptr, "UnmapProcessCodeMemory"},
  1185. {0x79, nullptr, "CreateProcess"},
  1186. {0x7A, nullptr, "StartProcess"},
  1187. {0x7B, nullptr, "TerminateProcess"},
  1188. {0x7C, SvcWrap<GetProcessInfo>, "GetProcessInfo"},
  1189. {0x7D, nullptr, "CreateResourceLimit"},
  1190. {0x7E, nullptr, "SetResourceLimitLimitValue"},
  1191. {0x7F, nullptr, "CallSecureMonitor"},
  1192. };
  1193. static const FunctionDef* GetSVCInfo(u32 func_num) {
  1194. if (func_num >= std::size(SVC_Table)) {
  1195. LOG_ERROR(Kernel_SVC, "Unknown svc=0x{:02X}", func_num);
  1196. return nullptr;
  1197. }
  1198. return &SVC_Table[func_num];
  1199. }
  1200. MICROPROFILE_DEFINE(Kernel_SVC, "Kernel", "SVC", MP_RGB(70, 200, 70));
  1201. void CallSVC(u32 immediate) {
  1202. MICROPROFILE_SCOPE(Kernel_SVC);
  1203. // Lock the global kernel mutex when we enter the kernel HLE.
  1204. std::lock_guard<std::recursive_mutex> lock(HLE::g_hle_lock);
  1205. const FunctionDef* info = GetSVCInfo(immediate);
  1206. if (info) {
  1207. if (info->func) {
  1208. info->func();
  1209. } else {
  1210. LOG_CRITICAL(Kernel_SVC, "Unimplemented SVC function {}(..)", info->name);
  1211. }
  1212. } else {
  1213. LOG_CRITICAL(Kernel_SVC, "Unknown SVC function 0x{:X}", immediate);
  1214. }
  1215. }
  1216. } // namespace Kernel