svc.cpp 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997
  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. R_UNLESS(address == static_cast<uintptr_t>(address), ResultInvalidCurrentMemory);
  1075. R_UNLESS(size == static_cast<size_t>(size), ResultInvalidCurrentMemory);
  1076. // Validate the memory permission.
  1077. R_UNLESS(IsValidProcessMemoryPermission(perm), ResultInvalidNewMemoryPermission);
  1078. // Get the process from its handle.
  1079. KScopedAutoObject process =
  1080. system.CurrentProcess()->GetHandleTable().GetObject<KProcess>(process_handle);
  1081. R_UNLESS(process.IsNotNull(), ResultInvalidHandle);
  1082. // Validate that the address is in range.
  1083. auto& page_table = process->PageTable();
  1084. R_UNLESS(page_table.Contains(address, size), ResultInvalidCurrentMemory);
  1085. // Set the memory permission.
  1086. return page_table.SetProcessMemoryPermission(address, size, perm);
  1087. }
  1088. static ResultCode MapProcessMemory(Core::System& system, VAddr dst_address, Handle process_handle,
  1089. VAddr src_address, u64 size) {
  1090. LOG_TRACE(Kernel_SVC,
  1091. "called, dst_address=0x{:X}, process_handle=0x{:X}, src_address=0x{:X}, size=0x{:X}",
  1092. dst_address, process_handle, src_address, size);
  1093. // Validate the address/size.
  1094. R_UNLESS(Common::IsAligned(dst_address, PageSize), ResultInvalidAddress);
  1095. R_UNLESS(Common::IsAligned(src_address, PageSize), ResultInvalidAddress);
  1096. R_UNLESS(Common::IsAligned(size, PageSize), ResultInvalidSize);
  1097. R_UNLESS(size > 0, ResultInvalidSize);
  1098. R_UNLESS((dst_address < dst_address + size), ResultInvalidCurrentMemory);
  1099. R_UNLESS((src_address < src_address + size), ResultInvalidCurrentMemory);
  1100. // Get the processes.
  1101. KProcess* dst_process = system.CurrentProcess();
  1102. KScopedAutoObject src_process =
  1103. dst_process->GetHandleTable().GetObjectWithoutPseudoHandle<KProcess>(process_handle);
  1104. R_UNLESS(src_process.IsNotNull(), ResultInvalidHandle);
  1105. // Get the page tables.
  1106. auto& dst_pt = dst_process->PageTable();
  1107. auto& src_pt = src_process->PageTable();
  1108. // Validate that the mapping is in range.
  1109. R_UNLESS(src_pt.Contains(src_address, size), ResultInvalidCurrentMemory);
  1110. R_UNLESS(dst_pt.CanContain(dst_address, size, KMemoryState::SharedCode),
  1111. ResultInvalidMemoryRegion);
  1112. // Create a new page group.
  1113. KMemoryInfo kBlockInfo = dst_pt.QueryInfo(dst_address);
  1114. KPageLinkedList pg(kBlockInfo.GetAddress(), kBlockInfo.GetNumPages());
  1115. // Map the group.
  1116. R_TRY(dst_pt.MapPages(dst_address, pg, KMemoryState::SharedCode,
  1117. KMemoryPermission::UserReadWrite));
  1118. return ResultSuccess;
  1119. }
  1120. static ResultCode UnmapProcessMemory(Core::System& system, VAddr dst_address, Handle process_handle,
  1121. VAddr src_address, u64 size) {
  1122. LOG_TRACE(Kernel_SVC,
  1123. "called, dst_address=0x{:X}, process_handle=0x{:X}, src_address=0x{:X}, size=0x{:X}",
  1124. dst_address, process_handle, src_address, size);
  1125. // Validate the address/size.
  1126. R_UNLESS(Common::IsAligned(dst_address, PageSize), ResultInvalidAddress);
  1127. R_UNLESS(Common::IsAligned(src_address, PageSize), ResultInvalidAddress);
  1128. R_UNLESS(Common::IsAligned(size, PageSize), ResultInvalidSize);
  1129. R_UNLESS(size > 0, ResultInvalidSize);
  1130. R_UNLESS((dst_address < dst_address + size), ResultInvalidCurrentMemory);
  1131. R_UNLESS((src_address < src_address + size), ResultInvalidCurrentMemory);
  1132. // Get the processes.
  1133. KProcess* dst_process = system.CurrentProcess();
  1134. KScopedAutoObject src_process =
  1135. dst_process->GetHandleTable().GetObjectWithoutPseudoHandle<KProcess>(process_handle);
  1136. R_UNLESS(src_process.IsNotNull(), ResultInvalidHandle);
  1137. // Get the page tables.
  1138. auto& dst_pt = dst_process->PageTable();
  1139. auto& src_pt = src_process->PageTable();
  1140. // Validate that the mapping is in range.
  1141. R_UNLESS(src_pt.Contains(src_address, size), ResultInvalidCurrentMemory);
  1142. R_UNLESS(dst_pt.CanContain(dst_address, size, KMemoryState::SharedCode),
  1143. ResultInvalidMemoryRegion);
  1144. // Unmap the memory.
  1145. R_TRY(dst_pt.UnmapProcessMemory(dst_address, size, src_pt, src_address));
  1146. return ResultSuccess;
  1147. }
  1148. static ResultCode CreateCodeMemory(Core::System& system, Handle* out, VAddr address, size_t size) {
  1149. LOG_TRACE(Kernel_SVC, "called, handle_out=0x{:X}, address=0x{:X}, size=0x{:X}",
  1150. static_cast<void*>(out), address, size);
  1151. // Get kernel instance.
  1152. auto& kernel = system.Kernel();
  1153. // Validate address / size.
  1154. R_UNLESS(Common::IsAligned(address, PageSize), ResultInvalidAddress);
  1155. R_UNLESS(Common::IsAligned(size, PageSize), ResultInvalidSize);
  1156. R_UNLESS(size > 0, ResultInvalidSize);
  1157. R_UNLESS((address < address + size), ResultInvalidCurrentMemory);
  1158. // Create the code memory.
  1159. KCodeMemory* code_mem = KCodeMemory::Create(kernel);
  1160. R_UNLESS(code_mem != nullptr, ResultOutOfResource);
  1161. // Verify that the region is in range.
  1162. R_UNLESS(system.CurrentProcess()->PageTable().Contains(address, size),
  1163. ResultInvalidCurrentMemory);
  1164. // Initialize the code memory.
  1165. R_TRY(code_mem->Initialize(system.DeviceMemory(), address, size));
  1166. // Register the code memory.
  1167. KCodeMemory::Register(kernel, code_mem);
  1168. // Add the code memory to the handle table.
  1169. R_TRY(system.CurrentProcess()->GetHandleTable().Add(out, code_mem));
  1170. code_mem->Close();
  1171. return ResultSuccess;
  1172. }
  1173. static ResultCode ControlCodeMemory(Core::System& system, Handle code_memory_handle, u32 operation,
  1174. VAddr address, size_t size, Svc::MemoryPermission perm) {
  1175. LOG_TRACE(Kernel_SVC,
  1176. "called, code_memory_handle=0x{:X}, operation=0x{:X}, address=0x{:X}, size=0x{:X}, "
  1177. "permission=0x{:X}",
  1178. code_memory_handle, operation, address, size, perm);
  1179. // Validate the address / size.
  1180. R_UNLESS(Common::IsAligned(address, PageSize), ResultInvalidAddress);
  1181. R_UNLESS(Common::IsAligned(size, PageSize), ResultInvalidSize);
  1182. R_UNLESS(size > 0, ResultInvalidSize);
  1183. R_UNLESS((address < address + size), ResultInvalidCurrentMemory);
  1184. // Get the code memory from its handle.
  1185. KScopedAutoObject code_mem =
  1186. system.CurrentProcess()->GetHandleTable().GetObject<KCodeMemory>(code_memory_handle);
  1187. R_UNLESS(code_mem.IsNotNull(), ResultInvalidHandle);
  1188. // NOTE: Here, Atmosphere extends the SVC to allow code memory operations on one's own process.
  1189. // This enables homebrew usage of these SVCs for JIT.
  1190. // Perform the operation.
  1191. switch (static_cast<CodeMemoryOperation>(operation)) {
  1192. case CodeMemoryOperation::Map: {
  1193. // Check that the region is in range.
  1194. R_UNLESS(
  1195. system.CurrentProcess()->PageTable().CanContain(address, size, KMemoryState::CodeOut),
  1196. ResultInvalidMemoryRegion);
  1197. // Check the memory permission.
  1198. R_UNLESS(IsValidMapCodeMemoryPermission(perm), ResultInvalidNewMemoryPermission);
  1199. // Map the memory.
  1200. R_TRY(code_mem->Map(address, size));
  1201. } break;
  1202. case CodeMemoryOperation::Unmap: {
  1203. // Check that the region is in range.
  1204. R_UNLESS(
  1205. system.CurrentProcess()->PageTable().CanContain(address, size, KMemoryState::CodeOut),
  1206. ResultInvalidMemoryRegion);
  1207. // Check the memory permission.
  1208. R_UNLESS(IsValidUnmapCodeMemoryPermission(perm), ResultInvalidNewMemoryPermission);
  1209. // Unmap the memory.
  1210. R_TRY(code_mem->Unmap(address, size));
  1211. } break;
  1212. case CodeMemoryOperation::MapToOwner: {
  1213. // Check that the region is in range.
  1214. R_UNLESS(code_mem->GetOwner()->PageTable().CanContain(address, size,
  1215. KMemoryState::GeneratedCode),
  1216. ResultInvalidMemoryRegion);
  1217. // Check the memory permission.
  1218. R_UNLESS(IsValidMapToOwnerCodeMemoryPermission(perm), ResultInvalidNewMemoryPermission);
  1219. // Map the memory to its owner.
  1220. R_TRY(code_mem->MapToOwner(address, size, perm));
  1221. } break;
  1222. case CodeMemoryOperation::UnmapFromOwner: {
  1223. // Check that the region is in range.
  1224. R_UNLESS(code_mem->GetOwner()->PageTable().CanContain(address, size,
  1225. KMemoryState::GeneratedCode),
  1226. ResultInvalidMemoryRegion);
  1227. // Check the memory permission.
  1228. R_UNLESS(IsValidUnmapFromOwnerCodeMemoryPermission(perm), ResultInvalidNewMemoryPermission);
  1229. // Unmap the memory from its owner.
  1230. R_TRY(code_mem->UnmapFromOwner(address, size));
  1231. } break;
  1232. default:
  1233. return ResultInvalidEnumValue;
  1234. }
  1235. return ResultSuccess;
  1236. }
  1237. static ResultCode QueryProcessMemory(Core::System& system, VAddr memory_info_address,
  1238. VAddr page_info_address, Handle process_handle,
  1239. VAddr address) {
  1240. LOG_TRACE(Kernel_SVC, "called process=0x{:08X} address={:X}", process_handle, address);
  1241. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1242. KScopedAutoObject process = handle_table.GetObject<KProcess>(process_handle);
  1243. if (process.IsNull()) {
  1244. LOG_ERROR(Kernel_SVC, "Process handle does not exist, process_handle=0x{:08X}",
  1245. process_handle);
  1246. return ResultInvalidHandle;
  1247. }
  1248. auto& memory{system.Memory()};
  1249. const auto memory_info{process->PageTable().QueryInfo(address).GetSvcMemoryInfo()};
  1250. memory.Write64(memory_info_address + 0x00, memory_info.addr);
  1251. memory.Write64(memory_info_address + 0x08, memory_info.size);
  1252. memory.Write32(memory_info_address + 0x10, static_cast<u32>(memory_info.state) & 0xff);
  1253. memory.Write32(memory_info_address + 0x14, static_cast<u32>(memory_info.attr));
  1254. memory.Write32(memory_info_address + 0x18, static_cast<u32>(memory_info.perm));
  1255. memory.Write32(memory_info_address + 0x1c, memory_info.ipc_refcount);
  1256. memory.Write32(memory_info_address + 0x20, memory_info.device_refcount);
  1257. memory.Write32(memory_info_address + 0x24, 0);
  1258. // Page info appears to be currently unused by the kernel and is always set to zero.
  1259. memory.Write32(page_info_address, 0);
  1260. return ResultSuccess;
  1261. }
  1262. static ResultCode QueryMemory(Core::System& system, VAddr memory_info_address,
  1263. VAddr page_info_address, VAddr query_address) {
  1264. LOG_TRACE(Kernel_SVC,
  1265. "called, memory_info_address=0x{:016X}, page_info_address=0x{:016X}, "
  1266. "query_address=0x{:016X}",
  1267. memory_info_address, page_info_address, query_address);
  1268. return QueryProcessMemory(system, memory_info_address, page_info_address, CurrentProcess,
  1269. query_address);
  1270. }
  1271. static ResultCode QueryMemory32(Core::System& system, u32 memory_info_address,
  1272. u32 page_info_address, u32 query_address) {
  1273. return QueryMemory(system, memory_info_address, page_info_address, query_address);
  1274. }
  1275. static ResultCode MapProcessCodeMemory(Core::System& system, Handle process_handle, u64 dst_address,
  1276. u64 src_address, u64 size) {
  1277. LOG_DEBUG(Kernel_SVC,
  1278. "called. process_handle=0x{:08X}, dst_address=0x{:016X}, "
  1279. "src_address=0x{:016X}, size=0x{:016X}",
  1280. process_handle, dst_address, src_address, size);
  1281. if (!Common::Is4KBAligned(src_address)) {
  1282. LOG_ERROR(Kernel_SVC, "src_address is not page-aligned (src_address=0x{:016X}).",
  1283. src_address);
  1284. return ResultInvalidAddress;
  1285. }
  1286. if (!Common::Is4KBAligned(dst_address)) {
  1287. LOG_ERROR(Kernel_SVC, "dst_address is not page-aligned (dst_address=0x{:016X}).",
  1288. dst_address);
  1289. return ResultInvalidAddress;
  1290. }
  1291. if (size == 0 || !Common::Is4KBAligned(size)) {
  1292. LOG_ERROR(Kernel_SVC, "Size is zero or not page-aligned (size=0x{:016X})", size);
  1293. return ResultInvalidSize;
  1294. }
  1295. if (!IsValidAddressRange(dst_address, size)) {
  1296. LOG_ERROR(Kernel_SVC,
  1297. "Destination address range overflows the address space (dst_address=0x{:016X}, "
  1298. "size=0x{:016X}).",
  1299. dst_address, size);
  1300. return ResultInvalidCurrentMemory;
  1301. }
  1302. if (!IsValidAddressRange(src_address, size)) {
  1303. LOG_ERROR(Kernel_SVC,
  1304. "Source address range overflows the address space (src_address=0x{:016X}, "
  1305. "size=0x{:016X}).",
  1306. src_address, size);
  1307. return ResultInvalidCurrentMemory;
  1308. }
  1309. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1310. KScopedAutoObject process = handle_table.GetObject<KProcess>(process_handle);
  1311. if (process.IsNull()) {
  1312. LOG_ERROR(Kernel_SVC, "Invalid process handle specified (handle=0x{:08X}).",
  1313. process_handle);
  1314. return ResultInvalidHandle;
  1315. }
  1316. auto& page_table = process->PageTable();
  1317. if (!page_table.IsInsideAddressSpace(src_address, size)) {
  1318. LOG_ERROR(Kernel_SVC,
  1319. "Source address range is not within the address space (src_address=0x{:016X}, "
  1320. "size=0x{:016X}).",
  1321. src_address, size);
  1322. return ResultInvalidCurrentMemory;
  1323. }
  1324. if (!page_table.IsInsideASLRRegion(dst_address, size)) {
  1325. LOG_ERROR(Kernel_SVC,
  1326. "Destination address range is not within the ASLR region (dst_address=0x{:016X}, "
  1327. "size=0x{:016X}).",
  1328. dst_address, size);
  1329. return ResultInvalidMemoryRegion;
  1330. }
  1331. return page_table.MapCodeMemory(dst_address, src_address, size);
  1332. }
  1333. static ResultCode UnmapProcessCodeMemory(Core::System& system, Handle process_handle,
  1334. u64 dst_address, u64 src_address, u64 size) {
  1335. LOG_DEBUG(Kernel_SVC,
  1336. "called. process_handle=0x{:08X}, dst_address=0x{:016X}, src_address=0x{:016X}, "
  1337. "size=0x{:016X}",
  1338. process_handle, dst_address, src_address, size);
  1339. if (!Common::Is4KBAligned(dst_address)) {
  1340. LOG_ERROR(Kernel_SVC, "dst_address is not page-aligned (dst_address=0x{:016X}).",
  1341. dst_address);
  1342. return ResultInvalidAddress;
  1343. }
  1344. if (!Common::Is4KBAligned(src_address)) {
  1345. LOG_ERROR(Kernel_SVC, "src_address is not page-aligned (src_address=0x{:016X}).",
  1346. src_address);
  1347. return ResultInvalidAddress;
  1348. }
  1349. if (size == 0 || Common::Is4KBAligned(size)) {
  1350. LOG_ERROR(Kernel_SVC, "Size is zero or not page-aligned (size=0x{:016X}).", size);
  1351. return ResultInvalidSize;
  1352. }
  1353. if (!IsValidAddressRange(dst_address, size)) {
  1354. LOG_ERROR(Kernel_SVC,
  1355. "Destination address range overflows the address space (dst_address=0x{:016X}, "
  1356. "size=0x{:016X}).",
  1357. dst_address, size);
  1358. return ResultInvalidCurrentMemory;
  1359. }
  1360. if (!IsValidAddressRange(src_address, size)) {
  1361. LOG_ERROR(Kernel_SVC,
  1362. "Source address range overflows the address space (src_address=0x{:016X}, "
  1363. "size=0x{:016X}).",
  1364. src_address, size);
  1365. return ResultInvalidCurrentMemory;
  1366. }
  1367. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1368. KScopedAutoObject process = handle_table.GetObject<KProcess>(process_handle);
  1369. if (process.IsNull()) {
  1370. LOG_ERROR(Kernel_SVC, "Invalid process handle specified (handle=0x{:08X}).",
  1371. process_handle);
  1372. return ResultInvalidHandle;
  1373. }
  1374. auto& page_table = process->PageTable();
  1375. if (!page_table.IsInsideAddressSpace(src_address, size)) {
  1376. LOG_ERROR(Kernel_SVC,
  1377. "Source address range is not within the address space (src_address=0x{:016X}, "
  1378. "size=0x{:016X}).",
  1379. src_address, size);
  1380. return ResultInvalidCurrentMemory;
  1381. }
  1382. if (!page_table.IsInsideASLRRegion(dst_address, size)) {
  1383. LOG_ERROR(Kernel_SVC,
  1384. "Destination address range is not within the ASLR region (dst_address=0x{:016X}, "
  1385. "size=0x{:016X}).",
  1386. dst_address, size);
  1387. return ResultInvalidMemoryRegion;
  1388. }
  1389. return page_table.UnmapCodeMemory(dst_address, src_address, size);
  1390. }
  1391. /// Exits the current process
  1392. static void ExitProcess(Core::System& system) {
  1393. auto* current_process = system.Kernel().CurrentProcess();
  1394. UNIMPLEMENTED();
  1395. LOG_INFO(Kernel_SVC, "Process {} exiting", current_process->GetProcessID());
  1396. ASSERT_MSG(current_process->GetStatus() == ProcessStatus::Running,
  1397. "Process has already exited");
  1398. }
  1399. static void ExitProcess32(Core::System& system) {
  1400. ExitProcess(system);
  1401. }
  1402. namespace {
  1403. constexpr bool IsValidVirtualCoreId(int32_t core_id) {
  1404. return (0 <= core_id && core_id < static_cast<int32_t>(Core::Hardware::NUM_CPU_CORES));
  1405. }
  1406. } // Anonymous namespace
  1407. /// Creates a new thread
  1408. static ResultCode CreateThread(Core::System& system, Handle* out_handle, VAddr entry_point, u64 arg,
  1409. VAddr stack_bottom, u32 priority, s32 core_id) {
  1410. LOG_DEBUG(Kernel_SVC,
  1411. "called entry_point=0x{:08X}, arg=0x{:08X}, stack_bottom=0x{:08X}, "
  1412. "priority=0x{:08X}, core_id=0x{:08X}",
  1413. entry_point, arg, stack_bottom, priority, core_id);
  1414. // Adjust core id, if it's the default magic.
  1415. auto& kernel = system.Kernel();
  1416. auto& process = *kernel.CurrentProcess();
  1417. if (core_id == IdealCoreUseProcessValue) {
  1418. core_id = process.GetIdealCoreId();
  1419. }
  1420. // Validate arguments.
  1421. if (!IsValidVirtualCoreId(core_id)) {
  1422. LOG_ERROR(Kernel_SVC, "Invalid Core ID specified (id={})", core_id);
  1423. return ResultInvalidCoreId;
  1424. }
  1425. if (((1ULL << core_id) & process.GetCoreMask()) == 0) {
  1426. LOG_ERROR(Kernel_SVC, "Core ID doesn't fall within allowable cores (id={})", core_id);
  1427. return ResultInvalidCoreId;
  1428. }
  1429. if (HighestThreadPriority > priority || priority > LowestThreadPriority) {
  1430. LOG_ERROR(Kernel_SVC, "Invalid priority specified (priority={})", priority);
  1431. return ResultInvalidPriority;
  1432. }
  1433. if (!process.CheckThreadPriority(priority)) {
  1434. LOG_ERROR(Kernel_SVC, "Invalid allowable thread priority (priority={})", priority);
  1435. return ResultInvalidPriority;
  1436. }
  1437. // Reserve a new thread from the process resource limit (waiting up to 100ms).
  1438. KScopedResourceReservation thread_reservation(
  1439. kernel.CurrentProcess(), LimitableResource::Threads, 1,
  1440. system.CoreTiming().GetGlobalTimeNs().count() + 100000000);
  1441. if (!thread_reservation.Succeeded()) {
  1442. LOG_ERROR(Kernel_SVC, "Could not reserve a new thread");
  1443. return ResultLimitReached;
  1444. }
  1445. // Create the thread.
  1446. KThread* thread = KThread::Create(kernel);
  1447. if (!thread) {
  1448. LOG_ERROR(Kernel_SVC, "Unable to create new threads. Thread creation limit reached.");
  1449. return ResultOutOfResource;
  1450. }
  1451. SCOPE_EXIT({ thread->Close(); });
  1452. // Initialize the thread.
  1453. {
  1454. KScopedLightLock lk{process.GetStateLock()};
  1455. R_TRY(KThread::InitializeUserThread(system, thread, entry_point, arg, stack_bottom,
  1456. priority, core_id, &process));
  1457. }
  1458. // Set the thread name for debugging purposes.
  1459. thread->SetName(fmt::format("thread[entry_point={:X}, handle={:X}]", entry_point, *out_handle));
  1460. // Commit the thread reservation.
  1461. thread_reservation.Commit();
  1462. // Register the new thread.
  1463. KThread::Register(kernel, thread);
  1464. // Add the thread to the handle table.
  1465. R_TRY(process.GetHandleTable().Add(out_handle, thread));
  1466. return ResultSuccess;
  1467. }
  1468. static ResultCode CreateThread32(Core::System& system, Handle* out_handle, u32 priority,
  1469. u32 entry_point, u32 arg, u32 stack_top, s32 processor_id) {
  1470. return CreateThread(system, out_handle, entry_point, arg, stack_top, priority, processor_id);
  1471. }
  1472. /// Starts the thread for the provided handle
  1473. static ResultCode StartThread(Core::System& system, Handle thread_handle) {
  1474. LOG_DEBUG(Kernel_SVC, "called thread=0x{:08X}", thread_handle);
  1475. // Get the thread from its handle.
  1476. KScopedAutoObject thread =
  1477. system.Kernel().CurrentProcess()->GetHandleTable().GetObject<KThread>(thread_handle);
  1478. R_UNLESS(thread.IsNotNull(), ResultInvalidHandle);
  1479. // Try to start the thread.
  1480. R_TRY(thread->Run());
  1481. // If we succeeded, persist a reference to the thread.
  1482. thread->Open();
  1483. system.Kernel().RegisterInUseObject(thread.GetPointerUnsafe());
  1484. return ResultSuccess;
  1485. }
  1486. static ResultCode StartThread32(Core::System& system, Handle thread_handle) {
  1487. return StartThread(system, thread_handle);
  1488. }
  1489. /// Called when a thread exits
  1490. static void ExitThread(Core::System& system) {
  1491. LOG_DEBUG(Kernel_SVC, "called, pc=0x{:08X}", system.CurrentArmInterface().GetPC());
  1492. auto* const current_thread = system.Kernel().CurrentScheduler()->GetCurrentThread();
  1493. system.GlobalSchedulerContext().RemoveThread(current_thread);
  1494. current_thread->Exit();
  1495. system.Kernel().UnregisterInUseObject(current_thread);
  1496. }
  1497. static void ExitThread32(Core::System& system) {
  1498. ExitThread(system);
  1499. }
  1500. /// Sleep the current thread
  1501. static void SleepThread(Core::System& system, s64 nanoseconds) {
  1502. auto& kernel = system.Kernel();
  1503. const auto yield_type = static_cast<Svc::YieldType>(nanoseconds);
  1504. LOG_TRACE(Kernel_SVC, "called nanoseconds={}", nanoseconds);
  1505. // When the input tick is positive, sleep.
  1506. if (nanoseconds > 0) {
  1507. // Convert the timeout from nanoseconds to ticks.
  1508. // NOTE: Nintendo does not use this conversion logic in WaitSynchronization...
  1509. // Sleep.
  1510. // NOTE: Nintendo does not check the result of this sleep.
  1511. static_cast<void>(GetCurrentThread(kernel).Sleep(nanoseconds));
  1512. } else if (yield_type == Svc::YieldType::WithoutCoreMigration) {
  1513. KScheduler::YieldWithoutCoreMigration(kernel);
  1514. } else if (yield_type == Svc::YieldType::WithCoreMigration) {
  1515. KScheduler::YieldWithCoreMigration(kernel);
  1516. } else if (yield_type == Svc::YieldType::ToAnyThread) {
  1517. KScheduler::YieldToAnyThread(kernel);
  1518. } else {
  1519. // Nintendo does nothing at all if an otherwise invalid value is passed.
  1520. UNREACHABLE_MSG("Unimplemented sleep yield type '{:016X}'!", nanoseconds);
  1521. }
  1522. }
  1523. static void SleepThread32(Core::System& system, u32 nanoseconds_low, u32 nanoseconds_high) {
  1524. const auto nanoseconds = static_cast<s64>(u64{nanoseconds_low} | (u64{nanoseconds_high} << 32));
  1525. SleepThread(system, nanoseconds);
  1526. }
  1527. /// Wait process wide key atomic
  1528. static ResultCode WaitProcessWideKeyAtomic(Core::System& system, VAddr address, VAddr cv_key,
  1529. u32 tag, s64 timeout_ns) {
  1530. LOG_TRACE(Kernel_SVC, "called address={:X}, cv_key={:X}, tag=0x{:08X}, timeout_ns={}", address,
  1531. cv_key, tag, timeout_ns);
  1532. // Validate input.
  1533. if (IsKernelAddress(address)) {
  1534. LOG_ERROR(Kernel_SVC, "Attempted to wait on kernel address (address={:08X})", address);
  1535. return ResultInvalidCurrentMemory;
  1536. }
  1537. if (!Common::IsAligned(address, sizeof(s32))) {
  1538. LOG_ERROR(Kernel_SVC, "Address must be 4 byte aligned (address={:08X})", address);
  1539. return ResultInvalidAddress;
  1540. }
  1541. // Convert timeout from nanoseconds to ticks.
  1542. s64 timeout{};
  1543. if (timeout_ns > 0) {
  1544. const s64 offset_tick(timeout_ns);
  1545. if (offset_tick > 0) {
  1546. timeout = offset_tick + 2;
  1547. if (timeout <= 0) {
  1548. timeout = std::numeric_limits<s64>::max();
  1549. }
  1550. } else {
  1551. timeout = std::numeric_limits<s64>::max();
  1552. }
  1553. } else {
  1554. timeout = timeout_ns;
  1555. }
  1556. // Wait on the condition variable.
  1557. return system.Kernel().CurrentProcess()->WaitConditionVariable(
  1558. address, Common::AlignDown(cv_key, sizeof(u32)), tag, timeout);
  1559. }
  1560. static ResultCode WaitProcessWideKeyAtomic32(Core::System& system, u32 address, u32 cv_key, u32 tag,
  1561. u32 timeout_ns_low, u32 timeout_ns_high) {
  1562. const auto timeout_ns = static_cast<s64>(timeout_ns_low | (u64{timeout_ns_high} << 32));
  1563. return WaitProcessWideKeyAtomic(system, address, cv_key, tag, timeout_ns);
  1564. }
  1565. /// Signal process wide key
  1566. static void SignalProcessWideKey(Core::System& system, VAddr cv_key, s32 count) {
  1567. LOG_TRACE(Kernel_SVC, "called, cv_key=0x{:X}, count=0x{:08X}", cv_key, count);
  1568. // Signal the condition variable.
  1569. return system.Kernel().CurrentProcess()->SignalConditionVariable(
  1570. Common::AlignDown(cv_key, sizeof(u32)), count);
  1571. }
  1572. static void SignalProcessWideKey32(Core::System& system, u32 cv_key, s32 count) {
  1573. SignalProcessWideKey(system, cv_key, count);
  1574. }
  1575. namespace {
  1576. constexpr bool IsValidSignalType(Svc::SignalType type) {
  1577. switch (type) {
  1578. case Svc::SignalType::Signal:
  1579. case Svc::SignalType::SignalAndIncrementIfEqual:
  1580. case Svc::SignalType::SignalAndModifyByWaitingCountIfEqual:
  1581. return true;
  1582. default:
  1583. return false;
  1584. }
  1585. }
  1586. constexpr bool IsValidArbitrationType(Svc::ArbitrationType type) {
  1587. switch (type) {
  1588. case Svc::ArbitrationType::WaitIfLessThan:
  1589. case Svc::ArbitrationType::DecrementAndWaitIfLessThan:
  1590. case Svc::ArbitrationType::WaitIfEqual:
  1591. return true;
  1592. default:
  1593. return false;
  1594. }
  1595. }
  1596. } // namespace
  1597. // Wait for an address (via Address Arbiter)
  1598. static ResultCode WaitForAddress(Core::System& system, VAddr address, Svc::ArbitrationType arb_type,
  1599. s32 value, s64 timeout_ns) {
  1600. LOG_TRACE(Kernel_SVC, "called, address=0x{:X}, arb_type=0x{:X}, value=0x{:X}, timeout_ns={}",
  1601. address, arb_type, value, timeout_ns);
  1602. // Validate input.
  1603. if (IsKernelAddress(address)) {
  1604. LOG_ERROR(Kernel_SVC, "Attempting to wait on kernel address (address={:08X})", address);
  1605. return ResultInvalidCurrentMemory;
  1606. }
  1607. if (!Common::IsAligned(address, sizeof(s32))) {
  1608. LOG_ERROR(Kernel_SVC, "Wait address must be 4 byte aligned (address={:08X})", address);
  1609. return ResultInvalidAddress;
  1610. }
  1611. if (!IsValidArbitrationType(arb_type)) {
  1612. LOG_ERROR(Kernel_SVC, "Invalid arbitration type specified (type={})", arb_type);
  1613. return ResultInvalidEnumValue;
  1614. }
  1615. // Convert timeout from nanoseconds to ticks.
  1616. s64 timeout{};
  1617. if (timeout_ns > 0) {
  1618. const s64 offset_tick(timeout_ns);
  1619. if (offset_tick > 0) {
  1620. timeout = offset_tick + 2;
  1621. if (timeout <= 0) {
  1622. timeout = std::numeric_limits<s64>::max();
  1623. }
  1624. } else {
  1625. timeout = std::numeric_limits<s64>::max();
  1626. }
  1627. } else {
  1628. timeout = timeout_ns;
  1629. }
  1630. return system.Kernel().CurrentProcess()->WaitAddressArbiter(address, arb_type, value, timeout);
  1631. }
  1632. static ResultCode WaitForAddress32(Core::System& system, u32 address, Svc::ArbitrationType arb_type,
  1633. s32 value, u32 timeout_ns_low, u32 timeout_ns_high) {
  1634. const auto timeout = static_cast<s64>(timeout_ns_low | (u64{timeout_ns_high} << 32));
  1635. return WaitForAddress(system, address, arb_type, value, timeout);
  1636. }
  1637. // Signals to an address (via Address Arbiter)
  1638. static ResultCode SignalToAddress(Core::System& system, VAddr address, Svc::SignalType signal_type,
  1639. s32 value, s32 count) {
  1640. LOG_TRACE(Kernel_SVC, "called, address=0x{:X}, signal_type=0x{:X}, value=0x{:X}, count=0x{:X}",
  1641. address, signal_type, value, count);
  1642. // Validate input.
  1643. if (IsKernelAddress(address)) {
  1644. LOG_ERROR(Kernel_SVC, "Attempting to signal to a kernel address (address={:08X})", address);
  1645. return ResultInvalidCurrentMemory;
  1646. }
  1647. if (!Common::IsAligned(address, sizeof(s32))) {
  1648. LOG_ERROR(Kernel_SVC, "Signaled address must be 4 byte aligned (address={:08X})", address);
  1649. return ResultInvalidAddress;
  1650. }
  1651. if (!IsValidSignalType(signal_type)) {
  1652. LOG_ERROR(Kernel_SVC, "Invalid signal type specified (type={})", signal_type);
  1653. return ResultInvalidEnumValue;
  1654. }
  1655. return system.Kernel().CurrentProcess()->SignalAddressArbiter(address, signal_type, value,
  1656. count);
  1657. }
  1658. static void SynchronizePreemptionState(Core::System& system) {
  1659. auto& kernel = system.Kernel();
  1660. // Lock the scheduler.
  1661. KScopedSchedulerLock sl{kernel};
  1662. // If the current thread is pinned, unpin it.
  1663. KProcess* cur_process = system.Kernel().CurrentProcess();
  1664. const auto core_id = GetCurrentCoreId(kernel);
  1665. if (cur_process->GetPinnedThread(core_id) == GetCurrentThreadPointer(kernel)) {
  1666. // Clear the current thread's interrupt flag.
  1667. GetCurrentThread(kernel).ClearInterruptFlag();
  1668. // Unpin the current thread.
  1669. cur_process->UnpinCurrentThread(core_id);
  1670. }
  1671. }
  1672. static ResultCode SignalToAddress32(Core::System& system, u32 address, Svc::SignalType signal_type,
  1673. s32 value, s32 count) {
  1674. return SignalToAddress(system, address, signal_type, value, count);
  1675. }
  1676. static void KernelDebug([[maybe_unused]] Core::System& system,
  1677. [[maybe_unused]] u32 kernel_debug_type, [[maybe_unused]] u64 param1,
  1678. [[maybe_unused]] u64 param2, [[maybe_unused]] u64 param3) {
  1679. // Intentionally do nothing, as this does nothing in released kernel binaries.
  1680. }
  1681. static void ChangeKernelTraceState([[maybe_unused]] Core::System& system,
  1682. [[maybe_unused]] u32 trace_state) {
  1683. // Intentionally do nothing, as this does nothing in released kernel binaries.
  1684. }
  1685. /// This returns the total CPU ticks elapsed since the CPU was powered-on
  1686. static u64 GetSystemTick(Core::System& system) {
  1687. LOG_TRACE(Kernel_SVC, "called");
  1688. auto& core_timing = system.CoreTiming();
  1689. // Returns the value of cntpct_el0 (https://switchbrew.org/wiki/SVC#svcGetSystemTick)
  1690. const u64 result{system.CoreTiming().GetClockTicks()};
  1691. if (!system.Kernel().IsMulticore()) {
  1692. core_timing.AddTicks(400U);
  1693. }
  1694. return result;
  1695. }
  1696. static void GetSystemTick32(Core::System& system, u32* time_low, u32* time_high) {
  1697. const auto time = GetSystemTick(system);
  1698. *time_low = static_cast<u32>(time);
  1699. *time_high = static_cast<u32>(time >> 32);
  1700. }
  1701. /// Close a handle
  1702. static ResultCode CloseHandle(Core::System& system, Handle handle) {
  1703. LOG_TRACE(Kernel_SVC, "Closing handle 0x{:08X}", handle);
  1704. // Remove the handle.
  1705. R_UNLESS(system.Kernel().CurrentProcess()->GetHandleTable().Remove(handle),
  1706. ResultInvalidHandle);
  1707. return ResultSuccess;
  1708. }
  1709. static ResultCode CloseHandle32(Core::System& system, Handle handle) {
  1710. return CloseHandle(system, handle);
  1711. }
  1712. /// Clears the signaled state of an event or process.
  1713. static ResultCode ResetSignal(Core::System& system, Handle handle) {
  1714. LOG_DEBUG(Kernel_SVC, "called handle 0x{:08X}", handle);
  1715. // Get the current handle table.
  1716. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1717. // Try to reset as readable event.
  1718. {
  1719. KScopedAutoObject readable_event = handle_table.GetObject<KReadableEvent>(handle);
  1720. if (readable_event.IsNotNull()) {
  1721. return readable_event->Reset();
  1722. }
  1723. }
  1724. // Try to reset as process.
  1725. {
  1726. KScopedAutoObject process = handle_table.GetObject<KProcess>(handle);
  1727. if (process.IsNotNull()) {
  1728. return process->Reset();
  1729. }
  1730. }
  1731. LOG_ERROR(Kernel_SVC, "invalid handle (0x{:08X})", handle);
  1732. return ResultInvalidHandle;
  1733. }
  1734. static ResultCode ResetSignal32(Core::System& system, Handle handle) {
  1735. return ResetSignal(system, handle);
  1736. }
  1737. namespace {
  1738. constexpr bool IsValidTransferMemoryPermission(MemoryPermission perm) {
  1739. switch (perm) {
  1740. case MemoryPermission::None:
  1741. case MemoryPermission::Read:
  1742. case MemoryPermission::ReadWrite:
  1743. return true;
  1744. default:
  1745. return false;
  1746. }
  1747. }
  1748. } // Anonymous namespace
  1749. /// Creates a TransferMemory object
  1750. static ResultCode CreateTransferMemory(Core::System& system, Handle* out, VAddr address, u64 size,
  1751. MemoryPermission map_perm) {
  1752. auto& kernel = system.Kernel();
  1753. // Validate the size.
  1754. R_UNLESS(Common::IsAligned(address, PageSize), ResultInvalidAddress);
  1755. R_UNLESS(Common::IsAligned(size, PageSize), ResultInvalidSize);
  1756. R_UNLESS(size > 0, ResultInvalidSize);
  1757. R_UNLESS((address < address + size), ResultInvalidCurrentMemory);
  1758. // Validate the permissions.
  1759. R_UNLESS(IsValidTransferMemoryPermission(map_perm), ResultInvalidNewMemoryPermission);
  1760. // Get the current process and handle table.
  1761. auto& process = *kernel.CurrentProcess();
  1762. auto& handle_table = process.GetHandleTable();
  1763. // Reserve a new transfer memory from the process resource limit.
  1764. KScopedResourceReservation trmem_reservation(kernel.CurrentProcess(),
  1765. LimitableResource::TransferMemory);
  1766. R_UNLESS(trmem_reservation.Succeeded(), ResultLimitReached);
  1767. // Create the transfer memory.
  1768. KTransferMemory* trmem = KTransferMemory::Create(kernel);
  1769. R_UNLESS(trmem != nullptr, ResultOutOfResource);
  1770. // Ensure the only reference is in the handle table when we're done.
  1771. SCOPE_EXIT({ trmem->Close(); });
  1772. // Ensure that the region is in range.
  1773. R_UNLESS(process.PageTable().Contains(address, size), ResultInvalidCurrentMemory);
  1774. // Initialize the transfer memory.
  1775. R_TRY(trmem->Initialize(address, size, map_perm));
  1776. // Commit the reservation.
  1777. trmem_reservation.Commit();
  1778. // Register the transfer memory.
  1779. KTransferMemory::Register(kernel, trmem);
  1780. // Add the transfer memory to the handle table.
  1781. R_TRY(handle_table.Add(out, trmem));
  1782. return ResultSuccess;
  1783. }
  1784. static ResultCode CreateTransferMemory32(Core::System& system, Handle* out, u32 address, u32 size,
  1785. MemoryPermission map_perm) {
  1786. return CreateTransferMemory(system, out, address, size, map_perm);
  1787. }
  1788. static ResultCode GetThreadCoreMask(Core::System& system, Handle thread_handle, s32* out_core_id,
  1789. u64* out_affinity_mask) {
  1790. LOG_TRACE(Kernel_SVC, "called, handle=0x{:08X}", thread_handle);
  1791. // Get the thread from its handle.
  1792. KScopedAutoObject thread =
  1793. system.Kernel().CurrentProcess()->GetHandleTable().GetObject<KThread>(thread_handle);
  1794. R_UNLESS(thread.IsNotNull(), ResultInvalidHandle);
  1795. // Get the core mask.
  1796. R_TRY(thread->GetCoreMask(out_core_id, out_affinity_mask));
  1797. return ResultSuccess;
  1798. }
  1799. static ResultCode GetThreadCoreMask32(Core::System& system, Handle thread_handle, s32* out_core_id,
  1800. u32* out_affinity_mask_low, u32* out_affinity_mask_high) {
  1801. u64 out_affinity_mask{};
  1802. const auto result = GetThreadCoreMask(system, thread_handle, out_core_id, &out_affinity_mask);
  1803. *out_affinity_mask_high = static_cast<u32>(out_affinity_mask >> 32);
  1804. *out_affinity_mask_low = static_cast<u32>(out_affinity_mask);
  1805. return result;
  1806. }
  1807. static ResultCode SetThreadCoreMask(Core::System& system, Handle thread_handle, s32 core_id,
  1808. u64 affinity_mask) {
  1809. // Determine the core id/affinity mask.
  1810. if (core_id == IdealCoreUseProcessValue) {
  1811. core_id = system.Kernel().CurrentProcess()->GetIdealCoreId();
  1812. affinity_mask = (1ULL << core_id);
  1813. } else {
  1814. // Validate the affinity mask.
  1815. const u64 process_core_mask = system.Kernel().CurrentProcess()->GetCoreMask();
  1816. R_UNLESS((affinity_mask | process_core_mask) == process_core_mask, ResultInvalidCoreId);
  1817. R_UNLESS(affinity_mask != 0, ResultInvalidCombination);
  1818. // Validate the core id.
  1819. if (IsValidVirtualCoreId(core_id)) {
  1820. R_UNLESS(((1ULL << core_id) & affinity_mask) != 0, ResultInvalidCombination);
  1821. } else {
  1822. R_UNLESS(core_id == IdealCoreNoUpdate || core_id == IdealCoreDontCare,
  1823. ResultInvalidCoreId);
  1824. }
  1825. }
  1826. // Get the thread from its handle.
  1827. KScopedAutoObject thread =
  1828. system.Kernel().CurrentProcess()->GetHandleTable().GetObject<KThread>(thread_handle);
  1829. R_UNLESS(thread.IsNotNull(), ResultInvalidHandle);
  1830. // Set the core mask.
  1831. R_TRY(thread->SetCoreMask(core_id, affinity_mask));
  1832. return ResultSuccess;
  1833. }
  1834. static ResultCode SetThreadCoreMask32(Core::System& system, Handle thread_handle, s32 core_id,
  1835. u32 affinity_mask_low, u32 affinity_mask_high) {
  1836. const auto affinity_mask = u64{affinity_mask_low} | (u64{affinity_mask_high} << 32);
  1837. return SetThreadCoreMask(system, thread_handle, core_id, affinity_mask);
  1838. }
  1839. static ResultCode SignalEvent(Core::System& system, Handle event_handle) {
  1840. LOG_DEBUG(Kernel_SVC, "called, event_handle=0x{:08X}", event_handle);
  1841. // Get the current handle table.
  1842. const KHandleTable& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1843. // Get the writable event.
  1844. KScopedAutoObject writable_event = handle_table.GetObject<KWritableEvent>(event_handle);
  1845. R_UNLESS(writable_event.IsNotNull(), ResultInvalidHandle);
  1846. return writable_event->Signal();
  1847. }
  1848. static ResultCode SignalEvent32(Core::System& system, Handle event_handle) {
  1849. return SignalEvent(system, event_handle);
  1850. }
  1851. static ResultCode ClearEvent(Core::System& system, Handle event_handle) {
  1852. LOG_TRACE(Kernel_SVC, "called, event_handle=0x{:08X}", event_handle);
  1853. // Get the current handle table.
  1854. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1855. // Try to clear the writable event.
  1856. {
  1857. KScopedAutoObject writable_event = handle_table.GetObject<KWritableEvent>(event_handle);
  1858. if (writable_event.IsNotNull()) {
  1859. return writable_event->Clear();
  1860. }
  1861. }
  1862. // Try to clear the readable event.
  1863. {
  1864. KScopedAutoObject readable_event = handle_table.GetObject<KReadableEvent>(event_handle);
  1865. if (readable_event.IsNotNull()) {
  1866. return readable_event->Clear();
  1867. }
  1868. }
  1869. LOG_ERROR(Kernel_SVC, "Event handle does not exist, event_handle=0x{:08X}", event_handle);
  1870. return ResultInvalidHandle;
  1871. }
  1872. static ResultCode ClearEvent32(Core::System& system, Handle event_handle) {
  1873. return ClearEvent(system, event_handle);
  1874. }
  1875. static ResultCode CreateEvent(Core::System& system, Handle* out_write, Handle* out_read) {
  1876. LOG_DEBUG(Kernel_SVC, "called");
  1877. // Get the kernel reference and handle table.
  1878. auto& kernel = system.Kernel();
  1879. auto& handle_table = kernel.CurrentProcess()->GetHandleTable();
  1880. // Reserve a new event from the process resource limit
  1881. KScopedResourceReservation event_reservation(kernel.CurrentProcess(),
  1882. LimitableResource::Events);
  1883. R_UNLESS(event_reservation.Succeeded(), ResultLimitReached);
  1884. // Create a new event.
  1885. KEvent* event = KEvent::Create(kernel);
  1886. R_UNLESS(event != nullptr, ResultOutOfResource);
  1887. // Initialize the event.
  1888. event->Initialize("CreateEvent");
  1889. // Commit the thread reservation.
  1890. event_reservation.Commit();
  1891. // Ensure that we clean up the event (and its only references are handle table) on function end.
  1892. SCOPE_EXIT({
  1893. event->GetWritableEvent().Close();
  1894. event->GetReadableEvent().Close();
  1895. });
  1896. // Register the event.
  1897. KEvent::Register(kernel, event);
  1898. // Add the writable event to the handle table.
  1899. R_TRY(handle_table.Add(out_write, std::addressof(event->GetWritableEvent())));
  1900. // Add the writable event to the handle table.
  1901. auto handle_guard = SCOPE_GUARD({ handle_table.Remove(*out_write); });
  1902. // Add the readable event to the handle table.
  1903. R_TRY(handle_table.Add(out_read, std::addressof(event->GetReadableEvent())));
  1904. // We succeeded.
  1905. handle_guard.Cancel();
  1906. return ResultSuccess;
  1907. }
  1908. static ResultCode CreateEvent32(Core::System& system, Handle* out_write, Handle* out_read) {
  1909. return CreateEvent(system, out_write, out_read);
  1910. }
  1911. static ResultCode GetProcessInfo(Core::System& system, u64* out, Handle process_handle, u32 type) {
  1912. LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, type=0x{:X}", process_handle, type);
  1913. // This function currently only allows retrieving a process' status.
  1914. enum class InfoType {
  1915. Status,
  1916. };
  1917. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1918. KScopedAutoObject process = handle_table.GetObject<KProcess>(process_handle);
  1919. if (process.IsNull()) {
  1920. LOG_ERROR(Kernel_SVC, "Process handle does not exist, process_handle=0x{:08X}",
  1921. process_handle);
  1922. return ResultInvalidHandle;
  1923. }
  1924. const auto info_type = static_cast<InfoType>(type);
  1925. if (info_type != InfoType::Status) {
  1926. LOG_ERROR(Kernel_SVC, "Expected info_type to be Status but got {} instead", type);
  1927. return ResultInvalidEnumValue;
  1928. }
  1929. *out = static_cast<u64>(process->GetStatus());
  1930. return ResultSuccess;
  1931. }
  1932. static ResultCode CreateResourceLimit(Core::System& system, Handle* out_handle) {
  1933. LOG_DEBUG(Kernel_SVC, "called");
  1934. // Create a new resource limit.
  1935. auto& kernel = system.Kernel();
  1936. KResourceLimit* resource_limit = KResourceLimit::Create(kernel);
  1937. R_UNLESS(resource_limit != nullptr, ResultOutOfResource);
  1938. // Ensure we don't leak a reference to the limit.
  1939. SCOPE_EXIT({ resource_limit->Close(); });
  1940. // Initialize the resource limit.
  1941. resource_limit->Initialize(&system.CoreTiming());
  1942. // Register the limit.
  1943. KResourceLimit::Register(kernel, resource_limit);
  1944. // Add the limit to the handle table.
  1945. R_TRY(kernel.CurrentProcess()->GetHandleTable().Add(out_handle, resource_limit));
  1946. return ResultSuccess;
  1947. }
  1948. static ResultCode GetResourceLimitLimitValue(Core::System& system, u64* out_limit_value,
  1949. Handle resource_limit_handle,
  1950. LimitableResource which) {
  1951. LOG_DEBUG(Kernel_SVC, "called, resource_limit_handle={:08X}, which={}", resource_limit_handle,
  1952. which);
  1953. // Validate the resource.
  1954. R_UNLESS(IsValidResourceType(which), ResultInvalidEnumValue);
  1955. // Get the resource limit.
  1956. auto& kernel = system.Kernel();
  1957. KScopedAutoObject resource_limit =
  1958. kernel.CurrentProcess()->GetHandleTable().GetObject<KResourceLimit>(resource_limit_handle);
  1959. R_UNLESS(resource_limit.IsNotNull(), ResultInvalidHandle);
  1960. // Get the limit value.
  1961. *out_limit_value = resource_limit->GetLimitValue(which);
  1962. return ResultSuccess;
  1963. }
  1964. static ResultCode GetResourceLimitCurrentValue(Core::System& system, u64* out_current_value,
  1965. Handle resource_limit_handle,
  1966. LimitableResource which) {
  1967. LOG_DEBUG(Kernel_SVC, "called, resource_limit_handle={:08X}, which={}", resource_limit_handle,
  1968. which);
  1969. // Validate the resource.
  1970. R_UNLESS(IsValidResourceType(which), ResultInvalidEnumValue);
  1971. // Get the resource limit.
  1972. auto& kernel = system.Kernel();
  1973. KScopedAutoObject resource_limit =
  1974. kernel.CurrentProcess()->GetHandleTable().GetObject<KResourceLimit>(resource_limit_handle);
  1975. R_UNLESS(resource_limit.IsNotNull(), ResultInvalidHandle);
  1976. // Get the current value.
  1977. *out_current_value = resource_limit->GetCurrentValue(which);
  1978. return ResultSuccess;
  1979. }
  1980. static ResultCode SetResourceLimitLimitValue(Core::System& system, Handle resource_limit_handle,
  1981. LimitableResource which, u64 limit_value) {
  1982. LOG_DEBUG(Kernel_SVC, "called, resource_limit_handle={:08X}, which={}, limit_value={}",
  1983. resource_limit_handle, which, limit_value);
  1984. // Validate the resource.
  1985. R_UNLESS(IsValidResourceType(which), ResultInvalidEnumValue);
  1986. // Get the resource limit.
  1987. auto& kernel = system.Kernel();
  1988. KScopedAutoObject resource_limit =
  1989. kernel.CurrentProcess()->GetHandleTable().GetObject<KResourceLimit>(resource_limit_handle);
  1990. R_UNLESS(resource_limit.IsNotNull(), ResultInvalidHandle);
  1991. // Set the limit value.
  1992. R_TRY(resource_limit->SetLimitValue(which, limit_value));
  1993. return ResultSuccess;
  1994. }
  1995. static ResultCode GetProcessList(Core::System& system, u32* out_num_processes,
  1996. VAddr out_process_ids, u32 out_process_ids_size) {
  1997. LOG_DEBUG(Kernel_SVC, "called. out_process_ids=0x{:016X}, out_process_ids_size={}",
  1998. out_process_ids, out_process_ids_size);
  1999. // If the supplied size is negative or greater than INT32_MAX / sizeof(u64), bail.
  2000. if ((out_process_ids_size & 0xF0000000) != 0) {
  2001. LOG_ERROR(Kernel_SVC,
  2002. "Supplied size outside [0, 0x0FFFFFFF] range. out_process_ids_size={}",
  2003. out_process_ids_size);
  2004. return ResultOutOfRange;
  2005. }
  2006. const auto& kernel = system.Kernel();
  2007. const auto total_copy_size = out_process_ids_size * sizeof(u64);
  2008. if (out_process_ids_size > 0 && !kernel.CurrentProcess()->PageTable().IsInsideAddressSpace(
  2009. out_process_ids, total_copy_size)) {
  2010. LOG_ERROR(Kernel_SVC, "Address range outside address space. begin=0x{:016X}, end=0x{:016X}",
  2011. out_process_ids, out_process_ids + total_copy_size);
  2012. return ResultInvalidCurrentMemory;
  2013. }
  2014. auto& memory = system.Memory();
  2015. const auto& process_list = kernel.GetProcessList();
  2016. const auto num_processes = process_list.size();
  2017. const auto copy_amount = std::min(std::size_t{out_process_ids_size}, num_processes);
  2018. for (std::size_t i = 0; i < copy_amount; ++i) {
  2019. memory.Write64(out_process_ids, process_list[i]->GetProcessID());
  2020. out_process_ids += sizeof(u64);
  2021. }
  2022. *out_num_processes = static_cast<u32>(num_processes);
  2023. return ResultSuccess;
  2024. }
  2025. static ResultCode GetThreadList(Core::System& system, u32* out_num_threads, VAddr out_thread_ids,
  2026. u32 out_thread_ids_size, Handle debug_handle) {
  2027. // TODO: Handle this case when debug events are supported.
  2028. UNIMPLEMENTED_IF(debug_handle != InvalidHandle);
  2029. LOG_DEBUG(Kernel_SVC, "called. out_thread_ids=0x{:016X}, out_thread_ids_size={}",
  2030. out_thread_ids, out_thread_ids_size);
  2031. // If the size is negative or larger than INT32_MAX / sizeof(u64)
  2032. if ((out_thread_ids_size & 0xF0000000) != 0) {
  2033. LOG_ERROR(Kernel_SVC, "Supplied size outside [0, 0x0FFFFFFF] range. size={}",
  2034. out_thread_ids_size);
  2035. return ResultOutOfRange;
  2036. }
  2037. const auto* const current_process = system.Kernel().CurrentProcess();
  2038. const auto total_copy_size = out_thread_ids_size * sizeof(u64);
  2039. if (out_thread_ids_size > 0 &&
  2040. !current_process->PageTable().IsInsideAddressSpace(out_thread_ids, total_copy_size)) {
  2041. LOG_ERROR(Kernel_SVC, "Address range outside address space. begin=0x{:016X}, end=0x{:016X}",
  2042. out_thread_ids, out_thread_ids + total_copy_size);
  2043. return ResultInvalidCurrentMemory;
  2044. }
  2045. auto& memory = system.Memory();
  2046. const auto& thread_list = current_process->GetThreadList();
  2047. const auto num_threads = thread_list.size();
  2048. const auto copy_amount = std::min(std::size_t{out_thread_ids_size}, num_threads);
  2049. auto list_iter = thread_list.cbegin();
  2050. for (std::size_t i = 0; i < copy_amount; ++i, ++list_iter) {
  2051. memory.Write64(out_thread_ids, (*list_iter)->GetThreadID());
  2052. out_thread_ids += sizeof(u64);
  2053. }
  2054. *out_num_threads = static_cast<u32>(num_threads);
  2055. return ResultSuccess;
  2056. }
  2057. static ResultCode FlushProcessDataCache32([[maybe_unused]] Core::System& system,
  2058. [[maybe_unused]] Handle handle,
  2059. [[maybe_unused]] u32 address, [[maybe_unused]] u32 size) {
  2060. // Note(Blinkhawk): For emulation purposes of the data cache this is mostly a no-op,
  2061. // as all emulation is done in the same cache level in host architecture, thus data cache
  2062. // does not need flushing.
  2063. LOG_DEBUG(Kernel_SVC, "called");
  2064. return ResultSuccess;
  2065. }
  2066. namespace {
  2067. struct FunctionDef {
  2068. using Func = void(Core::System&);
  2069. u32 id;
  2070. Func* func;
  2071. const char* name;
  2072. };
  2073. } // namespace
  2074. static const FunctionDef SVC_Table_32[] = {
  2075. {0x00, nullptr, "Unknown"},
  2076. {0x01, SvcWrap32<SetHeapSize32>, "SetHeapSize32"},
  2077. {0x02, nullptr, "Unknown"},
  2078. {0x03, SvcWrap32<SetMemoryAttribute32>, "SetMemoryAttribute32"},
  2079. {0x04, SvcWrap32<MapMemory32>, "MapMemory32"},
  2080. {0x05, SvcWrap32<UnmapMemory32>, "UnmapMemory32"},
  2081. {0x06, SvcWrap32<QueryMemory32>, "QueryMemory32"},
  2082. {0x07, SvcWrap32<ExitProcess32>, "ExitProcess32"},
  2083. {0x08, SvcWrap32<CreateThread32>, "CreateThread32"},
  2084. {0x09, SvcWrap32<StartThread32>, "StartThread32"},
  2085. {0x0a, SvcWrap32<ExitThread32>, "ExitThread32"},
  2086. {0x0b, SvcWrap32<SleepThread32>, "SleepThread32"},
  2087. {0x0c, SvcWrap32<GetThreadPriority32>, "GetThreadPriority32"},
  2088. {0x0d, SvcWrap32<SetThreadPriority32>, "SetThreadPriority32"},
  2089. {0x0e, SvcWrap32<GetThreadCoreMask32>, "GetThreadCoreMask32"},
  2090. {0x0f, SvcWrap32<SetThreadCoreMask32>, "SetThreadCoreMask32"},
  2091. {0x10, SvcWrap32<GetCurrentProcessorNumber32>, "GetCurrentProcessorNumber32"},
  2092. {0x11, SvcWrap32<SignalEvent32>, "SignalEvent32"},
  2093. {0x12, SvcWrap32<ClearEvent32>, "ClearEvent32"},
  2094. {0x13, SvcWrap32<MapSharedMemory32>, "MapSharedMemory32"},
  2095. {0x14, SvcWrap32<UnmapSharedMemory32>, "UnmapSharedMemory32"},
  2096. {0x15, SvcWrap32<CreateTransferMemory32>, "CreateTransferMemory32"},
  2097. {0x16, SvcWrap32<CloseHandle32>, "CloseHandle32"},
  2098. {0x17, SvcWrap32<ResetSignal32>, "ResetSignal32"},
  2099. {0x18, SvcWrap32<WaitSynchronization32>, "WaitSynchronization32"},
  2100. {0x19, SvcWrap32<CancelSynchronization32>, "CancelSynchronization32"},
  2101. {0x1a, SvcWrap32<ArbitrateLock32>, "ArbitrateLock32"},
  2102. {0x1b, SvcWrap32<ArbitrateUnlock32>, "ArbitrateUnlock32"},
  2103. {0x1c, SvcWrap32<WaitProcessWideKeyAtomic32>, "WaitProcessWideKeyAtomic32"},
  2104. {0x1d, SvcWrap32<SignalProcessWideKey32>, "SignalProcessWideKey32"},
  2105. {0x1e, SvcWrap32<GetSystemTick32>, "GetSystemTick32"},
  2106. {0x1f, SvcWrap32<ConnectToNamedPort32>, "ConnectToNamedPort32"},
  2107. {0x20, nullptr, "Unknown"},
  2108. {0x21, SvcWrap32<SendSyncRequest32>, "SendSyncRequest32"},
  2109. {0x22, nullptr, "SendSyncRequestWithUserBuffer32"},
  2110. {0x23, nullptr, "Unknown"},
  2111. {0x24, SvcWrap32<GetProcessId32>, "GetProcessId32"},
  2112. {0x25, SvcWrap32<GetThreadId32>, "GetThreadId32"},
  2113. {0x26, SvcWrap32<Break32>, "Break32"},
  2114. {0x27, nullptr, "OutputDebugString32"},
  2115. {0x28, nullptr, "Unknown"},
  2116. {0x29, SvcWrap32<GetInfo32>, "GetInfo32"},
  2117. {0x2a, nullptr, "Unknown"},
  2118. {0x2b, nullptr, "Unknown"},
  2119. {0x2c, SvcWrap32<MapPhysicalMemory32>, "MapPhysicalMemory32"},
  2120. {0x2d, SvcWrap32<UnmapPhysicalMemory32>, "UnmapPhysicalMemory32"},
  2121. {0x2e, nullptr, "Unknown"},
  2122. {0x2f, nullptr, "Unknown"},
  2123. {0x30, nullptr, "Unknown"},
  2124. {0x31, nullptr, "Unknown"},
  2125. {0x32, SvcWrap32<SetThreadActivity32>, "SetThreadActivity32"},
  2126. {0x33, SvcWrap32<GetThreadContext32>, "GetThreadContext32"},
  2127. {0x34, SvcWrap32<WaitForAddress32>, "WaitForAddress32"},
  2128. {0x35, SvcWrap32<SignalToAddress32>, "SignalToAddress32"},
  2129. {0x36, nullptr, "Unknown"},
  2130. {0x37, nullptr, "Unknown"},
  2131. {0x38, nullptr, "Unknown"},
  2132. {0x39, nullptr, "Unknown"},
  2133. {0x3a, nullptr, "Unknown"},
  2134. {0x3b, nullptr, "Unknown"},
  2135. {0x3c, nullptr, "Unknown"},
  2136. {0x3d, nullptr, "Unknown"},
  2137. {0x3e, nullptr, "Unknown"},
  2138. {0x3f, nullptr, "Unknown"},
  2139. {0x40, nullptr, "CreateSession32"},
  2140. {0x41, nullptr, "AcceptSession32"},
  2141. {0x42, nullptr, "Unknown"},
  2142. {0x43, nullptr, "ReplyAndReceive32"},
  2143. {0x44, nullptr, "Unknown"},
  2144. {0x45, SvcWrap32<CreateEvent32>, "CreateEvent32"},
  2145. {0x46, nullptr, "Unknown"},
  2146. {0x47, nullptr, "Unknown"},
  2147. {0x48, nullptr, "Unknown"},
  2148. {0x49, nullptr, "Unknown"},
  2149. {0x4a, nullptr, "Unknown"},
  2150. {0x4b, nullptr, "Unknown"},
  2151. {0x4c, nullptr, "Unknown"},
  2152. {0x4d, nullptr, "Unknown"},
  2153. {0x4e, nullptr, "Unknown"},
  2154. {0x4f, nullptr, "Unknown"},
  2155. {0x50, nullptr, "Unknown"},
  2156. {0x51, nullptr, "Unknown"},
  2157. {0x52, nullptr, "Unknown"},
  2158. {0x53, nullptr, "Unknown"},
  2159. {0x54, nullptr, "Unknown"},
  2160. {0x55, nullptr, "Unknown"},
  2161. {0x56, nullptr, "Unknown"},
  2162. {0x57, nullptr, "Unknown"},
  2163. {0x58, nullptr, "Unknown"},
  2164. {0x59, nullptr, "Unknown"},
  2165. {0x5a, nullptr, "Unknown"},
  2166. {0x5b, nullptr, "Unknown"},
  2167. {0x5c, nullptr, "Unknown"},
  2168. {0x5d, nullptr, "Unknown"},
  2169. {0x5e, nullptr, "Unknown"},
  2170. {0x5F, SvcWrap32<FlushProcessDataCache32>, "FlushProcessDataCache32"},
  2171. {0x60, nullptr, "Unknown"},
  2172. {0x61, nullptr, "Unknown"},
  2173. {0x62, nullptr, "Unknown"},
  2174. {0x63, nullptr, "Unknown"},
  2175. {0x64, nullptr, "Unknown"},
  2176. {0x65, nullptr, "GetProcessList32"},
  2177. {0x66, nullptr, "Unknown"},
  2178. {0x67, nullptr, "Unknown"},
  2179. {0x68, nullptr, "Unknown"},
  2180. {0x69, nullptr, "Unknown"},
  2181. {0x6A, nullptr, "Unknown"},
  2182. {0x6B, nullptr, "Unknown"},
  2183. {0x6C, nullptr, "Unknown"},
  2184. {0x6D, nullptr, "Unknown"},
  2185. {0x6E, nullptr, "Unknown"},
  2186. {0x6f, nullptr, "GetSystemInfo32"},
  2187. {0x70, nullptr, "CreatePort32"},
  2188. {0x71, nullptr, "ManageNamedPort32"},
  2189. {0x72, nullptr, "ConnectToPort32"},
  2190. {0x73, nullptr, "SetProcessMemoryPermission32"},
  2191. {0x74, nullptr, "Unknown"},
  2192. {0x75, nullptr, "Unknown"},
  2193. {0x76, nullptr, "Unknown"},
  2194. {0x77, nullptr, "MapProcessCodeMemory32"},
  2195. {0x78, nullptr, "UnmapProcessCodeMemory32"},
  2196. {0x79, nullptr, "Unknown"},
  2197. {0x7A, nullptr, "Unknown"},
  2198. {0x7B, nullptr, "TerminateProcess32"},
  2199. {0x7C, nullptr, "GetProcessInfo32"},
  2200. {0x7D, nullptr, "CreateResourceLimit32"},
  2201. {0x7E, nullptr, "SetResourceLimitLimitValue32"},
  2202. {0x7F, nullptr, "CallSecureMonitor32"},
  2203. {0x80, nullptr, "Unknown"},
  2204. {0x81, nullptr, "Unknown"},
  2205. {0x82, nullptr, "Unknown"},
  2206. {0x83, nullptr, "Unknown"},
  2207. {0x84, nullptr, "Unknown"},
  2208. {0x85, nullptr, "Unknown"},
  2209. {0x86, nullptr, "Unknown"},
  2210. {0x87, nullptr, "Unknown"},
  2211. {0x88, nullptr, "Unknown"},
  2212. {0x89, nullptr, "Unknown"},
  2213. {0x8A, nullptr, "Unknown"},
  2214. {0x8B, nullptr, "Unknown"},
  2215. {0x8C, nullptr, "Unknown"},
  2216. {0x8D, nullptr, "Unknown"},
  2217. {0x8E, nullptr, "Unknown"},
  2218. {0x8F, nullptr, "Unknown"},
  2219. {0x90, nullptr, "Unknown"},
  2220. {0x91, nullptr, "Unknown"},
  2221. {0x92, nullptr, "Unknown"},
  2222. {0x93, nullptr, "Unknown"},
  2223. {0x94, nullptr, "Unknown"},
  2224. {0x95, nullptr, "Unknown"},
  2225. {0x96, nullptr, "Unknown"},
  2226. {0x97, nullptr, "Unknown"},
  2227. {0x98, nullptr, "Unknown"},
  2228. {0x99, nullptr, "Unknown"},
  2229. {0x9A, nullptr, "Unknown"},
  2230. {0x9B, nullptr, "Unknown"},
  2231. {0x9C, nullptr, "Unknown"},
  2232. {0x9D, nullptr, "Unknown"},
  2233. {0x9E, nullptr, "Unknown"},
  2234. {0x9F, nullptr, "Unknown"},
  2235. {0xA0, nullptr, "Unknown"},
  2236. {0xA1, nullptr, "Unknown"},
  2237. {0xA2, nullptr, "Unknown"},
  2238. {0xA3, nullptr, "Unknown"},
  2239. {0xA4, nullptr, "Unknown"},
  2240. {0xA5, nullptr, "Unknown"},
  2241. {0xA6, nullptr, "Unknown"},
  2242. {0xA7, nullptr, "Unknown"},
  2243. {0xA8, nullptr, "Unknown"},
  2244. {0xA9, nullptr, "Unknown"},
  2245. {0xAA, nullptr, "Unknown"},
  2246. {0xAB, nullptr, "Unknown"},
  2247. {0xAC, nullptr, "Unknown"},
  2248. {0xAD, nullptr, "Unknown"},
  2249. {0xAE, nullptr, "Unknown"},
  2250. {0xAF, nullptr, "Unknown"},
  2251. {0xB0, nullptr, "Unknown"},
  2252. {0xB1, nullptr, "Unknown"},
  2253. {0xB2, nullptr, "Unknown"},
  2254. {0xB3, nullptr, "Unknown"},
  2255. {0xB4, nullptr, "Unknown"},
  2256. {0xB5, nullptr, "Unknown"},
  2257. {0xB6, nullptr, "Unknown"},
  2258. {0xB7, nullptr, "Unknown"},
  2259. {0xB8, nullptr, "Unknown"},
  2260. {0xB9, nullptr, "Unknown"},
  2261. {0xBA, nullptr, "Unknown"},
  2262. {0xBB, nullptr, "Unknown"},
  2263. {0xBC, nullptr, "Unknown"},
  2264. {0xBD, nullptr, "Unknown"},
  2265. {0xBE, nullptr, "Unknown"},
  2266. {0xBF, nullptr, "Unknown"},
  2267. };
  2268. static const FunctionDef SVC_Table_64[] = {
  2269. {0x00, nullptr, "Unknown"},
  2270. {0x01, SvcWrap64<SetHeapSize>, "SetHeapSize"},
  2271. {0x02, SvcWrap64<SetMemoryPermission>, "SetMemoryPermission"},
  2272. {0x03, SvcWrap64<SetMemoryAttribute>, "SetMemoryAttribute"},
  2273. {0x04, SvcWrap64<MapMemory>, "MapMemory"},
  2274. {0x05, SvcWrap64<UnmapMemory>, "UnmapMemory"},
  2275. {0x06, SvcWrap64<QueryMemory>, "QueryMemory"},
  2276. {0x07, SvcWrap64<ExitProcess>, "ExitProcess"},
  2277. {0x08, SvcWrap64<CreateThread>, "CreateThread"},
  2278. {0x09, SvcWrap64<StartThread>, "StartThread"},
  2279. {0x0A, SvcWrap64<ExitThread>, "ExitThread"},
  2280. {0x0B, SvcWrap64<SleepThread>, "SleepThread"},
  2281. {0x0C, SvcWrap64<GetThreadPriority>, "GetThreadPriority"},
  2282. {0x0D, SvcWrap64<SetThreadPriority>, "SetThreadPriority"},
  2283. {0x0E, SvcWrap64<GetThreadCoreMask>, "GetThreadCoreMask"},
  2284. {0x0F, SvcWrap64<SetThreadCoreMask>, "SetThreadCoreMask"},
  2285. {0x10, SvcWrap64<GetCurrentProcessorNumber>, "GetCurrentProcessorNumber"},
  2286. {0x11, SvcWrap64<SignalEvent>, "SignalEvent"},
  2287. {0x12, SvcWrap64<ClearEvent>, "ClearEvent"},
  2288. {0x13, SvcWrap64<MapSharedMemory>, "MapSharedMemory"},
  2289. {0x14, SvcWrap64<UnmapSharedMemory>, "UnmapSharedMemory"},
  2290. {0x15, SvcWrap64<CreateTransferMemory>, "CreateTransferMemory"},
  2291. {0x16, SvcWrap64<CloseHandle>, "CloseHandle"},
  2292. {0x17, SvcWrap64<ResetSignal>, "ResetSignal"},
  2293. {0x18, SvcWrap64<WaitSynchronization>, "WaitSynchronization"},
  2294. {0x19, SvcWrap64<CancelSynchronization>, "CancelSynchronization"},
  2295. {0x1A, SvcWrap64<ArbitrateLock>, "ArbitrateLock"},
  2296. {0x1B, SvcWrap64<ArbitrateUnlock>, "ArbitrateUnlock"},
  2297. {0x1C, SvcWrap64<WaitProcessWideKeyAtomic>, "WaitProcessWideKeyAtomic"},
  2298. {0x1D, SvcWrap64<SignalProcessWideKey>, "SignalProcessWideKey"},
  2299. {0x1E, SvcWrap64<GetSystemTick>, "GetSystemTick"},
  2300. {0x1F, SvcWrap64<ConnectToNamedPort>, "ConnectToNamedPort"},
  2301. {0x20, nullptr, "SendSyncRequestLight"},
  2302. {0x21, SvcWrap64<SendSyncRequest>, "SendSyncRequest"},
  2303. {0x22, nullptr, "SendSyncRequestWithUserBuffer"},
  2304. {0x23, nullptr, "SendAsyncRequestWithUserBuffer"},
  2305. {0x24, SvcWrap64<GetProcessId>, "GetProcessId"},
  2306. {0x25, SvcWrap64<GetThreadId>, "GetThreadId"},
  2307. {0x26, SvcWrap64<Break>, "Break"},
  2308. {0x27, SvcWrap64<OutputDebugString>, "OutputDebugString"},
  2309. {0x28, nullptr, "ReturnFromException"},
  2310. {0x29, SvcWrap64<GetInfo>, "GetInfo"},
  2311. {0x2A, nullptr, "FlushEntireDataCache"},
  2312. {0x2B, nullptr, "FlushDataCache"},
  2313. {0x2C, SvcWrap64<MapPhysicalMemory>, "MapPhysicalMemory"},
  2314. {0x2D, SvcWrap64<UnmapPhysicalMemory>, "UnmapPhysicalMemory"},
  2315. {0x2E, nullptr, "GetFutureThreadInfo"},
  2316. {0x2F, nullptr, "GetLastThreadInfo"},
  2317. {0x30, SvcWrap64<GetResourceLimitLimitValue>, "GetResourceLimitLimitValue"},
  2318. {0x31, SvcWrap64<GetResourceLimitCurrentValue>, "GetResourceLimitCurrentValue"},
  2319. {0x32, SvcWrap64<SetThreadActivity>, "SetThreadActivity"},
  2320. {0x33, SvcWrap64<GetThreadContext>, "GetThreadContext"},
  2321. {0x34, SvcWrap64<WaitForAddress>, "WaitForAddress"},
  2322. {0x35, SvcWrap64<SignalToAddress>, "SignalToAddress"},
  2323. {0x36, SvcWrap64<SynchronizePreemptionState>, "SynchronizePreemptionState"},
  2324. {0x37, nullptr, "Unknown"},
  2325. {0x38, nullptr, "Unknown"},
  2326. {0x39, nullptr, "Unknown"},
  2327. {0x3A, nullptr, "Unknown"},
  2328. {0x3B, nullptr, "Unknown"},
  2329. {0x3C, SvcWrap64<KernelDebug>, "KernelDebug"},
  2330. {0x3D, SvcWrap64<ChangeKernelTraceState>, "ChangeKernelTraceState"},
  2331. {0x3E, nullptr, "Unknown"},
  2332. {0x3F, nullptr, "Unknown"},
  2333. {0x40, nullptr, "CreateSession"},
  2334. {0x41, nullptr, "AcceptSession"},
  2335. {0x42, nullptr, "ReplyAndReceiveLight"},
  2336. {0x43, nullptr, "ReplyAndReceive"},
  2337. {0x44, nullptr, "ReplyAndReceiveWithUserBuffer"},
  2338. {0x45, SvcWrap64<CreateEvent>, "CreateEvent"},
  2339. {0x46, nullptr, "Unknown"},
  2340. {0x47, nullptr, "Unknown"},
  2341. {0x48, nullptr, "MapPhysicalMemoryUnsafe"},
  2342. {0x49, nullptr, "UnmapPhysicalMemoryUnsafe"},
  2343. {0x4A, nullptr, "SetUnsafeLimit"},
  2344. {0x4B, SvcWrap64<CreateCodeMemory>, "CreateCodeMemory"},
  2345. {0x4C, SvcWrap64<ControlCodeMemory>, "ControlCodeMemory"},
  2346. {0x4D, nullptr, "SleepSystem"},
  2347. {0x4E, nullptr, "ReadWriteRegister"},
  2348. {0x4F, nullptr, "SetProcessActivity"},
  2349. {0x50, nullptr, "CreateSharedMemory"},
  2350. {0x51, nullptr, "MapTransferMemory"},
  2351. {0x52, nullptr, "UnmapTransferMemory"},
  2352. {0x53, nullptr, "CreateInterruptEvent"},
  2353. {0x54, nullptr, "QueryPhysicalAddress"},
  2354. {0x55, nullptr, "QueryIoMapping"},
  2355. {0x56, nullptr, "CreateDeviceAddressSpace"},
  2356. {0x57, nullptr, "AttachDeviceAddressSpace"},
  2357. {0x58, nullptr, "DetachDeviceAddressSpace"},
  2358. {0x59, nullptr, "MapDeviceAddressSpaceByForce"},
  2359. {0x5A, nullptr, "MapDeviceAddressSpaceAligned"},
  2360. {0x5B, nullptr, "MapDeviceAddressSpace"},
  2361. {0x5C, nullptr, "UnmapDeviceAddressSpace"},
  2362. {0x5D, nullptr, "InvalidateProcessDataCache"},
  2363. {0x5E, nullptr, "StoreProcessDataCache"},
  2364. {0x5F, nullptr, "FlushProcessDataCache"},
  2365. {0x60, nullptr, "DebugActiveProcess"},
  2366. {0x61, nullptr, "BreakDebugProcess"},
  2367. {0x62, nullptr, "TerminateDebugProcess"},
  2368. {0x63, nullptr, "GetDebugEvent"},
  2369. {0x64, nullptr, "ContinueDebugEvent"},
  2370. {0x65, SvcWrap64<GetProcessList>, "GetProcessList"},
  2371. {0x66, SvcWrap64<GetThreadList>, "GetThreadList"},
  2372. {0x67, nullptr, "GetDebugThreadContext"},
  2373. {0x68, nullptr, "SetDebugThreadContext"},
  2374. {0x69, nullptr, "QueryDebugProcessMemory"},
  2375. {0x6A, nullptr, "ReadDebugProcessMemory"},
  2376. {0x6B, nullptr, "WriteDebugProcessMemory"},
  2377. {0x6C, nullptr, "SetHardwareBreakPoint"},
  2378. {0x6D, nullptr, "GetDebugThreadParam"},
  2379. {0x6E, nullptr, "Unknown"},
  2380. {0x6F, nullptr, "GetSystemInfo"},
  2381. {0x70, nullptr, "CreatePort"},
  2382. {0x71, nullptr, "ManageNamedPort"},
  2383. {0x72, nullptr, "ConnectToPort"},
  2384. {0x73, SvcWrap64<SetProcessMemoryPermission>, "SetProcessMemoryPermission"},
  2385. {0x74, SvcWrap64<MapProcessMemory>, "MapProcessMemory"},
  2386. {0x75, SvcWrap64<UnmapProcessMemory>, "UnmapProcessMemory"},
  2387. {0x76, SvcWrap64<QueryProcessMemory>, "QueryProcessMemory"},
  2388. {0x77, SvcWrap64<MapProcessCodeMemory>, "MapProcessCodeMemory"},
  2389. {0x78, SvcWrap64<UnmapProcessCodeMemory>, "UnmapProcessCodeMemory"},
  2390. {0x79, nullptr, "CreateProcess"},
  2391. {0x7A, nullptr, "StartProcess"},
  2392. {0x7B, nullptr, "TerminateProcess"},
  2393. {0x7C, SvcWrap64<GetProcessInfo>, "GetProcessInfo"},
  2394. {0x7D, SvcWrap64<CreateResourceLimit>, "CreateResourceLimit"},
  2395. {0x7E, SvcWrap64<SetResourceLimitLimitValue>, "SetResourceLimitLimitValue"},
  2396. {0x7F, nullptr, "CallSecureMonitor"},
  2397. {0x80, nullptr, "Unknown"},
  2398. {0x81, nullptr, "Unknown"},
  2399. {0x82, nullptr, "Unknown"},
  2400. {0x83, nullptr, "Unknown"},
  2401. {0x84, nullptr, "Unknown"},
  2402. {0x85, nullptr, "Unknown"},
  2403. {0x86, nullptr, "Unknown"},
  2404. {0x87, nullptr, "Unknown"},
  2405. {0x88, nullptr, "Unknown"},
  2406. {0x89, nullptr, "Unknown"},
  2407. {0x8A, nullptr, "Unknown"},
  2408. {0x8B, nullptr, "Unknown"},
  2409. {0x8C, nullptr, "Unknown"},
  2410. {0x8D, nullptr, "Unknown"},
  2411. {0x8E, nullptr, "Unknown"},
  2412. {0x8F, nullptr, "Unknown"},
  2413. {0x90, nullptr, "Unknown"},
  2414. {0x91, nullptr, "Unknown"},
  2415. {0x92, nullptr, "Unknown"},
  2416. {0x93, nullptr, "Unknown"},
  2417. {0x94, nullptr, "Unknown"},
  2418. {0x95, nullptr, "Unknown"},
  2419. {0x96, nullptr, "Unknown"},
  2420. {0x97, nullptr, "Unknown"},
  2421. {0x98, nullptr, "Unknown"},
  2422. {0x99, nullptr, "Unknown"},
  2423. {0x9A, nullptr, "Unknown"},
  2424. {0x9B, nullptr, "Unknown"},
  2425. {0x9C, nullptr, "Unknown"},
  2426. {0x9D, nullptr, "Unknown"},
  2427. {0x9E, nullptr, "Unknown"},
  2428. {0x9F, nullptr, "Unknown"},
  2429. {0xA0, nullptr, "Unknown"},
  2430. {0xA1, nullptr, "Unknown"},
  2431. {0xA2, nullptr, "Unknown"},
  2432. {0xA3, nullptr, "Unknown"},
  2433. {0xA4, nullptr, "Unknown"},
  2434. {0xA5, nullptr, "Unknown"},
  2435. {0xA6, nullptr, "Unknown"},
  2436. {0xA7, nullptr, "Unknown"},
  2437. {0xA8, nullptr, "Unknown"},
  2438. {0xA9, nullptr, "Unknown"},
  2439. {0xAA, nullptr, "Unknown"},
  2440. {0xAB, nullptr, "Unknown"},
  2441. {0xAC, nullptr, "Unknown"},
  2442. {0xAD, nullptr, "Unknown"},
  2443. {0xAE, nullptr, "Unknown"},
  2444. {0xAF, nullptr, "Unknown"},
  2445. {0xB0, nullptr, "Unknown"},
  2446. {0xB1, nullptr, "Unknown"},
  2447. {0xB2, nullptr, "Unknown"},
  2448. {0xB3, nullptr, "Unknown"},
  2449. {0xB4, nullptr, "Unknown"},
  2450. {0xB5, nullptr, "Unknown"},
  2451. {0xB6, nullptr, "Unknown"},
  2452. {0xB7, nullptr, "Unknown"},
  2453. {0xB8, nullptr, "Unknown"},
  2454. {0xB9, nullptr, "Unknown"},
  2455. {0xBA, nullptr, "Unknown"},
  2456. {0xBB, nullptr, "Unknown"},
  2457. {0xBC, nullptr, "Unknown"},
  2458. {0xBD, nullptr, "Unknown"},
  2459. {0xBE, nullptr, "Unknown"},
  2460. {0xBF, nullptr, "Unknown"},
  2461. };
  2462. static const FunctionDef* GetSVCInfo32(u32 func_num) {
  2463. if (func_num >= std::size(SVC_Table_32)) {
  2464. LOG_ERROR(Kernel_SVC, "Unknown svc=0x{:02X}", func_num);
  2465. return nullptr;
  2466. }
  2467. return &SVC_Table_32[func_num];
  2468. }
  2469. static const FunctionDef* GetSVCInfo64(u32 func_num) {
  2470. if (func_num >= std::size(SVC_Table_64)) {
  2471. LOG_ERROR(Kernel_SVC, "Unknown svc=0x{:02X}", func_num);
  2472. return nullptr;
  2473. }
  2474. return &SVC_Table_64[func_num];
  2475. }
  2476. void Call(Core::System& system, u32 immediate) {
  2477. system.ExitDynarmicProfile();
  2478. auto& kernel = system.Kernel();
  2479. kernel.EnterSVCProfile();
  2480. auto* thread = kernel.CurrentScheduler()->GetCurrentThread();
  2481. thread->SetIsCallingSvc();
  2482. const FunctionDef* info = system.CurrentProcess()->Is64BitProcess() ? GetSVCInfo64(immediate)
  2483. : GetSVCInfo32(immediate);
  2484. if (info) {
  2485. if (info->func) {
  2486. info->func(system);
  2487. } else {
  2488. LOG_CRITICAL(Kernel_SVC, "Unimplemented SVC function {}(..)", info->name);
  2489. }
  2490. } else {
  2491. LOG_CRITICAL(Kernel_SVC, "Unknown SVC function 0x{:X}", immediate);
  2492. }
  2493. kernel.ExitSVCProfile();
  2494. if (!thread->IsCallingSvc()) {
  2495. auto* host_context = thread->GetHostContext().get();
  2496. host_context->Rewind();
  2497. }
  2498. system.EnterDynarmicProfile();
  2499. }
  2500. } // namespace Kernel::Svc