svc.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  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/profiler.h"
  7. #include "common/string_util.h"
  8. #include "common/symbols.h"
  9. #include "core/core_timing.h"
  10. #include "core/mem_map.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/mutex.h"
  15. #include "core/hle/kernel/semaphore.h"
  16. #include "core/hle/kernel/shared_memory.h"
  17. #include "core/hle/kernel/thread.h"
  18. #include "core/hle/kernel/timer.h"
  19. #include "core/hle/function_wrappers.h"
  20. #include "core/hle/result.h"
  21. #include "core/hle/service/service.h"
  22. ////////////////////////////////////////////////////////////////////////////////////////////////////
  23. // Namespace SVC
  24. using Kernel::SharedPtr;
  25. using Kernel::ERR_INVALID_HANDLE;
  26. namespace SVC {
  27. const ResultCode ERR_NOT_FOUND(ErrorDescription::NotFound, ErrorModule::Kernel,
  28. ErrorSummary::NotFound, ErrorLevel::Permanent); // 0xD88007FA
  29. const ResultCode ERR_PORT_NAME_TOO_LONG(ErrorDescription(30), ErrorModule::OS,
  30. ErrorSummary::InvalidArgument, ErrorLevel::Usage); // 0xE0E0181E
  31. /// An invalid result code that is meant to be overwritten when a thread resumes from waiting
  32. const ResultCode RESULT_INVALID(0xDEADC0DE);
  33. enum ControlMemoryOperation {
  34. MEMORY_OPERATION_HEAP = 0x00000003,
  35. MEMORY_OPERATION_GSP_HEAP = 0x00010003,
  36. };
  37. /// Map application or GSP heap memory
  38. static ResultCode ControlMemory(u32* out_addr, u32 operation, u32 addr0, u32 addr1, u32 size, u32 permissions) {
  39. LOG_TRACE(Kernel_SVC,"called operation=0x%08X, addr0=0x%08X, addr1=0x%08X, size=%08X, permissions=0x%08X",
  40. operation, addr0, addr1, size, permissions);
  41. switch (operation) {
  42. // Map normal heap memory
  43. case MEMORY_OPERATION_HEAP:
  44. *out_addr = Memory::MapBlock_Heap(size, operation, permissions);
  45. break;
  46. // Map GSP heap memory
  47. case MEMORY_OPERATION_GSP_HEAP:
  48. *out_addr = Memory::MapBlock_HeapLinear(size, operation, permissions);
  49. break;
  50. // Unknown ControlMemory operation
  51. default:
  52. LOG_ERROR(Kernel_SVC, "unknown operation=0x%08X", operation);
  53. }
  54. return RESULT_SUCCESS;
  55. }
  56. /// Maps a memory block to specified address
  57. static ResultCode MapMemoryBlock(Handle handle, u32 addr, u32 permissions, u32 other_permissions) {
  58. using Kernel::SharedMemory;
  59. using Kernel::MemoryPermission;
  60. LOG_TRACE(Kernel_SVC, "called memblock=0x%08X, addr=0x%08X, mypermissions=0x%08X, otherpermission=%d",
  61. handle, addr, permissions, other_permissions);
  62. SharedPtr<SharedMemory> shared_memory = Kernel::g_handle_table.Get<SharedMemory>(handle);
  63. if (shared_memory == nullptr)
  64. return ERR_INVALID_HANDLE;
  65. MemoryPermission permissions_type = static_cast<MemoryPermission>(permissions);
  66. switch (permissions_type) {
  67. case MemoryPermission::Read:
  68. case MemoryPermission::Write:
  69. case MemoryPermission::ReadWrite:
  70. case MemoryPermission::Execute:
  71. case MemoryPermission::ReadExecute:
  72. case MemoryPermission::WriteExecute:
  73. case MemoryPermission::ReadWriteExecute:
  74. case MemoryPermission::DontCare:
  75. shared_memory->Map(addr, permissions_type,
  76. static_cast<MemoryPermission>(other_permissions));
  77. break;
  78. default:
  79. LOG_ERROR(Kernel_SVC, "unknown permissions=0x%08X", permissions);
  80. }
  81. return RESULT_SUCCESS;
  82. }
  83. /// Connect to an OS service given the port name, returns the handle to the port to out
  84. static ResultCode ConnectToPort(Handle* out_handle, const char* port_name) {
  85. if (port_name == nullptr)
  86. return ERR_NOT_FOUND;
  87. if (std::strlen(port_name) > 11)
  88. return ERR_PORT_NAME_TOO_LONG;
  89. LOG_TRACE(Kernel_SVC, "called port_name=%s", port_name);
  90. auto it = Service::g_kernel_named_ports.find(port_name);
  91. if (it == Service::g_kernel_named_ports.end()) {
  92. LOG_WARNING(Kernel_SVC, "tried to connect to unknown port: %s", port_name);
  93. return ERR_NOT_FOUND;
  94. }
  95. CASCADE_RESULT(*out_handle, Kernel::g_handle_table.Create(it->second));
  96. return RESULT_SUCCESS;
  97. }
  98. /// Synchronize to an OS service
  99. static ResultCode SendSyncRequest(Handle handle) {
  100. SharedPtr<Kernel::Session> session = Kernel::g_handle_table.Get<Kernel::Session>(handle);
  101. if (session == nullptr) {
  102. return ERR_INVALID_HANDLE;
  103. }
  104. LOG_TRACE(Kernel_SVC, "called handle=0x%08X(%s)", handle, session->GetName().c_str());
  105. return session->SyncRequest().Code();
  106. }
  107. /// Close a handle
  108. static ResultCode CloseHandle(Handle handle) {
  109. LOG_TRACE(Kernel_SVC, "Closing handle 0x%08X", handle);
  110. return Kernel::g_handle_table.Close(handle);
  111. }
  112. /// Wait for a handle to synchronize, timeout after the specified nanoseconds
  113. static ResultCode WaitSynchronization1(Handle handle, s64 nano_seconds) {
  114. auto object = Kernel::g_handle_table.GetWaitObject(handle);
  115. if (object == nullptr)
  116. return ERR_INVALID_HANDLE;
  117. LOG_TRACE(Kernel_SVC, "called handle=0x%08X(%s:%s), nanoseconds=%lld", handle,
  118. object->GetTypeName().c_str(), object->GetName().c_str(), nano_seconds);
  119. HLE::Reschedule(__func__);
  120. // Check for next thread to schedule
  121. if (object->ShouldWait()) {
  122. object->AddWaitingThread(Kernel::GetCurrentThread());
  123. Kernel::WaitCurrentThread_WaitSynchronization({ object }, false, false);
  124. // Create an event to wake the thread up after the specified nanosecond delay has passed
  125. Kernel::GetCurrentThread()->WakeAfterDelay(nano_seconds);
  126. // NOTE: output of this SVC will be set later depending on how the thread resumes
  127. return RESULT_INVALID;
  128. }
  129. object->Acquire();
  130. return RESULT_SUCCESS;
  131. }
  132. /// Wait for the given handles to synchronize, timeout after the specified nanoseconds
  133. static ResultCode WaitSynchronizationN(s32* out, Handle* handles, s32 handle_count, bool wait_all, s64 nano_seconds) {
  134. bool wait_thread = !wait_all;
  135. int handle_index = 0;
  136. // Check if 'handles' is invalid
  137. if (handles == nullptr)
  138. return ResultCode(ErrorDescription::InvalidPointer, ErrorModule::Kernel, ErrorSummary::InvalidArgument, ErrorLevel::Permanent);
  139. // NOTE: on real hardware, there is no nullptr check for 'out' (tested with firmware 4.4). If
  140. // this happens, the running application will crash.
  141. ASSERT_MSG(out != nullptr, "invalid output pointer specified!");
  142. // Check if 'handle_count' is invalid
  143. if (handle_count < 0)
  144. return ResultCode(ErrorDescription::OutOfRange, ErrorModule::OS, ErrorSummary::InvalidArgument, ErrorLevel::Usage);
  145. // If 'handle_count' is non-zero, iterate through each handle and wait the current thread if
  146. // necessary
  147. if (handle_count != 0) {
  148. bool selected = false; // True once an object has been selected
  149. for (int i = 0; i < handle_count; ++i) {
  150. auto object = Kernel::g_handle_table.GetWaitObject(handles[i]);
  151. if (object == nullptr)
  152. return ERR_INVALID_HANDLE;
  153. // Check if the current thread should wait on this object...
  154. if (object->ShouldWait()) {
  155. // Check we are waiting on all objects...
  156. if (wait_all)
  157. // Wait the thread
  158. wait_thread = true;
  159. } else {
  160. // Do not wait on this object, check if this object should be selected...
  161. if (!wait_all && !selected) {
  162. // Do not wait the thread
  163. wait_thread = false;
  164. handle_index = i;
  165. selected = true;
  166. }
  167. }
  168. }
  169. } else {
  170. // If no handles were passed in, put the thread to sleep only when 'wait_all' is false
  171. // NOTE: This should deadlock the current thread if no timeout was specified
  172. if (!wait_all) {
  173. wait_thread = true;
  174. }
  175. }
  176. HLE::Reschedule(__func__);
  177. // If thread should wait, then set its state to waiting and then reschedule...
  178. if (wait_thread) {
  179. // Actually wait the current thread on each object if we decided to wait...
  180. std::vector<SharedPtr<Kernel::WaitObject>> wait_objects;
  181. wait_objects.reserve(handle_count);
  182. for (int i = 0; i < handle_count; ++i) {
  183. auto object = Kernel::g_handle_table.GetWaitObject(handles[i]);
  184. object->AddWaitingThread(Kernel::GetCurrentThread());
  185. wait_objects.push_back(object);
  186. }
  187. Kernel::WaitCurrentThread_WaitSynchronization(std::move(wait_objects), true, wait_all);
  188. // Create an event to wake the thread up after the specified nanosecond delay has passed
  189. Kernel::GetCurrentThread()->WakeAfterDelay(nano_seconds);
  190. // NOTE: output of this SVC will be set later depending on how the thread resumes
  191. return RESULT_INVALID;
  192. }
  193. // Acquire objects if we did not wait...
  194. for (int i = 0; i < handle_count; ++i) {
  195. auto object = Kernel::g_handle_table.GetWaitObject(handles[i]);
  196. // Acquire the object if it is not waiting...
  197. if (!object->ShouldWait()) {
  198. object->Acquire();
  199. // If this was the first non-waiting object and 'wait_all' is false, don't acquire
  200. // any other objects
  201. if (!wait_all)
  202. break;
  203. }
  204. }
  205. // TODO(bunnei): If 'wait_all' is true, this is probably wrong. However, real hardware does
  206. // not seem to set it to any meaningful value.
  207. *out = wait_all ? 0 : handle_index;
  208. return RESULT_SUCCESS;
  209. }
  210. /// Create an address arbiter (to allocate access to shared resources)
  211. static ResultCode CreateAddressArbiter(Handle* out_handle) {
  212. using Kernel::AddressArbiter;
  213. SharedPtr<AddressArbiter> arbiter = AddressArbiter::Create();
  214. CASCADE_RESULT(*out_handle, Kernel::g_handle_table.Create(std::move(arbiter)));
  215. LOG_TRACE(Kernel_SVC, "returned handle=0x%08X", *out_handle);
  216. return RESULT_SUCCESS;
  217. }
  218. /// Arbitrate address
  219. static ResultCode ArbitrateAddress(Handle handle, u32 address, u32 type, u32 value, s64 nanoseconds) {
  220. using Kernel::AddressArbiter;
  221. LOG_TRACE(Kernel_SVC, "called handle=0x%08X, address=0x%08X, type=0x%08X, value=0x%08X", handle,
  222. address, type, value);
  223. SharedPtr<AddressArbiter> arbiter = Kernel::g_handle_table.Get<AddressArbiter>(handle);
  224. if (arbiter == nullptr)
  225. return ERR_INVALID_HANDLE;
  226. auto res = arbiter->ArbitrateAddress(static_cast<Kernel::ArbitrationType>(type),
  227. address, value, nanoseconds);
  228. if (res == RESULT_SUCCESS)
  229. HLE::Reschedule(__func__);
  230. return res;
  231. }
  232. /// Used to output a message on a debug hardware unit - does nothing on a retail unit
  233. static void OutputDebugString(const char* string) {
  234. LOG_DEBUG(Debug_Emulated, "%s", string);
  235. }
  236. /// Get resource limit
  237. static ResultCode GetResourceLimit(Handle* resource_limit, Handle process) {
  238. // With regards to proceess values:
  239. // 0xFFFF8001 is a handle alias for the current KProcess, and 0xFFFF8000 is a handle alias for
  240. // the current KThread.
  241. *resource_limit = 0xDEADBEEF;
  242. LOG_ERROR(Kernel_SVC, "(UNIMPLEMENTED) called process=0x%08X", process);
  243. return RESULT_SUCCESS;
  244. }
  245. /// Get resource limit current values
  246. static ResultCode GetResourceLimitCurrentValues(s64* values, Handle resource_limit, void* names,
  247. s32 name_count) {
  248. LOG_ERROR(Kernel_SVC, "(UNIMPLEMENTED) called resource_limit=%08X, names=%p, name_count=%d",
  249. resource_limit, names, name_count);
  250. Memory::Write32(Core::g_app_core->GetReg(0), 0); // Normmatt: Set used memory to 0 for now
  251. return RESULT_SUCCESS;
  252. }
  253. /// Creates a new thread
  254. static ResultCode CreateThread(Handle* out_handle, s32 priority, u32 entry_point, u32 arg, u32 stack_top, s32 processor_id) {
  255. using Kernel::Thread;
  256. std::string name;
  257. if (Symbols::HasSymbol(entry_point)) {
  258. TSymbol symbol = Symbols::GetSymbol(entry_point);
  259. name = symbol.name;
  260. } else {
  261. name = Common::StringFromFormat("unknown-%08x", entry_point);
  262. }
  263. // TODO(bunnei): Implement resource limits to return an error code instead of the below assert.
  264. // The error code should be: Description::NotAuthorized, Module::OS, Summary::WrongArgument,
  265. // Level::Permanent
  266. ASSERT_MSG(priority >= THREADPRIO_USERLAND_MAX, "Unexpected thread priority!");
  267. if (priority > THREADPRIO_LOWEST) {
  268. return ResultCode(ErrorDescription::OutOfRange, ErrorModule::OS,
  269. ErrorSummary::InvalidArgument, ErrorLevel::Usage);
  270. }
  271. switch (processor_id) {
  272. case THREADPROCESSORID_DEFAULT:
  273. case THREADPROCESSORID_0:
  274. case THREADPROCESSORID_1:
  275. break;
  276. default:
  277. // TODO(bunnei): Implement support for other processor IDs
  278. ASSERT_MSG(false, "Unsupported thread processor ID: %d", processor_id);
  279. break;
  280. }
  281. CASCADE_RESULT(SharedPtr<Thread> thread, Kernel::Thread::Create(
  282. name, entry_point, priority, arg, processor_id, stack_top));
  283. CASCADE_RESULT(*out_handle, Kernel::g_handle_table.Create(std::move(thread)));
  284. LOG_TRACE(Kernel_SVC, "called entrypoint=0x%08X (%s), arg=0x%08X, stacktop=0x%08X, "
  285. "threadpriority=0x%08X, processorid=0x%08X : created handle=0x%08X", entry_point,
  286. name.c_str(), arg, stack_top, priority, processor_id, *out_handle);
  287. HLE::Reschedule(__func__);
  288. return RESULT_SUCCESS;
  289. }
  290. /// Called when a thread exits
  291. static void ExitThread() {
  292. LOG_TRACE(Kernel_SVC, "called, pc=0x%08X", Core::g_app_core->GetPC());
  293. Kernel::GetCurrentThread()->Stop();
  294. HLE::Reschedule(__func__);
  295. }
  296. /// Gets the priority for the specified thread
  297. static ResultCode GetThreadPriority(s32* priority, Handle handle) {
  298. const SharedPtr<Kernel::Thread> thread = Kernel::g_handle_table.Get<Kernel::Thread>(handle);
  299. if (thread == nullptr)
  300. return ERR_INVALID_HANDLE;
  301. *priority = thread->GetPriority();
  302. return RESULT_SUCCESS;
  303. }
  304. /// Sets the priority for the specified thread
  305. static ResultCode SetThreadPriority(Handle handle, s32 priority) {
  306. SharedPtr<Kernel::Thread> thread = Kernel::g_handle_table.Get<Kernel::Thread>(handle);
  307. if (thread == nullptr)
  308. return ERR_INVALID_HANDLE;
  309. thread->SetPriority(priority);
  310. return RESULT_SUCCESS;
  311. }
  312. /// Create a mutex
  313. static ResultCode CreateMutex(Handle* out_handle, u32 initial_locked) {
  314. using Kernel::Mutex;
  315. SharedPtr<Mutex> mutex = Mutex::Create(initial_locked != 0);
  316. CASCADE_RESULT(*out_handle, Kernel::g_handle_table.Create(std::move(mutex)));
  317. HLE::Reschedule(__func__);
  318. LOG_TRACE(Kernel_SVC, "called initial_locked=%s : created handle=0x%08X",
  319. initial_locked ? "true" : "false", *out_handle);
  320. return RESULT_SUCCESS;
  321. }
  322. /// Release a mutex
  323. static ResultCode ReleaseMutex(Handle handle) {
  324. using Kernel::Mutex;
  325. LOG_TRACE(Kernel_SVC, "called handle=0x%08X", handle);
  326. SharedPtr<Mutex> mutex = Kernel::g_handle_table.Get<Mutex>(handle);
  327. if (mutex == nullptr)
  328. return ERR_INVALID_HANDLE;
  329. mutex->Release();
  330. HLE::Reschedule(__func__);
  331. return RESULT_SUCCESS;
  332. }
  333. /// Get the ID for the specified thread.
  334. static ResultCode GetThreadId(u32* thread_id, Handle handle) {
  335. LOG_TRACE(Kernel_SVC, "called thread=0x%08X", handle);
  336. const SharedPtr<Kernel::Thread> thread = Kernel::g_handle_table.Get<Kernel::Thread>(handle);
  337. if (thread == nullptr)
  338. return ERR_INVALID_HANDLE;
  339. *thread_id = thread->GetThreadId();
  340. return RESULT_SUCCESS;
  341. }
  342. /// Creates a semaphore
  343. static ResultCode CreateSemaphore(Handle* out_handle, s32 initial_count, s32 max_count) {
  344. using Kernel::Semaphore;
  345. CASCADE_RESULT(SharedPtr<Semaphore> semaphore, Semaphore::Create(initial_count, max_count));
  346. CASCADE_RESULT(*out_handle, Kernel::g_handle_table.Create(std::move(semaphore)));
  347. LOG_TRACE(Kernel_SVC, "called initial_count=%d, max_count=%d, created handle=0x%08X",
  348. initial_count, max_count, *out_handle);
  349. return RESULT_SUCCESS;
  350. }
  351. /// Releases a certain number of slots in a semaphore
  352. static ResultCode ReleaseSemaphore(s32* count, Handle handle, s32 release_count) {
  353. using Kernel::Semaphore;
  354. LOG_TRACE(Kernel_SVC, "called release_count=%d, handle=0x%08X", release_count, handle);
  355. SharedPtr<Semaphore> semaphore = Kernel::g_handle_table.Get<Semaphore>(handle);
  356. if (semaphore == nullptr)
  357. return ERR_INVALID_HANDLE;
  358. CASCADE_RESULT(*count, semaphore->Release(release_count));
  359. HLE::Reschedule(__func__);
  360. return RESULT_SUCCESS;
  361. }
  362. /// Query memory
  363. static ResultCode QueryMemory(void* info, void* out, u32 addr) {
  364. LOG_ERROR(Kernel_SVC, "(UNIMPLEMENTED) called addr=0x%08X", addr);
  365. return RESULT_SUCCESS;
  366. }
  367. /// Create an event
  368. static ResultCode CreateEvent(Handle* out_handle, u32 reset_type) {
  369. using Kernel::Event;
  370. SharedPtr<Event> evt = Kernel::Event::Create(static_cast<ResetType>(reset_type));
  371. CASCADE_RESULT(*out_handle, Kernel::g_handle_table.Create(std::move(evt)));
  372. LOG_TRACE(Kernel_SVC, "called reset_type=0x%08X : created handle=0x%08X",
  373. reset_type, *out_handle);
  374. return RESULT_SUCCESS;
  375. }
  376. /// Duplicates a kernel handle
  377. static ResultCode DuplicateHandle(Handle* out, Handle handle) {
  378. CASCADE_RESULT(*out, Kernel::g_handle_table.Duplicate(handle));
  379. LOG_TRACE(Kernel_SVC, "duplicated 0x%08X to 0x%08X", handle, *out);
  380. return RESULT_SUCCESS;
  381. }
  382. /// Signals an event
  383. static ResultCode SignalEvent(Handle handle) {
  384. using Kernel::Event;
  385. LOG_TRACE(Kernel_SVC, "called event=0x%08X", handle);
  386. SharedPtr<Event> evt = Kernel::g_handle_table.Get<Kernel::Event>(handle);
  387. if (evt == nullptr)
  388. return ERR_INVALID_HANDLE;
  389. evt->Signal();
  390. HLE::Reschedule(__func__);
  391. return RESULT_SUCCESS;
  392. }
  393. /// Clears an event
  394. static ResultCode ClearEvent(Handle handle) {
  395. using Kernel::Event;
  396. LOG_TRACE(Kernel_SVC, "called event=0x%08X", handle);
  397. SharedPtr<Event> evt = Kernel::g_handle_table.Get<Kernel::Event>(handle);
  398. if (evt == nullptr)
  399. return ERR_INVALID_HANDLE;
  400. evt->Clear();
  401. return RESULT_SUCCESS;
  402. }
  403. /// Creates a timer
  404. static ResultCode CreateTimer(Handle* out_handle, u32 reset_type) {
  405. using Kernel::Timer;
  406. SharedPtr<Timer> timer = Timer::Create(static_cast<ResetType>(reset_type));
  407. CASCADE_RESULT(*out_handle, Kernel::g_handle_table.Create(std::move(timer)));
  408. LOG_TRACE(Kernel_SVC, "called reset_type=0x%08X : created handle=0x%08X",
  409. reset_type, *out_handle);
  410. return RESULT_SUCCESS;
  411. }
  412. /// Clears a timer
  413. static ResultCode ClearTimer(Handle handle) {
  414. using Kernel::Timer;
  415. LOG_TRACE(Kernel_SVC, "called timer=0x%08X", handle);
  416. SharedPtr<Timer> timer = Kernel::g_handle_table.Get<Timer>(handle);
  417. if (timer == nullptr)
  418. return ERR_INVALID_HANDLE;
  419. timer->Clear();
  420. return RESULT_SUCCESS;
  421. }
  422. /// Starts a timer
  423. static ResultCode SetTimer(Handle handle, s64 initial, s64 interval) {
  424. using Kernel::Timer;
  425. LOG_TRACE(Kernel_SVC, "called timer=0x%08X", handle);
  426. SharedPtr<Timer> timer = Kernel::g_handle_table.Get<Timer>(handle);
  427. if (timer == nullptr)
  428. return ERR_INVALID_HANDLE;
  429. timer->Set(initial, interval);
  430. HLE::Reschedule(__func__);
  431. return RESULT_SUCCESS;
  432. }
  433. /// Cancels a timer
  434. static ResultCode CancelTimer(Handle handle) {
  435. using Kernel::Timer;
  436. LOG_TRACE(Kernel_SVC, "called timer=0x%08X", handle);
  437. SharedPtr<Timer> timer = Kernel::g_handle_table.Get<Timer>(handle);
  438. if (timer == nullptr)
  439. return ERR_INVALID_HANDLE;
  440. timer->Cancel();
  441. HLE::Reschedule(__func__);
  442. return RESULT_SUCCESS;
  443. }
  444. /// Sleep the current thread
  445. static void SleepThread(s64 nanoseconds) {
  446. LOG_TRACE(Kernel_SVC, "called nanoseconds=%lld", nanoseconds);
  447. // Sleep current thread and check for next thread to schedule
  448. Kernel::WaitCurrentThread_Sleep();
  449. // Create an event to wake the thread up after the specified nanosecond delay has passed
  450. Kernel::GetCurrentThread()->WakeAfterDelay(nanoseconds);
  451. HLE::Reschedule(__func__);
  452. }
  453. /// This returns the total CPU ticks elapsed since the CPU was powered-on
  454. static s64 GetSystemTick() {
  455. return (s64)CoreTiming::GetTicks();
  456. }
  457. /// Creates a memory block at the specified address with the specified permissions and size
  458. static ResultCode CreateMemoryBlock(Handle* out_handle, u32 addr, u32 size, u32 my_permission,
  459. u32 other_permission) {
  460. using Kernel::SharedMemory;
  461. // TODO(Subv): Implement this function
  462. SharedPtr<SharedMemory> shared_memory = SharedMemory::Create();
  463. CASCADE_RESULT(*out_handle, Kernel::g_handle_table.Create(std::move(shared_memory)));
  464. LOG_WARNING(Kernel_SVC, "(STUBBED) called addr=0x%08X", addr);
  465. return RESULT_SUCCESS;
  466. }
  467. namespace {
  468. struct FunctionDef {
  469. using Func = void();
  470. u32 id;
  471. Func* func;
  472. const char* name;
  473. };
  474. }
  475. static const FunctionDef SVC_Table[] = {
  476. {0x00, nullptr, "Unknown"},
  477. {0x01, HLE::Wrap<ControlMemory>, "ControlMemory"},
  478. {0x02, HLE::Wrap<QueryMemory>, "QueryMemory"},
  479. {0x03, nullptr, "ExitProcess"},
  480. {0x04, nullptr, "GetProcessAffinityMask"},
  481. {0x05, nullptr, "SetProcessAffinityMask"},
  482. {0x06, nullptr, "GetProcessIdealProcessor"},
  483. {0x07, nullptr, "SetProcessIdealProcessor"},
  484. {0x08, HLE::Wrap<CreateThread>, "CreateThread"},
  485. {0x09, ExitThread, "ExitThread"},
  486. {0x0A, HLE::Wrap<SleepThread>, "SleepThread"},
  487. {0x0B, HLE::Wrap<GetThreadPriority>, "GetThreadPriority"},
  488. {0x0C, HLE::Wrap<SetThreadPriority>, "SetThreadPriority"},
  489. {0x0D, nullptr, "GetThreadAffinityMask"},
  490. {0x0E, nullptr, "SetThreadAffinityMask"},
  491. {0x0F, nullptr, "GetThreadIdealProcessor"},
  492. {0x10, nullptr, "SetThreadIdealProcessor"},
  493. {0x11, nullptr, "GetCurrentProcessorNumber"},
  494. {0x12, nullptr, "Run"},
  495. {0x13, HLE::Wrap<CreateMutex>, "CreateMutex"},
  496. {0x14, HLE::Wrap<ReleaseMutex>, "ReleaseMutex"},
  497. {0x15, HLE::Wrap<CreateSemaphore>, "CreateSemaphore"},
  498. {0x16, HLE::Wrap<ReleaseSemaphore>, "ReleaseSemaphore"},
  499. {0x17, HLE::Wrap<CreateEvent>, "CreateEvent"},
  500. {0x18, HLE::Wrap<SignalEvent>, "SignalEvent"},
  501. {0x19, HLE::Wrap<ClearEvent>, "ClearEvent"},
  502. {0x1A, HLE::Wrap<CreateTimer>, "CreateTimer"},
  503. {0x1B, HLE::Wrap<SetTimer>, "SetTimer"},
  504. {0x1C, HLE::Wrap<CancelTimer>, "CancelTimer"},
  505. {0x1D, HLE::Wrap<ClearTimer>, "ClearTimer"},
  506. {0x1E, HLE::Wrap<CreateMemoryBlock>, "CreateMemoryBlock"},
  507. {0x1F, HLE::Wrap<MapMemoryBlock>, "MapMemoryBlock"},
  508. {0x20, nullptr, "UnmapMemoryBlock"},
  509. {0x21, HLE::Wrap<CreateAddressArbiter>, "CreateAddressArbiter"},
  510. {0x22, HLE::Wrap<ArbitrateAddress>, "ArbitrateAddress"},
  511. {0x23, HLE::Wrap<CloseHandle>, "CloseHandle"},
  512. {0x24, HLE::Wrap<WaitSynchronization1>, "WaitSynchronization1"},
  513. {0x25, HLE::Wrap<WaitSynchronizationN>, "WaitSynchronizationN"},
  514. {0x26, nullptr, "SignalAndWait"},
  515. {0x27, HLE::Wrap<DuplicateHandle>, "DuplicateHandle"},
  516. {0x28, HLE::Wrap<GetSystemTick>, "GetSystemTick"},
  517. {0x29, nullptr, "GetHandleInfo"},
  518. {0x2A, nullptr, "GetSystemInfo"},
  519. {0x2B, nullptr, "GetProcessInfo"},
  520. {0x2C, nullptr, "GetThreadInfo"},
  521. {0x2D, HLE::Wrap<ConnectToPort>, "ConnectToPort"},
  522. {0x2E, nullptr, "SendSyncRequest1"},
  523. {0x2F, nullptr, "SendSyncRequest2"},
  524. {0x30, nullptr, "SendSyncRequest3"},
  525. {0x31, nullptr, "SendSyncRequest4"},
  526. {0x32, HLE::Wrap<SendSyncRequest>, "SendSyncRequest"},
  527. {0x33, nullptr, "OpenProcess"},
  528. {0x34, nullptr, "OpenThread"},
  529. {0x35, nullptr, "GetProcessId"},
  530. {0x36, nullptr, "GetProcessIdOfThread"},
  531. {0x37, HLE::Wrap<GetThreadId>, "GetThreadId"},
  532. {0x38, HLE::Wrap<GetResourceLimit>, "GetResourceLimit"},
  533. {0x39, nullptr, "GetResourceLimitLimitValues"},
  534. {0x3A, HLE::Wrap<GetResourceLimitCurrentValues>, "GetResourceLimitCurrentValues"},
  535. {0x3B, nullptr, "GetThreadContext"},
  536. {0x3C, nullptr, "Break"},
  537. {0x3D, HLE::Wrap<OutputDebugString>, "OutputDebugString"},
  538. {0x3E, nullptr, "ControlPerformanceCounter"},
  539. {0x3F, nullptr, "Unknown"},
  540. {0x40, nullptr, "Unknown"},
  541. {0x41, nullptr, "Unknown"},
  542. {0x42, nullptr, "Unknown"},
  543. {0x43, nullptr, "Unknown"},
  544. {0x44, nullptr, "Unknown"},
  545. {0x45, nullptr, "Unknown"},
  546. {0x46, nullptr, "Unknown"},
  547. {0x47, nullptr, "CreatePort"},
  548. {0x48, nullptr, "CreateSessionToPort"},
  549. {0x49, nullptr, "CreateSession"},
  550. {0x4A, nullptr, "AcceptSession"},
  551. {0x4B, nullptr, "ReplyAndReceive1"},
  552. {0x4C, nullptr, "ReplyAndReceive2"},
  553. {0x4D, nullptr, "ReplyAndReceive3"},
  554. {0x4E, nullptr, "ReplyAndReceive4"},
  555. {0x4F, nullptr, "ReplyAndReceive"},
  556. {0x50, nullptr, "BindInterrupt"},
  557. {0x51, nullptr, "UnbindInterrupt"},
  558. {0x52, nullptr, "InvalidateProcessDataCache"},
  559. {0x53, nullptr, "StoreProcessDataCache"},
  560. {0x54, nullptr, "FlushProcessDataCache"},
  561. {0x55, nullptr, "StartInterProcessDma"},
  562. {0x56, nullptr, "StopDma"},
  563. {0x57, nullptr, "GetDmaState"},
  564. {0x58, nullptr, "RestartDma"},
  565. {0x59, nullptr, "Unknown"},
  566. {0x5A, nullptr, "Unknown"},
  567. {0x5B, nullptr, "Unknown"},
  568. {0x5C, nullptr, "Unknown"},
  569. {0x5D, nullptr, "Unknown"},
  570. {0x5E, nullptr, "Unknown"},
  571. {0x5F, nullptr, "Unknown"},
  572. {0x60, nullptr, "DebugActiveProcess"},
  573. {0x61, nullptr, "BreakDebugProcess"},
  574. {0x62, nullptr, "TerminateDebugProcess"},
  575. {0x63, nullptr, "GetProcessDebugEvent"},
  576. {0x64, nullptr, "ContinueDebugEvent"},
  577. {0x65, nullptr, "GetProcessList"},
  578. {0x66, nullptr, "GetThreadList"},
  579. {0x67, nullptr, "GetDebugThreadContext"},
  580. {0x68, nullptr, "SetDebugThreadContext"},
  581. {0x69, nullptr, "QueryDebugProcessMemory"},
  582. {0x6A, nullptr, "ReadProcessMemory"},
  583. {0x6B, nullptr, "WriteProcessMemory"},
  584. {0x6C, nullptr, "SetHardwareBreakPoint"},
  585. {0x6D, nullptr, "GetDebugThreadParam"},
  586. {0x6E, nullptr, "Unknown"},
  587. {0x6F, nullptr, "Unknown"},
  588. {0x70, nullptr, "ControlProcessMemory"},
  589. {0x71, nullptr, "MapProcessMemory"},
  590. {0x72, nullptr, "UnmapProcessMemory"},
  591. {0x73, nullptr, "CreateCodeSet"},
  592. {0x74, nullptr, "RandomStub"},
  593. {0x75, nullptr, "CreateProcess"},
  594. {0x76, nullptr, "TerminateProcess"},
  595. {0x77, nullptr, "SetProcessResourceLimits"},
  596. {0x78, nullptr, "CreateResourceLimit"},
  597. {0x79, nullptr, "SetResourceLimitValues"},
  598. {0x7A, nullptr, "AddCodeSegment"},
  599. {0x7B, nullptr, "Backdoor"},
  600. {0x7C, nullptr, "KernelSetState"},
  601. {0x7D, nullptr, "QueryProcessMemory"},
  602. };
  603. Common::Profiling::TimingCategory profiler_svc("SVC Calls");
  604. static const FunctionDef* GetSVCInfo(u32 opcode) {
  605. u32 func_num = opcode & 0xFFFFFF; // 8 bits
  606. if (func_num >= ARRAY_SIZE(SVC_Table)) {
  607. LOG_ERROR(Kernel_SVC, "unknown svc=0x%02X", func_num);
  608. return nullptr;
  609. }
  610. return &SVC_Table[func_num];
  611. }
  612. void CallSVC(u32 opcode) {
  613. Common::Profiling::ScopeTimer timer_svc(profiler_svc);
  614. const FunctionDef *info = GetSVCInfo(opcode);
  615. if (info) {
  616. if (info->func) {
  617. info->func();
  618. } else {
  619. LOG_ERROR(Kernel_SVC, "unimplemented SVC function %s(..)", info->name);
  620. }
  621. }
  622. }
  623. } // namespace