#!/bin/sh
# Ensure that d_ino (from ls -di) and st_ino (from stat --format=%i) match.

# Copyright (C) 2006 Free Software Foundation, Inc.

# 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., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.

if test "$VERBOSE" = yes; then
  set -x
  ls --version
fi

. $srcdir/../envvar-check

pwd=`pwd`
t0=`echo "$0"|sed 's,.*/,,'`.tmp; tmp=$t0/$$
trap 'status=$?; cd "$pwd" && chmod -R u+rwx $t0 && rm -rf $t0 && exit $status' 0
trap '(exit $?); exit $?' 1 2 13 15

framework_failure=0
mkdir -p $tmp || framework_failure=1
cd $tmp || framework_failure=1

if test $framework_failure = 1; then
  echo "$0: failure in testing framework" 1>&2
  (exit 1); exit 1
fi

fail=0

root_dev_ino=`stat --format=%d-%i /`
t=`pwd`
while :; do
  ls -i1 "$t" > tmp
  if test $? = 0; then
    # Extract the inode number from the first line of output from ls -i1.
    # This value comes from dirent.d_ino, on systems with d_ino support.
    d_ino=`sed -n '1s/^ *\([0-9][0-9]*\) .*/\1/p;q' tmp`

    # Extract the name of the corresponding directory entry.
    file=`sed -n '1s/^ *[0-9][0-9]*  *//p;q' tmp`

    # Get its inode number (stat.st_ino) via stat(1)'s call to lstat.
    st_ino=`stat --format=%i "$t/$file"`

    # Make sure that they are the same.
    # We know from experience that there may be mismatches on some
    # buggy file systems, at mount points.
    if test "$d_ino" != "$st_ino"; then
      echo "$0: test failed: $t/$file: d_ino($d_ino) != st_ino($st_ino)
	This may indicate a flaw in your kernel or file system implementation.
	The flaw isn't serious for coreutils, but it might break other tools,
	so you should report it to your operating system vendor." 1>&2

      # This test fails too often, and we don't want to be distracted
      # with reports, since the code that could be affected by the losing
      # behavior (pwd and getcwd) works around any mismatch.
      # So do continue to issue the warning, but don't count it as a
      # real failure.
      # fail=1
      break
    fi
  fi

  t=`(cd "$t/.."; pwd)`
  dev_ino=`stat --format=%d-%i "$t"`
  test $dev_ino = $root_dev_ino && break
done

(exit $fail); exit $fail
