summaryrefslogtreecommitdiffstats
path: root/Tools/MemDumpAnalysis/MemDumpAnalysis.cpp
blob: 9faaef20f22f1cfd4106cdf97bd64d4198e5e349 (plain) (blame)
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

// MemDumpAnalysis.cpp

// Defines the entry point for the console application.

#include "Globals.h"

#ifdef _WIN32
	#pragma comment(lib, "ws2_32.lib")  // Needed for StringUtils' RawBEToUtf8() et al.
#endif  // _WIN32





typedef std::set<AString> AStringSet;





class cFunction
{
public:
	int        m_Size;   ///< Sum of memory block sizes allocated by this function or its children
	int        m_Count;  ///< Total number of memory blocks allocated by this function or its children
	AStringSet m_ChildrenNames;
	
	cFunction(void) :
		m_Size(0),
		m_Count(0)
	{
	}
} ;

typedef std::map<AString, cFunction> FunctionMap;





int g_CurrentID = 0;
int g_CurrentSize = 0;
FunctionMap g_FnMap;
AString g_PrevFunctionName;





bool IsFnBlackListed(const char * a_FnName)
{
	static const char * BlackList[] =
	{
		"MyAllocHook",
		"_heap_alloc_dbg_impl",
		"_nh_malloc_dbg_impl",
		"_nh_malloc_dbg",
		"malloc",
		"operator new",
		"_malloc_dbg",
		"realloc_help",
		"_realloc_dbg",
		"realloc",
		"l_alloc",
		"luaM_realloc_",
		"",
	} ;
	
	for (int i = 0; i < ARRAYCOUNT(BlackList); i++)
	{
		if (strcmp(BlackList[i], a_FnName) == 0)
		{
			return true;
		}
	}
	return false;
}





const char * FindAttr(const char ** a_Attrs, const char * a_AttrName)
{
	for (const char ** Attr = a_Attrs; *Attr != NULL; Attr += 2)
	{
		if (strcmp(*Attr, a_AttrName) == 0)
		{
			return *(Attr + 1);
		}
	}  // for Attr - a_Attrs[]
	return NULL;
}





void OnStartElement(void * a_Data, const char * a_Element, const char ** a_Attrs)
{
	if (strcmp(a_Element, "LEAK") == 0)
	{
		const char * attrID   = FindAttr(a_Attrs, "requestID");
		const char * attrSize = FindAttr(a_Attrs, "size");
		g_CurrentID   = atoi((attrID   == NULL) ? "-1" : attrID);
		g_CurrentSize = atoi((attrSize == NULL) ? "-1" : attrSize);
		g_PrevFunctionName.clear();
		return;
	}
	if (strcmp(a_Element, "STACKENTRY") == 0)
	{
		const char * fnName = FindAttr(a_Attrs, "decl");
		if (fnName == NULL)
		{
			g_CurrentID = -1;
			g_CurrentSize = -1;
			return;
		}
		if (g_CurrentSize < 0)
		{
			return;
		}
		if (IsFnBlackListed(fnName))
		{
			return;
		}
		AString FunctionName = fnName;
		cFunction & Function = g_FnMap[FunctionName];
		Function.m_Size += g_CurrentSize;
		Function.m_Count += 1;
		if (!g_PrevFunctionName.empty())
		{
			Function.m_ChildrenNames.insert(g_PrevFunctionName);
		}
		std::swap(g_PrevFunctionName, FunctionName);  // We only care about moving FunctionName into g_PrevFunctionName
		return;
	}
}





void OnEndElement(void * a_Data, const char * a_Element)
{
	if (strcmp(a_Element, "LEAK") == 0)
	{
		g_CurrentID = -1;
		g_CurrentSize = -1;
		return;
	}
}





bool CompareFnInt(const std::pair<AString, int> & a_First, const std::pair<AString, int> & a_Second)
{
	return (a_First.second < a_Second.second);
}





void WriteSizeStatistics(void)
{
	typedef std::vector<std::pair<AString, int> > StringIntPairs;
	StringIntPairs FnSizes;
	
	cFile f("memdump_totals.txt", cFile::fmWrite);
	if (!f.IsOpen())
	{
		LOGERROR("Cannot open memdump_totals.txt");
		return;
	}

	for (FunctionMap::iterator itr = g_FnMap.begin(), end = g_FnMap.end(); itr != end; ++itr)
	{
		FnSizes.push_back(std::pair<AString, int>(itr->first, itr->second.m_Size));
	}  // for itr - g_FnSizes[]
	std::sort(FnSizes.begin(), FnSizes.end(), CompareFnInt);
	
	for (StringIntPairs::const_iterator itr = FnSizes.begin(), end = FnSizes.end(); itr != end; ++itr)
	{
		f.Printf("%d\t%s\n", itr->second, itr->first.c_str());
	}  // for itr - FnSizes[]
}





void WriteCountStatistics(void)
{
	typedef std::vector<std::pair<AString, int> > StringIntPairs;
	StringIntPairs FnCounts;
	
	cFile f("memdump_counts.txt", cFile::fmWrite);
	if (!f.IsOpen())
	{
		LOGERROR("Cannot open memdump_counts.txt");
		return;
	}

	for (FunctionMap::iterator itr = g_FnMap.begin(), end = g_FnMap.end(); itr != end; ++itr)
	{
		FnCounts.push_back(std::pair<AString, int>(itr->first, itr->second.m_Count));
	}  // for itr - g_FnSizes[]
	std::sort(FnCounts.begin(), FnCounts.end(), CompareFnInt);
	
	for (StringIntPairs::const_iterator itr = FnCounts.begin(), end = FnCounts.end(); itr != end; ++itr)
	{
		f.Printf("%d\t%s\n", itr->second, itr->first.c_str());
	}  // for itr - FnSizes[]
}





AString HTMLEscape(const AString & a_Text)
{
	AString res;
	res.reserve(a_Text.size());
	size_t len = a_Text.length();
	for (size_t i = 0; i < len; i++)
	{
		switch (a_Text[i])
		{
			case '<': res.append("&lt;<BR/>"); break;
			case '>': res.append("<BR/>&gt;"); break;
			case '&': res.append("&amp;"); break;
			default:
			{
				res.push_back(a_Text[i]);
			}
		}
	}  // for i - a_Text[]
	return res;
}





void WriteDotGraph(void)
{
	cFile f("memdump.dot", cFile::fmWrite);
	if (!f.IsOpen())
	{
		LOGERROR("Cannot open memdump.dot");
		return;
	}
	
	f.Printf("digraph {\n\tnode [shape=plaintext]\n\n");
	for (FunctionMap::const_iterator itrF = g_FnMap.begin(), endF = g_FnMap.end(); itrF != endF; ++itrF)
	{
		f.Printf("\t\"%s\" [label=<%s<BR/>%d bytes (%d KiB)<BR/>%d blocks>]\n",
			itrF->first.c_str(),
			HTMLEscape(itrF->first).c_str(),
			itrF->second.m_Size,
			(itrF->second.m_Size + 1023) / 1024,
			itrF->second.m_Count
		);
		const AStringSet & Children = itrF->second.m_ChildrenNames;
		for (AStringSet::const_iterator itrN = Children.begin(), endN = Children.end(); itrN != endN; ++itrN)
		{
			f.Printf("\t\t\"%s\" -> \"%s\"\n", itrF->first.c_str(), itrN->c_str());
		}
		f.Printf("\n");
	}  // for itr
	f.Printf("}\n");
}





int main(int argc, char * argv[])
{
	// Open the dump file:
	cFile f("memdump.xml", cFile::fmRead);
	if (!f.IsOpen())
	{
		printf("Cannot open memdump.xml\n");
		return 1;
	}
	
	// Create the XML parser:
	XML_Parser Parser = XML_ParserCreate(NULL);
	XML_SetElementHandler(Parser, OnStartElement, OnEndElement);
	
	// Feed the file through XML parser:
	char Buffer[512 KiB];
	while (true)
	{
		int NumBytes = f.Read(Buffer, sizeof(Buffer));
		if (NumBytes <= 0)
		{
			break;
		}
		XML_Parse(Parser, Buffer, NumBytes, false);
		putc('.', stdout);
	}
	XML_Parse(Parser, "", 0, true);
	f.Close();
	
	// Output the statistics
	WriteSizeStatistics();
	WriteCountStatistics();
	WriteDotGraph();
	
	return 0;
}