svc.cpp 55 KB

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