]>
git.siccegge.de Git - frida/frida.git/blob - src/Binary.cxx
a659d5c450a58905effaf526d94f676360ac4935
3 #include "disassembler/Disassembler.hxx"
9 #include "llvm/Support/raw_ostream.h"
12 using namespace llvm::object
;
15 bool error(error_code ec
) {
16 if (!ec
) return false;
18 outs() << "error reading file: " << ec
.message() << ".\n";
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
;
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
];
41 assert(bytes
.size() <= 15
42 && "DumpBytes only supports instructions of up to 15 bytes");
43 memset(output
, ' ', sizeof(output
));
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];
52 output
[sizeof(output
) - 1] = 0;
56 std::map
<std::string
, SectionRef
> readSections(const ObjectFile
& o
) {
58 std::map
<std::string
, SectionRef
> result
;
59 section_iterator
i(o
.section_begin()), e(o
.section_end());
62 if (error(i
->getName(name
))) break;
64 result
.insert(make_pair(name
.str(), *i
));
69 std::map
<std::string
, SymbolRef
> readSymbols(const ObjectFile
& o
) {
71 std::map
<std::string
, SymbolRef
> result
;
72 symbol_iterator
si(o
.symbol_begin()), se(o
.symbol_end());
73 for (; si
!= se
; ++si
) {
75 if (error(si
->getName(name
))) break;
77 result
.insert(make_pair(name
.str(), *si
));
85 Binary::Binary(const std::string
& filename
)
86 : triple("unkown-unknown-unknown")
88 ::Disassembler
d(filename
);
91 binary
= createBinary(filename
).get();
92 if (Archive
*a
= dyn_cast
<Archive
>(binary
)) {
93 std::cerr
<< "Got an archive!" << std::endl
;
97 o
= dyn_cast
<ObjectFile
>(binary
);
99 triple
.setArch(Triple::ArchType(o
->getArch()));
100 std::string
tripleName(triple
.getTriple());
102 outs() << tripleName
<< "\n";
104 target
= TargetRegistry::lookupTarget("", triple
, error
);
110 outs() << target
->getName() << "\n";
112 MRI
.reset(target
->createMCRegInfo(tripleName
));
114 std::cerr
<< "error: no register info for target " << tripleName
<< "\n";
118 // Set up disassembler.
119 AsmInfo
.reset(target
->createMCAsmInfo(*MRI
, tripleName
));
121 std::cerr
<< "error: no assembly info for target " << tripleName
<< "\n";
125 STI
.reset(target
->createMCSubtargetInfo(tripleName
, "", ""));
127 errs() << "error: no subtarget info for target " << tripleName
<< "\n";
131 MII
.reset(target
->createMCInstrInfo());
133 std::cerr
<< "error: no instruction info for target " << tripleName
<< "\n";
137 DisAsm
.reset(target
->createMCDisassembler(*STI
));
139 std::cerr
<< "error: no disassembler for target " << tripleName
<< "\n";
143 MOFI
.reset(new MCObjectFileInfo
);
144 Ctx
.reset(new MCContext(AsmInfo
.get(), MRI
.get(), MOFI
.get()));
146 target
->createMCRelocationInfo(tripleName
, *Ctx
.get()));
149 MCObjectSymbolizer::createObjectSymbolizer(*Ctx
.get(), RelInfo
, o
));
151 DisAsm
->setSymbolizer(Symzer
);
154 MIA
.reset(target
->createMCInstrAnalysis(MII
.get()));
156 int AsmPrinterVariant
= AsmInfo
->getAssemblerDialect();
157 IP
.reset(target
->createMCInstPrinter(AsmPrinterVariant
, *AsmInfo
, *MII
, *MRI
, *STI
));
159 std::cerr
<< "error: no instruction printer for target " << tripleName
164 OwningPtr
<MCObjectDisassembler
> OD(
165 new MCObjectDisassembler(*o
, *DisAsm
, *MIA
));
166 Mod
.reset(OD
->buildModule(/* withCFG */ false));
168 symbols
= readSymbols(*o
);
169 sections
= readSections(*o
);
171 // for_each(sections.begin(), sections.end(), [](const std::pair<std::string, SectionRef>& i){
172 // std::cout << "Section: " << i.first << std::endl;
178 std::vector
<std::string
> Binary::getSymbols() {
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
) {
185 if (!error(r
.containsSymbol(i
.second
, contains
)) && contains
) {
187 if (SymbolRef::ST_Function
== t
)
188 result
.push_back(i
.first
);
194 void Binary::for_each_instruction(const std::string
& function
,
195 std::function
<void (long, std::string
, std::string
)> callback
) {
197 uint64_t base_address
, address
, ssize
, size(0), index
, end
;
198 StringRefMemoryObject
memoryObject("");
200 if (symbols
.end() != symbols
.find(function
)) {
202 section_iterator
sec(o
->section_begin());
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
;
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
;
225 // outs() << "Start for_each_instruction " << function << "\n";
228 for (end
= address
+ ssize
- base_address
, index
= address
- base_address
; index
< end
; index
+= size
) {
231 if (DisAsm
->getInstruction(Inst
, size
, memoryObject
, index
,
234 llvm::raw_string_ostream
s(buf
);
235 IP
->printInst(&Inst
, s
, "");
237 if (index
+ size
< bytes
.str().length())
238 callback(base_address
+ index
, bytes
.str().substr(index
, size
), s
.str());
241 errs() << "warning: invalid instruction encoding\n";
243 size
= 1; // skip illegible bytes
246 // outs() << "End for_each_instruction\n";
250 void Binary::disassemble() {
251 for (MCModule::const_atom_iterator AI
= Mod
->atom_begin(),
252 AE
= Mod
->atom_end();
255 if ((*AI
)->getKind() != llvm::MCAtom::TextAtom
)
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();
264 IP
->printInst(&II
->Inst
, outs(), "");
270 outs() << "binary " << triple
.getArchName() << "\n";
273 void Binary::disassemble_functions() {
275 for (section_iterator i
= o
->section_begin(),
276 e
= o
->section_end();
278 if (error(ec
)) break;
280 if (error(i
->isText(text
))) break;
283 uint64_t SectionAddr
;
284 if (error(i
->getAddress(SectionAddr
))) break;
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();
292 if (!error(i
->containsSymbol(*si
, contains
)) && contains
) {
294 if (error(si
->getAddress(Address
))) break;
295 if (Address
== UnknownAddressOrSize
) continue;
296 Address
-= SectionAddr
;
299 if (error(si
->getName(Name
))) break;
301 outs() << "\nXXX " << Name
<< "\n";
303 Symbols
.push_back(std::make_pair(Address
, Name
));
307 // Sort the symbols by address, just in case they didn't come in that way.
308 array_pod_sort(Symbols
.begin(), Symbols
.end());
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);
321 // Sort relocations by address.
322 std::sort(Rels
.begin(), Rels
.end(), RelocAddressLess
);
324 StringRef SegmentName
= "";
325 // if (const MachOObjectFile *MachO =
326 // dyn_cast<const MachOObjectFile>(o)) {
327 // DataRefImpl DR = i->getRawDataRefImpl();
328 // SegmentName = MachO->getSectionFinalSegmentName(DR);
331 if (error(i
->getName(name
))) break;
332 outs() << "Disassembly of section ";
333 if (!SegmentName
.empty())
334 outs() << SegmentName
<< ",";
335 outs() << name
<< ':';
337 // If the section has no symbols just insert a dummy one and disassemble
338 // the whole section.
340 Symbols
.push_back(std::make_pair(0, name
));
344 if (error(i
->getContents(Bytes
))) break;
345 StringRefMemoryObject
memoryObject(Bytes
);
349 if (error(i
->getSize(SectSize
))) break;
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
;
357 // The end is either the size of the section or the beginning of the next
361 // Make sure this symbol takes up space.
362 else if (Symbols
[si
+ 1].first
!= Start
)
363 End
= Symbols
[si
+ 1].first
- 1;
365 // This symbol has the same address as the next symbol. Skip it.
368 outs() << '\n' << Symbols
[si
].second
<< ":\n";
371 raw_ostream
&DebugOut
= nulls(); //DebugFlag ? dbgs() : nulls();
373 raw_ostream
&DebugOut
= nulls();
376 for (Index
= Start
; Index
< End
; Index
+= Size
) {
379 if (DisAsm
->getInstruction(Inst
, Size
, memoryObject
, Index
,
380 DebugOut
, nulls())) {
381 outs() << format("%8" PRIx64
":", SectionAddr
+ Index
);
383 DumpBytes(StringRef(Bytes
.data() + Index
, Size
));
385 IP
->printInst(&Inst
, outs(), "");
388 errs() << "warning: invalid instruction encoding\n";
390 Size
= 1; // skip illegible bytes
393 // Print relocation for instruction.
394 while (rel_cur
!= rel_end
) {
397 SmallString
<16> name
;
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
;
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
;
410 outs() << format("\t\t\t%8" PRIx64
": ", SectionAddr
+ addr
) << name
411 << "\t" << val
<< "\n";
421 void Binary::disassemble_cfg() {
422 for (MCModule::const_func_iterator FI
= Mod
->func_begin(),
423 FE
= Mod
->func_end();
425 static int filenum
= 0;
426 std::string FileName
= std::string("dot/") + (Twine((*FI
)->getName()) + "_" + utostr(filenum
) + ".dot").str();
428 std::cerr
<< FileName
<< std::endl
;
430 // Start a new dot file.
432 raw_fd_ostream
Out(FileName
.c_str(), Error
);
433 if (!Error
.empty()) {
434 errs() << "llvm-objdump: warning: " << Error
<< '\n';
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();
444 if (!hasPreds
&& i
!= (*FI
)->begin())
447 Out
<< '"' << (*i
)->getInsts()->getBeginAddr() << "\" [ label=\"<a>";
448 // Print instructions.
449 for (unsigned ii
= 0, ie
= (*i
)->getInsts()->size(); ii
!= ie
;
451 if (ii
!= 0) // Not the first line, start a new row.
453 if (ii
+ 1 == ie
) // Last line, add an end id.
456 // Escape special chars and print the instruction in mnemonic form.
458 raw_string_ostream
OS(Str
);
459 IP
->printInst(&(*i
)->getInsts()->at(ii
).Inst
, OS
, "");
460 Out
<< DOT::EscapeString(OS
.str());
462 Out
<< "\" shape=\"record\" ];\n";
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";