svc.cpp 94 KB

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