]> git.siccegge.de Git - frida/frida.git/blob - src/disassembler/llvm/LLVMDisassembler.cxx
Move to table widget -- looks nicer and matches better
[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
11 /*
12 * TODO: fallback code falls die Datei kein ELF/PE/COFF/MacO/.. binary
13 * ist sondern z.B. einfach nur Instruktionen oder ein Bootsektor oder
14 * foo
15 */
16 LLVMDisassembler::LLVMDisassembler(const std::string& filename)
17 : Disassembler(filename)
18 , logger(log4cxx::Logger::getLogger("LLVMDisassembler"))
19 , triple("unknown-unknown-unknown")
20 {
21 LOG4CXX_DEBUG(logger, "Handling file" << filename);
22 auto result = createBinary(filename);
23
24 error_code ec;
25 if ((ec = result.getError())) {
26 LOG4CXX_ERROR(logger, "Failed to load Binary" << ec.message());
27 binary = NULL;
28 return;
29 }
30
31 binary.reset(result.get());
32
33 o = dyn_cast<ObjectFile>(binary.get());
34
35 triple.setArch(Triple::ArchType(o->getArch()));
36 std::string tripleName(triple.getTriple());
37
38 LOG4CXX_INFO(logger, "Architecture " << tripleName);
39
40
41 std::string es;
42 target = TargetRegistry::lookupTarget("", triple, es);
43 if (!target) {
44 LOG4CXX_ERROR(logger, es);
45 return;
46 }
47
48 LOG4CXX_INFO(logger, "Target " << target->getName());
49
50 MRI.reset(target->createMCRegInfo(tripleName));
51 if (!MRI) {
52 LOG4CXX_ERROR(logger, "no register info for target " << tripleName);
53 return;
54 }
55
56 // Set up disassembler.
57 AsmInfo.reset(target->createMCAsmInfo(*MRI, tripleName));
58 if (!AsmInfo) {
59 LOG4CXX_ERROR(logger, "no assembly info for target " << tripleName);
60 return;
61 }
62
63 STI.reset(target->createMCSubtargetInfo(tripleName, "", ""));
64 if (!STI) {
65 LOG4CXX_ERROR(logger, "no subtarget info for target " << tripleName);
66 return;
67 }
68
69 MII.reset(target->createMCInstrInfo());
70 if (!MII) {
71 LOG4CXX_ERROR(logger, "no instruction info for target " << tripleName);
72 return;
73 }
74
75 DisAsm.reset(target->createMCDisassembler(*STI));
76 if (!DisAsm) {
77 LOG4CXX_ERROR(logger, "no disassembler for target " << tripleName);
78 return;
79 }
80
81 MOFI.reset(new MCObjectFileInfo);
82 Ctx.reset(new MCContext(AsmInfo.get(), MRI.get(), MOFI.get()));
83 RelInfo.reset(
84 target->createMCRelocationInfo(tripleName, *Ctx.get()));
85 if (RelInfo) {
86 Symzer.reset(
87 MCObjectSymbolizer::createObjectSymbolizer(*Ctx.get(), RelInfo, o));
88 if (Symzer)
89 DisAsm->setSymbolizer(Symzer);
90 }
91
92 MIA.reset(target->createMCInstrAnalysis(MII.get()));
93
94 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
95 IP.reset(target->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
96 if (!IP) {
97 LOG4CXX_ERROR(logger, "no instruction printer for target " << tripleName);
98 return;
99 }
100
101 IP->setPrintImmHex(llvm::HexStyle::C);
102 IP->setPrintImmHex(true);
103
104 OwningPtr<MCObjectDisassembler> OD(
105 new MCObjectDisassembler(*o, *DisAsm, *MIA));
106 Mod.reset(OD->buildModule(false));
107
108 readSymbols();
109 readSections();
110 disassemble();
111 }
112
113 LLVMDisassembler::~LLVMDisassembler() {
114 std::for_each(functions.begin(), functions.end(),
115 [](std::pair<uint64_t,LLVMFunction*> it) {
116 delete it.second;
117 });
118 std::for_each(blocks.begin(), blocks.end(),
119 [](std::pair<uint64_t, LLVMBasicBlock*> it) {
120 delete it.second;
121 });
122 }
123
124 /*
125 * TODO: If we jump into some Basic Block we need to split it there into two
126 */
127 void LLVMDisassembler::disassemble() {
128 std::stack<LLVMFunction*> remaining_functions;
129 std::stack<LLVMBasicBlock*> remaining_blocks;
130 SectionRef text_section = sections[".text"];
131
132 for (auto x = symbols.begin(); x != symbols.end(); ++x) {
133 uint64_t result;
134 bool contains;
135 SymbolRef::Type symbol_type;
136
137
138 if (text_section.containsSymbol(x->second, contains) || !contains)
139 continue;
140
141 if (x->second.getType(symbol_type)
142 || SymbolRef::ST_Function != symbol_type)
143 continue;
144
145 if (!x->second.getAddress(result)) {
146 LLVMFunction * fun = new LLVMFunction(x->first, result);
147 remaining_functions.push(fun);
148 functions.insert(std::make_pair(result, fun));
149 LOG4CXX_DEBUG(logger, "Disasembling " << x->first);
150 }
151 }
152
153 StringRef bytes;
154 text_section.getContents(bytes);
155 StringRefMemoryObject ref(bytes);
156
157 while (remaining_functions.size()) {
158 LLVMFunction * current_function = remaining_functions.top();
159 remaining_functions.pop();
160
161 LOG4CXX_DEBUG(logger, "Handling function " << current_function->getName());
162
163 // if ("_start" != current_function->getName())
164 // continue;
165
166 LLVMBasicBlock * block = new LLVMBasicBlock(current_function->getStartAddress(), this);
167 remaining_blocks.push(block);
168 blocks.insert(std::make_pair(block->getStartAddress(), block));
169
170 while (remaining_blocks.size()) {
171 LLVMBasicBlock * current_block = remaining_blocks.top();
172 remaining_blocks.pop();
173
174 LOG4CXX_DEBUG(logger, "Handling Block starting at " << std::hex << current_block->getStartAddress());
175
176 uint64_t inst_size;
177 uint64_t base_address;
178 text_section.getAddress(base_address);
179 uint64_t current_address = current_block->getStartAddress() - base_address;
180 while(true) {
181 MCInst inst;
182 std::string buf;
183 llvm::raw_string_ostream s(buf);
184
185 if(llvm::MCDisassembler::Success ==
186 DisAsm->getInstruction(inst, inst_size, ref, current_address, nulls(), nulls())) {
187
188 uint8_t bytes[inst_size+2];
189 ref.readBytes(current_address, inst_size, bytes);
190 s << '\t';
191 for(uint8_t* cur = bytes; cur < bytes + inst_size; ++cur) {
192 s.write_hex(*cur);
193 s << ' ';
194 }
195 s << '\t';
196
197 IP->printInst(&inst, s, "");
198
199 LOG4CXX_DEBUG(logger, std::hex << current_address + base_address << s.str());
200
201 uint64_t jmptarget;
202 if (MIA->evaluateBranch(inst, current_address, inst_size, jmptarget)) {
203 jmptarget += base_address;
204 if (!MIA->isIndirectBranch(inst)) {
205 if (MIA->isCall(inst)) {
206 if (functions.find(jmptarget) == functions.end()) {
207 std::stringstream s;
208 s << "<Unnamed 0x" << std::hex << jmptarget << ">";
209 LLVMFunction * fun = new LLVMFunction(s.str(), jmptarget);
210 functions.insert(std::make_pair(jmptarget, fun));
211 remaining_functions.push(fun);
212 }
213 } else {
214 if (blocks.find(jmptarget) == blocks.end()) {
215 LLVMBasicBlock * block = new LLVMBasicBlock(jmptarget, this);
216 blocks.insert(std::make_pair(block->getStartAddress(), block));
217 current_block->setNextBlock(0, block->getStartAddress());
218 remaining_blocks.push(block);
219 }
220 if (MIA->isConditionalBranch(inst)) {
221 jmptarget = base_address + current_address + inst_size;
222 if (blocks.find(jmptarget) == blocks.end()) {
223 LLVMBasicBlock * block = new LLVMBasicBlock(jmptarget, this);
224 blocks.insert(std::make_pair(block->getStartAddress(), block));
225 current_block->setNextBlock(1, block->getStartAddress());
226 remaining_blocks.push(block);
227 }
228 }
229 }
230 }
231 }
232 } else {
233 inst_size = 0;
234 }
235
236
237 if (inst_size == 0 || MIA->isTerminator(inst) || MIA->isBranch(inst)) {
238 current_block->setEndAddress(current_address + base_address + inst_size);
239 LOG4CXX_DEBUG(logger, "Finished Block at " << std::hex <<
240 current_block->getEndAddress());
241 break;
242 }
243 current_address += inst_size;
244 }
245 }
246 LOG4CXX_DEBUG(logger, "Finished function " << current_function->getName());
247 }
248 }
249
250 void LLVMDisassembler::readSymbols() {
251 error_code ec;
252 symbol_iterator si(o->symbol_begin()), se(o->symbol_end());
253 for (; si != se; ++si) {
254 StringRef name;
255 if ((ec = si->getName(name))) {
256 LOG4CXX_ERROR(logger, ec.message());
257 break;
258 }
259 LOG4CXX_DEBUG(logger, "Added symbol " << name.str());
260 symbols.insert(make_pair(name.str(), *si));
261 }
262 }
263
264 void LLVMDisassembler::readSections() {
265 error_code ec;
266 section_iterator i(o->section_begin()), e(o->section_end());
267 for (; i != e; ++i) {
268 StringRef name;
269 if ((ec = i->getName(name))) {
270 LOG4CXX_ERROR(logger, ec.message());
271 break;
272 }
273 LOG4CXX_DEBUG(logger, "Added section " << name.str());
274 sections.insert(make_pair(name.str(), *i));
275 }
276
277 }
278
279 void LLVMDisassembler::forEachFunction(std::function<void (uint64_t, Function*)> callback) {
280 std::for_each(functions.begin(), functions.end(),
281 [&](std::pair<uint64_t, LLVMFunction*> x) {
282 callback(x.first, x.second);
283 });
284 }
285
286 void LLVMDisassembler::printEachInstruction(uint64_t start, uint64_t end,
287 std::function<void (uint8_t*, size_t, const std::string&)> fun) {
288 SectionRef text_section = sections[".text"];
289 uint64_t base_address;
290 text_section.getAddress(base_address);
291 uint64_t current_address = start - base_address;
292
293 StringRef bytes;
294 text_section.getContents(bytes);
295 StringRefMemoryObject ref(bytes);
296
297 while (current_address < end - base_address) {
298 uint64_t inst_size;
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
306 uint8_t bytes[inst_size+2];
307 ref.readBytes(current_address, inst_size, bytes);
308
309 IP->printInst(&inst, s, "");
310 fun(bytes, inst_size, s.str());
311 } else {
312 fun(NULL, 0, "Invalid Byte");
313 inst_size = 1;
314 }
315
316 current_address += inst_size;
317 }
318 }