Files
gb-emu/src/apps/gbasm.c
2018-02-18 12:51:10 -08:00

90 lines
1.7 KiB
C

/* A simple, two-pass gameboy assembler */
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "gbasm/emitter.h"
#include "gbasm/assemble.h"
#define GBASM_FILE_BUFFER_SIZE (1024 * 1024)
static char file_buffer[GBASM_FILE_BUFFER_SIZE];
static void usage()
{
printf("gbasm -i <file> -o <file>\n"
" -h Print this usage \n"
" -i <input file> The file to assemble\n"
" -o <output file> The file to write the assembled program to\n");
}
int main(int argc, char **argv)
{
struct emitter emitter;
struct fd_emitter fd_emitter;
char opt;
int in_fd = -1;
int out_fd = -1;
while ((opt = getopt(argc, argv, "i:o:h")) != -1) {
switch (opt) {
case 'o':
if (out_fd >= 0) {
close(out_fd);
}
out_fd = open(optarg,
O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR);
if (out_fd < 0) {
fprintf(stderr, "failed to open output file %s\n", optarg);
exit(1);
}
break;
case 'i':
if (in_fd >= 0) {
close(in_fd);
}
in_fd = open(optarg, O_RDONLY);
if (in_fd < 0) {
fprintf(stderr, "failed to open input file %s\n", optarg);
exit(1);
}
break;
case 'h':
usage();
exit(1);
case ':':
fprintf(stderr, "Option -%c requires argument\n", optopt);
usage();
exit(1);
case '?':
fprintf(stderr, "Unrecognized option -%c\n", optopt);
usage();
exit(1);
}
}
if (in_fd < 0) {
exit(1);
} else {
pread(in_fd, file_buffer, GBASM_FILE_BUFFER_SIZE - 1, 0);
file_buffer[GBASM_FILE_BUFFER_SIZE - 1] = '\0';
}
if (out_fd < 0) {
exit(1);
}
fd_emitter_init(&emitter, &fd_emitter, out_fd);
return gbasm_assemble(file_buffer, &emitter);
}