agssim: factor null check out of vm_run()
[rofl0r-agsutils.git] / agssemble.c
blob46687633c1a45618dfe6d21f13b832e7100c48cb
1 #define _GNU_SOURCE
2 #include "Assembler.h"
3 #include "DataFile.h"
4 #include "preproc.h"
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <unistd.h>
8 #include "version.h"
9 #define ADS ":::AGSsemble " VERSION " by rofl0r:::"
11 static int usage(char *argv0) {
12 dprintf(2, ADS "\nusage:\n%s [-E] [-i file.i] [-I includedir] [-D preproc define] file.s [file.o]\n"
13 "pass an ags assembly filename.\n"
14 "-E: invoke built-in C preprocessor 'tinycpp' on the input file before assembling\n"
15 "-I includedir - add include dir for CPP\n"
16 "-D define - add define for CPP\n"
17 "-i file save preprocessor output to file\n"
18 "if optional second filename is ommited, will write into file.o\n", argv0);
19 return 1;
22 static FILE *freopen_r(FILE *f, char **buf, size_t *size) {
23 fflush(f);
24 fclose(f);
25 return fmemopen(*buf, *size, "r");
28 int main(int argc, char** argv) {
29 struct cpp* cpp = cpp_new();
30 char *tmp, *cppoutfn = 0;
31 int flags = 0, c;
32 while ((c = getopt(argc, argv, "Ei:I:D:")) != EOF) switch(c) {
33 case 'E': flags |= 1; break;
34 case 'i': cppoutfn = optarg; break;
35 case 'I': cpp_add_includedir(cpp, optarg); break;
36 case 'D':
37 if((tmp = strchr(optarg, '='))) *tmp = ' ';
38 cpp_add_define(cpp, optarg);
39 break;
40 default: return usage(argv[0]);
42 if(!argv[optind]) return usage(argv[0]);
43 char* file = argv[optind];
44 char out [256], *outn;
45 if(!argv[optind+1]) {
46 size_t l = strlen(file);
47 char *p;
48 snprintf(out, 256, "%s", file);
49 p = strrchr(out, '.');
50 if(!p) p = out + l;
51 *(p++) = '.';
52 *(p++) = 'o';
53 *p = 0;
54 outn = out;
55 } else outn = argv[optind+1];
56 if(!strcmp(outn, file)) {
57 dprintf(2, "error: input and output file (%s) identical!\n", file);
58 return 1;
61 FILE *in = fopen(file, "r");
62 if(!in) {
63 dprintf(2, "error opening file %s\n", file);
64 return 1;
67 if(flags & 1) {
68 struct FILE_container {
69 FILE *f;
70 char *buf;
71 size_t len;
72 } output = {0};
73 if(!cppoutfn) output.f = open_memstream(&output.buf, &output.len);
74 else output.f = fopen(cppoutfn, "w");
75 dprintf(1, "preprocessing %s ...", file);
76 int ret = cpp_run(cpp, in, output.f, file);
77 if(!ret) {
78 dprintf(1, "FAIL\n");
79 return 1;
81 dprintf(1, "OK\n");
82 fclose(in);
83 if(!cppoutfn) in = freopen_r(output.f, &output.buf, &output.len);
84 else {
85 fclose(output.f);
86 in = fopen(cppoutfn, "r");
89 cpp_free(cpp);
91 AS a_b, *a = &a_b;
92 AS_open_stream(a, in);
94 dprintf(1, "assembling %s -> %s ... ", file, outn);
95 int ret = AS_assemble(a, outn);
96 AS_close(a);
98 if(!ret) dprintf(1, "FAIL\n");
99 else dprintf(1, "OK\n");
100 return !ret;