svc.cpp 96 KB

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