/* Name 1: Joseph Ryan Name 2: Rahul Butani UTEID 1: jbr2558 UTEID 2: rhb834 */ #include #include #include #include #include #include #include #define MAX_LABEL_LEN 20 #define MAX_SYMBOLS 255 #define MAX_LINE_LEN 255 #define NUM_RESERVED 32 FILE* in_file; FILE* out_file; char buf[MAX_LINE_LEN + 1]; size_t line_len; char pretty_buf[MAX_LINE_LEN + 1]; char* current = NULL; const char* reserved[NUM_RESERVED] = { "add", "and", "ldb", "ldw", "lea", "stb", "stw", "xor", "not", "lshf", "rshfl", "rshfa", "nop", "jmp", "ret", "jsr", "jsrr", "rti", "trap", "getc", "out", "puts", "in", "halt", "br", "brn", "brz", "brp", "brnz", "brzp", "brnp", "brnzp"}; typedef struct Symbol { uint16_t addr; uint16_t line; char name[MAX_LABEL_LEN + 1]; } Symbol; Symbol SymbolTable[MAX_SYMBOLS]; size_t num_symbols; uint16_t line_num = 0; // Prints an error message and the current line, then exits void errmsg(int exit_code, const char* fmt, ...) { va_list args; va_start(args, fmt); printf("ERROR at line %d:\n", line_num); printf("\n%s\n\n", pretty_buf); vprintf(fmt, args); va_end(args); printf("\n"); exit(exit_code); } // Checks if a string is a reserved word _Bool is_reserved(char* s) { for (int i = 0; i < NUM_RESERVED; ++i) { if (!strcmp(s, reserved[i])) { return true; } } return false; } // Converts a string to lowercase in place and returns the same string char* lower(char* s) { for (int i = 0; s[i]; ++i) { s[i] = tolower(s[i]); } return s; } // Returns either a pointer to the symbol with the given name, // or NULL if it isn't found Symbol* get_symbol(char* s) { for (size_t i = 0; i < num_symbols; ++i) { if (!strncmp(SymbolTable[i].name, s, MAX_LABEL_LEN)) { return &SymbolTable[i]; } } return NULL; } // Adds a symbol with the given string at the given address void add_symbol(char* s, uint16_t addr) { if (isdigit(*s) || *s == 'x') { errmsg(4, "Labels cannot start with 'x' or a number"); } for (char* c = s; *c; ++c) { if (!isalnum(*c)) { errmsg(4, "Invalid character in label: %c", *c); } } if (num_symbols == MAX_SYMBOLS) { errmsg(4, "Exceeded translation limit, too many labels"); } Symbol* old = get_symbol(s); if (old) { errmsg(4, "Symbol '%s' is already defined on line %d", s, old->line); } SymbolTable[num_symbols] = (Symbol){.addr = addr, .line = line_num}; strncpy(SymbolTable[num_symbols++].name, s, MAX_LABEL_LEN + 1); } // Reads from in_file up to the next token and returns it char* next_tok() { if (current) { current = strtok(NULL, " ,\t\n"); } while (!current) { ++line_num; if (!(current = fgets(buf, MAX_LINE_LEN, in_file))) { errmsg(4, "Reached end of file"); } // If we've got a ';', kill: char* pos = strchr(buf, ';'); if (pos) { *pos = '\0'; } line_len = strlen(buf); strncpy(pretty_buf, buf, MAX_LINE_LEN + 1); current = strtok(buf, " ,\t\n"); } return lower(current); } // Reads the next token, but makes sure that it is from the same line char* next_arg() { uint16_t temp = line_num; char* tok = next_tok(); if (line_num != temp) { errmsg(4, "Incomplete instruction on previous line"); } return tok; } // Reads the next argument and returns the corresponding numeric constant // Also checks that the result falls within the representable range with the // given number of bits and signedness int32_t next_num(uint8_t bits, _Bool is_signed) { char* tok = next_arg(); size_t len = strlen(tok); if (len == 1) { errmsg(4, "'%s' is an invalid constant", tok); } int base; if (*tok == 'x') { base = 16; } else if (*tok == '#') { base = 10; } else { errmsg(4, "'%s' is an invalid constant", tok); } _Bool neg = (*++tok == '-'); if (!is_signed && neg) { errmsg(3, "Negative constant not allowed: '%s'", tok - 2); } char* c = tok + neg; if (!*c--) { errmsg(3, "No constant specified"); } while (*++c) { if ((base == 10 && !isdigit(*c)) || (base == 16 && !isxdigit(*c))) { errmsg(4, "'%s' is an invalid base-%d constant", tok, base); } } int32_t num = strtol(tok, NULL, base); if (bits == 17) { if (!(num < 65536 && num >= -32768)) { errmsg(3, "%s is outside the representable range (%d bits)", tok, bits); } return ((1 << bits) - 1) & num; } if ((is_signed && (num >= 1 << (bits - 1) || num < -1 << (bits - 1))) || (!is_signed && num >= 1 << bits)) { errmsg(3, "%s is outside the representable range (%d bits)", tok, bits); } return ((1 << bits) - 1) & num; } // Reads the next argument and returns the corresponding register number uint8_t next_reg() { char* tok = next_arg(); size_t len = strlen(tok); if (len != 2 || !(tok[0] == 'r' && tok[1] >= '0' && tok[1] < '8')) { errmsg(4, "'%s' is an invalid register", tok); } return tok[1] - '0'; } // Checks if the next argument is a register without reading from in_file _Bool peek_reg() { char* temp = current; // Advance to end of current token while (*temp++) {} // If we're at the end of buf and don't have another token: if ((size_t)(temp - buf) == line_len) { return false; } // Advance to beginning of next token while (*temp && isspace(*temp)) { ++temp; } // Check if it looks like a register constant return *temp && (*temp == 'r' || *temp == 'R'); } char* next_string() { // TODO: add support for .stringz return "This assembler doesn't support strings yet\n"; } // Reads the next argument and returns the corresponding label's // offset from the given address // Also checks that said offset is representable by a given number of bits int16_t next_label(uint8_t bits, int32_t addr) { char* tok = next_arg(); if (isdigit(*tok) || *tok == 'x') { errmsg(4, "Cannot use numeric constant as operand"); } Symbol* s = get_symbol(tok); if (!s) { errmsg(1, "Undefined label '%s'", tok); } int16_t offset = (s->addr - (addr + 2)) / 2; if (offset >= 1 << (bits - 1) || offset < -1 << (bits - 1)) { errmsg(4, "Label '%s' is too far away", tok); } return ((1 << bits) - 1) & offset; } // Reads through in_file, ignoring instructions and adding symbols to the table void build_table() { char* tok = next_tok(); if (strcmp(tok, ".orig")) { errmsg(4, "Expected '.ORIG', found: '%s'", tok); } int addr = next_num(16, false); if (addr % 2) { errmsg(3, ".ORIG address must be byte aligned"); } tok = next_tok(); while (strcmp(tok, ".end")) { if (!strcmp(tok, ".blkw")) { addr += next_num(16, false); // * 2? } else if (!strcmp(tok, ".stringz")) { addr += strlen(next_string()) + 1; } else { if (!is_reserved(tok) && tok[0] != '.') { uint16_t temp = line_num; next_tok(); if (line_num != temp) { errmsg(2, "Invalid opcode"); } add_symbol(tok, addr); } current = NULL; addr += 2; } tok = next_tok(); } } // Parses the arguments for the 'add', 'and', and 'xor' instructions uint16_t gen_arithmetic() { uint16_t temp = next_reg() << 9 | next_reg() << 6; return temp | (peek_reg() ? next_reg() : (1 << 5 | next_num(5, true))); } // Reads through the file, generating machine code for each instruction and // writing it as hex to out_file // TODO: Add support for push/pop macros void codegen() { // Skip the .orig next_tok(); uint16_t addr = next_num(16, false); // First line is the starting address fprintf(out_file, "0x%.4X\n", addr); char* tok = next_tok(); while (strcmp(tok, ".end")) { uint16_t inst = 0; if (get_symbol(tok)) { tok = next_arg(); } if (!strcmp(tok, "add")) { inst = 0x1000 | gen_arithmetic(); } else if (!strcmp(tok, "and")) { inst = 0x5000 | gen_arithmetic(); } else if (!strcmp(tok, "xor")) { inst = 0x9000 | gen_arithmetic(); } else if (!strcmp(tok, "not")) { inst = 0x903F | next_reg() << 9; inst |= next_reg() << 6; } else if (!strcmp(tok, "lshf")) { inst = 0xD000 | next_reg() << 9; inst |= next_reg() << 6; inst |= next_num(4, false); } else if (!strcmp(tok, "rshfl")) { inst = 0xD010 | next_reg() << 9; inst |= next_reg() << 6; inst |= next_num(4, false); } else if (!strcmp(tok, "rshfa")) { inst = 0xD030 | next_reg() << 9; inst |= next_reg() << 6; inst |= next_num(4, false); } else if (!strcmp(tok, "ldb")) { inst = 0x2000 | next_reg() << 9; inst |= next_reg() << 6; inst |= next_num(6, true); } else if (!strcmp(tok, "ldw")) { inst = 0x6000 | next_reg() << 9; inst |= next_reg() << 6; inst |= next_num(6, true); } else if (!strcmp(tok, "stb")) { inst = 0x3000 | next_reg() << 9; inst |= next_reg() << 6; inst |= next_num(6, true); } else if (!strcmp(tok, "stw")) { inst = 0x7000 | next_reg() << 9; inst |= next_reg() << 6; inst |= next_num(6, true); } else if (!strcmp(tok, "lea")) { inst = 0xE000 | next_reg() << 9; inst |= next_label(9, addr); } else if (!strcmp(tok, "jmp")) { inst = 0xC000 | next_reg() << 6; } else if (!strcmp(tok, "ret")) { inst = 0xC1C0; } else if (!strcmp(tok, "rti")) { inst = 0x8000; } else if (!strcmp(tok, "trap")) { // This should only take hex but it accepts decimal inst = 0xF000 | next_num(8, false); } else if (!strcmp(tok, "getc")) { inst = 0xF020; } else if (!strcmp(tok, "out")) { inst = 0xF021; } else if (!strcmp(tok, "puts")) { inst = 0xF022; } else if (!strcmp(tok, "in")) { inst = 0xF023; } else if (!strcmp(tok, "halt")) { inst = 0xF025; } else if (!strcmp(tok, "jsrr")) { inst = 0x4000 | next_reg() << 6; } else if (!strcmp(tok, "jsr")) { inst = 0x4800 | next_label(11, addr); } else if (!strcmp(tok, "nop")) { inst = 0x0000; } else if (!strcmp(tok, ".fill")) { inst = next_num(17, true); } else if (!strcmp(tok, ".blkw")) { // TODO } else { size_t len = strlen(tok); if (len >= 2 && tok[0] == 'b' && tok[1] == 'r') { char* temp = tok + 1; uint8_t nzp = 0; if (len == 2) { nzp = 7; } else { while (*++temp) { switch (*temp) { case 'n': nzp |= 4; break; case 'z': nzp |= 2; break; case 'p': nzp |= 1; break; } } } inst = 0x0000 | nzp << 9 | next_label(9, addr); } else { errmsg(2, "Invalid opcode '%s'", tok); } } uint16_t temp = line_num; tok = next_tok(); if (temp == line_num) { errmsg(4, "Extra token after instruction: %s", tok); } addr += 2; fprintf(out_file, "0x%.4X\n", inst); } } int main(int argc, char* argv[]) { if (argc != 3) { // TODO: if no output file is provided use input + ext printf("Usage: %s [INFILE] [OUTFILE]\n", argv[0]); exit(4); } if (!(in_file = fopen(argv[1], "r"))) { printf("ERROR: cannot open '%s'", argv[1]); exit(4); } build_table(); if (!(out_file = fopen(argv[2], "w"))) { printf("ERROR: cannot open '%s'", argv[2]); exit(4); } // Reset in_file after the first pass rewind(in_file); current = NULL; line_num = 0; codegen(); fclose(in_file); fclose(out_file); }