~macslow/nux/nux.fix-839476

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
// -*- Mode: C++; indent-tabs-mode: nil; tab-width: 2 -*-
/*
 * Copyright 2010-2011 Inalogic® Inc.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License, as
 * published by the  Free Software Foundation; either version 2.1 or 3.0
 * of the License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranties of
 * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the applicable version of the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of both the GNU Lesser General Public
 * License along with this program. If not, see <http://www.gnu.org/licenses/>
 *
 * Authored by: Jay Taoko <jaytaoko@inalogic.com>
 *
 */

#include "NuxCore.h"
#include "Object.h"
#include "ObjectPtr.h"
#include "Logger.h"

namespace nux
{
namespace
{
logging::Logger logger("nux.core.object");
}

  NUX_IMPLEMENT_ROOT_OBJECT_TYPE (Trackable);
  NUX_IMPLEMENT_OBJECT_TYPE (Object);
  NUX_IMPLEMENT_GLOBAL_OBJECT (ObjectStats);

  void ObjectStats::Constructor()
  {
    _total_allocated_size= 0;
    _number_of_objects = 0;
  }

  void ObjectStats::Destructor()
  {
#if defined(NUX_DEBUG)
    if (_number_of_objects)
    {
      std::cerr << "[ObjectStats::Destructor] "
                << _number_of_objects << " undeleted objects.\n\t"
                << _allocation_list.size() << " items in allocation list.\n";
    }

    int index = 0;

#if defined(NUX_OS_WINDOWS)
  // Visual Studio does not support range based for loops.
  for (AllocationList::iterator ptr = _allocation_list.begin(); ptr != _allocation_list.end(); ++ptr)
  {
    Object* obj = static_cast<Object*>(*ptr);
    
    std::stringstream sout;
    sout << "\t" << ++index << " Undeleted object: Type "
      << obj->Type().name << ", "
      << obj->GetAllocationLoation() << "\n";

    OutputDebugString (sout.str().c_str());

    std::cerr << sout.str().c_str();
  }
#else
    for (auto ptr : _allocation_list)
    {
      Object* obj = static_cast<Object*>(ptr);
      std::cerr << "\t" << ++index << " Undeleted object: Type "
                << obj->Type().name << ", "
                << obj->GetAllocationLoation() << "\n";
    }
#endif
#endif
  }

  std::new_handler Trackable::_new_current_handler = 0;

  Trackable::Trackable()
  {
    _heap_allocated = -1;

    _owns_the_reference = false;
  }

  Trackable::~Trackable()
  {
  }

  bool Trackable::Reference()
  {
    return false;
  }

  bool Trackable::UnReference()
  {
    return false;
  }

  bool Trackable::SinkReference()
  {
    return false;
  }

  bool Trackable::Dispose()
  {
    return false;
  }

  bool Trackable::OwnsTheReference()
  {
    return _owns_the_reference;
  }

  void Trackable::SetOwnedReference (bool b)
  {
    if (_owns_the_reference == true)
    {
      LOG_DEBUG(logger) << "Do not change the ownership if is already set to true!" << "\n";
      return;
    }

    _owns_the_reference = b;
  }

  std::new_handler Trackable::set_new_handler (std::new_handler handler)
  {
    std::new_handler old_handler = _new_current_handler;
    _new_current_handler = handler;
    return old_handler;
  }

  void* Trackable::operator new (size_t size)
  {
    // Set the new_handler for this call
    std::new_handler global_handler  = std::set_new_handler (_new_current_handler);

    // If allocation fails _new_current_handler is called, if specified,
    // otherwise the global new_handler is called.
    void *ptr;

    try
    {
      ptr = ::operator new (size);

      GObjectStats._allocation_list.push_front (ptr);
      NUX_STATIC_CAST (Trackable *, ptr)->_size_of_this_object = size;
      GObjectStats._total_allocated_size += size;
      ++GObjectStats._number_of_objects;
    }
    catch (std::bad_alloc &)
    {
      std::set_new_handler (global_handler);
      throw;
    }

    //  Reset gloabal new_handler
    std::set_new_handler (global_handler);
    return ptr;
  }

#if (__GNUC__ < 4 && __GNUC_MINOR__ < 4)

  void *Trackable::operator new (size_t size, void *ptr)
  {
    return ::operator new (size, ptr);
  }

#endif

  void Trackable::operator delete (void *ptr)
  {
    ObjectStats::AllocationList::iterator i = std::find (GObjectStats._allocation_list.begin(), GObjectStats._allocation_list.end(), ptr);

    if (i != GObjectStats._allocation_list.end() )
    {
      GObjectStats._total_allocated_size -= NUX_STATIC_CAST (Trackable *, ptr)->_size_of_this_object;
      --GObjectStats._number_of_objects;
      GObjectStats._allocation_list.erase (i);
      ::operator delete (ptr);
    }
  }

  bool Trackable::IsHeapAllocated()
  {
    if (_heap_allocated == -1)
    {
      _heap_allocated = (IsDynamic () ? 1 : 0);
    }

    return (_heap_allocated == 1 ? true : false);
  }

  bool Trackable::IsDynamic() const
  {
    // Get pointer to beginning of the memory occupied by this.
    const void *ptr = dynamic_cast<const void *> (this);

    // Search for ptr in allocation_list
#if defined(NUX_OS_WINDOWS) && !defined(NUX_VISUAL_STUDIO_2010)
    std::list<void*>::iterator i = std::find(GObjectStats._allocation_list.begin(),
      GObjectStats._allocation_list.end(), ptr);
#else
    auto i = std::find(GObjectStats._allocation_list.begin(),
                       GObjectStats._allocation_list.end(), ptr);
#endif
    return i != GObjectStats._allocation_list.end();
  }

  int Trackable::GetObjectSize ()
  {
    return _size_of_this_object;
  }

//////////////////////////////////////////////////////////////////////

  Object::Object(bool OwnTheReference, NUX_FILE_LINE_DECL)
    : allocation_file_name_(__Nux_FileName__)
    , allocation_line_number_(__Nux_LineNumber__)
    , reference_count_(new NThreadSafeCounter())
    , objectptr_count_(new NThreadSafeCounter())
  {
    reference_count_->Set(1);
    SetOwnedReference(OwnTheReference);
  }

  Object::~Object()
  {
    if (IsHeapAllocated())
    {
      // If the object has properly been UnReference, it should have gone
      // through Destroy(). if that is the case then _reference_count should
      // be NULL or its value (returned by GetValue ()) should be equal to 0;
      // We can use this to detect when delete is called directly on an
      // object.
      if (reference_count_->GetValue() > 0)
      {
        LOG_WARN(logger) << "Invalid object destruction, still has "
                         << reference_count_->GetValue() << " references."
                         << "\nObject allocated at: " << GetAllocationLoation() << "\n";
      }
    }
    delete reference_count_;
    delete objectptr_count_;
  }

  bool Object::Reference()
  {
    if (!IsHeapAllocated())
    {
      LOG_WARN(logger) << "Trying to reference an object that was not heap allocated."
                       << "\nObject allocated at: " << GetAllocationLoation() << "\n";
      return false;
    }

    if (!OwnsTheReference())
    {
      SetOwnedReference(true);
      // The ref count remains at 1. Exit the method.
      return true;
    }

    reference_count_->Increment();
    return true;
  }

  bool Object::UnReference()
  {
    if (!IsHeapAllocated())
    {
      LOG_WARN(logger) << "Trying to un-reference an object that was not heap allocated."
                       << "\nObject allocated at: " << GetAllocationLoation() << "\n";
      return false;
    }

    if (objectptr_count_->GetValue() == reference_count_->GetValue())
    {
      // There are ObjectPtr's hosting this object. Release all of them to
      // destroy this object.  This prevent from calling UnReference () many
      // times and destroying the object when there are ObjectPtr's hosting
      // it.  This method should not be called directly in that case.
      LOG_WARN(logger) << "There are ObjectPtr hosting this object. "
                       << "Release all of them to destroy this object. "
                       << "\nObject allocated at: " << GetAllocationLoation() << "\n";
      return false;
    }

    reference_count_->Decrement();

    if (reference_count_->GetValue() == 0)
    {
      Destroy();
      return true;
    }

    return false;
  }

  bool Object::SinkReference()
  {
    return Reference();
  }

  bool Object::Dispose()
  {
    // The intent of the Dispose call is to destroy objects with a float
    // reference (reference count is equal to 1 and the '_owns_the_reference'
    // flag is set to false). In Nux, only widgets object can have a floating
    // reference.  And widgets are only visible if added to the widget tree.
    // When an object with a floating reference is added to the widget tree,
    // it becomes "owned'. It looses it floating reference status but it still
    // has a reference count number of 1.  In practice, since widgets must be
    // added to the widget tree, there should never be a need to call Dispose
    // (except in a few cases).

    // Dispose() was designed to only destroy objects with floating
    // references, while UnReference() destroys objects that are "owned".
    // That is now relaxed. Dispose() calls UnReference().
    return UnReference();
  }

  void Object::Destroy()
  {
    static int delete_depth = 0;
    ++delete_depth;
    const char* obj_type = this->Type().name;
    LOG_TRACE(logger) << "Depth: " << delete_depth << ", about to delete "
                      << obj_type << " allocated at " << GetAllocationLoation();
    // Weak smart pointers will clear their pointers when they get this signal.
    object_destroyed.emit(this);
    delete this;
    LOG_TRACE(logger) << "Depth: " << delete_depth << ", delete successful for " << obj_type;
    --delete_depth;
  }

  int Object::GetReferenceCount() const
  {
    return reference_count_->GetValue();
  }

std::string Object::GetAllocationLoation() const
{
  std::ostringstream sout;
  sout << allocation_file_name_ << ":" << allocation_line_number_;
  return sout.str();
}

}