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 <boost/algorithm/string.hpp>
13 using namespace llvm::object
;
14 using std::error_code
;
29 Disassembler
* createLLVMDisassembler(const std::string
& filename
, InformationManager
* manager
) {
33 std::unique_ptr
<Binary
> o
;
34 o
.reset(createBinary(filename
).get());
35 Binary
* op
= o
.release();
37 // ELFType<endian, maxalign, 64bit>
38 if (ELF32LEObjectFile
* object
= dyn_cast
<ELF32LEObjectFile
>(op
)) {
39 return new LLVMDisassembler
<ELFType
<support::little
, 2, false>>(filename
, manager
, object
);
41 if (ELF64LEObjectFile
* object
= dyn_cast
<ELF64LEObjectFile
>(op
)) {
42 return new LLVMDisassembler
<ELFType
<support::little
, 2, true>>(filename
, manager
, object
);
44 if (ELF32BEObjectFile
* object
= dyn_cast
<ELF32BEObjectFile
>(op
)) {
45 return new LLVMDisassembler
<ELFType
<support::big
, 2, false>>(filename
, manager
, object
);
47 if (ELF64BEObjectFile
* object
= dyn_cast
<ELF64BEObjectFile
>(op
)) {
48 return new LLVMDisassembler
<ELFType
<support::big
, 2, true>>(filename
, manager
, object
);
50 if (COFFObjectFile
* object
= dyn_cast
<COFFObjectFile
>(op
)) {
51 return new LLVMDisassembler
<COFFT
>(filename
, manager
, object
);
53 if (MachOObjectFile
* object
= dyn_cast
<MachOObjectFile
>(op
)) {
54 return new LLVMDisassembler
<MACHOT
>(filename
, manager
, object
);
61 * TODO: fallback code falls die Datei kein ELF/PE/COFF/MacO/.. binary
62 * ist sondern z.B. einfach nur Instruktionen oder ein Bootsektor oder
65 template <typename ELFT
>
66 LLVMDisassembler
<ELFT
>::LLVMDisassembler(const std::string
& filename
,
67 InformationManager
* manager
,
70 , logger(log4cxx::Logger::getLogger("disassembler.LLVMDisassembler"))
71 , triple("unknown-unknown-unknown")
74 LOG4CXX_DEBUG(logger
, "Handling file " << filename
);
77 auto result
= createBinary(filename
);
80 if ((ec
= result
.getError())) {
81 LOG4CXX_ERROR(logger
, "Failed to load Binary" << ec
.message());
86 binary
.reset(result
.get());
88 o
= dyn_cast
<ObjectFile
>(binary
.get());
94 triple
.setArch(Triple::ArchType(o
->getArch()));
95 std::string
tripleName(triple
.getTriple());
97 LOG4CXX_INFO(logger
, "Architecture " << tripleName
);
101 target
= TargetRegistry::lookupTarget("", triple
, es
);
103 LOG4CXX_ERROR(logger
, es
);
107 LOG4CXX_INFO(logger
, "Target " << target
->getName());
109 MRI
.reset(target
->createMCRegInfo(tripleName
));
111 LOG4CXX_ERROR(logger
, "no register info for target " << tripleName
);
115 // Set up disassembler.
116 AsmInfo
.reset(target
->createMCAsmInfo(*MRI
, tripleName
));
118 LOG4CXX_ERROR(logger
, "no assembly info for target " << tripleName
);
122 STI
.reset(target
->createMCSubtargetInfo(tripleName
, "", ""));
124 LOG4CXX_ERROR(logger
, "no subtarget info for target " << tripleName
);
128 MII
.reset(target
->createMCInstrInfo());
130 LOG4CXX_ERROR(logger
, "no instruction info for target " << tripleName
);
134 MOFI
.reset(new MCObjectFileInfo
);
135 MCContext
Ctx(AsmInfo
.get(), MRI
.get(), MOFI
.get());
137 DisAsm
.reset(target
->createMCDisassembler(*STI
, Ctx
));
139 LOG4CXX_ERROR(logger
, "no disassembler for target " << tripleName
);
143 target
->createMCRelocationInfo(tripleName
, Ctx
));
146 // MCObjectSymbolizer::createObjectSymbolizer(Ctx, std::move(RelInfo), o));
148 // DisAsm->setSymbolizer(std::move(Symzer));
153 MIA
.reset(target
->createMCInstrAnalysis(MII
.get()));
155 LOG4CXX_ERROR(logger
, "no instruction analysis for target " << tripleName
);
159 int AsmPrinterVariant
= AsmInfo
->getAssemblerDialect();
160 IP
.reset(target
->createMCInstPrinter(AsmPrinterVariant
, *AsmInfo
, *MII
, *MRI
, *STI
));
162 LOG4CXX_ERROR(logger
, "no instruction printer for target " << tripleName
);
166 IP
->setPrintImmHex(llvm::HexStyle::C
);
167 IP
->setPrintImmHex(true);
169 std::unique_ptr
<MCObjectDisassembler
> OD(
170 new MCObjectDisassembler(*o
, *DisAsm
, *MIA
));
171 Mod
.reset(OD
->buildModule(false));
176 template <typename ELFT
>
177 void LLVMDisassembler
<ELFT
>::start() {
180 readDynamicSymbols();
183 template <typename ELFT
>
184 LLVMDisassembler
<ELFT
>::~LLVMDisassembler() {}
186 template <typename ELFT
>
187 Function
* LLVMDisassembler
<ELFT
>::disassembleFunctionAt(uint64_t address
, const std::string
& name
) {
189 SectionRef text_section
= getTextSection();
190 uint64_t base_address
, size
;
191 text_section
.getAddress(base_address
);
192 text_section
.getSize(size
);
194 if (address
< base_address
||
195 address
>= base_address
+ size
) {
199 if (NULL
== (function
= manager
->getFunction(address
))) {
203 s
<< "<Unnamed 0x" << std::hex
<< address
<< ">";
204 function
= manager
->newFunction(address
);
205 function
->setName(s
.str());
207 function
= manager
->newFunction(address
);
208 function
->setName(name
);
210 disassembleFunction(function
);
216 template <typename ELFT
>
217 void LLVMDisassembler
<ELFT
>::disassembleFunction(Function
* function
) {
218 std::vector
<uint64_t> called_functions
;
219 std::stack
<BasicBlock
*> remaining_blocks
;
221 * Do all blocks get added properly? We should take care to remove
222 * the other ones at the end of the function!
224 std::map
<uint64_t, BasicBlock
*> new_blocks
;
225 SectionRef text_section
= getTextSection();
227 text_section
.getContents(bytes
);
228 StringRefMemoryObject
ref(bytes
);
230 LOG4CXX_DEBUG(logger
, "Handling function " << function
->getName());
232 BasicBlock
* block
= manager
->newBasicBlock(function
->getStartAddress());
233 remaining_blocks
.push(block
);
234 new_blocks
.insert(std::make_pair(block
->getStartAddress(), block
));
235 function
->addBasicBlock(block
);
237 uint64_t base_address
, size
;
238 text_section
.getAddress(base_address
);
239 text_section
.getSize(size
);
240 LOG4CXX_DEBUG(logger
, "Text section at " << std::hex
<< base_address
<< " with size " << size
);
242 while (remaining_blocks
.size()) {
243 BasicBlock
* current_block
= remaining_blocks
.top();
244 remaining_blocks
.pop();
246 LOG4CXX_DEBUG(logger
, "Handling Block starting at " << std::hex
247 << current_block
->getStartAddress());
250 uint64_t current_address
= current_block
->getStartAddress() - base_address
;
254 llvm::raw_string_ostream
s(buf
);
256 if(llvm::MCDisassembler::Success
==
257 DisAsm
->getInstruction(inst
, inst_size
, ref
, current_address
, nulls(), nulls())) {
260 if (MIA
->evaluateBranch(inst
, current_address
, inst_size
, jmptarget
)) {
261 jmptarget
+= base_address
;
262 if (!MIA
->isIndirectBranch(inst
)) {
263 if (MIA
->isCall(inst
)) {
264 if (NULL
== manager
->getFunction(jmptarget
))
265 called_functions
.push_back(jmptarget
);
267 current_block
->setNextBlock(0, jmptarget
);
268 if (new_blocks
.find(jmptarget
) == new_blocks
.end()) {
269 BasicBlock
* block
= manager
->newBasicBlock(jmptarget
);
271 new_blocks
.insert(std::make_pair(block
->getStartAddress(), block
));
272 function
->addBasicBlock(block
);
273 remaining_blocks
.push(block
);
275 LOG4CXX_DEBUG(logger
, "Reusing Block starting at " << std::hex
276 << current_block
->getStartAddress());
277 function
->addBasicBlock(new_blocks
.find(jmptarget
)->second
);
279 if (MIA
->isConditionalBranch(inst
)) {
280 jmptarget
= base_address
+ current_address
+ inst_size
;
281 current_block
->setNextBlock(1, jmptarget
);
282 if (new_blocks
.find(jmptarget
) == new_blocks
.end()) {
283 BasicBlock
* block
= manager
->newBasicBlock(jmptarget
);
285 new_blocks
.insert(std::make_pair(block
->getStartAddress(), block
));
286 function
->addBasicBlock(block
);
287 remaining_blocks
.push(block
);
289 LOG4CXX_DEBUG(logger
, "Reusing Block starting at " << std::hex
290 << current_block
->getStartAddress());
291 function
->addBasicBlock(new_blocks
.find(jmptarget
)->second
);
302 if (inst_size
== 0 || MIA
->isTerminator(inst
) || MIA
->isBranch(inst
)) {
303 current_block
->setEndAddress(current_address
+ base_address
+ inst_size
);
304 LOG4CXX_DEBUG(logger
, "Finished Block at " << std::hex
<<
305 current_block
->getEndAddress());
308 current_address
+= inst_size
;
311 splitBlocks(function
);
312 LOG4CXX_DEBUG(logger
, "Finished function " << function
->getName());
313 manager
->finishFunction(function
);
314 for (uint64_t address
: called_functions
)
315 disassembleFunctionAt(address
);
318 template <typename ELFT
>
319 void LLVMDisassembler
<ELFT
>::disassemble() {
320 SectionRef text_section
= getTextSection();
321 std::vector
<Function
*> remaining_functions
;
323 // Assume all function symbols actually start a real function
324 for (auto x
= symbols
.begin(); x
!= symbols
.end(); ++x
) {
327 SymbolRef::Type symbol_type
;
330 if (text_section
.containsSymbol(x
->second
, contains
) || !contains
)
333 if (x
->second
.getType(symbol_type
)
334 || SymbolRef::ST_Function
!= symbol_type
)
337 if (!x
->second
.getAddress(result
)) {
338 Function
* fun
= manager
->newFunction(result
);
340 fun
->setName(x
->first
);
341 remaining_functions
.push_back(fun
);
342 LOG4CXX_DEBUG(logger
, "Disasembling " << x
->first
);
344 LOG4CXX_DEBUG(logger
, "Function at " << std::hex
<< result
345 << " already disassembled as " << manager
->getFunction(result
)->getName());
350 for (Function
* function
: remaining_functions
) {
351 disassembleFunction(function
);
352 manager
->finishFunction(function
);
355 if (binary
->isELF()) {
356 uint64_t _entryAddress
= entryAddress();
357 LOG4CXX_DEBUG(logger
, "Adding entryAddress at: " << std::hex
<< _entryAddress
);
359 s
<< "<_start 0x" << std::hex
<< _entryAddress
<< ">";
361 disassembleFunctionAt(_entryAddress
, s
.str());
364 if (!manager
->hasFunctions()) {
366 text_section
.getAddress(text_entry
);
367 LOG4CXX_INFO(logger
, "No Symbols found, starting at the beginning of the text segment");
368 disassembleFunctionAt(text_entry
);
373 uint64_t LLVMDisassembler
<COFFT
>::entryAddress() {
374 const auto coffobject
= dyn_cast
<COFFObjectFile
>(o
);
375 const struct pe32_header
* pe32_header
;
376 const struct pe32plus_header
* pe32plus_header
;
378 coffobject
->getPE32PlusHeader(pe32plus_header
);
380 if (pe32plus_header
) {
381 return pe32plus_header
->AddressOfEntryPoint
;
383 coffobject
->getPE32Header(pe32_header
);
384 return pe32_header
->AddressOfEntryPoint
;
389 uint64_t LLVMDisassembler
<MACHOT
>::entryAddress() {
394 template <typename ELFT
>
395 uint64_t LLVMDisassembler
<ELFT
>::entryAddress() {
396 const auto elffile
= dyn_cast
<ELFObjectFile
<ELFT
>>(o
)->getELFFile();
397 const auto * header
= elffile
->getHeader();
399 return header
->e_entry
;
402 template <typename ELFT
>
403 void LLVMDisassembler
<ELFT
>::splitBlocks(Function
* function
) {
404 SectionRef text_section
= getTextSection();
406 text_section
.getContents(bytes
);
407 StringRefMemoryObject
ref(bytes
);
409 LOG4CXX_DEBUG(logger
, "Splitting Blocks in Function " << function
->getName());
410 // Split blocks where jumps are going inside the block
411 for (auto it
= function
->blocks().begin();
412 it
!= function
->blocks().end();
414 BasicBlock
* current_block
= it
->second
;
415 if (current_block
->getEndAddress() == 0) {
416 LOG4CXX_ERROR(logger
, "UNFINISHED BLOCK " << std::hex
<< current_block
->getStartAddress());
420 uint64_t base_address
;
421 text_section
.getAddress(base_address
);
422 uint64_t current_address
= current_block
->getStartAddress() - base_address
;
423 while(current_block
->getEndAddress() - base_address
> current_address
) {
426 llvm::raw_string_ostream
s(buf
);
428 if(llvm::MCDisassembler::Success
==
429 DisAsm
->getInstruction(inst
, inst_size
, ref
, current_address
, nulls(), nulls())) {
430 // See if some other block starts here
431 BasicBlock
* other
= manager
->getBasicBlock(current_address
435 // Special case, other block starts here but we are at the end anyway
437 uint64_t endaddress
= current_address
+ inst_size
+ base_address
;
438 if (endaddress
!= current_block
->getEndAddress()) {
439 LOG4CXX_DEBUG(logger
, "Shortening block starting at "
441 << current_block
->getStartAddress()
443 << other
->getStartAddress());
444 function
->addBasicBlock(other
);
445 current_block
->setEndAddress(endaddress
);
446 current_block
->setNextBlock(0, other
->getStartAddress());
447 current_block
->setNextBlock(1, 0);
453 current_address
+= inst_size
;
459 void LLVMDisassembler
<COFFT
>::readDynamicSymbols() {
464 void LLVMDisassembler
<MACHOT
>::readDynamicSymbols() {
468 template <typename ELFT
>
469 void LLVMDisassembler
<ELFT
>::readDynamicSymbols() {
470 const auto elffile
= dyn_cast
<ELFObjectFile
<ELFT
>>(o
)->getELFFile();
471 for (auto it
= elffile
->begin_dynamic_symbols(),
472 end
= elffile
->end_dynamic_symbols();
475 if (it
->getType() == 2) { // Function
477 // TODO: Error handling
478 std::string symbolname
= *(elffile
->getSymbolName(it
));
479 std::string symbolversion
= *(elffile
->getSymbolVersion(nullptr, &*it
, is_default
));
480 // TODO: actually get the symbol address from relocations
481 Function
* f
= manager
->newDynamicFunction(0);
482 f
->setName(symbolname
+ (is_default
? "@@" : "@") + symbolversion
);
483 manager
->finishFunction(f
);
485 LOG4CXX_DEBUG(logger
, "Adding dynamic Symbol " << symbolname
<< (is_default
? "@@" : "@") << symbolversion
);
490 template <typename ELFT
>
491 void LLVMDisassembler
<ELFT
>::readSymbols() {
493 symbol_iterator
si(o
->symbol_begin()), se(o
->symbol_end());
494 for (; si
!= se
; ++si
) {
496 if ((ec
= si
->getName(name
))) {
497 LOG4CXX_ERROR(logger
, ec
.message());
500 LOG4CXX_DEBUG(logger
, "Added symbol " << name
.str());
501 symbols
.insert(make_pair(name
.str(), *si
));
505 template <typename ELFT
>
506 void LLVMDisassembler
<ELFT
>::readSections() {
508 section_iterator
i(o
->section_begin()), e(o
->section_end());
509 for (; i
!= e
; ++i
) {
511 if ((ec
= i
->getName(name
))) {
512 LOG4CXX_ERROR(logger
, ec
.message());
515 LOG4CXX_DEBUG(logger
, "Added section " << name
.str());
516 sections
.insert(make_pair(name
.str(), *i
));
521 // template <typename ELFT>
522 // void LLVMDisassembler<ELFT>::forEachFunction(std::function<void (uint64_t, Function*)> callback) {
523 // // std::for_each(functions.begin(), functions.end(),
524 // // [&](std::pair<uint64_t, Function*> x) {
525 // // callback(x.first, x.second);
529 template <typename ELFT
>
530 std::vector
<Instruction
> LLVMDisassembler
<ELFT
>::getInstructions(const BasicBlock
*block
) {
531 std::vector
<Instruction
> result
;
532 SectionRef text_section
= getTextSection();
533 uint64_t base_address
;
534 text_section
.getAddress(base_address
);
535 uint64_t current_address
= block
->getStartAddress() - base_address
;
536 uint64_t end_position
= block
->getEndAddress() - base_address
;
539 text_section
.getContents(bytes
);
540 StringRefMemoryObject
ref(bytes
);
542 while (current_address
< end_position
) {
546 llvm::raw_string_ostream
s(buf
);
548 if(llvm::MCDisassembler::Success
==
549 DisAsm
->getInstruction(inst
, inst_size
, ref
, current_address
, nulls(), nulls())) {
551 uint8_t bytes
[inst_size
+2];
552 ref
.readBytes(current_address
, inst_size
, bytes
);
556 IP
->printInst(&inst
, s
, "");
557 if (MIA
->evaluateBranch(inst
, current_address
, inst_size
, jmptarget
)) {
558 std::stringstream stream
;
559 if (MIA
->isCall(inst
))
560 stream
<< "function:";
564 stream
<< std::hex
<< (base_address
+ jmptarget
);
567 result
.push_back(Instruction(current_address
+ base_address
, boost::algorithm::trim_copy(s
.str()),
568 std::vector
<uint8_t>(bytes
, bytes
+inst_size
), ref
));
570 LOG4CXX_WARN(logger
, "Invalid byte at" << std::hex
<< current_address
+ base_address
);
572 ref
.readBytes(current_address
, 1, bytes
);
573 result
.push_back(Instruction(current_address
+ base_address
, "Invalid Instruction",
574 std::vector
<uint8_t>(bytes
, bytes
+1), ""));
578 current_address
+= inst_size
;
583 template <typename ELFT
>
584 void LLVMDisassembler
<ELFT
>::printEachInstruction(uint64_t start
, uint64_t end
,
585 std::function
<void (uint8_t*, size_t,
587 const std::string
&)> fun
) {
588 SectionRef text_section
= getTextSection();
589 uint64_t base_address
;
590 text_section
.getAddress(base_address
);
591 uint64_t current_address
= start
- base_address
;
594 text_section
.getContents(bytes
);
595 StringRefMemoryObject
ref(bytes
);
597 while (current_address
< end
- base_address
) {
601 llvm::raw_string_ostream
s(buf
);
603 if(llvm::MCDisassembler::Success
==
604 DisAsm
->getInstruction(inst
, inst_size
, ref
, current_address
, nulls(), nulls())) {
606 uint8_t bytes
[inst_size
+2];
607 ref
.readBytes(current_address
, inst_size
, bytes
);
611 IP
->printInst(&inst
, s
, "");
612 if (MIA
->evaluateBranch(inst
, current_address
, inst_size
, jmptarget
)) {
613 std::stringstream stream
;
614 if (MIA
->isCall(inst
))
615 stream
<< "function:";
619 stream
<< std::hex
<< (base_address
+ jmptarget
);
624 fun(bytes
, inst_size
, s
.str(), ref
);
626 LOG4CXX_WARN(logger
, "Invalid byte at" << std::hex
<< current_address
+ base_address
);
627 fun(NULL
, 0, "Invalid Byte", "");
631 current_address
+= inst_size
;
635 template <typename ELFT
>
636 SectionRef LLVMDisassembler
<ELFT
>::getTextSection() {
637 return sections
[".text"];
641 SectionRef LLVMDisassembler
<MACHOT
>::getTextSection() {
642 return sections
["__text"];