svc.cpp 115 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014
  1. // Copyright 2018 yuzu emulator team
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <cinttypes>
  6. #include <iterator>
  7. #include <mutex>
  8. #include <vector>
  9. #include "common/alignment.h"
  10. #include "common/assert.h"
  11. #include "common/common_funcs.h"
  12. #include "common/fiber.h"
  13. #include "common/logging/log.h"
  14. #include "common/scope_exit.h"
  15. #include "core/core.h"
  16. #include "core/core_timing.h"
  17. #include "core/hle/kernel/k_client_port.h"
  18. #include "core/hle/kernel/k_client_session.h"
  19. #include "core/hle/kernel/k_code_memory.h"
  20. #include "core/hle/kernel/k_event.h"
  21. #include "core/hle/kernel/k_handle_table.h"
  22. #include "core/hle/kernel/k_memory_block.h"
  23. #include "core/hle/kernel/k_memory_layout.h"
  24. #include "core/hle/kernel/k_page_table.h"
  25. #include "core/hle/kernel/k_process.h"
  26. #include "core/hle/kernel/k_readable_event.h"
  27. #include "core/hle/kernel/k_resource_limit.h"
  28. #include "core/hle/kernel/k_scheduler.h"
  29. #include "core/hle/kernel/k_scoped_resource_reservation.h"
  30. #include "core/hle/kernel/k_shared_memory.h"
  31. #include "core/hle/kernel/k_synchronization_object.h"
  32. #include "core/hle/kernel/k_thread.h"
  33. #include "core/hle/kernel/k_thread_queue.h"
  34. #include "core/hle/kernel/k_transfer_memory.h"
  35. #include "core/hle/kernel/k_writable_event.h"
  36. #include "core/hle/kernel/kernel.h"
  37. #include "core/hle/kernel/physical_core.h"
  38. #include "core/hle/kernel/svc.h"
  39. #include "core/hle/kernel/svc_results.h"
  40. #include "core/hle/kernel/svc_types.h"
  41. #include "core/hle/kernel/svc_wrap.h"
  42. #include "core/hle/result.h"
  43. #include "core/memory.h"
  44. #include "core/reporter.h"
  45. namespace Kernel::Svc {
  46. namespace {
  47. // Checks if address + size is greater than the given address
  48. // This can return false if the size causes an overflow of a 64-bit type
  49. // or if the given size is zero.
  50. constexpr bool IsValidAddressRange(VAddr address, u64 size) {
  51. return address + size > address;
  52. }
  53. // Helper function that performs the common sanity checks for svcMapMemory
  54. // and svcUnmapMemory. This is doable, as both functions perform their sanitizing
  55. // in the same order.
  56. ResultCode MapUnmapMemorySanityChecks(const KPageTable& manager, VAddr dst_addr, VAddr src_addr,
  57. u64 size) {
  58. if (!Common::Is4KBAligned(dst_addr)) {
  59. LOG_ERROR(Kernel_SVC, "Destination address is not aligned to 4KB, 0x{:016X}", dst_addr);
  60. return ResultInvalidAddress;
  61. }
  62. if (!Common::Is4KBAligned(src_addr)) {
  63. LOG_ERROR(Kernel_SVC, "Source address is not aligned to 4KB, 0x{:016X}", src_addr);
  64. return ResultInvalidSize;
  65. }
  66. if (size == 0) {
  67. LOG_ERROR(Kernel_SVC, "Size is 0");
  68. return ResultInvalidSize;
  69. }
  70. if (!Common::Is4KBAligned(size)) {
  71. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, 0x{:016X}", size);
  72. return ResultInvalidSize;
  73. }
  74. if (!IsValidAddressRange(dst_addr, size)) {
  75. LOG_ERROR(Kernel_SVC,
  76. "Destination is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
  77. dst_addr, size);
  78. return ResultInvalidCurrentMemory;
  79. }
  80. if (!IsValidAddressRange(src_addr, size)) {
  81. LOG_ERROR(Kernel_SVC, "Source is not a valid address range, addr=0x{:016X}, size=0x{:016X}",
  82. src_addr, size);
  83. return ResultInvalidCurrentMemory;
  84. }
  85. if (!manager.IsInsideAddressSpace(src_addr, size)) {
  86. LOG_ERROR(Kernel_SVC,
  87. "Source is not within the address space, addr=0x{:016X}, size=0x{:016X}",
  88. src_addr, size);
  89. return ResultInvalidCurrentMemory;
  90. }
  91. if (manager.IsOutsideStackRegion(dst_addr, size)) {
  92. LOG_ERROR(Kernel_SVC,
  93. "Destination is not within the stack region, addr=0x{:016X}, size=0x{:016X}",
  94. dst_addr, size);
  95. return ResultInvalidMemoryRegion;
  96. }
  97. if (manager.IsInsideHeapRegion(dst_addr, size)) {
  98. LOG_ERROR(Kernel_SVC,
  99. "Destination does not fit within the heap region, addr=0x{:016X}, "
  100. "size=0x{:016X}",
  101. dst_addr, size);
  102. return ResultInvalidMemoryRegion;
  103. }
  104. if (manager.IsInsideAliasRegion(dst_addr, size)) {
  105. LOG_ERROR(Kernel_SVC,
  106. "Destination does not fit within the map region, addr=0x{:016X}, "
  107. "size=0x{:016X}",
  108. dst_addr, size);
  109. return ResultInvalidMemoryRegion;
  110. }
  111. return ResultSuccess;
  112. }
  113. enum class ResourceLimitValueType {
  114. CurrentValue,
  115. LimitValue,
  116. PeakValue,
  117. };
  118. } // Anonymous namespace
  119. /// Set the process heap to a given Size. It can both extend and shrink the heap.
  120. static ResultCode SetHeapSize(Core::System& system, VAddr* out_address, u64 size) {
  121. LOG_TRACE(Kernel_SVC, "called, heap_size=0x{:X}", size);
  122. // Validate size.
  123. R_UNLESS(Common::IsAligned(size, HeapSizeAlignment), ResultInvalidSize);
  124. R_UNLESS(size < MainMemorySizeMax, ResultInvalidSize);
  125. // Set the heap size.
  126. R_TRY(system.Kernel().CurrentProcess()->PageTable().SetHeapSize(out_address, size));
  127. return ResultSuccess;
  128. }
  129. static ResultCode SetHeapSize32(Core::System& system, u32* heap_addr, u32 heap_size) {
  130. VAddr temp_heap_addr{};
  131. const ResultCode result{SetHeapSize(system, &temp_heap_addr, heap_size)};
  132. *heap_addr = static_cast<u32>(temp_heap_addr);
  133. return result;
  134. }
  135. constexpr bool IsValidSetMemoryPermission(MemoryPermission perm) {
  136. switch (perm) {
  137. case MemoryPermission::None:
  138. case MemoryPermission::Read:
  139. case MemoryPermission::ReadWrite:
  140. return true;
  141. default:
  142. return false;
  143. }
  144. }
  145. static ResultCode SetMemoryPermission(Core::System& system, VAddr address, u64 size,
  146. MemoryPermission perm) {
  147. LOG_DEBUG(Kernel_SVC, "called, address=0x{:016X}, size=0x{:X}, perm=0x{:08X", address, size,
  148. perm);
  149. // Validate address / size.
  150. R_UNLESS(Common::IsAligned(address, PageSize), ResultInvalidAddress);
  151. R_UNLESS(Common::IsAligned(size, PageSize), ResultInvalidSize);
  152. R_UNLESS(size > 0, ResultInvalidSize);
  153. R_UNLESS((address < address + size), ResultInvalidCurrentMemory);
  154. // Validate the permission.
  155. R_UNLESS(IsValidSetMemoryPermission(perm), ResultInvalidNewMemoryPermission);
  156. // Validate that the region is in range for the current process.
  157. auto& page_table = system.Kernel().CurrentProcess()->PageTable();
  158. R_UNLESS(page_table.Contains(address, size), ResultInvalidCurrentMemory);
  159. // Set the memory attribute.
  160. return page_table.SetMemoryPermission(address, size, perm);
  161. }
  162. static ResultCode SetMemoryAttribute(Core::System& system, VAddr address, u64 size, u32 mask,
  163. u32 attr) {
  164. LOG_DEBUG(Kernel_SVC,
  165. "called, address=0x{:016X}, size=0x{:X}, mask=0x{:08X}, attribute=0x{:08X}", address,
  166. size, mask, attr);
  167. // Validate address / size.
  168. R_UNLESS(Common::IsAligned(address, PageSize), ResultInvalidAddress);
  169. R_UNLESS(Common::IsAligned(size, PageSize), ResultInvalidSize);
  170. R_UNLESS(size > 0, ResultInvalidSize);
  171. R_UNLESS((address < address + size), ResultInvalidCurrentMemory);
  172. // Validate the attribute and mask.
  173. constexpr u32 SupportedMask = static_cast<u32>(MemoryAttribute::Uncached);
  174. R_UNLESS((mask | attr) == mask, ResultInvalidCombination);
  175. R_UNLESS((mask | attr | SupportedMask) == SupportedMask, ResultInvalidCombination);
  176. // Validate that the region is in range for the current process.
  177. auto& page_table{system.Kernel().CurrentProcess()->PageTable()};
  178. R_UNLESS(page_table.Contains(address, size), ResultInvalidCurrentMemory);
  179. // Set the memory attribute.
  180. return page_table.SetMemoryAttribute(address, size, mask, attr);
  181. }
  182. static ResultCode SetMemoryAttribute32(Core::System& system, u32 address, u32 size, u32 mask,
  183. u32 attr) {
  184. return SetMemoryAttribute(system, address, size, mask, attr);
  185. }
  186. /// Maps a memory range into a different range.
  187. static ResultCode MapMemory(Core::System& system, VAddr dst_addr, VAddr src_addr, u64 size) {
  188. LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr,
  189. src_addr, size);
  190. auto& page_table{system.Kernel().CurrentProcess()->PageTable()};
  191. if (const ResultCode result{MapUnmapMemorySanityChecks(page_table, dst_addr, src_addr, size)};
  192. result.IsError()) {
  193. return result;
  194. }
  195. return page_table.MapMemory(dst_addr, src_addr, size);
  196. }
  197. static ResultCode MapMemory32(Core::System& system, u32 dst_addr, u32 src_addr, u32 size) {
  198. return MapMemory(system, dst_addr, src_addr, size);
  199. }
  200. /// Unmaps a region that was previously mapped with svcMapMemory
  201. static ResultCode UnmapMemory(Core::System& system, VAddr dst_addr, VAddr src_addr, u64 size) {
  202. LOG_TRACE(Kernel_SVC, "called, dst_addr=0x{:X}, src_addr=0x{:X}, size=0x{:X}", dst_addr,
  203. src_addr, size);
  204. auto& page_table{system.Kernel().CurrentProcess()->PageTable()};
  205. if (const ResultCode result{MapUnmapMemorySanityChecks(page_table, dst_addr, src_addr, size)};
  206. result.IsError()) {
  207. return result;
  208. }
  209. return page_table.UnmapMemory(dst_addr, src_addr, size);
  210. }
  211. static ResultCode UnmapMemory32(Core::System& system, u32 dst_addr, u32 src_addr, u32 size) {
  212. return UnmapMemory(system, dst_addr, src_addr, size);
  213. }
  214. /// Connect to an OS service given the port name, returns the handle to the port to out
  215. static ResultCode ConnectToNamedPort(Core::System& system, Handle* out, VAddr port_name_address) {
  216. auto& memory = system.Memory();
  217. if (!memory.IsValidVirtualAddress(port_name_address)) {
  218. LOG_ERROR(Kernel_SVC,
  219. "Port Name Address is not a valid virtual address, port_name_address=0x{:016X}",
  220. port_name_address);
  221. return ResultNotFound;
  222. }
  223. static constexpr std::size_t PortNameMaxLength = 11;
  224. // Read 1 char beyond the max allowed port name to detect names that are too long.
  225. const std::string port_name = memory.ReadCString(port_name_address, PortNameMaxLength + 1);
  226. if (port_name.size() > PortNameMaxLength) {
  227. LOG_ERROR(Kernel_SVC, "Port name is too long, expected {} but got {}", PortNameMaxLength,
  228. port_name.size());
  229. return ResultOutOfRange;
  230. }
  231. LOG_TRACE(Kernel_SVC, "called port_name={}", port_name);
  232. // Get the current handle table.
  233. auto& kernel = system.Kernel();
  234. auto& handle_table = kernel.CurrentProcess()->GetHandleTable();
  235. // Find the client port.
  236. auto port = kernel.CreateNamedServicePort(port_name);
  237. if (!port) {
  238. LOG_ERROR(Kernel_SVC, "tried to connect to unknown port: {}", port_name);
  239. return ResultNotFound;
  240. }
  241. // Reserve a handle for the port.
  242. // NOTE: Nintendo really does write directly to the output handle here.
  243. R_TRY(handle_table.Reserve(out));
  244. auto handle_guard = SCOPE_GUARD({ handle_table.Unreserve(*out); });
  245. // Create a session.
  246. KClientSession* session{};
  247. R_TRY(port->CreateSession(std::addressof(session)));
  248. port->Close();
  249. // Register the session in the table, close the extra reference.
  250. handle_table.Register(*out, session);
  251. session->Close();
  252. // We succeeded.
  253. handle_guard.Cancel();
  254. return ResultSuccess;
  255. }
  256. static ResultCode ConnectToNamedPort32(Core::System& system, Handle* out_handle,
  257. u32 port_name_address) {
  258. return ConnectToNamedPort(system, out_handle, port_name_address);
  259. }
  260. /// Makes a blocking IPC call to an OS service.
  261. static ResultCode SendSyncRequest(Core::System& system, Handle handle) {
  262. auto& kernel = system.Kernel();
  263. // Create the wait queue.
  264. KThreadQueue wait_queue(kernel);
  265. // Get the client session from its handle.
  266. KScopedAutoObject session =
  267. kernel.CurrentProcess()->GetHandleTable().GetObject<KClientSession>(handle);
  268. R_UNLESS(session.IsNotNull(), ResultInvalidHandle);
  269. LOG_TRACE(Kernel_SVC, "called handle=0x{:08X}({})", handle, session->GetName());
  270. auto thread = kernel.CurrentScheduler()->GetCurrentThread();
  271. {
  272. KScopedSchedulerLock lock(kernel);
  273. // This is a synchronous request, so we should wait for our request to complete.
  274. GetCurrentThread(kernel).BeginWait(std::addressof(wait_queue));
  275. GetCurrentThread(kernel).SetWaitReasonForDebugging(ThreadWaitReasonForDebugging::IPC);
  276. session->SendSyncRequest(&GetCurrentThread(kernel), system.Memory(), system.CoreTiming());
  277. }
  278. return thread->GetWaitResult();
  279. }
  280. static ResultCode SendSyncRequest32(Core::System& system, Handle handle) {
  281. return SendSyncRequest(system, handle);
  282. }
  283. /// Get the ID for the specified thread.
  284. static ResultCode GetThreadId(Core::System& system, u64* out_thread_id, Handle thread_handle) {
  285. // Get the thread from its handle.
  286. KScopedAutoObject thread =
  287. system.Kernel().CurrentProcess()->GetHandleTable().GetObject<KThread>(thread_handle);
  288. R_UNLESS(thread.IsNotNull(), ResultInvalidHandle);
  289. // Get the thread's id.
  290. *out_thread_id = thread->GetId();
  291. return ResultSuccess;
  292. }
  293. static ResultCode GetThreadId32(Core::System& system, u32* out_thread_id_low,
  294. u32* out_thread_id_high, Handle thread_handle) {
  295. u64 out_thread_id{};
  296. const ResultCode result{GetThreadId(system, &out_thread_id, thread_handle)};
  297. *out_thread_id_low = static_cast<u32>(out_thread_id >> 32);
  298. *out_thread_id_high = static_cast<u32>(out_thread_id & std::numeric_limits<u32>::max());
  299. return result;
  300. }
  301. /// Gets the ID of the specified process or a specified thread's owning process.
  302. static ResultCode GetProcessId(Core::System& system, u64* out_process_id, Handle handle) {
  303. LOG_DEBUG(Kernel_SVC, "called handle=0x{:08X}", handle);
  304. // Get the object from the handle table.
  305. KScopedAutoObject obj =
  306. system.Kernel().CurrentProcess()->GetHandleTable().GetObject<KAutoObject>(
  307. static_cast<Handle>(handle));
  308. R_UNLESS(obj.IsNotNull(), ResultInvalidHandle);
  309. // Get the process from the object.
  310. KProcess* process = nullptr;
  311. if (KProcess* p = obj->DynamicCast<KProcess*>(); p != nullptr) {
  312. // The object is a process, so we can use it directly.
  313. process = p;
  314. } else if (KThread* t = obj->DynamicCast<KThread*>(); t != nullptr) {
  315. // The object is a thread, so we want to use its parent.
  316. process = reinterpret_cast<KThread*>(obj.GetPointerUnsafe())->GetOwnerProcess();
  317. } else {
  318. // TODO(bunnei): This should also handle debug objects before returning.
  319. UNIMPLEMENTED_MSG("Debug objects not implemented");
  320. }
  321. // Make sure the target process exists.
  322. R_UNLESS(process != nullptr, ResultInvalidHandle);
  323. // Get the process id.
  324. *out_process_id = process->GetId();
  325. return ResultSuccess;
  326. }
  327. static ResultCode GetProcessId32(Core::System& system, u32* out_process_id_low,
  328. u32* out_process_id_high, Handle handle) {
  329. u64 out_process_id{};
  330. const auto result = GetProcessId(system, &out_process_id, handle);
  331. *out_process_id_low = static_cast<u32>(out_process_id);
  332. *out_process_id_high = static_cast<u32>(out_process_id >> 32);
  333. return result;
  334. }
  335. /// Wait for the given handles to synchronize, timeout after the specified nanoseconds
  336. static ResultCode WaitSynchronization(Core::System& system, s32* index, VAddr handles_address,
  337. s32 num_handles, s64 nano_seconds) {
  338. LOG_TRACE(Kernel_SVC, "called handles_address=0x{:X}, num_handles={}, nano_seconds={}",
  339. handles_address, num_handles, nano_seconds);
  340. // Ensure number of handles is valid.
  341. R_UNLESS(0 <= num_handles && num_handles <= ArgumentHandleCountMax, ResultOutOfRange);
  342. auto& kernel = system.Kernel();
  343. std::vector<KSynchronizationObject*> objs(num_handles);
  344. const auto& handle_table = kernel.CurrentProcess()->GetHandleTable();
  345. Handle* handles = system.Memory().GetPointer<Handle>(handles_address);
  346. // Copy user handles.
  347. if (num_handles > 0) {
  348. // Convert the handles to objects.
  349. R_UNLESS(handle_table.GetMultipleObjects<KSynchronizationObject>(objs.data(), handles,
  350. num_handles),
  351. ResultInvalidHandle);
  352. for (const auto& obj : objs) {
  353. kernel.RegisterInUseObject(obj);
  354. }
  355. }
  356. // Ensure handles are closed when we're done.
  357. SCOPE_EXIT({
  358. for (s32 i = 0; i < num_handles; ++i) {
  359. kernel.UnregisterInUseObject(objs[i]);
  360. objs[i]->Close();
  361. }
  362. });
  363. return KSynchronizationObject::Wait(kernel, index, objs.data(), static_cast<s32>(objs.size()),
  364. nano_seconds);
  365. }
  366. static ResultCode WaitSynchronization32(Core::System& system, u32 timeout_low, u32 handles_address,
  367. s32 num_handles, u32 timeout_high, s32* index) {
  368. const s64 nano_seconds{(static_cast<s64>(timeout_high) << 32) | static_cast<s64>(timeout_low)};
  369. return WaitSynchronization(system, index, handles_address, num_handles, nano_seconds);
  370. }
  371. /// Resumes a thread waiting on WaitSynchronization
  372. static ResultCode CancelSynchronization(Core::System& system, Handle handle) {
  373. LOG_TRACE(Kernel_SVC, "called handle=0x{:X}", handle);
  374. // Get the thread from its handle.
  375. KScopedAutoObject thread =
  376. system.Kernel().CurrentProcess()->GetHandleTable().GetObject<KThread>(handle);
  377. R_UNLESS(thread.IsNotNull(), ResultInvalidHandle);
  378. // Cancel the thread's wait.
  379. thread->WaitCancel();
  380. return ResultSuccess;
  381. }
  382. static ResultCode CancelSynchronization32(Core::System& system, Handle handle) {
  383. return CancelSynchronization(system, handle);
  384. }
  385. /// Attempts to locks a mutex
  386. static ResultCode ArbitrateLock(Core::System& system, Handle thread_handle, VAddr address,
  387. u32 tag) {
  388. LOG_TRACE(Kernel_SVC, "called thread_handle=0x{:08X}, address=0x{:X}, tag=0x{:08X}",
  389. thread_handle, address, tag);
  390. // Validate the input address.
  391. if (IsKernelAddress(address)) {
  392. LOG_ERROR(Kernel_SVC, "Attempting to arbitrate a lock on a kernel address (address={:08X})",
  393. address);
  394. return ResultInvalidCurrentMemory;
  395. }
  396. if (!Common::IsAligned(address, sizeof(u32))) {
  397. LOG_ERROR(Kernel_SVC, "Input address must be 4 byte aligned (address: {:08X})", address);
  398. return ResultInvalidAddress;
  399. }
  400. return system.Kernel().CurrentProcess()->WaitForAddress(thread_handle, address, tag);
  401. }
  402. static ResultCode ArbitrateLock32(Core::System& system, Handle thread_handle, u32 address,
  403. u32 tag) {
  404. return ArbitrateLock(system, thread_handle, address, tag);
  405. }
  406. /// Unlock a mutex
  407. static ResultCode ArbitrateUnlock(Core::System& system, VAddr address) {
  408. LOG_TRACE(Kernel_SVC, "called address=0x{:X}", address);
  409. // Validate the input address.
  410. if (IsKernelAddress(address)) {
  411. LOG_ERROR(Kernel_SVC,
  412. "Attempting to arbitrate an unlock on a kernel address (address={:08X})",
  413. address);
  414. return ResultInvalidCurrentMemory;
  415. }
  416. if (!Common::IsAligned(address, sizeof(u32))) {
  417. LOG_ERROR(Kernel_SVC, "Input address must be 4 byte aligned (address: {:08X})", address);
  418. return ResultInvalidAddress;
  419. }
  420. return system.Kernel().CurrentProcess()->SignalToAddress(address);
  421. }
  422. static ResultCode ArbitrateUnlock32(Core::System& system, u32 address) {
  423. return ArbitrateUnlock(system, address);
  424. }
  425. enum class BreakType : u32 {
  426. Panic = 0,
  427. AssertionFailed = 1,
  428. PreNROLoad = 3,
  429. PostNROLoad = 4,
  430. PreNROUnload = 5,
  431. PostNROUnload = 6,
  432. CppException = 7,
  433. };
  434. struct BreakReason {
  435. union {
  436. u32 raw;
  437. BitField<0, 30, BreakType> break_type;
  438. BitField<31, 1, u32> signal_debugger;
  439. };
  440. };
  441. /// Break program execution
  442. static void Break(Core::System& system, u32 reason, u64 info1, u64 info2) {
  443. BreakReason break_reason{reason};
  444. bool has_dumped_buffer{};
  445. std::vector<u8> debug_buffer;
  446. const auto handle_debug_buffer = [&](VAddr addr, u64 sz) {
  447. if (sz == 0 || addr == 0 || has_dumped_buffer) {
  448. return;
  449. }
  450. auto& memory = system.Memory();
  451. // This typically is an error code so we're going to assume this is the case
  452. if (sz == sizeof(u32)) {
  453. LOG_CRITICAL(Debug_Emulated, "debug_buffer_err_code={:X}", memory.Read32(addr));
  454. } else {
  455. // We don't know what's in here so we'll hexdump it
  456. debug_buffer.resize(sz);
  457. memory.ReadBlock(addr, debug_buffer.data(), sz);
  458. std::string hexdump;
  459. for (std::size_t i = 0; i < debug_buffer.size(); i++) {
  460. hexdump += fmt::format("{:02X} ", debug_buffer[i]);
  461. if (i != 0 && i % 16 == 0) {
  462. hexdump += '\n';
  463. }
  464. }
  465. LOG_CRITICAL(Debug_Emulated, "debug_buffer=\n{}", hexdump);
  466. }
  467. has_dumped_buffer = true;
  468. };
  469. switch (break_reason.break_type) {
  470. case BreakType::Panic:
  471. LOG_CRITICAL(Debug_Emulated, "Signalling debugger, PANIC! info1=0x{:016X}, info2=0x{:016X}",
  472. info1, info2);
  473. handle_debug_buffer(info1, info2);
  474. break;
  475. case BreakType::AssertionFailed:
  476. LOG_CRITICAL(Debug_Emulated,
  477. "Signalling debugger, Assertion failed! info1=0x{:016X}, info2=0x{:016X}",
  478. info1, info2);
  479. handle_debug_buffer(info1, info2);
  480. break;
  481. case BreakType::PreNROLoad:
  482. LOG_WARNING(
  483. Debug_Emulated,
  484. "Signalling debugger, Attempting to load an NRO at 0x{:016X} with size 0x{:016X}",
  485. info1, info2);
  486. break;
  487. case BreakType::PostNROLoad:
  488. LOG_WARNING(Debug_Emulated,
  489. "Signalling debugger, Loaded an NRO at 0x{:016X} with size 0x{:016X}", info1,
  490. info2);
  491. break;
  492. case BreakType::PreNROUnload:
  493. LOG_WARNING(
  494. Debug_Emulated,
  495. "Signalling debugger, Attempting to unload an NRO at 0x{:016X} with size 0x{:016X}",
  496. info1, info2);
  497. break;
  498. case BreakType::PostNROUnload:
  499. LOG_WARNING(Debug_Emulated,
  500. "Signalling debugger, Unloaded an NRO at 0x{:016X} with size 0x{:016X}", info1,
  501. info2);
  502. break;
  503. case BreakType::CppException:
  504. LOG_CRITICAL(Debug_Emulated, "Signalling debugger. Uncaught C++ exception encountered.");
  505. break;
  506. default:
  507. LOG_WARNING(
  508. Debug_Emulated,
  509. "Signalling debugger, Unknown break reason {}, info1=0x{:016X}, info2=0x{:016X}",
  510. static_cast<u32>(break_reason.break_type.Value()), info1, info2);
  511. handle_debug_buffer(info1, info2);
  512. break;
  513. }
  514. system.GetReporter().SaveSvcBreakReport(
  515. static_cast<u32>(break_reason.break_type.Value()), break_reason.signal_debugger, info1,
  516. info2, has_dumped_buffer ? std::make_optional(debug_buffer) : std::nullopt);
  517. if (!break_reason.signal_debugger) {
  518. LOG_CRITICAL(
  519. Debug_Emulated,
  520. "Emulated program broke execution! reason=0x{:016X}, info1=0x{:016X}, info2=0x{:016X}",
  521. reason, info1, info2);
  522. handle_debug_buffer(info1, info2);
  523. auto* const current_thread = system.Kernel().CurrentScheduler()->GetCurrentThread();
  524. const auto thread_processor_id = current_thread->GetActiveCore();
  525. system.ArmInterface(static_cast<std::size_t>(thread_processor_id)).LogBacktrace();
  526. }
  527. }
  528. static void Break32(Core::System& system, u32 reason, u32 info1, u32 info2) {
  529. Break(system, reason, info1, info2);
  530. }
  531. /// Used to output a message on a debug hardware unit - does nothing on a retail unit
  532. static void OutputDebugString(Core::System& system, VAddr address, u64 len) {
  533. if (len == 0) {
  534. return;
  535. }
  536. std::string str(len, '\0');
  537. system.Memory().ReadBlock(address, str.data(), str.size());
  538. LOG_DEBUG(Debug_Emulated, "{}", str);
  539. }
  540. static void OutputDebugString32(Core::System& system, u32 address, u32 len) {
  541. OutputDebugString(system, address, len);
  542. }
  543. /// Gets system/memory information for the current process
  544. static ResultCode GetInfo(Core::System& system, u64* result, u64 info_id, Handle handle,
  545. u64 info_sub_id) {
  546. LOG_TRACE(Kernel_SVC, "called info_id=0x{:X}, info_sub_id=0x{:X}, handle=0x{:08X}", info_id,
  547. info_sub_id, handle);
  548. enum class GetInfoType : u64 {
  549. // 1.0.0+
  550. AllowedCPUCoreMask = 0,
  551. AllowedThreadPriorityMask = 1,
  552. MapRegionBaseAddr = 2,
  553. MapRegionSize = 3,
  554. HeapRegionBaseAddr = 4,
  555. HeapRegionSize = 5,
  556. TotalPhysicalMemoryAvailable = 6,
  557. TotalPhysicalMemoryUsed = 7,
  558. IsCurrentProcessBeingDebugged = 8,
  559. RegisterResourceLimit = 9,
  560. IdleTickCount = 10,
  561. RandomEntropy = 11,
  562. ThreadTickCount = 0xF0000002,
  563. // 2.0.0+
  564. ASLRRegionBaseAddr = 12,
  565. ASLRRegionSize = 13,
  566. StackRegionBaseAddr = 14,
  567. StackRegionSize = 15,
  568. // 3.0.0+
  569. SystemResourceSize = 16,
  570. SystemResourceUsage = 17,
  571. TitleId = 18,
  572. // 4.0.0+
  573. PrivilegedProcessId = 19,
  574. // 5.0.0+
  575. UserExceptionContextAddr = 20,
  576. // 6.0.0+
  577. TotalPhysicalMemoryAvailableWithoutSystemResource = 21,
  578. TotalPhysicalMemoryUsedWithoutSystemResource = 22,
  579. };
  580. const auto info_id_type = static_cast<GetInfoType>(info_id);
  581. switch (info_id_type) {
  582. case GetInfoType::AllowedCPUCoreMask:
  583. case GetInfoType::AllowedThreadPriorityMask:
  584. case GetInfoType::MapRegionBaseAddr:
  585. case GetInfoType::MapRegionSize:
  586. case GetInfoType::HeapRegionBaseAddr:
  587. case GetInfoType::HeapRegionSize:
  588. case GetInfoType::ASLRRegionBaseAddr:
  589. case GetInfoType::ASLRRegionSize:
  590. case GetInfoType::StackRegionBaseAddr:
  591. case GetInfoType::StackRegionSize:
  592. case GetInfoType::TotalPhysicalMemoryAvailable:
  593. case GetInfoType::TotalPhysicalMemoryUsed:
  594. case GetInfoType::SystemResourceSize:
  595. case GetInfoType::SystemResourceUsage:
  596. case GetInfoType::TitleId:
  597. case GetInfoType::UserExceptionContextAddr:
  598. case GetInfoType::TotalPhysicalMemoryAvailableWithoutSystemResource:
  599. case GetInfoType::TotalPhysicalMemoryUsedWithoutSystemResource: {
  600. if (info_sub_id != 0) {
  601. LOG_ERROR(Kernel_SVC, "Info sub id is non zero! info_id={}, info_sub_id={}", info_id,
  602. info_sub_id);
  603. return ResultInvalidEnumValue;
  604. }
  605. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  606. KScopedAutoObject process = handle_table.GetObject<KProcess>(handle);
  607. if (process.IsNull()) {
  608. LOG_ERROR(Kernel_SVC, "Process is not valid! info_id={}, info_sub_id={}, handle={:08X}",
  609. info_id, info_sub_id, handle);
  610. return ResultInvalidHandle;
  611. }
  612. switch (info_id_type) {
  613. case GetInfoType::AllowedCPUCoreMask:
  614. *result = process->GetCoreMask();
  615. return ResultSuccess;
  616. case GetInfoType::AllowedThreadPriorityMask:
  617. *result = process->GetPriorityMask();
  618. return ResultSuccess;
  619. case GetInfoType::MapRegionBaseAddr:
  620. *result = process->PageTable().GetAliasRegionStart();
  621. return ResultSuccess;
  622. case GetInfoType::MapRegionSize:
  623. *result = process->PageTable().GetAliasRegionSize();
  624. return ResultSuccess;
  625. case GetInfoType::HeapRegionBaseAddr:
  626. *result = process->PageTable().GetHeapRegionStart();
  627. return ResultSuccess;
  628. case GetInfoType::HeapRegionSize:
  629. *result = process->PageTable().GetHeapRegionSize();
  630. return ResultSuccess;
  631. case GetInfoType::ASLRRegionBaseAddr:
  632. *result = process->PageTable().GetAliasCodeRegionStart();
  633. return ResultSuccess;
  634. case GetInfoType::ASLRRegionSize:
  635. *result = process->PageTable().GetAliasCodeRegionSize();
  636. return ResultSuccess;
  637. case GetInfoType::StackRegionBaseAddr:
  638. *result = process->PageTable().GetStackRegionStart();
  639. return ResultSuccess;
  640. case GetInfoType::StackRegionSize:
  641. *result = process->PageTable().GetStackRegionSize();
  642. return ResultSuccess;
  643. case GetInfoType::TotalPhysicalMemoryAvailable:
  644. *result = process->GetTotalPhysicalMemoryAvailable();
  645. return ResultSuccess;
  646. case GetInfoType::TotalPhysicalMemoryUsed:
  647. *result = process->GetTotalPhysicalMemoryUsed();
  648. return ResultSuccess;
  649. case GetInfoType::SystemResourceSize:
  650. *result = process->GetSystemResourceSize();
  651. return ResultSuccess;
  652. case GetInfoType::SystemResourceUsage:
  653. LOG_WARNING(Kernel_SVC, "(STUBBED) Attempted to query system resource usage");
  654. *result = process->GetSystemResourceUsage();
  655. return ResultSuccess;
  656. case GetInfoType::TitleId:
  657. *result = process->GetProgramID();
  658. return ResultSuccess;
  659. case GetInfoType::UserExceptionContextAddr:
  660. *result = process->GetTLSRegionAddress();
  661. return ResultSuccess;
  662. case GetInfoType::TotalPhysicalMemoryAvailableWithoutSystemResource:
  663. *result = process->GetTotalPhysicalMemoryAvailableWithoutSystemResource();
  664. return ResultSuccess;
  665. case GetInfoType::TotalPhysicalMemoryUsedWithoutSystemResource:
  666. *result = process->GetTotalPhysicalMemoryUsedWithoutSystemResource();
  667. return ResultSuccess;
  668. default:
  669. break;
  670. }
  671. LOG_ERROR(Kernel_SVC, "Unimplemented svcGetInfo id=0x{:016X}", info_id);
  672. return ResultInvalidEnumValue;
  673. }
  674. case GetInfoType::IsCurrentProcessBeingDebugged:
  675. *result = 0;
  676. return ResultSuccess;
  677. case GetInfoType::RegisterResourceLimit: {
  678. if (handle != 0) {
  679. LOG_ERROR(Kernel, "Handle is non zero! handle={:08X}", handle);
  680. return ResultInvalidHandle;
  681. }
  682. if (info_sub_id != 0) {
  683. LOG_ERROR(Kernel, "Info sub id is non zero! info_id={}, info_sub_id={}", info_id,
  684. info_sub_id);
  685. return ResultInvalidCombination;
  686. }
  687. KProcess* const current_process = system.Kernel().CurrentProcess();
  688. KHandleTable& handle_table = current_process->GetHandleTable();
  689. const auto resource_limit = current_process->GetResourceLimit();
  690. if (!resource_limit) {
  691. *result = Svc::InvalidHandle;
  692. // Yes, the kernel considers this a successful operation.
  693. return ResultSuccess;
  694. }
  695. Handle resource_handle{};
  696. R_TRY(handle_table.Add(&resource_handle, resource_limit));
  697. *result = resource_handle;
  698. return ResultSuccess;
  699. }
  700. case GetInfoType::RandomEntropy:
  701. if (handle != 0) {
  702. LOG_ERROR(Kernel_SVC, "Process Handle is non zero, expected 0 result but got {:016X}",
  703. handle);
  704. return ResultInvalidHandle;
  705. }
  706. if (info_sub_id >= KProcess::RANDOM_ENTROPY_SIZE) {
  707. LOG_ERROR(Kernel_SVC, "Entropy size is out of range, expected {} but got {}",
  708. KProcess::RANDOM_ENTROPY_SIZE, info_sub_id);
  709. return ResultInvalidCombination;
  710. }
  711. *result = system.Kernel().CurrentProcess()->GetRandomEntropy(info_sub_id);
  712. return ResultSuccess;
  713. case GetInfoType::PrivilegedProcessId:
  714. LOG_WARNING(Kernel_SVC,
  715. "(STUBBED) Attempted to query privileged process id bounds, returned 0");
  716. *result = 0;
  717. return ResultSuccess;
  718. case GetInfoType::ThreadTickCount: {
  719. constexpr u64 num_cpus = 4;
  720. if (info_sub_id != 0xFFFFFFFFFFFFFFFF && info_sub_id >= num_cpus) {
  721. LOG_ERROR(Kernel_SVC, "Core count is out of range, expected {} but got {}", num_cpus,
  722. info_sub_id);
  723. return ResultInvalidCombination;
  724. }
  725. KScopedAutoObject thread =
  726. system.Kernel().CurrentProcess()->GetHandleTable().GetObject<KThread>(
  727. static_cast<Handle>(handle));
  728. if (thread.IsNull()) {
  729. LOG_ERROR(Kernel_SVC, "Thread handle does not exist, handle=0x{:08X}",
  730. static_cast<Handle>(handle));
  731. return ResultInvalidHandle;
  732. }
  733. const auto& core_timing = system.CoreTiming();
  734. const auto& scheduler = *system.Kernel().CurrentScheduler();
  735. const auto* const current_thread = scheduler.GetCurrentThread();
  736. const bool same_thread = current_thread == thread.GetPointerUnsafe();
  737. const u64 prev_ctx_ticks = scheduler.GetLastContextSwitchTicks();
  738. u64 out_ticks = 0;
  739. if (same_thread && info_sub_id == 0xFFFFFFFFFFFFFFFF) {
  740. const u64 thread_ticks = current_thread->GetCpuTime();
  741. out_ticks = thread_ticks + (core_timing.GetCPUTicks() - prev_ctx_ticks);
  742. } else if (same_thread && info_sub_id == system.Kernel().CurrentPhysicalCoreIndex()) {
  743. out_ticks = core_timing.GetCPUTicks() - prev_ctx_ticks;
  744. }
  745. *result = out_ticks;
  746. return ResultSuccess;
  747. }
  748. case GetInfoType::IdleTickCount: {
  749. // Verify the input handle is invalid.
  750. R_UNLESS(handle == InvalidHandle, ResultInvalidHandle);
  751. // Verify the requested core is valid.
  752. const bool core_valid =
  753. (info_sub_id == static_cast<u64>(-1ULL)) ||
  754. (info_sub_id == static_cast<u64>(system.Kernel().CurrentPhysicalCoreIndex()));
  755. R_UNLESS(core_valid, ResultInvalidCombination);
  756. // Get the idle tick count.
  757. *result = system.Kernel().CurrentScheduler()->GetIdleThread()->GetCpuTime();
  758. return ResultSuccess;
  759. }
  760. default:
  761. LOG_ERROR(Kernel_SVC, "Unimplemented svcGetInfo id=0x{:016X}", info_id);
  762. return ResultInvalidEnumValue;
  763. }
  764. }
  765. static ResultCode GetInfo32(Core::System& system, u32* result_low, u32* result_high, u32 sub_id_low,
  766. u32 info_id, u32 handle, u32 sub_id_high) {
  767. const u64 sub_id{u64{sub_id_low} | (u64{sub_id_high} << 32)};
  768. u64 res_value{};
  769. const ResultCode result{GetInfo(system, &res_value, info_id, handle, sub_id)};
  770. *result_high = static_cast<u32>(res_value >> 32);
  771. *result_low = static_cast<u32>(res_value & std::numeric_limits<u32>::max());
  772. return result;
  773. }
  774. /// Maps memory at a desired address
  775. static ResultCode MapPhysicalMemory(Core::System& system, VAddr addr, u64 size) {
  776. LOG_DEBUG(Kernel_SVC, "called, addr=0x{:016X}, size=0x{:X}", addr, size);
  777. if (!Common::Is4KBAligned(addr)) {
  778. LOG_ERROR(Kernel_SVC, "Address is not aligned to 4KB, 0x{:016X}", addr);
  779. return ResultInvalidAddress;
  780. }
  781. if (!Common::Is4KBAligned(size)) {
  782. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, 0x{:X}", size);
  783. return ResultInvalidSize;
  784. }
  785. if (size == 0) {
  786. LOG_ERROR(Kernel_SVC, "Size is zero");
  787. return ResultInvalidSize;
  788. }
  789. if (!(addr < addr + size)) {
  790. LOG_ERROR(Kernel_SVC, "Size causes 64-bit overflow of address");
  791. return ResultInvalidMemoryRegion;
  792. }
  793. KProcess* const current_process{system.Kernel().CurrentProcess()};
  794. auto& page_table{current_process->PageTable()};
  795. if (current_process->GetSystemResourceSize() == 0) {
  796. LOG_ERROR(Kernel_SVC, "System Resource Size is zero");
  797. return ResultInvalidState;
  798. }
  799. if (!page_table.IsInsideAddressSpace(addr, size)) {
  800. LOG_ERROR(Kernel_SVC,
  801. "Address is not within the address space, addr=0x{:016X}, size=0x{:016X}", addr,
  802. size);
  803. return ResultInvalidMemoryRegion;
  804. }
  805. if (page_table.IsOutsideAliasRegion(addr, size)) {
  806. LOG_ERROR(Kernel_SVC,
  807. "Address is not within the alias region, addr=0x{:016X}, size=0x{:016X}", addr,
  808. size);
  809. return ResultInvalidMemoryRegion;
  810. }
  811. return page_table.MapPhysicalMemory(addr, size);
  812. }
  813. static ResultCode MapPhysicalMemory32(Core::System& system, u32 addr, u32 size) {
  814. return MapPhysicalMemory(system, addr, size);
  815. }
  816. /// Unmaps memory previously mapped via MapPhysicalMemory
  817. static ResultCode UnmapPhysicalMemory(Core::System& system, VAddr addr, u64 size) {
  818. LOG_DEBUG(Kernel_SVC, "called, addr=0x{:016X}, size=0x{:X}", addr, size);
  819. if (!Common::Is4KBAligned(addr)) {
  820. LOG_ERROR(Kernel_SVC, "Address is not aligned to 4KB, 0x{:016X}", addr);
  821. return ResultInvalidAddress;
  822. }
  823. if (!Common::Is4KBAligned(size)) {
  824. LOG_ERROR(Kernel_SVC, "Size is not aligned to 4KB, 0x{:X}", size);
  825. return ResultInvalidSize;
  826. }
  827. if (size == 0) {
  828. LOG_ERROR(Kernel_SVC, "Size is zero");
  829. return ResultInvalidSize;
  830. }
  831. if (!(addr < addr + size)) {
  832. LOG_ERROR(Kernel_SVC, "Size causes 64-bit overflow of address");
  833. return ResultInvalidMemoryRegion;
  834. }
  835. KProcess* const current_process{system.Kernel().CurrentProcess()};
  836. auto& page_table{current_process->PageTable()};
  837. if (current_process->GetSystemResourceSize() == 0) {
  838. LOG_ERROR(Kernel_SVC, "System Resource Size is zero");
  839. return ResultInvalidState;
  840. }
  841. if (!page_table.IsInsideAddressSpace(addr, size)) {
  842. LOG_ERROR(Kernel_SVC,
  843. "Address is not within the address space, addr=0x{:016X}, size=0x{:016X}", addr,
  844. size);
  845. return ResultInvalidMemoryRegion;
  846. }
  847. if (page_table.IsOutsideAliasRegion(addr, size)) {
  848. LOG_ERROR(Kernel_SVC,
  849. "Address is not within the alias region, addr=0x{:016X}, size=0x{:016X}", addr,
  850. size);
  851. return ResultInvalidMemoryRegion;
  852. }
  853. return page_table.UnmapPhysicalMemory(addr, size);
  854. }
  855. static ResultCode UnmapPhysicalMemory32(Core::System& system, u32 addr, u32 size) {
  856. return UnmapPhysicalMemory(system, addr, size);
  857. }
  858. /// Sets the thread activity
  859. static ResultCode SetThreadActivity(Core::System& system, Handle thread_handle,
  860. ThreadActivity thread_activity) {
  861. LOG_DEBUG(Kernel_SVC, "called, handle=0x{:08X}, activity=0x{:08X}", thread_handle,
  862. thread_activity);
  863. // Validate the activity.
  864. constexpr auto IsValidThreadActivity = [](ThreadActivity activity) {
  865. return activity == ThreadActivity::Runnable || activity == ThreadActivity::Paused;
  866. };
  867. R_UNLESS(IsValidThreadActivity(thread_activity), ResultInvalidEnumValue);
  868. // Get the thread from its handle.
  869. KScopedAutoObject thread =
  870. system.Kernel().CurrentProcess()->GetHandleTable().GetObject<KThread>(thread_handle);
  871. R_UNLESS(thread.IsNotNull(), ResultInvalidHandle);
  872. // Check that the activity is being set on a non-current thread for the current process.
  873. R_UNLESS(thread->GetOwnerProcess() == system.Kernel().CurrentProcess(), ResultInvalidHandle);
  874. R_UNLESS(thread.GetPointerUnsafe() != GetCurrentThreadPointer(system.Kernel()), ResultBusy);
  875. // Set the activity.
  876. R_TRY(thread->SetActivity(thread_activity));
  877. return ResultSuccess;
  878. }
  879. static ResultCode SetThreadActivity32(Core::System& system, Handle thread_handle,
  880. Svc::ThreadActivity thread_activity) {
  881. return SetThreadActivity(system, thread_handle, thread_activity);
  882. }
  883. /// Gets the thread context
  884. static ResultCode GetThreadContext(Core::System& system, VAddr out_context, Handle thread_handle) {
  885. LOG_DEBUG(Kernel_SVC, "called, out_context=0x{:08X}, thread_handle=0x{:X}", out_context,
  886. thread_handle);
  887. auto& kernel = system.Kernel();
  888. // Get the thread from its handle.
  889. KScopedAutoObject thread =
  890. kernel.CurrentProcess()->GetHandleTable().GetObject<KThread>(thread_handle);
  891. R_UNLESS(thread.IsNotNull(), ResultInvalidHandle);
  892. // Require the handle be to a non-current thread in the current process.
  893. const auto* current_process = kernel.CurrentProcess();
  894. R_UNLESS(current_process == thread->GetOwnerProcess(), ResultInvalidId);
  895. // Verify that the thread isn't terminated.
  896. R_UNLESS(thread->GetState() != ThreadState::Terminated, ResultTerminationRequested);
  897. /// Check that the thread is not the current one.
  898. /// NOTE: Nintendo does not check this, and thus the following loop will deadlock.
  899. R_UNLESS(thread.GetPointerUnsafe() != GetCurrentThreadPointer(kernel), ResultInvalidId);
  900. // Try to get the thread context until the thread isn't current on any core.
  901. while (true) {
  902. KScopedSchedulerLock sl{kernel};
  903. // TODO(bunnei): Enforce that thread is suspended for debug here.
  904. // If the thread's raw state isn't runnable, check if it's current on some core.
  905. if (thread->GetRawState() != ThreadState::Runnable) {
  906. bool current = false;
  907. for (auto i = 0; i < static_cast<s32>(Core::Hardware::NUM_CPU_CORES); ++i) {
  908. if (thread.GetPointerUnsafe() == kernel.Scheduler(i).GetCurrentThread()) {
  909. current = true;
  910. break;
  911. }
  912. }
  913. // If the thread is current, retry until it isn't.
  914. if (current) {
  915. continue;
  916. }
  917. }
  918. // Get the thread context.
  919. std::vector<u8> context;
  920. R_TRY(thread->GetThreadContext3(context));
  921. // Copy the thread context to user space.
  922. system.Memory().WriteBlock(out_context, context.data(), context.size());
  923. return ResultSuccess;
  924. }
  925. return ResultSuccess;
  926. }
  927. static ResultCode GetThreadContext32(Core::System& system, u32 out_context, Handle thread_handle) {
  928. return GetThreadContext(system, out_context, thread_handle);
  929. }
  930. /// Gets the priority for the specified thread
  931. static ResultCode GetThreadPriority(Core::System& system, u32* out_priority, Handle handle) {
  932. LOG_TRACE(Kernel_SVC, "called");
  933. // Get the thread from its handle.
  934. KScopedAutoObject thread =
  935. system.Kernel().CurrentProcess()->GetHandleTable().GetObject<KThread>(handle);
  936. R_UNLESS(thread.IsNotNull(), ResultInvalidHandle);
  937. // Get the thread's priority.
  938. *out_priority = thread->GetPriority();
  939. return ResultSuccess;
  940. }
  941. static ResultCode GetThreadPriority32(Core::System& system, u32* out_priority, Handle handle) {
  942. return GetThreadPriority(system, out_priority, handle);
  943. }
  944. /// Sets the priority for the specified thread
  945. static ResultCode SetThreadPriority(Core::System& system, Handle thread_handle, u32 priority) {
  946. // Get the current process.
  947. KProcess& process = *system.Kernel().CurrentProcess();
  948. // Validate the priority.
  949. R_UNLESS(HighestThreadPriority <= priority && priority <= LowestThreadPriority,
  950. ResultInvalidPriority);
  951. R_UNLESS(process.CheckThreadPriority(priority), ResultInvalidPriority);
  952. // Get the thread from its handle.
  953. KScopedAutoObject thread = process.GetHandleTable().GetObject<KThread>(thread_handle);
  954. R_UNLESS(thread.IsNotNull(), ResultInvalidHandle);
  955. // Set the thread priority.
  956. thread->SetBasePriority(priority);
  957. return ResultSuccess;
  958. }
  959. static ResultCode SetThreadPriority32(Core::System& system, Handle thread_handle, u32 priority) {
  960. return SetThreadPriority(system, thread_handle, priority);
  961. }
  962. /// Get which CPU core is executing the current thread
  963. static u32 GetCurrentProcessorNumber(Core::System& system) {
  964. LOG_TRACE(Kernel_SVC, "called");
  965. return static_cast<u32>(system.CurrentPhysicalCore().CoreIndex());
  966. }
  967. static u32 GetCurrentProcessorNumber32(Core::System& system) {
  968. return GetCurrentProcessorNumber(system);
  969. }
  970. namespace {
  971. constexpr bool IsValidSharedMemoryPermission(Svc::MemoryPermission perm) {
  972. switch (perm) {
  973. case Svc::MemoryPermission::Read:
  974. case Svc::MemoryPermission::ReadWrite:
  975. return true;
  976. default:
  977. return false;
  978. }
  979. }
  980. [[maybe_unused]] constexpr bool IsValidRemoteSharedMemoryPermission(Svc::MemoryPermission perm) {
  981. return IsValidSharedMemoryPermission(perm) || perm == Svc::MemoryPermission::DontCare;
  982. }
  983. constexpr bool IsValidProcessMemoryPermission(Svc::MemoryPermission perm) {
  984. switch (perm) {
  985. case Svc::MemoryPermission::None:
  986. case Svc::MemoryPermission::Read:
  987. case Svc::MemoryPermission::ReadWrite:
  988. case Svc::MemoryPermission::ReadExecute:
  989. return true;
  990. default:
  991. return false;
  992. }
  993. }
  994. constexpr bool IsValidMapCodeMemoryPermission(Svc::MemoryPermission perm) {
  995. return perm == Svc::MemoryPermission::ReadWrite;
  996. }
  997. constexpr bool IsValidMapToOwnerCodeMemoryPermission(Svc::MemoryPermission perm) {
  998. return perm == Svc::MemoryPermission::Read || perm == Svc::MemoryPermission::ReadExecute;
  999. }
  1000. constexpr bool IsValidUnmapCodeMemoryPermission(Svc::MemoryPermission perm) {
  1001. return perm == Svc::MemoryPermission::None;
  1002. }
  1003. constexpr bool IsValidUnmapFromOwnerCodeMemoryPermission(Svc::MemoryPermission perm) {
  1004. return perm == Svc::MemoryPermission::None;
  1005. }
  1006. } // Anonymous namespace
  1007. static ResultCode MapSharedMemory(Core::System& system, Handle shmem_handle, VAddr address,
  1008. u64 size, Svc::MemoryPermission map_perm) {
  1009. LOG_TRACE(Kernel_SVC,
  1010. "called, shared_memory_handle=0x{:X}, addr=0x{:X}, size=0x{:X}, permissions=0x{:08X}",
  1011. shmem_handle, address, size, map_perm);
  1012. // Validate the address/size.
  1013. R_UNLESS(Common::IsAligned(address, PageSize), ResultInvalidAddress);
  1014. R_UNLESS(Common::IsAligned(size, PageSize), ResultInvalidSize);
  1015. R_UNLESS(size > 0, ResultInvalidSize);
  1016. R_UNLESS((address < address + size), ResultInvalidCurrentMemory);
  1017. // Validate the permission.
  1018. R_UNLESS(IsValidSharedMemoryPermission(map_perm), ResultInvalidNewMemoryPermission);
  1019. // Get the current process.
  1020. auto& process = *system.Kernel().CurrentProcess();
  1021. auto& page_table = process.PageTable();
  1022. // Get the shared memory.
  1023. KScopedAutoObject shmem = process.GetHandleTable().GetObject<KSharedMemory>(shmem_handle);
  1024. R_UNLESS(shmem.IsNotNull(), ResultInvalidHandle);
  1025. // Verify that the mapping is in range.
  1026. R_UNLESS(page_table.CanContain(address, size, KMemoryState::Shared), ResultInvalidMemoryRegion);
  1027. // Add the shared memory to the process.
  1028. R_TRY(process.AddSharedMemory(shmem.GetPointerUnsafe(), address, size));
  1029. // Ensure that we clean up the shared memory if we fail to map it.
  1030. auto guard =
  1031. SCOPE_GUARD({ process.RemoveSharedMemory(shmem.GetPointerUnsafe(), address, size); });
  1032. // Map the shared memory.
  1033. R_TRY(shmem->Map(process, address, size, map_perm));
  1034. // We succeeded.
  1035. guard.Cancel();
  1036. return ResultSuccess;
  1037. }
  1038. static ResultCode MapSharedMemory32(Core::System& system, Handle shmem_handle, u32 address,
  1039. u32 size, Svc::MemoryPermission map_perm) {
  1040. return MapSharedMemory(system, shmem_handle, address, size, map_perm);
  1041. }
  1042. static ResultCode UnmapSharedMemory(Core::System& system, Handle shmem_handle, VAddr address,
  1043. u64 size) {
  1044. // Validate the address/size.
  1045. R_UNLESS(Common::IsAligned(address, PageSize), ResultInvalidAddress);
  1046. R_UNLESS(Common::IsAligned(size, PageSize), ResultInvalidSize);
  1047. R_UNLESS(size > 0, ResultInvalidSize);
  1048. R_UNLESS((address < address + size), ResultInvalidCurrentMemory);
  1049. // Get the current process.
  1050. auto& process = *system.Kernel().CurrentProcess();
  1051. auto& page_table = process.PageTable();
  1052. // Get the shared memory.
  1053. KScopedAutoObject shmem = process.GetHandleTable().GetObject<KSharedMemory>(shmem_handle);
  1054. R_UNLESS(shmem.IsNotNull(), ResultInvalidHandle);
  1055. // Verify that the mapping is in range.
  1056. R_UNLESS(page_table.CanContain(address, size, KMemoryState::Shared), ResultInvalidMemoryRegion);
  1057. // Unmap the shared memory.
  1058. R_TRY(shmem->Unmap(process, address, size));
  1059. // Remove the shared memory from the process.
  1060. process.RemoveSharedMemory(shmem.GetPointerUnsafe(), address, size);
  1061. return ResultSuccess;
  1062. }
  1063. static ResultCode UnmapSharedMemory32(Core::System& system, Handle shmem_handle, u32 address,
  1064. u32 size) {
  1065. return UnmapSharedMemory(system, shmem_handle, address, size);
  1066. }
  1067. static ResultCode SetProcessMemoryPermission(Core::System& system, Handle process_handle,
  1068. VAddr address, u64 size, Svc::MemoryPermission perm) {
  1069. LOG_TRACE(Kernel_SVC,
  1070. "called, process_handle=0x{:X}, addr=0x{:X}, size=0x{:X}, permissions=0x{:08X}",
  1071. process_handle, address, size, perm);
  1072. // Validate the address/size.
  1073. R_UNLESS(Common::IsAligned(address, PageSize), ResultInvalidAddress);
  1074. R_UNLESS(Common::IsAligned(size, PageSize), ResultInvalidSize);
  1075. R_UNLESS(size > 0, ResultInvalidSize);
  1076. R_UNLESS((address < address + size), ResultInvalidCurrentMemory);
  1077. R_UNLESS(address == static_cast<uintptr_t>(address), ResultInvalidCurrentMemory);
  1078. R_UNLESS(size == static_cast<size_t>(size), ResultInvalidCurrentMemory);
  1079. // Validate the memory permission.
  1080. R_UNLESS(IsValidProcessMemoryPermission(perm), ResultInvalidNewMemoryPermission);
  1081. // Get the process from its handle.
  1082. KScopedAutoObject process =
  1083. system.CurrentProcess()->GetHandleTable().GetObject<KProcess>(process_handle);
  1084. R_UNLESS(process.IsNotNull(), ResultInvalidHandle);
  1085. // Validate that the address is in range.
  1086. auto& page_table = process->PageTable();
  1087. R_UNLESS(page_table.Contains(address, size), ResultInvalidCurrentMemory);
  1088. // Set the memory permission.
  1089. return page_table.SetProcessMemoryPermission(address, size, perm);
  1090. }
  1091. static ResultCode MapProcessMemory(Core::System& system, VAddr dst_address, Handle process_handle,
  1092. VAddr src_address, u64 size) {
  1093. LOG_TRACE(Kernel_SVC,
  1094. "called, dst_address=0x{:X}, process_handle=0x{:X}, src_address=0x{:X}, size=0x{:X}",
  1095. dst_address, process_handle, src_address, size);
  1096. // Validate the address/size.
  1097. R_UNLESS(Common::IsAligned(dst_address, PageSize), ResultInvalidAddress);
  1098. R_UNLESS(Common::IsAligned(src_address, PageSize), ResultInvalidAddress);
  1099. R_UNLESS(Common::IsAligned(size, PageSize), ResultInvalidSize);
  1100. R_UNLESS(size > 0, ResultInvalidSize);
  1101. R_UNLESS((dst_address < dst_address + size), ResultInvalidCurrentMemory);
  1102. R_UNLESS((src_address < src_address + size), ResultInvalidCurrentMemory);
  1103. // Get the processes.
  1104. KProcess* dst_process = system.CurrentProcess();
  1105. KScopedAutoObject src_process =
  1106. dst_process->GetHandleTable().GetObjectWithoutPseudoHandle<KProcess>(process_handle);
  1107. R_UNLESS(src_process.IsNotNull(), ResultInvalidHandle);
  1108. // Get the page tables.
  1109. auto& dst_pt = dst_process->PageTable();
  1110. auto& src_pt = src_process->PageTable();
  1111. // Validate that the mapping is in range.
  1112. R_UNLESS(src_pt.Contains(src_address, size), ResultInvalidCurrentMemory);
  1113. R_UNLESS(dst_pt.CanContain(dst_address, size, KMemoryState::SharedCode),
  1114. ResultInvalidMemoryRegion);
  1115. // Create a new page group.
  1116. KPageLinkedList pg;
  1117. R_TRY(src_pt.MakeAndOpenPageGroup(
  1118. std::addressof(pg), src_address, size / PageSize, KMemoryState::FlagCanMapProcess,
  1119. KMemoryState::FlagCanMapProcess, KMemoryPermission::None, KMemoryPermission::None,
  1120. KMemoryAttribute::All, KMemoryAttribute::None));
  1121. // Map the group.
  1122. R_TRY(dst_pt.MapPages(dst_address, pg, KMemoryState::SharedCode,
  1123. KMemoryPermission::UserReadWrite));
  1124. return ResultSuccess;
  1125. }
  1126. static ResultCode UnmapProcessMemory(Core::System& system, VAddr dst_address, Handle process_handle,
  1127. VAddr src_address, u64 size) {
  1128. LOG_TRACE(Kernel_SVC,
  1129. "called, dst_address=0x{:X}, process_handle=0x{:X}, src_address=0x{:X}, size=0x{:X}",
  1130. dst_address, process_handle, src_address, size);
  1131. // Validate the address/size.
  1132. R_UNLESS(Common::IsAligned(dst_address, PageSize), ResultInvalidAddress);
  1133. R_UNLESS(Common::IsAligned(src_address, PageSize), ResultInvalidAddress);
  1134. R_UNLESS(Common::IsAligned(size, PageSize), ResultInvalidSize);
  1135. R_UNLESS(size > 0, ResultInvalidSize);
  1136. R_UNLESS((dst_address < dst_address + size), ResultInvalidCurrentMemory);
  1137. R_UNLESS((src_address < src_address + size), ResultInvalidCurrentMemory);
  1138. // Get the processes.
  1139. KProcess* dst_process = system.CurrentProcess();
  1140. KScopedAutoObject src_process =
  1141. dst_process->GetHandleTable().GetObjectWithoutPseudoHandle<KProcess>(process_handle);
  1142. R_UNLESS(src_process.IsNotNull(), ResultInvalidHandle);
  1143. // Get the page tables.
  1144. auto& dst_pt = dst_process->PageTable();
  1145. auto& src_pt = src_process->PageTable();
  1146. // Validate that the mapping is in range.
  1147. R_UNLESS(src_pt.Contains(src_address, size), ResultInvalidCurrentMemory);
  1148. R_UNLESS(dst_pt.CanContain(dst_address, size, KMemoryState::SharedCode),
  1149. ResultInvalidMemoryRegion);
  1150. // Unmap the memory.
  1151. R_TRY(dst_pt.UnmapProcessMemory(dst_address, size, src_pt, src_address));
  1152. return ResultSuccess;
  1153. }
  1154. static ResultCode CreateCodeMemory(Core::System& system, Handle* out, VAddr address, size_t size) {
  1155. LOG_TRACE(Kernel_SVC, "called, address=0x{:X}, size=0x{:X}", address, size);
  1156. // Get kernel instance.
  1157. auto& kernel = system.Kernel();
  1158. // Validate address / size.
  1159. R_UNLESS(Common::IsAligned(address, PageSize), ResultInvalidAddress);
  1160. R_UNLESS(Common::IsAligned(size, PageSize), ResultInvalidSize);
  1161. R_UNLESS(size > 0, ResultInvalidSize);
  1162. R_UNLESS((address < address + size), ResultInvalidCurrentMemory);
  1163. // Create the code memory.
  1164. KCodeMemory* code_mem = KCodeMemory::Create(kernel);
  1165. R_UNLESS(code_mem != nullptr, ResultOutOfResource);
  1166. // Verify that the region is in range.
  1167. R_UNLESS(system.CurrentProcess()->PageTable().Contains(address, size),
  1168. ResultInvalidCurrentMemory);
  1169. // Initialize the code memory.
  1170. R_TRY(code_mem->Initialize(system.DeviceMemory(), address, size));
  1171. // Register the code memory.
  1172. KCodeMemory::Register(kernel, code_mem);
  1173. // Add the code memory to the handle table.
  1174. R_TRY(system.CurrentProcess()->GetHandleTable().Add(out, code_mem));
  1175. code_mem->Close();
  1176. return ResultSuccess;
  1177. }
  1178. static ResultCode CreateCodeMemory32(Core::System& system, Handle* out, u32 address, u32 size) {
  1179. return CreateCodeMemory(system, out, address, size);
  1180. }
  1181. static ResultCode ControlCodeMemory(Core::System& system, Handle code_memory_handle, u32 operation,
  1182. VAddr address, size_t size, Svc::MemoryPermission perm) {
  1183. LOG_TRACE(Kernel_SVC,
  1184. "called, code_memory_handle=0x{:X}, operation=0x{:X}, address=0x{:X}, size=0x{:X}, "
  1185. "permission=0x{:X}",
  1186. code_memory_handle, operation, address, size, perm);
  1187. // Validate the address / size.
  1188. R_UNLESS(Common::IsAligned(address, PageSize), ResultInvalidAddress);
  1189. R_UNLESS(Common::IsAligned(size, PageSize), ResultInvalidSize);
  1190. R_UNLESS(size > 0, ResultInvalidSize);
  1191. R_UNLESS((address < address + size), ResultInvalidCurrentMemory);
  1192. // Get the code memory from its handle.
  1193. KScopedAutoObject code_mem =
  1194. system.CurrentProcess()->GetHandleTable().GetObject<KCodeMemory>(code_memory_handle);
  1195. R_UNLESS(code_mem.IsNotNull(), ResultInvalidHandle);
  1196. // NOTE: Here, Atmosphere extends the SVC to allow code memory operations on one's own process.
  1197. // This enables homebrew usage of these SVCs for JIT.
  1198. // Perform the operation.
  1199. switch (static_cast<CodeMemoryOperation>(operation)) {
  1200. case CodeMemoryOperation::Map: {
  1201. // Check that the region is in range.
  1202. R_UNLESS(
  1203. system.CurrentProcess()->PageTable().CanContain(address, size, KMemoryState::CodeOut),
  1204. ResultInvalidMemoryRegion);
  1205. // Check the memory permission.
  1206. R_UNLESS(IsValidMapCodeMemoryPermission(perm), ResultInvalidNewMemoryPermission);
  1207. // Map the memory.
  1208. R_TRY(code_mem->Map(address, size));
  1209. } break;
  1210. case CodeMemoryOperation::Unmap: {
  1211. // Check that the region is in range.
  1212. R_UNLESS(
  1213. system.CurrentProcess()->PageTable().CanContain(address, size, KMemoryState::CodeOut),
  1214. ResultInvalidMemoryRegion);
  1215. // Check the memory permission.
  1216. R_UNLESS(IsValidUnmapCodeMemoryPermission(perm), ResultInvalidNewMemoryPermission);
  1217. // Unmap the memory.
  1218. R_TRY(code_mem->Unmap(address, size));
  1219. } break;
  1220. case CodeMemoryOperation::MapToOwner: {
  1221. // Check that the region is in range.
  1222. R_UNLESS(code_mem->GetOwner()->PageTable().CanContain(address, size,
  1223. KMemoryState::GeneratedCode),
  1224. ResultInvalidMemoryRegion);
  1225. // Check the memory permission.
  1226. R_UNLESS(IsValidMapToOwnerCodeMemoryPermission(perm), ResultInvalidNewMemoryPermission);
  1227. // Map the memory to its owner.
  1228. R_TRY(code_mem->MapToOwner(address, size, perm));
  1229. } break;
  1230. case CodeMemoryOperation::UnmapFromOwner: {
  1231. // Check that the region is in range.
  1232. R_UNLESS(code_mem->GetOwner()->PageTable().CanContain(address, size,
  1233. KMemoryState::GeneratedCode),
  1234. ResultInvalidMemoryRegion);
  1235. // Check the memory permission.
  1236. R_UNLESS(IsValidUnmapFromOwnerCodeMemoryPermission(perm), ResultInvalidNewMemoryPermission);
  1237. // Unmap the memory from its owner.
  1238. R_TRY(code_mem->UnmapFromOwner(address, size));
  1239. } break;
  1240. default:
  1241. return ResultInvalidEnumValue;
  1242. }
  1243. return ResultSuccess;
  1244. }
  1245. static ResultCode ControlCodeMemory32(Core::System& system, Handle code_memory_handle,
  1246. u32 operation, u64 address, u64 size,
  1247. Svc::MemoryPermission perm) {
  1248. return ControlCodeMemory(system, code_memory_handle, operation, address, size, perm);
  1249. }
  1250. static ResultCode QueryProcessMemory(Core::System& system, VAddr memory_info_address,
  1251. VAddr page_info_address, Handle process_handle,
  1252. VAddr address) {
  1253. LOG_TRACE(Kernel_SVC, "called process=0x{:08X} address={:X}", process_handle, address);
  1254. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1255. KScopedAutoObject process = handle_table.GetObject<KProcess>(process_handle);
  1256. if (process.IsNull()) {
  1257. LOG_ERROR(Kernel_SVC, "Process handle does not exist, process_handle=0x{:08X}",
  1258. process_handle);
  1259. return ResultInvalidHandle;
  1260. }
  1261. auto& memory{system.Memory()};
  1262. const auto memory_info{process->PageTable().QueryInfo(address).GetSvcMemoryInfo()};
  1263. memory.Write64(memory_info_address + 0x00, memory_info.addr);
  1264. memory.Write64(memory_info_address + 0x08, memory_info.size);
  1265. memory.Write32(memory_info_address + 0x10, static_cast<u32>(memory_info.state) & 0xff);
  1266. memory.Write32(memory_info_address + 0x14, static_cast<u32>(memory_info.attr));
  1267. memory.Write32(memory_info_address + 0x18, static_cast<u32>(memory_info.perm));
  1268. memory.Write32(memory_info_address + 0x1c, memory_info.ipc_refcount);
  1269. memory.Write32(memory_info_address + 0x20, memory_info.device_refcount);
  1270. memory.Write32(memory_info_address + 0x24, 0);
  1271. // Page info appears to be currently unused by the kernel and is always set to zero.
  1272. memory.Write32(page_info_address, 0);
  1273. return ResultSuccess;
  1274. }
  1275. static ResultCode QueryMemory(Core::System& system, VAddr memory_info_address,
  1276. VAddr page_info_address, VAddr query_address) {
  1277. LOG_TRACE(Kernel_SVC,
  1278. "called, memory_info_address=0x{:016X}, page_info_address=0x{:016X}, "
  1279. "query_address=0x{:016X}",
  1280. memory_info_address, page_info_address, query_address);
  1281. return QueryProcessMemory(system, memory_info_address, page_info_address, CurrentProcess,
  1282. query_address);
  1283. }
  1284. static ResultCode QueryMemory32(Core::System& system, u32 memory_info_address,
  1285. u32 page_info_address, u32 query_address) {
  1286. return QueryMemory(system, memory_info_address, page_info_address, query_address);
  1287. }
  1288. static ResultCode MapProcessCodeMemory(Core::System& system, Handle process_handle, u64 dst_address,
  1289. u64 src_address, u64 size) {
  1290. LOG_DEBUG(Kernel_SVC,
  1291. "called. process_handle=0x{:08X}, dst_address=0x{:016X}, "
  1292. "src_address=0x{:016X}, size=0x{:016X}",
  1293. process_handle, dst_address, src_address, size);
  1294. if (!Common::Is4KBAligned(src_address)) {
  1295. LOG_ERROR(Kernel_SVC, "src_address is not page-aligned (src_address=0x{:016X}).",
  1296. src_address);
  1297. return ResultInvalidAddress;
  1298. }
  1299. if (!Common::Is4KBAligned(dst_address)) {
  1300. LOG_ERROR(Kernel_SVC, "dst_address is not page-aligned (dst_address=0x{:016X}).",
  1301. dst_address);
  1302. return ResultInvalidAddress;
  1303. }
  1304. if (size == 0 || !Common::Is4KBAligned(size)) {
  1305. LOG_ERROR(Kernel_SVC, "Size is zero or not page-aligned (size=0x{:016X})", size);
  1306. return ResultInvalidSize;
  1307. }
  1308. if (!IsValidAddressRange(dst_address, size)) {
  1309. LOG_ERROR(Kernel_SVC,
  1310. "Destination address range overflows the address space (dst_address=0x{:016X}, "
  1311. "size=0x{:016X}).",
  1312. dst_address, size);
  1313. return ResultInvalidCurrentMemory;
  1314. }
  1315. if (!IsValidAddressRange(src_address, size)) {
  1316. LOG_ERROR(Kernel_SVC,
  1317. "Source address range overflows the address space (src_address=0x{:016X}, "
  1318. "size=0x{:016X}).",
  1319. src_address, size);
  1320. return ResultInvalidCurrentMemory;
  1321. }
  1322. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1323. KScopedAutoObject process = handle_table.GetObject<KProcess>(process_handle);
  1324. if (process.IsNull()) {
  1325. LOG_ERROR(Kernel_SVC, "Invalid process handle specified (handle=0x{:08X}).",
  1326. process_handle);
  1327. return ResultInvalidHandle;
  1328. }
  1329. auto& page_table = process->PageTable();
  1330. if (!page_table.IsInsideAddressSpace(src_address, size)) {
  1331. LOG_ERROR(Kernel_SVC,
  1332. "Source address range is not within the address space (src_address=0x{:016X}, "
  1333. "size=0x{:016X}).",
  1334. src_address, size);
  1335. return ResultInvalidCurrentMemory;
  1336. }
  1337. if (!page_table.IsInsideASLRRegion(dst_address, size)) {
  1338. LOG_ERROR(Kernel_SVC,
  1339. "Destination address range is not within the ASLR region (dst_address=0x{:016X}, "
  1340. "size=0x{:016X}).",
  1341. dst_address, size);
  1342. return ResultInvalidMemoryRegion;
  1343. }
  1344. return page_table.MapCodeMemory(dst_address, src_address, size);
  1345. }
  1346. static ResultCode UnmapProcessCodeMemory(Core::System& system, Handle process_handle,
  1347. u64 dst_address, u64 src_address, u64 size) {
  1348. LOG_DEBUG(Kernel_SVC,
  1349. "called. process_handle=0x{:08X}, dst_address=0x{:016X}, src_address=0x{:016X}, "
  1350. "size=0x{:016X}",
  1351. process_handle, dst_address, src_address, size);
  1352. if (!Common::Is4KBAligned(dst_address)) {
  1353. LOG_ERROR(Kernel_SVC, "dst_address is not page-aligned (dst_address=0x{:016X}).",
  1354. dst_address);
  1355. return ResultInvalidAddress;
  1356. }
  1357. if (!Common::Is4KBAligned(src_address)) {
  1358. LOG_ERROR(Kernel_SVC, "src_address is not page-aligned (src_address=0x{:016X}).",
  1359. src_address);
  1360. return ResultInvalidAddress;
  1361. }
  1362. if (size == 0 || !Common::Is4KBAligned(size)) {
  1363. LOG_ERROR(Kernel_SVC, "Size is zero or not page-aligned (size=0x{:016X}).", size);
  1364. return ResultInvalidSize;
  1365. }
  1366. if (!IsValidAddressRange(dst_address, size)) {
  1367. LOG_ERROR(Kernel_SVC,
  1368. "Destination address range overflows the address space (dst_address=0x{:016X}, "
  1369. "size=0x{:016X}).",
  1370. dst_address, size);
  1371. return ResultInvalidCurrentMemory;
  1372. }
  1373. if (!IsValidAddressRange(src_address, size)) {
  1374. LOG_ERROR(Kernel_SVC,
  1375. "Source address range overflows the address space (src_address=0x{:016X}, "
  1376. "size=0x{:016X}).",
  1377. src_address, size);
  1378. return ResultInvalidCurrentMemory;
  1379. }
  1380. const auto& handle_table = system.Kernel().CurrentProcess()->GetHandleTable();
  1381. KScopedAutoObject process = handle_table.GetObject<KProcess>(process_handle);
  1382. if (process.IsNull()) {
  1383. LOG_ERROR(Kernel_SVC, "Invalid process handle specified (handle=0x{:08X}).",
  1384. process_handle);
  1385. return ResultInvalidHandle;
  1386. }
  1387. auto& page_table = process->PageTable();
  1388. if (!page_table.IsInsideAddressSpace(src_address, size)) {
  1389. LOG_ERROR(Kernel_SVC,
  1390. "Source address range is not within the address space (src_address=0x{:016X}, "
  1391. "size=0x{:016X}).",
  1392. src_address, size);
  1393. return ResultInvalidCurrentMemory;
  1394. }
  1395. if (!page_table.IsInsideASLRRegion(dst_address, size)) {
  1396. LOG_ERROR(Kernel_SVC,
  1397. "Destination address range is not within the ASLR region (dst_address=0x{:016X}, "
  1398. "size=0x{:016X}).",
  1399. dst_address, size);
  1400. return ResultInvalidMemoryRegion;
  1401. }
  1402. return page_table.UnmapCodeMemory(dst_address, src_address, size);
  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. UNREACHABLE_MSG("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. const 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