svc.cpp 116 KB

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