#!/usr/bin/python

import argparse
import subprocess
import sys

parser = argparse.ArgumentParser( 	description='Creates a memory image of ELF files.',
					epilog='Use "gcc -fPIC -fno-stack-protector -fno-builtin -fno-jump-tables -c test.c" to compile the input files.' )
parser.add_argument( 	'-T',
			metavar='ldscript',
			nargs='?',
			const="/usr/local/include/Image_creator/linker.ld",
			default="/usr/local/include/Image_creator/linker.ld",
			help='The link script that should be used' )
parser.add_argument(	'-o',
			metavar='output',
			nargs='?',
			const="chunk",
			default="chunk",
			help='The name of the output file' )
parser.add_argument(	'-v',
			action='store_true',
			help='Outputs the different commands being called' )
parser.add_argument(	'i',
			metavar='ELF',
			nargs='+',
			help='a list of ELF files to combine' )

args = parser.parse_args()

boutput = args.o.split('.')[0];

link 	= 'ld -T ' + args.T + ' -o .' + boutput + ".img --no-allow-shlib-undefined --whole-archive " + " ".join(args.i)
extract	= 'objcopy -j IMAGE -O binary .' + boutput + '.img ' + boutput + '.img'

if args.v:
	print link

if  subprocess.call( link, shell=True ) == 0:
	if args.v:
		print extract
	
	if subprocess.call( extract, shell=True ) == 0:
		
		with open( boutput + ".S", "w" ) as assembly:
			assembly.write( "\t.file \"" + boutput + ".S\"\n" )
			assembly.write( ".text\n" )
			assembly.write( "\n" )
			assembly.write( ".globl " + boutput + "_start \n" )
			assembly.write( "\t.type " + boutput + "_start, @object\n" )
			assembly.write( boutput + "_start:\n" )
			
			with open( boutput + ".img", "rb" ) as image:
				byte = image.read( 1 )
				while byte != "":
					assembly.write( "\t.byte " + hex( ord( byte[0] ) ) + "\n" )
					byte = image.read( 1 )
			
			assembly.write( ".globl " + boutput + "_end \n" )
			assembly.write( "\t.type " + boutput + "_end, @object\n" )
			assembly.write( boutput + "_end:\n" )
			
			sys.exit( 0 );
	else:
		print "Failed! - Could not extract section from ELF file"
		sys.exit( -2 );
else:
	print "Failed! - Could not link objects"
	sys.exit( -1 );


