]> git.saurik.com Git - wxWidgets.git/blame - src/common/memory.cpp
Resize fine tuning
[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
905int wxDebugContext::CountObjectsLeft(void)
906{
907 int n = 0;
908
909 wxMemStruct *from = wxDebugContext::GetHead ();
910
911 for (wxMemStruct * st = from; st != 0; st = st->m_next)
912 {
913 void* data = st->GetActualData();
184b5d99
JS
914// if ((data != (void*)m_debugStream) && (data != (void*) m_streamBuf))
915 if (data != (void*) wxLog::GetActiveTarget())
c801d85f
KB
916 n ++;
917 }
918
919 return n ;
920}
921
922/*
923 The global operator new used for everything apart from getting
924 dynamic storage within this function itself.
925*/
926
927// We'll only do malloc and free for the moment: leave the interesting
928// stuff for the wxObject versions.
929
ea57084d 930#if defined(__WXDEBUG__) && wxUSE_GLOBAL_MEMORY_OPERATORS
c801d85f
KB
931
932#ifdef new
933#undef new
934#endif
935
936// Seems OK all of a sudden. Maybe to do with linking with multithreaded library?
937#if 0 // def _MSC_VER
938#define NO_DEBUG_ALLOCATION
939#endif
940
941// Unfortunately ~wxDebugStreamBuf doesn't work (VC++ 5) when we enable the debugging
942// code. I have no idea why. In BC++ 4.5, we have a similar problem the debug
943// stream myseriously changing pointer address between being passed from SetFile to SetStream.
944// See docs/msw/issues.txt.
945void * operator new (size_t size, char * fileName, int lineNum)
946{
947#ifdef NO_DEBUG_ALLOCATION
948 return malloc(size);
949#else
950 return wxDebugAlloc(size, fileName, lineNum, FALSE, FALSE);
951#endif
952}
953
16c1f7f3 954#if !( defined (_MSC_VER) && (_MSC_VER <= 1020) )
c801d85f
KB
955void * operator new[] (size_t size, char * fileName, int lineNum)
956{
957#ifdef NO_DEBUG_ALLOCATION
958 return malloc(size);
959#else
960 return wxDebugAlloc(size, fileName, lineNum, FALSE, TRUE);
961#endif
962}
5260b1c5 963#endif
c801d85f
KB
964
965void operator delete (void * buf)
966{
967#ifdef NO_DEBUG_ALLOCATION
968 free((char*) buf);
969#else
970 wxDebugFree(buf);
971#endif
972}
973
76626af2
JS
974// VC++ 6.0
975#if _MSC_VER >= 1200
976void operator delete(void* pData, char* /* fileName */, int /* lineNum */)
977{
184b5d99
JS
978// ::operator delete(pData);
979 // JACS 21/11/1998: surely we need to call wxDebugFree?
980 wxDebugFree(pData, FALSE);
981}
982// New operator 21/11/1998
983void operator delete[](void* pData, char* /* fileName */, int /* lineNum */)
984{
985 wxDebugFree(pData, TRUE);
76626af2
JS
986}
987#endif
988
16c1f7f3 989#if !( defined (_MSC_VER) && (_MSC_VER <= 1020) )
0f358732 990
c801d85f
KB
991void operator delete[] (void * buf)
992{
993#ifdef NO_DEBUG_ALLOCATION
994 free((char*) buf);
995#else
996 wxDebugFree(buf, TRUE);
997#endif
998}
5260b1c5 999#endif
c801d85f
KB
1000
1001#endif
1002
1003// TODO: store whether this is a vector or not.
bd7d06f2 1004void * wxDebugAlloc(size_t size, char * fileName, int lineNum, bool isObject, bool WXUNUSED(isVect) )
c801d85f
KB
1005{
1006 // If not in debugging allocation mode, do the normal thing
1007 // so we don't leave any trace of ourselves in the node list.
1008
1009 if (!wxDebugContext::GetDebugMode())
1010 {
1011 return (void *)malloc(size);
1012 }
1013
1014 char * buf = (char *) malloc(wxDebugContext::TotSize (size));
1015 if (!buf) {
184b5d99 1016 wxLogDebug("Call to malloc (%ld) failed.", (long)size);
c801d85f
KB
1017 return 0;
1018 }
1019 wxMemStruct * st = (wxMemStruct *)buf;
1020 st->m_firstMarker = MemStartCheck;
1021 st->m_reqSize = size;
1022 st->m_fileName = fileName;
1023 st->m_lineNum = lineNum;
1024 st->m_id = MemStructId;
1025 st->m_prev = 0;
1026 st->m_next = 0;
1027 st->m_isObject = isObject;
1028
1029 // Errors from Append() shouldn't really happen - but just in case!
1030 if (st->Append () == 0) {
1031 st->ErrorMsg ("Trying to append new node");
1032 }
1033
1034 if (wxDebugContext::GetCheckPrevious ()) {
1035 if (st->CheckAllPrevious () < 0) {
1036 st->ErrorMsg ("Checking previous nodes");
1037 }
1038 }
1039
1040 // Set up the extra markers at the middle and end.
1041 char * ptr = wxDebugContext::MidMarkerPos (buf);
1042 * (wxMarkerType *) ptr = MemMidCheck;
1043 ptr = wxDebugContext::EndMarkerPos (buf, size);
1044 * (wxMarkerType *) ptr = MemEndCheck;
1045
1046 // pointer returned points to the start of the caller's
1047 // usable area.
1048 void *m_actualData = (void *) wxDebugContext::CallerMemPos (buf);
1049 st->m_actualData = m_actualData;
1050
1051 return m_actualData;
1052}
1053
1054// TODO: check whether was allocated as a vector
bd7d06f2 1055void wxDebugFree(void * buf, bool WXUNUSED(isVect) )
c801d85f
KB
1056{
1057 if (!buf)
1058 return;
1059
1060 // If not in debugging allocation mode, do the normal thing
1061 // so we don't leave any trace of ourselves in the node list.
1062 if (!wxDebugContext::GetDebugMode())
1063 {
1064 free((char *)buf);
1065 return;
1066 }
1067
1068 // Points to the start of the entire allocated area.
1069 char * startPointer = wxDebugContext::StartPos ((char *) buf);
1070 // Find the struct and make sure that it's identifiable.
1071 wxMemStruct * st = (wxMemStruct *) wxDebugContext::StructPos (startPointer);
1072
1073 if (! st->ValidateNode ())
1074 return;
1075
1076 // If this is the current checkpoint, we need to
1077 // move the checkpoint back so it points to a valid
1078 // node.
1079 if (st == wxDebugContext::checkPoint)
1080 wxDebugContext::checkPoint = wxDebugContext::checkPoint->m_prev;
1081
1082 if (! st->Unlink ())
1083 {
1084 st->ErrorMsg ("Unlinking deleted node");
1085 }
1086
1087 // Now put in the fill char into the id slot and the caller requested
1088 // memory locations.
1089 st->SetDeleted ();
1090 (void) memset (wxDebugContext::CallerMemPos (startPointer), MemFillChar,
1091 st->RequestSize ());
1092
1093 // Don't allow delayed freeing of memory in this version
1094// if (!wxDebugContext::GetDelayFree())
1095// free((void *)st);
1096 free((char *)st);
1097}
1098
1099// Trace: send output to the current debugging stream
1100void wxTrace(const char *fmt ...)
1101{
1102 va_list ap;
1103 static char buffer[512];
1104
1105 va_start(ap, fmt);
1106
2049ba38 1107#ifdef __WXMSW__
c801d85f
KB
1108 wvsprintf(buffer,fmt,ap) ;
1109#else
1110 vsprintf(buffer,fmt,ap) ;
1111#endif
1112
1113 va_end(ap);
1114
1115 if (wxDebugContext::HasStream())
1116 {
1117 wxDebugContext::GetStream() << buffer;
1118 wxDebugContext::GetStream().flush();
1119 }
1120 else
2049ba38 1121#ifdef __WXMSW__
c801d85f
KB
1122 OutputDebugString((LPCSTR)buffer) ;
1123#else
1124 fprintf(stderr, buffer);
1125#endif
1126}
1127
1128// Trace with level
1129void wxTraceLevel(int level, const char *fmt ...)
1130{
1131 if (wxDebugContext::GetLevel() < level)
1132 return;
1133
1134 va_list ap;
1135 static char buffer[512];
1136
1137 va_start(ap, fmt);
1138
2049ba38 1139#ifdef __WXMSW__
c801d85f
KB
1140 wvsprintf(buffer,fmt,ap) ;
1141#else
1142 vsprintf(buffer,fmt,ap) ;
1143#endif
1144
1145 va_end(ap);
1146
1147 if (wxDebugContext::HasStream())
1148 {
1149 wxDebugContext::GetStream() << buffer;
1150 wxDebugContext::GetStream().flush();
1151 }
1152 else
2049ba38 1153#ifdef __WXMSW__
c801d85f
KB
1154 OutputDebugString((LPCSTR)buffer) ;
1155#else
1156 fprintf(stderr, buffer);
1157#endif
1158}
1159
ea57084d 1160#else // wxUSE_MEMORY_TRACING && defined(__WXDEBUG__)
c801d85f
KB
1161void wxTrace(const char *WXUNUSED(fmt) ...)
1162{
1163}
1164
1165void wxTraceLevel(int WXUNUSED(level), const char *WXUNUSED(fmt) ...)
1166{
1167}
1168#endif
1169