object.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. // Copyright 2018 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <atomic>
  6. #include <string>
  7. #include <utility>
  8. #include <boost/smart_ptr/intrusive_ptr.hpp>
  9. #include "common/common_types.h"
  10. namespace Kernel {
  11. class KernelCore;
  12. using Handle = u32;
  13. enum class HandleType : u32 {
  14. Unknown,
  15. Event,
  16. SharedMemory,
  17. Thread,
  18. Process,
  19. AddressArbiter,
  20. Timer,
  21. ResourceLimit,
  22. CodeSet,
  23. ClientPort,
  24. ServerPort,
  25. ClientSession,
  26. ServerSession,
  27. };
  28. enum class ResetType {
  29. OneShot,
  30. Sticky,
  31. Pulse,
  32. };
  33. class Object : NonCopyable {
  34. public:
  35. explicit Object(KernelCore& kernel);
  36. virtual ~Object();
  37. /// Returns a unique identifier for the object. For debugging purposes only.
  38. u32 GetObjectId() const {
  39. return object_id.load(std::memory_order_relaxed);
  40. }
  41. virtual std::string GetTypeName() const {
  42. return "[BAD KERNEL OBJECT TYPE]";
  43. }
  44. virtual std::string GetName() const {
  45. return "[UNKNOWN KERNEL OBJECT]";
  46. }
  47. virtual HandleType GetHandleType() const = 0;
  48. /**
  49. * Check if a thread can wait on the object
  50. * @return True if a thread can wait on the object, otherwise false
  51. */
  52. bool IsWaitable() const;
  53. protected:
  54. /// The kernel instance this object was created under.
  55. KernelCore& kernel;
  56. private:
  57. friend void intrusive_ptr_add_ref(Object*);
  58. friend void intrusive_ptr_release(Object*);
  59. std::atomic<u32> ref_count{0};
  60. std::atomic<u32> object_id{0};
  61. };
  62. // Special functions used by boost::instrusive_ptr to do automatic ref-counting
  63. inline void intrusive_ptr_add_ref(Object* object) {
  64. object->ref_count.fetch_add(1, std::memory_order_relaxed);
  65. }
  66. inline void intrusive_ptr_release(Object* object) {
  67. if (object->ref_count.fetch_sub(1, std::memory_order_acq_rel) == 1) {
  68. delete object;
  69. }
  70. }
  71. template <typename T>
  72. using SharedPtr = boost::intrusive_ptr<T>;
  73. /**
  74. * Attempts to downcast the given Object pointer to a pointer to T.
  75. * @return Derived pointer to the object, or `nullptr` if `object` isn't of type T.
  76. */
  77. template <typename T>
  78. inline SharedPtr<T> DynamicObjectCast(SharedPtr<Object> object) {
  79. if (object != nullptr && object->GetHandleType() == T::HANDLE_TYPE) {
  80. return boost::static_pointer_cast<T>(std::move(object));
  81. }
  82. return nullptr;
  83. }
  84. } // namespace Kernel