svc.cpp 104 KB

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