#!/bin/bash -eu
#
# Copyright © 2017 Samuel Holland <samuel@sholland.org>
# See LICENSE in the project directory for license terms.
#
# bash is only required for hexadecimal math.
#

# Adjust these as needed
ARCH=${ARCH:-or1k}
CROSS_COMPILE=${CROSS_COMPILE:-${ARCH}-linux-musl-}

# Command-line parameters
dir=$1

# Internal variables
assembly=${dir}/blob.s
blob=${dir}/blob.elf
comments=${dir}/comments
sections=${dir}/sections

# Ensure the disassembly and the comments file exist
make "$assembly"
make BLOB="$dir" save

# Ensure the comments file has enough lines
if ! grep -q . "$comments"; then
  sed 's/.*//' "$assembly" > "$comments"
fi

# Create temporary files for extracting parts of the blob
tmpfile=$(mktemp)
tmpimed=$(mktemp)
trap 'rm -f "$tmpfile" "$tmpimed"' EXIT
${CROSS_COMPILE}objcopy -O binary "$blob" "$tmpimed"

addrs=( $(grep 'text$' "$sections" | cut -d' ' -f1) )
for i in ${!addrs[@]}; do
  # Extract the code/data out of one part of the ELF (to get correct offsets)
  base=${addrs[i]}
  if test "$i" -lt "$((${#addrs[@]} - 1))"; then
    end=${addrs[i+1]}
    printf 'Dumping blob contents from 0x%08x to 0x%08x\n' "$base" "$end"
    dd bs=1 count="$((end - base))" if="$tmpimed" of="$tmpfile" \
      skip="$((base))" 2>/dev/null
  else
    printf 'Dumping blob contents baseing at 0x%08x\n' "$base"
    dd bs=1 if="$tmpimed" of="$tmpfile" \
      skip="$((base))" 2>/dev/null
  fi

  ${CROSS_COMPILE}strings -d -t x "$tmpfile" |
  while read -r addr msg; do
    addr=$((base + 0x${addr}))
    comment=$(printf '; msg = 0x%08x "%s"\n' "$addr" "$msg")
    pattern=$(printf 'l.ori r4,r4,0x%x' "$((addr & 0xffff))")
    printf '  Looking for l.ori r4,r4,0x%x ...' "$addr"
    grep -Fn "$pattern" "$assembly" | cut -d: -f1 |
    while read -r line; do
      printf ' %d' "$line"
      sed -i "${line}s@.*@${comment}@" "$comments"
    done
    printf '\n'
  done
done

# Build everything with the new symbols
make BLOB="$dir"
