svc.cpp 103 KB

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