]> git.saurik.com Git - wxWidgets.git/blame - src/common/memory.cpp
Sorry folks, a lot of changes to remedy GetFont, GetBrush etc.
[wxWidgets.git] / src / common / memory.cpp
CommitLineData
c801d85f
KB
1/////////////////////////////////////////////////////////////////////////////
2// Name: memory.cpp
3// Purpose: Memory checking implementation
4// Author: Arthur Seaton, Julian Smart
5// Modified by:
6// Created: 04/01/98
7// RCS-ID: $Id$
8// Copyright: (c) Julian Smart and Markus Holzem
9// Licence: wxWindows license
10/////////////////////////////////////////////////////////////////////////////
11
12#ifdef __GNUG__
13#pragma implementation "memory.h"
14#endif
15
16// For compilers that support precompilation, includes "wx.h".
17#include "wx/wxprec.h"
18
19#ifdef __BORLANDC__
20#pragma hdrstop
21#endif
22
23#ifndef WX_PRECOMP
24#include "wx/defs.h"
25#endif
26
ea57084d 27#if (defined(__WXDEBUG__) && wxUSE_MEMORY_TRACING) || wxUSE_DEBUG_CONTEXT
c801d85f
KB
28
29#ifdef __GNUG__
30// #pragma implementation
31#endif
32
33#ifndef WX_PRECOMP
34#include "wx/utils.h"
35#include "wx/app.h"
36#endif
37
184b5d99 38#include <wx/log.h>
c801d85f
KB
39#include <stdlib.h>
40
47d67540 41#if wxUSE_IOSTREAMH
c801d85f 42#include <iostream.h>
fbc535ff 43#include <fstream.h>
c801d85f
KB
44#else
45#include <iostream>
fbc535ff
JS
46#include <fstream>
47# ifdef _MSC_VER
48 using namespace std;
49# endif
c801d85f 50#endif
c801d85f
KB
51
52#if !defined(__WATCOMC__) && !defined(__VMS__)
53#include <memory.h>
54#endif
55
56#include <stdarg.h>
57#include <string.h>
58
2049ba38 59#ifdef __WXMSW__
c801d85f
KB
60#include <windows.h>
61
62#ifdef GetClassInfo
63#undef GetClassInfo
64#endif
65
66#ifdef GetClassName
67#undef GetClassName
68#endif
69
70#endif
71
72#include "wx/memory.h"
73
c801d85f
KB
74#ifdef new
75#undef new
76#endif
c801d85f
KB
77
78// wxDebugContext wxTheDebugContext;
79/*
80 Redefine new and delete so that we can pick up situations where:
81 - we overwrite or underwrite areas of malloc'd memory.
82 - we use uninitialise variables
83 Only do this in debug mode.
84
85 We change new to get enough memory to allocate a struct, followed
86 by the caller's requested memory, followed by a tag. The struct
87 is used to create a doubly linked list of these areas and also
88 contains another tag. The tags are used to determine when the area
89 has been over/under written.
90*/
91
92
93/*
94 Values which are used to set the markers which will be tested for
95 under/over write. There are 3 of these, one in the struct, one
96 immediately after the struct but before the caller requested memory and
97 one immediately after the requested memory.
98*/
99#define MemStartCheck 0x23A8
100#define MemMidCheck 0xA328
101#define MemEndCheck 0x8A32
102#define MemFillChar 0xAF
103#define MemStructId 0x666D
104
105/*
106 External interface for the wxMemStruct class. Others are
107 defined inline within the class def. Here we only need to be able
108 to add and delete nodes from the list and handle errors in some way.
109*/
110
111/*
112 Used for internal "this shouldn't happen" type of errors.
113*/
114void wxMemStruct::ErrorMsg (const char * mesg)
115{
184b5d99 116 wxLogDebug("wxWindows memory checking error: %s", mesg);
c801d85f
KB
117 PrintNode ();
118
119// << m_fileName << ' ' << m_lineNum << endl;
120}
121
122/*
123 Used when we find an overwrite or an underwrite error.
124*/
125void wxMemStruct::ErrorMsg ()
126{
184b5d99 127 wxLogDebug("wxWindows over/underwrite memory error:");
c801d85f
KB
128 PrintNode ();
129
130// cerr << m_fileName << ' ' << m_lineNum << endl;
131}
132
133
134/*
135 We want to find out if pointers have been overwritten as soon as is
136 possible, so test everything before we dereference it. Of course it's still
137 quite possible that, if things have been overwritten, this function will
138 fall over, but the only way of dealing with that would cost too much in terms
139 of time.
140*/
141int wxMemStruct::AssertList ()
142{
143 if (wxDebugContext::GetHead () != 0 && ! (wxDebugContext::GetHead ())->AssertIt () ||
144 wxDebugContext::GetTail () != 0 && ! wxDebugContext::GetTail ()->AssertIt ()) {
145 ErrorMsg ("Head or tail pointers trashed");
146 return 0;
147 }
148 return 1;
149}
150
151
152/*
153 Check that the thing we're pointing to has the correct id for a wxMemStruct
154 object and also that it's previous and next pointers are pointing at objects
155 which have valid ids.
156 This is definitely not perfect since we could fall over just trying to access
157 any of the slots which we use here, but I think it's about the best that I
158 can do without doing something like taking all new wxMemStruct pointers and
159 comparing them against all known pointer within the list and then only
160 doing this sort of check _after_ you've found the pointer in the list. That
161 would be safer, but also much more time consuming.
162*/
163int wxMemStruct::AssertIt ()
164{
165 return (m_id == MemStructId &&
166 (m_prev == 0 || m_prev->m_id == MemStructId) &&
167 (m_next == 0 || m_next->m_id == MemStructId));
168}
169
170
171/*
172 Additions are always at the tail of the list.
173 Returns 0 on error, non-zero on success.
174*/
175int wxMemStruct::Append ()
176{
177 if (! AssertList ())
178 return 0;
179
180 if (wxDebugContext::GetHead () == 0) {
181 if (wxDebugContext::GetTail () != 0) {
182 ErrorMsg ("Null list should have a null tail pointer");
183 return 0;
184 }
185 (void) wxDebugContext::SetHead (this);
186 (void) wxDebugContext::SetTail (this);
187 } else {
188 wxDebugContext::GetTail ()->m_next = this;
189 this->m_prev = wxDebugContext::GetTail ();
190 (void) wxDebugContext::SetTail (this);
191 }
192 return 1;
193}
194
195
196/*
197 Don't actually free up anything here as the space which is used
198 by the node will be free'd up when the whole block is free'd.
199 Returns 0 on error, non-zero on success.
200*/
201int wxMemStruct::Unlink ()
202{
203 if (! AssertList ())
204 return 0;
205
206 if (wxDebugContext::GetHead () == 0 || wxDebugContext::GetTail () == 0) {
207 ErrorMsg ("Trying to remove node from empty list");
208 return 0;
209 }
210
211 // Handle the part of the list before this node.
212 if (m_prev == 0) {
213 if (this != wxDebugContext::GetHead ()) {
214 ErrorMsg ("No previous node for non-head node");
215 return 0;
216 }
217 (void) wxDebugContext::SetHead (m_next);
218 } else {
219 if (! m_prev->AssertIt ()) {
220 ErrorMsg ("Trashed previous pointer");
221 return 0;
222 }
223
224 if (m_prev->m_next != this) {
225 ErrorMsg ("List is inconsistent");
226 return 0;
227 }
228 m_prev->m_next = m_next;
229 }
230
231 // Handle the part of the list after this node.
232 if (m_next == 0) {
233 if (this != wxDebugContext::GetTail ()) {
234 ErrorMsg ("No next node for non-tail node");
235 return 0;
236 }
237 (void) wxDebugContext::SetTail (m_prev);
238 } else {
239 if (! m_next->AssertIt ()) {
240 ErrorMsg ("Trashed next pointer");
241 return 0;
242 }
243
244 if (m_next->m_prev != this) {
245 ErrorMsg ("List is inconsistent");
246 return 0;
247 }
248 m_next->m_prev = m_prev;
249 }
250
251 return 1;
252}
253
254
255
256/*
257 Checks a node and block of memory to see that the markers are still
258 intact.
259*/
260int wxMemStruct::CheckBlock ()
261{
262 int nFailures = 0;
263
264 if (m_firstMarker != MemStartCheck) {
265 nFailures++;
266 ErrorMsg ();
267 }
268
269 char * pointer = wxDebugContext::MidMarkerPos ((char *) this);
270 if (* (wxMarkerType *) pointer != MemMidCheck) {
271 nFailures++;
272 ErrorMsg ();
273 }
274
275 pointer = wxDebugContext::EndMarkerPos ((char *) this, RequestSize ());
276 if (* (wxMarkerType *) pointer != MemEndCheck) {
277 nFailures++;
278 ErrorMsg ();
279 }
280
281 return nFailures;
282}
283
284
285/*
286 Check the list of nodes to see if they are all ok.
287*/
288int wxMemStruct::CheckAllPrevious ()
289{
290 int nFailures = 0;
291
292 for (wxMemStruct * st = this->m_prev; st != 0; st = st->m_prev) {
293 if (st->AssertIt ())
294 nFailures += st->CheckBlock ();
295 else
296 return -1;
297 }
298
299 return nFailures;
300}
301
302
303/*
304 When we delete a node we set the id slot to a specific value and then test
305 against this to see if a nodes have been deleted previously. I don't
306 just set the entire memory to the fillChar because then I'd be overwriting
307 useful stuff like the vtbl which may be needed to output the error message
308 including the file name and line numbers. Without this info the whole point
309 of this class is lost!
310*/
311void wxMemStruct::SetDeleted ()
312{
313 m_id = MemFillChar;
314}
315
316int wxMemStruct::IsDeleted ()
317{
318 return (m_id == MemFillChar);
319}
320
321
322/*
323 Print out a single node. There are many far better ways of doing this
324 but this will suffice for now.
325*/
326void wxMemStruct::PrintNode ()
327{
328 if (m_isObject)
329 {
330 wxObject *obj = (wxObject *)m_actualData;
331 wxClassInfo *info = obj->GetClassInfo();
c801d85f 332
f97c9854
JS
333 // Let's put this in standard form so IDEs can load the file at the appropriate
334 // line
184b5d99
JS
335 wxString msg("");
336
f97c9854 337 if (m_fileName)
184b5d99 338 msg.Printf("%s(%d): ", m_fileName, (int)m_lineNum);
f97c9854
JS
339
340 if (info && info->GetClassName())
184b5d99 341 msg += info->GetClassName();
f97c9854 342 else
184b5d99
JS
343 msg += "object";
344
345 wxString msg2;
346 msg2.Printf(" at $%lX, size %d", (long)GetActualData(), (int)RequestSize());
347 msg += msg2;
f97c9854 348
184b5d99 349 wxLogDebug(msg);
c801d85f
KB
350 }
351 else
352 {
184b5d99
JS
353 wxString msg("");
354
c801d85f 355 if (m_fileName)
184b5d99
JS
356 msg.Printf("%s(%d): ", m_fileName, (int)m_lineNum);
357 msg += ("non-object data");
358 wxString msg2;
359 msg2.Printf(" at $%lX, size %d\n", (long)GetActualData(), (int)RequestSize());
360 msg += msg2;
361
362 wxLogDebug(msg);
c801d85f
KB
363 }
364}
365
366void wxMemStruct::Dump ()
367{
368 if (!ValidateNode()) return;
369
370 if (m_isObject)
371 {
372 wxObject *obj = (wxObject *)m_actualData;
c801d85f 373
184b5d99 374 wxString msg("");
c801d85f 375 if (m_fileName)
184b5d99 376 msg.Printf("%s(%d): ", m_fileName, (int)m_lineNum);
c801d85f 377
184b5d99
JS
378
379 /* TODO: We no longer have a stream (using wxLogDebug) so we can't dump it.
380 * Instead, do what wxObject::Dump does.
381 * What should we do long-term, eliminate Dumping? Or specify
382 * that MyClass::Dump should use wxLogDebug? Ugh.
c801d85f 383 obj->Dump(wxDebugContext::GetStream());
184b5d99
JS
384 */
385
386 if (obj->GetClassInfo() && obj->GetClassInfo()->GetClassName())
387 msg += obj->GetClassInfo()->GetClassName();
388 else
389 msg += "unknown object class";
390
391 wxString msg2("");
392 msg2.Printf(" at $%lX, size %d", (long)GetActualData(), (int)RequestSize());
393 msg += msg2;
394
395 wxLogDebug(msg);
c801d85f
KB
396 }
397 else
398 {
184b5d99 399 wxString msg("");
c801d85f 400 if (m_fileName)
184b5d99
JS
401 msg.Printf("%s(%d): ", m_fileName, (int)m_lineNum);
402
403 wxString msg2("");
404 msg2.Printf("non-object data at $%lX, size %d", (long)GetActualData(), (int)RequestSize() );
405 msg += msg2;
406 wxLogDebug(msg);
c801d85f
KB
407 }
408}
409
410
411/*
412 Validate a node. Check to see that the node is "clean" in the sense
413 that nothing has over/underwritten it etc.
414*/
415int wxMemStruct::ValidateNode ()
416{
417 char * startPointer = (char *) this;
418 if (!AssertIt ()) {
419 if (IsDeleted ())
420 ErrorMsg ("Object already deleted");
421 else {
422 // Can't use the error routines as we have no recognisable object.
bd7d06f2 423#ifndef __WXGTK__
184b5d99 424 wxLogDebug("Can't verify memory struct - all bets are off!");
bd7d06f2 425#endif
c801d85f
KB
426 }
427 return 0;
428 }
429
430/*
431 int i;
432 for (i = 0; i < wxDebugContext::TotSize (requestSize ()); i++)
433 cout << startPointer [i];
434 cout << endl;
435*/
436 if (Marker () != MemStartCheck)
437 ErrorMsg ();
438 if (* (wxMarkerType *) wxDebugContext::MidMarkerPos (startPointer) != MemMidCheck)
439 ErrorMsg ();
440 if (* (wxMarkerType *) wxDebugContext::EndMarkerPos (startPointer,
441 RequestSize ()) !=
442 MemEndCheck)
443 ErrorMsg ();
444
445 // Back to before the extra buffer and check that
446 // we can still read what we originally wrote.
447 if (Marker () != MemStartCheck ||
448 * (wxMarkerType *) wxDebugContext::MidMarkerPos (startPointer)
449 != MemMidCheck ||
450 * (wxMarkerType *) wxDebugContext::EndMarkerPos (startPointer,
451 RequestSize ()) != MemEndCheck)
452 {
453 ErrorMsg ();
454 return 0;
455 }
456
457 return 1;
458}
459
460/*
461 The wxDebugContext class.
462*/
463
464wxMemStruct *wxDebugContext::m_head = NULL;
465wxMemStruct *wxDebugContext::m_tail = NULL;
466// ostream *wxDebugContext::m_debugStream = NULL;
467// streambuf *wxDebugContext::m_streamBuf = NULL;
468
469// Must initialise these in wxEntry, and then delete them just before wxEntry exits
470streambuf *wxDebugContext::m_streamBuf = NULL;
471ostream *wxDebugContext::m_debugStream = NULL;
472
473bool wxDebugContext::m_checkPrevious = FALSE;
474int wxDebugContext::debugLevel = 1;
475bool wxDebugContext::debugOn = TRUE;
476wxMemStruct *wxDebugContext::checkPoint = NULL;
477
478wxDebugContext::wxDebugContext(void)
479{
480// m_streamBuf = new wxDebugStreamBuf;
481// m_debugStream = new ostream(m_streamBuf);
482}
483
484wxDebugContext::~wxDebugContext(void)
485{
486 SetStream(NULL, NULL);
487}
488
489/*
490 * It's bizarre, but with BC++ 4.5, the value of str changes
491 * between SetFile and SetStream.
492 */
493
494void wxDebugContext::SetStream(ostream *str, streambuf *buf)
495{
c801d85f
KB
496 if (m_debugStream)
497 {
498 m_debugStream->flush();
499 delete m_debugStream;
500 }
501 m_debugStream = NULL;
502
503 // Not allowed in Watcom (~streambuf is protected).
504 // Is this trying to say something significant to us??
505#ifndef __WATCOMC__
506 if (m_streamBuf)
507 {
508 streambuf* oldBuf = m_streamBuf;
509 m_streamBuf = NULL;
510 delete oldBuf;
511 }
512#endif
513 m_streamBuf = buf;
514 m_debugStream = str;
515}
516
517bool wxDebugContext::SetFile(const wxString& file)
518{
519 ofstream *str = new ofstream((char *) (const char *)file);
520
521 if (str->bad())
522 {
523 delete str;
524 return FALSE;
525 }
526 else
527 {
c801d85f
KB
528 SetStream(str);
529 return TRUE;
530 }
531}
532
533bool wxDebugContext::SetStandardError(void)
534{
535#if !defined(_WINDLL)
536 wxDebugStreamBuf *buf = new wxDebugStreamBuf;
537 ostream *stream = new ostream(m_streamBuf);
538 SetStream(stream, buf);
539 return TRUE;
540#else
541 return FALSE;
542#endif
543}
544
545
546/*
547 Work out the positions of the markers by creating an array of 2 markers
548 and comparing the addresses of the 2 elements. Use this number as the
549 alignment for markers.
550*/
551size_t wxDebugContext::CalcAlignment ()
552{
553 wxMarkerType ar[2];
554 return (char *) &ar[1] - (char *) &ar[0];
555}
556
557
558char * wxDebugContext::StructPos (const char * buf)
559{
560 return (char *) buf;
561}
562
563char * wxDebugContext::MidMarkerPos (const char * buf)
564{
565 return StructPos (buf) + PaddedSize (sizeof (wxMemStruct));
566}
567
568char * wxDebugContext::CallerMemPos (const char * buf)
569{
570 return MidMarkerPos (buf) + PaddedSize (sizeof(wxMarkerType));
571}
572
573
574char * wxDebugContext::EndMarkerPos (const char * buf, const size_t size)
575{
576 return CallerMemPos (buf) + PaddedSize (size);
577}
578
579
580/*
581 Slightly different as this takes a pointer to the start of the caller
582 requested region and returns a pointer to the start of the buffer.
583 */
584char * wxDebugContext::StartPos (const char * caller)
585{
586 return ((char *) (caller - wxDebugContext::PaddedSize (sizeof(wxMarkerType)) -
587 wxDebugContext::PaddedSize (sizeof (wxMemStruct))));
588}
589
590/*
591 We may need padding between various parts of the allocated memory.
592 Given a size of memory, this returns the amount of memory which should
593 be allocated in order to allow for alignment of the following object.
594
595 I don't know how portable this stuff is, but it seems to work for me at
596 the moment. It would be real nice if I knew more about this!
597*/
598size_t wxDebugContext::GetPadding (const size_t size)
599{
600 size_t pad = size % CalcAlignment ();
601 return (pad) ? sizeof(wxMarkerType) - pad : 0;
602}
603
604
605
606size_t wxDebugContext::PaddedSize (const size_t size)
607{
608 return size + GetPadding (size);
609}
610
611/*
612 Returns the total amount of memory which we need to get from the system
613 in order to satisfy a caller request. This includes space for the struct
614 plus markers and the caller's memory as well.
615*/
616size_t wxDebugContext::TotSize (const size_t reqSize)
617{
618 return (PaddedSize (sizeof (wxMemStruct)) + PaddedSize (reqSize) +
619 2 * sizeof(wxMarkerType));
620}
621
622
623/*
624 Traverse the list of nodes executing the given function on each node.
625*/
626void wxDebugContext::TraverseList (PmSFV func, wxMemStruct *from)
627{
628 if (!from)
629 from = wxDebugContext::GetHead ();
630
631 for (wxMemStruct * st = from; st != 0; st = st->m_next)
632 {
633 void* data = st->GetActualData();
184b5d99
JS
634// if ((data != (void*)m_debugStream) && (data != (void*) m_streamBuf))
635 if (data != (void*) wxLog::GetActiveTarget())
c801d85f
KB
636 {
637 (st->*func) ();
638 }
639 }
640}
641
642
643/*
644 Print out the list.
645 */
646bool wxDebugContext::PrintList (void)
647{
ea57084d 648#ifdef __WXDEBUG__
184b5d99
JS
649// if (!HasStream())
650// return FALSE;
c801d85f 651
bd7d06f2 652 TraverseList ((PmSFV)&wxMemStruct::PrintNode, (checkPoint ? checkPoint->m_next : (wxMemStruct*)NULL));
c801d85f
KB
653
654 return TRUE;
655#else
656 return FALSE;
657#endif
658}
659
660bool wxDebugContext::Dump(void)
661{
ea57084d 662#ifdef __WXDEBUG__
184b5d99
JS
663// if (!HasStream())
664// return FALSE;
c801d85f
KB
665
666 if (TRUE)
667 {
668 char* appName = "application";
669 wxString appNameStr("");
670 if (wxTheApp)
671 {
672 appNameStr = wxTheApp->GetAppName();
673 appName = (char*) (const char*) appNameStr;
184b5d99 674 wxLogDebug("----- Memory dump of %s at %s -----", appName, WXSTRINGCAST wxNow() );
e55ad60e
RR
675 }
676 else
677 {
184b5d99 678 wxLogDebug( "----- Memory dump -----" );
c801d85f
KB
679 }
680 }
bd7d06f2 681 TraverseList ((PmSFV)&wxMemStruct::Dump, (checkPoint ? checkPoint->m_next : (wxMemStruct*)NULL));
e55ad60e 682
184b5d99
JS
683 wxLogDebug( "" );
684 wxLogDebug( "" );
c801d85f
KB
685
686 return TRUE;
687#else
688 return FALSE;
689#endif
690}
691
692struct wxDebugStatsStruct
693{
694 long instanceCount;
695 long totalSize;
696 char *instanceClass;
697 wxDebugStatsStruct *next;
698};
699
700static wxDebugStatsStruct *FindStatsStruct(wxDebugStatsStruct *st, char *name)
701{
702 while (st)
703 {
704 if (strcmp(st->instanceClass, name) == 0)
705 return st;
706 st = st->next;
707 }
708 return NULL;
709}
710
711static wxDebugStatsStruct *InsertStatsStruct(wxDebugStatsStruct *head, wxDebugStatsStruct *st)
712{
713 st->next = head;
714 return st;
715}
716
717bool wxDebugContext::PrintStatistics(bool detailed)
718{
ea57084d 719#ifdef __WXDEBUG__
184b5d99
JS
720// if (!HasStream())
721// return FALSE;
c801d85f 722
e55ad60e
RR
723 if (TRUE)
724 {
725 char* appName = "application";
726 wxString appNameStr("");
727 if (wxTheApp)
728 {
729 appNameStr = wxTheApp->GetAppName();
730 appName = (char*) (const char*) appNameStr;
184b5d99 731 wxLogDebug("----- Memory statistics of %s at %s -----", appName, WXSTRINGCAST wxNow() );
e55ad60e
RR
732 }
733 else
734 {
184b5d99 735 wxLogDebug( "----- Memory statistics -----" );
e55ad60e
RR
736 }
737 }
738
c801d85f
KB
739 bool currentMode = GetDebugMode();
740 SetDebugMode(FALSE);
741
742 long noNonObjectNodes = 0;
743 long noObjectNodes = 0;
744 long totalSize = 0;
745
746 wxDebugStatsStruct *list = NULL;
747
bd7d06f2 748 wxMemStruct *from = (checkPoint ? checkPoint->m_next : (wxMemStruct*)NULL );
c801d85f
KB
749 if (!from)
750 from = wxDebugContext::GetHead ();
751
752 wxMemStruct *st;
753 for (st = from; st != 0; st = st->m_next)
754 {
755 void* data = st->GetActualData();
184b5d99
JS
756// if (detailed && (data != (void*)m_debugStream) && (data != (void*) m_streamBuf))
757 if (detailed && (data != (void*) wxLog::GetActiveTarget()))
c801d85f
KB
758 {
759 char *className = "nonobject";
760 if (st->m_isObject && st->GetActualData())
761 {
762 wxObject *obj = (wxObject *)st->GetActualData();
763 if (obj->GetClassInfo()->GetClassName())
764 className = obj->GetClassInfo()->GetClassName();
765 }
766 wxDebugStatsStruct *stats = FindStatsStruct(list, className);
767 if (!stats)
768 {
769 stats = (wxDebugStatsStruct *)malloc(sizeof(wxDebugStatsStruct));
770 stats->instanceClass = className;
771 stats->instanceCount = 0;
772 stats->totalSize = 0;
773 list = InsertStatsStruct(list, stats);
774 }
775 stats->instanceCount ++;
776 stats->totalSize += st->RequestSize();
777 }
778
184b5d99
JS
779// if ((data != (void*)m_debugStream) && (data != (void*) m_streamBuf))
780 if (data != (void*) wxLog::GetActiveTarget())
c801d85f
KB
781 {
782 totalSize += st->RequestSize();
783 if (st->m_isObject)
784 noObjectNodes ++;
785 else
786 noNonObjectNodes ++;
787 }
788 }
789
790 if (detailed)
791 {
792 while (list)
793 {
184b5d99 794 wxLogDebug("%ld objects of class %s, total size %ld",
c801d85f
KB
795 list->instanceCount, list->instanceClass, list->totalSize);
796 wxDebugStatsStruct *old = list;
797 list = old->next;
798 free((char *)old);
799 }
184b5d99 800 wxLogDebug("");
c801d85f
KB
801 }
802
803 SetDebugMode(currentMode);
804
184b5d99
JS
805 wxLogDebug("Number of object items: %ld", noObjectNodes);
806 wxLogDebug("Number of non-object items: %ld", noNonObjectNodes);
807 wxLogDebug("Total allocated size: %ld", totalSize);
808 wxLogDebug("");
809 wxLogDebug("");
c801d85f
KB
810
811 return TRUE;
812#else
813 return FALSE;
814#endif
815}
816
817bool wxDebugContext::PrintClasses(void)
818{
184b5d99
JS
819// if (!HasStream())
820// return FALSE;
c801d85f
KB
821
822 if (TRUE)
823 {
824 char* appName = "application";
825 wxString appNameStr("");
826 if (wxTheApp)
827 {
828 appNameStr = wxTheApp->GetAppName();
829 appName = (char*) (const char*) appNameStr;
184b5d99 830 wxLogDebug("----- Classes in %s -----", appName);
c801d85f
KB
831 }
832 }
833
834 int n = 0;
f4a8c29f
GL
835 wxNode *node;
836 wxClassInfo *info;
837
0c32066b
JS
838 wxClassInfo::sm_classTable->BeginFind();
839 node = wxClassInfo::sm_classTable->Next();
f4a8c29f 840 while (node)
c801d85f 841 {
f4a8c29f 842 info = (wxClassInfo *)node->Data();
c801d85f
KB
843 if (info->GetClassName())
844 {
184b5d99
JS
845 wxString msg(info->GetClassName());
846 msg += " ";
847
848 if (info->GetBaseClassName1() && !info->GetBaseClassName2())
849 {
850 msg += "is a ";
851 msg += info->GetBaseClassName1();
852 }
853 else if (info->GetBaseClassName1() && info->GetBaseClassName2())
854 {
855 msg += "is a ";
856 msg += info->GetBaseClassName1() ;
857 msg += ", ";
858 msg += info->GetBaseClassName2() ;
859 }
860 if (info->GetConstructor())
861 msg += ": dynamic";
862
863 wxLogDebug(msg);
c801d85f 864 }
e55ad60e 865 node = wxClassInfo::sm_classTable->Next();
c801d85f
KB
866 n ++;
867 }
184b5d99
JS
868 wxLogDebug("");
869 wxLogDebug("There are %d classes derived from wxObject.", n);
870 wxLogDebug("");
871 wxLogDebug("");
c801d85f
KB
872 return TRUE;
873}
874
875void wxDebugContext::SetCheckpoint(bool all)
876{
877 if (all)
878 checkPoint = NULL;
879 else
880 checkPoint = m_tail;
881}
882
883// Checks all nodes since checkpoint, or since start.
884int wxDebugContext::Check(bool checkAll)
885{
886 int nFailures = 0;
887
bd7d06f2 888 wxMemStruct *from = (checkPoint ? checkPoint->m_next : (wxMemStruct*)NULL );
c801d85f
KB
889 if (!from || checkAll)
890 from = wxDebugContext::GetHead ();
891
892 for (wxMemStruct * st = from; st != 0; st = st->m_next)
893 {
894 if (st->AssertIt ())
895 nFailures += st->CheckBlock ();
896 else
897 return -1;
898 }
899
900 return nFailures;
901}
902
903// Count the number of non-wxDebugContext-related objects
904// that are outstanding
4fabb575 905int wxDebugContext::CountObjectsLeft(bool sinceCheckpoint)
c801d85f
KB
906{
907 int n = 0;
4fabb575
JS
908
909 wxMemStruct *from = NULL;
910 if (sinceCheckpoint && checkPoint)
911 from = checkPoint->m_next;
912 if (from == (wxMemStruct*) NULL)
913 from = wxDebugContext::GetHead () ;
c801d85f
KB
914
915 for (wxMemStruct * st = from; st != 0; st = st->m_next)
916 {
917 void* data = st->GetActualData();
184b5d99
JS
918// if ((data != (void*)m_debugStream) && (data != (void*) m_streamBuf))
919 if (data != (void*) wxLog::GetActiveTarget())
c801d85f
KB
920 n ++;
921 }
922
923 return n ;
924}
925
926/*
927 The global operator new used for everything apart from getting
928 dynamic storage within this function itself.
929*/
930
931// We'll only do malloc and free for the moment: leave the interesting
932// stuff for the wxObject versions.
933
ea57084d 934#if defined(__WXDEBUG__) && wxUSE_GLOBAL_MEMORY_OPERATORS
c801d85f
KB
935
936#ifdef new
937#undef new
938#endif
939
940// Seems OK all of a sudden. Maybe to do with linking with multithreaded library?
941#if 0 // def _MSC_VER
942#define NO_DEBUG_ALLOCATION
943#endif
944
945// Unfortunately ~wxDebugStreamBuf doesn't work (VC++ 5) when we enable the debugging
946// code. I have no idea why. In BC++ 4.5, we have a similar problem the debug
947// stream myseriously changing pointer address between being passed from SetFile to SetStream.
948// See docs/msw/issues.txt.
949void * operator new (size_t size, char * fileName, int lineNum)
950{
951#ifdef NO_DEBUG_ALLOCATION
952 return malloc(size);
953#else
954 return wxDebugAlloc(size, fileName, lineNum, FALSE, FALSE);
955#endif
956}
957
7fe7d506
JS
958// Added JACS 25/11/98
959void * operator new (size_t size)
960{
961#ifdef NO_DEBUG_ALLOCATION
962 return malloc(size);
963#else
964 return wxDebugAlloc(size, NULL, 0, FALSE);
965#endif
966}
967
968void * operator new[] (size_t size)
969{
970#ifdef NO_DEBUG_ALLOCATION
971 return malloc(size);
972#else
973 return wxDebugAlloc(size, NULL, 0, FALSE, TRUE);
974#endif
975}
976
16c1f7f3 977#if !( defined (_MSC_VER) && (_MSC_VER <= 1020) )
c801d85f
KB
978void * operator new[] (size_t size, char * fileName, int lineNum)
979{
980#ifdef NO_DEBUG_ALLOCATION
981 return malloc(size);
982#else
983 return wxDebugAlloc(size, fileName, lineNum, FALSE, TRUE);
984#endif
985}
5260b1c5 986#endif
c801d85f
KB
987
988void operator delete (void * buf)
989{
990#ifdef NO_DEBUG_ALLOCATION
991 free((char*) buf);
992#else
993 wxDebugFree(buf);
994#endif
995}
996
76626af2
JS
997// VC++ 6.0
998#if _MSC_VER >= 1200
999void operator delete(void* pData, char* /* fileName */, int /* lineNum */)
1000{
184b5d99
JS
1001// ::operator delete(pData);
1002 // JACS 21/11/1998: surely we need to call wxDebugFree?
1003 wxDebugFree(pData, FALSE);
1004}
1005// New operator 21/11/1998
1006void operator delete[](void* pData, char* /* fileName */, int /* lineNum */)
1007{
1008 wxDebugFree(pData, TRUE);
76626af2
JS
1009}
1010#endif
1011
16c1f7f3 1012#if !( defined (_MSC_VER) && (_MSC_VER <= 1020) )
0f358732 1013
c801d85f
KB
1014void operator delete[] (void * buf)
1015{
1016#ifdef NO_DEBUG_ALLOCATION
1017 free((char*) buf);
1018#else
1019 wxDebugFree(buf, TRUE);
1020#endif
1021}
5260b1c5 1022#endif
c801d85f
KB
1023
1024#endif
1025
1026// TODO: store whether this is a vector or not.
bd7d06f2 1027void * wxDebugAlloc(size_t size, char * fileName, int lineNum, bool isObject, bool WXUNUSED(isVect) )
c801d85f
KB
1028{
1029 // If not in debugging allocation mode, do the normal thing
1030 // so we don't leave any trace of ourselves in the node list.
1031
1032 if (!wxDebugContext::GetDebugMode())
1033 {
1034 return (void *)malloc(size);
1035 }
1036
1037 char * buf = (char *) malloc(wxDebugContext::TotSize (size));
1038 if (!buf) {
184b5d99 1039 wxLogDebug("Call to malloc (%ld) failed.", (long)size);
c801d85f
KB
1040 return 0;
1041 }
1042 wxMemStruct * st = (wxMemStruct *)buf;
1043 st->m_firstMarker = MemStartCheck;
1044 st->m_reqSize = size;
1045 st->m_fileName = fileName;
1046 st->m_lineNum = lineNum;
1047 st->m_id = MemStructId;
1048 st->m_prev = 0;
1049 st->m_next = 0;
1050 st->m_isObject = isObject;
1051
1052 // Errors from Append() shouldn't really happen - but just in case!
1053 if (st->Append () == 0) {
1054 st->ErrorMsg ("Trying to append new node");
1055 }
1056
1057 if (wxDebugContext::GetCheckPrevious ()) {
1058 if (st->CheckAllPrevious () < 0) {
1059 st->ErrorMsg ("Checking previous nodes");
1060 }
1061 }
1062
1063 // Set up the extra markers at the middle and end.
1064 char * ptr = wxDebugContext::MidMarkerPos (buf);
1065 * (wxMarkerType *) ptr = MemMidCheck;
1066 ptr = wxDebugContext::EndMarkerPos (buf, size);
1067 * (wxMarkerType *) ptr = MemEndCheck;
1068
1069 // pointer returned points to the start of the caller's
1070 // usable area.
1071 void *m_actualData = (void *) wxDebugContext::CallerMemPos (buf);
1072 st->m_actualData = m_actualData;
1073
1074 return m_actualData;
1075}
1076
1077// TODO: check whether was allocated as a vector
bd7d06f2 1078void wxDebugFree(void * buf, bool WXUNUSED(isVect) )
c801d85f
KB
1079{
1080 if (!buf)
1081 return;
1082
1083 // If not in debugging allocation mode, do the normal thing
1084 // so we don't leave any trace of ourselves in the node list.
1085 if (!wxDebugContext::GetDebugMode())
1086 {
1087 free((char *)buf);
1088 return;
1089 }
1090
1091 // Points to the start of the entire allocated area.
1092 char * startPointer = wxDebugContext::StartPos ((char *) buf);
1093 // Find the struct and make sure that it's identifiable.
1094 wxMemStruct * st = (wxMemStruct *) wxDebugContext::StructPos (startPointer);
1095
1096 if (! st->ValidateNode ())
1097 return;
1098
1099 // If this is the current checkpoint, we need to
1100 // move the checkpoint back so it points to a valid
1101 // node.
1102 if (st == wxDebugContext::checkPoint)
1103 wxDebugContext::checkPoint = wxDebugContext::checkPoint->m_prev;
1104
1105 if (! st->Unlink ())
1106 {
1107 st->ErrorMsg ("Unlinking deleted node");
1108 }
1109
1110 // Now put in the fill char into the id slot and the caller requested
1111 // memory locations.
1112 st->SetDeleted ();
1113 (void) memset (wxDebugContext::CallerMemPos (startPointer), MemFillChar,
1114 st->RequestSize ());
1115
1116 // Don't allow delayed freeing of memory in this version
1117// if (!wxDebugContext::GetDelayFree())
1118// free((void *)st);
1119 free((char *)st);
1120}
1121
1122// Trace: send output to the current debugging stream
1123void wxTrace(const char *fmt ...)
1124{
1125 va_list ap;
1126 static char buffer[512];
1127
1128 va_start(ap, fmt);
1129
2049ba38 1130#ifdef __WXMSW__
c801d85f
KB
1131 wvsprintf(buffer,fmt,ap) ;
1132#else
1133 vsprintf(buffer,fmt,ap) ;
1134#endif
1135
1136 va_end(ap);
1137
1138 if (wxDebugContext::HasStream())
1139 {
1140 wxDebugContext::GetStream() << buffer;
1141 wxDebugContext::GetStream().flush();
1142 }
1143 else
2049ba38 1144#ifdef __WXMSW__
c801d85f
KB
1145 OutputDebugString((LPCSTR)buffer) ;
1146#else
1147 fprintf(stderr, buffer);
1148#endif
1149}
1150
1151// Trace with level
1152void wxTraceLevel(int level, const char *fmt ...)
1153{
1154 if (wxDebugContext::GetLevel() < level)
1155 return;
1156
1157 va_list ap;
1158 static char buffer[512];
1159
1160 va_start(ap, fmt);
1161
2049ba38 1162#ifdef __WXMSW__
c801d85f
KB
1163 wvsprintf(buffer,fmt,ap) ;
1164#else
1165 vsprintf(buffer,fmt,ap) ;
1166#endif
1167
1168 va_end(ap);
1169
1170 if (wxDebugContext::HasStream())
1171 {
1172 wxDebugContext::GetStream() << buffer;
1173 wxDebugContext::GetStream().flush();
1174 }
1175 else
2049ba38 1176#ifdef __WXMSW__
c801d85f
KB
1177 OutputDebugString((LPCSTR)buffer) ;
1178#else
1179 fprintf(stderr, buffer);
1180#endif
1181}
1182
ea57084d 1183#else // wxUSE_MEMORY_TRACING && defined(__WXDEBUG__)
c801d85f
KB
1184void wxTrace(const char *WXUNUSED(fmt) ...)
1185{
1186}
1187
1188void wxTraceLevel(int WXUNUSED(level), const char *WXUNUSED(fmt) ...)
1189{
1190}
1191#endif
1192