svc.cpp 96 KB

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