#!/bin/sh
# Searches for symbols from libreadline which may be used in current rootfs.

set -e

find_undefs() {
  # Symbols marked with UND are obviously undefined
  # Example output:
  #   5115 1665: 000000000053d080    10 FUNC    GLOBAL DEFAULT  13 mod_path
  readelf -sDW $1 | awk '/UND/{print $9}'

  # If it's an executable, imported global variables are copy-relocated
  # and thus technically not undefined. Scan for these as well.
  # Example output:
  #   000000b75b08  040500000005 R_X86_64_COPY     0000000000b75b08 rl_line_buffer + 0
  readelf -rDW $1 | awk '/R_[^ ]*_COPY/{print $5}'
}

find_defs() {
  readelf -sDW $1 | awk '!/UND/{print $9}'
}

# Find all imported symbols in rootfs
for f in $(find /bin /sbin /usr/bin /usr/sbin /usr/lib* /lib*); do
#for f in $(find $HOME/install/binutils-gdb/bin); do
  if file $f | grep -q ELF; then
    find_undefs $f
  fi
done | sort -u > undefs.lst

ORIG=$HOME/install/readline/lib
NEW=$HOME/install/readline-patched/lib

# Find symbols exported by original readline
#( find_defs $ORIG/libhistory.so; find_defs $ORIG/libreadline.so ) | sort -u > rl_orig.lst

# Symbols from old readline which _may_ be used somewhere
comm -12 undefs.lst rl_orig.lst > rl_orig_used.lst

# Find symbols exported by new readline
#( find_defs $NEW/libhistory.so; find_defs $NEW/libreadline.so ) | sort -u > rl_new.lst

echo "Symbols which may be used and are missing in new libreadline:"
comm -23 rl_orig_used.lst rl_new.lst | tee rl_new_missing.lst

