]> git.siccegge.de Git - frida/frida.git/blob - src/Binary.cxx
Resize the basicBlock widget
[frida/frida.git] / src / Binary.cxx
1 #include "Binary.hxx"
2
3 #include "disassembler/Disassembler.hxx"
4
5 #include <iostream>
6 #include <string>
7 #include <algorithm>
8
9 #include "llvm/Support/raw_ostream.h"
10
11 using namespace llvm;
12 using namespace llvm::object;
13
14 namespace {
15 bool error(error_code ec) {
16 if (!ec) return false;
17
18 outs() << "error reading file: " << ec.message() << ".\n";
19 outs().flush();
20 return true;
21 }
22
23 bool RelocAddressLess(RelocationRef a, RelocationRef b) {
24 uint64_t a_addr, b_addr;
25 if (error(a.getOffset(a_addr))) return false;
26 if (error(b.getOffset(b_addr))) return false;
27 return a_addr < b_addr;
28 }
29
30 void DumpBytes(StringRef bytes) {
31 static const char hex_rep[] = "0123456789abcdef";
32 // FIXME: The real way to do this is to figure out the longest instruction
33 // and align to that size before printing. I'll fix this when I get
34 // around to outputting relocations.
35 // 15 is the longest x86 instruction
36 // 3 is for the hex rep of a byte + a space.
37 // 1 is for the null terminator.
38 enum { OutputSize = (15 * 3) + 1 };
39 char output[OutputSize];
40
41 assert(bytes.size() <= 15
42 && "DumpBytes only supports instructions of up to 15 bytes");
43 memset(output, ' ', sizeof(output));
44 unsigned index = 0;
45 for (StringRef::iterator i = bytes.begin(),
46 e = bytes.end(); i != e; ++i) {
47 output[index] = hex_rep[(*i & 0xF0) >> 4];
48 output[index + 1] = hex_rep[*i & 0xF];
49 index += 3;
50 }
51
52 output[sizeof(output) - 1] = 0;
53 outs() << output;
54 }
55
56 std::map<std::string, SectionRef> readSections(const ObjectFile& o) {
57 error_code ec;
58 std::map<std::string, SectionRef> result;
59 section_iterator i(o.section_begin()), e(o.section_end());
60 for (; i != e; ++i) {
61 StringRef name;
62 if (error(i->getName(name))) break;
63
64 result.insert(make_pair(name.str(), *i));
65 }
66 return result;
67 }
68
69 std::map<std::string, SymbolRef> readSymbols(const ObjectFile& o) {
70 error_code ec;
71 std::map<std::string, SymbolRef> result;
72 symbol_iterator si(o.symbol_begin()), se(o.symbol_end());
73 for (; si != se; ++si) {
74 StringRef name;
75 if (error(si->getName(name))) break;
76
77 result.insert(make_pair(name.str(), *si));
78 }
79 return result;
80 }
81 }
82
83 namespace qtlldb {
84
85 Binary::Binary(const std::string& filename)
86 : triple("unkown-unknown-unknown")
87 {
88 ::Disassembler d(filename);
89 std::string error;
90
91 binary = createBinary(filename).get();
92 if (Archive *a = dyn_cast<Archive>(binary)) {
93 std::cerr << "Got an archive!" << std::endl;
94 return;
95 }
96
97 o = dyn_cast<ObjectFile>(binary);
98
99 triple.setArch(Triple::ArchType(o->getArch()));
100 std::string tripleName(triple.getTriple());
101
102 outs() << tripleName << "\n";
103
104 target = TargetRegistry::lookupTarget("", triple, error);
105 if (!target) {
106 std::cerr << error;
107 return;
108 }
109
110 outs() << target->getName() << "\n";
111
112 MRI.reset(target->createMCRegInfo(tripleName));
113 if (!MRI) {
114 std::cerr << "error: no register info for target " << tripleName << "\n";
115 return;
116 }
117
118 // Set up disassembler.
119 AsmInfo.reset(target->createMCAsmInfo(*MRI, tripleName));
120 if (!AsmInfo) {
121 std::cerr << "error: no assembly info for target " << tripleName << "\n";
122 return;
123 }
124
125 STI.reset(target->createMCSubtargetInfo(tripleName, "", ""));
126 if (!STI) {
127 errs() << "error: no subtarget info for target " << tripleName << "\n";
128 return;
129 }
130
131 MII.reset(target->createMCInstrInfo());
132 if (!MII) {
133 std::cerr << "error: no instruction info for target " << tripleName << "\n";
134 return;
135 }
136
137 DisAsm.reset(target->createMCDisassembler(*STI));
138 if (!DisAsm) {
139 std::cerr << "error: no disassembler for target " << tripleName << "\n";
140 return;
141 }
142
143 MOFI.reset(new MCObjectFileInfo);
144 Ctx.reset(new MCContext(AsmInfo.get(), MRI.get(), MOFI.get()));
145 RelInfo.reset(
146 target->createMCRelocationInfo(tripleName, *Ctx.get()));
147 if (RelInfo) {
148 Symzer.reset(
149 MCObjectSymbolizer::createObjectSymbolizer(*Ctx.get(), RelInfo, o));
150 if (Symzer)
151 DisAsm->setSymbolizer(Symzer);
152 }
153
154 MIA.reset(target->createMCInstrAnalysis(MII.get()));
155
156 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
157 IP.reset(target->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
158 if (!IP) {
159 std::cerr << "error: no instruction printer for target " << tripleName
160 << '\n';
161 return;
162 }
163
164 OwningPtr<MCObjectDisassembler> OD(
165 new MCObjectDisassembler(*o, *DisAsm, *MIA));
166 Mod.reset(OD->buildModule(/* withCFG */ false));
167
168 symbols = readSymbols(*o);
169 sections = readSections(*o);
170
171 // for_each(sections.begin(), sections.end(), [](const std::pair<std::string, SectionRef>& i){
172 // std::cout << "Section: " << i.first << std::endl;
173 // });
174 }
175
176
177
178 std::vector<std::string> Binary::getSymbols() {
179 error_code ec;
180 SectionRef r = sections[".text"];
181 std::vector<std::string> result;
182 for_each(symbols.begin(), symbols.end(), [&](const std::pair<std::string, SymbolRef>& i) {
183 bool contains;
184 SymbolRef::Type t;
185 if (!error(r.containsSymbol(i.second, contains)) && contains) {
186 i.second.getType(t);
187 if (SymbolRef::ST_Function == t)
188 result.push_back(i.first);
189 }
190 });
191 return result;
192 }
193
194 void Binary::for_each_instruction(const std::string& function,
195 std::function<void (long, std::string, std::string)> callback) {
196 StringRef bytes;
197 uint64_t base_address, address, ssize, size(0), index, end;
198 StringRefMemoryObject memoryObject("");
199
200 if (symbols.end() != symbols.find(function)) {
201 SymbolRef ref;
202 section_iterator sec(o->section_begin());
203
204 ref = symbols.at(function);
205 if (error(ref.getSection(sec))) return;
206 if (error(ref.getAddress(address))) return;
207 if (address == UnknownAddressOrSize) return;
208 if (error(ref.getSize(ssize))) return;
209 if (error(sec->getAddress(base_address))) return;
210 if (error(sec->getContents(bytes))) return;
211 memoryObject = bytes;
212
213 }
214 else if (sections.end() != sections.find(function)) {
215 SectionRef sref = sections.at(function);
216 if (error(sref.getAddress(address))) return;
217 if (address == UnknownAddressOrSize) return;
218 if (error(sref.getSize(ssize))) return;
219 if (error(sref.getContents(bytes))) return;
220 base_address = address;
221 memoryObject = bytes;
222 }
223
224
225 // outs() << "Start for_each_instruction " << function << "\n";
226
227
228 for (end = address + ssize - base_address, index = address - base_address; index < end; index += size) {
229 MCInst Inst;
230
231 if (DisAsm->getInstruction(Inst, size, memoryObject, index,
232 nulls(), nulls())) {
233 std::string buf;
234 llvm::raw_string_ostream s(buf);
235 IP->printInst(&Inst, s, "");
236
237 if (index + size < bytes.str().length())
238 callback(base_address + index, bytes.str().substr(index, size), s.str());
239
240 } else {
241 errs() << "warning: invalid instruction encoding\n";
242 if (size == 0)
243 size = 1; // skip illegible bytes
244 }
245 }
246 // outs() << "End for_each_instruction\n";
247
248 }
249
250 void Binary::disassemble() {
251 for (MCModule::const_atom_iterator AI = Mod->atom_begin(),
252 AE = Mod->atom_end();
253 AI != AE; ++AI) {
254
255 if ((*AI)->getKind() != llvm::MCAtom::TextAtom)
256 continue;
257
258 outs() << "\n\nAtom " << (*AI)->getName() << ": \n";
259 if (const MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI)) {
260 for (MCTextAtom::const_iterator II = TA->begin(), IE = TA->end();
261 II != IE;
262 ++II) {
263 // II->Inst.dump();
264 IP->printInst(&II->Inst, outs(), "");
265 outs() << "\n";
266 }
267 }
268 }
269
270 outs() << "binary " << triple.getArchName() << "\n";
271 }
272
273 void Binary::disassemble_functions() {
274 error_code ec;
275 for (section_iterator i = o->section_begin(),
276 e = o->section_end();
277 i != e; ++i) {
278 if (error(ec)) break;
279 bool text;
280 if (error(i->isText(text))) break;
281 if (!text) continue;
282
283 uint64_t SectionAddr;
284 if (error(i->getAddress(SectionAddr))) break;
285
286 // Make a list of all the symbols in this section.
287 std::vector<std::pair<uint64_t, StringRef> > Symbols;
288 for (symbol_iterator si = o->symbol_begin(),
289 se = o->symbol_end();
290 si != se; ++si) {
291 bool contains;
292 if (!error(i->containsSymbol(*si, contains)) && contains) {
293 uint64_t Address;
294 if (error(si->getAddress(Address))) break;
295 if (Address == UnknownAddressOrSize) continue;
296 Address -= SectionAddr;
297
298 StringRef Name;
299 if (error(si->getName(Name))) break;
300
301 outs() << "\nXXX " << Name << "\n";
302
303 Symbols.push_back(std::make_pair(Address, Name));
304 }
305 }
306
307 // Sort the symbols by address, just in case they didn't come in that way.
308 array_pod_sort(Symbols.begin(), Symbols.end());
309
310 // Make a list of all the relocations for this section.
311 std::vector<RelocationRef> Rels;
312 // if (InlineRelocs) {
313 // for (relocation_iterator ri = i->begin_relocations(),
314 // re = i->end_relocations();
315 // ri != re; ri.increment(ec)) {
316 // if (error(ec)) break;
317 // Rels.push_back(*ri);
318 // }
319 // }
320
321 // Sort relocations by address.
322 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
323
324 StringRef SegmentName = "";
325 // if (const MachOObjectFile *MachO =
326 // dyn_cast<const MachOObjectFile>(o)) {
327 // DataRefImpl DR = i->getRawDataRefImpl();
328 // SegmentName = MachO->getSectionFinalSegmentName(DR);
329 // }
330 StringRef name;
331 if (error(i->getName(name))) break;
332 outs() << "Disassembly of section ";
333 if (!SegmentName.empty())
334 outs() << SegmentName << ",";
335 outs() << name << ':';
336
337 // If the section has no symbols just insert a dummy one and disassemble
338 // the whole section.
339 if (Symbols.empty())
340 Symbols.push_back(std::make_pair(0, name));
341
342
343 StringRef Bytes;
344 if (error(i->getContents(Bytes))) break;
345 StringRefMemoryObject memoryObject(Bytes);
346 uint64_t Size;
347 uint64_t Index;
348 uint64_t SectSize;
349 if (error(i->getSize(SectSize))) break;
350
351 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
352 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
353 // Disassemble symbol by symbol.
354 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
355 uint64_t Start = Symbols[si].first;
356 uint64_t End;
357 // The end is either the size of the section or the beginning of the next
358 // symbol.
359 if (si == se - 1)
360 End = SectSize;
361 // Make sure this symbol takes up space.
362 else if (Symbols[si + 1].first != Start)
363 End = Symbols[si + 1].first - 1;
364 else
365 // This symbol has the same address as the next symbol. Skip it.
366 continue;
367
368 outs() << '\n' << Symbols[si].second << ":\n";
369
370 #ifndef NDEBUG
371 raw_ostream &DebugOut = nulls(); //DebugFlag ? dbgs() : nulls();
372 #else
373 raw_ostream &DebugOut = nulls();
374 #endif
375
376 for (Index = Start; Index < End; Index += Size) {
377 MCInst Inst;
378
379 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
380 DebugOut, nulls())) {
381 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
382 outs() << "\t";
383 DumpBytes(StringRef(Bytes.data() + Index, Size));
384
385 IP->printInst(&Inst, outs(), "");
386 outs() << "\n";
387 } else {
388 errs() << "warning: invalid instruction encoding\n";
389 if (Size == 0)
390 Size = 1; // skip illegible bytes
391 }
392
393 // Print relocation for instruction.
394 while (rel_cur != rel_end) {
395 bool hidden = false;
396 uint64_t addr;
397 SmallString<16> name;
398 SmallString<32> val;
399
400 // If this relocation is hidden, skip it.
401 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
402 if (hidden) goto skip_print_rel;
403
404 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
405 // Stop when rel_cur's address is past the current instruction.
406 if (addr >= Index + Size) break;
407 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
408 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
409
410 outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
411 << "\t" << val << "\n";
412
413 skip_print_rel:
414 ++rel_cur;
415 }
416 }
417 }
418 }
419 }
420
421 void Binary::disassemble_cfg() {
422 for (MCModule::const_func_iterator FI = Mod->func_begin(),
423 FE = Mod->func_end();
424 FI != FE; ++FI) {
425 static int filenum = 0;
426 std::string FileName = std::string("dot/") + (Twine((*FI)->getName()) + "_" + utostr(filenum) + ".dot").str();
427
428 std::cerr << FileName << std::endl;
429
430 // Start a new dot file.
431 std::string Error;
432 raw_fd_ostream Out(FileName.c_str(), Error);
433 if (!Error.empty()) {
434 errs() << "llvm-objdump: warning: " << Error << '\n';
435 return;
436 }
437
438 Out << "digraph \"" << (*FI)->getName() << "\" {\n";
439 Out << "graph [ rankdir = \"LR\" ];\n";
440 for (MCFunction::const_iterator i = (*FI)->begin(), e = (*FI)->end(); i != e; ++i) {
441 // Only print blocks that have predecessors.
442 bool hasPreds = (*i)->pred_begin() != (*i)->pred_end();
443
444 if (!hasPreds && i != (*FI)->begin())
445 continue;
446
447 Out << '"' << (*i)->getInsts()->getBeginAddr() << "\" [ label=\"<a>";
448 // Print instructions.
449 for (unsigned ii = 0, ie = (*i)->getInsts()->size(); ii != ie;
450 ++ii) {
451 if (ii != 0) // Not the first line, start a new row.
452 Out << '|';
453 if (ii + 1 == ie) // Last line, add an end id.
454 Out << "<o>";
455
456 // Escape special chars and print the instruction in mnemonic form.
457 std::string Str;
458 raw_string_ostream OS(Str);
459 IP->printInst(&(*i)->getInsts()->at(ii).Inst, OS, "");
460 Out << DOT::EscapeString(OS.str());
461 }
462 Out << "\" shape=\"record\" ];\n";
463
464 // Add edges.
465 for (MCBasicBlock::succ_const_iterator si = (*i)->succ_begin(),
466 se = (*i)->succ_end(); si != se; ++si)
467 Out << (*i)->getInsts()->getBeginAddr() << ":o -> "
468 << (*si)->getInsts()->getBeginAddr() << ":a\n";
469 }
470 Out << "}\n";
471
472 ++filenum;
473 }
474 }
475 }