svc.cpp 96 KB

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