]> git.siccegge.de Git - frida/frida.git/blob - src/disassembler/llvm/LLVMDisassembler.cxx
Fallbacks if we do not have symbols
[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 void LLVMDisassembler::disassemble() {
132 std::stack<LLVMFunction*> remaining_functions;
133 std::stack<LLVMBasicBlock*> remaining_blocks;
134 SectionRef text_section = sections[".text"];
135
136 // Assume all function symbols actually start a real function
137 for (auto x = symbols.begin(); x != symbols.end(); ++x) {
138 uint64_t result;
139 bool contains;
140 SymbolRef::Type symbol_type;
141
142
143 if (text_section.containsSymbol(x->second, contains) || !contains)
144 continue;
145
146 if (x->second.getType(symbol_type)
147 || SymbolRef::ST_Function != symbol_type)
148 continue;
149
150 if (!x->second.getAddress(result)) {
151 LLVMFunction * fun = new LLVMFunction(x->first, result);
152 remaining_functions.push(fun);
153 functions.insert(std::make_pair(result, fun));
154 LOG4CXX_DEBUG(logger, "Disasembling " << x->first);
155 }
156 }
157
158 if (binary->isELF()) {
159 bool is64bit = (binary->getData()[4] == 0x02);
160
161 uint64_t entry(0);
162 for (int i(0); i < (is64bit? 8 : 4); ++i) {
163 if (binary->isLittleEndian()) {
164 entry |= (unsigned int)((unsigned char)binary->getData()[0x18 + i]) << 8*i;
165 } else {
166 entry = entry << 8;
167 entry |= (unsigned char)binary->getData()[0x18 + i];
168 }
169 }
170 if (functions.find(entry) == functions.end()) {
171 LOG4CXX_DEBUG(logger, "Adding entry at: " << std::hex << entry);
172 std::stringstream s;
173 s << "<_start 0x" << std::hex << entry << ">";
174 LLVMFunction * fun = new LLVMFunction(s.str(), entry);
175 functions.insert(std::make_pair(entry, fun));
176 remaining_functions.push(fun);
177 }
178 }
179
180 if (functions.empty()) {
181 uint64_t text_entry;
182 text_section.getAddress(text_entry);
183 LOG4CXX_INFO(logger, "No Symbols found, starting at the beginning of the text segment");
184
185 std::stringstream s;
186 s << "<Unnamed 0x" << std::hex << text_entry << ">";
187 LLVMFunction * fun = new LLVMFunction(s.str(), text_entry);
188 functions.insert(std::make_pair(text_entry, fun));
189 remaining_functions.push(fun);
190 }
191
192 StringRef bytes;
193 text_section.getContents(bytes);
194 StringRefMemoryObject ref(bytes);
195
196 while (remaining_functions.size()) {
197 LLVMFunction * current_function = remaining_functions.top();
198 remaining_functions.pop();
199
200 LOG4CXX_DEBUG(logger, "Handling function " << current_function->getName());
201
202 LLVMBasicBlock * block = new LLVMBasicBlock(current_function->getStartAddress(), this);
203 remaining_blocks.push(block);
204 blocks.insert(std::make_pair(block->getStartAddress(), block));
205
206 while (remaining_blocks.size()) {
207 LLVMBasicBlock * current_block = remaining_blocks.top();
208 remaining_blocks.pop();
209
210 LOG4CXX_DEBUG(logger, "Handling Block starting at " << std::hex << current_block->getStartAddress());
211
212 uint64_t inst_size;
213 uint64_t base_address;
214 text_section.getAddress(base_address);
215 uint64_t current_address = current_block->getStartAddress() - base_address;
216 while(true) {
217 MCInst inst;
218 std::string buf;
219 llvm::raw_string_ostream s(buf);
220
221 if(llvm::MCDisassembler::Success ==
222 DisAsm->getInstruction(inst, inst_size, ref, current_address, nulls(), nulls())) {
223
224 uint64_t jmptarget;
225 if (MIA->evaluateBranch(inst, current_address, inst_size, jmptarget)) {
226 jmptarget += base_address;
227 if (!MIA->isIndirectBranch(inst)) {
228 if (MIA->isCall(inst)) {
229 if (functions.find(jmptarget) == functions.end()) {
230 std::stringstream s;
231 s << "<Unnamed 0x" << std::hex << jmptarget << ">";
232 LLVMFunction * fun = new LLVMFunction(s.str(), jmptarget);
233 functions.insert(std::make_pair(jmptarget, fun));
234 remaining_functions.push(fun);
235 }
236 } else {
237 current_block->setNextBlock(0, jmptarget);
238 if (blocks.find(jmptarget) == blocks.end()) {
239 LLVMBasicBlock * block = new LLVMBasicBlock(jmptarget, this);
240 blocks.insert(std::make_pair(block->getStartAddress(), block));
241 remaining_blocks.push(block);
242 }
243 if (MIA->isConditionalBranch(inst)) {
244 jmptarget = base_address + current_address + inst_size;
245 current_block->setNextBlock(1, jmptarget);
246 if (blocks.find(jmptarget) == blocks.end()) {
247 LLVMBasicBlock * block = new LLVMBasicBlock(jmptarget, this);
248 blocks.insert(std::make_pair(block->getStartAddress(), block));
249 remaining_blocks.push(block);
250 }
251 }
252 }
253 }
254 }
255 } else {
256 inst_size = 0;
257 }
258
259
260 if (inst_size == 0 || MIA->isTerminator(inst) || MIA->isBranch(inst)) {
261 current_block->setEndAddress(current_address + base_address + inst_size);
262 LOG4CXX_DEBUG(logger, "Finished Block at " << std::hex <<
263 current_block->getEndAddress());
264 break;
265 }
266 current_address += inst_size;
267 }
268 }
269 LOG4CXX_DEBUG(logger, "Finished function " << current_function->getName());
270 }
271
272 // Split blocks where jumps are going inside the block
273 for (auto it = blocks.begin(); it != blocks.end(); ++it) {
274 LLVMBasicBlock * current_block = it->second;
275 uint64_t inst_size;
276 uint64_t base_address;
277 text_section.getAddress(base_address);
278 uint64_t current_address = current_block->getStartAddress() - base_address;
279 while(current_block->getEndAddress() - base_address > current_address) {
280 MCInst inst;
281 std::string buf;
282 llvm::raw_string_ostream s(buf);
283
284 if(llvm::MCDisassembler::Success ==
285 DisAsm->getInstruction(inst, inst_size, ref, current_address, nulls(), nulls())) {
286 auto other = blocks.find(current_address + inst_size + base_address);
287
288 if (other != blocks.end()) {
289 uint64_t endaddress = current_address + inst_size + base_address;
290 if (endaddress != current_block->getEndAddress()) {
291 LOG4CXX_DEBUG(logger, "Shortening block starting at "
292 << std::hex
293 << current_block->getStartAddress()
294 << " now ending at "
295 << other->first);
296 current_block->setEndAddress(endaddress);
297 current_block->setNextBlock(0, other->first);
298 current_block->setNextBlock(1, 0);
299 }
300 }
301 } else {
302 inst_size = 1;
303 }
304 current_address += inst_size;
305 }
306 }
307 }
308
309 void LLVMDisassembler::readSymbols() {
310 error_code ec;
311 symbol_iterator si(o->symbol_begin()), se(o->symbol_end());
312 for (; si != se; ++si) {
313 StringRef name;
314 if ((ec = si->getName(name))) {
315 LOG4CXX_ERROR(logger, ec.message());
316 break;
317 }
318 LOG4CXX_DEBUG(logger, "Added symbol " << name.str());
319 symbols.insert(make_pair(name.str(), *si));
320 }
321 }
322
323 void LLVMDisassembler::readSections() {
324 error_code ec;
325 section_iterator i(o->section_begin()), e(o->section_end());
326 for (; i != e; ++i) {
327 StringRef name;
328 if ((ec = i->getName(name))) {
329 LOG4CXX_ERROR(logger, ec.message());
330 break;
331 }
332 LOG4CXX_DEBUG(logger, "Added section " << name.str());
333 sections.insert(make_pair(name.str(), *i));
334 }
335
336 }
337
338 void LLVMDisassembler::forEachFunction(std::function<void (uint64_t, Function*)> callback) {
339 std::for_each(functions.begin(), functions.end(),
340 [&](std::pair<uint64_t, LLVMFunction*> x) {
341 callback(x.first, x.second);
342 });
343 }
344
345 void LLVMDisassembler::printEachInstruction(uint64_t start, uint64_t end,
346 std::function<void (uint8_t*, size_t, const std::string&)> fun) {
347 SectionRef text_section = sections[".text"];
348 uint64_t base_address;
349 text_section.getAddress(base_address);
350 uint64_t current_address = start - base_address;
351
352 StringRef bytes;
353 text_section.getContents(bytes);
354 StringRefMemoryObject ref(bytes);
355
356 while (current_address < end - base_address) {
357 uint64_t inst_size;
358 MCInst inst;
359 std::string buf;
360 llvm::raw_string_ostream s(buf);
361
362 if(llvm::MCDisassembler::Success ==
363 DisAsm->getInstruction(inst, inst_size, ref, current_address, nulls(), nulls())) {
364
365 uint8_t bytes[inst_size+2];
366 ref.readBytes(current_address, inst_size, bytes);
367
368 uint64_t jmptarget;
369 if (MIA->evaluateBranch(inst, current_address, inst_size, jmptarget)) {
370 std::stringstream stream;
371 stream << std::hex << (base_address + jmptarget);
372 IP->printInst(&inst, s, stream.str());
373 } else
374 IP->printInst(&inst, s, "");
375
376 fun(bytes, inst_size, s.str());
377 } else {
378 LOG4CXX_WARN(logger, "Invalid byte at" << std::hex << current_address + base_address);
379 fun(NULL, 0, "Invalid Byte");
380 inst_size = 1;
381 }
382
383 current_address += inst_size;
384 }
385 }