#include #include #include /* * Return the numeric value represented by the hex digit c. */ typedef struct assoc { char c; int v; } pair_t; pair_t hexval[] = {{'0',0},{'1',1},{'2',2},{'3',3},{'4',4}, {'5',5},{'6',6},{'7',7},{'8',8},{'9',9}, {'a',10},{'b',11},{'c',12},{'d',13},{'e',14},{'f',15}, {'A',10},{'B',11},{'C',12},{'D',13},{'E',14},{'F',15}}; int getval (char c) { int i; for (i=0; i < sizeof(hexval); i++) if (hexval[i].c == c) return hexval[i].v; return 0; } /* * Return the integer representation of the four-character string of hex digits. */ int toInt (char in[]) { int k, val; for (val=0, k=0; k<4; k++) val = val*16 + getval(in[k]); return val; } char *opcodes[] = {"add","or","xor","and","addi","rotr","st","ld","ldi", "uu","bneg","bz","jr","uu","uu","jmp"}; typedef unsigned int word_t; int getopcode(word_t inst) { return ((inst >> 12) & 0xF); } int getop1(word_t inst){ return (inst >> 8) & 0xF; } int getdest(word_t inst) { return (inst >> 4) & 0xF; } int getop2(word_t inst) { return (inst & 0xF); } int getim4(word_t inst) { return (inst & 0xF); } typedef void printFun_t(word_t instr, word_t pc); void printRR(word_t instr, word_t pc) { printf("%4x: %04X %s $%d $%d $%d;\n", pc,instr, opcodes[getopcode(instr)], getdest(instr),getop1(instr),getop2(instr)); } void printIM(word_t instr, word_t pc){ printf("%4x: %04X %s $%d $%d %d;\n", pc,instr, opcodes[getopcode(instr)], getdest(instr),getop1(instr),getim4(instr)); } void printMem(word_t instr, word_t pc){ printf("%4x: %04X %s;\n", pc,instr, opcodes[getopcode(instr)]); } void printBr(word_t instr, word_t pc){ printf("%4x: %04X %s;\n", pc,instr, opcodes[getopcode(instr)]); } void printRI8(word_t instr, word_t pc){ printf("%4x: %04X %s;\n", pc,instr, opcodes[getopcode(instr)]); } void printJmp(word_t instr, word_t pc){ printf("%4x: %04X %s;\n", pc,instr, opcodes[getopcode(instr)]); } void printUndef(word_t instr, word_t pc){ printf("%4x: %04X %s;\n", pc,instr, opcodes[getopcode(instr)]); } printFun_t *printers[16] = {printRR, printRR, printRR, printRR, printIM, printIM, printMem, printMem, printRI8, printUndef, printBr, printBr, printMem, printUndef, printUndef, printJmp}; int main (int argc, char* argv[]) { FILE *in; char line[256]; int addr = 0; unsigned int inst; if (argc != 2) { fprintf (stderr, "wrong number of arguments (one expected)\n"); exit (1); } in = fopen (argv[1], "r"); if (in == NULL) { fprintf (stderr, "can't open %s\n", argv[1]); exit (1); } while (fgets(line, 256, in)) { inst = toInt(line); printers[getopcode(inst)](inst,addr); addr = addr+2; } }