svc.cpp 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635
  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/common_funcs.h"
  12. #include "common/fiber.h"
  13. #include "common/logging/log.h"
  14. #include "common/microprofile.h"
  15. #include "common/scope_exit.h"
  16. #include "common/string_util.h"
  17. #include "core/arm/exclusive_monitor.h"
  18. #include "core/core.h"
  19. #include "core/core_timing.h"
  20. #include "core/core_timing_util.h"
  21. #include "core/cpu_manager.h"
  22. #include "core/hle/kernel/client_port.h"
  23. #include "core/hle/kernel/client_session.h"
  24. #include "core/hle/kernel/handle_table.h"
  25. #include "core/hle/kernel/k_address_arbiter.h"
  26. #include "core/hle/kernel/k_condition_variable.h"
  27. #include "core/hle/kernel/k_event.h"
  28. #include "core/hle/kernel/k_memory_block.h"
  29. #include "core/hle/kernel/k_memory_layout.h"
  30. #include "core/hle/kernel/k_page_table.h"
  31. #include "core/hle/kernel/k_readable_event.h"
  32. #include "core/hle/kernel/k_resource_limit.h"
  33. #include "core/hle/kernel/k_scheduler.h"
  34. #include "core/hle/kernel/k_scoped_resource_reservation.h"
  35. #include "core/hle/kernel/k_scoped_scheduler_lock_and_sleep.h"
  36. #include "core/hle/kernel/k_shared_memory.h"
  37. #include "core/hle/kernel/k_synchronization_object.h"
  38. #include "core/hle/kernel/k_thread.h"
  39. #include "core/hle/kernel/k_writable_event.h"
  40. #include "core/hle/kernel/kernel.h"
  41. #include "core/hle/kernel/physical_core.h"
  42. #include "core/hle/kernel/process.h"
  43. #include "core/hle/kernel/svc.h"
  44. #include "core/hle/kernel/svc_results.h"
  45. #include "core/hle/kernel/svc_types.h"
  46. #include "core/hle/kernel/svc_wrap.h"
  47. #include "core/hle/kernel/time_manager.h"
  48. #include "core/hle/kernel/transfer_memory.h"
  49. #include "core/hle/lock.h"
  50. #include "core/hle/result.h"
  51. #include "core/hle/service/service.h"
  52. #include "core/memory.h"
  53. #include "core/reporter.h"
  54. namespace Kernel::Svc {
  55. namespace {
  56. // Checks if address + size is greater than the given address
  57. // This can return false if the size causes an overflow of a 64-bit type
  58. // or if the given size is zero.
  59. constexpr bool IsValidAddressRange(VAddr address, u64 size) {
  60. return address + size > address;
  61. }
  62. // Helper function that performs the common sanity checks for svcMapMemory
  63. // and svcUnmapMemory. This is doable, as both functions perform their sanitizing
  64. // in the same order.
  65. ResultCode MapUnmapMemorySanityChecks(const KPageTable& manager, VAddr dst_addr, VAddr src_addr,
  66. u64 size) {
  67. if (!Common::Is4KBAligned(dst_addr)) {
  68. LOG_ERROR(Kernel_SVC, "Destination address is not aligned to 4KB, 0x{:016X}", dst_addr);
  69. return ResultInvalidAddress;
  70. }
  71. if (!Common::Is4KBAligned(src_addr)) {
  72. LOG_ERROR(Kernel_SVC, "Source address is not aligned to 4KB, 0x{:016X}", src_addr);
  73. return ResultInvalidSize;
  74. }
  75. if (size == 0) {
  76. LOG_ERROR(Kernel_SVC, "Size is 0");
  77. return ResultInvalidSize;
  78. }
  79. if (!Common::Is4KBAligned(size)) {
  80. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, 0x{:016X}", size);
  81. return ResultInvalidSize;
  82. }
  83. if (!IsValidAddressRange(dst_addr, size)) {
  84. LOG_ERROR(Kernel_SVC,
  85. "Destination is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
  86. dst_addr, size);
  87. return ResultInvalidCurrentMemory;
  88. }
  89. if (!IsValidAddressRange(src_addr, size)) {
  90. LOG_ERROR(Kernel_SVC, "Source is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
  91. src_addr, size);
  92. return ResultInvalidCurrentMemory;
  93. }
  94. if (!manager.IsInsideAddressSpace(src_addr, size)) {
  95. LOG_ERROR(Kernel_SVC,
  96. "Source is not within the address space, addr=0x{:016X}, size=0x{:016X}",
  97. src_addr, size);
  98. return ResultInvalidCurrentMemory;
  99. }
  100. if (manager.IsOutsideStackRegion(dst_addr, size)) {
  101. LOG_ERROR(Kernel_SVC,
  102. "Destination is not within the stack region, addr=0x{:016X}, size=0x{:016X}",
  103. dst_addr, size);
  104. return ResultInvalidMemoryRange;
  105. }
  106. if (manager.IsInsideHeapRegion(dst_addr, size)) {
  107. LOG_ERROR(Kernel_SVC,
  108. "Destination does not fit within the heap region, addr=0x{:016X}, "
  109. "size=0x{:016X}",
  110. dst_addr, size);
  111. return ResultInvalidMemoryRange;
  112. }
  113. if (manager.IsInsideAliasRegion(dst_addr, size)) {
  114. LOG_ERROR(Kernel_SVC,
  115. "Destination does not fit within the map region, addr=0x{:016X}, "
  116. "size=0x{:016X}",
  117. dst_addr, size);
  118. return ResultInvalidMemoryRange;
  119. }
  120. return RESULT_SUCCESS;
  121. }
  122. enum class ResourceLimitValueType {
  123. CurrentValue,
  124. LimitValue,
  125. PeakValue,
  126. };
  127. ResultVal<s64> RetrieveResourceLimitValue(Core::System& system, Handle resource_limit,
  128. u32 resource_type, ResourceLimitValueType value_type) {
  129. std::lock_guard lock{HLE::g_hle_lock};
  130. const auto type = static_cast<LimitableResource>(resource_type);
  131. if (!IsValidResourceType(type)) {
  132. LOG_ERROR(Kernel_SVC, "Invalid resource limit type: '{}'", resource_type);
  133. return ResultInvalidEnumValue;
  134. }
  135. const auto* const current_process = system.Kernel().CurrentProcess();
  136. ASSERT(current_process != nullptr);
  137. const auto resource_limit_object =
  138. current_process->GetHandleTable().Get<KResourceLimit>(resource_limit);
  139. if (!resource_limit_object) {
  140. LOG_ERROR(Kernel_SVC, "Handle to non-existent resource limit instance used. Handle={:08X}",
  141. resource_limit);
  142. return ResultInvalidHandle;
  143. }
  144. switch (value_type) {
  145. case ResourceLimitValueType::CurrentValue:
  146. return MakeResult(resource_limit_object->GetCurrentValue(type));
  147. case ResourceLimitValueType::LimitValue:
  148. return MakeResult(resource_limit_object->GetLimitValue(type));
  149. case ResourceLimitValueType::PeakValue:
  150. return MakeResult(resource_limit_object->GetPeakValue(type));
  151. default:
  152. LOG_ERROR(Kernel_SVC, "Invalid resource value_type: '{}'", value_type);
  153. return ResultInvalidEnumValue;
  154. }
  155. }
  156. } // Anonymous namespace
  157. /// Set the process heap to a given Size. It can both extend and shrink the heap.
  158. static ResultCode SetHeapSize(Core::System& system, VAddr* heap_addr, u64 heap_size) {
  159. std::lock_guard lock{HLE::g_hle_lock};
  160. LOG_TRACE(Kernel_SVC, "called, heap_size=0x{:X}", heap_size);
  161. // Size must be a multiple of 0x200000 (2MB) and be equal to or less than 8GB.
  162. if ((heap_size % 0x200000) != 0) {
  163. LOG_ERROR(Kernel_SVC, "The heap size is not a multiple of 2MB, heap_size=0x{:016X}",
  164. heap_size);
  165. return ResultInvalidSize;
  166. }
  167. if (heap_size >= 0x200000000) {
  168. LOG_ERROR(Kernel_SVC, "The heap size is not less than 8GB, heap_size=0x{:016X}", heap_size);
  169. return ResultInvalidSize;
  170. }
  171. auto& page_table{system.Kernel().CurrentProcess()->PageTable()};
  172. CASCADE_RESULT(*heap_addr, page_table.SetHeapSize(heap_size));
  173. return RESULT_SUCCESS;
  174. }
  175. static ResultCode SetHeapSize32(Core::System& system, u32* heap_addr, u32 heap_size) {
  176. VAddr temp_heap_addr{};
  177. const ResultCode result{SetHeapSize(system, &temp_heap_addr, heap_size)};
  178. *heap_addr = static_cast<u32>(temp_heap_addr);
  179. return result;
  180. }
  181. static ResultCode SetMemoryAttribute(Core::System& system, VAddr address, u64 size, u32 mask,
  182. u32 attribute) {
  183. std::lock_guard lock{HLE::g_hle_lock};
  184. LOG_DEBUG(Kernel_SVC,
  185. "called, address=0x{:016X}, size=0x{:X}, mask=0x{:08X}, attribute=0x{:08X}", address,
  186. size, mask, attribute);
  187. if (!Common::Is4KBAligned(address)) {
  188. LOG_ERROR(Kernel_SVC, "Address not page aligned (0x{:016X})", address);
  189. return ResultInvalidAddress;
  190. }
  191. if (size == 0 || !Common::Is4KBAligned(size)) {
  192. LOG_ERROR(Kernel_SVC, "Invalid size (0x{:X}). Size must be non-zero and page aligned.",
  193. size);
  194. return ResultInvalidAddress;
  195. }
  196. if (!IsValidAddressRange(address, size)) {
  197. LOG_ERROR(Kernel_SVC, "Address range overflowed (Address: 0x{:016X}, Size: 0x{:016X})",
  198. address, size);
  199. return ResultInvalidCurrentMemory;
  200. }
  201. const auto attributes{static_cast<MemoryAttribute>(mask | attribute)};
  202. if (attributes != static_cast<MemoryAttribute>(mask) ||
  203. (attributes | MemoryAttribute::Uncached) != MemoryAttribute::Uncached) {
  204. LOG_ERROR(Kernel_SVC,
  205. "Memory attribute doesn't match the given mask (Attribute: 0x{:X}, Mask: {:X}",
  206. attribute, mask);
  207. return ResultInvalidCombination;
  208. }
  209. auto& page_table{system.Kernel().CurrentProcess()->PageTable()};
  210. return page_table.SetMemoryAttribute(address, size, static_cast<KMemoryAttribute>(mask),
  211. static_cast<KMemoryAttribute>(attribute));
  212. }
  213. static ResultCode SetMemoryAttribute32(Core::System& system, u32 address, u32 size, u32 mask,
  214. u32 attribute) {
  215. return SetMemoryAttribute(system, address, size, mask, attribute);
  216. }
  217. /// Maps a memory range into a different range.
  218. static ResultCode MapMemory(Core::System& system, VAddr dst_addr, VAddr src_addr, u64 size) {
  219. std::lock_guard lock{HLE::g_hle_lock};
  220. LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr,
  221. src_addr, size);
  222. auto& page_table{system.Kernel().CurrentProcess()->PageTable()};
  223. if (const ResultCode result{MapUnmapMemorySanityChecks(page_table, dst_addr, src_addr, size)};
  224. result.IsError()) {
  225. return result;
  226. }
  227. return page_table.Map(dst_addr, src_addr, size);
  228. }
  229. static ResultCode MapMemory32(Core::System& system, u32 dst_addr, u32 src_addr, u32 size) {
  230. return MapMemory(system, dst_addr, src_addr, size);
  231. }
  232. /// Unmaps a region that was previously mapped with svcMapMemory
  233. static ResultCode UnmapMemory(Core::System& system, VAddr dst_addr, VAddr src_addr, u64 size) {
  234. std::lock_guard lock{HLE::g_hle_lock};
  235. LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr,
  236. src_addr, size);
  237. auto& page_table{system.Kernel().CurrentProcess()->PageTable()};
  238. if (const ResultCode result{MapUnmapMemorySanityChecks(page_table, dst_addr, src_addr, size)};
  239. result.IsError()) {
  240. return result;
  241. }
  242. return page_table.Unmap(dst_addr, src_addr, size);
  243. }
  244. static ResultCode UnmapMemory32(Core::System& system, u32 dst_addr, u32 src_addr, u32 size) {
  245. return UnmapMemory(system, dst_addr, src_addr, size);
  246. }
  247. /// Connect to an OS service given the port name, returns the handle to the port to out
  248. static ResultCode ConnectToNamedPort(Core::System& system, Handle* out_handle,
  249. VAddr port_name_address) {
  250. std::lock_guard lock{HLE::g_hle_lock};
  251. auto& memory = system.Memory();
  252. if (!memory.IsValidVirtualAddress(port_name_address)) {
  253. LOG_ERROR(Kernel_SVC,
  254. "Port Name Address is not a valid virtual address, port_name_address=0x{:016X}",
  255. port_name_address);
  256. return ResultNotFound;
  257. }
  258. static constexpr std::size_t PortNameMaxLength = 11;
  259. // Read 1 char beyond the max allowed port name to detect names that are too long.
  260. const std::string port_name = memory.ReadCString(port_name_address, PortNameMaxLength + 1);
  261. if (port_name.size() > PortNameMaxLength) {
  262. LOG_ERROR(Kernel_SVC, "Port name is too long, expected {} but got {}", PortNameMaxLength,
  263. port_name.size());
  264. return ResultOutOfRange;
  265. }
  266. LOG_TRACE(Kernel_SVC, "called port_name={}", port_name);
  267. auto& kernel = system.Kernel();
  268. const auto it = kernel.FindNamedPort(port_name);
  269. if (!kernel.IsValidNamedPort(it)) {
  270. LOG_WARNING(Kernel_SVC, "tried to connect to unknown port: {}", port_name);
  271. return ResultNotFound;
  272. }
  273. auto client_port = it->second;
  274. std::shared_ptr<ClientSession> client_session;
  275. CASCADE_RESULT(client_session, client_port->Connect());
  276. // Return the client session
  277. auto& handle_table = kernel.CurrentProcess()->GetHandleTable();
  278. CASCADE_RESULT(*out_handle, handle_table.Create(client_session));
  279. return RESULT_SUCCESS;
  280. }
  281. static ResultCode ConnectToNamedPort32(Core::System& system, Handle* out_handle,
  282. u32 port_name_address) {
  283. return ConnectToNamedPort(system, out_handle, port_name_address);
  284. }
  285. /// Makes a blocking IPC call to an OS service.
  286. static ResultCode SendSyncRequest(Core::System& system, Handle handle) {
  287. auto& kernel = system.Kernel();
  288. const auto& handle_table = kernel.CurrentProcess()->GetHandleTable();
  289. std::shared_ptr<ClientSession> session = handle_table.Get<ClientSession>(handle);
  290. if (!session) {
  291. LOG_ERROR(Kernel_SVC, "called with invalid handle=0x{:08X}", handle);
  292. return ResultInvalidHandle;
  293. }
  294. LOG_TRACE(Kernel_SVC, "called handle=0x{:08X}({})", handle, session->GetName());
  295. auto thread = kernel.CurrentScheduler()->GetCurrentThread();
  296. {
  297. KScopedSchedulerLock lock(kernel);
  298. thread->SetState(ThreadState::Waiting);
  299. thread->SetWaitReasonForDebugging(ThreadWaitReasonForDebugging::IPC);
  300. session->SendSyncRequest(SharedFrom(thread), system.Memory(), system.CoreTiming());
  301. }
  302. KSynchronizationObject* dummy{};
  303. return thread->GetWaitResult(std::addressof(dummy));
  304. }
  305. static ResultCode SendSyncRequest32(Core::System& system, Handle handle) {
  306. return SendSyncRequest(system, handle);
  307. }
  308. /// Get the ID for the specified thread.
  309. static ResultCode GetThreadId(Core::System& system, u64* out_thread_id, Handle thread_handle) {
  310. LOG_TRACE(Kernel_SVC, "called thread=0x{:08X}", thread_handle);
  311. // Get the thread from its handle.
  312. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  313. const std::shared_ptr<KThread> thread = handle_table.Get<KThread>(thread_handle);
  314. if (!thread) {
  315. LOG_ERROR(Kernel_SVC, "Invalid thread handle provided (handle={:08X})", thread_handle);
  316. return ResultInvalidHandle;
  317. }
  318. // Get the thread's id.
  319. *out_thread_id = thread->GetThreadID();
  320. return RESULT_SUCCESS;
  321. }
  322. static ResultCode GetThreadId32(Core::System& system, u32* out_thread_id_low,
  323. u32* out_thread_id_high, Handle thread_handle) {
  324. u64 out_thread_id{};
  325. const ResultCode result{GetThreadId(system, &out_thread_id, thread_handle)};
  326. *out_thread_id_low = static_cast<u32>(out_thread_id >> 32);
  327. *out_thread_id_high = static_cast<u32>(out_thread_id & std::numeric_limits<u32>::max());
  328. return result;
  329. }
  330. /// Gets the ID of the specified process or a specified thread's owning process.
  331. static ResultCode GetProcessId(Core::System& system, u64* process_id, Handle handle) {
  332. LOG_DEBUG(Kernel_SVC, "called handle=0x{:08X}", handle);
  333. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  334. const std::shared_ptr<Process> process = handle_table.Get<Process>(handle);
  335. if (process) {
  336. *process_id = process->GetProcessID();
  337. return RESULT_SUCCESS;
  338. }
  339. const std::shared_ptr<KThread> thread = handle_table.Get<KThread>(handle);
  340. if (thread) {
  341. const Process* const owner_process = thread->GetOwnerProcess();
  342. if (!owner_process) {
  343. LOG_ERROR(Kernel_SVC, "Non-existent owning process encountered.");
  344. return ResultInvalidHandle;
  345. }
  346. *process_id = owner_process->GetProcessID();
  347. return RESULT_SUCCESS;
  348. }
  349. // NOTE: This should also handle debug objects before returning.
  350. LOG_ERROR(Kernel_SVC, "Handle does not exist, handle=0x{:08X}", handle);
  351. return ResultInvalidHandle;
  352. }
  353. static ResultCode GetProcessId32(Core::System& system, u32* process_id_low, u32* process_id_high,
  354. Handle handle) {
  355. u64 process_id{};
  356. const auto result = GetProcessId(system, &process_id, handle);
  357. *process_id_low = static_cast<u32>(process_id);
  358. *process_id_high = static_cast<u32>(process_id >> 32);
  359. return result;
  360. }
  361. /// Wait for the given handles to synchronize, timeout after the specified nanoseconds
  362. static ResultCode WaitSynchronization(Core::System& system, s32* index, VAddr handles_address,
  363. u64 handle_count, s64 nano_seconds) {
  364. LOG_TRACE(Kernel_SVC, "called handles_address=0x{:X}, handle_count={}, nano_seconds={}",
  365. handles_address, handle_count, nano_seconds);
  366. auto& memory = system.Memory();
  367. if (!memory.IsValidVirtualAddress(handles_address)) {
  368. LOG_ERROR(Kernel_SVC,
  369. "Handle address is not a valid virtual address, handle_address=0x{:016X}",
  370. handles_address);
  371. return ResultInvalidPointer;
  372. }
  373. static constexpr u64 MaxHandles = 0x40;
  374. if (handle_count > MaxHandles) {
  375. LOG_ERROR(Kernel_SVC, "Handle count specified is too large, expected {} but got {}",
  376. MaxHandles, handle_count);
  377. return ResultOutOfRange;
  378. }
  379. auto& kernel = system.Kernel();
  380. std::vector<KSynchronizationObject*> objects(handle_count);
  381. const auto& handle_table = kernel.CurrentProcess()->GetHandleTable();
  382. for (u64 i = 0; i < handle_count; ++i) {
  383. const Handle handle = memory.Read32(handles_address + i * sizeof(Handle));
  384. const auto object = handle_table.Get<KSynchronizationObject>(handle);
  385. if (object == nullptr) {
  386. LOG_ERROR(Kernel_SVC, "Object is a nullptr");
  387. return ResultInvalidHandle;
  388. }
  389. objects[i] = object.get();
  390. }
  391. return KSynchronizationObject::Wait(kernel, index, objects.data(),
  392. static_cast<s32>(objects.size()), nano_seconds);
  393. }
  394. static ResultCode WaitSynchronization32(Core::System& system, u32 timeout_low, u32 handles_address,
  395. s32 handle_count, u32 timeout_high, s32* index) {
  396. const s64 nano_seconds{(static_cast<s64>(timeout_high) << 32) | static_cast<s64>(timeout_low)};
  397. return WaitSynchronization(system, index, handles_address, handle_count, nano_seconds);
  398. }
  399. /// Resumes a thread waiting on WaitSynchronization
  400. static ResultCode CancelSynchronization(Core::System& system, Handle thread_handle) {
  401. LOG_TRACE(Kernel_SVC, "called thread=0x{:X}", thread_handle);
  402. // Get the thread from its handle.
  403. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  404. std::shared_ptr<KThread> thread = handle_table.Get<KThread>(thread_handle);
  405. if (!thread) {
  406. LOG_ERROR(Kernel_SVC, "Invalid thread handle provided (handle={:08X})", thread_handle);
  407. return ResultInvalidHandle;
  408. }
  409. // Cancel the thread's wait.
  410. thread->WaitCancel();
  411. return RESULT_SUCCESS;
  412. }
  413. static ResultCode CancelSynchronization32(Core::System& system, Handle thread_handle) {
  414. return CancelSynchronization(system, thread_handle);
  415. }
  416. /// Attempts to locks a mutex
  417. static ResultCode ArbitrateLock(Core::System& system, Handle thread_handle, VAddr address,
  418. u32 tag) {
  419. LOG_TRACE(Kernel_SVC, "called thread_handle=0x{:08X}, address=0x{:X}, tag=0x{:08X}",
  420. thread_handle, address, tag);
  421. // Validate the input address.
  422. if (IsKernelAddress(address)) {
  423. LOG_ERROR(Kernel_SVC, "Attempting to arbitrate a lock on a kernel address (address={:08X})",
  424. address);
  425. return ResultInvalidCurrentMemory;
  426. }
  427. if (!Common::IsAligned(address, sizeof(u32))) {
  428. LOG_ERROR(Kernel_SVC, "Input address must be 4 byte aligned (address: {:08X})", address);
  429. return ResultInvalidAddress;
  430. }
  431. return system.Kernel().CurrentProcess()->WaitForAddress(thread_handle, address, tag);
  432. }
  433. static ResultCode ArbitrateLock32(Core::System& system, Handle thread_handle, u32 address,
  434. u32 tag) {
  435. return ArbitrateLock(system, thread_handle, address, tag);
  436. }
  437. /// Unlock a mutex
  438. static ResultCode ArbitrateUnlock(Core::System& system, VAddr address) {
  439. LOG_TRACE(Kernel_SVC, "called address=0x{:X}", address);
  440. // Validate the input address.
  441. if (IsKernelAddress(address)) {
  442. LOG_ERROR(Kernel_SVC,
  443. "Attempting to arbitrate an unlock on a kernel address (address={:08X})",
  444. address);
  445. return ResultInvalidCurrentMemory;
  446. }
  447. if (!Common::IsAligned(address, sizeof(u32))) {
  448. LOG_ERROR(Kernel_SVC, "Input address must be 4 byte aligned (address: {:08X})", address);
  449. return ResultInvalidAddress;
  450. }
  451. return system.Kernel().CurrentProcess()->SignalToAddress(address);
  452. }
  453. static ResultCode ArbitrateUnlock32(Core::System& system, u32 address) {
  454. return ArbitrateUnlock(system, address);
  455. }
  456. enum class BreakType : u32 {
  457. Panic = 0,
  458. AssertionFailed = 1,
  459. PreNROLoad = 3,
  460. PostNROLoad = 4,
  461. PreNROUnload = 5,
  462. PostNROUnload = 6,
  463. CppException = 7,
  464. };
  465. struct BreakReason {
  466. union {
  467. u32 raw;
  468. BitField<0, 30, BreakType> break_type;
  469. BitField<31, 1, u32> signal_debugger;
  470. };
  471. };
  472. /// Break program execution
  473. static void Break(Core::System& system, u32 reason, u64 info1, u64 info2) {
  474. BreakReason break_reason{reason};
  475. bool has_dumped_buffer{};
  476. std::vector<u8> debug_buffer;
  477. const auto handle_debug_buffer = [&](VAddr addr, u64 sz) {
  478. if (sz == 0 || addr == 0 || has_dumped_buffer) {
  479. return;
  480. }
  481. auto& memory = system.Memory();
  482. // This typically is an error code so we're going to assume this is the case
  483. if (sz == sizeof(u32)) {
  484. LOG_CRITICAL(Debug_Emulated, "debug_buffer_err_code={:X}", memory.Read32(addr));
  485. } else {
  486. // We don't know what's in here so we'll hexdump it
  487. debug_buffer.resize(sz);
  488. memory.ReadBlock(addr, debug_buffer.data(), sz);
  489. std::string hexdump;
  490. for (std::size_t i = 0; i < debug_buffer.size(); i++) {
  491. hexdump += fmt::format("{:02X} ", debug_buffer[i]);
  492. if (i != 0 && i % 16 == 0) {
  493. hexdump += '\n';
  494. }
  495. }
  496. LOG_CRITICAL(Debug_Emulated, "debug_buffer=\n{}", hexdump);
  497. }
  498. has_dumped_buffer = true;
  499. };
  500. switch (break_reason.break_type) {
  501. case BreakType::Panic:
  502. LOG_CRITICAL(Debug_Emulated, "Signalling debugger, PANIC! info1=0x{:016X}, info2=0x{:016X}",
  503. info1, info2);
  504. handle_debug_buffer(info1, info2);
  505. break;
  506. case BreakType::AssertionFailed:
  507. LOG_CRITICAL(Debug_Emulated,
  508. "Signalling debugger, Assertion failed! info1=0x{:016X}, info2=0x{:016X}",
  509. info1, info2);
  510. handle_debug_buffer(info1, info2);
  511. break;
  512. case BreakType::PreNROLoad:
  513. LOG_WARNING(
  514. Debug_Emulated,
  515. "Signalling debugger, Attempting to load an NRO at 0x{:016X} with size 0x{:016X}",
  516. info1, info2);
  517. break;
  518. case BreakType::PostNROLoad:
  519. LOG_WARNING(Debug_Emulated,
  520. "Signalling debugger, Loaded an NRO at 0x{:016X} with size 0x{:016X}", info1,
  521. info2);
  522. break;
  523. case BreakType::PreNROUnload:
  524. LOG_WARNING(
  525. Debug_Emulated,
  526. "Signalling debugger, Attempting to unload an NRO at 0x{:016X} with size 0x{:016X}",
  527. info1, info2);
  528. break;
  529. case BreakType::PostNROUnload:
  530. LOG_WARNING(Debug_Emulated,
  531. "Signalling debugger, Unloaded an NRO at 0x{:016X} with size 0x{:016X}", info1,
  532. info2);
  533. break;
  534. case BreakType::CppException:
  535. LOG_CRITICAL(Debug_Emulated, "Signalling debugger. Uncaught C++ exception encountered.");
  536. break;
  537. default:
  538. LOG_WARNING(
  539. Debug_Emulated,
  540. "Signalling debugger, Unknown break reason {}, info1=0x{:016X}, info2=0x{:016X}",
  541. static_cast<u32>(break_reason.break_type.Value()), info1, info2);
  542. handle_debug_buffer(info1, info2);
  543. break;
  544. }
  545. system.GetReporter().SaveSvcBreakReport(
  546. static_cast<u32>(break_reason.break_type.Value()), break_reason.signal_debugger, info1,
  547. info2, has_dumped_buffer ? std::make_optional(debug_buffer) : std::nullopt);
  548. if (!break_reason.signal_debugger) {
  549. LOG_CRITICAL(
  550. Debug_Emulated,
  551. "Emulated program broke execution! reason=0x{:016X}, info1=0x{:016X}, info2=0x{:016X}",
  552. reason, info1, info2);
  553. handle_debug_buffer(info1, info2);
  554. auto* const current_thread = system.Kernel().CurrentScheduler()->GetCurrentThread();
  555. const auto thread_processor_id = current_thread->GetActiveCore();
  556. system.ArmInterface(static_cast<std::size_t>(thread_processor_id)).LogBacktrace();
  557. }
  558. }
  559. static void Break32(Core::System& system, u32 reason, u32 info1, u32 info2) {
  560. Break(system, reason, info1, info2);
  561. }
  562. /// Used to output a message on a debug hardware unit - does nothing on a retail unit
  563. static void OutputDebugString(Core::System& system, VAddr address, u64 len) {
  564. if (len == 0) {
  565. return;
  566. }
  567. std::string str(len, '\0');
  568. system.Memory().ReadBlock(address, str.data(), str.size());
  569. LOG_DEBUG(Debug_Emulated, "{}", str);
  570. }
  571. /// Gets system/memory information for the current process
  572. static ResultCode GetInfo(Core::System& system, u64* result, u64 info_id, u64 handle,
  573. u64 info_sub_id) {
  574. std::lock_guard lock{HLE::g_hle_lock};
  575. LOG_TRACE(Kernel_SVC, "called info_id=0x{:X}, info_sub_id=0x{:X}, handle=0x{:08X}", info_id,
  576. info_sub_id, handle);
  577. enum class GetInfoType : u64 {
  578. // 1.0.0+
  579. AllowedCPUCoreMask = 0,
  580. AllowedThreadPriorityMask = 1,
  581. MapRegionBaseAddr = 2,
  582. MapRegionSize = 3,
  583. HeapRegionBaseAddr = 4,
  584. HeapRegionSize = 5,
  585. TotalPhysicalMemoryAvailable = 6,
  586. TotalPhysicalMemoryUsed = 7,
  587. IsCurrentProcessBeingDebugged = 8,
  588. RegisterResourceLimit = 9,
  589. IdleTickCount = 10,
  590. RandomEntropy = 11,
  591. ThreadTickCount = 0xF0000002,
  592. // 2.0.0+
  593. ASLRRegionBaseAddr = 12,
  594. ASLRRegionSize = 13,
  595. StackRegionBaseAddr = 14,
  596. StackRegionSize = 15,
  597. // 3.0.0+
  598. SystemResourceSize = 16,
  599. SystemResourceUsage = 17,
  600. TitleId = 18,
  601. // 4.0.0+
  602. PrivilegedProcessId = 19,
  603. // 5.0.0+
  604. UserExceptionContextAddr = 20,
  605. // 6.0.0+
  606. TotalPhysicalMemoryAvailableWithoutSystemResource = 21,
  607. TotalPhysicalMemoryUsedWithoutSystemResource = 22,
  608. };
  609. const auto info_id_type = static_cast<GetInfoType>(info_id);
  610. switch (info_id_type) {
  611. case GetInfoType::AllowedCPUCoreMask:
  612. case GetInfoType::AllowedThreadPriorityMask:
  613. case GetInfoType::MapRegionBaseAddr:
  614. case GetInfoType::MapRegionSize:
  615. case GetInfoType::HeapRegionBaseAddr:
  616. case GetInfoType::HeapRegionSize:
  617. case GetInfoType::ASLRRegionBaseAddr:
  618. case GetInfoType::ASLRRegionSize:
  619. case GetInfoType::StackRegionBaseAddr:
  620. case GetInfoType::StackRegionSize:
  621. case GetInfoType::TotalPhysicalMemoryAvailable:
  622. case GetInfoType::TotalPhysicalMemoryUsed:
  623. case GetInfoType::SystemResourceSize:
  624. case GetInfoType::SystemResourceUsage:
  625. case GetInfoType::TitleId:
  626. case GetInfoType::UserExceptionContextAddr:
  627. case GetInfoType::TotalPhysicalMemoryAvailableWithoutSystemResource:
  628. case GetInfoType::TotalPhysicalMemoryUsedWithoutSystemResource: {
  629. if (info_sub_id != 0) {
  630. LOG_ERROR(Kernel_SVC, "Info sub id is non zero! info_id={}, info_sub_id={}", info_id,
  631. info_sub_id);
  632. return ResultInvalidEnumValue;
  633. }
  634. const auto& current_process_handle_table =
  635. system.Kernel().CurrentProcess()->GetHandleTable();
  636. const auto process = current_process_handle_table.Get<Process>(static_cast<Handle>(handle));
  637. if (!process) {
  638. LOG_ERROR(Kernel_SVC, "Process is not valid! info_id={}, info_sub_id={}, handle={:08X}",
  639. info_id, info_sub_id, handle);
  640. return ResultInvalidHandle;
  641. }
  642. switch (info_id_type) {
  643. case GetInfoType::AllowedCPUCoreMask:
  644. *result = process->GetCoreMask();
  645. return RESULT_SUCCESS;
  646. case GetInfoType::AllowedThreadPriorityMask:
  647. *result = process->GetPriorityMask();
  648. return RESULT_SUCCESS;
  649. case GetInfoType::MapRegionBaseAddr:
  650. *result = process->PageTable().GetAliasRegionStart();
  651. return RESULT_SUCCESS;
  652. case GetInfoType::MapRegionSize:
  653. *result = process->PageTable().GetAliasRegionSize();
  654. return RESULT_SUCCESS;
  655. case GetInfoType::HeapRegionBaseAddr:
  656. *result = process->PageTable().GetHeapRegionStart();
  657. return RESULT_SUCCESS;
  658. case GetInfoType::HeapRegionSize:
  659. *result = process->PageTable().GetHeapRegionSize();
  660. return RESULT_SUCCESS;
  661. case GetInfoType::ASLRRegionBaseAddr:
  662. *result = process->PageTable().GetAliasCodeRegionStart();
  663. return RESULT_SUCCESS;
  664. case GetInfoType::ASLRRegionSize:
  665. *result = process->PageTable().GetAliasCodeRegionSize();
  666. return RESULT_SUCCESS;
  667. case GetInfoType::StackRegionBaseAddr:
  668. *result = process->PageTable().GetStackRegionStart();
  669. return RESULT_SUCCESS;
  670. case GetInfoType::StackRegionSize:
  671. *result = process->PageTable().GetStackRegionSize();
  672. return RESULT_SUCCESS;
  673. case GetInfoType::TotalPhysicalMemoryAvailable:
  674. *result = process->GetTotalPhysicalMemoryAvailable();
  675. return RESULT_SUCCESS;
  676. case GetInfoType::TotalPhysicalMemoryUsed:
  677. *result = process->GetTotalPhysicalMemoryUsed();
  678. return RESULT_SUCCESS;
  679. case GetInfoType::SystemResourceSize:
  680. *result = process->GetSystemResourceSize();
  681. return RESULT_SUCCESS;
  682. case GetInfoType::SystemResourceUsage:
  683. LOG_WARNING(Kernel_SVC, "(STUBBED) Attempted to query system resource usage");
  684. *result = process->GetSystemResourceUsage();
  685. return RESULT_SUCCESS;
  686. case GetInfoType::TitleId:
  687. *result = process->GetTitleID();
  688. return RESULT_SUCCESS;
  689. case GetInfoType::UserExceptionContextAddr:
  690. *result = process->GetTLSRegionAddress();
  691. return RESULT_SUCCESS;
  692. case GetInfoType::TotalPhysicalMemoryAvailableWithoutSystemResource:
  693. *result = process->GetTotalPhysicalMemoryAvailableWithoutSystemResource();
  694. return RESULT_SUCCESS;
  695. case GetInfoType::TotalPhysicalMemoryUsedWithoutSystemResource:
  696. *result = process->GetTotalPhysicalMemoryUsedWithoutSystemResource();
  697. return RESULT_SUCCESS;
  698. default:
  699. break;
  700. }
  701. LOG_ERROR(Kernel_SVC, "Unimplemented svcGetInfo id=0x{:016X}", info_id);
  702. return ResultInvalidEnumValue;
  703. }
  704. case GetInfoType::IsCurrentProcessBeingDebugged:
  705. *result = 0;
  706. return RESULT_SUCCESS;
  707. case GetInfoType::RegisterResourceLimit: {
  708. if (handle != 0) {
  709. LOG_ERROR(Kernel, "Handle is non zero! handle={:08X}", handle);
  710. return ResultInvalidHandle;
  711. }
  712. if (info_sub_id != 0) {
  713. LOG_ERROR(Kernel, "Info sub id is non zero! info_id={}, info_sub_id={}", info_id,
  714. info_sub_id);
  715. return ResultInvalidCombination;
  716. }
  717. Process* const current_process = system.Kernel().CurrentProcess();
  718. HandleTable& handle_table = current_process->GetHandleTable();
  719. const auto resource_limit = current_process->GetResourceLimit();
  720. if (!resource_limit) {
  721. *result = KernelHandle::InvalidHandle;
  722. // Yes, the kernel considers this a successful operation.
  723. return RESULT_SUCCESS;
  724. }
  725. const auto table_result = handle_table.Create(resource_limit);
  726. if (table_result.Failed()) {
  727. return table_result.Code();
  728. }
  729. *result = *table_result;
  730. return RESULT_SUCCESS;
  731. }
  732. case GetInfoType::RandomEntropy:
  733. if (handle != 0) {
  734. LOG_ERROR(Kernel_SVC, "Process Handle is non zero, expected 0 result but got {:016X}",
  735. handle);
  736. return ResultInvalidHandle;
  737. }
  738. if (info_sub_id >= Process::RANDOM_ENTROPY_SIZE) {
  739. LOG_ERROR(Kernel_SVC, "Entropy size is out of range, expected {} but got {}",
  740. Process::RANDOM_ENTROPY_SIZE, info_sub_id);
  741. return ResultInvalidCombination;
  742. }
  743. *result = system.Kernel().CurrentProcess()->GetRandomEntropy(info_sub_id);
  744. return RESULT_SUCCESS;
  745. case GetInfoType::PrivilegedProcessId:
  746. LOG_WARNING(Kernel_SVC,
  747. "(STUBBED) Attempted to query privileged process id bounds, returned 0");
  748. *result = 0;
  749. return RESULT_SUCCESS;
  750. case GetInfoType::ThreadTickCount: {
  751. constexpr u64 num_cpus = 4;
  752. if (info_sub_id != 0xFFFFFFFFFFFFFFFF && info_sub_id >= num_cpus) {
  753. LOG_ERROR(Kernel_SVC, "Core count is out of range, expected {} but got {}", num_cpus,
  754. info_sub_id);
  755. return ResultInvalidCombination;
  756. }
  757. const auto thread = system.Kernel().CurrentProcess()->GetHandleTable().Get<KThread>(
  758. static_cast<Handle>(handle));
  759. if (!thread) {
  760. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}",
  761. static_cast<Handle>(handle));
  762. return ResultInvalidHandle;
  763. }
  764. const auto& core_timing = system.CoreTiming();
  765. const auto& scheduler = *system.Kernel().CurrentScheduler();
  766. const auto* const current_thread = scheduler.GetCurrentThread();
  767. const bool same_thread = current_thread == thread.get();
  768. const u64 prev_ctx_ticks = scheduler.GetLastContextSwitchTicks();
  769. u64 out_ticks = 0;
  770. if (same_thread && info_sub_id == 0xFFFFFFFFFFFFFFFF) {
  771. const u64 thread_ticks = current_thread->GetCpuTime();
  772. out_ticks = thread_ticks + (core_timing.GetCPUTicks() - prev_ctx_ticks);
  773. } else if (same_thread && info_sub_id == system.CurrentCoreIndex()) {
  774. out_ticks = core_timing.GetCPUTicks() - prev_ctx_ticks;
  775. }
  776. *result = out_ticks;
  777. return RESULT_SUCCESS;
  778. }
  779. default:
  780. LOG_ERROR(Kernel_SVC, "Unimplemented svcGetInfo id=0x{:016X}", info_id);
  781. return ResultInvalidEnumValue;
  782. }
  783. }
  784. static ResultCode GetInfo32(Core::System& system, u32* result_low, u32* result_high, u32 sub_id_low,
  785. u32 info_id, u32 handle, u32 sub_id_high) {
  786. const u64 sub_id{u64{sub_id_low} | (u64{sub_id_high} << 32)};
  787. u64 res_value{};
  788. const ResultCode result{GetInfo(system, &res_value, info_id, handle, sub_id)};
  789. *result_high = static_cast<u32>(res_value >> 32);
  790. *result_low = static_cast<u32>(res_value & std::numeric_limits<u32>::max());
  791. return result;
  792. }
  793. /// Maps memory at a desired address
  794. static ResultCode MapPhysicalMemory(Core::System& system, VAddr addr, u64 size) {
  795. std::lock_guard lock{HLE::g_hle_lock};
  796. LOG_DEBUG(Kernel_SVC, "called, addr=0x{:016X}, size=0x{:X}", addr, size);
  797. if (!Common::Is4KBAligned(addr)) {
  798. LOG_ERROR(Kernel_SVC, "Address is not aligned to 4KB, 0x{:016X}", addr);
  799. return ResultInvalidAddress;
  800. }
  801. if (!Common::Is4KBAligned(size)) {
  802. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, 0x{:X}", size);
  803. return ResultInvalidSize;
  804. }
  805. if (size == 0) {
  806. LOG_ERROR(Kernel_SVC, "Size is zero");
  807. return ResultInvalidSize;
  808. }
  809. if (!(addr < addr + size)) {
  810. LOG_ERROR(Kernel_SVC, "Size causes 64-bit overflow of address");
  811. return ResultInvalidMemoryRange;
  812. }
  813. Process* const current_process{system.Kernel().CurrentProcess()};
  814. auto& page_table{current_process->PageTable()};
  815. if (current_process->GetSystemResourceSize() == 0) {
  816. LOG_ERROR(Kernel_SVC, "System Resource Size is zero");
  817. return ResultInvalidState;
  818. }
  819. if (!page_table.IsInsideAddressSpace(addr, size)) {
  820. LOG_ERROR(Kernel_SVC,
  821. "Address is not within the address space, addr=0x{:016X}, size=0x{:016X}", addr,
  822. size);
  823. return ResultInvalidMemoryRange;
  824. }
  825. if (page_table.IsOutsideAliasRegion(addr, size)) {
  826. LOG_ERROR(Kernel_SVC,
  827. "Address is not within the alias region, addr=0x{:016X}, size=0x{:016X}", addr,
  828. size);
  829. return ResultInvalidMemoryRange;
  830. }
  831. return page_table.MapPhysicalMemory(addr, size);
  832. }
  833. static ResultCode MapPhysicalMemory32(Core::System& system, u32 addr, u32 size) {
  834. return MapPhysicalMemory(system, addr, size);
  835. }
  836. /// Unmaps memory previously mapped via MapPhysicalMemory
  837. static ResultCode UnmapPhysicalMemory(Core::System& system, VAddr addr, u64 size) {
  838. std::lock_guard lock{HLE::g_hle_lock};
  839. LOG_DEBUG(Kernel_SVC, "called, addr=0x{:016X}, size=0x{:X}", addr, size);
  840. if (!Common::Is4KBAligned(addr)) {
  841. LOG_ERROR(Kernel_SVC, "Address is not aligned to 4KB, 0x{:016X}", addr);
  842. return ResultInvalidAddress;
  843. }
  844. if (!Common::Is4KBAligned(size)) {
  845. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, 0x{:X}", size);
  846. return ResultInvalidSize;
  847. }
  848. if (size == 0) {
  849. LOG_ERROR(Kernel_SVC, "Size is zero");
  850. return ResultInvalidSize;
  851. }
  852. if (!(addr < addr + size)) {
  853. LOG_ERROR(Kernel_SVC, "Size causes 64-bit overflow of address");
  854. return ResultInvalidMemoryRange;
  855. }
  856. Process* const current_process{system.Kernel().CurrentProcess()};
  857. auto& page_table{current_process->PageTable()};
  858. if (current_process->GetSystemResourceSize() == 0) {
  859. LOG_ERROR(Kernel_SVC, "System Resource Size is zero");
  860. return ResultInvalidState;
  861. }
  862. if (!page_table.IsInsideAddressSpace(addr, size)) {
  863. LOG_ERROR(Kernel_SVC,
  864. "Address is not within the address space, addr=0x{:016X}, size=0x{:016X}", addr,
  865. size);
  866. return ResultInvalidMemoryRange;
  867. }
  868. if (page_table.IsOutsideAliasRegion(addr, size)) {
  869. LOG_ERROR(Kernel_SVC,
  870. "Address is not within the alias region, addr=0x{:016X}, size=0x{:016X}", addr,
  871. size);
  872. return ResultInvalidMemoryRange;
  873. }
  874. return page_table.UnmapPhysicalMemory(addr, size);
  875. }
  876. static ResultCode UnmapPhysicalMemory32(Core::System& system, u32 addr, u32 size) {
  877. return UnmapPhysicalMemory(system, addr, size);
  878. }
  879. /// Sets the thread activity
  880. static ResultCode SetThreadActivity(Core::System& system, Handle thread_handle,
  881. ThreadActivity thread_activity) {
  882. LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, activity=0x{:08X}", thread_handle,
  883. thread_activity);
  884. // Validate the activity.
  885. constexpr auto IsValidThreadActivity = [](ThreadActivity activity) {
  886. return activity == ThreadActivity::Runnable || activity == ThreadActivity::Paused;
  887. };
  888. if (!IsValidThreadActivity(thread_activity)) {
  889. LOG_ERROR(Kernel_SVC, "Invalid thread activity value provided (activity={})",
  890. thread_activity);
  891. return ResultInvalidEnumValue;
  892. }
  893. // Get the thread from its handle.
  894. auto& kernel = system.Kernel();
  895. const auto& handle_table = kernel.CurrentProcess()->GetHandleTable();
  896. const std::shared_ptr<KThread> thread = handle_table.Get<KThread>(thread_handle);
  897. if (!thread) {
  898. LOG_ERROR(Kernel_SVC, "Invalid thread handle provided (handle={:08X})", thread_handle);
  899. return ResultInvalidHandle;
  900. }
  901. // Check that the activity is being set on a non-current thread for the current process.
  902. if (thread->GetOwnerProcess() != kernel.CurrentProcess()) {
  903. LOG_ERROR(Kernel_SVC, "Invalid owning process for the created thread.");
  904. return ResultInvalidHandle;
  905. }
  906. if (thread.get() == GetCurrentThreadPointer(kernel)) {
  907. LOG_ERROR(Kernel_SVC, "Thread is busy");
  908. return ResultBusy;
  909. }
  910. // Set the activity.
  911. const auto set_result = thread->SetActivity(thread_activity);
  912. if (set_result.IsError()) {
  913. LOG_ERROR(Kernel_SVC, "Failed to set thread activity.");
  914. return set_result;
  915. }
  916. return RESULT_SUCCESS;
  917. }
  918. static ResultCode SetThreadActivity32(Core::System& system, Handle thread_handle,
  919. Svc::ThreadActivity thread_activity) {
  920. return SetThreadActivity(system, thread_handle, thread_activity);
  921. }
  922. /// Gets the thread context
  923. static ResultCode GetThreadContext(Core::System& system, VAddr out_context, Handle thread_handle) {
  924. LOG_DEBUG(Kernel_SVC, "called, out_context=0x{:08X}, thread_handle=0x{:X}", out_context,
  925. thread_handle);
  926. // Get the thread from its handle.
  927. const auto* current_process = system.Kernel().CurrentProcess();
  928. const std::shared_ptr<KThread> thread =
  929. current_process->GetHandleTable().Get<KThread>(thread_handle);
  930. if (!thread) {
  931. LOG_ERROR(Kernel_SVC, "Invalid thread handle provided (handle={})", thread_handle);
  932. return ResultInvalidHandle;
  933. }
  934. // Require the handle be to a non-current thread in the current process.
  935. if (thread->GetOwnerProcess() != current_process) {
  936. LOG_ERROR(Kernel_SVC, "Thread owning process is not the current process.");
  937. return ResultInvalidHandle;
  938. }
  939. if (thread.get() == system.Kernel().CurrentScheduler()->GetCurrentThread()) {
  940. LOG_ERROR(Kernel_SVC, "Current thread is busy.");
  941. return ResultBusy;
  942. }
  943. // Get the thread context.
  944. std::vector<u8> context;
  945. const auto context_result = thread->GetThreadContext3(context);
  946. if (context_result.IsError()) {
  947. LOG_ERROR(Kernel_SVC, "Unable to successfully retrieve thread context (result: {})",
  948. context_result.raw);
  949. return context_result;
  950. }
  951. // Copy the thread context to user space.
  952. system.Memory().WriteBlock(out_context, context.data(), context.size());
  953. return RESULT_SUCCESS;
  954. }
  955. static ResultCode GetThreadContext32(Core::System& system, u32 out_context, Handle thread_handle) {
  956. return GetThreadContext(system, out_context, thread_handle);
  957. }
  958. /// Gets the priority for the specified thread
  959. static ResultCode GetThreadPriority(Core::System& system, u32* out_priority, Handle handle) {
  960. LOG_TRACE(Kernel_SVC, "called");
  961. // Get the thread from its handle.
  962. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  963. const std::shared_ptr<KThread> thread = handle_table.Get<KThread>(handle);
  964. if (!thread) {
  965. LOG_ERROR(Kernel_SVC, "Invalid thread handle provided (handle={:08X})", handle);
  966. return ResultInvalidHandle;
  967. }
  968. // Get the thread's priority.
  969. *out_priority = thread->GetPriority();
  970. return RESULT_SUCCESS;
  971. }
  972. static ResultCode GetThreadPriority32(Core::System& system, u32* out_priority, Handle handle) {
  973. return GetThreadPriority(system, out_priority, handle);
  974. }
  975. /// Sets the priority for the specified thread
  976. static ResultCode SetThreadPriority(Core::System& system, Handle handle, u32 priority) {
  977. LOG_TRACE(Kernel_SVC, "called");
  978. // Validate the priority.
  979. if (HighestThreadPriority > priority || priority > LowestThreadPriority) {
  980. LOG_ERROR(Kernel_SVC, "Invalid thread priority specified (priority={})", priority);
  981. return ResultInvalidPriority;
  982. }
  983. // Get the thread from its handle.
  984. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  985. const std::shared_ptr<KThread> thread = handle_table.Get<KThread>(handle);
  986. if (!thread) {
  987. LOG_ERROR(Kernel_SVC, "Invalid handle provided (handle={:08X})", handle);
  988. return ResultInvalidHandle;
  989. }
  990. // Set the thread priority.
  991. thread->SetBasePriority(priority);
  992. return RESULT_SUCCESS;
  993. }
  994. static ResultCode SetThreadPriority32(Core::System& system, Handle handle, u32 priority) {
  995. return SetThreadPriority(system, handle, priority);
  996. }
  997. /// Get which CPU core is executing the current thread
  998. static u32 GetCurrentProcessorNumber(Core::System& system) {
  999. LOG_TRACE(Kernel_SVC, "called");
  1000. return static_cast<u32>(system.CurrentPhysicalCore().CoreIndex());
  1001. }
  1002. static u32 GetCurrentProcessorNumber32(Core::System& system) {
  1003. return GetCurrentProcessorNumber(system);
  1004. }
  1005. static ResultCode MapSharedMemory(Core::System& system, Handle shared_memory_handle, VAddr addr,
  1006. u64 size, u32 permissions) {
  1007. std::lock_guard lock{HLE::g_hle_lock};
  1008. LOG_TRACE(Kernel_SVC,
  1009. "called, shared_memory_handle=0x{:X}, addr=0x{:X}, size=0x{:X}, permissions=0x{:08X}",
  1010. shared_memory_handle, addr, size, permissions);
  1011. if (!Common::Is4KBAligned(addr)) {
  1012. LOG_ERROR(Kernel_SVC, "Address is not aligned to 4KB, addr=0x{:016X}", addr);
  1013. return ResultInvalidAddress;
  1014. }
  1015. if (size == 0) {
  1016. LOG_ERROR(Kernel_SVC, "Size is 0");
  1017. return ResultInvalidSize;
  1018. }
  1019. if (!Common::Is4KBAligned(size)) {
  1020. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, size=0x{:016X}", size);
  1021. return ResultInvalidSize;
  1022. }
  1023. if (!IsValidAddressRange(addr, size)) {
  1024. LOG_ERROR(Kernel_SVC, "Region is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
  1025. addr, size);
  1026. return ResultInvalidCurrentMemory;
  1027. }
  1028. const auto permission_type = static_cast<MemoryPermission>(permissions);
  1029. if ((permission_type | MemoryPermission::Write) != MemoryPermission::ReadWrite) {
  1030. LOG_ERROR(Kernel_SVC, "Expected Read or ReadWrite permission but got permissions=0x{:08X}",
  1031. permissions);
  1032. return ResultInvalidMemoryPermissions;
  1033. }
  1034. auto* const current_process{system.Kernel().CurrentProcess()};
  1035. auto& page_table{current_process->PageTable()};
  1036. if (page_table.IsInvalidRegion(addr, size)) {
  1037. LOG_ERROR(Kernel_SVC,
  1038. "Addr does not fit within the valid region, addr=0x{:016X}, "
  1039. "size=0x{:016X}",
  1040. addr, size);
  1041. return ResultInvalidMemoryRange;
  1042. }
  1043. if (page_table.IsInsideHeapRegion(addr, size)) {
  1044. LOG_ERROR(Kernel_SVC,
  1045. "Addr does not fit within the heap region, addr=0x{:016X}, "
  1046. "size=0x{:016X}",
  1047. addr, size);
  1048. return ResultInvalidMemoryRange;
  1049. }
  1050. if (page_table.IsInsideAliasRegion(addr, size)) {
  1051. LOG_ERROR(Kernel_SVC,
  1052. "Address does not fit within the map region, addr=0x{:016X}, "
  1053. "size=0x{:016X}",
  1054. addr, size);
  1055. return ResultInvalidMemoryRange;
  1056. }
  1057. auto shared_memory{current_process->GetHandleTable().Get<KSharedMemory>(shared_memory_handle)};
  1058. if (!shared_memory) {
  1059. LOG_ERROR(Kernel_SVC, "Shared memory does not exist, shared_memory_handle=0x{:08X}",
  1060. shared_memory_handle);
  1061. return ResultInvalidHandle;
  1062. }
  1063. return shared_memory->Map(*current_process, addr, size,
  1064. static_cast<KMemoryPermission>(permission_type));
  1065. }
  1066. static ResultCode MapSharedMemory32(Core::System& system, Handle shared_memory_handle, u32 addr,
  1067. u32 size, u32 permissions) {
  1068. return MapSharedMemory(system, shared_memory_handle, addr, size, permissions);
  1069. }
  1070. static ResultCode QueryProcessMemory(Core::System& system, VAddr memory_info_address,
  1071. VAddr page_info_address, Handle process_handle,
  1072. VAddr address) {
  1073. std::lock_guard lock{HLE::g_hle_lock};
  1074. LOG_TRACE(Kernel_SVC, "called process=0x{:08X} address={:X}", process_handle, address);
  1075. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1076. std::shared_ptr<Process> process = handle_table.Get<Process>(process_handle);
  1077. if (!process) {
  1078. LOG_ERROR(Kernel_SVC, "Process handle does not exist, process_handle=0x{:08X}",
  1079. process_handle);
  1080. return ResultInvalidHandle;
  1081. }
  1082. auto& memory{system.Memory()};
  1083. const auto memory_info{process->PageTable().QueryInfo(address).GetSvcMemoryInfo()};
  1084. memory.Write64(memory_info_address + 0x00, memory_info.addr);
  1085. memory.Write64(memory_info_address + 0x08, memory_info.size);
  1086. memory.Write32(memory_info_address + 0x10, static_cast<u32>(memory_info.state) & 0xff);
  1087. memory.Write32(memory_info_address + 0x14, static_cast<u32>(memory_info.attr));
  1088. memory.Write32(memory_info_address + 0x18, static_cast<u32>(memory_info.perm));
  1089. memory.Write32(memory_info_address + 0x1c, memory_info.ipc_refcount);
  1090. memory.Write32(memory_info_address + 0x20, memory_info.device_refcount);
  1091. memory.Write32(memory_info_address + 0x24, 0);
  1092. // Page info appears to be currently unused by the kernel and is always set to zero.
  1093. memory.Write32(page_info_address, 0);
  1094. return RESULT_SUCCESS;
  1095. }
  1096. static ResultCode QueryMemory(Core::System& system, VAddr memory_info_address,
  1097. VAddr page_info_address, VAddr query_address) {
  1098. LOG_TRACE(Kernel_SVC,
  1099. "called, memory_info_address=0x{:016X}, page_info_address=0x{:016X}, "
  1100. "query_address=0x{:016X}",
  1101. memory_info_address, page_info_address, query_address);
  1102. return QueryProcessMemory(system, memory_info_address, page_info_address, CurrentProcess,
  1103. query_address);
  1104. }
  1105. static ResultCode QueryMemory32(Core::System& system, u32 memory_info_address,
  1106. u32 page_info_address, u32 query_address) {
  1107. return QueryMemory(system, memory_info_address, page_info_address, query_address);
  1108. }
  1109. static ResultCode MapProcessCodeMemory(Core::System& system, Handle process_handle, u64 dst_address,
  1110. u64 src_address, u64 size) {
  1111. LOG_DEBUG(Kernel_SVC,
  1112. "called. process_handle=0x{:08X}, dst_address=0x{:016X}, "
  1113. "src_address=0x{:016X}, size=0x{:016X}",
  1114. process_handle, dst_address, src_address, size);
  1115. if (!Common::Is4KBAligned(src_address)) {
  1116. LOG_ERROR(Kernel_SVC, "src_address is not page-aligned (src_address=0x{:016X}).",
  1117. src_address);
  1118. return ResultInvalidAddress;
  1119. }
  1120. if (!Common::Is4KBAligned(dst_address)) {
  1121. LOG_ERROR(Kernel_SVC, "dst_address is not page-aligned (dst_address=0x{:016X}).",
  1122. dst_address);
  1123. return ResultInvalidAddress;
  1124. }
  1125. if (size == 0 || !Common::Is4KBAligned(size)) {
  1126. LOG_ERROR(Kernel_SVC, "Size is zero or not page-aligned (size=0x{:016X})", size);
  1127. return ResultInvalidSize;
  1128. }
  1129. if (!IsValidAddressRange(dst_address, size)) {
  1130. LOG_ERROR(Kernel_SVC,
  1131. "Destination address range overflows the address space (dst_address=0x{:016X}, "
  1132. "size=0x{:016X}).",
  1133. dst_address, size);
  1134. return ResultInvalidCurrentMemory;
  1135. }
  1136. if (!IsValidAddressRange(src_address, size)) {
  1137. LOG_ERROR(Kernel_SVC,
  1138. "Source address range overflows the address space (src_address=0x{:016X}, "
  1139. "size=0x{:016X}).",
  1140. src_address, size);
  1141. return ResultInvalidCurrentMemory;
  1142. }
  1143. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1144. auto process = handle_table.Get<Process>(process_handle);
  1145. if (!process) {
  1146. LOG_ERROR(Kernel_SVC, "Invalid process handle specified (handle=0x{:08X}).",
  1147. process_handle);
  1148. return ResultInvalidHandle;
  1149. }
  1150. auto& page_table = process->PageTable();
  1151. if (!page_table.IsInsideAddressSpace(src_address, size)) {
  1152. LOG_ERROR(Kernel_SVC,
  1153. "Source address range is not within the address space (src_address=0x{:016X}, "
  1154. "size=0x{:016X}).",
  1155. src_address, size);
  1156. return ResultInvalidCurrentMemory;
  1157. }
  1158. if (!page_table.IsInsideASLRRegion(dst_address, size)) {
  1159. LOG_ERROR(Kernel_SVC,
  1160. "Destination address range is not within the ASLR region (dst_address=0x{:016X}, "
  1161. "size=0x{:016X}).",
  1162. dst_address, size);
  1163. return ResultInvalidMemoryRange;
  1164. }
  1165. return page_table.MapProcessCodeMemory(dst_address, src_address, size);
  1166. }
  1167. static ResultCode UnmapProcessCodeMemory(Core::System& system, Handle process_handle,
  1168. u64 dst_address, u64 src_address, u64 size) {
  1169. LOG_DEBUG(Kernel_SVC,
  1170. "called. process_handle=0x{:08X}, dst_address=0x{:016X}, src_address=0x{:016X}, "
  1171. "size=0x{:016X}",
  1172. process_handle, dst_address, src_address, size);
  1173. if (!Common::Is4KBAligned(dst_address)) {
  1174. LOG_ERROR(Kernel_SVC, "dst_address is not page-aligned (dst_address=0x{:016X}).",
  1175. dst_address);
  1176. return ResultInvalidAddress;
  1177. }
  1178. if (!Common::Is4KBAligned(src_address)) {
  1179. LOG_ERROR(Kernel_SVC, "src_address is not page-aligned (src_address=0x{:016X}).",
  1180. src_address);
  1181. return ResultInvalidAddress;
  1182. }
  1183. if (size == 0 || Common::Is4KBAligned(size)) {
  1184. LOG_ERROR(Kernel_SVC, "Size is zero or not page-aligned (size=0x{:016X}).", size);
  1185. return ResultInvalidSize;
  1186. }
  1187. if (!IsValidAddressRange(dst_address, size)) {
  1188. LOG_ERROR(Kernel_SVC,
  1189. "Destination address range overflows the address space (dst_address=0x{:016X}, "
  1190. "size=0x{:016X}).",
  1191. dst_address, size);
  1192. return ResultInvalidCurrentMemory;
  1193. }
  1194. if (!IsValidAddressRange(src_address, size)) {
  1195. LOG_ERROR(Kernel_SVC,
  1196. "Source address range overflows the address space (src_address=0x{:016X}, "
  1197. "size=0x{:016X}).",
  1198. src_address, size);
  1199. return ResultInvalidCurrentMemory;
  1200. }
  1201. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1202. auto process = handle_table.Get<Process>(process_handle);
  1203. if (!process) {
  1204. LOG_ERROR(Kernel_SVC, "Invalid process handle specified (handle=0x{:08X}).",
  1205. process_handle);
  1206. return ResultInvalidHandle;
  1207. }
  1208. auto& page_table = process->PageTable();
  1209. if (!page_table.IsInsideAddressSpace(src_address, size)) {
  1210. LOG_ERROR(Kernel_SVC,
  1211. "Source address range is not within the address space (src_address=0x{:016X}, "
  1212. "size=0x{:016X}).",
  1213. src_address, size);
  1214. return ResultInvalidCurrentMemory;
  1215. }
  1216. if (!page_table.IsInsideASLRRegion(dst_address, size)) {
  1217. LOG_ERROR(Kernel_SVC,
  1218. "Destination address range is not within the ASLR region (dst_address=0x{:016X}, "
  1219. "size=0x{:016X}).",
  1220. dst_address, size);
  1221. return ResultInvalidMemoryRange;
  1222. }
  1223. return page_table.UnmapProcessCodeMemory(dst_address, src_address, size);
  1224. }
  1225. /// Exits the current process
  1226. static void ExitProcess(Core::System& system) {
  1227. auto* current_process = system.Kernel().CurrentProcess();
  1228. UNIMPLEMENTED();
  1229. LOG_INFO(Kernel_SVC, "Process {} exiting", current_process->GetProcessID());
  1230. ASSERT_MSG(current_process->GetStatus() == ProcessStatus::Running,
  1231. "Process has already exited");
  1232. current_process->PrepareForTermination();
  1233. // Kill the current thread
  1234. system.Kernel().CurrentScheduler()->GetCurrentThread()->Exit();
  1235. }
  1236. static void ExitProcess32(Core::System& system) {
  1237. ExitProcess(system);
  1238. }
  1239. static constexpr bool IsValidCoreId(int32_t core_id) {
  1240. return (0 <= core_id && core_id < static_cast<int32_t>(Core::Hardware::NUM_CPU_CORES));
  1241. }
  1242. /// Creates a new thread
  1243. static ResultCode CreateThread(Core::System& system, Handle* out_handle, VAddr entry_point, u64 arg,
  1244. VAddr stack_bottom, u32 priority, s32 core_id) {
  1245. LOG_DEBUG(Kernel_SVC,
  1246. "called entry_point=0x{:08X}, arg=0x{:08X}, stack_bottom=0x{:08X}, "
  1247. "priority=0x{:08X}, core_id=0x{:08X}",
  1248. entry_point, arg, stack_bottom, priority, core_id);
  1249. // Adjust core id, if it's the default magic.
  1250. auto& kernel = system.Kernel();
  1251. auto& process = *kernel.CurrentProcess();
  1252. if (core_id == IdealCoreUseProcessValue) {
  1253. core_id = process.GetIdealCoreId();
  1254. }
  1255. // Validate arguments.
  1256. if (!IsValidCoreId(core_id)) {
  1257. LOG_ERROR(Kernel_SVC, "Invalid Core ID specified (id={})", core_id);
  1258. return ResultInvalidCoreId;
  1259. }
  1260. if (((1ULL << core_id) & process.GetCoreMask()) == 0) {
  1261. LOG_ERROR(Kernel_SVC, "Core ID doesn't fall within allowable cores (id={})", core_id);
  1262. return ResultInvalidCoreId;
  1263. }
  1264. if (HighestThreadPriority > priority || priority > LowestThreadPriority) {
  1265. LOG_ERROR(Kernel_SVC, "Invalid priority specified (priority={})", priority);
  1266. return ResultInvalidPriority;
  1267. }
  1268. if (!process.CheckThreadPriority(priority)) {
  1269. LOG_ERROR(Kernel_SVC, "Invalid allowable thread priority (priority={})", priority);
  1270. return ResultInvalidPriority;
  1271. }
  1272. KScopedResourceReservation thread_reservation(
  1273. kernel.CurrentProcess(), LimitableResource::Threads, 1,
  1274. system.CoreTiming().GetGlobalTimeNs().count() + 100000000);
  1275. if (!thread_reservation.Succeeded()) {
  1276. LOG_ERROR(Kernel_SVC, "Could not reserve a new thread");
  1277. return ResultResourceLimitedExceeded;
  1278. }
  1279. std::shared_ptr<KThread> thread;
  1280. {
  1281. KScopedLightLock lk{process.GetStateLock()};
  1282. CASCADE_RESULT(thread, KThread::Create(system, ThreadType::User, "", entry_point, priority,
  1283. arg, core_id, stack_bottom, &process));
  1284. }
  1285. const auto new_thread_handle = process.GetHandleTable().Create(thread);
  1286. if (new_thread_handle.Failed()) {
  1287. LOG_ERROR(Kernel_SVC, "Failed to create handle with error=0x{:X}",
  1288. new_thread_handle.Code().raw);
  1289. return new_thread_handle.Code();
  1290. }
  1291. *out_handle = *new_thread_handle;
  1292. // Set the thread name for debugging purposes.
  1293. thread->SetName(
  1294. fmt::format("thread[entry_point={:X}, handle={:X}]", entry_point, *new_thread_handle));
  1295. thread_reservation.Commit();
  1296. return RESULT_SUCCESS;
  1297. }
  1298. static ResultCode CreateThread32(Core::System& system, Handle* out_handle, u32 priority,
  1299. u32 entry_point, u32 arg, u32 stack_top, s32 processor_id) {
  1300. return CreateThread(system, out_handle, entry_point, arg, stack_top, priority, processor_id);
  1301. }
  1302. /// Starts the thread for the provided handle
  1303. static ResultCode StartThread(Core::System& system, Handle thread_handle) {
  1304. LOG_DEBUG(Kernel_SVC, "called thread=0x{:08X}", thread_handle);
  1305. // Get the thread from its handle.
  1306. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1307. const std::shared_ptr<KThread> thread = handle_table.Get<KThread>(thread_handle);
  1308. if (!thread) {
  1309. LOG_ERROR(Kernel_SVC, "Invalid thread handle provided (handle={:08X})", thread_handle);
  1310. return ResultInvalidHandle;
  1311. }
  1312. // Try to start the thread.
  1313. const auto run_result = thread->Run();
  1314. if (run_result.IsError()) {
  1315. LOG_ERROR(Kernel_SVC,
  1316. "Unable to successfuly start thread (thread handle={:08X}, result={})",
  1317. thread_handle, run_result.raw);
  1318. return run_result;
  1319. }
  1320. return RESULT_SUCCESS;
  1321. }
  1322. static ResultCode StartThread32(Core::System& system, Handle thread_handle) {
  1323. return StartThread(system, thread_handle);
  1324. }
  1325. /// Called when a thread exits
  1326. static void ExitThread(Core::System& system) {
  1327. LOG_DEBUG(Kernel_SVC, "called, pc=0x{:08X}", system.CurrentArmInterface().GetPC());
  1328. auto* const current_thread = system.Kernel().CurrentScheduler()->GetCurrentThread();
  1329. system.GlobalSchedulerContext().RemoveThread(SharedFrom(current_thread));
  1330. current_thread->Exit();
  1331. }
  1332. static void ExitThread32(Core::System& system) {
  1333. ExitThread(system);
  1334. }
  1335. /// Sleep the current thread
  1336. static void SleepThread(Core::System& system, s64 nanoseconds) {
  1337. auto& kernel = system.Kernel();
  1338. const auto yield_type = static_cast<Svc::YieldType>(nanoseconds);
  1339. LOG_TRACE(Kernel_SVC, "called nanoseconds={}", nanoseconds);
  1340. // When the input tick is positive, sleep.
  1341. if (nanoseconds > 0) {
  1342. // Convert the timeout from nanoseconds to ticks.
  1343. // NOTE: Nintendo does not use this conversion logic in WaitSynchronization...
  1344. // Sleep.
  1345. // NOTE: Nintendo does not check the result of this sleep.
  1346. static_cast<void>(GetCurrentThread(kernel).Sleep(nanoseconds));
  1347. } else if (yield_type == Svc::YieldType::WithoutCoreMigration) {
  1348. KScheduler::YieldWithoutCoreMigration(kernel);
  1349. } else if (yield_type == Svc::YieldType::WithCoreMigration) {
  1350. KScheduler::YieldWithCoreMigration(kernel);
  1351. } else if (yield_type == Svc::YieldType::ToAnyThread) {
  1352. KScheduler::YieldToAnyThread(kernel);
  1353. } else {
  1354. // Nintendo does nothing at all if an otherwise invalid value is passed.
  1355. UNREACHABLE_MSG("Unimplemented sleep yield type '{:016X}'!", nanoseconds);
  1356. }
  1357. }
  1358. static void SleepThread32(Core::System& system, u32 nanoseconds_low, u32 nanoseconds_high) {
  1359. const auto nanoseconds = static_cast<s64>(u64{nanoseconds_low} | (u64{nanoseconds_high} << 32));
  1360. SleepThread(system, nanoseconds);
  1361. }
  1362. /// Wait process wide key atomic
  1363. static ResultCode WaitProcessWideKeyAtomic(Core::System& system, VAddr address, VAddr cv_key,
  1364. u32 tag, s64 timeout_ns) {
  1365. LOG_TRACE(Kernel_SVC, "called address={:X}, cv_key={:X}, tag=0x{:08X}, timeout_ns={}", address,
  1366. cv_key, tag, timeout_ns);
  1367. // Validate input.
  1368. if (IsKernelAddress(address)) {
  1369. LOG_ERROR(Kernel_SVC, "Attempted to wait on kernel address (address={:08X})", address);
  1370. return ResultInvalidCurrentMemory;
  1371. }
  1372. if (!Common::IsAligned(address, sizeof(s32))) {
  1373. LOG_ERROR(Kernel_SVC, "Address must be 4 byte aligned (address={:08X})", address);
  1374. return ResultInvalidAddress;
  1375. }
  1376. // Convert timeout from nanoseconds to ticks.
  1377. s64 timeout{};
  1378. if (timeout_ns > 0) {
  1379. const s64 offset_tick(timeout_ns);
  1380. if (offset_tick > 0) {
  1381. timeout = offset_tick + 2;
  1382. if (timeout <= 0) {
  1383. timeout = std::numeric_limits<s64>::max();
  1384. }
  1385. } else {
  1386. timeout = std::numeric_limits<s64>::max();
  1387. }
  1388. } else {
  1389. timeout = timeout_ns;
  1390. }
  1391. // Wait on the condition variable.
  1392. return system.Kernel().CurrentProcess()->WaitConditionVariable(
  1393. address, Common::AlignDown(cv_key, sizeof(u32)), tag, timeout);
  1394. }
  1395. static ResultCode WaitProcessWideKeyAtomic32(Core::System& system, u32 address, u32 cv_key, u32 tag,
  1396. u32 timeout_ns_low, u32 timeout_ns_high) {
  1397. const auto timeout_ns = static_cast<s64>(timeout_ns_low | (u64{timeout_ns_high} << 32));
  1398. return WaitProcessWideKeyAtomic(system, address, cv_key, tag, timeout_ns);
  1399. }
  1400. /// Signal process wide key
  1401. static void SignalProcessWideKey(Core::System& system, VAddr cv_key, s32 count) {
  1402. LOG_TRACE(Kernel_SVC, "called, cv_key=0x{:X}, count=0x{:08X}", cv_key, count);
  1403. // Signal the condition variable.
  1404. return system.Kernel().CurrentProcess()->SignalConditionVariable(
  1405. Common::AlignDown(cv_key, sizeof(u32)), count);
  1406. }
  1407. static void SignalProcessWideKey32(Core::System& system, u32 cv_key, s32 count) {
  1408. SignalProcessWideKey(system, cv_key, count);
  1409. }
  1410. namespace {
  1411. constexpr bool IsValidSignalType(Svc::SignalType type) {
  1412. switch (type) {
  1413. case Svc::SignalType::Signal:
  1414. case Svc::SignalType::SignalAndIncrementIfEqual:
  1415. case Svc::SignalType::SignalAndModifyByWaitingCountIfEqual:
  1416. return true;
  1417. default:
  1418. return false;
  1419. }
  1420. }
  1421. constexpr bool IsValidArbitrationType(Svc::ArbitrationType type) {
  1422. switch (type) {
  1423. case Svc::ArbitrationType::WaitIfLessThan:
  1424. case Svc::ArbitrationType::DecrementAndWaitIfLessThan:
  1425. case Svc::ArbitrationType::WaitIfEqual:
  1426. return true;
  1427. default:
  1428. return false;
  1429. }
  1430. }
  1431. } // namespace
  1432. // Wait for an address (via Address Arbiter)
  1433. static ResultCode WaitForAddress(Core::System& system, VAddr address, Svc::ArbitrationType arb_type,
  1434. s32 value, s64 timeout_ns) {
  1435. LOG_TRACE(Kernel_SVC, "called, address=0x{:X}, arb_type=0x{:X}, value=0x{:X}, timeout_ns={}",
  1436. address, arb_type, value, timeout_ns);
  1437. // Validate input.
  1438. if (IsKernelAddress(address)) {
  1439. LOG_ERROR(Kernel_SVC, "Attempting to wait on kernel address (address={:08X})", address);
  1440. return ResultInvalidCurrentMemory;
  1441. }
  1442. if (!Common::IsAligned(address, sizeof(s32))) {
  1443. LOG_ERROR(Kernel_SVC, "Wait address must be 4 byte aligned (address={:08X})", address);
  1444. return ResultInvalidAddress;
  1445. }
  1446. if (!IsValidArbitrationType(arb_type)) {
  1447. LOG_ERROR(Kernel_SVC, "Invalid arbitration type specified (type={})", arb_type);
  1448. return ResultInvalidEnumValue;
  1449. }
  1450. // Convert timeout from nanoseconds to ticks.
  1451. s64 timeout{};
  1452. if (timeout_ns > 0) {
  1453. const s64 offset_tick(timeout_ns);
  1454. if (offset_tick > 0) {
  1455. timeout = offset_tick + 2;
  1456. if (timeout <= 0) {
  1457. timeout = std::numeric_limits<s64>::max();
  1458. }
  1459. } else {
  1460. timeout = std::numeric_limits<s64>::max();
  1461. }
  1462. } else {
  1463. timeout = timeout_ns;
  1464. }
  1465. return system.Kernel().CurrentProcess()->WaitAddressArbiter(address, arb_type, value, timeout);
  1466. }
  1467. static ResultCode WaitForAddress32(Core::System& system, u32 address, Svc::ArbitrationType arb_type,
  1468. s32 value, u32 timeout_ns_low, u32 timeout_ns_high) {
  1469. const auto timeout = static_cast<s64>(timeout_ns_low | (u64{timeout_ns_high} << 32));
  1470. return WaitForAddress(system, address, arb_type, value, timeout);
  1471. }
  1472. // Signals to an address (via Address Arbiter)
  1473. static ResultCode SignalToAddress(Core::System& system, VAddr address, Svc::SignalType signal_type,
  1474. s32 value, s32 count) {
  1475. LOG_TRACE(Kernel_SVC, "called, address=0x{:X}, signal_type=0x{:X}, value=0x{:X}, count=0x{:X}",
  1476. address, signal_type, value, count);
  1477. // Validate input.
  1478. if (IsKernelAddress(address)) {
  1479. LOG_ERROR(Kernel_SVC, "Attempting to signal to a kernel address (address={:08X})", address);
  1480. return ResultInvalidCurrentMemory;
  1481. }
  1482. if (!Common::IsAligned(address, sizeof(s32))) {
  1483. LOG_ERROR(Kernel_SVC, "Signaled address must be 4 byte aligned (address={:08X})", address);
  1484. return ResultInvalidAddress;
  1485. }
  1486. if (!IsValidSignalType(signal_type)) {
  1487. LOG_ERROR(Kernel_SVC, "Invalid signal type specified (type={})", signal_type);
  1488. return ResultInvalidEnumValue;
  1489. }
  1490. return system.Kernel().CurrentProcess()->SignalAddressArbiter(address, signal_type, value,
  1491. count);
  1492. }
  1493. static ResultCode SignalToAddress32(Core::System& system, u32 address, Svc::SignalType signal_type,
  1494. s32 value, s32 count) {
  1495. return SignalToAddress(system, address, signal_type, value, count);
  1496. }
  1497. static void KernelDebug([[maybe_unused]] Core::System& system,
  1498. [[maybe_unused]] u32 kernel_debug_type, [[maybe_unused]] u64 param1,
  1499. [[maybe_unused]] u64 param2, [[maybe_unused]] u64 param3) {
  1500. // Intentionally do nothing, as this does nothing in released kernel binaries.
  1501. }
  1502. static void ChangeKernelTraceState([[maybe_unused]] Core::System& system,
  1503. [[maybe_unused]] u32 trace_state) {
  1504. // Intentionally do nothing, as this does nothing in released kernel binaries.
  1505. }
  1506. /// This returns the total CPU ticks elapsed since the CPU was powered-on
  1507. static u64 GetSystemTick(Core::System& system) {
  1508. LOG_TRACE(Kernel_SVC, "called");
  1509. auto& core_timing = system.CoreTiming();
  1510. // Returns the value of cntpct_el0 (https://switchbrew.org/wiki/SVC#svcGetSystemTick)
  1511. const u64 result{system.CoreTiming().GetClockTicks()};
  1512. if (!system.Kernel().IsMulticore()) {
  1513. core_timing.AddTicks(400U);
  1514. }
  1515. return result;
  1516. }
  1517. static void GetSystemTick32(Core::System& system, u32* time_low, u32* time_high) {
  1518. const auto time = GetSystemTick(system);
  1519. *time_low = static_cast<u32>(time);
  1520. *time_high = static_cast<u32>(time >> 32);
  1521. }
  1522. /// Close a handle
  1523. static ResultCode CloseHandle(Core::System& system, Handle handle) {
  1524. LOG_TRACE(Kernel_SVC, "Closing handle 0x{:08X}", handle);
  1525. auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1526. return handle_table.Close(handle);
  1527. }
  1528. static ResultCode CloseHandle32(Core::System& system, Handle handle) {
  1529. return CloseHandle(system, handle);
  1530. }
  1531. /// Clears the signaled state of an event or process.
  1532. static ResultCode ResetSignal(Core::System& system, Handle handle) {
  1533. LOG_DEBUG(Kernel_SVC, "called handle 0x{:08X}", handle);
  1534. // Get the current handle table.
  1535. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1536. // Try to reset as readable event.
  1537. {
  1538. auto readable_event = handle_table.Get<KReadableEvent>(handle);
  1539. if (readable_event) {
  1540. return readable_event->Reset();
  1541. }
  1542. }
  1543. // Try to reset as process.
  1544. {
  1545. auto process = handle_table.Get<Process>(handle);
  1546. if (process) {
  1547. return process->Reset();
  1548. }
  1549. }
  1550. LOG_ERROR(Kernel_SVC, "invalid handle (0x{:08X})", handle);
  1551. return ResultInvalidHandle;
  1552. }
  1553. static ResultCode ResetSignal32(Core::System& system, Handle handle) {
  1554. return ResetSignal(system, handle);
  1555. }
  1556. /// Creates a TransferMemory object
  1557. static ResultCode CreateTransferMemory(Core::System& system, Handle* handle, VAddr addr, u64 size,
  1558. u32 permissions) {
  1559. std::lock_guard lock{HLE::g_hle_lock};
  1560. LOG_DEBUG(Kernel_SVC, "called addr=0x{:X}, size=0x{:X}, perms=0x{:08X}", addr, size,
  1561. permissions);
  1562. if (!Common::Is4KBAligned(addr)) {
  1563. LOG_ERROR(Kernel_SVC, "Address ({:016X}) is not page aligned!", addr);
  1564. return ResultInvalidAddress;
  1565. }
  1566. if (!Common::Is4KBAligned(size) || size == 0) {
  1567. LOG_ERROR(Kernel_SVC, "Size ({:016X}) is not page aligned or equal to zero!", size);
  1568. return ResultInvalidAddress;
  1569. }
  1570. if (!IsValidAddressRange(addr, size)) {
  1571. LOG_ERROR(Kernel_SVC, "Address and size cause overflow! (address={:016X}, size={:016X})",
  1572. addr, size);
  1573. return ResultInvalidCurrentMemory;
  1574. }
  1575. const auto perms{static_cast<MemoryPermission>(permissions)};
  1576. if (perms > MemoryPermission::ReadWrite || perms == MemoryPermission::Write) {
  1577. LOG_ERROR(Kernel_SVC, "Invalid memory permissions for transfer memory! (perms={:08X})",
  1578. permissions);
  1579. return ResultInvalidMemoryPermissions;
  1580. }
  1581. auto& kernel = system.Kernel();
  1582. // Reserve a new transfer memory from the process resource limit.
  1583. KScopedResourceReservation trmem_reservation(kernel.CurrentProcess(),
  1584. LimitableResource::TransferMemory);
  1585. if (!trmem_reservation.Succeeded()) {
  1586. LOG_ERROR(Kernel_SVC, "Could not reserve a new transfer memory");
  1587. return ResultResourceLimitedExceeded;
  1588. }
  1589. auto transfer_mem_handle = TransferMemory::Create(kernel, system.Memory(), addr, size,
  1590. static_cast<KMemoryPermission>(perms));
  1591. if (const auto reserve_result{transfer_mem_handle->Reserve()}; reserve_result.IsError()) {
  1592. return reserve_result;
  1593. }
  1594. auto& handle_table = kernel.CurrentProcess()->GetHandleTable();
  1595. const auto result{handle_table.Create(std::move(transfer_mem_handle))};
  1596. if (result.Failed()) {
  1597. return result.Code();
  1598. }
  1599. trmem_reservation.Commit();
  1600. *handle = *result;
  1601. return RESULT_SUCCESS;
  1602. }
  1603. static ResultCode CreateTransferMemory32(Core::System& system, Handle* handle, u32 addr, u32 size,
  1604. u32 permissions) {
  1605. return CreateTransferMemory(system, handle, addr, size, permissions);
  1606. }
  1607. static ResultCode GetThreadCoreMask(Core::System& system, Handle thread_handle, s32* out_core_id,
  1608. u64* out_affinity_mask) {
  1609. LOG_TRACE(Kernel_SVC, "called, handle=0x{:08X}", thread_handle);
  1610. // Get the thread from its handle.
  1611. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1612. const std::shared_ptr<KThread> thread = handle_table.Get<KThread>(thread_handle);
  1613. if (!thread) {
  1614. LOG_ERROR(Kernel_SVC, "Invalid thread handle specified (handle={:08X})", thread_handle);
  1615. return ResultInvalidHandle;
  1616. }
  1617. // Get the core mask.
  1618. const auto result = thread->GetCoreMask(out_core_id, out_affinity_mask);
  1619. if (result.IsError()) {
  1620. LOG_ERROR(Kernel_SVC, "Unable to successfully retrieve core mask (result={})", result.raw);
  1621. return result;
  1622. }
  1623. return RESULT_SUCCESS;
  1624. }
  1625. static ResultCode GetThreadCoreMask32(Core::System& system, Handle thread_handle, s32* out_core_id,
  1626. u32* out_affinity_mask_low, u32* out_affinity_mask_high) {
  1627. u64 out_affinity_mask{};
  1628. const auto result = GetThreadCoreMask(system, thread_handle, out_core_id, &out_affinity_mask);
  1629. *out_affinity_mask_high = static_cast<u32>(out_affinity_mask >> 32);
  1630. *out_affinity_mask_low = static_cast<u32>(out_affinity_mask);
  1631. return result;
  1632. }
  1633. static ResultCode SetThreadCoreMask(Core::System& system, Handle thread_handle, s32 core_id,
  1634. u64 affinity_mask) {
  1635. LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, core_id=0x{:X}, affinity_mask=0x{:016X}",
  1636. thread_handle, core_id, affinity_mask);
  1637. const auto& current_process = *system.Kernel().CurrentProcess();
  1638. // Determine the core id/affinity mask.
  1639. if (core_id == Svc::IdealCoreUseProcessValue) {
  1640. core_id = current_process.GetIdealCoreId();
  1641. affinity_mask = (1ULL << core_id);
  1642. } else {
  1643. // Validate the affinity mask.
  1644. const u64 process_core_mask = current_process.GetCoreMask();
  1645. if ((affinity_mask | process_core_mask) != process_core_mask) {
  1646. LOG_ERROR(Kernel_SVC,
  1647. "Affinity mask does match the process core mask (affinity mask={:016X}, core "
  1648. "mask={:016X})",
  1649. affinity_mask, process_core_mask);
  1650. return ResultInvalidCoreId;
  1651. }
  1652. if (affinity_mask == 0) {
  1653. LOG_ERROR(Kernel_SVC, "Affinity mask is zero.");
  1654. return ResultInvalidCombination;
  1655. }
  1656. // Validate the core id.
  1657. if (IsValidCoreId(core_id)) {
  1658. if (((1ULL << core_id) & affinity_mask) == 0) {
  1659. LOG_ERROR(Kernel_SVC, "Invalid core ID (ID={})", core_id);
  1660. return ResultInvalidCombination;
  1661. }
  1662. } else {
  1663. if (core_id != IdealCoreNoUpdate && core_id != IdealCoreDontCare) {
  1664. LOG_ERROR(Kernel_SVC, "Invalid core ID (ID={})", core_id);
  1665. return ResultInvalidCoreId;
  1666. }
  1667. }
  1668. }
  1669. // Get the thread from its handle.
  1670. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1671. const std::shared_ptr<KThread> thread = handle_table.Get<KThread>(thread_handle);
  1672. if (!thread) {
  1673. LOG_ERROR(Kernel_SVC, "Invalid thread handle (handle={:08X})", thread_handle);
  1674. return ResultInvalidHandle;
  1675. }
  1676. // Set the core mask.
  1677. const auto set_result = thread->SetCoreMask(core_id, affinity_mask);
  1678. if (set_result.IsError()) {
  1679. LOG_ERROR(Kernel_SVC, "Unable to successfully set core mask (result={})", set_result.raw);
  1680. return set_result;
  1681. }
  1682. return RESULT_SUCCESS;
  1683. }
  1684. static ResultCode SetThreadCoreMask32(Core::System& system, Handle thread_handle, s32 core_id,
  1685. u32 affinity_mask_low, u32 affinity_mask_high) {
  1686. const auto affinity_mask = u64{affinity_mask_low} | (u64{affinity_mask_high} << 32);
  1687. return SetThreadCoreMask(system, thread_handle, core_id, affinity_mask);
  1688. }
  1689. static ResultCode SignalEvent(Core::System& system, Handle event_handle) {
  1690. LOG_DEBUG(Kernel_SVC, "called, event_handle=0x{:08X}", event_handle);
  1691. auto& kernel = system.Kernel();
  1692. // Get the current handle table.
  1693. const HandleTable& handle_table = kernel.CurrentProcess()->GetHandleTable();
  1694. // Reserve a new event from the process resource limit.
  1695. KScopedResourceReservation event_reservation(kernel.CurrentProcess(),
  1696. LimitableResource::Events);
  1697. if (!event_reservation.Succeeded()) {
  1698. LOG_ERROR(Kernel, "Could not reserve a new event");
  1699. return ResultResourceLimitedExceeded;
  1700. }
  1701. // Get the writable event.
  1702. auto writable_event = handle_table.Get<KWritableEvent>(event_handle);
  1703. if (!writable_event) {
  1704. LOG_ERROR(Kernel_SVC, "Invalid event handle provided (handle={:08X})", event_handle);
  1705. return ResultInvalidHandle;
  1706. }
  1707. // Commit the successfuly reservation.
  1708. event_reservation.Commit();
  1709. return writable_event->Signal();
  1710. }
  1711. static ResultCode SignalEvent32(Core::System& system, Handle event_handle) {
  1712. return SignalEvent(system, event_handle);
  1713. }
  1714. static ResultCode ClearEvent(Core::System& system, Handle event_handle) {
  1715. LOG_TRACE(Kernel_SVC, "called, event_handle=0x{:08X}", event_handle);
  1716. // Get the current handle table.
  1717. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1718. // Try to clear the writable event.
  1719. {
  1720. auto writable_event = handle_table.Get<KWritableEvent>(event_handle);
  1721. if (writable_event) {
  1722. return writable_event->Clear();
  1723. }
  1724. }
  1725. // Try to clear the readable event.
  1726. {
  1727. auto readable_event = handle_table.Get<KReadableEvent>(event_handle);
  1728. if (readable_event) {
  1729. return readable_event->Clear();
  1730. }
  1731. }
  1732. LOG_ERROR(Kernel_SVC, "Event handle does not exist, event_handle=0x{:08X}", event_handle);
  1733. return ResultInvalidHandle;
  1734. }
  1735. static ResultCode ClearEvent32(Core::System& system, Handle event_handle) {
  1736. return ClearEvent(system, event_handle);
  1737. }
  1738. static ResultCode CreateEvent(Core::System& system, Handle* out_write, Handle* out_read) {
  1739. LOG_DEBUG(Kernel_SVC, "called");
  1740. // Get the kernel reference and handle table.
  1741. auto& kernel = system.Kernel();
  1742. HandleTable& handle_table = kernel.CurrentProcess()->GetHandleTable();
  1743. // Create a new event.
  1744. const auto event = KEvent::Create(kernel, "CreateEvent");
  1745. if (!event) {
  1746. LOG_ERROR(Kernel_SVC, "Unable to create new events. Event creation limit reached.");
  1747. return ResultOutOfResource;
  1748. }
  1749. // Initialize the event.
  1750. event->Initialize();
  1751. // Add the writable event to the handle table.
  1752. const auto write_create_result = handle_table.Create(event->GetWritableEvent());
  1753. if (write_create_result.Failed()) {
  1754. return write_create_result.Code();
  1755. }
  1756. *out_write = *write_create_result;
  1757. // Add the writable event to the handle table.
  1758. auto handle_guard = SCOPE_GUARD({ handle_table.Close(*write_create_result); });
  1759. // Add the readable event to the handle table.
  1760. const auto read_create_result = handle_table.Create(event->GetReadableEvent());
  1761. if (read_create_result.Failed()) {
  1762. return read_create_result.Code();
  1763. }
  1764. *out_read = *read_create_result;
  1765. // We succeeded.
  1766. handle_guard.Cancel();
  1767. return RESULT_SUCCESS;
  1768. }
  1769. static ResultCode CreateEvent32(Core::System& system, Handle* out_write, Handle* out_read) {
  1770. return CreateEvent(system, out_write, out_read);
  1771. }
  1772. static ResultCode GetProcessInfo(Core::System& system, u64* out, Handle process_handle, u32 type) {
  1773. LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, type=0x{:X}", process_handle, type);
  1774. // This function currently only allows retrieving a process' status.
  1775. enum class InfoType {
  1776. Status,
  1777. };
  1778. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1779. const auto process = handle_table.Get<Process>(process_handle);
  1780. if (!process) {
  1781. LOG_ERROR(Kernel_SVC, "Process handle does not exist, process_handle=0x{:08X}",
  1782. process_handle);
  1783. return ResultInvalidHandle;
  1784. }
  1785. const auto info_type = static_cast<InfoType>(type);
  1786. if (info_type != InfoType::Status) {
  1787. LOG_ERROR(Kernel_SVC, "Expected info_type to be Status but got {} instead", type);
  1788. return ResultInvalidEnumValue;
  1789. }
  1790. *out = static_cast<u64>(process->GetStatus());
  1791. return RESULT_SUCCESS;
  1792. }
  1793. static ResultCode CreateResourceLimit(Core::System& system, Handle* out_handle) {
  1794. std::lock_guard lock{HLE::g_hle_lock};
  1795. LOG_DEBUG(Kernel_SVC, "called");
  1796. auto& kernel = system.Kernel();
  1797. auto resource_limit = std::make_shared<KResourceLimit>(kernel, system);
  1798. auto* const current_process = kernel.CurrentProcess();
  1799. ASSERT(current_process != nullptr);
  1800. const auto handle = current_process->GetHandleTable().Create(std::move(resource_limit));
  1801. if (handle.Failed()) {
  1802. return handle.Code();
  1803. }
  1804. *out_handle = *handle;
  1805. return RESULT_SUCCESS;
  1806. }
  1807. static ResultCode GetResourceLimitLimitValue(Core::System& system, u64* out_value,
  1808. Handle resource_limit, u32 resource_type) {
  1809. LOG_DEBUG(Kernel_SVC, "called. Handle={:08X}, Resource type={}", resource_limit, resource_type);
  1810. const auto limit_value = RetrieveResourceLimitValue(system, resource_limit, resource_type,
  1811. ResourceLimitValueType::LimitValue);
  1812. if (limit_value.Failed()) {
  1813. return limit_value.Code();
  1814. }
  1815. *out_value = static_cast<u64>(*limit_value);
  1816. return RESULT_SUCCESS;
  1817. }
  1818. static ResultCode GetResourceLimitCurrentValue(Core::System& system, u64* out_value,
  1819. Handle resource_limit, u32 resource_type) {
  1820. LOG_DEBUG(Kernel_SVC, "called. Handle={:08X}, Resource type={}", resource_limit, resource_type);
  1821. const auto current_value = RetrieveResourceLimitValue(system, resource_limit, resource_type,
  1822. ResourceLimitValueType::CurrentValue);
  1823. if (current_value.Failed()) {
  1824. return current_value.Code();
  1825. }
  1826. *out_value = static_cast<u64>(*current_value);
  1827. return RESULT_SUCCESS;
  1828. }
  1829. static ResultCode SetResourceLimitLimitValue(Core::System& system, Handle resource_limit,
  1830. u32 resource_type, u64 value) {
  1831. LOG_DEBUG(Kernel_SVC, "called. Handle={:08X}, Resource type={}, Value={}", resource_limit,
  1832. resource_type, value);
  1833. const auto type = static_cast<LimitableResource>(resource_type);
  1834. if (!IsValidResourceType(type)) {
  1835. LOG_ERROR(Kernel_SVC, "Invalid resource limit type: '{}'", resource_type);
  1836. return ResultInvalidEnumValue;
  1837. }
  1838. auto* const current_process = system.Kernel().CurrentProcess();
  1839. ASSERT(current_process != nullptr);
  1840. auto resource_limit_object =
  1841. current_process->GetHandleTable().Get<KResourceLimit>(resource_limit);
  1842. if (!resource_limit_object) {
  1843. LOG_ERROR(Kernel_SVC, "Handle to non-existent resource limit instance used. Handle={:08X}",
  1844. resource_limit);
  1845. return ResultInvalidHandle;
  1846. }
  1847. const auto set_result = resource_limit_object->SetLimitValue(type, static_cast<s64>(value));
  1848. if (set_result.IsError()) {
  1849. LOG_ERROR(Kernel_SVC,
  1850. "Attempted to lower resource limit ({}) for category '{}' below its current "
  1851. "value ({})",
  1852. resource_limit_object->GetLimitValue(type), resource_type,
  1853. resource_limit_object->GetCurrentValue(type));
  1854. return set_result;
  1855. }
  1856. return RESULT_SUCCESS;
  1857. }
  1858. static ResultCode GetProcessList(Core::System& system, u32* out_num_processes,
  1859. VAddr out_process_ids, u32 out_process_ids_size) {
  1860. LOG_DEBUG(Kernel_SVC, "called. out_process_ids=0x{:016X}, out_process_ids_size={}",
  1861. out_process_ids, out_process_ids_size);
  1862. // If the supplied size is negative or greater than INT32_MAX / sizeof(u64), bail.
  1863. if ((out_process_ids_size & 0xF0000000) != 0) {
  1864. LOG_ERROR(Kernel_SVC,
  1865. "Supplied size outside [0, 0x0FFFFFFF] range. out_process_ids_size={}",
  1866. out_process_ids_size);
  1867. return ResultOutOfRange;
  1868. }
  1869. const auto& kernel = system.Kernel();
  1870. const auto total_copy_size = out_process_ids_size * sizeof(u64);
  1871. if (out_process_ids_size > 0 && !kernel.CurrentProcess()->PageTable().IsInsideAddressSpace(
  1872. out_process_ids, total_copy_size)) {
  1873. LOG_ERROR(Kernel_SVC, "Address range outside address space. begin=0x{:016X}, end=0x{:016X}",
  1874. out_process_ids, out_process_ids + total_copy_size);
  1875. return ResultInvalidCurrentMemory;
  1876. }
  1877. auto& memory = system.Memory();
  1878. const auto& process_list = kernel.GetProcessList();
  1879. const auto num_processes = process_list.size();
  1880. const auto copy_amount = std::min(std::size_t{out_process_ids_size}, num_processes);
  1881. for (std::size_t i = 0; i < copy_amount; ++i) {
  1882. memory.Write64(out_process_ids, process_list[i]->GetProcessID());
  1883. out_process_ids += sizeof(u64);
  1884. }
  1885. *out_num_processes = static_cast<u32>(num_processes);
  1886. return RESULT_SUCCESS;
  1887. }
  1888. static ResultCode GetThreadList(Core::System& system, u32* out_num_threads, VAddr out_thread_ids,
  1889. u32 out_thread_ids_size, Handle debug_handle) {
  1890. // TODO: Handle this case when debug events are supported.
  1891. UNIMPLEMENTED_IF(debug_handle != InvalidHandle);
  1892. LOG_DEBUG(Kernel_SVC, "called. out_thread_ids=0x{:016X}, out_thread_ids_size={}",
  1893. out_thread_ids, out_thread_ids_size);
  1894. // If the size is negative or larger than INT32_MAX / sizeof(u64)
  1895. if ((out_thread_ids_size & 0xF0000000) != 0) {
  1896. LOG_ERROR(Kernel_SVC, "Supplied size outside [0, 0x0FFFFFFF] range. size={}",
  1897. out_thread_ids_size);
  1898. return ResultOutOfRange;
  1899. }
  1900. const auto* const current_process = system.Kernel().CurrentProcess();
  1901. const auto total_copy_size = out_thread_ids_size * sizeof(u64);
  1902. if (out_thread_ids_size > 0 &&
  1903. !current_process->PageTable().IsInsideAddressSpace(out_thread_ids, total_copy_size)) {
  1904. LOG_ERROR(Kernel_SVC, "Address range outside address space. begin=0x{:016X}, end=0x{:016X}",
  1905. out_thread_ids, out_thread_ids + total_copy_size);
  1906. return ResultInvalidCurrentMemory;
  1907. }
  1908. auto& memory = system.Memory();
  1909. const auto& thread_list = current_process->GetThreadList();
  1910. const auto num_threads = thread_list.size();
  1911. const auto copy_amount = std::min(std::size_t{out_thread_ids_size}, num_threads);
  1912. auto list_iter = thread_list.cbegin();
  1913. for (std::size_t i = 0; i < copy_amount; ++i, ++list_iter) {
  1914. memory.Write64(out_thread_ids, (*list_iter)->GetThreadID());
  1915. out_thread_ids += sizeof(u64);
  1916. }
  1917. *out_num_threads = static_cast<u32>(num_threads);
  1918. return RESULT_SUCCESS;
  1919. }
  1920. static ResultCode FlushProcessDataCache32([[maybe_unused]] Core::System& system,
  1921. [[maybe_unused]] Handle handle,
  1922. [[maybe_unused]] u32 address, [[maybe_unused]] u32 size) {
  1923. // Note(Blinkhawk): For emulation purposes of the data cache this is mostly a no-op,
  1924. // as all emulation is done in the same cache level in host architecture, thus data cache
  1925. // does not need flushing.
  1926. LOG_DEBUG(Kernel_SVC, "called");
  1927. return RESULT_SUCCESS;
  1928. }
  1929. namespace {
  1930. struct FunctionDef {
  1931. using Func = void(Core::System&);
  1932. u32 id;
  1933. Func* func;
  1934. const char* name;
  1935. };
  1936. } // namespace
  1937. static const FunctionDef SVC_Table_32[] = {
  1938. {0x00, nullptr, "Unknown"},
  1939. {0x01, SvcWrap32<SetHeapSize32>, "SetHeapSize32"},
  1940. {0x02, nullptr, "Unknown"},
  1941. {0x03, SvcWrap32<SetMemoryAttribute32>, "SetMemoryAttribute32"},
  1942. {0x04, SvcWrap32<MapMemory32>, "MapMemory32"},
  1943. {0x05, SvcWrap32<UnmapMemory32>, "UnmapMemory32"},
  1944. {0x06, SvcWrap32<QueryMemory32>, "QueryMemory32"},
  1945. {0x07, SvcWrap32<ExitProcess32>, "ExitProcess32"},
  1946. {0x08, SvcWrap32<CreateThread32>, "CreateThread32"},
  1947. {0x09, SvcWrap32<StartThread32>, "StartThread32"},
  1948. {0x0a, SvcWrap32<ExitThread32>, "ExitThread32"},
  1949. {0x0b, SvcWrap32<SleepThread32>, "SleepThread32"},
  1950. {0x0c, SvcWrap32<GetThreadPriority32>, "GetThreadPriority32"},
  1951. {0x0d, SvcWrap32<SetThreadPriority32>, "SetThreadPriority32"},
  1952. {0x0e, SvcWrap32<GetThreadCoreMask32>, "GetThreadCoreMask32"},
  1953. {0x0f, SvcWrap32<SetThreadCoreMask32>, "SetThreadCoreMask32"},
  1954. {0x10, SvcWrap32<GetCurrentProcessorNumber32>, "GetCurrentProcessorNumber32"},
  1955. {0x11, SvcWrap32<SignalEvent32>, "SignalEvent32"},
  1956. {0x12, SvcWrap32<ClearEvent32>, "ClearEvent32"},
  1957. {0x13, SvcWrap32<MapSharedMemory32>, "MapSharedMemory32"},
  1958. {0x14, nullptr, "UnmapSharedMemory32"},
  1959. {0x15, SvcWrap32<CreateTransferMemory32>, "CreateTransferMemory32"},
  1960. {0x16, SvcWrap32<CloseHandle32>, "CloseHandle32"},
  1961. {0x17, SvcWrap32<ResetSignal32>, "ResetSignal32"},
  1962. {0x18, SvcWrap32<WaitSynchronization32>, "WaitSynchronization32"},
  1963. {0x19, SvcWrap32<CancelSynchronization32>, "CancelSynchronization32"},
  1964. {0x1a, SvcWrap32<ArbitrateLock32>, "ArbitrateLock32"},
  1965. {0x1b, SvcWrap32<ArbitrateUnlock32>, "ArbitrateUnlock32"},
  1966. {0x1c, SvcWrap32<WaitProcessWideKeyAtomic32>, "WaitProcessWideKeyAtomic32"},
  1967. {0x1d, SvcWrap32<SignalProcessWideKey32>, "SignalProcessWideKey32"},
  1968. {0x1e, SvcWrap32<GetSystemTick32>, "GetSystemTick32"},
  1969. {0x1f, SvcWrap32<ConnectToNamedPort32>, "ConnectToNamedPort32"},
  1970. {0x20, nullptr, "Unknown"},
  1971. {0x21, SvcWrap32<SendSyncRequest32>, "SendSyncRequest32"},
  1972. {0x22, nullptr, "SendSyncRequestWithUserBuffer32"},
  1973. {0x23, nullptr, "Unknown"},
  1974. {0x24, SvcWrap32<GetProcessId32>, "GetProcessId32"},
  1975. {0x25, SvcWrap32<GetThreadId32>, "GetThreadId32"},
  1976. {0x26, SvcWrap32<Break32>, "Break32"},
  1977. {0x27, nullptr, "OutputDebugString32"},
  1978. {0x28, nullptr, "Unknown"},
  1979. {0x29, SvcWrap32<GetInfo32>, "GetInfo32"},
  1980. {0x2a, nullptr, "Unknown"},
  1981. {0x2b, nullptr, "Unknown"},
  1982. {0x2c, SvcWrap32<MapPhysicalMemory32>, "MapPhysicalMemory32"},
  1983. {0x2d, SvcWrap32<UnmapPhysicalMemory32>, "UnmapPhysicalMemory32"},
  1984. {0x2e, nullptr, "Unknown"},
  1985. {0x2f, nullptr, "Unknown"},
  1986. {0x30, nullptr, "Unknown"},
  1987. {0x31, nullptr, "Unknown"},
  1988. {0x32, SvcWrap32<SetThreadActivity32>, "SetThreadActivity32"},
  1989. {0x33, SvcWrap32<GetThreadContext32>, "GetThreadContext32"},
  1990. {0x34, SvcWrap32<WaitForAddress32>, "WaitForAddress32"},
  1991. {0x35, SvcWrap32<SignalToAddress32>, "SignalToAddress32"},
  1992. {0x36, nullptr, "Unknown"},
  1993. {0x37, nullptr, "Unknown"},
  1994. {0x38, nullptr, "Unknown"},
  1995. {0x39, nullptr, "Unknown"},
  1996. {0x3a, nullptr, "Unknown"},
  1997. {0x3b, nullptr, "Unknown"},
  1998. {0x3c, nullptr, "Unknown"},
  1999. {0x3d, nullptr, "Unknown"},
  2000. {0x3e, nullptr, "Unknown"},
  2001. {0x3f, nullptr, "Unknown"},
  2002. {0x40, nullptr, "CreateSession32"},
  2003. {0x41, nullptr, "AcceptSession32"},
  2004. {0x42, nullptr, "Unknown"},
  2005. {0x43, nullptr, "ReplyAndReceive32"},
  2006. {0x44, nullptr, "Unknown"},
  2007. {0x45, SvcWrap32<CreateEvent32>, "CreateEvent32"},
  2008. {0x46, nullptr, "Unknown"},
  2009. {0x47, nullptr, "Unknown"},
  2010. {0x48, nullptr, "Unknown"},
  2011. {0x49, nullptr, "Unknown"},
  2012. {0x4a, nullptr, "Unknown"},
  2013. {0x4b, nullptr, "Unknown"},
  2014. {0x4c, nullptr, "Unknown"},
  2015. {0x4d, nullptr, "Unknown"},
  2016. {0x4e, nullptr, "Unknown"},
  2017. {0x4f, nullptr, "Unknown"},
  2018. {0x50, nullptr, "Unknown"},
  2019. {0x51, nullptr, "Unknown"},
  2020. {0x52, nullptr, "Unknown"},
  2021. {0x53, nullptr, "Unknown"},
  2022. {0x54, nullptr, "Unknown"},
  2023. {0x55, nullptr, "Unknown"},
  2024. {0x56, nullptr, "Unknown"},
  2025. {0x57, nullptr, "Unknown"},
  2026. {0x58, nullptr, "Unknown"},
  2027. {0x59, nullptr, "Unknown"},
  2028. {0x5a, nullptr, "Unknown"},
  2029. {0x5b, nullptr, "Unknown"},
  2030. {0x5c, nullptr, "Unknown"},
  2031. {0x5d, nullptr, "Unknown"},
  2032. {0x5e, nullptr, "Unknown"},
  2033. {0x5F, SvcWrap32<FlushProcessDataCache32>, "FlushProcessDataCache32"},
  2034. {0x60, nullptr, "Unknown"},
  2035. {0x61, nullptr, "Unknown"},
  2036. {0x62, nullptr, "Unknown"},
  2037. {0x63, nullptr, "Unknown"},
  2038. {0x64, nullptr, "Unknown"},
  2039. {0x65, nullptr, "GetProcessList32"},
  2040. {0x66, nullptr, "Unknown"},
  2041. {0x67, nullptr, "Unknown"},
  2042. {0x68, nullptr, "Unknown"},
  2043. {0x69, nullptr, "Unknown"},
  2044. {0x6A, nullptr, "Unknown"},
  2045. {0x6B, nullptr, "Unknown"},
  2046. {0x6C, nullptr, "Unknown"},
  2047. {0x6D, nullptr, "Unknown"},
  2048. {0x6E, nullptr, "Unknown"},
  2049. {0x6f, nullptr, "GetSystemInfo32"},
  2050. {0x70, nullptr, "CreatePort32"},
  2051. {0x71, nullptr, "ManageNamedPort32"},
  2052. {0x72, nullptr, "ConnectToPort32"},
  2053. {0x73, nullptr, "SetProcessMemoryPermission32"},
  2054. {0x74, nullptr, "Unknown"},
  2055. {0x75, nullptr, "Unknown"},
  2056. {0x76, nullptr, "Unknown"},
  2057. {0x77, nullptr, "MapProcessCodeMemory32"},
  2058. {0x78, nullptr, "UnmapProcessCodeMemory32"},
  2059. {0x79, nullptr, "Unknown"},
  2060. {0x7A, nullptr, "Unknown"},
  2061. {0x7B, nullptr, "TerminateProcess32"},
  2062. };
  2063. static const FunctionDef SVC_Table_64[] = {
  2064. {0x00, nullptr, "Unknown"},
  2065. {0x01, SvcWrap64<SetHeapSize>, "SetHeapSize"},
  2066. {0x02, nullptr, "SetMemoryPermission"},
  2067. {0x03, SvcWrap64<SetMemoryAttribute>, "SetMemoryAttribute"},
  2068. {0x04, SvcWrap64<MapMemory>, "MapMemory"},
  2069. {0x05, SvcWrap64<UnmapMemory>, "UnmapMemory"},
  2070. {0x06, SvcWrap64<QueryMemory>, "QueryMemory"},
  2071. {0x07, SvcWrap64<ExitProcess>, "ExitProcess"},
  2072. {0x08, SvcWrap64<CreateThread>, "CreateThread"},
  2073. {0x09, SvcWrap64<StartThread>, "StartThread"},
  2074. {0x0A, SvcWrap64<ExitThread>, "ExitThread"},
  2075. {0x0B, SvcWrap64<SleepThread>, "SleepThread"},
  2076. {0x0C, SvcWrap64<GetThreadPriority>, "GetThreadPriority"},
  2077. {0x0D, SvcWrap64<SetThreadPriority>, "SetThreadPriority"},
  2078. {0x0E, SvcWrap64<GetThreadCoreMask>, "GetThreadCoreMask"},
  2079. {0x0F, SvcWrap64<SetThreadCoreMask>, "SetThreadCoreMask"},
  2080. {0x10, SvcWrap64<GetCurrentProcessorNumber>, "GetCurrentProcessorNumber"},
  2081. {0x11, SvcWrap64<SignalEvent>, "SignalEvent"},
  2082. {0x12, SvcWrap64<ClearEvent>, "ClearEvent"},
  2083. {0x13, SvcWrap64<MapSharedMemory>, "MapSharedMemory"},
  2084. {0x14, nullptr, "UnmapSharedMemory"},
  2085. {0x15, SvcWrap64<CreateTransferMemory>, "CreateTransferMemory"},
  2086. {0x16, SvcWrap64<CloseHandle>, "CloseHandle"},
  2087. {0x17, SvcWrap64<ResetSignal>, "ResetSignal"},
  2088. {0x18, SvcWrap64<WaitSynchronization>, "WaitSynchronization"},
  2089. {0x19, SvcWrap64<CancelSynchronization>, "CancelSynchronization"},
  2090. {0x1A, SvcWrap64<ArbitrateLock>, "ArbitrateLock"},
  2091. {0x1B, SvcWrap64<ArbitrateUnlock>, "ArbitrateUnlock"},
  2092. {0x1C, SvcWrap64<WaitProcessWideKeyAtomic>, "WaitProcessWideKeyAtomic"},
  2093. {0x1D, SvcWrap64<SignalProcessWideKey>, "SignalProcessWideKey"},
  2094. {0x1E, SvcWrap64<GetSystemTick>, "GetSystemTick"},
  2095. {0x1F, SvcWrap64<ConnectToNamedPort>, "ConnectToNamedPort"},
  2096. {0x20, nullptr, "SendSyncRequestLight"},
  2097. {0x21, SvcWrap64<SendSyncRequest>, "SendSyncRequest"},
  2098. {0x22, nullptr, "SendSyncRequestWithUserBuffer"},
  2099. {0x23, nullptr, "SendAsyncRequestWithUserBuffer"},
  2100. {0x24, SvcWrap64<GetProcessId>, "GetProcessId"},
  2101. {0x25, SvcWrap64<GetThreadId>, "GetThreadId"},
  2102. {0x26, SvcWrap64<Break>, "Break"},
  2103. {0x27, SvcWrap64<OutputDebugString>, "OutputDebugString"},
  2104. {0x28, nullptr, "ReturnFromException"},
  2105. {0x29, SvcWrap64<GetInfo>, "GetInfo"},
  2106. {0x2A, nullptr, "FlushEntireDataCache"},
  2107. {0x2B, nullptr, "FlushDataCache"},
  2108. {0x2C, SvcWrap64<MapPhysicalMemory>, "MapPhysicalMemory"},
  2109. {0x2D, SvcWrap64<UnmapPhysicalMemory>, "UnmapPhysicalMemory"},
  2110. {0x2E, nullptr, "GetFutureThreadInfo"},
  2111. {0x2F, nullptr, "GetLastThreadInfo"},
  2112. {0x30, SvcWrap64<GetResourceLimitLimitValue>, "GetResourceLimitLimitValue"},
  2113. {0x31, SvcWrap64<GetResourceLimitCurrentValue>, "GetResourceLimitCurrentValue"},
  2114. {0x32, SvcWrap64<SetThreadActivity>, "SetThreadActivity"},
  2115. {0x33, SvcWrap64<GetThreadContext>, "GetThreadContext"},
  2116. {0x34, SvcWrap64<WaitForAddress>, "WaitForAddress"},
  2117. {0x35, SvcWrap64<SignalToAddress>, "SignalToAddress"},
  2118. {0x36, nullptr, "SynchronizePreemptionState"},
  2119. {0x37, nullptr, "Unknown"},
  2120. {0x38, nullptr, "Unknown"},
  2121. {0x39, nullptr, "Unknown"},
  2122. {0x3A, nullptr, "Unknown"},
  2123. {0x3B, nullptr, "Unknown"},
  2124. {0x3C, SvcWrap64<KernelDebug>, "KernelDebug"},
  2125. {0x3D, SvcWrap64<ChangeKernelTraceState>, "ChangeKernelTraceState"},
  2126. {0x3E, nullptr, "Unknown"},
  2127. {0x3F, nullptr, "Unknown"},
  2128. {0x40, nullptr, "CreateSession"},
  2129. {0x41, nullptr, "AcceptSession"},
  2130. {0x42, nullptr, "ReplyAndReceiveLight"},
  2131. {0x43, nullptr, "ReplyAndReceive"},
  2132. {0x44, nullptr, "ReplyAndReceiveWithUserBuffer"},
  2133. {0x45, SvcWrap64<CreateEvent>, "CreateEvent"},
  2134. {0x46, nullptr, "Unknown"},
  2135. {0x47, nullptr, "Unknown"},
  2136. {0x48, nullptr, "MapPhysicalMemoryUnsafe"},
  2137. {0x49, nullptr, "UnmapPhysicalMemoryUnsafe"},
  2138. {0x4A, nullptr, "SetUnsafeLimit"},
  2139. {0x4B, nullptr, "CreateCodeMemory"},
  2140. {0x4C, nullptr, "ControlCodeMemory"},
  2141. {0x4D, nullptr, "SleepSystem"},
  2142. {0x4E, nullptr, "ReadWriteRegister"},
  2143. {0x4F, nullptr, "SetProcessActivity"},
  2144. {0x50, nullptr, "CreateSharedMemory"},
  2145. {0x51, nullptr, "MapTransferMemory"},
  2146. {0x52, nullptr, "UnmapTransferMemory"},
  2147. {0x53, nullptr, "CreateInterruptEvent"},
  2148. {0x54, nullptr, "QueryPhysicalAddress"},
  2149. {0x55, nullptr, "QueryIoMapping"},
  2150. {0x56, nullptr, "CreateDeviceAddressSpace"},
  2151. {0x57, nullptr, "AttachDeviceAddressSpace"},
  2152. {0x58, nullptr, "DetachDeviceAddressSpace"},
  2153. {0x59, nullptr, "MapDeviceAddressSpaceByForce"},
  2154. {0x5A, nullptr, "MapDeviceAddressSpaceAligned"},
  2155. {0x5B, nullptr, "MapDeviceAddressSpace"},
  2156. {0x5C, nullptr, "UnmapDeviceAddressSpace"},
  2157. {0x5D, nullptr, "InvalidateProcessDataCache"},
  2158. {0x5E, nullptr, "StoreProcessDataCache"},
  2159. {0x5F, nullptr, "FlushProcessDataCache"},
  2160. {0x60, nullptr, "DebugActiveProcess"},
  2161. {0x61, nullptr, "BreakDebugProcess"},
  2162. {0x62, nullptr, "TerminateDebugProcess"},
  2163. {0x63, nullptr, "GetDebugEvent"},
  2164. {0x64, nullptr, "ContinueDebugEvent"},
  2165. {0x65, SvcWrap64<GetProcessList>, "GetProcessList"},
  2166. {0x66, SvcWrap64<GetThreadList>, "GetThreadList"},
  2167. {0x67, nullptr, "GetDebugThreadContext"},
  2168. {0x68, nullptr, "SetDebugThreadContext"},
  2169. {0x69, nullptr, "QueryDebugProcessMemory"},
  2170. {0x6A, nullptr, "ReadDebugProcessMemory"},
  2171. {0x6B, nullptr, "WriteDebugProcessMemory"},
  2172. {0x6C, nullptr, "SetHardwareBreakPoint"},
  2173. {0x6D, nullptr, "GetDebugThreadParam"},
  2174. {0x6E, nullptr, "Unknown"},
  2175. {0x6F, nullptr, "GetSystemInfo"},
  2176. {0x70, nullptr, "CreatePort"},
  2177. {0x71, nullptr, "ManageNamedPort"},
  2178. {0x72, nullptr, "ConnectToPort"},
  2179. {0x73, nullptr, "SetProcessMemoryPermission"},
  2180. {0x74, nullptr, "MapProcessMemory"},
  2181. {0x75, nullptr, "UnmapProcessMemory"},
  2182. {0x76, SvcWrap64<QueryProcessMemory>, "QueryProcessMemory"},
  2183. {0x77, SvcWrap64<MapProcessCodeMemory>, "MapProcessCodeMemory"},
  2184. {0x78, SvcWrap64<UnmapProcessCodeMemory>, "UnmapProcessCodeMemory"},
  2185. {0x79, nullptr, "CreateProcess"},
  2186. {0x7A, nullptr, "StartProcess"},
  2187. {0x7B, nullptr, "TerminateProcess"},
  2188. {0x7C, SvcWrap64<GetProcessInfo>, "GetProcessInfo"},
  2189. {0x7D, SvcWrap64<CreateResourceLimit>, "CreateResourceLimit"},
  2190. {0x7E, SvcWrap64<SetResourceLimitLimitValue>, "SetResourceLimitLimitValue"},
  2191. {0x7F, nullptr, "CallSecureMonitor"},
  2192. };
  2193. static const FunctionDef* GetSVCInfo32(u32 func_num) {
  2194. if (func_num >= std::size(SVC_Table_32)) {
  2195. LOG_ERROR(Kernel_SVC, "Unknown svc=0x{:02X}", func_num);
  2196. return nullptr;
  2197. }
  2198. return &SVC_Table_32[func_num];
  2199. }
  2200. static const FunctionDef* GetSVCInfo64(u32 func_num) {
  2201. if (func_num >= std::size(SVC_Table_64)) {
  2202. LOG_ERROR(Kernel_SVC, "Unknown svc=0x{:02X}", func_num);
  2203. return nullptr;
  2204. }
  2205. return &SVC_Table_64[func_num];
  2206. }
  2207. void Call(Core::System& system, u32 immediate) {
  2208. system.ExitDynarmicProfile();
  2209. auto& kernel = system.Kernel();
  2210. kernel.EnterSVCProfile();
  2211. auto* thread = kernel.CurrentScheduler()->GetCurrentThread();
  2212. thread->SetIsCallingSvc();
  2213. const FunctionDef* info = system.CurrentProcess()->Is64BitProcess() ? GetSVCInfo64(immediate)
  2214. : GetSVCInfo32(immediate);
  2215. if (info) {
  2216. if (info->func) {
  2217. info->func(system);
  2218. } else {
  2219. LOG_CRITICAL(Kernel_SVC, "Unimplemented SVC function {}(..)", info->name);
  2220. }
  2221. } else {
  2222. LOG_CRITICAL(Kernel_SVC, "Unknown SVC function 0x{:X}", immediate);
  2223. }
  2224. kernel.ExitSVCProfile();
  2225. if (!thread->IsCallingSvc()) {
  2226. thread->GetHostContext()->Rewind();
  2227. }
  2228. system.EnterDynarmicProfile();
  2229. }
  2230. } // namespace Kernel::Svc