linuxbashshellshopenbsd

Find all executable files that depend on the specified library in the specified directory


My goal is to write a shell script that uses "objdump -p" command to find all executable files that depend on the specified library in the specified directory. (OpenBSD). I try something like this:

find $1 -perm -111 -print0 | xargs -r0 objdump -p | grep -l "NEEDED      $2"

But this solution doesn't work because grep cannot figure out the filenames in which it found the given match. The difficulty is to determine the names of the executable files in which grep found the specified library. Can anyone suggest a solution using the "objdump -p" command?


Solution

  • The trick is to execute a shell script rather than a single command to be able to re-use the file name.

    finddepend() {
    # Arg 1: The directory where to find
    # Arg 2: The library name
      basedir=$1
      libname=$2
      find "$basedir" \
        \( -perm -100 -o -perm -010 -o -perm -001 \) \
        \( -type f -o -type l \) \
        -exec sh -c '
    # Arg 0: Is a dummy _ for this inline script
    # Arg 1: The executable file path
    # Arg 2: The library name
    filepath=$1
    libname=$2
    objdump -p "$filepath" 2>/dev/null |
      if grep -qF "  NEEDED               $libname"; then
        printf %s\\n "${filepath##*/}"
      fi
    ' _ {} "$libname" \;
    }
    

    Example usage:

    finddepend /bin libselinux.so
    mv
    systemctl
    tar
    sed
    udevadm
    ls
    mknod
    systemd
    mkdir
    ss
    dir
    vdir
    cp
    systemd-hwdb
    netstat