svc.cpp 31 KB

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