#!/bin/sh
# --- Copyright University of Sussex 1997. All rights reserved. ----------
# File:             C.mips/src/patch
# Purpose:          Patches assembler files produced by POPC
# Author:           Rob Duncan & Simon Nichols, May 29 1990 (see revisions)


# Horrible hack to cope with MIPS' assembler's inability to handle differences
# between relocatable labels.

# Reads an object file ($1) plus the corresponding assembler source ($2)
# which may include some patch indicators as comments, and produces a new
# version of the object with the patches made.

FLAGS=
while true; do
	case "$1" in
		-G)	FLAGS="$FLAGS $1 $2"
			shift; shift;;

		-*)	FLAGS="$FLAGS $1"
			shift;;

		*)	break;;
	esac
done

tmpfile=${TMPDIR-/tmp}/patch.$$
patchfile=$2.patch
trap "rm -f $tmpfile $patchfile" 0

# Step 1:
# read the symbol table of the object file and write out the values of all
# local labels
# NB: standard error of nm needs to be redirected, because it may give a
# segmentation violation at the end (!)

# format of output from nm varies between systems
case `uname -r -s` in
	IRIX*)
		ARGS=
		NF=7
		NAME=7
		VALUE=2
		CLASS=4
		;;
	*)
		ARGS=-A
		NF=7
		NAME=1
		VALUE=2
		CLASS=3
		;;
esac
nm $ARGS $1 2>/dev/null | awk -F'|' > $tmpfile '
	NF=='$NF' && $'$NAME' ~ /^ *[Lx]/ && $'$CLASS' !~ /stNil/ && $'$CLASS' !~ /End/ {
			printf " ##PATCH## %s %d\n", $'$NAME', $'$VALUE'
		}'

# Step 2:
# append the contents of the assembler source, but with all patches moved
# to the top of the file and to the start of the line

grep '^L[0-9A-Za-z_]* =' $2 | sed -e '/.*##PATCH##/s// ##PATCH##/' >> $tmpfile
grep -v '^L[0-9A-Za-z_]* =' $2 >> $tmpfile

# Step 3:
# substitute all patches in the file with proper label assignments

awk < $tmpfile > $patchfile '
	$1 == "##PATCH##" {
		if (NF == 3)
			# Label definition
			L[$2] = $3;
		else if (NF == 4)
			# Simple difference
			printf "%s = %d-%d\n", $2, L[$3], L[$4];
		else
			# Procedure length
			printf "%s = ((%d-%d)>>2)+%d\n", $2, L[$3], L[$4], $5;
	}
	$1 != "##PATCH##" {
		print $0
	}'

# Step 4:
# reassemble the patched file

as $FLAGS -o $1 $patchfile

# --- Revision History ---------------------------------------------------
# --- Robert Duncan, Dec  3 1997
#		All IRIX versions now use nm without -A and get the same output
# --- Robert John Duncan, Nov 22 1994
#		Added case for IRIX 6.0 (assumed to be the same as IRIX 5)
# --- Robert John Duncan, May 24 1994
#		Further tweaks for IRIX 5
# --- Robert John Duncan, Mar 25 1994
#		Now copes with the revised ordering of information produced by nm
#		under IRIX 5
# --- Robert John Duncan, Mar 18 1994
#		Improved argument processing
# --- Robert John Duncan, Jan  9 1991
#		Changed to use assembler's temporary directory (TMPDIR) if set.
