#!/bin/sh
#-----------------------------------------------------------------------------
# ldmap: Determine dependencies between object modules from a namelist
#-----------------------------------------------------------------------------
#
#   Copyright (C) 1996-2005
#   Associated Universities, Inc. Washington DC, USA.
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#   Correspondence concerning AIPS++ should be addressed as follows:
#          Internet email: casa-feedback@nrao.edu.
#          Postal address: AIPS++ Project Office
#                          National Radio Astronomy Observatory
#                          520 Edgemont Road
#                          Charlottesville, VA 22903-2475 USA
#
#-----------------------------------------------------------------------------
# Usage: ldmap <options> <namelist [namelist...]>
# Options:  [-1]
#           [-h #]
#           [-m|-M]
#           [-n]
#           [-o|-O <object>]
#           [-p <file> -P <directory>]
#           [-r]
#           [-s <file>|<directory>]
#           [-t]
#           [-v <file>]
#-----------------------------------------------------------------------------
# ldmap reads through a file containing namelist output (produced by 'nm') and
# determines the dependency hierarchy of .o files.  That is, if X is an
# undefined symbol in a.o, and X is defined in b.o, then a.o depends on b.o.
#
# The expected format of the namelist output is as generated by GNU 'nm' using
# the "posix" output format option:
#
#   nm --format=posix -g <object library | file>
#
# Only global symbols are used and the "-g" option is used here (optionally)
# to suppress local symbols.
#
# The name list file may be specified as "-" whence ldmap will read it from
# stdin.
#
# The analysis is done in two stages.  First the namelist is converted to a
# list of dependencies of the form
#
#    a.o b.o
#
# meaning that a.o requires b.o.  If the -m option is specified the output
# looks like
#
#    a.o usym b.o
#
# where "usym" is the undefined symbol in a.o which would cause the linker to
# load b.o.  If the -M option is specified the output also includes lines such
# as
#
#    a.o dsym a.o
#
# where dsym is a symbol defined in a.o.
#
# Unresolved symbols may be included in the output via the -n option
#
#    a.o (usym)
#
# and if the output from 'ar tv' is given via the -v option, the size of the
# object file will be included as
#
#    a.o size
#
# The stage 2 analysis consists of iterating through the dependency list to
# find all object modules required by each particular object module.  By
# default, all object modules in the dependency list are processed, however
# the analysis may be done for a set of object modules via the -o option.
#
# Since the stage 1 analysis is time-consuming, the intermediate results can
# be saved for later use in either or both of two forms.  In packed form, the
# stage 1 results are stored in a single file.  In the unpacked form, which is
# the most efficient for the stage two analysis, the results for each object
# module are stored in a separate file in a subdirectory.
#
# Options:
#   -1     Quit after the stage 1 analysis.
#
#   -h #   Set a limit to the depth of the dependency hierarchy in the stage 2
#          analysis.
#
#   -m|-M  Produce a stage 1 analysis with more information than is needed
#          for stage 2.
#
#          -m includes symbol names in the output of the stage 1 analysis, and
#          -M also includes symbols defined in each object module.
#
#          The -m and -M options are meant to be used with the -p option to
#          produce a file for visual inspection.  The extra information is
#          thrown away when the stage 1 analysis is unpacked.
#
#   -n     Include unresolved symbols in the stage 1 analysis.  They appear
#          in the stage 1 output in parentheses.
#
#   -o <object>
#   -O <object>
#          Determine dependencies for the specified object module only.
#          Multiple object modules may be specified in a single -o, or
#          multiple -o options may be specified.  Either way the analysis is
#          performed for the group as a whole.
#
#          If -O is specified the stage 1 analysis will be unpacked, otherwise
#          the packed analysis will be used unless the unpacked analysis is
#          already available.
#
#   -p <file>
#   -P <directory>
#          Preserve the result of the stage 1 analysis.
#
#          -p saves the packed result in the specified file.
#
#          -P saves the unpacked result in the specified directory.
#
#          If the file and/or directory already exist they will be deleted.
#          Both options may be specified together.
#
#   -r     Reverse the direction of the dependency analysis.  In the stage 1
#          analysis the namelist is converted to a list of dependencies of the
#          form
#
#             a.o b.o
#
#          meaning that a.o is required by b.o.  The stage 2 analysis is
#          unaffected.  Use of the -r option precludes the use of the -n and
#          -v options.
#
#   -s <file>
#   -s <directory>
#          Skip stage 1 of the analysis.
#
#          -s specifies the name of a file containing the stage 1 analysis
#             from a previous invokation of 'ldmap -p', or the name of a
#             directory containing the unpacked stage 1 analysis from a
#             previous invokation of 'ldmap -P'.
#
#          In either case the namefile need not be specified.
#
#          A -s option may not be combined with stage 1 analysis options
#          except for the combination "-s <file> -P <directory>".
#
#   -t     Print timing information.
#
#   -v <file>
#          A file containing the output of 'ar tv' used for determining object
#          module sizes.  The expected format is as generated by GNU 'ar',
#          noting in particular that 'ar' in Solaris produces a slightly
#          different, and incompatible format.  Multiple -v options may be
#          specified.
#
# Status return values correspond to the various phases of the operation
#    0:  success
#    1:  initialization error
#
# Notes:
#    1) The output of ldmap may be piped through c++filt to demangle C++
#       names.
#
# Original: Mark Calabretta, ATNF
# $Id$
#-----------------------------------------------------------------------------
# Parse options.
  S1OPT=
  QUIT1=
  HIER=
  MORE=
  UNRES=
  OBJS=
  UNPACK=1
  KEEP1P=
  KEEP1U=
  REVERSE=
  SKIP1=
  TIMER=
  ARTVS=
  FILES=
  while [ "$#" -gt 0 ]
  do
     case $1 in
     -1)
        S1OPT=2
        QUIT1=1
        ;;
     -h*)
        case $1 in
        -h)
           shift
           HIER="$1"
           ;;
        *)
           HIER=`echo $1 | sed -e 's/^-h//'`
           ;;
        esac
        ;;
     -m)
        S1OPT=1
        MORE=1
        ;;
     -M)
        S1OPT=1
        MORE=2
        ;;
     -n)
        S1OPT=1
        UNRES=1
        ;;
     -[oO]*)
        case $1 in
        -o*)
           [ "$UNPACK" = 1 ] && UNPACK=
           ;;
        esac

        case $1 in
        -[oO])
           shift
           OBJS="$OBJS $1"
           ;;
        *)
           OBJS="$OBJS `echo $1 | sed -e 's/^-o//'`"
           ;;
        esac
        ;;
     -p*)
        S1OPT=1
        case $1 in
        -p)
           shift
           KEEP1P="$1"
           ;;
        *)
           KEEP1P=`echo $1 | sed -e 's/^-p//'`
           ;;
        esac
        ;;
     -P*)
        S1OPT=2
        case $1 in
        -P)
           shift
           KEEP1U="$1"
           ;;
        *)
           KEEP1U=`echo $1 | sed -e 's/^-P//'`
           ;;
        esac
        ;;
     -r)
        S1OPT=1
        REVERSE=1
        ;;
     -s*)
        case $1 in
        -s)
           shift
           SKIP1="$1"
           ;;
        *)
           SKIP1=`echo $1 | sed -e 's/^-s//'`
           ;;
        esac
        ;;
     -t)
        TIMER=date
        ;;
     -v*)
        S1OPT=1
        case $1 in
        -v)
           shift
           ARTVS="$ARTVS $1"
           ;;
        *)
           ARTVS="$ARTVS `echo $1 | sed -e 's/^-v//'`"
           ;;
        esac
        ;;
     *)
        S1OPT=1
        FILES="$FILES $1"
        ;;
     esac

     [ "$2" = "" ] && break

     shift
  done

  if [ "$REVERSE" ]
  then
     UNRES=
     ARTVS=
  fi

  if [ "$SKIP1" ]
  then
     if [ ! \( -f "$SKIP1" -o -d "$SKIP1" \) ]
     then
        echo "ldmap: Couldn't open $SKIP1, no such file or directory." 1>&2
        exit 1
     fi
  elif [ "$ARTVS" ]
  then
     for ARTV in $ARTVS
     do
        if [ ! -f "$ARTV" ]
        then
           echo "ldmap: Couldn't open $ARTV, no such file." 1>&2
           exit 1
        fi
     done
  else
     for FILE in $FILES
     do
        if [ "$FILE" != - ]
        then
           if [ ! -f "$FILE" ]
           then
              echo "ldmap: Couldn't open $FILE, no such file." 1>&2
              exit 1
           fi
        fi
     done
  fi

  [ "$S1OPT" = 2 -a -f "$SKIP1" ] && S1OPT=

  if [ "$S1OPT" -a "$SKIP1" -o "$FILES" = "" -a "$SKIP1" = "" ]
  then
     exec 1>&2
     echo "Usage: ldmap <options> <namelist>"
     echo "   Stage 1 analysis options:"
     echo "      -1               ...stop after stage 1"
     echo "      -m               ...include unresolved symbol names"
     echo "      -M               ...include all symbol names"
     echo "      -n               ...include unresolved symbols"
     echo "      -p <file>        ...preserve packed analysis"
     echo "      -P <directory>   ...preserve unpacked analysis"
     echo "      -r               ...reverse the dependency analysis"
     echo "      -v <file>        ...'ar tv' output containing size info"
     echo "   Other options:"
     echo "      -o <object>      ...map object, use unpacked if available"
     echo "      -O <object>      ...map object, use unpacked analysis"
     echo "      -s <file>        ...skip stage 1, specify packed input"
     echo "      -s <directory>   ...skip stage 1, specify unpacked input"
     echo "      -t               ...print timing information"
     echo "   Stage 1 analysis options may not be combined with -s."
     exit 1
  fi

  if [ "$OBJS" ]
  then
#    Add a .o suffix if necessary.
     TEMP=
     for OBJ in $OBJS
     do
        case $OBJ in
        *\.o)
           ;;
        *)
           OBJ="$OBJ.o"
           ;;
        esac

        TEMP="$TEMP $OBJ"
     done

     OBJS="$TEMP"
  fi


# Stage 1 analysis.
  trap 'rm -rf ldtmp[0-9].$$' 0
  trap 'echo "Cleaning up..." ; exit' 1 2 3 15

  if [ "$SKIP1" = "" ]
  then
     [ "$TIMER" ] && $TIMER 1>&2
     echo "Extracting dependencies (stage 1 analysis)..." 1>&2

     # 1) Firstly sed reformats the 'nm' output into entries of the form
     #    "symbol D|U location", with 'D' or 'U' for defined or undefined
     #    symbols, and the location of the form lib-module.o, e.g. wcs-prj.o.
     # 2) The first 'sort' gathers symbols together, putting 'D' ahead of 'U'
     #    for each.  It also removes any duplicates.
     # 3) The first awk script scans the list remembering the location of a
     #    defined symbol and associates it with each undefined occurrence that
     #    follows in the list.
     # 4) The second awk script simply appends size information gathered from
     #    'ar tv', and the final sort puts this size information into the
     #    correct sequence.
     expand $FILES |
        sed -n \
           -e '/\.o\]:$/{s/.*lib\(.*\)\.a\[\(.*\)\]:/\1-\2/;h;d;}' \
           -e '/\.o:$/{s/.* //;s/.*\///;s/:$//;h;d;}' \
           -e '/ U *$/{s/ U *$//;G;s/\n/ U /;p;d;}' \
           -e '{s/ [A-Z] .*//;G;s/\n/ D /;p;d;}' \
           -e 'd' | \
        sort -u |
        awk \
          'BEGIN {
              def = ""
              src = ""
           }
           $2 == "D" {
              # Found a defined symbol.
              if (more == 2) print $3 " " $1 " " $3
              if ($1 == def) {
                 # Multiply defined, prefer casa.
                 if (src ~ /^casa/) next
		 if ($3 !~ /^casa/) next
              }
              def = $1
              src = $3
           }
           $2 == "U" {
              # An undefined symbol.
              if ($1 == def) {
                 # It matches the previous defined symbol.
                 if (more) {
                    if (rev) {
                       print src " " $1 " " $3
                    } else {
                       print $3 " " $1 " " src
                    }
                 } else {
                    if (rev) {
                       print src " " $3
                    } else {
                       print $3 " " src
                    }
                 }
              } else {
                 # This undefined symbol cannot be resolved.
                 if (unres) print $3 " (" $1 ")"
              }
           }' more=$MORE unres=$UNRES rev=$REVERSE |
        {
           cat -
           [ "$ARTVS" ] && awk '{print $8 " " $3}' $ARTVS
        } |
        sort -u > ldtmp0.$$

  else
     [ -f "$SKIP1" ] && ln $SKIP1 ldtmp0.$$
  fi

# Preserve packed stage 1 results?
  if [ "$KEEP1P" ]
  then
     rm -f $KEEP1P
     ln ldtmp0.$$ $KEEP1P
  fi

# Stop now?
  if [ "$QUIT1" -a "$KEEP1U" = "" ]
  then
     [ "$TIMER" ] && $TIMER 1>&2
     exit 0
  fi


# Unpack stage 1 analysis?
  if [ -d "$SKIP1" ]
  then
     ln -s $SKIP1 ldtmp0.$$
     UNPACK=2
  elif [ "$UNPACK" ]
  then
#    Unpack the stage 1 analysis for greater speed.
     [ "$TIMER" ] && $TIMER 1>&2
     echo "Unpacking stage 1 analysis..." 1>&2

     [ -d ldtmp1.$$ ] || mkdir ldtmp1.$$
     awk '{print $1 " " $NF}' ldtmp0.$$ |
     {
        while read OBJ SRC
        do
           [ -f ldtmp1.$$/$OBJ ] || echo "+ $OBJ" > ldtmp1.$$/$OBJ
           echo "$SRC" >> ldtmp1.$$/$OBJ
        done
     }

     awk '{print $NF}' ldtmp0.$$ | grep "\.o$" | sort -u |
     {
        while read SRC
        do
           [ -f ldtmp1.$$/$SRC ] || echo "+ $SRC" > ldtmp1.$$/$SRC
        done
     }

     rm -f ldtmp0.$$
     mv ldtmp1.$$ ldtmp0.$$

     [ "$TIMER" ] && $TIMER 1>&2
  fi

# Preserve unpacked stage 1 results?
  if [ "$KEEP1U" ]
  then
     rm -rf $KEEP1U
     mv ldtmp0.$$ $KEEP1U
     ln -s $KEEP1U ldtmp0.$$
  fi

# Stop now?
  [ "$QUIT1" ] && exit 0


#-----------------------------------------------------------------------------
# Stage 2 analysis.
#-----------------------------------------------------------------------------
# ldtmp0 contains the stage 1 analysis, packed (file) or unpacked (directory).
# ldtmp1 lists object modules to be analysed.
# ldtmp2 lists the object modules encountered so far.
# ldtmp3 lists the sizes of the object modules encountered so far.
# ldtmp4 lists the object modules remaining to be processed.
# ldtmp5 is an accumulator for ldtmp2.
# ldtmp6 is used as a temporary.
#-----------------------------------------------------------------------------
  if [ "$OBJS" = "" ]
  then
     (cd ldtmp0.$$ && ls -1 > ../ldtmp1.$$)
  else
     echo "$OBJS" > ldtmp1.$$
     for OBJ in $OBJS
     do
        echo "$OBJ" >> ldtmp2.$$
     done

     sort -u ldtmp2.$$ > ldtmp6.$$
     mv ldtmp6.$$ ldtmp2.$$
  fi

  exec 3<ldtmp1.$$

  while read OBJ 0<&3
  do
     echo ""
     [ "$OBJS" ] || echo "$OBJ" > ldtmp2.$$

     cp /dev/null ldtmp3.$$
     cp ldtmp2.$$ ldtmp4.$$
     cp ldtmp2.$$ ldtmp5.$$

     INDENT=""
     ITER=1
     while true
     do
        if [ "$UNPACK" ]
        then
#          Use unpacked results of stage 1 analysis.
           (cd ldtmp0.$$ && cat `cat ../ldtmp4.$$`) </dev/null 2>/dev/null |
              awk \
                 'BEGIN {doprint = 0}
                  $1 == "+" {
                     if (doprint && obj) print indent obj
                     obj = $2
                     doprint = 1
                     next
                  }
                  /^[0-9][0-9]*$/ {
                     print indent obj " " $1
                     doprint = 0
                     print $1 >> ldtmp3
                     next
                  }
                  {
                     print $NF >> ldtmp5
                  }
                  END {if (doprint && obj) print indent obj}' \
                  indent="$INDENT" ldtmp3=ldtmp3.$$ ldtmp5=ldtmp5.$$
        else
#          Use packed results of stage 1 analysis.
           while read OBJ
           do
              grep "^$OBJ " ldtmp0.$$ |
                 awk \
                    '/[0-9][0-9]*$/ {print indent $1 " " $2
                                printed = 1
                                print $2 >> ldtmp3}
                    !/[0-9][0-9]*$/ {print $NF >> ldtmp5}
                    END {if (! printed) print indent obj }' \
                    obj="$OBJ" indent="$INDENT" \
                    ldtmp3=ldtmp3.$$ ldtmp5=ldtmp5.$$
           done < ldtmp4.$$
        fi

        grep -v '(.*)' ldtmp5.$$ | sort -u > ldtmp6.$$
        mv ldtmp6.$$ ldtmp5.$$

        diff ldtmp2.$$ ldtmp5.$$ |
        sed -n -e "s/^> //p" > ldtmp4.$$

        cp ldtmp5.$$ ldtmp2.$$

        [ -s "ldtmp4.$$" ] || break

        if [ "$HIER" != "" ]
        then
           [ "$ITER" -ge "$HIER" ] && break 2
           ITER=`expr $ITER + 1`
        fi

        INDENT=`echo "$INDENT   " | sed -e 's/        /	/'`
     done

     COUNT=`awk 'END {print NR}' ldtmp2.$$`
     SIZE=`awk '{size += $1} ; END {print size}' ldtmp3.$$`
     if [ "$SIZE" != "" ]
     then
        echo "Count: $COUNT   Size: $SIZE"
     else
        echo "Count: $COUNT"
     fi
  done

  exit 0
