svc.cpp 114 KB

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