ls: fix spurious output with -Z
[coreutils.git] / src / ls.c
blob290ce35d24b0c091ee94abaf8bcd86b72550a1c7
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 <uchar.h>
60 #if HAVE_LANGINFO_CODESET
61 # include <langinfo.h>
62 #endif
64 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
65 present. */
66 #ifndef SA_NOCLDSTOP
67 # define SA_NOCLDSTOP 0
68 # define sigprocmask(How, Set, Oset) /* empty */
69 # define sigset_t int
70 # if ! HAVE_SIGINTERRUPT
71 # define siginterrupt(sig, flag) /* empty */
72 # endif
73 #endif
75 /* NonStop circa 2011 lacks both SA_RESTART and siginterrupt, so don't
76 restart syscalls after a signal handler fires. This may cause
77 colors to get messed up on the screen if 'ls' is interrupted, but
78 that's the best we can do on such a platform. */
79 #ifndef SA_RESTART
80 # define SA_RESTART 0
81 #endif
83 #include "system.h"
84 #include <fnmatch.h>
86 #include "acl.h"
87 #include "argmatch.h"
88 #include "assure.h"
89 #include "c-strcase.h"
90 #include "dev-ino.h"
91 #include "filenamecat.h"
92 #include "hard-locale.h"
93 #include "hash.h"
94 #include "human.h"
95 #include "filemode.h"
96 #include "filevercmp.h"
97 #include "idcache.h"
98 #include "ls.h"
99 #include "mbswidth.h"
100 #include "mpsort.h"
101 #include "obstack.h"
102 #include "quote.h"
103 #include "stat-size.h"
104 #include "stat-time.h"
105 #include "strftime.h"
106 #include "xdectoint.h"
107 #include "xstrtol.h"
108 #include "xstrtol-error.h"
109 #include "areadlink.h"
110 #include "dircolors.h"
111 #include "xgethostname.h"
112 #include "c-ctype.h"
113 #include "canonicalize.h"
114 #include "statx.h"
116 /* Include <sys/capability.h> last to avoid a clash of <sys/types.h>
117 include guards with some premature versions of libcap.
118 For more details, see <https://bugzilla.redhat.com/483548>. */
119 #ifdef HAVE_CAP
120 # include <sys/capability.h>
121 #endif
123 #if HAVE_LINUX_XATTR_H
124 # include <linux/xattr.h>
125 #endif
127 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
128 : (ls_mode == LS_MULTI_COL \
129 ? "dir" : "vdir"))
131 #define AUTHORS \
132 proper_name ("Richard M. Stallman"), \
133 proper_name ("David MacKenzie")
135 #define obstack_chunk_alloc malloc
136 #define obstack_chunk_free free
138 /* Unix-based readdir implementations have historically returned a dirent.d_ino
139 value that is sometimes not equal to the stat-obtained st_ino value for
140 that same entry. This error occurs for a readdir entry that refers
141 to a mount point. readdir's error is to return the inode number of
142 the underlying directory -- one that typically cannot be stat'ed, as
143 long as a file system is mounted on that directory. RELIABLE_D_INO
144 encapsulates whether we can use the more efficient approach of relying
145 on readdir-supplied d_ino values, or whether we must incur the cost of
146 calling stat or lstat to obtain each guaranteed-valid inode number. */
148 #ifndef READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
149 # define READDIR_LIES_ABOUT_MOUNTPOINT_D_INO 1
150 #endif
152 #if READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
153 # define RELIABLE_D_INO(dp) NOT_AN_INODE_NUMBER
154 #else
155 # define RELIABLE_D_INO(dp) D_INO (dp)
156 #endif
158 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
159 # define st_author st_uid
160 #endif
162 enum filetype
164 unknown,
165 fifo,
166 chardev,
167 directory,
168 blockdev,
169 normal,
170 symbolic_link,
171 sock,
172 whiteout,
173 arg_directory
175 enum { filetype_cardinality = arg_directory + 1 };
177 /* Display letters and indicators for each filetype.
178 Keep these in sync with enum filetype. */
179 static char const filetype_letter[] =
180 {'?', 'p', 'c', 'd', 'b', '-', 'l', 's', 'w', 'd'};
181 static_assert (ARRAY_CARDINALITY (filetype_letter) == filetype_cardinality);
183 /* Map enum filetype to <dirent.h> d_type values. */
184 static unsigned char const filetype_d_type[] =
186 DT_UNKNOWN, DT_FIFO, DT_CHR, DT_DIR, DT_BLK, DT_REG, DT_LNK, DT_SOCK,
187 DT_WHT, DT_DIR
189 static_assert (ARRAY_CARDINALITY (filetype_d_type) == filetype_cardinality);
191 /* Map d_type values to enum filetype. */
192 static char const d_type_filetype[UCHAR_MAX + 1] =
194 [DT_BLK] = blockdev, [DT_CHR] = chardev, [DT_DIR] = directory,
195 [DT_FIFO] = fifo, [DT_LNK] = symbolic_link, [DT_REG] = normal,
196 [DT_SOCK] = sock, [DT_WHT] = whiteout
199 enum acl_type
201 ACL_T_NONE,
202 ACL_T_LSM_CONTEXT_ONLY,
203 ACL_T_YES
206 struct fileinfo
208 /* The file name. */
209 char *name;
211 /* For symbolic link, name of the file linked to, otherwise zero. */
212 char *linkname;
214 /* For terminal hyperlinks. */
215 char *absolute_name;
217 struct stat stat;
219 enum filetype filetype;
221 /* For symbolic link and long listing, st_mode of file linked to, otherwise
222 zero. */
223 mode_t linkmode;
225 /* security context. */
226 char *scontext;
228 bool stat_ok;
230 /* For symbolic link and color printing, true if linked-to file
231 exists, otherwise false. */
232 bool linkok;
234 /* For long listings, true if the file has an access control list,
235 or a security context. */
236 enum acl_type acl_type;
238 /* For color listings, true if a regular file has capability info. */
239 bool has_capability;
241 /* Whether file name needs quoting. tri-state with -1 == unknown. */
242 int quoted;
244 /* Cached screen width (including quoting). */
245 size_t width;
248 #define BIN_STR(...) \
249 sizeof ((char []) {__VA_ARGS__}), (char const []) {__VA_ARGS__}
251 /* Null is a valid character in a color indicator (think about Epson
252 printers, for example) so we have to use a length/buffer string
253 type. */
255 struct bin_str
257 size_t len; /* Number of bytes */
258 char const *string; /* Pointer to the same */
261 #if ! HAVE_TCGETPGRP
262 # define tcgetpgrp(Fd) 0
263 #endif
265 static size_t quote_name (char const *name,
266 struct quoting_options const *options,
267 int needs_general_quoting,
268 const struct bin_str *color,
269 bool allow_pad, struct obstack *stack,
270 char const *absolute_name);
271 static size_t quote_name_buf (char **inbuf, size_t bufsize, char *name,
272 struct quoting_options const *options,
273 int needs_general_quoting, size_t *width,
274 bool *pad);
275 static int decode_switches (int argc, char **argv);
276 static bool file_ignored (char const *name);
277 static uintmax_t gobble_file (char const *name, enum filetype type,
278 ino_t inode, bool command_line_arg,
279 char const *dirname);
280 static const struct bin_str * get_color_indicator (const struct fileinfo *f,
281 bool symlink_target);
282 static bool print_color_indicator (const struct bin_str *ind);
283 static void put_indicator (const struct bin_str *ind);
284 static void add_ignore_pattern (char const *pattern);
285 static void attach (char *dest, char const *dirname, char const *name);
286 static void clear_files (void);
287 static void extract_dirs_from_files (char const *dirname,
288 bool command_line_arg);
289 static void get_link_name (char const *filename, struct fileinfo *f,
290 bool command_line_arg);
291 static void indent (size_t from, size_t to);
292 static size_t calculate_columns (bool by_columns);
293 static void print_current_files (void);
294 static void print_dir (char const *name, char const *realname,
295 bool command_line_arg);
296 static size_t print_file_name_and_frills (const struct fileinfo *f,
297 size_t start_col);
298 static void print_horizontal (void);
299 static int format_user_width (uid_t u);
300 static int format_group_width (gid_t g);
301 static void print_long_format (const struct fileinfo *f);
302 static void print_many_per_line (void);
303 static size_t print_name_with_quoting (const struct fileinfo *f,
304 bool symlink_target,
305 struct obstack *stack,
306 size_t start_col);
307 static void prep_non_filename_text (void);
308 static bool print_type_indicator (bool stat_ok, mode_t mode,
309 enum filetype type);
310 static void print_with_separator (char sep);
311 static void queue_directory (char const *name, char const *realname,
312 bool command_line_arg);
313 static void sort_files (void);
314 static void parse_ls_color (void);
316 static int getenv_quoting_style (void);
318 static size_t quote_name_width (char const *name,
319 struct quoting_options const *options,
320 int needs_general_quoting);
322 /* Initial size of hash table.
323 Most hierarchies are likely to be shallower than this. */
324 enum { INITIAL_TABLE_SIZE = 30 };
326 /* The set of 'active' directories, from the current command-line argument
327 to the level in the hierarchy at which files are being listed.
328 A directory is represented by its device and inode numbers (struct dev_ino).
329 A directory is added to this set when ls begins listing it or its
330 entries, and it is removed from the set just after ls has finished
331 processing it. This set is used solely to detect loops, e.g., with
332 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
333 static Hash_table *active_dir_set;
335 #define LOOP_DETECT (!!active_dir_set)
337 /* The table of files in the current directory:
339 'cwd_file' points to a vector of 'struct fileinfo', one per file.
340 'cwd_n_alloc' is the number of elements space has been allocated for.
341 'cwd_n_used' is the number actually in use. */
343 /* Address of block containing the files that are described. */
344 static struct fileinfo *cwd_file;
346 /* Length of block that 'cwd_file' points to, measured in files. */
347 static size_t cwd_n_alloc;
349 /* Index of first unused slot in 'cwd_file'. */
350 static size_t cwd_n_used;
352 /* Whether files needs may need padding due to quoting. */
353 static bool cwd_some_quoted;
355 /* Whether quoting style _may_ add outer quotes,
356 and whether aligning those is useful. */
357 static bool align_variable_outer_quotes;
359 /* Vector of pointers to files, in proper sorted order, and the number
360 of entries allocated for it. */
361 static void **sorted_file;
362 static size_t sorted_file_alloc;
364 /* When true, in a color listing, color each symlink name according to the
365 type of file it points to. Otherwise, color them according to the 'ln'
366 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
367 regardless. This is set when 'ln=target' appears in LS_COLORS. */
369 static bool color_symlink_as_referent;
371 static char const *hostname;
373 /* Mode of appropriate file for coloring. */
374 static mode_t
375 file_or_link_mode (struct fileinfo const *file)
377 return (color_symlink_as_referent && file->linkok
378 ? file->linkmode : file->stat.st_mode);
382 /* Record of one pending directory waiting to be listed. */
384 struct pending
386 char *name;
387 /* If the directory is actually the file pointed to by a symbolic link we
388 were told to list, 'realname' will contain the name of the symbolic
389 link, otherwise zero. */
390 char *realname;
391 bool command_line_arg;
392 struct pending *next;
395 static struct pending *pending_dirs;
397 /* Current time in seconds and nanoseconds since 1970, updated as
398 needed when deciding whether a file is recent. */
400 static struct timespec current_time;
402 static bool print_scontext;
403 static char UNKNOWN_SECURITY_CONTEXT[] = "?";
405 /* Whether any of the files has an ACL. This affects the width of the
406 mode column. */
408 static bool any_has_acl;
410 /* The number of columns to use for columns containing inode numbers,
411 block sizes, link counts, owners, groups, authors, major device
412 numbers, minor device numbers, and file sizes, respectively. */
414 static int inode_number_width;
415 static int block_size_width;
416 static int nlink_width;
417 static int scontext_width;
418 static int owner_width;
419 static int group_width;
420 static int author_width;
421 static int major_device_number_width;
422 static int minor_device_number_width;
423 static int file_size_width;
425 /* Option flags */
427 /* long_format for lots of info, one per line.
428 one_per_line for just names, one per line.
429 many_per_line for just names, many per line, sorted vertically.
430 horizontal for just names, many per line, sorted horizontally.
431 with_commas for just names, many per line, separated by commas.
433 -l (and other options that imply -l), -1, -C, -x and -m control
434 this parameter. */
436 enum format
438 long_format, /* -l and other options that imply -l */
439 one_per_line, /* -1 */
440 many_per_line, /* -C */
441 horizontal, /* -x */
442 with_commas /* -m */
445 static enum format format;
447 /* 'full-iso' uses full ISO-style dates and times. 'long-iso' uses longer
448 ISO-style timestamps, though shorter than 'full-iso'. 'iso' uses shorter
449 ISO-style timestamps. 'locale' uses locale-dependent timestamps. */
450 enum time_style
452 full_iso_time_style, /* --time-style=full-iso */
453 long_iso_time_style, /* --time-style=long-iso */
454 iso_time_style, /* --time-style=iso */
455 locale_time_style /* --time-style=locale */
458 static char const *const time_style_args[] =
460 "full-iso", "long-iso", "iso", "locale", nullptr
462 static enum time_style const time_style_types[] =
464 full_iso_time_style, long_iso_time_style, iso_time_style,
465 locale_time_style
467 ARGMATCH_VERIFY (time_style_args, time_style_types);
469 /* Type of time to print or sort by. Controlled by -c and -u.
470 The values of each item of this enum are important since they are
471 used as indices in the sort functions array (see sort_files()). */
473 enum time_type
475 time_mtime = 0, /* default */
476 time_ctime, /* -c */
477 time_atime, /* -u */
478 time_btime, /* birth time */
479 time_numtypes /* the number of elements of this enum */
482 static enum time_type time_type;
483 static bool explicit_time;
485 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v.
486 The values of each item of this enum are important since they are
487 used as indices in the sort functions array (see sort_files()). */
489 enum sort_type
491 sort_name = 0, /* default */
492 sort_extension, /* -X */
493 sort_width,
494 sort_size, /* -S */
495 sort_version, /* -v */
496 sort_time, /* -t; must be second to last */
497 sort_none, /* -U; must be last */
498 sort_numtypes /* the number of elements of this enum */
501 static enum sort_type sort_type;
503 /* Direction of sort.
504 false means highest first if numeric,
505 lowest first if alphabetic;
506 these are the defaults.
507 true means the opposite order in each case. -r */
509 static bool sort_reverse;
511 /* True means to display owner information. -g turns this off. */
513 static bool print_owner = true;
515 /* True means to display author information. */
517 static bool print_author;
519 /* True means to display group information. -G and -o turn this off. */
521 static bool print_group = true;
523 /* True means print the user and group id's as numbers rather
524 than as names. -n */
526 static bool numeric_ids;
528 /* True means mention the size in blocks of each file. -s */
530 static bool print_block_size;
532 /* Human-readable options for output, when printing block counts. */
533 static int human_output_opts;
535 /* The units to use when printing block counts. */
536 static uintmax_t output_block_size;
538 /* Likewise, but for file sizes. */
539 static int file_human_output_opts;
540 static uintmax_t file_output_block_size = 1;
542 /* Follow the output with a special string. Using this format,
543 Emacs' dired mode starts up twice as fast, and can handle all
544 strange characters in file names. */
545 static bool dired;
547 /* 'none' means don't mention the type of files.
548 'slash' means mention directories only, with a '/'.
549 'file_type' means mention file types.
550 'classify' means mention file types and mark executables.
552 Controlled by -F, -p, and --indicator-style. */
554 enum indicator_style
556 none = 0, /* --indicator-style=none (default) */
557 slash, /* -p, --indicator-style=slash */
558 file_type, /* --indicator-style=file-type */
559 classify /* -F, --indicator-style=classify */
562 static enum indicator_style indicator_style;
564 /* Names of indicator styles. */
565 static char const *const indicator_style_args[] =
567 "none", "slash", "file-type", "classify", nullptr
569 static enum indicator_style const indicator_style_types[] =
571 none, slash, file_type, classify
573 ARGMATCH_VERIFY (indicator_style_args, indicator_style_types);
575 /* True means use colors to mark types. Also define the different
576 colors as well as the stuff for the LS_COLORS environment variable.
577 The LS_COLORS variable is now in a termcap-like format. */
579 static bool print_with_color;
581 static bool print_hyperlink;
583 /* Whether we used any colors in the output so far. If so, we will
584 need to restore the default color later. If not, we will need to
585 call prep_non_filename_text before using color for the first time. */
587 static bool used_color = false;
589 enum when_type
591 when_never, /* 0: default or --color=never */
592 when_always, /* 1: --color=always */
593 when_if_tty /* 2: --color=tty */
596 enum Dereference_symlink
598 DEREF_UNDEFINED = 0, /* default */
599 DEREF_NEVER,
600 DEREF_COMMAND_LINE_ARGUMENTS, /* -H */
601 DEREF_COMMAND_LINE_SYMLINK_TO_DIR, /* the default, in certain cases */
602 DEREF_ALWAYS /* -L */
605 enum indicator_no
607 C_LEFT, C_RIGHT, C_END, C_RESET, C_NORM, C_FILE, C_DIR, C_LINK,
608 C_FIFO, C_SOCK,
609 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR, C_SETUID, C_SETGID,
610 C_STICKY, C_OTHER_WRITABLE, C_STICKY_OTHER_WRITABLE, C_CAP, C_MULTIHARDLINK,
611 C_CLR_TO_EOL
614 static char const indicator_name[][2]=
616 {'l','c'}, {'r','c'}, {'e','c'}, {'r','s'}, {'n','o'},
617 {'f','i'}, {'d','i'}, {'l','n'},
618 {'p','i'}, {'s','o'},
619 {'b','d'}, {'c','d'}, {'m','i'}, {'o','r'}, {'e','x'},
620 {'d','o'}, {'s','u'}, {'s','g'},
621 {'s','t'}, {'o','w'}, {'t','w'}, {'c','a'}, {'m','h'},
622 {'c','l'}
625 struct color_ext_type
627 struct bin_str ext; /* The extension we're looking for */
628 struct bin_str seq; /* The sequence to output when we do */
629 bool exact_match; /* Whether to compare case insensitively */
630 struct color_ext_type *next; /* Next in list */
633 static struct bin_str color_indicator[] =
635 { BIN_STR ('\033','[') }, /* lc: Left of color sequence */
636 { BIN_STR ('m') }, /* rc: Right of color sequence */
637 { 0, nullptr }, /* ec: End color (replaces lc+rs+rc) */
638 { BIN_STR ('0') }, /* rs: Reset to ordinary colors */
639 { 0, nullptr }, /* no: Normal */
640 { 0, nullptr }, /* fi: File: default */
641 { BIN_STR ('0','1',';','3','4') }, /* di: Directory: bright blue */
642 { BIN_STR ('0','1',';','3','6') }, /* ln: Symlink: bright cyan */
643 { BIN_STR ('3','3') }, /* pi: Pipe: yellow/brown */
644 { BIN_STR ('0','1',';','3','5') }, /* so: Socket: bright magenta */
645 { BIN_STR ('0','1',';','3','3') }, /* bd: Block device: bright yellow */
646 { BIN_STR ('0','1',';','3','3') }, /* cd: Char device: bright yellow */
647 { 0, nullptr }, /* mi: Missing file: undefined */
648 { 0, nullptr }, /* or: Orphaned symlink: undefined */
649 { BIN_STR ('0','1',';','3','2') }, /* ex: Executable: bright green */
650 { BIN_STR ('0','1',';','3','5') }, /* do: Door: bright magenta */
651 { BIN_STR ('3','7',';','4','1') }, /* su: setuid: white on red */
652 { BIN_STR ('3','0',';','4','3') }, /* sg: setgid: black on yellow */
653 { BIN_STR ('3','7',';','4','4') }, /* st: sticky: black on blue */
654 { BIN_STR ('3','4',';','4','2') }, /* ow: other-writable: blue on green */
655 { BIN_STR ('3','0',';','4','2') }, /* tw: ow w/ sticky: black on green */
656 { 0, nullptr }, /* ca: disabled by default */
657 { 0, nullptr }, /* mh: disabled by default */
658 { BIN_STR ('\033','[','K') }, /* cl: clear to end of line */
661 /* A list mapping file extensions to corresponding display sequence. */
662 static struct color_ext_type *color_ext_list = nullptr;
664 /* Buffer for color sequences */
665 static char *color_buf;
667 /* True means to check for orphaned symbolic link, for displaying
668 colors, or to group symlink to directories with other dirs. */
670 static bool check_symlink_mode;
672 /* True means mention the inode number of each file. -i */
674 static bool print_inode;
676 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
677 other options that imply -l), and -L. */
679 static enum Dereference_symlink dereference;
681 /* True means when a directory is found, display info on its
682 contents. -R */
684 static bool recursive;
686 /* True means when an argument is a directory name, display info
687 on it itself. -d */
689 static bool immediate_dirs;
691 /* True means that directories are grouped before files. */
693 static bool directories_first;
695 /* Which files to ignore. */
697 static enum
699 /* Ignore files whose names start with '.', and files specified by
700 --hide and --ignore. */
701 IGNORE_DEFAULT = 0,
703 /* Ignore '.', '..', and files specified by --ignore. */
704 IGNORE_DOT_AND_DOTDOT,
706 /* Ignore only files specified by --ignore. */
707 IGNORE_MINIMAL
708 } ignore_mode;
710 /* A linked list of shell-style globbing patterns. If a non-argument
711 file name matches any of these patterns, it is ignored.
712 Controlled by -I. Multiple -I options accumulate.
713 The -B option adds '*~' and '.*~' to this list. */
715 struct ignore_pattern
717 char const *pattern;
718 struct ignore_pattern *next;
721 static struct ignore_pattern *ignore_patterns;
723 /* Similar to IGNORE_PATTERNS, except that -a or -A causes this
724 variable itself to be ignored. */
725 static struct ignore_pattern *hide_patterns;
727 /* True means output nongraphic chars in file names as '?'.
728 (-q, --hide-control-chars)
729 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
730 independent. The algorithm is: first, obey the quoting style to get a
731 string representing the file name; then, if qmark_funny_chars is set,
732 replace all nonprintable chars in that string with '?'. It's necessary
733 to replace nonprintable chars even in quoted strings, because we don't
734 want to mess up the terminal if control chars get sent to it, and some
735 quoting methods pass through control chars as-is. */
736 static bool qmark_funny_chars;
738 /* Quoting options for file and dir name output. */
740 static struct quoting_options *filename_quoting_options;
741 static struct quoting_options *dirname_quoting_options;
743 /* The number of chars per hardware tab stop. Setting this to zero
744 inhibits the use of TAB characters for separating columns. -T */
745 static size_t tabsize;
747 /* True means print each directory name before listing it. */
749 static bool print_dir_name;
751 /* The line length to use for breaking lines in many-per-line format.
752 Can be set with -w. If zero, there is no limit. */
754 static size_t line_length;
756 /* The local time zone rules, as per the TZ environment variable. */
758 static timezone_t localtz;
760 /* If true, the file listing format requires that stat be called on
761 each file. */
763 static bool format_needs_stat;
765 /* Similar to 'format_needs_stat', but set if only the file type is
766 needed. */
768 static bool format_needs_type;
770 /* Like 'format_needs_stat', but set only if capability colors are needed. */
772 static bool format_needs_capability;
774 /* An arbitrary limit on the number of bytes in a printed timestamp.
775 This is set to a relatively small value to avoid the need to worry
776 about denial-of-service attacks on servers that run "ls" on behalf
777 of remote clients. 1000 bytes should be enough for any practical
778 timestamp format. */
780 enum { TIME_STAMP_LEN_MAXIMUM = MAX (1000, INT_STRLEN_BOUND (time_t)) };
782 /* strftime formats for non-recent and recent files, respectively, in
783 -l output. */
785 static char const *long_time_format[2] =
787 /* strftime format for non-recent files (older than 6 months), in
788 -l output. This should contain the year, month and day (at
789 least), in an order that is understood by people in your
790 locale's territory. Please try to keep the number of used
791 screen columns small, because many people work in windows with
792 only 80 columns. But make this as wide as the other string
793 below, for recent files. */
794 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
795 so be wary of using variable width fields from the locale.
796 Note %b is handled specially by ls and aligned correctly.
797 Note also that specifying a width as in %5b is erroneous as strftime
798 will count bytes rather than characters in multibyte locales. */
799 N_("%b %e %Y"),
800 /* strftime format for recent files (younger than 6 months), in -l
801 output. This should contain the month, day and time (at
802 least), in an order that is understood by people in your
803 locale's territory. Please try to keep the number of used
804 screen columns small, because many people work in windows with
805 only 80 columns. But make this as wide as the other string
806 above, for non-recent files. */
807 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
808 so be wary of using variable width fields from the locale.
809 Note %b is handled specially by ls and aligned correctly.
810 Note also that specifying a width as in %5b is erroneous as strftime
811 will count bytes rather than characters in multibyte locales. */
812 N_("%b %e %H:%M")
815 /* The set of signals that are caught. */
817 static sigset_t caught_signals;
819 /* If nonzero, the value of the pending fatal signal. */
821 static sig_atomic_t volatile interrupt_signal;
823 /* A count of the number of pending stop signals that have been received. */
825 static sig_atomic_t volatile stop_signal_count;
827 /* Desired exit status. */
829 static int exit_status;
831 /* Exit statuses. */
832 enum
834 /* "ls" had a minor problem. E.g., while processing a directory,
835 ls obtained the name of an entry via readdir, yet was later
836 unable to stat that name. This happens when listing a directory
837 in which entries are actively being removed or renamed. */
838 LS_MINOR_PROBLEM = 1,
840 /* "ls" had more serious trouble (e.g., memory exhausted, invalid
841 option or failure to stat a command line argument. */
842 LS_FAILURE = 2
845 /* For long options that have no equivalent short option, use a
846 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
847 enum
849 AUTHOR_OPTION = CHAR_MAX + 1,
850 BLOCK_SIZE_OPTION,
851 COLOR_OPTION,
852 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION,
853 FILE_TYPE_INDICATOR_OPTION,
854 FORMAT_OPTION,
855 FULL_TIME_OPTION,
856 GROUP_DIRECTORIES_FIRST_OPTION,
857 HIDE_OPTION,
858 HYPERLINK_OPTION,
859 INDICATOR_STYLE_OPTION,
860 QUOTING_STYLE_OPTION,
861 SHOW_CONTROL_CHARS_OPTION,
862 SI_OPTION,
863 SORT_OPTION,
864 TIME_OPTION,
865 TIME_STYLE_OPTION,
866 ZERO_OPTION,
869 static struct option const long_options[] =
871 {"all", no_argument, nullptr, 'a'},
872 {"escape", no_argument, nullptr, 'b'},
873 {"directory", no_argument, nullptr, 'd'},
874 {"dired", no_argument, nullptr, 'D'},
875 {"full-time", no_argument, nullptr, FULL_TIME_OPTION},
876 {"group-directories-first", no_argument, nullptr,
877 GROUP_DIRECTORIES_FIRST_OPTION},
878 {"human-readable", no_argument, nullptr, 'h'},
879 {"inode", no_argument, nullptr, 'i'},
880 {"kibibytes", no_argument, nullptr, 'k'},
881 {"numeric-uid-gid", no_argument, nullptr, 'n'},
882 {"no-group", no_argument, nullptr, 'G'},
883 {"hide-control-chars", no_argument, nullptr, 'q'},
884 {"reverse", no_argument, nullptr, 'r'},
885 {"size", no_argument, nullptr, 's'},
886 {"width", required_argument, nullptr, 'w'},
887 {"almost-all", no_argument, nullptr, 'A'},
888 {"ignore-backups", no_argument, nullptr, 'B'},
889 {"classify", optional_argument, nullptr, 'F'},
890 {"file-type", no_argument, nullptr, FILE_TYPE_INDICATOR_OPTION},
891 {"si", no_argument, nullptr, SI_OPTION},
892 {"dereference-command-line", no_argument, nullptr, 'H'},
893 {"dereference-command-line-symlink-to-dir", no_argument, nullptr,
894 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION},
895 {"hide", required_argument, nullptr, HIDE_OPTION},
896 {"ignore", required_argument, nullptr, 'I'},
897 {"indicator-style", required_argument, nullptr, INDICATOR_STYLE_OPTION},
898 {"dereference", no_argument, nullptr, 'L'},
899 {"literal", no_argument, nullptr, 'N'},
900 {"quote-name", no_argument, nullptr, 'Q'},
901 {"quoting-style", required_argument, nullptr, QUOTING_STYLE_OPTION},
902 {"recursive", no_argument, nullptr, 'R'},
903 {"format", required_argument, nullptr, FORMAT_OPTION},
904 {"show-control-chars", no_argument, nullptr, SHOW_CONTROL_CHARS_OPTION},
905 {"sort", required_argument, nullptr, SORT_OPTION},
906 {"tabsize", required_argument, nullptr, 'T'},
907 {"time", required_argument, nullptr, TIME_OPTION},
908 {"time-style", required_argument, nullptr, TIME_STYLE_OPTION},
909 {"zero", no_argument, nullptr, ZERO_OPTION},
910 {"color", optional_argument, nullptr, COLOR_OPTION},
911 {"hyperlink", optional_argument, nullptr, HYPERLINK_OPTION},
912 {"block-size", required_argument, nullptr, BLOCK_SIZE_OPTION},
913 {"context", no_argument, 0, 'Z'},
914 {"author", no_argument, nullptr, AUTHOR_OPTION},
915 {GETOPT_HELP_OPTION_DECL},
916 {GETOPT_VERSION_OPTION_DECL},
917 {nullptr, 0, nullptr, 0}
920 static char const *const format_args[] =
922 "verbose", "long", "commas", "horizontal", "across",
923 "vertical", "single-column", nullptr
925 static enum format const format_types[] =
927 long_format, long_format, with_commas, horizontal, horizontal,
928 many_per_line, one_per_line
930 ARGMATCH_VERIFY (format_args, format_types);
932 static char const *const sort_args[] =
934 "none", "size", "time", "version", "extension",
935 "name", "width", nullptr
937 static enum sort_type const sort_types[] =
939 sort_none, sort_size, sort_time, sort_version, sort_extension,
940 sort_name, sort_width
942 ARGMATCH_VERIFY (sort_args, sort_types);
944 static char const *const time_args[] =
946 "atime", "access", "use",
947 "ctime", "status",
948 "mtime", "modification",
949 "birth", "creation",
950 nullptr
952 static enum time_type const time_types[] =
954 time_atime, time_atime, time_atime,
955 time_ctime, time_ctime,
956 time_mtime, time_mtime,
957 time_btime, time_btime,
959 ARGMATCH_VERIFY (time_args, time_types);
961 static char const *const when_args[] =
963 /* force and none are for compatibility with another color-ls version */
964 "always", "yes", "force",
965 "never", "no", "none",
966 "auto", "tty", "if-tty", nullptr
968 static enum when_type const when_types[] =
970 when_always, when_always, when_always,
971 when_never, when_never, when_never,
972 when_if_tty, when_if_tty, when_if_tty
974 ARGMATCH_VERIFY (when_args, when_types);
976 /* Information about filling a column. */
977 struct column_info
979 bool valid_len;
980 size_t line_len;
981 size_t *col_arr;
984 /* Array with information about column fullness. */
985 static struct column_info *column_info;
987 /* Maximum number of columns ever possible for this display. */
988 static size_t max_idx;
990 /* The minimum width of a column is 3: 1 character for the name and 2
991 for the separating white space. */
992 enum { MIN_COLUMN_WIDTH = 3 };
995 /* This zero-based index is for the --dired option. It is incremented
996 for each byte of output generated by this program so that the beginning
997 and ending indices (in that output) of every file name can be recorded
998 and later output themselves. */
999 static off_t dired_pos;
1001 static void
1002 dired_outbyte (char c)
1004 dired_pos++;
1005 putchar (c);
1008 /* Output the buffer S, of length S_LEN, and increment DIRED_POS by S_LEN. */
1009 static void
1010 dired_outbuf (char const *s, size_t s_len)
1012 dired_pos += s_len;
1013 fwrite (s, sizeof *s, s_len, stdout);
1016 /* Output the string S, and increment DIRED_POS by its length. */
1017 static void
1018 dired_outstring (char const *s)
1020 dired_outbuf (s, strlen (s));
1023 static void
1024 dired_indent (void)
1026 if (dired)
1027 dired_outstring (" ");
1030 /* With --dired, store pairs of beginning and ending indices of file names. */
1031 static struct obstack dired_obstack;
1033 /* With --dired, store pairs of beginning and ending indices of any
1034 directory names that appear as headers (just before 'total' line)
1035 for lists of directory entries. Such directory names are seen when
1036 listing hierarchies using -R and when a directory is listed with at
1037 least one other command line argument. */
1038 static struct obstack subdired_obstack;
1040 /* Save the current index on the specified obstack, OBS. */
1041 static void
1042 push_current_dired_pos (struct obstack *obs)
1044 if (dired)
1045 obstack_grow (obs, &dired_pos, sizeof dired_pos);
1048 /* With -R, this stack is used to help detect directory cycles.
1049 The device/inode pairs on this stack mirror the pairs in the
1050 active_dir_set hash table. */
1051 static struct obstack dev_ino_obstack;
1053 /* Push a pair onto the device/inode stack. */
1054 static void
1055 dev_ino_push (dev_t dev, ino_t ino)
1057 void *vdi;
1058 struct dev_ino *di;
1059 int dev_ino_size = sizeof *di;
1060 obstack_blank (&dev_ino_obstack, dev_ino_size);
1061 vdi = obstack_next_free (&dev_ino_obstack);
1062 di = vdi;
1063 di--;
1064 di->st_dev = dev;
1065 di->st_ino = ino;
1068 /* Pop a dev/ino struct off the global dev_ino_obstack
1069 and return that struct. */
1070 static struct dev_ino
1071 dev_ino_pop (void)
1073 void *vdi;
1074 struct dev_ino *di;
1075 int dev_ino_size = sizeof *di;
1076 affirm (dev_ino_size <= obstack_object_size (&dev_ino_obstack));
1077 obstack_blank_fast (&dev_ino_obstack, -dev_ino_size);
1078 vdi = obstack_next_free (&dev_ino_obstack);
1079 di = vdi;
1080 return *di;
1083 static void
1084 assert_matching_dev_ino (char const *name, struct dev_ino di)
1086 MAYBE_UNUSED struct stat sb;
1087 assure (0 <= stat (name, &sb));
1088 assure (sb.st_dev == di.st_dev);
1089 assure (sb.st_ino == di.st_ino);
1092 static char eolbyte = '\n';
1094 /* Write to standard output PREFIX, followed by the quoting style and
1095 a space-separated list of the integers stored in OS all on one line. */
1097 static void
1098 dired_dump_obstack (char const *prefix, struct obstack *os)
1100 size_t n_pos;
1102 n_pos = obstack_object_size (os) / sizeof (dired_pos);
1103 if (n_pos > 0)
1105 off_t *pos = obstack_finish (os);
1106 fputs (prefix, stdout);
1107 for (size_t i = 0; i < n_pos; i++)
1109 intmax_t p = pos[i];
1110 printf (" %jd", p);
1112 putchar ('\n');
1116 /* Return the platform birthtime member of the stat structure,
1117 or fallback to the mtime member, which we have populated
1118 from the statx structure or reset to an invalid timestamp
1119 where birth time is not supported. */
1120 static struct timespec
1121 get_stat_btime (struct stat const *st)
1123 struct timespec btimespec;
1125 #if HAVE_STATX && defined STATX_INO
1126 btimespec = get_stat_mtime (st);
1127 #else
1128 btimespec = get_stat_birthtime (st);
1129 #endif
1131 return btimespec;
1134 #if HAVE_STATX && defined STATX_INO
1135 ATTRIBUTE_PURE
1136 static unsigned int
1137 time_type_to_statx (void)
1139 switch (time_type)
1141 case time_ctime:
1142 return STATX_CTIME;
1143 case time_mtime:
1144 return STATX_MTIME;
1145 case time_atime:
1146 return STATX_ATIME;
1147 case time_btime:
1148 return STATX_BTIME;
1149 default:
1150 unreachable ();
1152 return 0;
1155 ATTRIBUTE_PURE
1156 static unsigned int
1157 calc_req_mask (void)
1159 unsigned int mask = STATX_MODE;
1161 if (print_inode)
1162 mask |= STATX_INO;
1164 if (print_block_size)
1165 mask |= STATX_BLOCKS;
1167 if (format == long_format) {
1168 mask |= STATX_NLINK | STATX_SIZE | time_type_to_statx ();
1169 if (print_owner || print_author)
1170 mask |= STATX_UID;
1171 if (print_group)
1172 mask |= STATX_GID;
1175 switch (sort_type)
1177 case sort_none:
1178 case sort_name:
1179 case sort_version:
1180 case sort_extension:
1181 case sort_width:
1182 break;
1183 case sort_time:
1184 mask |= time_type_to_statx ();
1185 break;
1186 case sort_size:
1187 mask |= STATX_SIZE;
1188 break;
1189 default:
1190 unreachable ();
1193 return mask;
1196 static int
1197 do_statx (int fd, char const *name, struct stat *st, int flags,
1198 unsigned int mask)
1200 struct statx stx;
1201 bool want_btime = mask & STATX_BTIME;
1202 int ret = statx (fd, name, flags | AT_NO_AUTOMOUNT, mask, &stx);
1203 if (ret >= 0)
1205 statx_to_stat (&stx, st);
1206 /* Since we only need one timestamp type,
1207 store birth time in st_mtim. */
1208 if (want_btime)
1210 if (stx.stx_mask & STATX_BTIME)
1211 st->st_mtim = statx_timestamp_to_timespec (stx.stx_btime);
1212 else
1213 st->st_mtim.tv_sec = st->st_mtim.tv_nsec = -1;
1217 return ret;
1220 static int
1221 do_stat (char const *name, struct stat *st)
1223 return do_statx (AT_FDCWD, name, st, 0, calc_req_mask ());
1226 static int
1227 do_lstat (char const *name, struct stat *st)
1229 return do_statx (AT_FDCWD, name, st, AT_SYMLINK_NOFOLLOW, calc_req_mask ());
1232 static int
1233 stat_for_mode (char const *name, struct stat *st)
1235 return do_statx (AT_FDCWD, name, st, 0, STATX_MODE);
1238 /* dev+ino should be static, so no need to sync with backing store */
1239 static int
1240 stat_for_ino (char const *name, struct stat *st)
1242 return do_statx (AT_FDCWD, name, st, 0, STATX_INO);
1245 static int
1246 fstat_for_ino (int fd, struct stat *st)
1248 return do_statx (fd, "", st, AT_EMPTY_PATH, STATX_INO);
1250 #else
1251 static int
1252 do_stat (char const *name, struct stat *st)
1254 return stat (name, st);
1257 static int
1258 do_lstat (char const *name, struct stat *st)
1260 return lstat (name, st);
1263 static int
1264 stat_for_mode (char const *name, struct stat *st)
1266 return stat (name, st);
1269 static int
1270 stat_for_ino (char const *name, struct stat *st)
1272 return stat (name, st);
1275 static int
1276 fstat_for_ino (int fd, struct stat *st)
1278 return fstat (fd, st);
1280 #endif
1282 /* Return the address of the first plain %b spec in FMT, or nullptr if
1283 there is no such spec. %5b etc. do not match, so that user
1284 widths/flags are honored. */
1286 ATTRIBUTE_PURE
1287 static char const *
1288 first_percent_b (char const *fmt)
1290 for (; *fmt; fmt++)
1291 if (fmt[0] == '%')
1292 switch (fmt[1])
1294 case 'b': return fmt;
1295 case '%': fmt++; break;
1297 return nullptr;
1300 static char RFC3986[256];
1301 static void
1302 file_escape_init (void)
1304 for (int i = 0; i < 256; i++)
1305 RFC3986[i] |= c_isalnum (i) || i == '~' || i == '-' || i == '.' || i == '_';
1308 enum { MBSWIDTH_FLAGS = MBSW_REJECT_INVALID | MBSW_REJECT_UNPRINTABLE };
1310 /* Read the abbreviated month names from the locale, to align them
1311 and to determine the max width of the field and to truncate names
1312 greater than our max allowed.
1313 Note even though this handles multibyte locales correctly
1314 it's not restricted to them as single byte locales can have
1315 variable width abbreviated months and also precomputing/caching
1316 the names was seen to increase the performance of ls significantly. */
1318 /* abformat[RECENT][MON] is the format to use for timestamps with
1319 recentness RECENT and month MON. */
1320 enum { ABFORMAT_SIZE = 128 };
1321 static char abformat[2][12][ABFORMAT_SIZE];
1322 /* True if precomputed formats should be used. This can be false if
1323 nl_langinfo fails, if a format or month abbreviation is unusually
1324 long, or if a month abbreviation contains '%'. */
1325 static bool use_abformat;
1327 /* Store into ABMON the abbreviated month names, suitably aligned.
1328 Return true if successful. */
1330 static bool
1331 abmon_init (char abmon[12][ABFORMAT_SIZE])
1333 #ifndef HAVE_NL_LANGINFO
1334 return false;
1335 #else
1336 int max_mon_width = 0;
1337 int mon_width[12];
1338 int mon_len[12];
1340 for (int i = 0; i < 12; i++)
1342 char const *abbr = nl_langinfo (ABMON_1 + i);
1343 mon_len[i] = strnlen (abbr, ABFORMAT_SIZE);
1344 if (mon_len[i] == ABFORMAT_SIZE)
1345 return false;
1346 if (strchr (abbr, '%'))
1347 return false;
1348 mon_width[i] = mbswidth (strcpy (abmon[i], abbr), MBSWIDTH_FLAGS);
1349 if (mon_width[i] < 0)
1350 return false;
1351 max_mon_width = MAX (max_mon_width, mon_width[i]);
1354 for (int i = 0; i < 12; i++)
1356 int fill = max_mon_width - mon_width[i];
1357 if (ABFORMAT_SIZE - mon_len[i] <= fill)
1358 return false;
1359 bool align_left = !isdigit (to_uchar (abmon[i][0]));
1360 int fill_offset;
1361 if (align_left)
1362 fill_offset = mon_len[i];
1363 else
1365 memmove (abmon[i] + fill, abmon[i], mon_len[i]);
1366 fill_offset = 0;
1368 memset (abmon[i] + fill_offset, ' ', fill);
1369 abmon[i][mon_len[i] + fill] = '\0';
1372 return true;
1373 #endif
1376 /* Initialize ABFORMAT and USE_ABFORMAT. */
1378 static void
1379 abformat_init (void)
1381 char const *pb[2];
1382 for (int recent = 0; recent < 2; recent++)
1383 pb[recent] = first_percent_b (long_time_format[recent]);
1384 if (! (pb[0] || pb[1]))
1385 return;
1387 char abmon[12][ABFORMAT_SIZE];
1388 if (! abmon_init (abmon))
1389 return;
1391 for (int recent = 0; recent < 2; recent++)
1393 char const *fmt = long_time_format[recent];
1394 for (int i = 0; i < 12; i++)
1396 char *nfmt = abformat[recent][i];
1397 int nbytes;
1399 if (! pb[recent])
1400 nbytes = snprintf (nfmt, ABFORMAT_SIZE, "%s", fmt);
1401 else
1403 if (! (pb[recent] - fmt <= MIN (ABFORMAT_SIZE, INT_MAX)))
1404 return;
1405 int prefix_len = pb[recent] - fmt;
1406 nbytes = snprintf (nfmt, ABFORMAT_SIZE, "%.*s%s%s",
1407 prefix_len, fmt, abmon[i], pb[recent] + 2);
1410 if (! (0 <= nbytes && nbytes < ABFORMAT_SIZE))
1411 return;
1415 use_abformat = true;
1418 static size_t
1419 dev_ino_hash (void const *x, size_t table_size)
1421 struct dev_ino const *p = x;
1422 return (uintmax_t) p->st_ino % table_size;
1425 static bool
1426 dev_ino_compare (void const *x, void const *y)
1428 struct dev_ino const *a = x;
1429 struct dev_ino const *b = y;
1430 return PSAME_INODE (a, b);
1433 static void
1434 dev_ino_free (void *x)
1436 free (x);
1439 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
1440 active directories. Return true if there is already a matching
1441 entry in the table. */
1443 static bool
1444 visit_dir (dev_t dev, ino_t ino)
1446 struct dev_ino *ent;
1447 struct dev_ino *ent_from_table;
1448 bool found_match;
1450 ent = xmalloc (sizeof *ent);
1451 ent->st_ino = ino;
1452 ent->st_dev = dev;
1454 /* Attempt to insert this entry into the table. */
1455 ent_from_table = hash_insert (active_dir_set, ent);
1457 if (ent_from_table == nullptr)
1459 /* Insertion failed due to lack of memory. */
1460 xalloc_die ();
1463 found_match = (ent_from_table != ent);
1465 if (found_match)
1467 /* ent was not inserted, so free it. */
1468 free (ent);
1471 return found_match;
1474 static void
1475 free_pending_ent (struct pending *p)
1477 free (p->name);
1478 free (p->realname);
1479 free (p);
1482 static bool
1483 is_colored (enum indicator_no type)
1485 /* Return true unless the string is "", "0" or "00"; try to be efficient. */
1486 size_t len = color_indicator[type].len;
1487 if (len == 0)
1488 return false;
1489 if (2 < len)
1490 return true;
1491 char const *s = color_indicator[type].string;
1492 return (s[0] != '0') | (s[len - 1] != '0');
1495 static void
1496 restore_default_color (void)
1498 put_indicator (&color_indicator[C_LEFT]);
1499 put_indicator (&color_indicator[C_RIGHT]);
1502 static void
1503 set_normal_color (void)
1505 if (print_with_color && is_colored (C_NORM))
1507 put_indicator (&color_indicator[C_LEFT]);
1508 put_indicator (&color_indicator[C_NORM]);
1509 put_indicator (&color_indicator[C_RIGHT]);
1513 /* An ordinary signal was received; arrange for the program to exit. */
1515 static void
1516 sighandler (int sig)
1518 if (! SA_NOCLDSTOP)
1519 signal (sig, SIG_IGN);
1520 if (! interrupt_signal)
1521 interrupt_signal = sig;
1524 /* A SIGTSTP was received; arrange for the program to suspend itself. */
1526 static void
1527 stophandler (int sig)
1529 if (! SA_NOCLDSTOP)
1530 signal (sig, stophandler);
1531 if (! interrupt_signal)
1532 stop_signal_count++;
1535 /* Process any pending signals. If signals are caught, this function
1536 should be called periodically. Ideally there should never be an
1537 unbounded amount of time when signals are not being processed.
1538 Signal handling can restore the default colors, so callers must
1539 immediately change colors after invoking this function. */
1541 static void
1542 process_signals (void)
1544 while (interrupt_signal || stop_signal_count)
1546 int sig;
1547 int stops;
1548 sigset_t oldset;
1550 if (used_color)
1551 restore_default_color ();
1552 fflush (stdout);
1554 sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
1556 /* Reload interrupt_signal and stop_signal_count, in case a new
1557 signal was handled before sigprocmask took effect. */
1558 sig = interrupt_signal;
1559 stops = stop_signal_count;
1561 /* SIGTSTP is special, since the application can receive that signal
1562 more than once. In this case, don't set the signal handler to the
1563 default. Instead, just raise the uncatchable SIGSTOP. */
1564 if (stops)
1566 stop_signal_count = stops - 1;
1567 sig = SIGSTOP;
1569 else
1570 signal (sig, SIG_DFL);
1572 /* Exit or suspend the program. */
1573 raise (sig);
1574 sigprocmask (SIG_SETMASK, &oldset, nullptr);
1576 /* If execution reaches here, then the program has been
1577 continued (after being suspended). */
1581 /* Setup signal handlers if INIT is true,
1582 otherwise restore to the default. */
1584 static void
1585 signal_setup (bool init)
1587 /* The signals that are trapped, and the number of such signals. */
1588 static int const sig[] =
1590 /* This one is handled specially. */
1591 SIGTSTP,
1593 /* The usual suspects. */
1594 SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM,
1595 #ifdef SIGPOLL
1596 SIGPOLL,
1597 #endif
1598 #ifdef SIGPROF
1599 SIGPROF,
1600 #endif
1601 #ifdef SIGVTALRM
1602 SIGVTALRM,
1603 #endif
1604 #ifdef SIGXCPU
1605 SIGXCPU,
1606 #endif
1607 #ifdef SIGXFSZ
1608 SIGXFSZ,
1609 #endif
1611 enum { nsigs = ARRAY_CARDINALITY (sig) };
1613 #if ! SA_NOCLDSTOP
1614 static bool caught_sig[nsigs];
1615 #endif
1617 int j;
1619 if (init)
1621 #if SA_NOCLDSTOP
1622 struct sigaction act;
1624 sigemptyset (&caught_signals);
1625 for (j = 0; j < nsigs; j++)
1627 sigaction (sig[j], nullptr, &act);
1628 if (act.sa_handler != SIG_IGN)
1629 sigaddset (&caught_signals, sig[j]);
1632 act.sa_mask = caught_signals;
1633 act.sa_flags = SA_RESTART;
1635 for (j = 0; j < nsigs; j++)
1636 if (sigismember (&caught_signals, sig[j]))
1638 act.sa_handler = sig[j] == SIGTSTP ? stophandler : sighandler;
1639 sigaction (sig[j], &act, nullptr);
1641 #else
1642 for (j = 0; j < nsigs; j++)
1644 caught_sig[j] = (signal (sig[j], SIG_IGN) != SIG_IGN);
1645 if (caught_sig[j])
1647 signal (sig[j], sig[j] == SIGTSTP ? stophandler : sighandler);
1648 siginterrupt (sig[j], 0);
1651 #endif
1653 else /* restore. */
1655 #if SA_NOCLDSTOP
1656 for (j = 0; j < nsigs; j++)
1657 if (sigismember (&caught_signals, sig[j]))
1658 signal (sig[j], SIG_DFL);
1659 #else
1660 for (j = 0; j < nsigs; j++)
1661 if (caught_sig[j])
1662 signal (sig[j], SIG_DFL);
1663 #endif
1667 static void
1668 signal_init (void)
1670 signal_setup (true);
1673 static void
1674 signal_restore (void)
1676 signal_setup (false);
1680 main (int argc, char **argv)
1682 int i;
1683 struct pending *thispend;
1684 int n_files;
1686 initialize_main (&argc, &argv);
1687 set_program_name (argv[0]);
1688 setlocale (LC_ALL, "");
1689 bindtextdomain (PACKAGE, LOCALEDIR);
1690 textdomain (PACKAGE);
1692 initialize_exit_failure (LS_FAILURE);
1693 atexit (close_stdout);
1695 static_assert (ARRAY_CARDINALITY (color_indicator)
1696 == ARRAY_CARDINALITY (indicator_name));
1698 exit_status = EXIT_SUCCESS;
1699 print_dir_name = true;
1700 pending_dirs = nullptr;
1702 current_time.tv_sec = TYPE_MINIMUM (time_t);
1703 current_time.tv_nsec = -1;
1705 i = decode_switches (argc, argv);
1707 if (print_with_color)
1708 parse_ls_color ();
1710 /* Test print_with_color again, because the call to parse_ls_color
1711 may have just reset it -- e.g., if LS_COLORS is invalid. */
1713 if (print_with_color)
1715 /* Don't use TAB characters in output. Some terminal
1716 emulators can't handle the combination of tabs and
1717 color codes on the same line. */
1718 tabsize = 0;
1721 if (directories_first)
1722 check_symlink_mode = true;
1723 else if (print_with_color)
1725 /* Avoid following symbolic links when possible. */
1726 if (is_colored (C_ORPHAN)
1727 || (is_colored (C_EXEC) && color_symlink_as_referent)
1728 || (is_colored (C_MISSING) && format == long_format))
1729 check_symlink_mode = true;
1732 if (dereference == DEREF_UNDEFINED)
1733 dereference = ((immediate_dirs
1734 || indicator_style == classify
1735 || format == long_format)
1736 ? DEREF_NEVER
1737 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
1739 /* When using -R, initialize a data structure we'll use to
1740 detect any directory cycles. */
1741 if (recursive)
1743 active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, nullptr,
1744 dev_ino_hash,
1745 dev_ino_compare,
1746 dev_ino_free);
1747 if (active_dir_set == nullptr)
1748 xalloc_die ();
1750 obstack_init (&dev_ino_obstack);
1753 localtz = tzalloc (getenv ("TZ"));
1755 format_needs_stat = ((sort_type == sort_time) | (sort_type == sort_size)
1756 | (format == long_format)
1757 | print_block_size | print_hyperlink);
1758 format_needs_type = ((! format_needs_stat)
1759 & (recursive | print_with_color | print_scontext
1760 | directories_first
1761 | (indicator_style != none)));
1762 format_needs_capability = print_with_color && is_colored (C_CAP);
1764 if (dired)
1766 obstack_init (&dired_obstack);
1767 obstack_init (&subdired_obstack);
1770 if (print_hyperlink)
1772 file_escape_init ();
1774 hostname = xgethostname ();
1775 /* The hostname is generally ignored,
1776 so ignore failures obtaining it. */
1777 if (! hostname)
1778 hostname = "";
1781 cwd_n_alloc = 100;
1782 cwd_file = xnmalloc (cwd_n_alloc, sizeof *cwd_file);
1783 cwd_n_used = 0;
1785 clear_files ();
1787 n_files = argc - i;
1789 if (n_files <= 0)
1791 if (immediate_dirs)
1792 gobble_file (".", directory, NOT_AN_INODE_NUMBER, true, nullptr);
1793 else
1794 queue_directory (".", nullptr, true);
1796 else
1798 gobble_file (argv[i++], unknown, NOT_AN_INODE_NUMBER, true, nullptr);
1799 while (i < argc);
1801 if (cwd_n_used)
1803 sort_files ();
1804 if (!immediate_dirs)
1805 extract_dirs_from_files (nullptr, true);
1806 /* 'cwd_n_used' might be zero now. */
1809 /* In the following if/else blocks, it is sufficient to test 'pending_dirs'
1810 (and not pending_dirs->name) because there may be no markers in the queue
1811 at this point. A marker may be enqueued when extract_dirs_from_files is
1812 called with a non-empty string or via print_dir. */
1813 if (cwd_n_used)
1815 print_current_files ();
1816 if (pending_dirs)
1817 dired_outbyte ('\n');
1819 else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1820 print_dir_name = false;
1822 while (pending_dirs)
1824 thispend = pending_dirs;
1825 pending_dirs = pending_dirs->next;
1827 if (LOOP_DETECT)
1829 if (thispend->name == nullptr)
1831 /* thispend->name == nullptr means this is a marker entry
1832 indicating we've finished processing the directory.
1833 Use its dev/ino numbers to remove the corresponding
1834 entry from the active_dir_set hash table. */
1835 struct dev_ino di = dev_ino_pop ();
1836 struct dev_ino *found = hash_remove (active_dir_set, &di);
1837 if (false)
1838 assert_matching_dev_ino (thispend->realname, di);
1839 affirm (found);
1840 dev_ino_free (found);
1841 free_pending_ent (thispend);
1842 continue;
1846 print_dir (thispend->name, thispend->realname,
1847 thispend->command_line_arg);
1849 free_pending_ent (thispend);
1850 print_dir_name = true;
1853 if (print_with_color && used_color)
1855 int j;
1857 /* Skip the restore when it would be a no-op, i.e.,
1858 when left is "\033[" and right is "m". */
1859 if (!(color_indicator[C_LEFT].len == 2
1860 && memcmp (color_indicator[C_LEFT].string, "\033[", 2) == 0
1861 && color_indicator[C_RIGHT].len == 1
1862 && color_indicator[C_RIGHT].string[0] == 'm'))
1863 restore_default_color ();
1865 fflush (stdout);
1867 signal_restore ();
1869 /* Act on any signals that arrived before the default was restored.
1870 This can process signals out of order, but there doesn't seem to
1871 be an easy way to do them in order, and the order isn't that
1872 important anyway. */
1873 for (j = stop_signal_count; j; j--)
1874 raise (SIGSTOP);
1875 j = interrupt_signal;
1876 if (j)
1877 raise (j);
1880 if (dired)
1882 /* No need to free these since we're about to exit. */
1883 dired_dump_obstack ("//DIRED//", &dired_obstack);
1884 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1885 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1886 quoting_style_args[get_quoting_style (filename_quoting_options)]);
1889 if (LOOP_DETECT)
1891 assure (hash_get_n_entries (active_dir_set) == 0);
1892 hash_free (active_dir_set);
1895 return exit_status;
1898 /* Return the line length indicated by the value given by SPEC, or -1
1899 if unsuccessful. 0 means no limit on line length. */
1901 static ptrdiff_t
1902 decode_line_length (char const *spec)
1904 uintmax_t val;
1906 /* Treat too-large values as if they were 0, which is
1907 effectively infinity. */
1908 switch (xstrtoumax (spec, nullptr, 0, &val, ""))
1910 case LONGINT_OK:
1911 return val <= MIN (PTRDIFF_MAX, SIZE_MAX) ? val : 0;
1913 case LONGINT_OVERFLOW:
1914 return 0;
1916 default:
1917 return -1;
1921 /* Return true if standard output is a tty, caching the result. */
1923 static bool
1924 stdout_isatty (void)
1926 static signed char out_tty = -1;
1927 if (out_tty < 0)
1928 out_tty = isatty (STDOUT_FILENO);
1929 assume (out_tty == 0 || out_tty == 1);
1930 return out_tty;
1933 /* Set all the option flags according to the switches specified.
1934 Return the index of the first non-option argument. */
1936 static int
1937 decode_switches (int argc, char **argv)
1939 char const *time_style_option = nullptr;
1941 /* These variables are false or -1 unless a switch says otherwise. */
1942 bool kibibytes_specified = false;
1943 int format_opt = -1;
1944 int hide_control_chars_opt = -1;
1945 int quoting_style_opt = -1;
1946 int sort_opt = -1;
1947 ptrdiff_t tabsize_opt = -1;
1948 ptrdiff_t width_opt = -1;
1950 while (true)
1952 int oi = -1;
1953 int c = getopt_long (argc, argv,
1954 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1",
1955 long_options, &oi);
1956 if (c == -1)
1957 break;
1959 switch (c)
1961 case 'a':
1962 ignore_mode = IGNORE_MINIMAL;
1963 break;
1965 case 'b':
1966 quoting_style_opt = escape_quoting_style;
1967 break;
1969 case 'c':
1970 time_type = time_ctime;
1971 explicit_time = true;
1972 break;
1974 case 'd':
1975 immediate_dirs = true;
1976 break;
1978 case 'f':
1979 ignore_mode = IGNORE_MINIMAL; /* enable -a */
1980 sort_opt = sort_none; /* enable -U */
1981 break;
1983 case FILE_TYPE_INDICATOR_OPTION: /* --file-type */
1984 indicator_style = file_type;
1985 break;
1987 case 'g':
1988 format_opt = long_format;
1989 print_owner = false;
1990 break;
1992 case 'h':
1993 file_human_output_opts = human_output_opts =
1994 human_autoscale | human_SI | human_base_1024;
1995 file_output_block_size = output_block_size = 1;
1996 break;
1998 case 'i':
1999 print_inode = true;
2000 break;
2002 case 'k':
2003 kibibytes_specified = true;
2004 break;
2006 case 'l':
2007 format_opt = long_format;
2008 break;
2010 case 'm':
2011 format_opt = with_commas;
2012 break;
2014 case 'n':
2015 numeric_ids = true;
2016 format_opt = long_format;
2017 break;
2019 case 'o': /* Just like -l, but don't display group info. */
2020 format_opt = long_format;
2021 print_group = false;
2022 break;
2024 case 'p':
2025 indicator_style = slash;
2026 break;
2028 case 'q':
2029 hide_control_chars_opt = true;
2030 break;
2032 case 'r':
2033 sort_reverse = true;
2034 break;
2036 case 's':
2037 print_block_size = true;
2038 break;
2040 case 't':
2041 sort_opt = sort_time;
2042 break;
2044 case 'u':
2045 time_type = time_atime;
2046 explicit_time = true;
2047 break;
2049 case 'v':
2050 sort_opt = sort_version;
2051 break;
2053 case 'w':
2054 width_opt = decode_line_length (optarg);
2055 if (width_opt < 0)
2056 error (LS_FAILURE, 0, "%s: %s", _("invalid line width"),
2057 quote (optarg));
2058 break;
2060 case 'x':
2061 format_opt = horizontal;
2062 break;
2064 case 'A':
2065 ignore_mode = IGNORE_DOT_AND_DOTDOT;
2066 break;
2068 case 'B':
2069 add_ignore_pattern ("*~");
2070 add_ignore_pattern (".*~");
2071 break;
2073 case 'C':
2074 format_opt = many_per_line;
2075 break;
2077 case 'D':
2078 format_opt = long_format;
2079 print_hyperlink = false;
2080 dired = true;
2081 break;
2083 case 'F':
2085 int i;
2086 if (optarg)
2087 i = XARGMATCH ("--classify", optarg, when_args, when_types);
2088 else
2089 /* Using --classify with no argument is equivalent to using
2090 --classify=always. */
2091 i = when_always;
2093 if (i == when_always || (i == when_if_tty && stdout_isatty ()))
2094 indicator_style = classify;
2095 break;
2098 case 'G': /* inhibit display of group info */
2099 print_group = false;
2100 break;
2102 case 'H':
2103 dereference = DEREF_COMMAND_LINE_ARGUMENTS;
2104 break;
2106 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
2107 dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
2108 break;
2110 case 'I':
2111 add_ignore_pattern (optarg);
2112 break;
2114 case 'L':
2115 dereference = DEREF_ALWAYS;
2116 break;
2118 case 'N':
2119 quoting_style_opt = literal_quoting_style;
2120 break;
2122 case 'Q':
2123 quoting_style_opt = c_quoting_style;
2124 break;
2126 case 'R':
2127 recursive = true;
2128 break;
2130 case 'S':
2131 sort_opt = sort_size;
2132 break;
2134 case 'T':
2135 tabsize_opt = xnumtoumax (optarg, 0, 0, MIN (PTRDIFF_MAX, SIZE_MAX),
2136 "", _("invalid tab size"), LS_FAILURE, 0);
2137 break;
2139 case 'U':
2140 sort_opt = sort_none;
2141 break;
2143 case 'X':
2144 sort_opt = sort_extension;
2145 break;
2147 case '1':
2148 /* -1 has no effect after -l. */
2149 if (format_opt != long_format)
2150 format_opt = one_per_line;
2151 break;
2153 case AUTHOR_OPTION:
2154 print_author = true;
2155 break;
2157 case HIDE_OPTION:
2159 struct ignore_pattern *hide = xmalloc (sizeof *hide);
2160 hide->pattern = optarg;
2161 hide->next = hide_patterns;
2162 hide_patterns = hide;
2164 break;
2166 case SORT_OPTION:
2167 sort_opt = XARGMATCH ("--sort", optarg, sort_args, sort_types);
2168 break;
2170 case GROUP_DIRECTORIES_FIRST_OPTION:
2171 directories_first = true;
2172 break;
2174 case TIME_OPTION:
2175 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
2176 explicit_time = true;
2177 break;
2179 case FORMAT_OPTION:
2180 format_opt = XARGMATCH ("--format", optarg, format_args,
2181 format_types);
2182 break;
2184 case FULL_TIME_OPTION:
2185 format_opt = long_format;
2186 time_style_option = "full-iso";
2187 break;
2189 case COLOR_OPTION:
2191 int i;
2192 if (optarg)
2193 i = XARGMATCH ("--color", optarg, when_args, when_types);
2194 else
2195 /* Using --color with no argument is equivalent to using
2196 --color=always. */
2197 i = when_always;
2199 print_with_color = (i == when_always
2200 || (i == when_if_tty && stdout_isatty ()));
2201 break;
2204 case HYPERLINK_OPTION:
2206 int i;
2207 if (optarg)
2208 i = XARGMATCH ("--hyperlink", optarg, when_args, when_types);
2209 else
2210 /* Using --hyperlink with no argument is equivalent to using
2211 --hyperlink=always. */
2212 i = when_always;
2214 print_hyperlink = (i == when_always
2215 || (i == when_if_tty && stdout_isatty ()));
2216 break;
2219 case INDICATOR_STYLE_OPTION:
2220 indicator_style = XARGMATCH ("--indicator-style", optarg,
2221 indicator_style_args,
2222 indicator_style_types);
2223 break;
2225 case QUOTING_STYLE_OPTION:
2226 quoting_style_opt = XARGMATCH ("--quoting-style", optarg,
2227 quoting_style_args,
2228 quoting_style_vals);
2229 break;
2231 case TIME_STYLE_OPTION:
2232 time_style_option = optarg;
2233 break;
2235 case SHOW_CONTROL_CHARS_OPTION:
2236 hide_control_chars_opt = false;
2237 break;
2239 case BLOCK_SIZE_OPTION:
2241 enum strtol_error e = human_options (optarg, &human_output_opts,
2242 &output_block_size);
2243 if (e != LONGINT_OK)
2244 xstrtol_fatal (e, oi, 0, long_options, optarg);
2245 file_human_output_opts = human_output_opts;
2246 file_output_block_size = output_block_size;
2248 break;
2250 case SI_OPTION:
2251 file_human_output_opts = human_output_opts =
2252 human_autoscale | human_SI;
2253 file_output_block_size = output_block_size = 1;
2254 break;
2256 case 'Z':
2257 print_scontext = true;
2258 break;
2260 case ZERO_OPTION:
2261 eolbyte = 0;
2262 hide_control_chars_opt = false;
2263 if (format_opt != long_format)
2264 format_opt = one_per_line;
2265 print_with_color = false;
2266 quoting_style_opt = literal_quoting_style;
2267 break;
2269 case_GETOPT_HELP_CHAR;
2271 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
2273 default:
2274 usage (LS_FAILURE);
2278 if (! output_block_size)
2280 char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
2281 human_options (ls_block_size,
2282 &human_output_opts, &output_block_size);
2283 if (ls_block_size || getenv ("BLOCK_SIZE"))
2285 file_human_output_opts = human_output_opts;
2286 file_output_block_size = output_block_size;
2288 if (kibibytes_specified)
2290 human_output_opts = 0;
2291 output_block_size = 1024;
2295 format = (0 <= format_opt ? format_opt
2296 : ls_mode == LS_LS ? (stdout_isatty ()
2297 ? many_per_line : one_per_line)
2298 : ls_mode == LS_MULTI_COL ? many_per_line
2299 : /* ls_mode == LS_LONG_FORMAT */ long_format);
2301 /* If the line length was not set by a switch but is needed to determine
2302 output, go to the work of obtaining it from the environment. */
2303 ptrdiff_t linelen = width_opt;
2304 if (format == many_per_line || format == horizontal || format == with_commas
2305 || print_with_color)
2307 #ifdef TIOCGWINSZ
2308 if (linelen < 0)
2310 struct winsize ws;
2311 if (stdout_isatty ()
2312 && 0 <= ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws)
2313 && 0 < ws.ws_col)
2314 linelen = ws.ws_col <= MIN (PTRDIFF_MAX, SIZE_MAX) ? ws.ws_col : 0;
2316 #endif
2317 if (linelen < 0)
2319 char const *p = getenv ("COLUMNS");
2320 if (p && *p)
2322 linelen = decode_line_length (p);
2323 if (linelen < 0)
2324 error (0, 0,
2325 _("ignoring invalid width"
2326 " in environment variable COLUMNS: %s"),
2327 quote (p));
2332 line_length = linelen < 0 ? 80 : linelen;
2334 /* Determine the max possible number of display columns. */
2335 max_idx = line_length / MIN_COLUMN_WIDTH;
2336 /* Account for first display column not having a separator,
2337 or line_lengths shorter than MIN_COLUMN_WIDTH. */
2338 max_idx += line_length % MIN_COLUMN_WIDTH != 0;
2340 if (format == many_per_line || format == horizontal || format == with_commas)
2342 if (0 <= tabsize_opt)
2343 tabsize = tabsize_opt;
2344 else
2346 tabsize = 8;
2347 char const *p = getenv ("TABSIZE");
2348 if (p)
2350 uintmax_t tmp;
2351 if (xstrtoumax (p, nullptr, 0, &tmp, "") == LONGINT_OK
2352 && tmp <= SIZE_MAX)
2353 tabsize = tmp;
2354 else
2355 error (0, 0,
2356 _("ignoring invalid tab size"
2357 " in environment variable TABSIZE: %s"),
2358 quote (p));
2363 qmark_funny_chars = (hide_control_chars_opt < 0
2364 ? ls_mode == LS_LS && stdout_isatty ()
2365 : hide_control_chars_opt);
2367 int qs = quoting_style_opt;
2368 if (qs < 0)
2369 qs = getenv_quoting_style ();
2370 if (qs < 0)
2371 qs = (ls_mode == LS_LS
2372 ? (stdout_isatty () ? shell_escape_quoting_style : -1)
2373 : escape_quoting_style);
2374 if (0 <= qs)
2375 set_quoting_style (nullptr, qs);
2376 qs = get_quoting_style (nullptr);
2377 align_variable_outer_quotes
2378 = ((format == long_format
2379 || ((format == many_per_line || format == horizontal) && line_length))
2380 && (qs == shell_quoting_style
2381 || qs == shell_escape_quoting_style
2382 || qs == c_maybe_quoting_style));
2383 filename_quoting_options = clone_quoting_options (nullptr);
2384 if (qs == escape_quoting_style)
2385 set_char_quoting (filename_quoting_options, ' ', 1);
2386 if (file_type <= indicator_style)
2388 char const *p;
2389 for (p = &"*=>@|"[indicator_style - file_type]; *p; p++)
2390 set_char_quoting (filename_quoting_options, *p, 1);
2393 dirname_quoting_options = clone_quoting_options (nullptr);
2394 set_char_quoting (dirname_quoting_options, ':', 1);
2396 /* --dired implies --format=long (-l) and sans --hyperlink.
2397 So ignore it if those overridden. */
2398 dired &= (format == long_format) & !print_hyperlink;
2400 if (eolbyte < dired)
2401 error (LS_FAILURE, 0, _("--dired and --zero are incompatible"));
2403 /* If a time type is explicitly specified (with -c, -u, or --time=)
2404 and we're not showing a time (-l not specified), then sort by that time,
2405 rather than by name. Note this behavior is unspecified by POSIX. */
2407 sort_type = (0 <= sort_opt ? sort_opt
2408 : (format != long_format && explicit_time)
2409 ? sort_time : sort_name);
2411 if (format == long_format)
2413 char const *style = time_style_option;
2414 static char const posix_prefix[] = "posix-";
2416 if (! style)
2418 style = getenv ("TIME_STYLE");
2419 if (! style)
2420 style = "locale";
2423 while (STREQ_LEN (style, posix_prefix, sizeof posix_prefix - 1))
2425 if (! hard_locale (LC_TIME))
2426 return optind;
2427 style += sizeof posix_prefix - 1;
2430 if (*style == '+')
2432 char const *p0 = style + 1;
2433 char *p0nl = strchr (p0, '\n');
2434 char const *p1 = p0;
2435 if (p0nl)
2437 if (strchr (p0nl + 1, '\n'))
2438 error (LS_FAILURE, 0, _("invalid time style format %s"),
2439 quote (p0));
2440 *p0nl++ = '\0';
2441 p1 = p0nl;
2443 long_time_format[0] = p0;
2444 long_time_format[1] = p1;
2446 else
2448 ptrdiff_t res = argmatch (style, time_style_args,
2449 (char const *) time_style_types,
2450 sizeof (*time_style_types));
2451 if (res < 0)
2453 /* This whole block used to be a simple use of XARGMATCH.
2454 but that didn't print the "posix-"-prefixed variants or
2455 the "+"-prefixed format string option upon failure. */
2456 argmatch_invalid ("time style", style, res);
2458 /* The following is a manual expansion of argmatch_valid,
2459 but with the added "+ ..." description and the [posix-]
2460 prefixes prepended. Note that this simplification works
2461 only because all four existing time_style_types values
2462 are distinct. */
2463 fputs (_("Valid arguments are:\n"), stderr);
2464 char const *const *p = time_style_args;
2465 while (*p)
2466 fprintf (stderr, " - [posix-]%s\n", *p++);
2467 fputs (_(" - +FORMAT (e.g., +%H:%M) for a 'date'-style"
2468 " format\n"), stderr);
2469 usage (LS_FAILURE);
2471 switch (res)
2473 case full_iso_time_style:
2474 long_time_format[0] = long_time_format[1] =
2475 "%Y-%m-%d %H:%M:%S.%N %z";
2476 break;
2478 case long_iso_time_style:
2479 long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
2480 break;
2482 case iso_time_style:
2483 long_time_format[0] = "%Y-%m-%d ";
2484 long_time_format[1] = "%m-%d %H:%M";
2485 break;
2487 case locale_time_style:
2488 if (hard_locale (LC_TIME))
2490 for (int i = 0; i < 2; i++)
2491 long_time_format[i] =
2492 dcgettext (nullptr, long_time_format[i], LC_TIME);
2497 abformat_init ();
2500 return optind;
2503 /* Parse a string as part of the LS_COLORS variable; this may involve
2504 decoding all kinds of escape characters. If equals_end is set an
2505 unescaped equal sign ends the string, otherwise only a : or \0
2506 does. Set *OUTPUT_COUNT to the number of bytes output. Return
2507 true if successful.
2509 The resulting string is *not* null-terminated, but may contain
2510 embedded nulls.
2512 Note that both dest and src are char **; on return they point to
2513 the first free byte after the array and the character that ended
2514 the input string, respectively. */
2516 static bool
2517 get_funky_string (char **dest, char const **src, bool equals_end,
2518 size_t *output_count)
2520 char num; /* For numerical codes */
2521 size_t count; /* Something to count with */
2522 enum {
2523 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
2524 } state;
2525 char const *p;
2526 char *q;
2528 p = *src; /* We don't want to double-indirect */
2529 q = *dest; /* the whole darn time. */
2531 count = 0; /* No characters counted in yet. */
2532 num = 0;
2534 state = ST_GND; /* Start in ground state. */
2535 while (state < ST_END)
2537 switch (state)
2539 case ST_GND: /* Ground state (no escapes) */
2540 switch (*p)
2542 case ':':
2543 case '\0':
2544 state = ST_END; /* End of string */
2545 break;
2546 case '\\':
2547 state = ST_BACKSLASH; /* Backslash escape sequence */
2548 ++p;
2549 break;
2550 case '^':
2551 state = ST_CARET; /* Caret escape */
2552 ++p;
2553 break;
2554 case '=':
2555 if (equals_end)
2557 state = ST_END; /* End */
2558 break;
2560 FALLTHROUGH;
2561 default:
2562 *(q++) = *(p++);
2563 ++count;
2564 break;
2566 break;
2568 case ST_BACKSLASH: /* Backslash escaped character */
2569 switch (*p)
2571 case '0':
2572 case '1':
2573 case '2':
2574 case '3':
2575 case '4':
2576 case '5':
2577 case '6':
2578 case '7':
2579 state = ST_OCTAL; /* Octal sequence */
2580 num = *p - '0';
2581 break;
2582 case 'x':
2583 case 'X':
2584 state = ST_HEX; /* Hex sequence */
2585 num = 0;
2586 break;
2587 case 'a': /* Bell */
2588 num = '\a';
2589 break;
2590 case 'b': /* Backspace */
2591 num = '\b';
2592 break;
2593 case 'e': /* Escape */
2594 num = 27;
2595 break;
2596 case 'f': /* Form feed */
2597 num = '\f';
2598 break;
2599 case 'n': /* Newline */
2600 num = '\n';
2601 break;
2602 case 'r': /* Carriage return */
2603 num = '\r';
2604 break;
2605 case 't': /* Tab */
2606 num = '\t';
2607 break;
2608 case 'v': /* Vtab */
2609 num = '\v';
2610 break;
2611 case '?': /* Delete */
2612 num = 127;
2613 break;
2614 case '_': /* Space */
2615 num = ' ';
2616 break;
2617 case '\0': /* End of string */
2618 state = ST_ERROR; /* Error! */
2619 break;
2620 default: /* Escaped character like \ ^ : = */
2621 num = *p;
2622 break;
2624 if (state == ST_BACKSLASH)
2626 *(q++) = num;
2627 ++count;
2628 state = ST_GND;
2630 ++p;
2631 break;
2633 case ST_OCTAL: /* Octal sequence */
2634 if (*p < '0' || *p > '7')
2636 *(q++) = num;
2637 ++count;
2638 state = ST_GND;
2640 else
2641 num = (num << 3) + (*(p++) - '0');
2642 break;
2644 case ST_HEX: /* Hex sequence */
2645 switch (*p)
2647 case '0':
2648 case '1':
2649 case '2':
2650 case '3':
2651 case '4':
2652 case '5':
2653 case '6':
2654 case '7':
2655 case '8':
2656 case '9':
2657 num = (num << 4) + (*(p++) - '0');
2658 break;
2659 case 'a':
2660 case 'b':
2661 case 'c':
2662 case 'd':
2663 case 'e':
2664 case 'f':
2665 num = (num << 4) + (*(p++) - 'a') + 10;
2666 break;
2667 case 'A':
2668 case 'B':
2669 case 'C':
2670 case 'D':
2671 case 'E':
2672 case 'F':
2673 num = (num << 4) + (*(p++) - 'A') + 10;
2674 break;
2675 default:
2676 *(q++) = num;
2677 ++count;
2678 state = ST_GND;
2679 break;
2681 break;
2683 case ST_CARET: /* Caret escape */
2684 state = ST_GND; /* Should be the next state... */
2685 if (*p >= '@' && *p <= '~')
2687 *(q++) = *(p++) & 037;
2688 ++count;
2690 else if (*p == '?')
2692 *(q++) = 127;
2693 ++count;
2695 else
2696 state = ST_ERROR;
2697 break;
2699 default:
2700 unreachable ();
2704 *dest = q;
2705 *src = p;
2706 *output_count = count;
2708 return state != ST_ERROR;
2711 enum parse_state
2713 PS_START = 1,
2714 PS_2,
2715 PS_3,
2716 PS_4,
2717 PS_DONE,
2718 PS_FAIL
2722 /* Check if the content of TERM is a valid name in dircolors. */
2724 static bool
2725 known_term_type (void)
2727 char const *term = getenv ("TERM");
2728 if (! term || ! *term)
2729 return false;
2731 char const *line = G_line;
2732 while (line - G_line < sizeof (G_line))
2734 if (STRNCMP_LIT (line, "TERM ") == 0)
2736 if (fnmatch (line + 5, term, 0) == 0)
2737 return true;
2739 line += strlen (line) + 1;
2742 return false;
2745 static void
2746 parse_ls_color (void)
2748 char const *p; /* Pointer to character being parsed */
2749 char *buf; /* color_buf buffer pointer */
2750 char label0, label1; /* Indicator label */
2751 struct color_ext_type *ext; /* Extension we are working on */
2753 if ((p = getenv ("LS_COLORS")) == nullptr || *p == '\0')
2755 /* LS_COLORS takes precedence, but if that's not set then
2756 honor the COLORTERM and TERM env variables so that
2757 we only go with the internal ANSI color codes if the
2758 former is non empty or the latter is set to a known value. */
2759 char const *colorterm = getenv ("COLORTERM");
2760 if (! (colorterm && *colorterm) && ! known_term_type ())
2761 print_with_color = false;
2762 return;
2765 ext = nullptr;
2767 /* This is an overly conservative estimate, but any possible
2768 LS_COLORS string will *not* generate a color_buf longer than
2769 itself, so it is a safe way of allocating a buffer in
2770 advance. */
2771 buf = color_buf = xstrdup (p);
2773 enum parse_state state = PS_START;
2774 while (true)
2776 switch (state)
2778 case PS_START: /* First label character */
2779 switch (*p)
2781 case ':':
2782 ++p;
2783 break;
2785 case '*':
2786 /* Allocate new extension block and add to head of
2787 linked list (this way a later definition will
2788 override an earlier one, which can be useful for
2789 having terminal-specific defs override global). */
2791 ext = xmalloc (sizeof *ext);
2792 ext->next = color_ext_list;
2793 color_ext_list = ext;
2794 ext->exact_match = false;
2796 ++p;
2797 ext->ext.string = buf;
2799 state = (get_funky_string (&buf, &p, true, &ext->ext.len)
2800 ? PS_4 : PS_FAIL);
2801 break;
2803 case '\0':
2804 state = PS_DONE; /* Done! */
2805 goto done;
2807 default: /* Assume it is file type label */
2808 label0 = *p++;
2809 state = PS_2;
2810 break;
2812 break;
2814 case PS_2: /* Second label character */
2815 if (*p)
2817 label1 = *p++;
2818 state = PS_3;
2820 else
2821 state = PS_FAIL; /* Error */
2822 break;
2824 case PS_3: /* Equal sign after indicator label */
2825 state = PS_FAIL; /* Assume failure... */
2826 if (*(p++) == '=')/* It *should* be... */
2828 for (int i = 0; i < ARRAY_CARDINALITY (indicator_name); i++)
2830 if ((label0 == indicator_name[i][0])
2831 && (label1 == indicator_name[i][1]))
2833 color_indicator[i].string = buf;
2834 state = (get_funky_string (&buf, &p, false,
2835 &color_indicator[i].len)
2836 ? PS_START : PS_FAIL);
2837 break;
2840 if (state == PS_FAIL)
2841 error (0, 0, _("unrecognized prefix: %s"),
2842 quote ((char []) {label0, label1, '\0'}));
2844 break;
2846 case PS_4: /* Equal sign after *.ext */
2847 if (*(p++) == '=')
2849 ext->seq.string = buf;
2850 state = (get_funky_string (&buf, &p, false, &ext->seq.len)
2851 ? PS_START : PS_FAIL);
2853 else
2854 state = PS_FAIL;
2855 break;
2857 case PS_FAIL:
2858 goto done;
2860 default:
2861 affirm (false);
2864 done:
2866 if (state == PS_FAIL)
2868 struct color_ext_type *e;
2869 struct color_ext_type *e2;
2871 error (0, 0,
2872 _("unparsable value for LS_COLORS environment variable"));
2873 free (color_buf);
2874 for (e = color_ext_list; e != nullptr; /* empty */)
2876 e2 = e;
2877 e = e->next;
2878 free (e2);
2880 print_with_color = false;
2882 else
2884 /* Postprocess list to set EXACT_MATCH on entries where there are
2885 different cased extensions with separate sequences defined.
2886 Also set ext.len to SIZE_MAX on any entries that can't
2887 match due to precedence, to avoid redundant string compares. */
2888 struct color_ext_type *e1;
2890 for (e1 = color_ext_list; e1 != nullptr; e1 = e1->next)
2892 struct color_ext_type *e2;
2893 bool case_ignored = false;
2895 for (e2 = e1->next; e2 != nullptr; e2 = e2->next)
2897 if (e2->ext.len < SIZE_MAX && e1->ext.len == e2->ext.len)
2899 if (memcmp (e1->ext.string, e2->ext.string, e1->ext.len) == 0)
2900 e2->ext.len = SIZE_MAX; /* Ignore */
2901 else if (c_strncasecmp (e1->ext.string, e2->ext.string,
2902 e1->ext.len) == 0)
2904 if (case_ignored)
2906 e2->ext.len = SIZE_MAX; /* Ignore */
2908 else if (e1->seq.len == e2->seq.len
2909 && memcmp (e1->seq.string, e2->seq.string,
2910 e1->seq.len) == 0)
2912 e2->ext.len = SIZE_MAX; /* Ignore */
2913 case_ignored = true; /* Ignore all subsequent */
2915 else
2917 e1->exact_match = true;
2918 e2->exact_match = true;
2926 if (color_indicator[C_LINK].len == 6
2927 && !STRNCMP_LIT (color_indicator[C_LINK].string, "target"))
2928 color_symlink_as_referent = true;
2931 /* Return the quoting style specified by the environment variable
2932 QUOTING_STYLE if set and valid, -1 otherwise. */
2934 static int
2935 getenv_quoting_style (void)
2937 char const *q_style = getenv ("QUOTING_STYLE");
2938 if (!q_style)
2939 return -1;
2940 int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
2941 if (i < 0)
2943 error (0, 0,
2944 _("ignoring invalid value"
2945 " of environment variable QUOTING_STYLE: %s"),
2946 quote (q_style));
2947 return -1;
2949 return quoting_style_vals[i];
2952 /* Set the exit status to report a failure. If SERIOUS, it is a
2953 serious failure; otherwise, it is merely a minor problem. */
2955 static void
2956 set_exit_status (bool serious)
2958 if (serious)
2959 exit_status = LS_FAILURE;
2960 else if (exit_status == EXIT_SUCCESS)
2961 exit_status = LS_MINOR_PROBLEM;
2964 /* Assuming a failure is serious if SERIOUS, use the printf-style
2965 MESSAGE to report the failure to access a file named FILE. Assume
2966 errno is set appropriately for the failure. */
2968 static void
2969 file_failure (bool serious, char const *message, char const *file)
2971 error (0, errno, message, quoteaf (file));
2972 set_exit_status (serious);
2975 /* Request that the directory named NAME have its contents listed later.
2976 If REALNAME is nonzero, it will be used instead of NAME when the
2977 directory name is printed. This allows symbolic links to directories
2978 to be treated as regular directories but still be listed under their
2979 real names. NAME == nullptr is used to insert a marker entry for the
2980 directory named in REALNAME.
2981 If NAME is non-null, we use its dev/ino information to save
2982 a call to stat -- when doing a recursive (-R) traversal.
2983 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2985 static void
2986 queue_directory (char const *name, char const *realname, bool command_line_arg)
2988 struct pending *new = xmalloc (sizeof *new);
2989 new->realname = realname ? xstrdup (realname) : nullptr;
2990 new->name = name ? xstrdup (name) : nullptr;
2991 new->command_line_arg = command_line_arg;
2992 new->next = pending_dirs;
2993 pending_dirs = new;
2996 /* Read directory NAME, and list the files in it.
2997 If REALNAME is nonzero, print its name instead of NAME;
2998 this is used for symbolic links to directories.
2999 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
3001 static void
3002 print_dir (char const *name, char const *realname, bool command_line_arg)
3004 DIR *dirp;
3005 struct dirent *next;
3006 uintmax_t total_blocks = 0;
3007 static bool first = true;
3009 errno = 0;
3010 dirp = opendir (name);
3011 if (!dirp)
3013 file_failure (command_line_arg, _("cannot open directory %s"), name);
3014 return;
3017 if (LOOP_DETECT)
3019 struct stat dir_stat;
3020 int fd = dirfd (dirp);
3022 /* If dirfd failed, endure the overhead of stat'ing by path */
3023 if ((0 <= fd
3024 ? fstat_for_ino (fd, &dir_stat)
3025 : stat_for_ino (name, &dir_stat)) < 0)
3027 file_failure (command_line_arg,
3028 _("cannot determine device and inode of %s"), name);
3029 closedir (dirp);
3030 return;
3033 /* If we've already visited this dev/inode pair, warn that
3034 we've found a loop, and do not process this directory. */
3035 if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
3037 error (0, 0, _("%s: not listing already-listed directory"),
3038 quotef (name));
3039 closedir (dirp);
3040 set_exit_status (true);
3041 return;
3044 dev_ino_push (dir_stat.st_dev, dir_stat.st_ino);
3047 clear_files ();
3049 if (recursive || print_dir_name)
3051 if (!first)
3052 dired_outbyte ('\n');
3053 first = false;
3054 dired_indent ();
3056 char *absolute_name = nullptr;
3057 if (print_hyperlink)
3059 absolute_name = canonicalize_filename_mode (name, CAN_MISSING);
3060 if (! absolute_name)
3061 file_failure (command_line_arg,
3062 _("error canonicalizing %s"), name);
3064 quote_name (realname ? realname : name, dirname_quoting_options, -1,
3065 nullptr, true, &subdired_obstack, absolute_name);
3067 free (absolute_name);
3069 dired_outstring (":\n");
3072 /* Read the directory entries, and insert the subfiles into the 'cwd_file'
3073 table. */
3075 while (true)
3077 /* Set errno to zero so we can distinguish between a readdir failure
3078 and when readdir simply finds that there are no more entries. */
3079 errno = 0;
3080 next = readdir (dirp);
3081 /* Some readdir()s do not absorb ENOENT (dir deleted but open). */
3082 if (errno == ENOENT)
3083 errno = 0;
3084 if (next)
3086 if (! file_ignored (next->d_name))
3088 enum filetype type;
3089 #if HAVE_STRUCT_DIRENT_D_TYPE
3090 type = d_type_filetype[next->d_type];
3091 #else
3092 type = unknown;
3093 #endif
3094 total_blocks += gobble_file (next->d_name, type,
3095 RELIABLE_D_INO (next),
3096 false, name);
3098 /* In this narrow case, print out each name right away, so
3099 ls uses constant memory while processing the entries of
3100 this directory. Useful when there are many (millions)
3101 of entries in a directory. */
3102 if (format == one_per_line && sort_type == sort_none
3103 && !print_block_size && !recursive)
3105 /* We must call sort_files in spite of
3106 "sort_type == sort_none" for its initialization
3107 of the sorted_file vector. */
3108 sort_files ();
3109 print_current_files ();
3110 clear_files ();
3114 else if (errno != 0)
3116 file_failure (command_line_arg, _("reading directory %s"), name);
3117 if (errno != EOVERFLOW)
3118 break;
3120 else
3121 break;
3123 /* When processing a very large directory, and since we've inhibited
3124 interrupts, this loop would take so long that ls would be annoyingly
3125 uninterruptible. This ensures that it handles signals promptly. */
3126 process_signals ();
3129 if (closedir (dirp) != 0)
3131 file_failure (command_line_arg, _("closing directory %s"), name);
3132 /* Don't return; print whatever we got. */
3135 /* Sort the directory contents. */
3136 sort_files ();
3138 /* If any member files are subdirectories, perhaps they should have their
3139 contents listed rather than being mentioned here as files. */
3141 if (recursive)
3142 extract_dirs_from_files (name, false);
3144 if (format == long_format || print_block_size)
3146 char buf[LONGEST_HUMAN_READABLE + 3];
3147 char *p = human_readable (total_blocks, buf + 1, human_output_opts,
3148 ST_NBLOCKSIZE, output_block_size);
3149 char *pend = p + strlen (p);
3150 *--p = ' ';
3151 *pend++ = eolbyte;
3152 dired_indent ();
3153 dired_outstring (_("total"));
3154 dired_outbuf (p, pend - p);
3157 if (cwd_n_used)
3158 print_current_files ();
3161 /* Add 'pattern' to the list of patterns for which files that match are
3162 not listed. */
3164 static void
3165 add_ignore_pattern (char const *pattern)
3167 struct ignore_pattern *ignore;
3169 ignore = xmalloc (sizeof *ignore);
3170 ignore->pattern = pattern;
3171 /* Add it to the head of the linked list. */
3172 ignore->next = ignore_patterns;
3173 ignore_patterns = ignore;
3176 /* Return true if one of the PATTERNS matches FILE. */
3178 static bool
3179 patterns_match (struct ignore_pattern const *patterns, char const *file)
3181 struct ignore_pattern const *p;
3182 for (p = patterns; p; p = p->next)
3183 if (fnmatch (p->pattern, file, FNM_PERIOD) == 0)
3184 return true;
3185 return false;
3188 /* Return true if FILE should be ignored. */
3190 static bool
3191 file_ignored (char const *name)
3193 return ((ignore_mode != IGNORE_MINIMAL
3194 && name[0] == '.'
3195 && (ignore_mode == IGNORE_DEFAULT || ! name[1 + (name[1] == '.')]))
3196 || (ignore_mode == IGNORE_DEFAULT
3197 && patterns_match (hide_patterns, name))
3198 || patterns_match (ignore_patterns, name));
3201 /* POSIX requires that a file size be printed without a sign, even
3202 when negative. Assume the typical case where negative sizes are
3203 actually positive values that have wrapped around. */
3205 static uintmax_t
3206 unsigned_file_size (off_t size)
3208 return size + (size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
3211 #ifdef HAVE_CAP
3212 /* Return true if NAME has a capability (see linux/capability.h) */
3213 static bool
3214 has_capability (char const *name)
3216 char *result;
3217 bool has_cap;
3219 cap_t cap_d = cap_get_file (name);
3220 if (cap_d == nullptr)
3221 return false;
3223 result = cap_to_text (cap_d, nullptr);
3224 cap_free (cap_d);
3225 if (!result)
3226 return false;
3228 /* check if human-readable capability string is empty */
3229 has_cap = !!*result;
3231 cap_free (result);
3232 return has_cap;
3234 #else
3235 static bool
3236 has_capability (MAYBE_UNUSED char const *name)
3238 errno = ENOTSUP;
3239 return false;
3241 #endif
3243 /* Enter and remove entries in the table 'cwd_file'. */
3245 static void
3246 free_ent (struct fileinfo *f)
3248 free (f->name);
3249 free (f->linkname);
3250 free (f->absolute_name);
3251 if (f->scontext != UNKNOWN_SECURITY_CONTEXT)
3252 aclinfo_scontext_free (f->scontext);
3255 /* Empty the table of files. */
3256 static void
3257 clear_files (void)
3259 for (size_t i = 0; i < cwd_n_used; i++)
3261 struct fileinfo *f = sorted_file[i];
3262 free_ent (f);
3265 cwd_n_used = 0;
3266 cwd_some_quoted = false;
3267 any_has_acl = false;
3268 inode_number_width = 0;
3269 block_size_width = 0;
3270 nlink_width = 0;
3271 owner_width = 0;
3272 group_width = 0;
3273 author_width = 0;
3274 scontext_width = 0;
3275 major_device_number_width = 0;
3276 minor_device_number_width = 0;
3277 file_size_width = 0;
3280 /* Return true if ERR implies lack-of-support failure by a
3281 getxattr-calling function like file_has_acl. */
3282 static bool
3283 errno_unsupported (int err)
3285 return (err == EINVAL || err == ENOSYS || is_ENOTSUP (err));
3288 /* Cache file_has_aclinfo failure, when it's trivial to do.
3289 Like file_has_aclinfo, but when F's st_dev says it's on a file
3290 system lacking ACL support, return 0 with ENOTSUP immediately. */
3291 static int
3292 file_has_aclinfo_cache (char const *file, struct fileinfo *f,
3293 struct aclinfo *ai, int flags)
3295 /* st_dev of the most recently processed device for which we've
3296 found that file_has_acl fails indicating lack of support. */
3297 static dev_t unsupported_device;
3299 if (f->stat.st_dev == unsupported_device)
3301 errno = ENOTSUP;
3302 return 0;
3305 int n = file_has_aclinfo (file, ai, flags);
3306 if (n <= 0 && errno_unsupported (ai->u.err))
3307 unsupported_device = f->stat.st_dev;
3308 return n;
3311 /* Cache has_capability failure, when it's trivial to do.
3312 Like has_capability, but when F's st_dev says it's on a file
3313 system lacking capability support, return 0 with ENOTSUP immediately. */
3314 static bool
3315 has_capability_cache (char const *file, struct fileinfo *f)
3317 /* st_dev of the most recently processed device for which we've
3318 found that has_capability fails indicating lack of support. */
3319 static dev_t unsupported_device;
3321 if (f->stat.st_dev == unsupported_device)
3323 errno = ENOTSUP;
3324 return 0;
3327 bool b = has_capability (file);
3328 if ( !b && errno_unsupported (errno))
3329 unsupported_device = f->stat.st_dev;
3330 return b;
3333 static bool
3334 needs_quoting (char const *name)
3336 char test[2];
3337 size_t len = quotearg_buffer (test, sizeof test , name, -1,
3338 filename_quoting_options);
3339 return *name != *test || strlen (name) != len;
3342 /* Add a file to the current table of files.
3343 Verify that the file exists, and print an error message if it does not.
3344 Return the number of blocks that the file occupies. */
3345 static uintmax_t
3346 gobble_file (char const *name, enum filetype type, ino_t inode,
3347 bool command_line_arg, char const *dirname)
3349 uintmax_t blocks = 0;
3350 struct fileinfo *f;
3352 /* An inode value prior to gobble_file necessarily came from readdir,
3353 which is not used for command line arguments. */
3354 affirm (! command_line_arg || inode == NOT_AN_INODE_NUMBER);
3356 if (cwd_n_used == cwd_n_alloc)
3358 cwd_file = xnrealloc (cwd_file, cwd_n_alloc, 2 * sizeof *cwd_file);
3359 cwd_n_alloc *= 2;
3362 f = &cwd_file[cwd_n_used];
3363 memset (f, '\0', sizeof *f);
3364 f->stat.st_ino = inode;
3365 f->filetype = type;
3366 f->scontext = UNKNOWN_SECURITY_CONTEXT;
3368 f->quoted = -1;
3369 if ((! cwd_some_quoted) && align_variable_outer_quotes)
3371 /* Determine if any quoted for padding purposes. */
3372 f->quoted = needs_quoting (name);
3373 if (f->quoted)
3374 cwd_some_quoted = 1;
3377 bool check_stat =
3378 (command_line_arg
3379 || print_hyperlink
3380 || format_needs_stat
3381 || (format_needs_type && type == unknown)
3382 /* When coloring a directory, stat it to indicate
3383 sticky and/or other-writable attributes. */
3384 || ((type == directory || type == unknown) && print_with_color
3385 && (is_colored (C_OTHER_WRITABLE)
3386 || is_colored (C_STICKY)
3387 || is_colored (C_STICKY_OTHER_WRITABLE)))
3388 /* When dereferencing symlinks, the inode and type must come from
3389 stat, but readdir provides the inode and type of lstat. */
3390 || ((print_inode || format_needs_type)
3391 && (type == symbolic_link || type == unknown)
3392 && (dereference == DEREF_ALWAYS
3393 || color_symlink_as_referent || check_symlink_mode))
3394 /* Command line dereferences are already taken care of by the above
3395 assertion that the inode number is not yet known. */
3396 || (print_inode && inode == NOT_AN_INODE_NUMBER)
3397 /* --indicator-style=classify (aka -F) requires statting each
3398 regular file to see whether it's executable. */
3399 || ((type == normal || type == unknown)
3400 && (indicator_style == classify
3401 /* This is so that --color ends up highlighting files with these
3402 mode bits set even when options like -F are not specified. */
3403 || (print_with_color && (is_colored (C_EXEC)
3404 || is_colored (C_SETUID)
3405 || is_colored (C_SETGID))))));
3407 /* Absolute name of this file, if needed. */
3408 char const *full_name = name;
3409 if (check_stat | print_scontext | format_needs_capability
3410 && name[0] != '/' && dirname)
3412 char *p = alloca (strlen (name) + strlen (dirname) + 2);
3413 attach (p, dirname, name);
3414 full_name = p;
3417 bool do_deref;
3419 if (!check_stat)
3420 do_deref = dereference == DEREF_ALWAYS;
3421 else
3423 int err;
3425 if (print_hyperlink)
3427 f->absolute_name = canonicalize_filename_mode (full_name,
3428 CAN_MISSING);
3429 if (! f->absolute_name)
3430 file_failure (command_line_arg,
3431 _("error canonicalizing %s"), full_name);
3434 switch (dereference)
3436 case DEREF_ALWAYS:
3437 err = do_stat (full_name, &f->stat);
3438 do_deref = true;
3439 break;
3441 case DEREF_COMMAND_LINE_ARGUMENTS:
3442 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
3443 if (command_line_arg)
3445 bool need_lstat;
3446 err = do_stat (full_name, &f->stat);
3447 do_deref = true;
3449 if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
3450 break;
3452 need_lstat = (err < 0
3453 ? (errno == ENOENT || errno == ELOOP)
3454 : ! S_ISDIR (f->stat.st_mode));
3455 if (!need_lstat)
3456 break;
3458 /* stat failed because of ENOENT || ELOOP, maybe indicating a
3459 non-traversable symlink. Or stat succeeded,
3460 FULL_NAME does not refer to a directory,
3461 and --dereference-command-line-symlink-to-dir is in effect.
3462 Fall through so that we call lstat instead. */
3464 FALLTHROUGH;
3466 default: /* DEREF_NEVER */
3467 err = do_lstat (full_name, &f->stat);
3468 do_deref = false;
3469 break;
3472 if (err != 0)
3474 /* Failure to stat a command line argument leads to
3475 an exit status of 2. For other files, stat failure
3476 provokes an exit status of 1. */
3477 file_failure (command_line_arg,
3478 _("cannot access %s"), full_name);
3480 if (command_line_arg)
3481 return 0;
3483 f->name = xstrdup (name);
3484 cwd_n_used++;
3486 return 0;
3489 f->stat_ok = true;
3490 f->filetype = type = d_type_filetype[IFTODT (f->stat.st_mode)];
3493 if (type == directory && command_line_arg && !immediate_dirs)
3494 f->filetype = type = arg_directory;
3496 bool check_capability = format_needs_capability & (type == normal);
3498 if ((format == long_format) | print_scontext | check_capability)
3500 struct aclinfo ai;
3501 int n = file_has_aclinfo_cache (full_name, f, &ai,
3502 ((do_deref ? ACL_SYMLINK_FOLLOW : 0)
3503 | filetype_d_type[type]));
3504 bool have_acl = 0 < n;
3505 bool have_scontext = !ai.scontext_err;
3506 f->acl_type = (!have_scontext && !have_acl
3507 ? ACL_T_NONE
3508 : (have_scontext && !have_acl
3509 ? ACL_T_LSM_CONTEXT_ONLY
3510 : ACL_T_YES));
3511 any_has_acl |= f->acl_type != ACL_T_NONE;
3513 if (format == long_format && n < 0)
3514 error (0, ai.u.err, "%s", quotef (full_name));
3515 else
3517 /* When requesting security context information, don't make
3518 ls fail just because the file (even a command line argument)
3519 isn't on the right type of file system. I.e., a getfilecon
3520 failure isn't in the same class as a stat failure. */
3521 if (print_scontext && ai.scontext_err
3522 && (! (is_ENOTSUP (ai.scontext_err)
3523 || ai.scontext_err == ENODATA)))
3524 error (0, ai.scontext_err, "%s", quotef (full_name));
3527 /* has_capability adds around 30% runtime to 'ls --color',
3528 so call it only if really needed. Note capability coloring
3529 is disabled in the default color config. */
3530 if (check_capability && aclinfo_has_xattr (&ai, XATTR_NAME_CAPS))
3531 f->has_capability = has_capability_cache (full_name, f);
3533 f->scontext = ai.scontext;
3534 ai.scontext = nullptr;
3535 aclinfo_free (&ai);
3538 if ((type == symbolic_link)
3539 & ((format == long_format) | check_symlink_mode))
3541 struct stat linkstats;
3543 get_link_name (full_name, f, command_line_arg);
3545 /* Use the slower quoting path for this entry, though
3546 don't update CWD_SOME_QUOTED since alignment not affected. */
3547 if (f->linkname && f->quoted == 0 && needs_quoting (f->linkname))
3548 f->quoted = -1;
3550 /* Avoid following symbolic links when possible, i.e., when
3551 they won't be traced and when no indicator is needed. */
3552 if (f->linkname
3553 && (file_type <= indicator_style || check_symlink_mode)
3554 && stat_for_mode (full_name, &linkstats) == 0)
3556 f->linkok = true;
3557 f->linkmode = linkstats.st_mode;
3561 blocks = STP_NBLOCKS (&f->stat);
3562 if (format == long_format || print_block_size)
3564 char buf[LONGEST_HUMAN_READABLE + 1];
3565 int len = mbswidth (human_readable (blocks, buf, human_output_opts,
3566 ST_NBLOCKSIZE, output_block_size),
3567 MBSWIDTH_FLAGS);
3568 if (block_size_width < len)
3569 block_size_width = len;
3572 if (format == long_format)
3574 if (print_owner)
3576 int len = format_user_width (f->stat.st_uid);
3577 if (owner_width < len)
3578 owner_width = len;
3581 if (print_group)
3583 int len = format_group_width (f->stat.st_gid);
3584 if (group_width < len)
3585 group_width = len;
3588 if (print_author)
3590 int len = format_user_width (f->stat.st_author);
3591 if (author_width < len)
3592 author_width = len;
3596 if (print_scontext)
3598 int len = strlen (f->scontext);
3599 if (scontext_width < len)
3600 scontext_width = len;
3603 if (format == long_format)
3605 char b[INT_BUFSIZE_BOUND (uintmax_t)];
3606 int b_len = strlen (umaxtostr (f->stat.st_nlink, b));
3607 if (nlink_width < b_len)
3608 nlink_width = b_len;
3610 if ((type == chardev) | (type == blockdev))
3612 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
3613 int len = strlen (umaxtostr (major (f->stat.st_rdev), buf));
3614 if (major_device_number_width < len)
3615 major_device_number_width = len;
3616 len = strlen (umaxtostr (minor (f->stat.st_rdev), buf));
3617 if (minor_device_number_width < len)
3618 minor_device_number_width = len;
3619 len = major_device_number_width + 2 + minor_device_number_width;
3620 if (file_size_width < len)
3621 file_size_width = len;
3623 else
3625 char buf[LONGEST_HUMAN_READABLE + 1];
3626 uintmax_t size = unsigned_file_size (f->stat.st_size);
3627 int len = mbswidth (human_readable (size, buf,
3628 file_human_output_opts,
3629 1, file_output_block_size),
3630 MBSWIDTH_FLAGS);
3631 if (file_size_width < len)
3632 file_size_width = len;
3636 if (print_inode)
3638 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
3639 int len = strlen (umaxtostr (f->stat.st_ino, buf));
3640 if (inode_number_width < len)
3641 inode_number_width = len;
3644 f->name = xstrdup (name);
3645 cwd_n_used++;
3647 return blocks;
3650 /* Return true if F refers to a directory. */
3651 static bool
3652 is_directory (const struct fileinfo *f)
3654 return f->filetype == directory || f->filetype == arg_directory;
3657 /* Return true if F refers to a (symlinked) directory. */
3658 static bool
3659 is_linked_directory (const struct fileinfo *f)
3661 return f->filetype == directory || f->filetype == arg_directory
3662 || S_ISDIR (f->linkmode);
3665 /* Put the name of the file that FILENAME is a symbolic link to
3666 into the LINKNAME field of 'f'. COMMAND_LINE_ARG indicates whether
3667 FILENAME is a command-line argument. */
3669 static void
3670 get_link_name (char const *filename, struct fileinfo *f, bool command_line_arg)
3672 f->linkname = areadlink_with_size (filename, f->stat.st_size);
3673 if (f->linkname == nullptr)
3674 file_failure (command_line_arg, _("cannot read symbolic link %s"),
3675 filename);
3678 /* Return true if the last component of NAME is '.' or '..'
3679 This is so we don't try to recurse on '././././. ...' */
3681 static bool
3682 basename_is_dot_or_dotdot (char const *name)
3684 char const *base = last_component (name);
3685 return dot_or_dotdot (base);
3688 /* Remove any entries from CWD_FILE that are for directories,
3689 and queue them to be listed as directories instead.
3690 DIRNAME is the prefix to prepend to each dirname
3691 to make it correct relative to ls's working dir;
3692 if it is null, no prefix is needed and "." and ".." should not be ignored.
3693 If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
3694 This is desirable when processing directories recursively. */
3696 static void
3697 extract_dirs_from_files (char const *dirname, bool command_line_arg)
3699 size_t i;
3700 size_t j;
3701 bool ignore_dot_and_dot_dot = (dirname != nullptr);
3703 if (dirname && LOOP_DETECT)
3705 /* Insert a marker entry first. When we dequeue this marker entry,
3706 we'll know that DIRNAME has been processed and may be removed
3707 from the set of active directories. */
3708 queue_directory (nullptr, dirname, false);
3711 /* Queue the directories last one first, because queueing reverses the
3712 order. */
3713 for (i = cwd_n_used; i-- != 0; )
3715 struct fileinfo *f = sorted_file[i];
3717 if (is_directory (f)
3718 && (! ignore_dot_and_dot_dot
3719 || ! basename_is_dot_or_dotdot (f->name)))
3721 if (!dirname || f->name[0] == '/')
3722 queue_directory (f->name, f->linkname, command_line_arg);
3723 else
3725 char *name = file_name_concat (dirname, f->name, nullptr);
3726 queue_directory (name, f->linkname, command_line_arg);
3727 free (name);
3729 if (f->filetype == arg_directory)
3730 free_ent (f);
3734 /* Now delete the directories from the table, compacting all the remaining
3735 entries. */
3737 for (i = 0, j = 0; i < cwd_n_used; i++)
3739 struct fileinfo *f = sorted_file[i];
3740 sorted_file[j] = f;
3741 j += (f->filetype != arg_directory);
3743 cwd_n_used = j;
3746 /* Use strcoll to compare strings in this locale. If an error occurs,
3747 report an error and longjmp to failed_strcoll. */
3749 static jmp_buf failed_strcoll;
3751 static int
3752 xstrcoll (char const *a, char const *b)
3754 int diff;
3755 errno = 0;
3756 diff = strcoll (a, b);
3757 if (errno)
3759 error (0, errno, _("cannot compare file names %s and %s"),
3760 quote_n (0, a), quote_n (1, b));
3761 set_exit_status (false);
3762 longjmp (failed_strcoll, 1);
3764 return diff;
3767 /* Comparison routines for sorting the files. */
3769 typedef void const *V;
3770 typedef int (*qsortFunc)(V a, V b);
3772 /* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants. */
3773 static int
3774 dirfirst_check (struct fileinfo const *a, struct fileinfo const *b,
3775 int (*cmp) (V, V))
3777 int diff = is_linked_directory (b) - is_linked_directory (a);
3778 return diff ? diff : cmp (a, b);
3781 /* Define the 8 different sort function variants required for each sortkey.
3782 KEY_NAME is a token describing the sort key, e.g., ctime, atime, size.
3783 KEY_CMP_FUNC is a function to compare records based on that key, e.g.,
3784 ctime_cmp, atime_cmp, size_cmp. Append KEY_NAME to the string,
3785 '[rev_][x]str{cmp|coll}[_df]_', to create each function name. */
3786 #define DEFINE_SORT_FUNCTIONS(key_name, key_cmp_func) \
3787 /* direct, non-dirfirst versions */ \
3788 static int xstrcoll_##key_name (V a, V b) \
3789 { return key_cmp_func (a, b, xstrcoll); } \
3790 ATTRIBUTE_PURE static int strcmp_##key_name (V a, V b) \
3791 { return key_cmp_func (a, b, strcmp); } \
3793 /* reverse, non-dirfirst versions */ \
3794 static int rev_xstrcoll_##key_name (V a, V b) \
3795 { return key_cmp_func (b, a, xstrcoll); } \
3796 ATTRIBUTE_PURE static int rev_strcmp_##key_name (V a, V b) \
3797 { return key_cmp_func (b, a, strcmp); } \
3799 /* direct, dirfirst versions */ \
3800 static int xstrcoll_df_##key_name (V a, V b) \
3801 { return dirfirst_check (a, b, xstrcoll_##key_name); } \
3802 ATTRIBUTE_PURE static int strcmp_df_##key_name (V a, V b) \
3803 { return dirfirst_check (a, b, strcmp_##key_name); } \
3805 /* reverse, dirfirst versions */ \
3806 static int rev_xstrcoll_df_##key_name (V a, V b) \
3807 { return dirfirst_check (a, b, rev_xstrcoll_##key_name); } \
3808 ATTRIBUTE_PURE static int rev_strcmp_df_##key_name (V a, V b) \
3809 { return dirfirst_check (a, b, rev_strcmp_##key_name); }
3811 static int
3812 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
3813 int (*cmp) (char const *, char const *))
3815 int diff = timespec_cmp (get_stat_ctime (&b->stat),
3816 get_stat_ctime (&a->stat));
3817 return diff ? diff : cmp (a->name, b->name);
3820 static int
3821 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
3822 int (*cmp) (char const *, char const *))
3824 int diff = timespec_cmp (get_stat_mtime (&b->stat),
3825 get_stat_mtime (&a->stat));
3826 return diff ? diff : cmp (a->name, b->name);
3829 static int
3830 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
3831 int (*cmp) (char const *, char const *))
3833 int diff = timespec_cmp (get_stat_atime (&b->stat),
3834 get_stat_atime (&a->stat));
3835 return diff ? diff : cmp (a->name, b->name);
3838 static int
3839 cmp_btime (struct fileinfo const *a, struct fileinfo const *b,
3840 int (*cmp) (char const *, char const *))
3842 int diff = timespec_cmp (get_stat_btime (&b->stat),
3843 get_stat_btime (&a->stat));
3844 return diff ? diff : cmp (a->name, b->name);
3847 static int
3848 off_cmp (off_t a, off_t b)
3850 return (a > b) - (a < b);
3853 static int
3854 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
3855 int (*cmp) (char const *, char const *))
3857 int diff = off_cmp (b->stat.st_size, a->stat.st_size);
3858 return diff ? diff : cmp (a->name, b->name);
3861 static int
3862 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
3863 int (*cmp) (char const *, char const *))
3865 return cmp (a->name, b->name);
3868 /* Compare file extensions. Files with no extension are 'smallest'.
3869 If extensions are the same, compare by file names instead. */
3871 static int
3872 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
3873 int (*cmp) (char const *, char const *))
3875 char const *base1 = strrchr (a->name, '.');
3876 char const *base2 = strrchr (b->name, '.');
3877 int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
3878 return diff ? diff : cmp (a->name, b->name);
3881 /* Return the (cached) screen width,
3882 for the NAME associated with the passed fileinfo F. */
3884 static size_t
3885 fileinfo_name_width (struct fileinfo const *f)
3887 return f->width
3888 ? f->width
3889 : quote_name_width (f->name, filename_quoting_options, f->quoted);
3892 static int
3893 cmp_width (struct fileinfo const *a, struct fileinfo const *b,
3894 int (*cmp) (char const *, char const *))
3896 int diff = fileinfo_name_width (a) - fileinfo_name_width (b);
3897 return diff ? diff : cmp (a->name, b->name);
3900 DEFINE_SORT_FUNCTIONS (ctime, cmp_ctime)
3901 DEFINE_SORT_FUNCTIONS (mtime, cmp_mtime)
3902 DEFINE_SORT_FUNCTIONS (atime, cmp_atime)
3903 DEFINE_SORT_FUNCTIONS (btime, cmp_btime)
3904 DEFINE_SORT_FUNCTIONS (size, cmp_size)
3905 DEFINE_SORT_FUNCTIONS (name, cmp_name)
3906 DEFINE_SORT_FUNCTIONS (extension, cmp_extension)
3907 DEFINE_SORT_FUNCTIONS (width, cmp_width)
3909 /* Compare file versions.
3910 Unlike the other compare functions, cmp_version does not fail
3911 because filevercmp and strcmp do not fail; cmp_version uses strcmp
3912 instead of xstrcoll because filevercmp is locale-independent so
3913 strcmp is its appropriate secondary.
3915 All the other sort options need xstrcoll and strcmp variants,
3916 because they all use xstrcoll (either as the primary or secondary
3917 sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
3918 locale reasons. */
3919 static int
3920 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
3922 int diff = filevercmp (a->name, b->name);
3923 return diff ? diff : strcmp (a->name, b->name);
3926 static int
3927 xstrcoll_version (V a, V b)
3929 return cmp_version (a, b);
3931 static int
3932 rev_xstrcoll_version (V a, V b)
3934 return cmp_version (b, a);
3936 static int
3937 xstrcoll_df_version (V a, V b)
3939 return dirfirst_check (a, b, xstrcoll_version);
3941 static int
3942 rev_xstrcoll_df_version (V a, V b)
3944 return dirfirst_check (a, b, rev_xstrcoll_version);
3948 /* We have 2^3 different variants for each sort-key function
3949 (for 3 independent sort modes).
3950 The function pointers stored in this array must be dereferenced as:
3952 sort_variants[sort_key][use_strcmp][reverse][dirs_first]
3954 Note that the order in which sort keys are listed in the function pointer
3955 array below is defined by the order of the elements in the time_type and
3956 sort_type enums! */
3958 #define LIST_SORTFUNCTION_VARIANTS(key_name) \
3961 { xstrcoll_##key_name, xstrcoll_df_##key_name }, \
3962 { rev_xstrcoll_##key_name, rev_xstrcoll_df_##key_name }, \
3963 }, \
3965 { strcmp_##key_name, strcmp_df_##key_name }, \
3966 { rev_strcmp_##key_name, rev_strcmp_df_##key_name }, \
3970 static qsortFunc const sort_functions[][2][2][2] =
3972 LIST_SORTFUNCTION_VARIANTS (name),
3973 LIST_SORTFUNCTION_VARIANTS (extension),
3974 LIST_SORTFUNCTION_VARIANTS (width),
3975 LIST_SORTFUNCTION_VARIANTS (size),
3979 { xstrcoll_version, xstrcoll_df_version },
3980 { rev_xstrcoll_version, rev_xstrcoll_df_version },
3983 /* We use nullptr for the strcmp variants of version comparison
3984 since as explained in cmp_version definition, version comparison
3985 does not rely on xstrcoll, so it will never longjmp, and never
3986 need to try the strcmp fallback. */
3988 { nullptr, nullptr },
3989 { nullptr, nullptr },
3993 /* last are time sort functions */
3994 LIST_SORTFUNCTION_VARIANTS (mtime),
3995 LIST_SORTFUNCTION_VARIANTS (ctime),
3996 LIST_SORTFUNCTION_VARIANTS (atime),
3997 LIST_SORTFUNCTION_VARIANTS (btime)
4000 /* The number of sort keys is calculated as the sum of
4001 the number of elements in the sort_type enum (i.e., sort_numtypes)
4002 -2 because neither sort_time nor sort_none use entries themselves
4003 the number of elements in the time_type enum (i.e., time_numtypes)
4004 This is because when sort_type==sort_time, we have up to
4005 time_numtypes possible sort keys.
4007 This line verifies at compile-time that the array of sort functions has been
4008 initialized for all possible sort keys. */
4009 static_assert (ARRAY_CARDINALITY (sort_functions)
4010 == sort_numtypes - 2 + time_numtypes);
4012 /* Set up SORTED_FILE to point to the in-use entries in CWD_FILE, in order. */
4014 static void
4015 initialize_ordering_vector (void)
4017 for (size_t i = 0; i < cwd_n_used; i++)
4018 sorted_file[i] = &cwd_file[i];
4021 /* Cache values based on attributes global to all files. */
4023 static void
4024 update_current_files_info (void)
4026 /* Cache screen width of name, if needed multiple times. */
4027 if (sort_type == sort_width
4028 || (line_length && (format == many_per_line || format == horizontal)))
4030 size_t i;
4031 for (i = 0; i < cwd_n_used; i++)
4033 struct fileinfo *f = sorted_file[i];
4034 f->width = fileinfo_name_width (f);
4039 /* Sort the files now in the table. */
4041 static void
4042 sort_files (void)
4044 bool use_strcmp;
4046 if (sorted_file_alloc < cwd_n_used + cwd_n_used / 2)
4048 free (sorted_file);
4049 sorted_file = xnmalloc (cwd_n_used, 3 * sizeof *sorted_file);
4050 sorted_file_alloc = 3 * cwd_n_used;
4053 initialize_ordering_vector ();
4055 update_current_files_info ();
4057 if (sort_type == sort_none)
4058 return;
4060 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
4061 ignore strcoll failures, as a failing strcoll might be a
4062 comparison function that is not a total order, and if we ignored
4063 the failure this might cause qsort to dump core. */
4065 if (! setjmp (failed_strcoll))
4066 use_strcmp = false; /* strcoll() succeeded */
4067 else
4069 use_strcmp = true;
4070 affirm (sort_type != sort_version);
4071 initialize_ordering_vector ();
4074 /* When sort_type == sort_time, use time_type as subindex. */
4075 mpsort ((void const **) sorted_file, cwd_n_used,
4076 sort_functions[sort_type + (sort_type == sort_time ? time_type : 0)]
4077 [use_strcmp][sort_reverse]
4078 [directories_first]);
4081 /* List all the files now in the table. */
4083 static void
4084 print_current_files (void)
4086 size_t i;
4088 switch (format)
4090 case one_per_line:
4091 for (i = 0; i < cwd_n_used; i++)
4093 print_file_name_and_frills (sorted_file[i], 0);
4094 putchar (eolbyte);
4096 break;
4098 case many_per_line:
4099 if (! line_length)
4100 print_with_separator (' ');
4101 else
4102 print_many_per_line ();
4103 break;
4105 case horizontal:
4106 if (! line_length)
4107 print_with_separator (' ');
4108 else
4109 print_horizontal ();
4110 break;
4112 case with_commas:
4113 print_with_separator (',');
4114 break;
4116 case long_format:
4117 for (i = 0; i < cwd_n_used; i++)
4119 set_normal_color ();
4120 print_long_format (sorted_file[i]);
4121 dired_outbyte (eolbyte);
4123 break;
4127 /* Replace the first %b with precomputed aligned month names.
4128 Note on glibc-2.7 at least, this speeds up the whole 'ls -lU'
4129 process by around 17%, compared to letting strftime() handle the %b. */
4131 static size_t
4132 align_nstrftime (char *buf, size_t size, bool recent, struct tm const *tm,
4133 timezone_t tz, int ns)
4135 char const *nfmt = (use_abformat
4136 ? abformat[recent][tm->tm_mon]
4137 : long_time_format[recent]);
4138 return nstrftime (buf, size, nfmt, tm, tz, ns);
4141 /* Return the expected number of columns in a long-format timestamp,
4142 or zero if it cannot be calculated. */
4144 static int
4145 long_time_expected_width (void)
4147 static int width = -1;
4149 if (width < 0)
4151 time_t epoch = 0;
4152 struct tm tm;
4153 char buf[TIME_STAMP_LEN_MAXIMUM + 1];
4155 /* In case you're wondering if localtime_rz can fail with an input time_t
4156 value of 0, let's just say it's very unlikely, but not inconceivable.
4157 The TZ environment variable would have to specify a time zone that
4158 is 2**31-1900 years or more ahead of UTC. This could happen only on
4159 a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
4160 However, this is not possible with Solaris 10 or glibc-2.3.5, since
4161 their implementations limit the offset to 167:59 and 24:00, resp. */
4162 if (localtime_rz (localtz, &epoch, &tm))
4164 size_t len = align_nstrftime (buf, sizeof buf, false,
4165 &tm, localtz, 0);
4166 if (len != 0)
4167 width = mbsnwidth (buf, len, MBSWIDTH_FLAGS);
4170 if (width < 0)
4171 width = 0;
4174 return width;
4177 /* Print the user or group name NAME, with numeric id ID, using a
4178 print width of WIDTH columns. */
4180 static void
4181 format_user_or_group (char const *name, uintmax_t id, int width)
4183 if (name)
4185 int name_width = mbswidth (name, MBSWIDTH_FLAGS);
4186 int width_gap = name_width < 0 ? 0 : width - name_width;
4187 int pad = MAX (0, width_gap);
4188 dired_outstring (name);
4191 dired_outbyte (' ');
4192 while (pad--);
4194 else
4195 dired_pos += printf ("%*ju ", width, id);
4198 /* Print the name or id of the user with id U, using a print width of
4199 WIDTH. */
4201 static void
4202 format_user (uid_t u, int width, bool stat_ok)
4204 format_user_or_group (! stat_ok ? "?" :
4205 (numeric_ids ? nullptr : getuser (u)), u, width);
4208 /* Likewise, for groups. */
4210 static void
4211 format_group (gid_t g, int width, bool stat_ok)
4213 format_user_or_group (! stat_ok ? "?" :
4214 (numeric_ids ? nullptr : getgroup (g)), g, width);
4217 /* Return the number of columns that format_user_or_group will print,
4218 or -1 if unknown. */
4220 static int
4221 format_user_or_group_width (char const *name, uintmax_t id)
4223 return (name
4224 ? mbswidth (name, MBSWIDTH_FLAGS)
4225 : snprintf (nullptr, 0, "%ju", id));
4228 /* Return the number of columns that format_user will print,
4229 or -1 if unknown. */
4231 static int
4232 format_user_width (uid_t u)
4234 return format_user_or_group_width (numeric_ids ? nullptr : getuser (u), u);
4237 /* Likewise, for groups. */
4239 static int
4240 format_group_width (gid_t g)
4242 return format_user_or_group_width (numeric_ids ? nullptr : getgroup (g), g);
4245 /* Return a pointer to a formatted version of F->stat.st_ino,
4246 possibly using buffer, which must be at least
4247 INT_BUFSIZE_BOUND (uintmax_t) bytes. */
4248 static char *
4249 format_inode (char buf[INT_BUFSIZE_BOUND (uintmax_t)],
4250 const struct fileinfo *f)
4252 return (f->stat_ok && f->stat.st_ino != NOT_AN_INODE_NUMBER
4253 ? umaxtostr (f->stat.st_ino, buf)
4254 : (char *) "?");
4257 /* Print information about F in long format. */
4258 static void
4259 print_long_format (const struct fileinfo *f)
4261 char modebuf[12];
4262 char buf
4263 [LONGEST_HUMAN_READABLE + 1 /* inode */
4264 + LONGEST_HUMAN_READABLE + 1 /* size in blocks */
4265 + sizeof (modebuf) - 1 + 1 /* mode string */
4266 + INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
4267 + LONGEST_HUMAN_READABLE + 2 /* major device number */
4268 + LONGEST_HUMAN_READABLE + 1 /* minor device number */
4269 + TIME_STAMP_LEN_MAXIMUM + 1 /* max length of time/date */
4271 size_t s;
4272 char *p;
4273 struct timespec when_timespec;
4274 struct tm when_local;
4275 bool btime_ok = true;
4277 /* Compute the mode string, except remove the trailing space if no
4278 file in this directory has an ACL or security context. */
4279 if (f->stat_ok)
4280 filemodestring (&f->stat, modebuf);
4281 else
4283 modebuf[0] = filetype_letter[f->filetype];
4284 memset (modebuf + 1, '?', 10);
4285 modebuf[11] = '\0';
4287 if (! any_has_acl)
4288 modebuf[10] = '\0';
4289 else if (f->acl_type == ACL_T_LSM_CONTEXT_ONLY)
4290 modebuf[10] = '.';
4291 else if (f->acl_type == ACL_T_YES)
4292 modebuf[10] = '+';
4294 switch (time_type)
4296 case time_ctime:
4297 when_timespec = get_stat_ctime (&f->stat);
4298 break;
4299 case time_mtime:
4300 when_timespec = get_stat_mtime (&f->stat);
4301 break;
4302 case time_atime:
4303 when_timespec = get_stat_atime (&f->stat);
4304 break;
4305 case time_btime:
4306 when_timespec = get_stat_btime (&f->stat);
4307 if (when_timespec.tv_sec == -1 && when_timespec.tv_nsec == -1)
4308 btime_ok = false;
4309 break;
4310 default:
4311 unreachable ();
4314 p = buf;
4316 if (print_inode)
4318 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
4319 p += sprintf (p, "%*s ", inode_number_width, format_inode (hbuf, f));
4322 if (print_block_size)
4324 char hbuf[LONGEST_HUMAN_READABLE + 1];
4325 char const *blocks =
4326 (! f->stat_ok
4327 ? "?"
4328 : human_readable (STP_NBLOCKS (&f->stat), hbuf, human_output_opts,
4329 ST_NBLOCKSIZE, output_block_size));
4330 int blocks_width = mbswidth (blocks, MBSWIDTH_FLAGS);
4331 for (int pad = blocks_width < 0 ? 0 : block_size_width - blocks_width;
4332 0 < pad; pad--)
4333 *p++ = ' ';
4334 while ((*p++ = *blocks++))
4335 continue;
4336 p[-1] = ' ';
4339 /* The last byte of the mode string is the POSIX
4340 "optional alternate access method flag". */
4342 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
4343 p += sprintf (p, "%s %*s ", modebuf, nlink_width,
4344 ! f->stat_ok ? "?" : umaxtostr (f->stat.st_nlink, hbuf));
4347 dired_indent ();
4349 if (print_owner || print_group || print_author || print_scontext)
4351 dired_outbuf (buf, p - buf);
4353 if (print_owner)
4354 format_user (f->stat.st_uid, owner_width, f->stat_ok);
4356 if (print_group)
4357 format_group (f->stat.st_gid, group_width, f->stat_ok);
4359 if (print_author)
4360 format_user (f->stat.st_author, author_width, f->stat_ok);
4362 if (print_scontext)
4363 format_user_or_group (f->scontext, 0, scontext_width);
4365 p = buf;
4368 if (f->stat_ok
4369 && (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode)))
4371 char majorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
4372 char minorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
4373 int blanks_width = (file_size_width
4374 - (major_device_number_width + 2
4375 + minor_device_number_width));
4376 p += sprintf (p, "%*s, %*s ",
4377 major_device_number_width + MAX (0, blanks_width),
4378 umaxtostr (major (f->stat.st_rdev), majorbuf),
4379 minor_device_number_width,
4380 umaxtostr (minor (f->stat.st_rdev), minorbuf));
4382 else
4384 char hbuf[LONGEST_HUMAN_READABLE + 1];
4385 char const *size =
4386 (! f->stat_ok
4387 ? "?"
4388 : human_readable (unsigned_file_size (f->stat.st_size),
4389 hbuf, file_human_output_opts, 1,
4390 file_output_block_size));
4391 int size_width = mbswidth (size, MBSWIDTH_FLAGS);
4392 for (int pad = size_width < 0 ? 0 : file_size_width - size_width;
4393 0 < pad; pad--)
4394 *p++ = ' ';
4395 while ((*p++ = *size++))
4396 continue;
4397 p[-1] = ' ';
4400 s = 0;
4401 *p = '\1';
4403 if (f->stat_ok && btime_ok
4404 && localtime_rz (localtz, &when_timespec.tv_sec, &when_local))
4406 struct timespec six_months_ago;
4407 bool recent;
4409 /* If the file appears to be in the future, update the current
4410 time, in case the file happens to have been modified since
4411 the last time we checked the clock. */
4412 if (timespec_cmp (current_time, when_timespec) < 0)
4413 gettime (&current_time);
4415 /* Consider a time to be recent if it is within the past six months.
4416 A Gregorian year has 365.2425 * 24 * 60 * 60 == 31556952 seconds
4417 on the average. Write this value as an integer constant to
4418 avoid floating point hassles. */
4419 six_months_ago.tv_sec = current_time.tv_sec - 31556952 / 2;
4420 six_months_ago.tv_nsec = current_time.tv_nsec;
4422 recent = (timespec_cmp (six_months_ago, when_timespec) < 0
4423 && timespec_cmp (when_timespec, current_time) < 0);
4425 /* We assume here that all time zones are offset from UTC by a
4426 whole number of seconds. */
4427 s = align_nstrftime (p, TIME_STAMP_LEN_MAXIMUM + 1, recent,
4428 &when_local, localtz, when_timespec.tv_nsec);
4431 if (s || !*p)
4433 p += s;
4434 *p++ = ' ';
4436 else
4438 /* The time cannot be converted using the desired format, so
4439 print it as a huge integer number of seconds. */
4440 char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
4441 p += sprintf (p, "%*s ", long_time_expected_width (),
4442 (! f->stat_ok || ! btime_ok
4443 ? "?"
4444 : timetostr (when_timespec.tv_sec, hbuf)));
4445 /* FIXME: (maybe) We discarded when_timespec.tv_nsec. */
4448 dired_outbuf (buf, p - buf);
4449 size_t w = print_name_with_quoting (f, false, &dired_obstack, p - buf);
4451 if (f->filetype == symbolic_link)
4453 if (f->linkname)
4455 dired_outstring (" -> ");
4456 print_name_with_quoting (f, true, nullptr, (p - buf) + w + 4);
4457 if (indicator_style != none)
4458 print_type_indicator (true, f->linkmode, unknown);
4461 else if (indicator_style != none)
4462 print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4465 /* Write to *BUF a quoted representation of the file name NAME, if non-null,
4466 using OPTIONS to control quoting. *BUF is set to NAME if no quoting
4467 is required. *BUF is allocated if more space required (and the original
4468 *BUF is not deallocated).
4469 Store the number of screen columns occupied by NAME's quoted
4470 representation into WIDTH, if non-null.
4471 Store into PAD whether an initial space is needed for padding.
4472 Return the number of bytes in *BUF. */
4474 static size_t
4475 quote_name_buf (char **inbuf, size_t bufsize, char *name,
4476 struct quoting_options const *options,
4477 int needs_general_quoting, size_t *width, bool *pad)
4479 char *buf = *inbuf;
4480 size_t displayed_width IF_LINT ( = 0);
4481 size_t len = 0;
4482 bool quoted;
4484 enum quoting_style qs = get_quoting_style (options);
4485 bool needs_further_quoting = qmark_funny_chars
4486 && (qs == shell_quoting_style
4487 || qs == shell_always_quoting_style
4488 || qs == literal_quoting_style);
4490 if (needs_general_quoting != 0)
4492 len = quotearg_buffer (buf, bufsize, name, -1, options);
4493 if (bufsize <= len)
4495 buf = xmalloc (len + 1);
4496 quotearg_buffer (buf, len + 1, name, -1, options);
4499 quoted = (*name != *buf) || strlen (name) != len;
4501 else if (needs_further_quoting)
4503 len = strlen (name);
4504 if (bufsize <= len)
4505 buf = xmalloc (len + 1);
4506 memcpy (buf, name, len + 1);
4508 quoted = false;
4510 else
4512 len = strlen (name);
4513 buf = name;
4514 quoted = false;
4517 if (needs_further_quoting)
4519 if (MB_CUR_MAX > 1)
4521 char const *p = buf;
4522 char const *plimit = buf + len;
4523 char *q = buf;
4524 displayed_width = 0;
4526 while (p < plimit)
4527 switch (*p)
4529 case ' ': case '!': case '"': case '#': case '%':
4530 case '&': case '\'': case '(': case ')': case '*':
4531 case '+': case ',': case '-': case '.': case '/':
4532 case '0': case '1': case '2': case '3': case '4':
4533 case '5': case '6': case '7': case '8': case '9':
4534 case ':': case ';': case '<': case '=': case '>':
4535 case '?':
4536 case 'A': case 'B': case 'C': case 'D': case 'E':
4537 case 'F': case 'G': case 'H': case 'I': case 'J':
4538 case 'K': case 'L': case 'M': case 'N': case 'O':
4539 case 'P': case 'Q': case 'R': case 'S': case 'T':
4540 case 'U': case 'V': case 'W': case 'X': case 'Y':
4541 case 'Z':
4542 case '[': case '\\': case ']': case '^': case '_':
4543 case 'a': case 'b': case 'c': case 'd': case 'e':
4544 case 'f': case 'g': case 'h': case 'i': case 'j':
4545 case 'k': case 'l': case 'm': case 'n': case 'o':
4546 case 'p': case 'q': case 'r': case 's': case 't':
4547 case 'u': case 'v': case 'w': case 'x': case 'y':
4548 case 'z': case '{': case '|': case '}': case '~':
4549 /* These characters are printable ASCII characters. */
4550 *q++ = *p++;
4551 displayed_width += 1;
4552 break;
4553 default:
4554 /* If we have a multibyte sequence, copy it until we
4555 reach its end, replacing each non-printable multibyte
4556 character with a single question mark. */
4558 mbstate_t mbstate; mbszero (&mbstate);
4561 char32_t wc;
4562 size_t bytes;
4563 int w;
4565 bytes = mbrtoc32 (&wc, p, plimit - p, &mbstate);
4567 if (bytes == (size_t) -1)
4569 /* An invalid multibyte sequence was
4570 encountered. Skip one input byte, and
4571 put a question mark. */
4572 p++;
4573 *q++ = '?';
4574 displayed_width += 1;
4575 break;
4578 if (bytes == (size_t) -2)
4580 /* An incomplete multibyte character
4581 at the end. Replace it entirely with
4582 a question mark. */
4583 p = plimit;
4584 *q++ = '?';
4585 displayed_width += 1;
4586 break;
4589 if (bytes == 0)
4590 /* A null wide character was encountered. */
4591 bytes = 1;
4593 w = c32width (wc);
4594 if (w >= 0)
4596 /* A printable multibyte character.
4597 Keep it. */
4598 for (; bytes > 0; --bytes)
4599 *q++ = *p++;
4600 displayed_width += w;
4602 else
4604 /* An nonprintable multibyte character.
4605 Replace it entirely with a question
4606 mark. */
4607 p += bytes;
4608 *q++ = '?';
4609 displayed_width += 1;
4612 while (! mbsinit (&mbstate));
4614 break;
4617 /* The buffer may have shrunk. */
4618 len = q - buf;
4620 else
4622 char *p = buf;
4623 char const *plimit = buf + len;
4625 while (p < plimit)
4627 if (! isprint (to_uchar (*p)))
4628 *p = '?';
4629 p++;
4631 displayed_width = len;
4634 else if (width != nullptr)
4636 if (MB_CUR_MAX > 1)
4638 displayed_width = mbsnwidth (buf, len, MBSWIDTH_FLAGS);
4639 displayed_width = MAX (0, displayed_width);
4641 else
4643 char const *p = buf;
4644 char const *plimit = buf + len;
4646 displayed_width = 0;
4647 while (p < plimit)
4649 if (isprint (to_uchar (*p)))
4650 displayed_width++;
4651 p++;
4656 /* Set padding to better align quoted items,
4657 and also give a visual indication that quotes are
4658 not actually part of the name. */
4659 *pad = (align_variable_outer_quotes && cwd_some_quoted && ! quoted);
4661 if (width != nullptr)
4662 *width = displayed_width;
4664 *inbuf = buf;
4666 return len;
4669 static size_t
4670 quote_name_width (char const *name, struct quoting_options const *options,
4671 int needs_general_quoting)
4673 char smallbuf[BUFSIZ];
4674 char *buf = smallbuf;
4675 size_t width;
4676 bool pad;
4678 quote_name_buf (&buf, sizeof smallbuf, (char *) name, options,
4679 needs_general_quoting, &width, &pad);
4681 if (buf != smallbuf && buf != name)
4682 free (buf);
4684 width += pad;
4686 return width;
4689 /* %XX escape any input out of range as defined in RFC3986,
4690 and also if PATH, convert all path separators to '/'. */
4691 static char *
4692 file_escape (char const *str, bool path)
4694 char *esc = xnmalloc (3, strlen (str) + 1);
4695 char *p = esc;
4696 while (*str)
4698 if (path && ISSLASH (*str))
4700 *p++ = '/';
4701 str++;
4703 else if (RFC3986[to_uchar (*str)])
4704 *p++ = *str++;
4705 else
4706 p += sprintf (p, "%%%02x", to_uchar (*str++));
4708 *p = '\0';
4709 return esc;
4712 static size_t
4713 quote_name (char const *name, struct quoting_options const *options,
4714 int needs_general_quoting, const struct bin_str *color,
4715 bool allow_pad, struct obstack *stack, char const *absolute_name)
4717 char smallbuf[BUFSIZ];
4718 char *buf = smallbuf;
4719 size_t len;
4720 bool pad;
4722 len = quote_name_buf (&buf, sizeof smallbuf, (char *) name, options,
4723 needs_general_quoting, nullptr, &pad);
4725 if (pad && allow_pad)
4726 dired_outbyte (' ');
4728 if (color)
4729 print_color_indicator (color);
4731 /* If we're padding, then don't include the outer quotes in
4732 the --hyperlink, to improve the alignment of those links. */
4733 bool skip_quotes = false;
4735 if (absolute_name)
4737 if (align_variable_outer_quotes && cwd_some_quoted && ! pad)
4739 skip_quotes = true;
4740 putchar (*buf);
4742 char *h = file_escape (hostname, /* path= */ false);
4743 char *n = file_escape (absolute_name, /* path= */ true);
4744 /* TODO: It would be good to be able to define parameters
4745 to give hints to the terminal as how best to render the URI.
4746 For example since ls is outputting a dense block of URIs
4747 it would be best to not underline by default, and only
4748 do so upon hover etc. */
4749 printf ("\033]8;;file://%s%s%s\a", h, *n == '/' ? "" : "/", n);
4750 free (h);
4751 free (n);
4754 if (stack)
4755 push_current_dired_pos (stack);
4757 fwrite (buf + skip_quotes, 1, len - (skip_quotes * 2), stdout);
4759 dired_pos += len;
4761 if (stack)
4762 push_current_dired_pos (stack);
4764 if (absolute_name)
4766 fputs ("\033]8;;\a", stdout);
4767 if (skip_quotes)
4768 putchar (*(buf + len - 1));
4771 if (buf != smallbuf && buf != name)
4772 free (buf);
4774 return len + pad;
4777 static size_t
4778 print_name_with_quoting (const struct fileinfo *f,
4779 bool symlink_target,
4780 struct obstack *stack,
4781 size_t start_col)
4783 char const *name = symlink_target ? f->linkname : f->name;
4785 const struct bin_str *color
4786 = print_with_color ? get_color_indicator (f, symlink_target) : nullptr;
4788 bool used_color_this_time = (print_with_color
4789 && (color || is_colored (C_NORM)));
4791 size_t len = quote_name (name, filename_quoting_options, f->quoted,
4792 color, !symlink_target, stack, f->absolute_name);
4794 process_signals ();
4795 if (used_color_this_time)
4797 prep_non_filename_text ();
4799 /* We use the byte length rather than display width here as
4800 an optimization to avoid accurately calculating the width,
4801 because we only output the clear to EOL sequence if the name
4802 _might_ wrap to the next line. This may output a sequence
4803 unnecessarily in multi-byte locales for example,
4804 but in that case it's inconsequential to the output. */
4805 if (line_length
4806 && (start_col / line_length != (start_col + len - 1) / line_length))
4807 put_indicator (&color_indicator[C_CLR_TO_EOL]);
4810 return len;
4813 static void
4814 prep_non_filename_text (void)
4816 if (color_indicator[C_END].string != nullptr)
4817 put_indicator (&color_indicator[C_END]);
4818 else
4820 put_indicator (&color_indicator[C_LEFT]);
4821 put_indicator (&color_indicator[C_RESET]);
4822 put_indicator (&color_indicator[C_RIGHT]);
4826 /* Print the file name of 'f' with appropriate quoting.
4827 Also print file size, inode number, and filetype indicator character,
4828 as requested by switches. */
4830 static size_t
4831 print_file_name_and_frills (const struct fileinfo *f, size_t start_col)
4833 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
4835 set_normal_color ();
4837 if (print_inode)
4838 printf ("%*s ", format == with_commas ? 0 : inode_number_width,
4839 format_inode (buf, f));
4841 if (print_block_size)
4842 printf ("%*s ", format == with_commas ? 0 : block_size_width,
4843 ! f->stat_ok ? "?"
4844 : human_readable (STP_NBLOCKS (&f->stat), buf, human_output_opts,
4845 ST_NBLOCKSIZE, output_block_size));
4847 if (print_scontext)
4848 printf ("%*s ", format == with_commas ? 0 : scontext_width, f->scontext);
4850 size_t width = print_name_with_quoting (f, false, nullptr, start_col);
4852 if (indicator_style != none)
4853 width += print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4855 return width;
4858 /* Given these arguments describing a file, return the single-byte
4859 type indicator, or 0. */
4860 static char
4861 get_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
4863 char c;
4865 if (stat_ok ? S_ISREG (mode) : type == normal)
4867 if (stat_ok && indicator_style == classify && (mode & S_IXUGO))
4868 c = '*';
4869 else
4870 c = 0;
4872 else
4874 if (stat_ok ? S_ISDIR (mode) : type == directory || type == arg_directory)
4875 c = '/';
4876 else if (indicator_style == slash)
4877 c = 0;
4878 else if (stat_ok ? S_ISLNK (mode) : type == symbolic_link)
4879 c = '@';
4880 else if (stat_ok ? S_ISFIFO (mode) : type == fifo)
4881 c = '|';
4882 else if (stat_ok ? S_ISSOCK (mode) : type == sock)
4883 c = '=';
4884 else if (stat_ok && S_ISDOOR (mode))
4885 c = '>';
4886 else
4887 c = 0;
4889 return c;
4892 static bool
4893 print_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
4895 char c = get_type_indicator (stat_ok, mode, type);
4896 if (c)
4897 dired_outbyte (c);
4898 return !!c;
4901 /* Returns if color sequence was printed. */
4902 static bool
4903 print_color_indicator (const struct bin_str *ind)
4905 if (ind)
4907 /* Need to reset so not dealing with attribute combinations */
4908 if (is_colored (C_NORM))
4909 restore_default_color ();
4910 put_indicator (&color_indicator[C_LEFT]);
4911 put_indicator (ind);
4912 put_indicator (&color_indicator[C_RIGHT]);
4915 return ind != nullptr;
4918 /* Returns color indicator or nullptr if none. */
4919 ATTRIBUTE_PURE
4920 static const struct bin_str*
4921 get_color_indicator (const struct fileinfo *f, bool symlink_target)
4923 enum indicator_no type;
4924 struct color_ext_type *ext; /* Color extension */
4925 size_t len; /* Length of name */
4927 char const *name;
4928 mode_t mode;
4929 int linkok;
4930 if (symlink_target)
4932 name = f->linkname;
4933 mode = f->linkmode;
4934 linkok = f->linkok ? 0 : -1;
4936 else
4938 name = f->name;
4939 mode = file_or_link_mode (f);
4940 linkok = f->linkok;
4943 /* Is this a nonexistent file? If so, linkok == -1. */
4945 if (linkok == -1 && is_colored (C_MISSING))
4946 type = C_MISSING;
4947 else if (!f->stat_ok)
4949 static enum indicator_no const filetype_indicator[] =
4951 C_ORPHAN, C_FIFO, C_CHR, C_DIR, C_BLK, C_FILE,
4952 C_LINK, C_SOCK, C_FILE, C_DIR
4954 static_assert (ARRAY_CARDINALITY (filetype_indicator)
4955 == filetype_cardinality);
4956 type = filetype_indicator[f->filetype];
4958 else
4960 if (S_ISREG (mode))
4962 type = C_FILE;
4964 if ((mode & S_ISUID) != 0 && is_colored (C_SETUID))
4965 type = C_SETUID;
4966 else if ((mode & S_ISGID) != 0 && is_colored (C_SETGID))
4967 type = C_SETGID;
4968 else if (f->has_capability)
4969 type = C_CAP;
4970 else if ((mode & S_IXUGO) != 0 && is_colored (C_EXEC))
4971 type = C_EXEC;
4972 else if ((1 < f->stat.st_nlink) && is_colored (C_MULTIHARDLINK))
4973 type = C_MULTIHARDLINK;
4975 else if (S_ISDIR (mode))
4977 type = C_DIR;
4979 if ((mode & S_ISVTX) && (mode & S_IWOTH)
4980 && is_colored (C_STICKY_OTHER_WRITABLE))
4981 type = C_STICKY_OTHER_WRITABLE;
4982 else if ((mode & S_IWOTH) != 0 && is_colored (C_OTHER_WRITABLE))
4983 type = C_OTHER_WRITABLE;
4984 else if ((mode & S_ISVTX) != 0 && is_colored (C_STICKY))
4985 type = C_STICKY;
4987 else if (S_ISLNK (mode))
4988 type = C_LINK;
4989 else if (S_ISFIFO (mode))
4990 type = C_FIFO;
4991 else if (S_ISSOCK (mode))
4992 type = C_SOCK;
4993 else if (S_ISBLK (mode))
4994 type = C_BLK;
4995 else if (S_ISCHR (mode))
4996 type = C_CHR;
4997 else if (S_ISDOOR (mode))
4998 type = C_DOOR;
4999 else
5001 /* Classify a file of some other type as C_ORPHAN. */
5002 type = C_ORPHAN;
5006 /* Check the file's suffix only if still classified as C_FILE. */
5007 ext = nullptr;
5008 if (type == C_FILE)
5010 /* Test if NAME has a recognized suffix. */
5012 len = strlen (name);
5013 name += len; /* Pointer to final \0. */
5014 for (ext = color_ext_list; ext != nullptr; ext = ext->next)
5016 if (ext->ext.len <= len)
5018 if (ext->exact_match)
5020 if (STREQ_LEN (name - ext->ext.len, ext->ext.string,
5021 ext->ext.len))
5022 break;
5024 else
5026 if (c_strncasecmp (name - ext->ext.len, ext->ext.string,
5027 ext->ext.len) == 0)
5028 break;
5034 /* Adjust the color for orphaned symlinks. */
5035 if (type == C_LINK && !linkok)
5037 if (color_symlink_as_referent || is_colored (C_ORPHAN))
5038 type = C_ORPHAN;
5041 const struct bin_str *const s
5042 = ext ? &(ext->seq) : &color_indicator[type];
5044 return s->string ? s : nullptr;
5047 /* Output a color indicator (which may contain nulls). */
5048 static void
5049 put_indicator (const struct bin_str *ind)
5051 if (! used_color)
5053 used_color = true;
5055 /* If the standard output is a controlling terminal, watch out
5056 for signals, so that the colors can be restored to the
5057 default state if "ls" is suspended or interrupted. */
5059 if (0 <= tcgetpgrp (STDOUT_FILENO))
5060 signal_init ();
5062 prep_non_filename_text ();
5065 fwrite (ind->string, ind->len, 1, stdout);
5068 static size_t
5069 length_of_file_name_and_frills (const struct fileinfo *f)
5071 size_t len = 0;
5072 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
5074 if (print_inode)
5075 len += 1 + (format == with_commas
5076 ? strlen (umaxtostr (f->stat.st_ino, buf))
5077 : inode_number_width);
5079 if (print_block_size)
5080 len += 1 + (format == with_commas
5081 ? strlen (! f->stat_ok ? "?"
5082 : human_readable (STP_NBLOCKS (&f->stat), buf,
5083 human_output_opts, ST_NBLOCKSIZE,
5084 output_block_size))
5085 : block_size_width);
5087 if (print_scontext)
5088 len += 1 + (format == with_commas ? strlen (f->scontext) : scontext_width);
5090 len += fileinfo_name_width (f);
5092 if (indicator_style != none)
5094 char c = get_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
5095 len += (c != 0);
5098 return len;
5101 static void
5102 print_many_per_line (void)
5104 size_t row; /* Current row. */
5105 size_t cols = calculate_columns (true);
5106 struct column_info const *line_fmt = &column_info[cols - 1];
5108 /* Calculate the number of rows that will be in each column except possibly
5109 for a short column on the right. */
5110 size_t rows = cwd_n_used / cols + (cwd_n_used % cols != 0);
5112 for (row = 0; row < rows; row++)
5114 size_t col = 0;
5115 size_t filesno = row;
5116 size_t pos = 0;
5118 /* Print the next row. */
5119 while (true)
5121 struct fileinfo const *f = sorted_file[filesno];
5122 size_t name_length = length_of_file_name_and_frills (f);
5123 size_t max_name_length = line_fmt->col_arr[col++];
5124 print_file_name_and_frills (f, pos);
5126 filesno += rows;
5127 if (filesno >= cwd_n_used)
5128 break;
5130 indent (pos + name_length, pos + max_name_length);
5131 pos += max_name_length;
5133 putchar (eolbyte);
5137 static void
5138 print_horizontal (void)
5140 size_t filesno;
5141 size_t pos = 0;
5142 size_t cols = calculate_columns (false);
5143 struct column_info const *line_fmt = &column_info[cols - 1];
5144 struct fileinfo const *f = sorted_file[0];
5145 size_t name_length = length_of_file_name_and_frills (f);
5146 size_t max_name_length = line_fmt->col_arr[0];
5148 /* Print first entry. */
5149 print_file_name_and_frills (f, 0);
5151 /* Now the rest. */
5152 for (filesno = 1; filesno < cwd_n_used; ++filesno)
5154 size_t col = filesno % cols;
5156 if (col == 0)
5158 putchar (eolbyte);
5159 pos = 0;
5161 else
5163 indent (pos + name_length, pos + max_name_length);
5164 pos += max_name_length;
5167 f = sorted_file[filesno];
5168 print_file_name_and_frills (f, pos);
5170 name_length = length_of_file_name_and_frills (f);
5171 max_name_length = line_fmt->col_arr[col];
5173 putchar (eolbyte);
5176 /* Output name + SEP + ' '. */
5178 static void
5179 print_with_separator (char sep)
5181 size_t filesno;
5182 size_t pos = 0;
5184 for (filesno = 0; filesno < cwd_n_used; filesno++)
5186 struct fileinfo const *f = sorted_file[filesno];
5187 size_t len = line_length ? length_of_file_name_and_frills (f) : 0;
5189 if (filesno != 0)
5191 char separator;
5193 if (! line_length
5194 || ((pos + len + 2 < line_length)
5195 && (pos <= SIZE_MAX - len - 2)))
5197 pos += 2;
5198 separator = ' ';
5200 else
5202 pos = 0;
5203 separator = eolbyte;
5206 putchar (sep);
5207 putchar (separator);
5210 print_file_name_and_frills (f, pos);
5211 pos += len;
5213 putchar (eolbyte);
5216 /* Assuming cursor is at position FROM, indent up to position TO.
5217 Use a TAB character instead of two or more spaces whenever possible. */
5219 static void
5220 indent (size_t from, size_t to)
5222 while (from < to)
5224 if (tabsize != 0 && to / tabsize > (from + 1) / tabsize)
5226 putchar ('\t');
5227 from += tabsize - from % tabsize;
5229 else
5231 putchar (' ');
5232 from++;
5237 /* Put DIRNAME/NAME into DEST, handling '.' and '/' properly. */
5238 /* FIXME: maybe remove this function someday. See about using a
5239 non-malloc'ing version of file_name_concat. */
5241 static void
5242 attach (char *dest, char const *dirname, char const *name)
5244 char const *dirnamep = dirname;
5246 /* Copy dirname if it is not ".". */
5247 if (dirname[0] != '.' || dirname[1] != 0)
5249 while (*dirnamep)
5250 *dest++ = *dirnamep++;
5251 /* Add '/' if 'dirname' doesn't already end with it. */
5252 if (dirnamep > dirname && dirnamep[-1] != '/')
5253 *dest++ = '/';
5255 while (*name)
5256 *dest++ = *name++;
5257 *dest = 0;
5260 /* Allocate enough column info suitable for the current number of
5261 files and display columns, and initialize the info to represent the
5262 narrowest possible columns. */
5264 static void
5265 init_column_info (size_t max_cols)
5267 size_t i;
5269 /* Currently allocated columns in column_info. */
5270 static size_t column_info_alloc;
5272 if (column_info_alloc < max_cols)
5274 size_t new_column_info_alloc;
5275 size_t *p;
5277 if (!max_idx || max_cols < max_idx / 2)
5279 /* The number of columns is far less than the display width
5280 allows. Grow the allocation, but only so that it's
5281 double the current requirements. If the display is
5282 extremely wide, this avoids allocating a lot of memory
5283 that is never needed. */
5284 column_info = xnrealloc (column_info, max_cols,
5285 2 * sizeof *column_info);
5286 new_column_info_alloc = 2 * max_cols;
5288 else
5290 column_info = xnrealloc (column_info, max_idx, sizeof *column_info);
5291 new_column_info_alloc = max_idx;
5294 /* Allocate the new size_t objects by computing the triangle
5295 formula n * (n + 1) / 2, except that we don't need to
5296 allocate the part of the triangle that we've already
5297 allocated. Check for address arithmetic overflow. */
5299 size_t column_info_growth = new_column_info_alloc - column_info_alloc;
5300 size_t s = column_info_alloc + 1 + new_column_info_alloc;
5301 size_t t = s * column_info_growth;
5302 if (s < new_column_info_alloc || t / column_info_growth != s)
5303 xalloc_die ();
5304 p = xnmalloc (t / 2, sizeof *p);
5307 /* Grow the triangle by parceling out the cells just allocated. */
5308 for (i = column_info_alloc; i < new_column_info_alloc; i++)
5310 column_info[i].col_arr = p;
5311 p += i + 1;
5314 column_info_alloc = new_column_info_alloc;
5317 for (i = 0; i < max_cols; ++i)
5319 size_t j;
5321 column_info[i].valid_len = true;
5322 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
5323 for (j = 0; j <= i; ++j)
5324 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
5328 /* Calculate the number of columns needed to represent the current set
5329 of files in the current display width. */
5331 static size_t
5332 calculate_columns (bool by_columns)
5334 size_t filesno; /* Index into cwd_file. */
5335 size_t cols; /* Number of files across. */
5337 /* Normally the maximum number of columns is determined by the
5338 screen width. But if few files are available this might limit it
5339 as well. */
5340 size_t max_cols = 0 < max_idx && max_idx < cwd_n_used ? max_idx : cwd_n_used;
5342 init_column_info (max_cols);
5344 /* Compute the maximum number of possible columns. */
5345 for (filesno = 0; filesno < cwd_n_used; ++filesno)
5347 struct fileinfo const *f = sorted_file[filesno];
5348 size_t name_length = length_of_file_name_and_frills (f);
5350 for (size_t i = 0; i < max_cols; ++i)
5352 if (column_info[i].valid_len)
5354 size_t idx = (by_columns
5355 ? filesno / ((cwd_n_used + i) / (i + 1))
5356 : filesno % (i + 1));
5357 size_t real_length = name_length + (idx == i ? 0 : 2);
5359 if (column_info[i].col_arr[idx] < real_length)
5361 column_info[i].line_len += (real_length
5362 - column_info[i].col_arr[idx]);
5363 column_info[i].col_arr[idx] = real_length;
5364 column_info[i].valid_len = (column_info[i].line_len
5365 < line_length);
5371 /* Find maximum allowed columns. */
5372 for (cols = max_cols; 1 < cols; --cols)
5374 if (column_info[cols - 1].valid_len)
5375 break;
5378 return cols;
5381 void
5382 usage (int status)
5384 if (status != EXIT_SUCCESS)
5385 emit_try_help ();
5386 else
5388 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
5389 fputs (_("\
5390 List information about the FILEs (the current directory by default).\n\
5391 Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.\n\
5392 "), stdout);
5394 emit_mandatory_arg_note ();
5396 fputs (_("\
5397 -a, --all do not ignore entries starting with .\n\
5398 -A, --almost-all do not list implied . and ..\n\
5399 --author with -l, print the author of each file\n\
5400 -b, --escape print C-style escapes for nongraphic characters\n\
5401 "), stdout);
5402 fputs (_("\
5403 --block-size=SIZE with -l, scale sizes by SIZE when printing them;\n\
5404 e.g., '--block-size=M'; see SIZE format below\n\
5406 "), stdout);
5407 fputs (_("\
5408 -B, --ignore-backups do not list implied entries ending with ~\n\
5409 "), stdout);
5410 fputs (_("\
5411 -c with -lt: sort by, and show, ctime (time of last\n\
5412 change of file status information);\n\
5413 with -l: show ctime and sort by name;\n\
5414 otherwise: sort by ctime, newest first\n\
5416 "), stdout);
5417 fputs (_("\
5418 -C list entries by columns\n\
5419 --color[=WHEN] color the output WHEN; more info below\n\
5420 -d, --directory list directories themselves, not their contents\n\
5421 -D, --dired generate output designed for Emacs' dired mode\n\
5422 "), stdout);
5423 fputs (_("\
5424 -f same as -a -U\n\
5425 -F, --classify[=WHEN] append indicator (one of */=>@|) to entries WHEN\n\
5426 --file-type likewise, except do not append '*'\n\
5427 "), stdout);
5428 fputs (_("\
5429 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
5430 single-column -1, verbose -l, vertical -C\n\
5432 "), stdout);
5433 fputs (_("\
5434 --full-time like -l --time-style=full-iso\n\
5435 "), stdout);
5436 fputs (_("\
5437 -g like -l, but do not list owner\n\
5438 "), stdout);
5439 fputs (_("\
5440 --group-directories-first\n\
5441 group directories before files\n\
5442 "), stdout);
5443 fputs (_("\
5444 -G, --no-group in a long listing, don't print group names\n\
5445 "), stdout);
5446 fputs (_("\
5447 -h, --human-readable with -l and -s, print sizes like 1K 234M 2G etc.\n\
5448 --si likewise, but use powers of 1000 not 1024\n\
5449 "), stdout);
5450 fputs (_("\
5451 -H, --dereference-command-line\n\
5452 follow symbolic links listed on the command line\n\
5453 "), stdout);
5454 fputs (_("\
5455 --dereference-command-line-symlink-to-dir\n\
5456 follow each command line symbolic link\n\
5457 that points to a directory\n\
5459 "), stdout);
5460 fputs (_("\
5461 --hide=PATTERN do not list implied entries matching shell PATTERN\
5463 (overridden by -a or -A)\n\
5465 "), stdout);
5466 fputs (_("\
5467 --hyperlink[=WHEN] hyperlink file names WHEN\n\
5468 "), stdout);
5469 fputs (_("\
5470 --indicator-style=WORD\n\
5471 append indicator with style WORD to entry names:\n\
5472 none (default), slash (-p),\n\
5473 file-type (--file-type), classify (-F)\n\
5475 "), stdout);
5476 fputs (_("\
5477 -i, --inode print the index number of each file\n\
5478 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\
5480 "), stdout);
5481 fputs (_("\
5482 -k, --kibibytes default to 1024-byte blocks for file system usage;\
5484 used only with -s and per directory totals\n\
5486 "), stdout);
5487 fputs (_("\
5488 -l use a long listing format\n\
5489 "), stdout);
5490 fputs (_("\
5491 -L, --dereference when showing file information for a symbolic\n\
5492 link, show information for the file the link\n\
5493 references rather than for the link itself\n\
5495 "), stdout);
5496 fputs (_("\
5497 -m fill width with a comma separated list of entries\
5499 "), stdout);
5500 fputs (_("\
5501 -n, --numeric-uid-gid like -l, but list numeric user and group IDs\n\
5502 -N, --literal print entry names without quoting\n\
5503 -o like -l, but do not list group information\n\
5504 -p, --indicator-style=slash\n\
5505 append / indicator to directories\n\
5506 "), stdout);
5507 fputs (_("\
5508 -q, --hide-control-chars print ? instead of nongraphic characters\n\
5509 "), stdout);
5510 fputs (_("\
5511 --show-control-chars show nongraphic characters as-is (the default,\n\
5512 unless program is 'ls' and output is a terminal)\
5515 "), stdout);
5516 fputs (_("\
5517 -Q, --quote-name enclose entry names in double quotes\n\
5518 "), stdout);
5519 fputs (_("\
5520 --quoting-style=WORD use quoting style WORD for entry names:\n\
5521 literal, locale, shell, shell-always,\n\
5522 shell-escape, shell-escape-always, c, escape\n\
5523 (overrides QUOTING_STYLE environment variable)\n\
5525 "), stdout);
5526 fputs (_("\
5527 -r, --reverse reverse order while sorting\n\
5528 -R, --recursive list subdirectories recursively\n\
5529 -s, --size print the allocated size of each file, in blocks\n\
5530 "), stdout);
5531 fputs (_("\
5532 -S sort by file size, largest first\n\
5533 "), stdout);
5534 fputs (_("\
5535 --sort=WORD change default 'name' sort to WORD:\n\
5536 none (-U), size (-S), time (-t),\n\
5537 version (-v), extension (-X), name, width\n\
5539 "), stdout);
5540 fputs (_("\
5541 --time=WORD select which timestamp used to display or sort;\n\
5542 access time (-u): atime, access, use;\n\
5543 metadata change time (-c): ctime, status;\n\
5544 modified time (default): mtime, modification;\n\
5545 birth time: birth, creation;\n\
5546 with -l, WORD determines which time to show;\n\
5547 with --sort=time, sort by WORD (newest first)\n\
5549 "), stdout);
5550 fputs (_("\
5551 --time-style=TIME_STYLE\n\
5552 time/date format with -l; see TIME_STYLE below\n\
5553 "), stdout);
5554 fputs (_("\
5555 -t sort by time, newest first; see --time\n\
5556 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
5557 "), stdout);
5558 fputs (_("\
5559 -u with -lt: sort by, and show, access time;\n\
5560 with -l: show access time and sort by name;\n\
5561 otherwise: sort by access time, newest first\n\
5563 "), stdout);
5564 fputs (_("\
5565 -U do not sort directory entries\n\
5566 "), stdout);
5567 fputs (_("\
5568 -v natural sort of (version) numbers within text\n\
5569 "), stdout);
5570 fputs (_("\
5571 -w, --width=COLS set output width to COLS. 0 means no limit\n\
5572 -x list entries by lines instead of by columns\n\
5573 -X sort alphabetically by entry extension\n\
5574 -Z, --context print any security context of each file\n\
5575 --zero end each output line with NUL, not newline\n\
5576 -1 list one file per line\n\
5577 "), stdout);
5578 fputs (HELP_OPTION_DESCRIPTION, stdout);
5579 fputs (VERSION_OPTION_DESCRIPTION, stdout);
5580 emit_size_note ();
5581 fputs (_("\
5583 The TIME_STYLE argument can be full-iso, long-iso, iso, locale, or +FORMAT.\n\
5584 FORMAT is interpreted like in date(1). If FORMAT is FORMAT1<newline>FORMAT2,\n\
5585 then FORMAT1 applies to non-recent files and FORMAT2 to recent files.\n\
5586 TIME_STYLE prefixed with 'posix-' takes effect only outside the POSIX locale.\n\
5587 Also the TIME_STYLE environment variable sets the default style to use.\n\
5588 "), stdout);
5589 fputs (_("\
5591 The WHEN argument defaults to 'always' and can also be 'auto' or 'never'.\n\
5592 "), stdout);
5593 fputs (_("\
5595 Using color to distinguish file types is disabled both by default and\n\
5596 with --color=never. With --color=auto, ls emits color codes only when\n\
5597 standard output is connected to a terminal. The LS_COLORS environment\n\
5598 variable can change the settings. Use the dircolors(1) command to set it.\n\
5599 "), stdout);
5600 fputs (_("\
5602 Exit status:\n\
5603 0 if OK,\n\
5604 1 if minor problems (e.g., cannot access subdirectory),\n\
5605 2 if serious trouble (e.g., cannot access command-line argument).\n\
5606 "), stdout);
5607 emit_ancillary_info (PROGRAM_NAME);
5609 exit (status);