view src/main.c @ 0:57495da01900

Initial checking of LWASM
author lost
date Fri, 03 Oct 2008 02:44:20 +0000
parents
children 34568fab6058
line wrap: on
line source

/*
main.c

Implements the program startup code

*/

#include <argp.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

#include "lwasm.h"

// external declarations
extern void resolve_phasing(asmstate_t *as);
extern void generate_code(asmstate_t *as);
extern void list_code(asmstate_t *as);
extern void write_code(asmstate_t *as);


// command line option handling
const char *argp_program_version = "LWASM Version 0.0";
const char *argp_program_bug_address = "lost@l-w.ca";

static error_t parse_opts(int key, char *arg, struct argp_state *state)
{
	asmstate_t *as = state -> input;
	
	switch (key)
	{
	case 'o':
		// output
		if (as -> outfile)
		{
		}
		as -> outfile = arg;
		break;
	
	case 'd':
		// debug
		as -> debug++;
		break;
	
	case 'l':
		// list
		if (arg)
			as -> listfile = arg;
		else
			as -> listfile = "-";
		break;
	
	case 'b':
		// decb output
		as -> outformat = OUTPUT_DECB;
		break;
	
	case 'r':
		// raw binary output
		as -> outformat = OUTPUT_RAW;
		break;
		
	case ARGP_KEY_END:
		// done; sanity check
		if (!as -> outfile)
			as -> outfile = "a.out";
		break;
	
	case ARGP_KEY_ARG:
		// non-option arg
		if (as -> infile)
			argp_usage(state);
		as -> infile = arg;
		break;
		
	default:
		return ARGP_ERR_UNKNOWN;
	}
	return 0;
}

static struct argp_option options[] =
{
	{ "output",		'o',	"FILE",	0,
				"Output to FILE"},
	{ "debug",		'd',	0,		0,
				"Set debug mode"},
	{ "list",		'l',	"FILE",	OPTION_ARG_OPTIONAL,
				"Generate list [to FILE]"},
	{ "decb",		'b',	0,		0,
				"Generate DECB .bin format output"},
	{ "raw",		'r',	0,		0,
				"Generate raw binary format output"},
	{ "rawrel",		0,		0,		0,
				"Generate raw binary respecing ORG statements as offsets from the start of the file"},
	{ 0 }
};

static struct argp argp =
{
	options,
	parse_opts,
	"<input file>",
	"LWASM, a HD6309 and MC6809 cross-assembler"
};

// main function; parse command line, set up assembler state, and run the
// assembler on the first file
int main(int argc, char **argv)
{
	// assembler state
	asmstate_t asmstate = { 0 };

	argp_parse(&argp, argc, argv, 0, 0, &asmstate);
	if (!asmstate.listfile)
		asmstate.listfile = "-";
	
//	printf("Assembling %s to %s; list to %s\n", asmstate.infile, asmstate.outfile, asmstate.listfile);

	/* pass 1 - collect the symbols and assign addresses where possible */
	/* pass 1 also resolves included files, etc. */
	/* that means files are read exactly once unless included multiple times */
	lwasm_read_file(&asmstate, (char *)(asmstate.infile));
	
	// pass 2: actually generate the code; if any phasing errors appear
	// at this stage, we have a bug
	generate_code(&asmstate);

	// now make a pretty listing
	list_code(&asmstate);

	// now write the code out to the output file
	write_code(&asmstate);

	if (asmstate.errorcount > 0)
		exit(1);

	exit(0);
}