svc.cpp 102 KB

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