svc.cpp 103 KB

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