svc.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <map>
  5. #include "common/logging/log.h"
  6. #include "common/microprofile.h"
  7. #include "common/profiler.h"
  8. #include "common/string_util.h"
  9. #include "common/symbols.h"
  10. #include "core/core_timing.h"
  11. #include "core/arm/arm_interface.h"
  12. #include "core/hle/kernel/address_arbiter.h"
  13. #include "core/hle/kernel/event.h"
  14. #include "core/hle/kernel/memory.h"
  15. #include "core/hle/kernel/mutex.h"
  16. #include "core/hle/kernel/process.h"
  17. #include "core/hle/kernel/resource_limit.h"
  18. #include "core/hle/kernel/semaphore.h"
  19. #include "core/hle/kernel/shared_memory.h"
  20. #include "core/hle/kernel/thread.h"
  21. #include "core/hle/kernel/timer.h"
  22. #include "core/hle/kernel/vm_manager.h"
  23. #include "core/hle/function_wrappers.h"
  24. #include "core/hle/result.h"
  25. #include "core/hle/service/service.h"
  26. ////////////////////////////////////////////////////////////////////////////////////////////////////
  27. // Namespace SVC
  28. using Kernel::SharedPtr;
  29. using Kernel::ERR_INVALID_HANDLE;
  30. namespace SVC {
  31. const ResultCode ERR_NOT_FOUND(ErrorDescription::NotFound, ErrorModule::Kernel,
  32. ErrorSummary::NotFound, ErrorLevel::Permanent); // 0xD88007FA
  33. const ResultCode ERR_PORT_NAME_TOO_LONG(ErrorDescription(30), ErrorModule::OS,
  34. ErrorSummary::InvalidArgument, ErrorLevel::Usage); // 0xE0E0181E
  35. const ResultCode ERR_MISALIGNED_ADDRESS{ // 0xE0E01BF1
  36. ErrorDescription::MisalignedAddress, ErrorModule::OS,
  37. ErrorSummary::InvalidArgument, ErrorLevel::Usage};
  38. const ResultCode ERR_MISALIGNED_SIZE{ // 0xE0E01BF2
  39. ErrorDescription::MisalignedSize, ErrorModule::OS,
  40. ErrorSummary::InvalidArgument, ErrorLevel::Usage};
  41. const ResultCode ERR_INVALID_COMBINATION{ // 0xE0E01BEE
  42. ErrorDescription::InvalidCombination, ErrorModule::OS,
  43. ErrorSummary::InvalidArgument, ErrorLevel::Usage};
  44. enum ControlMemoryOperation {
  45. MEMOP_FREE = 1,
  46. MEMOP_RESERVE = 2, // This operation seems to be unsupported in the kernel
  47. MEMOP_COMMIT = 3,
  48. MEMOP_MAP = 4,
  49. MEMOP_UNMAP = 5,
  50. MEMOP_PROTECT = 6,
  51. MEMOP_OPERATION_MASK = 0xFF,
  52. MEMOP_REGION_APP = 0x100,
  53. MEMOP_REGION_SYSTEM = 0x200,
  54. MEMOP_REGION_BASE = 0x300,
  55. MEMOP_REGION_MASK = 0xF00,
  56. MEMOP_LINEAR = 0x10000,
  57. };
  58. /// Map application or GSP heap memory
  59. static ResultCode ControlMemory(u32* out_addr, u32 operation, u32 addr0, u32 addr1, u32 size, u32 permissions) {
  60. using namespace Kernel;
  61. LOG_DEBUG(Kernel_SVC,"called operation=0x%08X, addr0=0x%08X, addr1=0x%08X, size=0x%X, permissions=0x%08X",
  62. operation, addr0, addr1, size, permissions);
  63. if ((addr0 & Memory::PAGE_MASK) != 0 || (addr1 & Memory::PAGE_MASK) != 0) {
  64. return ERR_MISALIGNED_ADDRESS;
  65. }
  66. if ((size & Memory::PAGE_MASK) != 0) {
  67. return ERR_MISALIGNED_SIZE;
  68. }
  69. u32 region = operation & MEMOP_REGION_MASK;
  70. operation &= ~MEMOP_REGION_MASK;
  71. if (region != 0) {
  72. LOG_WARNING(Kernel_SVC, "ControlMemory with specified region not supported, region=%X", region);
  73. }
  74. if ((permissions & (u32)MemoryPermission::ReadWrite) != permissions) {
  75. return ERR_INVALID_COMBINATION;
  76. }
  77. VMAPermission vma_permissions = (VMAPermission)permissions;
  78. auto& process = *g_current_process;
  79. switch (operation & MEMOP_OPERATION_MASK) {
  80. case MEMOP_FREE:
  81. {
  82. if (addr0 >= Memory::HEAP_VADDR && addr0 < Memory::HEAP_VADDR_END) {
  83. ResultCode result = process.HeapFree(addr0, size);
  84. if (result.IsError()) return result;
  85. } else if (addr0 >= process.GetLinearHeapBase() && addr0 < process.GetLinearHeapLimit()) {
  86. ResultCode result = process.LinearFree(addr0, size);
  87. if (result.IsError()) return result;
  88. } else {
  89. return ERR_INVALID_ADDRESS;
  90. }
  91. *out_addr = addr0;
  92. break;
  93. }
  94. case MEMOP_COMMIT:
  95. {
  96. if (operation & MEMOP_LINEAR) {
  97. CASCADE_RESULT(*out_addr, process.LinearAllocate(addr0, size, vma_permissions));
  98. } else {
  99. CASCADE_RESULT(*out_addr, process.HeapAllocate(addr0, size, vma_permissions));
  100. }
  101. break;
  102. }
  103. case MEMOP_MAP: // TODO: This is just a hack to avoid regressions until memory aliasing is implemented
  104. {
  105. CASCADE_RESULT(*out_addr, process.HeapAllocate(addr0, size, vma_permissions));
  106. break;
  107. }
  108. case MEMOP_UNMAP: // TODO: This is just a hack to avoid regressions until memory aliasing is implemented
  109. {
  110. ResultCode result = process.HeapFree(addr0, size);
  111. if (result.IsError()) return result;
  112. break;
  113. }
  114. case MEMOP_PROTECT:
  115. {
  116. ResultCode result = process.vm_manager.ReprotectRange(addr0, size, vma_permissions);
  117. if (result.IsError()) return result;
  118. break;
  119. }
  120. default:
  121. LOG_ERROR(Kernel_SVC, "unknown operation=0x%08X", operation);
  122. return ERR_INVALID_COMBINATION;
  123. }
  124. process.vm_manager.LogLayout(Log::Level::Trace);
  125. return RESULT_SUCCESS;
  126. }
  127. /// Maps a memory block to specified address
  128. static ResultCode MapMemoryBlock(Handle handle, u32 addr, u32 permissions, u32 other_permissions) {
  129. using Kernel::SharedMemory;
  130. using Kernel::MemoryPermission;
  131. LOG_TRACE(Kernel_SVC, "called memblock=0x%08X, addr=0x%08X, mypermissions=0x%08X, otherpermission=%d",
  132. handle, addr, permissions, other_permissions);
  133. SharedPtr<SharedMemory> shared_memory = Kernel::g_handle_table.Get<SharedMemory>(handle);
  134. if (shared_memory == nullptr)
  135. return ERR_INVALID_HANDLE;
  136. MemoryPermission permissions_type = static_cast<MemoryPermission>(permissions);
  137. switch (permissions_type) {
  138. case MemoryPermission::Read:
  139. case MemoryPermission::Write:
  140. case MemoryPermission::ReadWrite:
  141. case MemoryPermission::Execute:
  142. case MemoryPermission::ReadExecute:
  143. case MemoryPermission::WriteExecute:
  144. case MemoryPermission::ReadWriteExecute:
  145. case MemoryPermission::DontCare:
  146. shared_memory->Map(addr, permissions_type,
  147. static_cast<MemoryPermission>(other_permissions));
  148. break;
  149. default:
  150. LOG_ERROR(Kernel_SVC, "unknown permissions=0x%08X", permissions);
  151. }
  152. return RESULT_SUCCESS;
  153. }
  154. /// Connect to an OS service given the port name, returns the handle to the port to out
  155. static ResultCode ConnectToPort(Handle* out_handle, const char* port_name) {
  156. if (port_name == nullptr)
  157. return ERR_NOT_FOUND;
  158. if (std::strlen(port_name) > 11)
  159. return ERR_PORT_NAME_TOO_LONG;
  160. LOG_TRACE(Kernel_SVC, "called port_name=%s", port_name);
  161. auto it = Service::g_kernel_named_ports.find(port_name);
  162. if (it == Service::g_kernel_named_ports.end()) {
  163. LOG_WARNING(Kernel_SVC, "tried to connect to unknown port: %s", port_name);
  164. return ERR_NOT_FOUND;
  165. }
  166. CASCADE_RESULT(*out_handle, Kernel::g_handle_table.Create(it->second));
  167. return RESULT_SUCCESS;
  168. }
  169. /// Synchronize to an OS service
  170. static ResultCode SendSyncRequest(Handle handle) {
  171. SharedPtr<Kernel::Session> session = Kernel::g_handle_table.Get<Kernel::Session>(handle);
  172. if (session == nullptr) {
  173. return ERR_INVALID_HANDLE;
  174. }
  175. LOG_TRACE(Kernel_SVC, "called handle=0x%08X(%s)", handle, session->GetName().c_str());
  176. return session->SyncRequest().Code();
  177. }
  178. /// Close a handle
  179. static ResultCode CloseHandle(Handle handle) {
  180. LOG_TRACE(Kernel_SVC, "Closing handle 0x%08X", handle);
  181. return Kernel::g_handle_table.Close(handle);
  182. }
  183. /// Wait for a handle to synchronize, timeout after the specified nanoseconds
  184. static ResultCode WaitSynchronization1(Handle handle, s64 nano_seconds) {
  185. auto object = Kernel::g_handle_table.GetWaitObject(handle);
  186. Kernel::Thread* thread = Kernel::GetCurrentThread();
  187. thread->waitsynch_waited = false;
  188. if (object == nullptr)
  189. return ERR_INVALID_HANDLE;
  190. LOG_TRACE(Kernel_SVC, "called handle=0x%08X(%s:%s), nanoseconds=%lld", handle,
  191. object->GetTypeName().c_str(), object->GetName().c_str(), nano_seconds);
  192. HLE::Reschedule(__func__);
  193. // Check for next thread to schedule
  194. if (object->ShouldWait()) {
  195. object->AddWaitingThread(thread);
  196. Kernel::WaitCurrentThread_WaitSynchronization({ object }, false, false);
  197. // Create an event to wake the thread up after the specified nanosecond delay has passed
  198. thread->WakeAfterDelay(nano_seconds);
  199. // NOTE: output of this SVC will be set later depending on how the thread resumes
  200. return HLE::RESULT_INVALID;
  201. }
  202. object->Acquire();
  203. return RESULT_SUCCESS;
  204. }
  205. /// Wait for the given handles to synchronize, timeout after the specified nanoseconds
  206. static ResultCode WaitSynchronizationN(s32* out, Handle* handles, s32 handle_count, bool wait_all, s64 nano_seconds) {
  207. bool wait_thread = !wait_all;
  208. int handle_index = 0;
  209. Kernel::Thread* thread = Kernel::GetCurrentThread();
  210. bool was_waiting = thread->waitsynch_waited;
  211. thread->waitsynch_waited = false;
  212. // Check if 'handles' is invalid
  213. if (handles == nullptr)
  214. return ResultCode(ErrorDescription::InvalidPointer, ErrorModule::Kernel, ErrorSummary::InvalidArgument, ErrorLevel::Permanent);
  215. // NOTE: on real hardware, there is no nullptr check for 'out' (tested with firmware 4.4). If
  216. // this happens, the running application will crash.
  217. ASSERT_MSG(out != nullptr, "invalid output pointer specified!");
  218. // Check if 'handle_count' is invalid
  219. if (handle_count < 0)
  220. return ResultCode(ErrorDescription::OutOfRange, ErrorModule::OS, ErrorSummary::InvalidArgument, ErrorLevel::Usage);
  221. // If 'handle_count' is non-zero, iterate through each handle and wait the current thread if
  222. // necessary
  223. if (handle_count != 0) {
  224. bool selected = false; // True once an object has been selected
  225. Kernel::SharedPtr<Kernel::WaitObject> wait_object;
  226. for (int i = 0; i < handle_count; ++i) {
  227. auto object = Kernel::g_handle_table.GetWaitObject(handles[i]);
  228. if (object == nullptr)
  229. return ERR_INVALID_HANDLE;
  230. // Check if the current thread should wait on this object...
  231. if (object->ShouldWait()) {
  232. // Check we are waiting on all objects...
  233. if (wait_all)
  234. // Wait the thread
  235. wait_thread = true;
  236. } else {
  237. // Do not wait on this object, check if this object should be selected...
  238. if (!wait_all && (!selected || (wait_object == object && was_waiting))) {
  239. // Do not wait the thread
  240. wait_thread = false;
  241. handle_index = i;
  242. wait_object = object;
  243. selected = true;
  244. }
  245. }
  246. }
  247. } else {
  248. // If no handles were passed in, put the thread to sleep only when 'wait_all' is false
  249. // NOTE: This should deadlock the current thread if no timeout was specified
  250. if (!wait_all) {
  251. wait_thread = true;
  252. }
  253. }
  254. HLE::Reschedule(__func__);
  255. // If thread should wait, then set its state to waiting and then reschedule...
  256. if (wait_thread) {
  257. // Actually wait the current thread on each object if we decided to wait...
  258. std::vector<SharedPtr<Kernel::WaitObject>> wait_objects;
  259. wait_objects.reserve(handle_count);
  260. for (int i = 0; i < handle_count; ++i) {
  261. auto object = Kernel::g_handle_table.GetWaitObject(handles[i]);
  262. object->AddWaitingThread(Kernel::GetCurrentThread());
  263. wait_objects.push_back(object);
  264. }
  265. Kernel::WaitCurrentThread_WaitSynchronization(std::move(wait_objects), true, wait_all);
  266. // Create an event to wake the thread up after the specified nanosecond delay has passed
  267. Kernel::GetCurrentThread()->WakeAfterDelay(nano_seconds);
  268. // NOTE: output of this SVC will be set later depending on how the thread resumes
  269. return HLE::RESULT_INVALID;
  270. }
  271. // Acquire objects if we did not wait...
  272. for (int i = 0; i < handle_count; ++i) {
  273. auto object = Kernel::g_handle_table.GetWaitObject(handles[i]);
  274. // Acquire the object if it is not waiting...
  275. if (!object->ShouldWait()) {
  276. object->Acquire();
  277. // If this was the first non-waiting object and 'wait_all' is false, don't acquire
  278. // any other objects
  279. if (!wait_all)
  280. break;
  281. }
  282. }
  283. // TODO(bunnei): If 'wait_all' is true, this is probably wrong. However, real hardware does
  284. // not seem to set it to any meaningful value.
  285. *out = handle_count != 0 ? (wait_all ? -1 : handle_index) : 0;
  286. return RESULT_SUCCESS;
  287. }
  288. /// Create an address arbiter (to allocate access to shared resources)
  289. static ResultCode CreateAddressArbiter(Handle* out_handle) {
  290. using Kernel::AddressArbiter;
  291. SharedPtr<AddressArbiter> arbiter = AddressArbiter::Create();
  292. CASCADE_RESULT(*out_handle, Kernel::g_handle_table.Create(std::move(arbiter)));
  293. LOG_TRACE(Kernel_SVC, "returned handle=0x%08X", *out_handle);
  294. return RESULT_SUCCESS;
  295. }
  296. /// Arbitrate address
  297. static ResultCode ArbitrateAddress(Handle handle, u32 address, u32 type, u32 value, s64 nanoseconds) {
  298. using Kernel::AddressArbiter;
  299. LOG_TRACE(Kernel_SVC, "called handle=0x%08X, address=0x%08X, type=0x%08X, value=0x%08X", handle,
  300. address, type, value);
  301. SharedPtr<AddressArbiter> arbiter = Kernel::g_handle_table.Get<AddressArbiter>(handle);
  302. if (arbiter == nullptr)
  303. return ERR_INVALID_HANDLE;
  304. auto res = arbiter->ArbitrateAddress(static_cast<Kernel::ArbitrationType>(type),
  305. address, value, nanoseconds);
  306. return res;
  307. }
  308. static void Break(u8 break_reason) {
  309. LOG_CRITICAL(Debug_Emulated, "Emulated program broke execution!");
  310. std::string reason_str;
  311. switch (break_reason) {
  312. case 0: reason_str = "PANIC"; break;
  313. case 1: reason_str = "ASSERT"; break;
  314. case 2: reason_str = "USER"; break;
  315. default: reason_str = "UNKNOWN"; break;
  316. }
  317. LOG_CRITICAL(Debug_Emulated, "Break reason: %s", reason_str.c_str());
  318. }
  319. /// Used to output a message on a debug hardware unit - does nothing on a retail unit
  320. static void OutputDebugString(const char* string) {
  321. LOG_DEBUG(Debug_Emulated, "%s", string);
  322. }
  323. /// Get resource limit
  324. static ResultCode GetResourceLimit(Handle* resource_limit, Handle process_handle) {
  325. LOG_TRACE(Kernel_SVC, "called process=0x%08X", process_handle);
  326. SharedPtr<Kernel::Process> process = Kernel::g_handle_table.Get<Kernel::Process>(process_handle);
  327. if (process == nullptr)
  328. return ERR_INVALID_HANDLE;
  329. CASCADE_RESULT(*resource_limit, Kernel::g_handle_table.Create(process->resource_limit));
  330. return RESULT_SUCCESS;
  331. }
  332. /// Get resource limit current values
  333. static ResultCode GetResourceLimitCurrentValues(s64* values, Handle resource_limit_handle, u32* names,
  334. u32 name_count) {
  335. LOG_TRACE(Kernel_SVC, "called resource_limit=%08X, names=%p, name_count=%d",
  336. resource_limit_handle, names, name_count);
  337. SharedPtr<Kernel::ResourceLimit> resource_limit = Kernel::g_handle_table.Get<Kernel::ResourceLimit>(resource_limit_handle);
  338. if (resource_limit == nullptr)
  339. return ERR_INVALID_HANDLE;
  340. for (unsigned int i = 0; i < name_count; ++i)
  341. values[i] = resource_limit->GetCurrentResourceValue(names[i]);
  342. return RESULT_SUCCESS;
  343. }
  344. /// Get resource limit max values
  345. static ResultCode GetResourceLimitLimitValues(s64* values, Handle resource_limit_handle, u32* names,
  346. u32 name_count) {
  347. LOG_TRACE(Kernel_SVC, "called resource_limit=%08X, names=%p, name_count=%d",
  348. resource_limit_handle, names, name_count);
  349. SharedPtr<Kernel::ResourceLimit> resource_limit = Kernel::g_handle_table.Get<Kernel::ResourceLimit>(resource_limit_handle);
  350. if (resource_limit == nullptr)
  351. return ERR_INVALID_HANDLE;
  352. for (unsigned int i = 0; i < name_count; ++i)
  353. values[i] = resource_limit->GetMaxResourceValue(names[i]);
  354. return RESULT_SUCCESS;
  355. }
  356. /// Creates a new thread
  357. static ResultCode CreateThread(Handle* out_handle, s32 priority, u32 entry_point, u32 arg, u32 stack_top, s32 processor_id) {
  358. using Kernel::Thread;
  359. std::string name;
  360. if (Symbols::HasSymbol(entry_point)) {
  361. TSymbol symbol = Symbols::GetSymbol(entry_point);
  362. name = symbol.name;
  363. } else {
  364. name = Common::StringFromFormat("unknown-%08x", entry_point);
  365. }
  366. // TODO(bunnei): Implement resource limits to return an error code instead of the below assert.
  367. // The error code should be: Description::NotAuthorized, Module::OS, Summary::WrongArgument,
  368. // Level::Permanent
  369. ASSERT_MSG(priority >= THREADPRIO_USERLAND_MAX, "Unexpected thread priority!");
  370. if (priority > THREADPRIO_LOWEST) {
  371. return ResultCode(ErrorDescription::OutOfRange, ErrorModule::OS,
  372. ErrorSummary::InvalidArgument, ErrorLevel::Usage);
  373. }
  374. switch (processor_id) {
  375. case THREADPROCESSORID_DEFAULT:
  376. case THREADPROCESSORID_0:
  377. case THREADPROCESSORID_1:
  378. break;
  379. default:
  380. // TODO(bunnei): Implement support for other processor IDs
  381. ASSERT_MSG(false, "Unsupported thread processor ID: %d", processor_id);
  382. break;
  383. }
  384. CASCADE_RESULT(SharedPtr<Thread> thread, Kernel::Thread::Create(
  385. name, entry_point, priority, arg, processor_id, stack_top));
  386. CASCADE_RESULT(*out_handle, Kernel::g_handle_table.Create(std::move(thread)));
  387. LOG_TRACE(Kernel_SVC, "called entrypoint=0x%08X (%s), arg=0x%08X, stacktop=0x%08X, "
  388. "threadpriority=0x%08X, processorid=0x%08X : created handle=0x%08X", entry_point,
  389. name.c_str(), arg, stack_top, priority, processor_id, *out_handle);
  390. return RESULT_SUCCESS;
  391. }
  392. /// Called when a thread exits
  393. static void ExitThread() {
  394. LOG_TRACE(Kernel_SVC, "called, pc=0x%08X", Core::g_app_core->GetPC());
  395. Kernel::GetCurrentThread()->Stop();
  396. }
  397. /// Gets the priority for the specified thread
  398. static ResultCode GetThreadPriority(s32* priority, Handle handle) {
  399. const SharedPtr<Kernel::Thread> thread = Kernel::g_handle_table.Get<Kernel::Thread>(handle);
  400. if (thread == nullptr)
  401. return ERR_INVALID_HANDLE;
  402. *priority = thread->GetPriority();
  403. return RESULT_SUCCESS;
  404. }
  405. /// Sets the priority for the specified thread
  406. static ResultCode SetThreadPriority(Handle handle, s32 priority) {
  407. SharedPtr<Kernel::Thread> thread = Kernel::g_handle_table.Get<Kernel::Thread>(handle);
  408. if (thread == nullptr)
  409. return ERR_INVALID_HANDLE;
  410. thread->SetPriority(priority);
  411. return RESULT_SUCCESS;
  412. }
  413. /// Create a mutex
  414. static ResultCode CreateMutex(Handle* out_handle, u32 initial_locked) {
  415. using Kernel::Mutex;
  416. SharedPtr<Mutex> mutex = Mutex::Create(initial_locked != 0);
  417. CASCADE_RESULT(*out_handle, Kernel::g_handle_table.Create(std::move(mutex)));
  418. LOG_TRACE(Kernel_SVC, "called initial_locked=%s : created handle=0x%08X",
  419. initial_locked ? "true" : "false", *out_handle);
  420. return RESULT_SUCCESS;
  421. }
  422. /// Release a mutex
  423. static ResultCode ReleaseMutex(Handle handle) {
  424. using Kernel::Mutex;
  425. LOG_TRACE(Kernel_SVC, "called handle=0x%08X", handle);
  426. SharedPtr<Mutex> mutex = Kernel::g_handle_table.Get<Mutex>(handle);
  427. if (mutex == nullptr)
  428. return ERR_INVALID_HANDLE;
  429. mutex->Release();
  430. return RESULT_SUCCESS;
  431. }
  432. /// Get the ID of the specified process
  433. static ResultCode GetProcessId(u32* process_id, Handle process_handle) {
  434. LOG_TRACE(Kernel_SVC, "called process=0x%08X", process_handle);
  435. const SharedPtr<Kernel::Process> process = Kernel::g_handle_table.Get<Kernel::Process>(process_handle);
  436. if (process == nullptr)
  437. return ERR_INVALID_HANDLE;
  438. *process_id = process->process_id;
  439. return RESULT_SUCCESS;
  440. }
  441. /// Get the ID of the process that owns the specified thread
  442. static ResultCode GetProcessIdOfThread(u32* process_id, Handle thread_handle) {
  443. LOG_TRACE(Kernel_SVC, "called thread=0x%08X", thread_handle);
  444. const SharedPtr<Kernel::Thread> thread = Kernel::g_handle_table.Get<Kernel::Thread>(thread_handle);
  445. if (thread == nullptr)
  446. return ERR_INVALID_HANDLE;
  447. const SharedPtr<Kernel::Process> process = thread->owner_process;
  448. ASSERT_MSG(process != nullptr, "Invalid parent process for thread=0x%08X", thread_handle);
  449. *process_id = process->process_id;
  450. return RESULT_SUCCESS;
  451. }
  452. /// Get the ID for the specified thread.
  453. static ResultCode GetThreadId(u32* thread_id, Handle handle) {
  454. LOG_TRACE(Kernel_SVC, "called thread=0x%08X", handle);
  455. const SharedPtr<Kernel::Thread> thread = Kernel::g_handle_table.Get<Kernel::Thread>(handle);
  456. if (thread == nullptr)
  457. return ERR_INVALID_HANDLE;
  458. *thread_id = thread->GetThreadId();
  459. return RESULT_SUCCESS;
  460. }
  461. /// Creates a semaphore
  462. static ResultCode CreateSemaphore(Handle* out_handle, s32 initial_count, s32 max_count) {
  463. using Kernel::Semaphore;
  464. CASCADE_RESULT(SharedPtr<Semaphore> semaphore, Semaphore::Create(initial_count, max_count));
  465. CASCADE_RESULT(*out_handle, Kernel::g_handle_table.Create(std::move(semaphore)));
  466. LOG_TRACE(Kernel_SVC, "called initial_count=%d, max_count=%d, created handle=0x%08X",
  467. initial_count, max_count, *out_handle);
  468. return RESULT_SUCCESS;
  469. }
  470. /// Releases a certain number of slots in a semaphore
  471. static ResultCode ReleaseSemaphore(s32* count, Handle handle, s32 release_count) {
  472. using Kernel::Semaphore;
  473. LOG_TRACE(Kernel_SVC, "called release_count=%d, handle=0x%08X", release_count, handle);
  474. SharedPtr<Semaphore> semaphore = Kernel::g_handle_table.Get<Semaphore>(handle);
  475. if (semaphore == nullptr)
  476. return ERR_INVALID_HANDLE;
  477. CASCADE_RESULT(*count, semaphore->Release(release_count));
  478. return RESULT_SUCCESS;
  479. }
  480. /// Query process memory
  481. static ResultCode QueryProcessMemory(MemoryInfo* memory_info, PageInfo* page_info, Handle process_handle, u32 addr) {
  482. using Kernel::Process;
  483. Kernel::SharedPtr<Process> process = Kernel::g_handle_table.Get<Process>(process_handle);
  484. if (process == nullptr)
  485. return ERR_INVALID_HANDLE;
  486. auto vma = process->vm_manager.FindVMA(addr);
  487. if (vma == Kernel::g_current_process->vm_manager.vma_map.end())
  488. return ResultCode(ErrorDescription::InvalidAddress, ErrorModule::OS, ErrorSummary::InvalidArgument, ErrorLevel::Usage);
  489. memory_info->base_address = vma->second.base;
  490. memory_info->permission = static_cast<u32>(vma->second.permissions);
  491. memory_info->size = vma->second.size;
  492. memory_info->state = static_cast<u32>(vma->second.meminfo_state);
  493. page_info->flags = 0;
  494. LOG_TRACE(Kernel_SVC, "called process=0x%08X addr=0x%08X", process_handle, addr);
  495. return RESULT_SUCCESS;
  496. }
  497. /// Query memory
  498. static ResultCode QueryMemory(MemoryInfo* memory_info, PageInfo* page_info, u32 addr) {
  499. return QueryProcessMemory(memory_info, page_info, Kernel::CurrentProcess, addr);
  500. }
  501. /// Create an event
  502. static ResultCode CreateEvent(Handle* out_handle, u32 reset_type) {
  503. using Kernel::Event;
  504. SharedPtr<Event> evt = Kernel::Event::Create(static_cast<ResetType>(reset_type));
  505. CASCADE_RESULT(*out_handle, Kernel::g_handle_table.Create(std::move(evt)));
  506. LOG_TRACE(Kernel_SVC, "called reset_type=0x%08X : created handle=0x%08X",
  507. reset_type, *out_handle);
  508. return RESULT_SUCCESS;
  509. }
  510. /// Duplicates a kernel handle
  511. static ResultCode DuplicateHandle(Handle* out, Handle handle) {
  512. CASCADE_RESULT(*out, Kernel::g_handle_table.Duplicate(handle));
  513. LOG_TRACE(Kernel_SVC, "duplicated 0x%08X to 0x%08X", handle, *out);
  514. return RESULT_SUCCESS;
  515. }
  516. /// Signals an event
  517. static ResultCode SignalEvent(Handle handle) {
  518. using Kernel::Event;
  519. LOG_TRACE(Kernel_SVC, "called event=0x%08X", handle);
  520. SharedPtr<Event> evt = Kernel::g_handle_table.Get<Kernel::Event>(handle);
  521. if (evt == nullptr)
  522. return ERR_INVALID_HANDLE;
  523. evt->Signal();
  524. return RESULT_SUCCESS;
  525. }
  526. /// Clears an event
  527. static ResultCode ClearEvent(Handle handle) {
  528. using Kernel::Event;
  529. LOG_TRACE(Kernel_SVC, "called event=0x%08X", handle);
  530. SharedPtr<Event> evt = Kernel::g_handle_table.Get<Kernel::Event>(handle);
  531. if (evt == nullptr)
  532. return ERR_INVALID_HANDLE;
  533. evt->Clear();
  534. return RESULT_SUCCESS;
  535. }
  536. /// Creates a timer
  537. static ResultCode CreateTimer(Handle* out_handle, u32 reset_type) {
  538. using Kernel::Timer;
  539. SharedPtr<Timer> timer = Timer::Create(static_cast<ResetType>(reset_type));
  540. CASCADE_RESULT(*out_handle, Kernel::g_handle_table.Create(std::move(timer)));
  541. LOG_TRACE(Kernel_SVC, "called reset_type=0x%08X : created handle=0x%08X",
  542. reset_type, *out_handle);
  543. return RESULT_SUCCESS;
  544. }
  545. /// Clears a timer
  546. static ResultCode ClearTimer(Handle handle) {
  547. using Kernel::Timer;
  548. LOG_TRACE(Kernel_SVC, "called timer=0x%08X", handle);
  549. SharedPtr<Timer> timer = Kernel::g_handle_table.Get<Timer>(handle);
  550. if (timer == nullptr)
  551. return ERR_INVALID_HANDLE;
  552. timer->Clear();
  553. return RESULT_SUCCESS;
  554. }
  555. /// Starts a timer
  556. static ResultCode SetTimer(Handle handle, s64 initial, s64 interval) {
  557. using Kernel::Timer;
  558. LOG_TRACE(Kernel_SVC, "called timer=0x%08X", handle);
  559. SharedPtr<Timer> timer = Kernel::g_handle_table.Get<Timer>(handle);
  560. if (timer == nullptr)
  561. return ERR_INVALID_HANDLE;
  562. timer->Set(initial, interval);
  563. return RESULT_SUCCESS;
  564. }
  565. /// Cancels a timer
  566. static ResultCode CancelTimer(Handle handle) {
  567. using Kernel::Timer;
  568. LOG_TRACE(Kernel_SVC, "called timer=0x%08X", handle);
  569. SharedPtr<Timer> timer = Kernel::g_handle_table.Get<Timer>(handle);
  570. if (timer == nullptr)
  571. return ERR_INVALID_HANDLE;
  572. timer->Cancel();
  573. return RESULT_SUCCESS;
  574. }
  575. /// Sleep the current thread
  576. static void SleepThread(s64 nanoseconds) {
  577. LOG_TRACE(Kernel_SVC, "called nanoseconds=%lld", nanoseconds);
  578. // Sleep current thread and check for next thread to schedule
  579. Kernel::WaitCurrentThread_Sleep();
  580. // Create an event to wake the thread up after the specified nanosecond delay has passed
  581. Kernel::GetCurrentThread()->WakeAfterDelay(nanoseconds);
  582. }
  583. /// This returns the total CPU ticks elapsed since the CPU was powered-on
  584. static s64 GetSystemTick() {
  585. s64 result = CoreTiming::GetTicks();
  586. // Advance time to defeat dumb games (like Cubic Ninja) that busy-wait for the frame to end.
  587. Core::g_app_core->AddTicks(150); // Measured time between two calls on a 9.2 o3DS with Ninjhax 1.1b
  588. return result;
  589. }
  590. /// Creates a memory block at the specified address with the specified permissions and size
  591. static ResultCode CreateMemoryBlock(Handle* out_handle, u32 addr, u32 size, u32 my_permission,
  592. u32 other_permission) {
  593. using Kernel::SharedMemory;
  594. // TODO(Subv): Implement this function
  595. using Kernel::MemoryPermission;
  596. SharedPtr<SharedMemory> shared_memory = SharedMemory::Create(size,
  597. (MemoryPermission)my_permission, (MemoryPermission)other_permission);
  598. // Map the SharedMemory to the specified address
  599. shared_memory->base_address = addr;
  600. CASCADE_RESULT(*out_handle, Kernel::g_handle_table.Create(std::move(shared_memory)));
  601. LOG_WARNING(Kernel_SVC, "(STUBBED) called addr=0x%08X", addr);
  602. return RESULT_SUCCESS;
  603. }
  604. static ResultCode GetProcessInfo(s64* out, Handle process_handle, u32 type) {
  605. LOG_TRACE(Kernel_SVC, "called process=0x%08X type=%u", process_handle, type);
  606. using Kernel::Process;
  607. Kernel::SharedPtr<Process> process = Kernel::g_handle_table.Get<Process>(process_handle);
  608. if (process == nullptr)
  609. return ERR_INVALID_HANDLE;
  610. switch (type) {
  611. case 0:
  612. case 2:
  613. // TODO(yuriks): Type 0 returns a slightly higher number than type 2, but I'm not sure
  614. // what's the difference between them.
  615. *out = process->heap_used + process->linear_heap_used + process->misc_memory_used;
  616. break;
  617. case 1:
  618. case 3:
  619. case 4:
  620. case 5:
  621. case 6:
  622. case 7:
  623. case 8:
  624. // These are valid, but not implemented yet
  625. LOG_ERROR(Kernel_SVC, "unimplemented GetProcessInfo type=%u", type);
  626. break;
  627. case 20:
  628. *out = Memory::FCRAM_PADDR - process->GetLinearHeapBase();
  629. break;
  630. default:
  631. LOG_ERROR(Kernel_SVC, "unknown GetProcessInfo type=%u", type);
  632. if (type >= 21 && type <= 23) {
  633. return ResultCode( // 0xE0E01BF4
  634. ErrorDescription::NotImplemented, ErrorModule::OS,
  635. ErrorSummary::InvalidArgument, ErrorLevel::Usage);
  636. } else {
  637. return ResultCode( // 0xD8E007ED
  638. ErrorDescription::InvalidEnumValue, ErrorModule::Kernel,
  639. ErrorSummary::InvalidArgument, ErrorLevel::Permanent);
  640. }
  641. break;
  642. }
  643. return RESULT_SUCCESS;
  644. }
  645. namespace {
  646. struct FunctionDef {
  647. using Func = void();
  648. u32 id;
  649. Func* func;
  650. const char* name;
  651. };
  652. }
  653. static const FunctionDef SVC_Table[] = {
  654. {0x00, nullptr, "Unknown"},
  655. {0x01, HLE::Wrap<ControlMemory>, "ControlMemory"},
  656. {0x02, HLE::Wrap<QueryMemory>, "QueryMemory"},
  657. {0x03, nullptr, "ExitProcess"},
  658. {0x04, nullptr, "GetProcessAffinityMask"},
  659. {0x05, nullptr, "SetProcessAffinityMask"},
  660. {0x06, nullptr, "GetProcessIdealProcessor"},
  661. {0x07, nullptr, "SetProcessIdealProcessor"},
  662. {0x08, HLE::Wrap<CreateThread>, "CreateThread"},
  663. {0x09, ExitThread, "ExitThread"},
  664. {0x0A, HLE::Wrap<SleepThread>, "SleepThread"},
  665. {0x0B, HLE::Wrap<GetThreadPriority>, "GetThreadPriority"},
  666. {0x0C, HLE::Wrap<SetThreadPriority>, "SetThreadPriority"},
  667. {0x0D, nullptr, "GetThreadAffinityMask"},
  668. {0x0E, nullptr, "SetThreadAffinityMask"},
  669. {0x0F, nullptr, "GetThreadIdealProcessor"},
  670. {0x10, nullptr, "SetThreadIdealProcessor"},
  671. {0x11, nullptr, "GetCurrentProcessorNumber"},
  672. {0x12, nullptr, "Run"},
  673. {0x13, HLE::Wrap<CreateMutex>, "CreateMutex"},
  674. {0x14, HLE::Wrap<ReleaseMutex>, "ReleaseMutex"},
  675. {0x15, HLE::Wrap<CreateSemaphore>, "CreateSemaphore"},
  676. {0x16, HLE::Wrap<ReleaseSemaphore>, "ReleaseSemaphore"},
  677. {0x17, HLE::Wrap<CreateEvent>, "CreateEvent"},
  678. {0x18, HLE::Wrap<SignalEvent>, "SignalEvent"},
  679. {0x19, HLE::Wrap<ClearEvent>, "ClearEvent"},
  680. {0x1A, HLE::Wrap<CreateTimer>, "CreateTimer"},
  681. {0x1B, HLE::Wrap<SetTimer>, "SetTimer"},
  682. {0x1C, HLE::Wrap<CancelTimer>, "CancelTimer"},
  683. {0x1D, HLE::Wrap<ClearTimer>, "ClearTimer"},
  684. {0x1E, HLE::Wrap<CreateMemoryBlock>, "CreateMemoryBlock"},
  685. {0x1F, HLE::Wrap<MapMemoryBlock>, "MapMemoryBlock"},
  686. {0x20, nullptr, "UnmapMemoryBlock"},
  687. {0x21, HLE::Wrap<CreateAddressArbiter>, "CreateAddressArbiter"},
  688. {0x22, HLE::Wrap<ArbitrateAddress>, "ArbitrateAddress"},
  689. {0x23, HLE::Wrap<CloseHandle>, "CloseHandle"},
  690. {0x24, HLE::Wrap<WaitSynchronization1>, "WaitSynchronization1"},
  691. {0x25, HLE::Wrap<WaitSynchronizationN>, "WaitSynchronizationN"},
  692. {0x26, nullptr, "SignalAndWait"},
  693. {0x27, HLE::Wrap<DuplicateHandle>, "DuplicateHandle"},
  694. {0x28, HLE::Wrap<GetSystemTick>, "GetSystemTick"},
  695. {0x29, nullptr, "GetHandleInfo"},
  696. {0x2A, nullptr, "GetSystemInfo"},
  697. {0x2B, HLE::Wrap<GetProcessInfo>, "GetProcessInfo"},
  698. {0x2C, nullptr, "GetThreadInfo"},
  699. {0x2D, HLE::Wrap<ConnectToPort>, "ConnectToPort"},
  700. {0x2E, nullptr, "SendSyncRequest1"},
  701. {0x2F, nullptr, "SendSyncRequest2"},
  702. {0x30, nullptr, "SendSyncRequest3"},
  703. {0x31, nullptr, "SendSyncRequest4"},
  704. {0x32, HLE::Wrap<SendSyncRequest>, "SendSyncRequest"},
  705. {0x33, nullptr, "OpenProcess"},
  706. {0x34, nullptr, "OpenThread"},
  707. {0x35, HLE::Wrap<GetProcessId>, "GetProcessId"},
  708. {0x36, HLE::Wrap<GetProcessIdOfThread>, "GetProcessIdOfThread"},
  709. {0x37, HLE::Wrap<GetThreadId>, "GetThreadId"},
  710. {0x38, HLE::Wrap<GetResourceLimit>, "GetResourceLimit"},
  711. {0x39, HLE::Wrap<GetResourceLimitLimitValues>, "GetResourceLimitLimitValues"},
  712. {0x3A, HLE::Wrap<GetResourceLimitCurrentValues>, "GetResourceLimitCurrentValues"},
  713. {0x3B, nullptr, "GetThreadContext"},
  714. {0x3C, HLE::Wrap<Break>, "Break"},
  715. {0x3D, HLE::Wrap<OutputDebugString>, "OutputDebugString"},
  716. {0x3E, nullptr, "ControlPerformanceCounter"},
  717. {0x3F, nullptr, "Unknown"},
  718. {0x40, nullptr, "Unknown"},
  719. {0x41, nullptr, "Unknown"},
  720. {0x42, nullptr, "Unknown"},
  721. {0x43, nullptr, "Unknown"},
  722. {0x44, nullptr, "Unknown"},
  723. {0x45, nullptr, "Unknown"},
  724. {0x46, nullptr, "Unknown"},
  725. {0x47, nullptr, "CreatePort"},
  726. {0x48, nullptr, "CreateSessionToPort"},
  727. {0x49, nullptr, "CreateSession"},
  728. {0x4A, nullptr, "AcceptSession"},
  729. {0x4B, nullptr, "ReplyAndReceive1"},
  730. {0x4C, nullptr, "ReplyAndReceive2"},
  731. {0x4D, nullptr, "ReplyAndReceive3"},
  732. {0x4E, nullptr, "ReplyAndReceive4"},
  733. {0x4F, nullptr, "ReplyAndReceive"},
  734. {0x50, nullptr, "BindInterrupt"},
  735. {0x51, nullptr, "UnbindInterrupt"},
  736. {0x52, nullptr, "InvalidateProcessDataCache"},
  737. {0x53, nullptr, "StoreProcessDataCache"},
  738. {0x54, nullptr, "FlushProcessDataCache"},
  739. {0x55, nullptr, "StartInterProcessDma"},
  740. {0x56, nullptr, "StopDma"},
  741. {0x57, nullptr, "GetDmaState"},
  742. {0x58, nullptr, "RestartDma"},
  743. {0x59, nullptr, "Unknown"},
  744. {0x5A, nullptr, "Unknown"},
  745. {0x5B, nullptr, "Unknown"},
  746. {0x5C, nullptr, "Unknown"},
  747. {0x5D, nullptr, "Unknown"},
  748. {0x5E, nullptr, "Unknown"},
  749. {0x5F, nullptr, "Unknown"},
  750. {0x60, nullptr, "DebugActiveProcess"},
  751. {0x61, nullptr, "BreakDebugProcess"},
  752. {0x62, nullptr, "TerminateDebugProcess"},
  753. {0x63, nullptr, "GetProcessDebugEvent"},
  754. {0x64, nullptr, "ContinueDebugEvent"},
  755. {0x65, nullptr, "GetProcessList"},
  756. {0x66, nullptr, "GetThreadList"},
  757. {0x67, nullptr, "GetDebugThreadContext"},
  758. {0x68, nullptr, "SetDebugThreadContext"},
  759. {0x69, nullptr, "QueryDebugProcessMemory"},
  760. {0x6A, nullptr, "ReadProcessMemory"},
  761. {0x6B, nullptr, "WriteProcessMemory"},
  762. {0x6C, nullptr, "SetHardwareBreakPoint"},
  763. {0x6D, nullptr, "GetDebugThreadParam"},
  764. {0x6E, nullptr, "Unknown"},
  765. {0x6F, nullptr, "Unknown"},
  766. {0x70, nullptr, "ControlProcessMemory"},
  767. {0x71, nullptr, "MapProcessMemory"},
  768. {0x72, nullptr, "UnmapProcessMemory"},
  769. {0x73, nullptr, "CreateCodeSet"},
  770. {0x74, nullptr, "RandomStub"},
  771. {0x75, nullptr, "CreateProcess"},
  772. {0x76, nullptr, "TerminateProcess"},
  773. {0x77, nullptr, "SetProcessResourceLimits"},
  774. {0x78, nullptr, "CreateResourceLimit"},
  775. {0x79, nullptr, "SetResourceLimitValues"},
  776. {0x7A, nullptr, "AddCodeSegment"},
  777. {0x7B, nullptr, "Backdoor"},
  778. {0x7C, nullptr, "KernelSetState"},
  779. {0x7D, HLE::Wrap<QueryProcessMemory>, "QueryProcessMemory"},
  780. };
  781. Common::Profiling::TimingCategory profiler_svc("SVC Calls");
  782. static const FunctionDef* GetSVCInfo(u32 func_num) {
  783. if (func_num >= ARRAY_SIZE(SVC_Table)) {
  784. LOG_ERROR(Kernel_SVC, "unknown svc=0x%02X", func_num);
  785. return nullptr;
  786. }
  787. return &SVC_Table[func_num];
  788. }
  789. MICROPROFILE_DEFINE(Kernel_SVC, "Kernel", "SVC", MP_RGB(70, 200, 70));
  790. void CallSVC(u32 immediate) {
  791. Common::Profiling::ScopeTimer timer_svc(profiler_svc);
  792. MICROPROFILE_SCOPE(Kernel_SVC);
  793. const FunctionDef* info = GetSVCInfo(immediate);
  794. if (info) {
  795. if (info->func) {
  796. info->func();
  797. } else {
  798. LOG_ERROR(Kernel_SVC, "unimplemented SVC function %s(..)", info->name);
  799. }
  800. }
  801. }
  802. } // namespace