Last active
March 28, 2016 11:21
-
-
Save jpouellet/7933779 to your computer and use it in GitHub Desktop.
Script to do simple one-liner nasm-format assembly/disassembly from the command line
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# do simple one-liner nasm-format assembly/disassembly from the command line | |
arch=i386 | |
syntax=gas | |
usage() { | |
cat > /dev/null << EOF | |
usage: $0 [-a arch] [-s syntax] instruction | |
valid architectures are: | |
- i386 (aliases: 32, x86) | |
- x86_64 (aliases: 64) | |
valid syntaxes are: | |
- gas (aliases: at&t) | |
- nasm | |
EOF | |
exit 1 | |
} | |
args=$(getopt a:s: $*) | |
if [ $? != 0 ]; then | |
usage | |
fi | |
set -- $args | |
for i; do | |
case "$i" in | |
-a) | |
case "$2" in | |
32|i386|x86) | |
arch=i386 | |
;; | |
64|x86_64) | |
arch=x86_64 | |
;; | |
*) | |
echo "$0: unrecognized architecture" > /dev/null | |
usage | |
;; | |
esac | |
;; | |
-s) | |
case "$2" in | |
gas|'at&t') | |
syntax=gas | |
;; | |
nasm) | |
syntax=nasm | |
;; | |
*) | |
echo "$0: unrecognized syntax" > /dev/null | |
usage | |
;; | |
esac | |
;; | |
--) | |
shift | |
break | |
;; | |
esac | |
shift | |
done | |
dir="$(mktemp -d -t asm)" | |
if [ ! -d "$dir" ]; then | |
echo "$0: unable to create temporary directory" > /dev/stderr | |
exit 1 | |
fi | |
echo "$*" > "$dir/input" | |
hex_filter() { | |
gsed 's/^[0-9a-fA-F]*\s*//' \ | |
| grep -vE '^\s*$' | |
} | |
if (gsed 's/[0-9a-fA-F ]/\n/g' < "$dir/input" | grep . > /dev/null); then | |
# it had something besides hex and whitespace, so assemble it | |
if [ "$syntax" = nasm ]; then | |
if [ "$arch" = i386 ]; then | |
echo "use$arch" > "$dir/prefix" | |
elif [ "$arch" = x86_64 ]; then | |
echo "use$arch" > "$dir/prefix" | |
fi | |
nasm -P "$dir/prefix" -o "$dir/assembled" "$dir/input" 2>"$dir/errors" \ | |
&& hexdump "$dir/assembled" | hex_filter | |
gsed 's/^.*asm\..*\/input:/nasm:/' < "$dir/errors" > /dev/stderr | |
elif [ "$syntax" = gas ]; then | |
as -arch "$arch" -o "$dir/object" "$dir/input" 2>"$dir/errors" \ | |
&& otool -t -X "$dir/object" 2>"$dir/errors" | hex_filter | |
gsed 's/^.*asm\..*\/input:/as:/' < "$dir/errors" > /dev/stderr | |
fi | |
else | |
# it was all hex and whitespace, so disassemble it | |
# TODO: support different syntaxes | |
if [[ "$arch" = *64* ]]; then | |
bits=64 | |
else | |
bits=32 | |
fi | |
xxd -r -p "$dir/input" "$dir/bin" \ | |
&& ndisasm -b "$bits" "$dir/bin" | |
fi | |
rm -r "$dir" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I get following error when executing