1 #include "disassembler/Instruction.hxx"
2 #include "disassembler/llvm/LLVMDisassembler.hxx"
3 #include "core/InformationManager.hxx"
4 #include "core/Function.hxx"
5 #include "core/BasicBlock.hxx"
6 #include "core/Exception.hxx"
7 #include <boost/algorithm/string.hpp>
14 using namespace llvm::object
;
15 using std::error_code
;
30 Disassembler
* createLLVMDisassembler(const std::string
& filename
, InformationManager
* manager
) {
31 log4cxx::LoggerPtr
logger(log4cxx::Logger::getLogger("disassembler.LLVMDisassembler"));
35 auto retval
= createBinary(filename
);
36 if (error_code ec
= retval
.getError()) {
37 LOG4CXX_ERROR(logger
, ec
.message());
41 Binary
* op
= retval
.get();
42 #elif defined(LLVM_36)
43 OwningBinary
<Binary
> ob
;
44 ob
= std::move(retval
.get());
45 Binary
* op
= ob
.getBinary();
46 auto foo
= ob
.takeBinary();
52 // ELFType<endian, maxalign, 64bit>
53 if (ELF32LEObjectFile
* object
= dyn_cast
<ELF32LEObjectFile
>(op
)) {
54 return new LLVMDisassembler
<ELFType
<support::little
, 2, false>>(filename
, manager
, object
);
56 if (ELF64LEObjectFile
* object
= dyn_cast
<ELF64LEObjectFile
>(op
)) {
57 return new LLVMDisassembler
<ELFType
<support::little
, 2, true>>(filename
, manager
, object
);
59 if (ELF32BEObjectFile
* object
= dyn_cast
<ELF32BEObjectFile
>(op
)) {
60 return new LLVMDisassembler
<ELFType
<support::big
, 2, false>>(filename
, manager
, object
);
62 if (ELF64BEObjectFile
* object
= dyn_cast
<ELF64BEObjectFile
>(op
)) {
63 return new LLVMDisassembler
<ELFType
<support::big
, 2, true>>(filename
, manager
, object
);
65 if (COFFObjectFile
* object
= dyn_cast
<COFFObjectFile
>(op
)) {
66 return new LLVMDisassembler
<COFFT
>(filename
, manager
, object
);
68 if (MachOObjectFile
* object
= dyn_cast
<MachOObjectFile
>(op
)) {
69 return new LLVMDisassembler
<MACHOT
>(filename
, manager
, object
);
71 } catch (BinaryNotSupported
& e
) {
78 * TODO: fallback code falls die Datei kein ELF/PE/COFF/MacO/.. binary
79 * ist sondern z.B. einfach nur Instruktionen oder ein Bootsektor oder
82 template <typename ELFT
>
83 LLVMDisassembler
<ELFT
>::LLVMDisassembler(const std::string
& filename
,
84 InformationManager
* manager
,
87 , logger(log4cxx::Logger::getLogger("disassembler.LLVMDisassembler"))
88 , triple("unknown-unknown-unknown")
91 LOG4CXX_DEBUG(logger
, "Handling file " << filename
);
94 auto result
= createBinary(filename
);
97 if ((ec
= result
.getError())) {
98 LOG4CXX_ERROR(logger
, "Failed to load Binary" << ec
.message());
104 binary
.reset(result
.get());
105 #elif defined(LLVM_36)
106 OwningBinary
<Binary
> ob
;
107 ob
= std::move(result
.get());
108 Binary
* op
= ob
.getBinary();
113 o
= dyn_cast
<ObjectFile
>(binary
.get());
119 triple
.setArch(Triple::ArchType(o
->getArch()));
120 std::string
tripleName(triple
.getTriple());
122 LOG4CXX_INFO(logger
, "Architecture " << tripleName
);
126 target
= TargetRegistry::lookupTarget("", triple
, es
);
128 LOG4CXX_ERROR(logger
, es
);
129 BinaryNotSupported e
;
133 LOG4CXX_INFO(logger
, "Target " << target
->getName());
135 MRI
.reset(target
->createMCRegInfo(tripleName
));
137 LOG4CXX_ERROR(logger
, "no register info for target " << tripleName
);
138 BinaryNotSupported e
;
142 // Set up disassembler.
143 AsmInfo
.reset(target
->createMCAsmInfo(*MRI
, tripleName
));
145 LOG4CXX_ERROR(logger
, "no assembly info for target " << tripleName
);
146 BinaryNotSupported e
;
150 STI
.reset(target
->createMCSubtargetInfo(tripleName
, "", ""));
152 LOG4CXX_ERROR(logger
, "no subtarget info for target " << tripleName
);
153 BinaryNotSupported e
;
157 MII
.reset(target
->createMCInstrInfo());
159 LOG4CXX_ERROR(logger
, "no instruction info for target " << tripleName
);
160 BinaryNotSupported e
;
164 MOFI
.reset(new MCObjectFileInfo
);
165 MCContext
Ctx(AsmInfo
.get(), MRI
.get(), MOFI
.get());
167 DisAsm
.reset(target
->createMCDisassembler(*STI
, Ctx
));
169 LOG4CXX_ERROR(logger
, "no disassembler for target " << tripleName
);
170 BinaryNotSupported e
;
174 target
->createMCRelocationInfo(tripleName
, Ctx
));
177 // MCObjectSymbolizer::createObjectSymbolizer(Ctx, std::move(RelInfo), o));
179 // DisAsm->setSymbolizer(std::move(Symzer));
184 MIA
.reset(target
->createMCInstrAnalysis(MII
.get()));
186 LOG4CXX_ERROR(logger
, "no instruction analysis for target " << tripleName
);
187 BinaryNotSupported e
;
191 int AsmPrinterVariant
= AsmInfo
->getAssemblerDialect();
192 IP
.reset(target
->createMCInstPrinter(AsmPrinterVariant
, *AsmInfo
, *MII
, *MRI
, *STI
));
194 LOG4CXX_ERROR(logger
, "no instruction printer for target " << tripleName
);
195 BinaryNotSupported e
;
199 IP
->setPrintImmHex(llvm::HexStyle::C
);
200 IP
->setPrintImmHex(true);
202 // std::unique_ptr<MCObjectDisassembler> OD(
203 // new MCObjectDisassembler(*o, *DisAsm, *MIA));
204 //Mod.reset(OD->buildModule(false));
209 template <typename ELFT
>
210 void LLVMDisassembler
<ELFT
>::start() {
213 readDynamicSymbols();
216 template <typename ELFT
>
217 LLVMDisassembler
<ELFT
>::~LLVMDisassembler() {}
219 template <typename ELFT
>
220 Function
* LLVMDisassembler
<ELFT
>::disassembleFunctionAt(uint64_t address
, const std::string
& name
) {
222 SectionRef text_section
= getTextSection();
223 uint64_t base_address
, size
;
225 text_section
.getAddress(base_address
);
226 text_section
.getSize(size
);
227 #elif defined(LLVM_36)
228 base_address
= text_section
.getAddress();
229 size
= text_section
.getSize();
231 if (address
< base_address
||
232 address
>= base_address
+ size
) {
236 if (NULL
== (function
= manager
->getFunction(address
))) {
240 s
<< "<Unnamed 0x" << std::hex
<< address
<< ">";
241 function
= manager
->newFunction(address
);
242 function
->setName(s
.str());
244 function
= manager
->newFunction(address
);
245 function
->setName(name
);
247 disassembleFunction(function
);
253 template <typename ELFT
>
254 void LLVMDisassembler
<ELFT
>::disassembleFunction(Function
* function
) {
255 std::vector
<uint64_t> called_functions
;
256 std::stack
<BasicBlock
*> remaining_blocks
;
258 * Do all blocks get added properly? We should take care to remove
259 * the other ones at the end of the function!
261 std::map
<uint64_t, BasicBlock
*> new_blocks
;
262 SectionRef text_section
= getTextSection();
264 uint64_t base_address
, size
;
265 text_section
.getContents(bytes
);
267 StringRefMemoryObject
ref(bytes
);
268 text_section
.getAddress(base_address
);
269 text_section
.getSize(size
);
270 #elif defined(LLVM_36)
271 ArrayRef
<uint8_t> bytearray(reinterpret_cast<const uint8_t *>(bytes
.data()),
273 base_address
= text_section
.getAddress();
274 size
= text_section
.getSize();
276 #error LLVM != 3.5 | 3.6 not supported
279 LOG4CXX_DEBUG(logger
, "Handling function " << function
->getName());
281 if(function
->getStartAddress() < base_address
|| function
->getStartAddress() > base_address
+ size
) {
282 LOG4CXX_INFO(logger
, "Trying to disassemble function " << function
->getName() << " but start address " << std::hex
<< function
->getStartAddress() << " is located outside the text segment");
286 BasicBlock
* block
= manager
->newBasicBlock(function
->getStartAddress());
287 remaining_blocks
.push(block
);
288 new_blocks
.insert(std::make_pair(block
->getStartAddress(), block
));
289 function
->addBasicBlock(block
);
291 LOG4CXX_DEBUG(logger
, "Text section at " << std::hex
<< base_address
<< " with size " << size
);
293 while (remaining_blocks
.size()) {
294 BasicBlock
* current_block
= remaining_blocks
.top();
295 remaining_blocks
.pop();
297 LOG4CXX_DEBUG(logger
, "Handling Block starting at " << std::hex
298 << current_block
->getStartAddress());
301 uint64_t current_address
= current_block
->getStartAddress() - base_address
;
305 llvm::raw_string_ostream
s(buf
);
307 if(llvm::MCDisassembler::Success
==
309 DisAsm
->getInstruction(inst
, inst_size
, ref
, current_address
, nulls(), nulls())) {
310 #elif defined(LLVM_36)
311 DisAsm
->getInstruction(inst
, inst_size
,
312 bytearray
.slice(current_address
),
313 base_address
+ current_address
,
318 if (MIA
->evaluateBranch(inst
, current_address
, inst_size
, jmptarget
)) {
319 jmptarget
+= base_address
;
320 if (!MIA
->isIndirectBranch(inst
)) {
321 if (MIA
->isCall(inst
)) {
322 if (NULL
== manager
->getFunction(jmptarget
))
323 called_functions
.push_back(jmptarget
);
325 if(jmptarget
< base_address
|| jmptarget
> base_address
+ size
) {
326 if (MIA
->isConditionalBranch(inst
)) {
327 LOG4CXX_WARN(logger
, "Conditional jump out of the text segment. This should never happen!");
329 LOG4CXX_INFO(logger
, "Unconditional jump to PLT. Assuming Tail-Call to some library");
330 current_address
+= inst_size
;
334 current_block
->setNextBlock(0, jmptarget
);
335 if (new_blocks
.find(jmptarget
) == new_blocks
.end()) {
336 BasicBlock
* block
= manager
->newBasicBlock(jmptarget
);
338 new_blocks
.insert(std::make_pair(block
->getStartAddress(), block
));
339 function
->addBasicBlock(block
);
340 remaining_blocks
.push(block
);
342 LOG4CXX_DEBUG(logger
, "Reusing Block starting at " << std::hex
343 << current_block
->getStartAddress());
344 function
->addBasicBlock(new_blocks
.find(jmptarget
)->second
);
346 if (MIA
->isConditionalBranch(inst
)) {
347 jmptarget
= base_address
+ current_address
+ inst_size
;
348 current_block
->setNextBlock(1, jmptarget
);
349 if (new_blocks
.find(jmptarget
) == new_blocks
.end()) {
350 BasicBlock
* block
= manager
->newBasicBlock(jmptarget
);
352 new_blocks
.insert(std::make_pair(block
->getStartAddress(), block
));
353 function
->addBasicBlock(block
);
354 remaining_blocks
.push(block
);
356 LOG4CXX_DEBUG(logger
, "Reusing Block starting at " << std::hex
357 << current_block
->getStartAddress());
358 function
->addBasicBlock(new_blocks
.find(jmptarget
)->second
);
369 if (inst_size
== 0 || MIA
->isTerminator(inst
) || MIA
->isBranch(inst
)) {
370 current_block
->setEndAddress(current_address
+ base_address
+ inst_size
);
371 LOG4CXX_DEBUG(logger
, "Finished Block at " << std::hex
<<
372 current_block
->getEndAddress());
375 current_address
+= inst_size
;
378 splitBlocks(function
);
379 LOG4CXX_DEBUG(logger
, "Finished function " << function
->getName());
380 manager
->finishFunction(function
);
381 for (uint64_t address
: called_functions
)
382 disassembleFunctionAt(address
);
385 template <typename ELFT
>
386 void LLVMDisassembler
<ELFT
>::disassemble() {
387 SectionRef text_section
= getTextSection();
388 std::vector
<Function
*> remaining_functions
;
390 // Assume all function symbols actually start a real function
391 for (auto x
= symbols
.begin(); x
!= symbols
.end(); ++x
) {
394 SymbolRef::Type symbol_type
;
397 if (text_section
.containsSymbol(x
->second
, contains
) || !contains
)
398 #elif defined(LLVM_36)
399 if (!text_section
.containsSymbol(x
->second
))
403 if (x
->second
.getType(symbol_type
)
404 || SymbolRef::ST_Function
!= symbol_type
)
407 if (!x
->second
.getAddress(result
)) {
408 Function
* fun
= manager
->newFunction(result
);
410 fun
->setName(x
->first
);
411 remaining_functions
.push_back(fun
);
412 LOG4CXX_DEBUG(logger
, "Disasembling " << x
->first
);
414 LOG4CXX_DEBUG(logger
, "Function at " << std::hex
<< result
415 << " already disassembled as " << manager
->getFunction(result
)->getName());
420 for (Function
* function
: remaining_functions
) {
421 disassembleFunction(function
);
422 manager
->finishFunction(function
);
425 if (binary
->isELF()) {
426 uint64_t _entryAddress
= entryAddress();
427 LOG4CXX_DEBUG(logger
, "Adding entryAddress at: " << std::hex
<< _entryAddress
);
429 s
<< "<_start 0x" << std::hex
<< _entryAddress
<< ">";
431 disassembleFunctionAt(_entryAddress
, s
.str());
434 if (!manager
->hasFunctions()) {
437 text_section
.getAddress(text_entry
);
438 #elif defined(LLVM_36)
439 text_entry
= text_section
.getAddress();
441 LOG4CXX_INFO(logger
, "No Symbols found, starting at the beginning of the text segment");
442 disassembleFunctionAt(text_entry
);
447 uint64_t LLVMDisassembler
<COFFT
>::entryAddress() {
448 const auto coffobject
= dyn_cast
<COFFObjectFile
>(o
);
449 const struct pe32_header
* pe32_header
;
450 const struct pe32plus_header
* pe32plus_header
;
452 coffobject
->getPE32PlusHeader(pe32plus_header
);
454 if (pe32plus_header
) {
455 return pe32plus_header
->AddressOfEntryPoint
;
457 coffobject
->getPE32Header(pe32_header
);
458 return pe32_header
->AddressOfEntryPoint
;
463 uint64_t LLVMDisassembler
<MACHOT
>::entryAddress() {
468 template <typename ELFT
>
469 uint64_t LLVMDisassembler
<ELFT
>::entryAddress() {
470 const auto elffile
= dyn_cast
<ELFObjectFile
<ELFT
>>(o
)->getELFFile();
471 const auto * header
= elffile
->getHeader();
473 return header
->e_entry
;
476 template <typename ELFT
>
477 void LLVMDisassembler
<ELFT
>::splitBlocks(Function
* function
) {
478 SectionRef text_section
= getTextSection();
480 text_section
.getContents(bytes
);
482 StringRefMemoryObject
ref(bytes
);
483 #elif defined(LLVM_36)
484 ArrayRef
<uint8_t> bytearray(reinterpret_cast<const uint8_t *>(bytes
.data()),
489 LOG4CXX_DEBUG(logger
, "Splitting Blocks in Function " << function
->getName());
490 // Split blocks where jumps are going inside the block
491 for (auto it
= function
->blocks().begin();
492 it
!= function
->blocks().end();
494 BasicBlock
* current_block
= it
->second
;
495 if (current_block
->getEndAddress() == 0) {
496 LOG4CXX_ERROR(logger
, "UNFINISHED BLOCK " << std::hex
<< current_block
->getStartAddress());
500 uint64_t base_address
;
502 text_section
.getAddress(base_address
);
503 #elif defined(LLVM_36)
504 base_address
= text_section
.getAddress();
506 uint64_t current_address
= current_block
->getStartAddress() - base_address
;
507 while(current_block
->getEndAddress() - base_address
> current_address
) {
510 llvm::raw_string_ostream
s(buf
);
512 if(llvm::MCDisassembler::Success
==
514 DisAsm
->getInstruction(inst
, inst_size
, ref
, current_address
, nulls(), nulls())) {
515 #elif defined(LLVM_36)
516 DisAsm
->getInstruction(inst
, inst_size
,
517 bytearray
.slice(current_address
),
518 base_address
+ current_address
,
522 // See if some other block starts here
523 BasicBlock
* other
= manager
->getBasicBlock(current_address
527 // Special case, other block starts here but we are at the end anyway
529 uint64_t endaddress
= current_address
+ inst_size
+ base_address
;
530 if (endaddress
!= current_block
->getEndAddress()) {
531 LOG4CXX_DEBUG(logger
, "Shortening block starting at "
533 << current_block
->getStartAddress()
535 << other
->getStartAddress());
536 function
->addBasicBlock(other
);
537 current_block
->setEndAddress(endaddress
);
538 current_block
->setNextBlock(0, other
->getStartAddress());
539 current_block
->setNextBlock(1, 0);
545 current_address
+= inst_size
;
551 void LLVMDisassembler
<COFFT
>::readDynamicSymbols() {
556 void LLVMDisassembler
<MACHOT
>::readDynamicSymbols() {
560 template <typename ELFT
>
561 void LLVMDisassembler
<ELFT
>::readDynamicSymbols() {
562 const auto elffile
= dyn_cast
<ELFObjectFile
<ELFT
>>(o
)->getELFFile();
563 for (auto it
= elffile
->begin_dynamic_symbols(),
564 end
= elffile
->end_dynamic_symbols();
567 if (it
->getType() == 2) { // Function
569 // TODO: Error handling
570 std::string symbolname
= *(elffile
->getSymbolName(it
));
571 std::string symbolversion
= *(elffile
->getSymbolVersion(nullptr, &*it
, is_default
));
572 // TODO: actually get the symbol address from relocations
573 Function
* f
= manager
->newDynamicFunction(0);
574 f
->setName(symbolname
+ (is_default
? "@@" : "@") + symbolversion
);
575 manager
->finishFunction(f
);
577 LOG4CXX_DEBUG(logger
, "Adding dynamic Symbol " << symbolname
<< (is_default
? "@@" : "@") << symbolversion
);
582 template <typename ELFT
>
583 void LLVMDisassembler
<ELFT
>::readSymbols() {
585 symbol_iterator
si(o
->symbol_begin()), se(o
->symbol_end());
586 for (; si
!= se
; ++si
) {
589 si
->getAddress(address
);
590 if ((ec
= si
->getName(name
))) {
591 LOG4CXX_ERROR(logger
, ec
.message());
594 LOG4CXX_DEBUG(logger
, "Added symbol " << name
.str() << " at address " << std::hex
<< address
);
595 symbols
.insert(make_pair(name
.str(), *si
));
599 template <typename ELFT
>
600 void LLVMDisassembler
<ELFT
>::readSections() {
602 section_iterator
i(o
->section_begin()), e(o
->section_end());
603 for (; i
!= e
; ++i
) {
605 if ((ec
= i
->getName(name
))) {
606 LOG4CXX_ERROR(logger
, ec
.message());
609 LOG4CXX_DEBUG(logger
, "Added section " << name
.str());
610 sections
.insert(make_pair(name
.str(), *i
));
615 // template <typename ELFT>
616 // void LLVMDisassembler<ELFT>::forEachFunction(std::function<void (uint64_t, Function*)> callback) {
617 // // std::for_each(functions.begin(), functions.end(),
618 // // [&](std::pair<uint64_t, Function*> x) {
619 // // callback(x.first, x.second);
623 template <typename ELFT
>
624 std::vector
<Instruction
> LLVMDisassembler
<ELFT
>::getInstructions(const BasicBlock
*block
) {
625 std::vector
<Instruction
> result
;
626 SectionRef text_section
= getTextSection();
627 uint64_t base_address
;
629 text_section
.getAddress(base_address
);
630 #elif defined(LLVM_36)
631 base_address
= text_section
.getAddress();
634 uint64_t current_address
= block
->getStartAddress() - base_address
;
635 uint64_t end_position
= block
->getEndAddress() - base_address
;
638 text_section
.getContents(bytes
);
640 StringRefMemoryObject
ref(bytes
);
641 #elif defined(LLVM_36)
642 ArrayRef
<uint8_t> bytearray(reinterpret_cast<const uint8_t *>(bytes
.data()),
647 while (current_address
< end_position
) {
651 llvm::raw_string_ostream
s(buf
);
653 if(llvm::MCDisassembler::Success
==
655 DisAsm
->getInstruction(inst
, inst_size
, ref
, current_address
, nulls(), nulls())) {
656 #elif defined(LLVM_36)
657 DisAsm
->getInstruction(inst
, inst_size
,
658 bytearray
.slice(current_address
),
659 base_address
+ current_address
,
663 uint8_t bytes
[inst_size
+2];
665 ref
.readBytes(current_address
, inst_size
, bytes
);
666 #elif defined(LLVM_36)
667 size_t bytesindex(0);
668 for (uint8_t byte
: bytearray
.slice(current_address
, inst_size
)) {
669 bytes
[bytesindex
++] = byte
;
675 IP
->printInst(&inst
, s
, "");
676 if (MIA
->evaluateBranch(inst
, current_address
, inst_size
, jmptarget
)) {
677 std::stringstream stream
;
678 if (MIA
->isCall(inst
))
679 stream
<< "function:";
683 stream
<< std::hex
<< (base_address
+ jmptarget
);
686 result
.push_back(Instruction(current_address
+ base_address
, boost::algorithm::trim_copy(s
.str()),
687 std::vector
<uint8_t>(bytes
, bytes
+inst_size
), ref
));
689 LOG4CXX_WARN(logger
, "Invalid byte at" << std::hex
<< current_address
+ base_address
);
692 ref
.readBytes(current_address
, 1, bytes
);
693 #elif defined(LLVM_36)
694 bytes
[0] = bytearray
[current_address
];
696 result
.push_back(Instruction(current_address
+ base_address
, "Invalid Instruction",
697 std::vector
<uint8_t>(bytes
, bytes
+1), ""));
701 current_address
+= inst_size
;
706 template <typename ELFT
>
707 SectionRef LLVMDisassembler
<ELFT
>::getTextSection() {
708 return sections
[".text"];
712 SectionRef LLVMDisassembler
<MACHOT
>::getTextSection() {
713 return sections
["__text"];