]> git.siccegge.de Git - frida/frida.git/blob - src/disassembler/llvm/LLVMDisassembler.cxx
Correctly handle the case where we do not have Instruction Analysis
[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 StringRef bytes;
159 text_section.getContents(bytes);
160 StringRefMemoryObject ref(bytes);
161
162 while (remaining_functions.size()) {
163 LLVMFunction * current_function = remaining_functions.top();
164 remaining_functions.pop();
165
166 LOG4CXX_DEBUG(logger, "Handling function " << current_function->getName());
167
168 LLVMBasicBlock * block = new LLVMBasicBlock(current_function->getStartAddress(), this);
169 remaining_blocks.push(block);
170 blocks.insert(std::make_pair(block->getStartAddress(), block));
171
172 while (remaining_blocks.size()) {
173 LLVMBasicBlock * current_block = remaining_blocks.top();
174 remaining_blocks.pop();
175
176 LOG4CXX_DEBUG(logger, "Handling Block starting at " << std::hex << current_block->getStartAddress());
177
178 uint64_t inst_size;
179 uint64_t base_address;
180 text_section.getAddress(base_address);
181 uint64_t current_address = current_block->getStartAddress() - base_address;
182 while(true) {
183 MCInst inst;
184 std::string buf;
185 llvm::raw_string_ostream s(buf);
186
187 if(llvm::MCDisassembler::Success ==
188 DisAsm->getInstruction(inst, inst_size, ref, current_address, nulls(), nulls())) {
189
190 uint64_t jmptarget;
191 if (MIA->evaluateBranch(inst, current_address, inst_size, jmptarget)) {
192 jmptarget += base_address;
193 if (!MIA->isIndirectBranch(inst)) {
194 if (MIA->isCall(inst)) {
195 if (functions.find(jmptarget) == functions.end()) {
196 std::stringstream s;
197 s << "<Unnamed 0x" << std::hex << jmptarget << ">";
198 LLVMFunction * fun = new LLVMFunction(s.str(), jmptarget);
199 functions.insert(std::make_pair(jmptarget, fun));
200 remaining_functions.push(fun);
201 }
202 } else {
203 current_block->setNextBlock(0, jmptarget);
204 if (blocks.find(jmptarget) == blocks.end()) {
205 LLVMBasicBlock * block = new LLVMBasicBlock(jmptarget, this);
206 blocks.insert(std::make_pair(block->getStartAddress(), block));
207 remaining_blocks.push(block);
208 }
209 if (MIA->isConditionalBranch(inst)) {
210 jmptarget = base_address + current_address + inst_size;
211 current_block->setNextBlock(1, jmptarget);
212 if (blocks.find(jmptarget) == blocks.end()) {
213 LLVMBasicBlock * block = new LLVMBasicBlock(jmptarget, this);
214 blocks.insert(std::make_pair(block->getStartAddress(), block));
215 remaining_blocks.push(block);
216 }
217 }
218 }
219 }
220 }
221 } else {
222 inst_size = 0;
223 }
224
225
226 if (inst_size == 0 || MIA->isTerminator(inst) || MIA->isBranch(inst)) {
227 current_block->setEndAddress(current_address + base_address + inst_size);
228 LOG4CXX_DEBUG(logger, "Finished Block at " << std::hex <<
229 current_block->getEndAddress());
230 break;
231 }
232 current_address += inst_size;
233 }
234 }
235 LOG4CXX_DEBUG(logger, "Finished function " << current_function->getName());
236 }
237
238 // Split blocks where jumps are going inside the block
239 for (auto it = blocks.begin(); it != blocks.end(); ++it) {
240 LLVMBasicBlock * current_block = it->second;
241 uint64_t inst_size;
242 uint64_t base_address;
243 text_section.getAddress(base_address);
244 uint64_t current_address = current_block->getStartAddress() - base_address;
245 while(current_block->getEndAddress() - base_address > current_address) {
246 MCInst inst;
247 std::string buf;
248 llvm::raw_string_ostream s(buf);
249
250 if(llvm::MCDisassembler::Success ==
251 DisAsm->getInstruction(inst, inst_size, ref, current_address, nulls(), nulls())) {
252 auto other = blocks.find(current_address + inst_size + base_address);
253
254 if (other != blocks.end()) {
255 uint64_t endaddress = current_address + inst_size + base_address;
256 if (endaddress != current_block->getEndAddress()) {
257 LOG4CXX_DEBUG(logger, "Shortening block starting at "
258 << std::hex
259 << current_block->getStartAddress()
260 << " now ending at "
261 << other->first);
262 current_block->setEndAddress(endaddress);
263 current_block->setNextBlock(0, other->first);
264 current_block->setNextBlock(1, 0);
265 }
266 }
267 } else {
268 inst_size = 1;
269 }
270 current_address += inst_size;
271 }
272 }
273 }
274
275 void LLVMDisassembler::readSymbols() {
276 error_code ec;
277 symbol_iterator si(o->symbol_begin()), se(o->symbol_end());
278 for (; si != se; ++si) {
279 StringRef name;
280 if ((ec = si->getName(name))) {
281 LOG4CXX_ERROR(logger, ec.message());
282 break;
283 }
284 LOG4CXX_DEBUG(logger, "Added symbol " << name.str());
285 symbols.insert(make_pair(name.str(), *si));
286 }
287 }
288
289 void LLVMDisassembler::readSections() {
290 error_code ec;
291 section_iterator i(o->section_begin()), e(o->section_end());
292 for (; i != e; ++i) {
293 StringRef name;
294 if ((ec = i->getName(name))) {
295 LOG4CXX_ERROR(logger, ec.message());
296 break;
297 }
298 LOG4CXX_DEBUG(logger, "Added section " << name.str());
299 sections.insert(make_pair(name.str(), *i));
300 }
301
302 }
303
304 void LLVMDisassembler::forEachFunction(std::function<void (uint64_t, Function*)> callback) {
305 std::for_each(functions.begin(), functions.end(),
306 [&](std::pair<uint64_t, LLVMFunction*> x) {
307 callback(x.first, x.second);
308 });
309 }
310
311 void LLVMDisassembler::printEachInstruction(uint64_t start, uint64_t end,
312 std::function<void (uint8_t*, size_t, const std::string&)> fun) {
313 SectionRef text_section = sections[".text"];
314 uint64_t base_address;
315 text_section.getAddress(base_address);
316 uint64_t current_address = start - base_address;
317
318 StringRef bytes;
319 text_section.getContents(bytes);
320 StringRefMemoryObject ref(bytes);
321
322 while (current_address < end - base_address) {
323 uint64_t inst_size;
324 MCInst inst;
325 std::string buf;
326 llvm::raw_string_ostream s(buf);
327
328 if(llvm::MCDisassembler::Success ==
329 DisAsm->getInstruction(inst, inst_size, ref, current_address, nulls(), nulls())) {
330
331 uint8_t bytes[inst_size+2];
332 ref.readBytes(current_address, inst_size, bytes);
333
334 uint64_t jmptarget;
335 if (MIA->evaluateBranch(inst, current_address, inst_size, jmptarget)) {
336 std::stringstream stream;
337 stream << std::hex << (base_address + jmptarget);
338 IP->printInst(&inst, s, stream.str());
339 } else
340 IP->printInst(&inst, s, "");
341
342 fun(bytes, inst_size, s.str());
343 } else {
344 LOG4CXX_WARN(logger, "Invalid byte at" << std::hex << current_address + base_address);
345 fun(NULL, 0, "Invalid Byte");
346 inst_size = 1;
347 }
348
349 current_address += inst_size;
350 }
351 }