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
,
221 const std::string
& name
) {
223 SectionRef text_section
= getTextSection();
224 uint64_t base_address
, size
;
226 text_section
.getAddress(base_address
);
227 text_section
.getSize(size
);
228 #elif defined(LLVM_36)
229 base_address
= text_section
.getAddress();
230 size
= text_section
.getSize();
232 if (address
< base_address
||
233 address
>= base_address
+ size
) {
237 if (NULL
== (function
= manager
->getFunction(address
))) {
241 s
<< "<Unnamed 0x" << std::hex
<< address
<< ">";
242 function
= manager
->newFunction(address
);
243 function
->setName(s
.str());
245 function
= manager
->newFunction(address
);
246 function
->setName(name
);
248 disassembleFunction(function
);
254 template <typename ELFT
>
255 void LLVMDisassembler
<ELFT
>::disassembleFunction(Function
* function
) {
256 std::vector
<uint64_t> called_functions
;
257 std::stack
<BasicBlock
*> remaining_blocks
;
259 * Do all blocks get added properly? We should take care to remove
260 * the other ones at the end of the function!
262 std::map
<uint64_t, BasicBlock
*> new_blocks
;
263 SectionRef text_section
= getTextSection();
265 uint64_t base_address
, size
;
266 text_section
.getContents(bytes
);
268 StringRefMemoryObject
ref(bytes
);
269 text_section
.getAddress(base_address
);
270 text_section
.getSize(size
);
271 #elif defined(LLVM_36)
272 ArrayRef
<uint8_t> bytearray(reinterpret_cast<const uint8_t *>(bytes
.data()),
274 base_address
= text_section
.getAddress();
275 size
= text_section
.getSize();
277 #error LLVM != 3.5 | 3.6 not supported
280 LOG4CXX_DEBUG(logger
, "Handling function " << function
->getName());
282 if(function
->getStartAddress() < base_address
|| function
->getStartAddress() > base_address
+ size
) {
283 LOG4CXX_INFO(logger
, "Trying to disassemble function " << function
->getName() << " but start address " << std::hex
<< function
->getStartAddress() << " is located outside the text segment");
287 BasicBlock
* block
= manager
->newBasicBlock(function
->getStartAddress());
288 remaining_blocks
.push(block
);
289 new_blocks
.insert(std::make_pair(block
->getStartAddress(), block
));
290 function
->addBasicBlock(block
);
292 LOG4CXX_DEBUG(logger
, "Text section at " << std::hex
<< base_address
<< " with size " << size
);
294 while (remaining_blocks
.size()) {
295 BasicBlock
* current_block
= remaining_blocks
.top();
296 remaining_blocks
.pop();
298 LOG4CXX_DEBUG(logger
, "Handling Block starting at " << std::hex
299 << current_block
->getStartAddress());
302 uint64_t current_address
= current_block
->getStartAddress() - base_address
;
306 llvm::raw_string_ostream
s(buf
);
308 if(llvm::MCDisassembler::Success
==
310 DisAsm
->getInstruction(inst
, inst_size
, ref
, current_address
, nulls(), nulls())) {
311 #elif defined(LLVM_36)
312 DisAsm
->getInstruction(inst
, inst_size
,
313 bytearray
.slice(current_address
),
314 base_address
+ current_address
,
319 if (MIA
->evaluateBranch(inst
, current_address
, inst_size
, jmptarget
)) {
320 jmptarget
+= base_address
;
321 if (!MIA
->isIndirectBranch(inst
)) {
322 if (MIA
->isCall(inst
)) {
323 if (NULL
== manager
->getFunction(jmptarget
))
324 called_functions
.push_back(jmptarget
);
326 if(jmptarget
< base_address
|| jmptarget
> base_address
+ size
) {
327 if (MIA
->isConditionalBranch(inst
)) {
328 LOG4CXX_WARN(logger
, "Conditional jump out of the text segment. This should never happen!");
330 LOG4CXX_INFO(logger
, "Unconditional jump to PLT. Assuming Tail-Call to some library");
331 current_address
+= inst_size
;
335 current_block
->setNextBlock(0, jmptarget
);
336 if (new_blocks
.find(jmptarget
) == new_blocks
.end()) {
337 BasicBlock
* block
= manager
->newBasicBlock(jmptarget
);
339 new_blocks
.insert(std::make_pair(block
->getStartAddress(), block
));
340 function
->addBasicBlock(block
);
341 remaining_blocks
.push(block
);
343 LOG4CXX_DEBUG(logger
, "Reusing Block starting at " << std::hex
344 << current_block
->getStartAddress());
345 function
->addBasicBlock(new_blocks
.find(jmptarget
)->second
);
347 if (MIA
->isConditionalBranch(inst
)) {
348 jmptarget
= base_address
+ current_address
+ inst_size
;
349 current_block
->setNextBlock(1, jmptarget
);
350 if (new_blocks
.find(jmptarget
) == new_blocks
.end()) {
351 BasicBlock
* block
= manager
->newBasicBlock(jmptarget
);
353 new_blocks
.insert(std::make_pair(block
->getStartAddress(), block
));
354 function
->addBasicBlock(block
);
355 remaining_blocks
.push(block
);
357 LOG4CXX_DEBUG(logger
, "Reusing Block starting at " << std::hex
358 << current_block
->getStartAddress());
359 function
->addBasicBlock(new_blocks
.find(jmptarget
)->second
);
370 if (inst_size
== 0 || MIA
->isTerminator(inst
) || MIA
->isBranch(inst
)) {
371 current_block
->setEndAddress(current_address
+ base_address
+ inst_size
);
372 LOG4CXX_DEBUG(logger
, "Finished Block at " << std::hex
<<
373 current_block
->getEndAddress());
376 current_address
+= inst_size
;
379 splitBlocks(function
);
380 LOG4CXX_DEBUG(logger
, "Finished function " << function
->getName());
381 manager
->finishFunction(function
);
382 for (uint64_t address
: called_functions
)
383 disassembleFunctionAt(address
);
386 template <typename ELFT
>
387 void LLVMDisassembler
<ELFT
>::disassemble() {
388 SectionRef text_section
= getTextSection();
389 std::vector
<Function
*> remaining_functions
;
391 // Assume all function symbols actually start a real function
392 for (auto x
= symbols
.begin(); x
!= symbols
.end(); ++x
) {
394 SymbolRef::Type symbol_type
;
398 if (text_section
.containsSymbol(x
->second
, contains
) || !contains
)
399 #elif defined(LLVM_36)
400 if (!text_section
.containsSymbol(x
->second
))
404 if (x
->second
.getType(symbol_type
)
405 || SymbolRef::ST_Function
!= symbol_type
)
408 if (!x
->second
.getAddress(result
)) {
409 Function
* fun
= manager
->newFunction(result
);
411 fun
->setName(x
->first
);
412 remaining_functions
.push_back(fun
);
413 LOG4CXX_DEBUG(logger
, "Disasembling " << x
->first
);
415 LOG4CXX_DEBUG(logger
, "Function at " << std::hex
<< result
416 << " already disassembled as " << manager
->getFunction(result
)->getName());
421 for (Function
* function
: remaining_functions
) {
422 disassembleFunction(function
);
423 manager
->finishFunction(function
);
426 if (binary
->isELF()) {
427 uint64_t _entryAddress
= entryAddress();
428 LOG4CXX_DEBUG(logger
, "Adding entryAddress at: " << std::hex
<< _entryAddress
);
430 s
<< "<_start 0x" << std::hex
<< _entryAddress
<< ">";
432 disassembleFunctionAt(_entryAddress
, s
.str());
435 if (!manager
->hasFunctions()) {
438 text_section
.getAddress(text_entry
);
439 #elif defined(LLVM_36)
440 text_entry
= text_section
.getAddress();
442 LOG4CXX_INFO(logger
, "No Symbols found, starting at the beginning of the text segment");
443 disassembleFunctionAt(text_entry
);
448 uint64_t LLVMDisassembler
<COFFT
>::entryAddress() {
449 const auto coffobject
= dyn_cast
<COFFObjectFile
>(o
);
450 const struct pe32_header
* pe32_header
;
451 const struct pe32plus_header
* pe32plus_header
;
453 coffobject
->getPE32PlusHeader(pe32plus_header
);
455 if (pe32plus_header
) {
456 return pe32plus_header
->AddressOfEntryPoint
;
458 coffobject
->getPE32Header(pe32_header
);
459 return pe32_header
->AddressOfEntryPoint
;
464 uint64_t LLVMDisassembler
<MACHOT
>::entryAddress() {
469 template <typename ELFT
>
470 uint64_t LLVMDisassembler
<ELFT
>::entryAddress() {
471 const auto elffile
= dyn_cast
<ELFObjectFile
<ELFT
>>(o
)->getELFFile();
472 const auto * header
= elffile
->getHeader();
474 return header
->e_entry
;
477 template <typename ELFT
>
478 void LLVMDisassembler
<ELFT
>::splitBlocks(Function
* function
) {
479 SectionRef text_section
= getTextSection();
481 text_section
.getContents(bytes
);
483 StringRefMemoryObject
ref(bytes
);
484 #elif defined(LLVM_36)
485 ArrayRef
<uint8_t> bytearray(reinterpret_cast<const uint8_t *>(bytes
.data()),
490 LOG4CXX_DEBUG(logger
, "Splitting Blocks in Function " << function
->getName());
491 // Split blocks where jumps are going inside the block
492 for (auto it
= function
->blocks().begin();
493 it
!= function
->blocks().end();
495 BasicBlock
* current_block
= it
->second
;
496 if (current_block
->getEndAddress() == 0) {
497 LOG4CXX_ERROR(logger
, "UNFINISHED BLOCK " << std::hex
<< current_block
->getStartAddress());
501 uint64_t base_address
;
503 text_section
.getAddress(base_address
);
504 #elif defined(LLVM_36)
505 base_address
= text_section
.getAddress();
507 uint64_t current_address
= current_block
->getStartAddress() - base_address
;
508 while(current_block
->getEndAddress() - base_address
> current_address
) {
511 llvm::raw_string_ostream
s(buf
);
513 if(llvm::MCDisassembler::Success
==
515 DisAsm
->getInstruction(inst
, inst_size
, ref
, current_address
, nulls(), nulls())) {
516 #elif defined(LLVM_36)
517 DisAsm
->getInstruction(inst
, inst_size
,
518 bytearray
.slice(current_address
),
519 base_address
+ current_address
,
523 // See if some other block starts here
524 BasicBlock
* other
= manager
->getBasicBlock(current_address
528 // Special case, other block starts here but we are at the end anyway
530 uint64_t endaddress
= current_address
+ inst_size
+ base_address
;
531 if (endaddress
!= current_block
->getEndAddress()) {
532 LOG4CXX_DEBUG(logger
, "Shortening block starting at "
534 << current_block
->getStartAddress()
536 << other
->getStartAddress());
537 function
->addBasicBlock(other
);
538 current_block
->setEndAddress(endaddress
);
539 current_block
->setNextBlock(0, other
->getStartAddress());
540 current_block
->setNextBlock(1, 0);
546 current_address
+= inst_size
;
552 void LLVMDisassembler
<COFFT
>::readDynamicSymbols() {
557 void LLVMDisassembler
<MACHOT
>::readDynamicSymbols() {
561 template <typename ELFT
>
562 void LLVMDisassembler
<ELFT
>::readDynamicSymbols() {
563 const auto elffile
= dyn_cast
<ELFObjectFile
<ELFT
>>(o
)->getELFFile();
564 for (auto it
= elffile
->begin_dynamic_symbols(),
565 end
= elffile
->end_dynamic_symbols();
568 if (it
->getType() == 2) { // Function
569 bool is_default(false);
570 // TODO: Error handling
571 std::string symbolname
= *(elffile
->getSymbolName(it
));
572 std::string symbolversion
= *(elffile
->getSymbolVersion(nullptr, &*it
, is_default
));
573 // TODO: actually get the symbol address from relocations
574 Function
* f
= manager
->newDynamicFunction(0);
575 f
->setName(symbolname
+ (is_default
? "@@" : "@") + symbolversion
);
576 manager
->finishFunction(f
);
578 LOG4CXX_DEBUG(logger
, "Adding dynamic Symbol " << symbolname
<< (is_default
? "@@" : "@") << symbolversion
);
583 template <typename ELFT
>
584 void LLVMDisassembler
<ELFT
>::readSymbols() {
586 symbol_iterator
si(o
->symbol_begin()), se(o
->symbol_end());
587 for (; si
!= se
; ++si
) {
590 si
->getAddress(address
);
591 if ((ec
= si
->getName(name
))) {
592 LOG4CXX_ERROR(logger
, ec
.message());
595 LOG4CXX_DEBUG(logger
, "Added symbol " << name
.str() << " at address " << std::hex
<< address
);
596 symbols
.insert(make_pair(name
.str(), *si
));
600 template <typename ELFT
>
601 void LLVMDisassembler
<ELFT
>::readSections() {
603 section_iterator
i(o
->section_begin()), e(o
->section_end());
604 for (; i
!= e
; ++i
) {
606 if ((ec
= i
->getName(name
))) {
607 LOG4CXX_ERROR(logger
, ec
.message());
610 LOG4CXX_DEBUG(logger
, "Added section " << name
.str());
611 sections
.insert(make_pair(name
.str(), *i
));
616 // template <typename ELFT>
617 // void LLVMDisassembler<ELFT>::forEachFunction(std::function<void (uint64_t, Function*)> callback) {
618 // // std::for_each(functions.begin(), functions.end(),
619 // // [&](std::pair<uint64_t, Function*> x) {
620 // // callback(x.first, x.second);
624 template <typename ELFT
>
625 std::vector
<Instruction
> LLVMDisassembler
<ELFT
>::getInstructions(const BasicBlock
*block
) {
626 std::vector
<Instruction
> result
;
627 SectionRef text_section
= getTextSection();
628 uint64_t base_address
;
630 text_section
.getAddress(base_address
);
631 #elif defined(LLVM_36)
632 base_address
= text_section
.getAddress();
635 uint64_t current_address
= block
->getStartAddress() - base_address
;
636 uint64_t end_position
= block
->getEndAddress() - base_address
;
639 text_section
.getContents(bytes
);
641 StringRefMemoryObject
ref(bytes
);
642 #elif defined(LLVM_36)
643 ArrayRef
<uint8_t> bytearray(reinterpret_cast<const uint8_t *>(bytes
.data()),
648 while (current_address
< end_position
) {
652 llvm::raw_string_ostream
s(buf
);
654 if(llvm::MCDisassembler::Success
==
656 DisAsm
->getInstruction(inst
, inst_size
, ref
, current_address
, nulls(), nulls())) {
657 #elif defined(LLVM_36)
658 DisAsm
->getInstruction(inst
, inst_size
,
659 bytearray
.slice(current_address
),
660 base_address
+ current_address
,
664 uint8_t bytes
[inst_size
+2];
666 ref
.readBytes(current_address
, inst_size
, bytes
);
667 #elif defined(LLVM_36)
668 size_t bytesindex(0);
669 for (uint8_t byte
: bytearray
.slice(current_address
, inst_size
)) {
670 bytes
[bytesindex
++] = byte
;
676 IP
->printInst(&inst
, s
, "");
677 if (MIA
->evaluateBranch(inst
, current_address
, inst_size
, jmptarget
)) {
678 std::stringstream stream
;
679 if (MIA
->isCall(inst
))
680 stream
<< "function:";
684 stream
<< std::hex
<< (base_address
+ jmptarget
);
687 result
.push_back(Instruction(current_address
+ base_address
, boost::algorithm::trim_copy(s
.str()),
688 std::vector
<uint8_t>(bytes
, bytes
+inst_size
), ref
));
690 LOG4CXX_WARN(logger
, "Invalid byte at" << std::hex
<< current_address
+ base_address
);
693 ref
.readBytes(current_address
, 1, bytes
);
694 #elif defined(LLVM_36)
695 bytes
[0] = bytearray
[current_address
];
697 result
.push_back(Instruction(current_address
+ base_address
, "Invalid Instruction",
698 std::vector
<uint8_t>(bytes
, bytes
+1), ""));
702 current_address
+= inst_size
;
707 template <typename ELFT
>
708 SectionRef LLVMDisassembler
<ELFT
>::getTextSection() {
709 return sections
[".text"];
713 SectionRef LLVMDisassembler
<MACHOT
>::getTextSection() {
714 return sections
["__text"];