svc.cpp 103 KB

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