Whamcloud - gitweb
LU-10059 tests: sanityn 32a error messages
[fs/lustre-release.git] / lustre / tests / statx.c
1 /*
2  * LGPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
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
11  *
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.
16  *
17  * LGPL HEADER END
18  */
19 /*
20  * Copyright (c) 2019, DDN Storage Corporation.
21  */
22 /*
23  * This file is part of Lustre, http://www.lustre.org/
24  */
25 /*
26  *
27  * Test for Lustre statx().
28  * It uses some code in coreutils ('ls.c' and 'stat.c') for reference.
29  *
30  * Author: Qian Yingjin <qian@ddn.com>
31  */
32 #define _ATFILE_SOURCE
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <getopt.h>
37 #include <limits.h>
38 #include <unistd.h>
39 #include <ctype.h>
40 #include <errno.h>
41 #include <time.h>
42 #include <sys/time.h>
43 #include <pwd.h>
44 #include <grp.h>
45 #include <dirent.h>
46 #include <sys/syscall.h>
47 #include <sys/types.h>
48 #include <sys/param.h>
49 #include <sys/sysmacros.h>
50 #include <inttypes.h>
51 #include <fcntl.h>
52 #include <locale.h>
53 #include <libiberty.h>
54 #include <linux/lustre/lustre_user.h>
55
56 #ifdef HAVE_SELINUX
57 #include <selinux/selinux.h>
58 #endif
59
60 /* Factor out some of the common --help and --version processing code. */
61
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.
65  */
66 enum {
67         PRINTF_OPTION = (CHAR_MAX + 1),
68         GETOPT_HELP_CHAR = (CHAR_MIN - 2),
69         GETOPT_VERSION_CHAR = (CHAR_MIN - 3)
70 };
71
72 static bool o_quiet;
73
74 #ifdef __NR_statx
75 #ifndef HAVE_STATX
76
77 #define AT_STATX_SYNC_TYPE      0x6000
78 #define AT_STATX_FORCE_SYNC     0x2000
79 #define AT_STATX_DONT_SYNC      0x4000
80
81 static __attribute__((unused))
82 ssize_t statx(int dfd, const char *filename, int flags,
83               unsigned int mask, struct statx *buffer)
84 {
85         return syscall(__NR_statx, dfd, filename, flags, mask, buffer);
86 }
87 #endif /* HAVE_STATX */
88
89 /* coreutils/lib/intprops.h */
90 #define _GL_SIGNED_TYPE_OR_EXPR(t) TYPE_SIGNED(__typeof__(t))
91
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.
95  */
96 #define INT_BITS_STRLEN_BOUND(b) (((b) * 146 + 484) / 485)
97
98 /* The width in bits of the integer type or expression T.
99  * Do not evaluate T.
100  * Padding bits are not supported; this is checked at compile-time below.
101  */
102 #define TYPE_WIDTH(t) (sizeof(t) * CHAR_BIT)
103
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.
107  *
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.
111  */
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))
115
116 /* Bound on buffer size needed to represent an integer type or expression T,
117  * including the terminating null.
118  */
119 #define INT_BUFSIZE_BOUND(t) (INT_STRLEN_BOUND(t) + 1)
120
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)                                   \
125         ? (t)-1                                         \
126         : ((((t)1 << (TYPE_WIDTH(t) - 2)) - 1) * 2 + 1)))
127
128 static bool o_dir_list;
129 static bool long_format; /* use a long listing format */
130
131 /* Current time in seconds and nanoseconds since 1970, updated as
132  * needed when deciding whether a file is recent.
133  */
134 static struct timespec current_time;
135
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')
141
142 #define ISDIGIT(c) ((unsigned int)(c) - '0' <= 9)
143
144 /* True if the real type T is signed.  */
145 #define TYPE_SIGNED(t) (!((t)0 < (t)-1))
146
147 static char const digits[] = "0123456789";
148
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
154  * out_epoch_sec.
155  */
156 static char const printf_flags[] = "'-+ #0I";
157
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"
161                                         " %X %Y %Z %W %o\n";
162 #ifdef HAVE_SELINUX
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";
165 #endif
166 static char *format;
167
168 /* Whether to follow symbolic links;  True for --dereference (-L).  */
169 static bool follow_links;
170
171 /* Whether to interpret backslash-escape sequences.
172  * True for --printf=FMT, not for --format=FMT (-c).
173  */
174 static bool interpret_backslash_escapes;
175
176 /* The trailing delimiter string:
177  * "" for --printf=FMT, "\n" for --format=FMT (-c).
178  */
179 static char const *trailing_delim = "";
180
181 /* The representation of the decimal point in the current locale.  */
182 static char const *decimal_point;
183 static size_t decimal_point_len;
184
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.
188  */
189 static inline unsigned char to_uchar(char ch)
190 {
191         return ch;
192 }
193
194 void usage(char *prog)
195 {
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"
200                "options:\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 "
205                "default;\n"
206                "\t                     output a newline after each use of "
207                "FORMAT\n"
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"
216                "\n"
217                "The valid format sequences for files (without --file-system):\n"
218                "\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"
227                "\t%%F   file type\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"
233                "\t%%n   file name\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: "
238                "stx_attributes\n"
239                "\t%%s   total size, in bytes\n"
240                "\t%%t   major device type in hex, for character/block device "
241                "special files\n"
242                "\t%%T   minor device type in hex, for character/block device "
243                "special files\n"
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");
254         exit(0);
255 }
256
257 /* gnulib/lib/filemode.c */
258 /* Return a character indicating the type of file described by
259  * file mode BITS:
260  * '-' regular file
261  * 'b' block special file
262  * 'c' character special file
263  * 'C' high performance ("contiguous data") file
264  * 'd' directory
265  * 'D' door
266  * 'l' symbolic link
267  * 'm' multiplexed file (7th edition Unix; obsolete)
268  * 'n' network special file (HP-UX)
269  * 'p' fifo (named pipe)
270  * 'P' port
271  * 's' socket
272  * 'w' whiteout (4.4BSD)
273  * '?' some other file type
274  */
275 static char ftypelet(mode_t bits)
276 {
277         /* These are the most common, so test for them first.*/
278         if (S_ISREG(bits))
279                 return '-';
280         if (S_ISDIR(bits))
281                 return 'd';
282
283         /* Other letters standardized by POSIX 1003.1-2004.*/
284         if (S_ISBLK(bits))
285                 return 'b';
286         if (S_ISCHR(bits))
287                 return 'c';
288         if (S_ISLNK(bits))
289                 return 'l';
290         if (S_ISFIFO(bits))
291                 return 'p';
292
293         /* Other file types (though not letters) standardized by POSIX.*/
294         if (S_ISSOCK(bits))
295                 return 's';
296
297         return '?';
298 }
299
300 /* Like filemodestring, but rely only on MODE.*/
301 static void strmode(mode_t mode, char *str)
302 {
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' : '-'));
319         str[10] = ' ';
320         str[11] = '\0';
321 }
322
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:
327  *
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:
330  *
331  *          'F' semaphore
332  *          'M' migrated file (Cray DMF)
333  *          'Q' message queue
334  *          'S' shared memory object
335  *          'T' typed memory object
336  *
337  * 1    'r' if the owner may read, '-' otherwise.
338  *
339  * 2    'w' if the owner may write, '-' otherwise.
340  *
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
344  *      bit isn't set.
345  *
346  * 4    'r' if group members may read, '-' otherwise.
347  *
348  * 5    'w' if group members may write, '-' otherwise.
349  *
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.
353  *
354  * 7    'r' if any user may read, '-' otherwise.
355  *
356  * 8    'w' if any user may write, '-' otherwise.
357  *
358  * 9    'x' if any user may execute, 't' if the file is "sticky"
359  *      (will be retained in swap space after execution), '-'
360  *      otherwise.
361  *      'T' if the file is sticky but not executable.
362  *
363  * 10   ' ' for compatibility with 4.4BSD strmode,
364  *      since this interface does not support ACLs.
365  *
366  * 11   '\0'.
367  */
368 static void filemodestring(struct statx const *stxp, char *str)
369 {
370         strmode(stxp->stx_mode, str);
371
372 /*
373         if (S_TYPEISSEM(statp))
374                 str[0] = 'F';
375         else if (IS_MIGRATED_FILE (statp))
376                 str[0] = 'M';
377         else if (S_TYPEISMQ (statp))
378                 str[0] = 'Q';
379         else if (S_TYPEISSHM (statp))
380                 str[0] = 'S';
381         else if (S_TYPEISTMO (statp))
382                 str[0] = 'T';
383  */
384 }
385
386 /* gnulib/lib/file-type.c */
387 static char const *file_type(struct statx const *stx)
388 {
389         /* See POSIX 1003.1-2001 XCU Table 4-8 lines 17093-17107 for some of
390          * these formats.
391          *
392          * To keep diagnostics grammatical in English, the returned string
393          * must start with a consonant.
394          */
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" :
398                                             "regular file";
399
400         if (S_ISDIR(stx->stx_mode))
401                 return "directory";
402
403         if (S_ISLNK(stx->stx_mode))
404                 return "symbolic link";
405
406         /* The remaining are in alphabetical order.  */
407         if (S_ISBLK(stx->stx_mode))
408                 return "block special file";
409
410         if (S_ISCHR(stx->stx_mode))
411                 return "character special file";
412
413         if (S_ISFIFO(stx->stx_mode))
414                 return "fifo";
415
416         if (S_ISSOCK(stx->stx_mode))
417                 return "socket";
418
419         return "weird file";
420 }
421
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.
426  */
427 #ifndef SYMLINK_MAX
428 #define SYMLINK_MAX 1024
429 #endif
430
431 #define MAXSIZE (SIZE_MAX < SSIZE_MAX ? SIZE_MAX : SSIZE_MAX)
432
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).
439  */
440 static char *areadlink_with_size(char const *file, size_t size)
441 {
442         /* Some buggy file systems report garbage in st_size.  Defend
443          * against them by ignoring outlandish st_size values in the initial
444          * memory allocation.
445          */
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);
454
455         while (1) {
456                 ssize_t r;
457                 size_t link_length;
458                 char stackbuf[stackbuf_size];
459                 char *buf = stackbuf;
460                 char *buffer = NULL;
461
462                 if (!(size == 0 && buf_size == stackbuf_size)) {
463                         buf = buffer = malloc(buf_size);
464                         if (!buffer)
465                                 return NULL;
466                 }
467
468                 r = readlink(file, buf, buf_size);
469                 link_length = r;
470
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.
473                  */
474                 if (r < 0 && errno != ERANGE) {
475                         int saved_errno = errno;
476
477                         free(buffer);
478                         errno = saved_errno;
479                         return NULL;
480                 }
481
482                 if (link_length < buf_size) {
483                         buf[link_length] = 0;
484                         if (!buffer) {
485                                 buffer = malloc(link_length + 1);
486                                 if (buffer)
487                                         return memcpy(buffer, buf,
488                                                       link_length + 1);
489                         } else if (link_length + 1 < buf_size) {
490                                 /* Shrink BUFFER before returning it. */
491                                 char *shrinked_buffer;
492
493                                 shrinked_buffer = realloc(buffer,
494                                                           link_length + 1);
495                                 if (shrinked_buffer != NULL)
496                                         buffer = shrinked_buffer;
497                         }
498                         return buffer;
499                 }
500
501                 free(buffer);
502                 if (buf_size <= MAXSIZE / 2) {
503                         buf_size *= 2;
504                 } else if (buf_size < MAXSIZE) {
505                         buf_size = MAXSIZE;
506                 } else {
507                         errno = ENOMEM;
508                         return NULL;
509                 }
510         }
511 }
512
513 /* coreutils/src/stat.c */
514 /* Output a single-character \ escape.  */
515 static void print_esc_char(char c)
516 {
517         switch (c) {
518         case 'a':                       /* Alert. */
519                 c = '\a';
520                 break;
521         case 'b':                       /* Backspace. */
522                 c = '\b';
523                 break;
524         case 'e':                       /* Escape. */
525                 c = '\x1B';
526                 break;
527         case 'f':                       /* Form feed. */
528                 c = '\f';
529                 break;
530         case 'n':                       /* New line. */
531                 c = '\n';
532                 break;
533         case 'r':                       /* Carriage return. */
534                 c = '\r';
535                 break;
536         case 't':                       /* Horizontal tab. */
537                 c = '\t';
538                 break;
539         case 'v':                       /* Vertical tab. */
540                 c = '\v';
541                 break;
542         case '"':
543         case '\\':
544                 break;
545         default:
546                 printf("warning: unrecognized escape '\\%c'", c);
547                 break;
548         }
549         putchar (c);
550 }
551
552 static size_t format_code_offset(char const *directive)
553 {
554         size_t len = strspn(directive + 1, printf_flags);
555         char const *fmt_char = directive + len + 1;
556
557         fmt_char += strspn(fmt_char, digits);
558         if (*fmt_char == '.')
559                 fmt_char += 1 + strspn(fmt_char + 1, digits);
560
561         return fmt_char - directive;
562 }
563
564 static unsigned int fmt_to_mask(char fmt)
565 {
566         switch (fmt) {
567         case 'N':
568                 return STATX_MODE;
569         case 'd':
570         case 'D':
571                 return STATX_MODE;
572         case 'i':
573                 return STATX_INO;
574         case 'a':
575         case 'A':
576                 return STATX_MODE;
577         case 'f':
578                 return STATX_MODE|STATX_TYPE;
579         case 'F':
580                 return STATX_TYPE;
581         case 'h':
582                 return STATX_NLINK;
583         case 'u':
584         case 'U':
585                 return STATX_UID;
586         case 'g':
587         case 'G':
588                 return STATX_GID;
589         case 'm':
590                 return STATX_MODE|STATX_INO;
591         case 's':
592                 return STATX_SIZE;
593         case 't':
594         case 'T':
595                 return STATX_MODE;
596         case 'b':
597                 return STATX_BLOCKS;
598         case 'w':
599         case 'W':
600                 return STATX_BTIME;
601         case 'x':
602         case 'X':
603                 return STATX_ATIME;
604         case 'y':
605         case 'Y':
606                 return STATX_MTIME;
607         case 'z':
608         case 'Z':
609                 return STATX_CTIME;
610         }
611         return 0;
612 }
613
614 static unsigned int format_to_mask(char const *format)
615 {
616         unsigned int mask = 0;
617         char const *b;
618
619         for (b = format; *b; b++) {
620                 if (*b != '%')
621                         continue;
622
623                 b += format_code_offset(b);
624                 if (*b == '\0')
625                         break;
626                 mask |= fmt_to_mask(*b);
627         }
628
629         return mask;
630 }
631
632 static char *human_access(struct statx const *stxbuf)
633 {
634         static char modebuf[12];
635
636         filemodestring(stxbuf, modebuf);
637         modebuf[10] = 0;
638         return modebuf;
639 }
640
641 static inline struct timespec
642 statx_timestamp_to_timespec(struct statx_timestamp tsx)
643 {
644         struct timespec ts;
645
646         ts.tv_sec = tsx.tv_sec;
647         ts.tv_nsec = tsx.tv_nsec;
648
649         return ts;
650 }
651
652 static int timespec_cmp(struct timespec a, struct timespec b)
653 {
654         if (a.tv_sec < b.tv_sec)
655                 return -1;
656         if (a.tv_sec > b.tv_sec)
657                 return 1;
658
659         return a.tv_nsec - b.tv_nsec;
660 }
661
662 static char *human_time(const struct statx_timestamp *ts)
663 {
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.
667          */
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 +"];
672         struct tm tm;
673         time_t tim;
674         int len;
675         int len2;
676
677         tim = ts->tv_sec;
678         if (!localtime_r(&tim, &tm)) {
679                 perror("localtime_r");
680                 exit(EXIT_FAILURE);
681         }
682
683         if (o_dir_list && long_format) {
684                 struct timespec when_timespec;
685                 struct timespec six_months_ago;
686                 bool recent;
687
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.
692                  */
693                 if (timespec_cmp(current_time, when_timespec) < 0) {
694                         struct timeval tv;
695
696                         gettimeofday(&tv, NULL);
697                         current_time.tv_sec = tv.tv_sec;
698                         current_time.tv_nsec = tv.tv_usec * 1000;
699                 }
700
701                 /* Consider a time to be recent if it is within the past six
702                  * months.
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.
706                  */
707                 six_months_ago.tv_sec = current_time.tv_sec - 31556952 / 2;
708                 six_months_ago.tv_nsec = current_time.tv_nsec;
709
710                 recent = (timespec_cmp(six_months_ago, when_timespec) < 0 &&
711                           (timespec_cmp(when_timespec, current_time) < 0));
712
713                 /* We assume here that all time zones are offset from UTC by a
714                  * whole number of seconds.
715                  */
716                 len = strftime(str, sizeof(str),
717                                recent ? "%b %e %H:%M" : "%b %e %Y", &tm);
718                 if (len == 0) {
719                         perror("strftime");
720                         exit(EXIT_FAILURE);
721                 }
722
723                 return str;
724         }
725
726         len = strftime(str, sizeof(str), "%Y-%m-%d %H:%M:%S", &tm);
727         if (len == 0) {
728                 perror("strftime");
729                 exit(EXIT_FAILURE);
730         }
731
732         len2 = snprintf(str + len, sizeof(str) - len, ".%09u ", ts->tv_nsec);
733         len = strftime(str + len + len2, sizeof(str) - len - len2, "%z", &tm);
734         if (len == 0) {
735                 perror("strftime2");
736                 exit(1);
737         }
738
739         return str;
740 }
741
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
745  * append SUFFIX.
746  */
747 static void make_format(char *pformat, size_t prefix_len,
748                         char const *allowed_flags, char const *suffix)
749 {
750         char *dst = pformat + 1;
751         char const *src;
752         char const *srclim = pformat + prefix_len;
753
754         for (src = dst; src < srclim && strchr(printf_flags, *src); src++)
755                 if (strchr(allowed_flags, *src))
756                         *dst++ = *src;
757         while (src < srclim)
758                 *dst++ = *src++;
759         strcpy(dst, suffix);
760 }
761
762 static void out_string(char *pformat, size_t prefix_len, char const *arg)
763 {
764         make_format(pformat, prefix_len, "-", "s");
765         printf(pformat, arg);
766 }
767
768 static int out_int(char *pformat, size_t prefix_len, intmax_t arg)
769 {
770         make_format(pformat, prefix_len, "'-+ 0", PRIdMAX);
771         return printf(pformat, arg);
772 }
773
774 static int out_uint(char *pformat, size_t prefix_len, uintmax_t arg)
775 {
776         make_format(pformat, prefix_len, "'-0", PRIuMAX);
777         return printf(pformat, arg);
778 }
779
780 static void out_uint_o(char *pformat, size_t prefix_len, uintmax_t arg)
781 {
782         make_format(pformat, prefix_len, "-#0", PRIoMAX);
783         printf(pformat, arg);
784 }
785
786 static void out_uint_x(char *pformat, size_t prefix_len, uintmax_t arg)
787 {
788         make_format(pformat, prefix_len, "-#0", PRIxMAX);
789         printf(pformat, arg);
790 }
791
792 static int out_minus_zero(char *pformat, size_t prefix_len)
793 {
794         make_format(pformat, prefix_len, "'-+ 0", ".0f");
795         return printf(pformat, -0.25);
796 }
797
798 /* Output the number of seconds since the Epoch, using a format that
799  * acts like printf's %f format.
800  */
801 static void out_epoch_sec(char *pformat, size_t prefix_len,
802                           struct timespec arg)
803 {
804         char *dot = memchr(pformat, '.', prefix_len);
805         size_t sec_prefix_len = prefix_len;
806         int width = 0;
807         int precision = 0;
808         bool frac_left_adjust = false;
809
810         if (dot) {
811                 sec_prefix_len = dot - pformat;
812                 pformat[prefix_len] = '\0';
813
814                 if (ISDIGIT(dot[1])) {
815                         long int lprec = strtol(dot + 1, NULL, 10);
816
817                         precision = (lprec <= INT_MAX ? lprec : INT_MAX);
818                 } else {
819                         precision = 9;
820                 }
821
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
825                          * be output later.
826                          */
827                         char *p = dot;
828
829                         *dot = '\0';
830
831                         do
832                                 --p;
833                         while (ISDIGIT(p[-1]));
834
835                         long int lwidth = strtol(p, NULL, 10);
836
837                         width = (lwidth <= INT_MAX ? lwidth : INT_MAX);
838                         if (width > 1) {
839                                 p += (*p == '0');
840                                 sec_prefix_len = p - pformat;
841
842                                 int w_d = (decimal_point_len < width ?
843                                            width - decimal_point_len : 0);
844
845                                 if (w_d > 1) {
846                                         int w = w_d - precision;
847
848                                         if (w > 1) {
849                                                 char *dst = pformat;
850                                                 char const *src = dst;
851                                                 for (; src < p; src++) {
852                                                         if (*src == '-')
853                                                                 frac_left_adjust = true;
854                                                         else
855                                                                 *dst++ = *src;
856                                                 }
857                                                 sec_prefix_len =
858                                                         (dst - pformat
859                         + (frac_left_adjust ? 0 : sprintf(dst, "%d", w)));
860                                         }
861                                 }
862                         }
863                 }
864         }
865
866         int divisor = 1;
867         int i;
868
869         for (i = precision; i < 9; i++)
870                 divisor *= 10;
871
872         int frac_sec = arg.tv_nsec / divisor;
873         int int_len;
874
875
876         if (TYPE_SIGNED(time_t)) {
877                 bool minus_zero = false;
878
879                 if (arg.tv_sec < 0 && arg.tv_nsec != 0) {
880                         int frac_sec_modulus = 1000000000 / divisor;
881
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);
886                 }
887                 int_len = (minus_zero ?
888                            out_minus_zero(pformat, sec_prefix_len) :
889                            out_int(pformat, sec_prefix_len, arg.tv_sec));
890         } else {
891                 int_len = out_uint(pformat, sec_prefix_len, arg.tv_sec);
892         }
893
894         if (precision) {
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 :
901                                       0);
902
903                 printf("%s%.*d%-*.*d", decimal_point, prec, frac_sec,
904                         trailing_width, trailing_prec, 0);
905         }
906 }
907
908 /* Print the context information of FILENAME, and return true iff the
909  * context could not be obtained.
910  */
911 static int out_file_context(char *pformat, size_t prefix_len,
912                             char const *filename)
913 {
914         char *scontext = NULL;
915         int rc = 0;
916
917 #ifdef HAVE_SELINUX
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));
922                 scontext = NULL;
923                 rc  = -errno;
924         }
925 #endif
926
927         strcpy(pformat + prefix_len, "s");
928         printf(pformat, (scontext ? scontext : "?"));
929 #ifdef HAVE_SELINUX
930         if (scontext)
931                 freecon(scontext);
932 #endif
933         return rc;
934 }
935
936 /* Map a TS with negative TS.tv_nsec to {0,0}.  */
937 static inline struct timespec neg_to_zero(struct timespec ts)
938 {
939         if (ts.tv_nsec >= 0) {
940                 return ts;
941         } else {
942                 struct timespec z = {0, 0};
943
944                 return z;
945         }
946 }
947
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)
951
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)
955 {
956         struct passwd *pw_ent;
957         struct group *gw_ent;
958         int rc = 0;
959         int ret;
960
961         switch (m) {
962         case 'n':
963                 out_string(pformat, prefix_len,
964                            o_dir_list ? strrchr(filename, '/') + 1 : filename);
965                 break;
966         case 'N':
967                 out_string(pformat, prefix_len,
968                            o_dir_list ? strrchr(filename, '/')  + 1 : filename);
969                 if (S_ISLNK(stx->stx_mode)) {
970                         char *linkname;
971
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));
976                                 return -errno;
977                         }
978                         printf(" -> ");
979                         out_string(pformat, prefix_len, linkname);
980                         free(linkname);
981                 }
982                 break;
983         case 'd':
984                 out_uint(pformat, prefix_len, makedev(stx->stx_dev_major,
985                                                       stx->stx_dev_minor));
986                 break;
987         case 'D':
988                 out_uint_x(pformat, prefix_len, makedev(stx->stx_dev_major,
989                                                         stx->stx_dev_minor));
990                 break;
991         case 'i':
992                 out_uint(pformat, prefix_len, stx->stx_ino);
993                 break;
994         case 'a':
995                 out_uint_o(pformat, prefix_len,
996                            stx->stx_mode & CHMOD_MODE_BITS);
997                 break;
998         case 'A':
999                 out_string(pformat, prefix_len, human_access(stx));
1000                 break;
1001         case 'f':
1002                 out_uint_x(pformat, prefix_len, stx->stx_mode);
1003                 break;
1004         case 'F':
1005                 out_string(pformat, prefix_len, file_type(stx));
1006                 break;
1007         case 'h':
1008                 out_uint(pformat, prefix_len, stx->stx_nlink);
1009                 break;
1010         case 'u':
1011                 out_uint(pformat, prefix_len, stx->stx_uid);
1012                 break;
1013         case 'U':
1014                 pw_ent = getpwuid(stx->stx_uid);
1015                 out_string(pformat, prefix_len,
1016                            pw_ent ? pw_ent->pw_name : "UNKNOWN");
1017                 break;
1018         case 'g':
1019                 out_uint(pformat, prefix_len, stx->stx_gid);
1020                 break;
1021         case 'G':
1022                 gw_ent = getgrgid(stx->stx_gid);
1023                 out_string(pformat, prefix_len,
1024                            gw_ent ? gw_ent->gr_name : "UNKNOWN");
1025                 break;
1026         case 'm':
1027                 /*
1028                  * fail |= out_mount_point(filename, pformat, prefix_len,
1029                  *                         statbuf);
1030                  */
1031                 if (!rc)
1032                         rc = -ENOTSUP;
1033                 break;
1034         case 's':
1035                 out_int(pformat, prefix_len, stx->stx_size);
1036                 break;
1037         case 't':
1038                 out_uint_x(pformat, prefix_len,
1039                            major(makedev(stx->stx_rdev_major,
1040                                          stx->stx_rdev_minor)));
1041                 break;
1042         case 'T':
1043                 out_uint_x(pformat, prefix_len,
1044                            minor(makedev(stx->stx_rdev_major,
1045                                          stx->stx_rdev_minor)));
1046                 break;
1047         case 'B':
1048                 out_uint(pformat, prefix_len, S_BLKSIZE);
1049                 break;
1050         case 'b':
1051                 out_uint(pformat, prefix_len, stx->stx_blocks);
1052                 break;
1053         case 'o':
1054                 out_uint(pformat, prefix_len, stx->stx_blksize);
1055                 break;
1056         case 'p':
1057                 out_uint_x(pformat, prefix_len, stx->stx_attributes_mask);
1058                 break;
1059         case 'r':
1060                 out_uint_x(pformat, prefix_len, stx->stx_attributes);
1061                 break;
1062         case 'w':
1063                 if (stx->stx_btime.tv_nsec < 0)
1064                         out_string(pformat, prefix_len, "-");
1065                 else
1066                         out_string(pformat, prefix_len,
1067                                    human_time(&stx->stx_btime));
1068                 break;
1069         case 'W':
1070                 out_epoch_sec(pformat, prefix_len,
1071                               neg_to_zero(statx_timestamp_to_timespec(
1072                                               stx->stx_btime)));
1073                 break;
1074         case 'x':
1075                 out_string(pformat, prefix_len,
1076                            human_time(&stx->stx_atime));
1077                 break;
1078         case 'X':
1079                 out_epoch_sec(pformat, prefix_len,
1080                               neg_to_zero(statx_timestamp_to_timespec(
1081                                               stx->stx_atime)));
1082                 break;
1083         case 'y':
1084                 out_string(pformat, prefix_len,
1085                            human_time(&stx->stx_mtime));
1086                 break;
1087         case 'Y':
1088                 out_epoch_sec(pformat, prefix_len,
1089                               neg_to_zero(statx_timestamp_to_timespec(
1090                                               stx->stx_mtime)));
1091                 break;
1092         case 'z':
1093                 out_string(pformat, prefix_len,
1094                            human_time(&stx->stx_ctime));
1095                 break;
1096         case 'Z':
1097                 out_epoch_sec(pformat, prefix_len,
1098                               neg_to_zero(statx_timestamp_to_timespec(
1099                                               stx->stx_ctime)));
1100                 break;
1101         case 'C':
1102                 ret = out_file_context(pformat, prefix_len, filename);
1103                 if (!rc && ret)
1104                         rc = ret;
1105                 break;
1106         default:
1107                 fputc('?', stdout);
1108                 break;
1109         }
1110
1111         return rc;
1112 }
1113
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 *),
1117                     void const *data)
1118 {
1119         /* Add 2 to accommodate our conversion of the stat '%s' format string
1120          * to the longer printf '%llu' one.
1121          */
1122         enum {
1123                 MAX_ADDITIONAL_BYTES = (MAX(sizeof(PRIdMAX),
1124                                         MAX(sizeof(PRIoMAX),
1125                                             MAX(sizeof(PRIuMAX),
1126                                                 sizeof(PRIxMAX)))) - 1)
1127         };
1128         size_t n_alloc;
1129         char *dest;
1130         char const *b;
1131         int rc = 0;
1132
1133         if (o_quiet)
1134                 return 0;
1135
1136         n_alloc = strlen(format) + MAX_ADDITIONAL_BYTES + 1;
1137         dest = malloc(n_alloc);
1138         if (dest == NULL)
1139                 return -ENOMEM;
1140
1141         for (b = format; *b; b++) {
1142                 switch (*b) {
1143                 case '%': {
1144                         size_t len = format_code_offset(b);
1145                         char const *fmt_char = b + len;
1146                         int ret;
1147
1148                         memcpy(dest, b, len);
1149                         b += len;
1150
1151                         switch (*fmt_char) {
1152                         case '\0':
1153                                 --b;
1154                         case '%':
1155                                 if (len > 1) {
1156                                         dest[len] = *fmt_char;
1157                                         dest[len + 1] = '\0';
1158                                         printf("%s: invalid directive", dest);
1159                                         return -EINVAL;
1160                                 }
1161                                 putchar('%');
1162                                 break;
1163                         default:
1164                                 ret = print_func(dest, len, to_uchar(*fmt_char),
1165                                                  fd, filename, data);
1166                                 if (rc == 0 && ret)
1167                                         rc = ret;
1168                                 break;
1169                         }
1170                         break;
1171                 }
1172                 case '\\':
1173                         if (!interpret_backslash_escapes) {
1174                                 putchar ('\\');
1175                                 break;
1176                         }
1177                         ++b;
1178                         if (isodigit(*b)) {
1179                                 int esc_value = octtobin(*b);
1180                                 int esc_length = 1; /* number of octal digits */
1181
1182                                 for (++b; esc_length < 3 && isodigit(*b);
1183                                      ++esc_length, ++b) {
1184                                         esc_value = esc_value * 8 +
1185                                                     octtobin(*b);
1186                                 }
1187                                 putchar(esc_value);
1188                                 --b;
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.
1194                                  */
1195
1196                                 ++b;
1197                                 if (isxdigit(to_uchar(b[1]))) {
1198                                         ++b;
1199                                         esc_value = esc_value * 16 +
1200                                                     hextobin(*b);
1201                                 }
1202                                 putchar(esc_value);
1203                         } else if (*b == '\0') {
1204                                 printf("warning: backslash at end of format");
1205                                 putchar('\\');
1206                                 /* Arrange to exit the loop.  */
1207                                 --b;
1208                         } else {
1209                                 print_esc_char(*b);
1210                         }
1211                         break;
1212
1213                 default:
1214                         putchar(*b);
1215                         break;
1216                 }
1217         }
1218         free(dest);
1219
1220         fputs(trailing_delim, stdout);
1221
1222         return rc;
1223 }
1224
1225 /* Return an allocated format string in static storage that
1226  * corresponds to whether FS and TERSE options were declared.
1227  */
1228 static char *default_format(bool fs, bool terse, bool device)
1229 {
1230         char *format;
1231
1232         if (fs) {
1233                 if (terse) {
1234                         format = xstrdup(fmt_terse_fs);
1235                 } else {
1236                         /* TRANSLATORS: This string uses format specifiers from
1237                          * 'stat --help' with --file-system, and NOT from
1238                          * printf.
1239                          */
1240                         format = xstrdup(
1241                         "  File: \"%n\"\n"
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");
1246                 }
1247         } else /* ! fs */ {
1248                 if (terse) {
1249 #ifdef HAVE_SELINUX
1250                         if (is_selinux_enabled() > 0)
1251                                 format = xstrdup(fmt_terse_selinux);
1252                         else
1253 #endif
1254                                 format = xstrdup(fmt_terse_regular);
1255                 } else {
1256                         char *temp;
1257
1258                         /* TRANSLATORS: This string uses format specifiers from
1259                          * 'stat --help' without --file-system, and NOT from
1260                          * printf.
1261                          */
1262                         format = xstrdup("\
1263   File: %N\n\
1264   Size: %-10s\tBlocks: %-10b IO Block: %-6o %F\n\
1265 ");
1266
1267                         temp = format;
1268                         if (device) {
1269                                 /* TRANSLATORS: This string uses format
1270                                  * specifiers from 'stat --help' without
1271                                  * --file-system, and NOT from printf.
1272                                  */
1273                                 format = xasprintf("%s%s", format, "\
1274 " "Device: %Dh/%dd\tInode: %-10i  Links: %-5h Device type: %t,%T\n\
1275 ");
1276                         } else {
1277                                 /* TRANSLATORS: This string uses format
1278                                  * specifiers from 'stat --help' without
1279                                  * --file-system, and NOT from printf.
1280                                  */
1281                                 format = xasprintf("%s%s", format, "\
1282 " "Device: %Dh/%dd\tInode: %-10i  Links: %h\n\
1283 ");
1284                         }
1285                         free(temp);
1286
1287                         temp = format;
1288                         /* TRANSLATORS: This string uses format specifiers from
1289                          * 'stat --help' without --file-system, and NOT from
1290                          * printf.
1291                          */
1292                         format = xasprintf("%s%s", format, "\
1293 " "Access: (%04a/%10.10A)  Uid: (%5u/%8U)   Gid: (%5g/%8G)\n\
1294 ");
1295                         free(temp);
1296
1297 #ifdef HAVE_SELINUX
1298                         if (is_selinux_enabled() > 0) {
1299                                 temp = format;
1300                                 /* TRANSLATORS: This string uses format
1301                                  * specifiers from 'stat --help' without
1302                                  * --file-system, and NOT from printf.
1303                                  */
1304                                 format = xasprintf("%s%s", format,
1305                                                    "Context: %C\n");
1306                                 free(temp);
1307                         }
1308 #endif
1309                         temp = format;
1310                         /* TRANSLATORS: This string uses format specifiers from
1311                          * 'stat --help' without --file-system, and NOT from
1312                          * printf.
1313                          */
1314                         format = xasprintf("%s%s", format,
1315                                            "Access: %x\n"
1316                                            "Modify: %y\n"
1317                                            "Change: %z\n"
1318                                            " Birth: %w\n");
1319                         free(temp);
1320                 }
1321         }
1322         return format;
1323 }
1324
1325 static char *list_long_format(void)
1326 {
1327         char *format;
1328
1329         format = xstrdup("\
1330 " "%10.10A %h %8U %8G %-10s %y %N\
1331 ");
1332
1333         return format;
1334 }
1335
1336 static int do_statx(char const *filename, unsigned int request_mask, int flags)
1337 {
1338         const char *pathname = filename;
1339         struct statx stx = { 0, };
1340         int fd;
1341
1342         if (strcmp(filename, "-") == 0)
1343                 fd = 0;
1344         else
1345                 fd = AT_FDCWD;
1346
1347         if (fd != AT_FDCWD) {
1348                 pathname = "";
1349                 flags |= AT_EMPTY_PATH;
1350         }
1351
1352         fd = statx(fd, pathname, flags, request_mask, &stx);
1353         if (fd < 0) {
1354                 if (flags & AT_EMPTY_PATH)
1355                         printf("cannot stat standard input\n");
1356                 else
1357                         printf("cannot statx %s: %s\n",
1358                                filename, strerror(errno));
1359
1360                 return -errno;
1361         }
1362
1363         return print_it(fd, filename, print_statx, &stx);
1364 }
1365
1366 /* Return true if FILE should be ignored. */
1367 static bool file_ignored(char const *name)
1368 {
1369         return name[0] == '.';
1370 }
1371
1372 static int do_dir_list(char const *dirname, unsigned int request_mask,
1373                        int flags)
1374 {
1375         DIR *dir;
1376         struct dirent *ent;
1377         char fullname[PATH_MAX];
1378         int rc = 0;
1379
1380         dir = opendir(dirname);
1381         if (!dir) {
1382                 rc = -errno;
1383                 printf("lsx: cannot open directory '%s': %s\n",
1384                        dirname, strerror(errno));
1385                 return rc;
1386         }
1387
1388         while ((ent = readdir(dir)) != NULL) {
1389                 int ret;
1390
1391                 /* skip "." and ".." */
1392                 if (file_ignored(ent->d_name))
1393                         continue;
1394
1395                 /* ls -1 */
1396                 if (!format) {
1397                         if (o_quiet)
1398                                 continue;
1399
1400                         printf("%s", ent->d_name);
1401                         putchar('\n');
1402                 } else {
1403                         if (strlen(ent->d_name) + strlen(dirname) + 1 >=
1404                             sizeof(fullname)) {
1405                                 errno = ENAMETOOLONG;
1406                                 fprintf(stderr,
1407                                         "lsx: ignored too long path: %s/%s\n",
1408                                         dirname, ent->d_name);
1409                                 if (!rc)
1410                                         rc = -ENAMETOOLONG;
1411                                 continue;
1412                         }
1413                         snprintf(fullname, PATH_MAX, "%s/%s",
1414                                  dirname, ent->d_name);
1415                         ret = do_statx(fullname, request_mask, flags);
1416                         if (!ret)
1417                                 putchar('\n');
1418                         else if (rc == 0)
1419                                 rc = ret;
1420                 }
1421         }
1422
1423         closedir(dir);
1424         return rc;
1425 }
1426
1427 int main(int argc, char **argv)
1428 {
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},
1440                 {NULL, 0, NULL, 0}
1441         };
1442         bool terse = false;
1443         unsigned int request_mask;
1444         int flags = AT_SYMLINK_NOFOLLOW;
1445         struct lconv const *locale = localeconv();
1446         int c;
1447         int rc = 0;
1448         int i = 0;
1449
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;
1454
1455         while ((c = getopt_long(argc, argv, "c:DqLlt", options, NULL)) != EOF) {
1456                 switch (c) {
1457                 case 'L':
1458                         flags &= ~AT_SYMLINK_NOFOLLOW;
1459                         follow_links = true;
1460                         break;
1461                 case PRINTF_OPTION:
1462                         format = optarg;
1463                         interpret_backslash_escapes = true;
1464                         trailing_delim = "";
1465                         break;
1466                 case 'c':
1467                         format = optarg;
1468                         interpret_backslash_escapes = false;
1469                         trailing_delim = "\n";
1470                         break;
1471                 case 'q':
1472                         o_quiet = true;
1473                         break;
1474                 case 'l':
1475                         o_dir_list = true;
1476                         long_format = true;
1477                         break;
1478                 case 'D':
1479                         o_dir_list = true;
1480                         break;
1481                 case 't':
1482                         terse = true;
1483                         break;
1484                 case 0:
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;
1494                         } else {
1495                                 printf("%s: invalid cached mode: %s\n",
1496                                        argv[0], optarg);
1497                                 return -EINVAL;
1498                         }
1499                         break;
1500                 case GETOPT_HELP_CHAR:
1501                         usage(argv[0]);
1502                 case GETOPT_VERSION_CHAR:
1503                         if (!o_quiet)
1504                                 printf("Lustre statx: version 0.1\n");
1505                         return 0;
1506                 default:
1507                         printf("%s: unknown option '-%c'\n",
1508                                argv[0], optopt);
1509                         return -EINVAL;
1510                 }
1511         }
1512
1513         if (format) {
1514                 request_mask = format_to_mask(format);
1515         } else {
1516                 request_mask = STATX_ALL;
1517                 if (o_dir_list)
1518                         format = long_format ? list_long_format() : NULL;
1519                 else
1520                         format = default_format(false, terse, false);
1521         }
1522
1523         if (optind == argc) {
1524                 if (o_dir_list)
1525                         return do_dir_list(".", request_mask, flags);
1526
1527                 printf("statx: missing operand\n"
1528                        "Try 'stat --help' for more information.\n");
1529                 return 0;
1530         }
1531
1532         for (i = optind; i < argc; i++) {
1533                 int ret;
1534
1535                 if (o_dir_list)
1536                         ret = do_dir_list(argv[i], request_mask, flags);
1537                 else
1538                         ret = do_statx(argv[i], request_mask, flags);
1539
1540                 if (rc == 0 && ret)
1541                         rc = ret;
1542         }
1543
1544         return rc;
1545 }
1546 #else
1547 int main(int argc, char **argv)
1548 {
1549         static struct option options[] = {
1550                 {"version", no_argument, NULL, GETOPT_VERSION_CHAR},
1551                 {"quiet", no_argument, NULL, 'q'},
1552                 {NULL, 0, NULL, 0}
1553         };
1554         int c;
1555
1556         while ((c = getopt_long(argc, argv, "q", options, NULL)) != EOF) {
1557                 switch (c) {
1558                 case 'q':
1559                         o_quiet = true;
1560                         break;
1561                 case GETOPT_VERSION_CHAR:
1562                         if (!o_quiet)
1563                                 printf("statx: Not support statx() syscall\n");
1564                         return -ENOTSUP;
1565                 }
1566         }
1567         printf("Skip: system does not support statx syscall.\n");
1568         return 0;
1569 }
1570 #endif /* __NR_statx */