svc.cpp 116 KB

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