64 lines
2.1 KiB
C
64 lines
2.1 KiB
C
/***************************************************************************
|
|
* file name : assembler.c *
|
|
* author : *
|
|
* description : This program will assemble a .ASM file into a .OBJ file *
|
|
* This program will use the "asm_parser" library to achieve *
|
|
* its functionality. *
|
|
* *
|
|
***************************************************************************
|
|
*
|
|
*/
|
|
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
#include <stdlib.h>
|
|
#include "asm_parser.h"
|
|
|
|
int main(int argc, char **argv) {
|
|
if (argc < 2) {
|
|
printf("Usage: %s <assembly_file.asm>\n", argv[0]);
|
|
return 1;
|
|
}
|
|
char *filename = argv[1]; // name of ASM file
|
|
char program[ROWS][COLS]; // ASM file line-by-line
|
|
char program_bin_str[ROWS][17]; // instructions converted to a binary string
|
|
unsigned short int program_bin[ROWS]; // instructions in binary (HEX)
|
|
int num_lines = read_asm_file(filename, program);
|
|
if (num_lines < 0) {
|
|
return 1;
|
|
}
|
|
int instr_count = 0;
|
|
for (int i = 0; i < num_lines; i++) {
|
|
char *line = program[i];
|
|
char instr_bin_str[17];
|
|
int ret = parse_instruction(line, instr_bin_str);
|
|
if (ret == 1) {
|
|
strcpy(program_bin_str[instr_count], instr_bin_str);
|
|
program_bin[instr_count] = str_to_bin(instr_bin_str);
|
|
instr_count++;
|
|
} else if (ret == 0) {
|
|
// Skip empty or comment line
|
|
continue;
|
|
} else {
|
|
printf("Error parsing line %d: %s\n", i + 1, line);
|
|
return 1;
|
|
}
|
|
}
|
|
// Write the object file
|
|
char obj_filename[256];
|
|
strcpy(obj_filename, filename);
|
|
char *dot = strrchr(obj_filename, '.');
|
|
if (dot != NULL) {
|
|
strcpy(dot, ".obj");
|
|
} else {
|
|
strcat(obj_filename, ".obj");
|
|
}
|
|
int ret = write_obj_file(obj_filename, program_bin, instr_count);
|
|
if (ret < 0) {
|
|
printf("Error writing object file\n");
|
|
return 1;
|
|
}
|
|
printf("Successfully assembled %s to %s\n", filename, obj_filename);
|
|
return 0;
|
|
}
|