svc.cpp 69 KB

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