Split disassemble()
[frida/frida.git] / src / disassembler / llvm / LLVMDisassembler.cxx
1 #include "disassembler/llvm/LLVMDisassembler.hxx"
2 #include "disassembler/llvm/LLVMBasicBlock.hxx"
3 #include "disassembler/llvm/LLVMFunction.hxx"
4
5 #include <stack>
6 #include <algorithm>
7
8 using namespace llvm;
9 using namespace llvm::object;
10 using std::error_code;
11
12 /*
13 * TODO: fallback code falls die Datei kein ELF/PE/COFF/MacO/.. binary
14 * ist sondern z.B. einfach nur Instruktionen oder ein Bootsektor oder
15 * foo
16 */
17 LLVMDisassembler::LLVMDisassembler(const std::string& filename)
18 : Disassembler(filename)
19 , logger(log4cxx::Logger::getLogger("LLVMDisassembler"))
20 , triple("unknown-unknown-unknown")
21 {
22 LOG4CXX_DEBUG(logger, "Handling file" << filename);
23 auto result = createBinary(filename);
24
25 error_code ec;
26 if ((ec = result.getError())) {
27 LOG4CXX_ERROR(logger, "Failed to load Binary" << ec.message());
28 binary = NULL;
29 return;
30 }
31
32 binary.reset(result.get());
33
34 o = dyn_cast<ObjectFile>(binary.get());
35
36 triple.setArch(Triple::ArchType(o->getArch()));
37 std::string tripleName(triple.getTriple());
38
39 LOG4CXX_INFO(logger, "Architecture " << tripleName);
40
41
42 std::string es;
43 target = TargetRegistry::lookupTarget("", triple, es);
44 if (!target) {
45 LOG4CXX_ERROR(logger, es);
46 return;
47 }
48
49 LOG4CXX_INFO(logger, "Target " << target->getName());
50
51 MRI.reset(target->createMCRegInfo(tripleName));
52 if (!MRI) {
53 LOG4CXX_ERROR(logger, "no register info for target " << tripleName);
54 return;
55 }
56
57 // Set up disassembler.
58 AsmInfo.reset(target->createMCAsmInfo(*MRI, tripleName));
59 if (!AsmInfo) {
60 LOG4CXX_ERROR(logger, "no assembly info for target " << tripleName);
61 return;
62 }
63
64 STI.reset(target->createMCSubtargetInfo(tripleName, "", ""));
65 if (!STI) {
66 LOG4CXX_ERROR(logger, "no subtarget info for target " << tripleName);
67 return;
68 }
69
70 MII.reset(target->createMCInstrInfo());
71 if (!MII) {
72 LOG4CXX_ERROR(logger, "no instruction info for target " << tripleName);
73 return;
74 }
75
76 MOFI.reset(new MCObjectFileInfo);
77 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
78
79 DisAsm.reset(target->createMCDisassembler(*STI, Ctx));
80 if (!DisAsm) {
81 LOG4CXX_ERROR(logger, "no disassembler for target " << tripleName);
82 return;
83 }
84 RelInfo.reset(
85 target->createMCRelocationInfo(tripleName, Ctx));
86 if (RelInfo) {
87 Symzer.reset(
88 MCObjectSymbolizer::createObjectSymbolizer(Ctx, std::move(RelInfo), o));
89 if (Symzer)
90 DisAsm->setSymbolizer(std::move(Symzer));
91 }
92 RelInfo.release();
93 Symzer.release();
94
95 MIA.reset(target->createMCInstrAnalysis(MII.get()));
96 if (!MIA) {
97 LOG4CXX_ERROR(logger, "no instruction analysis for target " << tripleName);
98 return;
99 }
100
101 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
102 IP.reset(target->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
103 if (!IP) {
104 LOG4CXX_ERROR(logger, "no instruction printer for target " << tripleName);
105 return;
106 }
107
108 IP->setPrintImmHex(llvm::HexStyle::C);
109 IP->setPrintImmHex(true);
110
111 std::unique_ptr<MCObjectDisassembler> OD(
112 new MCObjectDisassembler(*o, *DisAsm, *MIA));
113 Mod.reset(OD->buildModule(false));
114
115 readSymbols();
116 readSections();
117 disassemble();
118 }
119
120 LLVMDisassembler::~LLVMDisassembler() {
121 std::for_each(functions.begin(), functions.end(),
122 [](std::pair<uint64_t,LLVMFunction*> it) {
123 delete it.second;
124 });
125 std::for_each(blocks.begin(), blocks.end(),
126 [](std::pair<uint64_t, LLVMBasicBlock*> it) {
127 delete it.second;
128 });
129 }
130
131 Function* LLVMDisassembler::disassembleFunctionAt(uint64_t address, const std::string& name) {
132 if (functions.find(address) != functions.end()) {
133 return functions[address];
134 }
135
136 LLVMFunction * function;
137 if (name == "") {
138 std::stringstream s;
139 s << "<Unnamed 0x" << std::hex << address << ">";
140 function = new LLVMFunction(s.str(), address);
141 } else {
142 function = new LLVMFunction(name, address);
143 }
144 functions.insert(std::make_pair(address, function));
145
146 disassembleFunction(function);
147
148 return function;
149 }
150
151 void LLVMDisassembler::disassembleFunction(LLVMFunction* function) {
152 std::stack<LLVMBasicBlock*> remaining_blocks;
153 SectionRef text_section = sections[".text"];
154 StringRef bytes;
155 text_section.getContents(bytes);
156 StringRefMemoryObject ref(bytes);
157
158 LOG4CXX_DEBUG(logger, "Handling function " << function->getName());
159
160 LLVMBasicBlock * block = new LLVMBasicBlock(function->getStartAddress(), this);
161 remaining_blocks.push(block);
162 blocks.insert(std::make_pair(block->getStartAddress(), block));
163
164 while (remaining_blocks.size()) {
165 LLVMBasicBlock * current_block = remaining_blocks.top();
166 remaining_blocks.pop();
167
168 LOG4CXX_DEBUG(logger, "Handling Block starting at " << std::hex << current_block->getStartAddress());
169
170 uint64_t inst_size;
171 uint64_t base_address;
172 text_section.getAddress(base_address);
173 uint64_t current_address = current_block->getStartAddress() - base_address;
174 while(true) {
175 MCInst inst;
176 std::string buf;
177 llvm::raw_string_ostream s(buf);
178
179 if(llvm::MCDisassembler::Success ==
180 DisAsm->getInstruction(inst, inst_size, ref, current_address, nulls(), nulls())) {
181 uint64_t jmptarget;
182
183 if (MIA->evaluateBranch(inst, current_address, inst_size, jmptarget)) {
184 jmptarget += base_address;
185 if (!MIA->isIndirectBranch(inst)) {
186 if (MIA->isCall(inst)) {
187 if (functions.find(jmptarget) == functions.end()) {
188 disassembleFunctionAt(jmptarget);
189 }
190 } else {
191 current_block->setNextBlock(0, jmptarget);
192 if (blocks.find(jmptarget) == blocks.end()) {
193 LLVMBasicBlock * block = new LLVMBasicBlock(jmptarget, this);
194 blocks.insert(std::make_pair(block->getStartAddress(), block));
195 remaining_blocks.push(block);
196 }
197 if (MIA->isConditionalBranch(inst)) {
198 jmptarget = base_address + current_address + inst_size;
199 current_block->setNextBlock(1, jmptarget);
200 if (blocks.find(jmptarget) == blocks.end()) {
201 LLVMBasicBlock * block = new LLVMBasicBlock(jmptarget, this);
202 blocks.insert(std::make_pair(block->getStartAddress(), block));
203 remaining_blocks.push(block);
204 }
205 }
206 }
207 }
208 }
209 } else {
210 inst_size = 0;
211 }
212
213
214 if (inst_size == 0 || MIA->isTerminator(inst) || MIA->isBranch(inst)) {
215 current_block->setEndAddress(current_address + base_address + inst_size);
216 LOG4CXX_DEBUG(logger, "Finished Block at " << std::hex <<
217 current_block->getEndAddress());
218 break;
219 }
220 current_address += inst_size;
221 }
222 }
223 LOG4CXX_DEBUG(logger, "Finished function " << function->getName());
224 }
225
226 void LLVMDisassembler::disassemble() {
227 SectionRef text_section = sections[".text"];
228 std::vector<LLVMFunction*> remaining_functions;
229
230 // Assume all function symbols actually start a real function
231 for (auto x = symbols.begin(); x != symbols.end(); ++x) {
232 uint64_t result;
233 bool contains;
234 SymbolRef::Type symbol_type;
235
236
237 if (text_section.containsSymbol(x->second, contains) || !contains)
238 continue;
239
240 if (x->second.getType(symbol_type)
241 || SymbolRef::ST_Function != symbol_type)
242 continue;
243
244 if (!x->second.getAddress(result)) {
245 LLVMFunction * fun = new LLVMFunction(x->first, result);
246 remaining_functions.push_back(fun);
247 functions.insert(std::make_pair(result, fun));
248 LOG4CXX_DEBUG(logger, "Disasembling " << x->first);
249 }
250 }
251
252 for (LLVMFunction* function : remaining_functions) {
253 disassembleFunction(function);
254 }
255
256 if (binary->isELF()) {
257 bool is64bit = (binary->getData()[4] == 0x02);
258
259 uint64_t entry(0);
260 for (int i(0); i < (is64bit? 8 : 4); ++i) {
261 if (binary->isLittleEndian()) {
262 entry |= (unsigned int)((unsigned char)binary->getData()[0x18 + i]) << 8*i;
263 } else {
264 entry = entry << 8;
265 entry |= (unsigned char)binary->getData()[0x18 + i];
266 }
267 }
268 LOG4CXX_DEBUG(logger, "Adding entry at: " << std::hex << entry);
269 std::stringstream s;
270 s << "<_start 0x" << std::hex << entry << ">";
271
272 disassembleFunctionAt(entry, s.str());
273 }
274
275 if (functions.empty()) {
276 uint64_t text_entry;
277 text_section.getAddress(text_entry);
278 LOG4CXX_INFO(logger, "No Symbols found, starting at the beginning of the text segment");
279 disassembleFunctionAt(text_entry);
280 }
281
282 splitBlocks();
283 }
284
285 void LLVMDisassembler::splitBlocks() {
286 SectionRef text_section = sections[".text"];
287 StringRef bytes;
288 text_section.getContents(bytes);
289 StringRefMemoryObject ref(bytes);
290
291 // Split blocks where jumps are going inside the block
292 for (auto it = blocks.begin(); it != blocks.end(); ++it) {
293 LLVMBasicBlock * current_block = it->second;
294 uint64_t inst_size;
295 uint64_t base_address;
296 text_section.getAddress(base_address);
297 uint64_t current_address = current_block->getStartAddress() - base_address;
298 while(current_block->getEndAddress() - base_address > current_address) {
299 MCInst inst;
300 std::string buf;
301 llvm::raw_string_ostream s(buf);
302
303 if(llvm::MCDisassembler::Success ==
304 DisAsm->getInstruction(inst, inst_size, ref, current_address, nulls(), nulls())) {
305 auto other = blocks.find(current_address + inst_size + base_address);
306
307 if (other != blocks.end()) {
308 uint64_t endaddress = current_address + inst_size + base_address;
309 if (endaddress != current_block->getEndAddress()) {
310 LOG4CXX_DEBUG(logger, "Shortening block starting at "
311 << std::hex
312 << current_block->getStartAddress()
313 << " now ending at "
314 << other->first);
315 current_block->setEndAddress(endaddress);
316 current_block->setNextBlock(0, other->first);
317 current_block->setNextBlock(1, 0);
318 }
319 }
320 } else {
321 inst_size = 1;
322 }
323 current_address += inst_size;
324 }
325 }
326 }
327
328 void LLVMDisassembler::readSymbols() {
329 error_code ec;
330 symbol_iterator si(o->symbol_begin()), se(o->symbol_end());
331 for (; si != se; ++si) {
332 StringRef name;
333 if ((ec = si->getName(name))) {
334 LOG4CXX_ERROR(logger, ec.message());
335 break;
336 }
337 LOG4CXX_DEBUG(logger, "Added symbol " << name.str());
338 symbols.insert(make_pair(name.str(), *si));
339 }
340 }
341
342 void LLVMDisassembler::readSections() {
343 error_code ec;
344 section_iterator i(o->section_begin()), e(o->section_end());
345 for (; i != e; ++i) {
346 StringRef name;
347 if ((ec = i->getName(name))) {
348 LOG4CXX_ERROR(logger, ec.message());
349 break;
350 }
351 LOG4CXX_DEBUG(logger, "Added section " << name.str());
352 sections.insert(make_pair(name.str(), *i));
353 }
354
355 }
356
357 void LLVMDisassembler::forEachFunction(std::function<void (uint64_t, Function*)> callback) {
358 std::for_each(functions.begin(), functions.end(),
359 [&](std::pair<uint64_t, LLVMFunction*> x) {
360 callback(x.first, x.second);
361 });
362 }
363
364 void LLVMDisassembler::printEachInstruction(uint64_t start, uint64_t end,
365 std::function<void (uint8_t*, size_t, const std::string&)> fun) {
366 SectionRef text_section = sections[".text"];
367 uint64_t base_address;
368 text_section.getAddress(base_address);
369 uint64_t current_address = start - base_address;
370
371 StringRef bytes;
372 text_section.getContents(bytes);
373 StringRefMemoryObject ref(bytes);
374
375 while (current_address < end - base_address) {
376 uint64_t inst_size;
377 MCInst inst;
378 std::string buf;
379 llvm::raw_string_ostream s(buf);
380
381 if(llvm::MCDisassembler::Success ==
382 DisAsm->getInstruction(inst, inst_size, ref, current_address, nulls(), nulls())) {
383
384 uint8_t bytes[inst_size+2];
385 ref.readBytes(current_address, inst_size, bytes);
386
387 uint64_t jmptarget;
388 if (MIA->evaluateBranch(inst, current_address, inst_size, jmptarget)) {
389 std::stringstream stream;
390 stream << std::hex << (base_address + jmptarget);
391 IP->printInst(&inst, s, stream.str());
392 } else
393 IP->printInst(&inst, s, "");
394
395 fun(bytes, inst_size, s.str());
396 } else {
397 LOG4CXX_WARN(logger, "Invalid byte at" << std::hex << current_address + base_address);
398 fun(NULL, 0, "Invalid Byte");
399 inst_size = 1;
400 }
401
402 current_address += inst_size;
403 }
404 }