#!/bin/sh
# SPDX-License-Identifier: GPL-2.0-or-later

# Simple script to disassemble a file .inc generated by
# src/helper/bin2char.sh
# Can be useful to check the correctness of the file .inc
#
# By default it decodes ARM thumb little-endian, e.g. cortex-m.
# Set CROSS_COMPILE for other toolchains.
# Set OBJDUMP_FLAGS for different objdump flags.
#
# Usage:
#   contrib/loaders/disassemble_inc.sh file.inc

default_CROSS_COMPILE="arm-none-eabi-"
default_OBJDUMP_FLAGS="-m arm -EL -M force-thumb"

if [ $# != 1 -o ! -f "$1" ]; then
	echo "Usage:"
	echo "    $0 path/to/file.inc"
	echo ""
	echo "Set CROSS_COMPILE and/or OBJDUMP_FLAGS to override current default:"
	echo "    export CROSS_COMPILE=\"${default_CROSS_COMPILE}\""
	echo "    export OBJDUMP_FLAGS=\"${default_OBJDUMP_FLAGS}\""
	exit 1
fi

if [ -z "${CROSS_COMPILE}" ]; then
	CROSS_COMPILE="${default_CROSS_COMPILE}"
fi

if [ -z "${OBJDUMP_FLAGS}" ]; then
	OBJDUMP_FLAGS="${default_OBJDUMP_FLAGS}"
fi

perl -v > /dev/null 2>&1
if [ $? != 0 ]; then
	echo "Error: 'perl' interpreter not available."
	exit 1
fi

tmpfile=$(mktemp --suffix=.bin)

echo "Disassemble $1:"
echo "${CROSS_COMPILE}objdump ${OBJDUMP_FLAGS} -b binary -D ${tmpfile}"

perl -e 'while (<>){while ($_=~/(0x..)/g){print chr(hex($1));}}' $1 > ${tmpfile}
${CROSS_COMPILE}objdump ${OBJDUMP_FLAGS} -b binary -D ${tmpfile}

rm ${tmpfile}
