1#!/bin/sh
2# ensure that ls does not stat a symlink in an unusual case
3
4# Copyright (C) 2007-2023 Free Software Foundation, Inc.
5
6# This program is free software: you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation, either version 3 of the License, or
9# (at your option) any later version.
10
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15
16# You should have received a copy of the GNU General Public License
17# along with this program.  If not, see <https://www.gnu.org/licenses/>.
18
19. "${srcdir=.}/tests/init.sh"; path_prepend_ ./src
20print_ver_ ls
21require_strace_ stat
22
23stats='stat'
24# List of other _file name_ stat functions to increase coverage.
25other_stats='statx lstat stat64 lstat64 newfstatat fstatat64'
26for stat in $other_stats; do
27  strace -qe "$stat" true > /dev/null 2>&1 &&
28    stats="$stats,$stat"
29done
30
31# The system may perform additional stat-like calls before main.
32# Furthermore, underlying library functions may also implicitly
33# add an extra stat call, e.g. opendir since glibc-2.21-360-g46f894d.
34# To avoid counting those, first get a baseline count for running
35# ls with one empty directory argument.  Then, compare that with the
36# invocation under test.
37count_stats() { grep -vE '\+\+\+|ENOSYS|NOTSUP' "$1" | wc -l; }
38mkdir d || framework_failure_
39strace -q -o log1 -e $stats ls -F --color=always d || fail=1
40n_stat1=$(count_stats log1) || framework_failure_
41
42test $n_stat1 = 0 \
43  && skip_ 'No stat calls recognized on this platform'
44
45
46touch x || framework_failure_
47chmod a+x x || framework_failure_
48ln -s x link-to-x || framework_failure_
49
50
51# ls from coreutils 6.9 would unnecessarily stat a symlink in an unusual case:
52# When not coloring orphan and missing entries, and without ln=target,
53# ensure that ls -F (or -d, or -l: i.e., when not dereferencing)
54# does not stat a symlink to directory, and does still color that
55# symlink and an executable file properly.
56
57LS_COLORS='or=0:mi=0:ex=01;32:ln=01;35' \
58  strace -qe $stats -o log2 ls -F --color=always x link-to-x > out.tmp || fail=1
59n_stat2=$(count_stats log2) || framework_failure_
60
61# Expect one more stat call,
62# which failed with coreutils 6.9 and earlier, which had 2.
63test $n_stat1 = $(($n_stat2 - 1)) \
64  || { fail=1; head -n30 log*; }
65
66# Check that output is colored, as requested, too.
67{
68  printf '\033[0m\033[01;35mlink-to-x\033[0m@\n'
69  printf '\033[01;32mx\033[0m*\n'
70} > exp || fail=1
71# Elide info messages strace can send to stdout of the form:
72#   [ Process PID=1234 runs in 32 bit mode. ]
73sed '/Process PID=/d' out.tmp > out
74compare exp out || fail=1
75
76Exit $fail
77