CCRef.cpp 6.7 KB

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