Whamcloud - gitweb
LU-17744 ldiskfs: mballoc stats fixes
[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 <linux/lustre/lustre_user.h>
54
55 #ifdef HAVE_SELINUX
56 #include <selinux/selinux.h>
57 #endif
58
59 /* Factor out some of the common --help and --version processing code. */
60
61 /* These enum values cannot possibly conflict with the option values
62  * ordinarily used by commands, including CHAR_MAX + 1, etc.  Avoid
63  * CHAR_MIN - 1, as it may equal -1, the getopt end-of-options value.
64  */
65 enum {
66         PRINTF_OPTION = (CHAR_MAX + 1),
67         GETOPT_HELP_CHAR = (CHAR_MIN - 2),
68         GETOPT_VERSION_CHAR = (CHAR_MIN - 3)
69 };
70
71 static bool o_quiet;
72
73 #ifdef __NR_statx
74 #ifndef HAVE_STATX
75
76 #define AT_STATX_SYNC_TYPE      0x6000
77 #define AT_STATX_FORCE_SYNC     0x2000
78 #define AT_STATX_DONT_SYNC      0x4000
79
80 static __attribute__((unused))
81 ssize_t statx(int dfd, const char *filename, int flags,
82               unsigned int mask, struct statx *buffer)
83 {
84         return syscall(__NR_statx, dfd, filename, flags, mask, buffer);
85 }
86 #endif /* HAVE_STATX */
87
88 #define xstrdup(str) strdup(str)
89 static inline
90 char *xasprintf(const char *fmt, const char *old_fmt, const char *str)
91 {
92         char *tmp = NULL;
93
94         if (asprintf(&tmp, fmt, old_fmt, str) < 0) {
95                 fprintf(stderr, "asprintf allocation failed\n");
96                 exit(1);
97         }
98
99         return tmp;
100 }
101
102
103 /* coreutils/lib/intprops.h */
104 #define _GL_SIGNED_TYPE_OR_EXPR(t) TYPE_SIGNED(__typeof__(t))
105
106 /* Bound on length of the string representing an unsigned integer
107  * value representable in B bits.  log10 (2.0) < 146/485.  The
108  * smallest value of B where this bound is not tight is 2621.
109  */
110 #define INT_BITS_STRLEN_BOUND(b) (((b) * 146 + 484) / 485)
111
112 /* The width in bits of the integer type or expression T.
113  * Do not evaluate T.
114  * Padding bits are not supported; this is checked at compile-time below.
115  */
116 #define TYPE_WIDTH(t) (sizeof(t) * CHAR_BIT)
117
118 /* Bound on length of the string representing an integer type or expression T.
119  * Subtract 1 for the sign bit if T is signed, and then add 1 more for
120  * a minus sign if needed.
121  *
122  * Because _GL_SIGNED_TYPE_OR_EXPR sometimes returns 1 when its argument is
123  * unsigned, this macro may overestimate the true bound by one byte when
124  * applied to unsigned types of size 2, 4, 16, ... bytes.
125  */
126 #define INT_STRLEN_BOUND(t)                                     \
127         (INT_BITS_STRLEN_BOUND(TYPE_WIDTH(t) - _GL_SIGNED_TYPE_OR_EXPR(t)) \
128         + _GL_SIGNED_TYPE_OR_EXPR(t))
129
130 /* Bound on buffer size needed to represent an integer type or expression T,
131  * including the terminating null.
132  */
133 #define INT_BUFSIZE_BOUND(t) (INT_STRLEN_BOUND(t) + 1)
134
135 /* The maximum and minimum values for the integer type T.  */
136 #define TYPE_MINIMUM(t) ((t)~TYPE_MAXIMUM(t))
137 #define TYPE_MAXIMUM(t)                                         \
138         ((t) (!TYPE_SIGNED(t)                                   \
139         ? (t)-1                                         \
140         : ((((t)1 << (TYPE_WIDTH(t) - 2)) - 1) * 2 + 1)))
141
142 static bool o_dir_list;
143 static bool long_format; /* use a long listing format */
144
145 /* Current time in seconds and nanoseconds since 1970, updated as
146  * needed when deciding whether a file is recent.
147  */
148 static struct timespec current_time;
149
150 /* FIXME: these are used by printf.c, too */
151 #define isodigit(c) ('0' <= (c) && (c) <= '7')
152 #define octtobin(c) ((c) - '0')
153 #define hextobin(c) ((c) >= 'a' && (c) <= 'f' ? (c) - 'a' + 10 : \
154                      (c) >= 'A' && (c) <= 'F' ? (c) - 'A' + 10 : (c) - '0')
155
156 #define ISDIGIT(c) ((unsigned int)(c) - '0' <= 9)
157
158 /* True if the real type T is signed.  */
159 #define TYPE_SIGNED(t) (!((t)0 < (t)-1))
160
161 static char const digits[] = "0123456789";
162
163 /* Flags that are portable for use in printf, for at least one
164  * conversion specifier; make_format removes unportable flags as
165  * needed for particular specifiers.  The glibc 2.2 extension "I" is
166  * listed here; it is removed by make_format because it has undefined
167  * behavior elsewhere and because it is incompatible with
168  * out_epoch_sec.
169  */
170 static char const printf_flags[] = "'-+ #0I";
171
172 /* Formats for the --terse option. */
173 static char const fmt_terse_fs[] = "%n %i %l %t %s %S %b %f %a %c %d\n";
174 static char const fmt_terse_regular[] = "%n %s %b %f %u %g %D %i %h %t %T %X %Y %Z %W %o\n";
175 #ifdef HAVE_SELINUX
176 static char const fmt_terse_selinux[] = "%n %s %b %f %u %g %D %i %h %t %T %X %Y %Z %W %o %C\n";
177 #endif
178 static char *format;
179
180 /* Whether to follow symbolic links;  True for --dereference (-L).  */
181 static bool follow_links;
182
183 /* Whether to interpret backslash-escape sequences.
184  * True for --printf=FMT, not for --format=FMT (-c).
185  */
186 static bool interpret_backslash_escapes;
187
188 /* The trailing delimiter string:
189  * "" for --printf=FMT, "\n" for --format=FMT (-c).
190  */
191 static char const *trailing_delim = "";
192
193 /* The representation of the decimal point in the current locale.  */
194 static char const *decimal_point;
195 static size_t decimal_point_len;
196
197 /* Convert a possibly-signed character to an unsigned character.  This is
198  * a bit safer than casting to unsigned char, since it catches some type
199  * errors that the cast doesn't.
200  */
201 static inline unsigned char to_uchar(char ch)
202 {
203         return ch;
204 }
205
206 static void usage(char *prog)
207 {
208         printf("Usage: %s [options] <FILE>...\n", prog);
209         printf("Display file status via statx() syscall.\n"
210                "List information about the FILE "
211                "(the current diretory by default) via statx() syscall.\n"
212                "options:\n"
213                "\t-L --dereference   follow links\n"
214                "\t--cached=MODE      specify how to use cached attributes;\n"
215                "\t                     See MODE below\n"
216                "\t-c --format=FORMAT use the specified FORMAT instead of the "
217                "default;\n"
218                "\t                     output a newline after each use of "
219                "FORMAT\n"
220                "\t-t, --terse        print the information in terse form\n"
221                "\t-D --dir           list information about the FILE (ls)\n"
222                "\t-l                 use a long listing format\n"
223                "\t-q --quiet         do not display results, test only\n\n"
224                "The --cached MODE argument can be; always, never, or default.\n"
225                "`always` will use cached attributes if available, while\n"
226                "`never` will try to synchronize with the latest attributes,\n"
227                "and `default` will leave it up to the underlying file system.\n"
228                "\n"
229                "The valid format sequences for files (without --file-system):\n"
230                "\n"
231                "\t%%a  access rights in octal (note '#' and '0' printf flags)\n"
232                "\t%%A   access rights in human readable form\n"
233                "\t%%b   number of blocks allocated (see %%B)\n"
234                "\t%%B   the size in bytes of each block reported by %%b\n"
235                "\t%%C   SELinux security context string\n"
236                "\t%%d   device number in decimal\n"
237                "\t%%D   device number in hex\n"
238                "\t%%f   raw mode in hex\n"
239                "\t%%F   file type\n"
240                "\t%%g   group ID of owner\n"
241                "\t%%G   group name of owner\n"
242                "\t%%h   number of hard links\n"
243                "\t%%i   inode number\n"
244                "\t%%m   mount point\n"
245                "\t%%n   file name\n"
246                "\t%%N   quoted file name with dereference if symbolic link\n"
247                "\t%%o   optimal I/O transfer size hint\n"
248                "\t%%p   Mask to show what's supported in stx_attributes\n"
249                "\t%%r   Flags conveying information about the file: "
250                "stx_attributes\n"
251                "\t%%s   total size, in bytes\n"
252                "\t%%t   major device type in hex, for character/block device "
253                "special files\n"
254                "\t%%T   minor device type in hex, for character/block device "
255                "special files\n"
256                "\t%%u   user ID of owner\n"
257                "\t%%U   user name of owner\n"
258                "\t%%w   time of file birth, human-readable; - if unknown\n"
259                "\t%%W   time of file birth, seconds since Epoch; 0 if unknown\n"
260                "\t%%x   time of last access, human-readable\n"
261                "\t%%X   time of last access, seconds since Epoch\n"
262                "\t%%y   time of last data modification, human-readable\n"
263                "\t%%Y   time of last data modification, seconds since Epoch\n"
264                "\t%%z   time of last status change, human-readable\n"
265                "\t%%Z   time of last status change, seconds since Epoch\n");
266         exit(0);
267 }
268
269 /* gnulib/lib/filemode.c */
270 /* Return a character indicating the type of file described by
271  * file mode BITS:
272  * '-' regular file
273  * 'b' block special file
274  * 'c' character special file
275  * 'C' high performance ("contiguous data") file
276  * 'd' directory
277  * 'D' door
278  * 'l' symbolic link
279  * 'm' multiplexed file (7th edition Unix; obsolete)
280  * 'n' network special file (HP-UX)
281  * 'p' fifo (named pipe)
282  * 'P' port
283  * 's' socket
284  * 'w' whiteout (4.4BSD)
285  * '?' some other file type
286  */
287 static char ftypelet(mode_t bits)
288 {
289         /* These are the most common, so test for them first.*/
290         if (S_ISREG(bits))
291                 return '-';
292         if (S_ISDIR(bits))
293                 return 'd';
294
295         /* Other letters standardized by POSIX 1003.1-2004.*/
296         if (S_ISBLK(bits))
297                 return 'b';
298         if (S_ISCHR(bits))
299                 return 'c';
300         if (S_ISLNK(bits))
301                 return 'l';
302         if (S_ISFIFO(bits))
303                 return 'p';
304
305         /* Other file types (though not letters) standardized by POSIX.*/
306         if (S_ISSOCK(bits))
307                 return 's';
308
309         return '?';
310 }
311
312 /* Like filemodestring, but rely only on MODE.*/
313 static void strmode(mode_t mode, char *str)
314 {
315         str[0] = ftypelet(mode);
316         str[1] = mode & 0400 ? 'r' : '-';
317         str[2] = mode & 0200 ? 'w' : '-';
318         str[3] = (mode & S_ISUID
319                         ? (mode & 0100 ? 's' : 'S')
320                         : (mode & 0100 ? 'x' : '-'));
321         str[4] = mode & 0040 ? 'r' : '-';
322         str[5] = mode & 0020 ? 'w' : '-';
323         str[6] = (mode & S_ISGID
324                         ? (mode & 0010 ? 's' : 'S')
325                         : (mode & 0010 ? 'x' : '-'));
326         str[7] = mode & 0004 ? 'r' : '-';
327         str[8] = mode & 0002 ? 'w' : '-';
328         str[9] = (mode & S_ISVTX
329                         ? (mode & 0001 ? 't' : 'T')
330                         : (mode & 0001 ? 'x' : '-'));
331         str[10] = ' ';
332         str[11] = '\0';
333 }
334
335 /* filemodestring - fill in string STR with an ls-style ASCII
336  * representation of the st_mode field of file stats block STATP.
337  * 12 characters are stored in STR.
338  * The characters stored in STR are:
339  *
340  * 0    File type, as in ftypelet above, except that other letters are used
341  *      for files whose type cannot be determined solely from st_mode:
342  *
343  *          'F' semaphore
344  *          'M' migrated file (Cray DMF)
345  *          'Q' message queue
346  *          'S' shared memory object
347  *          'T' typed memory object
348  *
349  * 1    'r' if the owner may read, '-' otherwise.
350  *
351  * 2    'w' if the owner may write, '-' otherwise.
352  *
353  * 3    'x' if the owner may execute, 's' if the file is
354  *      set-user-id, '-' otherwise.
355  *      'S' if the file is set-user-id, but the execute
356  *      bit isn't set.
357  *
358  * 4    'r' if group members may read, '-' otherwise.
359  *
360  * 5    'w' if group members may write, '-' otherwise.
361  *
362  * 6    'x' if group members may execute, 's' if the file is
363  *      set-group-id, '-' otherwise.
364  *      'S' if it is set-group-id but not executable.
365  *
366  * 7    'r' if any user may read, '-' otherwise.
367  *
368  * 8    'w' if any user may write, '-' otherwise.
369  *
370  * 9    'x' if any user may execute, 't' if the file is "sticky"
371  *      (will be retained in swap space after execution), '-'
372  *      otherwise.
373  *      'T' if the file is sticky but not executable.
374  *
375  * 10   ' ' for compatibility with 4.4BSD strmode,
376  *      since this interface does not support ACLs.
377  *
378  * 11   '\0'.
379  */
380 static void filemodestring(struct statx const *stxp, char *str)
381 {
382         strmode(stxp->stx_mode, str);
383 }
384
385 /* gnulib/lib/file-type.c */
386 static char const *file_type(struct statx const *stx)
387 {
388         /* See POSIX 1003.1-2001 XCU Table 4-8 lines 17093-17107 for some of
389          * these formats.
390          *
391          * To keep diagnostics grammatical in English, the returned string
392          * must start with a consonant.
393          */
394         /* Do these three first, as they're the most common.  */
395         if (S_ISREG(stx->stx_mode))
396                 return stx->stx_size == 0 ? "regular empty file" :
397                                             "regular file";
398
399         if (S_ISDIR(stx->stx_mode))
400                 return "directory";
401
402         if (S_ISLNK(stx->stx_mode))
403                 return "symbolic link";
404
405         /* The remaining are in alphabetical order.  */
406         if (S_ISBLK(stx->stx_mode))
407                 return "block special file";
408
409         if (S_ISCHR(stx->stx_mode))
410                 return "character special file";
411
412         if (S_ISFIFO(stx->stx_mode))
413                 return "fifo";
414
415         if (S_ISSOCK(stx->stx_mode))
416                 return "socket";
417
418         return "weird file";
419 }
420
421 /* gnulib/lib/areadlink-with-size.c */
422 /* SYMLINK_MAX is used only for an initial memory-allocation sanity
423  * check, so it's OK to guess too small on hosts where there is no
424  * arbitrary limit to symbolic link length.
425  */
426 #ifndef SYMLINK_MAX
427 #define SYMLINK_MAX 1024
428 #endif
429
430 #define MAXSIZE (SIZE_MAX < SSIZE_MAX ? SIZE_MAX : SSIZE_MAX)
431
432 /* Call readlink to get the symbolic link value of FILE.
433  * SIZE is a hint as to how long the link is expected to be;
434  * typically it is taken from st_size.  It need not be correct.
435  * Return a pointer to that NUL-terminated string in malloc'd storage.
436  * If readlink fails, malloc fails, or if the link value is longer
437  * than SSIZE_MAX, return NULL (caller may use errno to diagnose).
438  */
439 static char *areadlink_with_size(char const *file, size_t size)
440 {
441         /* Some buggy file systems report garbage in st_size.  Defend
442          * against them by ignoring outlandish st_size values in the initial
443          * memory allocation.
444          */
445         size_t symlink_max = SYMLINK_MAX;
446         size_t INITIAL_LIMIT_BOUND = 8 * 1024;
447         size_t initial_limit = (symlink_max < INITIAL_LIMIT_BOUND ?
448                                 symlink_max + 1 : INITIAL_LIMIT_BOUND);
449         enum { stackbuf_size = 128 };
450         /* The initial buffer size for the link value. */
451         size_t buf_size = (size == 0 ? stackbuf_size : size < initial_limit ?
452                            size + 1 : initial_limit);
453
454         while (1) {
455                 ssize_t r;
456                 size_t link_length;
457                 char stackbuf[stackbuf_size];
458                 char *buf = stackbuf;
459                 char *buffer = NULL;
460
461                 if (!(size == 0 && buf_size == stackbuf_size)) {
462                         buf = buffer = malloc(buf_size);
463                         if (!buffer)
464                                 return NULL;
465                 }
466
467                 r = readlink(file, buf, buf_size);
468                 link_length = r;
469
470                 /* On AIX 5L v5.3 and HP-UX 11i v2 04/09, readlink returns -1
471                  * with errno == ERANGE if the buffer is too small.
472                  */
473                 if (r < 0 && errno != ERANGE) {
474                         int saved_errno = errno;
475
476                         free(buffer);
477                         errno = saved_errno;
478                         return NULL;
479                 }
480
481                 if (link_length < buf_size) {
482                         buf[link_length] = 0;
483                         if (!buffer) {
484                                 buffer = malloc(link_length + 1);
485                                 if (buffer)
486                                         return memcpy(buffer, buf,
487                                                       link_length + 1);
488                         } else if (link_length + 1 < buf_size) {
489                                 /* Shrink BUFFER before returning it. */
490                                 char *shrinked_buffer;
491
492                                 shrinked_buffer = realloc(buffer,
493                                                           link_length + 1);
494                                 if (shrinked_buffer != NULL)
495                                         buffer = shrinked_buffer;
496                         }
497                         return buffer;
498                 }
499
500                 free(buffer);
501                 if (buf_size <= MAXSIZE / 2) {
502                         buf_size *= 2;
503                 } else if (buf_size < MAXSIZE) {
504                         buf_size = MAXSIZE;
505                 } else {
506                         errno = ENOMEM;
507                         return NULL;
508                 }
509         }
510 }
511
512 /* coreutils/src/stat.c */
513 /* Output a single-character \ escape.  */
514 static void print_esc_char(char c)
515 {
516         switch (c) {
517         case 'a':                       /* Alert. */
518                 c = '\a';
519                 break;
520         case 'b':                       /* Backspace. */
521                 c = '\b';
522                 break;
523         case 'e':                       /* Escape. */
524                 c = '\x1B';
525                 break;
526         case 'f':                       /* Form feed. */
527                 c = '\f';
528                 break;
529         case 'n':                       /* New line. */
530                 c = '\n';
531                 break;
532         case 'r':                       /* Carriage return. */
533                 c = '\r';
534                 break;
535         case 't':                       /* Horizontal tab. */
536                 c = '\t';
537                 break;
538         case 'v':                       /* Vertical tab. */
539                 c = '\v';
540                 break;
541         case '"':
542         case '\\':
543                 break;
544         default:
545                 printf("warning: unrecognized escape '\\%c'", c);
546                 break;
547         }
548         putchar (c);
549 }
550
551 static size_t format_code_offset(char const *directive)
552 {
553         size_t len = strspn(directive + 1, printf_flags);
554         char const *fmt_char = directive + len + 1;
555
556         fmt_char += strspn(fmt_char, digits);
557         if (*fmt_char == '.')
558                 fmt_char += 1 + strspn(fmt_char + 1, digits);
559
560         return fmt_char - directive;
561 }
562
563 static unsigned int fmt_to_mask(char fmt)
564 {
565         switch (fmt) {
566         case 'N':
567                 return STATX_MODE;
568         case 'd':
569         case 'D':
570                 return STATX_MODE;
571         case 'i':
572                 return STATX_INO;
573         case 'a':
574         case 'A':
575                 return STATX_MODE;
576         case 'f':
577                 return STATX_MODE|STATX_TYPE;
578         case 'F':
579                 return STATX_TYPE;
580         case 'h':
581                 return STATX_NLINK;
582         case 'u':
583         case 'U':
584                 return STATX_UID;
585         case 'g':
586         case 'G':
587                 return STATX_GID;
588         case 'm':
589                 return STATX_MODE|STATX_INO;
590         case 's':
591                 return STATX_SIZE;
592         case 't':
593         case 'T':
594                 return STATX_MODE;
595         case 'b':
596                 return STATX_BLOCKS;
597         case 'w':
598         case 'W':
599                 return STATX_BTIME;
600         case 'x':
601         case 'X':
602                 return STATX_ATIME;
603         case 'y':
604         case 'Y':
605                 return STATX_MTIME;
606         case 'z':
607         case 'Z':
608                 return STATX_CTIME;
609         }
610         return 0;
611 }
612
613 static unsigned int format_to_mask(char const *format)
614 {
615         unsigned int mask = 0;
616         char const *b;
617
618         for (b = format; *b; b++) {
619                 if (*b != '%')
620                         continue;
621
622                 b += format_code_offset(b);
623                 if (*b == '\0')
624                         break;
625                 mask |= fmt_to_mask(*b);
626         }
627
628         return mask;
629 }
630
631 static char *human_access(struct statx const *stxbuf)
632 {
633         static char modebuf[12];
634
635         filemodestring(stxbuf, modebuf);
636         modebuf[10] = 0;
637         return modebuf;
638 }
639
640 static inline struct timespec
641 statx_timestamp_to_timespec(struct statx_timestamp tsx)
642 {
643         struct timespec ts;
644
645         ts.tv_sec = tsx.tv_sec;
646         ts.tv_nsec = tsx.tv_nsec;
647
648         return ts;
649 }
650
651 static int timespec_cmp(struct timespec a, struct timespec b)
652 {
653         if (a.tv_sec < b.tv_sec)
654                 return -1;
655         if (a.tv_sec > b.tv_sec)
656                 return 1;
657
658         return a.tv_nsec - b.tv_nsec;
659 }
660
661 static char *human_time(const struct statx_timestamp *ts)
662 {
663         /* STR must be at least INT_BUFSIZE_BOUND (intmax_t) big, either
664          * because localtime_rz fails, or because the time zone is truly
665          * outlandish so that %z expands to a long string.
666          */
667         static char str[INT_BUFSIZE_BOUND(intmax_t)
668                 + INT_STRLEN_BOUND(int) /* YYYY */
669                 + 1 /* because YYYY might equal INT_MAX + 1900 */
670                 + sizeof "-MM-DD HH:MM:SS.NNNNNNNNN +"];
671         struct tm tm;
672         time_t tim;
673         int len;
674         int len2;
675
676         tim = ts->tv_sec;
677         if (!localtime_r(&tim, &tm)) {
678                 perror("localtime_r");
679                 exit(EXIT_FAILURE);
680         }
681
682         if (o_dir_list && long_format) {
683                 struct timespec when_timespec;
684                 struct timespec six_months_ago;
685                 bool recent;
686
687                 when_timespec = statx_timestamp_to_timespec(*ts);
688                 /* If the file appears to be in the future, update the current
689                  * time, in case the file happens to have been modified since
690                  * the last time we checked the clock.
691                  */
692                 if (timespec_cmp(current_time, when_timespec) < 0) {
693                         struct timeval tv;
694
695                         gettimeofday(&tv, NULL);
696                         current_time.tv_sec = tv.tv_sec;
697                         current_time.tv_nsec = tv.tv_usec * 1000;
698                 }
699
700                 /* Consider a time to be recent if it is within the past six
701                  * months.
702                  * A Gregorian year has 365.2425 * 24 * 60 * 60 == 31556952
703                  * seconds on the average.  Write this value as an integer
704                  * constant to avoid floating point hassles.
705                  */
706                 six_months_ago.tv_sec = current_time.tv_sec - 31556952 / 2;
707                 six_months_ago.tv_nsec = current_time.tv_nsec;
708
709                 recent = (timespec_cmp(six_months_ago, when_timespec) < 0 &&
710                           (timespec_cmp(when_timespec, current_time) < 0));
711
712                 /* We assume here that all time zones are offset from UTC by a
713                  * whole number of seconds.
714                  */
715                 len = strftime(str, sizeof(str),
716                                recent ? "%b %e %H:%M" : "%b %e %Y", &tm);
717                 if (len == 0) {
718                         perror("strftime");
719                         exit(EXIT_FAILURE);
720                 }
721
722                 return str;
723         }
724
725         len = strftime(str, sizeof(str), "%Y-%m-%d %H:%M:%S", &tm);
726         if (len == 0) {
727                 perror("strftime");
728                 exit(EXIT_FAILURE);
729         }
730
731         len2 = snprintf(str + len, sizeof(str) - len, ".%09u ", ts->tv_nsec);
732         len = strftime(str + len + len2, sizeof(str) - len - len2, "%z", &tm);
733         if (len == 0) {
734                 perror("strftime2");
735                 exit(1);
736         }
737
738         return str;
739 }
740
741 /* PFORMAT points to a '%' followed by a prefix of a format, all of
742  * size PREFIX_LEN.  The flags allowed for this format are
743  * ALLOWED_FLAGS; remove other printf flags from the prefix, then
744  * append SUFFIX.
745  */
746 static void make_format(char *pformat, size_t prefix_len,
747                         char const *allowed_flags, char const *suffix)
748 {
749         char *dst = pformat + 1;
750         char const *src;
751         char const *srclim = pformat + prefix_len;
752
753         for (src = dst; src < srclim && strchr(printf_flags, *src); src++)
754                 if (strchr(allowed_flags, *src))
755                         *dst++ = *src;
756         while (src < srclim)
757                 *dst++ = *src++;
758         strcpy(dst, suffix);
759 }
760
761 static void out_string(char *pformat, size_t prefix_len, char const *arg)
762 {
763         make_format(pformat, prefix_len, "-", "s");
764         printf(pformat, arg);
765 }
766
767 static int out_int(char *pformat, size_t prefix_len, intmax_t arg)
768 {
769         make_format(pformat, prefix_len, "'-+ 0", PRIdMAX);
770         return printf(pformat, arg);
771 }
772
773 static int out_uint(char *pformat, size_t prefix_len, uintmax_t arg)
774 {
775         make_format(pformat, prefix_len, "'-0", PRIuMAX);
776         return printf(pformat, arg);
777 }
778
779 static void out_uint_o(char *pformat, size_t prefix_len, uintmax_t arg)
780 {
781         make_format(pformat, prefix_len, "-#0", PRIoMAX);
782         printf(pformat, arg);
783 }
784
785 static void out_uint_x(char *pformat, size_t prefix_len, uintmax_t arg)
786 {
787         make_format(pformat, prefix_len, "-#0", PRIxMAX);
788         printf(pformat, arg);
789 }
790
791 static int out_minus_zero(char *pformat, size_t prefix_len)
792 {
793         make_format(pformat, prefix_len, "'-+ 0", ".0f");
794         return printf(pformat, -0.25);
795 }
796
797 /* Output the number of seconds since the Epoch, using a format that
798  * acts like printf's %f format.
799  */
800 static void out_epoch_sec(char *pformat, size_t prefix_len,
801                           struct timespec arg)
802 {
803         char *dot = memchr(pformat, '.', prefix_len);
804         size_t sec_prefix_len = prefix_len;
805         int width = 0;
806         int precision = 0;
807         bool frac_left_adjust = false;
808
809         if (dot) {
810                 sec_prefix_len = dot - pformat;
811                 pformat[prefix_len] = '\0';
812
813                 if (ISDIGIT(dot[1])) {
814                         long int lprec = strtol(dot + 1, NULL, 10);
815
816                         precision = (lprec <= INT_MAX ? lprec : INT_MAX);
817                 } else {
818                         precision = 9;
819                 }
820
821                 if (precision && ISDIGIT(dot[-1])) {
822                         /* If a nontrivial width is given, subtract the width
823                          * of the decimal point and PRECISION digits that will
824                          * be output later.
825                          */
826                         char *p = dot;
827
828                         *dot = '\0';
829
830                         do
831                                 --p;
832                         while (ISDIGIT(p[-1]));
833
834                         long int lwidth = strtol(p, NULL, 10);
835
836                         width = (lwidth <= INT_MAX ? lwidth : INT_MAX);
837                         if (width > 1) {
838                                 p += (*p == '0');
839                                 sec_prefix_len = p - pformat;
840
841                                 int w_d = (decimal_point_len < width ?
842                                            width - decimal_point_len : 0);
843
844                                 if (w_d > 1) {
845                                         int w = w_d - precision;
846
847                                         if (w > 1) {
848                                                 char *dst = pformat;
849                                                 char const *src = dst;
850
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
942         struct timespec z = {0, 0};
943
944         return z;
945 }
946
947 /* All the mode bits that can be affected by chmod.  */
948 #define CHMOD_MODE_BITS \
949         (S_ISUID | S_ISGID | S_ISVTX | 0700 | 0070 | 0007)
950
951 /* Print statx info.  Return zero upon success, nonzero upon failure.  */
952 static int print_statx(char *pformat, size_t prefix_len, unsigned int m,
953                        int fd, char const *filename, struct statx const *stx)
954 {
955         struct passwd *pw_ent;
956         struct group *gw_ent;
957         int rc = 0;
958         int ret;
959
960         switch (m) {
961         case 'n':
962                 out_string(pformat, prefix_len,
963                            o_dir_list ? strrchr(filename, '/') + 1 : filename);
964                 break;
965         case 'N':
966                 out_string(pformat, prefix_len,
967                            o_dir_list ? strrchr(filename, '/')  + 1 : filename);
968                 if (S_ISLNK(stx->stx_mode)) {
969                         char *linkname;
970
971                         linkname = areadlink_with_size(filename, stx->stx_size);
972                         if (linkname == NULL) {
973                                 printf("cannot read symbolic link %s: %s",
974                                        filename, strerror(errno));
975                                 return -errno;
976                         }
977                         printf(" -> ");
978                         out_string(pformat, prefix_len, linkname);
979                         free(linkname);
980                 }
981                 break;
982         case 'd':
983                 out_uint(pformat, prefix_len, makedev(stx->stx_dev_major,
984                                                       stx->stx_dev_minor));
985                 break;
986         case 'D':
987                 out_uint_x(pformat, prefix_len, makedev(stx->stx_dev_major,
988                                                         stx->stx_dev_minor));
989                 break;
990         case 'i':
991                 out_uint(pformat, prefix_len, stx->stx_ino);
992                 break;
993         case 'a':
994                 out_uint_o(pformat, prefix_len,
995                            stx->stx_mode & CHMOD_MODE_BITS);
996                 break;
997         case 'A':
998                 out_string(pformat, prefix_len, human_access(stx));
999                 break;
1000         case 'f':
1001                 out_uint_x(pformat, prefix_len, stx->stx_mode);
1002                 break;
1003         case 'F':
1004                 out_string(pformat, prefix_len, file_type(stx));
1005                 break;
1006         case 'h':
1007                 out_uint(pformat, prefix_len, stx->stx_nlink);
1008                 break;
1009         case 'u':
1010                 out_uint(pformat, prefix_len, stx->stx_uid);
1011                 break;
1012         case 'U':
1013                 pw_ent = getpwuid(stx->stx_uid);
1014                 out_string(pformat, prefix_len,
1015                            pw_ent ? pw_ent->pw_name : "UNKNOWN");
1016                 break;
1017         case 'g':
1018                 out_uint(pformat, prefix_len, stx->stx_gid);
1019                 break;
1020         case 'G':
1021                 gw_ent = getgrgid(stx->stx_gid);
1022                 out_string(pformat, prefix_len,
1023                            gw_ent ? gw_ent->gr_name : "UNKNOWN");
1024                 break;
1025         case 'm':
1026                 /*
1027                  * fail |= out_mount_point(filename, pformat, prefix_len,
1028                  *                         statbuf);
1029                  */
1030                 if (!rc)
1031                         rc = -ENOTSUP;
1032                 break;
1033         case 's':
1034                 out_int(pformat, prefix_len, stx->stx_size);
1035                 break;
1036         case 't':
1037                 out_uint_x(pformat, prefix_len,
1038                            major(makedev(stx->stx_rdev_major,
1039                                          stx->stx_rdev_minor)));
1040                 break;
1041         case 'T':
1042                 out_uint_x(pformat, prefix_len,
1043                            minor(makedev(stx->stx_rdev_major,
1044                                          stx->stx_rdev_minor)));
1045                 break;
1046         case 'B':
1047                 out_uint(pformat, prefix_len, S_BLKSIZE);
1048                 break;
1049         case 'b':
1050                 out_uint(pformat, prefix_len, stx->stx_blocks);
1051                 break;
1052         case 'o':
1053                 out_uint(pformat, prefix_len, stx->stx_blksize);
1054                 break;
1055         case 'p':
1056                 out_uint_x(pformat, prefix_len, stx->stx_attributes_mask);
1057                 break;
1058         case 'r':
1059                 out_uint_x(pformat, prefix_len, stx->stx_attributes);
1060                 break;
1061         case 'w':
1062                 if (stx->stx_btime.tv_nsec < 0)
1063                         out_string(pformat, prefix_len, "-");
1064                 else
1065                         out_string(pformat, prefix_len,
1066                                    human_time(&stx->stx_btime));
1067                 break;
1068         case 'W':
1069                 out_epoch_sec(pformat, prefix_len,
1070                               neg_to_zero(statx_timestamp_to_timespec(
1071                                               stx->stx_btime)));
1072                 break;
1073         case 'x':
1074                 out_string(pformat, prefix_len,
1075                            human_time(&stx->stx_atime));
1076                 break;
1077         case 'X':
1078                 out_epoch_sec(pformat, prefix_len,
1079                               neg_to_zero(statx_timestamp_to_timespec(
1080                                               stx->stx_atime)));
1081                 break;
1082         case 'y':
1083                 out_string(pformat, prefix_len,
1084                            human_time(&stx->stx_mtime));
1085                 break;
1086         case 'Y':
1087                 out_epoch_sec(pformat, prefix_len,
1088                               neg_to_zero(statx_timestamp_to_timespec(
1089                                               stx->stx_mtime)));
1090                 break;
1091         case 'z':
1092                 out_string(pformat, prefix_len,
1093                            human_time(&stx->stx_ctime));
1094                 break;
1095         case 'Z':
1096                 out_epoch_sec(pformat, prefix_len,
1097                               neg_to_zero(statx_timestamp_to_timespec(
1098                                               stx->stx_ctime)));
1099                 break;
1100         case 'C':
1101                 ret = out_file_context(pformat, prefix_len, filename);
1102                 if (!rc && ret)
1103                         rc = ret;
1104                 break;
1105         default:
1106                 fputc('?', stdout);
1107                 break;
1108         }
1109
1110         return rc;
1111 }
1112
1113 static int print_it(int fd, char const *filename,
1114                     int (*print_func)(char *, size_t, unsigned int,
1115                                       int, char const *, struct statx const *),
1116                     void const *data)
1117 {
1118         /* Add 2 to accommodate our conversion of the stat '%s' format string
1119          * to the longer printf '%llu' one.
1120          */
1121         enum {
1122                 MAX_ADDITIONAL_BYTES = (MAX(sizeof(PRIdMAX),
1123                                         MAX(sizeof(PRIoMAX),
1124                                             MAX(sizeof(PRIuMAX),
1125                                                 sizeof(PRIxMAX)))) - 1)
1126         };
1127         size_t n_alloc;
1128         char *dest;
1129         char const *b;
1130         int rc = 0;
1131
1132         if (o_quiet)
1133                 return 0;
1134
1135         n_alloc = strlen(format) + MAX_ADDITIONAL_BYTES + 1;
1136         dest = malloc(n_alloc);
1137         if (dest == NULL)
1138                 return -ENOMEM;
1139
1140         for (b = format; *b; b++) {
1141                 switch (*b) {
1142                 case '%': {
1143                         size_t len = format_code_offset(b);
1144                         char const *fmt_char = b + len;
1145                         int ret;
1146
1147                         memcpy(dest, b, len);
1148                         b += len;
1149
1150                         switch (*fmt_char) {
1151                         case '\0':
1152                                 --b;
1153                         case '%':
1154                                 if (len > 1) {
1155                                         dest[len] = *fmt_char;
1156                                         dest[len + 1] = '\0';
1157                                         printf("%s: invalid directive", dest);
1158                                         return -EINVAL;
1159                                 }
1160                                 putchar('%');
1161                                 break;
1162                         default:
1163                                 ret = print_func(dest, len, to_uchar(*fmt_char),
1164                                                  fd, filename, data);
1165                                 if (rc == 0 && ret)
1166                                         rc = ret;
1167                                 break;
1168                         }
1169                         break;
1170                 }
1171                 case '\\':
1172                         if (!interpret_backslash_escapes) {
1173                                 putchar ('\\');
1174                                 break;
1175                         }
1176                         ++b;
1177                         if (isodigit(*b)) {
1178                                 int esc_value = octtobin(*b);
1179                                 int esc_length = 1; /* number of octal digits */
1180
1181                                 for (++b; esc_length < 3 && isodigit(*b);
1182                                      ++esc_length, ++b) {
1183                                         esc_value = esc_value * 8 +
1184                                                     octtobin(*b);
1185                                 }
1186                                 putchar(esc_value);
1187                                 --b;
1188                         } else if (*b == 'x' && isxdigit(to_uchar(b[1]))) {
1189                                 /* Value of \xhh escape. */
1190                                 int esc_value = hextobin(b[1]);
1191                                 /* A hexadecimal \xhh escape sequence must have
1192                                  * 1 or 2 hex. digits.
1193                                  */
1194
1195                                 ++b;
1196                                 if (isxdigit(to_uchar(b[1]))) {
1197                                         ++b;
1198                                         esc_value = esc_value * 16 +
1199                                                     hextobin(*b);
1200                                 }
1201                                 putchar(esc_value);
1202                         } else if (*b == '\0') {
1203                                 printf("warning: backslash at end of format");
1204                                 putchar('\\');
1205                                 /* Arrange to exit the loop.  */
1206                                 --b;
1207                         } else {
1208                                 print_esc_char(*b);
1209                         }
1210                         break;
1211
1212                 default:
1213                         putchar(*b);
1214                         break;
1215                 }
1216         }
1217         free(dest);
1218
1219         fputs(trailing_delim, stdout);
1220
1221         return rc;
1222 }
1223
1224 /* Return an allocated format string in static storage that
1225  * corresponds to whether FS and TERSE options were declared.
1226  */
1227 static char *default_format(bool fs, bool terse, bool device)
1228 {
1229         char *format;
1230
1231         if (fs) {
1232                 if (terse) {
1233                         format = xstrdup(fmt_terse_fs);
1234                 } else {
1235                         /* TRANSLATORS: This string uses format specifiers from
1236                          * 'stat --help' with --file-system, and NOT from
1237                          * printf.
1238                          */
1239                         format = xstrdup(
1240                         "  File: \"%n\"\n"
1241                         "    ID: %-8i Namelen: %-7l Type: %T\n"
1242                         "Block size: %-10s Fundamental block size: %S\n"
1243                         "Blocks: Total: %-10b Free: %-10f Available: %a\n"
1244                         "Inodes: Total: %-10c Free: %d\n");
1245                 }
1246         } else /* ! fs */ {
1247                 if (terse) {
1248 #ifdef HAVE_SELINUX
1249                         if (is_selinux_enabled() > 0)
1250                                 format = xstrdup(fmt_terse_selinux);
1251                         else
1252 #endif
1253                                 format = xstrdup(fmt_terse_regular);
1254                 } else {
1255                         char *temp;
1256
1257                         /* TRANSLATORS: This string uses format specifiers from
1258                          * 'stat --help' without --file-system, and NOT from
1259                          * printf.
1260                          */
1261                         format = xstrdup("\
1262   File: %N\n\
1263   Size: %-10s\tBlocks: %-10b IO Block: %-6o %F\n\
1264 ");
1265
1266                         temp = format;
1267                         if (device) {
1268                                 /* TRANSLATORS: This string uses format
1269                                  * specifiers from 'stat --help' without
1270                                  * --file-system, and NOT from printf.
1271                                  */
1272                                 format = xasprintf("%s%s", format, "\
1273 " "Device: %Dh/%dd\tInode: %-10i  Links: %-5h Device type: %t,%T\n\
1274 ");
1275                         } else {
1276                                 /* TRANSLATORS: This string uses format
1277                                  * specifiers from 'stat --help' without
1278                                  * --file-system, and NOT from printf.
1279                                  */
1280                                 format = xasprintf("%s%s", format, "\
1281 " "Device: %Dh/%dd\tInode: %-10i  Links: %h\n\
1282 ");
1283                         }
1284                         free(temp);
1285
1286                         temp = format;
1287                         /* TRANSLATORS: This string uses format specifiers from
1288                          * 'stat --help' without --file-system, and NOT from
1289                          * printf.
1290                          */
1291                         format = xasprintf("%s%s", format, "\
1292 " "Access: (%04a/%10.10A)  Uid: (%5u/%8U)   Gid: (%5g/%8G)\n\
1293 ");
1294                         free(temp);
1295
1296 #ifdef HAVE_SELINUX
1297                         if (is_selinux_enabled() > 0) {
1298                                 temp = format;
1299                                 /* TRANSLATORS: This string uses format
1300                                  * specifiers from 'stat --help' without
1301                                  * --file-system, and NOT from printf.
1302                                  */
1303                                 format = xasprintf("%s%s", format,
1304                                                    "Context: %C\n");
1305                                 free(temp);
1306                         }
1307 #endif
1308                         temp = format;
1309                         /* TRANSLATORS: This string uses format specifiers from
1310                          * 'stat --help' without --file-system, and NOT from
1311                          * printf.
1312                          */
1313                         format = xasprintf("%s%s", format,
1314                                            "Access: %x\n"
1315                                            "Modify: %y\n"
1316                                            "Change: %z\n"
1317                                            " Birth: %w\n");
1318                         free(temp);
1319                 }
1320         }
1321         return format;
1322 }
1323
1324 static char *list_long_format(void)
1325 {
1326         char *format;
1327
1328         format = xstrdup("\
1329 " "%10.10A %h %8U %8G %-10s %y %N\
1330 ");
1331
1332         return format;
1333 }
1334
1335 static int do_statx(char const *filename, unsigned int request_mask, int flags)
1336 {
1337         const char *pathname = filename;
1338         struct statx stx = { 0, };
1339         int fd;
1340
1341         if (strcmp(filename, "-") == 0)
1342                 fd = 0;
1343         else
1344                 fd = AT_FDCWD;
1345
1346         if (fd != AT_FDCWD) {
1347                 pathname = "";
1348                 flags |= AT_EMPTY_PATH;
1349         }
1350
1351         fd = statx(fd, pathname, flags, request_mask, &stx);
1352         if (fd < 0) {
1353                 if (flags & AT_EMPTY_PATH)
1354                         printf("cannot stat standard input\n");
1355                 else
1356                         printf("cannot statx %s: %s\n",
1357                                filename, strerror(errno));
1358
1359                 return -errno;
1360         }
1361
1362         return print_it(fd, filename, print_statx, &stx);
1363 }
1364
1365 /* Return true if FILE should be ignored. */
1366 static bool file_ignored(char const *name)
1367 {
1368         return name[0] == '.';
1369 }
1370
1371 static int do_dir_list(char const *dirname, unsigned int request_mask,
1372                        int flags)
1373 {
1374         DIR *dir;
1375         struct dirent *ent;
1376         char fullname[PATH_MAX];
1377         size_t size = sizeof(fullname);
1378         int namelen;
1379         int rc = 0;
1380
1381         dir = opendir(dirname);
1382         if (!dir) {
1383                 rc = -errno;
1384                 printf("lsx: cannot open directory '%s': %s\n",
1385                        dirname, strerror(errno));
1386                 return rc;
1387         }
1388
1389         while ((ent = readdir(dir)) != NULL) {
1390                 int ret;
1391
1392                 /* skip "." and ".." */
1393                 if (file_ignored(ent->d_name))
1394                         continue;
1395
1396                 /* ls -1 */
1397                 if (!format) {
1398                         if (o_quiet)
1399                                 continue;
1400
1401                         printf("%s", ent->d_name);
1402                         putchar('\n');
1403                 } else {
1404                         if (strlen(ent->d_name) + strlen(dirname) + 1 >=
1405                             sizeof(fullname)) {
1406                                 errno = ENAMETOOLONG;
1407                                 fprintf(stderr,
1408                                         "lsx: ignored too long path: %s/%s\n",
1409                                         dirname, ent->d_name);
1410                                 if (!rc)
1411                                         rc = -ENAMETOOLONG;
1412                                 continue;
1413                         }
1414                         namelen = snprintf(fullname, size, "%s/%s",
1415                                            dirname, ent->d_name);
1416                         if (namelen >= size)
1417                                 fullname[size - 1] = '\0';
1418
1419                         ret = do_statx(fullname, request_mask, flags);
1420                         if (!ret)
1421                                 putchar('\n');
1422                         else if (rc == 0)
1423                                 rc = ret;
1424                 }
1425         }
1426
1427         closedir(dir);
1428         return rc;
1429 }
1430
1431 int main(int argc, char **argv)
1432 {
1433         static struct option options[] = {
1434                 {"dereference", no_argument, NULL, 'L'},
1435                 {"format", required_argument, NULL, 'c'},
1436                 {"printf", required_argument, NULL, PRINTF_OPTION},
1437                 {"terse", no_argument, NULL, 't'},
1438                 {"cached", required_argument, NULL, 0},
1439                 {"dir", no_argument, NULL, 'D'},
1440                 {"long-format", no_argument, NULL, 'l'},
1441                 {"quiet", no_argument, NULL, 'q'},
1442                 {"help", no_argument, NULL, GETOPT_HELP_CHAR},
1443                 {"version", no_argument, NULL, GETOPT_VERSION_CHAR},
1444                 {NULL, 0, NULL, 0}
1445         };
1446         bool terse = false;
1447         unsigned int request_mask;
1448         int flags = AT_SYMLINK_NOFOLLOW;
1449         struct lconv const *locale = localeconv();
1450         int c;
1451         int rc = 0;
1452         int i = 0;
1453
1454         decimal_point = locale->decimal_point[0] ? locale->decimal_point : ".";
1455         decimal_point_len = strlen(decimal_point);
1456         current_time.tv_sec = TYPE_MINIMUM(time_t);
1457         current_time.tv_nsec = -1;
1458
1459         while ((c = getopt_long(argc, argv, "c:DqLlt", options, NULL)) != EOF) {
1460                 switch (c) {
1461                 case 'L':
1462                         flags &= ~AT_SYMLINK_NOFOLLOW;
1463                         follow_links = true;
1464                         break;
1465                 case PRINTF_OPTION:
1466                         format = optarg;
1467                         interpret_backslash_escapes = true;
1468                         trailing_delim = "";
1469                         break;
1470                 case 'c':
1471                         format = optarg;
1472                         interpret_backslash_escapes = false;
1473                         trailing_delim = "\n";
1474                         break;
1475                 case 'q':
1476                         o_quiet = true;
1477                         break;
1478                 case 'l':
1479                         o_dir_list = true;
1480                         long_format = true;
1481                         break;
1482                 case 'D':
1483                         o_dir_list = true;
1484                         break;
1485                 case 't':
1486                         terse = true;
1487                         break;
1488                 case 0:
1489                         if (strcmp(optarg, "never") == 0) {
1490                                 flags &= ~AT_STATX_SYNC_TYPE;
1491                                 flags |= AT_STATX_FORCE_SYNC;
1492                         } else if (strcmp(optarg, "always") == 0) {
1493                                 flags &= ~AT_STATX_SYNC_TYPE;
1494                                 flags |= AT_STATX_DONT_SYNC;
1495                         } else if (strcmp(optarg, "default") == 0) {
1496                                 flags &= ~AT_STATX_SYNC_TYPE;
1497                                 flags |= AT_SYMLINK_NOFOLLOW;
1498                         } else {
1499                                 printf("%s: invalid cached mode: %s\n",
1500                                        argv[0], optarg);
1501                                 return -EINVAL;
1502                         }
1503                         break;
1504                 case GETOPT_HELP_CHAR:
1505                         usage(argv[0]);
1506                 case GETOPT_VERSION_CHAR:
1507                         if (!o_quiet)
1508                                 printf("Lustre statx: version 0.1\n");
1509                         return 0;
1510                 default:
1511                         printf("%s: unknown option '-%c'\n",
1512                                argv[0], optopt);
1513                         return -EINVAL;
1514                 }
1515         }
1516
1517         if (format) {
1518                 request_mask = format_to_mask(format);
1519         } else {
1520                 request_mask = STATX_ALL;
1521                 if (o_dir_list)
1522                         format = long_format ? list_long_format() : NULL;
1523                 else
1524                         format = default_format(false, terse, false);
1525         }
1526
1527         if (optind == argc) {
1528                 if (o_dir_list)
1529                         return do_dir_list(".", request_mask, flags);
1530
1531                 printf("statx: missing operand\n"
1532                        "Try 'stat --help' for more information.\n");
1533                 return 0;
1534         }
1535
1536         for (i = optind; i < argc; i++) {
1537                 int ret;
1538
1539                 if (o_dir_list)
1540                         ret = do_dir_list(argv[i], request_mask, flags);
1541                 else
1542                         ret = do_statx(argv[i], request_mask, flags);
1543
1544                 if (rc == 0 && ret)
1545                         rc = ret;
1546         }
1547
1548         return rc;
1549 }
1550 #else
1551 int main(int argc, char **argv)
1552 {
1553         static struct option options[] = {
1554                 {"version", no_argument, NULL, GETOPT_VERSION_CHAR},
1555                 {"quiet", no_argument, NULL, 'q'},
1556                 {NULL, 0, NULL, 0}
1557         };
1558         int c;
1559
1560         while ((c = getopt_long(argc, argv, "q", options, NULL)) != EOF) {
1561                 switch (c) {
1562                 case 'q':
1563                         o_quiet = true;
1564                         break;
1565                 case GETOPT_VERSION_CHAR:
1566                         if (!o_quiet)
1567                                 printf("statx: Not support statx() syscall\n");
1568                         return -ENOTSUP;
1569                 }
1570         }
1571         printf("Skip: system does not support statx syscall.\n");
1572         return 0;
1573 }
1574 #endif /* __NR_statx */