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