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"
163 static char const fmt_terse_selinux[] = "%n %s %b %f %u %g %D %i %h %t %T"
164 " %X %Y %Z %W %o %C\n";
168 /* Whether to follow symbolic links; True for --dereference (-L). */
169 static bool follow_links;
171 /* Whether to interpret backslash-escape sequences.
172 * True for --printf=FMT, not for --format=FMT (-c).
174 static bool interpret_backslash_escapes;
176 /* The trailing delimiter string:
177 * "" for --printf=FMT, "\n" for --format=FMT (-c).
179 static char const *trailing_delim = "";
181 /* The representation of the decimal point in the current locale. */
182 static char const *decimal_point;
183 static size_t decimal_point_len;
185 /* Convert a possibly-signed character to an unsigned character. This is
186 * a bit safer than casting to unsigned char, since it catches some type
187 * errors that the cast doesn't.
189 static inline unsigned char to_uchar(char ch)
194 void usage(char *prog)
196 printf("Usage: %s [options] <FILE>...\n", prog);
197 printf("Display file status via statx() syscall.\n"
198 "List information about the FILE "
199 "(the current diretory by default) via statx() syscall.\n"
201 "\t-L --dereference follow links\n"
202 "\t--cached=MODE specify how to use cached attributes;\n"
203 "\t See MODE below\n"
204 "\t-c --format=FORMAT use the specified FORMAT instead of the "
206 "\t output a newline after each use of "
208 "\t-t, --terse print the information in terse form\n"
209 "\t-D --dir list information about the FILE (ls)\n"
210 "\t-l use a long listing format\n"
211 "\t-q --quiet do not display results, test only\n\n"
212 "The --cached MODE argument can be; always, never, or default.\n"
213 "`always` will use cached attributes if available, while\n"
214 "`never` will try to synchronize with the latest attributes,\n"
215 "and `default` will leave it up to the underlying file system.\n"
217 "The valid format sequences for files (without --file-system):\n"
219 "\t%%a access rights in octal (note '#' and '0' printf flags)\n"
220 "\t%%A access rights in human readable form\n"
221 "\t%%b number of blocks allocated (see %%B)\n"
222 "\t%%B the size in bytes of each block reported by %%b\n"
223 "\t%%C SELinux security context string\n"
224 "\t%%d device number in decimal\n"
225 "\t%%D device number in hex\n"
226 "\t%%f raw mode in hex\n"
228 "\t%%g group ID of owner\n"
229 "\t%%G group name of owner\n"
230 "\t%%h number of hard links\n"
231 "\t%%i inode number\n"
232 "\t%%m mount point\n"
234 "\t%%N quoted file name with dereference if symbolic link\n"
235 "\t%%o optimal I/O transfer size hint\n"
236 "\t%%p Mask to show what's supported in stx_attributes\n"
237 "\t%%r Flags conveying information about the file: "
239 "\t%%s total size, in bytes\n"
240 "\t%%t major device type in hex, for character/block device "
242 "\t%%T minor device type in hex, for character/block device "
244 "\t%%u user ID of owner\n"
245 "\t%%U user name of owner\n"
246 "\t%%w time of file birth, human-readable; - if unknown\n"
247 "\t%%W time of file birth, seconds since Epoch; 0 if unknown\n"
248 "\t%%x time of last access, human-readable\n"
249 "\t%%X time of last access, seconds since Epoch\n"
250 "\t%%y time of last data modification, human-readable\n"
251 "\t%%Y time of last data modification, seconds since Epoch\n"
252 "\t%%z time of last status change, human-readable\n"
253 "\t%%Z time of last status change, seconds since Epoch\n");
257 /* gnulib/lib/filemode.c */
258 /* Return a character indicating the type of file described by
261 * 'b' block special file
262 * 'c' character special file
263 * 'C' high performance ("contiguous data") file
267 * 'm' multiplexed file (7th edition Unix; obsolete)
268 * 'n' network special file (HP-UX)
269 * 'p' fifo (named pipe)
272 * 'w' whiteout (4.4BSD)
273 * '?' some other file type
275 static char ftypelet(mode_t bits)
277 /* These are the most common, so test for them first.*/
283 /* Other letters standardized by POSIX 1003.1-2004.*/
293 /* Other file types (though not letters) standardized by POSIX.*/
300 /* Like filemodestring, but rely only on MODE.*/
301 static void strmode(mode_t mode, char *str)
303 str[0] = ftypelet(mode);
304 str[1] = mode & S_IRUSR ? 'r' : '-';
305 str[2] = mode & S_IWUSR ? 'w' : '-';
306 str[3] = (mode & S_ISUID
307 ? (mode & S_IXUSR ? 's' : 'S')
308 : (mode & S_IXUSR ? 'x' : '-'));
309 str[4] = mode & S_IRGRP ? 'r' : '-';
310 str[5] = mode & S_IWGRP ? 'w' : '-';
311 str[6] = (mode & S_ISGID
312 ? (mode & S_IXGRP ? 's' : 'S')
313 : (mode & S_IXGRP ? 'x' : '-'));
314 str[7] = mode & S_IROTH ? 'r' : '-';
315 str[8] = mode & S_IWOTH ? 'w' : '-';
316 str[9] = (mode & S_ISVTX
317 ? (mode & S_IXOTH ? 't' : 'T')
318 : (mode & S_IXOTH ? 'x' : '-'));
323 /* filemodestring - fill in string STR with an ls-style ASCII
324 * representation of the st_mode field of file stats block STATP.
325 * 12 characters are stored in STR.
326 * The characters stored in STR are:
328 * 0 File type, as in ftypelet above, except that other letters are used
329 * for files whose type cannot be determined solely from st_mode:
332 * 'M' migrated file (Cray DMF)
334 * 'S' shared memory object
335 * 'T' typed memory object
337 * 1 'r' if the owner may read, '-' otherwise.
339 * 2 'w' if the owner may write, '-' otherwise.
341 * 3 'x' if the owner may execute, 's' if the file is
342 * set-user-id, '-' otherwise.
343 * 'S' if the file is set-user-id, but the execute
346 * 4 'r' if group members may read, '-' otherwise.
348 * 5 'w' if group members may write, '-' otherwise.
350 * 6 'x' if group members may execute, 's' if the file is
351 * set-group-id, '-' otherwise.
352 * 'S' if it is set-group-id but not executable.
354 * 7 'r' if any user may read, '-' otherwise.
356 * 8 'w' if any user may write, '-' otherwise.
358 * 9 'x' if any user may execute, 't' if the file is "sticky"
359 * (will be retained in swap space after execution), '-'
361 * 'T' if the file is sticky but not executable.
363 * 10 ' ' for compatibility with 4.4BSD strmode,
364 * since this interface does not support ACLs.
368 static void filemodestring(struct statx const *stxp, char *str)
370 strmode(stxp->stx_mode, str);
373 if (S_TYPEISSEM(statp))
375 else if (IS_MIGRATED_FILE (statp))
377 else if (S_TYPEISMQ (statp))
379 else if (S_TYPEISSHM (statp))
381 else if (S_TYPEISTMO (statp))
386 /* gnulib/lib/file-type.c */
387 static char const *file_type(struct statx const *stx)
389 /* See POSIX 1003.1-2001 XCU Table 4-8 lines 17093-17107 for some of
392 * To keep diagnostics grammatical in English, the returned string
393 * must start with a consonant.
395 /* Do these three first, as they're the most common. */
396 if (S_ISREG(stx->stx_mode))
397 return stx->stx_size == 0 ? "regular empty file" :
400 if (S_ISDIR(stx->stx_mode))
403 if (S_ISLNK(stx->stx_mode))
404 return "symbolic link";
406 /* The remaining are in alphabetical order. */
407 if (S_ISBLK(stx->stx_mode))
408 return "block special file";
410 if (S_ISCHR(stx->stx_mode))
411 return "character special file";
413 if (S_ISFIFO(stx->stx_mode))
416 if (S_ISSOCK(stx->stx_mode))
422 /* gnulib/lib/areadlink-with-size.c */
423 /* SYMLINK_MAX is used only for an initial memory-allocation sanity
424 * check, so it's OK to guess too small on hosts where there is no
425 * arbitrary limit to symbolic link length.
428 #define SYMLINK_MAX 1024
431 #define MAXSIZE (SIZE_MAX < SSIZE_MAX ? SIZE_MAX : SSIZE_MAX)
433 /* Call readlink to get the symbolic link value of FILE.
434 * SIZE is a hint as to how long the link is expected to be;
435 * typically it is taken from st_size. It need not be correct.
436 * Return a pointer to that NUL-terminated string in malloc'd storage.
437 * If readlink fails, malloc fails, or if the link value is longer
438 * than SSIZE_MAX, return NULL (caller may use errno to diagnose).
440 static char *areadlink_with_size(char const *file, size_t size)
442 /* Some buggy file systems report garbage in st_size. Defend
443 * against them by ignoring outlandish st_size values in the initial
446 size_t symlink_max = SYMLINK_MAX;
447 size_t INITIAL_LIMIT_BOUND = 8 * 1024;
448 size_t initial_limit = (symlink_max < INITIAL_LIMIT_BOUND ?
449 symlink_max + 1 : INITIAL_LIMIT_BOUND);
450 enum { stackbuf_size = 128 };
451 /* The initial buffer size for the link value. */
452 size_t buf_size = (size == 0 ? stackbuf_size : size < initial_limit ?
453 size + 1 : initial_limit);
458 char stackbuf[stackbuf_size];
459 char *buf = stackbuf;
462 if (!(size == 0 && buf_size == stackbuf_size)) {
463 buf = buffer = malloc(buf_size);
468 r = readlink(file, buf, buf_size);
471 /* On AIX 5L v5.3 and HP-UX 11i v2 04/09, readlink returns -1
472 * with errno == ERANGE if the buffer is too small.
474 if (r < 0 && errno != ERANGE) {
475 int saved_errno = errno;
482 if (link_length < buf_size) {
483 buf[link_length] = 0;
485 buffer = malloc(link_length + 1);
487 return memcpy(buffer, buf,
489 } else if (link_length + 1 < buf_size) {
490 /* Shrink BUFFER before returning it. */
491 char *shrinked_buffer;
493 shrinked_buffer = realloc(buffer,
495 if (shrinked_buffer != NULL)
496 buffer = shrinked_buffer;
502 if (buf_size <= MAXSIZE / 2) {
504 } else if (buf_size < MAXSIZE) {
513 /* coreutils/src/stat.c */
514 /* Output a single-character \ escape. */
515 static void print_esc_char(char c)
518 case 'a': /* Alert. */
521 case 'b': /* Backspace. */
524 case 'e': /* Escape. */
527 case 'f': /* Form feed. */
530 case 'n': /* New line. */
533 case 'r': /* Carriage return. */
536 case 't': /* Horizontal tab. */
539 case 'v': /* Vertical tab. */
546 printf("warning: unrecognized escape '\\%c'", c);
552 static size_t format_code_offset(char const *directive)
554 size_t len = strspn(directive + 1, printf_flags);
555 char const *fmt_char = directive + len + 1;
557 fmt_char += strspn(fmt_char, digits);
558 if (*fmt_char == '.')
559 fmt_char += 1 + strspn(fmt_char + 1, digits);
561 return fmt_char - directive;
564 static unsigned int fmt_to_mask(char fmt)
578 return STATX_MODE|STATX_TYPE;
590 return STATX_MODE|STATX_INO;
614 static unsigned int format_to_mask(char const *format)
616 unsigned int mask = 0;
619 for (b = format; *b; b++) {
623 b += format_code_offset(b);
626 mask |= fmt_to_mask(*b);
632 static char *human_access(struct statx const *stxbuf)
634 static char modebuf[12];
636 filemodestring(stxbuf, modebuf);
641 static inline struct timespec
642 statx_timestamp_to_timespec(struct statx_timestamp tsx)
646 ts.tv_sec = tsx.tv_sec;
647 ts.tv_nsec = tsx.tv_nsec;
652 static int timespec_cmp(struct timespec a, struct timespec b)
654 if (a.tv_sec < b.tv_sec)
656 if (a.tv_sec > b.tv_sec)
659 return a.tv_nsec - b.tv_nsec;
662 static char *human_time(const struct statx_timestamp *ts)
664 /* STR must be at least INT_BUFSIZE_BOUND (intmax_t) big, either
665 * because localtime_rz fails, or because the time zone is truly
666 * outlandish so that %z expands to a long string.
668 static char str[INT_BUFSIZE_BOUND(intmax_t)
669 + INT_STRLEN_BOUND(int) /* YYYY */
670 + 1 /* because YYYY might equal INT_MAX + 1900 */
671 + sizeof "-MM-DD HH:MM:SS.NNNNNNNNN +"];
678 if (!localtime_r(&tim, &tm)) {
679 perror("localtime_r");
683 if (o_dir_list && long_format) {
684 struct timespec when_timespec;
685 struct timespec six_months_ago;
688 when_timespec = statx_timestamp_to_timespec(*ts);
689 /* If the file appears to be in the future, update the current
690 * time, in case the file happens to have been modified since
691 * the last time we checked the clock.
693 if (timespec_cmp(current_time, when_timespec) < 0) {
696 gettimeofday(&tv, NULL);
697 current_time.tv_sec = tv.tv_sec;
698 current_time.tv_nsec = tv.tv_usec * 1000;
701 /* Consider a time to be recent if it is within the past six
703 * A Gregorian year has 365.2425 * 24 * 60 * 60 == 31556952
704 * seconds on the average. Write this value as an integer
705 * constant to avoid floating point hassles.
707 six_months_ago.tv_sec = current_time.tv_sec - 31556952 / 2;
708 six_months_ago.tv_nsec = current_time.tv_nsec;
710 recent = (timespec_cmp(six_months_ago, when_timespec) < 0 &&
711 (timespec_cmp(when_timespec, current_time) < 0));
713 /* We assume here that all time zones are offset from UTC by a
714 * whole number of seconds.
716 len = strftime(str, sizeof(str),
717 recent ? "%b %e %H:%M" : "%b %e %Y", &tm);
726 len = strftime(str, sizeof(str), "%Y-%m-%d %H:%M:%S", &tm);
732 len2 = snprintf(str + len, sizeof(str) - len, ".%09u ", ts->tv_nsec);
733 len = strftime(str + len + len2, sizeof(str) - len - len2, "%z", &tm);
742 /* PFORMAT points to a '%' followed by a prefix of a format, all of
743 * size PREFIX_LEN. The flags allowed for this format are
744 * ALLOWED_FLAGS; remove other printf flags from the prefix, then
747 static void make_format(char *pformat, size_t prefix_len,
748 char const *allowed_flags, char const *suffix)
750 char *dst = pformat + 1;
752 char const *srclim = pformat + prefix_len;
754 for (src = dst; src < srclim && strchr(printf_flags, *src); src++)
755 if (strchr(allowed_flags, *src))
762 static void out_string(char *pformat, size_t prefix_len, char const *arg)
764 make_format(pformat, prefix_len, "-", "s");
765 printf(pformat, arg);
768 static int out_int(char *pformat, size_t prefix_len, intmax_t arg)
770 make_format(pformat, prefix_len, "'-+ 0", PRIdMAX);
771 return printf(pformat, arg);
774 static int out_uint(char *pformat, size_t prefix_len, uintmax_t arg)
776 make_format(pformat, prefix_len, "'-0", PRIuMAX);
777 return printf(pformat, arg);
780 static void out_uint_o(char *pformat, size_t prefix_len, uintmax_t arg)
782 make_format(pformat, prefix_len, "-#0", PRIoMAX);
783 printf(pformat, arg);
786 static void out_uint_x(char *pformat, size_t prefix_len, uintmax_t arg)
788 make_format(pformat, prefix_len, "-#0", PRIxMAX);
789 printf(pformat, arg);
792 static int out_minus_zero(char *pformat, size_t prefix_len)
794 make_format(pformat, prefix_len, "'-+ 0", ".0f");
795 return printf(pformat, -0.25);
798 /* Output the number of seconds since the Epoch, using a format that
799 * acts like printf's %f format.
801 static void out_epoch_sec(char *pformat, size_t prefix_len,
804 char *dot = memchr(pformat, '.', prefix_len);
805 size_t sec_prefix_len = prefix_len;
808 bool frac_left_adjust = false;
811 sec_prefix_len = dot - pformat;
812 pformat[prefix_len] = '\0';
814 if (ISDIGIT(dot[1])) {
815 long int lprec = strtol(dot + 1, NULL, 10);
817 precision = (lprec <= INT_MAX ? lprec : INT_MAX);
822 if (precision && ISDIGIT(dot[-1])) {
823 /* If a nontrivial width is given, subtract the width
824 * of the decimal point and PRECISION digits that will
833 while (ISDIGIT(p[-1]));
835 long int lwidth = strtol(p, NULL, 10);
837 width = (lwidth <= INT_MAX ? lwidth : INT_MAX);
840 sec_prefix_len = p - pformat;
842 int w_d = (decimal_point_len < width ?
843 width - decimal_point_len : 0);
846 int w = w_d - precision;
850 char const *src = dst;
851 for (; src < p; src++) {
853 frac_left_adjust = true;
859 + (frac_left_adjust ? 0 : sprintf(dst, "%d", w)));
869 for (i = precision; i < 9; i++)
872 int frac_sec = arg.tv_nsec / divisor;
876 if (TYPE_SIGNED(time_t)) {
877 bool minus_zero = false;
879 if (arg.tv_sec < 0 && arg.tv_nsec != 0) {
880 int frac_sec_modulus = 1000000000 / divisor;
882 frac_sec = (frac_sec_modulus - frac_sec
883 - (arg.tv_nsec % divisor != 0));
884 arg.tv_sec += (frac_sec != 0);
885 minus_zero = (arg.tv_sec == 0);
887 int_len = (minus_zero ?
888 out_minus_zero(pformat, sec_prefix_len) :
889 out_int(pformat, sec_prefix_len, arg.tv_sec));
891 int_len = out_uint(pformat, sec_prefix_len, arg.tv_sec);
895 int prec = (precision < 9 ? precision : 9);
896 int trailing_prec = precision - prec;
897 int ilen = (int_len < 0 ? 0 : int_len);
898 int trailing_width = (ilen < width &&
899 decimal_point_len < width - ilen ?
900 width - ilen - decimal_point_len - prec :
903 printf("%s%.*d%-*.*d", decimal_point, prec, frac_sec,
904 trailing_width, trailing_prec, 0);
908 /* Print the context information of FILENAME, and return true iff the
909 * context could not be obtained.
911 static int out_file_context(char *pformat, size_t prefix_len,
912 char const *filename)
914 char *scontext = NULL;
918 if ((follow_links ? getfilecon(filename, &scontext) :
919 lgetfilecon(filename, &scontext)) < 0) {
920 printf("failed to get security context of %s: %s\n",
921 filename, strerror(errno));
927 strcpy(pformat + prefix_len, "s");
928 printf(pformat, (scontext ? scontext : "?"));
936 /* Map a TS with negative TS.tv_nsec to {0,0}. */
937 static inline struct timespec neg_to_zero(struct timespec ts)
939 if (ts.tv_nsec >= 0) {
942 struct timespec z = {0, 0};
948 /* All the mode bits that can be affected by chmod. */
949 #define CHMOD_MODE_BITS \
950 (S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
952 /* Print statx info. Return zero upon success, nonzero upon failure. */
953 static int print_statx(char *pformat, size_t prefix_len, unsigned int m,
954 int fd, char const *filename, struct statx const *stx)
956 struct passwd *pw_ent;
957 struct group *gw_ent;
963 out_string(pformat, prefix_len,
964 o_dir_list ? strrchr(filename, '/') + 1 : filename);
967 out_string(pformat, prefix_len,
968 o_dir_list ? strrchr(filename, '/') + 1 : filename);
969 if (S_ISLNK(stx->stx_mode)) {
972 linkname = areadlink_with_size(filename, stx->stx_size);
973 if (linkname == NULL) {
974 printf("cannot read symbolic link %s: %s",
975 filename, strerror(errno));
979 out_string(pformat, prefix_len, linkname);
984 out_uint(pformat, prefix_len, makedev(stx->stx_dev_major,
985 stx->stx_dev_minor));
988 out_uint_x(pformat, prefix_len, makedev(stx->stx_dev_major,
989 stx->stx_dev_minor));
992 out_uint(pformat, prefix_len, stx->stx_ino);
995 out_uint_o(pformat, prefix_len,
996 stx->stx_mode & CHMOD_MODE_BITS);
999 out_string(pformat, prefix_len, human_access(stx));
1002 out_uint_x(pformat, prefix_len, stx->stx_mode);
1005 out_string(pformat, prefix_len, file_type(stx));
1008 out_uint(pformat, prefix_len, stx->stx_nlink);
1011 out_uint(pformat, prefix_len, stx->stx_uid);
1014 pw_ent = getpwuid(stx->stx_uid);
1015 out_string(pformat, prefix_len,
1016 pw_ent ? pw_ent->pw_name : "UNKNOWN");
1019 out_uint(pformat, prefix_len, stx->stx_gid);
1022 gw_ent = getgrgid(stx->stx_gid);
1023 out_string(pformat, prefix_len,
1024 gw_ent ? gw_ent->gr_name : "UNKNOWN");
1028 * fail |= out_mount_point(filename, pformat, prefix_len,
1035 out_int(pformat, prefix_len, stx->stx_size);
1038 out_uint_x(pformat, prefix_len,
1039 major(makedev(stx->stx_rdev_major,
1040 stx->stx_rdev_minor)));
1043 out_uint_x(pformat, prefix_len,
1044 minor(makedev(stx->stx_rdev_major,
1045 stx->stx_rdev_minor)));
1048 out_uint(pformat, prefix_len, S_BLKSIZE);
1051 out_uint(pformat, prefix_len, stx->stx_blocks);
1054 out_uint(pformat, prefix_len, stx->stx_blksize);
1057 out_uint_x(pformat, prefix_len, stx->stx_attributes_mask);
1060 out_uint_x(pformat, prefix_len, stx->stx_attributes);
1063 if (stx->stx_btime.tv_nsec < 0)
1064 out_string(pformat, prefix_len, "-");
1066 out_string(pformat, prefix_len,
1067 human_time(&stx->stx_btime));
1070 out_epoch_sec(pformat, prefix_len,
1071 neg_to_zero(statx_timestamp_to_timespec(
1075 out_string(pformat, prefix_len,
1076 human_time(&stx->stx_atime));
1079 out_epoch_sec(pformat, prefix_len,
1080 neg_to_zero(statx_timestamp_to_timespec(
1084 out_string(pformat, prefix_len,
1085 human_time(&stx->stx_mtime));
1088 out_epoch_sec(pformat, prefix_len,
1089 neg_to_zero(statx_timestamp_to_timespec(
1093 out_string(pformat, prefix_len,
1094 human_time(&stx->stx_ctime));
1097 out_epoch_sec(pformat, prefix_len,
1098 neg_to_zero(statx_timestamp_to_timespec(
1102 ret = out_file_context(pformat, prefix_len, filename);
1114 static int print_it(int fd, char const *filename,
1115 int (*print_func)(char *, size_t, unsigned int,
1116 int, char const *, struct statx const *),
1119 /* Add 2 to accommodate our conversion of the stat '%s' format string
1120 * to the longer printf '%llu' one.
1123 MAX_ADDITIONAL_BYTES = (MAX(sizeof(PRIdMAX),
1124 MAX(sizeof(PRIoMAX),
1125 MAX(sizeof(PRIuMAX),
1126 sizeof(PRIxMAX)))) - 1)
1136 n_alloc = strlen(format) + MAX_ADDITIONAL_BYTES + 1;
1137 dest = malloc(n_alloc);
1141 for (b = format; *b; b++) {
1144 size_t len = format_code_offset(b);
1145 char const *fmt_char = b + len;
1148 memcpy(dest, b, len);
1151 switch (*fmt_char) {
1156 dest[len] = *fmt_char;
1157 dest[len + 1] = '\0';
1158 printf("%s: invalid directive", dest);
1164 ret = print_func(dest, len, to_uchar(*fmt_char),
1165 fd, filename, data);
1173 if (!interpret_backslash_escapes) {
1179 int esc_value = octtobin(*b);
1180 int esc_length = 1; /* number of octal digits */
1182 for (++b; esc_length < 3 && isodigit(*b);
1183 ++esc_length, ++b) {
1184 esc_value = esc_value * 8 +
1189 } else if (*b == 'x' && isxdigit(to_uchar(b[1]))) {
1190 /* Value of \xhh escape. */
1191 int esc_value = hextobin(b[1]);
1192 /* A hexadecimal \xhh escape sequence must have
1193 * 1 or 2 hex. digits.
1197 if (isxdigit(to_uchar(b[1]))) {
1199 esc_value = esc_value * 16 +
1203 } else if (*b == '\0') {
1204 printf("warning: backslash at end of format");
1206 /* Arrange to exit the loop. */
1220 fputs(trailing_delim, stdout);
1225 /* Return an allocated format string in static storage that
1226 * corresponds to whether FS and TERSE options were declared.
1228 static char *default_format(bool fs, bool terse, bool device)
1234 format = xstrdup(fmt_terse_fs);
1236 /* TRANSLATORS: This string uses format specifiers from
1237 * 'stat --help' with --file-system, and NOT from
1242 " ID: %-8i Namelen: %-7l Type: %T\n"
1243 "Block size: %-10s Fundamental block size: %S\n"
1244 "Blocks: Total: %-10b Free: %-10f Available: %a\n"
1245 "Inodes: Total: %-10c Free: %d\n");
1250 if (is_selinux_enabled() > 0)
1251 format = xstrdup(fmt_terse_selinux);
1254 format = xstrdup(fmt_terse_regular);
1258 /* TRANSLATORS: This string uses format specifiers from
1259 * 'stat --help' without --file-system, and NOT from
1264 Size: %-10s\tBlocks: %-10b IO Block: %-6o %F\n\
1269 /* TRANSLATORS: This string uses format
1270 * specifiers from 'stat --help' without
1271 * --file-system, and NOT from printf.
1273 format = xasprintf("%s%s", format, "\
1274 " "Device: %Dh/%dd\tInode: %-10i Links: %-5h Device type: %t,%T\n\
1277 /* TRANSLATORS: This string uses format
1278 * specifiers from 'stat --help' without
1279 * --file-system, and NOT from printf.
1281 format = xasprintf("%s%s", format, "\
1282 " "Device: %Dh/%dd\tInode: %-10i Links: %h\n\
1288 /* TRANSLATORS: This string uses format specifiers from
1289 * 'stat --help' without --file-system, and NOT from
1292 format = xasprintf("%s%s", format, "\
1293 " "Access: (%04a/%10.10A) Uid: (%5u/%8U) Gid: (%5g/%8G)\n\
1298 if (is_selinux_enabled() > 0) {
1300 /* TRANSLATORS: This string uses format
1301 * specifiers from 'stat --help' without
1302 * --file-system, and NOT from printf.
1304 format = xasprintf("%s%s", format,
1310 /* TRANSLATORS: This string uses format specifiers from
1311 * 'stat --help' without --file-system, and NOT from
1314 format = xasprintf("%s%s", format,
1325 static char *list_long_format(void)
1330 " "%10.10A %h %8U %8G %-10s %y %N\
1336 static int do_statx(char const *filename, unsigned int request_mask, int flags)
1338 const char *pathname = filename;
1339 struct statx stx = { 0, };
1342 if (strcmp(filename, "-") == 0)
1347 if (fd != AT_FDCWD) {
1349 flags |= AT_EMPTY_PATH;
1352 fd = statx(fd, pathname, flags, request_mask, &stx);
1354 if (flags & AT_EMPTY_PATH)
1355 printf("cannot stat standard input\n");
1357 printf("cannot statx %s: %s\n",
1358 filename, strerror(errno));
1363 return print_it(fd, filename, print_statx, &stx);
1366 /* Return true if FILE should be ignored. */
1367 static bool file_ignored(char const *name)
1369 return name[0] == '.';
1372 static int do_dir_list(char const *dirname, unsigned int request_mask,
1377 char fullname[PATH_MAX];
1380 dir = opendir(dirname);
1383 printf("lsx: cannot open directory '%s': %s\n",
1384 dirname, strerror(errno));
1388 while ((ent = readdir(dir)) != NULL) {
1391 /* skip "." and ".." */
1392 if (file_ignored(ent->d_name))
1400 printf("%s", ent->d_name);
1403 if (strlen(ent->d_name) + strlen(dirname) + 1 >=
1405 errno = ENAMETOOLONG;
1407 "lsx: ignored too long path: %s/%s\n",
1408 dirname, ent->d_name);
1413 snprintf(fullname, PATH_MAX, "%s/%s",
1414 dirname, ent->d_name);
1415 ret = do_statx(fullname, request_mask, flags);
1427 int main(int argc, char **argv)
1429 static struct option options[] = {
1430 {"dereference", no_argument, NULL, 'L'},
1431 {"format", required_argument, NULL, 'c'},
1432 {"printf", required_argument, NULL, PRINTF_OPTION},
1433 {"terse", no_argument, NULL, 't'},
1434 {"cached", required_argument, NULL, 0},
1435 {"dir", no_argument, NULL, 'D'},
1436 {"long-format", no_argument, NULL, 'l'},
1437 {"quiet", no_argument, NULL, 'q'},
1438 {"help", no_argument, NULL, GETOPT_HELP_CHAR},
1439 {"version", no_argument, NULL, GETOPT_VERSION_CHAR},
1443 unsigned int request_mask;
1444 int flags = AT_SYMLINK_NOFOLLOW;
1445 struct lconv const *locale = localeconv();
1450 decimal_point = locale->decimal_point[0] ? locale->decimal_point : ".";
1451 decimal_point_len = strlen(decimal_point);
1452 current_time.tv_sec = TYPE_MINIMUM(time_t);
1453 current_time.tv_nsec = -1;
1455 while ((c = getopt_long(argc, argv, "c:DqLlt", options, NULL)) != EOF) {
1458 flags &= ~AT_SYMLINK_NOFOLLOW;
1459 follow_links = true;
1463 interpret_backslash_escapes = true;
1464 trailing_delim = "";
1468 interpret_backslash_escapes = false;
1469 trailing_delim = "\n";
1485 if (strcmp(optarg, "never") == 0) {
1486 flags &= ~AT_STATX_SYNC_TYPE;
1487 flags |= AT_STATX_FORCE_SYNC;
1488 } else if (strcmp(optarg, "always") == 0) {
1489 flags &= ~AT_STATX_SYNC_TYPE;
1490 flags |= AT_STATX_DONT_SYNC;
1491 } else if (strcmp(optarg, "default") == 0) {
1492 flags &= ~AT_STATX_SYNC_TYPE;
1493 flags |= AT_SYMLINK_NOFOLLOW;
1495 printf("%s: invalid cached mode: %s\n",
1500 case GETOPT_HELP_CHAR:
1502 case GETOPT_VERSION_CHAR:
1504 printf("Lustre statx: version 0.1\n");
1507 printf("%s: unknown option '-%c'\n",
1514 request_mask = format_to_mask(format);
1516 request_mask = STATX_ALL;
1518 format = long_format ? list_long_format() : NULL;
1520 format = default_format(false, terse, false);
1523 if (optind == argc) {
1525 return do_dir_list(".", request_mask, flags);
1527 printf("statx: missing operand\n"
1528 "Try 'stat --help' for more information.\n");
1532 for (i = optind; i < argc; i++) {
1536 ret = do_dir_list(argv[i], request_mask, flags);
1538 ret = do_statx(argv[i], request_mask, flags);
1547 int main(int argc, char **argv)
1549 static struct option options[] = {
1550 {"version", no_argument, NULL, GETOPT_VERSION_CHAR},
1551 {"quiet", no_argument, NULL, 'q'},
1556 while ((c = getopt_long(argc, argv, "q", options, NULL)) != EOF) {
1561 case GETOPT_VERSION_CHAR:
1563 printf("statx: Not support statx() syscall\n");
1567 printf("Skip: system does not support statx syscall.\n");
1570 #endif /* __NR_statx */