CCRef.cpp 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. /****************************************************************************
  2. Copyright (c) 2010-2012 cocos2d-x.org
  3. Copyright (c) 2013-2017 Chukong Technologies
  4. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  5. http://www.cocos2d-x.org
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in
  13. all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. THE SOFTWARE.
  21. ****************************************************************************/
  22. #include "base/CCRef.h"
  23. #include "base/CCAutoreleasePool.h"
  24. #include "base/ccMacros.h"
  25. #include "base/CCScriptSupport.h"
  26. #if CC_REF_LEAK_DETECTION
  27. #include <algorithm> // std::find
  28. #include <thread>
  29. #include <mutex>
  30. #include <vector>
  31. #endif
  32. NS_CC_BEGIN
  33. #if CC_REF_LEAK_DETECTION
  34. static void trackRef(Ref* ref);
  35. static void untrackRef(Ref* ref);
  36. #endif
  37. Ref::Ref()
  38. : _referenceCount(1) // when the Ref is created, the reference count of it is 1
  39. #if CC_ENABLE_SCRIPT_BINDING
  40. , _luaID (0)
  41. , _scriptObject(nullptr)
  42. , _rooted(false)
  43. #endif
  44. {
  45. #if CC_ENABLE_SCRIPT_BINDING
  46. static unsigned int uObjectCount = 0;
  47. _ID = ++uObjectCount;
  48. #endif
  49. #if CC_REF_LEAK_DETECTION
  50. trackRef(this);
  51. #endif
  52. }
  53. Ref::~Ref()
  54. {
  55. #if CC_ENABLE_SCRIPT_BINDING
  56. // if the object is referenced by Lua engine, remove it
  57. if (_luaID)
  58. {
  59. ScriptEngineManager::getInstance()->getScriptEngine()->removeScriptObjectByObject(this);
  60. }
  61. #if !CC_ENABLE_GC_FOR_NATIVE_OBJECTS
  62. else
  63. {
  64. ScriptEngineProtocol* pEngine = ScriptEngineManager::getInstance()->getScriptEngine();
  65. if (pEngine != nullptr && pEngine->getScriptType() == kScriptTypeJavascript)
  66. {
  67. pEngine->removeScriptObjectByObject(this);
  68. }
  69. }
  70. #endif // !CC_ENABLE_GC_FOR_NATIVE_OBJECTS
  71. #endif // CC_ENABLE_SCRIPT_BINDING
  72. #if CC_REF_LEAK_DETECTION
  73. if (_referenceCount != 0)
  74. untrackRef(this);
  75. #endif
  76. }
  77. void Ref::retain()
  78. {
  79. CCASSERT(_referenceCount > 0, "reference count should be greater than 0");
  80. ++_referenceCount;
  81. }
  82. void Ref::release()
  83. {
  84. CCASSERT(_referenceCount > 0, "reference count should be greater than 0");
  85. --_referenceCount;
  86. if (_referenceCount == 0)
  87. {
  88. #if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0)
  89. auto poolManager = PoolManager::getInstance();
  90. if (!poolManager->getCurrentPool()->isClearing() && poolManager->isObjectInPools(this))
  91. {
  92. // Trigger an assert if the reference count is 0 but the Ref is still in autorelease pool.
  93. // This happens when 'autorelease/release' were not used in pairs with 'new/retain'.
  94. //
  95. // Wrong usage (1):
  96. //
  97. // auto obj = Node::create(); // Ref = 1, but it's an autorelease Ref which means it was in the autorelease pool.
  98. // obj->autorelease(); // Wrong: If you wish to invoke autorelease several times, you should retain `obj` first.
  99. //
  100. // Wrong usage (2):
  101. //
  102. // auto obj = Node::create();
  103. // obj->release(); // Wrong: obj is an autorelease Ref, it will be released when clearing current pool.
  104. //
  105. // Correct usage (1):
  106. //
  107. // auto obj = Node::create();
  108. // |- new Node(); // `new` is the pair of the `autorelease` of next line
  109. // |- autorelease(); // The pair of `new Node`.
  110. //
  111. // obj->retain();
  112. // obj->autorelease(); // This `autorelease` is the pair of `retain` of previous line.
  113. //
  114. // Correct usage (2):
  115. //
  116. // auto obj = Node::create();
  117. // obj->retain();
  118. // obj->release(); // This `release` is the pair of `retain` of previous line.
  119. CCASSERT(false, "The reference shouldn't be 0 because it is still in autorelease pool.");
  120. }
  121. #endif
  122. #if CC_ENABLE_SCRIPT_BINDING
  123. ScriptEngineProtocol* pEngine = ScriptEngineManager::getInstance()->getScriptEngine();
  124. if (pEngine != nullptr && pEngine->getScriptType() == kScriptTypeJavascript)
  125. {
  126. pEngine->removeObjectProxy(this);
  127. }
  128. #endif // CC_ENABLE_SCRIPT_BINDING
  129. #if CC_REF_LEAK_DETECTION
  130. untrackRef(this);
  131. #endif
  132. delete this;
  133. }
  134. }
  135. Ref* Ref::autorelease()
  136. {
  137. PoolManager::getInstance()->getCurrentPool()->addObject(this);
  138. return this;
  139. }
  140. unsigned int Ref::getReferenceCount() const
  141. {
  142. return _referenceCount;
  143. }
  144. #if CC_REF_LEAK_DETECTION
  145. static std::vector<Ref*> __refAllocationList;
  146. static std::mutex __refMutex;
  147. void Ref::printLeaks()
  148. {
  149. std::lock_guard<std::mutex> refLockGuard(__refMutex);
  150. // Dump Ref object memory leaks
  151. if (__refAllocationList.empty())
  152. {
  153. log("[memory] All Ref objects successfully cleaned up (no leaks detected).\n");
  154. }
  155. else
  156. {
  157. log("[memory] WARNING: %d Ref objects still active in memory.\n", (int)__refAllocationList.size());
  158. for (const auto& ref : __refAllocationList)
  159. {
  160. CC_ASSERT(ref);
  161. const char* type = typeid(*ref).name();
  162. log("[memory] LEAK: Ref object '%s' still active with reference count %d.\n", (type ? type : ""), ref->getReferenceCount());
  163. }
  164. }
  165. }
  166. static void trackRef(Ref* ref)
  167. {
  168. std::lock_guard<std::mutex> refLockGuard(__refMutex);
  169. CCASSERT(ref, "Invalid parameter, ref should not be null!");
  170. // Create memory allocation record.
  171. __refAllocationList.push_back(ref);
  172. }
  173. static void untrackRef(Ref* ref)
  174. {
  175. std::lock_guard<std::mutex> refLockGuard(__refMutex);
  176. auto iter = std::find(__refAllocationList.begin(), __refAllocationList.end(), ref);
  177. if (iter == __refAllocationList.end())
  178. {
  179. log("[memory] CORRUPTION: Attempting to free (%s) with invalid ref tracking record.\n", typeid(*ref).name());
  180. return;
  181. }
  182. __refAllocationList.erase(iter);
  183. }
  184. #endif // #if CC_REF_LEAK_DETECTION
  185. NS_CC_END