svc.cpp 114 KB

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