File: DialogHeap.cpp

package info (click to toggle)
edb-debugger 1.3.0-2.2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,124 kB
  • sloc: cpp: 46,241; xml: 4,998; ansic: 3,088; sh: 52; asm: 33; makefile: 5
file content (606 lines) | stat: -rw-r--r-- 18,153 bytes parent folder | download | duplicates (4)
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
/*
Copyright (C) 2006 - 2015 Evan Teran
                          evan.teran@gmail.com

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "DialogHeap.h"
#include "Configuration.h"
#include "IDebugger.h"
#include "IProcess.h"
#include "IRegion.h"
#include "ISymbolManager.h"
#include "MemoryRegions.h"
#include "Module.h"
#include "ResultViewModel.h"
#include "Symbol.h"
#include "edb.h"
#include "util/Math.h"

#ifdef ENABLE_GRAPH
#include "GraphEdge.h"
#include "GraphNode.h"
#include "GraphWidget.h"
#endif

#include <QFileInfo>
#include <QHeaderView>
#include <QMessageBox>
#include <QPushButton>
#include <QSortFilterProxyModel>
#include <QStack>
#include <QString>
#include <QVector>
#include <QtDebug>
#include <algorithm>
#include <functional>

namespace HeapAnalyzerPlugin {
namespace {

constexpr int PreviousInUse = 0x1;
constexpr int IsMMapped     = 0x2;
constexpr int NonMainArena  = 0x4;

constexpr int SizeBits = (PreviousInUse | IsMMapped | NonMainArena);

// NOTE: the details of this structure are 32/64-bit sensitive!
template <class MallocChunkPtr>
struct malloc_chunk {
	using ULong = MallocChunkPtr; // ulong has the same size

	ULong prevSize; /* Size of previous chunk (if free).  */
	ULong size;     /* Size in bytes, including overhead. */

	MallocChunkPtr fd; /* double links -- used only if free. */
	MallocChunkPtr bk;

	edb::address_t chunkSize() const { return edb::address_t::fromZeroExtended(size & ~(SizeBits)); }
	bool prevInUse() const { return size & PreviousInUse; }
};

template <class Addr>
edb::address_t next_chunk(edb::address_t p, const malloc_chunk<Addr> &c) {
	return p + c.chunkSize();
}

/**
 * @brief block_start
 * @param pointer
 * @return
 */
edb::address_t block_start(edb::address_t pointer) {
	return pointer + edb::v1::pointer_size() * 2; // pointer_size() is malloc_chunk*
}

/**
 * @brief block_start
 * @param result
 * @return
 */
edb::address_t block_start(const ResultViewModel::Result &result) {
	return block_start(result.address);
}

/**
 * @brief get_library_names
 * @param libcName
 * @param ldName
 */
void get_library_names(QString *libcName, QString *ldName) {

	Q_ASSERT(libcName);
	Q_ASSERT(ldName);

	if (edb::v1::debugger_core) {
		if (IProcess *process = edb::v1::debugger_core->process()) {
			const QList<Module> libs = process->loadedModules();

			for (const Module &module : libs) {
				if (!ldName->isEmpty() && !libcName->isEmpty()) {
					break;
				}

				const QFileInfo fileinfo(module.name);

				// this tries its best to cover all possible libc library versioning
				// possibilities we need to find out if this is 100% accurate, so far
				// seems correct based on my system

				if (fileinfo.completeBaseName().startsWith("libc-")) {
					*libcName = fileinfo.completeBaseName() + "." + fileinfo.suffix();
					qDebug() << "[Heap Analyzer] libc library appears to be:" << *libcName;
					continue;
				}

				if (fileinfo.completeBaseName().startsWith("libc.so")) {
					*libcName = fileinfo.completeBaseName() + "." + fileinfo.suffix();
					qDebug() << "[Heap Analyzer] libc library appears to be:" << *libcName;
					continue;
				}

				if (fileinfo.completeBaseName().startsWith("ld-")) {
					*ldName = fileinfo.completeBaseName() + "." + fileinfo.suffix();
					qDebug() << "[Heap Analyzer] ld library appears to be:" << *ldName;
					continue;
				}
			}
		}
	}
}

}

/**
 * @brief DialogHeap::DialogHeap
 * @param parent
 * @param f
 */
DialogHeap::DialogHeap(QWidget *parent, Qt::WindowFlags f)
	: QDialog(parent, f) {
	ui.setupUi(this);

	model_ = new ResultViewModel(this);

	filterModel_ = new QSortFilterProxyModel(this);
	connect(ui.lineEdit, &QLineEdit::textChanged, filterModel_, &QSortFilterProxyModel::setFilterFixedString);

	filterModel_->setFilterKeyColumn(3);
	filterModel_->setSourceModel(model_);
	ui.tableView->setModel(filterModel_);

	ui.tableView->verticalHeader()->hide();
	ui.tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);

	buttonAnalyze_ = new QPushButton(QIcon::fromTheme("edit-find"), tr("Analyze"));
	buttonGraph_   = new QPushButton(QIcon::fromTheme("distribute-graph"), tr("&Graph Selected Blocks"));
	connect(buttonAnalyze_, &QPushButton::clicked, this, [this]() {
		buttonAnalyze_->setEnabled(false);
		ui.progressBar->setValue(0);
		ui.tableView->setUpdatesEnabled(false);

		if (edb::v1::debuggeeIs32Bit()) {
			doFind<edb::value32>();
		} else {
			doFind<edb::value64>();
		}

		ui.tableView->setUpdatesEnabled(true);
		ui.progressBar->setValue(100);
		buttonAnalyze_->setEnabled(true);
	});

	connect(buttonGraph_, &QPushButton::clicked, this, [this]() {
#ifdef ENABLE_GRAPH
		constexpr int MaxNodes = 5000;

		auto graph = new GraphWidget(nullptr);
		graph->setAttribute(Qt::WA_DeleteOnClose);

		do {
			QMap<edb::address_t, GraphNode *> nodes;
			QStack<const ResultViewModel::Result *> result_stack;
			QSet<const ResultViewModel::Result *> seen_results;

			QMap<edb::address_t, const ResultViewModel::Result *> result_map = createResultMap();

			// seed our search with the selected blocks
			const QItemSelectionModel *const selModel = ui.tableView->selectionModel();
			const QModelIndexList sel                 = selModel->selectedRows();
			if (sel.size() != 0) {
				for (const QModelIndex &index : sel) {
					const QModelIndex idx = filterModel_->mapToSource(index);
					auto item             = static_cast<ResultViewModel::Result *>(idx.internalPointer());
					result_stack.push(item);
					seen_results.insert(item);
				}
			}

			while (!result_stack.isEmpty()) {
				const ResultViewModel::Result *const result = result_stack.pop();

				GraphNode *node = new GraphNode(graph, edb::v1::format_pointer(result->address), result->type == ResultViewModel::Result::Busy ? Qt::lightGray : Qt::red);

				nodes.insert(result->address, node);

				for (edb::address_t pointer : result->pointers) {
					const ResultViewModel::Result *next_result = result_map[pointer];
					if (!seen_results.contains(next_result)) {
						seen_results.insert(next_result);
						result_stack.push(next_result);
					}
				}
			}
			qDebug("[Heap Analyzer] Done Processing %d Nodes", nodes.size());

			if (nodes.size() > MaxNodes) {
				qDebug("[Heap Analyzer] Too Many Nodes! (%d)", nodes.size());
				delete graph;
				return;
			}

			Q_FOREACH (const ResultViewModel::Result *result, result_map) {
				const edb::address_t addr = result->address;
				if (nodes.contains(addr)) {
					for (edb::address_t pointer : result->pointers) {
						new GraphEdge(nodes[addr], nodes[pointer]);
					}
				}
			}
			qDebug("[Heap Analyzer] Done Processing Edges");
		} while (0);

		graph->layout();
		graph->show();
#endif
	});

	ui.buttonBox->addButton(buttonGraph_, QDialogButtonBox::ActionRole);
	ui.buttonBox->addButton(buttonAnalyze_, QDialogButtonBox::ActionRole);

#ifdef ENABLE_GRAPH
	buttonGraph_->setEnabled(true);
#else
	buttonGraph_->setEnabled(false);
#endif
}

/**
 * @brief DialogHeap::showEvent
 */
void DialogHeap::showEvent(QShowEvent *) {
	model_->clearResults();
	ui.progressBar->setValue(0);
}

/**
 * @brief DialogHeap::on_tableView_doubleClicked
 * @param index
 */
void DialogHeap::on_tableView_doubleClicked(const QModelIndex &index) {
	const QModelIndex idx = filterModel_->mapToSource(index);
	if (auto item = static_cast<ResultViewModel::Result *>(idx.internalPointer())) {
		edb::v1::dump_data_range(item->address, item->address + item->size, false);
	}
}

/**
 * @brief DialogHeap::processPotentialPointers
 * @param targets
 * @param index
 */
void DialogHeap::processPotentialPointers(const QHash<edb::address_t, edb::address_t> &targets, const QModelIndex &index) {

	if (auto result = static_cast<ResultViewModel::Result *>(index.internalPointer())) {

		std::vector<edb::address_t> pointers;

		if (IProcess *process = edb::v1::debugger_core->process()) {
			if (result->dataType == ResultViewModel::Result::Unknown) {
				edb::address_t pointer(0);
				edb::address_t block_ptr = block_start(*result);
				edb::address_t block_end = block_ptr + result->size;

				while (block_ptr < block_end) {

					if (process->readBytes(block_ptr, &pointer, edb::v1::pointer_size())) {
						auto it = targets.find(pointer);
						if (it != targets.end()) {
							pointers.push_back(it.value());
						}
					}

					block_ptr += edb::v1::pointer_size();
				}

				if (!pointers.empty()) {
					model_->setPointerData(index, pointers);
				}
			}
		}
	}
}

/**
 * @brief DialogHeap::detectPointers
 */
void DialogHeap::detectPointers() {

	qDebug() << "[Heap Analyzer] detecting pointers in heap blocks";

	QHash<edb::address_t, edb::address_t> targets;

	qDebug() << "[Heap Analyzer] collecting possible targets addresses";
	for (int row = 0; row < model_->rowCount(); ++row) {
		QModelIndex index = model_->index(row, 0);
		if (auto result = static_cast<ResultViewModel::Result *>(index.internalPointer())) {
			edb::address_t block_ptr = block_start(*result);
			edb::address_t block_end = block_ptr + result->size;
			while (block_ptr < block_end) {
				targets.insert(block_ptr, result->address);
				block_ptr += edb::v1::pointer_size();
			}
		}
	}

	qDebug() << "[Heap Analyzer] linking blocks to taget addresses";
	for (int row = 0; row < model_->rowCount(); ++row) {
		QModelIndex index = model_->index(row, 0);
		processPotentialPointers(targets, index);
	}
}

/**
 * @brief DialogHeap::collectBlocks
 * @param start_address
 * @param end_address
 */
template <class Addr>
void DialogHeap::collectBlocks(edb::address_t start_address, edb::address_t end_address) {
	model_->clearResults();
	ui.labelFree->setText(tr("Free Blocks: ?"));
	ui.labelBusy->setText(tr("Busy Blocks: ?"));
	ui.labelTotal->setText(tr("Total: ?"));

	int64_t freeBlocks = 0;
	int64_t busyBlocks = 0;

	if (IProcess *process = edb::v1::debugger_core->process()) {
		const int min_string_length = edb::v1::config().min_string_length;

		if (start_address != 0 && end_address != 0) {
#if defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD)
			malloc_chunk<Addr> currentChunk;
			malloc_chunk<Addr> nextChunk;
			edb::address_t currentChunkAddress = start_address;

			const edb::address_t how_many = end_address - start_address;
			while (currentChunkAddress != end_address) {
				// read in the current chunk..
				process->readBytes(currentChunkAddress, &currentChunk, sizeof(currentChunk));

				// figure out the address of the next chunk
				const edb::address_t nextChunkAddress = next_chunk(currentChunkAddress, currentChunk);

				// is this the last chunk (if so, it's the 'top')
				if (nextChunkAddress == end_address) {
					model_->addResult({currentChunkAddress, currentChunk.chunkSize(), ResultViewModel::Result::Top, ResultViewModel::Result::Unknown, {}, {}});
				} else {

					// make sure we aren't following a broken heap...
					if (nextChunkAddress > end_address || nextChunkAddress < start_address) {
						break;
					}

					QString data;
					ResultViewModel::Result::DataType data_type = ResultViewModel::Result::Unknown;

					// read in the next chunk
					process->readBytes(nextChunkAddress, &nextChunk, sizeof(nextChunk));

					// if this block is a container for an ascii string, display it...
					// there is a lot of room for improvement here, but it's a start
					QString asciiData;
					QString utf16Data;
					int asciisz;
					int utf16sz;
					if (edb::v1::get_ascii_string_at_address(
							block_start(currentChunkAddress),
							asciiData,
							min_string_length,
							currentChunk.chunkSize(),
							asciisz)) {

						data      = asciiData;
						data_type = ResultViewModel::Result::Ascii;
					} else if (edb::v1::get_utf16_string_at_address(
								   block_start(currentChunkAddress),
								   utf16Data,
								   min_string_length,
								   currentChunk.chunkSize(),
								   utf16sz)) {
						data      = utf16Data;
						data_type = ResultViewModel::Result::Utf16;
					} else {

						using std::memcmp;

						uint8_t bytes[16];
						process->readBytes(block_start(currentChunkAddress), bytes, sizeof(bytes));

						if (memcmp(bytes, "\x89\x50\x4e\x47", 4) == 0) {
							data_type = ResultViewModel::Result::Png;
						} else if (memcmp(bytes, "\x2f\x2a\x20\x58\x50\x4d\x20\x2a\x2f", 9) == 0) {
							data_type = ResultViewModel::Result::Xpm;
						} else if (memcmp(bytes, "\x42\x5a", 2) == 0) {
							data_type = ResultViewModel::Result::Bzip;
						} else if (memcmp(bytes, "\x1f\x9d", 2) == 0) {
							data_type = ResultViewModel::Result::Compress;
						} else if (memcmp(bytes, "\x1f\x8b", 2) == 0) {
							data_type = ResultViewModel::Result::Gzip;
						}
					}

					// TODO(eteran): should this be unsigned int? Or should it be sizeof(value32)/sizeof(value64)?
					const ResultViewModel::Result r{
						currentChunkAddress,
						currentChunk.chunkSize() + sizeof(unsigned int),
						nextChunk.prevInUse() ? ResultViewModel::Result::Busy : ResultViewModel::Result::Free,
						data_type,
						data,
						{}};

					if (nextChunk.prevInUse()) {
						++busyBlocks;
					} else {
						++freeBlocks;
					}

					model_->addResult(r);
				}

				// avoif self referencing blocks
				if (currentChunkAddress == nextChunkAddress) {
					break;
				}

				currentChunkAddress = nextChunkAddress;

				ui.progressBar->setValue(util::percentage(currentChunkAddress - start_address, how_many));
			}

			detectPointers();

			ui.labelFree->setText(tr("Free Blocks: %1").arg(freeBlocks));
			ui.labelBusy->setText(tr("Busy Blocks: %1").arg(busyBlocks));
			ui.labelTotal->setText(tr("Total: %1").arg(freeBlocks + busyBlocks));

#else
#error "Unsupported Platform"
#endif
		}
	}
}

/**
 * @brief DialogHeap::findHeapStartHeuristic
 * @param end_address
 * @param offset
 * @return
 */
edb::address_t DialogHeap::findHeapStartHeuristic(edb::address_t end_address, size_t offset) const {
	const edb::address_t start_address = end_address - offset;

	const edb::address_t heap_symbol = start_address - 4 * edb::v1::pointer_size();

	edb::address_t test_addr(0);
	if (IProcess *process = edb::v1::debugger_core->process()) {
		process->readBytes(heap_symbol, &test_addr, edb::v1::pointer_size());

		if (test_addr != edb::v1::debugger_core->pageSize()) {
			return 0;
		}

		return start_address;
	}

	return 0;
}

/**
 * @brief DialogHeap::do_find
 */
template <class Addr>
void DialogHeap::doFind() {
	// get both the libc and ld symbols of __curbrk
	// this will be the 'before/after libc' addresses

	if (IProcess *process = edb::v1::debugger_core->process()) {
		edb::address_t start_address = 0;
		edb::address_t end_address   = 0;

		QString libcName;
		QString ldName;

		get_library_names(&libcName, &ldName);
#if defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD)

		if (std::shared_ptr<Symbol> s = edb::v1::symbol_manager().find(libcName + "::__curbrk")) {
			end_address = s->address;
		} else {
			qDebug() << "[Heap Analyzer] __curbrk symbol not found in libc, falling back on heuristic! This may or may not work.";
		}

		if (std::shared_ptr<Symbol> s = edb::v1::symbol_manager().find(ldName + "::__curbrk")) {
			start_address = s->address;
		} else {

			qDebug() << "[Heap Analyzer] __curbrk symbol not found in ld, falling back on heuristic! This may or may not work.";

			for (edb::address_t offset = 0x0000; offset != 0x1000; offset += edb::v1::pointer_size()) {
				start_address = findHeapStartHeuristic(end_address, offset);
				if (start_address != 0) {
					break;
				}
			}
		}

		if (start_address != 0 && end_address != 0) {
			qDebug() << "[Heap Analyzer] heap start symbol : " << edb::v1::format_pointer(start_address);
			qDebug() << "[Heap Analyzer] heap end symbol   : " << edb::v1::format_pointer(end_address);

			// read the contents of those symbols
			process->readBytes(end_address, &end_address, edb::v1::pointer_size());
			process->readBytes(start_address, &start_address, edb::v1::pointer_size());
		}

		// just assume it's the bounds of the [heap] memory region for now
		if (start_address == 0 || end_address == 0) {

			const QList<std::shared_ptr<IRegion>> &regions = edb::v1::memory_regions().regions();

			auto it = std::find_if(regions.begin(), regions.end(), [](const std::shared_ptr<IRegion> &region) {
				return region->name() == "[heap]";
			});

			if (it != regions.end()) {
				qDebug() << "Found a memory region named '[heap]', assuming that it provides sane bounds";

				if (start_address == 0) {
					start_address = (*it)->start();
				}

				if (end_address == 0) {
					end_address = (*it)->end();
				}
			}
		}

		// ok, I give up
		if (start_address == 0 || end_address == 0) {
			QMessageBox::critical(this, tr("Could not calculate heap bounds"), tr("Failed to calculate the bounds of the heap."));
			return;
		}

#else
#error "Unsupported Platform"
#endif

		qDebug() << "[Heap Analyzer] heap start : " << edb::v1::format_pointer(start_address);
		qDebug() << "[Heap Analyzer] heap end   : " << edb::v1::format_pointer(end_address);

		collectBlocks<Addr>(start_address, end_address);
	}
}

/**
 * @brief DialogHeap::createResultMap
 * @return
 */
QMap<edb::address_t, const ResultViewModel::Result *> DialogHeap::createResultMap() const {

	const QVector<ResultViewModel::Result> &results = model_->results();
	QMap<edb::address_t, const ResultViewModel::Result *> result_map;

	// first we make a nice index for our results, this is likely redundant,
	// but won't take long
	for (const ResultViewModel::Result &result : results) {
		result_map.insert(result.address, &result);
	}

	return result_map;
}

}