svc.cpp 103 KB

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