svc.cpp 119 KB

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