handle_table.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <utility>
  5. #include "common/assert.h"
  6. #include "common/logging/log.h"
  7. #include "core/core.h"
  8. #include "core/hle/kernel/errors.h"
  9. #include "core/hle/kernel/handle_table.h"
  10. #include "core/hle/kernel/process.h"
  11. #include "core/hle/kernel/thread.h"
  12. namespace Kernel {
  13. HandleTable::HandleTable() {
  14. next_generation = 1;
  15. Clear();
  16. }
  17. ResultVal<Handle> HandleTable::Create(SharedPtr<Object> obj) {
  18. DEBUG_ASSERT(obj != nullptr);
  19. u16 slot = next_free_slot;
  20. if (slot >= generations.size()) {
  21. LOG_ERROR(Kernel, "Unable to allocate Handle, too many slots in use.");
  22. return ERR_HANDLE_TABLE_FULL;
  23. }
  24. next_free_slot = generations[slot];
  25. u16 generation = next_generation++;
  26. // Overflow count so it fits in the 15 bits dedicated to the generation in the handle.
  27. // CTR-OS doesn't use generation 0, so skip straight to 1.
  28. if (next_generation >= (1 << 15))
  29. next_generation = 1;
  30. generations[slot] = generation;
  31. objects[slot] = std::move(obj);
  32. Handle handle = generation | (slot << 15);
  33. return MakeResult<Handle>(handle);
  34. }
  35. ResultVal<Handle> HandleTable::Duplicate(Handle handle) {
  36. SharedPtr<Object> object = GetGeneric(handle);
  37. if (object == nullptr) {
  38. LOG_ERROR(Kernel, "Tried to duplicate invalid handle: {:08X}", handle);
  39. return ERR_INVALID_HANDLE;
  40. }
  41. return Create(std::move(object));
  42. }
  43. ResultCode HandleTable::Close(Handle handle) {
  44. if (!IsValid(handle))
  45. return ERR_INVALID_HANDLE;
  46. u16 slot = GetSlot(handle);
  47. objects[slot] = nullptr;
  48. generations[slot] = next_free_slot;
  49. next_free_slot = slot;
  50. return RESULT_SUCCESS;
  51. }
  52. bool HandleTable::IsValid(Handle handle) const {
  53. std::size_t slot = GetSlot(handle);
  54. u16 generation = GetGeneration(handle);
  55. return slot < MAX_COUNT && objects[slot] != nullptr && generations[slot] == generation;
  56. }
  57. SharedPtr<Object> HandleTable::GetGeneric(Handle handle) const {
  58. if (handle == CurrentThread) {
  59. return GetCurrentThread();
  60. } else if (handle == CurrentProcess) {
  61. return Core::CurrentProcess();
  62. }
  63. if (!IsValid(handle)) {
  64. return nullptr;
  65. }
  66. return objects[GetSlot(handle)];
  67. }
  68. void HandleTable::Clear() {
  69. for (u16 i = 0; i < MAX_COUNT; ++i) {
  70. generations[i] = i + 1;
  71. objects[i] = nullptr;
  72. }
  73. next_free_slot = 0;
  74. }
  75. } // namespace Kernel