]>
git.siccegge.de Git - frida/frida.git/blob - src/Binary.cxx
7 #include "llvm/Support/raw_ostream.h"
10 using namespace llvm::object
;
13 bool error(error_code ec
) {
14 if (!ec
) return false;
16 outs() << "error reading file: " << ec
.message() << ".\n";
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
;
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
];
39 assert(bytes
.size() <= 15
40 && "DumpBytes only supports instructions of up to 15 bytes");
41 memset(output
, ' ', sizeof(output
));
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];
50 output
[sizeof(output
) - 1] = 0;
54 std::map
<std::string
, SectionRef
> readSections(const ObjectFile
& o
) {
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
)) {
60 if (error(i
->getName(name
))) break;
62 result
.insert(make_pair(name
.str(), *i
));
67 std::map
<std::string
, SymbolRef
> readSymbols(const ObjectFile
& o
) {
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
)) {
73 if (error(si
->getName(name
))) break;
75 result
.insert(make_pair(name
.str(), *si
));
83 Binary::Binary(const std::string
& filename
)
84 : triple("unkown-unknown-unknown")
88 createBinary(filename
, binary
);
89 if (Archive
*a
= dyn_cast
<Archive
>(binary
.get())) {
90 std::cerr
<< "Got an archive!" << std::endl
;
94 o
= dyn_cast
<ObjectFile
>(binary
.get());
96 triple
.setArch(Triple::ArchType(o
->getArch()));
97 std::string
tripleName(triple
.getTriple());
99 outs() << tripleName
<< "\n";
101 target
= TargetRegistry::lookupTarget("", triple
, error
);
107 outs() << target
->getName() << "\n";
109 MRI
.reset(target
->createMCRegInfo(tripleName
));
111 std::cerr
<< "error: no register info for target " << tripleName
<< "\n";
115 // Set up disassembler.
116 AsmInfo
.reset(target
->createMCAsmInfo(*MRI
, tripleName
));
118 std::cerr
<< "error: no assembly info for target " << tripleName
<< "\n";
122 STI
.reset(target
->createMCSubtargetInfo(tripleName
, "", ""));
124 errs() << "error: no subtarget info for target " << tripleName
<< "\n";
128 MII
.reset(target
->createMCInstrInfo());
130 std::cerr
<< "error: no instruction info for target " << tripleName
<< "\n";
134 DisAsm
.reset(target
->createMCDisassembler(*STI
));
136 std::cerr
<< "error: no disassembler for target " << tripleName
<< "\n";
140 MOFI
.reset(new MCObjectFileInfo
);
141 Ctx
.reset(new MCContext(AsmInfo
.get(), MRI
.get(), MOFI
.get()));
143 target
->createMCRelocationInfo(tripleName
, *Ctx
.get()));
146 MCObjectSymbolizer::createObjectSymbolizer(*Ctx
.get(), RelInfo
, o
));
148 DisAsm
->setSymbolizer(Symzer
);
151 MIA
.reset(target
->createMCInstrAnalysis(MII
.get()));
153 int AsmPrinterVariant
= AsmInfo
->getAssemblerDialect();
154 IP
.reset(target
->createMCInstPrinter(AsmPrinterVariant
, *AsmInfo
, *MII
, *MRI
, *STI
));
156 std::cerr
<< "error: no instruction printer for target " << tripleName
161 OwningPtr
<MCObjectDisassembler
> OD(
162 new MCObjectDisassembler(*o
, *DisAsm
, *MIA
));
163 Mod
.reset(OD
->buildModule(/* withCFG */ false));
165 symbols
= readSymbols(*o
);
166 sections
= readSections(*o
);
168 // for_each(sections.begin(), sections.end(), [](const std::pair<std::string, SectionRef>& i){
169 // std::cout << "Section: " << i.first << std::endl;
175 std::vector
<std::string
> Binary::getSymbols() {
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
) {
181 if (!error(r
.containsSymbol(i
.second
, contains
)) && contains
)
182 result
.push_back(i
.first
);
187 void Binary::for_each_instruction(const std::string
& function
,
188 std::function
<void (long, std::string
, std::string
)> callback
) {
190 SymbolRef ref
= symbols
[function
];
191 section_iterator
sec(o
->begin_sections());
192 uint64_t base_address
, address
, ssize
, size(0), index
, end
;
194 // outs() << "Start for_each_instruction " << function << "\n";
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;
203 // outs() << "Middle for_each_instruction " << function << " Size: " << ssize << "\n";
205 StringRefMemoryObject
memoryObject(bytes
);
207 for (end
= address
+ ssize
- base_address
, index
= address
- base_address
; index
< end
; index
+= size
) {
210 if (DisAsm
->getInstruction(Inst
, size
, memoryObject
, index
,
213 llvm::raw_string_ostream
s(buf
);
214 IP
->printInst(&Inst
, s
, "");
216 if (index
+ size
< bytes
.str().length())
217 callback(base_address
+ index
, bytes
.str().substr(index
, size
), s
.str());
220 errs() << "warning: invalid instruction encoding\n";
222 size
= 1; // skip illegible bytes
225 // outs() << "End for_each_instruction\n";
229 void Binary::disassemble() {
230 for (MCModule::const_atom_iterator AI
= Mod
->atom_begin(),
231 AE
= Mod
->atom_end();
234 if ((*AI
)->getKind() != llvm::MCAtom::TextAtom
)
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();
243 IP
->printInst(&II
->Inst
, outs(), "");
249 outs() << "binary " << triple
.getArchName() << "\n";
252 void Binary::disassemble_functions() {
254 for (section_iterator i
= o
->begin_sections(),
255 e
= o
->end_sections();
256 i
!= e
; i
.increment(ec
)) {
257 if (error(ec
)) break;
259 if (error(i
->isText(text
))) break;
262 uint64_t SectionAddr
;
263 if (error(i
->getAddress(SectionAddr
))) break;
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
)) {
271 if (!error(i
->containsSymbol(*si
, contains
)) && contains
) {
273 if (error(si
->getAddress(Address
))) break;
274 if (Address
== UnknownAddressOrSize
) continue;
275 Address
-= SectionAddr
;
278 if (error(si
->getName(Name
))) break;
280 outs() << "\nXXX " << Name
<< "\n";
282 Symbols
.push_back(std::make_pair(Address
, Name
));
286 // Sort the symbols by address, just in case they didn't come in that way.
287 array_pod_sort(Symbols
.begin(), Symbols
.end());
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);
300 // Sort relocations by address.
301 std::sort(Rels
.begin(), Rels
.end(), RelocAddressLess
);
303 StringRef SegmentName
= "";
304 // if (const MachOObjectFile *MachO =
305 // dyn_cast<const MachOObjectFile>(o)) {
306 // DataRefImpl DR = i->getRawDataRefImpl();
307 // SegmentName = MachO->getSectionFinalSegmentName(DR);
310 if (error(i
->getName(name
))) break;
311 outs() << "Disassembly of section ";
312 if (!SegmentName
.empty())
313 outs() << SegmentName
<< ",";
314 outs() << name
<< ':';
316 // If the section has no symbols just insert a dummy one and disassemble
317 // the whole section.
319 Symbols
.push_back(std::make_pair(0, name
));
323 if (error(i
->getContents(Bytes
))) break;
324 StringRefMemoryObject
memoryObject(Bytes
);
328 if (error(i
->getSize(SectSize
))) break;
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
;
336 // The end is either the size of the section or the beginning of the next
340 // Make sure this symbol takes up space.
341 else if (Symbols
[si
+ 1].first
!= Start
)
342 End
= Symbols
[si
+ 1].first
- 1;
344 // This symbol has the same address as the next symbol. Skip it.
347 outs() << '\n' << Symbols
[si
].second
<< ":\n";
350 raw_ostream
&DebugOut
= DebugFlag
? dbgs() : nulls();
352 raw_ostream
&DebugOut
= nulls();
355 for (Index
= Start
; Index
< End
; Index
+= Size
) {
358 if (DisAsm
->getInstruction(Inst
, Size
, memoryObject
, Index
,
359 DebugOut
, nulls())) {
360 outs() << format("%8" PRIx64
":", SectionAddr
+ Index
);
362 DumpBytes(StringRef(Bytes
.data() + Index
, Size
));
364 IP
->printInst(&Inst
, outs(), "");
367 errs() << "warning: invalid instruction encoding\n";
369 Size
= 1; // skip illegible bytes
372 // Print relocation for instruction.
373 while (rel_cur
!= rel_end
) {
376 SmallString
<16> name
;
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
;
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
;
389 outs() << format("\t\t\t%8" PRIx64
": ", SectionAddr
+ addr
) << name
390 << "\t" << val
<< "\n";
400 void Binary::disassemble_cfg() {
401 for (MCModule::const_func_iterator FI
= Mod
->func_begin(),
402 FE
= Mod
->func_end();
404 static int filenum
= 0;
405 std::string FileName
= std::string("dot/") + (Twine((*FI
)->getName()) + "_" + utostr(filenum
) + ".dot").str();
407 std::cerr
<< FileName
<< std::endl
;
409 // Start a new dot file.
411 raw_fd_ostream
Out(FileName
.c_str(), Error
);
412 if (!Error
.empty()) {
413 errs() << "llvm-objdump: warning: " << Error
<< '\n';
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();
423 if (!hasPreds
&& i
!= (*FI
)->begin())
426 Out
<< '"' << (*i
)->getInsts()->getBeginAddr() << "\" [ label=\"<a>";
427 // Print instructions.
428 for (unsigned ii
= 0, ie
= (*i
)->getInsts()->size(); ii
!= ie
;
430 if (ii
!= 0) // Not the first line, start a new row.
432 if (ii
+ 1 == ie
) // Last line, add an end id.
435 // Escape special chars and print the instruction in mnemonic form.
437 raw_string_ostream
OS(Str
);
438 IP
->printInst(&(*i
)->getInsts()->at(ii
).Inst
, OS
, "");
439 Out
<< DOT::EscapeString(OS
.str());
441 Out
<< "\" shape=\"record\" ];\n";
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";