-
Notifications
You must be signed in to change notification settings - Fork 133
/
MicrocodeExplorer.cpp
536 lines (462 loc) · 12 KB
/
MicrocodeExplorer.cpp
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
#include <memory>
#define USE_DANGEROUS_FUNCTIONS
#include <hexrays.hpp>
#include "HexRaysUtil.hpp"
typedef std::shared_ptr<mbl_array_t *> shared_mbl_array_t;
struct mblock_virtual_dumper_t : public vd_printer_t
{
int nline;
int serial;
mblock_virtual_dumper_t() : nline(0), serial(0) {};
virtual void AddLine(qstring &qs) = 0;
AS_PRINTF(3, 4) int print(int indent, const char *format, ...)
{
qstring buf;
if (indent > 0)
buf.fill(0, ' ', indent);
va_list va;
va_start(va, format);
buf.cat_vsprnt(format, va);
va_end(va);
// ida 7.1 apparently has a problem with line prefixes, remove this color
static const char pfx_on[] = { COLOR_ON, COLOR_PREFIX };
static const char pfx_off[] = { COLOR_OFF, COLOR_PREFIX };
buf.replace(pfx_on, "");
buf.replace(pfx_off, "");
AddLine(buf);
return buf.length();
}
};
struct mblock_qstring_dumper_t : public mblock_virtual_dumper_t
{
qstring qStr;
mblock_qstring_dumper_t() : mblock_virtual_dumper_t() {};
virtual void AddLine(qstring &qs)
{
qStr.append(qs);
}
};
struct mblock_dumper_t : public mblock_virtual_dumper_t
{
strvec_t lines;
mblock_dumper_t() : mblock_virtual_dumper_t() {};
virtual void AddLine(qstring &qs)
{
lines.push_back(simpleline_t(qs));
}
};
struct sample_info_t
{
TWidget *cv;
mblock_dumper_t md;
shared_mbl_array_t mba;
mba_maturity_t mat;
sample_info_t() : cv(NULL), mba(NULL) {}
};
#include <graph.hpp>
class MicrocodeInstructionGraph
{
public:
qstring tmp; // temporary buffer for grcode_user_text
qstrvec_t m_ShortText;
qstrvec_t m_BlockText;
intvec_t m_EdgeColors;
edgevec_t m_Edges;
int m_NumBlocks;
void Clear()
{
m_ShortText.clear();
m_BlockText.clear();
m_EdgeColors.clear();
m_Edges.clear();
m_NumBlocks = 0;
}
void Build(minsn_t *top)
{
Clear();
Insert(top, -1);
}
protected:
void AddEdge(int iSrc, int iDest, int iPos)
{
if (iSrc < 0 || iDest < 0)
return;
m_Edges.push_back(edge_t(iSrc, iDest));
m_EdgeColors.push_back(iPos);
}
int GetIncrBlockNum()
{
return m_NumBlocks++;
}
int Insert(minsn_t *ins, int iParent)
{
char l_Buf[MAXSTR];
mcode_t_to_string(ins, l_Buf, sizeof(l_Buf));
m_ShortText.push_back(l_Buf);
qstring qStr;
ins->print(&qStr);
m_BlockText.push_back(qStr);
int iThisBlock = GetIncrBlockNum();
Insert(ins->l, iThisBlock, 0);
Insert(ins->r, iThisBlock, 1);
Insert(ins->d, iThisBlock, 2);
return iThisBlock;
}
int Insert(mop_t &op, int iParent, int iPos)
{
if (op.t == mop_z)
return -1;
m_ShortText.push_back(mopt_t_to_string(op.t));
qstring qStr;
op.print(&qStr);
m_BlockText.push_back(qStr);
int iThisBlock = GetIncrBlockNum();
AddEdge(iParent, iThisBlock, iPos);
switch (op.t)
{
case mop_d: // result of another instruction
{
int iDestBlock = Insert(op.d, iThisBlock);
AddEdge(iThisBlock, iDestBlock, 0);
break;
}
case mop_f: // list of arguments
for (int i = 0; i < op.f->args.size(); ++i)
Insert(op.f->args[i], iThisBlock, i);
break;
case mop_p: // operand pair
{
Insert(op.pair->lop, iThisBlock, 0);
Insert(op.pair->hop, iThisBlock, 1);
break;
}
case mop_a: // result of another instruction
{
int iDestBlock = Insert(*op.a, iThisBlock, 0);
break;
}
}
return iThisBlock;
}
};
class MicrocodeInstructionGraphContainer;
static ssize_t idaapi migr_callback(void *ud, int code, va_list va);
class MicrocodeInstructionGraphContainer
{
protected:
TWidget * m_TW;
graph_viewer_t *m_GV;
qstring m_Title;
qstring m_GVName;
public:
MicrocodeInstructionGraph m_MG;
MicrocodeInstructionGraphContainer() : m_TW(NULL), m_GV(NULL) {};
bool Display(minsn_t *top, sample_info_t *si, int nBlock, int nSerial)
{
mbl_array_t *mba = *si->mba;
m_MG.Build(top);
m_Title.cat_sprnt("Microinstruction Graph - %a[%s]/%d:%d", mba->entry_ea, MicroMaturityToString(si->mat), nBlock, nSerial);
m_TW = create_empty_widget(m_Title.c_str());
netnode id;
id.create();
m_GVName.cat_sprnt("microins_%a_%s_%d_%d", mba->entry_ea, MicroMaturityToString(si->mat), nBlock, nSerial);
m_GV = create_graph_viewer(m_GVName.c_str(), id, migr_callback, this, 0, m_TW);
activate_widget(m_TW, true);
#if IDA_SDK_VERSION == 710
display_widget(m_TW, WOPN_TAB | WOPN_MENU);
#elif IDA_SDK_VERSION == 720
display_widget(m_TW, WOPN_TAB);
#elif IDA_SDK_VERSION >= 730
display_widget(m_TW, WOPN_DP_TAB);
#endif
viewer_fit_window(m_GV);
return true;
}
};
static ssize_t idaapi migr_callback(void *ud, int code, va_list va)
{
MicrocodeInstructionGraphContainer *gcont = (MicrocodeInstructionGraphContainer *)ud;
MicrocodeInstructionGraph *microg = &gcont->m_MG;
bool result = false;
switch (code)
{
case grcode_user_gentext:
result = true;
break;
// refresh user-defined graph nodes and edges
case grcode_user_refresh:
// in: mutable_graph_t *g
// out: success
{
mutable_graph_t *mg = va_arg(va, mutable_graph_t *);
// we have to resize
mg->resize(microg->m_NumBlocks);
for (auto &it : microg->m_Edges)
mg->add_edge(it.src, it.dst, NULL);
result = true;
}
break;
// retrieve text for user-defined graph node
case grcode_user_text:
//mutable_graph_t *g
// int node
// const char **result
// bgcolor_t *bg_color (maybe NULL)
// out: must return 0, result must be filled
// NB: do not use anything calling GDI!
{
va_arg(va, mutable_graph_t *);
int node = va_arg(va, int);
const char **text = va_arg(va, const char **);
microg->tmp = microg->m_ShortText[node];
microg->tmp.append('\n');
microg->tmp.append(microg->m_BlockText[node]);
*text = microg->tmp.begin();
result = true;
}
break;
}
return (int)result;
}
static ssize_t idaapi mgr_callback(void *ud, int code, va_list va);
class MicrocodeGraphContainer
{
public:
shared_mbl_array_t m_MBA;
mblock_qstring_dumper_t m_MQD;
qstring m_Title;
qstring m_GVName;
qstring tmp;
MicrocodeGraphContainer(shared_mbl_array_t mba) : m_MBA(mba) {};
bool Display(sample_info_t *si)
{
mbl_array_t *mba = *si->mba;
m_Title.cat_sprnt("Microcode Graph - %a[%s]", mba->entry_ea, MicroMaturityToString(si->mat));
TWidget *tw = create_empty_widget(m_Title.c_str());
netnode id;
id.create();
m_GVName.cat_sprnt("microblkgraph_%a_%s", mba->entry_ea, MicroMaturityToString(si->mat));
graph_viewer_t *gv = create_graph_viewer(m_GVName.c_str(), id, mgr_callback, this, 0, tw);
activate_widget(tw, true);
#if IDA_SDK_VERSION == 710
display_widget(tw, WOPN_TAB | WOPN_MENU);
#elif IDA_SDK_VERSION == 720
display_widget(tw, WOPN_TAB);
#elif IDA_SDK_VERSION >= 730
display_widget(tw, WOPN_DP_TAB);
#endif
viewer_fit_window(gv);
return true;
}
};
static ssize_t idaapi mgr_callback(void *ud, int code, va_list va)
{
MicrocodeGraphContainer *gcont = (MicrocodeGraphContainer *)ud;
mbl_array_t *mba = *gcont->m_MBA;
bool result = false;
switch (code)
{
case grcode_user_gentext:
result = true;
break;
// refresh user-defined graph nodes and edges
case grcode_user_refresh:
// in: mutable_graph_t *g
// out: success
{
mutable_graph_t *mg = va_arg(va, mutable_graph_t *);
// we have to resize
mg->resize(mba->qty);
for (int i = 0; i < mba->qty; ++i)
for (auto dst : mba->get_mblock(i)->succset)
mg->add_edge(i, dst, NULL);
result = true;
}
break;
// retrieve text for user-defined graph node
case grcode_user_text:
//mutable_graph_t *g
// int node
// const char **result
// bgcolor_t *bg_color (maybe NULL)
// out: must return 0, result must be filled
// NB: do not use anything calling GDI!
{
va_arg(va, mutable_graph_t *);
int node = va_arg(va, int);
const char **text = va_arg(va, const char **);
gcont->m_MQD.qStr.clear();
mba->get_mblock(node)->print(gcont->m_MQD);
*text = gcont->m_MQD.qStr.begin();
result = true;
}
break;
}
return (int)result;
}
static bool idaapi ct_keyboard(TWidget * /*v*/, int key, int shift, void *ud)
{
if (shift == 0)
{
sample_info_t *si = (sample_info_t *)ud;
switch (key)
{
case 'G':
{
MicrocodeGraphContainer *mgc = new MicrocodeGraphContainer(si->mba);
return mgc->Display(si);
}
// User wants to show a graph of the current instruction
case 'I':
{
qstring buf;
tag_remove(&buf, get_custom_viewer_curline(si->cv, false));
const char *pLine = buf.c_str();
const char *pDot = strchr(pLine, '.');
if (pDot == NULL)
{
warning(
"Couldn't find the block number on the current line; was the block empty?\n"
"If it was not empty, and you don't see [int].[int] at the beginning of the lines\n"
"please run the plugin again to generate a new microcode listing.\n"
"That should fix it.");
return true; // reacted to the keypress
}
int nBlock = atoi(pLine);
int nSerial = atoi(pDot + 1);
mbl_array_t *mba = *si->mba;
if (nBlock > mba->qty)
{
warning("Plugin error: line prefix was %d:%d, but block only has %d basic blocks.", nBlock, nSerial, mba->qty);
return true;
}
mblock_t *blk = mba->get_mblock(nBlock);
minsn_t *minsn = blk->head;
int i;
for (i = 0; i < nSerial; ++i)
{
minsn = minsn->next;
if (minsn == NULL)
break;
}
if (minsn == NULL)
{
if (i == 0)
warning(
"Couldn't get first minsn_t from %d:%d; was the block empty?\n"
"If it was not empty, and you don't see [int].[int] at the beginning of the lines\n"
"please run the plugin again to generate a new microcode listing.\n"
"That should fix it.", nBlock, nSerial);
else
warning("Couldn't get first minsn_t from %d:%d; last valid instruction was %d", nBlock, nSerial, i - 1);
return true;
}
char repr[MAXSTR];
mcode_t_to_string(minsn, repr, sizeof(repr));
MicrocodeInstructionGraphContainer *mcg = new MicrocodeInstructionGraphContainer;
return mcg->Display(minsn, si, nBlock, nSerial);
}
case IK_ESCAPE:
close_widget(si->cv, WCLS_SAVE | WCLS_CLOSE_LATER);
return true;
}
}
return false;
}
static const custom_viewer_handlers_t handlers(
ct_keyboard,
NULL, // popup
NULL, // mouse_moved
NULL, // click
NULL, // dblclick
NULL,
NULL, // close
NULL, // help
NULL);// adjust_place
ssize_t idaapi ui_callback(void *ud, int code, va_list va)
{
sample_info_t *si = (sample_info_t *)ud;
switch (code)
{
case ui_widget_invisible:
{
TWidget *f = va_arg(va, TWidget *);
if (f == si->cv)
{
delete si;
unhook_from_notification_point(HT_UI, ui_callback);
}
}
break;
}
return 0;
}
const char *matLevels[] =
{
"MMAT_GENERATED",
"MMAT_PREOPTIMIZED",
"MMAT_LOCOPT",
"MMAT_CALLS",
"MMAT_GLBOPT1",
"MMAT_GLBOPT2",
"MMAT_GLBOPT3",
"MMAT_LVARS"
};
mba_maturity_t AskDesiredMaturity()
{
const char dlgText[] =
"Select maturity level\n"
"<Desired ~m~aturity level:b:0:::>\n";
qstrvec_t opts;
for (int i = 0; i < qnumber(matLevels); ++i)
opts.push_back(matLevels[i]);
int sel = 0;
int ret = ask_form(dlgText, &opts, &sel);
if (ret > 0)
return (mba_maturity_t)((int)MMAT_GENERATED + sel);
return MMAT_ZERO;
}
void ShowMicrocodeExplorer()
{
func_t *pfn = get_func(get_screen_ea());
if (pfn == NULL)
{
warning("Please position the cursor within a function");
return;
}
mba_maturity_t mmat = AskDesiredMaturity();
if (mmat == MMAT_ZERO)
return;
hexrays_failure_t hf;
mbl_array_t *mba = gen_microcode(pfn, &hf, NULL, 0, mmat);
if (mba == NULL)
{
warning("#error \"%a: %s", hf.errea, hf.desc().c_str());
return;
}
sample_info_t *si = new sample_info_t;
si->mba = std::make_shared<mbl_array_t *>(mba);
si->mat = mmat;
// Dump the microcode to the output window
mba->print(si->md);
simpleline_place_t s1;
simpleline_place_t s2(si->md.lines.size() - 1);
qstring title;
title.cat_sprnt("Microcode Explorer - %a - %s", pfn->start_ea, MicroMaturityToString(mmat));
si->cv = create_custom_viewer(
title.c_str(), // title
&s1, // minplace
&s2, // maxplace
&s1, // curplace
NULL, // renderer_info_t *rinfo
&si->md.lines, // ud
&handlers, // cvhandlers
si, // cvhandlers_ud
NULL); // parent
hook_to_notification_point(HT_UI, ui_callback, si);
#if IDA_SDK_VERSION >= 730
display_widget(si->cv, WOPN_DP_TAB | WOPN_RESTORE);
#else
display_widget(si->cv, WOPN_TAB | WOPN_RESTORE);
#endif
}