maint: remove unnecessary inttostr usage in printf
[coreutils.git] / src / ls.c
blobf7ffe1086ef188afebf403c2634abd9486ead7d2
1 /* 'dir', 'vdir' and 'ls' directory listing programs for GNU.
2 Copyright (C) 1985-2024 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 /* If ls_mode is LS_MULTI_COL,
18 the multi-column format is the default regardless
19 of the type of output device.
20 This is for the 'dir' program.
22 If ls_mode is LS_LONG_FORMAT,
23 the long format is the default regardless of the
24 type of output device.
25 This is for the 'vdir' program.
27 If ls_mode is LS_LS,
28 the output format depends on whether the output
29 device is a terminal.
30 This is for the 'ls' program. */
32 /* Written by Richard Stallman and David MacKenzie. */
34 /* Color support by Peter Anvin <Peter.Anvin@linux.org> and Dennis
35 Flaherty <dennisf@denix.elk.miles.com> based on original patches by
36 Greg Lee <lee@uhunix.uhcc.hawaii.edu>. */
38 #include <config.h>
39 #include <ctype.h>
40 #include <sys/types.h>
42 #include <termios.h>
43 #if HAVE_STROPTS_H
44 # include <stropts.h>
45 #endif
46 #include <sys/ioctl.h>
48 #ifdef WINSIZE_IN_PTEM
49 # include <sys/stream.h>
50 # include <sys/ptem.h>
51 #endif
53 #include <stdio.h>
54 #include <setjmp.h>
55 #include <pwd.h>
56 #include <getopt.h>
57 #include <signal.h>
58 #include <selinux/selinux.h>
59 #include <uchar.h>
61 #if HAVE_LANGINFO_CODESET
62 # include <langinfo.h>
63 #endif
65 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
66 present. */
67 #ifndef SA_NOCLDSTOP
68 # define SA_NOCLDSTOP 0
69 # define sigprocmask(How, Set, Oset) /* empty */
70 # define sigset_t int
71 # if ! HAVE_SIGINTERRUPT
72 # define siginterrupt(sig, flag) /* empty */
73 # endif
74 #endif
76 /* NonStop circa 2011 lacks both SA_RESTART and siginterrupt, so don't
77 restart syscalls after a signal handler fires. This may cause
78 colors to get messed up on the screen if 'ls' is interrupted, but
79 that's the best we can do on such a platform. */
80 #ifndef SA_RESTART
81 # define SA_RESTART 0
82 #endif
84 #include "system.h"
85 #include <fnmatch.h>
87 #include "acl.h"
88 #include "argmatch.h"
89 #include "assure.h"
90 #include "c-strcase.h"
91 #include "dev-ino.h"
92 #include "filenamecat.h"
93 #include "hard-locale.h"
94 #include "hash.h"
95 #include "human.h"
96 #include "filemode.h"
97 #include "filevercmp.h"
98 #include "idcache.h"
99 #include "ls.h"
100 #include "mbswidth.h"
101 #include "mpsort.h"
102 #include "obstack.h"
103 #include "quote.h"
104 #include "smack.h"
105 #include "stat-size.h"
106 #include "stat-time.h"
107 #include "strftime.h"
108 #include "xdectoint.h"
109 #include "xstrtol.h"
110 #include "xstrtol-error.h"
111 #include "areadlink.h"
112 #include "dircolors.h"
113 #include "xgethostname.h"
114 #include "c-ctype.h"
115 #include "canonicalize.h"
116 #include "statx.h"
118 /* Include <sys/capability.h> last to avoid a clash of <sys/types.h>
119 include guards with some premature versions of libcap.
120 For more details, see <https://bugzilla.redhat.com/483548>. */
121 #ifdef HAVE_CAP
122 # include <sys/capability.h>
123 #endif
125 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
126 : (ls_mode == LS_MULTI_COL \
127 ? "dir" : "vdir"))
129 #define AUTHORS \
130 proper_name ("Richard M. Stallman"), \
131 proper_name ("David MacKenzie")
133 #define obstack_chunk_alloc malloc
134 #define obstack_chunk_free free
136 /* Unix-based readdir implementations have historically returned a dirent.d_ino
137 value that is sometimes not equal to the stat-obtained st_ino value for
138 that same entry. This error occurs for a readdir entry that refers
139 to a mount point. readdir's error is to return the inode number of
140 the underlying directory -- one that typically cannot be stat'ed, as
141 long as a file system is mounted on that directory. RELIABLE_D_INO
142 encapsulates whether we can use the more efficient approach of relying
143 on readdir-supplied d_ino values, or whether we must incur the cost of
144 calling stat or lstat to obtain each guaranteed-valid inode number. */
146 #ifndef READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
147 # define READDIR_LIES_ABOUT_MOUNTPOINT_D_INO 1
148 #endif
150 #if READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
151 # define RELIABLE_D_INO(dp) NOT_AN_INODE_NUMBER
152 #else
153 # define RELIABLE_D_INO(dp) D_INO (dp)
154 #endif
156 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
157 # define st_author st_uid
158 #endif
160 enum filetype
162 unknown,
163 fifo,
164 chardev,
165 directory,
166 blockdev,
167 normal,
168 symbolic_link,
169 sock,
170 whiteout,
171 arg_directory
174 /* Display letters and indicators for each filetype.
175 Keep these in sync with enum filetype. */
176 static char const filetype_letter[] = "?pcdb-lswd";
178 /* Ensure that filetype and filetype_letter have the same
179 number of elements. */
180 static_assert (sizeof filetype_letter - 1 == arg_directory + 1);
182 #define FILETYPE_INDICATORS \
184 C_ORPHAN, C_FIFO, C_CHR, C_DIR, C_BLK, C_FILE, \
185 C_LINK, C_SOCK, C_FILE, C_DIR \
188 enum acl_type
190 ACL_T_NONE,
191 ACL_T_LSM_CONTEXT_ONLY,
192 ACL_T_YES
195 struct fileinfo
197 /* The file name. */
198 char *name;
200 /* For symbolic link, name of the file linked to, otherwise zero. */
201 char *linkname;
203 /* For terminal hyperlinks. */
204 char *absolute_name;
206 struct stat stat;
208 enum filetype filetype;
210 /* For symbolic link and long listing, st_mode of file linked to, otherwise
211 zero. */
212 mode_t linkmode;
214 /* security context. */
215 char *scontext;
217 bool stat_ok;
219 /* For symbolic link and color printing, true if linked-to file
220 exists, otherwise false. */
221 bool linkok;
223 /* For long listings, true if the file has an access control list,
224 or a security context. */
225 enum acl_type acl_type;
227 /* For color listings, true if a regular file has capability info. */
228 bool has_capability;
230 /* Whether file name needs quoting. tri-state with -1 == unknown. */
231 int quoted;
233 /* Cached screen width (including quoting). */
234 size_t width;
237 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
239 /* Null is a valid character in a color indicator (think about Epson
240 printers, for example) so we have to use a length/buffer string
241 type. */
243 struct bin_str
245 size_t len; /* Number of bytes */
246 char const *string; /* Pointer to the same */
249 #if ! HAVE_TCGETPGRP
250 # define tcgetpgrp(Fd) 0
251 #endif
253 static size_t quote_name (char const *name,
254 struct quoting_options const *options,
255 int needs_general_quoting,
256 const struct bin_str *color,
257 bool allow_pad, struct obstack *stack,
258 char const *absolute_name);
259 static size_t quote_name_buf (char **inbuf, size_t bufsize, char *name,
260 struct quoting_options const *options,
261 int needs_general_quoting, size_t *width,
262 bool *pad);
263 static int decode_switches (int argc, char **argv);
264 static bool file_ignored (char const *name);
265 static uintmax_t gobble_file (char const *name, enum filetype type,
266 ino_t inode, bool command_line_arg,
267 char const *dirname);
268 static const struct bin_str * get_color_indicator (const struct fileinfo *f,
269 bool symlink_target);
270 static bool print_color_indicator (const struct bin_str *ind);
271 static void put_indicator (const struct bin_str *ind);
272 static void add_ignore_pattern (char const *pattern);
273 static void attach (char *dest, char const *dirname, char const *name);
274 static void clear_files (void);
275 static void extract_dirs_from_files (char const *dirname,
276 bool command_line_arg);
277 static void get_link_name (char const *filename, struct fileinfo *f,
278 bool command_line_arg);
279 static void indent (size_t from, size_t to);
280 static size_t calculate_columns (bool by_columns);
281 static void print_current_files (void);
282 static void print_dir (char const *name, char const *realname,
283 bool command_line_arg);
284 static size_t print_file_name_and_frills (const struct fileinfo *f,
285 size_t start_col);
286 static void print_horizontal (void);
287 static int format_user_width (uid_t u);
288 static int format_group_width (gid_t g);
289 static void print_long_format (const struct fileinfo *f);
290 static void print_many_per_line (void);
291 static size_t print_name_with_quoting (const struct fileinfo *f,
292 bool symlink_target,
293 struct obstack *stack,
294 size_t start_col);
295 static void prep_non_filename_text (void);
296 static bool print_type_indicator (bool stat_ok, mode_t mode,
297 enum filetype type);
298 static void print_with_separator (char sep);
299 static void queue_directory (char const *name, char const *realname,
300 bool command_line_arg);
301 static void sort_files (void);
302 static void parse_ls_color (void);
304 static int getenv_quoting_style (void);
306 static size_t quote_name_width (char const *name,
307 struct quoting_options const *options,
308 int needs_general_quoting);
310 /* Initial size of hash table.
311 Most hierarchies are likely to be shallower than this. */
312 enum { INITIAL_TABLE_SIZE = 30 };
314 /* The set of 'active' directories, from the current command-line argument
315 to the level in the hierarchy at which files are being listed.
316 A directory is represented by its device and inode numbers (struct dev_ino).
317 A directory is added to this set when ls begins listing it or its
318 entries, and it is removed from the set just after ls has finished
319 processing it. This set is used solely to detect loops, e.g., with
320 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
321 static Hash_table *active_dir_set;
323 #define LOOP_DETECT (!!active_dir_set)
325 /* The table of files in the current directory:
327 'cwd_file' points to a vector of 'struct fileinfo', one per file.
328 'cwd_n_alloc' is the number of elements space has been allocated for.
329 'cwd_n_used' is the number actually in use. */
331 /* Address of block containing the files that are described. */
332 static struct fileinfo *cwd_file;
334 /* Length of block that 'cwd_file' points to, measured in files. */
335 static size_t cwd_n_alloc;
337 /* Index of first unused slot in 'cwd_file'. */
338 static size_t cwd_n_used;
340 /* Whether files needs may need padding due to quoting. */
341 static bool cwd_some_quoted;
343 /* Whether quoting style _may_ add outer quotes,
344 and whether aligning those is useful. */
345 static bool align_variable_outer_quotes;
347 /* Vector of pointers to files, in proper sorted order, and the number
348 of entries allocated for it. */
349 static void **sorted_file;
350 static size_t sorted_file_alloc;
352 /* When true, in a color listing, color each symlink name according to the
353 type of file it points to. Otherwise, color them according to the 'ln'
354 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
355 regardless. This is set when 'ln=target' appears in LS_COLORS. */
357 static bool color_symlink_as_referent;
359 static char const *hostname;
361 /* Mode of appropriate file for coloring. */
362 static mode_t
363 file_or_link_mode (struct fileinfo const *file)
365 return (color_symlink_as_referent && file->linkok
366 ? file->linkmode : file->stat.st_mode);
370 /* Record of one pending directory waiting to be listed. */
372 struct pending
374 char *name;
375 /* If the directory is actually the file pointed to by a symbolic link we
376 were told to list, 'realname' will contain the name of the symbolic
377 link, otherwise zero. */
378 char *realname;
379 bool command_line_arg;
380 struct pending *next;
383 static struct pending *pending_dirs;
385 /* Current time in seconds and nanoseconds since 1970, updated as
386 needed when deciding whether a file is recent. */
388 static struct timespec current_time;
390 static bool print_scontext;
391 static char UNKNOWN_SECURITY_CONTEXT[] = "?";
393 /* Whether any of the files has an ACL. This affects the width of the
394 mode column. */
396 static bool any_has_acl;
398 /* The number of columns to use for columns containing inode numbers,
399 block sizes, link counts, owners, groups, authors, major device
400 numbers, minor device numbers, and file sizes, respectively. */
402 static int inode_number_width;
403 static int block_size_width;
404 static int nlink_width;
405 static int scontext_width;
406 static int owner_width;
407 static int group_width;
408 static int author_width;
409 static int major_device_number_width;
410 static int minor_device_number_width;
411 static int file_size_width;
413 /* Option flags */
415 /* long_format for lots of info, one per line.
416 one_per_line for just names, one per line.
417 many_per_line for just names, many per line, sorted vertically.
418 horizontal for just names, many per line, sorted horizontally.
419 with_commas for just names, many per line, separated by commas.
421 -l (and other options that imply -l), -1, -C, -x and -m control
422 this parameter. */
424 enum format
426 long_format, /* -l and other options that imply -l */
427 one_per_line, /* -1 */
428 many_per_line, /* -C */
429 horizontal, /* -x */
430 with_commas /* -m */
433 static enum format format;
435 /* 'full-iso' uses full ISO-style dates and times. 'long-iso' uses longer
436 ISO-style timestamps, though shorter than 'full-iso'. 'iso' uses shorter
437 ISO-style timestamps. 'locale' uses locale-dependent timestamps. */
438 enum time_style
440 full_iso_time_style, /* --time-style=full-iso */
441 long_iso_time_style, /* --time-style=long-iso */
442 iso_time_style, /* --time-style=iso */
443 locale_time_style /* --time-style=locale */
446 static char const *const time_style_args[] =
448 "full-iso", "long-iso", "iso", "locale", nullptr
450 static enum time_style const time_style_types[] =
452 full_iso_time_style, long_iso_time_style, iso_time_style,
453 locale_time_style
455 ARGMATCH_VERIFY (time_style_args, time_style_types);
457 /* Type of time to print or sort by. Controlled by -c and -u.
458 The values of each item of this enum are important since they are
459 used as indices in the sort functions array (see sort_files()). */
461 enum time_type
463 time_mtime = 0, /* default */
464 time_ctime, /* -c */
465 time_atime, /* -u */
466 time_btime, /* birth time */
467 time_numtypes /* the number of elements of this enum */
470 static enum time_type time_type;
471 static bool explicit_time;
473 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v.
474 The values of each item of this enum are important since they are
475 used as indices in the sort functions array (see sort_files()). */
477 enum sort_type
479 sort_name = 0, /* default */
480 sort_extension, /* -X */
481 sort_width,
482 sort_size, /* -S */
483 sort_version, /* -v */
484 sort_time, /* -t; must be second to last */
485 sort_none, /* -U; must be last */
486 sort_numtypes /* the number of elements of this enum */
489 static enum sort_type sort_type;
491 /* Direction of sort.
492 false means highest first if numeric,
493 lowest first if alphabetic;
494 these are the defaults.
495 true means the opposite order in each case. -r */
497 static bool sort_reverse;
499 /* True means to display owner information. -g turns this off. */
501 static bool print_owner = true;
503 /* True means to display author information. */
505 static bool print_author;
507 /* True means to display group information. -G and -o turn this off. */
509 static bool print_group = true;
511 /* True means print the user and group id's as numbers rather
512 than as names. -n */
514 static bool numeric_ids;
516 /* True means mention the size in blocks of each file. -s */
518 static bool print_block_size;
520 /* Human-readable options for output, when printing block counts. */
521 static int human_output_opts;
523 /* The units to use when printing block counts. */
524 static uintmax_t output_block_size;
526 /* Likewise, but for file sizes. */
527 static int file_human_output_opts;
528 static uintmax_t file_output_block_size = 1;
530 /* Follow the output with a special string. Using this format,
531 Emacs' dired mode starts up twice as fast, and can handle all
532 strange characters in file names. */
533 static bool dired;
535 /* 'none' means don't mention the type of files.
536 'slash' means mention directories only, with a '/'.
537 'file_type' means mention file types.
538 'classify' means mention file types and mark executables.
540 Controlled by -F, -p, and --indicator-style. */
542 enum indicator_style
544 none = 0, /* --indicator-style=none (default) */
545 slash, /* -p, --indicator-style=slash */
546 file_type, /* --indicator-style=file-type */
547 classify /* -F, --indicator-style=classify */
550 static enum indicator_style indicator_style;
552 /* Names of indicator styles. */
553 static char const *const indicator_style_args[] =
555 "none", "slash", "file-type", "classify", nullptr
557 static enum indicator_style const indicator_style_types[] =
559 none, slash, file_type, classify
561 ARGMATCH_VERIFY (indicator_style_args, indicator_style_types);
563 /* True means use colors to mark types. Also define the different
564 colors as well as the stuff for the LS_COLORS environment variable.
565 The LS_COLORS variable is now in a termcap-like format. */
567 static bool print_with_color;
569 static bool print_hyperlink;
571 /* Whether we used any colors in the output so far. If so, we will
572 need to restore the default color later. If not, we will need to
573 call prep_non_filename_text before using color for the first time. */
575 static bool used_color = false;
577 enum when_type
579 when_never, /* 0: default or --color=never */
580 when_always, /* 1: --color=always */
581 when_if_tty /* 2: --color=tty */
584 enum Dereference_symlink
586 DEREF_UNDEFINED = 0, /* default */
587 DEREF_NEVER,
588 DEREF_COMMAND_LINE_ARGUMENTS, /* -H */
589 DEREF_COMMAND_LINE_SYMLINK_TO_DIR, /* the default, in certain cases */
590 DEREF_ALWAYS /* -L */
593 enum indicator_no
595 C_LEFT, C_RIGHT, C_END, C_RESET, C_NORM, C_FILE, C_DIR, C_LINK,
596 C_FIFO, C_SOCK,
597 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR, C_SETUID, C_SETGID,
598 C_STICKY, C_OTHER_WRITABLE, C_STICKY_OTHER_WRITABLE, C_CAP, C_MULTIHARDLINK,
599 C_CLR_TO_EOL
602 static char const *const indicator_name[]=
604 "lc", "rc", "ec", "rs", "no", "fi", "di", "ln", "pi", "so",
605 "bd", "cd", "mi", "or", "ex", "do", "su", "sg", "st",
606 "ow", "tw", "ca", "mh", "cl", nullptr
609 struct color_ext_type
611 struct bin_str ext; /* The extension we're looking for */
612 struct bin_str seq; /* The sequence to output when we do */
613 bool exact_match; /* Whether to compare case insensitively */
614 struct color_ext_type *next; /* Next in list */
617 static struct bin_str color_indicator[] =
619 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
620 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
621 { 0, nullptr }, /* ec: End color (replaces lc+rs+rc) */
622 { LEN_STR_PAIR ("0") }, /* rs: Reset to ordinary colors */
623 { 0, nullptr }, /* no: Normal */
624 { 0, nullptr }, /* fi: File: default */
625 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
626 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
627 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
628 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
629 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
630 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
631 { 0, nullptr }, /* mi: Missing file: undefined */
632 { 0, nullptr }, /* or: Orphaned symlink: undefined */
633 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
634 { LEN_STR_PAIR ("01;35") }, /* do: Door: bright magenta */
635 { LEN_STR_PAIR ("37;41") }, /* su: setuid: white on red */
636 { LEN_STR_PAIR ("30;43") }, /* sg: setgid: black on yellow */
637 { LEN_STR_PAIR ("37;44") }, /* st: sticky: black on blue */
638 { LEN_STR_PAIR ("34;42") }, /* ow: other-writable: blue on green */
639 { LEN_STR_PAIR ("30;42") }, /* tw: ow w/ sticky: black on green */
640 { 0, nullptr }, /* ca: disabled by default */
641 { 0, nullptr }, /* mh: disabled by default */
642 { LEN_STR_PAIR ("\033[K") }, /* cl: clear to end of line */
645 /* A list mapping file extensions to corresponding display sequence. */
646 static struct color_ext_type *color_ext_list = nullptr;
648 /* Buffer for color sequences */
649 static char *color_buf;
651 /* True means to check for orphaned symbolic link, for displaying
652 colors, or to group symlink to directories with other dirs. */
654 static bool check_symlink_mode;
656 /* True means mention the inode number of each file. -i */
658 static bool print_inode;
660 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
661 other options that imply -l), and -L. */
663 static enum Dereference_symlink dereference;
665 /* True means when a directory is found, display info on its
666 contents. -R */
668 static bool recursive;
670 /* True means when an argument is a directory name, display info
671 on it itself. -d */
673 static bool immediate_dirs;
675 /* True means that directories are grouped before files. */
677 static bool directories_first;
679 /* Which files to ignore. */
681 static enum
683 /* Ignore files whose names start with '.', and files specified by
684 --hide and --ignore. */
685 IGNORE_DEFAULT = 0,
687 /* Ignore '.', '..', and files specified by --ignore. */
688 IGNORE_DOT_AND_DOTDOT,
690 /* Ignore only files specified by --ignore. */
691 IGNORE_MINIMAL
692 } ignore_mode;
694 /* A linked list of shell-style globbing patterns. If a non-argument
695 file name matches any of these patterns, it is ignored.
696 Controlled by -I. Multiple -I options accumulate.
697 The -B option adds '*~' and '.*~' to this list. */
699 struct ignore_pattern
701 char const *pattern;
702 struct ignore_pattern *next;
705 static struct ignore_pattern *ignore_patterns;
707 /* Similar to IGNORE_PATTERNS, except that -a or -A causes this
708 variable itself to be ignored. */
709 static struct ignore_pattern *hide_patterns;
711 /* True means output nongraphic chars in file names as '?'.
712 (-q, --hide-control-chars)
713 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
714 independent. The algorithm is: first, obey the quoting style to get a
715 string representing the file name; then, if qmark_funny_chars is set,
716 replace all nonprintable chars in that string with '?'. It's necessary
717 to replace nonprintable chars even in quoted strings, because we don't
718 want to mess up the terminal if control chars get sent to it, and some
719 quoting methods pass through control chars as-is. */
720 static bool qmark_funny_chars;
722 /* Quoting options for file and dir name output. */
724 static struct quoting_options *filename_quoting_options;
725 static struct quoting_options *dirname_quoting_options;
727 /* The number of chars per hardware tab stop. Setting this to zero
728 inhibits the use of TAB characters for separating columns. -T */
729 static size_t tabsize;
731 /* True means print each directory name before listing it. */
733 static bool print_dir_name;
735 /* The line length to use for breaking lines in many-per-line format.
736 Can be set with -w. If zero, there is no limit. */
738 static size_t line_length;
740 /* The local time zone rules, as per the TZ environment variable. */
742 static timezone_t localtz;
744 /* If true, the file listing format requires that stat be called on
745 each file. */
747 static bool format_needs_stat;
749 /* Similar to 'format_needs_stat', but set if only the file type is
750 needed. */
752 static bool format_needs_type;
754 /* An arbitrary limit on the number of bytes in a printed timestamp.
755 This is set to a relatively small value to avoid the need to worry
756 about denial-of-service attacks on servers that run "ls" on behalf
757 of remote clients. 1000 bytes should be enough for any practical
758 timestamp format. */
760 enum { TIME_STAMP_LEN_MAXIMUM = MAX (1000, INT_STRLEN_BOUND (time_t)) };
762 /* strftime formats for non-recent and recent files, respectively, in
763 -l output. */
765 static char const *long_time_format[2] =
767 /* strftime format for non-recent files (older than 6 months), in
768 -l output. This should contain the year, month and day (at
769 least), in an order that is understood by people in your
770 locale's territory. Please try to keep the number of used
771 screen columns small, because many people work in windows with
772 only 80 columns. But make this as wide as the other string
773 below, for recent files. */
774 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
775 so be wary of using variable width fields from the locale.
776 Note %b is handled specially by ls and aligned correctly.
777 Note also that specifying a width as in %5b is erroneous as strftime
778 will count bytes rather than characters in multibyte locales. */
779 N_("%b %e %Y"),
780 /* strftime format for recent files (younger than 6 months), in -l
781 output. This should contain the month, day and time (at
782 least), in an order that is understood by people in your
783 locale's territory. Please try to keep the number of used
784 screen columns small, because many people work in windows with
785 only 80 columns. But make this as wide as the other string
786 above, for non-recent files. */
787 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
788 so be wary of using variable width fields from the locale.
789 Note %b is handled specially by ls and aligned correctly.
790 Note also that specifying a width as in %5b is erroneous as strftime
791 will count bytes rather than characters in multibyte locales. */
792 N_("%b %e %H:%M")
795 /* The set of signals that are caught. */
797 static sigset_t caught_signals;
799 /* If nonzero, the value of the pending fatal signal. */
801 static sig_atomic_t volatile interrupt_signal;
803 /* A count of the number of pending stop signals that have been received. */
805 static sig_atomic_t volatile stop_signal_count;
807 /* Desired exit status. */
809 static int exit_status;
811 /* Exit statuses. */
812 enum
814 /* "ls" had a minor problem. E.g., while processing a directory,
815 ls obtained the name of an entry via readdir, yet was later
816 unable to stat that name. This happens when listing a directory
817 in which entries are actively being removed or renamed. */
818 LS_MINOR_PROBLEM = 1,
820 /* "ls" had more serious trouble (e.g., memory exhausted, invalid
821 option or failure to stat a command line argument. */
822 LS_FAILURE = 2
825 /* For long options that have no equivalent short option, use a
826 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
827 enum
829 AUTHOR_OPTION = CHAR_MAX + 1,
830 BLOCK_SIZE_OPTION,
831 COLOR_OPTION,
832 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION,
833 FILE_TYPE_INDICATOR_OPTION,
834 FORMAT_OPTION,
835 FULL_TIME_OPTION,
836 GROUP_DIRECTORIES_FIRST_OPTION,
837 HIDE_OPTION,
838 HYPERLINK_OPTION,
839 INDICATOR_STYLE_OPTION,
840 QUOTING_STYLE_OPTION,
841 SHOW_CONTROL_CHARS_OPTION,
842 SI_OPTION,
843 SORT_OPTION,
844 TIME_OPTION,
845 TIME_STYLE_OPTION,
846 ZERO_OPTION,
849 static struct option const long_options[] =
851 {"all", no_argument, nullptr, 'a'},
852 {"escape", no_argument, nullptr, 'b'},
853 {"directory", no_argument, nullptr, 'd'},
854 {"dired", no_argument, nullptr, 'D'},
855 {"full-time", no_argument, nullptr, FULL_TIME_OPTION},
856 {"group-directories-first", no_argument, nullptr,
857 GROUP_DIRECTORIES_FIRST_OPTION},
858 {"human-readable", no_argument, nullptr, 'h'},
859 {"inode", no_argument, nullptr, 'i'},
860 {"kibibytes", no_argument, nullptr, 'k'},
861 {"numeric-uid-gid", no_argument, nullptr, 'n'},
862 {"no-group", no_argument, nullptr, 'G'},
863 {"hide-control-chars", no_argument, nullptr, 'q'},
864 {"reverse", no_argument, nullptr, 'r'},
865 {"size", no_argument, nullptr, 's'},
866 {"width", required_argument, nullptr, 'w'},
867 {"almost-all", no_argument, nullptr, 'A'},
868 {"ignore-backups", no_argument, nullptr, 'B'},
869 {"classify", optional_argument, nullptr, 'F'},
870 {"file-type", no_argument, nullptr, FILE_TYPE_INDICATOR_OPTION},
871 {"si", no_argument, nullptr, SI_OPTION},
872 {"dereference-command-line", no_argument, nullptr, 'H'},
873 {"dereference-command-line-symlink-to-dir", no_argument, nullptr,
874 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION},
875 {"hide", required_argument, nullptr, HIDE_OPTION},
876 {"ignore", required_argument, nullptr, 'I'},
877 {"indicator-style", required_argument, nullptr, INDICATOR_STYLE_OPTION},
878 {"dereference", no_argument, nullptr, 'L'},
879 {"literal", no_argument, nullptr, 'N'},
880 {"quote-name", no_argument, nullptr, 'Q'},
881 {"quoting-style", required_argument, nullptr, QUOTING_STYLE_OPTION},
882 {"recursive", no_argument, nullptr, 'R'},
883 {"format", required_argument, nullptr, FORMAT_OPTION},
884 {"show-control-chars", no_argument, nullptr, SHOW_CONTROL_CHARS_OPTION},
885 {"sort", required_argument, nullptr, SORT_OPTION},
886 {"tabsize", required_argument, nullptr, 'T'},
887 {"time", required_argument, nullptr, TIME_OPTION},
888 {"time-style", required_argument, nullptr, TIME_STYLE_OPTION},
889 {"zero", no_argument, nullptr, ZERO_OPTION},
890 {"color", optional_argument, nullptr, COLOR_OPTION},
891 {"hyperlink", optional_argument, nullptr, HYPERLINK_OPTION},
892 {"block-size", required_argument, nullptr, BLOCK_SIZE_OPTION},
893 {"context", no_argument, 0, 'Z'},
894 {"author", no_argument, nullptr, AUTHOR_OPTION},
895 {GETOPT_HELP_OPTION_DECL},
896 {GETOPT_VERSION_OPTION_DECL},
897 {nullptr, 0, nullptr, 0}
900 static char const *const format_args[] =
902 "verbose", "long", "commas", "horizontal", "across",
903 "vertical", "single-column", nullptr
905 static enum format const format_types[] =
907 long_format, long_format, with_commas, horizontal, horizontal,
908 many_per_line, one_per_line
910 ARGMATCH_VERIFY (format_args, format_types);
912 static char const *const sort_args[] =
914 "none", "time", "size", "extension", "version", "width", nullptr
916 static enum sort_type const sort_types[] =
918 sort_none, sort_time, sort_size, sort_extension, sort_version, sort_width
920 ARGMATCH_VERIFY (sort_args, sort_types);
922 static char const *const time_args[] =
924 "atime", "access", "use",
925 "ctime", "status",
926 "mtime", "modification",
927 "birth", "creation",
928 nullptr
930 static enum time_type const time_types[] =
932 time_atime, time_atime, time_atime,
933 time_ctime, time_ctime,
934 time_mtime, time_mtime,
935 time_btime, time_btime,
937 ARGMATCH_VERIFY (time_args, time_types);
939 static char const *const when_args[] =
941 /* force and none are for compatibility with another color-ls version */
942 "always", "yes", "force",
943 "never", "no", "none",
944 "auto", "tty", "if-tty", nullptr
946 static enum when_type const when_types[] =
948 when_always, when_always, when_always,
949 when_never, when_never, when_never,
950 when_if_tty, when_if_tty, when_if_tty
952 ARGMATCH_VERIFY (when_args, when_types);
954 /* Information about filling a column. */
955 struct column_info
957 bool valid_len;
958 size_t line_len;
959 size_t *col_arr;
962 /* Array with information about column fullness. */
963 static struct column_info *column_info;
965 /* Maximum number of columns ever possible for this display. */
966 static size_t max_idx;
968 /* The minimum width of a column is 3: 1 character for the name and 2
969 for the separating white space. */
970 enum { MIN_COLUMN_WIDTH = 3 };
973 /* This zero-based index is for the --dired option. It is incremented
974 for each byte of output generated by this program so that the beginning
975 and ending indices (in that output) of every file name can be recorded
976 and later output themselves. */
977 static off_t dired_pos;
979 static void
980 dired_outbyte (char c)
982 dired_pos++;
983 putchar (c);
986 /* Output the buffer S, of length S_LEN, and increment DIRED_POS by S_LEN. */
987 static void
988 dired_outbuf (char const *s, size_t s_len)
990 dired_pos += s_len;
991 fwrite (s, sizeof *s, s_len, stdout);
994 /* Output the string S, and increment DIRED_POS by its length. */
995 static void
996 dired_outstring (char const *s)
998 dired_outbuf (s, strlen (s));
1001 static void
1002 dired_indent (void)
1004 if (dired)
1005 dired_outstring (" ");
1008 /* With --dired, store pairs of beginning and ending indices of file names. */
1009 static struct obstack dired_obstack;
1011 /* With --dired, store pairs of beginning and ending indices of any
1012 directory names that appear as headers (just before 'total' line)
1013 for lists of directory entries. Such directory names are seen when
1014 listing hierarchies using -R and when a directory is listed with at
1015 least one other command line argument. */
1016 static struct obstack subdired_obstack;
1018 /* Save the current index on the specified obstack, OBS. */
1019 static void
1020 push_current_dired_pos (struct obstack *obs)
1022 if (dired)
1023 obstack_grow (obs, &dired_pos, sizeof dired_pos);
1026 /* With -R, this stack is used to help detect directory cycles.
1027 The device/inode pairs on this stack mirror the pairs in the
1028 active_dir_set hash table. */
1029 static struct obstack dev_ino_obstack;
1031 /* Push a pair onto the device/inode stack. */
1032 static void
1033 dev_ino_push (dev_t dev, ino_t ino)
1035 void *vdi;
1036 struct dev_ino *di;
1037 int dev_ino_size = sizeof *di;
1038 obstack_blank (&dev_ino_obstack, dev_ino_size);
1039 vdi = obstack_next_free (&dev_ino_obstack);
1040 di = vdi;
1041 di--;
1042 di->st_dev = dev;
1043 di->st_ino = ino;
1046 /* Pop a dev/ino struct off the global dev_ino_obstack
1047 and return that struct. */
1048 static struct dev_ino
1049 dev_ino_pop (void)
1051 void *vdi;
1052 struct dev_ino *di;
1053 int dev_ino_size = sizeof *di;
1054 affirm (dev_ino_size <= obstack_object_size (&dev_ino_obstack));
1055 obstack_blank_fast (&dev_ino_obstack, -dev_ino_size);
1056 vdi = obstack_next_free (&dev_ino_obstack);
1057 di = vdi;
1058 return *di;
1061 static void
1062 assert_matching_dev_ino (char const *name, struct dev_ino di)
1064 MAYBE_UNUSED struct stat sb;
1065 assure (0 <= stat (name, &sb));
1066 assure (sb.st_dev == di.st_dev);
1067 assure (sb.st_ino == di.st_ino);
1070 static char eolbyte = '\n';
1072 /* Write to standard output PREFIX, followed by the quoting style and
1073 a space-separated list of the integers stored in OS all on one line. */
1075 static void
1076 dired_dump_obstack (char const *prefix, struct obstack *os)
1078 size_t n_pos;
1080 n_pos = obstack_object_size (os) / sizeof (dired_pos);
1081 if (n_pos > 0)
1083 off_t *pos = obstack_finish (os);
1084 fputs (prefix, stdout);
1085 for (size_t i = 0; i < n_pos; i++)
1087 intmax_t p = pos[i];
1088 printf (" %jd", p);
1090 putchar ('\n');
1094 /* Return the platform birthtime member of the stat structure,
1095 or fallback to the mtime member, which we have populated
1096 from the statx structure or reset to an invalid timestamp
1097 where birth time is not supported. */
1098 static struct timespec
1099 get_stat_btime (struct stat const *st)
1101 struct timespec btimespec;
1103 #if HAVE_STATX && defined STATX_INO
1104 btimespec = get_stat_mtime (st);
1105 #else
1106 btimespec = get_stat_birthtime (st);
1107 #endif
1109 return btimespec;
1112 #if HAVE_STATX && defined STATX_INO
1113 ATTRIBUTE_PURE
1114 static unsigned int
1115 time_type_to_statx (void)
1117 switch (time_type)
1119 case time_ctime:
1120 return STATX_CTIME;
1121 case time_mtime:
1122 return STATX_MTIME;
1123 case time_atime:
1124 return STATX_ATIME;
1125 case time_btime:
1126 return STATX_BTIME;
1127 default:
1128 unreachable ();
1130 return 0;
1133 ATTRIBUTE_PURE
1134 static unsigned int
1135 calc_req_mask (void)
1137 unsigned int mask = STATX_MODE;
1139 if (print_inode)
1140 mask |= STATX_INO;
1142 if (print_block_size)
1143 mask |= STATX_BLOCKS;
1145 if (format == long_format) {
1146 mask |= STATX_NLINK | STATX_SIZE | time_type_to_statx ();
1147 if (print_owner || print_author)
1148 mask |= STATX_UID;
1149 if (print_group)
1150 mask |= STATX_GID;
1153 switch (sort_type)
1155 case sort_none:
1156 case sort_name:
1157 case sort_version:
1158 case sort_extension:
1159 case sort_width:
1160 break;
1161 case sort_time:
1162 mask |= time_type_to_statx ();
1163 break;
1164 case sort_size:
1165 mask |= STATX_SIZE;
1166 break;
1167 default:
1168 unreachable ();
1171 return mask;
1174 static int
1175 do_statx (int fd, char const *name, struct stat *st, int flags,
1176 unsigned int mask)
1178 struct statx stx;
1179 bool want_btime = mask & STATX_BTIME;
1180 int ret = statx (fd, name, flags | AT_NO_AUTOMOUNT, mask, &stx);
1181 if (ret >= 0)
1183 statx_to_stat (&stx, st);
1184 /* Since we only need one timestamp type,
1185 store birth time in st_mtim. */
1186 if (want_btime)
1188 if (stx.stx_mask & STATX_BTIME)
1189 st->st_mtim = statx_timestamp_to_timespec (stx.stx_btime);
1190 else
1191 st->st_mtim.tv_sec = st->st_mtim.tv_nsec = -1;
1195 return ret;
1198 static int
1199 do_stat (char const *name, struct stat *st)
1201 return do_statx (AT_FDCWD, name, st, 0, calc_req_mask ());
1204 static int
1205 do_lstat (char const *name, struct stat *st)
1207 return do_statx (AT_FDCWD, name, st, AT_SYMLINK_NOFOLLOW, calc_req_mask ());
1210 static int
1211 stat_for_mode (char const *name, struct stat *st)
1213 return do_statx (AT_FDCWD, name, st, 0, STATX_MODE);
1216 /* dev+ino should be static, so no need to sync with backing store */
1217 static int
1218 stat_for_ino (char const *name, struct stat *st)
1220 return do_statx (AT_FDCWD, name, st, 0, STATX_INO);
1223 static int
1224 fstat_for_ino (int fd, struct stat *st)
1226 return do_statx (fd, "", st, AT_EMPTY_PATH, STATX_INO);
1228 #else
1229 static int
1230 do_stat (char const *name, struct stat *st)
1232 return stat (name, st);
1235 static int
1236 do_lstat (char const *name, struct stat *st)
1238 return lstat (name, st);
1241 static int
1242 stat_for_mode (char const *name, struct stat *st)
1244 return stat (name, st);
1247 static int
1248 stat_for_ino (char const *name, struct stat *st)
1250 return stat (name, st);
1253 static int
1254 fstat_for_ino (int fd, struct stat *st)
1256 return fstat (fd, st);
1258 #endif
1260 /* Return the address of the first plain %b spec in FMT, or nullptr if
1261 there is no such spec. %5b etc. do not match, so that user
1262 widths/flags are honored. */
1264 ATTRIBUTE_PURE
1265 static char const *
1266 first_percent_b (char const *fmt)
1268 for (; *fmt; fmt++)
1269 if (fmt[0] == '%')
1270 switch (fmt[1])
1272 case 'b': return fmt;
1273 case '%': fmt++; break;
1275 return nullptr;
1278 static char RFC3986[256];
1279 static void
1280 file_escape_init (void)
1282 for (int i = 0; i < 256; i++)
1283 RFC3986[i] |= c_isalnum (i) || i == '~' || i == '-' || i == '.' || i == '_';
1286 enum { MBSWIDTH_FLAGS = MBSW_REJECT_INVALID | MBSW_REJECT_UNPRINTABLE };
1288 /* Read the abbreviated month names from the locale, to align them
1289 and to determine the max width of the field and to truncate names
1290 greater than our max allowed.
1291 Note even though this handles multibyte locales correctly
1292 it's not restricted to them as single byte locales can have
1293 variable width abbreviated months and also precomputing/caching
1294 the names was seen to increase the performance of ls significantly. */
1296 /* abformat[RECENT][MON] is the format to use for timestamps with
1297 recentness RECENT and month MON. */
1298 enum { ABFORMAT_SIZE = 128 };
1299 static char abformat[2][12][ABFORMAT_SIZE];
1300 /* True if precomputed formats should be used. This can be false if
1301 nl_langinfo fails, if a format or month abbreviation is unusually
1302 long, or if a month abbreviation contains '%'. */
1303 static bool use_abformat;
1305 /* Store into ABMON the abbreviated month names, suitably aligned.
1306 Return true if successful. */
1308 static bool
1309 abmon_init (char abmon[12][ABFORMAT_SIZE])
1311 #ifndef HAVE_NL_LANGINFO
1312 return false;
1313 #else
1314 int max_mon_width = 0;
1315 int mon_width[12];
1316 int mon_len[12];
1318 for (int i = 0; i < 12; i++)
1320 char const *abbr = nl_langinfo (ABMON_1 + i);
1321 mon_len[i] = strnlen (abbr, ABFORMAT_SIZE);
1322 if (mon_len[i] == ABFORMAT_SIZE)
1323 return false;
1324 if (strchr (abbr, '%'))
1325 return false;
1326 mon_width[i] = mbswidth (strcpy (abmon[i], abbr), MBSWIDTH_FLAGS);
1327 if (mon_width[i] < 0)
1328 return false;
1329 max_mon_width = MAX (max_mon_width, mon_width[i]);
1332 for (int i = 0; i < 12; i++)
1334 int fill = max_mon_width - mon_width[i];
1335 if (ABFORMAT_SIZE - mon_len[i] <= fill)
1336 return false;
1337 bool align_left = !isdigit (to_uchar (abmon[i][0]));
1338 int fill_offset;
1339 if (align_left)
1340 fill_offset = mon_len[i];
1341 else
1343 memmove (abmon[i] + fill, abmon[i], mon_len[i]);
1344 fill_offset = 0;
1346 memset (abmon[i] + fill_offset, ' ', fill);
1347 abmon[i][mon_len[i] + fill] = '\0';
1350 return true;
1351 #endif
1354 /* Initialize ABFORMAT and USE_ABFORMAT. */
1356 static void
1357 abformat_init (void)
1359 char const *pb[2];
1360 for (int recent = 0; recent < 2; recent++)
1361 pb[recent] = first_percent_b (long_time_format[recent]);
1362 if (! (pb[0] || pb[1]))
1363 return;
1365 char abmon[12][ABFORMAT_SIZE];
1366 if (! abmon_init (abmon))
1367 return;
1369 for (int recent = 0; recent < 2; recent++)
1371 char const *fmt = long_time_format[recent];
1372 for (int i = 0; i < 12; i++)
1374 char *nfmt = abformat[recent][i];
1375 int nbytes;
1377 if (! pb[recent])
1378 nbytes = snprintf (nfmt, ABFORMAT_SIZE, "%s", fmt);
1379 else
1381 if (! (pb[recent] - fmt <= MIN (ABFORMAT_SIZE, INT_MAX)))
1382 return;
1383 int prefix_len = pb[recent] - fmt;
1384 nbytes = snprintf (nfmt, ABFORMAT_SIZE, "%.*s%s%s",
1385 prefix_len, fmt, abmon[i], pb[recent] + 2);
1388 if (! (0 <= nbytes && nbytes < ABFORMAT_SIZE))
1389 return;
1393 use_abformat = true;
1396 static size_t
1397 dev_ino_hash (void const *x, size_t table_size)
1399 struct dev_ino const *p = x;
1400 return (uintmax_t) p->st_ino % table_size;
1403 static bool
1404 dev_ino_compare (void const *x, void const *y)
1406 struct dev_ino const *a = x;
1407 struct dev_ino const *b = y;
1408 return PSAME_INODE (a, b);
1411 static void
1412 dev_ino_free (void *x)
1414 free (x);
1417 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
1418 active directories. Return true if there is already a matching
1419 entry in the table. */
1421 static bool
1422 visit_dir (dev_t dev, ino_t ino)
1424 struct dev_ino *ent;
1425 struct dev_ino *ent_from_table;
1426 bool found_match;
1428 ent = xmalloc (sizeof *ent);
1429 ent->st_ino = ino;
1430 ent->st_dev = dev;
1432 /* Attempt to insert this entry into the table. */
1433 ent_from_table = hash_insert (active_dir_set, ent);
1435 if (ent_from_table == nullptr)
1437 /* Insertion failed due to lack of memory. */
1438 xalloc_die ();
1441 found_match = (ent_from_table != ent);
1443 if (found_match)
1445 /* ent was not inserted, so free it. */
1446 free (ent);
1449 return found_match;
1452 static void
1453 free_pending_ent (struct pending *p)
1455 free (p->name);
1456 free (p->realname);
1457 free (p);
1460 static bool
1461 is_colored (enum indicator_no type)
1463 size_t len = color_indicator[type].len;
1464 char const *s = color_indicator[type].string;
1465 return ! (len == 0
1466 || (len == 1 && STRNCMP_LIT (s, "0") == 0)
1467 || (len == 2 && STRNCMP_LIT (s, "00") == 0));
1470 static void
1471 restore_default_color (void)
1473 put_indicator (&color_indicator[C_LEFT]);
1474 put_indicator (&color_indicator[C_RIGHT]);
1477 static void
1478 set_normal_color (void)
1480 if (print_with_color && is_colored (C_NORM))
1482 put_indicator (&color_indicator[C_LEFT]);
1483 put_indicator (&color_indicator[C_NORM]);
1484 put_indicator (&color_indicator[C_RIGHT]);
1488 /* An ordinary signal was received; arrange for the program to exit. */
1490 static void
1491 sighandler (int sig)
1493 if (! SA_NOCLDSTOP)
1494 signal (sig, SIG_IGN);
1495 if (! interrupt_signal)
1496 interrupt_signal = sig;
1499 /* A SIGTSTP was received; arrange for the program to suspend itself. */
1501 static void
1502 stophandler (int sig)
1504 if (! SA_NOCLDSTOP)
1505 signal (sig, stophandler);
1506 if (! interrupt_signal)
1507 stop_signal_count++;
1510 /* Process any pending signals. If signals are caught, this function
1511 should be called periodically. Ideally there should never be an
1512 unbounded amount of time when signals are not being processed.
1513 Signal handling can restore the default colors, so callers must
1514 immediately change colors after invoking this function. */
1516 static void
1517 process_signals (void)
1519 while (interrupt_signal || stop_signal_count)
1521 int sig;
1522 int stops;
1523 sigset_t oldset;
1525 if (used_color)
1526 restore_default_color ();
1527 fflush (stdout);
1529 sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
1531 /* Reload interrupt_signal and stop_signal_count, in case a new
1532 signal was handled before sigprocmask took effect. */
1533 sig = interrupt_signal;
1534 stops = stop_signal_count;
1536 /* SIGTSTP is special, since the application can receive that signal
1537 more than once. In this case, don't set the signal handler to the
1538 default. Instead, just raise the uncatchable SIGSTOP. */
1539 if (stops)
1541 stop_signal_count = stops - 1;
1542 sig = SIGSTOP;
1544 else
1545 signal (sig, SIG_DFL);
1547 /* Exit or suspend the program. */
1548 raise (sig);
1549 sigprocmask (SIG_SETMASK, &oldset, nullptr);
1551 /* If execution reaches here, then the program has been
1552 continued (after being suspended). */
1556 /* Setup signal handlers if INIT is true,
1557 otherwise restore to the default. */
1559 static void
1560 signal_setup (bool init)
1562 /* The signals that are trapped, and the number of such signals. */
1563 static int const sig[] =
1565 /* This one is handled specially. */
1566 SIGTSTP,
1568 /* The usual suspects. */
1569 SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM,
1570 #ifdef SIGPOLL
1571 SIGPOLL,
1572 #endif
1573 #ifdef SIGPROF
1574 SIGPROF,
1575 #endif
1576 #ifdef SIGVTALRM
1577 SIGVTALRM,
1578 #endif
1579 #ifdef SIGXCPU
1580 SIGXCPU,
1581 #endif
1582 #ifdef SIGXFSZ
1583 SIGXFSZ,
1584 #endif
1586 enum { nsigs = ARRAY_CARDINALITY (sig) };
1588 #if ! SA_NOCLDSTOP
1589 static bool caught_sig[nsigs];
1590 #endif
1592 int j;
1594 if (init)
1596 #if SA_NOCLDSTOP
1597 struct sigaction act;
1599 sigemptyset (&caught_signals);
1600 for (j = 0; j < nsigs; j++)
1602 sigaction (sig[j], nullptr, &act);
1603 if (act.sa_handler != SIG_IGN)
1604 sigaddset (&caught_signals, sig[j]);
1607 act.sa_mask = caught_signals;
1608 act.sa_flags = SA_RESTART;
1610 for (j = 0; j < nsigs; j++)
1611 if (sigismember (&caught_signals, sig[j]))
1613 act.sa_handler = sig[j] == SIGTSTP ? stophandler : sighandler;
1614 sigaction (sig[j], &act, nullptr);
1616 #else
1617 for (j = 0; j < nsigs; j++)
1619 caught_sig[j] = (signal (sig[j], SIG_IGN) != SIG_IGN);
1620 if (caught_sig[j])
1622 signal (sig[j], sig[j] == SIGTSTP ? stophandler : sighandler);
1623 siginterrupt (sig[j], 0);
1626 #endif
1628 else /* restore. */
1630 #if SA_NOCLDSTOP
1631 for (j = 0; j < nsigs; j++)
1632 if (sigismember (&caught_signals, sig[j]))
1633 signal (sig[j], SIG_DFL);
1634 #else
1635 for (j = 0; j < nsigs; j++)
1636 if (caught_sig[j])
1637 signal (sig[j], SIG_DFL);
1638 #endif
1642 static void
1643 signal_init (void)
1645 signal_setup (true);
1648 static void
1649 signal_restore (void)
1651 signal_setup (false);
1655 main (int argc, char **argv)
1657 int i;
1658 struct pending *thispend;
1659 int n_files;
1661 initialize_main (&argc, &argv);
1662 set_program_name (argv[0]);
1663 setlocale (LC_ALL, "");
1664 bindtextdomain (PACKAGE, LOCALEDIR);
1665 textdomain (PACKAGE);
1667 initialize_exit_failure (LS_FAILURE);
1668 atexit (close_stdout);
1670 static_assert (ARRAY_CARDINALITY (color_indicator) + 1
1671 == ARRAY_CARDINALITY (indicator_name));
1673 exit_status = EXIT_SUCCESS;
1674 print_dir_name = true;
1675 pending_dirs = nullptr;
1677 current_time.tv_sec = TYPE_MINIMUM (time_t);
1678 current_time.tv_nsec = -1;
1680 i = decode_switches (argc, argv);
1682 if (print_with_color)
1683 parse_ls_color ();
1685 /* Test print_with_color again, because the call to parse_ls_color
1686 may have just reset it -- e.g., if LS_COLORS is invalid. */
1688 if (print_with_color)
1690 /* Don't use TAB characters in output. Some terminal
1691 emulators can't handle the combination of tabs and
1692 color codes on the same line. */
1693 tabsize = 0;
1696 if (directories_first)
1697 check_symlink_mode = true;
1698 else if (print_with_color)
1700 /* Avoid following symbolic links when possible. */
1701 if (is_colored (C_ORPHAN)
1702 || (is_colored (C_EXEC) && color_symlink_as_referent)
1703 || (is_colored (C_MISSING) && format == long_format))
1704 check_symlink_mode = true;
1707 if (dereference == DEREF_UNDEFINED)
1708 dereference = ((immediate_dirs
1709 || indicator_style == classify
1710 || format == long_format)
1711 ? DEREF_NEVER
1712 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
1714 /* When using -R, initialize a data structure we'll use to
1715 detect any directory cycles. */
1716 if (recursive)
1718 active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, nullptr,
1719 dev_ino_hash,
1720 dev_ino_compare,
1721 dev_ino_free);
1722 if (active_dir_set == nullptr)
1723 xalloc_die ();
1725 obstack_init (&dev_ino_obstack);
1728 localtz = tzalloc (getenv ("TZ"));
1730 format_needs_stat = sort_type == sort_time || sort_type == sort_size
1731 || format == long_format
1732 || print_scontext
1733 || print_block_size;
1734 format_needs_type = (! format_needs_stat
1735 && (recursive
1736 || print_with_color
1737 || indicator_style != none
1738 || directories_first));
1740 if (dired)
1742 obstack_init (&dired_obstack);
1743 obstack_init (&subdired_obstack);
1746 if (print_hyperlink)
1748 file_escape_init ();
1750 hostname = xgethostname ();
1751 /* The hostname is generally ignored,
1752 so ignore failures obtaining it. */
1753 if (! hostname)
1754 hostname = "";
1757 cwd_n_alloc = 100;
1758 cwd_file = xnmalloc (cwd_n_alloc, sizeof *cwd_file);
1759 cwd_n_used = 0;
1761 clear_files ();
1763 n_files = argc - i;
1765 if (n_files <= 0)
1767 if (immediate_dirs)
1768 gobble_file (".", directory, NOT_AN_INODE_NUMBER, true, "");
1769 else
1770 queue_directory (".", nullptr, true);
1772 else
1774 gobble_file (argv[i++], unknown, NOT_AN_INODE_NUMBER, true, "");
1775 while (i < argc);
1777 if (cwd_n_used)
1779 sort_files ();
1780 if (!immediate_dirs)
1781 extract_dirs_from_files (nullptr, true);
1782 /* 'cwd_n_used' might be zero now. */
1785 /* In the following if/else blocks, it is sufficient to test 'pending_dirs'
1786 (and not pending_dirs->name) because there may be no markers in the queue
1787 at this point. A marker may be enqueued when extract_dirs_from_files is
1788 called with a non-empty string or via print_dir. */
1789 if (cwd_n_used)
1791 print_current_files ();
1792 if (pending_dirs)
1793 dired_outbyte ('\n');
1795 else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1796 print_dir_name = false;
1798 while (pending_dirs)
1800 thispend = pending_dirs;
1801 pending_dirs = pending_dirs->next;
1803 if (LOOP_DETECT)
1805 if (thispend->name == nullptr)
1807 /* thispend->name == nullptr means this is a marker entry
1808 indicating we've finished processing the directory.
1809 Use its dev/ino numbers to remove the corresponding
1810 entry from the active_dir_set hash table. */
1811 struct dev_ino di = dev_ino_pop ();
1812 struct dev_ino *found = hash_remove (active_dir_set, &di);
1813 if (false)
1814 assert_matching_dev_ino (thispend->realname, di);
1815 affirm (found);
1816 dev_ino_free (found);
1817 free_pending_ent (thispend);
1818 continue;
1822 print_dir (thispend->name, thispend->realname,
1823 thispend->command_line_arg);
1825 free_pending_ent (thispend);
1826 print_dir_name = true;
1829 if (print_with_color && used_color)
1831 int j;
1833 /* Skip the restore when it would be a no-op, i.e.,
1834 when left is "\033[" and right is "m". */
1835 if (!(color_indicator[C_LEFT].len == 2
1836 && memcmp (color_indicator[C_LEFT].string, "\033[", 2) == 0
1837 && color_indicator[C_RIGHT].len == 1
1838 && color_indicator[C_RIGHT].string[0] == 'm'))
1839 restore_default_color ();
1841 fflush (stdout);
1843 signal_restore ();
1845 /* Act on any signals that arrived before the default was restored.
1846 This can process signals out of order, but there doesn't seem to
1847 be an easy way to do them in order, and the order isn't that
1848 important anyway. */
1849 for (j = stop_signal_count; j; j--)
1850 raise (SIGSTOP);
1851 j = interrupt_signal;
1852 if (j)
1853 raise (j);
1856 if (dired)
1858 /* No need to free these since we're about to exit. */
1859 dired_dump_obstack ("//DIRED//", &dired_obstack);
1860 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1861 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1862 quoting_style_args[get_quoting_style (filename_quoting_options)]);
1865 if (LOOP_DETECT)
1867 assure (hash_get_n_entries (active_dir_set) == 0);
1868 hash_free (active_dir_set);
1871 return exit_status;
1874 /* Return the line length indicated by the value given by SPEC, or -1
1875 if unsuccessful. 0 means no limit on line length. */
1877 static ptrdiff_t
1878 decode_line_length (char const *spec)
1880 uintmax_t val;
1882 /* Treat too-large values as if they were 0, which is
1883 effectively infinity. */
1884 switch (xstrtoumax (spec, nullptr, 0, &val, ""))
1886 case LONGINT_OK:
1887 return val <= MIN (PTRDIFF_MAX, SIZE_MAX) ? val : 0;
1889 case LONGINT_OVERFLOW:
1890 return 0;
1892 default:
1893 return -1;
1897 /* Return true if standard output is a tty, caching the result. */
1899 static bool
1900 stdout_isatty (void)
1902 static signed char out_tty = -1;
1903 if (out_tty < 0)
1904 out_tty = isatty (STDOUT_FILENO);
1905 assume (out_tty == 0 || out_tty == 1);
1906 return out_tty;
1909 /* Set all the option flags according to the switches specified.
1910 Return the index of the first non-option argument. */
1912 static int
1913 decode_switches (int argc, char **argv)
1915 char const *time_style_option = nullptr;
1917 /* These variables are false or -1 unless a switch says otherwise. */
1918 bool kibibytes_specified = false;
1919 int format_opt = -1;
1920 int hide_control_chars_opt = -1;
1921 int quoting_style_opt = -1;
1922 int sort_opt = -1;
1923 ptrdiff_t tabsize_opt = -1;
1924 ptrdiff_t width_opt = -1;
1926 while (true)
1928 int oi = -1;
1929 int c = getopt_long (argc, argv,
1930 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1",
1931 long_options, &oi);
1932 if (c == -1)
1933 break;
1935 switch (c)
1937 case 'a':
1938 ignore_mode = IGNORE_MINIMAL;
1939 break;
1941 case 'b':
1942 quoting_style_opt = escape_quoting_style;
1943 break;
1945 case 'c':
1946 time_type = time_ctime;
1947 explicit_time = true;
1948 break;
1950 case 'd':
1951 immediate_dirs = true;
1952 break;
1954 case 'f':
1955 ignore_mode = IGNORE_MINIMAL; /* enable -a */
1956 sort_opt = sort_none; /* enable -U */
1957 break;
1959 case FILE_TYPE_INDICATOR_OPTION: /* --file-type */
1960 indicator_style = file_type;
1961 break;
1963 case 'g':
1964 format_opt = long_format;
1965 print_owner = false;
1966 break;
1968 case 'h':
1969 file_human_output_opts = human_output_opts =
1970 human_autoscale | human_SI | human_base_1024;
1971 file_output_block_size = output_block_size = 1;
1972 break;
1974 case 'i':
1975 print_inode = true;
1976 break;
1978 case 'k':
1979 kibibytes_specified = true;
1980 break;
1982 case 'l':
1983 format_opt = long_format;
1984 break;
1986 case 'm':
1987 format_opt = with_commas;
1988 break;
1990 case 'n':
1991 numeric_ids = true;
1992 format_opt = long_format;
1993 break;
1995 case 'o': /* Just like -l, but don't display group info. */
1996 format_opt = long_format;
1997 print_group = false;
1998 break;
2000 case 'p':
2001 indicator_style = slash;
2002 break;
2004 case 'q':
2005 hide_control_chars_opt = true;
2006 break;
2008 case 'r':
2009 sort_reverse = true;
2010 break;
2012 case 's':
2013 print_block_size = true;
2014 break;
2016 case 't':
2017 sort_opt = sort_time;
2018 break;
2020 case 'u':
2021 time_type = time_atime;
2022 explicit_time = true;
2023 break;
2025 case 'v':
2026 sort_opt = sort_version;
2027 break;
2029 case 'w':
2030 width_opt = decode_line_length (optarg);
2031 if (width_opt < 0)
2032 error (LS_FAILURE, 0, "%s: %s", _("invalid line width"),
2033 quote (optarg));
2034 break;
2036 case 'x':
2037 format_opt = horizontal;
2038 break;
2040 case 'A':
2041 ignore_mode = IGNORE_DOT_AND_DOTDOT;
2042 break;
2044 case 'B':
2045 add_ignore_pattern ("*~");
2046 add_ignore_pattern (".*~");
2047 break;
2049 case 'C':
2050 format_opt = many_per_line;
2051 break;
2053 case 'D':
2054 format_opt = long_format;
2055 print_hyperlink = false;
2056 dired = true;
2057 break;
2059 case 'F':
2061 int i;
2062 if (optarg)
2063 i = XARGMATCH ("--classify", optarg, when_args, when_types);
2064 else
2065 /* Using --classify with no argument is equivalent to using
2066 --classify=always. */
2067 i = when_always;
2069 if (i == when_always || (i == when_if_tty && stdout_isatty ()))
2070 indicator_style = classify;
2071 break;
2074 case 'G': /* inhibit display of group info */
2075 print_group = false;
2076 break;
2078 case 'H':
2079 dereference = DEREF_COMMAND_LINE_ARGUMENTS;
2080 break;
2082 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
2083 dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
2084 break;
2086 case 'I':
2087 add_ignore_pattern (optarg);
2088 break;
2090 case 'L':
2091 dereference = DEREF_ALWAYS;
2092 break;
2094 case 'N':
2095 quoting_style_opt = literal_quoting_style;
2096 break;
2098 case 'Q':
2099 quoting_style_opt = c_quoting_style;
2100 break;
2102 case 'R':
2103 recursive = true;
2104 break;
2106 case 'S':
2107 sort_opt = sort_size;
2108 break;
2110 case 'T':
2111 tabsize_opt = xnumtoumax (optarg, 0, 0, MIN (PTRDIFF_MAX, SIZE_MAX),
2112 "", _("invalid tab size"), LS_FAILURE);
2113 break;
2115 case 'U':
2116 sort_opt = sort_none;
2117 break;
2119 case 'X':
2120 sort_opt = sort_extension;
2121 break;
2123 case '1':
2124 /* -1 has no effect after -l. */
2125 if (format_opt != long_format)
2126 format_opt = one_per_line;
2127 break;
2129 case AUTHOR_OPTION:
2130 print_author = true;
2131 break;
2133 case HIDE_OPTION:
2135 struct ignore_pattern *hide = xmalloc (sizeof *hide);
2136 hide->pattern = optarg;
2137 hide->next = hide_patterns;
2138 hide_patterns = hide;
2140 break;
2142 case SORT_OPTION:
2143 sort_opt = XARGMATCH ("--sort", optarg, sort_args, sort_types);
2144 break;
2146 case GROUP_DIRECTORIES_FIRST_OPTION:
2147 directories_first = true;
2148 break;
2150 case TIME_OPTION:
2151 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
2152 explicit_time = true;
2153 break;
2155 case FORMAT_OPTION:
2156 format_opt = XARGMATCH ("--format", optarg, format_args,
2157 format_types);
2158 break;
2160 case FULL_TIME_OPTION:
2161 format_opt = long_format;
2162 time_style_option = "full-iso";
2163 break;
2165 case COLOR_OPTION:
2167 int i;
2168 if (optarg)
2169 i = XARGMATCH ("--color", optarg, when_args, when_types);
2170 else
2171 /* Using --color with no argument is equivalent to using
2172 --color=always. */
2173 i = when_always;
2175 print_with_color = (i == when_always
2176 || (i == when_if_tty && stdout_isatty ()));
2177 break;
2180 case HYPERLINK_OPTION:
2182 int i;
2183 if (optarg)
2184 i = XARGMATCH ("--hyperlink", optarg, when_args, when_types);
2185 else
2186 /* Using --hyperlink with no argument is equivalent to using
2187 --hyperlink=always. */
2188 i = when_always;
2190 print_hyperlink = (i == when_always
2191 || (i == when_if_tty && stdout_isatty ()));
2192 break;
2195 case INDICATOR_STYLE_OPTION:
2196 indicator_style = XARGMATCH ("--indicator-style", optarg,
2197 indicator_style_args,
2198 indicator_style_types);
2199 break;
2201 case QUOTING_STYLE_OPTION:
2202 quoting_style_opt = XARGMATCH ("--quoting-style", optarg,
2203 quoting_style_args,
2204 quoting_style_vals);
2205 break;
2207 case TIME_STYLE_OPTION:
2208 time_style_option = optarg;
2209 break;
2211 case SHOW_CONTROL_CHARS_OPTION:
2212 hide_control_chars_opt = false;
2213 break;
2215 case BLOCK_SIZE_OPTION:
2217 enum strtol_error e = human_options (optarg, &human_output_opts,
2218 &output_block_size);
2219 if (e != LONGINT_OK)
2220 xstrtol_fatal (e, oi, 0, long_options, optarg);
2221 file_human_output_opts = human_output_opts;
2222 file_output_block_size = output_block_size;
2224 break;
2226 case SI_OPTION:
2227 file_human_output_opts = human_output_opts =
2228 human_autoscale | human_SI;
2229 file_output_block_size = output_block_size = 1;
2230 break;
2232 case 'Z':
2233 print_scontext = true;
2234 break;
2236 case ZERO_OPTION:
2237 eolbyte = 0;
2238 hide_control_chars_opt = false;
2239 if (format_opt != long_format)
2240 format_opt = one_per_line;
2241 print_with_color = false;
2242 quoting_style_opt = literal_quoting_style;
2243 break;
2245 case_GETOPT_HELP_CHAR;
2247 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
2249 default:
2250 usage (LS_FAILURE);
2254 if (! output_block_size)
2256 char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
2257 human_options (ls_block_size,
2258 &human_output_opts, &output_block_size);
2259 if (ls_block_size || getenv ("BLOCK_SIZE"))
2261 file_human_output_opts = human_output_opts;
2262 file_output_block_size = output_block_size;
2264 if (kibibytes_specified)
2266 human_output_opts = 0;
2267 output_block_size = 1024;
2271 format = (0 <= format_opt ? format_opt
2272 : ls_mode == LS_LS ? (stdout_isatty ()
2273 ? many_per_line : one_per_line)
2274 : ls_mode == LS_MULTI_COL ? many_per_line
2275 : /* ls_mode == LS_LONG_FORMAT */ long_format);
2277 /* If the line length was not set by a switch but is needed to determine
2278 output, go to the work of obtaining it from the environment. */
2279 ptrdiff_t linelen = width_opt;
2280 if (format == many_per_line || format == horizontal || format == with_commas
2281 || print_with_color)
2283 #ifdef TIOCGWINSZ
2284 if (linelen < 0)
2286 struct winsize ws;
2287 if (stdout_isatty ()
2288 && 0 <= ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws)
2289 && 0 < ws.ws_col)
2290 linelen = ws.ws_col <= MIN (PTRDIFF_MAX, SIZE_MAX) ? ws.ws_col : 0;
2292 #endif
2293 if (linelen < 0)
2295 char const *p = getenv ("COLUMNS");
2296 if (p && *p)
2298 linelen = decode_line_length (p);
2299 if (linelen < 0)
2300 error (0, 0,
2301 _("ignoring invalid width"
2302 " in environment variable COLUMNS: %s"),
2303 quote (p));
2308 line_length = linelen < 0 ? 80 : linelen;
2310 /* Determine the max possible number of display columns. */
2311 max_idx = line_length / MIN_COLUMN_WIDTH;
2312 /* Account for first display column not having a separator,
2313 or line_lengths shorter than MIN_COLUMN_WIDTH. */
2314 max_idx += line_length % MIN_COLUMN_WIDTH != 0;
2316 if (format == many_per_line || format == horizontal || format == with_commas)
2318 if (0 <= tabsize_opt)
2319 tabsize = tabsize_opt;
2320 else
2322 tabsize = 8;
2323 char const *p = getenv ("TABSIZE");
2324 if (p)
2326 uintmax_t tmp;
2327 if (xstrtoumax (p, nullptr, 0, &tmp, "") == LONGINT_OK
2328 && tmp <= SIZE_MAX)
2329 tabsize = tmp;
2330 else
2331 error (0, 0,
2332 _("ignoring invalid tab size"
2333 " in environment variable TABSIZE: %s"),
2334 quote (p));
2339 qmark_funny_chars = (hide_control_chars_opt < 0
2340 ? ls_mode == LS_LS && stdout_isatty ()
2341 : hide_control_chars_opt);
2343 int qs = quoting_style_opt;
2344 if (qs < 0)
2345 qs = getenv_quoting_style ();
2346 if (qs < 0)
2347 qs = (ls_mode == LS_LS
2348 ? (stdout_isatty () ? shell_escape_quoting_style : -1)
2349 : escape_quoting_style);
2350 if (0 <= qs)
2351 set_quoting_style (nullptr, qs);
2352 qs = get_quoting_style (nullptr);
2353 align_variable_outer_quotes
2354 = ((format == long_format
2355 || ((format == many_per_line || format == horizontal) && line_length))
2356 && (qs == shell_quoting_style
2357 || qs == shell_escape_quoting_style
2358 || qs == c_maybe_quoting_style));
2359 filename_quoting_options = clone_quoting_options (nullptr);
2360 if (qs == escape_quoting_style)
2361 set_char_quoting (filename_quoting_options, ' ', 1);
2362 if (file_type <= indicator_style)
2364 char const *p;
2365 for (p = &"*=>@|"[indicator_style - file_type]; *p; p++)
2366 set_char_quoting (filename_quoting_options, *p, 1);
2369 dirname_quoting_options = clone_quoting_options (nullptr);
2370 set_char_quoting (dirname_quoting_options, ':', 1);
2372 /* --dired implies --format=long (-l) and sans --hyperlink.
2373 So ignore it if those overridden. */
2374 dired &= (format == long_format) & !print_hyperlink;
2376 if (eolbyte < dired)
2377 error (LS_FAILURE, 0, _("--dired and --zero are incompatible"));
2379 /* If a time type is explicitly specified (with -c, -u, or --time=)
2380 and we're not showing a time (-l not specified), then sort by that time,
2381 rather than by name. Note this behavior is unspecified by POSIX. */
2383 sort_type = (0 <= sort_opt ? sort_opt
2384 : (format != long_format && explicit_time)
2385 ? sort_time : sort_name);
2387 if (format == long_format)
2389 char const *style = time_style_option;
2390 static char const posix_prefix[] = "posix-";
2392 if (! style)
2394 style = getenv ("TIME_STYLE");
2395 if (! style)
2396 style = "locale";
2399 while (STREQ_LEN (style, posix_prefix, sizeof posix_prefix - 1))
2401 if (! hard_locale (LC_TIME))
2402 return optind;
2403 style += sizeof posix_prefix - 1;
2406 if (*style == '+')
2408 char const *p0 = style + 1;
2409 char *p0nl = strchr (p0, '\n');
2410 char const *p1 = p0;
2411 if (p0nl)
2413 if (strchr (p0nl + 1, '\n'))
2414 error (LS_FAILURE, 0, _("invalid time style format %s"),
2415 quote (p0));
2416 *p0nl++ = '\0';
2417 p1 = p0nl;
2419 long_time_format[0] = p0;
2420 long_time_format[1] = p1;
2422 else
2424 ptrdiff_t res = argmatch (style, time_style_args,
2425 (char const *) time_style_types,
2426 sizeof (*time_style_types));
2427 if (res < 0)
2429 /* This whole block used to be a simple use of XARGMATCH.
2430 but that didn't print the "posix-"-prefixed variants or
2431 the "+"-prefixed format string option upon failure. */
2432 argmatch_invalid ("time style", style, res);
2434 /* The following is a manual expansion of argmatch_valid,
2435 but with the added "+ ..." description and the [posix-]
2436 prefixes prepended. Note that this simplification works
2437 only because all four existing time_style_types values
2438 are distinct. */
2439 fputs (_("Valid arguments are:\n"), stderr);
2440 char const *const *p = time_style_args;
2441 while (*p)
2442 fprintf (stderr, " - [posix-]%s\n", *p++);
2443 fputs (_(" - +FORMAT (e.g., +%H:%M) for a 'date'-style"
2444 " format\n"), stderr);
2445 usage (LS_FAILURE);
2447 switch (res)
2449 case full_iso_time_style:
2450 long_time_format[0] = long_time_format[1] =
2451 "%Y-%m-%d %H:%M:%S.%N %z";
2452 break;
2454 case long_iso_time_style:
2455 long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
2456 break;
2458 case iso_time_style:
2459 long_time_format[0] = "%Y-%m-%d ";
2460 long_time_format[1] = "%m-%d %H:%M";
2461 break;
2463 case locale_time_style:
2464 if (hard_locale (LC_TIME))
2466 for (int i = 0; i < 2; i++)
2467 long_time_format[i] =
2468 dcgettext (nullptr, long_time_format[i], LC_TIME);
2473 abformat_init ();
2476 return optind;
2479 /* Parse a string as part of the LS_COLORS variable; this may involve
2480 decoding all kinds of escape characters. If equals_end is set an
2481 unescaped equal sign ends the string, otherwise only a : or \0
2482 does. Set *OUTPUT_COUNT to the number of bytes output. Return
2483 true if successful.
2485 The resulting string is *not* null-terminated, but may contain
2486 embedded nulls.
2488 Note that both dest and src are char **; on return they point to
2489 the first free byte after the array and the character that ended
2490 the input string, respectively. */
2492 static bool
2493 get_funky_string (char **dest, char const **src, bool equals_end,
2494 size_t *output_count)
2496 char num; /* For numerical codes */
2497 size_t count; /* Something to count with */
2498 enum {
2499 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
2500 } state;
2501 char const *p;
2502 char *q;
2504 p = *src; /* We don't want to double-indirect */
2505 q = *dest; /* the whole darn time. */
2507 count = 0; /* No characters counted in yet. */
2508 num = 0;
2510 state = ST_GND; /* Start in ground state. */
2511 while (state < ST_END)
2513 switch (state)
2515 case ST_GND: /* Ground state (no escapes) */
2516 switch (*p)
2518 case ':':
2519 case '\0':
2520 state = ST_END; /* End of string */
2521 break;
2522 case '\\':
2523 state = ST_BACKSLASH; /* Backslash escape sequence */
2524 ++p;
2525 break;
2526 case '^':
2527 state = ST_CARET; /* Caret escape */
2528 ++p;
2529 break;
2530 case '=':
2531 if (equals_end)
2533 state = ST_END; /* End */
2534 break;
2536 FALLTHROUGH;
2537 default:
2538 *(q++) = *(p++);
2539 ++count;
2540 break;
2542 break;
2544 case ST_BACKSLASH: /* Backslash escaped character */
2545 switch (*p)
2547 case '0':
2548 case '1':
2549 case '2':
2550 case '3':
2551 case '4':
2552 case '5':
2553 case '6':
2554 case '7':
2555 state = ST_OCTAL; /* Octal sequence */
2556 num = *p - '0';
2557 break;
2558 case 'x':
2559 case 'X':
2560 state = ST_HEX; /* Hex sequence */
2561 num = 0;
2562 break;
2563 case 'a': /* Bell */
2564 num = '\a';
2565 break;
2566 case 'b': /* Backspace */
2567 num = '\b';
2568 break;
2569 case 'e': /* Escape */
2570 num = 27;
2571 break;
2572 case 'f': /* Form feed */
2573 num = '\f';
2574 break;
2575 case 'n': /* Newline */
2576 num = '\n';
2577 break;
2578 case 'r': /* Carriage return */
2579 num = '\r';
2580 break;
2581 case 't': /* Tab */
2582 num = '\t';
2583 break;
2584 case 'v': /* Vtab */
2585 num = '\v';
2586 break;
2587 case '?': /* Delete */
2588 num = 127;
2589 break;
2590 case '_': /* Space */
2591 num = ' ';
2592 break;
2593 case '\0': /* End of string */
2594 state = ST_ERROR; /* Error! */
2595 break;
2596 default: /* Escaped character like \ ^ : = */
2597 num = *p;
2598 break;
2600 if (state == ST_BACKSLASH)
2602 *(q++) = num;
2603 ++count;
2604 state = ST_GND;
2606 ++p;
2607 break;
2609 case ST_OCTAL: /* Octal sequence */
2610 if (*p < '0' || *p > '7')
2612 *(q++) = num;
2613 ++count;
2614 state = ST_GND;
2616 else
2617 num = (num << 3) + (*(p++) - '0');
2618 break;
2620 case ST_HEX: /* Hex sequence */
2621 switch (*p)
2623 case '0':
2624 case '1':
2625 case '2':
2626 case '3':
2627 case '4':
2628 case '5':
2629 case '6':
2630 case '7':
2631 case '8':
2632 case '9':
2633 num = (num << 4) + (*(p++) - '0');
2634 break;
2635 case 'a':
2636 case 'b':
2637 case 'c':
2638 case 'd':
2639 case 'e':
2640 case 'f':
2641 num = (num << 4) + (*(p++) - 'a') + 10;
2642 break;
2643 case 'A':
2644 case 'B':
2645 case 'C':
2646 case 'D':
2647 case 'E':
2648 case 'F':
2649 num = (num << 4) + (*(p++) - 'A') + 10;
2650 break;
2651 default:
2652 *(q++) = num;
2653 ++count;
2654 state = ST_GND;
2655 break;
2657 break;
2659 case ST_CARET: /* Caret escape */
2660 state = ST_GND; /* Should be the next state... */
2661 if (*p >= '@' && *p <= '~')
2663 *(q++) = *(p++) & 037;
2664 ++count;
2666 else if (*p == '?')
2668 *(q++) = 127;
2669 ++count;
2671 else
2672 state = ST_ERROR;
2673 break;
2675 default:
2676 unreachable ();
2680 *dest = q;
2681 *src = p;
2682 *output_count = count;
2684 return state != ST_ERROR;
2687 enum parse_state
2689 PS_START = 1,
2690 PS_2,
2691 PS_3,
2692 PS_4,
2693 PS_DONE,
2694 PS_FAIL
2698 /* Check if the content of TERM is a valid name in dircolors. */
2700 static bool
2701 known_term_type (void)
2703 char const *term = getenv ("TERM");
2704 if (! term || ! *term)
2705 return false;
2707 char const *line = G_line;
2708 while (line - G_line < sizeof (G_line))
2710 if (STRNCMP_LIT (line, "TERM ") == 0)
2712 if (fnmatch (line + 5, term, 0) == 0)
2713 return true;
2715 line += strlen (line) + 1;
2718 return false;
2721 static void
2722 parse_ls_color (void)
2724 char const *p; /* Pointer to character being parsed */
2725 char *buf; /* color_buf buffer pointer */
2726 int ind_no; /* Indicator number */
2727 char label[3]; /* Indicator label */
2728 struct color_ext_type *ext; /* Extension we are working on */
2730 if ((p = getenv ("LS_COLORS")) == nullptr || *p == '\0')
2732 /* LS_COLORS takes precedence, but if that's not set then
2733 honor the COLORTERM and TERM env variables so that
2734 we only go with the internal ANSI color codes if the
2735 former is non empty or the latter is set to a known value. */
2736 char const *colorterm = getenv ("COLORTERM");
2737 if (! (colorterm && *colorterm) && ! known_term_type ())
2738 print_with_color = false;
2739 return;
2742 ext = nullptr;
2743 strcpy (label, "??");
2745 /* This is an overly conservative estimate, but any possible
2746 LS_COLORS string will *not* generate a color_buf longer than
2747 itself, so it is a safe way of allocating a buffer in
2748 advance. */
2749 buf = color_buf = xstrdup (p);
2751 enum parse_state state = PS_START;
2752 while (true)
2754 switch (state)
2756 case PS_START: /* First label character */
2757 switch (*p)
2759 case ':':
2760 ++p;
2761 break;
2763 case '*':
2764 /* Allocate new extension block and add to head of
2765 linked list (this way a later definition will
2766 override an earlier one, which can be useful for
2767 having terminal-specific defs override global). */
2769 ext = xmalloc (sizeof *ext);
2770 ext->next = color_ext_list;
2771 color_ext_list = ext;
2772 ext->exact_match = false;
2774 ++p;
2775 ext->ext.string = buf;
2777 state = (get_funky_string (&buf, &p, true, &ext->ext.len)
2778 ? PS_4 : PS_FAIL);
2779 break;
2781 case '\0':
2782 state = PS_DONE; /* Done! */
2783 goto done;
2785 default: /* Assume it is file type label */
2786 label[0] = *(p++);
2787 state = PS_2;
2788 break;
2790 break;
2792 case PS_2: /* Second label character */
2793 if (*p)
2795 label[1] = *(p++);
2796 state = PS_3;
2798 else
2799 state = PS_FAIL; /* Error */
2800 break;
2802 case PS_3: /* Equal sign after indicator label */
2803 state = PS_FAIL; /* Assume failure... */
2804 if (*(p++) == '=')/* It *should* be... */
2806 for (ind_no = 0; indicator_name[ind_no] != nullptr; ++ind_no)
2808 if (STREQ (label, indicator_name[ind_no]))
2810 color_indicator[ind_no].string = buf;
2811 state = (get_funky_string (&buf, &p, false,
2812 &color_indicator[ind_no].len)
2813 ? PS_START : PS_FAIL);
2814 break;
2817 if (state == PS_FAIL)
2818 error (0, 0, _("unrecognized prefix: %s"), quote (label));
2820 break;
2822 case PS_4: /* Equal sign after *.ext */
2823 if (*(p++) == '=')
2825 ext->seq.string = buf;
2826 state = (get_funky_string (&buf, &p, false, &ext->seq.len)
2827 ? PS_START : PS_FAIL);
2829 else
2830 state = PS_FAIL;
2831 break;
2833 case PS_FAIL:
2834 goto done;
2836 default:
2837 affirm (false);
2840 done:
2842 if (state == PS_FAIL)
2844 struct color_ext_type *e;
2845 struct color_ext_type *e2;
2847 error (0, 0,
2848 _("unparsable value for LS_COLORS environment variable"));
2849 free (color_buf);
2850 for (e = color_ext_list; e != nullptr; /* empty */)
2852 e2 = e;
2853 e = e->next;
2854 free (e2);
2856 print_with_color = false;
2858 else
2860 /* Postprocess list to set EXACT_MATCH on entries where there are
2861 different cased extensions with separate sequences defined.
2862 Also set ext.len to SIZE_MAX on any entries that can't
2863 match due to precedence, to avoid redundant string compares. */
2864 struct color_ext_type *e1;
2866 for (e1 = color_ext_list; e1 != nullptr; e1 = e1->next)
2868 struct color_ext_type *e2;
2869 bool case_ignored = false;
2871 for (e2 = e1->next; e2 != nullptr; e2 = e2->next)
2873 if (e2->ext.len < SIZE_MAX && e1->ext.len == e2->ext.len)
2875 if (memcmp (e1->ext.string, e2->ext.string, e1->ext.len) == 0)
2876 e2->ext.len = SIZE_MAX; /* Ignore */
2877 else if (c_strncasecmp (e1->ext.string, e2->ext.string,
2878 e1->ext.len) == 0)
2880 if (case_ignored)
2882 e2->ext.len = SIZE_MAX; /* Ignore */
2884 else if (e1->seq.len == e2->seq.len
2885 && memcmp (e1->seq.string, e2->seq.string,
2886 e1->seq.len) == 0)
2888 e2->ext.len = SIZE_MAX; /* Ignore */
2889 case_ignored = true; /* Ignore all subsequent */
2891 else
2893 e1->exact_match = true;
2894 e2->exact_match = true;
2902 if (color_indicator[C_LINK].len == 6
2903 && !STRNCMP_LIT (color_indicator[C_LINK].string, "target"))
2904 color_symlink_as_referent = true;
2907 /* Return the quoting style specified by the environment variable
2908 QUOTING_STYLE if set and valid, -1 otherwise. */
2910 static int
2911 getenv_quoting_style (void)
2913 char const *q_style = getenv ("QUOTING_STYLE");
2914 if (!q_style)
2915 return -1;
2916 int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
2917 if (i < 0)
2919 error (0, 0,
2920 _("ignoring invalid value"
2921 " of environment variable QUOTING_STYLE: %s"),
2922 quote (q_style));
2923 return -1;
2925 return quoting_style_vals[i];
2928 /* Set the exit status to report a failure. If SERIOUS, it is a
2929 serious failure; otherwise, it is merely a minor problem. */
2931 static void
2932 set_exit_status (bool serious)
2934 if (serious)
2935 exit_status = LS_FAILURE;
2936 else if (exit_status == EXIT_SUCCESS)
2937 exit_status = LS_MINOR_PROBLEM;
2940 /* Assuming a failure is serious if SERIOUS, use the printf-style
2941 MESSAGE to report the failure to access a file named FILE. Assume
2942 errno is set appropriately for the failure. */
2944 static void
2945 file_failure (bool serious, char const *message, char const *file)
2947 error (0, errno, message, quoteaf (file));
2948 set_exit_status (serious);
2951 /* Request that the directory named NAME have its contents listed later.
2952 If REALNAME is nonzero, it will be used instead of NAME when the
2953 directory name is printed. This allows symbolic links to directories
2954 to be treated as regular directories but still be listed under their
2955 real names. NAME == nullptr is used to insert a marker entry for the
2956 directory named in REALNAME.
2957 If NAME is non-null, we use its dev/ino information to save
2958 a call to stat -- when doing a recursive (-R) traversal.
2959 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2961 static void
2962 queue_directory (char const *name, char const *realname, bool command_line_arg)
2964 struct pending *new = xmalloc (sizeof *new);
2965 new->realname = realname ? xstrdup (realname) : nullptr;
2966 new->name = name ? xstrdup (name) : nullptr;
2967 new->command_line_arg = command_line_arg;
2968 new->next = pending_dirs;
2969 pending_dirs = new;
2972 /* Read directory NAME, and list the files in it.
2973 If REALNAME is nonzero, print its name instead of NAME;
2974 this is used for symbolic links to directories.
2975 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2977 static void
2978 print_dir (char const *name, char const *realname, bool command_line_arg)
2980 DIR *dirp;
2981 struct dirent *next;
2982 uintmax_t total_blocks = 0;
2983 static bool first = true;
2985 errno = 0;
2986 dirp = opendir (name);
2987 if (!dirp)
2989 file_failure (command_line_arg, _("cannot open directory %s"), name);
2990 return;
2993 if (LOOP_DETECT)
2995 struct stat dir_stat;
2996 int fd = dirfd (dirp);
2998 /* If dirfd failed, endure the overhead of stat'ing by path */
2999 if ((0 <= fd
3000 ? fstat_for_ino (fd, &dir_stat)
3001 : stat_for_ino (name, &dir_stat)) < 0)
3003 file_failure (command_line_arg,
3004 _("cannot determine device and inode of %s"), name);
3005 closedir (dirp);
3006 return;
3009 /* If we've already visited this dev/inode pair, warn that
3010 we've found a loop, and do not process this directory. */
3011 if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
3013 error (0, 0, _("%s: not listing already-listed directory"),
3014 quotef (name));
3015 closedir (dirp);
3016 set_exit_status (true);
3017 return;
3020 dev_ino_push (dir_stat.st_dev, dir_stat.st_ino);
3023 clear_files ();
3025 if (recursive || print_dir_name)
3027 if (!first)
3028 dired_outbyte ('\n');
3029 first = false;
3030 dired_indent ();
3032 char *absolute_name = nullptr;
3033 if (print_hyperlink)
3035 absolute_name = canonicalize_filename_mode (name, CAN_MISSING);
3036 if (! absolute_name)
3037 file_failure (command_line_arg,
3038 _("error canonicalizing %s"), name);
3040 quote_name (realname ? realname : name, dirname_quoting_options, -1,
3041 nullptr, true, &subdired_obstack, absolute_name);
3043 free (absolute_name);
3045 dired_outstring (":\n");
3048 /* Read the directory entries, and insert the subfiles into the 'cwd_file'
3049 table. */
3051 while (true)
3053 /* Set errno to zero so we can distinguish between a readdir failure
3054 and when readdir simply finds that there are no more entries. */
3055 errno = 0;
3056 next = readdir (dirp);
3057 /* Some readdir()s do not absorb ENOENT (dir deleted but open). */
3058 if (errno == ENOENT)
3059 errno = 0;
3060 if (next)
3062 if (! file_ignored (next->d_name))
3064 enum filetype type = unknown;
3066 #if HAVE_STRUCT_DIRENT_D_TYPE
3067 switch (next->d_type)
3069 case DT_BLK: type = blockdev; break;
3070 case DT_CHR: type = chardev; break;
3071 case DT_DIR: type = directory; break;
3072 case DT_FIFO: type = fifo; break;
3073 case DT_LNK: type = symbolic_link; break;
3074 case DT_REG: type = normal; break;
3075 case DT_SOCK: type = sock; break;
3076 # ifdef DT_WHT
3077 case DT_WHT: type = whiteout; break;
3078 # endif
3080 #endif
3081 total_blocks += gobble_file (next->d_name, type,
3082 RELIABLE_D_INO (next),
3083 false, name);
3085 /* In this narrow case, print out each name right away, so
3086 ls uses constant memory while processing the entries of
3087 this directory. Useful when there are many (millions)
3088 of entries in a directory. */
3089 if (format == one_per_line && sort_type == sort_none
3090 && !print_block_size && !recursive)
3092 /* We must call sort_files in spite of
3093 "sort_type == sort_none" for its initialization
3094 of the sorted_file vector. */
3095 sort_files ();
3096 print_current_files ();
3097 clear_files ();
3101 else if (errno != 0)
3103 file_failure (command_line_arg, _("reading directory %s"), name);
3104 if (errno != EOVERFLOW)
3105 break;
3107 else
3108 break;
3110 /* When processing a very large directory, and since we've inhibited
3111 interrupts, this loop would take so long that ls would be annoyingly
3112 uninterruptible. This ensures that it handles signals promptly. */
3113 process_signals ();
3116 if (closedir (dirp) != 0)
3118 file_failure (command_line_arg, _("closing directory %s"), name);
3119 /* Don't return; print whatever we got. */
3122 /* Sort the directory contents. */
3123 sort_files ();
3125 /* If any member files are subdirectories, perhaps they should have their
3126 contents listed rather than being mentioned here as files. */
3128 if (recursive)
3129 extract_dirs_from_files (name, false);
3131 if (format == long_format || print_block_size)
3133 char buf[LONGEST_HUMAN_READABLE + 3];
3134 char *p = human_readable (total_blocks, buf + 1, human_output_opts,
3135 ST_NBLOCKSIZE, output_block_size);
3136 char *pend = p + strlen (p);
3137 *--p = ' ';
3138 *pend++ = eolbyte;
3139 dired_indent ();
3140 dired_outstring (_("total"));
3141 dired_outbuf (p, pend - p);
3144 if (cwd_n_used)
3145 print_current_files ();
3148 /* Add 'pattern' to the list of patterns for which files that match are
3149 not listed. */
3151 static void
3152 add_ignore_pattern (char const *pattern)
3154 struct ignore_pattern *ignore;
3156 ignore = xmalloc (sizeof *ignore);
3157 ignore->pattern = pattern;
3158 /* Add it to the head of the linked list. */
3159 ignore->next = ignore_patterns;
3160 ignore_patterns = ignore;
3163 /* Return true if one of the PATTERNS matches FILE. */
3165 static bool
3166 patterns_match (struct ignore_pattern const *patterns, char const *file)
3168 struct ignore_pattern const *p;
3169 for (p = patterns; p; p = p->next)
3170 if (fnmatch (p->pattern, file, FNM_PERIOD) == 0)
3171 return true;
3172 return false;
3175 /* Return true if FILE should be ignored. */
3177 static bool
3178 file_ignored (char const *name)
3180 return ((ignore_mode != IGNORE_MINIMAL
3181 && name[0] == '.'
3182 && (ignore_mode == IGNORE_DEFAULT || ! name[1 + (name[1] == '.')]))
3183 || (ignore_mode == IGNORE_DEFAULT
3184 && patterns_match (hide_patterns, name))
3185 || patterns_match (ignore_patterns, name));
3188 /* POSIX requires that a file size be printed without a sign, even
3189 when negative. Assume the typical case where negative sizes are
3190 actually positive values that have wrapped around. */
3192 static uintmax_t
3193 unsigned_file_size (off_t size)
3195 return size + (size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
3198 #ifdef HAVE_CAP
3199 /* Return true if NAME has a capability (see linux/capability.h) */
3200 static bool
3201 has_capability (char const *name)
3203 char *result;
3204 bool has_cap;
3206 cap_t cap_d = cap_get_file (name);
3207 if (cap_d == nullptr)
3208 return false;
3210 result = cap_to_text (cap_d, nullptr);
3211 cap_free (cap_d);
3212 if (!result)
3213 return false;
3215 /* check if human-readable capability string is empty */
3216 has_cap = !!*result;
3218 cap_free (result);
3219 return has_cap;
3221 #else
3222 static bool
3223 has_capability (MAYBE_UNUSED char const *name)
3225 errno = ENOTSUP;
3226 return false;
3228 #endif
3230 /* Enter and remove entries in the table 'cwd_file'. */
3232 static void
3233 free_ent (struct fileinfo *f)
3235 free (f->name);
3236 free (f->linkname);
3237 free (f->absolute_name);
3238 if (f->scontext != UNKNOWN_SECURITY_CONTEXT)
3240 if (is_smack_enabled ())
3241 free (f->scontext);
3242 else
3243 freecon (f->scontext);
3247 /* Empty the table of files. */
3248 static void
3249 clear_files (void)
3251 for (size_t i = 0; i < cwd_n_used; i++)
3253 struct fileinfo *f = sorted_file[i];
3254 free_ent (f);
3257 cwd_n_used = 0;
3258 cwd_some_quoted = false;
3259 any_has_acl = false;
3260 inode_number_width = 0;
3261 block_size_width = 0;
3262 nlink_width = 0;
3263 owner_width = 0;
3264 group_width = 0;
3265 author_width = 0;
3266 scontext_width = 0;
3267 major_device_number_width = 0;
3268 minor_device_number_width = 0;
3269 file_size_width = 0;
3272 /* Return true if ERR implies lack-of-support failure by a
3273 getxattr-calling function like getfilecon or file_has_acl. */
3274 static bool
3275 errno_unsupported (int err)
3277 return (err == EINVAL || err == ENOSYS || is_ENOTSUP (err));
3280 /* Cache *getfilecon failure, when it's trivial to do so.
3281 Like getfilecon/lgetfilecon, but when F's st_dev says it's doesn't
3282 support getting the security context, fail with ENOTSUP immediately. */
3283 static int
3284 getfilecon_cache (char const *file, struct fileinfo *f, bool deref)
3286 /* st_dev of the most recently processed device for which we've
3287 found that [l]getfilecon fails indicating lack of support. */
3288 static dev_t unsupported_device;
3290 if (f->stat.st_dev == unsupported_device)
3292 errno = ENOTSUP;
3293 return -1;
3295 int r = 0;
3296 #ifdef HAVE_SMACK
3297 if (is_smack_enabled ())
3298 r = smack_new_label_from_path (file, "security.SMACK64", deref,
3299 &f->scontext);
3300 else
3301 #endif
3302 r = (deref
3303 ? getfilecon (file, &f->scontext)
3304 : lgetfilecon (file, &f->scontext));
3305 if (r < 0 && errno_unsupported (errno))
3306 unsupported_device = f->stat.st_dev;
3307 return r;
3310 /* Cache file_has_acl failure, when it's trivial to do.
3311 Like file_has_acl, but when F's st_dev says it's on a file
3312 system lacking ACL support, return 0 with ENOTSUP immediately. */
3313 static int
3314 file_has_acl_cache (char const *file, struct fileinfo *f)
3316 /* st_dev of the most recently processed device for which we've
3317 found that file_has_acl fails indicating lack of support. */
3318 static dev_t unsupported_device;
3320 if (f->stat.st_dev == unsupported_device)
3322 errno = ENOTSUP;
3323 return 0;
3326 /* Zero errno so that we can distinguish between two 0-returning cases:
3327 "has-ACL-support, but only a default ACL" and "no ACL support". */
3328 errno = 0;
3329 int n = file_has_acl (file, &f->stat);
3330 if (n <= 0 && errno_unsupported (errno))
3331 unsupported_device = f->stat.st_dev;
3332 return n;
3335 /* Cache has_capability failure, when it's trivial to do.
3336 Like has_capability, but when F's st_dev says it's on a file
3337 system lacking capability support, return 0 with ENOTSUP immediately. */
3338 static bool
3339 has_capability_cache (char const *file, struct fileinfo *f)
3341 /* st_dev of the most recently processed device for which we've
3342 found that has_capability fails indicating lack of support. */
3343 static dev_t unsupported_device;
3345 if (f->stat.st_dev == unsupported_device)
3347 errno = ENOTSUP;
3348 return 0;
3351 bool b = has_capability (file);
3352 if ( !b && errno_unsupported (errno))
3353 unsupported_device = f->stat.st_dev;
3354 return b;
3357 static bool
3358 needs_quoting (char const *name)
3360 char test[2];
3361 size_t len = quotearg_buffer (test, sizeof test , name, -1,
3362 filename_quoting_options);
3363 return *name != *test || strlen (name) != len;
3366 /* Add a file to the current table of files.
3367 Verify that the file exists, and print an error message if it does not.
3368 Return the number of blocks that the file occupies. */
3369 static uintmax_t
3370 gobble_file (char const *name, enum filetype type, ino_t inode,
3371 bool command_line_arg, char const *dirname)
3373 uintmax_t blocks = 0;
3374 struct fileinfo *f;
3376 /* An inode value prior to gobble_file necessarily came from readdir,
3377 which is not used for command line arguments. */
3378 affirm (! command_line_arg || inode == NOT_AN_INODE_NUMBER);
3380 if (cwd_n_used == cwd_n_alloc)
3382 cwd_file = xnrealloc (cwd_file, cwd_n_alloc, 2 * sizeof *cwd_file);
3383 cwd_n_alloc *= 2;
3386 f = &cwd_file[cwd_n_used];
3387 memset (f, '\0', sizeof *f);
3388 f->stat.st_ino = inode;
3389 f->filetype = type;
3391 f->quoted = -1;
3392 if ((! cwd_some_quoted) && align_variable_outer_quotes)
3394 /* Determine if any quoted for padding purposes. */
3395 f->quoted = needs_quoting (name);
3396 if (f->quoted)
3397 cwd_some_quoted = 1;
3400 if (command_line_arg
3401 || print_hyperlink
3402 || format_needs_stat
3403 /* When coloring a directory (we may know the type from
3404 direct.d_type), we have to stat it in order to indicate
3405 sticky and/or other-writable attributes. */
3406 || (type == directory && print_with_color
3407 && (is_colored (C_OTHER_WRITABLE)
3408 || is_colored (C_STICKY)
3409 || is_colored (C_STICKY_OTHER_WRITABLE)))
3410 /* When dereferencing symlinks, the inode and type must come from
3411 stat, but readdir provides the inode and type of lstat. */
3412 || ((print_inode || format_needs_type)
3413 && (type == symbolic_link || type == unknown)
3414 && (dereference == DEREF_ALWAYS
3415 || color_symlink_as_referent || check_symlink_mode))
3416 /* Command line dereferences are already taken care of by the above
3417 assertion that the inode number is not yet known. */
3418 || (print_inode && inode == NOT_AN_INODE_NUMBER)
3419 || (format_needs_type
3420 && (type == unknown || command_line_arg
3421 /* --indicator-style=classify (aka -F)
3422 requires that we stat each regular file
3423 to see if it's executable. */
3424 || (type == normal && (indicator_style == classify
3425 /* This is so that --color ends up
3426 highlighting files with these mode
3427 bits set even when options like -F are
3428 not specified. Note we do a redundant
3429 stat in the very unlikely case where
3430 C_CAP is set but not the others. */
3431 || (print_with_color
3432 && (is_colored (C_EXEC)
3433 || is_colored (C_SETUID)
3434 || is_colored (C_SETGID)
3435 || is_colored (C_CAP)))
3436 )))))
3439 /* Absolute name of this file. */
3440 char *full_name;
3441 bool do_deref;
3442 int err;
3444 if (name[0] == '/' || dirname[0] == 0)
3445 full_name = (char *) name;
3446 else
3448 full_name = alloca (strlen (name) + strlen (dirname) + 2);
3449 attach (full_name, dirname, name);
3452 if (print_hyperlink)
3454 f->absolute_name = canonicalize_filename_mode (full_name,
3455 CAN_MISSING);
3456 if (! f->absolute_name)
3457 file_failure (command_line_arg,
3458 _("error canonicalizing %s"), full_name);
3461 switch (dereference)
3463 case DEREF_ALWAYS:
3464 err = do_stat (full_name, &f->stat);
3465 do_deref = true;
3466 break;
3468 case DEREF_COMMAND_LINE_ARGUMENTS:
3469 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
3470 if (command_line_arg)
3472 bool need_lstat;
3473 err = do_stat (full_name, &f->stat);
3474 do_deref = true;
3476 if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
3477 break;
3479 need_lstat = (err < 0
3480 ? (errno == ENOENT || errno == ELOOP)
3481 : ! S_ISDIR (f->stat.st_mode));
3482 if (!need_lstat)
3483 break;
3485 /* stat failed because of ENOENT || ELOOP, maybe indicating a
3486 non-traversable symlink. Or stat succeeded,
3487 FULL_NAME does not refer to a directory,
3488 and --dereference-command-line-symlink-to-dir is in effect.
3489 Fall through so that we call lstat instead. */
3491 FALLTHROUGH;
3493 default: /* DEREF_NEVER */
3494 err = do_lstat (full_name, &f->stat);
3495 do_deref = false;
3496 break;
3499 if (err != 0)
3501 /* Failure to stat a command line argument leads to
3502 an exit status of 2. For other files, stat failure
3503 provokes an exit status of 1. */
3504 file_failure (command_line_arg,
3505 _("cannot access %s"), full_name);
3507 f->scontext = UNKNOWN_SECURITY_CONTEXT;
3509 if (command_line_arg)
3510 return 0;
3512 f->name = xstrdup (name);
3513 cwd_n_used++;
3515 return 0;
3518 f->stat_ok = true;
3520 /* Note has_capability() adds around 30% runtime to 'ls --color' */
3521 if ((type == normal || S_ISREG (f->stat.st_mode))
3522 && print_with_color && is_colored (C_CAP))
3523 f->has_capability = has_capability_cache (full_name, f);
3525 if (format == long_format || print_scontext)
3527 bool have_scontext = false;
3528 bool have_acl = false;
3529 int attr_len = getfilecon_cache (full_name, f, do_deref);
3530 err = (attr_len < 0);
3532 if (err == 0)
3534 if (is_smack_enabled ())
3535 have_scontext = ! STREQ ("_", f->scontext);
3536 else
3537 have_scontext = ! STREQ ("unlabeled", f->scontext);
3539 else
3541 f->scontext = UNKNOWN_SECURITY_CONTEXT;
3543 /* When requesting security context information, don't make
3544 ls fail just because the file (even a command line argument)
3545 isn't on the right type of file system. I.e., a getfilecon
3546 failure isn't in the same class as a stat failure. */
3547 if (is_ENOTSUP (errno) || errno == ENODATA)
3548 err = 0;
3551 if (err == 0 && format == long_format)
3553 int n = file_has_acl_cache (full_name, f);
3554 err = (n < 0);
3555 have_acl = (0 < n);
3558 f->acl_type = (!have_scontext && !have_acl
3559 ? ACL_T_NONE
3560 : (have_scontext && !have_acl
3561 ? ACL_T_LSM_CONTEXT_ONLY
3562 : ACL_T_YES));
3563 any_has_acl |= f->acl_type != ACL_T_NONE;
3565 if (err)
3566 error (0, errno, "%s", quotef (full_name));
3569 if (S_ISLNK (f->stat.st_mode)
3570 && (format == long_format || check_symlink_mode))
3572 struct stat linkstats;
3574 get_link_name (full_name, f, command_line_arg);
3576 /* Use the slower quoting path for this entry, though
3577 don't update CWD_SOME_QUOTED since alignment not affected. */
3578 if (f->linkname && f->quoted == 0 && needs_quoting (f->linkname))
3579 f->quoted = -1;
3581 /* Avoid following symbolic links when possible, i.e., when
3582 they won't be traced and when no indicator is needed. */
3583 if (f->linkname
3584 && (file_type <= indicator_style || check_symlink_mode)
3585 && stat_for_mode (full_name, &linkstats) == 0)
3587 f->linkok = true;
3588 f->linkmode = linkstats.st_mode;
3592 if (S_ISLNK (f->stat.st_mode))
3593 f->filetype = symbolic_link;
3594 else if (S_ISDIR (f->stat.st_mode))
3596 if (command_line_arg && !immediate_dirs)
3597 f->filetype = arg_directory;
3598 else
3599 f->filetype = directory;
3601 else
3602 f->filetype = normal;
3604 blocks = STP_NBLOCKS (&f->stat);
3605 if (format == long_format || print_block_size)
3607 char buf[LONGEST_HUMAN_READABLE + 1];
3608 int len = mbswidth (human_readable (blocks, buf, human_output_opts,
3609 ST_NBLOCKSIZE, output_block_size),
3610 MBSWIDTH_FLAGS);
3611 if (block_size_width < len)
3612 block_size_width = len;
3615 if (format == long_format)
3617 if (print_owner)
3619 int len = format_user_width (f->stat.st_uid);
3620 if (owner_width < len)
3621 owner_width = len;
3624 if (print_group)
3626 int len = format_group_width (f->stat.st_gid);
3627 if (group_width < len)
3628 group_width = len;
3631 if (print_author)
3633 int len = format_user_width (f->stat.st_author);
3634 if (author_width < len)
3635 author_width = len;
3639 if (print_scontext)
3641 int len = strlen (f->scontext);
3642 if (scontext_width < len)
3643 scontext_width = len;
3646 if (format == long_format)
3648 char b[INT_BUFSIZE_BOUND (uintmax_t)];
3649 int b_len = strlen (umaxtostr (f->stat.st_nlink, b));
3650 if (nlink_width < b_len)
3651 nlink_width = b_len;
3653 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
3655 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
3656 int len = strlen (umaxtostr (major (f->stat.st_rdev), buf));
3657 if (major_device_number_width < len)
3658 major_device_number_width = len;
3659 len = strlen (umaxtostr (minor (f->stat.st_rdev), buf));
3660 if (minor_device_number_width < len)
3661 minor_device_number_width = len;
3662 len = major_device_number_width + 2 + minor_device_number_width;
3663 if (file_size_width < len)
3664 file_size_width = len;
3666 else
3668 char buf[LONGEST_HUMAN_READABLE + 1];
3669 uintmax_t size = unsigned_file_size (f->stat.st_size);
3670 int len = mbswidth (human_readable (size, buf,
3671 file_human_output_opts,
3672 1, file_output_block_size),
3673 MBSWIDTH_FLAGS);
3674 if (file_size_width < len)
3675 file_size_width = len;
3680 if (print_inode)
3682 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
3683 int len = strlen (umaxtostr (f->stat.st_ino, buf));
3684 if (inode_number_width < len)
3685 inode_number_width = len;
3688 f->name = xstrdup (name);
3689 cwd_n_used++;
3691 return blocks;
3694 /* Return true if F refers to a directory. */
3695 static bool
3696 is_directory (const struct fileinfo *f)
3698 return f->filetype == directory || f->filetype == arg_directory;
3701 /* Return true if F refers to a (symlinked) directory. */
3702 static bool
3703 is_linked_directory (const struct fileinfo *f)
3705 return f->filetype == directory || f->filetype == arg_directory
3706 || S_ISDIR (f->linkmode);
3709 /* Put the name of the file that FILENAME is a symbolic link to
3710 into the LINKNAME field of 'f'. COMMAND_LINE_ARG indicates whether
3711 FILENAME is a command-line argument. */
3713 static void
3714 get_link_name (char const *filename, struct fileinfo *f, bool command_line_arg)
3716 f->linkname = areadlink_with_size (filename, f->stat.st_size);
3717 if (f->linkname == nullptr)
3718 file_failure (command_line_arg, _("cannot read symbolic link %s"),
3719 filename);
3722 /* Return true if the last component of NAME is '.' or '..'
3723 This is so we don't try to recurse on '././././. ...' */
3725 static bool
3726 basename_is_dot_or_dotdot (char const *name)
3728 char const *base = last_component (name);
3729 return dot_or_dotdot (base);
3732 /* Remove any entries from CWD_FILE that are for directories,
3733 and queue them to be listed as directories instead.
3734 DIRNAME is the prefix to prepend to each dirname
3735 to make it correct relative to ls's working dir;
3736 if it is null, no prefix is needed and "." and ".." should not be ignored.
3737 If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
3738 This is desirable when processing directories recursively. */
3740 static void
3741 extract_dirs_from_files (char const *dirname, bool command_line_arg)
3743 size_t i;
3744 size_t j;
3745 bool ignore_dot_and_dot_dot = (dirname != nullptr);
3747 if (dirname && LOOP_DETECT)
3749 /* Insert a marker entry first. When we dequeue this marker entry,
3750 we'll know that DIRNAME has been processed and may be removed
3751 from the set of active directories. */
3752 queue_directory (nullptr, dirname, false);
3755 /* Queue the directories last one first, because queueing reverses the
3756 order. */
3757 for (i = cwd_n_used; i-- != 0; )
3759 struct fileinfo *f = sorted_file[i];
3761 if (is_directory (f)
3762 && (! ignore_dot_and_dot_dot
3763 || ! basename_is_dot_or_dotdot (f->name)))
3765 if (!dirname || f->name[0] == '/')
3766 queue_directory (f->name, f->linkname, command_line_arg);
3767 else
3769 char *name = file_name_concat (dirname, f->name, nullptr);
3770 queue_directory (name, f->linkname, command_line_arg);
3771 free (name);
3773 if (f->filetype == arg_directory)
3774 free_ent (f);
3778 /* Now delete the directories from the table, compacting all the remaining
3779 entries. */
3781 for (i = 0, j = 0; i < cwd_n_used; i++)
3783 struct fileinfo *f = sorted_file[i];
3784 sorted_file[j] = f;
3785 j += (f->filetype != arg_directory);
3787 cwd_n_used = j;
3790 /* Use strcoll to compare strings in this locale. If an error occurs,
3791 report an error and longjmp to failed_strcoll. */
3793 static jmp_buf failed_strcoll;
3795 static int
3796 xstrcoll (char const *a, char const *b)
3798 int diff;
3799 errno = 0;
3800 diff = strcoll (a, b);
3801 if (errno)
3803 error (0, errno, _("cannot compare file names %s and %s"),
3804 quote_n (0, a), quote_n (1, b));
3805 set_exit_status (false);
3806 longjmp (failed_strcoll, 1);
3808 return diff;
3811 /* Comparison routines for sorting the files. */
3813 typedef void const *V;
3814 typedef int (*qsortFunc)(V a, V b);
3816 /* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants. */
3817 static int
3818 dirfirst_check (struct fileinfo const *a, struct fileinfo const *b,
3819 int (*cmp) (V, V))
3821 int diff = is_linked_directory (b) - is_linked_directory (a);
3822 return diff ? diff : cmp (a, b);
3825 /* Define the 8 different sort function variants required for each sortkey.
3826 KEY_NAME is a token describing the sort key, e.g., ctime, atime, size.
3827 KEY_CMP_FUNC is a function to compare records based on that key, e.g.,
3828 ctime_cmp, atime_cmp, size_cmp. Append KEY_NAME to the string,
3829 '[rev_][x]str{cmp|coll}[_df]_', to create each function name. */
3830 #define DEFINE_SORT_FUNCTIONS(key_name, key_cmp_func) \
3831 /* direct, non-dirfirst versions */ \
3832 static int xstrcoll_##key_name (V a, V b) \
3833 { return key_cmp_func (a, b, xstrcoll); } \
3834 ATTRIBUTE_PURE static int strcmp_##key_name (V a, V b) \
3835 { return key_cmp_func (a, b, strcmp); } \
3837 /* reverse, non-dirfirst versions */ \
3838 static int rev_xstrcoll_##key_name (V a, V b) \
3839 { return key_cmp_func (b, a, xstrcoll); } \
3840 ATTRIBUTE_PURE static int rev_strcmp_##key_name (V a, V b) \
3841 { return key_cmp_func (b, a, strcmp); } \
3843 /* direct, dirfirst versions */ \
3844 static int xstrcoll_df_##key_name (V a, V b) \
3845 { return dirfirst_check (a, b, xstrcoll_##key_name); } \
3846 ATTRIBUTE_PURE static int strcmp_df_##key_name (V a, V b) \
3847 { return dirfirst_check (a, b, strcmp_##key_name); } \
3849 /* reverse, dirfirst versions */ \
3850 static int rev_xstrcoll_df_##key_name (V a, V b) \
3851 { return dirfirst_check (a, b, rev_xstrcoll_##key_name); } \
3852 ATTRIBUTE_PURE static int rev_strcmp_df_##key_name (V a, V b) \
3853 { return dirfirst_check (a, b, rev_strcmp_##key_name); }
3855 static int
3856 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
3857 int (*cmp) (char const *, char const *))
3859 int diff = timespec_cmp (get_stat_ctime (&b->stat),
3860 get_stat_ctime (&a->stat));
3861 return diff ? diff : cmp (a->name, b->name);
3864 static int
3865 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
3866 int (*cmp) (char const *, char const *))
3868 int diff = timespec_cmp (get_stat_mtime (&b->stat),
3869 get_stat_mtime (&a->stat));
3870 return diff ? diff : cmp (a->name, b->name);
3873 static int
3874 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
3875 int (*cmp) (char const *, char const *))
3877 int diff = timespec_cmp (get_stat_atime (&b->stat),
3878 get_stat_atime (&a->stat));
3879 return diff ? diff : cmp (a->name, b->name);
3882 static int
3883 cmp_btime (struct fileinfo const *a, struct fileinfo const *b,
3884 int (*cmp) (char const *, char const *))
3886 int diff = timespec_cmp (get_stat_btime (&b->stat),
3887 get_stat_btime (&a->stat));
3888 return diff ? diff : cmp (a->name, b->name);
3891 static int
3892 off_cmp (off_t a, off_t b)
3894 return (a > b) - (a < b);
3897 static int
3898 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
3899 int (*cmp) (char const *, char const *))
3901 int diff = off_cmp (b->stat.st_size, a->stat.st_size);
3902 return diff ? diff : cmp (a->name, b->name);
3905 static int
3906 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
3907 int (*cmp) (char const *, char const *))
3909 return cmp (a->name, b->name);
3912 /* Compare file extensions. Files with no extension are 'smallest'.
3913 If extensions are the same, compare by file names instead. */
3915 static int
3916 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
3917 int (*cmp) (char const *, char const *))
3919 char const *base1 = strrchr (a->name, '.');
3920 char const *base2 = strrchr (b->name, '.');
3921 int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
3922 return diff ? diff : cmp (a->name, b->name);
3925 /* Return the (cached) screen width,
3926 for the NAME associated with the passed fileinfo F. */
3928 static size_t
3929 fileinfo_name_width (struct fileinfo const *f)
3931 return f->width
3932 ? f->width
3933 : quote_name_width (f->name, filename_quoting_options, f->quoted);
3936 static int
3937 cmp_width (struct fileinfo const *a, struct fileinfo const *b,
3938 int (*cmp) (char const *, char const *))
3940 int diff = fileinfo_name_width (a) - fileinfo_name_width (b);
3941 return diff ? diff : cmp (a->name, b->name);
3944 DEFINE_SORT_FUNCTIONS (ctime, cmp_ctime)
3945 DEFINE_SORT_FUNCTIONS (mtime, cmp_mtime)
3946 DEFINE_SORT_FUNCTIONS (atime, cmp_atime)
3947 DEFINE_SORT_FUNCTIONS (btime, cmp_btime)
3948 DEFINE_SORT_FUNCTIONS (size, cmp_size)
3949 DEFINE_SORT_FUNCTIONS (name, cmp_name)
3950 DEFINE_SORT_FUNCTIONS (extension, cmp_extension)
3951 DEFINE_SORT_FUNCTIONS (width, cmp_width)
3953 /* Compare file versions.
3954 Unlike the other compare functions, cmp_version does not fail
3955 because filevercmp and strcmp do not fail; cmp_version uses strcmp
3956 instead of xstrcoll because filevercmp is locale-independent so
3957 strcmp is its appropriate secondary.
3959 All the other sort options need xstrcoll and strcmp variants,
3960 because they all use xstrcoll (either as the primary or secondary
3961 sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
3962 locale reasons. */
3963 static int
3964 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
3966 int diff = filevercmp (a->name, b->name);
3967 return diff ? diff : strcmp (a->name, b->name);
3970 static int
3971 xstrcoll_version (V a, V b)
3973 return cmp_version (a, b);
3975 static int
3976 rev_xstrcoll_version (V a, V b)
3978 return cmp_version (b, a);
3980 static int
3981 xstrcoll_df_version (V a, V b)
3983 return dirfirst_check (a, b, xstrcoll_version);
3985 static int
3986 rev_xstrcoll_df_version (V a, V b)
3988 return dirfirst_check (a, b, rev_xstrcoll_version);
3992 /* We have 2^3 different variants for each sort-key function
3993 (for 3 independent sort modes).
3994 The function pointers stored in this array must be dereferenced as:
3996 sort_variants[sort_key][use_strcmp][reverse][dirs_first]
3998 Note that the order in which sort keys are listed in the function pointer
3999 array below is defined by the order of the elements in the time_type and
4000 sort_type enums! */
4002 #define LIST_SORTFUNCTION_VARIANTS(key_name) \
4005 { xstrcoll_##key_name, xstrcoll_df_##key_name }, \
4006 { rev_xstrcoll_##key_name, rev_xstrcoll_df_##key_name }, \
4007 }, \
4009 { strcmp_##key_name, strcmp_df_##key_name }, \
4010 { rev_strcmp_##key_name, rev_strcmp_df_##key_name }, \
4014 static qsortFunc const sort_functions[][2][2][2] =
4016 LIST_SORTFUNCTION_VARIANTS (name),
4017 LIST_SORTFUNCTION_VARIANTS (extension),
4018 LIST_SORTFUNCTION_VARIANTS (width),
4019 LIST_SORTFUNCTION_VARIANTS (size),
4023 { xstrcoll_version, xstrcoll_df_version },
4024 { rev_xstrcoll_version, rev_xstrcoll_df_version },
4027 /* We use nullptr for the strcmp variants of version comparison
4028 since as explained in cmp_version definition, version comparison
4029 does not rely on xstrcoll, so it will never longjmp, and never
4030 need to try the strcmp fallback. */
4032 { nullptr, nullptr },
4033 { nullptr, nullptr },
4037 /* last are time sort functions */
4038 LIST_SORTFUNCTION_VARIANTS (mtime),
4039 LIST_SORTFUNCTION_VARIANTS (ctime),
4040 LIST_SORTFUNCTION_VARIANTS (atime),
4041 LIST_SORTFUNCTION_VARIANTS (btime)
4044 /* The number of sort keys is calculated as the sum of
4045 the number of elements in the sort_type enum (i.e., sort_numtypes)
4046 -2 because neither sort_time nor sort_none use entries themselves
4047 the number of elements in the time_type enum (i.e., time_numtypes)
4048 This is because when sort_type==sort_time, we have up to
4049 time_numtypes possible sort keys.
4051 This line verifies at compile-time that the array of sort functions has been
4052 initialized for all possible sort keys. */
4053 static_assert (ARRAY_CARDINALITY (sort_functions)
4054 == sort_numtypes - 2 + time_numtypes);
4056 /* Set up SORTED_FILE to point to the in-use entries in CWD_FILE, in order. */
4058 static void
4059 initialize_ordering_vector (void)
4061 for (size_t i = 0; i < cwd_n_used; i++)
4062 sorted_file[i] = &cwd_file[i];
4065 /* Cache values based on attributes global to all files. */
4067 static void
4068 update_current_files_info (void)
4070 /* Cache screen width of name, if needed multiple times. */
4071 if (sort_type == sort_width
4072 || (line_length && (format == many_per_line || format == horizontal)))
4074 size_t i;
4075 for (i = 0; i < cwd_n_used; i++)
4077 struct fileinfo *f = sorted_file[i];
4078 f->width = fileinfo_name_width (f);
4083 /* Sort the files now in the table. */
4085 static void
4086 sort_files (void)
4088 bool use_strcmp;
4090 if (sorted_file_alloc < cwd_n_used + cwd_n_used / 2)
4092 free (sorted_file);
4093 sorted_file = xnmalloc (cwd_n_used, 3 * sizeof *sorted_file);
4094 sorted_file_alloc = 3 * cwd_n_used;
4097 initialize_ordering_vector ();
4099 update_current_files_info ();
4101 if (sort_type == sort_none)
4102 return;
4104 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
4105 ignore strcoll failures, as a failing strcoll might be a
4106 comparison function that is not a total order, and if we ignored
4107 the failure this might cause qsort to dump core. */
4109 if (! setjmp (failed_strcoll))
4110 use_strcmp = false; /* strcoll() succeeded */
4111 else
4113 use_strcmp = true;
4114 affirm (sort_type != sort_version);
4115 initialize_ordering_vector ();
4118 /* When sort_type == sort_time, use time_type as subindex. */
4119 mpsort ((void const **) sorted_file, cwd_n_used,
4120 sort_functions[sort_type + (sort_type == sort_time ? time_type : 0)]
4121 [use_strcmp][sort_reverse]
4122 [directories_first]);
4125 /* List all the files now in the table. */
4127 static void
4128 print_current_files (void)
4130 size_t i;
4132 switch (format)
4134 case one_per_line:
4135 for (i = 0; i < cwd_n_used; i++)
4137 print_file_name_and_frills (sorted_file[i], 0);
4138 putchar (eolbyte);
4140 break;
4142 case many_per_line:
4143 if (! line_length)
4144 print_with_separator (' ');
4145 else
4146 print_many_per_line ();
4147 break;
4149 case horizontal:
4150 if (! line_length)
4151 print_with_separator (' ');
4152 else
4153 print_horizontal ();
4154 break;
4156 case with_commas:
4157 print_with_separator (',');
4158 break;
4160 case long_format:
4161 for (i = 0; i < cwd_n_used; i++)
4163 set_normal_color ();
4164 print_long_format (sorted_file[i]);
4165 dired_outbyte (eolbyte);
4167 break;
4171 /* Replace the first %b with precomputed aligned month names.
4172 Note on glibc-2.7 at least, this speeds up the whole 'ls -lU'
4173 process by around 17%, compared to letting strftime() handle the %b. */
4175 static size_t
4176 align_nstrftime (char *buf, size_t size, bool recent, struct tm const *tm,
4177 timezone_t tz, int ns)
4179 char const *nfmt = (use_abformat
4180 ? abformat[recent][tm->tm_mon]
4181 : long_time_format[recent]);
4182 return nstrftime (buf, size, nfmt, tm, tz, ns);
4185 /* Return the expected number of columns in a long-format timestamp,
4186 or zero if it cannot be calculated. */
4188 static int
4189 long_time_expected_width (void)
4191 static int width = -1;
4193 if (width < 0)
4195 time_t epoch = 0;
4196 struct tm tm;
4197 char buf[TIME_STAMP_LEN_MAXIMUM + 1];
4199 /* In case you're wondering if localtime_rz can fail with an input time_t
4200 value of 0, let's just say it's very unlikely, but not inconceivable.
4201 The TZ environment variable would have to specify a time zone that
4202 is 2**31-1900 years or more ahead of UTC. This could happen only on
4203 a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
4204 However, this is not possible with Solaris 10 or glibc-2.3.5, since
4205 their implementations limit the offset to 167:59 and 24:00, resp. */
4206 if (localtime_rz (localtz, &epoch, &tm))
4208 size_t len = align_nstrftime (buf, sizeof buf, false,
4209 &tm, localtz, 0);
4210 if (len != 0)
4211 width = mbsnwidth (buf, len, MBSWIDTH_FLAGS);
4214 if (width < 0)
4215 width = 0;
4218 return width;
4221 /* Print the user or group name NAME, with numeric id ID, using a
4222 print width of WIDTH columns. */
4224 static void
4225 format_user_or_group (char const *name, uintmax_t id, int width)
4227 if (name)
4229 int name_width = mbswidth (name, MBSWIDTH_FLAGS);
4230 int width_gap = name_width < 0 ? 0 : width - name_width;
4231 int pad = MAX (0, width_gap);
4232 dired_outstring (name);
4235 dired_outbyte (' ');
4236 while (pad--);
4238 else
4239 dired_pos += printf ("%*ju ", width, id);
4242 /* Print the name or id of the user with id U, using a print width of
4243 WIDTH. */
4245 static void
4246 format_user (uid_t u, int width, bool stat_ok)
4248 format_user_or_group (! stat_ok ? "?" :
4249 (numeric_ids ? nullptr : getuser (u)), u, width);
4252 /* Likewise, for groups. */
4254 static void
4255 format_group (gid_t g, int width, bool stat_ok)
4257 format_user_or_group (! stat_ok ? "?" :
4258 (numeric_ids ? nullptr : getgroup (g)), g, width);
4261 /* Return the number of columns that format_user_or_group will print,
4262 or -1 if unknown. */
4264 static int
4265 format_user_or_group_width (char const *name, uintmax_t id)
4267 return (name
4268 ? mbswidth (name, MBSWIDTH_FLAGS)
4269 : snprintf (nullptr, 0, "%ju", id));
4272 /* Return the number of columns that format_user will print,
4273 or -1 if unknown. */
4275 static int
4276 format_user_width (uid_t u)
4278 return format_user_or_group_width (numeric_ids ? nullptr : getuser (u), u);
4281 /* Likewise, for groups. */
4283 static int
4284 format_group_width (gid_t g)
4286 return format_user_or_group_width (numeric_ids ? nullptr : getgroup (g), g);
4289 /* Return a pointer to a formatted version of F->stat.st_ino,
4290 possibly using buffer, which must be at least
4291 INT_BUFSIZE_BOUND (uintmax_t) bytes. */
4292 static char *
4293 format_inode (char buf[INT_BUFSIZE_BOUND (uintmax_t)],
4294 const struct fileinfo *f)
4296 return (f->stat_ok && f->stat.st_ino != NOT_AN_INODE_NUMBER
4297 ? umaxtostr (f->stat.st_ino, buf)
4298 : (char *) "?");
4301 /* Print information about F in long format. */
4302 static void
4303 print_long_format (const struct fileinfo *f)
4305 char modebuf[12];
4306 char buf
4307 [LONGEST_HUMAN_READABLE + 1 /* inode */
4308 + LONGEST_HUMAN_READABLE + 1 /* size in blocks */
4309 + sizeof (modebuf) - 1 + 1 /* mode string */
4310 + INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
4311 + LONGEST_HUMAN_READABLE + 2 /* major device number */
4312 + LONGEST_HUMAN_READABLE + 1 /* minor device number */
4313 + TIME_STAMP_LEN_MAXIMUM + 1 /* max length of time/date */
4315 size_t s;
4316 char *p;
4317 struct timespec when_timespec;
4318 struct tm when_local;
4319 bool btime_ok = true;
4321 /* Compute the mode string, except remove the trailing space if no
4322 file in this directory has an ACL or security context. */
4323 if (f->stat_ok)
4324 filemodestring (&f->stat, modebuf);
4325 else
4327 modebuf[0] = filetype_letter[f->filetype];
4328 memset (modebuf + 1, '?', 10);
4329 modebuf[11] = '\0';
4331 if (! any_has_acl)
4332 modebuf[10] = '\0';
4333 else if (f->acl_type == ACL_T_LSM_CONTEXT_ONLY)
4334 modebuf[10] = '.';
4335 else if (f->acl_type == ACL_T_YES)
4336 modebuf[10] = '+';
4338 switch (time_type)
4340 case time_ctime:
4341 when_timespec = get_stat_ctime (&f->stat);
4342 break;
4343 case time_mtime:
4344 when_timespec = get_stat_mtime (&f->stat);
4345 break;
4346 case time_atime:
4347 when_timespec = get_stat_atime (&f->stat);
4348 break;
4349 case time_btime:
4350 when_timespec = get_stat_btime (&f->stat);
4351 if (when_timespec.tv_sec == -1 && when_timespec.tv_nsec == -1)
4352 btime_ok = false;
4353 break;
4354 default:
4355 unreachable ();
4358 p = buf;
4360 if (print_inode)
4362 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
4363 p += sprintf (p, "%*s ", inode_number_width, format_inode (hbuf, f));
4366 if (print_block_size)
4368 char hbuf[LONGEST_HUMAN_READABLE + 1];
4369 char const *blocks =
4370 (! f->stat_ok
4371 ? "?"
4372 : human_readable (STP_NBLOCKS (&f->stat), hbuf, human_output_opts,
4373 ST_NBLOCKSIZE, output_block_size));
4374 int blocks_width = mbswidth (blocks, MBSWIDTH_FLAGS);
4375 for (int pad = blocks_width < 0 ? 0 : block_size_width - blocks_width;
4376 0 < pad; pad--)
4377 *p++ = ' ';
4378 while ((*p++ = *blocks++))
4379 continue;
4380 p[-1] = ' ';
4383 /* The last byte of the mode string is the POSIX
4384 "optional alternate access method flag". */
4386 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
4387 p += sprintf (p, "%s %*s ", modebuf, nlink_width,
4388 ! f->stat_ok ? "?" : umaxtostr (f->stat.st_nlink, hbuf));
4391 dired_indent ();
4393 if (print_owner || print_group || print_author || print_scontext)
4395 dired_outbuf (buf, p - buf);
4397 if (print_owner)
4398 format_user (f->stat.st_uid, owner_width, f->stat_ok);
4400 if (print_group)
4401 format_group (f->stat.st_gid, group_width, f->stat_ok);
4403 if (print_author)
4404 format_user (f->stat.st_author, author_width, f->stat_ok);
4406 if (print_scontext)
4407 format_user_or_group (f->scontext, 0, scontext_width);
4409 p = buf;
4412 if (f->stat_ok
4413 && (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode)))
4415 char majorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
4416 char minorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
4417 int blanks_width = (file_size_width
4418 - (major_device_number_width + 2
4419 + minor_device_number_width));
4420 p += sprintf (p, "%*s, %*s ",
4421 major_device_number_width + MAX (0, blanks_width),
4422 umaxtostr (major (f->stat.st_rdev), majorbuf),
4423 minor_device_number_width,
4424 umaxtostr (minor (f->stat.st_rdev), minorbuf));
4426 else
4428 char hbuf[LONGEST_HUMAN_READABLE + 1];
4429 char const *size =
4430 (! f->stat_ok
4431 ? "?"
4432 : human_readable (unsigned_file_size (f->stat.st_size),
4433 hbuf, file_human_output_opts, 1,
4434 file_output_block_size));
4435 int size_width = mbswidth (size, MBSWIDTH_FLAGS);
4436 for (int pad = size_width < 0 ? 0 : file_size_width - size_width;
4437 0 < pad; pad--)
4438 *p++ = ' ';
4439 while ((*p++ = *size++))
4440 continue;
4441 p[-1] = ' ';
4444 s = 0;
4445 *p = '\1';
4447 if (f->stat_ok && btime_ok
4448 && localtime_rz (localtz, &when_timespec.tv_sec, &when_local))
4450 struct timespec six_months_ago;
4451 bool recent;
4453 /* If the file appears to be in the future, update the current
4454 time, in case the file happens to have been modified since
4455 the last time we checked the clock. */
4456 if (timespec_cmp (current_time, when_timespec) < 0)
4457 gettime (&current_time);
4459 /* Consider a time to be recent if it is within the past six months.
4460 A Gregorian year has 365.2425 * 24 * 60 * 60 == 31556952 seconds
4461 on the average. Write this value as an integer constant to
4462 avoid floating point hassles. */
4463 six_months_ago.tv_sec = current_time.tv_sec - 31556952 / 2;
4464 six_months_ago.tv_nsec = current_time.tv_nsec;
4466 recent = (timespec_cmp (six_months_ago, when_timespec) < 0
4467 && timespec_cmp (when_timespec, current_time) < 0);
4469 /* We assume here that all time zones are offset from UTC by a
4470 whole number of seconds. */
4471 s = align_nstrftime (p, TIME_STAMP_LEN_MAXIMUM + 1, recent,
4472 &when_local, localtz, when_timespec.tv_nsec);
4475 if (s || !*p)
4477 p += s;
4478 *p++ = ' ';
4480 else
4482 /* The time cannot be converted using the desired format, so
4483 print it as a huge integer number of seconds. */
4484 char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
4485 p += sprintf (p, "%*s ", long_time_expected_width (),
4486 (! f->stat_ok || ! btime_ok
4487 ? "?"
4488 : timetostr (when_timespec.tv_sec, hbuf)));
4489 /* FIXME: (maybe) We discarded when_timespec.tv_nsec. */
4492 dired_outbuf (buf, p - buf);
4493 size_t w = print_name_with_quoting (f, false, &dired_obstack, p - buf);
4495 if (f->filetype == symbolic_link)
4497 if (f->linkname)
4499 dired_outstring (" -> ");
4500 print_name_with_quoting (f, true, nullptr, (p - buf) + w + 4);
4501 if (indicator_style != none)
4502 print_type_indicator (true, f->linkmode, unknown);
4505 else if (indicator_style != none)
4506 print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4509 /* Write to *BUF a quoted representation of the file name NAME, if non-null,
4510 using OPTIONS to control quoting. *BUF is set to NAME if no quoting
4511 is required. *BUF is allocated if more space required (and the original
4512 *BUF is not deallocated).
4513 Store the number of screen columns occupied by NAME's quoted
4514 representation into WIDTH, if non-null.
4515 Store into PAD whether an initial space is needed for padding.
4516 Return the number of bytes in *BUF. */
4518 static size_t
4519 quote_name_buf (char **inbuf, size_t bufsize, char *name,
4520 struct quoting_options const *options,
4521 int needs_general_quoting, size_t *width, bool *pad)
4523 char *buf = *inbuf;
4524 size_t displayed_width IF_LINT ( = 0);
4525 size_t len = 0;
4526 bool quoted;
4528 enum quoting_style qs = get_quoting_style (options);
4529 bool needs_further_quoting = qmark_funny_chars
4530 && (qs == shell_quoting_style
4531 || qs == shell_always_quoting_style
4532 || qs == literal_quoting_style);
4534 if (needs_general_quoting != 0)
4536 len = quotearg_buffer (buf, bufsize, name, -1, options);
4537 if (bufsize <= len)
4539 buf = xmalloc (len + 1);
4540 quotearg_buffer (buf, len + 1, name, -1, options);
4543 quoted = (*name != *buf) || strlen (name) != len;
4545 else if (needs_further_quoting)
4547 len = strlen (name);
4548 if (bufsize <= len)
4549 buf = xmalloc (len + 1);
4550 memcpy (buf, name, len + 1);
4552 quoted = false;
4554 else
4556 len = strlen (name);
4557 buf = name;
4558 quoted = false;
4561 if (needs_further_quoting)
4563 if (MB_CUR_MAX > 1)
4565 char const *p = buf;
4566 char const *plimit = buf + len;
4567 char *q = buf;
4568 displayed_width = 0;
4570 while (p < plimit)
4571 switch (*p)
4573 case ' ': case '!': case '"': case '#': case '%':
4574 case '&': case '\'': case '(': case ')': case '*':
4575 case '+': case ',': case '-': case '.': case '/':
4576 case '0': case '1': case '2': case '3': case '4':
4577 case '5': case '6': case '7': case '8': case '9':
4578 case ':': case ';': case '<': case '=': case '>':
4579 case '?':
4580 case 'A': case 'B': case 'C': case 'D': case 'E':
4581 case 'F': case 'G': case 'H': case 'I': case 'J':
4582 case 'K': case 'L': case 'M': case 'N': case 'O':
4583 case 'P': case 'Q': case 'R': case 'S': case 'T':
4584 case 'U': case 'V': case 'W': case 'X': case 'Y':
4585 case 'Z':
4586 case '[': case '\\': case ']': case '^': case '_':
4587 case 'a': case 'b': case 'c': case 'd': case 'e':
4588 case 'f': case 'g': case 'h': case 'i': case 'j':
4589 case 'k': case 'l': case 'm': case 'n': case 'o':
4590 case 'p': case 'q': case 'r': case 's': case 't':
4591 case 'u': case 'v': case 'w': case 'x': case 'y':
4592 case 'z': case '{': case '|': case '}': case '~':
4593 /* These characters are printable ASCII characters. */
4594 *q++ = *p++;
4595 displayed_width += 1;
4596 break;
4597 default:
4598 /* If we have a multibyte sequence, copy it until we
4599 reach its end, replacing each non-printable multibyte
4600 character with a single question mark. */
4602 mbstate_t mbstate; mbszero (&mbstate);
4605 char32_t wc;
4606 size_t bytes;
4607 int w;
4609 bytes = mbrtoc32 (&wc, p, plimit - p, &mbstate);
4611 if (bytes == (size_t) -1)
4613 /* An invalid multibyte sequence was
4614 encountered. Skip one input byte, and
4615 put a question mark. */
4616 p++;
4617 *q++ = '?';
4618 displayed_width += 1;
4619 break;
4622 if (bytes == (size_t) -2)
4624 /* An incomplete multibyte character
4625 at the end. Replace it entirely with
4626 a question mark. */
4627 p = plimit;
4628 *q++ = '?';
4629 displayed_width += 1;
4630 break;
4633 if (bytes == 0)
4634 /* A null wide character was encountered. */
4635 bytes = 1;
4637 w = c32width (wc);
4638 if (w >= 0)
4640 /* A printable multibyte character.
4641 Keep it. */
4642 for (; bytes > 0; --bytes)
4643 *q++ = *p++;
4644 displayed_width += w;
4646 else
4648 /* An nonprintable multibyte character.
4649 Replace it entirely with a question
4650 mark. */
4651 p += bytes;
4652 *q++ = '?';
4653 displayed_width += 1;
4656 while (! mbsinit (&mbstate));
4658 break;
4661 /* The buffer may have shrunk. */
4662 len = q - buf;
4664 else
4666 char *p = buf;
4667 char const *plimit = buf + len;
4669 while (p < plimit)
4671 if (! isprint (to_uchar (*p)))
4672 *p = '?';
4673 p++;
4675 displayed_width = len;
4678 else if (width != nullptr)
4680 if (MB_CUR_MAX > 1)
4682 displayed_width = mbsnwidth (buf, len, MBSWIDTH_FLAGS);
4683 displayed_width = MAX (0, displayed_width);
4685 else
4687 char const *p = buf;
4688 char const *plimit = buf + len;
4690 displayed_width = 0;
4691 while (p < plimit)
4693 if (isprint (to_uchar (*p)))
4694 displayed_width++;
4695 p++;
4700 /* Set padding to better align quoted items,
4701 and also give a visual indication that quotes are
4702 not actually part of the name. */
4703 *pad = (align_variable_outer_quotes && cwd_some_quoted && ! quoted);
4705 if (width != nullptr)
4706 *width = displayed_width;
4708 *inbuf = buf;
4710 return len;
4713 static size_t
4714 quote_name_width (char const *name, struct quoting_options const *options,
4715 int needs_general_quoting)
4717 char smallbuf[BUFSIZ];
4718 char *buf = smallbuf;
4719 size_t width;
4720 bool pad;
4722 quote_name_buf (&buf, sizeof smallbuf, (char *) name, options,
4723 needs_general_quoting, &width, &pad);
4725 if (buf != smallbuf && buf != name)
4726 free (buf);
4728 width += pad;
4730 return width;
4733 /* %XX escape any input out of range as defined in RFC3986,
4734 and also if PATH, convert all path separators to '/'. */
4735 static char *
4736 file_escape (char const *str, bool path)
4738 char *esc = xnmalloc (3, strlen (str) + 1);
4739 char *p = esc;
4740 while (*str)
4742 if (path && ISSLASH (*str))
4744 *p++ = '/';
4745 str++;
4747 else if (RFC3986[to_uchar (*str)])
4748 *p++ = *str++;
4749 else
4750 p += sprintf (p, "%%%02x", to_uchar (*str++));
4752 *p = '\0';
4753 return esc;
4756 static size_t
4757 quote_name (char const *name, struct quoting_options const *options,
4758 int needs_general_quoting, const struct bin_str *color,
4759 bool allow_pad, struct obstack *stack, char const *absolute_name)
4761 char smallbuf[BUFSIZ];
4762 char *buf = smallbuf;
4763 size_t len;
4764 bool pad;
4766 len = quote_name_buf (&buf, sizeof smallbuf, (char *) name, options,
4767 needs_general_quoting, nullptr, &pad);
4769 if (pad && allow_pad)
4770 dired_outbyte (' ');
4772 if (color)
4773 print_color_indicator (color);
4775 /* If we're padding, then don't include the outer quotes in
4776 the --hyperlink, to improve the alignment of those links. */
4777 bool skip_quotes = false;
4779 if (absolute_name)
4781 if (align_variable_outer_quotes && cwd_some_quoted && ! pad)
4783 skip_quotes = true;
4784 putchar (*buf);
4786 char *h = file_escape (hostname, /* path= */ false);
4787 char *n = file_escape (absolute_name, /* path= */ true);
4788 /* TODO: It would be good to be able to define parameters
4789 to give hints to the terminal as how best to render the URI.
4790 For example since ls is outputting a dense block of URIs
4791 it would be best to not underline by default, and only
4792 do so upon hover etc. */
4793 printf ("\033]8;;file://%s%s%s\a", h, *n == '/' ? "" : "/", n);
4794 free (h);
4795 free (n);
4798 if (stack)
4799 push_current_dired_pos (stack);
4801 fwrite (buf + skip_quotes, 1, len - (skip_quotes * 2), stdout);
4803 dired_pos += len;
4805 if (stack)
4806 push_current_dired_pos (stack);
4808 if (absolute_name)
4810 fputs ("\033]8;;\a", stdout);
4811 if (skip_quotes)
4812 putchar (*(buf + len - 1));
4815 if (buf != smallbuf && buf != name)
4816 free (buf);
4818 return len + pad;
4821 static size_t
4822 print_name_with_quoting (const struct fileinfo *f,
4823 bool symlink_target,
4824 struct obstack *stack,
4825 size_t start_col)
4827 char const *name = symlink_target ? f->linkname : f->name;
4829 const struct bin_str *color
4830 = print_with_color ? get_color_indicator (f, symlink_target) : nullptr;
4832 bool used_color_this_time = (print_with_color
4833 && (color || is_colored (C_NORM)));
4835 size_t len = quote_name (name, filename_quoting_options, f->quoted,
4836 color, !symlink_target, stack, f->absolute_name);
4838 process_signals ();
4839 if (used_color_this_time)
4841 prep_non_filename_text ();
4843 /* We use the byte length rather than display width here as
4844 an optimization to avoid accurately calculating the width,
4845 because we only output the clear to EOL sequence if the name
4846 _might_ wrap to the next line. This may output a sequence
4847 unnecessarily in multi-byte locales for example,
4848 but in that case it's inconsequential to the output. */
4849 if (line_length
4850 && (start_col / line_length != (start_col + len - 1) / line_length))
4851 put_indicator (&color_indicator[C_CLR_TO_EOL]);
4854 return len;
4857 static void
4858 prep_non_filename_text (void)
4860 if (color_indicator[C_END].string != nullptr)
4861 put_indicator (&color_indicator[C_END]);
4862 else
4864 put_indicator (&color_indicator[C_LEFT]);
4865 put_indicator (&color_indicator[C_RESET]);
4866 put_indicator (&color_indicator[C_RIGHT]);
4870 /* Print the file name of 'f' with appropriate quoting.
4871 Also print file size, inode number, and filetype indicator character,
4872 as requested by switches. */
4874 static size_t
4875 print_file_name_and_frills (const struct fileinfo *f, size_t start_col)
4877 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
4879 set_normal_color ();
4881 if (print_inode)
4882 printf ("%*s ", format == with_commas ? 0 : inode_number_width,
4883 format_inode (buf, f));
4885 if (print_block_size)
4886 printf ("%*s ", format == with_commas ? 0 : block_size_width,
4887 ! f->stat_ok ? "?"
4888 : human_readable (STP_NBLOCKS (&f->stat), buf, human_output_opts,
4889 ST_NBLOCKSIZE, output_block_size));
4891 if (print_scontext)
4892 printf ("%*s ", format == with_commas ? 0 : scontext_width, f->scontext);
4894 size_t width = print_name_with_quoting (f, false, nullptr, start_col);
4896 if (indicator_style != none)
4897 width += print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4899 return width;
4902 /* Given these arguments describing a file, return the single-byte
4903 type indicator, or 0. */
4904 static char
4905 get_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
4907 char c;
4909 if (stat_ok ? S_ISREG (mode) : type == normal)
4911 if (stat_ok && indicator_style == classify && (mode & S_IXUGO))
4912 c = '*';
4913 else
4914 c = 0;
4916 else
4918 if (stat_ok ? S_ISDIR (mode) : type == directory || type == arg_directory)
4919 c = '/';
4920 else if (indicator_style == slash)
4921 c = 0;
4922 else if (stat_ok ? S_ISLNK (mode) : type == symbolic_link)
4923 c = '@';
4924 else if (stat_ok ? S_ISFIFO (mode) : type == fifo)
4925 c = '|';
4926 else if (stat_ok ? S_ISSOCK (mode) : type == sock)
4927 c = '=';
4928 else if (stat_ok && S_ISDOOR (mode))
4929 c = '>';
4930 else
4931 c = 0;
4933 return c;
4936 static bool
4937 print_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
4939 char c = get_type_indicator (stat_ok, mode, type);
4940 if (c)
4941 dired_outbyte (c);
4942 return !!c;
4945 /* Returns if color sequence was printed. */
4946 static bool
4947 print_color_indicator (const struct bin_str *ind)
4949 if (ind)
4951 /* Need to reset so not dealing with attribute combinations */
4952 if (is_colored (C_NORM))
4953 restore_default_color ();
4954 put_indicator (&color_indicator[C_LEFT]);
4955 put_indicator (ind);
4956 put_indicator (&color_indicator[C_RIGHT]);
4959 return ind != nullptr;
4962 /* Returns color indicator or nullptr if none. */
4963 ATTRIBUTE_PURE
4964 static const struct bin_str*
4965 get_color_indicator (const struct fileinfo *f, bool symlink_target)
4967 enum indicator_no type;
4968 struct color_ext_type *ext; /* Color extension */
4969 size_t len; /* Length of name */
4971 char const *name;
4972 mode_t mode;
4973 int linkok;
4974 if (symlink_target)
4976 name = f->linkname;
4977 mode = f->linkmode;
4978 linkok = f->linkok ? 0 : -1;
4980 else
4982 name = f->name;
4983 mode = file_or_link_mode (f);
4984 linkok = f->linkok;
4987 /* Is this a nonexistent file? If so, linkok == -1. */
4989 if (linkok == -1 && is_colored (C_MISSING))
4990 type = C_MISSING;
4991 else if (!f->stat_ok)
4993 static enum indicator_no filetype_indicator[] = FILETYPE_INDICATORS;
4994 type = filetype_indicator[f->filetype];
4996 else
4998 if (S_ISREG (mode))
5000 type = C_FILE;
5002 if ((mode & S_ISUID) != 0 && is_colored (C_SETUID))
5003 type = C_SETUID;
5004 else if ((mode & S_ISGID) != 0 && is_colored (C_SETGID))
5005 type = C_SETGID;
5006 else if (is_colored (C_CAP) && f->has_capability)
5007 type = C_CAP;
5008 else if ((mode & S_IXUGO) != 0 && is_colored (C_EXEC))
5009 type = C_EXEC;
5010 else if ((1 < f->stat.st_nlink) && is_colored (C_MULTIHARDLINK))
5011 type = C_MULTIHARDLINK;
5013 else if (S_ISDIR (mode))
5015 type = C_DIR;
5017 if ((mode & S_ISVTX) && (mode & S_IWOTH)
5018 && is_colored (C_STICKY_OTHER_WRITABLE))
5019 type = C_STICKY_OTHER_WRITABLE;
5020 else if ((mode & S_IWOTH) != 0 && is_colored (C_OTHER_WRITABLE))
5021 type = C_OTHER_WRITABLE;
5022 else if ((mode & S_ISVTX) != 0 && is_colored (C_STICKY))
5023 type = C_STICKY;
5025 else if (S_ISLNK (mode))
5026 type = C_LINK;
5027 else if (S_ISFIFO (mode))
5028 type = C_FIFO;
5029 else if (S_ISSOCK (mode))
5030 type = C_SOCK;
5031 else if (S_ISBLK (mode))
5032 type = C_BLK;
5033 else if (S_ISCHR (mode))
5034 type = C_CHR;
5035 else if (S_ISDOOR (mode))
5036 type = C_DOOR;
5037 else
5039 /* Classify a file of some other type as C_ORPHAN. */
5040 type = C_ORPHAN;
5044 /* Check the file's suffix only if still classified as C_FILE. */
5045 ext = nullptr;
5046 if (type == C_FILE)
5048 /* Test if NAME has a recognized suffix. */
5050 len = strlen (name);
5051 name += len; /* Pointer to final \0. */
5052 for (ext = color_ext_list; ext != nullptr; ext = ext->next)
5054 if (ext->ext.len <= len)
5056 if (ext->exact_match)
5058 if (STREQ_LEN (name - ext->ext.len, ext->ext.string,
5059 ext->ext.len))
5060 break;
5062 else
5064 if (c_strncasecmp (name - ext->ext.len, ext->ext.string,
5065 ext->ext.len) == 0)
5066 break;
5072 /* Adjust the color for orphaned symlinks. */
5073 if (type == C_LINK && !linkok)
5075 if (color_symlink_as_referent || is_colored (C_ORPHAN))
5076 type = C_ORPHAN;
5079 const struct bin_str *const s
5080 = ext ? &(ext->seq) : &color_indicator[type];
5082 return s->string ? s : nullptr;
5085 /* Output a color indicator (which may contain nulls). */
5086 static void
5087 put_indicator (const struct bin_str *ind)
5089 if (! used_color)
5091 used_color = true;
5093 /* If the standard output is a controlling terminal, watch out
5094 for signals, so that the colors can be restored to the
5095 default state if "ls" is suspended or interrupted. */
5097 if (0 <= tcgetpgrp (STDOUT_FILENO))
5098 signal_init ();
5100 prep_non_filename_text ();
5103 fwrite (ind->string, ind->len, 1, stdout);
5106 static size_t
5107 length_of_file_name_and_frills (const struct fileinfo *f)
5109 size_t len = 0;
5110 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
5112 if (print_inode)
5113 len += 1 + (format == with_commas
5114 ? strlen (umaxtostr (f->stat.st_ino, buf))
5115 : inode_number_width);
5117 if (print_block_size)
5118 len += 1 + (format == with_commas
5119 ? strlen (! f->stat_ok ? "?"
5120 : human_readable (STP_NBLOCKS (&f->stat), buf,
5121 human_output_opts, ST_NBLOCKSIZE,
5122 output_block_size))
5123 : block_size_width);
5125 if (print_scontext)
5126 len += 1 + (format == with_commas ? strlen (f->scontext) : scontext_width);
5128 len += fileinfo_name_width (f);
5130 if (indicator_style != none)
5132 char c = get_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
5133 len += (c != 0);
5136 return len;
5139 static void
5140 print_many_per_line (void)
5142 size_t row; /* Current row. */
5143 size_t cols = calculate_columns (true);
5144 struct column_info const *line_fmt = &column_info[cols - 1];
5146 /* Calculate the number of rows that will be in each column except possibly
5147 for a short column on the right. */
5148 size_t rows = cwd_n_used / cols + (cwd_n_used % cols != 0);
5150 for (row = 0; row < rows; row++)
5152 size_t col = 0;
5153 size_t filesno = row;
5154 size_t pos = 0;
5156 /* Print the next row. */
5157 while (true)
5159 struct fileinfo const *f = sorted_file[filesno];
5160 size_t name_length = length_of_file_name_and_frills (f);
5161 size_t max_name_length = line_fmt->col_arr[col++];
5162 print_file_name_and_frills (f, pos);
5164 filesno += rows;
5165 if (filesno >= cwd_n_used)
5166 break;
5168 indent (pos + name_length, pos + max_name_length);
5169 pos += max_name_length;
5171 putchar (eolbyte);
5175 static void
5176 print_horizontal (void)
5178 size_t filesno;
5179 size_t pos = 0;
5180 size_t cols = calculate_columns (false);
5181 struct column_info const *line_fmt = &column_info[cols - 1];
5182 struct fileinfo const *f = sorted_file[0];
5183 size_t name_length = length_of_file_name_and_frills (f);
5184 size_t max_name_length = line_fmt->col_arr[0];
5186 /* Print first entry. */
5187 print_file_name_and_frills (f, 0);
5189 /* Now the rest. */
5190 for (filesno = 1; filesno < cwd_n_used; ++filesno)
5192 size_t col = filesno % cols;
5194 if (col == 0)
5196 putchar (eolbyte);
5197 pos = 0;
5199 else
5201 indent (pos + name_length, pos + max_name_length);
5202 pos += max_name_length;
5205 f = sorted_file[filesno];
5206 print_file_name_and_frills (f, pos);
5208 name_length = length_of_file_name_and_frills (f);
5209 max_name_length = line_fmt->col_arr[col];
5211 putchar (eolbyte);
5214 /* Output name + SEP + ' '. */
5216 static void
5217 print_with_separator (char sep)
5219 size_t filesno;
5220 size_t pos = 0;
5222 for (filesno = 0; filesno < cwd_n_used; filesno++)
5224 struct fileinfo const *f = sorted_file[filesno];
5225 size_t len = line_length ? length_of_file_name_and_frills (f) : 0;
5227 if (filesno != 0)
5229 char separator;
5231 if (! line_length
5232 || ((pos + len + 2 < line_length)
5233 && (pos <= SIZE_MAX - len - 2)))
5235 pos += 2;
5236 separator = ' ';
5238 else
5240 pos = 0;
5241 separator = eolbyte;
5244 putchar (sep);
5245 putchar (separator);
5248 print_file_name_and_frills (f, pos);
5249 pos += len;
5251 putchar (eolbyte);
5254 /* Assuming cursor is at position FROM, indent up to position TO.
5255 Use a TAB character instead of two or more spaces whenever possible. */
5257 static void
5258 indent (size_t from, size_t to)
5260 while (from < to)
5262 if (tabsize != 0 && to / tabsize > (from + 1) / tabsize)
5264 putchar ('\t');
5265 from += tabsize - from % tabsize;
5267 else
5269 putchar (' ');
5270 from++;
5275 /* Put DIRNAME/NAME into DEST, handling '.' and '/' properly. */
5276 /* FIXME: maybe remove this function someday. See about using a
5277 non-malloc'ing version of file_name_concat. */
5279 static void
5280 attach (char *dest, char const *dirname, char const *name)
5282 char const *dirnamep = dirname;
5284 /* Copy dirname if it is not ".". */
5285 if (dirname[0] != '.' || dirname[1] != 0)
5287 while (*dirnamep)
5288 *dest++ = *dirnamep++;
5289 /* Add '/' if 'dirname' doesn't already end with it. */
5290 if (dirnamep > dirname && dirnamep[-1] != '/')
5291 *dest++ = '/';
5293 while (*name)
5294 *dest++ = *name++;
5295 *dest = 0;
5298 /* Allocate enough column info suitable for the current number of
5299 files and display columns, and initialize the info to represent the
5300 narrowest possible columns. */
5302 static void
5303 init_column_info (size_t max_cols)
5305 size_t i;
5307 /* Currently allocated columns in column_info. */
5308 static size_t column_info_alloc;
5310 if (column_info_alloc < max_cols)
5312 size_t new_column_info_alloc;
5313 size_t *p;
5315 if (!max_idx || max_cols < max_idx / 2)
5317 /* The number of columns is far less than the display width
5318 allows. Grow the allocation, but only so that it's
5319 double the current requirements. If the display is
5320 extremely wide, this avoids allocating a lot of memory
5321 that is never needed. */
5322 column_info = xnrealloc (column_info, max_cols,
5323 2 * sizeof *column_info);
5324 new_column_info_alloc = 2 * max_cols;
5326 else
5328 column_info = xnrealloc (column_info, max_idx, sizeof *column_info);
5329 new_column_info_alloc = max_idx;
5332 /* Allocate the new size_t objects by computing the triangle
5333 formula n * (n + 1) / 2, except that we don't need to
5334 allocate the part of the triangle that we've already
5335 allocated. Check for address arithmetic overflow. */
5337 size_t column_info_growth = new_column_info_alloc - column_info_alloc;
5338 size_t s = column_info_alloc + 1 + new_column_info_alloc;
5339 size_t t = s * column_info_growth;
5340 if (s < new_column_info_alloc || t / column_info_growth != s)
5341 xalloc_die ();
5342 p = xnmalloc (t / 2, sizeof *p);
5345 /* Grow the triangle by parceling out the cells just allocated. */
5346 for (i = column_info_alloc; i < new_column_info_alloc; i++)
5348 column_info[i].col_arr = p;
5349 p += i + 1;
5352 column_info_alloc = new_column_info_alloc;
5355 for (i = 0; i < max_cols; ++i)
5357 size_t j;
5359 column_info[i].valid_len = true;
5360 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
5361 for (j = 0; j <= i; ++j)
5362 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
5366 /* Calculate the number of columns needed to represent the current set
5367 of files in the current display width. */
5369 static size_t
5370 calculate_columns (bool by_columns)
5372 size_t filesno; /* Index into cwd_file. */
5373 size_t cols; /* Number of files across. */
5375 /* Normally the maximum number of columns is determined by the
5376 screen width. But if few files are available this might limit it
5377 as well. */
5378 size_t max_cols = 0 < max_idx && max_idx < cwd_n_used ? max_idx : cwd_n_used;
5380 init_column_info (max_cols);
5382 /* Compute the maximum number of possible columns. */
5383 for (filesno = 0; filesno < cwd_n_used; ++filesno)
5385 struct fileinfo const *f = sorted_file[filesno];
5386 size_t name_length = length_of_file_name_and_frills (f);
5388 for (size_t i = 0; i < max_cols; ++i)
5390 if (column_info[i].valid_len)
5392 size_t idx = (by_columns
5393 ? filesno / ((cwd_n_used + i) / (i + 1))
5394 : filesno % (i + 1));
5395 size_t real_length = name_length + (idx == i ? 0 : 2);
5397 if (column_info[i].col_arr[idx] < real_length)
5399 column_info[i].line_len += (real_length
5400 - column_info[i].col_arr[idx]);
5401 column_info[i].col_arr[idx] = real_length;
5402 column_info[i].valid_len = (column_info[i].line_len
5403 < line_length);
5409 /* Find maximum allowed columns. */
5410 for (cols = max_cols; 1 < cols; --cols)
5412 if (column_info[cols - 1].valid_len)
5413 break;
5416 return cols;
5419 void
5420 usage (int status)
5422 if (status != EXIT_SUCCESS)
5423 emit_try_help ();
5424 else
5426 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
5427 fputs (_("\
5428 List information about the FILEs (the current directory by default).\n\
5429 Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.\n\
5430 "), stdout);
5432 emit_mandatory_arg_note ();
5434 fputs (_("\
5435 -a, --all do not ignore entries starting with .\n\
5436 -A, --almost-all do not list implied . and ..\n\
5437 --author with -l, print the author of each file\n\
5438 -b, --escape print C-style escapes for nongraphic characters\n\
5439 "), stdout);
5440 fputs (_("\
5441 --block-size=SIZE with -l, scale sizes by SIZE when printing them;\n\
5442 e.g., '--block-size=M'; see SIZE format below\n\
5444 "), stdout);
5445 fputs (_("\
5446 -B, --ignore-backups do not list implied entries ending with ~\n\
5447 "), stdout);
5448 fputs (_("\
5449 -c with -lt: sort by, and show, ctime (time of last\n\
5450 change of file status information);\n\
5451 with -l: show ctime and sort by name;\n\
5452 otherwise: sort by ctime, newest first\n\
5454 "), stdout);
5455 fputs (_("\
5456 -C list entries by columns\n\
5457 --color[=WHEN] color the output WHEN; more info below\n\
5458 -d, --directory list directories themselves, not their contents\n\
5459 -D, --dired generate output designed for Emacs' dired mode\n\
5460 "), stdout);
5461 fputs (_("\
5462 -f same as -a -U\n\
5463 -F, --classify[=WHEN] append indicator (one of */=>@|) to entries WHEN\n\
5464 --file-type likewise, except do not append '*'\n\
5465 "), stdout);
5466 fputs (_("\
5467 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
5468 single-column -1, verbose -l, vertical -C\n\
5470 "), stdout);
5471 fputs (_("\
5472 --full-time like -l --time-style=full-iso\n\
5473 "), stdout);
5474 fputs (_("\
5475 -g like -l, but do not list owner\n\
5476 "), stdout);
5477 fputs (_("\
5478 --group-directories-first\n\
5479 group directories before files\n\
5480 "), stdout);
5481 fputs (_("\
5482 -G, --no-group in a long listing, don't print group names\n\
5483 "), stdout);
5484 fputs (_("\
5485 -h, --human-readable with -l and -s, print sizes like 1K 234M 2G etc.\n\
5486 --si likewise, but use powers of 1000 not 1024\n\
5487 "), stdout);
5488 fputs (_("\
5489 -H, --dereference-command-line\n\
5490 follow symbolic links listed on the command line\n\
5491 "), stdout);
5492 fputs (_("\
5493 --dereference-command-line-symlink-to-dir\n\
5494 follow each command line symbolic link\n\
5495 that points to a directory\n\
5497 "), stdout);
5498 fputs (_("\
5499 --hide=PATTERN do not list implied entries matching shell PATTERN\
5501 (overridden by -a or -A)\n\
5503 "), stdout);
5504 fputs (_("\
5505 --hyperlink[=WHEN] hyperlink file names WHEN\n\
5506 "), stdout);
5507 fputs (_("\
5508 --indicator-style=WORD\n\
5509 append indicator with style WORD to entry names:\n\
5510 none (default), slash (-p),\n\
5511 file-type (--file-type), classify (-F)\n\
5513 "), stdout);
5514 fputs (_("\
5515 -i, --inode print the index number of each file\n\
5516 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\
5518 "), stdout);
5519 fputs (_("\
5520 -k, --kibibytes default to 1024-byte blocks for file system usage;\
5522 used only with -s and per directory totals\n\
5524 "), stdout);
5525 fputs (_("\
5526 -l use a long listing format\n\
5527 "), stdout);
5528 fputs (_("\
5529 -L, --dereference when showing file information for a symbolic\n\
5530 link, show information for the file the link\n\
5531 references rather than for the link itself\n\
5533 "), stdout);
5534 fputs (_("\
5535 -m fill width with a comma separated list of entries\
5537 "), stdout);
5538 fputs (_("\
5539 -n, --numeric-uid-gid like -l, but list numeric user and group IDs\n\
5540 -N, --literal print entry names without quoting\n\
5541 -o like -l, but do not list group information\n\
5542 -p, --indicator-style=slash\n\
5543 append / indicator to directories\n\
5544 "), stdout);
5545 fputs (_("\
5546 -q, --hide-control-chars print ? instead of nongraphic characters\n\
5547 "), stdout);
5548 fputs (_("\
5549 --show-control-chars show nongraphic characters as-is (the default,\n\
5550 unless program is 'ls' and output is a terminal)\
5553 "), stdout);
5554 fputs (_("\
5555 -Q, --quote-name enclose entry names in double quotes\n\
5556 "), stdout);
5557 fputs (_("\
5558 --quoting-style=WORD use quoting style WORD for entry names:\n\
5559 literal, locale, shell, shell-always,\n\
5560 shell-escape, shell-escape-always, c, escape\n\
5561 (overrides QUOTING_STYLE environment variable)\n\
5563 "), stdout);
5564 fputs (_("\
5565 -r, --reverse reverse order while sorting\n\
5566 -R, --recursive list subdirectories recursively\n\
5567 -s, --size print the allocated size of each file, in blocks\n\
5568 "), stdout);
5569 fputs (_("\
5570 -S sort by file size, largest first\n\
5571 "), stdout);
5572 fputs (_("\
5573 --sort=WORD sort by WORD instead of name: none (-U), size (-S)\
5574 ,\n\
5575 time (-t), version (-v), extension (-X), width\n\
5577 "), stdout);
5578 fputs (_("\
5579 --time=WORD select which timestamp used to display or sort;\n\
5580 access time (-u): atime, access, use;\n\
5581 metadata change time (-c): ctime, status;\n\
5582 modified time (default): mtime, modification;\n\
5583 birth time: birth, creation;\n\
5584 with -l, WORD determines which time to show;\n\
5585 with --sort=time, sort by WORD (newest first)\n\
5587 "), stdout);
5588 fputs (_("\
5589 --time-style=TIME_STYLE\n\
5590 time/date format with -l; see TIME_STYLE below\n\
5591 "), stdout);
5592 fputs (_("\
5593 -t sort by time, newest first; see --time\n\
5594 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
5595 "), stdout);
5596 fputs (_("\
5597 -u with -lt: sort by, and show, access time;\n\
5598 with -l: show access time and sort by name;\n\
5599 otherwise: sort by access time, newest first\n\
5601 "), stdout);
5602 fputs (_("\
5603 -U do not sort directory entries\n\
5604 "), stdout);
5605 fputs (_("\
5606 -v natural sort of (version) numbers within text\n\
5607 "), stdout);
5608 fputs (_("\
5609 -w, --width=COLS set output width to COLS. 0 means no limit\n\
5610 -x list entries by lines instead of by columns\n\
5611 -X sort alphabetically by entry extension\n\
5612 -Z, --context print any security context of each file\n\
5613 --zero end each output line with NUL, not newline\n\
5614 -1 list one file per line\n\
5615 "), stdout);
5616 fputs (HELP_OPTION_DESCRIPTION, stdout);
5617 fputs (VERSION_OPTION_DESCRIPTION, stdout);
5618 emit_size_note ();
5619 fputs (_("\
5621 The TIME_STYLE argument can be full-iso, long-iso, iso, locale, or +FORMAT.\n\
5622 FORMAT is interpreted like in date(1). If FORMAT is FORMAT1<newline>FORMAT2,\n\
5623 then FORMAT1 applies to non-recent files and FORMAT2 to recent files.\n\
5624 TIME_STYLE prefixed with 'posix-' takes effect only outside the POSIX locale.\n\
5625 Also the TIME_STYLE environment variable sets the default style to use.\n\
5626 "), stdout);
5627 fputs (_("\
5629 The WHEN argument defaults to 'always' and can also be 'auto' or 'never'.\n\
5630 "), stdout);
5631 fputs (_("\
5633 Using color to distinguish file types is disabled both by default and\n\
5634 with --color=never. With --color=auto, ls emits color codes only when\n\
5635 standard output is connected to a terminal. The LS_COLORS environment\n\
5636 variable can change the settings. Use the dircolors(1) command to set it.\n\
5637 "), stdout);
5638 fputs (_("\
5640 Exit status:\n\
5641 0 if OK,\n\
5642 1 if minor problems (e.g., cannot access subdirectory),\n\
5643 2 if serious trouble (e.g., cannot access command-line argument).\n\
5644 "), stdout);
5645 emit_ancillary_info (PROGRAM_NAME);
5647 exit (status);