svc.cpp 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479
  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_manager.h"
  17. #include "core/core_timing.h"
  18. #include "core/core_timing_util.h"
  19. #include "core/hle/kernel/address_arbiter.h"
  20. #include "core/hle/kernel/client_port.h"
  21. #include "core/hle/kernel/client_session.h"
  22. #include "core/hle/kernel/errors.h"
  23. #include "core/hle/kernel/handle_table.h"
  24. #include "core/hle/kernel/kernel.h"
  25. #include "core/hle/kernel/mutex.h"
  26. #include "core/hle/kernel/process.h"
  27. #include "core/hle/kernel/readable_event.h"
  28. #include "core/hle/kernel/resource_limit.h"
  29. #include "core/hle/kernel/scheduler.h"
  30. #include "core/hle/kernel/shared_memory.h"
  31. #include "core/hle/kernel/svc.h"
  32. #include "core/hle/kernel/svc_wrap.h"
  33. #include "core/hle/kernel/synchronization.h"
  34. #include "core/hle/kernel/thread.h"
  35. #include "core/hle/kernel/transfer_memory.h"
  36. #include "core/hle/kernel/writable_event.h"
  37. #include "core/hle/lock.h"
  38. #include "core/hle/result.h"
  39. #include "core/hle/service/service.h"
  40. #include "core/memory.h"
  41. #include "core/reporter.h"
  42. namespace Kernel {
  43. namespace {
  44. // Checks if address + size is greater than the given address
  45. // This can return false if the size causes an overflow of a 64-bit type
  46. // or if the given size is zero.
  47. constexpr bool IsValidAddressRange(VAddr address, u64 size) {
  48. return address + size > address;
  49. }
  50. // 8 GiB
  51. constexpr u64 MAIN_MEMORY_SIZE = 0x200000000;
  52. // Helper function that performs the common sanity checks for svcMapMemory
  53. // and svcUnmapMemory. This is doable, as both functions perform their sanitizing
  54. // in the same order.
  55. ResultCode MapUnmapMemorySanityChecks(const VMManager& vm_manager, VAddr dst_addr, VAddr src_addr,
  56. u64 size) {
  57. if (!Common::Is4KBAligned(dst_addr)) {
  58. LOG_ERROR(Kernel_SVC, "Destination address is not aligned to 4KB, 0x{:016X}", dst_addr);
  59. return ERR_INVALID_ADDRESS;
  60. }
  61. if (!Common::Is4KBAligned(src_addr)) {
  62. LOG_ERROR(Kernel_SVC, "Source address is not aligned to 4KB, 0x{:016X}", src_addr);
  63. return ERR_INVALID_SIZE;
  64. }
  65. if (size == 0) {
  66. LOG_ERROR(Kernel_SVC, "Size is 0");
  67. return ERR_INVALID_SIZE;
  68. }
  69. if (!Common::Is4KBAligned(size)) {
  70. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, 0x{:016X}", size);
  71. return ERR_INVALID_SIZE;
  72. }
  73. if (!IsValidAddressRange(dst_addr, size)) {
  74. LOG_ERROR(Kernel_SVC,
  75. "Destination is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
  76. dst_addr, size);
  77. return ERR_INVALID_ADDRESS_STATE;
  78. }
  79. if (!IsValidAddressRange(src_addr, size)) {
  80. LOG_ERROR(Kernel_SVC, "Source is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
  81. src_addr, size);
  82. return ERR_INVALID_ADDRESS_STATE;
  83. }
  84. if (!vm_manager.IsWithinAddressSpace(src_addr, size)) {
  85. LOG_ERROR(Kernel_SVC,
  86. "Source is not within the address space, addr=0x{:016X}, size=0x{:016X}",
  87. src_addr, size);
  88. return ERR_INVALID_ADDRESS_STATE;
  89. }
  90. if (!vm_manager.IsWithinStackRegion(dst_addr, size)) {
  91. LOG_ERROR(Kernel_SVC,
  92. "Destination is not within the stack region, addr=0x{:016X}, size=0x{:016X}",
  93. dst_addr, size);
  94. return ERR_INVALID_MEMORY_RANGE;
  95. }
  96. const VAddr dst_end_address = dst_addr + size;
  97. if (dst_end_address > vm_manager.GetHeapRegionBaseAddress() &&
  98. vm_manager.GetHeapRegionEndAddress() > dst_addr) {
  99. LOG_ERROR(Kernel_SVC,
  100. "Destination does not fit within the heap region, addr=0x{:016X}, "
  101. "size=0x{:016X}, end_addr=0x{:016X}",
  102. dst_addr, size, dst_end_address);
  103. return ERR_INVALID_MEMORY_RANGE;
  104. }
  105. if (dst_end_address > vm_manager.GetMapRegionBaseAddress() &&
  106. vm_manager.GetMapRegionEndAddress() > dst_addr) {
  107. LOG_ERROR(Kernel_SVC,
  108. "Destination does not fit within the map 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. return RESULT_SUCCESS;
  114. }
  115. enum class ResourceLimitValueType {
  116. CurrentValue,
  117. LimitValue,
  118. };
  119. ResultVal<s64> RetrieveResourceLimitValue(Core::System& system, Handle resource_limit,
  120. u32 resource_type, ResourceLimitValueType value_type) {
  121. const auto type = static_cast<ResourceType>(resource_type);
  122. if (!IsValidResourceType(type)) {
  123. LOG_ERROR(Kernel_SVC, "Invalid resource limit type: '{}'", resource_type);
  124. return ERR_INVALID_ENUM_VALUE;
  125. }
  126. const auto* const current_process = system.Kernel().CurrentProcess();
  127. ASSERT(current_process != nullptr);
  128. const auto resource_limit_object =
  129. current_process->GetHandleTable().Get<ResourceLimit>(resource_limit);
  130. if (!resource_limit_object) {
  131. LOG_ERROR(Kernel_SVC, "Handle to non-existent resource limit instance used. Handle={:08X}",
  132. resource_limit);
  133. return ERR_INVALID_HANDLE;
  134. }
  135. if (value_type == ResourceLimitValueType::CurrentValue) {
  136. return MakeResult(resource_limit_object->GetCurrentResourceValue(type));
  137. }
  138. return MakeResult(resource_limit_object->GetMaxResourceValue(type));
  139. }
  140. } // Anonymous namespace
  141. /// Set the process heap to a given Size. It can both extend and shrink the heap.
  142. static ResultCode SetHeapSize(Core::System& system, VAddr* heap_addr, u64 heap_size) {
  143. LOG_TRACE(Kernel_SVC, "called, heap_size=0x{:X}", heap_size);
  144. // Size must be a multiple of 0x200000 (2MB) and be equal to or less than 8GB.
  145. if ((heap_size % 0x200000) != 0) {
  146. LOG_ERROR(Kernel_SVC, "The heap size is not a multiple of 2MB, heap_size=0x{:016X}",
  147. heap_size);
  148. return ERR_INVALID_SIZE;
  149. }
  150. if (heap_size >= 0x200000000) {
  151. LOG_ERROR(Kernel_SVC, "The heap size is not less than 8GB, heap_size=0x{:016X}", heap_size);
  152. return ERR_INVALID_SIZE;
  153. }
  154. auto& vm_manager = system.Kernel().CurrentProcess()->VMManager();
  155. const auto alloc_result = vm_manager.SetHeapSize(heap_size);
  156. if (alloc_result.Failed()) {
  157. return alloc_result.Code();
  158. }
  159. *heap_addr = *alloc_result;
  160. return RESULT_SUCCESS;
  161. }
  162. static ResultCode SetMemoryPermission(Core::System& system, VAddr addr, u64 size, u32 prot) {
  163. LOG_TRACE(Kernel_SVC, "called, addr=0x{:X}, size=0x{:X}, prot=0x{:X}", addr, size, prot);
  164. if (!Common::Is4KBAligned(addr)) {
  165. LOG_ERROR(Kernel_SVC, "Address is not aligned to 4KB, addr=0x{:016X}", addr);
  166. return ERR_INVALID_ADDRESS;
  167. }
  168. if (size == 0) {
  169. LOG_ERROR(Kernel_SVC, "Size is 0");
  170. return ERR_INVALID_SIZE;
  171. }
  172. if (!Common::Is4KBAligned(size)) {
  173. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, size=0x{:016X}", size);
  174. return ERR_INVALID_SIZE;
  175. }
  176. if (!IsValidAddressRange(addr, size)) {
  177. LOG_ERROR(Kernel_SVC, "Region is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
  178. addr, size);
  179. return ERR_INVALID_ADDRESS_STATE;
  180. }
  181. const auto permission = static_cast<MemoryPermission>(prot);
  182. if (permission != MemoryPermission::None && permission != MemoryPermission::Read &&
  183. permission != MemoryPermission::ReadWrite) {
  184. LOG_ERROR(Kernel_SVC, "Invalid memory permission specified, Got memory permission=0x{:08X}",
  185. static_cast<u32>(permission));
  186. return ERR_INVALID_MEMORY_PERMISSIONS;
  187. }
  188. auto* const current_process = system.Kernel().CurrentProcess();
  189. auto& vm_manager = current_process->VMManager();
  190. if (!vm_manager.IsWithinAddressSpace(addr, size)) {
  191. LOG_ERROR(Kernel_SVC,
  192. "Source is not within the address space, addr=0x{:016X}, size=0x{:016X}", addr,
  193. size);
  194. return ERR_INVALID_ADDRESS_STATE;
  195. }
  196. const VMManager::VMAHandle iter = vm_manager.FindVMA(addr);
  197. if (!vm_manager.IsValidHandle(iter)) {
  198. LOG_ERROR(Kernel_SVC, "Unable to find VMA for address=0x{:016X}", addr);
  199. return ERR_INVALID_ADDRESS_STATE;
  200. }
  201. LOG_WARNING(Kernel_SVC, "Uniformity check on protected memory is not implemented.");
  202. // TODO: Performs a uniformity check to make sure only protected memory is changed (it doesn't
  203. // make sense to allow changing permissions on kernel memory itself, etc).
  204. const auto converted_permissions = SharedMemory::ConvertPermissions(permission);
  205. return vm_manager.ReprotectRange(addr, size, converted_permissions);
  206. }
  207. static ResultCode SetMemoryAttribute(Core::System& system, VAddr address, u64 size, u32 mask,
  208. u32 attribute) {
  209. LOG_DEBUG(Kernel_SVC,
  210. "called, address=0x{:016X}, size=0x{:X}, mask=0x{:08X}, attribute=0x{:08X}", address,
  211. size, mask, attribute);
  212. if (!Common::Is4KBAligned(address)) {
  213. LOG_ERROR(Kernel_SVC, "Address not page aligned (0x{:016X})", address);
  214. return ERR_INVALID_ADDRESS;
  215. }
  216. if (size == 0 || !Common::Is4KBAligned(size)) {
  217. LOG_ERROR(Kernel_SVC, "Invalid size (0x{:X}). Size must be non-zero and page aligned.",
  218. size);
  219. return ERR_INVALID_ADDRESS;
  220. }
  221. if (!IsValidAddressRange(address, size)) {
  222. LOG_ERROR(Kernel_SVC, "Address range overflowed (Address: 0x{:016X}, Size: 0x{:016X})",
  223. address, size);
  224. return ERR_INVALID_ADDRESS_STATE;
  225. }
  226. const auto mem_attribute = static_cast<MemoryAttribute>(attribute);
  227. const auto mem_mask = static_cast<MemoryAttribute>(mask);
  228. const auto attribute_with_mask = mem_attribute | mem_mask;
  229. if (attribute_with_mask != mem_mask) {
  230. LOG_ERROR(Kernel_SVC,
  231. "Memory attribute doesn't match the given mask (Attribute: 0x{:X}, Mask: {:X}",
  232. attribute, mask);
  233. return ERR_INVALID_COMBINATION;
  234. }
  235. if ((attribute_with_mask | MemoryAttribute::Uncached) != MemoryAttribute::Uncached) {
  236. LOG_ERROR(Kernel_SVC, "Specified attribute isn't equal to MemoryAttributeUncached (8).");
  237. return ERR_INVALID_COMBINATION;
  238. }
  239. auto& vm_manager = system.Kernel().CurrentProcess()->VMManager();
  240. if (!vm_manager.IsWithinAddressSpace(address, size)) {
  241. LOG_ERROR(Kernel_SVC,
  242. "Given address (0x{:016X}) is outside the bounds of the address space.", address);
  243. return ERR_INVALID_ADDRESS_STATE;
  244. }
  245. return vm_manager.SetMemoryAttribute(address, size, mem_mask, mem_attribute);
  246. }
  247. /// Maps a memory range into a different range.
  248. static ResultCode MapMemory(Core::System& system, VAddr dst_addr, VAddr src_addr, u64 size) {
  249. LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr,
  250. src_addr, size);
  251. auto& vm_manager = system.Kernel().CurrentProcess()->VMManager();
  252. const auto result = MapUnmapMemorySanityChecks(vm_manager, dst_addr, src_addr, size);
  253. if (result.IsError()) {
  254. return result;
  255. }
  256. return vm_manager.MirrorMemory(dst_addr, src_addr, size, MemoryState::Stack);
  257. }
  258. /// Unmaps a region that was previously mapped with svcMapMemory
  259. static ResultCode UnmapMemory(Core::System& system, VAddr dst_addr, VAddr src_addr, u64 size) {
  260. LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr,
  261. src_addr, size);
  262. auto& vm_manager = system.Kernel().CurrentProcess()->VMManager();
  263. const auto result = MapUnmapMemorySanityChecks(vm_manager, dst_addr, src_addr, size);
  264. if (result.IsError()) {
  265. return result;
  266. }
  267. const auto unmap_res = vm_manager.UnmapRange(dst_addr, size);
  268. // Reprotect the source mapping on success
  269. if (unmap_res.IsSuccess()) {
  270. ASSERT(vm_manager.ReprotectRange(src_addr, size, VMAPermission::ReadWrite).IsSuccess());
  271. }
  272. return unmap_res;
  273. }
  274. /// Connect to an OS service given the port name, returns the handle to the port to out
  275. static ResultCode ConnectToNamedPort(Core::System& system, Handle* out_handle,
  276. VAddr port_name_address) {
  277. auto& memory = system.Memory();
  278. if (!memory.IsValidVirtualAddress(port_name_address)) {
  279. LOG_ERROR(Kernel_SVC,
  280. "Port Name Address is not a valid virtual address, port_name_address=0x{:016X}",
  281. port_name_address);
  282. return ERR_NOT_FOUND;
  283. }
  284. static constexpr std::size_t PortNameMaxLength = 11;
  285. // Read 1 char beyond the max allowed port name to detect names that are too long.
  286. const std::string port_name = memory.ReadCString(port_name_address, PortNameMaxLength + 1);
  287. if (port_name.size() > PortNameMaxLength) {
  288. LOG_ERROR(Kernel_SVC, "Port name is too long, expected {} but got {}", PortNameMaxLength,
  289. port_name.size());
  290. return ERR_OUT_OF_RANGE;
  291. }
  292. LOG_TRACE(Kernel_SVC, "called port_name={}", port_name);
  293. auto& kernel = system.Kernel();
  294. const auto it = kernel.FindNamedPort(port_name);
  295. if (!kernel.IsValidNamedPort(it)) {
  296. LOG_WARNING(Kernel_SVC, "tried to connect to unknown port: {}", port_name);
  297. return ERR_NOT_FOUND;
  298. }
  299. auto client_port = it->second;
  300. std::shared_ptr<ClientSession> client_session;
  301. CASCADE_RESULT(client_session, client_port->Connect());
  302. // Return the client session
  303. auto& handle_table = kernel.CurrentProcess()->GetHandleTable();
  304. CASCADE_RESULT(*out_handle, handle_table.Create(client_session));
  305. return RESULT_SUCCESS;
  306. }
  307. /// Makes a blocking IPC call to an OS service.
  308. static ResultCode SendSyncRequest(Core::System& system, Handle handle) {
  309. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  310. std::shared_ptr<ClientSession> session = handle_table.Get<ClientSession>(handle);
  311. if (!session) {
  312. LOG_ERROR(Kernel_SVC, "called with invalid handle=0x{:08X}", handle);
  313. return ERR_INVALID_HANDLE;
  314. }
  315. LOG_TRACE(Kernel_SVC, "called handle=0x{:08X}({})", handle, session->GetName());
  316. auto thread = system.CurrentScheduler().GetCurrentThread();
  317. thread->InvalidateWakeupCallback();
  318. thread->SetStatus(ThreadStatus::WaitIPC);
  319. system.PrepareReschedule(thread->GetProcessorID());
  320. return session->SendSyncRequest(SharedFrom(thread), system.Memory());
  321. }
  322. /// Get the ID for the specified thread.
  323. static ResultCode GetThreadId(Core::System& system, u64* thread_id, Handle thread_handle) {
  324. LOG_TRACE(Kernel_SVC, "called thread=0x{:08X}", thread_handle);
  325. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  326. const std::shared_ptr<Thread> thread = handle_table.Get<Thread>(thread_handle);
  327. if (!thread) {
  328. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}", thread_handle);
  329. return ERR_INVALID_HANDLE;
  330. }
  331. *thread_id = thread->GetThreadID();
  332. return RESULT_SUCCESS;
  333. }
  334. /// Gets the ID of the specified process or a specified thread's owning process.
  335. static ResultCode GetProcessId(Core::System& system, u64* process_id, Handle handle) {
  336. LOG_DEBUG(Kernel_SVC, "called handle=0x{:08X}", handle);
  337. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  338. const std::shared_ptr<Process> process = handle_table.Get<Process>(handle);
  339. if (process) {
  340. *process_id = process->GetProcessID();
  341. return RESULT_SUCCESS;
  342. }
  343. const std::shared_ptr<Thread> thread = handle_table.Get<Thread>(handle);
  344. if (thread) {
  345. const Process* const owner_process = thread->GetOwnerProcess();
  346. if (!owner_process) {
  347. LOG_ERROR(Kernel_SVC, "Non-existent owning process encountered.");
  348. return ERR_INVALID_HANDLE;
  349. }
  350. *process_id = owner_process->GetProcessID();
  351. return RESULT_SUCCESS;
  352. }
  353. // NOTE: This should also handle debug objects before returning.
  354. LOG_ERROR(Kernel_SVC, "Handle does not exist, handle=0x{:08X}", handle);
  355. return ERR_INVALID_HANDLE;
  356. }
  357. /// Wait for the given handles to synchronize, timeout after the specified nanoseconds
  358. static ResultCode WaitSynchronization(Core::System& system, Handle* index, VAddr handles_address,
  359. u64 handle_count, s64 nano_seconds) {
  360. LOG_TRACE(Kernel_SVC, "called handles_address=0x{:X}, handle_count={}, nano_seconds={}",
  361. handles_address, handle_count, nano_seconds);
  362. auto& memory = system.Memory();
  363. if (!memory.IsValidVirtualAddress(handles_address)) {
  364. LOG_ERROR(Kernel_SVC,
  365. "Handle address is not a valid virtual address, handle_address=0x{:016X}",
  366. handles_address);
  367. return ERR_INVALID_POINTER;
  368. }
  369. static constexpr u64 MaxHandles = 0x40;
  370. if (handle_count > MaxHandles) {
  371. LOG_ERROR(Kernel_SVC, "Handle count specified is too large, expected {} but got {}",
  372. MaxHandles, handle_count);
  373. return ERR_OUT_OF_RANGE;
  374. }
  375. auto* const thread = system.CurrentScheduler().GetCurrentThread();
  376. auto& kernel = system.Kernel();
  377. using ObjectPtr = Thread::ThreadSynchronizationObjects::value_type;
  378. Thread::ThreadSynchronizationObjects objects(handle_count);
  379. const auto& handle_table = kernel.CurrentProcess()->GetHandleTable();
  380. for (u64 i = 0; i < handle_count; ++i) {
  381. const Handle handle = memory.Read32(handles_address + i * sizeof(Handle));
  382. const auto object = handle_table.Get<SynchronizationObject>(handle);
  383. if (object == nullptr) {
  384. LOG_ERROR(Kernel_SVC, "Object is a nullptr");
  385. return ERR_INVALID_HANDLE;
  386. }
  387. objects[i] = object;
  388. }
  389. auto& synchronization = kernel.Synchronization();
  390. const auto [result, handle_result] = synchronization.WaitFor(objects, nano_seconds);
  391. *index = handle_result;
  392. return result;
  393. }
  394. /// Resumes a thread waiting on WaitSynchronization
  395. static ResultCode CancelSynchronization(Core::System& system, Handle thread_handle) {
  396. LOG_TRACE(Kernel_SVC, "called thread=0x{:X}", thread_handle);
  397. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  398. std::shared_ptr<Thread> thread = handle_table.Get<Thread>(thread_handle);
  399. if (!thread) {
  400. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, thread_handle=0x{:08X}",
  401. thread_handle);
  402. return ERR_INVALID_HANDLE;
  403. }
  404. thread->CancelWait();
  405. system.PrepareReschedule(thread->GetProcessorID());
  406. return RESULT_SUCCESS;
  407. }
  408. /// Attempts to locks a mutex, creating it if it does not already exist
  409. static ResultCode ArbitrateLock(Core::System& system, Handle holding_thread_handle,
  410. VAddr mutex_addr, Handle requesting_thread_handle) {
  411. LOG_TRACE(Kernel_SVC,
  412. "called holding_thread_handle=0x{:08X}, mutex_addr=0x{:X}, "
  413. "requesting_current_thread_handle=0x{:08X}",
  414. holding_thread_handle, mutex_addr, requesting_thread_handle);
  415. if (Memory::IsKernelVirtualAddress(mutex_addr)) {
  416. LOG_ERROR(Kernel_SVC, "Mutex Address is a kernel virtual address, mutex_addr={:016X}",
  417. mutex_addr);
  418. return ERR_INVALID_ADDRESS_STATE;
  419. }
  420. if (!Common::IsWordAligned(mutex_addr)) {
  421. LOG_ERROR(Kernel_SVC, "Mutex Address is not word aligned, mutex_addr={:016X}", mutex_addr);
  422. return ERR_INVALID_ADDRESS;
  423. }
  424. auto* const current_process = system.Kernel().CurrentProcess();
  425. return current_process->GetMutex().TryAcquire(mutex_addr, holding_thread_handle,
  426. requesting_thread_handle);
  427. }
  428. /// Unlock a mutex
  429. static ResultCode ArbitrateUnlock(Core::System& system, VAddr mutex_addr) {
  430. LOG_TRACE(Kernel_SVC, "called mutex_addr=0x{:X}", mutex_addr);
  431. if (Memory::IsKernelVirtualAddress(mutex_addr)) {
  432. LOG_ERROR(Kernel_SVC, "Mutex Address is a kernel virtual address, mutex_addr={:016X}",
  433. mutex_addr);
  434. return ERR_INVALID_ADDRESS_STATE;
  435. }
  436. if (!Common::IsWordAligned(mutex_addr)) {
  437. LOG_ERROR(Kernel_SVC, "Mutex Address is not word aligned, mutex_addr={:016X}", mutex_addr);
  438. return ERR_INVALID_ADDRESS;
  439. }
  440. auto* const current_process = system.Kernel().CurrentProcess();
  441. return current_process->GetMutex().Release(mutex_addr);
  442. }
  443. enum class BreakType : u32 {
  444. Panic = 0,
  445. AssertionFailed = 1,
  446. PreNROLoad = 3,
  447. PostNROLoad = 4,
  448. PreNROUnload = 5,
  449. PostNROUnload = 6,
  450. CppException = 7,
  451. };
  452. struct BreakReason {
  453. union {
  454. u32 raw;
  455. BitField<0, 30, BreakType> break_type;
  456. BitField<31, 1, u32> signal_debugger;
  457. };
  458. };
  459. /// Break program execution
  460. static void Break(Core::System& system, u32 reason, u64 info1, u64 info2) {
  461. BreakReason break_reason{reason};
  462. bool has_dumped_buffer{};
  463. std::vector<u8> debug_buffer;
  464. const auto handle_debug_buffer = [&](VAddr addr, u64 sz) {
  465. if (sz == 0 || addr == 0 || has_dumped_buffer) {
  466. return;
  467. }
  468. auto& memory = system.Memory();
  469. // This typically is an error code so we're going to assume this is the case
  470. if (sz == sizeof(u32)) {
  471. LOG_CRITICAL(Debug_Emulated, "debug_buffer_err_code={:X}", memory.Read32(addr));
  472. } else {
  473. // We don't know what's in here so we'll hexdump it
  474. debug_buffer.resize(sz);
  475. memory.ReadBlock(addr, debug_buffer.data(), sz);
  476. std::string hexdump;
  477. for (std::size_t i = 0; i < debug_buffer.size(); i++) {
  478. hexdump += fmt::format("{:02X} ", debug_buffer[i]);
  479. if (i != 0 && i % 16 == 0) {
  480. hexdump += '\n';
  481. }
  482. }
  483. LOG_CRITICAL(Debug_Emulated, "debug_buffer=\n{}", hexdump);
  484. }
  485. has_dumped_buffer = true;
  486. };
  487. switch (break_reason.break_type) {
  488. case BreakType::Panic:
  489. LOG_CRITICAL(Debug_Emulated, "Signalling debugger, PANIC! info1=0x{:016X}, info2=0x{:016X}",
  490. info1, info2);
  491. handle_debug_buffer(info1, info2);
  492. break;
  493. case BreakType::AssertionFailed:
  494. LOG_CRITICAL(Debug_Emulated,
  495. "Signalling debugger, Assertion failed! info1=0x{:016X}, info2=0x{:016X}",
  496. info1, info2);
  497. handle_debug_buffer(info1, info2);
  498. break;
  499. case BreakType::PreNROLoad:
  500. LOG_WARNING(
  501. Debug_Emulated,
  502. "Signalling debugger, Attempting to load an NRO at 0x{:016X} with size 0x{:016X}",
  503. info1, info2);
  504. break;
  505. case BreakType::PostNROLoad:
  506. LOG_WARNING(Debug_Emulated,
  507. "Signalling debugger, Loaded an NRO at 0x{:016X} with size 0x{:016X}", info1,
  508. info2);
  509. break;
  510. case BreakType::PreNROUnload:
  511. LOG_WARNING(
  512. Debug_Emulated,
  513. "Signalling debugger, Attempting to unload an NRO at 0x{:016X} with size 0x{:016X}",
  514. info1, info2);
  515. break;
  516. case BreakType::PostNROUnload:
  517. LOG_WARNING(Debug_Emulated,
  518. "Signalling debugger, Unloaded an NRO at 0x{:016X} with size 0x{:016X}", info1,
  519. info2);
  520. break;
  521. case BreakType::CppException:
  522. LOG_CRITICAL(Debug_Emulated, "Signalling debugger. Uncaught C++ exception encountered.");
  523. break;
  524. default:
  525. LOG_WARNING(
  526. Debug_Emulated,
  527. "Signalling debugger, Unknown break reason {}, info1=0x{:016X}, info2=0x{:016X}",
  528. static_cast<u32>(break_reason.break_type.Value()), info1, info2);
  529. handle_debug_buffer(info1, info2);
  530. break;
  531. }
  532. system.GetReporter().SaveSvcBreakReport(
  533. static_cast<u32>(break_reason.break_type.Value()), break_reason.signal_debugger, info1,
  534. info2, has_dumped_buffer ? std::make_optional(debug_buffer) : std::nullopt);
  535. if (!break_reason.signal_debugger) {
  536. LOG_CRITICAL(
  537. Debug_Emulated,
  538. "Emulated program broke execution! reason=0x{:016X}, info1=0x{:016X}, info2=0x{:016X}",
  539. reason, info1, info2);
  540. handle_debug_buffer(info1, info2);
  541. auto* const current_thread = system.CurrentScheduler().GetCurrentThread();
  542. const auto thread_processor_id = current_thread->GetProcessorID();
  543. system.ArmInterface(static_cast<std::size_t>(thread_processor_id)).LogBacktrace();
  544. ASSERT(false);
  545. system.Kernel().CurrentProcess()->PrepareForTermination();
  546. // Kill the current thread
  547. current_thread->Stop();
  548. system.PrepareReschedule();
  549. }
  550. }
  551. /// Used to output a message on a debug hardware unit - does nothing on a retail unit
  552. static void OutputDebugString([[maybe_unused]] Core::System& system, VAddr address, u64 len) {
  553. if (len == 0) {
  554. return;
  555. }
  556. std::string str(len, '\0');
  557. system.Memory().ReadBlock(address, str.data(), str.size());
  558. LOG_DEBUG(Debug_Emulated, "{}", str);
  559. }
  560. /// Gets system/memory information for the current process
  561. static ResultCode GetInfo(Core::System& system, u64* result, u64 info_id, u64 handle,
  562. u64 info_sub_id) {
  563. LOG_TRACE(Kernel_SVC, "called info_id=0x{:X}, info_sub_id=0x{:X}, handle=0x{:08X}", info_id,
  564. info_sub_id, handle);
  565. enum class GetInfoType : u64 {
  566. // 1.0.0+
  567. AllowedCPUCoreMask = 0,
  568. AllowedThreadPriorityMask = 1,
  569. MapRegionBaseAddr = 2,
  570. MapRegionSize = 3,
  571. HeapRegionBaseAddr = 4,
  572. HeapRegionSize = 5,
  573. TotalPhysicalMemoryAvailable = 6,
  574. TotalPhysicalMemoryUsed = 7,
  575. IsCurrentProcessBeingDebugged = 8,
  576. RegisterResourceLimit = 9,
  577. IdleTickCount = 10,
  578. RandomEntropy = 11,
  579. ThreadTickCount = 0xF0000002,
  580. // 2.0.0+
  581. ASLRRegionBaseAddr = 12,
  582. ASLRRegionSize = 13,
  583. StackRegionBaseAddr = 14,
  584. StackRegionSize = 15,
  585. // 3.0.0+
  586. SystemResourceSize = 16,
  587. SystemResourceUsage = 17,
  588. TitleId = 18,
  589. // 4.0.0+
  590. PrivilegedProcessId = 19,
  591. // 5.0.0+
  592. UserExceptionContextAddr = 20,
  593. // 6.0.0+
  594. TotalPhysicalMemoryAvailableWithoutSystemResource = 21,
  595. TotalPhysicalMemoryUsedWithoutSystemResource = 22,
  596. };
  597. const auto info_id_type = static_cast<GetInfoType>(info_id);
  598. switch (info_id_type) {
  599. case GetInfoType::AllowedCPUCoreMask:
  600. case GetInfoType::AllowedThreadPriorityMask:
  601. case GetInfoType::MapRegionBaseAddr:
  602. case GetInfoType::MapRegionSize:
  603. case GetInfoType::HeapRegionBaseAddr:
  604. case GetInfoType::HeapRegionSize:
  605. case GetInfoType::ASLRRegionBaseAddr:
  606. case GetInfoType::ASLRRegionSize:
  607. case GetInfoType::StackRegionBaseAddr:
  608. case GetInfoType::StackRegionSize:
  609. case GetInfoType::TotalPhysicalMemoryAvailable:
  610. case GetInfoType::TotalPhysicalMemoryUsed:
  611. case GetInfoType::SystemResourceSize:
  612. case GetInfoType::SystemResourceUsage:
  613. case GetInfoType::TitleId:
  614. case GetInfoType::UserExceptionContextAddr:
  615. case GetInfoType::TotalPhysicalMemoryAvailableWithoutSystemResource:
  616. case GetInfoType::TotalPhysicalMemoryUsedWithoutSystemResource: {
  617. if (info_sub_id != 0) {
  618. return ERR_INVALID_ENUM_VALUE;
  619. }
  620. const auto& current_process_handle_table =
  621. system.Kernel().CurrentProcess()->GetHandleTable();
  622. const auto process = current_process_handle_table.Get<Process>(static_cast<Handle>(handle));
  623. if (!process) {
  624. return ERR_INVALID_HANDLE;
  625. }
  626. switch (info_id_type) {
  627. case GetInfoType::AllowedCPUCoreMask:
  628. *result = process->GetCoreMask();
  629. return RESULT_SUCCESS;
  630. case GetInfoType::AllowedThreadPriorityMask:
  631. *result = process->GetPriorityMask();
  632. return RESULT_SUCCESS;
  633. case GetInfoType::MapRegionBaseAddr:
  634. *result = process->VMManager().GetMapRegionBaseAddress();
  635. return RESULT_SUCCESS;
  636. case GetInfoType::MapRegionSize:
  637. *result = process->VMManager().GetMapRegionSize();
  638. return RESULT_SUCCESS;
  639. case GetInfoType::HeapRegionBaseAddr:
  640. *result = process->VMManager().GetHeapRegionBaseAddress();
  641. return RESULT_SUCCESS;
  642. case GetInfoType::HeapRegionSize:
  643. *result = process->VMManager().GetHeapRegionSize();
  644. return RESULT_SUCCESS;
  645. case GetInfoType::ASLRRegionBaseAddr:
  646. *result = process->VMManager().GetASLRRegionBaseAddress();
  647. return RESULT_SUCCESS;
  648. case GetInfoType::ASLRRegionSize:
  649. *result = process->VMManager().GetASLRRegionSize();
  650. return RESULT_SUCCESS;
  651. case GetInfoType::StackRegionBaseAddr:
  652. *result = process->VMManager().GetStackRegionBaseAddress();
  653. return RESULT_SUCCESS;
  654. case GetInfoType::StackRegionSize:
  655. *result = process->VMManager().GetStackRegionSize();
  656. return RESULT_SUCCESS;
  657. case GetInfoType::TotalPhysicalMemoryAvailable:
  658. *result = process->GetTotalPhysicalMemoryAvailable();
  659. return RESULT_SUCCESS;
  660. case GetInfoType::TotalPhysicalMemoryUsed:
  661. *result = process->GetTotalPhysicalMemoryUsed();
  662. return RESULT_SUCCESS;
  663. case GetInfoType::SystemResourceSize:
  664. *result = process->GetSystemResourceSize();
  665. return RESULT_SUCCESS;
  666. case GetInfoType::SystemResourceUsage:
  667. LOG_WARNING(Kernel_SVC, "(STUBBED) Attempted to query system resource usage");
  668. *result = process->GetSystemResourceUsage();
  669. return RESULT_SUCCESS;
  670. case GetInfoType::TitleId:
  671. *result = process->GetTitleID();
  672. return RESULT_SUCCESS;
  673. case GetInfoType::UserExceptionContextAddr:
  674. *result = process->GetTLSRegionAddress();
  675. return RESULT_SUCCESS;
  676. case GetInfoType::TotalPhysicalMemoryAvailableWithoutSystemResource:
  677. *result = process->GetTotalPhysicalMemoryAvailableWithoutSystemResource();
  678. return RESULT_SUCCESS;
  679. case GetInfoType::TotalPhysicalMemoryUsedWithoutSystemResource:
  680. *result = process->GetTotalPhysicalMemoryUsedWithoutSystemResource();
  681. return RESULT_SUCCESS;
  682. default:
  683. break;
  684. }
  685. LOG_WARNING(Kernel_SVC, "(STUBBED) Unimplemented svcGetInfo id=0x{:016X}", info_id);
  686. return ERR_INVALID_ENUM_VALUE;
  687. }
  688. case GetInfoType::IsCurrentProcessBeingDebugged:
  689. *result = 0;
  690. return RESULT_SUCCESS;
  691. case GetInfoType::RegisterResourceLimit: {
  692. if (handle != 0) {
  693. return ERR_INVALID_HANDLE;
  694. }
  695. if (info_sub_id != 0) {
  696. return ERR_INVALID_COMBINATION;
  697. }
  698. Process* const current_process = system.Kernel().CurrentProcess();
  699. HandleTable& handle_table = current_process->GetHandleTable();
  700. const auto resource_limit = current_process->GetResourceLimit();
  701. if (!resource_limit) {
  702. *result = KernelHandle::InvalidHandle;
  703. // Yes, the kernel considers this a successful operation.
  704. return RESULT_SUCCESS;
  705. }
  706. const auto table_result = handle_table.Create(resource_limit);
  707. if (table_result.Failed()) {
  708. return table_result.Code();
  709. }
  710. *result = *table_result;
  711. return RESULT_SUCCESS;
  712. }
  713. case GetInfoType::RandomEntropy:
  714. if (handle != 0) {
  715. LOG_ERROR(Kernel_SVC, "Process Handle is non zero, expected 0 result but got {:016X}",
  716. handle);
  717. return ERR_INVALID_HANDLE;
  718. }
  719. if (info_sub_id >= Process::RANDOM_ENTROPY_SIZE) {
  720. LOG_ERROR(Kernel_SVC, "Entropy size is out of range, expected {} but got {}",
  721. Process::RANDOM_ENTROPY_SIZE, info_sub_id);
  722. return ERR_INVALID_COMBINATION;
  723. }
  724. *result = system.Kernel().CurrentProcess()->GetRandomEntropy(info_sub_id);
  725. return RESULT_SUCCESS;
  726. case GetInfoType::PrivilegedProcessId:
  727. LOG_WARNING(Kernel_SVC,
  728. "(STUBBED) Attempted to query privileged process id bounds, returned 0");
  729. *result = 0;
  730. return RESULT_SUCCESS;
  731. case GetInfoType::ThreadTickCount: {
  732. constexpr u64 num_cpus = 4;
  733. if (info_sub_id != 0xFFFFFFFFFFFFFFFF && info_sub_id >= num_cpus) {
  734. LOG_ERROR(Kernel_SVC, "Core count is out of range, expected {} but got {}", num_cpus,
  735. info_sub_id);
  736. return ERR_INVALID_COMBINATION;
  737. }
  738. const auto thread = system.Kernel().CurrentProcess()->GetHandleTable().Get<Thread>(
  739. static_cast<Handle>(handle));
  740. if (!thread) {
  741. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}",
  742. static_cast<Handle>(handle));
  743. return ERR_INVALID_HANDLE;
  744. }
  745. const auto& core_timing = system.CoreTiming();
  746. const auto& scheduler = system.CurrentScheduler();
  747. const auto* const current_thread = scheduler.GetCurrentThread();
  748. const bool same_thread = current_thread == thread.get();
  749. const u64 prev_ctx_ticks = scheduler.GetLastContextSwitchTicks();
  750. u64 out_ticks = 0;
  751. if (same_thread && info_sub_id == 0xFFFFFFFFFFFFFFFF) {
  752. const u64 thread_ticks = current_thread->GetTotalCPUTimeTicks();
  753. out_ticks = thread_ticks + (core_timing.GetTicks() - prev_ctx_ticks);
  754. } else if (same_thread && info_sub_id == system.CurrentCoreIndex()) {
  755. out_ticks = core_timing.GetTicks() - prev_ctx_ticks;
  756. }
  757. *result = out_ticks;
  758. return RESULT_SUCCESS;
  759. }
  760. default:
  761. LOG_WARNING(Kernel_SVC, "(STUBBED) Unimplemented svcGetInfo id=0x{:016X}", info_id);
  762. return ERR_INVALID_ENUM_VALUE;
  763. }
  764. }
  765. /// Maps memory at a desired address
  766. static ResultCode MapPhysicalMemory(Core::System& system, VAddr addr, u64 size) {
  767. LOG_DEBUG(Kernel_SVC, "called, addr=0x{:016X}, size=0x{:X}", addr, size);
  768. if (!Common::Is4KBAligned(addr)) {
  769. LOG_ERROR(Kernel_SVC, "Address is not aligned to 4KB, 0x{:016X}", addr);
  770. return ERR_INVALID_ADDRESS;
  771. }
  772. if (!Common::Is4KBAligned(size)) {
  773. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, 0x{:X}", size);
  774. return ERR_INVALID_SIZE;
  775. }
  776. if (size == 0) {
  777. LOG_ERROR(Kernel_SVC, "Size is zero");
  778. return ERR_INVALID_SIZE;
  779. }
  780. if (!(addr < addr + size)) {
  781. LOG_ERROR(Kernel_SVC, "Size causes 64-bit overflow of address");
  782. return ERR_INVALID_MEMORY_RANGE;
  783. }
  784. Process* const current_process = system.Kernel().CurrentProcess();
  785. auto& vm_manager = current_process->VMManager();
  786. if (current_process->GetSystemResourceSize() == 0) {
  787. LOG_ERROR(Kernel_SVC, "System Resource Size is zero");
  788. return ERR_INVALID_STATE;
  789. }
  790. if (!vm_manager.IsWithinMapRegion(addr, size)) {
  791. LOG_ERROR(Kernel_SVC, "Range not within map region");
  792. return ERR_INVALID_MEMORY_RANGE;
  793. }
  794. return vm_manager.MapPhysicalMemory(addr, size);
  795. }
  796. /// Unmaps memory previously mapped via MapPhysicalMemory
  797. static ResultCode UnmapPhysicalMemory(Core::System& system, VAddr addr, u64 size) {
  798. LOG_DEBUG(Kernel_SVC, "called, addr=0x{:016X}, size=0x{:X}", addr, size);
  799. if (!Common::Is4KBAligned(addr)) {
  800. LOG_ERROR(Kernel_SVC, "Address is not aligned to 4KB, 0x{:016X}", addr);
  801. return ERR_INVALID_ADDRESS;
  802. }
  803. if (!Common::Is4KBAligned(size)) {
  804. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, 0x{:X}", size);
  805. return ERR_INVALID_SIZE;
  806. }
  807. if (size == 0) {
  808. LOG_ERROR(Kernel_SVC, "Size is zero");
  809. return ERR_INVALID_SIZE;
  810. }
  811. if (!(addr < addr + size)) {
  812. LOG_ERROR(Kernel_SVC, "Size causes 64-bit overflow of address");
  813. return ERR_INVALID_MEMORY_RANGE;
  814. }
  815. Process* const current_process = system.Kernel().CurrentProcess();
  816. auto& vm_manager = current_process->VMManager();
  817. if (current_process->GetSystemResourceSize() == 0) {
  818. LOG_ERROR(Kernel_SVC, "System Resource Size is zero");
  819. return ERR_INVALID_STATE;
  820. }
  821. if (!vm_manager.IsWithinMapRegion(addr, size)) {
  822. LOG_ERROR(Kernel_SVC, "Range not within map region");
  823. return ERR_INVALID_MEMORY_RANGE;
  824. }
  825. return vm_manager.UnmapPhysicalMemory(addr, size);
  826. }
  827. /// Sets the thread activity
  828. static ResultCode SetThreadActivity(Core::System& system, Handle handle, u32 activity) {
  829. LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, activity=0x{:08X}", handle, activity);
  830. if (activity > static_cast<u32>(ThreadActivity::Paused)) {
  831. return ERR_INVALID_ENUM_VALUE;
  832. }
  833. const auto* current_process = system.Kernel().CurrentProcess();
  834. const std::shared_ptr<Thread> thread = current_process->GetHandleTable().Get<Thread>(handle);
  835. if (!thread) {
  836. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}", handle);
  837. return ERR_INVALID_HANDLE;
  838. }
  839. if (thread->GetOwnerProcess() != current_process) {
  840. LOG_ERROR(Kernel_SVC,
  841. "The current process does not own the current thread, thread_handle={:08X} "
  842. "thread_pid={}, "
  843. "current_process_pid={}",
  844. handle, thread->GetOwnerProcess()->GetProcessID(),
  845. current_process->GetProcessID());
  846. return ERR_INVALID_HANDLE;
  847. }
  848. if (thread.get() == system.CurrentScheduler().GetCurrentThread()) {
  849. LOG_ERROR(Kernel_SVC, "The thread handle specified is the current running thread");
  850. return ERR_BUSY;
  851. }
  852. thread->SetActivity(static_cast<ThreadActivity>(activity));
  853. system.PrepareReschedule(thread->GetProcessorID());
  854. return RESULT_SUCCESS;
  855. }
  856. /// Gets the thread context
  857. static ResultCode GetThreadContext(Core::System& system, VAddr thread_context, Handle handle) {
  858. LOG_DEBUG(Kernel_SVC, "called, context=0x{:08X}, thread=0x{:X}", thread_context, handle);
  859. const auto* current_process = system.Kernel().CurrentProcess();
  860. const std::shared_ptr<Thread> thread = current_process->GetHandleTable().Get<Thread>(handle);
  861. if (!thread) {
  862. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}", handle);
  863. return ERR_INVALID_HANDLE;
  864. }
  865. if (thread->GetOwnerProcess() != current_process) {
  866. LOG_ERROR(Kernel_SVC,
  867. "The current process does not own the current thread, thread_handle={:08X} "
  868. "thread_pid={}, "
  869. "current_process_pid={}",
  870. handle, thread->GetOwnerProcess()->GetProcessID(),
  871. current_process->GetProcessID());
  872. return ERR_INVALID_HANDLE;
  873. }
  874. if (thread.get() == system.CurrentScheduler().GetCurrentThread()) {
  875. LOG_ERROR(Kernel_SVC, "The thread handle specified is the current running thread");
  876. return ERR_BUSY;
  877. }
  878. Core::ARM_Interface::ThreadContext ctx = thread->GetContext();
  879. // Mask away mode bits, interrupt bits, IL bit, and other reserved bits.
  880. ctx.pstate &= 0xFF0FFE20;
  881. // If 64-bit, we can just write the context registers directly and we're good.
  882. // However, if 32-bit, we have to ensure some registers are zeroed out.
  883. if (!current_process->Is64BitProcess()) {
  884. std::fill(ctx.cpu_registers.begin() + 15, ctx.cpu_registers.end(), 0);
  885. std::fill(ctx.vector_registers.begin() + 16, ctx.vector_registers.end(), u128{});
  886. }
  887. system.Memory().WriteBlock(thread_context, &ctx, sizeof(ctx));
  888. return RESULT_SUCCESS;
  889. }
  890. /// Gets the priority for the specified thread
  891. static ResultCode GetThreadPriority(Core::System& system, u32* priority, Handle handle) {
  892. LOG_TRACE(Kernel_SVC, "called");
  893. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  894. const std::shared_ptr<Thread> thread = handle_table.Get<Thread>(handle);
  895. if (!thread) {
  896. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}", handle);
  897. return ERR_INVALID_HANDLE;
  898. }
  899. *priority = thread->GetPriority();
  900. return RESULT_SUCCESS;
  901. }
  902. /// Sets the priority for the specified thread
  903. static ResultCode SetThreadPriority(Core::System& system, Handle handle, u32 priority) {
  904. LOG_TRACE(Kernel_SVC, "called");
  905. if (priority > THREADPRIO_LOWEST) {
  906. LOG_ERROR(
  907. Kernel_SVC,
  908. "An invalid priority was specified, expected {} but got {} for thread_handle={:08X}",
  909. THREADPRIO_LOWEST, priority, handle);
  910. return ERR_INVALID_THREAD_PRIORITY;
  911. }
  912. const auto* const current_process = system.Kernel().CurrentProcess();
  913. std::shared_ptr<Thread> thread = current_process->GetHandleTable().Get<Thread>(handle);
  914. if (!thread) {
  915. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}", handle);
  916. return ERR_INVALID_HANDLE;
  917. }
  918. thread->SetPriority(priority);
  919. system.PrepareReschedule(thread->GetProcessorID());
  920. return RESULT_SUCCESS;
  921. }
  922. /// Get which CPU core is executing the current thread
  923. static u32 GetCurrentProcessorNumber(Core::System& system) {
  924. LOG_TRACE(Kernel_SVC, "called");
  925. return system.CurrentScheduler().GetCurrentThread()->GetProcessorID();
  926. }
  927. static ResultCode MapSharedMemory(Core::System& system, Handle shared_memory_handle, VAddr addr,
  928. u64 size, u32 permissions) {
  929. LOG_TRACE(Kernel_SVC,
  930. "called, shared_memory_handle=0x{:X}, addr=0x{:X}, size=0x{:X}, permissions=0x{:08X}",
  931. shared_memory_handle, addr, size, permissions);
  932. if (!Common::Is4KBAligned(addr)) {
  933. LOG_ERROR(Kernel_SVC, "Address is not aligned to 4KB, addr=0x{:016X}", addr);
  934. return ERR_INVALID_ADDRESS;
  935. }
  936. if (size == 0) {
  937. LOG_ERROR(Kernel_SVC, "Size is 0");
  938. return ERR_INVALID_SIZE;
  939. }
  940. if (!Common::Is4KBAligned(size)) {
  941. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, size=0x{:016X}", size);
  942. return ERR_INVALID_SIZE;
  943. }
  944. if (!IsValidAddressRange(addr, size)) {
  945. LOG_ERROR(Kernel_SVC, "Region is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
  946. addr, size);
  947. return ERR_INVALID_ADDRESS_STATE;
  948. }
  949. const auto permissions_type = static_cast<MemoryPermission>(permissions);
  950. if (permissions_type != MemoryPermission::Read &&
  951. permissions_type != MemoryPermission::ReadWrite) {
  952. LOG_ERROR(Kernel_SVC, "Expected Read or ReadWrite permission but got permissions=0x{:08X}",
  953. permissions);
  954. return ERR_INVALID_MEMORY_PERMISSIONS;
  955. }
  956. auto* const current_process = system.Kernel().CurrentProcess();
  957. auto shared_memory = current_process->GetHandleTable().Get<SharedMemory>(shared_memory_handle);
  958. if (!shared_memory) {
  959. LOG_ERROR(Kernel_SVC, "Shared memory does not exist, shared_memory_handle=0x{:08X}",
  960. shared_memory_handle);
  961. return ERR_INVALID_HANDLE;
  962. }
  963. const auto& vm_manager = current_process->VMManager();
  964. if (!vm_manager.IsWithinASLRRegion(addr, size)) {
  965. LOG_ERROR(Kernel_SVC, "Region is not within the ASLR region. addr=0x{:016X}, size={:016X}",
  966. addr, size);
  967. return ERR_INVALID_MEMORY_RANGE;
  968. }
  969. return shared_memory->Map(*current_process, addr, permissions_type, MemoryPermission::DontCare);
  970. }
  971. static ResultCode UnmapSharedMemory(Core::System& system, Handle shared_memory_handle, VAddr addr,
  972. u64 size) {
  973. LOG_WARNING(Kernel_SVC, "called, shared_memory_handle=0x{:08X}, addr=0x{:X}, size=0x{:X}",
  974. shared_memory_handle, addr, size);
  975. if (!Common::Is4KBAligned(addr)) {
  976. LOG_ERROR(Kernel_SVC, "Address is not aligned to 4KB, addr=0x{:016X}", addr);
  977. return ERR_INVALID_ADDRESS;
  978. }
  979. if (size == 0) {
  980. LOG_ERROR(Kernel_SVC, "Size is 0");
  981. return ERR_INVALID_SIZE;
  982. }
  983. if (!Common::Is4KBAligned(size)) {
  984. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, size=0x{:016X}", size);
  985. return ERR_INVALID_SIZE;
  986. }
  987. if (!IsValidAddressRange(addr, size)) {
  988. LOG_ERROR(Kernel_SVC, "Region is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
  989. addr, size);
  990. return ERR_INVALID_ADDRESS_STATE;
  991. }
  992. auto* const current_process = system.Kernel().CurrentProcess();
  993. auto shared_memory = current_process->GetHandleTable().Get<SharedMemory>(shared_memory_handle);
  994. if (!shared_memory) {
  995. LOG_ERROR(Kernel_SVC, "Shared memory does not exist, shared_memory_handle=0x{:08X}",
  996. shared_memory_handle);
  997. return ERR_INVALID_HANDLE;
  998. }
  999. const auto& vm_manager = current_process->VMManager();
  1000. if (!vm_manager.IsWithinASLRRegion(addr, size)) {
  1001. LOG_ERROR(Kernel_SVC, "Region is not within the ASLR region. addr=0x{:016X}, size={:016X}",
  1002. addr, size);
  1003. return ERR_INVALID_MEMORY_RANGE;
  1004. }
  1005. return shared_memory->Unmap(*current_process, addr, size);
  1006. }
  1007. static ResultCode QueryProcessMemory(Core::System& system, VAddr memory_info_address,
  1008. VAddr page_info_address, Handle process_handle,
  1009. VAddr address) {
  1010. LOG_TRACE(Kernel_SVC, "called process=0x{:08X} address={:X}", process_handle, address);
  1011. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1012. std::shared_ptr<Process> process = handle_table.Get<Process>(process_handle);
  1013. if (!process) {
  1014. LOG_ERROR(Kernel_SVC, "Process handle does not exist, process_handle=0x{:08X}",
  1015. process_handle);
  1016. return ERR_INVALID_HANDLE;
  1017. }
  1018. auto& memory = system.Memory();
  1019. const auto& vm_manager = process->VMManager();
  1020. const MemoryInfo memory_info = vm_manager.QueryMemory(address);
  1021. memory.Write64(memory_info_address, memory_info.base_address);
  1022. memory.Write64(memory_info_address + 8, memory_info.size);
  1023. memory.Write32(memory_info_address + 16, memory_info.state);
  1024. memory.Write32(memory_info_address + 20, memory_info.attributes);
  1025. memory.Write32(memory_info_address + 24, memory_info.permission);
  1026. memory.Write32(memory_info_address + 32, memory_info.ipc_ref_count);
  1027. memory.Write32(memory_info_address + 28, memory_info.device_ref_count);
  1028. memory.Write32(memory_info_address + 36, 0);
  1029. // Page info appears to be currently unused by the kernel and is always set to zero.
  1030. memory.Write32(page_info_address, 0);
  1031. return RESULT_SUCCESS;
  1032. }
  1033. static ResultCode QueryMemory(Core::System& system, VAddr memory_info_address,
  1034. VAddr page_info_address, VAddr query_address) {
  1035. LOG_TRACE(Kernel_SVC,
  1036. "called, memory_info_address=0x{:016X}, page_info_address=0x{:016X}, "
  1037. "query_address=0x{:016X}",
  1038. memory_info_address, page_info_address, query_address);
  1039. return QueryProcessMemory(system, memory_info_address, page_info_address, CurrentProcess,
  1040. query_address);
  1041. }
  1042. static ResultCode MapProcessCodeMemory(Core::System& system, Handle process_handle, u64 dst_address,
  1043. u64 src_address, u64 size) {
  1044. LOG_DEBUG(Kernel_SVC,
  1045. "called. process_handle=0x{:08X}, dst_address=0x{:016X}, "
  1046. "src_address=0x{:016X}, size=0x{:016X}",
  1047. process_handle, dst_address, src_address, size);
  1048. if (!Common::Is4KBAligned(src_address)) {
  1049. LOG_ERROR(Kernel_SVC, "src_address is not page-aligned (src_address=0x{:016X}).",
  1050. src_address);
  1051. return ERR_INVALID_ADDRESS;
  1052. }
  1053. if (!Common::Is4KBAligned(dst_address)) {
  1054. LOG_ERROR(Kernel_SVC, "dst_address is not page-aligned (dst_address=0x{:016X}).",
  1055. dst_address);
  1056. return ERR_INVALID_ADDRESS;
  1057. }
  1058. if (size == 0 || !Common::Is4KBAligned(size)) {
  1059. LOG_ERROR(Kernel_SVC, "Size is zero or not page-aligned (size=0x{:016X})", size);
  1060. return ERR_INVALID_SIZE;
  1061. }
  1062. if (!IsValidAddressRange(dst_address, size)) {
  1063. LOG_ERROR(Kernel_SVC,
  1064. "Destination address range overflows the address space (dst_address=0x{:016X}, "
  1065. "size=0x{:016X}).",
  1066. dst_address, size);
  1067. return ERR_INVALID_ADDRESS_STATE;
  1068. }
  1069. if (!IsValidAddressRange(src_address, size)) {
  1070. LOG_ERROR(Kernel_SVC,
  1071. "Source address range overflows the address space (src_address=0x{:016X}, "
  1072. "size=0x{:016X}).",
  1073. src_address, size);
  1074. return ERR_INVALID_ADDRESS_STATE;
  1075. }
  1076. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1077. auto process = handle_table.Get<Process>(process_handle);
  1078. if (!process) {
  1079. LOG_ERROR(Kernel_SVC, "Invalid process handle specified (handle=0x{:08X}).",
  1080. process_handle);
  1081. return ERR_INVALID_HANDLE;
  1082. }
  1083. auto& vm_manager = process->VMManager();
  1084. if (!vm_manager.IsWithinAddressSpace(src_address, size)) {
  1085. LOG_ERROR(Kernel_SVC,
  1086. "Source address range is not within the address space (src_address=0x{:016X}, "
  1087. "size=0x{:016X}).",
  1088. src_address, size);
  1089. return ERR_INVALID_ADDRESS_STATE;
  1090. }
  1091. if (!vm_manager.IsWithinASLRRegion(dst_address, size)) {
  1092. LOG_ERROR(Kernel_SVC,
  1093. "Destination address range is not within the ASLR region (dst_address=0x{:016X}, "
  1094. "size=0x{:016X}).",
  1095. dst_address, size);
  1096. return ERR_INVALID_MEMORY_RANGE;
  1097. }
  1098. return vm_manager.MapCodeMemory(dst_address, src_address, size);
  1099. }
  1100. static ResultCode UnmapProcessCodeMemory(Core::System& system, Handle process_handle,
  1101. u64 dst_address, u64 src_address, u64 size) {
  1102. LOG_DEBUG(Kernel_SVC,
  1103. "called. process_handle=0x{:08X}, dst_address=0x{:016X}, src_address=0x{:016X}, "
  1104. "size=0x{:016X}",
  1105. process_handle, dst_address, src_address, size);
  1106. if (!Common::Is4KBAligned(dst_address)) {
  1107. LOG_ERROR(Kernel_SVC, "dst_address is not page-aligned (dst_address=0x{:016X}).",
  1108. dst_address);
  1109. return ERR_INVALID_ADDRESS;
  1110. }
  1111. if (!Common::Is4KBAligned(src_address)) {
  1112. LOG_ERROR(Kernel_SVC, "src_address is not page-aligned (src_address=0x{:016X}).",
  1113. src_address);
  1114. return ERR_INVALID_ADDRESS;
  1115. }
  1116. if (size == 0 || Common::Is4KBAligned(size)) {
  1117. LOG_ERROR(Kernel_SVC, "Size is zero or not page-aligned (size=0x{:016X}).", size);
  1118. return ERR_INVALID_SIZE;
  1119. }
  1120. if (!IsValidAddressRange(dst_address, size)) {
  1121. LOG_ERROR(Kernel_SVC,
  1122. "Destination address range overflows the address space (dst_address=0x{:016X}, "
  1123. "size=0x{:016X}).",
  1124. dst_address, size);
  1125. return ERR_INVALID_ADDRESS_STATE;
  1126. }
  1127. if (!IsValidAddressRange(src_address, size)) {
  1128. LOG_ERROR(Kernel_SVC,
  1129. "Source address range overflows the address space (src_address=0x{:016X}, "
  1130. "size=0x{:016X}).",
  1131. src_address, size);
  1132. return ERR_INVALID_ADDRESS_STATE;
  1133. }
  1134. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1135. auto process = handle_table.Get<Process>(process_handle);
  1136. if (!process) {
  1137. LOG_ERROR(Kernel_SVC, "Invalid process handle specified (handle=0x{:08X}).",
  1138. process_handle);
  1139. return ERR_INVALID_HANDLE;
  1140. }
  1141. auto& vm_manager = process->VMManager();
  1142. if (!vm_manager.IsWithinAddressSpace(src_address, size)) {
  1143. LOG_ERROR(Kernel_SVC,
  1144. "Source address range is not within the address space (src_address=0x{:016X}, "
  1145. "size=0x{:016X}).",
  1146. src_address, size);
  1147. return ERR_INVALID_ADDRESS_STATE;
  1148. }
  1149. if (!vm_manager.IsWithinASLRRegion(dst_address, size)) {
  1150. LOG_ERROR(Kernel_SVC,
  1151. "Destination address range is not within the ASLR region (dst_address=0x{:016X}, "
  1152. "size=0x{:016X}).",
  1153. dst_address, size);
  1154. return ERR_INVALID_MEMORY_RANGE;
  1155. }
  1156. return vm_manager.UnmapCodeMemory(dst_address, src_address, size);
  1157. }
  1158. /// Exits the current process
  1159. static void ExitProcess(Core::System& system) {
  1160. auto* current_process = system.Kernel().CurrentProcess();
  1161. LOG_INFO(Kernel_SVC, "Process {} exiting", current_process->GetProcessID());
  1162. ASSERT_MSG(current_process->GetStatus() == ProcessStatus::Running,
  1163. "Process has already exited");
  1164. current_process->PrepareForTermination();
  1165. // Kill the current thread
  1166. system.CurrentScheduler().GetCurrentThread()->Stop();
  1167. system.PrepareReschedule();
  1168. }
  1169. /// Creates a new thread
  1170. static ResultCode CreateThread(Core::System& system, Handle* out_handle, VAddr entry_point, u64 arg,
  1171. VAddr stack_top, u32 priority, s32 processor_id) {
  1172. LOG_DEBUG(Kernel_SVC,
  1173. "called entrypoint=0x{:08X}, arg=0x{:08X}, stacktop=0x{:08X}, "
  1174. "threadpriority=0x{:08X}, processorid=0x{:08X} : created handle=0x{:08X}",
  1175. entry_point, arg, stack_top, priority, processor_id, *out_handle);
  1176. auto* const current_process = system.Kernel().CurrentProcess();
  1177. if (processor_id == THREADPROCESSORID_IDEAL) {
  1178. // Set the target CPU to the one specified by the process.
  1179. processor_id = current_process->GetIdealCore();
  1180. ASSERT(processor_id != THREADPROCESSORID_IDEAL);
  1181. }
  1182. if (processor_id < THREADPROCESSORID_0 || processor_id > THREADPROCESSORID_3) {
  1183. LOG_ERROR(Kernel_SVC, "Invalid thread processor ID: {}", processor_id);
  1184. return ERR_INVALID_PROCESSOR_ID;
  1185. }
  1186. const u64 core_mask = current_process->GetCoreMask();
  1187. if ((core_mask | (1ULL << processor_id)) != core_mask) {
  1188. LOG_ERROR(Kernel_SVC, "Invalid thread core specified ({})", processor_id);
  1189. return ERR_INVALID_PROCESSOR_ID;
  1190. }
  1191. if (priority > THREADPRIO_LOWEST) {
  1192. LOG_ERROR(Kernel_SVC,
  1193. "Invalid thread priority specified ({}). Must be within the range 0-64",
  1194. priority);
  1195. return ERR_INVALID_THREAD_PRIORITY;
  1196. }
  1197. if (((1ULL << priority) & current_process->GetPriorityMask()) == 0) {
  1198. LOG_ERROR(Kernel_SVC, "Invalid thread priority specified ({})", priority);
  1199. return ERR_INVALID_THREAD_PRIORITY;
  1200. }
  1201. auto& kernel = system.Kernel();
  1202. CASCADE_RESULT(std::shared_ptr<Thread> thread,
  1203. Thread::Create(kernel, "", entry_point, priority, arg, processor_id, stack_top,
  1204. *current_process));
  1205. const auto new_thread_handle = current_process->GetHandleTable().Create(thread);
  1206. if (new_thread_handle.Failed()) {
  1207. LOG_ERROR(Kernel_SVC, "Failed to create handle with error=0x{:X}",
  1208. new_thread_handle.Code().raw);
  1209. return new_thread_handle.Code();
  1210. }
  1211. *out_handle = *new_thread_handle;
  1212. // Set the thread name for debugging purposes.
  1213. thread->SetName(
  1214. fmt::format("thread[entry_point={:X}, handle={:X}]", entry_point, *new_thread_handle));
  1215. system.PrepareReschedule(thread->GetProcessorID());
  1216. return RESULT_SUCCESS;
  1217. }
  1218. /// Starts the thread for the provided handle
  1219. static ResultCode StartThread(Core::System& system, Handle thread_handle) {
  1220. LOG_DEBUG(Kernel_SVC, "called thread=0x{:08X}", thread_handle);
  1221. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1222. const std::shared_ptr<Thread> thread = handle_table.Get<Thread>(thread_handle);
  1223. if (!thread) {
  1224. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, thread_handle=0x{:08X}",
  1225. thread_handle);
  1226. return ERR_INVALID_HANDLE;
  1227. }
  1228. ASSERT(thread->GetStatus() == ThreadStatus::Dormant);
  1229. thread->ResumeFromWait();
  1230. if (thread->GetStatus() == ThreadStatus::Ready) {
  1231. system.PrepareReschedule(thread->GetProcessorID());
  1232. }
  1233. return RESULT_SUCCESS;
  1234. }
  1235. /// Called when a thread exits
  1236. static void ExitThread(Core::System& system) {
  1237. LOG_DEBUG(Kernel_SVC, "called, pc=0x{:08X}", system.CurrentArmInterface().GetPC());
  1238. auto* const current_thread = system.CurrentScheduler().GetCurrentThread();
  1239. current_thread->Stop();
  1240. system.GlobalScheduler().RemoveThread(SharedFrom(current_thread));
  1241. system.PrepareReschedule();
  1242. }
  1243. /// Sleep the current thread
  1244. static void SleepThread(Core::System& system, s64 nanoseconds) {
  1245. LOG_DEBUG(Kernel_SVC, "called nanoseconds={}", nanoseconds);
  1246. enum class SleepType : s64 {
  1247. YieldWithoutLoadBalancing = 0,
  1248. YieldWithLoadBalancing = -1,
  1249. YieldAndWaitForLoadBalancing = -2,
  1250. };
  1251. auto& scheduler = system.CurrentScheduler();
  1252. auto* const current_thread = scheduler.GetCurrentThread();
  1253. bool is_redundant = false;
  1254. if (nanoseconds <= 0) {
  1255. switch (static_cast<SleepType>(nanoseconds)) {
  1256. case SleepType::YieldWithoutLoadBalancing:
  1257. is_redundant = current_thread->YieldSimple();
  1258. break;
  1259. case SleepType::YieldWithLoadBalancing:
  1260. is_redundant = current_thread->YieldAndBalanceLoad();
  1261. break;
  1262. case SleepType::YieldAndWaitForLoadBalancing:
  1263. is_redundant = current_thread->YieldAndWaitForLoadBalancing();
  1264. break;
  1265. default:
  1266. UNREACHABLE_MSG("Unimplemented sleep yield type '{:016X}'!", nanoseconds);
  1267. }
  1268. } else {
  1269. current_thread->Sleep(nanoseconds);
  1270. }
  1271. if (is_redundant) {
  1272. // If it's redundant, the core is pretty much idle. Some games keep idling
  1273. // a core while it's doing nothing, we advance timing to avoid costly continuous
  1274. // calls.
  1275. system.CoreTiming().AddTicks(2000);
  1276. }
  1277. system.PrepareReschedule(current_thread->GetProcessorID());
  1278. }
  1279. /// Wait process wide key atomic
  1280. static ResultCode WaitProcessWideKeyAtomic(Core::System& system, VAddr mutex_addr,
  1281. VAddr condition_variable_addr, Handle thread_handle,
  1282. s64 nano_seconds) {
  1283. LOG_TRACE(
  1284. Kernel_SVC,
  1285. "called mutex_addr={:X}, condition_variable_addr={:X}, thread_handle=0x{:08X}, timeout={}",
  1286. mutex_addr, condition_variable_addr, thread_handle, nano_seconds);
  1287. if (Memory::IsKernelVirtualAddress(mutex_addr)) {
  1288. LOG_ERROR(
  1289. Kernel_SVC,
  1290. "Given mutex address must not be within the kernel address space. address=0x{:016X}",
  1291. mutex_addr);
  1292. return ERR_INVALID_ADDRESS_STATE;
  1293. }
  1294. if (!Common::IsWordAligned(mutex_addr)) {
  1295. LOG_ERROR(Kernel_SVC, "Given mutex address must be word-aligned. address=0x{:016X}",
  1296. mutex_addr);
  1297. return ERR_INVALID_ADDRESS;
  1298. }
  1299. ASSERT(condition_variable_addr == Common::AlignDown(condition_variable_addr, 4));
  1300. auto* const current_process = system.Kernel().CurrentProcess();
  1301. const auto& handle_table = current_process->GetHandleTable();
  1302. std::shared_ptr<Thread> thread = handle_table.Get<Thread>(thread_handle);
  1303. ASSERT(thread);
  1304. const auto release_result = current_process->GetMutex().Release(mutex_addr);
  1305. if (release_result.IsError()) {
  1306. return release_result;
  1307. }
  1308. Thread* current_thread = system.CurrentScheduler().GetCurrentThread();
  1309. current_thread->SetCondVarWaitAddress(condition_variable_addr);
  1310. current_thread->SetMutexWaitAddress(mutex_addr);
  1311. current_thread->SetWaitHandle(thread_handle);
  1312. current_thread->SetStatus(ThreadStatus::WaitCondVar);
  1313. current_thread->InvalidateWakeupCallback();
  1314. current_process->InsertConditionVariableThread(SharedFrom(current_thread));
  1315. current_thread->WakeAfterDelay(nano_seconds);
  1316. // Note: Deliberately don't attempt to inherit the lock owner's priority.
  1317. system.PrepareReschedule(current_thread->GetProcessorID());
  1318. return RESULT_SUCCESS;
  1319. }
  1320. /// Signal process wide key
  1321. static void SignalProcessWideKey(Core::System& system, VAddr condition_variable_addr, s32 target) {
  1322. LOG_TRACE(Kernel_SVC, "called, condition_variable_addr=0x{:X}, target=0x{:08X}",
  1323. condition_variable_addr, target);
  1324. ASSERT(condition_variable_addr == Common::AlignDown(condition_variable_addr, 4));
  1325. // Retrieve a list of all threads that are waiting for this condition variable.
  1326. auto* const current_process = system.Kernel().CurrentProcess();
  1327. std::vector<std::shared_ptr<Thread>> waiting_threads =
  1328. current_process->GetConditionVariableThreads(condition_variable_addr);
  1329. // Only process up to 'target' threads, unless 'target' is less equal 0, in which case process
  1330. // them all.
  1331. std::size_t last = waiting_threads.size();
  1332. if (target > 0)
  1333. last = std::min(waiting_threads.size(), static_cast<std::size_t>(target));
  1334. for (std::size_t index = 0; index < last; ++index) {
  1335. auto& thread = waiting_threads[index];
  1336. ASSERT(thread->GetCondVarWaitAddress() == condition_variable_addr);
  1337. // liberate Cond Var Thread.
  1338. current_process->RemoveConditionVariableThread(thread);
  1339. thread->SetCondVarWaitAddress(0);
  1340. const std::size_t current_core = system.CurrentCoreIndex();
  1341. auto& monitor = system.Monitor();
  1342. auto& memory = system.Memory();
  1343. // Atomically read the value of the mutex.
  1344. u32 mutex_val = 0;
  1345. u32 update_val = 0;
  1346. const VAddr mutex_address = thread->GetMutexWaitAddress();
  1347. do {
  1348. monitor.SetExclusive(current_core, mutex_address);
  1349. // If the mutex is not yet acquired, acquire it.
  1350. mutex_val = memory.Read32(mutex_address);
  1351. if (mutex_val != 0) {
  1352. update_val = mutex_val | Mutex::MutexHasWaitersFlag;
  1353. } else {
  1354. update_val = thread->GetWaitHandle();
  1355. }
  1356. } while (!monitor.ExclusiveWrite32(current_core, mutex_address, update_val));
  1357. if (mutex_val == 0) {
  1358. // We were able to acquire the mutex, resume this thread.
  1359. ASSERT(thread->GetStatus() == ThreadStatus::WaitCondVar);
  1360. thread->ResumeFromWait();
  1361. auto* const lock_owner = thread->GetLockOwner();
  1362. if (lock_owner != nullptr) {
  1363. lock_owner->RemoveMutexWaiter(thread);
  1364. }
  1365. thread->SetLockOwner(nullptr);
  1366. thread->SetMutexWaitAddress(0);
  1367. thread->SetWaitHandle(0);
  1368. thread->SetWaitSynchronizationResult(RESULT_SUCCESS);
  1369. system.PrepareReschedule(thread->GetProcessorID());
  1370. } else {
  1371. // The mutex is already owned by some other thread, make this thread wait on it.
  1372. const Handle owner_handle = static_cast<Handle>(mutex_val & Mutex::MutexOwnerMask);
  1373. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1374. auto owner = handle_table.Get<Thread>(owner_handle);
  1375. ASSERT(owner);
  1376. ASSERT(thread->GetStatus() == ThreadStatus::WaitCondVar);
  1377. thread->InvalidateWakeupCallback();
  1378. thread->SetStatus(ThreadStatus::WaitMutex);
  1379. owner->AddMutexWaiter(thread);
  1380. system.PrepareReschedule(thread->GetProcessorID());
  1381. }
  1382. }
  1383. }
  1384. // Wait for an address (via Address Arbiter)
  1385. static ResultCode WaitForAddress(Core::System& system, VAddr address, u32 type, s32 value,
  1386. s64 timeout) {
  1387. LOG_TRACE(Kernel_SVC, "called, address=0x{:X}, type=0x{:X}, value=0x{:X}, timeout={}", address,
  1388. type, value, timeout);
  1389. // If the passed address is a kernel virtual address, return invalid memory state.
  1390. if (Memory::IsKernelVirtualAddress(address)) {
  1391. LOG_ERROR(Kernel_SVC, "Address is a kernel virtual address, address={:016X}", address);
  1392. return ERR_INVALID_ADDRESS_STATE;
  1393. }
  1394. // If the address is not properly aligned to 4 bytes, return invalid address.
  1395. if (!Common::IsWordAligned(address)) {
  1396. LOG_ERROR(Kernel_SVC, "Address is not word aligned, address={:016X}", address);
  1397. return ERR_INVALID_ADDRESS;
  1398. }
  1399. const auto arbitration_type = static_cast<AddressArbiter::ArbitrationType>(type);
  1400. auto& address_arbiter = system.Kernel().CurrentProcess()->GetAddressArbiter();
  1401. const ResultCode result =
  1402. address_arbiter.WaitForAddress(address, arbitration_type, value, timeout);
  1403. if (result == RESULT_SUCCESS) {
  1404. system.PrepareReschedule();
  1405. }
  1406. return result;
  1407. }
  1408. // Signals to an address (via Address Arbiter)
  1409. static ResultCode SignalToAddress(Core::System& system, VAddr address, u32 type, s32 value,
  1410. s32 num_to_wake) {
  1411. LOG_TRACE(Kernel_SVC, "called, address=0x{:X}, type=0x{:X}, value=0x{:X}, num_to_wake=0x{:X}",
  1412. address, type, value, num_to_wake);
  1413. // If the passed address is a kernel virtual address, return invalid memory state.
  1414. if (Memory::IsKernelVirtualAddress(address)) {
  1415. LOG_ERROR(Kernel_SVC, "Address is a kernel virtual address, address={:016X}", address);
  1416. return ERR_INVALID_ADDRESS_STATE;
  1417. }
  1418. // If the address is not properly aligned to 4 bytes, return invalid address.
  1419. if (!Common::IsWordAligned(address)) {
  1420. LOG_ERROR(Kernel_SVC, "Address is not word aligned, address={:016X}", address);
  1421. return ERR_INVALID_ADDRESS;
  1422. }
  1423. const auto signal_type = static_cast<AddressArbiter::SignalType>(type);
  1424. auto& address_arbiter = system.Kernel().CurrentProcess()->GetAddressArbiter();
  1425. return address_arbiter.SignalToAddress(address, signal_type, value, num_to_wake);
  1426. }
  1427. static void KernelDebug([[maybe_unused]] Core::System& system,
  1428. [[maybe_unused]] u32 kernel_debug_type, [[maybe_unused]] u64 param1,
  1429. [[maybe_unused]] u64 param2, [[maybe_unused]] u64 param3) {
  1430. // Intentionally do nothing, as this does nothing in released kernel binaries.
  1431. }
  1432. static void ChangeKernelTraceState([[maybe_unused]] Core::System& system,
  1433. [[maybe_unused]] u32 trace_state) {
  1434. // Intentionally do nothing, as this does nothing in released kernel binaries.
  1435. }
  1436. /// This returns the total CPU ticks elapsed since the CPU was powered-on
  1437. static u64 GetSystemTick(Core::System& system) {
  1438. LOG_TRACE(Kernel_SVC, "called");
  1439. auto& core_timing = system.CoreTiming();
  1440. // Returns the value of cntpct_el0 (https://switchbrew.org/wiki/SVC#svcGetSystemTick)
  1441. const u64 result{Core::Timing::CpuCyclesToClockCycles(system.CoreTiming().GetTicks())};
  1442. // Advance time to defeat dumb games that busy-wait for the frame to end.
  1443. core_timing.AddTicks(400);
  1444. return result;
  1445. }
  1446. /// Close a handle
  1447. static ResultCode CloseHandle(Core::System& system, Handle handle) {
  1448. LOG_TRACE(Kernel_SVC, "Closing handle 0x{:08X}", handle);
  1449. auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1450. return handle_table.Close(handle);
  1451. }
  1452. /// Clears the signaled state of an event or process.
  1453. static ResultCode ResetSignal(Core::System& system, Handle handle) {
  1454. LOG_DEBUG(Kernel_SVC, "called handle 0x{:08X}", handle);
  1455. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1456. auto event = handle_table.Get<ReadableEvent>(handle);
  1457. if (event) {
  1458. return event->Reset();
  1459. }
  1460. auto process = handle_table.Get<Process>(handle);
  1461. if (process) {
  1462. return process->ClearSignalState();
  1463. }
  1464. LOG_ERROR(Kernel_SVC, "Invalid handle (0x{:08X})", handle);
  1465. return ERR_INVALID_HANDLE;
  1466. }
  1467. /// Creates a TransferMemory object
  1468. static ResultCode CreateTransferMemory(Core::System& system, Handle* handle, VAddr addr, u64 size,
  1469. u32 permissions) {
  1470. LOG_DEBUG(Kernel_SVC, "called addr=0x{:X}, size=0x{:X}, perms=0x{:08X}", addr, size,
  1471. permissions);
  1472. if (!Common::Is4KBAligned(addr)) {
  1473. LOG_ERROR(Kernel_SVC, "Address ({:016X}) is not page aligned!", addr);
  1474. return ERR_INVALID_ADDRESS;
  1475. }
  1476. if (!Common::Is4KBAligned(size) || size == 0) {
  1477. LOG_ERROR(Kernel_SVC, "Size ({:016X}) is not page aligned or equal to zero!", size);
  1478. return ERR_INVALID_ADDRESS;
  1479. }
  1480. if (!IsValidAddressRange(addr, size)) {
  1481. LOG_ERROR(Kernel_SVC, "Address and size cause overflow! (address={:016X}, size={:016X})",
  1482. addr, size);
  1483. return ERR_INVALID_ADDRESS_STATE;
  1484. }
  1485. const auto perms = static_cast<MemoryPermission>(permissions);
  1486. if (perms != MemoryPermission::None && perms != MemoryPermission::Read &&
  1487. perms != MemoryPermission::ReadWrite) {
  1488. LOG_ERROR(Kernel_SVC, "Invalid memory permissions for transfer memory! (perms={:08X})",
  1489. permissions);
  1490. return ERR_INVALID_MEMORY_PERMISSIONS;
  1491. }
  1492. auto& kernel = system.Kernel();
  1493. auto transfer_mem_handle = TransferMemory::Create(kernel, system.Memory(), addr, size, perms);
  1494. if (const auto reserve_result{transfer_mem_handle->Reserve()}; reserve_result.IsError()) {
  1495. return reserve_result;
  1496. }
  1497. auto& handle_table = kernel.CurrentProcess()->GetHandleTable();
  1498. const auto result{handle_table.Create(std::move(transfer_mem_handle))};
  1499. if (result.Failed()) {
  1500. return result.Code();
  1501. }
  1502. *handle = *result;
  1503. return RESULT_SUCCESS;
  1504. }
  1505. static ResultCode MapTransferMemory(Core::System& system, Handle handle, VAddr address, u64 size,
  1506. u32 permission_raw) {
  1507. LOG_DEBUG(Kernel_SVC,
  1508. "called. handle=0x{:08X}, address=0x{:016X}, size=0x{:016X}, permissions=0x{:08X}",
  1509. handle, address, size, permission_raw);
  1510. if (!Common::Is4KBAligned(address)) {
  1511. LOG_ERROR(Kernel_SVC, "Transfer memory addresses must be 4KB aligned (size=0x{:016X}).",
  1512. address);
  1513. return ERR_INVALID_ADDRESS;
  1514. }
  1515. if (size == 0 || !Common::Is4KBAligned(size)) {
  1516. LOG_ERROR(Kernel_SVC,
  1517. "Transfer memory sizes must be 4KB aligned and not be zero (size=0x{:016X}).",
  1518. size);
  1519. return ERR_INVALID_SIZE;
  1520. }
  1521. if (!IsValidAddressRange(address, size)) {
  1522. LOG_ERROR(Kernel_SVC,
  1523. "Given address and size overflows the 64-bit range (address=0x{:016X}, "
  1524. "size=0x{:016X}).",
  1525. address, size);
  1526. return ERR_INVALID_ADDRESS_STATE;
  1527. }
  1528. const auto permissions = static_cast<MemoryPermission>(permission_raw);
  1529. if (permissions != MemoryPermission::None && permissions != MemoryPermission::Read &&
  1530. permissions != MemoryPermission::ReadWrite) {
  1531. LOG_ERROR(Kernel_SVC, "Invalid transfer memory permissions given (permissions=0x{:08X}).",
  1532. permission_raw);
  1533. return ERR_INVALID_STATE;
  1534. }
  1535. const auto& kernel = system.Kernel();
  1536. const auto* const current_process = kernel.CurrentProcess();
  1537. const auto& handle_table = current_process->GetHandleTable();
  1538. auto transfer_memory = handle_table.Get<TransferMemory>(handle);
  1539. if (!transfer_memory) {
  1540. LOG_ERROR(Kernel_SVC, "Nonexistent transfer memory handle given (handle=0x{:08X}).",
  1541. handle);
  1542. return ERR_INVALID_HANDLE;
  1543. }
  1544. if (!current_process->VMManager().IsWithinASLRRegion(address, size)) {
  1545. LOG_ERROR(Kernel_SVC,
  1546. "Given address and size don't fully fit within the ASLR region "
  1547. "(address=0x{:016X}, size=0x{:016X}).",
  1548. address, size);
  1549. return ERR_INVALID_MEMORY_RANGE;
  1550. }
  1551. return transfer_memory->MapMemory(address, size, permissions);
  1552. }
  1553. static ResultCode UnmapTransferMemory(Core::System& system, Handle handle, VAddr address,
  1554. u64 size) {
  1555. LOG_DEBUG(Kernel_SVC, "called. handle=0x{:08X}, address=0x{:016X}, size=0x{:016X}", handle,
  1556. address, size);
  1557. if (!Common::Is4KBAligned(address)) {
  1558. LOG_ERROR(Kernel_SVC, "Transfer memory addresses must be 4KB aligned (size=0x{:016X}).",
  1559. address);
  1560. return ERR_INVALID_ADDRESS;
  1561. }
  1562. if (size == 0 || !Common::Is4KBAligned(size)) {
  1563. LOG_ERROR(Kernel_SVC,
  1564. "Transfer memory sizes must be 4KB aligned and not be zero (size=0x{:016X}).",
  1565. size);
  1566. return ERR_INVALID_SIZE;
  1567. }
  1568. if (!IsValidAddressRange(address, size)) {
  1569. LOG_ERROR(Kernel_SVC,
  1570. "Given address and size overflows the 64-bit range (address=0x{:016X}, "
  1571. "size=0x{:016X}).",
  1572. address, size);
  1573. return ERR_INVALID_ADDRESS_STATE;
  1574. }
  1575. const auto& kernel = system.Kernel();
  1576. const auto* const current_process = kernel.CurrentProcess();
  1577. const auto& handle_table = current_process->GetHandleTable();
  1578. auto transfer_memory = handle_table.Get<TransferMemory>(handle);
  1579. if (!transfer_memory) {
  1580. LOG_ERROR(Kernel_SVC, "Nonexistent transfer memory handle given (handle=0x{:08X}).",
  1581. handle);
  1582. return ERR_INVALID_HANDLE;
  1583. }
  1584. if (!current_process->VMManager().IsWithinASLRRegion(address, size)) {
  1585. LOG_ERROR(Kernel_SVC,
  1586. "Given address and size don't fully fit within the ASLR region "
  1587. "(address=0x{:016X}, size=0x{:016X}).",
  1588. address, size);
  1589. return ERR_INVALID_MEMORY_RANGE;
  1590. }
  1591. return transfer_memory->UnmapMemory(address, size);
  1592. }
  1593. static ResultCode GetThreadCoreMask(Core::System& system, Handle thread_handle, u32* core,
  1594. u64* mask) {
  1595. LOG_TRACE(Kernel_SVC, "called, handle=0x{:08X}", thread_handle);
  1596. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1597. const std::shared_ptr<Thread> thread = handle_table.Get<Thread>(thread_handle);
  1598. if (!thread) {
  1599. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, thread_handle=0x{:08X}",
  1600. thread_handle);
  1601. return ERR_INVALID_HANDLE;
  1602. }
  1603. *core = thread->GetIdealCore();
  1604. *mask = thread->GetAffinityMask();
  1605. return RESULT_SUCCESS;
  1606. }
  1607. static ResultCode SetThreadCoreMask(Core::System& system, Handle thread_handle, u32 core,
  1608. u64 affinity_mask) {
  1609. LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, core=0x{:X}, affinity_mask=0x{:016X}",
  1610. thread_handle, core, affinity_mask);
  1611. const auto* const current_process = system.Kernel().CurrentProcess();
  1612. if (core == static_cast<u32>(THREADPROCESSORID_IDEAL)) {
  1613. const u8 ideal_cpu_core = current_process->GetIdealCore();
  1614. ASSERT(ideal_cpu_core != static_cast<u8>(THREADPROCESSORID_IDEAL));
  1615. // Set the target CPU to the ideal core specified by the process.
  1616. core = ideal_cpu_core;
  1617. affinity_mask = 1ULL << core;
  1618. } else {
  1619. const u64 core_mask = current_process->GetCoreMask();
  1620. if ((core_mask | affinity_mask) != core_mask) {
  1621. LOG_ERROR(
  1622. Kernel_SVC,
  1623. "Invalid processor ID specified (core_mask=0x{:08X}, affinity_mask=0x{:016X})",
  1624. core_mask, affinity_mask);
  1625. return ERR_INVALID_PROCESSOR_ID;
  1626. }
  1627. if (affinity_mask == 0) {
  1628. LOG_ERROR(Kernel_SVC, "Specfified affinity mask is zero.");
  1629. return ERR_INVALID_COMBINATION;
  1630. }
  1631. if (core < Core::NUM_CPU_CORES) {
  1632. if ((affinity_mask & (1ULL << core)) == 0) {
  1633. LOG_ERROR(Kernel_SVC,
  1634. "Core is not enabled for the current mask, core={}, mask={:016X}", core,
  1635. affinity_mask);
  1636. return ERR_INVALID_COMBINATION;
  1637. }
  1638. } else if (core != static_cast<u32>(THREADPROCESSORID_DONT_CARE) &&
  1639. core != static_cast<u32>(THREADPROCESSORID_DONT_UPDATE)) {
  1640. LOG_ERROR(Kernel_SVC, "Invalid processor ID specified (core={}).", core);
  1641. return ERR_INVALID_PROCESSOR_ID;
  1642. }
  1643. }
  1644. const auto& handle_table = current_process->GetHandleTable();
  1645. const std::shared_ptr<Thread> thread = handle_table.Get<Thread>(thread_handle);
  1646. if (!thread) {
  1647. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, thread_handle=0x{:08X}",
  1648. thread_handle);
  1649. return ERR_INVALID_HANDLE;
  1650. }
  1651. system.PrepareReschedule(thread->GetProcessorID());
  1652. thread->ChangeCore(core, affinity_mask);
  1653. system.PrepareReschedule(thread->GetProcessorID());
  1654. return RESULT_SUCCESS;
  1655. }
  1656. static ResultCode CreateSharedMemory(Core::System& system, Handle* handle, u64 size,
  1657. u32 local_permissions, u32 remote_permissions) {
  1658. LOG_TRACE(Kernel_SVC, "called, size=0x{:X}, localPerms=0x{:08X}, remotePerms=0x{:08X}", size,
  1659. local_permissions, remote_permissions);
  1660. if (size == 0) {
  1661. LOG_ERROR(Kernel_SVC, "Size is 0");
  1662. return ERR_INVALID_SIZE;
  1663. }
  1664. if (!Common::Is4KBAligned(size)) {
  1665. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, 0x{:016X}", size);
  1666. return ERR_INVALID_SIZE;
  1667. }
  1668. if (size >= MAIN_MEMORY_SIZE) {
  1669. LOG_ERROR(Kernel_SVC, "Size is not less than 8GB, 0x{:016X}", size);
  1670. return ERR_INVALID_SIZE;
  1671. }
  1672. const auto local_perms = static_cast<MemoryPermission>(local_permissions);
  1673. if (local_perms != MemoryPermission::Read && local_perms != MemoryPermission::ReadWrite) {
  1674. LOG_ERROR(Kernel_SVC,
  1675. "Invalid local memory permissions, expected Read or ReadWrite but got "
  1676. "local_permissions={}",
  1677. static_cast<u32>(local_permissions));
  1678. return ERR_INVALID_MEMORY_PERMISSIONS;
  1679. }
  1680. const auto remote_perms = static_cast<MemoryPermission>(remote_permissions);
  1681. if (remote_perms != MemoryPermission::Read && remote_perms != MemoryPermission::ReadWrite &&
  1682. remote_perms != MemoryPermission::DontCare) {
  1683. LOG_ERROR(Kernel_SVC,
  1684. "Invalid remote memory permissions, expected Read, ReadWrite or DontCare but got "
  1685. "remote_permissions={}",
  1686. static_cast<u32>(remote_permissions));
  1687. return ERR_INVALID_MEMORY_PERMISSIONS;
  1688. }
  1689. auto& kernel = system.Kernel();
  1690. auto process = kernel.CurrentProcess();
  1691. auto& handle_table = process->GetHandleTable();
  1692. auto shared_mem_handle = SharedMemory::Create(kernel, process, size, local_perms, remote_perms);
  1693. CASCADE_RESULT(*handle, handle_table.Create(shared_mem_handle));
  1694. return RESULT_SUCCESS;
  1695. }
  1696. static ResultCode CreateEvent(Core::System& system, Handle* write_handle, Handle* read_handle) {
  1697. LOG_DEBUG(Kernel_SVC, "called");
  1698. auto& kernel = system.Kernel();
  1699. const auto [readable_event, writable_event] =
  1700. WritableEvent::CreateEventPair(kernel, "CreateEvent");
  1701. HandleTable& handle_table = kernel.CurrentProcess()->GetHandleTable();
  1702. const auto write_create_result = handle_table.Create(writable_event);
  1703. if (write_create_result.Failed()) {
  1704. return write_create_result.Code();
  1705. }
  1706. *write_handle = *write_create_result;
  1707. const auto read_create_result = handle_table.Create(readable_event);
  1708. if (read_create_result.Failed()) {
  1709. handle_table.Close(*write_create_result);
  1710. return read_create_result.Code();
  1711. }
  1712. *read_handle = *read_create_result;
  1713. LOG_DEBUG(Kernel_SVC,
  1714. "successful. Writable event handle=0x{:08X}, Readable event handle=0x{:08X}",
  1715. *write_create_result, *read_create_result);
  1716. return RESULT_SUCCESS;
  1717. }
  1718. static ResultCode ClearEvent(Core::System& system, Handle handle) {
  1719. LOG_TRACE(Kernel_SVC, "called, event=0x{:08X}", handle);
  1720. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1721. auto writable_event = handle_table.Get<WritableEvent>(handle);
  1722. if (writable_event) {
  1723. writable_event->Clear();
  1724. return RESULT_SUCCESS;
  1725. }
  1726. auto readable_event = handle_table.Get<ReadableEvent>(handle);
  1727. if (readable_event) {
  1728. readable_event->Clear();
  1729. return RESULT_SUCCESS;
  1730. }
  1731. LOG_ERROR(Kernel_SVC, "Event handle does not exist, handle=0x{:08X}", handle);
  1732. return ERR_INVALID_HANDLE;
  1733. }
  1734. static ResultCode SignalEvent(Core::System& system, Handle handle) {
  1735. LOG_DEBUG(Kernel_SVC, "called. Handle=0x{:08X}", handle);
  1736. HandleTable& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1737. auto writable_event = handle_table.Get<WritableEvent>(handle);
  1738. if (!writable_event) {
  1739. LOG_ERROR(Kernel_SVC, "Non-existent writable event handle used (0x{:08X})", handle);
  1740. return ERR_INVALID_HANDLE;
  1741. }
  1742. writable_event->Signal();
  1743. system.PrepareReschedule();
  1744. return RESULT_SUCCESS;
  1745. }
  1746. static ResultCode GetProcessInfo(Core::System& system, u64* out, Handle process_handle, u32 type) {
  1747. LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, type=0x{:X}", process_handle, type);
  1748. // This function currently only allows retrieving a process' status.
  1749. enum class InfoType {
  1750. Status,
  1751. };
  1752. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1753. const auto process = handle_table.Get<Process>(process_handle);
  1754. if (!process) {
  1755. LOG_ERROR(Kernel_SVC, "Process handle does not exist, process_handle=0x{:08X}",
  1756. process_handle);
  1757. return ERR_INVALID_HANDLE;
  1758. }
  1759. const auto info_type = static_cast<InfoType>(type);
  1760. if (info_type != InfoType::Status) {
  1761. LOG_ERROR(Kernel_SVC, "Expected info_type to be Status but got {} instead", type);
  1762. return ERR_INVALID_ENUM_VALUE;
  1763. }
  1764. *out = static_cast<u64>(process->GetStatus());
  1765. return RESULT_SUCCESS;
  1766. }
  1767. static ResultCode CreateResourceLimit(Core::System& system, Handle* out_handle) {
  1768. LOG_DEBUG(Kernel_SVC, "called");
  1769. auto& kernel = system.Kernel();
  1770. auto resource_limit = ResourceLimit::Create(kernel);
  1771. auto* const current_process = kernel.CurrentProcess();
  1772. ASSERT(current_process != nullptr);
  1773. const auto handle = current_process->GetHandleTable().Create(std::move(resource_limit));
  1774. if (handle.Failed()) {
  1775. return handle.Code();
  1776. }
  1777. *out_handle = *handle;
  1778. return RESULT_SUCCESS;
  1779. }
  1780. static ResultCode GetResourceLimitLimitValue(Core::System& system, u64* out_value,
  1781. Handle resource_limit, u32 resource_type) {
  1782. LOG_DEBUG(Kernel_SVC, "called. Handle={:08X}, Resource type={}", resource_limit, resource_type);
  1783. const auto limit_value = RetrieveResourceLimitValue(system, resource_limit, resource_type,
  1784. ResourceLimitValueType::LimitValue);
  1785. if (limit_value.Failed()) {
  1786. return limit_value.Code();
  1787. }
  1788. *out_value = static_cast<u64>(*limit_value);
  1789. return RESULT_SUCCESS;
  1790. }
  1791. static ResultCode GetResourceLimitCurrentValue(Core::System& system, u64* out_value,
  1792. Handle resource_limit, u32 resource_type) {
  1793. LOG_DEBUG(Kernel_SVC, "called. Handle={:08X}, Resource type={}", resource_limit, resource_type);
  1794. const auto current_value = RetrieveResourceLimitValue(system, resource_limit, resource_type,
  1795. ResourceLimitValueType::CurrentValue);
  1796. if (current_value.Failed()) {
  1797. return current_value.Code();
  1798. }
  1799. *out_value = static_cast<u64>(*current_value);
  1800. return RESULT_SUCCESS;
  1801. }
  1802. static ResultCode SetResourceLimitLimitValue(Core::System& system, Handle resource_limit,
  1803. u32 resource_type, u64 value) {
  1804. LOG_DEBUG(Kernel_SVC, "called. Handle={:08X}, Resource type={}, Value={}", resource_limit,
  1805. resource_type, value);
  1806. const auto type = static_cast<ResourceType>(resource_type);
  1807. if (!IsValidResourceType(type)) {
  1808. LOG_ERROR(Kernel_SVC, "Invalid resource limit type: '{}'", resource_type);
  1809. return ERR_INVALID_ENUM_VALUE;
  1810. }
  1811. auto* const current_process = system.Kernel().CurrentProcess();
  1812. ASSERT(current_process != nullptr);
  1813. auto resource_limit_object =
  1814. current_process->GetHandleTable().Get<ResourceLimit>(resource_limit);
  1815. if (!resource_limit_object) {
  1816. LOG_ERROR(Kernel_SVC, "Handle to non-existent resource limit instance used. Handle={:08X}",
  1817. resource_limit);
  1818. return ERR_INVALID_HANDLE;
  1819. }
  1820. const auto set_result = resource_limit_object->SetLimitValue(type, static_cast<s64>(value));
  1821. if (set_result.IsError()) {
  1822. LOG_ERROR(
  1823. Kernel_SVC,
  1824. "Attempted to lower resource limit ({}) for category '{}' below its current value ({})",
  1825. resource_limit_object->GetMaxResourceValue(type), resource_type,
  1826. resource_limit_object->GetCurrentResourceValue(type));
  1827. return set_result;
  1828. }
  1829. return RESULT_SUCCESS;
  1830. }
  1831. static ResultCode GetProcessList(Core::System& system, u32* out_num_processes,
  1832. VAddr out_process_ids, u32 out_process_ids_size) {
  1833. LOG_DEBUG(Kernel_SVC, "called. out_process_ids=0x{:016X}, out_process_ids_size={}",
  1834. out_process_ids, out_process_ids_size);
  1835. // If the supplied size is negative or greater than INT32_MAX / sizeof(u64), bail.
  1836. if ((out_process_ids_size & 0xF0000000) != 0) {
  1837. LOG_ERROR(Kernel_SVC,
  1838. "Supplied size outside [0, 0x0FFFFFFF] range. out_process_ids_size={}",
  1839. out_process_ids_size);
  1840. return ERR_OUT_OF_RANGE;
  1841. }
  1842. const auto& kernel = system.Kernel();
  1843. const auto& vm_manager = kernel.CurrentProcess()->VMManager();
  1844. const auto total_copy_size = out_process_ids_size * sizeof(u64);
  1845. if (out_process_ids_size > 0 &&
  1846. !vm_manager.IsWithinAddressSpace(out_process_ids, total_copy_size)) {
  1847. LOG_ERROR(Kernel_SVC, "Address range outside address space. begin=0x{:016X}, end=0x{:016X}",
  1848. out_process_ids, out_process_ids + total_copy_size);
  1849. return ERR_INVALID_ADDRESS_STATE;
  1850. }
  1851. auto& memory = system.Memory();
  1852. const auto& process_list = kernel.GetProcessList();
  1853. const auto num_processes = process_list.size();
  1854. const auto copy_amount = std::min(std::size_t{out_process_ids_size}, num_processes);
  1855. for (std::size_t i = 0; i < copy_amount; ++i) {
  1856. memory.Write64(out_process_ids, process_list[i]->GetProcessID());
  1857. out_process_ids += sizeof(u64);
  1858. }
  1859. *out_num_processes = static_cast<u32>(num_processes);
  1860. return RESULT_SUCCESS;
  1861. }
  1862. static ResultCode GetThreadList(Core::System& system, u32* out_num_threads, VAddr out_thread_ids,
  1863. u32 out_thread_ids_size, Handle debug_handle) {
  1864. // TODO: Handle this case when debug events are supported.
  1865. UNIMPLEMENTED_IF(debug_handle != InvalidHandle);
  1866. LOG_DEBUG(Kernel_SVC, "called. out_thread_ids=0x{:016X}, out_thread_ids_size={}",
  1867. out_thread_ids, out_thread_ids_size);
  1868. // If the size is negative or larger than INT32_MAX / sizeof(u64)
  1869. if ((out_thread_ids_size & 0xF0000000) != 0) {
  1870. LOG_ERROR(Kernel_SVC, "Supplied size outside [0, 0x0FFFFFFF] range. size={}",
  1871. out_thread_ids_size);
  1872. return ERR_OUT_OF_RANGE;
  1873. }
  1874. const auto* const current_process = system.Kernel().CurrentProcess();
  1875. const auto& vm_manager = current_process->VMManager();
  1876. const auto total_copy_size = out_thread_ids_size * sizeof(u64);
  1877. if (out_thread_ids_size > 0 &&
  1878. !vm_manager.IsWithinAddressSpace(out_thread_ids, total_copy_size)) {
  1879. LOG_ERROR(Kernel_SVC, "Address range outside address space. begin=0x{:016X}, end=0x{:016X}",
  1880. out_thread_ids, out_thread_ids + total_copy_size);
  1881. return ERR_INVALID_ADDRESS_STATE;
  1882. }
  1883. auto& memory = system.Memory();
  1884. const auto& thread_list = current_process->GetThreadList();
  1885. const auto num_threads = thread_list.size();
  1886. const auto copy_amount = std::min(std::size_t{out_thread_ids_size}, num_threads);
  1887. auto list_iter = thread_list.cbegin();
  1888. for (std::size_t i = 0; i < copy_amount; ++i, ++list_iter) {
  1889. memory.Write64(out_thread_ids, (*list_iter)->GetThreadID());
  1890. out_thread_ids += sizeof(u64);
  1891. }
  1892. *out_num_threads = static_cast<u32>(num_threads);
  1893. return RESULT_SUCCESS;
  1894. }
  1895. namespace {
  1896. struct FunctionDef {
  1897. using Func = void(Core::System&);
  1898. u32 id;
  1899. Func* func;
  1900. const char* name;
  1901. };
  1902. } // namespace
  1903. static const FunctionDef SVC_Table[] = {
  1904. {0x00, nullptr, "Unknown"},
  1905. {0x01, SvcWrap<SetHeapSize>, "SetHeapSize"},
  1906. {0x02, SvcWrap<SetMemoryPermission>, "SetMemoryPermission"},
  1907. {0x03, SvcWrap<SetMemoryAttribute>, "SetMemoryAttribute"},
  1908. {0x04, SvcWrap<MapMemory>, "MapMemory"},
  1909. {0x05, SvcWrap<UnmapMemory>, "UnmapMemory"},
  1910. {0x06, SvcWrap<QueryMemory>, "QueryMemory"},
  1911. {0x07, SvcWrap<ExitProcess>, "ExitProcess"},
  1912. {0x08, SvcWrap<CreateThread>, "CreateThread"},
  1913. {0x09, SvcWrap<StartThread>, "StartThread"},
  1914. {0x0A, SvcWrap<ExitThread>, "ExitThread"},
  1915. {0x0B, SvcWrap<SleepThread>, "SleepThread"},
  1916. {0x0C, SvcWrap<GetThreadPriority>, "GetThreadPriority"},
  1917. {0x0D, SvcWrap<SetThreadPriority>, "SetThreadPriority"},
  1918. {0x0E, SvcWrap<GetThreadCoreMask>, "GetThreadCoreMask"},
  1919. {0x0F, SvcWrap<SetThreadCoreMask>, "SetThreadCoreMask"},
  1920. {0x10, SvcWrap<GetCurrentProcessorNumber>, "GetCurrentProcessorNumber"},
  1921. {0x11, SvcWrap<SignalEvent>, "SignalEvent"},
  1922. {0x12, SvcWrap<ClearEvent>, "ClearEvent"},
  1923. {0x13, SvcWrap<MapSharedMemory>, "MapSharedMemory"},
  1924. {0x14, SvcWrap<UnmapSharedMemory>, "UnmapSharedMemory"},
  1925. {0x15, SvcWrap<CreateTransferMemory>, "CreateTransferMemory"},
  1926. {0x16, SvcWrap<CloseHandle>, "CloseHandle"},
  1927. {0x17, SvcWrap<ResetSignal>, "ResetSignal"},
  1928. {0x18, SvcWrap<WaitSynchronization>, "WaitSynchronization"},
  1929. {0x19, SvcWrap<CancelSynchronization>, "CancelSynchronization"},
  1930. {0x1A, SvcWrap<ArbitrateLock>, "ArbitrateLock"},
  1931. {0x1B, SvcWrap<ArbitrateUnlock>, "ArbitrateUnlock"},
  1932. {0x1C, SvcWrap<WaitProcessWideKeyAtomic>, "WaitProcessWideKeyAtomic"},
  1933. {0x1D, SvcWrap<SignalProcessWideKey>, "SignalProcessWideKey"},
  1934. {0x1E, SvcWrap<GetSystemTick>, "GetSystemTick"},
  1935. {0x1F, SvcWrap<ConnectToNamedPort>, "ConnectToNamedPort"},
  1936. {0x20, nullptr, "SendSyncRequestLight"},
  1937. {0x21, SvcWrap<SendSyncRequest>, "SendSyncRequest"},
  1938. {0x22, nullptr, "SendSyncRequestWithUserBuffer"},
  1939. {0x23, nullptr, "SendAsyncRequestWithUserBuffer"},
  1940. {0x24, SvcWrap<GetProcessId>, "GetProcessId"},
  1941. {0x25, SvcWrap<GetThreadId>, "GetThreadId"},
  1942. {0x26, SvcWrap<Break>, "Break"},
  1943. {0x27, SvcWrap<OutputDebugString>, "OutputDebugString"},
  1944. {0x28, nullptr, "ReturnFromException"},
  1945. {0x29, SvcWrap<GetInfo>, "GetInfo"},
  1946. {0x2A, nullptr, "FlushEntireDataCache"},
  1947. {0x2B, nullptr, "FlushDataCache"},
  1948. {0x2C, SvcWrap<MapPhysicalMemory>, "MapPhysicalMemory"},
  1949. {0x2D, SvcWrap<UnmapPhysicalMemory>, "UnmapPhysicalMemory"},
  1950. {0x2E, nullptr, "GetFutureThreadInfo"},
  1951. {0x2F, nullptr, "GetLastThreadInfo"},
  1952. {0x30, SvcWrap<GetResourceLimitLimitValue>, "GetResourceLimitLimitValue"},
  1953. {0x31, SvcWrap<GetResourceLimitCurrentValue>, "GetResourceLimitCurrentValue"},
  1954. {0x32, SvcWrap<SetThreadActivity>, "SetThreadActivity"},
  1955. {0x33, SvcWrap<GetThreadContext>, "GetThreadContext"},
  1956. {0x34, SvcWrap<WaitForAddress>, "WaitForAddress"},
  1957. {0x35, SvcWrap<SignalToAddress>, "SignalToAddress"},
  1958. {0x36, nullptr, "SynchronizePreemptionState"},
  1959. {0x37, nullptr, "Unknown"},
  1960. {0x38, nullptr, "Unknown"},
  1961. {0x39, nullptr, "Unknown"},
  1962. {0x3A, nullptr, "Unknown"},
  1963. {0x3B, nullptr, "Unknown"},
  1964. {0x3C, SvcWrap<KernelDebug>, "KernelDebug"},
  1965. {0x3D, SvcWrap<ChangeKernelTraceState>, "ChangeKernelTraceState"},
  1966. {0x3E, nullptr, "Unknown"},
  1967. {0x3F, nullptr, "Unknown"},
  1968. {0x40, nullptr, "CreateSession"},
  1969. {0x41, nullptr, "AcceptSession"},
  1970. {0x42, nullptr, "ReplyAndReceiveLight"},
  1971. {0x43, nullptr, "ReplyAndReceive"},
  1972. {0x44, nullptr, "ReplyAndReceiveWithUserBuffer"},
  1973. {0x45, SvcWrap<CreateEvent>, "CreateEvent"},
  1974. {0x46, nullptr, "Unknown"},
  1975. {0x47, nullptr, "Unknown"},
  1976. {0x48, nullptr, "MapPhysicalMemoryUnsafe"},
  1977. {0x49, nullptr, "UnmapPhysicalMemoryUnsafe"},
  1978. {0x4A, nullptr, "SetUnsafeLimit"},
  1979. {0x4B, nullptr, "CreateCodeMemory"},
  1980. {0x4C, nullptr, "ControlCodeMemory"},
  1981. {0x4D, nullptr, "SleepSystem"},
  1982. {0x4E, nullptr, "ReadWriteRegister"},
  1983. {0x4F, nullptr, "SetProcessActivity"},
  1984. {0x50, SvcWrap<CreateSharedMemory>, "CreateSharedMemory"},
  1985. {0x51, SvcWrap<MapTransferMemory>, "MapTransferMemory"},
  1986. {0x52, SvcWrap<UnmapTransferMemory>, "UnmapTransferMemory"},
  1987. {0x53, nullptr, "CreateInterruptEvent"},
  1988. {0x54, nullptr, "QueryPhysicalAddress"},
  1989. {0x55, nullptr, "QueryIoMapping"},
  1990. {0x56, nullptr, "CreateDeviceAddressSpace"},
  1991. {0x57, nullptr, "AttachDeviceAddressSpace"},
  1992. {0x58, nullptr, "DetachDeviceAddressSpace"},
  1993. {0x59, nullptr, "MapDeviceAddressSpaceByForce"},
  1994. {0x5A, nullptr, "MapDeviceAddressSpaceAligned"},
  1995. {0x5B, nullptr, "MapDeviceAddressSpace"},
  1996. {0x5C, nullptr, "UnmapDeviceAddressSpace"},
  1997. {0x5D, nullptr, "InvalidateProcessDataCache"},
  1998. {0x5E, nullptr, "StoreProcessDataCache"},
  1999. {0x5F, nullptr, "FlushProcessDataCache"},
  2000. {0x60, nullptr, "DebugActiveProcess"},
  2001. {0x61, nullptr, "BreakDebugProcess"},
  2002. {0x62, nullptr, "TerminateDebugProcess"},
  2003. {0x63, nullptr, "GetDebugEvent"},
  2004. {0x64, nullptr, "ContinueDebugEvent"},
  2005. {0x65, SvcWrap<GetProcessList>, "GetProcessList"},
  2006. {0x66, SvcWrap<GetThreadList>, "GetThreadList"},
  2007. {0x67, nullptr, "GetDebugThreadContext"},
  2008. {0x68, nullptr, "SetDebugThreadContext"},
  2009. {0x69, nullptr, "QueryDebugProcessMemory"},
  2010. {0x6A, nullptr, "ReadDebugProcessMemory"},
  2011. {0x6B, nullptr, "WriteDebugProcessMemory"},
  2012. {0x6C, nullptr, "SetHardwareBreakPoint"},
  2013. {0x6D, nullptr, "GetDebugThreadParam"},
  2014. {0x6E, nullptr, "Unknown"},
  2015. {0x6F, nullptr, "GetSystemInfo"},
  2016. {0x70, nullptr, "CreatePort"},
  2017. {0x71, nullptr, "ManageNamedPort"},
  2018. {0x72, nullptr, "ConnectToPort"},
  2019. {0x73, nullptr, "SetProcessMemoryPermission"},
  2020. {0x74, nullptr, "MapProcessMemory"},
  2021. {0x75, nullptr, "UnmapProcessMemory"},
  2022. {0x76, SvcWrap<QueryProcessMemory>, "QueryProcessMemory"},
  2023. {0x77, SvcWrap<MapProcessCodeMemory>, "MapProcessCodeMemory"},
  2024. {0x78, SvcWrap<UnmapProcessCodeMemory>, "UnmapProcessCodeMemory"},
  2025. {0x79, nullptr, "CreateProcess"},
  2026. {0x7A, nullptr, "StartProcess"},
  2027. {0x7B, nullptr, "TerminateProcess"},
  2028. {0x7C, SvcWrap<GetProcessInfo>, "GetProcessInfo"},
  2029. {0x7D, SvcWrap<CreateResourceLimit>, "CreateResourceLimit"},
  2030. {0x7E, SvcWrap<SetResourceLimitLimitValue>, "SetResourceLimitLimitValue"},
  2031. {0x7F, nullptr, "CallSecureMonitor"},
  2032. };
  2033. static const FunctionDef* GetSVCInfo(u32 func_num) {
  2034. if (func_num >= std::size(SVC_Table)) {
  2035. LOG_ERROR(Kernel_SVC, "Unknown svc=0x{:02X}", func_num);
  2036. return nullptr;
  2037. }
  2038. return &SVC_Table[func_num];
  2039. }
  2040. MICROPROFILE_DEFINE(Kernel_SVC, "Kernel", "SVC", MP_RGB(70, 200, 70));
  2041. void CallSVC(Core::System& system, u32 immediate) {
  2042. MICROPROFILE_SCOPE(Kernel_SVC);
  2043. // Lock the global kernel mutex when we enter the kernel HLE.
  2044. std::lock_guard lock{HLE::g_hle_lock};
  2045. const FunctionDef* info = GetSVCInfo(immediate);
  2046. if (info) {
  2047. if (info->func) {
  2048. info->func(system);
  2049. } else {
  2050. LOG_CRITICAL(Kernel_SVC, "Unimplemented SVC function {}(..)", info->name);
  2051. }
  2052. } else {
  2053. LOG_CRITICAL(Kernel_SVC, "Unknown SVC function 0x{:X}", immediate);
  2054. }
  2055. }
  2056. } // namespace Kernel