Navigation Menu

Skip to content

Commit

Permalink
Improve debug support for analyzing memory leaks
Browse files Browse the repository at this point in the history
refs #10963
  • Loading branch information
gunnarbeutner committed Feb 23, 2016
1 parent e80b335 commit abfacd9
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
51 changes: 51 additions & 0 deletions lib/base/object.cpp
Expand Up @@ -22,11 +22,20 @@
#include "base/dictionary.hpp"
#include "base/primitivetype.hpp"
#include "base/utility.hpp"
#include "base/timer.hpp"
#include "base/logger.hpp"
#include <boost/foreach.hpp>

using namespace icinga;

DEFINE_TYPE_INSTANCE(Object);

#ifdef I2_DEBUG
static boost::mutex l_ObjectCountLock;
static std::map<String, int> l_ObjectCounts;
static Timer::Ptr l_ObjectCountTimer;
#endif

/**
* Default constructor for the Object class.
*/
Expand Down Expand Up @@ -117,3 +126,45 @@ Type::Ptr Object::GetReflectionType(void) const
return Object::TypeInstance;
}

#ifdef I2_DEBUG
void icinga::TypeAddObject(Object *object)
{
boost::mutex::scoped_lock lock(l_ObjectCountLock);
String typeName = Utility::GetTypeName(typeid(*object));
l_ObjectCounts[typeName]++;
}

void icinga::TypeRemoveObject(Object *object)
{
boost::mutex::scoped_lock lock(l_ObjectCountLock);
String typeName = Utility::GetTypeName(typeid(*object));
l_ObjectCounts[typeName]--;
}

static void TypeInfoTimerHandler(void)
{
boost::mutex::scoped_lock lock(l_ObjectCountLock);

typedef std::map<String, int>::value_type kv_pair;
BOOST_FOREACH(kv_pair& kv, l_ObjectCounts) {
if (kv.second == 0)
continue;

Log(LogInformation, "TypeInfo")
<< kv.second << " " << kv.first << " objects";

kv.second = 0;
}
}

static void StartTypeInfoTimer(void)
{
l_ObjectCountTimer = new Timer();
l_ObjectCountTimer->SetInterval(10);
l_ObjectCountTimer->OnTimerExpired.connect(boost::bind(TypeInfoTimerHandler));
l_ObjectCountTimer->Start();
}

INITIALIZE_ONCE(StartTypeInfoTimer);
#endif /* I2_DEBUG */

15 changes: 14 additions & 1 deletion lib/base/object.hpp
Expand Up @@ -134,8 +134,16 @@ class I2_BASE_API Object
friend void intrusive_ptr_release(Object *object);
};

void TypeAddObject(Object *object);
void TypeRemoveObject(Object *object);

inline void intrusive_ptr_add_ref(Object *object)
{
#ifdef I2_DEBUG
if (object->m_References == 0)
TypeAddObject(object);
#endif /* I2_DEBUG */

#ifdef _WIN32
InterlockedIncrement(&object->m_References);
#else /* _WIN32 */
Expand All @@ -153,8 +161,13 @@ inline void intrusive_ptr_release(Object *object)
refs = __sync_sub_and_fetch(&object->m_References, 1);
#endif /* _WIN32 */

if (refs == 0)
if (refs == 0) {
#ifdef I2_DEBUG
TypeRemoveObject(object);
#endif /* I2_DEBUG */

delete object;
}
}

template<typename T>
Expand Down

0 comments on commit abfacd9

Please sign in to comment.