summaryrefslogtreecommitdiff
path: root/plugins/warp/ui/shared/fetchdialog.cpp
blob: 44d7c2375d40c95cc80398f943f14baaadcb1fe8 (plain)
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
#include "fetchdialog.h"

#include <QDialogButtonBox>
#include <QFormLayout>
#include <QInputDialog>
#include <QLabel>

#include "action.h"
#include "fetcher.h"
#include "misc.h"

using namespace BinaryNinja;

static void AddListItem(QListWidget* list, const QString& value)
{
	if (value.trimmed().isEmpty())
		return;
	// Avoid duplicates
	for (int i = 0; i < list->count(); ++i)
		if (list->item(i)->text().compare(value, Qt::CaseInsensitive) == 0)
			return;
	list->addItem(value.trimmed());
}

WarpFetchDialog::WarpFetchDialog(BinaryViewRef bv, std::shared_ptr<WarpFetcher> fetcher, QWidget* parent) :
	QDialog(parent), m_fetchProcessor(std::move(fetcher)), m_bv(std::move(bv))
{
	setWindowTitle("Fetch WARP Functions");

	auto form = new QFormLayout();
	m_containerCombo = new QComboBox(this);
	populateContainers();
	m_containerCombo->addItem("All Containers");  // index 0 for "all"
	for (const auto& c : m_containers)
		m_containerCombo->addItem(QString::fromStdString(c->GetName()));

	// Tags editor
	m_tagsList = new QListWidget(this);
	m_addTagBtn = new QPushButton(this);
	m_addTagBtn->setText("+");
	m_addTagBtn->setToolTip("Add tag");
	m_removeTagBtn = new QPushButton(this);
	m_removeTagBtn->setText("-");
	m_removeTagBtn->setToolTip("Remove selected tag(s)");
	m_resetTagBtn = new QPushButton(this);
	m_resetTagBtn->setText("Reset");
	m_resetTagBtn->setToolTip("Reset tags to: official, trusted");
	auto tagBtnRow = new QHBoxLayout();
	tagBtnRow->addWidget(m_addTagBtn);
	tagBtnRow->addWidget(m_removeTagBtn);
	tagBtnRow->addWidget(m_resetTagBtn);
	tagBtnRow->addStretch();
	auto tagCol = new QVBoxLayout();
	tagCol->addWidget(m_tagsList);
	tagCol->addLayout(tagBtnRow);
	auto tagWrapper = new QWidget(this);
	tagWrapper->setLayout(tagCol);

	// Make tags list compact with a fixed maximum height and no vertical expansion
	m_tagsList->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents);
	m_tagsList->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
	m_tagsList->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
	m_tagsList->setMaximumHeight(120);
	m_tagsList->setToolTip("A source must have atleast ONE of these tags to be considered");

	// Defaults from processor tags
	for (const auto& t : GetAllowedTagsFromView(m_bv))
		AddListItem(m_tagsList, QString::fromStdString(t));

	m_rerunMatcher = new QCheckBox("Re-run matcher after fetch", this);
	m_rerunMatcher->setChecked(true);

	m_clearProcessed = new QCheckBox("Refetch all functions", this);
	m_clearProcessed->setToolTip(
		"Clears the processed cache before fetching again, this will refetch all functions in the view");
	m_clearProcessed->setChecked(false);

	form->addRow(new QLabel("Container: "), m_containerCombo);
	form->addRow(new QLabel("Allowed Tags: "), tagWrapper);
	form->addRow(m_rerunMatcher);
	form->addRow(m_clearProcessed);

	auto buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);
	connect(buttons, &QDialogButtonBox::accepted, this, &WarpFetchDialog::onAccept);
	connect(buttons, &QDialogButtonBox::rejected, this, &WarpFetchDialog::onReject);

	auto root = new QVBoxLayout(this);
	root->addLayout(form);
	root->addWidget(buttons);
	setLayout(root);

	// Wire buttons
	connect(m_addTagBtn, &QPushButton::clicked, this, &WarpFetchDialog::onAddTag);
	connect(m_removeTagBtn, &QPushButton::clicked, this, &WarpFetchDialog::onRemoveTag);
	connect(m_resetTagBtn, &QPushButton::clicked, this, &WarpFetchDialog::onResetTags);
}

void WarpFetchDialog::populateContainers()
{
	m_containers = Warp::Container::All();
}

void WarpFetchDialog::onAddTag()
{
	bool ok = false;
	const auto text = QInputDialog::getText(this, "Add Tag", "Tag:", QLineEdit::Normal, {}, &ok);
	if (ok)
		AddListItem(m_tagsList, text);
}

void WarpFetchDialog::onRemoveTag()
{
	for (auto* item : m_tagsList->selectedItems())
		delete item;
}

void WarpFetchDialog::onResetTags()
{
	m_tagsList->clear();
	AddListItem(m_tagsList, "official");
	AddListItem(m_tagsList, "trusted");
}

std::vector<Warp::SourceTag> WarpFetchDialog::collectTags() const
{
	std::vector<Warp::SourceTag> out;
	out.reserve(m_tagsList->count());
	for (int i = 0; i < m_tagsList->count(); ++i)
		out.emplace_back(m_tagsList->item(i)->text().trimmed().toStdString());
	return out;
}

void WarpFetchDialog::onAccept()
{
	const int idx = m_containerCombo->currentIndex();
	std::optional<size_t> containerIndex;
	if (idx > 0)  // 0 == All Containers
		containerIndex = static_cast<size_t>(idx - 1);

	const bool rerun = m_rerunMatcher->isChecked();

	const auto tags = collectTags();
	// Persist tags to the view settings.
	SetTagsToView(m_bv, tags);

	if (m_clearProcessed->isChecked())
		m_fetchProcessor->ClearProcessed();

	// Execute the network fetch in batches
	runBatchedFetch(containerIndex, tags, rerun);

	accept();
}

void WarpFetchDialog::onReject()
{
	const auto tags = collectTags();
	// Persist tags to the view settings.
	SetTagsToView(m_bv, tags);
	reject();
}

void WarpFetchDialog::runBatchedFetch(const std::optional<size_t>& containerIndex,
	const std::vector<Warp::SourceTag>& allowedTags, bool rerunMatcher)
{
	if (!m_bv)
		return;
	// Collect functions in the view and enqueue them to the shared fetcher
	std::vector<Ref<Function>> funcs = m_bv->GetAnalysisFunctionList();
	if (funcs.empty())
		return;

	// Create a background task to show progress in the UI
	Ref<BackgroundTask> task =
		new BackgroundTask("Fetching WARP functions (0 / " + std::to_string(funcs.size()) + ")", true);

	auto fetcher = m_fetchProcessor;
	auto bv = m_bv;

	// TODO: Too many captures in this thing lol.
	WorkerInteractiveEnqueue(
		[fetcher, bv, funcs = std::move(funcs), rerunMatcher, task, allowedTags]() mutable {
			const auto batchSize = GetBatchSizeFromView(bv);
			size_t processed = 0;
			while (processed < funcs.size())
			{
				if (task->IsCancelled())
					break;
				const size_t remaining = funcs.size() - processed;
				const size_t thisBatchCount = std::min(batchSize, remaining);
				for (size_t i = 0; i < thisBatchCount; ++i)
					fetcher->AddPendingFunction(funcs[processed + i]);
				fetcher->FetchPendingFunctions(allowedTags);
				processed += thisBatchCount;
				task->SetProgressText("Fetching WARP functions (" + std::to_string(processed) + " / " + std::to_string(funcs.size()) + ")");
			}

			task->Finish();
			Logger("WARP Fetcher").LogInfo("Finished fetching WARP functions in %d seconds...", task->GetRuntimeSeconds());

			if (rerunMatcher && bv)
				Warp::RunMatcher(*bv);
		});
}

void RegisterWarpFetchFunctionsCommand()
{
	// Register a UI action and bind it globally. Add it to the Tools menu.
	const QString actionName = "WARP\\Fetch";
	if (!UIAction::isActionRegistered(actionName))
		UIAction::registerAction(actionName);

	UIActionHandler::globalActions()->bindAction(actionName,
		UIAction(
			[](const UIActionContext& context) {
				if (const BinaryViewRef bv = context.binaryView; bv)
				{
					WarpFetchDialog dlg(bv, WarpFetcher::Global(), nullptr);
					dlg.exec();
				}
			},
			[](const UIActionContext& context) { return context.binaryView != nullptr; }));

	Menu::mainMenu("Plugins")->addAction(actionName, "Plugins");
}