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