]>
git.siccegge.de Git - frida/frida.git/blob - src/disassembler/llvm/LLVMDisassembler.cxx
1 #include "disassembler/llvm/LLVMDisassembler.hxx"
2 #include "core/InformationManager.hxx"
3 #include "core/Function.hxx"
4 #include "core/BasicBlock.hxx"
11 using namespace llvm::object
;
12 using std::error_code
;
23 Disassembler
* createLLVMDisassembler(const std::string
& filename
, InformationManager
* manager
) {
27 std::unique_ptr
<Binary
> o
;
28 o
.reset(createBinary(filename
).get());
29 Binary
* op
= o
.release();
31 // ELFType<endian, maxalign, 64bit>
32 if (ELF32LEObjectFile
* object
= dyn_cast
<ELF32LEObjectFile
>(op
)) {
33 return new LLVMDisassembler
<ELFType
<support::little
, 2, false>>(filename
, manager
, object
);
35 if (ELF64LEObjectFile
* object
= dyn_cast
<ELF64LEObjectFile
>(op
)) {
36 return new LLVMDisassembler
<ELFType
<support::little
, 2, true>>(filename
, manager
, object
);
38 if (ELF32BEObjectFile
* object
= dyn_cast
<ELF32BEObjectFile
>(op
)) {
39 return new LLVMDisassembler
<ELFType
<support::big
, 2, false>>(filename
, manager
, object
);
41 if (ELF64BEObjectFile
* object
= dyn_cast
<ELF64BEObjectFile
>(op
)) {
42 return new LLVMDisassembler
<ELFType
<support::big
, 2, true>>(filename
, manager
, object
);
44 if (COFFObjectFile
* object
= dyn_cast
<COFFObjectFile
>(op
)) {
45 return new LLVMDisassembler
<COFFT
>(filename
, manager
, object
);
52 * TODO: fallback code falls die Datei kein ELF/PE/COFF/MacO/.. binary
53 * ist sondern z.B. einfach nur Instruktionen oder ein Bootsektor oder
56 template <typename ELFT
>
57 LLVMDisassembler
<ELFT
>::LLVMDisassembler(const std::string
& filename
,
58 InformationManager
* manager
,
61 , logger(log4cxx::Logger::getLogger("LLVMDisassembler"))
62 , triple("unknown-unknown-unknown")
65 LOG4CXX_DEBUG(logger
, "Handling file " << filename
);
68 auto result
= createBinary(filename
);
71 if ((ec
= result
.getError())) {
72 LOG4CXX_ERROR(logger
, "Failed to load Binary" << ec
.message());
77 binary
.reset(result
.get());
79 o
= dyn_cast
<ObjectFile
>(binary
.get());
85 triple
.setArch(Triple::ArchType(o
->getArch()));
86 std::string
tripleName(triple
.getTriple());
88 LOG4CXX_INFO(logger
, "Architecture " << tripleName
);
92 target
= TargetRegistry::lookupTarget("", triple
, es
);
94 LOG4CXX_ERROR(logger
, es
);
98 LOG4CXX_INFO(logger
, "Target " << target
->getName());
100 MRI
.reset(target
->createMCRegInfo(tripleName
));
102 LOG4CXX_ERROR(logger
, "no register info for target " << tripleName
);
106 // Set up disassembler.
107 AsmInfo
.reset(target
->createMCAsmInfo(*MRI
, tripleName
));
109 LOG4CXX_ERROR(logger
, "no assembly info for target " << tripleName
);
113 STI
.reset(target
->createMCSubtargetInfo(tripleName
, "", ""));
115 LOG4CXX_ERROR(logger
, "no subtarget info for target " << tripleName
);
119 MII
.reset(target
->createMCInstrInfo());
121 LOG4CXX_ERROR(logger
, "no instruction info for target " << tripleName
);
125 MOFI
.reset(new MCObjectFileInfo
);
126 MCContext
Ctx(AsmInfo
.get(), MRI
.get(), MOFI
.get());
128 DisAsm
.reset(target
->createMCDisassembler(*STI
, Ctx
));
130 LOG4CXX_ERROR(logger
, "no disassembler for target " << tripleName
);
134 target
->createMCRelocationInfo(tripleName
, Ctx
));
137 // MCObjectSymbolizer::createObjectSymbolizer(Ctx, std::move(RelInfo), o));
139 // DisAsm->setSymbolizer(std::move(Symzer));
144 MIA
.reset(target
->createMCInstrAnalysis(MII
.get()));
146 LOG4CXX_ERROR(logger
, "no instruction analysis for target " << tripleName
);
150 int AsmPrinterVariant
= AsmInfo
->getAssemblerDialect();
151 IP
.reset(target
->createMCInstPrinter(AsmPrinterVariant
, *AsmInfo
, *MII
, *MRI
, *STI
));
153 LOG4CXX_ERROR(logger
, "no instruction printer for target " << tripleName
);
157 IP
->setPrintImmHex(llvm::HexStyle::C
);
158 IP
->setPrintImmHex(true);
160 std::unique_ptr
<MCObjectDisassembler
> OD(
161 new MCObjectDisassembler(*o
, *DisAsm
, *MIA
));
162 Mod
.reset(OD
->buildModule(false));
167 template <typename ELFT
>
168 void LLVMDisassembler
<ELFT
>::start() {
171 readDynamicSymbols();
174 template <typename ELFT
>
175 LLVMDisassembler
<ELFT
>::~LLVMDisassembler() {}
177 template <typename ELFT
>
178 Function
* LLVMDisassembler
<ELFT
>::disassembleFunctionAt(uint64_t address
, const std::string
& name
) {
180 SectionRef text_section
= sections
[".text"];
181 uint64_t base_address
, size
;
182 text_section
.getAddress(base_address
);
183 text_section
.getSize(size
);
185 if (address
< base_address
||
186 address
>= base_address
+ size
) {
190 if (NULL
== (function
= manager
->getFunction(address
))) {
194 s
<< "<Unnamed 0x" << std::hex
<< address
<< ">";
195 function
= manager
->newFunction(address
);
196 function
->setName(s
.str());
198 function
= manager
->newFunction(address
);
199 function
->setName(name
);
201 disassembleFunction(function
);
207 template <typename ELFT
>
208 void LLVMDisassembler
<ELFT
>::disassembleFunction(Function
* function
) {
209 std::vector
<uint64_t> called_functions
;
210 std::stack
<BasicBlock
*> remaining_blocks
;
212 * Do all blocks get added properly? We should take care to remove
213 * the other ones at the end of the function!
215 std::map
<uint64_t, BasicBlock
*> new_blocks
;
216 SectionRef text_section
= sections
[".text"];
218 text_section
.getContents(bytes
);
219 StringRefMemoryObject
ref(bytes
);
221 LOG4CXX_DEBUG(logger
, "Handling function " << function
->getName());
223 BasicBlock
* block
= manager
->newBasicBlock(function
->getStartAddress());
224 remaining_blocks
.push(block
);
225 new_blocks
.insert(std::make_pair(block
->getStartAddress(), block
));
226 function
->addBasicBlock(block
);
228 while (remaining_blocks
.size()) {
229 BasicBlock
* current_block
= remaining_blocks
.top();
230 remaining_blocks
.pop();
232 LOG4CXX_DEBUG(logger
, "Handling Block starting at " << std::hex
233 << current_block
->getStartAddress());
236 uint64_t base_address
;
237 text_section
.getAddress(base_address
);
238 uint64_t current_address
= current_block
->getStartAddress() - base_address
;
242 llvm::raw_string_ostream
s(buf
);
244 if(llvm::MCDisassembler::Success
==
245 DisAsm
->getInstruction(inst
, inst_size
, ref
, current_address
, nulls(), nulls())) {
248 if (MIA
->evaluateBranch(inst
, current_address
, inst_size
, jmptarget
)) {
249 jmptarget
+= base_address
;
250 if (!MIA
->isIndirectBranch(inst
)) {
251 if (MIA
->isCall(inst
)) {
252 if (NULL
== manager
->getFunction(jmptarget
))
253 called_functions
.push_back(jmptarget
);
255 current_block
->setNextBlock(0, jmptarget
);
256 if (new_blocks
.find(jmptarget
) == new_blocks
.end()) {
257 BasicBlock
* block
= manager
->newBasicBlock(jmptarget
);
259 new_blocks
.insert(std::make_pair(block
->getStartAddress(), block
));
260 function
->addBasicBlock(block
);
261 remaining_blocks
.push(block
);
263 LOG4CXX_DEBUG(logger
, "Reusing Block starting at " << std::hex
264 << current_block
->getStartAddress());
265 function
->addBasicBlock(new_blocks
.find(jmptarget
)->second
);
267 if (MIA
->isConditionalBranch(inst
)) {
268 jmptarget
= base_address
+ current_address
+ inst_size
;
269 current_block
->setNextBlock(1, jmptarget
);
270 if (new_blocks
.find(jmptarget
) == new_blocks
.end()) {
271 BasicBlock
* block
= manager
->newBasicBlock(jmptarget
);
273 new_blocks
.insert(std::make_pair(block
->getStartAddress(), block
));
274 function
->addBasicBlock(block
);
275 remaining_blocks
.push(block
);
277 LOG4CXX_DEBUG(logger
, "Reusing Block starting at " << std::hex
278 << current_block
->getStartAddress());
279 function
->addBasicBlock(new_blocks
.find(jmptarget
)->second
);
290 if (inst_size
== 0 || MIA
->isTerminator(inst
) || MIA
->isBranch(inst
)) {
291 current_block
->setEndAddress(current_address
+ base_address
+ inst_size
);
292 LOG4CXX_DEBUG(logger
, "Finished Block at " << std::hex
<<
293 current_block
->getEndAddress());
296 current_address
+= inst_size
;
299 splitBlocks(function
);
300 LOG4CXX_DEBUG(logger
, "Finished function " << function
->getName());
301 manager
->finishFunction(function
);
302 for (uint64_t address
: called_functions
)
303 disassembleFunctionAt(address
);
306 template <typename ELFT
>
307 void LLVMDisassembler
<ELFT
>::disassemble() {
308 SectionRef text_section
= sections
[".text"];
309 std::vector
<Function
*> remaining_functions
;
311 // Assume all function symbols actually start a real function
312 for (auto x
= symbols
.begin(); x
!= symbols
.end(); ++x
) {
315 SymbolRef::Type symbol_type
;
318 if (text_section
.containsSymbol(x
->second
, contains
) || !contains
)
321 if (x
->second
.getType(symbol_type
)
322 || SymbolRef::ST_Function
!= symbol_type
)
325 if (!x
->second
.getAddress(result
)) {
326 Function
* fun
= manager
->newFunction(result
);
327 fun
->setName(x
->first
);
328 remaining_functions
.push_back(fun
);
329 LOG4CXX_DEBUG(logger
, "Disasembling " << x
->first
);
333 for (Function
* function
: remaining_functions
) {
334 disassembleFunction(function
);
335 manager
->finishFunction(function
);
338 if (binary
->isELF()) {
339 uint64_t _entryAddress
= entryAddress();
340 LOG4CXX_DEBUG(logger
, "Adding entryAddress at: " << std::hex
<< _entryAddress
);
342 s
<< "<_start 0x" << std::hex
<< _entryAddress
<< ">";
344 disassembleFunctionAt(_entryAddress
, s
.str());
347 if (!manager
->hasFunctions()) {
349 text_section
.getAddress(text_entry
);
350 LOG4CXX_INFO(logger
, "No Symbols found, starting at the beginning of the text segment");
351 disassembleFunctionAt(text_entry
);
356 uint64_t LLVMDisassembler
<COFFT
>::entryAddress() {
357 const auto coffobject
= dyn_cast
<COFFObjectFile
>(o
);
358 const struct pe32_header
* pe32_header
;
359 const struct pe32plus_header
* pe32plus_header
;
361 coffobject
->getPE32PlusHeader(pe32plus_header
);
363 if (pe32plus_header
) {
364 return pe32plus_header
->AddressOfEntryPoint
;
366 coffobject
->getPE32Header(pe32_header
);
367 return pe32_header
->AddressOfEntryPoint
;
371 template <typename ELFT
>
372 uint64_t LLVMDisassembler
<ELFT
>::entryAddress() {
373 const auto elffile
= dyn_cast
<ELFObjectFile
<ELFT
>>(o
)->getELFFile();
374 const auto * header
= elffile
->getHeader();
376 return header
->e_entry
;
379 template <typename ELFT
>
380 void LLVMDisassembler
<ELFT
>::splitBlocks(Function
* function
) {
381 SectionRef text_section
= sections
[".text"];
383 text_section
.getContents(bytes
);
384 StringRefMemoryObject
ref(bytes
);
386 // Split blocks where jumps are going inside the block
387 for (auto it
= function
->blocks().begin();
388 it
!= function
->blocks().end();
390 BasicBlock
* current_block
= it
->second
;
392 uint64_t base_address
;
393 text_section
.getAddress(base_address
);
394 uint64_t current_address
= current_block
->getStartAddress() - base_address
;
395 while(current_block
->getEndAddress() - base_address
> current_address
) {
398 llvm::raw_string_ostream
s(buf
);
400 if(llvm::MCDisassembler::Success
==
401 DisAsm
->getInstruction(inst
, inst_size
, ref
, current_address
, nulls(), nulls())) {
402 // See if some other block starts here
403 BasicBlock
* other
= manager
->getBasicBlock(current_address
407 // Special case, other block starts here but we are at the end anyway
409 uint64_t endaddress
= current_address
+ inst_size
+ base_address
;
410 if (endaddress
!= current_block
->getEndAddress()) {
411 LOG4CXX_DEBUG(logger
, "Shortening block starting at "
413 << current_block
->getStartAddress()
415 << other
->getStartAddress());
416 function
->addBasicBlock(other
);
417 current_block
->setEndAddress(endaddress
);
418 current_block
->setNextBlock(0, other
->getStartAddress());
419 current_block
->setNextBlock(1, 0);
425 current_address
+= inst_size
;
431 void LLVMDisassembler
<COFFT
>::readDynamicSymbols() {
435 template <typename ELFT
>
436 void LLVMDisassembler
<ELFT
>::readDynamicSymbols() {
437 const auto elffile
= dyn_cast
<ELFObjectFile
<ELFT
>>(o
)->getELFFile();
438 for (auto it
= elffile
->begin_dynamic_symbols(),
439 end
= elffile
->end_dynamic_symbols();
442 if (it
->getType() == 2) { // Function
444 // TODO: Error handling
445 std::string symbolname
= *(elffile
->getSymbolName(it
));
446 std::string symbolversion
= *(elffile
->getSymbolVersion(nullptr, &*it
, is_default
));
447 manager
->signal_new_dyn_symbol(symbolname
+ (is_default
? "@@" : "@") + symbolversion
);
448 LOG4CXX_DEBUG(logger
, "Adding dynamic Symbol " << symbolname
<< (is_default
? "@@" : "@") << symbolversion
);
453 template <typename ELFT
>
454 void LLVMDisassembler
<ELFT
>::readSymbols() {
456 symbol_iterator
si(o
->symbol_begin()), se(o
->symbol_end());
457 for (; si
!= se
; ++si
) {
459 if ((ec
= si
->getName(name
))) {
460 LOG4CXX_ERROR(logger
, ec
.message());
463 LOG4CXX_DEBUG(logger
, "Added symbol " << name
.str());
464 symbols
.insert(make_pair(name
.str(), *si
));
468 template <typename ELFT
>
469 void LLVMDisassembler
<ELFT
>::readSections() {
471 section_iterator
i(o
->section_begin()), e(o
->section_end());
472 for (; i
!= e
; ++i
) {
474 if ((ec
= i
->getName(name
))) {
475 LOG4CXX_ERROR(logger
, ec
.message());
478 LOG4CXX_DEBUG(logger
, "Added section " << name
.str());
479 sections
.insert(make_pair(name
.str(), *i
));
484 // template <typename ELFT>
485 // void LLVMDisassembler<ELFT>::forEachFunction(std::function<void (uint64_t, Function*)> callback) {
486 // // std::for_each(functions.begin(), functions.end(),
487 // // [&](std::pair<uint64_t, Function*> x) {
488 // // callback(x.first, x.second);
492 template <typename ELFT
>
493 void LLVMDisassembler
<ELFT
>::printEachInstruction(uint64_t start
, uint64_t end
,
494 std::function
<void (uint8_t*, size_t,
496 const std::string
&)> fun
) {
497 SectionRef text_section
= sections
[".text"];
498 uint64_t base_address
;
499 text_section
.getAddress(base_address
);
500 uint64_t current_address
= start
- base_address
;
503 text_section
.getContents(bytes
);
504 StringRefMemoryObject
ref(bytes
);
506 while (current_address
< end
- base_address
) {
510 llvm::raw_string_ostream
s(buf
);
512 if(llvm::MCDisassembler::Success
==
513 DisAsm
->getInstruction(inst
, inst_size
, ref
, current_address
, nulls(), nulls())) {
515 uint8_t bytes
[inst_size
+2];
516 ref
.readBytes(current_address
, inst_size
, bytes
);
520 IP
->printInst(&inst
, s
, "");
521 if (MIA
->evaluateBranch(inst
, current_address
, inst_size
, jmptarget
)) {
522 std::stringstream stream
;
523 if (MIA
->isCall(inst
))
524 stream
<< "function:";
528 stream
<< std::hex
<< (base_address
+ jmptarget
);
533 fun(bytes
, inst_size
, s
.str(), ref
);
535 LOG4CXX_WARN(logger
, "Invalid byte at" << std::hex
<< current_address
+ base_address
);
536 fun(NULL
, 0, "Invalid Byte", "");
540 current_address
+= inst_size
;