object.h 2.4 KB

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