#! /bin/bash
# ========================================================================== 
# tiobj2bin - Converts TI object file from COFF or ELF to binary
#     dump format.  Intended for use as a post-build step in CCS.
#
# This code released under a license detailed at the end of this file.
#
# Invoke: tiobj2bin file.out file.bin [ofd] [hex] [mkhex]
#
# file.out - The TI .out file to convert to binary.  Can be COFF or ELF.
# file.bin - Name the binary output file
# ofd      - The object file display (ofd) utility command to invoke, with
#            path info as needed.  If not given, defaults to ofd470.
# hex      - The hex utility command to invoke, with path info as needed.
#            If not given, defaults to hex470.
# mkhex    - A custom utility which takes XML from OFD and outputs the hex
#            command file needed for the hex utility.  Path info is given
#            as needed.  If not given, defaults to mkhex4bin.  
#
# You may need to put "quotes" around the parameters.
#
# Here is an example of how this file is invoked as a post-build step in
# CCSv4 (not CCSv3.3):
#
# "${CCE_INSTALL_ROOT}/utils/tiobj2bin/tiobj2bin.bat" "${BuildArtifactFileName}" "${BuildArtifactFileBaseName}.bin" "${CG_TOOL_ROOT}/bin/ofd470.exe" "${CG_TOOL_ROOT}/bin/hex470.exe" "${CCE_INSTALL_ROOT}/utils/tiobj2bin/mkhex4bin.exe" 
#
# ========================================================================== 

# ========================================================================== 
# Automated Revision Information
# Changed: $Date$
# Revision: $Revision$
# ========================================================================== 

# ========================================================================== 
# Presumptions: 
# - Unless directory path info is provided as part of the parameter name, 
#   ofd470 and friends are in the system path
# ========================================================================== 

# ========================================================================== 
# ========================================================================== 
# FUNCTION: make_exe_work
# If ofd470 is requested, but armofd is what is available, then change it.
# Also works for hex470/armhex.  Works the other way too, i.e. ofd470
# to armofd.
# $1 Original command that may be changed
# $2 The old command name, i.e. ofd470 or hex470
# $3 The new command name, i.e. armofd or armhex
# ========================================================================== 
# ========================================================================== 
function make_exe_work()
{
    # ====================================================================== 
    # The effect of these statements is to parse the orignal command into
    # the path and file name parts.  Run "call /?" to see what %~dp1 etc
    # means.  Keep path drive letter, and ignore file name extension
    # ====================================================================== 
    orig_cmd=${1}
    orig_cmd_path=`dirname ${1}`
    orig_cmd_name=`basename ${1}`

    oldname=${2}
    newname=${3}

    final_cmd=${orig_cmd}

    # ====================================================================== 
    # If the command is not ofd470, hex470, armofd, armhex then skip
    # everything
    # ====================================================================== 
    if [ "${orig_cmd_name}" != "${oldname}" ]
    then
        if [ "${orig_cmd_name}" != "${newname}" ]
        then
            return
        fi
    fi

    # ====================================================================== 
    # If the command works now, we're done.  First, see if the file exists.
    # Second, see if the command is on the system path.
    # ====================================================================== 
    if [ -e ${final_cmd} ]
    then
        return
    fi
    if [ -e ${final_cmd}.bin ]
    then
        return
    fi
    if command -V ${final_cmd} >/dev/null 2>&1
    then
        return
    fi

    # ====================================================================== 
    # Change the base cmd name from old to new, or vice versa
    # ====================================================================== 
    if [ "${orig_cmd_name}" == "${oldname}" ]
    then
        final_cmd_name=${newname}
    else
        final_cmd_name=${oldname}
    fi

    # ====================================================================== 
    # If the cmd path is the same as the current directory, then no path
    # info was given.  The final cmd is the same as the base cmd.
    # Otherwise, concatenate the original path with the new base cmd name.
    # ====================================================================== 
    if [ ${orig_cmd_path} == `basename ${0}` ]
    then
        final_cmd=${final_cmd_name}
    else
        final_cmd=${orig_cmd_path}/${final_cmd_name}
    fi

    # ====================================================================== 
    # Test final_cmd again.  If it doesn't work now, issue an error message.
    # ====================================================================== 
    if [ -e ${final_cmd} ]
    then
        return
    fi
    if [ -e ${final_cmd}.bin ]
    then
        return
    fi
    if command -V ${final_cmd} >/dev/null 2>&1
    then
        return
    fi

    # ======================================================================
    # If we get here, there is an error
    # ======================================================================
    echo "ERROR: Command Not Found"
}

# ========================================================================== 
# Handle command line args
# ========================================================================== 
if [ "${1}" = "" ];
then
    echo "Usage: ${0} file.out file.bin [ofd] [hex] [mkhex]"
    exit 1
fi
outfile=${1}

if [ "${2}" = "" ];
then
    echo "Usage: ${0} file.out file.bin [ofd] [hex] [mkhex]"
    exit 1
fi
binfile=${2}

ofdcmd=ofd470
if [ "${3}" != "" ];
then
    ofdcmd=${3}
fi
hexcmd=hex470
if [ "${4}" != "" ];
then
    hexcmd=${4}
fi
mkhexcmd=mkhex4bin
if [ "${5}" != "" ];
then
    mkhexcmd=${5}
fi

# ========================================================================== 
# Possibly change the OFD and HEX commands.  See make_exe_work for details.
# ========================================================================== 
make_exe_work ${ofdcmd} ofd470 armofd
ofdcmd=${final_cmd}
make_exe_work ${hexcmd} hex470 armhex
hexcmd=${final_cmd}

# ========================================================================== 
# Compose temporary file names used for ofd and hex cmds
#    Run "set /?" to see documentation of %random%
# ========================================================================== 
xmltmp=ofd_${RANDOM}_${RANDOM}_${RANDOM}.xml
hextmp=hexcmd_${RANDOM}_${RANDOM}_${RANDOM}.tmp

# ========================================================================== 
# Paranoid checks on the temp files
# ========================================================================== 
if [ -e ${xmltmp} ]
then
   echo "XML temp file exists. Giving up."
   exit 1
fi

if [ -e ${hextmp} ]
then
   echo "HEX temp file exists. Giving up."
   exit 1
fi

# ========================================================================== 
# 1. Create the XML from the .out file
# 2. Create the hex command file from the XML
# 3. Create the binary from the .out file and hex file
# ========================================================================== 
${ofdcmd} -x --xml_indent=0 --obj_display=none,sections,header,segments ${outfile} > ${xmltmp}

${mkhexcmd} ${xmltmp} > ${hextmp}

${hexcmd} -q -b -image -o ${binfile} ${hextmp} ${outfile}

# ========================================================================== 
# Remove the temp files
# ========================================================================== 
rm -f ${xmltmp}
rm -f ${hextmp}

# /*
# *
# * Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ 
# * 
# * 
# *  Redistribution and use in source and binary forms, with or without 
# *  modification, are permitted provided that the following conditions 
# *  are met:
# *
# *    Redistributions of source code must retain the above copyright 
# *    notice, this list of conditions and the following disclaimer.
# *
# *    Redistributions in binary form must reproduce the above copyright
# *    notice, this list of conditions and the following disclaimer in the 
# *    documentation and/or other materials provided with the   
# *    distribution.
# *
# *    Neither the name of Texas Instruments Incorporated nor the names of
# *    its contributors may be used to endorse or promote products derived
# *    from this software without specific prior written permission.
# *
# *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
# *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
# *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
# *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
# *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
# *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
# *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
# *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# *
# */
