svc.cpp 95 KB

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