-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdisassembler.cc
478 lines (442 loc) · 14.2 KB
/
disassembler.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
/*-
* Copyright (c) 2015 David T. Chisnall
*
* All rights reserved.
*
* This software was developed by SRI International and the University of
* Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237
* ("CTSRD"), as part of the DARPA CRASH research programme.
*
* This software was developed by SRI International and the University of
* Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-11-C-0249
* ("MRC2"), as part of the DARPA MRC research programme.
*
* @BERI_LICENSE_HEADER_START@
*
* Licensed to BERI Open Systems C.I.C. (BERI) under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. BERI licenses this
* file to you under the BERI Hardware-Software License, Version 1.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.beri-open-systems.org/legal/license-1-0.txt
*
* Unless required by applicable law or agreed to in writing, Work distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* @BERI_LICENSE_HEADER_END@
*/
#include "cheri.hh"
#include "disassembler.hh"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/SMLoc.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstrAnalysis.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCDisassembler/MCDisassembler.h"
#include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCTargetOptions.h"
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCCodeEmitter.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCParser/MCAsmParser.h"
#include "llvm/MC/MCParser/MCTargetAsmParser.h"
#include <mutex>
#include <assert.h>
using namespace cheri::disassembler;
namespace llvm {
extern const MCInstrDesc MipsInsts[];
}
using llvm::MipsInsts;
namespace {
int registerIndexForString(const char *str)
{
if (str[0] == '$')
{
str++;
}
char *end;
if (strcmp(str, "cnull") == 0)
{
// same as C0
return 64;
}
if (strcmp(str, "ddc") == 0)
{
// special case, this is the same as chwr_ddc
return 96;
}
if (str[0] == 'c' && str[1] != 'h')
{
// GP capability register, not a capability hardware register
str++;
long idx = strtol(str, &end, 10);
if (str == end)
{
return -1;
}
return idx + 64;
}
if (str[0] == 'f' && str[1] != 'p')
{
// float register, not frame pointer
str++;
long idx = strtol(str, &end, 10);
if (str == end)
{
return -1;
}
return idx + 32;
}
long idx = strtol(str, &end, 10);
if (str != end)
{
return (int)idx;
}
for (size_t i=0 ; i<(sizeof(MipsRegisterNames) / sizeof(*MipsRegisterNames)) ; i++)
{
// other register name or hardware capability register
if (strcmp(str, MipsRegisterNames[i]) == 0)
{
return (int)i;
}
}
return -1;
}
} // Anonymous namespace
namespace cheri {
namespace disassembler{
static std::unique_ptr<const llvm::MCRegisterInfo> mri;
static std::unique_ptr<llvm::MCSubtargetInfo> sti;
struct disassembler_impl
{
/**
* LLVM machine code context.
*/
std::unique_ptr<llvm::MCContext> mccontext;
/**
* LLVM disassembler.
*/
std::unique_ptr<llvm::MCDisassembler> disAsm;
/**
* LLVM instruction printer.
*/
std::unique_ptr<llvm::MCInstPrinter> instrPrinter;
/**
* Map from LLVM's notion of registers to something stable.
*/
int registerIndexForLLVMRegNo(unsigned regNo);
disassembler_impl();
};
}
} // cheri::disassembler
int disassembler_impl::registerIndexForLLVMRegNo(unsigned regNo)
{
std::string regName;
llvm::raw_string_ostream regStream(regName);
instrPrinter->printRegName(regStream, regNo);
int idx = registerIndexForString(regStream.str().c_str());
return idx;
}
disassembler::disassembler()
{
pimpl = new disassembler_impl();
}
disassembler::~disassembler()
{
delete pimpl;
}
disassembler_impl::disassembler_impl()
{
static std::once_flag flag;
static const llvm::Target *target;
static std::unique_ptr<const llvm::MCAsmInfo> asmInfo;
static std::unique_ptr<const llvm::MCInstrInfo> mii;
static std::unique_ptr<const llvm::MCInstrAnalysis> mia;
static llvm::Triple targetTriple;
static llvm::MCTargetOptions MCOptions;
LLVMInitializeMipsTargetInfo();
LLVMInitializeMipsTargetMC();
LLVMInitializeMipsAsmParser();
LLVMInitializeMipsDisassembler();
std::call_once(flag, [this](){
std::string cheriTriple("cheri-unknown-freebsd");
std::string mipsTriple("mips64-unknown-freebsd");
std::string triple = cheriTriple;
std::string features("");
const llvm::MCRegisterInfo *MRI = nullptr;
std::string Error;
target = llvm::TargetRegistry::lookupTarget(triple, Error);
if (target)
{
MRI = target->createMCRegInfo(triple);
}
// First try to set up the target for CHERI, if it doesn't work then fall back to MIPS
if (MRI == 0)
{
triple = mipsTriple;
target = llvm::TargetRegistry::lookupTarget(triple, Error);
if (target)
{
MRI = target->createMCRegInfo(triple);
}
}
targetTriple = llvm::Triple(triple);
assert(MRI != 0);
mri.reset(MRI);
assert(mri && "Failed to create MCRegisterInfo");
asmInfo.reset(target->createMCAsmInfo(*mri, triple, MCOptions));
assert(asmInfo && "Failed to create MCAsmInfo");
sti.reset(target->createMCSubtargetInfo(triple, "", features));
assert(sti && "Failed to create MCSubtargetInfo");
mii.reset(target->createMCInstrInfo());
assert(mii && "Failed to create MCInstrInfo");
mia.reset(new llvm::MCInstrAnalysis(mii.get()));
assert(mia && "Failed to create MCInstrAnalysis");
});
assert(mri);
mccontext.reset(new llvm::MCContext(asmInfo.get(), mri.get(), nullptr));
disAsm.reset(target->createMCDisassembler(*sti, *mccontext));
assert(disAsm && "Failed to create MCDisassembler");
instrPrinter.reset(target->createMCInstPrinter(targetTriple,
asmInfo->getAssemblerDialect(), *asmInfo, *mii, *mri));
assert(instrPrinter && "Failed to create MCInstPrinter");
}
instruction_info disassembler::disassemble(uint32_t anInstruction)
{
assert(pimpl->mccontext->getAsmInfo());
instruction_info info;
uint8_t instbytes[4];
std::memcpy(instbytes, &anInstruction, sizeof(anInstruction));
static_assert(sizeof(anInstruction) == sizeof(instbytes),
"Instruction size is wrong!");
llvm::MCInst inst;
uint64_t size;
auto status = pimpl->disAsm->getInstruction(inst, size, instbytes, 0,
llvm::errs());
if (status != llvm::MCDisassembler::Success)
{
info.name = "<Unable to disassemble>";
return info;
}
llvm::raw_string_ostream os(info.name);
pimpl->instrPrinter->printInst(&inst, 0, "", *sti, os);
os.str();
auto &desc = MipsInsts[inst.getOpcode()];
if (desc.isBranch() || desc.isCall() || desc.isReturn())
{
info.type = instruction_info::flow_control;
}
else if (desc.mayLoad() || desc.mayStore())
{
info.type = instruction_info::memory_access;
}
info.has_delay_slot = desc.hasDelaySlot();
// The MIPS back end currently uses a pseudo for returns and so the
// disassembled instruction is not identifiable as a return.
info.is_return = (anInstruction == 0x03e00008) || desc.isReturn();
info.is_call = desc.isCall();
const uint16_t *implicitDefs = desc.getImplicitDefs();
unsigned numImplicitDefs = desc.getNumImplicitDefs();
for (unsigned i = 0; i < numImplicitDefs; i++)
{
int regNo = pimpl->registerIndexForLLVMRegNo(implicitDefs[i]);
if (regNo >= 0)
{
info.destination_register = regNo;
break;
}
}
if ((info.destination_register == -1) && (inst.getNumOperands() > 0))
{
llvm::MCOperand op0 = inst.getOperand(0);
if (op0.isReg())
{
if (desc.hasDefOfPhysReg(inst, op0.getReg(), *mri.get()))
{
int regNo = pimpl->registerIndexForLLVMRegNo(op0.getReg());
if (regNo >= 0)
info.destination_register = regNo;
}
// else if (info.name.find("cwritehwr") != std::string::npos) {
// /*
// * XXX-AM: Handle this case specially because cwritehwr
// * in LLVM does not have a valid output register description.
// */
// int regNo = pimpl->registerIndexForLLVMRegNo(inst.getOperand(1).getReg());
// if (regNo >= 0)
// info.destination_register = regNo;
// }
}
}
if ((info.destination_register == -1) && desc.mayStore())
{
int regNo = pimpl->registerIndexForLLVMRegNo(inst.getOperand(0).getReg());
if (regNo >= 0)
info.destination_register = regNo;
}
/* Extract operands of the instruction */
for (unsigned i=0; i<inst.getNumOperands(); i++)
{
operand_info op_info;
llvm::MCOperand op = inst.getOperand(i);
op_info.is_valid = op.isValid();
op_info.is_register = op.isReg();
op_info.is_immediate = op.isImm();
op_info.is_fp_immediate = op.isFPImm();
op_info.is_expr = op.isExpr();
op_info.is_inst = op.isInst();
if (op.isReg())
{
op_info.register_number = pimpl->registerIndexForLLVMRegNo(op.getReg());
}
else if (op.isImm())
{
op_info.immediate = op.getImm();
}
else if (op.isFPImm())
{
op_info.fp_immediate = op.getFPImm();
}
info.operands.push_back(op_info);
}
return info;
}
namespace cheri {
namespace disassembler{
using namespace llvm;
struct assembler_impl
{
const std::string cheriTriple;
const llvm::Triple targetTriple;
const llvm::Target *target;
std::unique_ptr<llvm::MCRegisterInfo> MRI;
std::unique_ptr<llvm::MCAsmInfo> MAI;
std::unique_ptr<llvm::MCInstrInfo> MCII;
std::unique_ptr<llvm::MCSubtargetInfo> STI;
llvm::MCObjectFileInfo MOFI;
llvm::MCTargetOptions MCOptions;
assembler_impl();
};
class MCInstEncodingStreamer final : public llvm::MCStreamer
{
llvm::raw_ostream &OS;
std::unique_ptr<llvm::MCCodeEmitter> Emitter;
public:
MCInstEncodingStreamer(llvm::MCContext &Context, llvm::raw_ostream &os, llvm::MCCodeEmitter *emitter)
: MCStreamer(Context), OS(os), Emitter(emitter)
{
assert(Emitter);
}
void emitInstruction(const llvm::MCInst &Inst, const llvm::MCSubtargetInfo &STI) override;
void emitZerofill(llvm::MCSection *Section, llvm::MCSymbol *Symbol,
uint64_t Size, unsigned ByteAlignment, llvm::TailPaddingAmount TailPadding,
llvm::SMLoc Loc = llvm::SMLoc()) override;
bool emitSymbolAttribute(llvm::MCSymbol *Symbol, llvm::MCSymbolAttr Attribute) override;
void emitCommonSymbol(llvm::MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment,
llvm::TailPaddingAmount TailPadding) override;
};
}
}
void MCInstEncodingStreamer::emitZerofill(llvm::MCSection *Section, llvm::MCSymbol *Symbol, uint64_t Size,
unsigned ByteAlignment, llvm::TailPaddingAmount TailPadding, llvm::SMLoc Loc)
{
assert(false && "Not implemented");
}
bool MCInstEncodingStreamer::emitSymbolAttribute(llvm::MCSymbol *Symbol, llvm::MCSymbolAttr Attribute)
{
assert(false && "Not implemented");
return false;
}
void MCInstEncodingStreamer::emitCommonSymbol(llvm::MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment,
llvm::TailPaddingAmount TailPadding)
{
assert(false && "Not implemented");
}
void MCInstEncodingStreamer::emitInstruction(const llvm::MCInst &Inst, const llvm::MCSubtargetInfo &STI)
{
llvm::SmallVector<llvm::MCFixup, 4> Fixups;
Emitter->encodeInstruction(Inst, OS, Fixups, STI);
assert(Fixups.size() == 0 && "Instruction requires fixups");
}
assembler::assembler()
{
pimpl.reset(new assembler_impl);
}
assembler::~assembler() = default;
assembler_impl::assembler_impl()
: cheriTriple("cheri-unknown-freebsd"), targetTriple(llvm::Triple(cheriTriple))
{
std::string MCPU("");
std::string FeatureStr("");
LLVMInitializeMipsTargetInfo();
LLVMInitializeMipsTargetMC();
LLVMInitializeMipsAsmParser();
LLVMInitializeMipsDisassembler();
/* require the cheri target */
std::string Error;
target = llvm::TargetRegistry::lookupTarget(cheriTriple, Error);
assert(target);
/* make machine register info mri */
MRI.reset(target->createMCRegInfo(cheriTriple));
assert(MRI && "Unable to create target register info");
/* make asm info asmInfo */
MAI.reset(target->createMCAsmInfo(*MRI, cheriTriple, MCOptions));
assert(MAI && "Failed to create MCAsmInfo");
/* create mc instr info mcii */
MCII.reset(target->createMCInstrInfo());
assert(MCII && "Failed to create MCInstrInfo");
/* create mc subtarget info sti */
STI.reset(target->createMCSubtargetInfo(cheriTriple, MCPU, FeatureStr));
assert(STI && "Failed to create MCSubtargetInfo");
}
uint32_t assembler::assemble(const std::string &asmexpr)
{
auto& MRI = pimpl->MRI;
auto& MAI = pimpl->MAI;
auto& MOFI = pimpl->MOFI;
auto& MCII = pimpl->MCII;
auto& STI = pimpl->STI;
auto& MCOptions = pimpl->MCOptions;
auto& targetTriple = pimpl->targetTriple;
auto target = pimpl->target;
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> BufferPtr =
llvm::MemoryBuffer::getMemBuffer(asmexpr);
assert(!BufferPtr.getError() && "Can not create input buffer");
llvm::SourceMgr SrcMgr;
SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), llvm::SMLoc());
/* make context */
llvm::MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
assert(Ctx.getRegisterInfo() && "Register info is NULL");
MOFI.InitMCObjectFileInfo(targetTriple, /*PIC*/ false, Ctx);
llvm::SmallString<256> instrBuffer;
llvm::raw_svector_ostream OS(instrBuffer);
llvm::MCCodeEmitter *CE = target->createMCCodeEmitter(*MCII, *MRI, Ctx);
std::unique_ptr<MCInstEncodingStreamer> Str(new MCInstEncodingStreamer(Ctx, OS, CE));
/* ownership of the target streamer is taken by the MCInstEncodingStreamer */
target->createNullTargetStreamer(*Str);
std::unique_ptr<llvm::MCAsmParser> Parser(llvm::createMCAsmParser(SrcMgr, Ctx, *Str, *MAI));
std::unique_ptr<llvm::MCTargetAsmParser> TAP(target->createMCAsmParser(*STI, *Parser, *MCII, MCOptions));
assert(TAP && "Failed to create MCTargetAsmParser");
Parser->setTargetParser(*TAP);
int Res = Parser->Run(/*NoInitialTextSection*/ false);
assert(Res == 0 && "Failed to run MCAsmParser");
uint32_t opcode;
memcpy((void *)&opcode, instrBuffer.data(), sizeof(opcode));
return opcode;
}