4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
6 * All rights reserved. This program and the accompanying materials
7 * are made available under the terms of the GNU Lesser General Public License
8 * (LGPL) version 2.1 or (at your discretion) any later version.
9 * (LGPL) version 2.1 accompanies this distribution, and is available at
10 * http://www.gnu.org/licenses/lgpl-2.1.html
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
20 * Copyright (c) 2019, DDN Storage Corporation.
23 * This file is part of Lustre, http://www.lustre.org/
27 * Test for Lustre statx().
28 * It uses some code in coreutils ('ls.c' and 'stat.c') for reference.
30 * Author: Qian Yingjin <qian@ddn.com>
32 #define _ATFILE_SOURCE
46 #include <sys/syscall.h>
47 #include <sys/types.h>
48 #include <sys/param.h>
49 #include <sys/sysmacros.h>
53 #include <libiberty.h>
54 #include <linux/lustre/lustre_user.h>
57 #include <selinux/selinux.h>
60 /* Factor out some of the common --help and --version processing code. */
62 /* These enum values cannot possibly conflict with the option values
63 * ordinarily used by commands, including CHAR_MAX + 1, etc. Avoid
64 * CHAR_MIN - 1, as it may equal -1, the getopt end-of-options value.
67 PRINTF_OPTION = (CHAR_MAX + 1),
68 GETOPT_HELP_CHAR = (CHAR_MIN - 2),
69 GETOPT_VERSION_CHAR = (CHAR_MIN - 3)
77 #define AT_STATX_SYNC_TYPE 0x6000
78 #define AT_STATX_FORCE_SYNC 0x2000
79 #define AT_STATX_DONT_SYNC 0x4000
81 static __attribute__((unused))
82 ssize_t statx(int dfd, const char *filename, int flags,
83 unsigned int mask, struct statx *buffer)
85 return syscall(__NR_statx, dfd, filename, flags, mask, buffer);
87 #endif /* HAVE_STATX */
89 /* coreutils/lib/intprops.h */
90 #define _GL_SIGNED_TYPE_OR_EXPR(t) TYPE_SIGNED(__typeof__(t))
92 /* Bound on length of the string representing an unsigned integer
93 * value representable in B bits. log10 (2.0) < 146/485. The
94 * smallest value of B where this bound is not tight is 2621.
96 #define INT_BITS_STRLEN_BOUND(b) (((b) * 146 + 484) / 485)
98 /* The width in bits of the integer type or expression T.
100 * Padding bits are not supported; this is checked at compile-time below.
102 #define TYPE_WIDTH(t) (sizeof(t) * CHAR_BIT)
104 /* Bound on length of the string representing an integer type or expression T.
105 * Subtract 1 for the sign bit if T is signed, and then add 1 more for
106 * a minus sign if needed.
108 * Because _GL_SIGNED_TYPE_OR_EXPR sometimes returns 1 when its argument is
109 * unsigned, this macro may overestimate the true bound by one byte when
110 * applied to unsigned types of size 2, 4, 16, ... bytes.
112 #define INT_STRLEN_BOUND(t) \
113 (INT_BITS_STRLEN_BOUND(TYPE_WIDTH(t) - _GL_SIGNED_TYPE_OR_EXPR(t)) \
114 + _GL_SIGNED_TYPE_OR_EXPR(t))
116 /* Bound on buffer size needed to represent an integer type or expression T,
117 * including the terminating null.
119 #define INT_BUFSIZE_BOUND(t) (INT_STRLEN_BOUND(t) + 1)
121 /* The maximum and minimum values for the integer type T. */
122 #define TYPE_MINIMUM(t) ((t)~TYPE_MAXIMUM(t))
123 #define TYPE_MAXIMUM(t) \
124 ((t) (!TYPE_SIGNED(t) \
126 : ((((t)1 << (TYPE_WIDTH(t) - 2)) - 1) * 2 + 1)))
128 static bool o_dir_list;
129 static bool long_format; /* use a long listing format */
131 /* Current time in seconds and nanoseconds since 1970, updated as
132 * needed when deciding whether a file is recent.
134 static struct timespec current_time;
136 /* FIXME: these are used by printf.c, too */
137 #define isodigit(c) ('0' <= (c) && (c) <= '7')
138 #define octtobin(c) ((c) - '0')
139 #define hextobin(c) ((c) >= 'a' && (c) <= 'f' ? (c) - 'a' + 10 : \
140 (c) >= 'A' && (c) <= 'F' ? (c) - 'A' + 10 : (c) - '0')
142 #define ISDIGIT(c) ((unsigned int)(c) - '0' <= 9)
144 /* True if the real type T is signed. */
145 #define TYPE_SIGNED(t) (!((t)0 < (t)-1))
147 static char const digits[] = "0123456789";
149 /* Flags that are portable for use in printf, for at least one
150 * conversion specifier; make_format removes unportable flags as
151 * needed for particular specifiers. The glibc 2.2 extension "I" is
152 * listed here; it is removed by make_format because it has undefined
153 * behavior elsewhere and because it is incompatible with
156 static char const printf_flags[] = "'-+ #0I";
158 /* Formats for the --terse option. */
159 static char const fmt_terse_fs[] = "%n %i %l %t %s %S %b %f %a %c %d\n";
160 static char const fmt_terse_regular[] = "%n %s %b %f %u %g %D %i %h %t %T"
162 static char const fmt_terse_selinux[] = "%n %s %b %f %u %g %D %i %h %t %T"
163 " %X %Y %Z %W %o %C\n";
167 /* Whether to follow symbolic links; True for --dereference (-L). */
168 static bool follow_links;
170 /* Whether to interpret backslash-escape sequences.
171 * True for --printf=FMT, not for --format=FMT (-c).
173 static bool interpret_backslash_escapes;
175 /* The trailing delimiter string:
176 * "" for --printf=FMT, "\n" for --format=FMT (-c).
178 static char const *trailing_delim = "";
180 /* The representation of the decimal point in the current locale. */
181 static char const *decimal_point;
182 static size_t decimal_point_len;
184 /* Convert a possibly-signed character to an unsigned character. This is
185 * a bit safer than casting to unsigned char, since it catches some type
186 * errors that the cast doesn't.
188 static inline unsigned char to_uchar(char ch)
193 void usage(char *prog)
195 printf("Usage: %s [options] <FILE>...\n", prog);
196 printf("Display file status via statx() syscall.\n"
197 "List information about the FILE "
198 "(the current diretory by default) via statx() syscall.\n"
200 "\t-L --dereference follow links\n"
201 "\t--cached=MODE specify how to use cached attributes;\n"
202 "\t See MODE below\n"
203 "\t-c --format=FORMAT use the specified FORMAT instead of the "
205 "\t output a newline after each use of "
207 "\t-t, --terse print the information in terse form\n"
208 "\t-D --dir list information about the FILE (ls)\n"
209 "\t-l use a long listing format\n"
210 "\t-q --quiet do not display results, test only\n\n"
211 "The --cached MODE argument can be; always, never, or default.\n"
212 "`always` will use cached attributes if available, while\n"
213 "`never` will try to synchronize with the latest attributes,\n"
214 "and `default` will leave it up to the underlying file system.\n"
216 "The valid format sequences for files (without --file-system):\n"
218 "\t%%a access rights in octal (note '#' and '0' printf flags)\n"
219 "\t%%A access rights in human readable form\n"
220 "\t%%b number of blocks allocated (see %%B)\n"
221 "\t%%B the size in bytes of each block reported by %%b\n"
222 "\t%%C SELinux security context string\n"
223 "\t%%d device number in decimal\n"
224 "\t%%D device number in hex\n"
225 "\t%%f raw mode in hex\n"
227 "\t%%g group ID of owner\n"
228 "\t%%G group name of owner\n"
229 "\t%%h number of hard links\n"
230 "\t%%i inode number\n"
231 "\t%%m mount point\n"
233 "\t%%N quoted file name with dereference if symbolic link\n"
234 "\t%%o optimal I/O transfer size hint\n"
235 "\t%%p Mask to show what's supported in stx_attributes\n"
236 "\t%%r Flags conveying information about the file: "
238 "\t%%s total size, in bytes\n"
239 "\t%%t major device type in hex, for character/block device "
241 "\t%%T minor device type in hex, for character/block device "
243 "\t%%u user ID of owner\n"
244 "\t%%U user name of owner\n"
245 "\t%%w time of file birth, human-readable; - if unknown\n"
246 "\t%%W time of file birth, seconds since Epoch; 0 if unknown\n"
247 "\t%%x time of last access, human-readable\n"
248 "\t%%X time of last access, seconds since Epoch\n"
249 "\t%%y time of last data modification, human-readable\n"
250 "\t%%Y time of last data modification, seconds since Epoch\n"
251 "\t%%z time of last status change, human-readable\n"
252 "\t%%Z time of last status change, seconds since Epoch\n");
256 /* gnulib/lib/filemode.c */
257 /* Return a character indicating the type of file described by
260 * 'b' block special file
261 * 'c' character special file
262 * 'C' high performance ("contiguous data") file
266 * 'm' multiplexed file (7th edition Unix; obsolete)
267 * 'n' network special file (HP-UX)
268 * 'p' fifo (named pipe)
271 * 'w' whiteout (4.4BSD)
272 * '?' some other file type
274 static char ftypelet(mode_t bits)
276 /* These are the most common, so test for them first.*/
282 /* Other letters standardized by POSIX 1003.1-2004.*/
292 /* Other file types (though not letters) standardized by POSIX.*/
299 /* Like filemodestring, but rely only on MODE.*/
300 static void strmode(mode_t mode, char *str)
302 str[0] = ftypelet(mode);
303 str[1] = mode & S_IRUSR ? 'r' : '-';
304 str[2] = mode & S_IWUSR ? 'w' : '-';
305 str[3] = (mode & S_ISUID
306 ? (mode & S_IXUSR ? 's' : 'S')
307 : (mode & S_IXUSR ? 'x' : '-'));
308 str[4] = mode & S_IRGRP ? 'r' : '-';
309 str[5] = mode & S_IWGRP ? 'w' : '-';
310 str[6] = (mode & S_ISGID
311 ? (mode & S_IXGRP ? 's' : 'S')
312 : (mode & S_IXGRP ? 'x' : '-'));
313 str[7] = mode & S_IROTH ? 'r' : '-';
314 str[8] = mode & S_IWOTH ? 'w' : '-';
315 str[9] = (mode & S_ISVTX
316 ? (mode & S_IXOTH ? 't' : 'T')
317 : (mode & S_IXOTH ? 'x' : '-'));
322 /* filemodestring - fill in string STR with an ls-style ASCII
323 * representation of the st_mode field of file stats block STATP.
324 * 12 characters are stored in STR.
325 * The characters stored in STR are:
327 * 0 File type, as in ftypelet above, except that other letters are used
328 * for files whose type cannot be determined solely from st_mode:
331 * 'M' migrated file (Cray DMF)
333 * 'S' shared memory object
334 * 'T' typed memory object
336 * 1 'r' if the owner may read, '-' otherwise.
338 * 2 'w' if the owner may write, '-' otherwise.
340 * 3 'x' if the owner may execute, 's' if the file is
341 * set-user-id, '-' otherwise.
342 * 'S' if the file is set-user-id, but the execute
345 * 4 'r' if group members may read, '-' otherwise.
347 * 5 'w' if group members may write, '-' otherwise.
349 * 6 'x' if group members may execute, 's' if the file is
350 * set-group-id, '-' otherwise.
351 * 'S' if it is set-group-id but not executable.
353 * 7 'r' if any user may read, '-' otherwise.
355 * 8 'w' if any user may write, '-' otherwise.
357 * 9 'x' if any user may execute, 't' if the file is "sticky"
358 * (will be retained in swap space after execution), '-'
360 * 'T' if the file is sticky but not executable.
362 * 10 ' ' for compatibility with 4.4BSD strmode,
363 * since this interface does not support ACLs.
367 static void filemodestring(struct statx const *stxp, char *str)
369 strmode(stxp->stx_mode, str);
372 if (S_TYPEISSEM(statp))
374 else if (IS_MIGRATED_FILE (statp))
376 else if (S_TYPEISMQ (statp))
378 else if (S_TYPEISSHM (statp))
380 else if (S_TYPEISTMO (statp))
385 /* gnulib/lib/file-type.c */
386 static char const *file_type(struct statx const *stx)
388 /* See POSIX 1003.1-2001 XCU Table 4-8 lines 17093-17107 for some of
391 * To keep diagnostics grammatical in English, the returned string
392 * must start with a consonant.
394 /* Do these three first, as they're the most common. */
395 if (S_ISREG(stx->stx_mode))
396 return stx->stx_size == 0 ? "regular empty file" :
399 if (S_ISDIR(stx->stx_mode))
402 if (S_ISLNK(stx->stx_mode))
403 return "symbolic link";
405 /* The remaining are in alphabetical order. */
406 if (S_ISBLK(stx->stx_mode))
407 return "block special file";
409 if (S_ISCHR(stx->stx_mode))
410 return "character special file";
412 if (S_ISFIFO(stx->stx_mode))
415 if (S_ISSOCK(stx->stx_mode))
421 /* gnulib/lib/areadlink-with-size.c */
422 /* SYMLINK_MAX is used only for an initial memory-allocation sanity
423 * check, so it's OK to guess too small on hosts where there is no
424 * arbitrary limit to symbolic link length.
427 #define SYMLINK_MAX 1024
430 #define MAXSIZE (SIZE_MAX < SSIZE_MAX ? SIZE_MAX : SSIZE_MAX)
432 /* Call readlink to get the symbolic link value of FILE.
433 * SIZE is a hint as to how long the link is expected to be;
434 * typically it is taken from st_size. It need not be correct.
435 * Return a pointer to that NUL-terminated string in malloc'd storage.
436 * If readlink fails, malloc fails, or if the link value is longer
437 * than SSIZE_MAX, return NULL (caller may use errno to diagnose).
439 static char *areadlink_with_size(char const *file, size_t size)
441 /* Some buggy file systems report garbage in st_size. Defend
442 * against them by ignoring outlandish st_size values in the initial
445 size_t symlink_max = SYMLINK_MAX;
446 size_t INITIAL_LIMIT_BOUND = 8 * 1024;
447 size_t initial_limit = (symlink_max < INITIAL_LIMIT_BOUND ?
448 symlink_max + 1 : INITIAL_LIMIT_BOUND);
449 enum { stackbuf_size = 128 };
450 /* The initial buffer size for the link value. */
451 size_t buf_size = (size == 0 ? stackbuf_size : size < initial_limit ?
452 size + 1 : initial_limit);
457 char stackbuf[stackbuf_size];
458 char *buf = stackbuf;
461 if (!(size == 0 && buf_size == stackbuf_size)) {
462 buf = buffer = malloc(buf_size);
467 r = readlink(file, buf, buf_size);
470 /* On AIX 5L v5.3 and HP-UX 11i v2 04/09, readlink returns -1
471 * with errno == ERANGE if the buffer is too small.
473 if (r < 0 && errno != ERANGE) {
474 int saved_errno = errno;
481 if (link_length < buf_size) {
482 buf[link_length] = 0;
484 buffer = malloc(link_length + 1);
486 return memcpy(buffer, buf,
488 } else if (link_length + 1 < buf_size) {
489 /* Shrink BUFFER before returning it. */
490 char *shrinked_buffer;
492 shrinked_buffer = realloc(buffer,
494 if (shrinked_buffer != NULL)
495 buffer = shrinked_buffer;
501 if (buf_size <= MAXSIZE / 2) {
503 } else if (buf_size < MAXSIZE) {
512 /* coreutils/src/stat.c */
513 /* Output a single-character \ escape. */
514 static void print_esc_char(char c)
517 case 'a': /* Alert. */
520 case 'b': /* Backspace. */
523 case 'e': /* Escape. */
526 case 'f': /* Form feed. */
529 case 'n': /* New line. */
532 case 'r': /* Carriage return. */
535 case 't': /* Horizontal tab. */
538 case 'v': /* Vertical tab. */
545 printf("warning: unrecognized escape '\\%c'", c);
551 static size_t format_code_offset(char const *directive)
553 size_t len = strspn(directive + 1, printf_flags);
554 char const *fmt_char = directive + len + 1;
556 fmt_char += strspn(fmt_char, digits);
557 if (*fmt_char == '.')
558 fmt_char += 1 + strspn(fmt_char + 1, digits);
560 return fmt_char - directive;
563 static unsigned int fmt_to_mask(char fmt)
577 return STATX_MODE|STATX_TYPE;
589 return STATX_MODE|STATX_INO;
613 static unsigned int format_to_mask(char const *format)
615 unsigned int mask = 0;
618 for (b = format; *b; b++) {
622 b += format_code_offset(b);
625 mask |= fmt_to_mask(*b);
631 static char *human_access(struct statx const *stxbuf)
633 static char modebuf[12];
635 filemodestring(stxbuf, modebuf);
640 static inline struct timespec
641 statx_timestamp_to_timespec(struct statx_timestamp tsx)
645 ts.tv_sec = tsx.tv_sec;
646 ts.tv_nsec = tsx.tv_nsec;
651 static int timespec_cmp(struct timespec a, struct timespec b)
653 if (a.tv_sec < b.tv_sec)
655 if (a.tv_sec > b.tv_sec)
658 return a.tv_nsec - b.tv_nsec;
661 static char *human_time(const struct statx_timestamp *ts)
663 /* STR must be at least INT_BUFSIZE_BOUND (intmax_t) big, either
664 * because localtime_rz fails, or because the time zone is truly
665 * outlandish so that %z expands to a long string.
667 static char str[INT_BUFSIZE_BOUND(intmax_t)
668 + INT_STRLEN_BOUND(int) /* YYYY */
669 + 1 /* because YYYY might equal INT_MAX + 1900 */
670 + sizeof "-MM-DD HH:MM:SS.NNNNNNNNN +"];
677 if (!localtime_r(&tim, &tm)) {
678 perror("localtime_r");
682 if (o_dir_list && long_format) {
683 struct timespec when_timespec;
684 struct timespec six_months_ago;
687 when_timespec = statx_timestamp_to_timespec(*ts);
688 /* If the file appears to be in the future, update the current
689 * time, in case the file happens to have been modified since
690 * the last time we checked the clock.
692 if (timespec_cmp(current_time, when_timespec) < 0) {
695 gettimeofday(&tv, NULL);
696 current_time.tv_sec = tv.tv_sec;
697 current_time.tv_nsec = tv.tv_usec * 1000;
700 /* Consider a time to be recent if it is within the past six
702 * A Gregorian year has 365.2425 * 24 * 60 * 60 == 31556952
703 * seconds on the average. Write this value as an integer
704 * constant to avoid floating point hassles.
706 six_months_ago.tv_sec = current_time.tv_sec - 31556952 / 2;
707 six_months_ago.tv_nsec = current_time.tv_nsec;
709 recent = (timespec_cmp(six_months_ago, when_timespec) < 0 &&
710 (timespec_cmp(when_timespec, current_time) < 0));
712 /* We assume here that all time zones are offset from UTC by a
713 * whole number of seconds.
715 len = strftime(str, sizeof(str),
716 recent ? "%b %e %H:%M" : "%b %e %Y", &tm);
725 len = strftime(str, sizeof(str), "%Y-%m-%d %H:%M:%S", &tm);
731 len2 = snprintf(str + len, sizeof(str) - len, ".%09u ", ts->tv_nsec);
732 len = strftime(str + len + len2, sizeof(str) - len - len2, "%z", &tm);
741 /* PFORMAT points to a '%' followed by a prefix of a format, all of
742 * size PREFIX_LEN. The flags allowed for this format are
743 * ALLOWED_FLAGS; remove other printf flags from the prefix, then
746 static void make_format(char *pformat, size_t prefix_len,
747 char const *allowed_flags, char const *suffix)
749 char *dst = pformat + 1;
751 char const *srclim = pformat + prefix_len;
753 for (src = dst; src < srclim && strchr(printf_flags, *src); src++)
754 if (strchr(allowed_flags, *src))
761 static void out_string(char *pformat, size_t prefix_len, char const *arg)
763 make_format(pformat, prefix_len, "-", "s");
764 printf(pformat, arg);
767 static int out_int(char *pformat, size_t prefix_len, intmax_t arg)
769 make_format(pformat, prefix_len, "'-+ 0", PRIdMAX);
770 return printf(pformat, arg);
773 static int out_uint(char *pformat, size_t prefix_len, uintmax_t arg)
775 make_format(pformat, prefix_len, "'-0", PRIuMAX);
776 return printf(pformat, arg);
779 static void out_uint_o(char *pformat, size_t prefix_len, uintmax_t arg)
781 make_format(pformat, prefix_len, "-#0", PRIoMAX);
782 printf(pformat, arg);
785 static void out_uint_x(char *pformat, size_t prefix_len, uintmax_t arg)
787 make_format(pformat, prefix_len, "-#0", PRIxMAX);
788 printf(pformat, arg);
791 static int out_minus_zero(char *pformat, size_t prefix_len)
793 make_format(pformat, prefix_len, "'-+ 0", ".0f");
794 return printf(pformat, -0.25);
797 /* Output the number of seconds since the Epoch, using a format that
798 * acts like printf's %f format.
800 static void out_epoch_sec(char *pformat, size_t prefix_len,
803 char *dot = memchr(pformat, '.', prefix_len);
804 size_t sec_prefix_len = prefix_len;
807 bool frac_left_adjust = false;
810 sec_prefix_len = dot - pformat;
811 pformat[prefix_len] = '\0';
813 if (ISDIGIT(dot[1])) {
814 long int lprec = strtol(dot + 1, NULL, 10);
816 precision = (lprec <= INT_MAX ? lprec : INT_MAX);
821 if (precision && ISDIGIT(dot[-1])) {
822 /* If a nontrivial width is given, subtract the width
823 * of the decimal point and PRECISION digits that will
832 while (ISDIGIT(p[-1]));
834 long int lwidth = strtol(p, NULL, 10);
836 width = (lwidth <= INT_MAX ? lwidth : INT_MAX);
839 sec_prefix_len = p - pformat;
841 int w_d = (decimal_point_len < width ?
842 width - decimal_point_len : 0);
845 int w = w_d - precision;
849 char const *src = dst;
850 for (; src < p; src++) {
852 frac_left_adjust = true;
858 + (frac_left_adjust ? 0 : sprintf(dst, "%d", w)));
868 for (i = precision; i < 9; i++)
871 int frac_sec = arg.tv_nsec / divisor;
875 if (TYPE_SIGNED(time_t)) {
876 bool minus_zero = false;
878 if (arg.tv_sec < 0 && arg.tv_nsec != 0) {
879 int frac_sec_modulus = 1000000000 / divisor;
881 frac_sec = (frac_sec_modulus - frac_sec
882 - (arg.tv_nsec % divisor != 0));
883 arg.tv_sec += (frac_sec != 0);
884 minus_zero = (arg.tv_sec == 0);
886 int_len = (minus_zero ?
887 out_minus_zero(pformat, sec_prefix_len) :
888 out_int(pformat, sec_prefix_len, arg.tv_sec));
890 int_len = out_uint(pformat, sec_prefix_len, arg.tv_sec);
894 int prec = (precision < 9 ? precision : 9);
895 int trailing_prec = precision - prec;
896 int ilen = (int_len < 0 ? 0 : int_len);
897 int trailing_width = (ilen < width &&
898 decimal_point_len < width - ilen ?
899 width - ilen - decimal_point_len - prec :
902 printf("%s%.*d%-*.*d", decimal_point, prec, frac_sec,
903 trailing_width, trailing_prec, 0);
907 /* Print the context information of FILENAME, and return true iff the
908 * context could not be obtained.
910 static int out_file_context(char *pformat, size_t prefix_len,
911 char const *filename)
913 char *scontext = NULL;
917 if ((follow_links ? getfilecon(filename, &scontext) :
918 lgetfilecon(filename, &scontext)) < 0) {
919 printf("failed to get security context of %s: %s\n",
920 filename, strerror(errno));
926 strcpy(pformat + prefix_len, "s");
927 printf(pformat, (scontext ? scontext : "?"));
933 /* Map a TS with negative TS.tv_nsec to {0,0}. */
934 static inline struct timespec neg_to_zero(struct timespec ts)
936 if (ts.tv_nsec >= 0) {
939 struct timespec z = {0, 0};
945 /* All the mode bits that can be affected by chmod. */
946 #define CHMOD_MODE_BITS \
947 (S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
949 /* Print statx info. Return zero upon success, nonzero upon failure. */
950 static int print_statx(char *pformat, size_t prefix_len, unsigned int m,
951 int fd, char const *filename, struct statx const *stx)
953 struct passwd *pw_ent;
954 struct group *gw_ent;
960 out_string(pformat, prefix_len,
961 o_dir_list ? strrchr(filename, '/') + 1 : filename);
964 out_string(pformat, prefix_len,
965 o_dir_list ? strrchr(filename, '/') + 1 : filename);
966 if (S_ISLNK(stx->stx_mode)) {
969 linkname = areadlink_with_size(filename, stx->stx_size);
970 if (linkname == NULL) {
971 printf("cannot read symbolic link %s: %s",
972 filename, strerror(errno));
976 out_string(pformat, prefix_len, linkname);
981 out_uint(pformat, prefix_len, makedev(stx->stx_dev_major,
982 stx->stx_dev_minor));
985 out_uint_x(pformat, prefix_len, makedev(stx->stx_dev_major,
986 stx->stx_dev_minor));
989 out_uint(pformat, prefix_len, stx->stx_ino);
992 out_uint_o(pformat, prefix_len,
993 stx->stx_mode & CHMOD_MODE_BITS);
996 out_string(pformat, prefix_len, human_access(stx));
999 out_uint_x(pformat, prefix_len, stx->stx_mode);
1002 out_string(pformat, prefix_len, file_type(stx));
1005 out_uint(pformat, prefix_len, stx->stx_nlink);
1008 out_uint(pformat, prefix_len, stx->stx_uid);
1011 pw_ent = getpwuid(stx->stx_uid);
1012 out_string(pformat, prefix_len,
1013 pw_ent ? pw_ent->pw_name : "UNKNOWN");
1016 out_uint(pformat, prefix_len, stx->stx_gid);
1019 gw_ent = getgrgid(stx->stx_gid);
1020 out_string(pformat, prefix_len,
1021 gw_ent ? gw_ent->gr_name : "UNKNOWN");
1025 * fail |= out_mount_point(filename, pformat, prefix_len,
1032 out_int(pformat, prefix_len, stx->stx_size);
1035 out_uint_x(pformat, prefix_len,
1036 major(makedev(stx->stx_rdev_major,
1037 stx->stx_rdev_minor)));
1040 out_uint_x(pformat, prefix_len,
1041 minor(makedev(stx->stx_rdev_major,
1042 stx->stx_rdev_minor)));
1045 out_uint(pformat, prefix_len, S_BLKSIZE);
1048 out_uint(pformat, prefix_len, stx->stx_blocks);
1051 out_uint(pformat, prefix_len, stx->stx_blksize);
1054 out_uint_x(pformat, prefix_len, stx->stx_attributes_mask);
1057 out_uint_x(pformat, prefix_len, stx->stx_attributes);
1060 if (stx->stx_btime.tv_nsec < 0)
1061 out_string(pformat, prefix_len, "-");
1063 out_string(pformat, prefix_len,
1064 human_time(&stx->stx_btime));
1067 out_epoch_sec(pformat, prefix_len,
1068 neg_to_zero(statx_timestamp_to_timespec(
1072 out_string(pformat, prefix_len,
1073 human_time(&stx->stx_atime));
1076 out_epoch_sec(pformat, prefix_len,
1077 neg_to_zero(statx_timestamp_to_timespec(
1081 out_string(pformat, prefix_len,
1082 human_time(&stx->stx_mtime));
1085 out_epoch_sec(pformat, prefix_len,
1086 neg_to_zero(statx_timestamp_to_timespec(
1090 out_string(pformat, prefix_len,
1091 human_time(&stx->stx_ctime));
1094 out_epoch_sec(pformat, prefix_len,
1095 neg_to_zero(statx_timestamp_to_timespec(
1099 ret = out_file_context(pformat, prefix_len, filename);
1111 static int print_it(int fd, char const *filename,
1112 int (*print_func)(char *, size_t, unsigned int,
1113 int, char const *, struct statx const *),
1116 /* Add 2 to accommodate our conversion of the stat '%s' format string
1117 * to the longer printf '%llu' one.
1120 MAX_ADDITIONAL_BYTES = (MAX(sizeof(PRIdMAX),
1121 MAX(sizeof(PRIoMAX),
1122 MAX(sizeof(PRIuMAX),
1123 sizeof(PRIxMAX)))) - 1)
1133 n_alloc = strlen(format) + MAX_ADDITIONAL_BYTES + 1;
1134 dest = malloc(n_alloc);
1138 for (b = format; *b; b++) {
1141 size_t len = format_code_offset(b);
1142 char const *fmt_char = b + len;
1145 memcpy(dest, b, len);
1148 switch (*fmt_char) {
1153 dest[len] = *fmt_char;
1154 dest[len + 1] = '\0';
1155 printf("%s: invalid directive", dest);
1161 ret = print_func(dest, len, to_uchar(*fmt_char),
1162 fd, filename, data);
1170 if (!interpret_backslash_escapes) {
1176 int esc_value = octtobin(*b);
1177 int esc_length = 1; /* number of octal digits */
1179 for (++b; esc_length < 3 && isodigit(*b);
1180 ++esc_length, ++b) {
1181 esc_value = esc_value * 8 +
1186 } else if (*b == 'x' && isxdigit(to_uchar(b[1]))) {
1187 /* Value of \xhh escape. */
1188 int esc_value = hextobin(b[1]);
1189 /* A hexadecimal \xhh escape sequence must have
1190 * 1 or 2 hex. digits.
1194 if (isxdigit(to_uchar(b[1]))) {
1196 esc_value = esc_value * 16 +
1200 } else if (*b == '\0') {
1201 printf("warning: backslash at end of format");
1203 /* Arrange to exit the loop. */
1217 fputs(trailing_delim, stdout);
1222 /* Return an allocated format string in static storage that
1223 * corresponds to whether FS and TERSE options were declared.
1225 static char *default_format(bool fs, bool terse, bool device)
1231 format = xstrdup(fmt_terse_fs);
1233 /* TRANSLATORS: This string uses format specifiers from
1234 * 'stat --help' with --file-system, and NOT from
1239 " ID: %-8i Namelen: %-7l Type: %T\n"
1240 "Block size: %-10s Fundamental block size: %S\n"
1241 "Blocks: Total: %-10b Free: %-10f Available: %a\n"
1242 "Inodes: Total: %-10c Free: %d\n");
1247 if (is_selinux_enabled() > 0)
1248 format = xstrdup(fmt_terse_selinux);
1251 format = xstrdup(fmt_terse_regular);
1255 /* TRANSLATORS: This string uses format specifiers from
1256 * 'stat --help' without --file-system, and NOT from
1261 Size: %-10s\tBlocks: %-10b IO Block: %-6o %F\n\
1266 /* TRANSLATORS: This string uses format
1267 * specifiers from 'stat --help' without
1268 * --file-system, and NOT from printf.
1270 format = xasprintf("%s%s", format, "\
1271 " "Device: %Dh/%dd\tInode: %-10i Links: %-5h Device type: %t,%T\n\
1274 /* TRANSLATORS: This string uses format
1275 * specifiers from 'stat --help' without
1276 * --file-system, and NOT from printf.
1278 format = xasprintf("%s%s", format, "\
1279 " "Device: %Dh/%dd\tInode: %-10i Links: %h\n\
1285 /* TRANSLATORS: This string uses format specifiers from
1286 * 'stat --help' without --file-system, and NOT from
1289 format = xasprintf("%s%s", format, "\
1290 " "Access: (%04a/%10.10A) Uid: (%5u/%8U) Gid: (%5g/%8G)\n\
1294 if (is_selinux_enabled() > 0) {
1296 /* TRANSLATORS: This string uses format
1297 * specifiers from 'stat --help' without
1298 * --file-system, and NOT from printf.
1300 format = xasprintf("%s%s", format,
1306 /* TRANSLATORS: This string uses format specifiers from
1307 * 'stat --help' without --file-system, and NOT from
1310 format = xasprintf("%s%s", format,
1321 static char *list_long_format(void)
1326 " "%10.10A %h %8U %8G %-10s %y %N\
1332 static int do_statx(char const *filename, unsigned int request_mask, int flags)
1334 const char *pathname = filename;
1335 struct statx stx = { 0, };
1338 if (strcmp(filename, "-") == 0)
1343 if (fd != AT_FDCWD) {
1345 flags |= AT_EMPTY_PATH;
1348 fd = statx(fd, pathname, flags, request_mask, &stx);
1350 if (flags & AT_EMPTY_PATH)
1351 printf("cannot stat standard input\n");
1353 printf("cannot statx %s: %s\n",
1354 filename, strerror(errno));
1359 return print_it(fd, filename, print_statx, &stx);
1362 /* Return true if FILE should be ignored. */
1363 static bool file_ignored(char const *name)
1365 return name[0] == '.';
1368 static int do_dir_list(char const *dirname, unsigned int request_mask,
1373 char fullname[PATH_MAX];
1376 dir = opendir(dirname);
1379 printf("lsx: cannot open directory '%s': %s\n",
1380 dirname, strerror(errno));
1384 while ((ent = readdir(dir)) != NULL) {
1387 /* skip "." and ".." */
1388 if (file_ignored(ent->d_name))
1396 printf("%s", ent->d_name);
1399 if (strlen(ent->d_name) + strlen(dirname) + 1 >=
1401 errno = ENAMETOOLONG;
1403 "lsx: ignored too long path: %s/%s\n",
1404 dirname, ent->d_name);
1409 snprintf(fullname, PATH_MAX, "%s/%s",
1410 dirname, ent->d_name);
1411 ret = do_statx(fullname, request_mask, flags);
1423 int main(int argc, char **argv)
1425 static struct option options[] = {
1426 {"dereference", no_argument, NULL, 'L'},
1427 {"format", required_argument, NULL, 'c'},
1428 {"printf", required_argument, NULL, PRINTF_OPTION},
1429 {"terse", no_argument, NULL, 't'},
1430 {"cached", required_argument, NULL, 0},
1431 {"dir", no_argument, NULL, 'D'},
1432 {"long-format", no_argument, NULL, 'l'},
1433 {"quiet", no_argument, NULL, 'q'},
1434 {"help", no_argument, NULL, GETOPT_HELP_CHAR},
1435 {"version", no_argument, NULL, GETOPT_VERSION_CHAR},
1439 unsigned int request_mask;
1440 int flags = AT_SYMLINK_NOFOLLOW;
1441 struct lconv const *locale = localeconv();
1446 decimal_point = locale->decimal_point[0] ? locale->decimal_point : ".";
1447 decimal_point_len = strlen(decimal_point);
1448 current_time.tv_sec = TYPE_MINIMUM(time_t);
1449 current_time.tv_nsec = -1;
1451 while ((c = getopt_long(argc, argv, "c:DqLlt", options, NULL)) != EOF) {
1454 flags &= ~AT_SYMLINK_NOFOLLOW;
1455 follow_links = true;
1459 interpret_backslash_escapes = true;
1460 trailing_delim = "";
1464 interpret_backslash_escapes = false;
1465 trailing_delim = "\n";
1481 if (strcmp(optarg, "never") == 0) {
1482 flags &= ~AT_STATX_SYNC_TYPE;
1483 flags |= AT_STATX_FORCE_SYNC;
1484 } else if (strcmp(optarg, "always") == 0) {
1485 flags &= ~AT_STATX_SYNC_TYPE;
1486 flags |= AT_STATX_DONT_SYNC;
1487 } else if (strcmp(optarg, "default") == 0) {
1488 flags &= ~AT_STATX_SYNC_TYPE;
1489 flags |= AT_SYMLINK_NOFOLLOW;
1491 printf("%s: invalid cached mode: %s\n",
1496 case GETOPT_HELP_CHAR:
1498 case GETOPT_VERSION_CHAR:
1500 printf("Lustre statx: version 0.1\n");
1503 printf("%s: unknown option '-%c'\n",
1510 request_mask = format_to_mask(format);
1512 request_mask = STATX_ALL;
1514 format = long_format ? list_long_format() : NULL;
1516 format = default_format(false, terse, false);
1519 if (optind == argc) {
1521 return do_dir_list(".", request_mask, flags);
1523 printf("statx: missing operand\n"
1524 "Try 'stat --help' for more information.\n");
1528 for (i = optind; i < argc; i++) {
1532 ret = do_dir_list(argv[i], request_mask, flags);
1534 ret = do_statx(argv[i], request_mask, flags);
1543 int main(int argc, char **argv)
1545 static struct option options[] = {
1546 {"version", no_argument, NULL, GETOPT_VERSION_CHAR},
1547 {"quiet", no_argument, NULL, 'q'},
1552 while ((c = getopt_long(argc, argv, "q", options, NULL)) != EOF) {
1557 case GETOPT_VERSION_CHAR:
1559 printf("statx: Not support statx() syscall\n");
1563 printf("Skip: system does not support statx syscall.\n");
1566 #endif /* __NR_statx */