svc.cpp 77 KB

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