Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support encode, more documentation #43

Merged
merged 1 commit into from
May 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 47 additions & 5 deletions python/examples/test-py-arch.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
from r2lang import R

def pyarch(a):
# describes layout of register file for the architecture
# return: string with layout of the register file
def regs():
return "=PC pc\n" + \
"=SP sp\n" + \
Expand All @@ -23,6 +25,9 @@ def regs():
"gpr sp .32 24 0\n" + \
"gpr pc .32 28 0\n"

# provides radare2 with information about instruction size and memory alignment
# query: attribute requested
# return: value of requested attribute
def info(query):
arch_info = {
R.R_ARCH_INFO_MINOP_SIZE: 1,
Expand All @@ -40,7 +45,20 @@ def info(query):
else:
return res

def decode(buf, pc):
# decodes machine code and returns information about the instruction
# buf: buffer with bytes to decode
# pc: memory address where the buffer came from
# mask: information requested by radare, use is optional for better performance
# see radare2/libr/include/r_arch.h for documentation
# return: list object with:
# number of bytes processed in from buf to decode instruction
# dict with disassembly and metadata about the instruction, most important fields are:
# mnemonic: string with disassembled instruction, as shown to user
# type: type of instruction
# jump: target address for branch instructions
# ptr: address for instructions that access memory
# see radare2/libr/include/r_anal/op.h for more details and complete list of fields
def decode(buf, pc, mask):
ops = {
0: {
"op": {
Expand All @@ -52,7 +70,7 @@ def decode(buf, pc):
},
1: {
"op": {
"mnemonic" : "mov r{}, 0x{:02x}".format(buf[1], buf[2]),
"mnemonic" : "mov r{}, [0x{:02x}]".format(buf[1], buf[2]),
"type" : R.R_ANAL_OP_TYPE_MOV,
"cycles" : 2,
"ptr" : buf[2],
Expand All @@ -62,7 +80,7 @@ def decode(buf, pc):
},
2: {
"op": {
"mnemonic" : "fadd r{}, #0x{:02x}".format(buf[1], buf[2]),
"mnemonic" : "fadd r{}, 0x{:02x}".format(buf[1], buf[2]),
"type" : R.R_ANAL_OP_TYPE_ADD,
"family" : R.R_ANAL_OP_FAMILY_FPU,
"cycles" : 2,
Expand All @@ -88,6 +106,30 @@ def decode(buf, pc):
return [ 2, None ]
return [ decoded_op.get("size"), decoded_op.get("op") ]

# assembles provided string into machine code
# addr: memory address where assembled instruction will be located
# str: line of code to assemble
# return: bytes of assembled code, or None on error
def encode(addr, str):
import pyparsing as pp
p = pp.Word(pp.alphanums) + pp.Optional( pp.Word(pp.alphanums) + pp.Optional(',' + pp.Word(pp.alphanums)))
asm = p.parseString(str)
if asm[0] == "nop":
return b'\x00'
elif asm[0] == "mov" and len(asm) == 4:
if asm[1].startswith("r") and asm[3].isdigit():
return bytes([1, int(asm[1][1:]), int(asm[3])])
return None

# definition of the architecture this plugin implements
# return: dict with metadata about the plugin, and the functions that implement the plugin
# name: pretty name of the plugin
# arch: identifier used for referencing architecture in radare, e.g. via: e asm.arch=x
# bits: bits of this architecture
# regs: layout of register file
# info: info about instruction size and memory alignment
# decode: disassemble code
# encode: assemble code
return {
"name": "MyPyArch",
"arch": "pyarch",
Expand All @@ -97,9 +139,9 @@ def decode(buf, pc):
"regs": regs,
"info": info,
"decode": decode,
"encode": encode,
}

# The r2lang.plugin function register the plugin with radare2
# The r2lang.plugin function registers the plugin with radare2
if not r2lang.plugin("arch", pyarch):
print("Failed to register the python arch plugin.")

51 changes: 42 additions & 9 deletions python/python/arch.c
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ void py_export_arch_enum(PyObject *tp_dict) {
}\
}

// arch info, see radare2/libr/include/r_arch.h for documentation
// arch info, see radare2/libr/include/r_arch.h for documentation
PYENUM(R_ARCH_INFO_MINOP_SIZE);
PYENUM(R_ARCH_INFO_MAXOP_SIZE);
PYENUM(R_ARCH_INFO_INVOP_SIZE);
Expand All @@ -39,7 +39,16 @@ void py_export_arch_enum(PyObject *tp_dict) {
PYENUM(R_ARCH_INFO_DATA4_ALIGN);
PYENUM(R_ARCH_INFO_DATA8_ALIGN);

// opcode type, see radare2/libr/include/r_anal/op.h for documentation
// decode/encode operations, see radare2/libr/include/r_arch.h for documentation
PYENUM(R_ARCH_OP_MASK_BASIC);
PYENUM(R_ARCH_OP_MASK_ESIL);
PYENUM(R_ARCH_OP_MASK_VAL);
PYENUM(R_ARCH_OP_MASK_HINT);
PYENUM(R_ARCH_OP_MASK_OPEX);
PYENUM(R_ARCH_OP_MASK_DISASM);
PYENUM(R_ARCH_OP_MASK_ALL);

// opcode type, see radare2/libr/include/r_anal/op.h for documentation
PYENUM(R_ARCH_OP_MOD_COND);
PYENUM(R_ARCH_OP_MOD_REP);
PYENUM(R_ARCH_OP_MOD_MEM);
Expand Down Expand Up @@ -238,9 +247,33 @@ static char *py_arch_regs(RArchSession *as) {

static bool py_arch_encode(RArchSession *as, RAnalOp *op, RArchEncodeMask mask) {
r_return_val_if_fail (as && op, false);
// TODO
// R_LOG_WARN ("py_arch_encode not implemented");
return true;
// R_LOG_INFO ("py_arch_encode called");
bool res = false;
if (py_arch_encode_cb) {
PyObject *arglist = Py_BuildValue ("(Ks)", op->addr, op->mnemonic);
PyObject *result = PyObject_CallObject (py_arch_encode_cb, arglist);
if (result) {
if (PyBytes_Check (result)) {
int size = PyBytes_Size (result);
if (size > 0) {
free (op->bytes);
op->bytes = r_mem_dup (PyBytes_AsString (result), size);
op->size = size;
res = true;
} else {
R_LOG_WARN ("No assembled bytes returned by Python arch plugin");
}
}
Py_DECREF (result);
}
Py_DECREF (arglist);
} else {
R_LOG_WARN ("Python arch plugin does not implement encode");
}
if (PyErr_Occurred ()) {
PyErr_Print ();
}
return res;
}

static bool py_arch_decode(RArchSession *as, RAnalOp *op, RAnalOpMask mask) {
Expand All @@ -257,8 +290,8 @@ static bool py_arch_decode(RArchSession *as, RAnalOp *op, RAnalOpMask mask) {
.itemsize = 1
};
PyObject *memview = PyMemoryView_FromBuffer (&pybuf);
PyObject *arglist = Py_BuildValue ("(NK)", memview, op->addr);
PyObject *result = PyObject_CallFunction (py_arch_decode_cb, "NK", memview, op->addr);
PyObject *arglist = Py_BuildValue ("(NKi)", memview, op->addr, mask);
PyObject *result = PyObject_CallObject (py_arch_decode_cb, arglist);
if (result) {
if (PyList_Check (result)) {
PyObject *len = PyList_GetItem (result, 0);
Expand Down Expand Up @@ -352,7 +385,7 @@ static bool py_arch_decode(RArchSession *as, RAnalOp *op, RAnalOpMask mask) {
Py_DECREF (arglist);
Py_DECREF (memview);
} else {
R_LOG_WARN ("arch plugin does not implement decode");
R_LOG_WARN ("Python arch plugin does not implement decode");
}

if (PyErr_Occurred ()) {
Expand Down Expand Up @@ -384,7 +417,7 @@ static RList *py_arch_preludes(RArchSession *as) {

static bool py_arch_esilcb(RArchSession *as, RArchEsilAction action) {
r_return_val_if_fail (as, false);
// TODO
// TODO?
// R_LOG_WARN ("py_arch_esilcb not implemented");
return true;
}
Expand Down
Loading