svc.cpp 97 KB

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