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 current_block
->setNextBlock(0, jmptarget
);
326 if (new_blocks
.find(jmptarget
) == new_blocks
.end()) {
327 BasicBlock
* block
= manager
->newBasicBlock(jmptarget
);
329 new_blocks
.insert(std::make_pair(block
->getStartAddress(), block
));
330 function
->addBasicBlock(block
);
331 remaining_blocks
.push(block
);
333 LOG4CXX_DEBUG(logger
, "Reusing Block starting at " << std::hex
334 << current_block
->getStartAddress());
335 function
->addBasicBlock(new_blocks
.find(jmptarget
)->second
);
337 if (MIA
->isConditionalBranch(inst
)) {
338 jmptarget
= base_address
+ current_address
+ inst_size
;
339 current_block
->setNextBlock(1, jmptarget
);
340 if (new_blocks
.find(jmptarget
) == new_blocks
.end()) {
341 BasicBlock
* block
= manager
->newBasicBlock(jmptarget
);
343 new_blocks
.insert(std::make_pair(block
->getStartAddress(), block
));
344 function
->addBasicBlock(block
);
345 remaining_blocks
.push(block
);
347 LOG4CXX_DEBUG(logger
, "Reusing Block starting at " << std::hex
348 << current_block
->getStartAddress());
349 function
->addBasicBlock(new_blocks
.find(jmptarget
)->second
);
360 if (inst_size
== 0 || MIA
->isTerminator(inst
) || MIA
->isBranch(inst
)) {
361 current_block
->setEndAddress(current_address
+ base_address
+ inst_size
);
362 LOG4CXX_DEBUG(logger
, "Finished Block at " << std::hex
<<
363 current_block
->getEndAddress());
366 current_address
+= inst_size
;
369 splitBlocks(function
);
370 LOG4CXX_DEBUG(logger
, "Finished function " << function
->getName());
371 manager
->finishFunction(function
);
372 for (uint64_t address
: called_functions
)
373 disassembleFunctionAt(address
);
376 template <typename ELFT
>
377 void LLVMDisassembler
<ELFT
>::disassemble() {
378 SectionRef text_section
= getTextSection();
379 std::vector
<Function
*> remaining_functions
;
381 // Assume all function symbols actually start a real function
382 for (auto x
= symbols
.begin(); x
!= symbols
.end(); ++x
) {
385 SymbolRef::Type symbol_type
;
388 if (text_section
.containsSymbol(x
->second
, contains
) || !contains
)
389 #elif defined(LLVM_36)
390 if (!text_section
.containsSymbol(x
->second
))
394 if (x
->second
.getType(symbol_type
)
395 || SymbolRef::ST_Function
!= symbol_type
)
398 if (!x
->second
.getAddress(result
)) {
399 Function
* fun
= manager
->newFunction(result
);
401 fun
->setName(x
->first
);
402 remaining_functions
.push_back(fun
);
403 LOG4CXX_DEBUG(logger
, "Disasembling " << x
->first
);
405 LOG4CXX_DEBUG(logger
, "Function at " << std::hex
<< result
406 << " already disassembled as " << manager
->getFunction(result
)->getName());
411 for (Function
* function
: remaining_functions
) {
412 disassembleFunction(function
);
413 manager
->finishFunction(function
);
416 if (binary
->isELF()) {
417 uint64_t _entryAddress
= entryAddress();
418 LOG4CXX_DEBUG(logger
, "Adding entryAddress at: " << std::hex
<< _entryAddress
);
420 s
<< "<_start 0x" << std::hex
<< _entryAddress
<< ">";
422 disassembleFunctionAt(_entryAddress
, s
.str());
425 if (!manager
->hasFunctions()) {
428 text_section
.getAddress(text_entry
);
429 #elif defined(LLVM_36)
430 text_entry
= text_section
.getAddress();
432 LOG4CXX_INFO(logger
, "No Symbols found, starting at the beginning of the text segment");
433 disassembleFunctionAt(text_entry
);
438 uint64_t LLVMDisassembler
<COFFT
>::entryAddress() {
439 const auto coffobject
= dyn_cast
<COFFObjectFile
>(o
);
440 const struct pe32_header
* pe32_header
;
441 const struct pe32plus_header
* pe32plus_header
;
443 coffobject
->getPE32PlusHeader(pe32plus_header
);
445 if (pe32plus_header
) {
446 return pe32plus_header
->AddressOfEntryPoint
;
448 coffobject
->getPE32Header(pe32_header
);
449 return pe32_header
->AddressOfEntryPoint
;
454 uint64_t LLVMDisassembler
<MACHOT
>::entryAddress() {
459 template <typename ELFT
>
460 uint64_t LLVMDisassembler
<ELFT
>::entryAddress() {
461 const auto elffile
= dyn_cast
<ELFObjectFile
<ELFT
>>(o
)->getELFFile();
462 const auto * header
= elffile
->getHeader();
464 return header
->e_entry
;
467 template <typename ELFT
>
468 void LLVMDisassembler
<ELFT
>::splitBlocks(Function
* function
) {
469 SectionRef text_section
= getTextSection();
471 text_section
.getContents(bytes
);
473 StringRefMemoryObject
ref(bytes
);
474 #elif defined(LLVM_36)
475 ArrayRef
<uint8_t> bytearray(reinterpret_cast<const uint8_t *>(bytes
.data()),
480 LOG4CXX_DEBUG(logger
, "Splitting Blocks in Function " << function
->getName());
481 // Split blocks where jumps are going inside the block
482 for (auto it
= function
->blocks().begin();
483 it
!= function
->blocks().end();
485 BasicBlock
* current_block
= it
->second
;
486 if (current_block
->getEndAddress() == 0) {
487 LOG4CXX_ERROR(logger
, "UNFINISHED BLOCK " << std::hex
<< current_block
->getStartAddress());
491 uint64_t base_address
;
493 text_section
.getAddress(base_address
);
494 #elif defined(LLVM_36)
495 base_address
= text_section
.getAddress();
497 uint64_t current_address
= current_block
->getStartAddress() - base_address
;
498 while(current_block
->getEndAddress() - base_address
> current_address
) {
501 llvm::raw_string_ostream
s(buf
);
503 if(llvm::MCDisassembler::Success
==
505 DisAsm
->getInstruction(inst
, inst_size
, ref
, current_address
, nulls(), nulls())) {
506 #elif defined(LLVM_36)
507 DisAsm
->getInstruction(inst
, inst_size
,
508 bytearray
.slice(current_address
),
509 base_address
+ current_address
,
513 // See if some other block starts here
514 BasicBlock
* other
= manager
->getBasicBlock(current_address
518 // Special case, other block starts here but we are at the end anyway
520 uint64_t endaddress
= current_address
+ inst_size
+ base_address
;
521 if (endaddress
!= current_block
->getEndAddress()) {
522 LOG4CXX_DEBUG(logger
, "Shortening block starting at "
524 << current_block
->getStartAddress()
526 << other
->getStartAddress());
527 function
->addBasicBlock(other
);
528 current_block
->setEndAddress(endaddress
);
529 current_block
->setNextBlock(0, other
->getStartAddress());
530 current_block
->setNextBlock(1, 0);
536 current_address
+= inst_size
;
542 void LLVMDisassembler
<COFFT
>::readDynamicSymbols() {
547 void LLVMDisassembler
<MACHOT
>::readDynamicSymbols() {
551 template <typename ELFT
>
552 void LLVMDisassembler
<ELFT
>::readDynamicSymbols() {
553 const auto elffile
= dyn_cast
<ELFObjectFile
<ELFT
>>(o
)->getELFFile();
554 for (auto it
= elffile
->begin_dynamic_symbols(),
555 end
= elffile
->end_dynamic_symbols();
558 if (it
->getType() == 2) { // Function
560 // TODO: Error handling
561 std::string symbolname
= *(elffile
->getSymbolName(it
));
562 std::string symbolversion
= *(elffile
->getSymbolVersion(nullptr, &*it
, is_default
));
563 // TODO: actually get the symbol address from relocations
564 Function
* f
= manager
->newDynamicFunction(0);
565 f
->setName(symbolname
+ (is_default
? "@@" : "@") + symbolversion
);
566 manager
->finishFunction(f
);
568 LOG4CXX_DEBUG(logger
, "Adding dynamic Symbol " << symbolname
<< (is_default
? "@@" : "@") << symbolversion
);
573 template <typename ELFT
>
574 void LLVMDisassembler
<ELFT
>::readSymbols() {
576 symbol_iterator
si(o
->symbol_begin()), se(o
->symbol_end());
577 for (; si
!= se
; ++si
) {
580 si
->getAddress(address
);
581 if ((ec
= si
->getName(name
))) {
582 LOG4CXX_ERROR(logger
, ec
.message());
585 LOG4CXX_DEBUG(logger
, "Added symbol " << name
.str() << " at address " << std::hex
<< address
);
586 symbols
.insert(make_pair(name
.str(), *si
));
590 template <typename ELFT
>
591 void LLVMDisassembler
<ELFT
>::readSections() {
593 section_iterator
i(o
->section_begin()), e(o
->section_end());
594 for (; i
!= e
; ++i
) {
596 if ((ec
= i
->getName(name
))) {
597 LOG4CXX_ERROR(logger
, ec
.message());
600 LOG4CXX_DEBUG(logger
, "Added section " << name
.str());
601 sections
.insert(make_pair(name
.str(), *i
));
606 // template <typename ELFT>
607 // void LLVMDisassembler<ELFT>::forEachFunction(std::function<void (uint64_t, Function*)> callback) {
608 // // std::for_each(functions.begin(), functions.end(),
609 // // [&](std::pair<uint64_t, Function*> x) {
610 // // callback(x.first, x.second);
614 template <typename ELFT
>
615 std::vector
<Instruction
> LLVMDisassembler
<ELFT
>::getInstructions(const BasicBlock
*block
) {
616 std::vector
<Instruction
> result
;
617 SectionRef text_section
= getTextSection();
618 uint64_t base_address
;
620 text_section
.getAddress(base_address
);
621 #elif defined(LLVM_36)
622 base_address
= text_section
.getAddress();
625 uint64_t current_address
= block
->getStartAddress() - base_address
;
626 uint64_t end_position
= block
->getEndAddress() - base_address
;
629 text_section
.getContents(bytes
);
631 StringRefMemoryObject
ref(bytes
);
632 #elif defined(LLVM_36)
633 ArrayRef
<uint8_t> bytearray(reinterpret_cast<const uint8_t *>(bytes
.data()),
638 while (current_address
< end_position
) {
642 llvm::raw_string_ostream
s(buf
);
644 if(llvm::MCDisassembler::Success
==
646 DisAsm
->getInstruction(inst
, inst_size
, ref
, current_address
, nulls(), nulls())) {
647 #elif defined(LLVM_36)
648 DisAsm
->getInstruction(inst
, inst_size
,
649 bytearray
.slice(current_address
),
650 base_address
+ current_address
,
654 uint8_t bytes
[inst_size
+2];
656 ref
.readBytes(current_address
, inst_size
, bytes
);
657 #elif defined(LLVM_36)
658 size_t bytesindex(0);
659 for (uint8_t byte
: bytearray
.slice(current_address
, inst_size
)) {
660 bytes
[bytesindex
++] = byte
;
666 IP
->printInst(&inst
, s
, "");
667 if (MIA
->evaluateBranch(inst
, current_address
, inst_size
, jmptarget
)) {
668 std::stringstream stream
;
669 if (MIA
->isCall(inst
))
670 stream
<< "function:";
674 stream
<< std::hex
<< (base_address
+ jmptarget
);
677 result
.push_back(Instruction(current_address
+ base_address
, boost::algorithm::trim_copy(s
.str()),
678 std::vector
<uint8_t>(bytes
, bytes
+inst_size
), ref
));
680 LOG4CXX_WARN(logger
, "Invalid byte at" << std::hex
<< current_address
+ base_address
);
683 ref
.readBytes(current_address
, 1, bytes
);
684 #elif defined(LLVM_36)
685 bytes
[0] = bytearray
[current_address
];
687 result
.push_back(Instruction(current_address
+ base_address
, "Invalid Instruction",
688 std::vector
<uint8_t>(bytes
, bytes
+1), ""));
692 current_address
+= inst_size
;
697 template <typename ELFT
>
698 SectionRef LLVMDisassembler
<ELFT
>::getTextSection() {
699 return sections
[".text"];
703 SectionRef LLVMDisassembler
<MACHOT
>::getTextSection() {
704 return sections
["__text"];