svc.cpp 105 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773
  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/common_funcs.h"
  12. #include "common/fiber.h"
  13. #include "common/logging/log.h"
  14. #include "common/scope_exit.h"
  15. #include "core/core.h"
  16. #include "core/core_timing.h"
  17. #include "core/hle/kernel/k_client_port.h"
  18. #include "core/hle/kernel/k_client_session.h"
  19. #include "core/hle/kernel/k_event.h"
  20. #include "core/hle/kernel/k_handle_table.h"
  21. #include "core/hle/kernel/k_memory_block.h"
  22. #include "core/hle/kernel/k_memory_layout.h"
  23. #include "core/hle/kernel/k_page_table.h"
  24. #include "core/hle/kernel/k_process.h"
  25. #include "core/hle/kernel/k_readable_event.h"
  26. #include "core/hle/kernel/k_resource_limit.h"
  27. #include "core/hle/kernel/k_scheduler.h"
  28. #include "core/hle/kernel/k_scoped_resource_reservation.h"
  29. #include "core/hle/kernel/k_shared_memory.h"
  30. #include "core/hle/kernel/k_synchronization_object.h"
  31. #include "core/hle/kernel/k_thread.h"
  32. #include "core/hle/kernel/k_thread_queue.h"
  33. #include "core/hle/kernel/k_transfer_memory.h"
  34. #include "core/hle/kernel/k_writable_event.h"
  35. #include "core/hle/kernel/kernel.h"
  36. #include "core/hle/kernel/physical_core.h"
  37. #include "core/hle/kernel/svc.h"
  38. #include "core/hle/kernel/svc_results.h"
  39. #include "core/hle/kernel/svc_types.h"
  40. #include "core/hle/kernel/svc_wrap.h"
  41. #include "core/hle/lock.h"
  42. #include "core/hle/result.h"
  43. #include "core/memory.h"
  44. #include "core/reporter.h"
  45. namespace Kernel::Svc {
  46. namespace {
  47. // Checks if address + size is greater than the given address
  48. // This can return false if the size causes an overflow of a 64-bit type
  49. // or if the given size is zero.
  50. constexpr bool IsValidAddressRange(VAddr address, u64 size) {
  51. return address + size > address;
  52. }
  53. // Helper function that performs the common sanity checks for svcMapMemory
  54. // and svcUnmapMemory. This is doable, as both functions perform their sanitizing
  55. // in the same order.
  56. ResultCode MapUnmapMemorySanityChecks(const KPageTable& manager, VAddr dst_addr, VAddr src_addr,
  57. u64 size) {
  58. if (!Common::Is4KBAligned(dst_addr)) {
  59. LOG_ERROR(Kernel_SVC, "Destination address is not aligned to 4KB, 0x{:016X}", dst_addr);
  60. return ResultInvalidAddress;
  61. }
  62. if (!Common::Is4KBAligned(src_addr)) {
  63. LOG_ERROR(Kernel_SVC, "Source address is not aligned to 4KB, 0x{:016X}", src_addr);
  64. return ResultInvalidSize;
  65. }
  66. if (size == 0) {
  67. LOG_ERROR(Kernel_SVC, "Size is 0");
  68. return ResultInvalidSize;
  69. }
  70. if (!Common::Is4KBAligned(size)) {
  71. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, 0x{:016X}", size);
  72. return ResultInvalidSize;
  73. }
  74. if (!IsValidAddressRange(dst_addr, size)) {
  75. LOG_ERROR(Kernel_SVC,
  76. "Destination is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
  77. dst_addr, size);
  78. return ResultInvalidCurrentMemory;
  79. }
  80. if (!IsValidAddressRange(src_addr, size)) {
  81. LOG_ERROR(Kernel_SVC, "Source is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
  82. src_addr, size);
  83. return ResultInvalidCurrentMemory;
  84. }
  85. if (!manager.IsInsideAddressSpace(src_addr, size)) {
  86. LOG_ERROR(Kernel_SVC,
  87. "Source is not within the address space, addr=0x{:016X}, size=0x{:016X}",
  88. src_addr, size);
  89. return ResultInvalidCurrentMemory;
  90. }
  91. if (manager.IsOutsideStackRegion(dst_addr, size)) {
  92. LOG_ERROR(Kernel_SVC,
  93. "Destination is not within the stack region, addr=0x{:016X}, size=0x{:016X}",
  94. dst_addr, size);
  95. return ResultInvalidMemoryRegion;
  96. }
  97. if (manager.IsInsideHeapRegion(dst_addr, size)) {
  98. LOG_ERROR(Kernel_SVC,
  99. "Destination does not fit within the heap region, addr=0x{:016X}, "
  100. "size=0x{:016X}",
  101. dst_addr, size);
  102. return ResultInvalidMemoryRegion;
  103. }
  104. if (manager.IsInsideAliasRegion(dst_addr, size)) {
  105. LOG_ERROR(Kernel_SVC,
  106. "Destination does not fit within the map region, addr=0x{:016X}, "
  107. "size=0x{:016X}",
  108. dst_addr, size);
  109. return ResultInvalidMemoryRegion;
  110. }
  111. return ResultSuccess;
  112. }
  113. enum class ResourceLimitValueType {
  114. CurrentValue,
  115. LimitValue,
  116. PeakValue,
  117. };
  118. } // Anonymous namespace
  119. /// Set the process heap to a given Size. It can both extend and shrink the heap.
  120. static ResultCode SetHeapSize(Core::System& system, VAddr* heap_addr, u64 heap_size) {
  121. std::lock_guard lock{HLE::g_hle_lock};
  122. LOG_TRACE(Kernel_SVC, "called, heap_size=0x{:X}", heap_size);
  123. // Size must be a multiple of 0x200000 (2MB) and be equal to or less than 8GB.
  124. if ((heap_size % 0x200000) != 0) {
  125. LOG_ERROR(Kernel_SVC, "The heap size is not a multiple of 2MB, heap_size=0x{:016X}",
  126. heap_size);
  127. return ResultInvalidSize;
  128. }
  129. if (heap_size >= 0x200000000) {
  130. LOG_ERROR(Kernel_SVC, "The heap size is not less than 8GB, heap_size=0x{:016X}", heap_size);
  131. return ResultInvalidSize;
  132. }
  133. auto& page_table{system.Kernel().CurrentProcess()->PageTable()};
  134. CASCADE_RESULT(*heap_addr, page_table.SetHeapSize(heap_size));
  135. return ResultSuccess;
  136. }
  137. static ResultCode SetHeapSize32(Core::System& system, u32* heap_addr, u32 heap_size) {
  138. VAddr temp_heap_addr{};
  139. const ResultCode result{SetHeapSize(system, &temp_heap_addr, heap_size)};
  140. *heap_addr = static_cast<u32>(temp_heap_addr);
  141. return result;
  142. }
  143. static ResultCode SetMemoryAttribute(Core::System& system, VAddr address, u64 size, u32 mask,
  144. u32 attribute) {
  145. std::lock_guard lock{HLE::g_hle_lock};
  146. LOG_DEBUG(Kernel_SVC,
  147. "called, address=0x{:016X}, size=0x{:X}, mask=0x{:08X}, attribute=0x{:08X}", address,
  148. size, mask, attribute);
  149. if (!Common::Is4KBAligned(address)) {
  150. LOG_ERROR(Kernel_SVC, "Address not page aligned (0x{:016X})", address);
  151. return ResultInvalidAddress;
  152. }
  153. if (size == 0 || !Common::Is4KBAligned(size)) {
  154. LOG_ERROR(Kernel_SVC, "Invalid size (0x{:X}). Size must be non-zero and page aligned.",
  155. size);
  156. return ResultInvalidAddress;
  157. }
  158. if (!IsValidAddressRange(address, size)) {
  159. LOG_ERROR(Kernel_SVC, "Address range overflowed (Address: 0x{:016X}, Size: 0x{:016X})",
  160. address, size);
  161. return ResultInvalidCurrentMemory;
  162. }
  163. const auto attributes{static_cast<MemoryAttribute>(mask | attribute)};
  164. if (attributes != static_cast<MemoryAttribute>(mask) ||
  165. (attributes | MemoryAttribute::Uncached) != MemoryAttribute::Uncached) {
  166. LOG_ERROR(Kernel_SVC,
  167. "Memory attribute doesn't match the given mask (Attribute: 0x{:X}, Mask: {:X}",
  168. attribute, mask);
  169. return ResultInvalidCombination;
  170. }
  171. auto& page_table{system.Kernel().CurrentProcess()->PageTable()};
  172. return page_table.SetMemoryAttribute(address, size, static_cast<KMemoryAttribute>(mask),
  173. static_cast<KMemoryAttribute>(attribute));
  174. }
  175. static ResultCode SetMemoryAttribute32(Core::System& system, u32 address, u32 size, u32 mask,
  176. u32 attribute) {
  177. return SetMemoryAttribute(system, address, size, mask, attribute);
  178. }
  179. /// Maps a memory range into a different range.
  180. static ResultCode MapMemory(Core::System& system, VAddr dst_addr, VAddr src_addr, u64 size) {
  181. std::lock_guard lock{HLE::g_hle_lock};
  182. LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr,
  183. src_addr, size);
  184. auto& page_table{system.Kernel().CurrentProcess()->PageTable()};
  185. if (const ResultCode result{MapUnmapMemorySanityChecks(page_table, dst_addr, src_addr, size)};
  186. result.IsError()) {
  187. return result;
  188. }
  189. return page_table.Map(dst_addr, src_addr, size);
  190. }
  191. static ResultCode MapMemory32(Core::System& system, u32 dst_addr, u32 src_addr, u32 size) {
  192. return MapMemory(system, dst_addr, src_addr, size);
  193. }
  194. /// Unmaps a region that was previously mapped with svcMapMemory
  195. static ResultCode UnmapMemory(Core::System& system, VAddr dst_addr, VAddr src_addr, u64 size) {
  196. std::lock_guard lock{HLE::g_hle_lock};
  197. LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr,
  198. src_addr, size);
  199. auto& page_table{system.Kernel().CurrentProcess()->PageTable()};
  200. if (const ResultCode result{MapUnmapMemorySanityChecks(page_table, dst_addr, src_addr, size)};
  201. result.IsError()) {
  202. return result;
  203. }
  204. return page_table.Unmap(dst_addr, src_addr, size);
  205. }
  206. static ResultCode UnmapMemory32(Core::System& system, u32 dst_addr, u32 src_addr, u32 size) {
  207. return UnmapMemory(system, dst_addr, src_addr, size);
  208. }
  209. /// Connect to an OS service given the port name, returns the handle to the port to out
  210. static ResultCode ConnectToNamedPort(Core::System& system, Handle* out, VAddr port_name_address) {
  211. auto& memory = system.Memory();
  212. if (!memory.IsValidVirtualAddress(port_name_address)) {
  213. LOG_ERROR(Kernel_SVC,
  214. "Port Name Address is not a valid virtual address, port_name_address=0x{:016X}",
  215. port_name_address);
  216. return ResultNotFound;
  217. }
  218. static constexpr std::size_t PortNameMaxLength = 11;
  219. // Read 1 char beyond the max allowed port name to detect names that are too long.
  220. const std::string port_name = memory.ReadCString(port_name_address, PortNameMaxLength + 1);
  221. if (port_name.size() > PortNameMaxLength) {
  222. LOG_ERROR(Kernel_SVC, "Port name is too long, expected {} but got {}", PortNameMaxLength,
  223. port_name.size());
  224. return ResultOutOfRange;
  225. }
  226. LOG_TRACE(Kernel_SVC, "called port_name={}", port_name);
  227. // Get the current handle table.
  228. auto& kernel = system.Kernel();
  229. auto& handle_table = kernel.CurrentProcess()->GetHandleTable();
  230. // Find the client port.
  231. auto port = kernel.CreateNamedServicePort(port_name);
  232. if (!port) {
  233. LOG_ERROR(Kernel_SVC, "tried to connect to unknown port: {}", port_name);
  234. return ResultNotFound;
  235. }
  236. // Reserve a handle for the port.
  237. // NOTE: Nintendo really does write directly to the output handle here.
  238. R_TRY(handle_table.Reserve(out));
  239. auto handle_guard = SCOPE_GUARD({ handle_table.Unreserve(*out); });
  240. // Create a session.
  241. KClientSession* session{};
  242. R_TRY(port->CreateSession(std::addressof(session)));
  243. port->Close();
  244. // Register the session in the table, close the extra reference.
  245. handle_table.Register(*out, session);
  246. session->Close();
  247. // We succeeded.
  248. handle_guard.Cancel();
  249. return ResultSuccess;
  250. }
  251. static ResultCode ConnectToNamedPort32(Core::System& system, Handle* out_handle,
  252. u32 port_name_address) {
  253. return ConnectToNamedPort(system, out_handle, port_name_address);
  254. }
  255. /// Makes a blocking IPC call to an OS service.
  256. static ResultCode SendSyncRequest(Core::System& system, Handle handle) {
  257. auto& kernel = system.Kernel();
  258. // Create the wait queue.
  259. KThreadQueue wait_queue(kernel);
  260. // Get the client session from its handle.
  261. KScopedAutoObject session =
  262. kernel.CurrentProcess()->GetHandleTable().GetObject<KClientSession>(handle);
  263. R_UNLESS(session.IsNotNull(), ResultInvalidHandle);
  264. LOG_TRACE(Kernel_SVC, "called handle=0x{:08X}({})", handle, session->GetName());
  265. auto thread = kernel.CurrentScheduler()->GetCurrentThread();
  266. {
  267. KScopedSchedulerLock lock(kernel);
  268. // This is a synchronous request, so we should wait for our request to complete.
  269. GetCurrentThread(kernel).BeginWait(std::addressof(wait_queue));
  270. GetCurrentThread(kernel).SetWaitReasonForDebugging(ThreadWaitReasonForDebugging::IPC);
  271. session->SendSyncRequest(&GetCurrentThread(kernel), system.Memory(), system.CoreTiming());
  272. }
  273. return thread->GetWaitResult();
  274. }
  275. static ResultCode SendSyncRequest32(Core::System& system, Handle handle) {
  276. return SendSyncRequest(system, handle);
  277. }
  278. /// Get the ID for the specified thread.
  279. static ResultCode GetThreadId(Core::System& system, u64* out_thread_id, Handle thread_handle) {
  280. // Get the thread from its handle.
  281. KScopedAutoObject thread =
  282. system.Kernel().CurrentProcess()->GetHandleTable().GetObject<KThread>(thread_handle);
  283. R_UNLESS(thread.IsNotNull(), ResultInvalidHandle);
  284. // Get the thread's id.
  285. *out_thread_id = thread->GetId();
  286. return ResultSuccess;
  287. }
  288. static ResultCode GetThreadId32(Core::System& system, u32* out_thread_id_low,
  289. u32* out_thread_id_high, Handle thread_handle) {
  290. u64 out_thread_id{};
  291. const ResultCode result{GetThreadId(system, &out_thread_id, thread_handle)};
  292. *out_thread_id_low = static_cast<u32>(out_thread_id >> 32);
  293. *out_thread_id_high = static_cast<u32>(out_thread_id & std::numeric_limits<u32>::max());
  294. return result;
  295. }
  296. /// Gets the ID of the specified process or a specified thread's owning process.
  297. static ResultCode GetProcessId(Core::System& system, u64* out_process_id, Handle handle) {
  298. LOG_DEBUG(Kernel_SVC, "called handle=0x{:08X}", handle);
  299. // Get the object from the handle table.
  300. KScopedAutoObject obj =
  301. system.Kernel().CurrentProcess()->GetHandleTable().GetObject<KAutoObject>(
  302. static_cast<Handle>(handle));
  303. R_UNLESS(obj.IsNotNull(), ResultInvalidHandle);
  304. // Get the process from the object.
  305. KProcess* process = nullptr;
  306. if (KProcess* p = obj->DynamicCast<KProcess*>(); p != nullptr) {
  307. // The object is a process, so we can use it directly.
  308. process = p;
  309. } else if (KThread* t = obj->DynamicCast<KThread*>(); t != nullptr) {
  310. // The object is a thread, so we want to use its parent.
  311. process = reinterpret_cast<KThread*>(obj.GetPointerUnsafe())->GetOwnerProcess();
  312. } else {
  313. // TODO(bunnei): This should also handle debug objects before returning.
  314. UNIMPLEMENTED_MSG("Debug objects not implemented");
  315. }
  316. // Make sure the target process exists.
  317. R_UNLESS(process != nullptr, ResultInvalidHandle);
  318. // Get the process id.
  319. *out_process_id = process->GetId();
  320. return ResultInvalidHandle;
  321. }
  322. static ResultCode GetProcessId32(Core::System& system, u32* out_process_id_low,
  323. u32* out_process_id_high, Handle handle) {
  324. u64 out_process_id{};
  325. const auto result = GetProcessId(system, &out_process_id, handle);
  326. *out_process_id_low = static_cast<u32>(out_process_id);
  327. *out_process_id_high = static_cast<u32>(out_process_id >> 32);
  328. return result;
  329. }
  330. /// Wait for the given handles to synchronize, timeout after the specified nanoseconds
  331. static ResultCode WaitSynchronization(Core::System& system, s32* index, VAddr handles_address,
  332. s32 num_handles, s64 nano_seconds) {
  333. LOG_TRACE(Kernel_SVC, "called handles_address=0x{:X}, num_handles={}, nano_seconds={}",
  334. handles_address, num_handles, nano_seconds);
  335. // Ensure number of handles is valid.
  336. R_UNLESS(0 <= num_handles && num_handles <= ArgumentHandleCountMax, ResultOutOfRange);
  337. auto& kernel = system.Kernel();
  338. std::vector<KSynchronizationObject*> objs(num_handles);
  339. const auto& handle_table = kernel.CurrentProcess()->GetHandleTable();
  340. Handle* handles = system.Memory().GetPointer<Handle>(handles_address);
  341. // Copy user handles.
  342. if (num_handles > 0) {
  343. // Convert the handles to objects.
  344. R_UNLESS(handle_table.GetMultipleObjects<KSynchronizationObject>(objs.data(), handles,
  345. num_handles),
  346. ResultInvalidHandle);
  347. for (const auto& obj : objs) {
  348. kernel.RegisterInUseObject(obj);
  349. }
  350. }
  351. // Ensure handles are closed when we're done.
  352. SCOPE_EXIT({
  353. for (s32 i = 0; i < num_handles; ++i) {
  354. kernel.UnregisterInUseObject(objs[i]);
  355. objs[i]->Close();
  356. }
  357. });
  358. return KSynchronizationObject::Wait(kernel, index, objs.data(), static_cast<s32>(objs.size()),
  359. nano_seconds);
  360. }
  361. static ResultCode WaitSynchronization32(Core::System& system, u32 timeout_low, u32 handles_address,
  362. s32 num_handles, u32 timeout_high, s32* index) {
  363. const s64 nano_seconds{(static_cast<s64>(timeout_high) << 32) | static_cast<s64>(timeout_low)};
  364. return WaitSynchronization(system, index, handles_address, num_handles, nano_seconds);
  365. }
  366. /// Resumes a thread waiting on WaitSynchronization
  367. static ResultCode CancelSynchronization(Core::System& system, Handle handle) {
  368. LOG_TRACE(Kernel_SVC, "called handle=0x{:X}", handle);
  369. // Get the thread from its handle.
  370. KScopedAutoObject thread =
  371. system.Kernel().CurrentProcess()->GetHandleTable().GetObject<KThread>(handle);
  372. R_UNLESS(thread.IsNotNull(), ResultInvalidHandle);
  373. // Cancel the thread's wait.
  374. thread->WaitCancel();
  375. return ResultSuccess;
  376. }
  377. static ResultCode CancelSynchronization32(Core::System& system, Handle handle) {
  378. return CancelSynchronization(system, handle);
  379. }
  380. /// Attempts to locks a mutex
  381. static ResultCode ArbitrateLock(Core::System& system, Handle thread_handle, VAddr address,
  382. u32 tag) {
  383. LOG_TRACE(Kernel_SVC, "called thread_handle=0x{:08X}, address=0x{:X}, tag=0x{:08X}",
  384. thread_handle, address, tag);
  385. // Validate the input address.
  386. if (IsKernelAddress(address)) {
  387. LOG_ERROR(Kernel_SVC, "Attempting to arbitrate a lock on a kernel address (address={:08X})",
  388. address);
  389. return ResultInvalidCurrentMemory;
  390. }
  391. if (!Common::IsAligned(address, sizeof(u32))) {
  392. LOG_ERROR(Kernel_SVC, "Input address must be 4 byte aligned (address: {:08X})", address);
  393. return ResultInvalidAddress;
  394. }
  395. return system.Kernel().CurrentProcess()->WaitForAddress(thread_handle, address, tag);
  396. }
  397. static ResultCode ArbitrateLock32(Core::System& system, Handle thread_handle, u32 address,
  398. u32 tag) {
  399. return ArbitrateLock(system, thread_handle, address, tag);
  400. }
  401. /// Unlock a mutex
  402. static ResultCode ArbitrateUnlock(Core::System& system, VAddr address) {
  403. LOG_TRACE(Kernel_SVC, "called address=0x{:X}", address);
  404. // Validate the input address.
  405. if (IsKernelAddress(address)) {
  406. LOG_ERROR(Kernel_SVC,
  407. "Attempting to arbitrate an unlock on a kernel address (address={:08X})",
  408. address);
  409. return ResultInvalidCurrentMemory;
  410. }
  411. if (!Common::IsAligned(address, sizeof(u32))) {
  412. LOG_ERROR(Kernel_SVC, "Input address must be 4 byte aligned (address: {:08X})", address);
  413. return ResultInvalidAddress;
  414. }
  415. return system.Kernel().CurrentProcess()->SignalToAddress(address);
  416. }
  417. static ResultCode ArbitrateUnlock32(Core::System& system, u32 address) {
  418. return ArbitrateUnlock(system, address);
  419. }
  420. enum class BreakType : u32 {
  421. Panic = 0,
  422. AssertionFailed = 1,
  423. PreNROLoad = 3,
  424. PostNROLoad = 4,
  425. PreNROUnload = 5,
  426. PostNROUnload = 6,
  427. CppException = 7,
  428. };
  429. struct BreakReason {
  430. union {
  431. u32 raw;
  432. BitField<0, 30, BreakType> break_type;
  433. BitField<31, 1, u32> signal_debugger;
  434. };
  435. };
  436. /// Break program execution
  437. static void Break(Core::System& system, u32 reason, u64 info1, u64 info2) {
  438. BreakReason break_reason{reason};
  439. bool has_dumped_buffer{};
  440. std::vector<u8> debug_buffer;
  441. const auto handle_debug_buffer = [&](VAddr addr, u64 sz) {
  442. if (sz == 0 || addr == 0 || has_dumped_buffer) {
  443. return;
  444. }
  445. auto& memory = system.Memory();
  446. // This typically is an error code so we're going to assume this is the case
  447. if (sz == sizeof(u32)) {
  448. LOG_CRITICAL(Debug_Emulated, "debug_buffer_err_code={:X}", memory.Read32(addr));
  449. } else {
  450. // We don't know what's in here so we'll hexdump it
  451. debug_buffer.resize(sz);
  452. memory.ReadBlock(addr, debug_buffer.data(), sz);
  453. std::string hexdump;
  454. for (std::size_t i = 0; i < debug_buffer.size(); i++) {
  455. hexdump += fmt::format("{:02X} ", debug_buffer[i]);
  456. if (i != 0 && i % 16 == 0) {
  457. hexdump += '\n';
  458. }
  459. }
  460. LOG_CRITICAL(Debug_Emulated, "debug_buffer=\n{}", hexdump);
  461. }
  462. has_dumped_buffer = true;
  463. };
  464. switch (break_reason.break_type) {
  465. case BreakType::Panic:
  466. LOG_CRITICAL(Debug_Emulated, "Signalling debugger, PANIC! info1=0x{:016X}, info2=0x{:016X}",
  467. info1, info2);
  468. handle_debug_buffer(info1, info2);
  469. break;
  470. case BreakType::AssertionFailed:
  471. LOG_CRITICAL(Debug_Emulated,
  472. "Signalling debugger, Assertion failed! info1=0x{:016X}, info2=0x{:016X}",
  473. info1, info2);
  474. handle_debug_buffer(info1, info2);
  475. break;
  476. case BreakType::PreNROLoad:
  477. LOG_WARNING(
  478. Debug_Emulated,
  479. "Signalling debugger, Attempting to load an NRO at 0x{:016X} with size 0x{:016X}",
  480. info1, info2);
  481. break;
  482. case BreakType::PostNROLoad:
  483. LOG_WARNING(Debug_Emulated,
  484. "Signalling debugger, Loaded an NRO at 0x{:016X} with size 0x{:016X}", info1,
  485. info2);
  486. break;
  487. case BreakType::PreNROUnload:
  488. LOG_WARNING(
  489. Debug_Emulated,
  490. "Signalling debugger, Attempting to unload an NRO at 0x{:016X} with size 0x{:016X}",
  491. info1, info2);
  492. break;
  493. case BreakType::PostNROUnload:
  494. LOG_WARNING(Debug_Emulated,
  495. "Signalling debugger, Unloaded an NRO at 0x{:016X} with size 0x{:016X}", info1,
  496. info2);
  497. break;
  498. case BreakType::CppException:
  499. LOG_CRITICAL(Debug_Emulated, "Signalling debugger. Uncaught C++ exception encountered.");
  500. break;
  501. default:
  502. LOG_WARNING(
  503. Debug_Emulated,
  504. "Signalling debugger, Unknown break reason {}, info1=0x{:016X}, info2=0x{:016X}",
  505. static_cast<u32>(break_reason.break_type.Value()), info1, info2);
  506. handle_debug_buffer(info1, info2);
  507. break;
  508. }
  509. system.GetReporter().SaveSvcBreakReport(
  510. static_cast<u32>(break_reason.break_type.Value()), break_reason.signal_debugger, info1,
  511. info2, has_dumped_buffer ? std::make_optional(debug_buffer) : std::nullopt);
  512. if (!break_reason.signal_debugger) {
  513. LOG_CRITICAL(
  514. Debug_Emulated,
  515. "Emulated program broke execution! reason=0x{:016X}, info1=0x{:016X}, info2=0x{:016X}",
  516. reason, info1, info2);
  517. handle_debug_buffer(info1, info2);
  518. auto* const current_thread = system.Kernel().CurrentScheduler()->GetCurrentThread();
  519. const auto thread_processor_id = current_thread->GetActiveCore();
  520. system.ArmInterface(static_cast<std::size_t>(thread_processor_id)).LogBacktrace();
  521. }
  522. }
  523. static void Break32(Core::System& system, u32 reason, u32 info1, u32 info2) {
  524. Break(system, reason, info1, info2);
  525. }
  526. /// Used to output a message on a debug hardware unit - does nothing on a retail unit
  527. static void OutputDebugString(Core::System& system, VAddr address, u64 len) {
  528. if (len == 0) {
  529. return;
  530. }
  531. std::string str(len, '\0');
  532. system.Memory().ReadBlock(address, str.data(), str.size());
  533. LOG_DEBUG(Debug_Emulated, "{}", str);
  534. }
  535. /// Gets system/memory information for the current process
  536. static ResultCode GetInfo(Core::System& system, u64* result, u64 info_id, Handle handle,
  537. u64 info_sub_id) {
  538. std::lock_guard lock{HLE::g_hle_lock};
  539. LOG_TRACE(Kernel_SVC, "called info_id=0x{:X}, info_sub_id=0x{:X}, handle=0x{:08X}", info_id,
  540. info_sub_id, handle);
  541. enum class GetInfoType : u64 {
  542. // 1.0.0+
  543. AllowedCPUCoreMask = 0,
  544. AllowedThreadPriorityMask = 1,
  545. MapRegionBaseAddr = 2,
  546. MapRegionSize = 3,
  547. HeapRegionBaseAddr = 4,
  548. HeapRegionSize = 5,
  549. TotalPhysicalMemoryAvailable = 6,
  550. TotalPhysicalMemoryUsed = 7,
  551. IsCurrentProcessBeingDebugged = 8,
  552. RegisterResourceLimit = 9,
  553. IdleTickCount = 10,
  554. RandomEntropy = 11,
  555. ThreadTickCount = 0xF0000002,
  556. // 2.0.0+
  557. ASLRRegionBaseAddr = 12,
  558. ASLRRegionSize = 13,
  559. StackRegionBaseAddr = 14,
  560. StackRegionSize = 15,
  561. // 3.0.0+
  562. SystemResourceSize = 16,
  563. SystemResourceUsage = 17,
  564. TitleId = 18,
  565. // 4.0.0+
  566. PrivilegedProcessId = 19,
  567. // 5.0.0+
  568. UserExceptionContextAddr = 20,
  569. // 6.0.0+
  570. TotalPhysicalMemoryAvailableWithoutSystemResource = 21,
  571. TotalPhysicalMemoryUsedWithoutSystemResource = 22,
  572. };
  573. const auto info_id_type = static_cast<GetInfoType>(info_id);
  574. switch (info_id_type) {
  575. case GetInfoType::AllowedCPUCoreMask:
  576. case GetInfoType::AllowedThreadPriorityMask:
  577. case GetInfoType::MapRegionBaseAddr:
  578. case GetInfoType::MapRegionSize:
  579. case GetInfoType::HeapRegionBaseAddr:
  580. case GetInfoType::HeapRegionSize:
  581. case GetInfoType::ASLRRegionBaseAddr:
  582. case GetInfoType::ASLRRegionSize:
  583. case GetInfoType::StackRegionBaseAddr:
  584. case GetInfoType::StackRegionSize:
  585. case GetInfoType::TotalPhysicalMemoryAvailable:
  586. case GetInfoType::TotalPhysicalMemoryUsed:
  587. case GetInfoType::SystemResourceSize:
  588. case GetInfoType::SystemResourceUsage:
  589. case GetInfoType::TitleId:
  590. case GetInfoType::UserExceptionContextAddr:
  591. case GetInfoType::TotalPhysicalMemoryAvailableWithoutSystemResource:
  592. case GetInfoType::TotalPhysicalMemoryUsedWithoutSystemResource: {
  593. if (info_sub_id != 0) {
  594. LOG_ERROR(Kernel_SVC, "Info sub id is non zero! info_id={}, info_sub_id={}", info_id,
  595. info_sub_id);
  596. return ResultInvalidEnumValue;
  597. }
  598. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  599. KScopedAutoObject process = handle_table.GetObject<KProcess>(handle);
  600. if (process.IsNull()) {
  601. LOG_ERROR(Kernel_SVC, "Process is not valid! info_id={}, info_sub_id={}, handle={:08X}",
  602. info_id, info_sub_id, handle);
  603. return ResultInvalidHandle;
  604. }
  605. switch (info_id_type) {
  606. case GetInfoType::AllowedCPUCoreMask:
  607. *result = process->GetCoreMask();
  608. return ResultSuccess;
  609. case GetInfoType::AllowedThreadPriorityMask:
  610. *result = process->GetPriorityMask();
  611. return ResultSuccess;
  612. case GetInfoType::MapRegionBaseAddr:
  613. *result = process->PageTable().GetAliasRegionStart();
  614. return ResultSuccess;
  615. case GetInfoType::MapRegionSize:
  616. *result = process->PageTable().GetAliasRegionSize();
  617. return ResultSuccess;
  618. case GetInfoType::HeapRegionBaseAddr:
  619. *result = process->PageTable().GetHeapRegionStart();
  620. return ResultSuccess;
  621. case GetInfoType::HeapRegionSize:
  622. *result = process->PageTable().GetHeapRegionSize();
  623. return ResultSuccess;
  624. case GetInfoType::ASLRRegionBaseAddr:
  625. *result = process->PageTable().GetAliasCodeRegionStart();
  626. return ResultSuccess;
  627. case GetInfoType::ASLRRegionSize:
  628. *result = process->PageTable().GetAliasCodeRegionSize();
  629. return ResultSuccess;
  630. case GetInfoType::StackRegionBaseAddr:
  631. *result = process->PageTable().GetStackRegionStart();
  632. return ResultSuccess;
  633. case GetInfoType::StackRegionSize:
  634. *result = process->PageTable().GetStackRegionSize();
  635. return ResultSuccess;
  636. case GetInfoType::TotalPhysicalMemoryAvailable:
  637. *result = process->GetTotalPhysicalMemoryAvailable();
  638. return ResultSuccess;
  639. case GetInfoType::TotalPhysicalMemoryUsed:
  640. *result = process->GetTotalPhysicalMemoryUsed();
  641. return ResultSuccess;
  642. case GetInfoType::SystemResourceSize:
  643. *result = process->GetSystemResourceSize();
  644. return ResultSuccess;
  645. case GetInfoType::SystemResourceUsage:
  646. LOG_WARNING(Kernel_SVC, "(STUBBED) Attempted to query system resource usage");
  647. *result = process->GetSystemResourceUsage();
  648. return ResultSuccess;
  649. case GetInfoType::TitleId:
  650. *result = process->GetProgramID();
  651. return ResultSuccess;
  652. case GetInfoType::UserExceptionContextAddr:
  653. *result = process->GetTLSRegionAddress();
  654. return ResultSuccess;
  655. case GetInfoType::TotalPhysicalMemoryAvailableWithoutSystemResource:
  656. *result = process->GetTotalPhysicalMemoryAvailableWithoutSystemResource();
  657. return ResultSuccess;
  658. case GetInfoType::TotalPhysicalMemoryUsedWithoutSystemResource:
  659. *result = process->GetTotalPhysicalMemoryUsedWithoutSystemResource();
  660. return ResultSuccess;
  661. default:
  662. break;
  663. }
  664. LOG_ERROR(Kernel_SVC, "Unimplemented svcGetInfo id=0x{:016X}", info_id);
  665. return ResultInvalidEnumValue;
  666. }
  667. case GetInfoType::IsCurrentProcessBeingDebugged:
  668. *result = 0;
  669. return ResultSuccess;
  670. case GetInfoType::RegisterResourceLimit: {
  671. if (handle != 0) {
  672. LOG_ERROR(Kernel, "Handle is non zero! handle={:08X}", handle);
  673. return ResultInvalidHandle;
  674. }
  675. if (info_sub_id != 0) {
  676. LOG_ERROR(Kernel, "Info sub id is non zero! info_id={}, info_sub_id={}", info_id,
  677. info_sub_id);
  678. return ResultInvalidCombination;
  679. }
  680. KProcess* const current_process = system.Kernel().CurrentProcess();
  681. KHandleTable& handle_table = current_process->GetHandleTable();
  682. const auto resource_limit = current_process->GetResourceLimit();
  683. if (!resource_limit) {
  684. *result = Svc::InvalidHandle;
  685. // Yes, the kernel considers this a successful operation.
  686. return ResultSuccess;
  687. }
  688. Handle resource_handle{};
  689. R_TRY(handle_table.Add(&resource_handle, resource_limit));
  690. *result = resource_handle;
  691. return ResultSuccess;
  692. }
  693. case GetInfoType::RandomEntropy:
  694. if (handle != 0) {
  695. LOG_ERROR(Kernel_SVC, "Process Handle is non zero, expected 0 result but got {:016X}",
  696. handle);
  697. return ResultInvalidHandle;
  698. }
  699. if (info_sub_id >= KProcess::RANDOM_ENTROPY_SIZE) {
  700. LOG_ERROR(Kernel_SVC, "Entropy size is out of range, expected {} but got {}",
  701. KProcess::RANDOM_ENTROPY_SIZE, info_sub_id);
  702. return ResultInvalidCombination;
  703. }
  704. *result = system.Kernel().CurrentProcess()->GetRandomEntropy(info_sub_id);
  705. return ResultSuccess;
  706. case GetInfoType::PrivilegedProcessId:
  707. LOG_WARNING(Kernel_SVC,
  708. "(STUBBED) Attempted to query privileged process id bounds, returned 0");
  709. *result = 0;
  710. return ResultSuccess;
  711. case GetInfoType::ThreadTickCount: {
  712. constexpr u64 num_cpus = 4;
  713. if (info_sub_id != 0xFFFFFFFFFFFFFFFF && info_sub_id >= num_cpus) {
  714. LOG_ERROR(Kernel_SVC, "Core count is out of range, expected {} but got {}", num_cpus,
  715. info_sub_id);
  716. return ResultInvalidCombination;
  717. }
  718. KScopedAutoObject thread =
  719. system.Kernel().CurrentProcess()->GetHandleTable().GetObject<KThread>(
  720. static_cast<Handle>(handle));
  721. if (thread.IsNull()) {
  722. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}",
  723. static_cast<Handle>(handle));
  724. return ResultInvalidHandle;
  725. }
  726. const auto& core_timing = system.CoreTiming();
  727. const auto& scheduler = *system.Kernel().CurrentScheduler();
  728. const auto* const current_thread = scheduler.GetCurrentThread();
  729. const bool same_thread = current_thread == thread.GetPointerUnsafe();
  730. const u64 prev_ctx_ticks = scheduler.GetLastContextSwitchTicks();
  731. u64 out_ticks = 0;
  732. if (same_thread && info_sub_id == 0xFFFFFFFFFFFFFFFF) {
  733. const u64 thread_ticks = current_thread->GetCpuTime();
  734. out_ticks = thread_ticks + (core_timing.GetCPUTicks() - prev_ctx_ticks);
  735. } else if (same_thread && info_sub_id == system.Kernel().CurrentPhysicalCoreIndex()) {
  736. out_ticks = core_timing.GetCPUTicks() - prev_ctx_ticks;
  737. }
  738. *result = out_ticks;
  739. return ResultSuccess;
  740. }
  741. case GetInfoType::IdleTickCount: {
  742. if (handle == 0) {
  743. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}",
  744. static_cast<Handle>(handle));
  745. return ResultInvalidHandle;
  746. }
  747. if (info_sub_id != 0xFFFFFFFFFFFFFFFF &&
  748. info_sub_id != system.Kernel().CurrentPhysicalCoreIndex()) {
  749. LOG_ERROR(Kernel_SVC, "Core is not the current core, got {}", info_sub_id);
  750. return ResultInvalidCombination;
  751. }
  752. const auto& scheduler = *system.Kernel().CurrentScheduler();
  753. const auto* const idle_thread = scheduler.GetIdleThread();
  754. *result = idle_thread->GetCpuTime();
  755. return ResultSuccess;
  756. }
  757. default:
  758. LOG_ERROR(Kernel_SVC, "Unimplemented svcGetInfo id=0x{:016X}", info_id);
  759. return ResultInvalidEnumValue;
  760. }
  761. }
  762. static ResultCode GetInfo32(Core::System& system, u32* result_low, u32* result_high, u32 sub_id_low,
  763. u32 info_id, u32 handle, u32 sub_id_high) {
  764. const u64 sub_id{u64{sub_id_low} | (u64{sub_id_high} << 32)};
  765. u64 res_value{};
  766. const ResultCode result{GetInfo(system, &res_value, info_id, handle, sub_id)};
  767. *result_high = static_cast<u32>(res_value >> 32);
  768. *result_low = static_cast<u32>(res_value & std::numeric_limits<u32>::max());
  769. return result;
  770. }
  771. /// Maps memory at a desired address
  772. static ResultCode MapPhysicalMemory(Core::System& system, VAddr addr, u64 size) {
  773. std::lock_guard lock{HLE::g_hle_lock};
  774. LOG_DEBUG(Kernel_SVC, "called, addr=0x{:016X}, size=0x{:X}", addr, size);
  775. if (!Common::Is4KBAligned(addr)) {
  776. LOG_ERROR(Kernel_SVC, "Address is not aligned to 4KB, 0x{:016X}", addr);
  777. return ResultInvalidAddress;
  778. }
  779. if (!Common::Is4KBAligned(size)) {
  780. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, 0x{:X}", size);
  781. return ResultInvalidSize;
  782. }
  783. if (size == 0) {
  784. LOG_ERROR(Kernel_SVC, "Size is zero");
  785. return ResultInvalidSize;
  786. }
  787. if (!(addr < addr + size)) {
  788. LOG_ERROR(Kernel_SVC, "Size causes 64-bit overflow of address");
  789. return ResultInvalidMemoryRegion;
  790. }
  791. KProcess* const current_process{system.Kernel().CurrentProcess()};
  792. auto& page_table{current_process->PageTable()};
  793. if (current_process->GetSystemResourceSize() == 0) {
  794. LOG_ERROR(Kernel_SVC, "System Resource Size is zero");
  795. return ResultInvalidState;
  796. }
  797. if (!page_table.IsInsideAddressSpace(addr, size)) {
  798. LOG_ERROR(Kernel_SVC,
  799. "Address is not within the address space, addr=0x{:016X}, size=0x{:016X}", addr,
  800. size);
  801. return ResultInvalidMemoryRegion;
  802. }
  803. if (page_table.IsOutsideAliasRegion(addr, size)) {
  804. LOG_ERROR(Kernel_SVC,
  805. "Address is not within the alias region, addr=0x{:016X}, size=0x{:016X}", addr,
  806. size);
  807. return ResultInvalidMemoryRegion;
  808. }
  809. return page_table.MapPhysicalMemory(addr, size);
  810. }
  811. static ResultCode MapPhysicalMemory32(Core::System& system, u32 addr, u32 size) {
  812. return MapPhysicalMemory(system, addr, size);
  813. }
  814. /// Unmaps memory previously mapped via MapPhysicalMemory
  815. static ResultCode UnmapPhysicalMemory(Core::System& system, VAddr addr, u64 size) {
  816. std::lock_guard lock{HLE::g_hle_lock};
  817. LOG_DEBUG(Kernel_SVC, "called, addr=0x{:016X}, size=0x{:X}", addr, size);
  818. if (!Common::Is4KBAligned(addr)) {
  819. LOG_ERROR(Kernel_SVC, "Address is not aligned to 4KB, 0x{:016X}", addr);
  820. return ResultInvalidAddress;
  821. }
  822. if (!Common::Is4KBAligned(size)) {
  823. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, 0x{:X}", size);
  824. return ResultInvalidSize;
  825. }
  826. if (size == 0) {
  827. LOG_ERROR(Kernel_SVC, "Size is zero");
  828. return ResultInvalidSize;
  829. }
  830. if (!(addr < addr + size)) {
  831. LOG_ERROR(Kernel_SVC, "Size causes 64-bit overflow of address");
  832. return ResultInvalidMemoryRegion;
  833. }
  834. KProcess* const current_process{system.Kernel().CurrentProcess()};
  835. auto& page_table{current_process->PageTable()};
  836. if (current_process->GetSystemResourceSize() == 0) {
  837. LOG_ERROR(Kernel_SVC, "System Resource Size is zero");
  838. return ResultInvalidState;
  839. }
  840. if (!page_table.IsInsideAddressSpace(addr, size)) {
  841. LOG_ERROR(Kernel_SVC,
  842. "Address is not within the address space, addr=0x{:016X}, size=0x{:016X}", addr,
  843. size);
  844. return ResultInvalidMemoryRegion;
  845. }
  846. if (page_table.IsOutsideAliasRegion(addr, size)) {
  847. LOG_ERROR(Kernel_SVC,
  848. "Address is not within the alias region, addr=0x{:016X}, size=0x{:016X}", addr,
  849. size);
  850. return ResultInvalidMemoryRegion;
  851. }
  852. return page_table.UnmapPhysicalMemory(addr, size);
  853. }
  854. static ResultCode UnmapPhysicalMemory32(Core::System& system, u32 addr, u32 size) {
  855. return UnmapPhysicalMemory(system, addr, size);
  856. }
  857. /// Sets the thread activity
  858. static ResultCode SetThreadActivity(Core::System& system, Handle thread_handle,
  859. ThreadActivity thread_activity) {
  860. LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, activity=0x{:08X}", thread_handle,
  861. thread_activity);
  862. // Validate the activity.
  863. constexpr auto IsValidThreadActivity = [](ThreadActivity activity) {
  864. return activity == ThreadActivity::Runnable || activity == ThreadActivity::Paused;
  865. };
  866. R_UNLESS(IsValidThreadActivity(thread_activity), ResultInvalidEnumValue);
  867. // Get the thread from its handle.
  868. KScopedAutoObject thread =
  869. system.Kernel().CurrentProcess()->GetHandleTable().GetObject<KThread>(thread_handle);
  870. R_UNLESS(thread.IsNotNull(), ResultInvalidHandle);
  871. // Check that the activity is being set on a non-current thread for the current process.
  872. R_UNLESS(thread->GetOwnerProcess() == system.Kernel().CurrentProcess(), ResultInvalidHandle);
  873. R_UNLESS(thread.GetPointerUnsafe() != GetCurrentThreadPointer(system.Kernel()), ResultBusy);
  874. // Set the activity.
  875. R_TRY(thread->SetActivity(thread_activity));
  876. return ResultSuccess;
  877. }
  878. static ResultCode SetThreadActivity32(Core::System& system, Handle thread_handle,
  879. Svc::ThreadActivity thread_activity) {
  880. return SetThreadActivity(system, thread_handle, thread_activity);
  881. }
  882. /// Gets the thread context
  883. static ResultCode GetThreadContext(Core::System& system, VAddr out_context, Handle thread_handle) {
  884. LOG_DEBUG(Kernel_SVC, "called, out_context=0x{:08X}, thread_handle=0x{:X}", out_context,
  885. thread_handle);
  886. auto& kernel = system.Kernel();
  887. // Get the thread from its handle.
  888. KScopedAutoObject thread =
  889. kernel.CurrentProcess()->GetHandleTable().GetObject<KThread>(thread_handle);
  890. R_UNLESS(thread.IsNotNull(), ResultInvalidHandle);
  891. // Require the handle be to a non-current thread in the current process.
  892. const auto* current_process = kernel.CurrentProcess();
  893. R_UNLESS(current_process == thread->GetOwnerProcess(), ResultInvalidId);
  894. // Verify that the thread isn't terminated.
  895. R_UNLESS(thread->GetState() != ThreadState::Terminated, ResultTerminationRequested);
  896. /// Check that the thread is not the current one.
  897. /// NOTE: Nintendo does not check this, and thus the following loop will deadlock.
  898. R_UNLESS(thread.GetPointerUnsafe() != GetCurrentThreadPointer(kernel), ResultInvalidId);
  899. // Try to get the thread context until the thread isn't current on any core.
  900. while (true) {
  901. KScopedSchedulerLock sl{kernel};
  902. // TODO(bunnei): Enforce that thread is suspended for debug here.
  903. // If the thread's raw state isn't runnable, check if it's current on some core.
  904. if (thread->GetRawState() != ThreadState::Runnable) {
  905. bool current = false;
  906. for (auto i = 0; i < static_cast<s32>(Core::Hardware::NUM_CPU_CORES); ++i) {
  907. if (thread.GetPointerUnsafe() == kernel.Scheduler(i).GetCurrentThread()) {
  908. current = true;
  909. break;
  910. }
  911. }
  912. // If the thread is current, retry until it isn't.
  913. if (current) {
  914. continue;
  915. }
  916. }
  917. // Get the thread context.
  918. std::vector<u8> context;
  919. R_TRY(thread->GetThreadContext3(context));
  920. // Copy the thread context to user space.
  921. system.Memory().WriteBlock(out_context, context.data(), context.size());
  922. return ResultSuccess;
  923. }
  924. return ResultSuccess;
  925. }
  926. static ResultCode GetThreadContext32(Core::System& system, u32 out_context, Handle thread_handle) {
  927. return GetThreadContext(system, out_context, thread_handle);
  928. }
  929. /// Gets the priority for the specified thread
  930. static ResultCode GetThreadPriority(Core::System& system, u32* out_priority, Handle handle) {
  931. LOG_TRACE(Kernel_SVC, "called");
  932. // Get the thread from its handle.
  933. KScopedAutoObject thread =
  934. system.Kernel().CurrentProcess()->GetHandleTable().GetObject<KThread>(handle);
  935. R_UNLESS(thread.IsNotNull(), ResultInvalidHandle);
  936. // Get the thread's priority.
  937. *out_priority = thread->GetPriority();
  938. return ResultSuccess;
  939. }
  940. static ResultCode GetThreadPriority32(Core::System& system, u32* out_priority, Handle handle) {
  941. return GetThreadPriority(system, out_priority, handle);
  942. }
  943. /// Sets the priority for the specified thread
  944. static ResultCode SetThreadPriority(Core::System& system, Handle thread_handle, u32 priority) {
  945. // Get the current process.
  946. KProcess& process = *system.Kernel().CurrentProcess();
  947. // Validate the priority.
  948. R_UNLESS(HighestThreadPriority <= priority && priority <= LowestThreadPriority,
  949. ResultInvalidPriority);
  950. R_UNLESS(process.CheckThreadPriority(priority), ResultInvalidPriority);
  951. // Get the thread from its handle.
  952. KScopedAutoObject thread = process.GetHandleTable().GetObject<KThread>(thread_handle);
  953. R_UNLESS(thread.IsNotNull(), ResultInvalidHandle);
  954. // Set the thread priority.
  955. thread->SetBasePriority(priority);
  956. return ResultSuccess;
  957. }
  958. static ResultCode SetThreadPriority32(Core::System& system, Handle thread_handle, u32 priority) {
  959. return SetThreadPriority(system, thread_handle, priority);
  960. }
  961. /// Get which CPU core is executing the current thread
  962. static u32 GetCurrentProcessorNumber(Core::System& system) {
  963. LOG_TRACE(Kernel_SVC, "called");
  964. return static_cast<u32>(system.CurrentPhysicalCore().CoreIndex());
  965. }
  966. static u32 GetCurrentProcessorNumber32(Core::System& system) {
  967. return GetCurrentProcessorNumber(system);
  968. }
  969. namespace {
  970. constexpr bool IsValidSharedMemoryPermission(Svc::MemoryPermission perm) {
  971. switch (perm) {
  972. case Svc::MemoryPermission::Read:
  973. case Svc::MemoryPermission::ReadWrite:
  974. return true;
  975. default:
  976. return false;
  977. }
  978. }
  979. [[maybe_unused]] constexpr bool IsValidRemoteSharedMemoryPermission(Svc::MemoryPermission perm) {
  980. return IsValidSharedMemoryPermission(perm) || perm == Svc::MemoryPermission::DontCare;
  981. }
  982. constexpr bool IsValidProcessMemoryPermission(Svc::MemoryPermission perm) {
  983. switch (perm) {
  984. case Svc::MemoryPermission::None:
  985. case Svc::MemoryPermission::Read:
  986. case Svc::MemoryPermission::ReadWrite:
  987. case Svc::MemoryPermission::ReadExecute:
  988. return true;
  989. default:
  990. return false;
  991. }
  992. }
  993. } // Anonymous namespace
  994. static ResultCode MapSharedMemory(Core::System& system, Handle shmem_handle, VAddr address,
  995. u64 size, Svc::MemoryPermission map_perm) {
  996. LOG_TRACE(Kernel_SVC,
  997. "called, shared_memory_handle=0x{:X}, addr=0x{:X}, size=0x{:X}, permissions=0x{:08X}",
  998. shmem_handle, address, size, map_perm);
  999. // Validate the address/size.
  1000. R_UNLESS(Common::IsAligned(address, PageSize), ResultInvalidAddress);
  1001. R_UNLESS(Common::IsAligned(size, PageSize), ResultInvalidSize);
  1002. R_UNLESS(size > 0, ResultInvalidSize);
  1003. R_UNLESS((address < address + size), ResultInvalidCurrentMemory);
  1004. // Validate the permission.
  1005. R_UNLESS(IsValidSharedMemoryPermission(map_perm), ResultInvalidNewMemoryPermission);
  1006. // Get the current process.
  1007. auto& process = *system.Kernel().CurrentProcess();
  1008. auto& page_table = process.PageTable();
  1009. // Get the shared memory.
  1010. KScopedAutoObject shmem = process.GetHandleTable().GetObject<KSharedMemory>(shmem_handle);
  1011. R_UNLESS(shmem.IsNotNull(), ResultInvalidHandle);
  1012. // Verify that the mapping is in range.
  1013. R_UNLESS(page_table.CanContain(address, size, KMemoryState::Shared), ResultInvalidMemoryRegion);
  1014. // Add the shared memory to the process.
  1015. R_TRY(process.AddSharedMemory(shmem.GetPointerUnsafe(), address, size));
  1016. // Ensure that we clean up the shared memory if we fail to map it.
  1017. auto guard =
  1018. SCOPE_GUARD({ process.RemoveSharedMemory(shmem.GetPointerUnsafe(), address, size); });
  1019. // Map the shared memory.
  1020. R_TRY(shmem->Map(process, address, size, map_perm));
  1021. // We succeeded.
  1022. guard.Cancel();
  1023. return ResultSuccess;
  1024. }
  1025. static ResultCode MapSharedMemory32(Core::System& system, Handle shmem_handle, u32 address,
  1026. u32 size, Svc::MemoryPermission map_perm) {
  1027. return MapSharedMemory(system, shmem_handle, address, size, map_perm);
  1028. }
  1029. static ResultCode UnmapSharedMemory(Core::System& system, Handle shmem_handle, VAddr address,
  1030. u64 size) {
  1031. // Validate the address/size.
  1032. R_UNLESS(Common::IsAligned(address, PageSize), ResultInvalidAddress);
  1033. R_UNLESS(Common::IsAligned(size, PageSize), ResultInvalidSize);
  1034. R_UNLESS(size > 0, ResultInvalidSize);
  1035. R_UNLESS((address < address + size), ResultInvalidCurrentMemory);
  1036. // Get the current process.
  1037. auto& process = *system.Kernel().CurrentProcess();
  1038. auto& page_table = process.PageTable();
  1039. // Get the shared memory.
  1040. KScopedAutoObject shmem = process.GetHandleTable().GetObject<KSharedMemory>(shmem_handle);
  1041. R_UNLESS(shmem.IsNotNull(), ResultInvalidHandle);
  1042. // Verify that the mapping is in range.
  1043. R_UNLESS(page_table.CanContain(address, size, KMemoryState::Shared), ResultInvalidMemoryRegion);
  1044. // Unmap the shared memory.
  1045. R_TRY(shmem->Unmap(process, address, size));
  1046. // Remove the shared memory from the process.
  1047. process.RemoveSharedMemory(shmem.GetPointerUnsafe(), address, size);
  1048. return ResultSuccess;
  1049. }
  1050. static ResultCode UnmapSharedMemory32(Core::System& system, Handle shmem_handle, u32 address,
  1051. u32 size) {
  1052. return UnmapSharedMemory(system, shmem_handle, address, size);
  1053. }
  1054. static ResultCode SetProcessMemoryPermission(Core::System& system, Handle process_handle,
  1055. VAddr address, u64 size, Svc::MemoryPermission perm) {
  1056. LOG_TRACE(Kernel_SVC,
  1057. "called, process_handle=0x{:X}, addr=0x{:X}, size=0x{:X}, permissions=0x{:08X}",
  1058. process_handle, address, size, perm);
  1059. // Validate the address/size.
  1060. R_UNLESS(Common::IsAligned(address, PageSize), ResultInvalidAddress);
  1061. R_UNLESS(Common::IsAligned(size, PageSize), ResultInvalidSize);
  1062. R_UNLESS(size > 0, ResultInvalidSize);
  1063. R_UNLESS((address < address + size), ResultInvalidCurrentMemory);
  1064. // Validate the memory permission.
  1065. R_UNLESS(IsValidProcessMemoryPermission(perm), ResultInvalidNewMemoryPermission);
  1066. // Get the process from its handle.
  1067. KScopedAutoObject process =
  1068. system.CurrentProcess()->GetHandleTable().GetObject<KProcess>(process_handle);
  1069. R_UNLESS(process.IsNotNull(), ResultInvalidHandle);
  1070. // Validate that the address is in range.
  1071. auto& page_table = process->PageTable();
  1072. R_UNLESS(page_table.Contains(address, size), ResultInvalidCurrentMemory);
  1073. // Set the memory permission.
  1074. return page_table.SetProcessMemoryPermission(address, size, ConvertToKMemoryPermission(perm));
  1075. }
  1076. static ResultCode QueryProcessMemory(Core::System& system, VAddr memory_info_address,
  1077. VAddr page_info_address, Handle process_handle,
  1078. VAddr address) {
  1079. std::lock_guard lock{HLE::g_hle_lock};
  1080. LOG_TRACE(Kernel_SVC, "called process=0x{:08X} address={:X}", process_handle, address);
  1081. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1082. KScopedAutoObject process = handle_table.GetObject<KProcess>(process_handle);
  1083. if (process.IsNull()) {
  1084. LOG_ERROR(Kernel_SVC, "Process handle does not exist, process_handle=0x{:08X}",
  1085. process_handle);
  1086. return ResultInvalidHandle;
  1087. }
  1088. auto& memory{system.Memory()};
  1089. const auto memory_info{process->PageTable().QueryInfo(address).GetSvcMemoryInfo()};
  1090. memory.Write64(memory_info_address + 0x00, memory_info.addr);
  1091. memory.Write64(memory_info_address + 0x08, memory_info.size);
  1092. memory.Write32(memory_info_address + 0x10, static_cast<u32>(memory_info.state) & 0xff);
  1093. memory.Write32(memory_info_address + 0x14, static_cast<u32>(memory_info.attr));
  1094. memory.Write32(memory_info_address + 0x18, static_cast<u32>(memory_info.perm));
  1095. memory.Write32(memory_info_address + 0x1c, memory_info.ipc_refcount);
  1096. memory.Write32(memory_info_address + 0x20, memory_info.device_refcount);
  1097. memory.Write32(memory_info_address + 0x24, 0);
  1098. // Page info appears to be currently unused by the kernel and is always set to zero.
  1099. memory.Write32(page_info_address, 0);
  1100. return ResultSuccess;
  1101. }
  1102. static ResultCode QueryMemory(Core::System& system, VAddr memory_info_address,
  1103. VAddr page_info_address, VAddr query_address) {
  1104. LOG_TRACE(Kernel_SVC,
  1105. "called, memory_info_address=0x{:016X}, page_info_address=0x{:016X}, "
  1106. "query_address=0x{:016X}",
  1107. memory_info_address, page_info_address, query_address);
  1108. return QueryProcessMemory(system, memory_info_address, page_info_address, CurrentProcess,
  1109. query_address);
  1110. }
  1111. static ResultCode QueryMemory32(Core::System& system, u32 memory_info_address,
  1112. u32 page_info_address, u32 query_address) {
  1113. return QueryMemory(system, memory_info_address, page_info_address, query_address);
  1114. }
  1115. static ResultCode MapProcessCodeMemory(Core::System& system, Handle process_handle, u64 dst_address,
  1116. u64 src_address, u64 size) {
  1117. LOG_DEBUG(Kernel_SVC,
  1118. "called. process_handle=0x{:08X}, dst_address=0x{:016X}, "
  1119. "src_address=0x{:016X}, size=0x{:016X}",
  1120. process_handle, dst_address, src_address, size);
  1121. if (!Common::Is4KBAligned(src_address)) {
  1122. LOG_ERROR(Kernel_SVC, "src_address is not page-aligned (src_address=0x{:016X}).",
  1123. src_address);
  1124. return ResultInvalidAddress;
  1125. }
  1126. if (!Common::Is4KBAligned(dst_address)) {
  1127. LOG_ERROR(Kernel_SVC, "dst_address is not page-aligned (dst_address=0x{:016X}).",
  1128. dst_address);
  1129. return ResultInvalidAddress;
  1130. }
  1131. if (size == 0 || !Common::Is4KBAligned(size)) {
  1132. LOG_ERROR(Kernel_SVC, "Size is zero or not page-aligned (size=0x{:016X})", size);
  1133. return ResultInvalidSize;
  1134. }
  1135. if (!IsValidAddressRange(dst_address, size)) {
  1136. LOG_ERROR(Kernel_SVC,
  1137. "Destination address range overflows the address space (dst_address=0x{:016X}, "
  1138. "size=0x{:016X}).",
  1139. dst_address, size);
  1140. return ResultInvalidCurrentMemory;
  1141. }
  1142. if (!IsValidAddressRange(src_address, size)) {
  1143. LOG_ERROR(Kernel_SVC,
  1144. "Source address range overflows the address space (src_address=0x{:016X}, "
  1145. "size=0x{:016X}).",
  1146. src_address, size);
  1147. return ResultInvalidCurrentMemory;
  1148. }
  1149. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1150. KScopedAutoObject process = handle_table.GetObject<KProcess>(process_handle);
  1151. if (process.IsNull()) {
  1152. LOG_ERROR(Kernel_SVC, "Invalid process handle specified (handle=0x{:08X}).",
  1153. process_handle);
  1154. return ResultInvalidHandle;
  1155. }
  1156. auto& page_table = process->PageTable();
  1157. if (!page_table.IsInsideAddressSpace(src_address, size)) {
  1158. LOG_ERROR(Kernel_SVC,
  1159. "Source address range is not within the address space (src_address=0x{:016X}, "
  1160. "size=0x{:016X}).",
  1161. src_address, size);
  1162. return ResultInvalidCurrentMemory;
  1163. }
  1164. if (!page_table.IsInsideASLRRegion(dst_address, size)) {
  1165. LOG_ERROR(Kernel_SVC,
  1166. "Destination address range is not within the ASLR region (dst_address=0x{:016X}, "
  1167. "size=0x{:016X}).",
  1168. dst_address, size);
  1169. return ResultInvalidMemoryRegion;
  1170. }
  1171. return page_table.MapProcessCodeMemory(dst_address, src_address, size);
  1172. }
  1173. static ResultCode UnmapProcessCodeMemory(Core::System& system, Handle process_handle,
  1174. u64 dst_address, u64 src_address, u64 size) {
  1175. LOG_DEBUG(Kernel_SVC,
  1176. "called. process_handle=0x{:08X}, dst_address=0x{:016X}, src_address=0x{:016X}, "
  1177. "size=0x{:016X}",
  1178. process_handle, dst_address, src_address, size);
  1179. if (!Common::Is4KBAligned(dst_address)) {
  1180. LOG_ERROR(Kernel_SVC, "dst_address is not page-aligned (dst_address=0x{:016X}).",
  1181. dst_address);
  1182. return ResultInvalidAddress;
  1183. }
  1184. if (!Common::Is4KBAligned(src_address)) {
  1185. LOG_ERROR(Kernel_SVC, "src_address is not page-aligned (src_address=0x{:016X}).",
  1186. src_address);
  1187. return ResultInvalidAddress;
  1188. }
  1189. if (size == 0 || Common::Is4KBAligned(size)) {
  1190. LOG_ERROR(Kernel_SVC, "Size is zero or not page-aligned (size=0x{:016X}).", size);
  1191. return ResultInvalidSize;
  1192. }
  1193. if (!IsValidAddressRange(dst_address, size)) {
  1194. LOG_ERROR(Kernel_SVC,
  1195. "Destination address range overflows the address space (dst_address=0x{:016X}, "
  1196. "size=0x{:016X}).",
  1197. dst_address, size);
  1198. return ResultInvalidCurrentMemory;
  1199. }
  1200. if (!IsValidAddressRange(src_address, size)) {
  1201. LOG_ERROR(Kernel_SVC,
  1202. "Source address range overflows the address space (src_address=0x{:016X}, "
  1203. "size=0x{:016X}).",
  1204. src_address, size);
  1205. return ResultInvalidCurrentMemory;
  1206. }
  1207. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1208. KScopedAutoObject process = handle_table.GetObject<KProcess>(process_handle);
  1209. if (process.IsNull()) {
  1210. LOG_ERROR(Kernel_SVC, "Invalid process handle specified (handle=0x{:08X}).",
  1211. process_handle);
  1212. return ResultInvalidHandle;
  1213. }
  1214. auto& page_table = process->PageTable();
  1215. if (!page_table.IsInsideAddressSpace(src_address, size)) {
  1216. LOG_ERROR(Kernel_SVC,
  1217. "Source address range is not within the address space (src_address=0x{:016X}, "
  1218. "size=0x{:016X}).",
  1219. src_address, size);
  1220. return ResultInvalidCurrentMemory;
  1221. }
  1222. if (!page_table.IsInsideASLRRegion(dst_address, size)) {
  1223. LOG_ERROR(Kernel_SVC,
  1224. "Destination address range is not within the ASLR region (dst_address=0x{:016X}, "
  1225. "size=0x{:016X}).",
  1226. dst_address, size);
  1227. return ResultInvalidMemoryRegion;
  1228. }
  1229. return page_table.UnmapProcessCodeMemory(dst_address, src_address, size);
  1230. }
  1231. /// Exits the current process
  1232. static void ExitProcess(Core::System& system) {
  1233. auto* current_process = system.Kernel().CurrentProcess();
  1234. UNIMPLEMENTED();
  1235. LOG_INFO(Kernel_SVC, "Process {} exiting", current_process->GetProcessID());
  1236. ASSERT_MSG(current_process->GetStatus() == ProcessStatus::Running,
  1237. "Process has already exited");
  1238. }
  1239. static void ExitProcess32(Core::System& system) {
  1240. ExitProcess(system);
  1241. }
  1242. namespace {
  1243. constexpr bool IsValidVirtualCoreId(int32_t core_id) {
  1244. return (0 <= core_id && core_id < static_cast<int32_t>(Core::Hardware::NUM_CPU_CORES));
  1245. }
  1246. } // Anonymous namespace
  1247. /// Creates a new thread
  1248. static ResultCode CreateThread(Core::System& system, Handle* out_handle, VAddr entry_point, u64 arg,
  1249. VAddr stack_bottom, u32 priority, s32 core_id) {
  1250. LOG_DEBUG(Kernel_SVC,
  1251. "called entry_point=0x{:08X}, arg=0x{:08X}, stack_bottom=0x{:08X}, "
  1252. "priority=0x{:08X}, core_id=0x{:08X}",
  1253. entry_point, arg, stack_bottom, priority, core_id);
  1254. // Adjust core id, if it's the default magic.
  1255. auto& kernel = system.Kernel();
  1256. auto& process = *kernel.CurrentProcess();
  1257. if (core_id == IdealCoreUseProcessValue) {
  1258. core_id = process.GetIdealCoreId();
  1259. }
  1260. // Validate arguments.
  1261. if (!IsValidVirtualCoreId(core_id)) {
  1262. LOG_ERROR(Kernel_SVC, "Invalid Core ID specified (id={})", core_id);
  1263. return ResultInvalidCoreId;
  1264. }
  1265. if (((1ULL << core_id) & process.GetCoreMask()) == 0) {
  1266. LOG_ERROR(Kernel_SVC, "Core ID doesn't fall within allowable cores (id={})", core_id);
  1267. return ResultInvalidCoreId;
  1268. }
  1269. if (HighestThreadPriority > priority || priority > LowestThreadPriority) {
  1270. LOG_ERROR(Kernel_SVC, "Invalid priority specified (priority={})", priority);
  1271. return ResultInvalidPriority;
  1272. }
  1273. if (!process.CheckThreadPriority(priority)) {
  1274. LOG_ERROR(Kernel_SVC, "Invalid allowable thread priority (priority={})", priority);
  1275. return ResultInvalidPriority;
  1276. }
  1277. // Reserve a new thread from the process resource limit (waiting up to 100ms).
  1278. KScopedResourceReservation thread_reservation(
  1279. kernel.CurrentProcess(), LimitableResource::Threads, 1,
  1280. system.CoreTiming().GetGlobalTimeNs().count() + 100000000);
  1281. if (!thread_reservation.Succeeded()) {
  1282. LOG_ERROR(Kernel_SVC, "Could not reserve a new thread");
  1283. return ResultLimitReached;
  1284. }
  1285. // Create the thread.
  1286. KThread* thread = KThread::Create(kernel);
  1287. if (!thread) {
  1288. LOG_ERROR(Kernel_SVC, "Unable to create new threads. Thread creation limit reached.");
  1289. return ResultOutOfResource;
  1290. }
  1291. SCOPE_EXIT({ thread->Close(); });
  1292. // Initialize the thread.
  1293. {
  1294. KScopedLightLock lk{process.GetStateLock()};
  1295. R_TRY(KThread::InitializeUserThread(system, thread, entry_point, arg, stack_bottom,
  1296. priority, core_id, &process));
  1297. }
  1298. // Set the thread name for debugging purposes.
  1299. thread->SetName(fmt::format("thread[entry_point={:X}, handle={:X}]", entry_point, *out_handle));
  1300. // Commit the thread reservation.
  1301. thread_reservation.Commit();
  1302. // Register the new thread.
  1303. KThread::Register(kernel, thread);
  1304. // Add the thread to the handle table.
  1305. R_TRY(process.GetHandleTable().Add(out_handle, thread));
  1306. return ResultSuccess;
  1307. }
  1308. static ResultCode CreateThread32(Core::System& system, Handle* out_handle, u32 priority,
  1309. u32 entry_point, u32 arg, u32 stack_top, s32 processor_id) {
  1310. return CreateThread(system, out_handle, entry_point, arg, stack_top, priority, processor_id);
  1311. }
  1312. /// Starts the thread for the provided handle
  1313. static ResultCode StartThread(Core::System& system, Handle thread_handle) {
  1314. LOG_DEBUG(Kernel_SVC, "called thread=0x{:08X}", thread_handle);
  1315. // Get the thread from its handle.
  1316. KScopedAutoObject thread =
  1317. system.Kernel().CurrentProcess()->GetHandleTable().GetObject<KThread>(thread_handle);
  1318. R_UNLESS(thread.IsNotNull(), ResultInvalidHandle);
  1319. // Try to start the thread.
  1320. R_TRY(thread->Run());
  1321. // If we succeeded, persist a reference to the thread.
  1322. thread->Open();
  1323. system.Kernel().RegisterInUseObject(thread.GetPointerUnsafe());
  1324. return ResultSuccess;
  1325. }
  1326. static ResultCode StartThread32(Core::System& system, Handle thread_handle) {
  1327. return StartThread(system, thread_handle);
  1328. }
  1329. /// Called when a thread exits
  1330. static void ExitThread(Core::System& system) {
  1331. LOG_DEBUG(Kernel_SVC, "called, pc=0x{:08X}", system.CurrentArmInterface().GetPC());
  1332. auto* const current_thread = system.Kernel().CurrentScheduler()->GetCurrentThread();
  1333. system.GlobalSchedulerContext().RemoveThread(current_thread);
  1334. current_thread->Exit();
  1335. system.Kernel().UnregisterInUseObject(current_thread);
  1336. }
  1337. static void ExitThread32(Core::System& system) {
  1338. ExitThread(system);
  1339. }
  1340. /// Sleep the current thread
  1341. static void SleepThread(Core::System& system, s64 nanoseconds) {
  1342. auto& kernel = system.Kernel();
  1343. const auto yield_type = static_cast<Svc::YieldType>(nanoseconds);
  1344. LOG_TRACE(Kernel_SVC, "called nanoseconds={}", nanoseconds);
  1345. // When the input tick is positive, sleep.
  1346. if (nanoseconds > 0) {
  1347. // Convert the timeout from nanoseconds to ticks.
  1348. // NOTE: Nintendo does not use this conversion logic in WaitSynchronization...
  1349. // Sleep.
  1350. // NOTE: Nintendo does not check the result of this sleep.
  1351. static_cast<void>(GetCurrentThread(kernel).Sleep(nanoseconds));
  1352. } else if (yield_type == Svc::YieldType::WithoutCoreMigration) {
  1353. KScheduler::YieldWithoutCoreMigration(kernel);
  1354. } else if (yield_type == Svc::YieldType::WithCoreMigration) {
  1355. KScheduler::YieldWithCoreMigration(kernel);
  1356. } else if (yield_type == Svc::YieldType::ToAnyThread) {
  1357. KScheduler::YieldToAnyThread(kernel);
  1358. } else {
  1359. // Nintendo does nothing at all if an otherwise invalid value is passed.
  1360. UNREACHABLE_MSG("Unimplemented sleep yield type '{:016X}'!", nanoseconds);
  1361. }
  1362. }
  1363. static void SleepThread32(Core::System& system, u32 nanoseconds_low, u32 nanoseconds_high) {
  1364. const auto nanoseconds = static_cast<s64>(u64{nanoseconds_low} | (u64{nanoseconds_high} << 32));
  1365. SleepThread(system, nanoseconds);
  1366. }
  1367. /// Wait process wide key atomic
  1368. static ResultCode WaitProcessWideKeyAtomic(Core::System& system, VAddr address, VAddr cv_key,
  1369. u32 tag, s64 timeout_ns) {
  1370. LOG_TRACE(Kernel_SVC, "called address={:X}, cv_key={:X}, tag=0x{:08X}, timeout_ns={}", address,
  1371. cv_key, tag, timeout_ns);
  1372. // Validate input.
  1373. if (IsKernelAddress(address)) {
  1374. LOG_ERROR(Kernel_SVC, "Attempted to wait on kernel address (address={:08X})", address);
  1375. return ResultInvalidCurrentMemory;
  1376. }
  1377. if (!Common::IsAligned(address, sizeof(s32))) {
  1378. LOG_ERROR(Kernel_SVC, "Address must be 4 byte aligned (address={:08X})", address);
  1379. return ResultInvalidAddress;
  1380. }
  1381. // Convert timeout from nanoseconds to ticks.
  1382. s64 timeout{};
  1383. if (timeout_ns > 0) {
  1384. const s64 offset_tick(timeout_ns);
  1385. if (offset_tick > 0) {
  1386. timeout = offset_tick + 2;
  1387. if (timeout <= 0) {
  1388. timeout = std::numeric_limits<s64>::max();
  1389. }
  1390. } else {
  1391. timeout = std::numeric_limits<s64>::max();
  1392. }
  1393. } else {
  1394. timeout = timeout_ns;
  1395. }
  1396. // Wait on the condition variable.
  1397. return system.Kernel().CurrentProcess()->WaitConditionVariable(
  1398. address, Common::AlignDown(cv_key, sizeof(u32)), tag, timeout);
  1399. }
  1400. static ResultCode WaitProcessWideKeyAtomic32(Core::System& system, u32 address, u32 cv_key, u32 tag,
  1401. u32 timeout_ns_low, u32 timeout_ns_high) {
  1402. const auto timeout_ns = static_cast<s64>(timeout_ns_low | (u64{timeout_ns_high} << 32));
  1403. return WaitProcessWideKeyAtomic(system, address, cv_key, tag, timeout_ns);
  1404. }
  1405. /// Signal process wide key
  1406. static void SignalProcessWideKey(Core::System& system, VAddr cv_key, s32 count) {
  1407. LOG_TRACE(Kernel_SVC, "called, cv_key=0x{:X}, count=0x{:08X}", cv_key, count);
  1408. // Signal the condition variable.
  1409. return system.Kernel().CurrentProcess()->SignalConditionVariable(
  1410. Common::AlignDown(cv_key, sizeof(u32)), count);
  1411. }
  1412. static void SignalProcessWideKey32(Core::System& system, u32 cv_key, s32 count) {
  1413. SignalProcessWideKey(system, cv_key, count);
  1414. }
  1415. namespace {
  1416. constexpr bool IsValidSignalType(Svc::SignalType type) {
  1417. switch (type) {
  1418. case Svc::SignalType::Signal:
  1419. case Svc::SignalType::SignalAndIncrementIfEqual:
  1420. case Svc::SignalType::SignalAndModifyByWaitingCountIfEqual:
  1421. return true;
  1422. default:
  1423. return false;
  1424. }
  1425. }
  1426. constexpr bool IsValidArbitrationType(Svc::ArbitrationType type) {
  1427. switch (type) {
  1428. case Svc::ArbitrationType::WaitIfLessThan:
  1429. case Svc::ArbitrationType::DecrementAndWaitIfLessThan:
  1430. case Svc::ArbitrationType::WaitIfEqual:
  1431. return true;
  1432. default:
  1433. return false;
  1434. }
  1435. }
  1436. } // namespace
  1437. // Wait for an address (via Address Arbiter)
  1438. static ResultCode WaitForAddress(Core::System& system, VAddr address, Svc::ArbitrationType arb_type,
  1439. s32 value, s64 timeout_ns) {
  1440. LOG_TRACE(Kernel_SVC, "called, address=0x{:X}, arb_type=0x{:X}, value=0x{:X}, timeout_ns={}",
  1441. address, arb_type, value, timeout_ns);
  1442. // Validate input.
  1443. if (IsKernelAddress(address)) {
  1444. LOG_ERROR(Kernel_SVC, "Attempting to wait on kernel address (address={:08X})", address);
  1445. return ResultInvalidCurrentMemory;
  1446. }
  1447. if (!Common::IsAligned(address, sizeof(s32))) {
  1448. LOG_ERROR(Kernel_SVC, "Wait address must be 4 byte aligned (address={:08X})", address);
  1449. return ResultInvalidAddress;
  1450. }
  1451. if (!IsValidArbitrationType(arb_type)) {
  1452. LOG_ERROR(Kernel_SVC, "Invalid arbitration type specified (type={})", arb_type);
  1453. return ResultInvalidEnumValue;
  1454. }
  1455. // Convert timeout from nanoseconds to ticks.
  1456. s64 timeout{};
  1457. if (timeout_ns > 0) {
  1458. const s64 offset_tick(timeout_ns);
  1459. if (offset_tick > 0) {
  1460. timeout = offset_tick + 2;
  1461. if (timeout <= 0) {
  1462. timeout = std::numeric_limits<s64>::max();
  1463. }
  1464. } else {
  1465. timeout = std::numeric_limits<s64>::max();
  1466. }
  1467. } else {
  1468. timeout = timeout_ns;
  1469. }
  1470. return system.Kernel().CurrentProcess()->WaitAddressArbiter(address, arb_type, value, timeout);
  1471. }
  1472. static ResultCode WaitForAddress32(Core::System& system, u32 address, Svc::ArbitrationType arb_type,
  1473. s32 value, u32 timeout_ns_low, u32 timeout_ns_high) {
  1474. const auto timeout = static_cast<s64>(timeout_ns_low | (u64{timeout_ns_high} << 32));
  1475. return WaitForAddress(system, address, arb_type, value, timeout);
  1476. }
  1477. // Signals to an address (via Address Arbiter)
  1478. static ResultCode SignalToAddress(Core::System& system, VAddr address, Svc::SignalType signal_type,
  1479. s32 value, s32 count) {
  1480. LOG_TRACE(Kernel_SVC, "called, address=0x{:X}, signal_type=0x{:X}, value=0x{:X}, count=0x{:X}",
  1481. address, signal_type, value, count);
  1482. // Validate input.
  1483. if (IsKernelAddress(address)) {
  1484. LOG_ERROR(Kernel_SVC, "Attempting to signal to a kernel address (address={:08X})", address);
  1485. return ResultInvalidCurrentMemory;
  1486. }
  1487. if (!Common::IsAligned(address, sizeof(s32))) {
  1488. LOG_ERROR(Kernel_SVC, "Signaled address must be 4 byte aligned (address={:08X})", address);
  1489. return ResultInvalidAddress;
  1490. }
  1491. if (!IsValidSignalType(signal_type)) {
  1492. LOG_ERROR(Kernel_SVC, "Invalid signal type specified (type={})", signal_type);
  1493. return ResultInvalidEnumValue;
  1494. }
  1495. return system.Kernel().CurrentProcess()->SignalAddressArbiter(address, signal_type, value,
  1496. count);
  1497. }
  1498. static ResultCode SignalToAddress32(Core::System& system, u32 address, Svc::SignalType signal_type,
  1499. s32 value, s32 count) {
  1500. return SignalToAddress(system, address, signal_type, value, count);
  1501. }
  1502. static void KernelDebug([[maybe_unused]] Core::System& system,
  1503. [[maybe_unused]] u32 kernel_debug_type, [[maybe_unused]] u64 param1,
  1504. [[maybe_unused]] u64 param2, [[maybe_unused]] u64 param3) {
  1505. // Intentionally do nothing, as this does nothing in released kernel binaries.
  1506. }
  1507. static void ChangeKernelTraceState([[maybe_unused]] Core::System& system,
  1508. [[maybe_unused]] u32 trace_state) {
  1509. // Intentionally do nothing, as this does nothing in released kernel binaries.
  1510. }
  1511. /// This returns the total CPU ticks elapsed since the CPU was powered-on
  1512. static u64 GetSystemTick(Core::System& system) {
  1513. LOG_TRACE(Kernel_SVC, "called");
  1514. auto& core_timing = system.CoreTiming();
  1515. // Returns the value of cntpct_el0 (https://switchbrew.org/wiki/SVC#svcGetSystemTick)
  1516. const u64 result{system.CoreTiming().GetClockTicks()};
  1517. if (!system.Kernel().IsMulticore()) {
  1518. core_timing.AddTicks(400U);
  1519. }
  1520. return result;
  1521. }
  1522. static void GetSystemTick32(Core::System& system, u32* time_low, u32* time_high) {
  1523. const auto time = GetSystemTick(system);
  1524. *time_low = static_cast<u32>(time);
  1525. *time_high = static_cast<u32>(time >> 32);
  1526. }
  1527. /// Close a handle
  1528. static ResultCode CloseHandle(Core::System& system, Handle handle) {
  1529. LOG_TRACE(Kernel_SVC, "Closing handle 0x{:08X}", handle);
  1530. // Remove the handle.
  1531. R_UNLESS(system.Kernel().CurrentProcess()->GetHandleTable().Remove(handle),
  1532. ResultInvalidHandle);
  1533. return ResultSuccess;
  1534. }
  1535. static ResultCode CloseHandle32(Core::System& system, Handle handle) {
  1536. return CloseHandle(system, handle);
  1537. }
  1538. /// Clears the signaled state of an event or process.
  1539. static ResultCode ResetSignal(Core::System& system, Handle handle) {
  1540. LOG_DEBUG(Kernel_SVC, "called handle 0x{:08X}", handle);
  1541. // Get the current handle table.
  1542. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1543. // Try to reset as readable event.
  1544. {
  1545. KScopedAutoObject readable_event = handle_table.GetObject<KReadableEvent>(handle);
  1546. if (readable_event.IsNotNull()) {
  1547. return readable_event->Reset();
  1548. }
  1549. }
  1550. // Try to reset as process.
  1551. {
  1552. KScopedAutoObject process = handle_table.GetObject<KProcess>(handle);
  1553. if (process.IsNotNull()) {
  1554. return process->Reset();
  1555. }
  1556. }
  1557. LOG_ERROR(Kernel_SVC, "invalid handle (0x{:08X})", handle);
  1558. return ResultInvalidHandle;
  1559. }
  1560. static ResultCode ResetSignal32(Core::System& system, Handle handle) {
  1561. return ResetSignal(system, handle);
  1562. }
  1563. namespace {
  1564. constexpr bool IsValidTransferMemoryPermission(MemoryPermission perm) {
  1565. switch (perm) {
  1566. case MemoryPermission::None:
  1567. case MemoryPermission::Read:
  1568. case MemoryPermission::ReadWrite:
  1569. return true;
  1570. default:
  1571. return false;
  1572. }
  1573. }
  1574. } // Anonymous namespace
  1575. /// Creates a TransferMemory object
  1576. static ResultCode CreateTransferMemory(Core::System& system, Handle* out, VAddr address, u64 size,
  1577. MemoryPermission map_perm) {
  1578. auto& kernel = system.Kernel();
  1579. // Validate the size.
  1580. R_UNLESS(Common::IsAligned(address, PageSize), ResultInvalidAddress);
  1581. R_UNLESS(Common::IsAligned(size, PageSize), ResultInvalidSize);
  1582. R_UNLESS(size > 0, ResultInvalidSize);
  1583. R_UNLESS((address < address + size), ResultInvalidCurrentMemory);
  1584. // Validate the permissions.
  1585. R_UNLESS(IsValidTransferMemoryPermission(map_perm), ResultInvalidNewMemoryPermission);
  1586. // Get the current process and handle table.
  1587. auto& process = *kernel.CurrentProcess();
  1588. auto& handle_table = process.GetHandleTable();
  1589. // Reserve a new transfer memory from the process resource limit.
  1590. KScopedResourceReservation trmem_reservation(kernel.CurrentProcess(),
  1591. LimitableResource::TransferMemory);
  1592. R_UNLESS(trmem_reservation.Succeeded(), ResultLimitReached);
  1593. // Create the transfer memory.
  1594. KTransferMemory* trmem = KTransferMemory::Create(kernel);
  1595. R_UNLESS(trmem != nullptr, ResultOutOfResource);
  1596. // Ensure the only reference is in the handle table when we're done.
  1597. SCOPE_EXIT({ trmem->Close(); });
  1598. // Ensure that the region is in range.
  1599. R_UNLESS(process.PageTable().Contains(address, size), ResultInvalidCurrentMemory);
  1600. // Initialize the transfer memory.
  1601. R_TRY(trmem->Initialize(address, size, map_perm));
  1602. // Commit the reservation.
  1603. trmem_reservation.Commit();
  1604. // Register the transfer memory.
  1605. KTransferMemory::Register(kernel, trmem);
  1606. // Add the transfer memory to the handle table.
  1607. R_TRY(handle_table.Add(out, trmem));
  1608. return ResultSuccess;
  1609. }
  1610. static ResultCode CreateTransferMemory32(Core::System& system, Handle* out, u32 address, u32 size,
  1611. MemoryPermission map_perm) {
  1612. return CreateTransferMemory(system, out, address, size, map_perm);
  1613. }
  1614. static ResultCode GetThreadCoreMask(Core::System& system, Handle thread_handle, s32* out_core_id,
  1615. u64* out_affinity_mask) {
  1616. LOG_TRACE(Kernel_SVC, "called, handle=0x{:08X}", thread_handle);
  1617. // Get the thread from its handle.
  1618. KScopedAutoObject thread =
  1619. system.Kernel().CurrentProcess()->GetHandleTable().GetObject<KThread>(thread_handle);
  1620. R_UNLESS(thread.IsNotNull(), ResultInvalidHandle);
  1621. // Get the core mask.
  1622. R_TRY(thread->GetCoreMask(out_core_id, out_affinity_mask));
  1623. return ResultSuccess;
  1624. }
  1625. static ResultCode GetThreadCoreMask32(Core::System& system, Handle thread_handle, s32* out_core_id,
  1626. u32* out_affinity_mask_low, u32* out_affinity_mask_high) {
  1627. u64 out_affinity_mask{};
  1628. const auto result = GetThreadCoreMask(system, thread_handle, out_core_id, &out_affinity_mask);
  1629. *out_affinity_mask_high = static_cast<u32>(out_affinity_mask >> 32);
  1630. *out_affinity_mask_low = static_cast<u32>(out_affinity_mask);
  1631. return result;
  1632. }
  1633. static ResultCode SetThreadCoreMask(Core::System& system, Handle thread_handle, s32 core_id,
  1634. u64 affinity_mask) {
  1635. // Determine the core id/affinity mask.
  1636. if (core_id == IdealCoreUseProcessValue) {
  1637. core_id = system.Kernel().CurrentProcess()->GetIdealCoreId();
  1638. affinity_mask = (1ULL << core_id);
  1639. } else {
  1640. // Validate the affinity mask.
  1641. const u64 process_core_mask = system.Kernel().CurrentProcess()->GetCoreMask();
  1642. R_UNLESS((affinity_mask | process_core_mask) == process_core_mask, ResultInvalidCoreId);
  1643. R_UNLESS(affinity_mask != 0, ResultInvalidCombination);
  1644. // Validate the core id.
  1645. if (IsValidVirtualCoreId(core_id)) {
  1646. R_UNLESS(((1ULL << core_id) & affinity_mask) != 0, ResultInvalidCombination);
  1647. } else {
  1648. R_UNLESS(core_id == IdealCoreNoUpdate || core_id == IdealCoreDontCare,
  1649. ResultInvalidCoreId);
  1650. }
  1651. }
  1652. // Get the thread from its handle.
  1653. KScopedAutoObject thread =
  1654. system.Kernel().CurrentProcess()->GetHandleTable().GetObject<KThread>(thread_handle);
  1655. R_UNLESS(thread.IsNotNull(), ResultInvalidHandle);
  1656. // Set the core mask.
  1657. R_TRY(thread->SetCoreMask(core_id, affinity_mask));
  1658. return ResultSuccess;
  1659. }
  1660. static ResultCode SetThreadCoreMask32(Core::System& system, Handle thread_handle, s32 core_id,
  1661. u32 affinity_mask_low, u32 affinity_mask_high) {
  1662. const auto affinity_mask = u64{affinity_mask_low} | (u64{affinity_mask_high} << 32);
  1663. return SetThreadCoreMask(system, thread_handle, core_id, affinity_mask);
  1664. }
  1665. static ResultCode SignalEvent(Core::System& system, Handle event_handle) {
  1666. LOG_DEBUG(Kernel_SVC, "called, event_handle=0x{:08X}", event_handle);
  1667. // Get the current handle table.
  1668. const KHandleTable& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1669. // Get the writable event.
  1670. KScopedAutoObject writable_event = handle_table.GetObject<KWritableEvent>(event_handle);
  1671. R_UNLESS(writable_event.IsNotNull(), ResultInvalidHandle);
  1672. return writable_event->Signal();
  1673. }
  1674. static ResultCode SignalEvent32(Core::System& system, Handle event_handle) {
  1675. return SignalEvent(system, event_handle);
  1676. }
  1677. static ResultCode ClearEvent(Core::System& system, Handle event_handle) {
  1678. LOG_TRACE(Kernel_SVC, "called, event_handle=0x{:08X}", event_handle);
  1679. // Get the current handle table.
  1680. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1681. // Try to clear the writable event.
  1682. {
  1683. KScopedAutoObject writable_event = handle_table.GetObject<KWritableEvent>(event_handle);
  1684. if (writable_event.IsNotNull()) {
  1685. return writable_event->Clear();
  1686. }
  1687. }
  1688. // Try to clear the readable event.
  1689. {
  1690. KScopedAutoObject readable_event = handle_table.GetObject<KReadableEvent>(event_handle);
  1691. if (readable_event.IsNotNull()) {
  1692. return readable_event->Clear();
  1693. }
  1694. }
  1695. LOG_ERROR(Kernel_SVC, "Event handle does not exist, event_handle=0x{:08X}", event_handle);
  1696. return ResultInvalidHandle;
  1697. }
  1698. static ResultCode ClearEvent32(Core::System& system, Handle event_handle) {
  1699. return ClearEvent(system, event_handle);
  1700. }
  1701. static ResultCode CreateEvent(Core::System& system, Handle* out_write, Handle* out_read) {
  1702. LOG_DEBUG(Kernel_SVC, "called");
  1703. // Get the kernel reference and handle table.
  1704. auto& kernel = system.Kernel();
  1705. auto& handle_table = kernel.CurrentProcess()->GetHandleTable();
  1706. // Reserve a new event from the process resource limit
  1707. KScopedResourceReservation event_reservation(kernel.CurrentProcess(),
  1708. LimitableResource::Events);
  1709. R_UNLESS(event_reservation.Succeeded(), ResultLimitReached);
  1710. // Create a new event.
  1711. KEvent* event = KEvent::Create(kernel);
  1712. R_UNLESS(event != nullptr, ResultOutOfResource);
  1713. // Initialize the event.
  1714. event->Initialize("CreateEvent");
  1715. // Commit the thread reservation.
  1716. event_reservation.Commit();
  1717. // Ensure that we clean up the event (and its only references are handle table) on function end.
  1718. SCOPE_EXIT({
  1719. event->GetWritableEvent().Close();
  1720. event->GetReadableEvent().Close();
  1721. });
  1722. // Register the event.
  1723. KEvent::Register(kernel, event);
  1724. // Add the writable event to the handle table.
  1725. R_TRY(handle_table.Add(out_write, std::addressof(event->GetWritableEvent())));
  1726. // Add the writable event to the handle table.
  1727. auto handle_guard = SCOPE_GUARD({ handle_table.Remove(*out_write); });
  1728. // Add the readable event to the handle table.
  1729. R_TRY(handle_table.Add(out_read, std::addressof(event->GetReadableEvent())));
  1730. // We succeeded.
  1731. handle_guard.Cancel();
  1732. return ResultSuccess;
  1733. }
  1734. static ResultCode CreateEvent32(Core::System& system, Handle* out_write, Handle* out_read) {
  1735. return CreateEvent(system, out_write, out_read);
  1736. }
  1737. static ResultCode GetProcessInfo(Core::System& system, u64* out, Handle process_handle, u32 type) {
  1738. LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, type=0x{:X}", process_handle, type);
  1739. // This function currently only allows retrieving a process' status.
  1740. enum class InfoType {
  1741. Status,
  1742. };
  1743. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1744. KScopedAutoObject process = handle_table.GetObject<KProcess>(process_handle);
  1745. if (process.IsNull()) {
  1746. LOG_ERROR(Kernel_SVC, "Process handle does not exist, process_handle=0x{:08X}",
  1747. process_handle);
  1748. return ResultInvalidHandle;
  1749. }
  1750. const auto info_type = static_cast<InfoType>(type);
  1751. if (info_type != InfoType::Status) {
  1752. LOG_ERROR(Kernel_SVC, "Expected info_type to be Status but got {} instead", type);
  1753. return ResultInvalidEnumValue;
  1754. }
  1755. *out = static_cast<u64>(process->GetStatus());
  1756. return ResultSuccess;
  1757. }
  1758. static ResultCode CreateResourceLimit(Core::System& system, Handle* out_handle) {
  1759. LOG_DEBUG(Kernel_SVC, "called");
  1760. // Create a new resource limit.
  1761. auto& kernel = system.Kernel();
  1762. KResourceLimit* resource_limit = KResourceLimit::Create(kernel);
  1763. R_UNLESS(resource_limit != nullptr, ResultOutOfResource);
  1764. // Ensure we don't leak a reference to the limit.
  1765. SCOPE_EXIT({ resource_limit->Close(); });
  1766. // Initialize the resource limit.
  1767. resource_limit->Initialize(&system.CoreTiming());
  1768. // Register the limit.
  1769. KResourceLimit::Register(kernel, resource_limit);
  1770. // Add the limit to the handle table.
  1771. R_TRY(kernel.CurrentProcess()->GetHandleTable().Add(out_handle, resource_limit));
  1772. return ResultSuccess;
  1773. }
  1774. static ResultCode GetResourceLimitLimitValue(Core::System& system, u64* out_limit_value,
  1775. Handle resource_limit_handle,
  1776. LimitableResource which) {
  1777. LOG_DEBUG(Kernel_SVC, "called, resource_limit_handle={:08X}, which={}", resource_limit_handle,
  1778. which);
  1779. // Validate the resource.
  1780. R_UNLESS(IsValidResourceType(which), ResultInvalidEnumValue);
  1781. // Get the resource limit.
  1782. auto& kernel = system.Kernel();
  1783. KScopedAutoObject resource_limit =
  1784. kernel.CurrentProcess()->GetHandleTable().GetObject<KResourceLimit>(resource_limit_handle);
  1785. R_UNLESS(resource_limit.IsNotNull(), ResultInvalidHandle);
  1786. // Get the limit value.
  1787. *out_limit_value = resource_limit->GetLimitValue(which);
  1788. return ResultSuccess;
  1789. }
  1790. static ResultCode GetResourceLimitCurrentValue(Core::System& system, u64* out_current_value,
  1791. Handle resource_limit_handle,
  1792. LimitableResource which) {
  1793. LOG_DEBUG(Kernel_SVC, "called, resource_limit_handle={:08X}, which={}", resource_limit_handle,
  1794. which);
  1795. // Validate the resource.
  1796. R_UNLESS(IsValidResourceType(which), ResultInvalidEnumValue);
  1797. // Get the resource limit.
  1798. auto& kernel = system.Kernel();
  1799. KScopedAutoObject resource_limit =
  1800. kernel.CurrentProcess()->GetHandleTable().GetObject<KResourceLimit>(resource_limit_handle);
  1801. R_UNLESS(resource_limit.IsNotNull(), ResultInvalidHandle);
  1802. // Get the current value.
  1803. *out_current_value = resource_limit->GetCurrentValue(which);
  1804. return ResultSuccess;
  1805. }
  1806. static ResultCode SetResourceLimitLimitValue(Core::System& system, Handle resource_limit_handle,
  1807. LimitableResource which, u64 limit_value) {
  1808. LOG_DEBUG(Kernel_SVC, "called, resource_limit_handle={:08X}, which={}, limit_value={}",
  1809. resource_limit_handle, which, limit_value);
  1810. // Validate the resource.
  1811. R_UNLESS(IsValidResourceType(which), ResultInvalidEnumValue);
  1812. // Get the resource limit.
  1813. auto& kernel = system.Kernel();
  1814. KScopedAutoObject resource_limit =
  1815. kernel.CurrentProcess()->GetHandleTable().GetObject<KResourceLimit>(resource_limit_handle);
  1816. R_UNLESS(resource_limit.IsNotNull(), ResultInvalidHandle);
  1817. // Set the limit value.
  1818. R_TRY(resource_limit->SetLimitValue(which, limit_value));
  1819. return ResultSuccess;
  1820. }
  1821. static ResultCode GetProcessList(Core::System& system, u32* out_num_processes,
  1822. VAddr out_process_ids, u32 out_process_ids_size) {
  1823. LOG_DEBUG(Kernel_SVC, "called. out_process_ids=0x{:016X}, out_process_ids_size={}",
  1824. out_process_ids, out_process_ids_size);
  1825. // If the supplied size is negative or greater than INT32_MAX / sizeof(u64), bail.
  1826. if ((out_process_ids_size & 0xF0000000) != 0) {
  1827. LOG_ERROR(Kernel_SVC,
  1828. "Supplied size outside [0, 0x0FFFFFFF] range. out_process_ids_size={}",
  1829. out_process_ids_size);
  1830. return ResultOutOfRange;
  1831. }
  1832. const auto& kernel = system.Kernel();
  1833. const auto total_copy_size = out_process_ids_size * sizeof(u64);
  1834. if (out_process_ids_size > 0 && !kernel.CurrentProcess()->PageTable().IsInsideAddressSpace(
  1835. out_process_ids, total_copy_size)) {
  1836. LOG_ERROR(Kernel_SVC, "Address range outside address space. begin=0x{:016X}, end=0x{:016X}",
  1837. out_process_ids, out_process_ids + total_copy_size);
  1838. return ResultInvalidCurrentMemory;
  1839. }
  1840. auto& memory = system.Memory();
  1841. const auto& process_list = kernel.GetProcessList();
  1842. const auto num_processes = process_list.size();
  1843. const auto copy_amount = std::min(std::size_t{out_process_ids_size}, num_processes);
  1844. for (std::size_t i = 0; i < copy_amount; ++i) {
  1845. memory.Write64(out_process_ids, process_list[i]->GetProcessID());
  1846. out_process_ids += sizeof(u64);
  1847. }
  1848. *out_num_processes = static_cast<u32>(num_processes);
  1849. return ResultSuccess;
  1850. }
  1851. static ResultCode GetThreadList(Core::System& system, u32* out_num_threads, VAddr out_thread_ids,
  1852. u32 out_thread_ids_size, Handle debug_handle) {
  1853. // TODO: Handle this case when debug events are supported.
  1854. UNIMPLEMENTED_IF(debug_handle != InvalidHandle);
  1855. LOG_DEBUG(Kernel_SVC, "called. out_thread_ids=0x{:016X}, out_thread_ids_size={}",
  1856. out_thread_ids, out_thread_ids_size);
  1857. // If the size is negative or larger than INT32_MAX / sizeof(u64)
  1858. if ((out_thread_ids_size & 0xF0000000) != 0) {
  1859. LOG_ERROR(Kernel_SVC, "Supplied size outside [0, 0x0FFFFFFF] range. size={}",
  1860. out_thread_ids_size);
  1861. return ResultOutOfRange;
  1862. }
  1863. const auto* const current_process = system.Kernel().CurrentProcess();
  1864. const auto total_copy_size = out_thread_ids_size * sizeof(u64);
  1865. if (out_thread_ids_size > 0 &&
  1866. !current_process->PageTable().IsInsideAddressSpace(out_thread_ids, total_copy_size)) {
  1867. LOG_ERROR(Kernel_SVC, "Address range outside address space. begin=0x{:016X}, end=0x{:016X}",
  1868. out_thread_ids, out_thread_ids + total_copy_size);
  1869. return ResultInvalidCurrentMemory;
  1870. }
  1871. auto& memory = system.Memory();
  1872. const auto& thread_list = current_process->GetThreadList();
  1873. const auto num_threads = thread_list.size();
  1874. const auto copy_amount = std::min(std::size_t{out_thread_ids_size}, num_threads);
  1875. auto list_iter = thread_list.cbegin();
  1876. for (std::size_t i = 0; i < copy_amount; ++i, ++list_iter) {
  1877. memory.Write64(out_thread_ids, (*list_iter)->GetThreadID());
  1878. out_thread_ids += sizeof(u64);
  1879. }
  1880. *out_num_threads = static_cast<u32>(num_threads);
  1881. return ResultSuccess;
  1882. }
  1883. static ResultCode FlushProcessDataCache32([[maybe_unused]] Core::System& system,
  1884. [[maybe_unused]] Handle handle,
  1885. [[maybe_unused]] u32 address, [[maybe_unused]] u32 size) {
  1886. // Note(Blinkhawk): For emulation purposes of the data cache this is mostly a no-op,
  1887. // as all emulation is done in the same cache level in host architecture, thus data cache
  1888. // does not need flushing.
  1889. LOG_DEBUG(Kernel_SVC, "called");
  1890. return ResultSuccess;
  1891. }
  1892. namespace {
  1893. struct FunctionDef {
  1894. using Func = void(Core::System&);
  1895. u32 id;
  1896. Func* func;
  1897. const char* name;
  1898. };
  1899. } // namespace
  1900. static const FunctionDef SVC_Table_32[] = {
  1901. {0x00, nullptr, "Unknown"},
  1902. {0x01, SvcWrap32<SetHeapSize32>, "SetHeapSize32"},
  1903. {0x02, nullptr, "Unknown"},
  1904. {0x03, SvcWrap32<SetMemoryAttribute32>, "SetMemoryAttribute32"},
  1905. {0x04, SvcWrap32<MapMemory32>, "MapMemory32"},
  1906. {0x05, SvcWrap32<UnmapMemory32>, "UnmapMemory32"},
  1907. {0x06, SvcWrap32<QueryMemory32>, "QueryMemory32"},
  1908. {0x07, SvcWrap32<ExitProcess32>, "ExitProcess32"},
  1909. {0x08, SvcWrap32<CreateThread32>, "CreateThread32"},
  1910. {0x09, SvcWrap32<StartThread32>, "StartThread32"},
  1911. {0x0a, SvcWrap32<ExitThread32>, "ExitThread32"},
  1912. {0x0b, SvcWrap32<SleepThread32>, "SleepThread32"},
  1913. {0x0c, SvcWrap32<GetThreadPriority32>, "GetThreadPriority32"},
  1914. {0x0d, SvcWrap32<SetThreadPriority32>, "SetThreadPriority32"},
  1915. {0x0e, SvcWrap32<GetThreadCoreMask32>, "GetThreadCoreMask32"},
  1916. {0x0f, SvcWrap32<SetThreadCoreMask32>, "SetThreadCoreMask32"},
  1917. {0x10, SvcWrap32<GetCurrentProcessorNumber32>, "GetCurrentProcessorNumber32"},
  1918. {0x11, SvcWrap32<SignalEvent32>, "SignalEvent32"},
  1919. {0x12, SvcWrap32<ClearEvent32>, "ClearEvent32"},
  1920. {0x13, SvcWrap32<MapSharedMemory32>, "MapSharedMemory32"},
  1921. {0x14, SvcWrap32<UnmapSharedMemory32>, "UnmapSharedMemory32"},
  1922. {0x15, SvcWrap32<CreateTransferMemory32>, "CreateTransferMemory32"},
  1923. {0x16, SvcWrap32<CloseHandle32>, "CloseHandle32"},
  1924. {0x17, SvcWrap32<ResetSignal32>, "ResetSignal32"},
  1925. {0x18, SvcWrap32<WaitSynchronization32>, "WaitSynchronization32"},
  1926. {0x19, SvcWrap32<CancelSynchronization32>, "CancelSynchronization32"},
  1927. {0x1a, SvcWrap32<ArbitrateLock32>, "ArbitrateLock32"},
  1928. {0x1b, SvcWrap32<ArbitrateUnlock32>, "ArbitrateUnlock32"},
  1929. {0x1c, SvcWrap32<WaitProcessWideKeyAtomic32>, "WaitProcessWideKeyAtomic32"},
  1930. {0x1d, SvcWrap32<SignalProcessWideKey32>, "SignalProcessWideKey32"},
  1931. {0x1e, SvcWrap32<GetSystemTick32>, "GetSystemTick32"},
  1932. {0x1f, SvcWrap32<ConnectToNamedPort32>, "ConnectToNamedPort32"},
  1933. {0x20, nullptr, "Unknown"},
  1934. {0x21, SvcWrap32<SendSyncRequest32>, "SendSyncRequest32"},
  1935. {0x22, nullptr, "SendSyncRequestWithUserBuffer32"},
  1936. {0x23, nullptr, "Unknown"},
  1937. {0x24, SvcWrap32<GetProcessId32>, "GetProcessId32"},
  1938. {0x25, SvcWrap32<GetThreadId32>, "GetThreadId32"},
  1939. {0x26, SvcWrap32<Break32>, "Break32"},
  1940. {0x27, nullptr, "OutputDebugString32"},
  1941. {0x28, nullptr, "Unknown"},
  1942. {0x29, SvcWrap32<GetInfo32>, "GetInfo32"},
  1943. {0x2a, nullptr, "Unknown"},
  1944. {0x2b, nullptr, "Unknown"},
  1945. {0x2c, SvcWrap32<MapPhysicalMemory32>, "MapPhysicalMemory32"},
  1946. {0x2d, SvcWrap32<UnmapPhysicalMemory32>, "UnmapPhysicalMemory32"},
  1947. {0x2e, nullptr, "Unknown"},
  1948. {0x2f, nullptr, "Unknown"},
  1949. {0x30, nullptr, "Unknown"},
  1950. {0x31, nullptr, "Unknown"},
  1951. {0x32, SvcWrap32<SetThreadActivity32>, "SetThreadActivity32"},
  1952. {0x33, SvcWrap32<GetThreadContext32>, "GetThreadContext32"},
  1953. {0x34, SvcWrap32<WaitForAddress32>, "WaitForAddress32"},
  1954. {0x35, SvcWrap32<SignalToAddress32>, "SignalToAddress32"},
  1955. {0x36, nullptr, "Unknown"},
  1956. {0x37, nullptr, "Unknown"},
  1957. {0x38, nullptr, "Unknown"},
  1958. {0x39, nullptr, "Unknown"},
  1959. {0x3a, nullptr, "Unknown"},
  1960. {0x3b, nullptr, "Unknown"},
  1961. {0x3c, nullptr, "Unknown"},
  1962. {0x3d, nullptr, "Unknown"},
  1963. {0x3e, nullptr, "Unknown"},
  1964. {0x3f, nullptr, "Unknown"},
  1965. {0x40, nullptr, "CreateSession32"},
  1966. {0x41, nullptr, "AcceptSession32"},
  1967. {0x42, nullptr, "Unknown"},
  1968. {0x43, nullptr, "ReplyAndReceive32"},
  1969. {0x44, nullptr, "Unknown"},
  1970. {0x45, SvcWrap32<CreateEvent32>, "CreateEvent32"},
  1971. {0x46, nullptr, "Unknown"},
  1972. {0x47, nullptr, "Unknown"},
  1973. {0x48, nullptr, "Unknown"},
  1974. {0x49, nullptr, "Unknown"},
  1975. {0x4a, nullptr, "Unknown"},
  1976. {0x4b, nullptr, "Unknown"},
  1977. {0x4c, nullptr, "Unknown"},
  1978. {0x4d, nullptr, "Unknown"},
  1979. {0x4e, nullptr, "Unknown"},
  1980. {0x4f, nullptr, "Unknown"},
  1981. {0x50, nullptr, "Unknown"},
  1982. {0x51, nullptr, "Unknown"},
  1983. {0x52, nullptr, "Unknown"},
  1984. {0x53, nullptr, "Unknown"},
  1985. {0x54, nullptr, "Unknown"},
  1986. {0x55, nullptr, "Unknown"},
  1987. {0x56, nullptr, "Unknown"},
  1988. {0x57, nullptr, "Unknown"},
  1989. {0x58, nullptr, "Unknown"},
  1990. {0x59, nullptr, "Unknown"},
  1991. {0x5a, nullptr, "Unknown"},
  1992. {0x5b, nullptr, "Unknown"},
  1993. {0x5c, nullptr, "Unknown"},
  1994. {0x5d, nullptr, "Unknown"},
  1995. {0x5e, nullptr, "Unknown"},
  1996. {0x5F, SvcWrap32<FlushProcessDataCache32>, "FlushProcessDataCache32"},
  1997. {0x60, nullptr, "Unknown"},
  1998. {0x61, nullptr, "Unknown"},
  1999. {0x62, nullptr, "Unknown"},
  2000. {0x63, nullptr, "Unknown"},
  2001. {0x64, nullptr, "Unknown"},
  2002. {0x65, nullptr, "GetProcessList32"},
  2003. {0x66, nullptr, "Unknown"},
  2004. {0x67, nullptr, "Unknown"},
  2005. {0x68, nullptr, "Unknown"},
  2006. {0x69, nullptr, "Unknown"},
  2007. {0x6A, nullptr, "Unknown"},
  2008. {0x6B, nullptr, "Unknown"},
  2009. {0x6C, nullptr, "Unknown"},
  2010. {0x6D, nullptr, "Unknown"},
  2011. {0x6E, nullptr, "Unknown"},
  2012. {0x6f, nullptr, "GetSystemInfo32"},
  2013. {0x70, nullptr, "CreatePort32"},
  2014. {0x71, nullptr, "ManageNamedPort32"},
  2015. {0x72, nullptr, "ConnectToPort32"},
  2016. {0x73, nullptr, "SetProcessMemoryPermission32"},
  2017. {0x74, nullptr, "Unknown"},
  2018. {0x75, nullptr, "Unknown"},
  2019. {0x76, nullptr, "Unknown"},
  2020. {0x77, nullptr, "MapProcessCodeMemory32"},
  2021. {0x78, nullptr, "UnmapProcessCodeMemory32"},
  2022. {0x79, nullptr, "Unknown"},
  2023. {0x7A, nullptr, "Unknown"},
  2024. {0x7B, nullptr, "TerminateProcess32"},
  2025. {0x7C, nullptr, "GetProcessInfo32"},
  2026. {0x7D, nullptr, "CreateResourceLimit32"},
  2027. {0x7E, nullptr, "SetResourceLimitLimitValue32"},
  2028. {0x7F, nullptr, "CallSecureMonitor32"},
  2029. {0x80, nullptr, "Unknown"},
  2030. {0x81, nullptr, "Unknown"},
  2031. {0x82, nullptr, "Unknown"},
  2032. {0x83, nullptr, "Unknown"},
  2033. {0x84, nullptr, "Unknown"},
  2034. {0x85, nullptr, "Unknown"},
  2035. {0x86, nullptr, "Unknown"},
  2036. {0x87, nullptr, "Unknown"},
  2037. {0x88, nullptr, "Unknown"},
  2038. {0x89, nullptr, "Unknown"},
  2039. {0x8A, nullptr, "Unknown"},
  2040. {0x8B, nullptr, "Unknown"},
  2041. {0x8C, nullptr, "Unknown"},
  2042. {0x8D, nullptr, "Unknown"},
  2043. {0x8E, nullptr, "Unknown"},
  2044. {0x8F, nullptr, "Unknown"},
  2045. {0x90, nullptr, "Unknown"},
  2046. {0x91, nullptr, "Unknown"},
  2047. {0x92, nullptr, "Unknown"},
  2048. {0x93, nullptr, "Unknown"},
  2049. {0x94, nullptr, "Unknown"},
  2050. {0x95, nullptr, "Unknown"},
  2051. {0x96, nullptr, "Unknown"},
  2052. {0x97, nullptr, "Unknown"},
  2053. {0x98, nullptr, "Unknown"},
  2054. {0x99, nullptr, "Unknown"},
  2055. {0x9A, nullptr, "Unknown"},
  2056. {0x9B, nullptr, "Unknown"},
  2057. {0x9C, nullptr, "Unknown"},
  2058. {0x9D, nullptr, "Unknown"},
  2059. {0x9E, nullptr, "Unknown"},
  2060. {0x9F, nullptr, "Unknown"},
  2061. {0xA0, nullptr, "Unknown"},
  2062. {0xA1, nullptr, "Unknown"},
  2063. {0xA2, nullptr, "Unknown"},
  2064. {0xA3, nullptr, "Unknown"},
  2065. {0xA4, nullptr, "Unknown"},
  2066. {0xA5, nullptr, "Unknown"},
  2067. {0xA6, nullptr, "Unknown"},
  2068. {0xA7, nullptr, "Unknown"},
  2069. {0xA8, nullptr, "Unknown"},
  2070. {0xA9, nullptr, "Unknown"},
  2071. {0xAA, nullptr, "Unknown"},
  2072. {0xAB, nullptr, "Unknown"},
  2073. {0xAC, nullptr, "Unknown"},
  2074. {0xAD, nullptr, "Unknown"},
  2075. {0xAE, nullptr, "Unknown"},
  2076. {0xAF, nullptr, "Unknown"},
  2077. {0xB0, nullptr, "Unknown"},
  2078. {0xB1, nullptr, "Unknown"},
  2079. {0xB2, nullptr, "Unknown"},
  2080. {0xB3, nullptr, "Unknown"},
  2081. {0xB4, nullptr, "Unknown"},
  2082. {0xB5, nullptr, "Unknown"},
  2083. {0xB6, nullptr, "Unknown"},
  2084. {0xB7, nullptr, "Unknown"},
  2085. {0xB8, nullptr, "Unknown"},
  2086. {0xB9, nullptr, "Unknown"},
  2087. {0xBA, nullptr, "Unknown"},
  2088. {0xBB, nullptr, "Unknown"},
  2089. {0xBC, nullptr, "Unknown"},
  2090. {0xBD, nullptr, "Unknown"},
  2091. {0xBE, nullptr, "Unknown"},
  2092. {0xBF, nullptr, "Unknown"},
  2093. };
  2094. static const FunctionDef SVC_Table_64[] = {
  2095. {0x00, nullptr, "Unknown"},
  2096. {0x01, SvcWrap64<SetHeapSize>, "SetHeapSize"},
  2097. {0x02, nullptr, "SetMemoryPermission"},
  2098. {0x03, SvcWrap64<SetMemoryAttribute>, "SetMemoryAttribute"},
  2099. {0x04, SvcWrap64<MapMemory>, "MapMemory"},
  2100. {0x05, SvcWrap64<UnmapMemory>, "UnmapMemory"},
  2101. {0x06, SvcWrap64<QueryMemory>, "QueryMemory"},
  2102. {0x07, SvcWrap64<ExitProcess>, "ExitProcess"},
  2103. {0x08, SvcWrap64<CreateThread>, "CreateThread"},
  2104. {0x09, SvcWrap64<StartThread>, "StartThread"},
  2105. {0x0A, SvcWrap64<ExitThread>, "ExitThread"},
  2106. {0x0B, SvcWrap64<SleepThread>, "SleepThread"},
  2107. {0x0C, SvcWrap64<GetThreadPriority>, "GetThreadPriority"},
  2108. {0x0D, SvcWrap64<SetThreadPriority>, "SetThreadPriority"},
  2109. {0x0E, SvcWrap64<GetThreadCoreMask>, "GetThreadCoreMask"},
  2110. {0x0F, SvcWrap64<SetThreadCoreMask>, "SetThreadCoreMask"},
  2111. {0x10, SvcWrap64<GetCurrentProcessorNumber>, "GetCurrentProcessorNumber"},
  2112. {0x11, SvcWrap64<SignalEvent>, "SignalEvent"},
  2113. {0x12, SvcWrap64<ClearEvent>, "ClearEvent"},
  2114. {0x13, SvcWrap64<MapSharedMemory>, "MapSharedMemory"},
  2115. {0x14, SvcWrap64<UnmapSharedMemory>, "UnmapSharedMemory"},
  2116. {0x15, SvcWrap64<CreateTransferMemory>, "CreateTransferMemory"},
  2117. {0x16, SvcWrap64<CloseHandle>, "CloseHandle"},
  2118. {0x17, SvcWrap64<ResetSignal>, "ResetSignal"},
  2119. {0x18, SvcWrap64<WaitSynchronization>, "WaitSynchronization"},
  2120. {0x19, SvcWrap64<CancelSynchronization>, "CancelSynchronization"},
  2121. {0x1A, SvcWrap64<ArbitrateLock>, "ArbitrateLock"},
  2122. {0x1B, SvcWrap64<ArbitrateUnlock>, "ArbitrateUnlock"},
  2123. {0x1C, SvcWrap64<WaitProcessWideKeyAtomic>, "WaitProcessWideKeyAtomic"},
  2124. {0x1D, SvcWrap64<SignalProcessWideKey>, "SignalProcessWideKey"},
  2125. {0x1E, SvcWrap64<GetSystemTick>, "GetSystemTick"},
  2126. {0x1F, SvcWrap64<ConnectToNamedPort>, "ConnectToNamedPort"},
  2127. {0x20, nullptr, "SendSyncRequestLight"},
  2128. {0x21, SvcWrap64<SendSyncRequest>, "SendSyncRequest"},
  2129. {0x22, nullptr, "SendSyncRequestWithUserBuffer"},
  2130. {0x23, nullptr, "SendAsyncRequestWithUserBuffer"},
  2131. {0x24, SvcWrap64<GetProcessId>, "GetProcessId"},
  2132. {0x25, SvcWrap64<GetThreadId>, "GetThreadId"},
  2133. {0x26, SvcWrap64<Break>, "Break"},
  2134. {0x27, SvcWrap64<OutputDebugString>, "OutputDebugString"},
  2135. {0x28, nullptr, "ReturnFromException"},
  2136. {0x29, SvcWrap64<GetInfo>, "GetInfo"},
  2137. {0x2A, nullptr, "FlushEntireDataCache"},
  2138. {0x2B, nullptr, "FlushDataCache"},
  2139. {0x2C, SvcWrap64<MapPhysicalMemory>, "MapPhysicalMemory"},
  2140. {0x2D, SvcWrap64<UnmapPhysicalMemory>, "UnmapPhysicalMemory"},
  2141. {0x2E, nullptr, "GetFutureThreadInfo"},
  2142. {0x2F, nullptr, "GetLastThreadInfo"},
  2143. {0x30, SvcWrap64<GetResourceLimitLimitValue>, "GetResourceLimitLimitValue"},
  2144. {0x31, SvcWrap64<GetResourceLimitCurrentValue>, "GetResourceLimitCurrentValue"},
  2145. {0x32, SvcWrap64<SetThreadActivity>, "SetThreadActivity"},
  2146. {0x33, SvcWrap64<GetThreadContext>, "GetThreadContext"},
  2147. {0x34, SvcWrap64<WaitForAddress>, "WaitForAddress"},
  2148. {0x35, SvcWrap64<SignalToAddress>, "SignalToAddress"},
  2149. {0x36, nullptr, "SynchronizePreemptionState"},
  2150. {0x37, nullptr, "Unknown"},
  2151. {0x38, nullptr, "Unknown"},
  2152. {0x39, nullptr, "Unknown"},
  2153. {0x3A, nullptr, "Unknown"},
  2154. {0x3B, nullptr, "Unknown"},
  2155. {0x3C, SvcWrap64<KernelDebug>, "KernelDebug"},
  2156. {0x3D, SvcWrap64<ChangeKernelTraceState>, "ChangeKernelTraceState"},
  2157. {0x3E, nullptr, "Unknown"},
  2158. {0x3F, nullptr, "Unknown"},
  2159. {0x40, nullptr, "CreateSession"},
  2160. {0x41, nullptr, "AcceptSession"},
  2161. {0x42, nullptr, "ReplyAndReceiveLight"},
  2162. {0x43, nullptr, "ReplyAndReceive"},
  2163. {0x44, nullptr, "ReplyAndReceiveWithUserBuffer"},
  2164. {0x45, SvcWrap64<CreateEvent>, "CreateEvent"},
  2165. {0x46, nullptr, "Unknown"},
  2166. {0x47, nullptr, "Unknown"},
  2167. {0x48, nullptr, "MapPhysicalMemoryUnsafe"},
  2168. {0x49, nullptr, "UnmapPhysicalMemoryUnsafe"},
  2169. {0x4A, nullptr, "SetUnsafeLimit"},
  2170. {0x4B, nullptr, "CreateCodeMemory"},
  2171. {0x4C, nullptr, "ControlCodeMemory"},
  2172. {0x4D, nullptr, "SleepSystem"},
  2173. {0x4E, nullptr, "ReadWriteRegister"},
  2174. {0x4F, nullptr, "SetProcessActivity"},
  2175. {0x50, nullptr, "CreateSharedMemory"},
  2176. {0x51, nullptr, "MapTransferMemory"},
  2177. {0x52, nullptr, "UnmapTransferMemory"},
  2178. {0x53, nullptr, "CreateInterruptEvent"},
  2179. {0x54, nullptr, "QueryPhysicalAddress"},
  2180. {0x55, nullptr, "QueryIoMapping"},
  2181. {0x56, nullptr, "CreateDeviceAddressSpace"},
  2182. {0x57, nullptr, "AttachDeviceAddressSpace"},
  2183. {0x58, nullptr, "DetachDeviceAddressSpace"},
  2184. {0x59, nullptr, "MapDeviceAddressSpaceByForce"},
  2185. {0x5A, nullptr, "MapDeviceAddressSpaceAligned"},
  2186. {0x5B, nullptr, "MapDeviceAddressSpace"},
  2187. {0x5C, nullptr, "UnmapDeviceAddressSpace"},
  2188. {0x5D, nullptr, "InvalidateProcessDataCache"},
  2189. {0x5E, nullptr, "StoreProcessDataCache"},
  2190. {0x5F, nullptr, "FlushProcessDataCache"},
  2191. {0x60, nullptr, "DebugActiveProcess"},
  2192. {0x61, nullptr, "BreakDebugProcess"},
  2193. {0x62, nullptr, "TerminateDebugProcess"},
  2194. {0x63, nullptr, "GetDebugEvent"},
  2195. {0x64, nullptr, "ContinueDebugEvent"},
  2196. {0x65, SvcWrap64<GetProcessList>, "GetProcessList"},
  2197. {0x66, SvcWrap64<GetThreadList>, "GetThreadList"},
  2198. {0x67, nullptr, "GetDebugThreadContext"},
  2199. {0x68, nullptr, "SetDebugThreadContext"},
  2200. {0x69, nullptr, "QueryDebugProcessMemory"},
  2201. {0x6A, nullptr, "ReadDebugProcessMemory"},
  2202. {0x6B, nullptr, "WriteDebugProcessMemory"},
  2203. {0x6C, nullptr, "SetHardwareBreakPoint"},
  2204. {0x6D, nullptr, "GetDebugThreadParam"},
  2205. {0x6E, nullptr, "Unknown"},
  2206. {0x6F, nullptr, "GetSystemInfo"},
  2207. {0x70, nullptr, "CreatePort"},
  2208. {0x71, nullptr, "ManageNamedPort"},
  2209. {0x72, nullptr, "ConnectToPort"},
  2210. {0x73, SvcWrap64<SetProcessMemoryPermission>, "SetProcessMemoryPermission"},
  2211. {0x74, nullptr, "MapProcessMemory"},
  2212. {0x75, nullptr, "UnmapProcessMemory"},
  2213. {0x76, SvcWrap64<QueryProcessMemory>, "QueryProcessMemory"},
  2214. {0x77, SvcWrap64<MapProcessCodeMemory>, "MapProcessCodeMemory"},
  2215. {0x78, SvcWrap64<UnmapProcessCodeMemory>, "UnmapProcessCodeMemory"},
  2216. {0x79, nullptr, "CreateProcess"},
  2217. {0x7A, nullptr, "StartProcess"},
  2218. {0x7B, nullptr, "TerminateProcess"},
  2219. {0x7C, SvcWrap64<GetProcessInfo>, "GetProcessInfo"},
  2220. {0x7D, SvcWrap64<CreateResourceLimit>, "CreateResourceLimit"},
  2221. {0x7E, SvcWrap64<SetResourceLimitLimitValue>, "SetResourceLimitLimitValue"},
  2222. {0x7F, nullptr, "CallSecureMonitor"},
  2223. {0x80, nullptr, "Unknown"},
  2224. {0x81, nullptr, "Unknown"},
  2225. {0x82, nullptr, "Unknown"},
  2226. {0x83, nullptr, "Unknown"},
  2227. {0x84, nullptr, "Unknown"},
  2228. {0x85, nullptr, "Unknown"},
  2229. {0x86, nullptr, "Unknown"},
  2230. {0x87, nullptr, "Unknown"},
  2231. {0x88, nullptr, "Unknown"},
  2232. {0x89, nullptr, "Unknown"},
  2233. {0x8A, nullptr, "Unknown"},
  2234. {0x8B, nullptr, "Unknown"},
  2235. {0x8C, nullptr, "Unknown"},
  2236. {0x8D, nullptr, "Unknown"},
  2237. {0x8E, nullptr, "Unknown"},
  2238. {0x8F, nullptr, "Unknown"},
  2239. {0x90, nullptr, "Unknown"},
  2240. {0x91, nullptr, "Unknown"},
  2241. {0x92, nullptr, "Unknown"},
  2242. {0x93, nullptr, "Unknown"},
  2243. {0x94, nullptr, "Unknown"},
  2244. {0x95, nullptr, "Unknown"},
  2245. {0x96, nullptr, "Unknown"},
  2246. {0x97, nullptr, "Unknown"},
  2247. {0x98, nullptr, "Unknown"},
  2248. {0x99, nullptr, "Unknown"},
  2249. {0x9A, nullptr, "Unknown"},
  2250. {0x9B, nullptr, "Unknown"},
  2251. {0x9C, nullptr, "Unknown"},
  2252. {0x9D, nullptr, "Unknown"},
  2253. {0x9E, nullptr, "Unknown"},
  2254. {0x9F, nullptr, "Unknown"},
  2255. {0xA0, nullptr, "Unknown"},
  2256. {0xA1, nullptr, "Unknown"},
  2257. {0xA2, nullptr, "Unknown"},
  2258. {0xA3, nullptr, "Unknown"},
  2259. {0xA4, nullptr, "Unknown"},
  2260. {0xA5, nullptr, "Unknown"},
  2261. {0xA6, nullptr, "Unknown"},
  2262. {0xA7, nullptr, "Unknown"},
  2263. {0xA8, nullptr, "Unknown"},
  2264. {0xA9, nullptr, "Unknown"},
  2265. {0xAA, nullptr, "Unknown"},
  2266. {0xAB, nullptr, "Unknown"},
  2267. {0xAC, nullptr, "Unknown"},
  2268. {0xAD, nullptr, "Unknown"},
  2269. {0xAE, nullptr, "Unknown"},
  2270. {0xAF, nullptr, "Unknown"},
  2271. {0xB0, nullptr, "Unknown"},
  2272. {0xB1, nullptr, "Unknown"},
  2273. {0xB2, nullptr, "Unknown"},
  2274. {0xB3, nullptr, "Unknown"},
  2275. {0xB4, nullptr, "Unknown"},
  2276. {0xB5, nullptr, "Unknown"},
  2277. {0xB6, nullptr, "Unknown"},
  2278. {0xB7, nullptr, "Unknown"},
  2279. {0xB8, nullptr, "Unknown"},
  2280. {0xB9, nullptr, "Unknown"},
  2281. {0xBA, nullptr, "Unknown"},
  2282. {0xBB, nullptr, "Unknown"},
  2283. {0xBC, nullptr, "Unknown"},
  2284. {0xBD, nullptr, "Unknown"},
  2285. {0xBE, nullptr, "Unknown"},
  2286. {0xBF, nullptr, "Unknown"},
  2287. };
  2288. static const FunctionDef* GetSVCInfo32(u32 func_num) {
  2289. if (func_num >= std::size(SVC_Table_32)) {
  2290. LOG_ERROR(Kernel_SVC, "Unknown svc=0x{:02X}", func_num);
  2291. return nullptr;
  2292. }
  2293. return &SVC_Table_32[func_num];
  2294. }
  2295. static const FunctionDef* GetSVCInfo64(u32 func_num) {
  2296. if (func_num >= std::size(SVC_Table_64)) {
  2297. LOG_ERROR(Kernel_SVC, "Unknown svc=0x{:02X}", func_num);
  2298. return nullptr;
  2299. }
  2300. return &SVC_Table_64[func_num];
  2301. }
  2302. void Call(Core::System& system, u32 immediate) {
  2303. system.ExitDynarmicProfile();
  2304. auto& kernel = system.Kernel();
  2305. kernel.EnterSVCProfile();
  2306. auto* thread = kernel.CurrentScheduler()->GetCurrentThread();
  2307. thread->SetIsCallingSvc();
  2308. const FunctionDef* info = system.CurrentProcess()->Is64BitProcess() ? GetSVCInfo64(immediate)
  2309. : GetSVCInfo32(immediate);
  2310. if (info) {
  2311. if (info->func) {
  2312. info->func(system);
  2313. } else {
  2314. LOG_CRITICAL(Kernel_SVC, "Unimplemented SVC function {}(..)", info->name);
  2315. }
  2316. } else {
  2317. LOG_CRITICAL(Kernel_SVC, "Unknown SVC function 0x{:X}", immediate);
  2318. }
  2319. kernel.ExitSVCProfile();
  2320. if (!thread->IsCallingSvc()) {
  2321. auto* host_context = thread->GetHostContext().get();
  2322. host_context->Rewind();
  2323. }
  2324. system.EnterDynarmicProfile();
  2325. }
  2326. } // namespace Kernel::Svc