asm2hex.pl

download

asm2hex

#!/usr/bin/perl
# asm2hex.pl
#
# author       : demod at foosel dot net
# description  : a perl-friendly at&t assembler to hex converter
#                (building ontop of gas and objdump)
# license      : bsd
# version      : 0.1 (19.09.2005)
#
# options:
#   -q   suppress comments
#
# usage example:
#   $ perl asm2hex.pl
#   Hit ^D to finish:
#   xorl %ebx,%ebx
#   leal 0x17(%ebx),%eax
#   int  $0x80
#   ^D
#
#  Output:
#
#   "\x31\xdb" .                       # xor    %ebx,%ebx
#   "\x8d\x43\x17" .                   # lea    0x17(%ebx),%eax
#   "\xcd\x80";                        # int    $0x80
 
use strict;
use IO::File;
use POSIX qw(tmpnam);
 
# settings
my $objdump="/usr/bin/objdump";
my $gas="/usr/bin/as";
my $indent = 35;
 
 
if(!-f $objdump ) { die "$!: $objdump" }
if(!-f $gas )     { die "$!: $gas" }
 
my ($name, $fh, $i);
my @output;
 
# getting a /tmp file
do {
	$name = tmpnam();
} until $fh = IO::File->new($name, O_RDWR|O_CREAT|O_EXCL);
 
 
print "Hit ^D to finish:\n";
 
# call gas
system("cat | $gas -o $name") == 0 || die;
 
# call objdump
my @input=`$objdump -d -j.text $name`;
 
 
# reformat the output
#
for(1..6) {
	shift @input;
}
 
print "\nOutput:\n\n";
 
foreach(@input) {
	if(/^\w*?$/) { next; };
 
	chomp();
 
	my @tmp = split("\t", $_);
 
 
	$tmp[1] =~ s/(\w\w)\s/\\x$1/g;
 
	if(defined($ARGV[0]) && ($ARGV[0] =~ m/-q/)) {	# -quiet output
		$tmp[1] =~ s/\s*?//g;
		push @output, "$tmp[1]";
 
	} else {	# normal output
		$tmp[1] =~ s/^/\"/;
		$tmp[1] =~ s/\s*?$/" ./;
 
		$i = $indent - length($tmp[1]);
 
		push @output, $tmp[1] . " " x $i . "# " . $tmp[2] . "\n";
	}
}
 
# reformat the beginning & end ouf the @output string
 
if(defined($ARGV[0]) && ($ARGV[0] =~ m/-q/)) {	# -quiet output
	unshift @output, '"';
	push @output, "\";\n";
} else {	# normal output
	#$output[-1] =~ s/ \./; /g;
}
 
 
foreach(@output) {
	print;
}
 
unlink($name) || die $!;