svc.cpp 103 KB

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