wc: increase I/O size from 16 KiB to 256KiB
[coreutils.git] / src / ls.c
blob916d7c0508cbba2342f18f195f830db82cd0163e
1 /* 'dir', 'vdir' and 'ls' directory listing programs for GNU.
2 Copyright (C) 1985-2024 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 /* If ls_mode is LS_MULTI_COL,
18 the multi-column format is the default regardless
19 of the type of output device.
20 This is for the 'dir' program.
22 If ls_mode is LS_LONG_FORMAT,
23 the long format is the default regardless of the
24 type of output device.
25 This is for the 'vdir' program.
27 If ls_mode is LS_LS,
28 the output format depends on whether the output
29 device is a terminal.
30 This is for the 'ls' program. */
32 /* Written by Richard Stallman and David MacKenzie. */
34 /* Color support by Peter Anvin <Peter.Anvin@linux.org> and Dennis
35 Flaherty <dennisf@denix.elk.miles.com> based on original patches by
36 Greg Lee <lee@uhunix.uhcc.hawaii.edu>. */
38 #include <config.h>
39 #include <ctype.h>
40 #include <sys/types.h>
42 #include <termios.h>
43 #if HAVE_STROPTS_H
44 # include <stropts.h>
45 #endif
46 #include <sys/ioctl.h>
48 #ifdef WINSIZE_IN_PTEM
49 # include <sys/stream.h>
50 # include <sys/ptem.h>
51 #endif
53 #include <stdio.h>
54 #include <setjmp.h>
55 #include <pwd.h>
56 #include <getopt.h>
57 #include <signal.h>
58 #include <selinux/selinux.h>
59 #include <uchar.h>
61 #if HAVE_LANGINFO_CODESET
62 # include <langinfo.h>
63 #endif
65 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
66 present. */
67 #ifndef SA_NOCLDSTOP
68 # define SA_NOCLDSTOP 0
69 # define sigprocmask(How, Set, Oset) /* empty */
70 # define sigset_t int
71 # if ! HAVE_SIGINTERRUPT
72 # define siginterrupt(sig, flag) /* empty */
73 # endif
74 #endif
76 /* NonStop circa 2011 lacks both SA_RESTART and siginterrupt, so don't
77 restart syscalls after a signal handler fires. This may cause
78 colors to get messed up on the screen if 'ls' is interrupted, but
79 that's the best we can do on such a platform. */
80 #ifndef SA_RESTART
81 # define SA_RESTART 0
82 #endif
84 #include "system.h"
85 #include <fnmatch.h>
87 #include "acl.h"
88 #include "argmatch.h"
89 #include "assure.h"
90 #include "c-strcase.h"
91 #include "dev-ino.h"
92 #include "filenamecat.h"
93 #include "hard-locale.h"
94 #include "hash.h"
95 #include "human.h"
96 #include "filemode.h"
97 #include "filevercmp.h"
98 #include "idcache.h"
99 #include "ls.h"
100 #include "mbswidth.h"
101 #include "mpsort.h"
102 #include "obstack.h"
103 #include "quote.h"
104 #include "smack.h"
105 #include "stat-size.h"
106 #include "stat-time.h"
107 #include "strftime.h"
108 #include "xdectoint.h"
109 #include "xstrtol.h"
110 #include "xstrtol-error.h"
111 #include "areadlink.h"
112 #include "dircolors.h"
113 #include "xgethostname.h"
114 #include "c-ctype.h"
115 #include "canonicalize.h"
116 #include "statx.h"
118 /* Include <sys/capability.h> last to avoid a clash of <sys/types.h>
119 include guards with some premature versions of libcap.
120 For more details, see <https://bugzilla.redhat.com/483548>. */
121 #ifdef HAVE_CAP
122 # include <sys/capability.h>
123 #endif
125 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
126 : (ls_mode == LS_MULTI_COL \
127 ? "dir" : "vdir"))
129 #define AUTHORS \
130 proper_name ("Richard M. Stallman"), \
131 proper_name ("David MacKenzie")
133 #define obstack_chunk_alloc malloc
134 #define obstack_chunk_free free
136 /* Unix-based readdir implementations have historically returned a dirent.d_ino
137 value that is sometimes not equal to the stat-obtained st_ino value for
138 that same entry. This error occurs for a readdir entry that refers
139 to a mount point. readdir's error is to return the inode number of
140 the underlying directory -- one that typically cannot be stat'ed, as
141 long as a file system is mounted on that directory. RELIABLE_D_INO
142 encapsulates whether we can use the more efficient approach of relying
143 on readdir-supplied d_ino values, or whether we must incur the cost of
144 calling stat or lstat to obtain each guaranteed-valid inode number. */
146 #ifndef READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
147 # define READDIR_LIES_ABOUT_MOUNTPOINT_D_INO 1
148 #endif
150 #if READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
151 # define RELIABLE_D_INO(dp) NOT_AN_INODE_NUMBER
152 #else
153 # define RELIABLE_D_INO(dp) D_INO (dp)
154 #endif
156 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
157 # define st_author st_uid
158 #endif
160 enum filetype
162 unknown,
163 fifo,
164 chardev,
165 directory,
166 blockdev,
167 normal,
168 symbolic_link,
169 sock,
170 whiteout,
171 arg_directory
174 /* Display letters and indicators for each filetype.
175 Keep these in sync with enum filetype. */
176 static char const filetype_letter[] = "?pcdb-lswd";
178 /* Ensure that filetype and filetype_letter have the same
179 number of elements. */
180 static_assert (sizeof filetype_letter - 1 == arg_directory + 1);
182 #define FILETYPE_INDICATORS \
184 C_ORPHAN, C_FIFO, C_CHR, C_DIR, C_BLK, C_FILE, \
185 C_LINK, C_SOCK, C_FILE, C_DIR \
188 enum acl_type
190 ACL_T_NONE,
191 ACL_T_LSM_CONTEXT_ONLY,
192 ACL_T_YES
195 struct fileinfo
197 /* The file name. */
198 char *name;
200 /* For symbolic link, name of the file linked to, otherwise zero. */
201 char *linkname;
203 /* For terminal hyperlinks. */
204 char *absolute_name;
206 struct stat stat;
208 enum filetype filetype;
210 /* For symbolic link and long listing, st_mode of file linked to, otherwise
211 zero. */
212 mode_t linkmode;
214 /* security context. */
215 char *scontext;
217 bool stat_ok;
219 /* For symbolic link and color printing, true if linked-to file
220 exists, otherwise false. */
221 bool linkok;
223 /* For long listings, true if the file has an access control list,
224 or a security context. */
225 enum acl_type acl_type;
227 /* For color listings, true if a regular file has capability info. */
228 bool has_capability;
230 /* Whether file name needs quoting. tri-state with -1 == unknown. */
231 int quoted;
233 /* Cached screen width (including quoting). */
234 size_t width;
237 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
239 /* Null is a valid character in a color indicator (think about Epson
240 printers, for example) so we have to use a length/buffer string
241 type. */
243 struct bin_str
245 size_t len; /* Number of bytes */
246 char const *string; /* Pointer to the same */
249 #if ! HAVE_TCGETPGRP
250 # define tcgetpgrp(Fd) 0
251 #endif
253 static size_t quote_name (char const *name,
254 struct quoting_options const *options,
255 int needs_general_quoting,
256 const struct bin_str *color,
257 bool allow_pad, struct obstack *stack,
258 char const *absolute_name);
259 static size_t quote_name_buf (char **inbuf, size_t bufsize, char *name,
260 struct quoting_options const *options,
261 int needs_general_quoting, size_t *width,
262 bool *pad);
263 static int decode_switches (int argc, char **argv);
264 static bool file_ignored (char const *name);
265 static uintmax_t gobble_file (char const *name, enum filetype type,
266 ino_t inode, bool command_line_arg,
267 char const *dirname);
268 static const struct bin_str * get_color_indicator (const struct fileinfo *f,
269 bool symlink_target);
270 static bool print_color_indicator (const struct bin_str *ind);
271 static void put_indicator (const struct bin_str *ind);
272 static void add_ignore_pattern (char const *pattern);
273 static void attach (char *dest, char const *dirname, char const *name);
274 static void clear_files (void);
275 static void extract_dirs_from_files (char const *dirname,
276 bool command_line_arg);
277 static void get_link_name (char const *filename, struct fileinfo *f,
278 bool command_line_arg);
279 static void indent (size_t from, size_t to);
280 static size_t calculate_columns (bool by_columns);
281 static void print_current_files (void);
282 static void print_dir (char const *name, char const *realname,
283 bool command_line_arg);
284 static size_t print_file_name_and_frills (const struct fileinfo *f,
285 size_t start_col);
286 static void print_horizontal (void);
287 static int format_user_width (uid_t u);
288 static int format_group_width (gid_t g);
289 static void print_long_format (const struct fileinfo *f);
290 static void print_many_per_line (void);
291 static size_t print_name_with_quoting (const struct fileinfo *f,
292 bool symlink_target,
293 struct obstack *stack,
294 size_t start_col);
295 static void prep_non_filename_text (void);
296 static bool print_type_indicator (bool stat_ok, mode_t mode,
297 enum filetype type);
298 static void print_with_separator (char sep);
299 static void queue_directory (char const *name, char const *realname,
300 bool command_line_arg);
301 static void sort_files (void);
302 static void parse_ls_color (void);
304 static int getenv_quoting_style (void);
306 static size_t quote_name_width (char const *name,
307 struct quoting_options const *options,
308 int needs_general_quoting);
310 /* Initial size of hash table.
311 Most hierarchies are likely to be shallower than this. */
312 enum { INITIAL_TABLE_SIZE = 30 };
314 /* The set of 'active' directories, from the current command-line argument
315 to the level in the hierarchy at which files are being listed.
316 A directory is represented by its device and inode numbers (struct dev_ino).
317 A directory is added to this set when ls begins listing it or its
318 entries, and it is removed from the set just after ls has finished
319 processing it. This set is used solely to detect loops, e.g., with
320 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
321 static Hash_table *active_dir_set;
323 #define LOOP_DETECT (!!active_dir_set)
325 /* The table of files in the current directory:
327 'cwd_file' points to a vector of 'struct fileinfo', one per file.
328 'cwd_n_alloc' is the number of elements space has been allocated for.
329 'cwd_n_used' is the number actually in use. */
331 /* Address of block containing the files that are described. */
332 static struct fileinfo *cwd_file;
334 /* Length of block that 'cwd_file' points to, measured in files. */
335 static size_t cwd_n_alloc;
337 /* Index of first unused slot in 'cwd_file'. */
338 static size_t cwd_n_used;
340 /* Whether files needs may need padding due to quoting. */
341 static bool cwd_some_quoted;
343 /* Whether quoting style _may_ add outer quotes,
344 and whether aligning those is useful. */
345 static bool align_variable_outer_quotes;
347 /* Vector of pointers to files, in proper sorted order, and the number
348 of entries allocated for it. */
349 static void **sorted_file;
350 static size_t sorted_file_alloc;
352 /* When true, in a color listing, color each symlink name according to the
353 type of file it points to. Otherwise, color them according to the 'ln'
354 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
355 regardless. This is set when 'ln=target' appears in LS_COLORS. */
357 static bool color_symlink_as_referent;
359 static char const *hostname;
361 /* Mode of appropriate file for coloring. */
362 static mode_t
363 file_or_link_mode (struct fileinfo const *file)
365 return (color_symlink_as_referent && file->linkok
366 ? file->linkmode : file->stat.st_mode);
370 /* Record of one pending directory waiting to be listed. */
372 struct pending
374 char *name;
375 /* If the directory is actually the file pointed to by a symbolic link we
376 were told to list, 'realname' will contain the name of the symbolic
377 link, otherwise zero. */
378 char *realname;
379 bool command_line_arg;
380 struct pending *next;
383 static struct pending *pending_dirs;
385 /* Current time in seconds and nanoseconds since 1970, updated as
386 needed when deciding whether a file is recent. */
388 static struct timespec current_time;
390 static bool print_scontext;
391 static char UNKNOWN_SECURITY_CONTEXT[] = "?";
393 /* Whether any of the files has an ACL. This affects the width of the
394 mode column. */
396 static bool any_has_acl;
398 /* The number of columns to use for columns containing inode numbers,
399 block sizes, link counts, owners, groups, authors, major device
400 numbers, minor device numbers, and file sizes, respectively. */
402 static int inode_number_width;
403 static int block_size_width;
404 static int nlink_width;
405 static int scontext_width;
406 static int owner_width;
407 static int group_width;
408 static int author_width;
409 static int major_device_number_width;
410 static int minor_device_number_width;
411 static int file_size_width;
413 /* Option flags */
415 /* long_format for lots of info, one per line.
416 one_per_line for just names, one per line.
417 many_per_line for just names, many per line, sorted vertically.
418 horizontal for just names, many per line, sorted horizontally.
419 with_commas for just names, many per line, separated by commas.
421 -l (and other options that imply -l), -1, -C, -x and -m control
422 this parameter. */
424 enum format
426 long_format, /* -l and other options that imply -l */
427 one_per_line, /* -1 */
428 many_per_line, /* -C */
429 horizontal, /* -x */
430 with_commas /* -m */
433 static enum format format;
435 /* 'full-iso' uses full ISO-style dates and times. 'long-iso' uses longer
436 ISO-style timestamps, though shorter than 'full-iso'. 'iso' uses shorter
437 ISO-style timestamps. 'locale' uses locale-dependent timestamps. */
438 enum time_style
440 full_iso_time_style, /* --time-style=full-iso */
441 long_iso_time_style, /* --time-style=long-iso */
442 iso_time_style, /* --time-style=iso */
443 locale_time_style /* --time-style=locale */
446 static char const *const time_style_args[] =
448 "full-iso", "long-iso", "iso", "locale", nullptr
450 static enum time_style const time_style_types[] =
452 full_iso_time_style, long_iso_time_style, iso_time_style,
453 locale_time_style
455 ARGMATCH_VERIFY (time_style_args, time_style_types);
457 /* Type of time to print or sort by. Controlled by -c and -u.
458 The values of each item of this enum are important since they are
459 used as indices in the sort functions array (see sort_files()). */
461 enum time_type
463 time_mtime = 0, /* default */
464 time_ctime, /* -c */
465 time_atime, /* -u */
466 time_btime, /* birth time */
467 time_numtypes /* the number of elements of this enum */
470 static enum time_type time_type;
472 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v.
473 The values of each item of this enum are important since they are
474 used as indices in the sort functions array (see sort_files()). */
476 enum sort_type
478 sort_name = 0, /* default */
479 sort_extension, /* -X */
480 sort_width,
481 sort_size, /* -S */
482 sort_version, /* -v */
483 sort_time, /* -t; must be second to last */
484 sort_none, /* -U; must be last */
485 sort_numtypes /* the number of elements of this enum */
488 static enum sort_type sort_type;
490 /* Direction of sort.
491 false means highest first if numeric,
492 lowest first if alphabetic;
493 these are the defaults.
494 true means the opposite order in each case. -r */
496 static bool sort_reverse;
498 /* True means to display owner information. -g turns this off. */
500 static bool print_owner = true;
502 /* True means to display author information. */
504 static bool print_author;
506 /* True means to display group information. -G and -o turn this off. */
508 static bool print_group = true;
510 /* True means print the user and group id's as numbers rather
511 than as names. -n */
513 static bool numeric_ids;
515 /* True means mention the size in blocks of each file. -s */
517 static bool print_block_size;
519 /* Human-readable options for output, when printing block counts. */
520 static int human_output_opts;
522 /* The units to use when printing block counts. */
523 static uintmax_t output_block_size;
525 /* Likewise, but for file sizes. */
526 static int file_human_output_opts;
527 static uintmax_t file_output_block_size = 1;
529 /* Follow the output with a special string. Using this format,
530 Emacs' dired mode starts up twice as fast, and can handle all
531 strange characters in file names. */
532 static bool dired;
534 /* 'none' means don't mention the type of files.
535 'slash' means mention directories only, with a '/'.
536 'file_type' means mention file types.
537 'classify' means mention file types and mark executables.
539 Controlled by -F, -p, and --indicator-style. */
541 enum indicator_style
543 none = 0, /* --indicator-style=none (default) */
544 slash, /* -p, --indicator-style=slash */
545 file_type, /* --indicator-style=file-type */
546 classify /* -F, --indicator-style=classify */
549 static enum indicator_style indicator_style;
551 /* Names of indicator styles. */
552 static char const *const indicator_style_args[] =
554 "none", "slash", "file-type", "classify", nullptr
556 static enum indicator_style const indicator_style_types[] =
558 none, slash, file_type, classify
560 ARGMATCH_VERIFY (indicator_style_args, indicator_style_types);
562 /* True means use colors to mark types. Also define the different
563 colors as well as the stuff for the LS_COLORS environment variable.
564 The LS_COLORS variable is now in a termcap-like format. */
566 static bool print_with_color;
568 static bool print_hyperlink;
570 /* Whether we used any colors in the output so far. If so, we will
571 need to restore the default color later. If not, we will need to
572 call prep_non_filename_text before using color for the first time. */
574 static bool used_color = false;
576 enum when_type
578 when_never, /* 0: default or --color=never */
579 when_always, /* 1: --color=always */
580 when_if_tty /* 2: --color=tty */
583 enum Dereference_symlink
585 DEREF_UNDEFINED = 0, /* default */
586 DEREF_NEVER,
587 DEREF_COMMAND_LINE_ARGUMENTS, /* -H */
588 DEREF_COMMAND_LINE_SYMLINK_TO_DIR, /* the default, in certain cases */
589 DEREF_ALWAYS /* -L */
592 enum indicator_no
594 C_LEFT, C_RIGHT, C_END, C_RESET, C_NORM, C_FILE, C_DIR, C_LINK,
595 C_FIFO, C_SOCK,
596 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR, C_SETUID, C_SETGID,
597 C_STICKY, C_OTHER_WRITABLE, C_STICKY_OTHER_WRITABLE, C_CAP, C_MULTIHARDLINK,
598 C_CLR_TO_EOL
601 static char const *const indicator_name[]=
603 "lc", "rc", "ec", "rs", "no", "fi", "di", "ln", "pi", "so",
604 "bd", "cd", "mi", "or", "ex", "do", "su", "sg", "st",
605 "ow", "tw", "ca", "mh", "cl", nullptr
608 struct color_ext_type
610 struct bin_str ext; /* The extension we're looking for */
611 struct bin_str seq; /* The sequence to output when we do */
612 bool exact_match; /* Whether to compare case insensitively */
613 struct color_ext_type *next; /* Next in list */
616 static struct bin_str color_indicator[] =
618 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
619 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
620 { 0, nullptr }, /* ec: End color (replaces lc+rs+rc) */
621 { LEN_STR_PAIR ("0") }, /* rs: Reset to ordinary colors */
622 { 0, nullptr }, /* no: Normal */
623 { 0, nullptr }, /* fi: File: default */
624 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
625 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
626 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
627 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
628 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
629 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
630 { 0, nullptr }, /* mi: Missing file: undefined */
631 { 0, nullptr }, /* or: Orphaned symlink: undefined */
632 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
633 { LEN_STR_PAIR ("01;35") }, /* do: Door: bright magenta */
634 { LEN_STR_PAIR ("37;41") }, /* su: setuid: white on red */
635 { LEN_STR_PAIR ("30;43") }, /* sg: setgid: black on yellow */
636 { LEN_STR_PAIR ("37;44") }, /* st: sticky: black on blue */
637 { LEN_STR_PAIR ("34;42") }, /* ow: other-writable: blue on green */
638 { LEN_STR_PAIR ("30;42") }, /* tw: ow w/ sticky: black on green */
639 { 0, nullptr }, /* ca: disabled by default */
640 { 0, nullptr }, /* mh: disabled by default */
641 { LEN_STR_PAIR ("\033[K") }, /* cl: clear to end of line */
644 /* A list mapping file extensions to corresponding display sequence. */
645 static struct color_ext_type *color_ext_list = nullptr;
647 /* Buffer for color sequences */
648 static char *color_buf;
650 /* True means to check for orphaned symbolic link, for displaying
651 colors, or to group symlink to directories with other dirs. */
653 static bool check_symlink_mode;
655 /* True means mention the inode number of each file. -i */
657 static bool print_inode;
659 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
660 other options that imply -l), and -L. */
662 static enum Dereference_symlink dereference;
664 /* True means when a directory is found, display info on its
665 contents. -R */
667 static bool recursive;
669 /* True means when an argument is a directory name, display info
670 on it itself. -d */
672 static bool immediate_dirs;
674 /* True means that directories are grouped before files. */
676 static bool directories_first;
678 /* Which files to ignore. */
680 static enum
682 /* Ignore files whose names start with '.', and files specified by
683 --hide and --ignore. */
684 IGNORE_DEFAULT = 0,
686 /* Ignore '.', '..', and files specified by --ignore. */
687 IGNORE_DOT_AND_DOTDOT,
689 /* Ignore only files specified by --ignore. */
690 IGNORE_MINIMAL
691 } ignore_mode;
693 /* A linked list of shell-style globbing patterns. If a non-argument
694 file name matches any of these patterns, it is ignored.
695 Controlled by -I. Multiple -I options accumulate.
696 The -B option adds '*~' and '.*~' to this list. */
698 struct ignore_pattern
700 char const *pattern;
701 struct ignore_pattern *next;
704 static struct ignore_pattern *ignore_patterns;
706 /* Similar to IGNORE_PATTERNS, except that -a or -A causes this
707 variable itself to be ignored. */
708 static struct ignore_pattern *hide_patterns;
710 /* True means output nongraphic chars in file names as '?'.
711 (-q, --hide-control-chars)
712 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
713 independent. The algorithm is: first, obey the quoting style to get a
714 string representing the file name; then, if qmark_funny_chars is set,
715 replace all nonprintable chars in that string with '?'. It's necessary
716 to replace nonprintable chars even in quoted strings, because we don't
717 want to mess up the terminal if control chars get sent to it, and some
718 quoting methods pass through control chars as-is. */
719 static bool qmark_funny_chars;
721 /* Quoting options for file and dir name output. */
723 static struct quoting_options *filename_quoting_options;
724 static struct quoting_options *dirname_quoting_options;
726 /* The number of chars per hardware tab stop. Setting this to zero
727 inhibits the use of TAB characters for separating columns. -T */
728 static size_t tabsize;
730 /* True means print each directory name before listing it. */
732 static bool print_dir_name;
734 /* The line length to use for breaking lines in many-per-line format.
735 Can be set with -w. If zero, there is no limit. */
737 static size_t line_length;
739 /* The local time zone rules, as per the TZ environment variable. */
741 static timezone_t localtz;
743 /* If true, the file listing format requires that stat be called on
744 each file. */
746 static bool format_needs_stat;
748 /* Similar to 'format_needs_stat', but set if only the file type is
749 needed. */
751 static bool format_needs_type;
753 /* An arbitrary limit on the number of bytes in a printed timestamp.
754 This is set to a relatively small value to avoid the need to worry
755 about denial-of-service attacks on servers that run "ls" on behalf
756 of remote clients. 1000 bytes should be enough for any practical
757 timestamp format. */
759 enum { TIME_STAMP_LEN_MAXIMUM = MAX (1000, INT_STRLEN_BOUND (time_t)) };
761 /* strftime formats for non-recent and recent files, respectively, in
762 -l output. */
764 static char const *long_time_format[2] =
766 /* strftime format for non-recent files (older than 6 months), in
767 -l output. This should contain the year, month and day (at
768 least), in an order that is understood by people in your
769 locale's territory. Please try to keep the number of used
770 screen columns small, because many people work in windows with
771 only 80 columns. But make this as wide as the other string
772 below, for recent files. */
773 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
774 so be wary of using variable width fields from the locale.
775 Note %b is handled specially by ls and aligned correctly.
776 Note also that specifying a width as in %5b is erroneous as strftime
777 will count bytes rather than characters in multibyte locales. */
778 N_("%b %e %Y"),
779 /* strftime format for recent files (younger than 6 months), in -l
780 output. This should contain the month, day and time (at
781 least), in an order that is understood by people in your
782 locale's territory. Please try to keep the number of used
783 screen columns small, because many people work in windows with
784 only 80 columns. But make this as wide as the other string
785 above, for non-recent files. */
786 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
787 so be wary of using variable width fields from the locale.
788 Note %b is handled specially by ls and aligned correctly.
789 Note also that specifying a width as in %5b is erroneous as strftime
790 will count bytes rather than characters in multibyte locales. */
791 N_("%b %e %H:%M")
794 /* The set of signals that are caught. */
796 static sigset_t caught_signals;
798 /* If nonzero, the value of the pending fatal signal. */
800 static sig_atomic_t volatile interrupt_signal;
802 /* A count of the number of pending stop signals that have been received. */
804 static sig_atomic_t volatile stop_signal_count;
806 /* Desired exit status. */
808 static int exit_status;
810 /* Exit statuses. */
811 enum
813 /* "ls" had a minor problem. E.g., while processing a directory,
814 ls obtained the name of an entry via readdir, yet was later
815 unable to stat that name. This happens when listing a directory
816 in which entries are actively being removed or renamed. */
817 LS_MINOR_PROBLEM = 1,
819 /* "ls" had more serious trouble (e.g., memory exhausted, invalid
820 option or failure to stat a command line argument. */
821 LS_FAILURE = 2
824 /* For long options that have no equivalent short option, use a
825 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
826 enum
828 AUTHOR_OPTION = CHAR_MAX + 1,
829 BLOCK_SIZE_OPTION,
830 COLOR_OPTION,
831 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION,
832 FILE_TYPE_INDICATOR_OPTION,
833 FORMAT_OPTION,
834 FULL_TIME_OPTION,
835 GROUP_DIRECTORIES_FIRST_OPTION,
836 HIDE_OPTION,
837 HYPERLINK_OPTION,
838 INDICATOR_STYLE_OPTION,
839 QUOTING_STYLE_OPTION,
840 SHOW_CONTROL_CHARS_OPTION,
841 SI_OPTION,
842 SORT_OPTION,
843 TIME_OPTION,
844 TIME_STYLE_OPTION,
845 ZERO_OPTION,
848 static struct option const long_options[] =
850 {"all", no_argument, nullptr, 'a'},
851 {"escape", no_argument, nullptr, 'b'},
852 {"directory", no_argument, nullptr, 'd'},
853 {"dired", no_argument, nullptr, 'D'},
854 {"full-time", no_argument, nullptr, FULL_TIME_OPTION},
855 {"group-directories-first", no_argument, nullptr,
856 GROUP_DIRECTORIES_FIRST_OPTION},
857 {"human-readable", no_argument, nullptr, 'h'},
858 {"inode", no_argument, nullptr, 'i'},
859 {"kibibytes", no_argument, nullptr, 'k'},
860 {"numeric-uid-gid", no_argument, nullptr, 'n'},
861 {"no-group", no_argument, nullptr, 'G'},
862 {"hide-control-chars", no_argument, nullptr, 'q'},
863 {"reverse", no_argument, nullptr, 'r'},
864 {"size", no_argument, nullptr, 's'},
865 {"width", required_argument, nullptr, 'w'},
866 {"almost-all", no_argument, nullptr, 'A'},
867 {"ignore-backups", no_argument, nullptr, 'B'},
868 {"classify", optional_argument, nullptr, 'F'},
869 {"file-type", no_argument, nullptr, FILE_TYPE_INDICATOR_OPTION},
870 {"si", no_argument, nullptr, SI_OPTION},
871 {"dereference-command-line", no_argument, nullptr, 'H'},
872 {"dereference-command-line-symlink-to-dir", no_argument, nullptr,
873 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION},
874 {"hide", required_argument, nullptr, HIDE_OPTION},
875 {"ignore", required_argument, nullptr, 'I'},
876 {"indicator-style", required_argument, nullptr, INDICATOR_STYLE_OPTION},
877 {"dereference", no_argument, nullptr, 'L'},
878 {"literal", no_argument, nullptr, 'N'},
879 {"quote-name", no_argument, nullptr, 'Q'},
880 {"quoting-style", required_argument, nullptr, QUOTING_STYLE_OPTION},
881 {"recursive", no_argument, nullptr, 'R'},
882 {"format", required_argument, nullptr, FORMAT_OPTION},
883 {"show-control-chars", no_argument, nullptr, SHOW_CONTROL_CHARS_OPTION},
884 {"sort", required_argument, nullptr, SORT_OPTION},
885 {"tabsize", required_argument, nullptr, 'T'},
886 {"time", required_argument, nullptr, TIME_OPTION},
887 {"time-style", required_argument, nullptr, TIME_STYLE_OPTION},
888 {"zero", no_argument, nullptr, ZERO_OPTION},
889 {"color", optional_argument, nullptr, COLOR_OPTION},
890 {"hyperlink", optional_argument, nullptr, HYPERLINK_OPTION},
891 {"block-size", required_argument, nullptr, BLOCK_SIZE_OPTION},
892 {"context", no_argument, 0, 'Z'},
893 {"author", no_argument, nullptr, AUTHOR_OPTION},
894 {GETOPT_HELP_OPTION_DECL},
895 {GETOPT_VERSION_OPTION_DECL},
896 {nullptr, 0, nullptr, 0}
899 static char const *const format_args[] =
901 "verbose", "long", "commas", "horizontal", "across",
902 "vertical", "single-column", nullptr
904 static enum format const format_types[] =
906 long_format, long_format, with_commas, horizontal, horizontal,
907 many_per_line, one_per_line
909 ARGMATCH_VERIFY (format_args, format_types);
911 static char const *const sort_args[] =
913 "none", "time", "size", "extension", "version", "width", nullptr
915 static enum sort_type const sort_types[] =
917 sort_none, sort_time, sort_size, sort_extension, sort_version, sort_width
919 ARGMATCH_VERIFY (sort_args, sort_types);
921 static char const *const time_args[] =
923 "atime", "access", "use",
924 "ctime", "status",
925 "mtime", "modification",
926 "birth", "creation",
927 nullptr
929 static enum time_type const time_types[] =
931 time_atime, time_atime, time_atime,
932 time_ctime, time_ctime,
933 time_mtime, time_mtime,
934 time_btime, time_btime,
936 ARGMATCH_VERIFY (time_args, time_types);
938 static char const *const when_args[] =
940 /* force and none are for compatibility with another color-ls version */
941 "always", "yes", "force",
942 "never", "no", "none",
943 "auto", "tty", "if-tty", nullptr
945 static enum when_type const when_types[] =
947 when_always, when_always, when_always,
948 when_never, when_never, when_never,
949 when_if_tty, when_if_tty, when_if_tty
951 ARGMATCH_VERIFY (when_args, when_types);
953 /* Information about filling a column. */
954 struct column_info
956 bool valid_len;
957 size_t line_len;
958 size_t *col_arr;
961 /* Array with information about column fullness. */
962 static struct column_info *column_info;
964 /* Maximum number of columns ever possible for this display. */
965 static size_t max_idx;
967 /* The minimum width of a column is 3: 1 character for the name and 2
968 for the separating white space. */
969 enum { MIN_COLUMN_WIDTH = 3 };
972 /* This zero-based index is for the --dired option. It is incremented
973 for each byte of output generated by this program so that the beginning
974 and ending indices (in that output) of every file name can be recorded
975 and later output themselves. */
976 static off_t dired_pos;
978 static void
979 dired_outbyte (char c)
981 dired_pos++;
982 putchar (c);
985 /* Output the buffer S, of length S_LEN, and increment DIRED_POS by S_LEN. */
986 static void
987 dired_outbuf (char const *s, size_t s_len)
989 dired_pos += s_len;
990 fwrite (s, sizeof *s, s_len, stdout);
993 /* Output the string S, and increment DIRED_POS by its length. */
994 static void
995 dired_outstring (char const *s)
997 dired_outbuf (s, strlen (s));
1000 static void
1001 dired_indent (void)
1003 if (dired)
1004 dired_outstring (" ");
1007 /* With --dired, store pairs of beginning and ending indices of file names. */
1008 static struct obstack dired_obstack;
1010 /* With --dired, store pairs of beginning and ending indices of any
1011 directory names that appear as headers (just before 'total' line)
1012 for lists of directory entries. Such directory names are seen when
1013 listing hierarchies using -R and when a directory is listed with at
1014 least one other command line argument. */
1015 static struct obstack subdired_obstack;
1017 /* Save the current index on the specified obstack, OBS. */
1018 static void
1019 push_current_dired_pos (struct obstack *obs)
1021 if (dired)
1022 obstack_grow (obs, &dired_pos, sizeof dired_pos);
1025 /* With -R, this stack is used to help detect directory cycles.
1026 The device/inode pairs on this stack mirror the pairs in the
1027 active_dir_set hash table. */
1028 static struct obstack dev_ino_obstack;
1030 /* Push a pair onto the device/inode stack. */
1031 static void
1032 dev_ino_push (dev_t dev, ino_t ino)
1034 void *vdi;
1035 struct dev_ino *di;
1036 int dev_ino_size = sizeof *di;
1037 obstack_blank (&dev_ino_obstack, dev_ino_size);
1038 vdi = obstack_next_free (&dev_ino_obstack);
1039 di = vdi;
1040 di--;
1041 di->st_dev = dev;
1042 di->st_ino = ino;
1045 /* Pop a dev/ino struct off the global dev_ino_obstack
1046 and return that struct. */
1047 static struct dev_ino
1048 dev_ino_pop (void)
1050 void *vdi;
1051 struct dev_ino *di;
1052 int dev_ino_size = sizeof *di;
1053 affirm (dev_ino_size <= obstack_object_size (&dev_ino_obstack));
1054 obstack_blank_fast (&dev_ino_obstack, -dev_ino_size);
1055 vdi = obstack_next_free (&dev_ino_obstack);
1056 di = vdi;
1057 return *di;
1060 static void
1061 assert_matching_dev_ino (char const *name, struct dev_ino di)
1063 MAYBE_UNUSED struct stat sb;
1064 assure (0 <= stat (name, &sb));
1065 assure (sb.st_dev == di.st_dev);
1066 assure (sb.st_ino == di.st_ino);
1069 static char eolbyte = '\n';
1071 /* Write to standard output PREFIX, followed by the quoting style and
1072 a space-separated list of the integers stored in OS all on one line. */
1074 static void
1075 dired_dump_obstack (char const *prefix, struct obstack *os)
1077 size_t n_pos;
1079 n_pos = obstack_object_size (os) / sizeof (dired_pos);
1080 if (n_pos > 0)
1082 off_t *pos = obstack_finish (os);
1083 fputs (prefix, stdout);
1084 for (size_t i = 0; i < n_pos; i++)
1086 intmax_t p = pos[i];
1087 printf (" %jd", p);
1089 putchar ('\n');
1093 /* Return the platform birthtime member of the stat structure,
1094 or fallback to the mtime member, which we have populated
1095 from the statx structure or reset to an invalid timestamp
1096 where birth time is not supported. */
1097 static struct timespec
1098 get_stat_btime (struct stat const *st)
1100 struct timespec btimespec;
1102 #if HAVE_STATX && defined STATX_INO
1103 btimespec = get_stat_mtime (st);
1104 #else
1105 btimespec = get_stat_birthtime (st);
1106 #endif
1108 return btimespec;
1111 #if HAVE_STATX && defined STATX_INO
1112 ATTRIBUTE_PURE
1113 static unsigned int
1114 time_type_to_statx (void)
1116 switch (time_type)
1118 case time_ctime:
1119 return STATX_CTIME;
1120 case time_mtime:
1121 return STATX_MTIME;
1122 case time_atime:
1123 return STATX_ATIME;
1124 case time_btime:
1125 return STATX_BTIME;
1126 default:
1127 unreachable ();
1129 return 0;
1132 ATTRIBUTE_PURE
1133 static unsigned int
1134 calc_req_mask (void)
1136 unsigned int mask = STATX_MODE;
1138 if (print_inode)
1139 mask |= STATX_INO;
1141 if (print_block_size)
1142 mask |= STATX_BLOCKS;
1144 if (format == long_format) {
1145 mask |= STATX_NLINK | STATX_SIZE | time_type_to_statx ();
1146 if (print_owner || print_author)
1147 mask |= STATX_UID;
1148 if (print_group)
1149 mask |= STATX_GID;
1152 switch (sort_type)
1154 case sort_none:
1155 case sort_name:
1156 case sort_version:
1157 case sort_extension:
1158 case sort_width:
1159 break;
1160 case sort_time:
1161 mask |= time_type_to_statx ();
1162 break;
1163 case sort_size:
1164 mask |= STATX_SIZE;
1165 break;
1166 default:
1167 unreachable ();
1170 return mask;
1173 static int
1174 do_statx (int fd, char const *name, struct stat *st, int flags,
1175 unsigned int mask)
1177 struct statx stx;
1178 bool want_btime = mask & STATX_BTIME;
1179 int ret = statx (fd, name, flags | AT_NO_AUTOMOUNT, mask, &stx);
1180 if (ret >= 0)
1182 statx_to_stat (&stx, st);
1183 /* Since we only need one timestamp type,
1184 store birth time in st_mtim. */
1185 if (want_btime)
1187 if (stx.stx_mask & STATX_BTIME)
1188 st->st_mtim = statx_timestamp_to_timespec (stx.stx_btime);
1189 else
1190 st->st_mtim.tv_sec = st->st_mtim.tv_nsec = -1;
1194 return ret;
1197 static int
1198 do_stat (char const *name, struct stat *st)
1200 return do_statx (AT_FDCWD, name, st, 0, calc_req_mask ());
1203 static int
1204 do_lstat (char const *name, struct stat *st)
1206 return do_statx (AT_FDCWD, name, st, AT_SYMLINK_NOFOLLOW, calc_req_mask ());
1209 static int
1210 stat_for_mode (char const *name, struct stat *st)
1212 return do_statx (AT_FDCWD, name, st, 0, STATX_MODE);
1215 /* dev+ino should be static, so no need to sync with backing store */
1216 static int
1217 stat_for_ino (char const *name, struct stat *st)
1219 return do_statx (AT_FDCWD, name, st, 0, STATX_INO);
1222 static int
1223 fstat_for_ino (int fd, struct stat *st)
1225 return do_statx (fd, "", st, AT_EMPTY_PATH, STATX_INO);
1227 #else
1228 static int
1229 do_stat (char const *name, struct stat *st)
1231 return stat (name, st);
1234 static int
1235 do_lstat (char const *name, struct stat *st)
1237 return lstat (name, st);
1240 static int
1241 stat_for_mode (char const *name, struct stat *st)
1243 return stat (name, st);
1246 static int
1247 stat_for_ino (char const *name, struct stat *st)
1249 return stat (name, st);
1252 static int
1253 fstat_for_ino (int fd, struct stat *st)
1255 return fstat (fd, st);
1257 #endif
1259 /* Return the address of the first plain %b spec in FMT, or nullptr if
1260 there is no such spec. %5b etc. do not match, so that user
1261 widths/flags are honored. */
1263 ATTRIBUTE_PURE
1264 static char const *
1265 first_percent_b (char const *fmt)
1267 for (; *fmt; fmt++)
1268 if (fmt[0] == '%')
1269 switch (fmt[1])
1271 case 'b': return fmt;
1272 case '%': fmt++; break;
1274 return nullptr;
1277 static char RFC3986[256];
1278 static void
1279 file_escape_init (void)
1281 for (int i = 0; i < 256; i++)
1282 RFC3986[i] |= c_isalnum (i) || i == '~' || i == '-' || i == '.' || i == '_';
1285 enum { MBSWIDTH_FLAGS = MBSW_REJECT_INVALID | MBSW_REJECT_UNPRINTABLE };
1287 /* Read the abbreviated month names from the locale, to align them
1288 and to determine the max width of the field and to truncate names
1289 greater than our max allowed.
1290 Note even though this handles multibyte locales correctly
1291 it's not restricted to them as single byte locales can have
1292 variable width abbreviated months and also precomputing/caching
1293 the names was seen to increase the performance of ls significantly. */
1295 /* abformat[RECENT][MON] is the format to use for timestamps with
1296 recentness RECENT and month MON. */
1297 enum { ABFORMAT_SIZE = 128 };
1298 static char abformat[2][12][ABFORMAT_SIZE];
1299 /* True if precomputed formats should be used. This can be false if
1300 nl_langinfo fails, if a format or month abbreviation is unusually
1301 long, or if a month abbreviation contains '%'. */
1302 static bool use_abformat;
1304 /* Store into ABMON the abbreviated month names, suitably aligned.
1305 Return true if successful. */
1307 static bool
1308 abmon_init (char abmon[12][ABFORMAT_SIZE])
1310 #ifndef HAVE_NL_LANGINFO
1311 return false;
1312 #else
1313 int max_mon_width = 0;
1314 int mon_width[12];
1315 int mon_len[12];
1317 for (int i = 0; i < 12; i++)
1319 char const *abbr = nl_langinfo (ABMON_1 + i);
1320 mon_len[i] = strnlen (abbr, ABFORMAT_SIZE);
1321 if (mon_len[i] == ABFORMAT_SIZE)
1322 return false;
1323 if (strchr (abbr, '%'))
1324 return false;
1325 mon_width[i] = mbswidth (strcpy (abmon[i], abbr), MBSWIDTH_FLAGS);
1326 if (mon_width[i] < 0)
1327 return false;
1328 max_mon_width = MAX (max_mon_width, mon_width[i]);
1331 for (int i = 0; i < 12; i++)
1333 int fill = max_mon_width - mon_width[i];
1334 if (ABFORMAT_SIZE - mon_len[i] <= fill)
1335 return false;
1336 bool align_left = !isdigit (to_uchar (abmon[i][0]));
1337 int fill_offset;
1338 if (align_left)
1339 fill_offset = mon_len[i];
1340 else
1342 memmove (abmon[i] + fill, abmon[i], mon_len[i]);
1343 fill_offset = 0;
1345 memset (abmon[i] + fill_offset, ' ', fill);
1346 abmon[i][mon_len[i] + fill] = '\0';
1349 return true;
1350 #endif
1353 /* Initialize ABFORMAT and USE_ABFORMAT. */
1355 static void
1356 abformat_init (void)
1358 char const *pb[2];
1359 for (int recent = 0; recent < 2; recent++)
1360 pb[recent] = first_percent_b (long_time_format[recent]);
1361 if (! (pb[0] || pb[1]))
1362 return;
1364 char abmon[12][ABFORMAT_SIZE];
1365 if (! abmon_init (abmon))
1366 return;
1368 for (int recent = 0; recent < 2; recent++)
1370 char const *fmt = long_time_format[recent];
1371 for (int i = 0; i < 12; i++)
1373 char *nfmt = abformat[recent][i];
1374 int nbytes;
1376 if (! pb[recent])
1377 nbytes = snprintf (nfmt, ABFORMAT_SIZE, "%s", fmt);
1378 else
1380 if (! (pb[recent] - fmt <= MIN (ABFORMAT_SIZE, INT_MAX)))
1381 return;
1382 int prefix_len = pb[recent] - fmt;
1383 nbytes = snprintf (nfmt, ABFORMAT_SIZE, "%.*s%s%s",
1384 prefix_len, fmt, abmon[i], pb[recent] + 2);
1387 if (! (0 <= nbytes && nbytes < ABFORMAT_SIZE))
1388 return;
1392 use_abformat = true;
1395 static size_t
1396 dev_ino_hash (void const *x, size_t table_size)
1398 struct dev_ino const *p = x;
1399 return (uintmax_t) p->st_ino % table_size;
1402 static bool
1403 dev_ino_compare (void const *x, void const *y)
1405 struct dev_ino const *a = x;
1406 struct dev_ino const *b = y;
1407 return PSAME_INODE (a, b);
1410 static void
1411 dev_ino_free (void *x)
1413 free (x);
1416 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
1417 active directories. Return true if there is already a matching
1418 entry in the table. */
1420 static bool
1421 visit_dir (dev_t dev, ino_t ino)
1423 struct dev_ino *ent;
1424 struct dev_ino *ent_from_table;
1425 bool found_match;
1427 ent = xmalloc (sizeof *ent);
1428 ent->st_ino = ino;
1429 ent->st_dev = dev;
1431 /* Attempt to insert this entry into the table. */
1432 ent_from_table = hash_insert (active_dir_set, ent);
1434 if (ent_from_table == nullptr)
1436 /* Insertion failed due to lack of memory. */
1437 xalloc_die ();
1440 found_match = (ent_from_table != ent);
1442 if (found_match)
1444 /* ent was not inserted, so free it. */
1445 free (ent);
1448 return found_match;
1451 static void
1452 free_pending_ent (struct pending *p)
1454 free (p->name);
1455 free (p->realname);
1456 free (p);
1459 static bool
1460 is_colored (enum indicator_no type)
1462 size_t len = color_indicator[type].len;
1463 char const *s = color_indicator[type].string;
1464 return ! (len == 0
1465 || (len == 1 && STRNCMP_LIT (s, "0") == 0)
1466 || (len == 2 && STRNCMP_LIT (s, "00") == 0));
1469 static void
1470 restore_default_color (void)
1472 put_indicator (&color_indicator[C_LEFT]);
1473 put_indicator (&color_indicator[C_RIGHT]);
1476 static void
1477 set_normal_color (void)
1479 if (print_with_color && is_colored (C_NORM))
1481 put_indicator (&color_indicator[C_LEFT]);
1482 put_indicator (&color_indicator[C_NORM]);
1483 put_indicator (&color_indicator[C_RIGHT]);
1487 /* An ordinary signal was received; arrange for the program to exit. */
1489 static void
1490 sighandler (int sig)
1492 if (! SA_NOCLDSTOP)
1493 signal (sig, SIG_IGN);
1494 if (! interrupt_signal)
1495 interrupt_signal = sig;
1498 /* A SIGTSTP was received; arrange for the program to suspend itself. */
1500 static void
1501 stophandler (int sig)
1503 if (! SA_NOCLDSTOP)
1504 signal (sig, stophandler);
1505 if (! interrupt_signal)
1506 stop_signal_count++;
1509 /* Process any pending signals. If signals are caught, this function
1510 should be called periodically. Ideally there should never be an
1511 unbounded amount of time when signals are not being processed.
1512 Signal handling can restore the default colors, so callers must
1513 immediately change colors after invoking this function. */
1515 static void
1516 process_signals (void)
1518 while (interrupt_signal || stop_signal_count)
1520 int sig;
1521 int stops;
1522 sigset_t oldset;
1524 if (used_color)
1525 restore_default_color ();
1526 fflush (stdout);
1528 sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
1530 /* Reload interrupt_signal and stop_signal_count, in case a new
1531 signal was handled before sigprocmask took effect. */
1532 sig = interrupt_signal;
1533 stops = stop_signal_count;
1535 /* SIGTSTP is special, since the application can receive that signal
1536 more than once. In this case, don't set the signal handler to the
1537 default. Instead, just raise the uncatchable SIGSTOP. */
1538 if (stops)
1540 stop_signal_count = stops - 1;
1541 sig = SIGSTOP;
1543 else
1544 signal (sig, SIG_DFL);
1546 /* Exit or suspend the program. */
1547 raise (sig);
1548 sigprocmask (SIG_SETMASK, &oldset, nullptr);
1550 /* If execution reaches here, then the program has been
1551 continued (after being suspended). */
1555 /* Setup signal handlers if INIT is true,
1556 otherwise restore to the default. */
1558 static void
1559 signal_setup (bool init)
1561 /* The signals that are trapped, and the number of such signals. */
1562 static int const sig[] =
1564 /* This one is handled specially. */
1565 SIGTSTP,
1567 /* The usual suspects. */
1568 SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM,
1569 #ifdef SIGPOLL
1570 SIGPOLL,
1571 #endif
1572 #ifdef SIGPROF
1573 SIGPROF,
1574 #endif
1575 #ifdef SIGVTALRM
1576 SIGVTALRM,
1577 #endif
1578 #ifdef SIGXCPU
1579 SIGXCPU,
1580 #endif
1581 #ifdef SIGXFSZ
1582 SIGXFSZ,
1583 #endif
1585 enum { nsigs = ARRAY_CARDINALITY (sig) };
1587 #if ! SA_NOCLDSTOP
1588 static bool caught_sig[nsigs];
1589 #endif
1591 int j;
1593 if (init)
1595 #if SA_NOCLDSTOP
1596 struct sigaction act;
1598 sigemptyset (&caught_signals);
1599 for (j = 0; j < nsigs; j++)
1601 sigaction (sig[j], nullptr, &act);
1602 if (act.sa_handler != SIG_IGN)
1603 sigaddset (&caught_signals, sig[j]);
1606 act.sa_mask = caught_signals;
1607 act.sa_flags = SA_RESTART;
1609 for (j = 0; j < nsigs; j++)
1610 if (sigismember (&caught_signals, sig[j]))
1612 act.sa_handler = sig[j] == SIGTSTP ? stophandler : sighandler;
1613 sigaction (sig[j], &act, nullptr);
1615 #else
1616 for (j = 0; j < nsigs; j++)
1618 caught_sig[j] = (signal (sig[j], SIG_IGN) != SIG_IGN);
1619 if (caught_sig[j])
1621 signal (sig[j], sig[j] == SIGTSTP ? stophandler : sighandler);
1622 siginterrupt (sig[j], 0);
1625 #endif
1627 else /* restore. */
1629 #if SA_NOCLDSTOP
1630 for (j = 0; j < nsigs; j++)
1631 if (sigismember (&caught_signals, sig[j]))
1632 signal (sig[j], SIG_DFL);
1633 #else
1634 for (j = 0; j < nsigs; j++)
1635 if (caught_sig[j])
1636 signal (sig[j], SIG_DFL);
1637 #endif
1641 static void
1642 signal_init (void)
1644 signal_setup (true);
1647 static void
1648 signal_restore (void)
1650 signal_setup (false);
1654 main (int argc, char **argv)
1656 int i;
1657 struct pending *thispend;
1658 int n_files;
1660 initialize_main (&argc, &argv);
1661 set_program_name (argv[0]);
1662 setlocale (LC_ALL, "");
1663 bindtextdomain (PACKAGE, LOCALEDIR);
1664 textdomain (PACKAGE);
1666 initialize_exit_failure (LS_FAILURE);
1667 atexit (close_stdout);
1669 static_assert (ARRAY_CARDINALITY (color_indicator) + 1
1670 == ARRAY_CARDINALITY (indicator_name));
1672 exit_status = EXIT_SUCCESS;
1673 print_dir_name = true;
1674 pending_dirs = nullptr;
1676 current_time.tv_sec = TYPE_MINIMUM (time_t);
1677 current_time.tv_nsec = -1;
1679 i = decode_switches (argc, argv);
1681 if (print_with_color)
1682 parse_ls_color ();
1684 /* Test print_with_color again, because the call to parse_ls_color
1685 may have just reset it -- e.g., if LS_COLORS is invalid. */
1687 if (print_with_color)
1689 /* Don't use TAB characters in output. Some terminal
1690 emulators can't handle the combination of tabs and
1691 color codes on the same line. */
1692 tabsize = 0;
1695 if (directories_first)
1696 check_symlink_mode = true;
1697 else if (print_with_color)
1699 /* Avoid following symbolic links when possible. */
1700 if (is_colored (C_ORPHAN)
1701 || (is_colored (C_EXEC) && color_symlink_as_referent)
1702 || (is_colored (C_MISSING) && format == long_format))
1703 check_symlink_mode = true;
1706 if (dereference == DEREF_UNDEFINED)
1707 dereference = ((immediate_dirs
1708 || indicator_style == classify
1709 || format == long_format)
1710 ? DEREF_NEVER
1711 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
1713 /* When using -R, initialize a data structure we'll use to
1714 detect any directory cycles. */
1715 if (recursive)
1717 active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, nullptr,
1718 dev_ino_hash,
1719 dev_ino_compare,
1720 dev_ino_free);
1721 if (active_dir_set == nullptr)
1722 xalloc_die ();
1724 obstack_init (&dev_ino_obstack);
1727 localtz = tzalloc (getenv ("TZ"));
1729 format_needs_stat = sort_type == sort_time || sort_type == sort_size
1730 || format == long_format
1731 || print_scontext
1732 || print_block_size;
1733 format_needs_type = (! format_needs_stat
1734 && (recursive
1735 || print_with_color
1736 || indicator_style != none
1737 || directories_first));
1739 if (dired)
1741 obstack_init (&dired_obstack);
1742 obstack_init (&subdired_obstack);
1745 if (print_hyperlink)
1747 file_escape_init ();
1749 hostname = xgethostname ();
1750 /* The hostname is generally ignored,
1751 so ignore failures obtaining it. */
1752 if (! hostname)
1753 hostname = "";
1756 cwd_n_alloc = 100;
1757 cwd_file = xnmalloc (cwd_n_alloc, sizeof *cwd_file);
1758 cwd_n_used = 0;
1760 clear_files ();
1762 n_files = argc - i;
1764 if (n_files <= 0)
1766 if (immediate_dirs)
1767 gobble_file (".", directory, NOT_AN_INODE_NUMBER, true, "");
1768 else
1769 queue_directory (".", nullptr, true);
1771 else
1773 gobble_file (argv[i++], unknown, NOT_AN_INODE_NUMBER, true, "");
1774 while (i < argc);
1776 if (cwd_n_used)
1778 sort_files ();
1779 if (!immediate_dirs)
1780 extract_dirs_from_files (nullptr, true);
1781 /* 'cwd_n_used' might be zero now. */
1784 /* In the following if/else blocks, it is sufficient to test 'pending_dirs'
1785 (and not pending_dirs->name) because there may be no markers in the queue
1786 at this point. A marker may be enqueued when extract_dirs_from_files is
1787 called with a non-empty string or via print_dir. */
1788 if (cwd_n_used)
1790 print_current_files ();
1791 if (pending_dirs)
1792 dired_outbyte ('\n');
1794 else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1795 print_dir_name = false;
1797 while (pending_dirs)
1799 thispend = pending_dirs;
1800 pending_dirs = pending_dirs->next;
1802 if (LOOP_DETECT)
1804 if (thispend->name == nullptr)
1806 /* thispend->name == nullptr means this is a marker entry
1807 indicating we've finished processing the directory.
1808 Use its dev/ino numbers to remove the corresponding
1809 entry from the active_dir_set hash table. */
1810 struct dev_ino di = dev_ino_pop ();
1811 struct dev_ino *found = hash_remove (active_dir_set, &di);
1812 if (false)
1813 assert_matching_dev_ino (thispend->realname, di);
1814 affirm (found);
1815 dev_ino_free (found);
1816 free_pending_ent (thispend);
1817 continue;
1821 print_dir (thispend->name, thispend->realname,
1822 thispend->command_line_arg);
1824 free_pending_ent (thispend);
1825 print_dir_name = true;
1828 if (print_with_color && used_color)
1830 int j;
1832 /* Skip the restore when it would be a no-op, i.e.,
1833 when left is "\033[" and right is "m". */
1834 if (!(color_indicator[C_LEFT].len == 2
1835 && memcmp (color_indicator[C_LEFT].string, "\033[", 2) == 0
1836 && color_indicator[C_RIGHT].len == 1
1837 && color_indicator[C_RIGHT].string[0] == 'm'))
1838 restore_default_color ();
1840 fflush (stdout);
1842 signal_restore ();
1844 /* Act on any signals that arrived before the default was restored.
1845 This can process signals out of order, but there doesn't seem to
1846 be an easy way to do them in order, and the order isn't that
1847 important anyway. */
1848 for (j = stop_signal_count; j; j--)
1849 raise (SIGSTOP);
1850 j = interrupt_signal;
1851 if (j)
1852 raise (j);
1855 if (dired)
1857 /* No need to free these since we're about to exit. */
1858 dired_dump_obstack ("//DIRED//", &dired_obstack);
1859 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1860 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1861 quoting_style_args[get_quoting_style (filename_quoting_options)]);
1864 if (LOOP_DETECT)
1866 assure (hash_get_n_entries (active_dir_set) == 0);
1867 hash_free (active_dir_set);
1870 return exit_status;
1873 /* Return the line length indicated by the value given by SPEC, or -1
1874 if unsuccessful. 0 means no limit on line length. */
1876 static ptrdiff_t
1877 decode_line_length (char const *spec)
1879 uintmax_t val;
1881 /* Treat too-large values as if they were 0, which is
1882 effectively infinity. */
1883 switch (xstrtoumax (spec, nullptr, 0, &val, ""))
1885 case LONGINT_OK:
1886 return val <= MIN (PTRDIFF_MAX, SIZE_MAX) ? val : 0;
1888 case LONGINT_OVERFLOW:
1889 return 0;
1891 default:
1892 return -1;
1896 /* Return true if standard output is a tty, caching the result. */
1898 static bool
1899 stdout_isatty (void)
1901 static signed char out_tty = -1;
1902 if (out_tty < 0)
1903 out_tty = isatty (STDOUT_FILENO);
1904 assume (out_tty == 0 || out_tty == 1);
1905 return out_tty;
1908 /* Set all the option flags according to the switches specified.
1909 Return the index of the first non-option argument. */
1911 static int
1912 decode_switches (int argc, char **argv)
1914 char const *time_style_option = nullptr;
1916 /* These variables are false or -1 unless a switch says otherwise. */
1917 bool kibibytes_specified = false;
1918 int format_opt = -1;
1919 int hide_control_chars_opt = -1;
1920 int quoting_style_opt = -1;
1921 int sort_opt = -1;
1922 ptrdiff_t tabsize_opt = -1;
1923 ptrdiff_t width_opt = -1;
1925 while (true)
1927 int oi = -1;
1928 int c = getopt_long (argc, argv,
1929 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1",
1930 long_options, &oi);
1931 if (c == -1)
1932 break;
1934 switch (c)
1936 case 'a':
1937 ignore_mode = IGNORE_MINIMAL;
1938 break;
1940 case 'b':
1941 quoting_style_opt = escape_quoting_style;
1942 break;
1944 case 'c':
1945 time_type = time_ctime;
1946 break;
1948 case 'd':
1949 immediate_dirs = true;
1950 break;
1952 case 'f':
1953 ignore_mode = IGNORE_MINIMAL; /* enable -a */
1954 sort_opt = sort_none; /* enable -U */
1955 break;
1957 case FILE_TYPE_INDICATOR_OPTION: /* --file-type */
1958 indicator_style = file_type;
1959 break;
1961 case 'g':
1962 format_opt = long_format;
1963 print_owner = false;
1964 break;
1966 case 'h':
1967 file_human_output_opts = human_output_opts =
1968 human_autoscale | human_SI | human_base_1024;
1969 file_output_block_size = output_block_size = 1;
1970 break;
1972 case 'i':
1973 print_inode = true;
1974 break;
1976 case 'k':
1977 kibibytes_specified = true;
1978 break;
1980 case 'l':
1981 format_opt = long_format;
1982 break;
1984 case 'm':
1985 format_opt = with_commas;
1986 break;
1988 case 'n':
1989 numeric_ids = true;
1990 format_opt = long_format;
1991 break;
1993 case 'o': /* Just like -l, but don't display group info. */
1994 format_opt = long_format;
1995 print_group = false;
1996 break;
1998 case 'p':
1999 indicator_style = slash;
2000 break;
2002 case 'q':
2003 hide_control_chars_opt = true;
2004 break;
2006 case 'r':
2007 sort_reverse = true;
2008 break;
2010 case 's':
2011 print_block_size = true;
2012 break;
2014 case 't':
2015 sort_opt = sort_time;
2016 break;
2018 case 'u':
2019 time_type = time_atime;
2020 break;
2022 case 'v':
2023 sort_opt = sort_version;
2024 break;
2026 case 'w':
2027 width_opt = decode_line_length (optarg);
2028 if (width_opt < 0)
2029 error (LS_FAILURE, 0, "%s: %s", _("invalid line width"),
2030 quote (optarg));
2031 break;
2033 case 'x':
2034 format_opt = horizontal;
2035 break;
2037 case 'A':
2038 ignore_mode = IGNORE_DOT_AND_DOTDOT;
2039 break;
2041 case 'B':
2042 add_ignore_pattern ("*~");
2043 add_ignore_pattern (".*~");
2044 break;
2046 case 'C':
2047 format_opt = many_per_line;
2048 break;
2050 case 'D':
2051 format_opt = long_format;
2052 print_hyperlink = false;
2053 dired = true;
2054 break;
2056 case 'F':
2058 int i;
2059 if (optarg)
2060 i = XARGMATCH ("--classify", optarg, when_args, when_types);
2061 else
2062 /* Using --classify with no argument is equivalent to using
2063 --classify=always. */
2064 i = when_always;
2066 if (i == when_always || (i == when_if_tty && stdout_isatty ()))
2067 indicator_style = classify;
2068 break;
2071 case 'G': /* inhibit display of group info */
2072 print_group = false;
2073 break;
2075 case 'H':
2076 dereference = DEREF_COMMAND_LINE_ARGUMENTS;
2077 break;
2079 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
2080 dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
2081 break;
2083 case 'I':
2084 add_ignore_pattern (optarg);
2085 break;
2087 case 'L':
2088 dereference = DEREF_ALWAYS;
2089 break;
2091 case 'N':
2092 quoting_style_opt = literal_quoting_style;
2093 break;
2095 case 'Q':
2096 quoting_style_opt = c_quoting_style;
2097 break;
2099 case 'R':
2100 recursive = true;
2101 break;
2103 case 'S':
2104 sort_opt = sort_size;
2105 break;
2107 case 'T':
2108 tabsize_opt = xnumtoumax (optarg, 0, 0, MIN (PTRDIFF_MAX, SIZE_MAX),
2109 "", _("invalid tab size"), LS_FAILURE);
2110 break;
2112 case 'U':
2113 sort_opt = sort_none;
2114 break;
2116 case 'X':
2117 sort_opt = sort_extension;
2118 break;
2120 case '1':
2121 /* -1 has no effect after -l. */
2122 if (format_opt != long_format)
2123 format_opt = one_per_line;
2124 break;
2126 case AUTHOR_OPTION:
2127 print_author = true;
2128 break;
2130 case HIDE_OPTION:
2132 struct ignore_pattern *hide = xmalloc (sizeof *hide);
2133 hide->pattern = optarg;
2134 hide->next = hide_patterns;
2135 hide_patterns = hide;
2137 break;
2139 case SORT_OPTION:
2140 sort_opt = XARGMATCH ("--sort", optarg, sort_args, sort_types);
2141 break;
2143 case GROUP_DIRECTORIES_FIRST_OPTION:
2144 directories_first = true;
2145 break;
2147 case TIME_OPTION:
2148 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
2149 break;
2151 case FORMAT_OPTION:
2152 format_opt = XARGMATCH ("--format", optarg, format_args,
2153 format_types);
2154 break;
2156 case FULL_TIME_OPTION:
2157 format_opt = long_format;
2158 time_style_option = "full-iso";
2159 break;
2161 case COLOR_OPTION:
2163 int i;
2164 if (optarg)
2165 i = XARGMATCH ("--color", optarg, when_args, when_types);
2166 else
2167 /* Using --color with no argument is equivalent to using
2168 --color=always. */
2169 i = when_always;
2171 print_with_color = (i == when_always
2172 || (i == when_if_tty && stdout_isatty ()));
2173 break;
2176 case HYPERLINK_OPTION:
2178 int i;
2179 if (optarg)
2180 i = XARGMATCH ("--hyperlink", optarg, when_args, when_types);
2181 else
2182 /* Using --hyperlink with no argument is equivalent to using
2183 --hyperlink=always. */
2184 i = when_always;
2186 print_hyperlink = (i == when_always
2187 || (i == when_if_tty && stdout_isatty ()));
2188 break;
2191 case INDICATOR_STYLE_OPTION:
2192 indicator_style = XARGMATCH ("--indicator-style", optarg,
2193 indicator_style_args,
2194 indicator_style_types);
2195 break;
2197 case QUOTING_STYLE_OPTION:
2198 quoting_style_opt = XARGMATCH ("--quoting-style", optarg,
2199 quoting_style_args,
2200 quoting_style_vals);
2201 break;
2203 case TIME_STYLE_OPTION:
2204 time_style_option = optarg;
2205 break;
2207 case SHOW_CONTROL_CHARS_OPTION:
2208 hide_control_chars_opt = false;
2209 break;
2211 case BLOCK_SIZE_OPTION:
2213 enum strtol_error e = human_options (optarg, &human_output_opts,
2214 &output_block_size);
2215 if (e != LONGINT_OK)
2216 xstrtol_fatal (e, oi, 0, long_options, optarg);
2217 file_human_output_opts = human_output_opts;
2218 file_output_block_size = output_block_size;
2220 break;
2222 case SI_OPTION:
2223 file_human_output_opts = human_output_opts =
2224 human_autoscale | human_SI;
2225 file_output_block_size = output_block_size = 1;
2226 break;
2228 case 'Z':
2229 print_scontext = true;
2230 break;
2232 case ZERO_OPTION:
2233 eolbyte = 0;
2234 hide_control_chars_opt = false;
2235 if (format_opt != long_format)
2236 format_opt = one_per_line;
2237 print_with_color = false;
2238 quoting_style_opt = literal_quoting_style;
2239 break;
2241 case_GETOPT_HELP_CHAR;
2243 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
2245 default:
2246 usage (LS_FAILURE);
2250 if (! output_block_size)
2252 char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
2253 human_options (ls_block_size,
2254 &human_output_opts, &output_block_size);
2255 if (ls_block_size || getenv ("BLOCK_SIZE"))
2257 file_human_output_opts = human_output_opts;
2258 file_output_block_size = output_block_size;
2260 if (kibibytes_specified)
2262 human_output_opts = 0;
2263 output_block_size = 1024;
2267 format = (0 <= format_opt ? format_opt
2268 : ls_mode == LS_LS ? (stdout_isatty ()
2269 ? many_per_line : one_per_line)
2270 : ls_mode == LS_MULTI_COL ? many_per_line
2271 : /* ls_mode == LS_LONG_FORMAT */ long_format);
2273 /* If the line length was not set by a switch but is needed to determine
2274 output, go to the work of obtaining it from the environment. */
2275 ptrdiff_t linelen = width_opt;
2276 if (format == many_per_line || format == horizontal || format == with_commas
2277 || print_with_color)
2279 #ifdef TIOCGWINSZ
2280 if (linelen < 0)
2282 struct winsize ws;
2283 if (stdout_isatty ()
2284 && 0 <= ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws)
2285 && 0 < ws.ws_col)
2286 linelen = ws.ws_col <= MIN (PTRDIFF_MAX, SIZE_MAX) ? ws.ws_col : 0;
2288 #endif
2289 if (linelen < 0)
2291 char const *p = getenv ("COLUMNS");
2292 if (p && *p)
2294 linelen = decode_line_length (p);
2295 if (linelen < 0)
2296 error (0, 0,
2297 _("ignoring invalid width"
2298 " in environment variable COLUMNS: %s"),
2299 quote (p));
2304 line_length = linelen < 0 ? 80 : linelen;
2306 /* Determine the max possible number of display columns. */
2307 max_idx = line_length / MIN_COLUMN_WIDTH;
2308 /* Account for first display column not having a separator,
2309 or line_lengths shorter than MIN_COLUMN_WIDTH. */
2310 max_idx += line_length % MIN_COLUMN_WIDTH != 0;
2312 if (format == many_per_line || format == horizontal || format == with_commas)
2314 if (0 <= tabsize_opt)
2315 tabsize = tabsize_opt;
2316 else
2318 tabsize = 8;
2319 char const *p = getenv ("TABSIZE");
2320 if (p)
2322 uintmax_t tmp;
2323 if (xstrtoumax (p, nullptr, 0, &tmp, "") == LONGINT_OK
2324 && tmp <= SIZE_MAX)
2325 tabsize = tmp;
2326 else
2327 error (0, 0,
2328 _("ignoring invalid tab size"
2329 " in environment variable TABSIZE: %s"),
2330 quote (p));
2335 qmark_funny_chars = (hide_control_chars_opt < 0
2336 ? ls_mode == LS_LS && stdout_isatty ()
2337 : hide_control_chars_opt);
2339 int qs = quoting_style_opt;
2340 if (qs < 0)
2341 qs = getenv_quoting_style ();
2342 if (qs < 0)
2343 qs = (ls_mode == LS_LS
2344 ? (stdout_isatty () ? shell_escape_quoting_style : -1)
2345 : escape_quoting_style);
2346 if (0 <= qs)
2347 set_quoting_style (nullptr, qs);
2348 qs = get_quoting_style (nullptr);
2349 align_variable_outer_quotes
2350 = ((format == long_format
2351 || ((format == many_per_line || format == horizontal) && line_length))
2352 && (qs == shell_quoting_style
2353 || qs == shell_escape_quoting_style
2354 || qs == c_maybe_quoting_style));
2355 filename_quoting_options = clone_quoting_options (nullptr);
2356 if (qs == escape_quoting_style)
2357 set_char_quoting (filename_quoting_options, ' ', 1);
2358 if (file_type <= indicator_style)
2360 char const *p;
2361 for (p = &"*=>@|"[indicator_style - file_type]; *p; p++)
2362 set_char_quoting (filename_quoting_options, *p, 1);
2365 dirname_quoting_options = clone_quoting_options (nullptr);
2366 set_char_quoting (dirname_quoting_options, ':', 1);
2368 /* --dired implies --format=long (-l) and sans --hyperlink.
2369 So ignore it if those overridden. */
2370 dired &= (format == long_format) & !print_hyperlink;
2372 if (eolbyte < dired)
2373 error (LS_FAILURE, 0, _("--dired and --zero are incompatible"));
2375 /* If -c or -u is specified and not -l (or any other option that implies -l),
2376 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
2377 The behavior of ls when using either -c or -u but with neither -l nor -t
2378 appears to be unspecified by POSIX. So, with GNU ls, '-u' alone means
2379 sort by atime (this is the one that's not specified by the POSIX spec),
2380 -lu means show atime and sort by name, -lut means show atime and sort
2381 by atime. */
2383 sort_type = (0 <= sort_opt ? sort_opt
2384 : (format != long_format
2385 && (time_type == time_ctime || time_type == time_atime
2386 || time_type == time_btime))
2387 ? sort_time : sort_name);
2389 if (format == long_format)
2391 char const *style = time_style_option;
2392 static char const posix_prefix[] = "posix-";
2394 if (! style)
2396 style = getenv ("TIME_STYLE");
2397 if (! style)
2398 style = "locale";
2401 while (STREQ_LEN (style, posix_prefix, sizeof posix_prefix - 1))
2403 if (! hard_locale (LC_TIME))
2404 return optind;
2405 style += sizeof posix_prefix - 1;
2408 if (*style == '+')
2410 char const *p0 = style + 1;
2411 char *p0nl = strchr (p0, '\n');
2412 char const *p1 = p0;
2413 if (p0nl)
2415 if (strchr (p0nl + 1, '\n'))
2416 error (LS_FAILURE, 0, _("invalid time style format %s"),
2417 quote (p0));
2418 *p0nl++ = '\0';
2419 p1 = p0nl;
2421 long_time_format[0] = p0;
2422 long_time_format[1] = p1;
2424 else
2426 ptrdiff_t res = argmatch (style, time_style_args,
2427 (char const *) time_style_types,
2428 sizeof (*time_style_types));
2429 if (res < 0)
2431 /* This whole block used to be a simple use of XARGMATCH.
2432 but that didn't print the "posix-"-prefixed variants or
2433 the "+"-prefixed format string option upon failure. */
2434 argmatch_invalid ("time style", style, res);
2436 /* The following is a manual expansion of argmatch_valid,
2437 but with the added "+ ..." description and the [posix-]
2438 prefixes prepended. Note that this simplification works
2439 only because all four existing time_style_types values
2440 are distinct. */
2441 fputs (_("Valid arguments are:\n"), stderr);
2442 char const *const *p = time_style_args;
2443 while (*p)
2444 fprintf (stderr, " - [posix-]%s\n", *p++);
2445 fputs (_(" - +FORMAT (e.g., +%H:%M) for a 'date'-style"
2446 " format\n"), stderr);
2447 usage (LS_FAILURE);
2449 switch (res)
2451 case full_iso_time_style:
2452 long_time_format[0] = long_time_format[1] =
2453 "%Y-%m-%d %H:%M:%S.%N %z";
2454 break;
2456 case long_iso_time_style:
2457 long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
2458 break;
2460 case iso_time_style:
2461 long_time_format[0] = "%Y-%m-%d ";
2462 long_time_format[1] = "%m-%d %H:%M";
2463 break;
2465 case locale_time_style:
2466 if (hard_locale (LC_TIME))
2468 for (int i = 0; i < 2; i++)
2469 long_time_format[i] =
2470 dcgettext (nullptr, long_time_format[i], LC_TIME);
2475 abformat_init ();
2478 return optind;
2481 /* Parse a string as part of the LS_COLORS variable; this may involve
2482 decoding all kinds of escape characters. If equals_end is set an
2483 unescaped equal sign ends the string, otherwise only a : or \0
2484 does. Set *OUTPUT_COUNT to the number of bytes output. Return
2485 true if successful.
2487 The resulting string is *not* null-terminated, but may contain
2488 embedded nulls.
2490 Note that both dest and src are char **; on return they point to
2491 the first free byte after the array and the character that ended
2492 the input string, respectively. */
2494 static bool
2495 get_funky_string (char **dest, char const **src, bool equals_end,
2496 size_t *output_count)
2498 char num; /* For numerical codes */
2499 size_t count; /* Something to count with */
2500 enum {
2501 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
2502 } state;
2503 char const *p;
2504 char *q;
2506 p = *src; /* We don't want to double-indirect */
2507 q = *dest; /* the whole darn time. */
2509 count = 0; /* No characters counted in yet. */
2510 num = 0;
2512 state = ST_GND; /* Start in ground state. */
2513 while (state < ST_END)
2515 switch (state)
2517 case ST_GND: /* Ground state (no escapes) */
2518 switch (*p)
2520 case ':':
2521 case '\0':
2522 state = ST_END; /* End of string */
2523 break;
2524 case '\\':
2525 state = ST_BACKSLASH; /* Backslash escape sequence */
2526 ++p;
2527 break;
2528 case '^':
2529 state = ST_CARET; /* Caret escape */
2530 ++p;
2531 break;
2532 case '=':
2533 if (equals_end)
2535 state = ST_END; /* End */
2536 break;
2538 FALLTHROUGH;
2539 default:
2540 *(q++) = *(p++);
2541 ++count;
2542 break;
2544 break;
2546 case ST_BACKSLASH: /* Backslash escaped character */
2547 switch (*p)
2549 case '0':
2550 case '1':
2551 case '2':
2552 case '3':
2553 case '4':
2554 case '5':
2555 case '6':
2556 case '7':
2557 state = ST_OCTAL; /* Octal sequence */
2558 num = *p - '0';
2559 break;
2560 case 'x':
2561 case 'X':
2562 state = ST_HEX; /* Hex sequence */
2563 num = 0;
2564 break;
2565 case 'a': /* Bell */
2566 num = '\a';
2567 break;
2568 case 'b': /* Backspace */
2569 num = '\b';
2570 break;
2571 case 'e': /* Escape */
2572 num = 27;
2573 break;
2574 case 'f': /* Form feed */
2575 num = '\f';
2576 break;
2577 case 'n': /* Newline */
2578 num = '\n';
2579 break;
2580 case 'r': /* Carriage return */
2581 num = '\r';
2582 break;
2583 case 't': /* Tab */
2584 num = '\t';
2585 break;
2586 case 'v': /* Vtab */
2587 num = '\v';
2588 break;
2589 case '?': /* Delete */
2590 num = 127;
2591 break;
2592 case '_': /* Space */
2593 num = ' ';
2594 break;
2595 case '\0': /* End of string */
2596 state = ST_ERROR; /* Error! */
2597 break;
2598 default: /* Escaped character like \ ^ : = */
2599 num = *p;
2600 break;
2602 if (state == ST_BACKSLASH)
2604 *(q++) = num;
2605 ++count;
2606 state = ST_GND;
2608 ++p;
2609 break;
2611 case ST_OCTAL: /* Octal sequence */
2612 if (*p < '0' || *p > '7')
2614 *(q++) = num;
2615 ++count;
2616 state = ST_GND;
2618 else
2619 num = (num << 3) + (*(p++) - '0');
2620 break;
2622 case ST_HEX: /* Hex sequence */
2623 switch (*p)
2625 case '0':
2626 case '1':
2627 case '2':
2628 case '3':
2629 case '4':
2630 case '5':
2631 case '6':
2632 case '7':
2633 case '8':
2634 case '9':
2635 num = (num << 4) + (*(p++) - '0');
2636 break;
2637 case 'a':
2638 case 'b':
2639 case 'c':
2640 case 'd':
2641 case 'e':
2642 case 'f':
2643 num = (num << 4) + (*(p++) - 'a') + 10;
2644 break;
2645 case 'A':
2646 case 'B':
2647 case 'C':
2648 case 'D':
2649 case 'E':
2650 case 'F':
2651 num = (num << 4) + (*(p++) - 'A') + 10;
2652 break;
2653 default:
2654 *(q++) = num;
2655 ++count;
2656 state = ST_GND;
2657 break;
2659 break;
2661 case ST_CARET: /* Caret escape */
2662 state = ST_GND; /* Should be the next state... */
2663 if (*p >= '@' && *p <= '~')
2665 *(q++) = *(p++) & 037;
2666 ++count;
2668 else if (*p == '?')
2670 *(q++) = 127;
2671 ++count;
2673 else
2674 state = ST_ERROR;
2675 break;
2677 default:
2678 unreachable ();
2682 *dest = q;
2683 *src = p;
2684 *output_count = count;
2686 return state != ST_ERROR;
2689 enum parse_state
2691 PS_START = 1,
2692 PS_2,
2693 PS_3,
2694 PS_4,
2695 PS_DONE,
2696 PS_FAIL
2700 /* Check if the content of TERM is a valid name in dircolors. */
2702 static bool
2703 known_term_type (void)
2705 char const *term = getenv ("TERM");
2706 if (! term || ! *term)
2707 return false;
2709 char const *line = G_line;
2710 while (line - G_line < sizeof (G_line))
2712 if (STRNCMP_LIT (line, "TERM ") == 0)
2714 if (fnmatch (line + 5, term, 0) == 0)
2715 return true;
2717 line += strlen (line) + 1;
2720 return false;
2723 static void
2724 parse_ls_color (void)
2726 char const *p; /* Pointer to character being parsed */
2727 char *buf; /* color_buf buffer pointer */
2728 int ind_no; /* Indicator number */
2729 char label[3]; /* Indicator label */
2730 struct color_ext_type *ext; /* Extension we are working on */
2732 if ((p = getenv ("LS_COLORS")) == nullptr || *p == '\0')
2734 /* LS_COLORS takes precedence, but if that's not set then
2735 honor the COLORTERM and TERM env variables so that
2736 we only go with the internal ANSI color codes if the
2737 former is non empty or the latter is set to a known value. */
2738 char const *colorterm = getenv ("COLORTERM");
2739 if (! (colorterm && *colorterm) && ! known_term_type ())
2740 print_with_color = false;
2741 return;
2744 ext = nullptr;
2745 strcpy (label, "??");
2747 /* This is an overly conservative estimate, but any possible
2748 LS_COLORS string will *not* generate a color_buf longer than
2749 itself, so it is a safe way of allocating a buffer in
2750 advance. */
2751 buf = color_buf = xstrdup (p);
2753 enum parse_state state = PS_START;
2754 while (true)
2756 switch (state)
2758 case PS_START: /* First label character */
2759 switch (*p)
2761 case ':':
2762 ++p;
2763 break;
2765 case '*':
2766 /* Allocate new extension block and add to head of
2767 linked list (this way a later definition will
2768 override an earlier one, which can be useful for
2769 having terminal-specific defs override global). */
2771 ext = xmalloc (sizeof *ext);
2772 ext->next = color_ext_list;
2773 color_ext_list = ext;
2774 ext->exact_match = false;
2776 ++p;
2777 ext->ext.string = buf;
2779 state = (get_funky_string (&buf, &p, true, &ext->ext.len)
2780 ? PS_4 : PS_FAIL);
2781 break;
2783 case '\0':
2784 state = PS_DONE; /* Done! */
2785 goto done;
2787 default: /* Assume it is file type label */
2788 label[0] = *(p++);
2789 state = PS_2;
2790 break;
2792 break;
2794 case PS_2: /* Second label character */
2795 if (*p)
2797 label[1] = *(p++);
2798 state = PS_3;
2800 else
2801 state = PS_FAIL; /* Error */
2802 break;
2804 case PS_3: /* Equal sign after indicator label */
2805 state = PS_FAIL; /* Assume failure... */
2806 if (*(p++) == '=')/* It *should* be... */
2808 for (ind_no = 0; indicator_name[ind_no] != nullptr; ++ind_no)
2810 if (STREQ (label, indicator_name[ind_no]))
2812 color_indicator[ind_no].string = buf;
2813 state = (get_funky_string (&buf, &p, false,
2814 &color_indicator[ind_no].len)
2815 ? PS_START : PS_FAIL);
2816 break;
2819 if (state == PS_FAIL)
2820 error (0, 0, _("unrecognized prefix: %s"), quote (label));
2822 break;
2824 case PS_4: /* Equal sign after *.ext */
2825 if (*(p++) == '=')
2827 ext->seq.string = buf;
2828 state = (get_funky_string (&buf, &p, false, &ext->seq.len)
2829 ? PS_START : PS_FAIL);
2831 else
2832 state = PS_FAIL;
2833 break;
2835 case PS_FAIL:
2836 goto done;
2838 default:
2839 affirm (false);
2842 done:
2844 if (state == PS_FAIL)
2846 struct color_ext_type *e;
2847 struct color_ext_type *e2;
2849 error (0, 0,
2850 _("unparsable value for LS_COLORS environment variable"));
2851 free (color_buf);
2852 for (e = color_ext_list; e != nullptr; /* empty */)
2854 e2 = e;
2855 e = e->next;
2856 free (e2);
2858 print_with_color = false;
2860 else
2862 /* Postprocess list to set EXACT_MATCH on entries where there are
2863 different cased extensions with separate sequences defined.
2864 Also set ext.len to SIZE_MAX on any entries that can't
2865 match due to precedence, to avoid redundant string compares. */
2866 struct color_ext_type *e1;
2868 for (e1 = color_ext_list; e1 != nullptr; e1 = e1->next)
2870 struct color_ext_type *e2;
2871 bool case_ignored = false;
2873 for (e2 = e1->next; e2 != nullptr; e2 = e2->next)
2875 if (e2->ext.len < SIZE_MAX && e1->ext.len == e2->ext.len)
2877 if (memcmp (e1->ext.string, e2->ext.string, e1->ext.len) == 0)
2878 e2->ext.len = SIZE_MAX; /* Ignore */
2879 else if (c_strncasecmp (e1->ext.string, e2->ext.string,
2880 e1->ext.len) == 0)
2882 if (case_ignored)
2884 e2->ext.len = SIZE_MAX; /* Ignore */
2886 else if (e1->seq.len == e2->seq.len
2887 && memcmp (e1->seq.string, e2->seq.string,
2888 e1->seq.len) == 0)
2890 e2->ext.len = SIZE_MAX; /* Ignore */
2891 case_ignored = true; /* Ignore all subsequent */
2893 else
2895 e1->exact_match = true;
2896 e2->exact_match = true;
2904 if (color_indicator[C_LINK].len == 6
2905 && !STRNCMP_LIT (color_indicator[C_LINK].string, "target"))
2906 color_symlink_as_referent = true;
2909 /* Return the quoting style specified by the environment variable
2910 QUOTING_STYLE if set and valid, -1 otherwise. */
2912 static int
2913 getenv_quoting_style (void)
2915 char const *q_style = getenv ("QUOTING_STYLE");
2916 if (!q_style)
2917 return -1;
2918 int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
2919 if (i < 0)
2921 error (0, 0,
2922 _("ignoring invalid value"
2923 " of environment variable QUOTING_STYLE: %s"),
2924 quote (q_style));
2925 return -1;
2927 return quoting_style_vals[i];
2930 /* Set the exit status to report a failure. If SERIOUS, it is a
2931 serious failure; otherwise, it is merely a minor problem. */
2933 static void
2934 set_exit_status (bool serious)
2936 if (serious)
2937 exit_status = LS_FAILURE;
2938 else if (exit_status == EXIT_SUCCESS)
2939 exit_status = LS_MINOR_PROBLEM;
2942 /* Assuming a failure is serious if SERIOUS, use the printf-style
2943 MESSAGE to report the failure to access a file named FILE. Assume
2944 errno is set appropriately for the failure. */
2946 static void
2947 file_failure (bool serious, char const *message, char const *file)
2949 error (0, errno, message, quoteaf (file));
2950 set_exit_status (serious);
2953 /* Request that the directory named NAME have its contents listed later.
2954 If REALNAME is nonzero, it will be used instead of NAME when the
2955 directory name is printed. This allows symbolic links to directories
2956 to be treated as regular directories but still be listed under their
2957 real names. NAME == nullptr is used to insert a marker entry for the
2958 directory named in REALNAME.
2959 If NAME is non-null, we use its dev/ino information to save
2960 a call to stat -- when doing a recursive (-R) traversal.
2961 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2963 static void
2964 queue_directory (char const *name, char const *realname, bool command_line_arg)
2966 struct pending *new = xmalloc (sizeof *new);
2967 new->realname = realname ? xstrdup (realname) : nullptr;
2968 new->name = name ? xstrdup (name) : nullptr;
2969 new->command_line_arg = command_line_arg;
2970 new->next = pending_dirs;
2971 pending_dirs = new;
2974 /* Read directory NAME, and list the files in it.
2975 If REALNAME is nonzero, print its name instead of NAME;
2976 this is used for symbolic links to directories.
2977 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2979 static void
2980 print_dir (char const *name, char const *realname, bool command_line_arg)
2982 DIR *dirp;
2983 struct dirent *next;
2984 uintmax_t total_blocks = 0;
2985 static bool first = true;
2987 errno = 0;
2988 dirp = opendir (name);
2989 if (!dirp)
2991 file_failure (command_line_arg, _("cannot open directory %s"), name);
2992 return;
2995 if (LOOP_DETECT)
2997 struct stat dir_stat;
2998 int fd = dirfd (dirp);
3000 /* If dirfd failed, endure the overhead of stat'ing by path */
3001 if ((0 <= fd
3002 ? fstat_for_ino (fd, &dir_stat)
3003 : stat_for_ino (name, &dir_stat)) < 0)
3005 file_failure (command_line_arg,
3006 _("cannot determine device and inode of %s"), name);
3007 closedir (dirp);
3008 return;
3011 /* If we've already visited this dev/inode pair, warn that
3012 we've found a loop, and do not process this directory. */
3013 if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
3015 error (0, 0, _("%s: not listing already-listed directory"),
3016 quotef (name));
3017 closedir (dirp);
3018 set_exit_status (true);
3019 return;
3022 dev_ino_push (dir_stat.st_dev, dir_stat.st_ino);
3025 clear_files ();
3027 if (recursive || print_dir_name)
3029 if (!first)
3030 dired_outbyte ('\n');
3031 first = false;
3032 dired_indent ();
3034 char *absolute_name = nullptr;
3035 if (print_hyperlink)
3037 absolute_name = canonicalize_filename_mode (name, CAN_MISSING);
3038 if (! absolute_name)
3039 file_failure (command_line_arg,
3040 _("error canonicalizing %s"), name);
3042 quote_name (realname ? realname : name, dirname_quoting_options, -1,
3043 nullptr, true, &subdired_obstack, absolute_name);
3045 free (absolute_name);
3047 dired_outstring (":\n");
3050 /* Read the directory entries, and insert the subfiles into the 'cwd_file'
3051 table. */
3053 while (true)
3055 /* Set errno to zero so we can distinguish between a readdir failure
3056 and when readdir simply finds that there are no more entries. */
3057 errno = 0;
3058 next = readdir (dirp);
3059 /* Some readdir()s do not absorb ENOENT (dir deleted but open). */
3060 if (errno == ENOENT)
3061 errno = 0;
3062 if (next)
3064 if (! file_ignored (next->d_name))
3066 enum filetype type = unknown;
3068 #if HAVE_STRUCT_DIRENT_D_TYPE
3069 switch (next->d_type)
3071 case DT_BLK: type = blockdev; break;
3072 case DT_CHR: type = chardev; break;
3073 case DT_DIR: type = directory; break;
3074 case DT_FIFO: type = fifo; break;
3075 case DT_LNK: type = symbolic_link; break;
3076 case DT_REG: type = normal; break;
3077 case DT_SOCK: type = sock; break;
3078 # ifdef DT_WHT
3079 case DT_WHT: type = whiteout; break;
3080 # endif
3082 #endif
3083 total_blocks += gobble_file (next->d_name, type,
3084 RELIABLE_D_INO (next),
3085 false, name);
3087 /* In this narrow case, print out each name right away, so
3088 ls uses constant memory while processing the entries of
3089 this directory. Useful when there are many (millions)
3090 of entries in a directory. */
3091 if (format == one_per_line && sort_type == sort_none
3092 && !print_block_size && !recursive)
3094 /* We must call sort_files in spite of
3095 "sort_type == sort_none" for its initialization
3096 of the sorted_file vector. */
3097 sort_files ();
3098 print_current_files ();
3099 clear_files ();
3103 else if (errno != 0)
3105 file_failure (command_line_arg, _("reading directory %s"), name);
3106 if (errno != EOVERFLOW)
3107 break;
3109 else
3110 break;
3112 /* When processing a very large directory, and since we've inhibited
3113 interrupts, this loop would take so long that ls would be annoyingly
3114 uninterruptible. This ensures that it handles signals promptly. */
3115 process_signals ();
3118 if (closedir (dirp) != 0)
3120 file_failure (command_line_arg, _("closing directory %s"), name);
3121 /* Don't return; print whatever we got. */
3124 /* Sort the directory contents. */
3125 sort_files ();
3127 /* If any member files are subdirectories, perhaps they should have their
3128 contents listed rather than being mentioned here as files. */
3130 if (recursive)
3131 extract_dirs_from_files (name, false);
3133 if (format == long_format || print_block_size)
3135 char buf[LONGEST_HUMAN_READABLE + 3];
3136 char *p = human_readable (total_blocks, buf + 1, human_output_opts,
3137 ST_NBLOCKSIZE, output_block_size);
3138 char *pend = p + strlen (p);
3139 *--p = ' ';
3140 *pend++ = eolbyte;
3141 dired_indent ();
3142 dired_outstring (_("total"));
3143 dired_outbuf (p, pend - p);
3146 if (cwd_n_used)
3147 print_current_files ();
3150 /* Add 'pattern' to the list of patterns for which files that match are
3151 not listed. */
3153 static void
3154 add_ignore_pattern (char const *pattern)
3156 struct ignore_pattern *ignore;
3158 ignore = xmalloc (sizeof *ignore);
3159 ignore->pattern = pattern;
3160 /* Add it to the head of the linked list. */
3161 ignore->next = ignore_patterns;
3162 ignore_patterns = ignore;
3165 /* Return true if one of the PATTERNS matches FILE. */
3167 static bool
3168 patterns_match (struct ignore_pattern const *patterns, char const *file)
3170 struct ignore_pattern const *p;
3171 for (p = patterns; p; p = p->next)
3172 if (fnmatch (p->pattern, file, FNM_PERIOD) == 0)
3173 return true;
3174 return false;
3177 /* Return true if FILE should be ignored. */
3179 static bool
3180 file_ignored (char const *name)
3182 return ((ignore_mode != IGNORE_MINIMAL
3183 && name[0] == '.'
3184 && (ignore_mode == IGNORE_DEFAULT || ! name[1 + (name[1] == '.')]))
3185 || (ignore_mode == IGNORE_DEFAULT
3186 && patterns_match (hide_patterns, name))
3187 || patterns_match (ignore_patterns, name));
3190 /* POSIX requires that a file size be printed without a sign, even
3191 when negative. Assume the typical case where negative sizes are
3192 actually positive values that have wrapped around. */
3194 static uintmax_t
3195 unsigned_file_size (off_t size)
3197 return size + (size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
3200 #ifdef HAVE_CAP
3201 /* Return true if NAME has a capability (see linux/capability.h) */
3202 static bool
3203 has_capability (char const *name)
3205 char *result;
3206 bool has_cap;
3208 cap_t cap_d = cap_get_file (name);
3209 if (cap_d == nullptr)
3210 return false;
3212 result = cap_to_text (cap_d, nullptr);
3213 cap_free (cap_d);
3214 if (!result)
3215 return false;
3217 /* check if human-readable capability string is empty */
3218 has_cap = !!*result;
3220 cap_free (result);
3221 return has_cap;
3223 #else
3224 static bool
3225 has_capability (MAYBE_UNUSED char const *name)
3227 errno = ENOTSUP;
3228 return false;
3230 #endif
3232 /* Enter and remove entries in the table 'cwd_file'. */
3234 static void
3235 free_ent (struct fileinfo *f)
3237 free (f->name);
3238 free (f->linkname);
3239 free (f->absolute_name);
3240 if (f->scontext != UNKNOWN_SECURITY_CONTEXT)
3242 if (is_smack_enabled ())
3243 free (f->scontext);
3244 else
3245 freecon (f->scontext);
3249 /* Empty the table of files. */
3250 static void
3251 clear_files (void)
3253 for (size_t i = 0; i < cwd_n_used; i++)
3255 struct fileinfo *f = sorted_file[i];
3256 free_ent (f);
3259 cwd_n_used = 0;
3260 cwd_some_quoted = false;
3261 any_has_acl = false;
3262 inode_number_width = 0;
3263 block_size_width = 0;
3264 nlink_width = 0;
3265 owner_width = 0;
3266 group_width = 0;
3267 author_width = 0;
3268 scontext_width = 0;
3269 major_device_number_width = 0;
3270 minor_device_number_width = 0;
3271 file_size_width = 0;
3274 /* Return true if ERR implies lack-of-support failure by a
3275 getxattr-calling function like getfilecon or file_has_acl. */
3276 static bool
3277 errno_unsupported (int err)
3279 return (err == EINVAL || err == ENOSYS || is_ENOTSUP (err));
3282 /* Cache *getfilecon failure, when it's trivial to do so.
3283 Like getfilecon/lgetfilecon, but when F's st_dev says it's doesn't
3284 support getting the security context, fail with ENOTSUP immediately. */
3285 static int
3286 getfilecon_cache (char const *file, struct fileinfo *f, bool deref)
3288 /* st_dev of the most recently processed device for which we've
3289 found that [l]getfilecon fails indicating lack of support. */
3290 static dev_t unsupported_device;
3292 if (f->stat.st_dev == unsupported_device)
3294 errno = ENOTSUP;
3295 return -1;
3297 int r = 0;
3298 #ifdef HAVE_SMACK
3299 if (is_smack_enabled ())
3300 r = smack_new_label_from_path (file, "security.SMACK64", deref,
3301 &f->scontext);
3302 else
3303 #endif
3304 r = (deref
3305 ? getfilecon (file, &f->scontext)
3306 : lgetfilecon (file, &f->scontext));
3307 if (r < 0 && errno_unsupported (errno))
3308 unsupported_device = f->stat.st_dev;
3309 return r;
3312 /* Cache file_has_acl failure, when it's trivial to do.
3313 Like file_has_acl, but when F's st_dev says it's on a file
3314 system lacking ACL support, return 0 with ENOTSUP immediately. */
3315 static int
3316 file_has_acl_cache (char const *file, struct fileinfo *f)
3318 /* st_dev of the most recently processed device for which we've
3319 found that file_has_acl fails indicating lack of support. */
3320 static dev_t unsupported_device;
3322 if (f->stat.st_dev == unsupported_device)
3324 errno = ENOTSUP;
3325 return 0;
3328 /* Zero errno so that we can distinguish between two 0-returning cases:
3329 "has-ACL-support, but only a default ACL" and "no ACL support". */
3330 errno = 0;
3331 int n = file_has_acl (file, &f->stat);
3332 if (n <= 0 && errno_unsupported (errno))
3333 unsupported_device = f->stat.st_dev;
3334 return n;
3337 /* Cache has_capability failure, when it's trivial to do.
3338 Like has_capability, but when F's st_dev says it's on a file
3339 system lacking capability support, return 0 with ENOTSUP immediately. */
3340 static bool
3341 has_capability_cache (char const *file, struct fileinfo *f)
3343 /* st_dev of the most recently processed device for which we've
3344 found that has_capability fails indicating lack of support. */
3345 static dev_t unsupported_device;
3347 if (f->stat.st_dev == unsupported_device)
3349 errno = ENOTSUP;
3350 return 0;
3353 bool b = has_capability (file);
3354 if ( !b && errno_unsupported (errno))
3355 unsupported_device = f->stat.st_dev;
3356 return b;
3359 static bool
3360 needs_quoting (char const *name)
3362 char test[2];
3363 size_t len = quotearg_buffer (test, sizeof test , name, -1,
3364 filename_quoting_options);
3365 return *name != *test || strlen (name) != len;
3368 /* Add a file to the current table of files.
3369 Verify that the file exists, and print an error message if it does not.
3370 Return the number of blocks that the file occupies. */
3371 static uintmax_t
3372 gobble_file (char const *name, enum filetype type, ino_t inode,
3373 bool command_line_arg, char const *dirname)
3375 uintmax_t blocks = 0;
3376 struct fileinfo *f;
3378 /* An inode value prior to gobble_file necessarily came from readdir,
3379 which is not used for command line arguments. */
3380 affirm (! command_line_arg || inode == NOT_AN_INODE_NUMBER);
3382 if (cwd_n_used == cwd_n_alloc)
3384 cwd_file = xnrealloc (cwd_file, cwd_n_alloc, 2 * sizeof *cwd_file);
3385 cwd_n_alloc *= 2;
3388 f = &cwd_file[cwd_n_used];
3389 memset (f, '\0', sizeof *f);
3390 f->stat.st_ino = inode;
3391 f->filetype = type;
3393 f->quoted = -1;
3394 if ((! cwd_some_quoted) && align_variable_outer_quotes)
3396 /* Determine if any quoted for padding purposes. */
3397 f->quoted = needs_quoting (name);
3398 if (f->quoted)
3399 cwd_some_quoted = 1;
3402 if (command_line_arg
3403 || print_hyperlink
3404 || format_needs_stat
3405 /* When coloring a directory (we may know the type from
3406 direct.d_type), we have to stat it in order to indicate
3407 sticky and/or other-writable attributes. */
3408 || (type == directory && print_with_color
3409 && (is_colored (C_OTHER_WRITABLE)
3410 || is_colored (C_STICKY)
3411 || is_colored (C_STICKY_OTHER_WRITABLE)))
3412 /* When dereferencing symlinks, the inode and type must come from
3413 stat, but readdir provides the inode and type of lstat. */
3414 || ((print_inode || format_needs_type)
3415 && (type == symbolic_link || type == unknown)
3416 && (dereference == DEREF_ALWAYS
3417 || color_symlink_as_referent || check_symlink_mode))
3418 /* Command line dereferences are already taken care of by the above
3419 assertion that the inode number is not yet known. */
3420 || (print_inode && inode == NOT_AN_INODE_NUMBER)
3421 || (format_needs_type
3422 && (type == unknown || command_line_arg
3423 /* --indicator-style=classify (aka -F)
3424 requires that we stat each regular file
3425 to see if it's executable. */
3426 || (type == normal && (indicator_style == classify
3427 /* This is so that --color ends up
3428 highlighting files with these mode
3429 bits set even when options like -F are
3430 not specified. Note we do a redundant
3431 stat in the very unlikely case where
3432 C_CAP is set but not the others. */
3433 || (print_with_color
3434 && (is_colored (C_EXEC)
3435 || is_colored (C_SETUID)
3436 || is_colored (C_SETGID)
3437 || is_colored (C_CAP)))
3438 )))))
3441 /* Absolute name of this file. */
3442 char *full_name;
3443 bool do_deref;
3444 int err;
3446 if (name[0] == '/' || dirname[0] == 0)
3447 full_name = (char *) name;
3448 else
3450 full_name = alloca (strlen (name) + strlen (dirname) + 2);
3451 attach (full_name, dirname, name);
3454 if (print_hyperlink)
3456 f->absolute_name = canonicalize_filename_mode (full_name,
3457 CAN_MISSING);
3458 if (! f->absolute_name)
3459 file_failure (command_line_arg,
3460 _("error canonicalizing %s"), full_name);
3463 switch (dereference)
3465 case DEREF_ALWAYS:
3466 err = do_stat (full_name, &f->stat);
3467 do_deref = true;
3468 break;
3470 case DEREF_COMMAND_LINE_ARGUMENTS:
3471 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
3472 if (command_line_arg)
3474 bool need_lstat;
3475 err = do_stat (full_name, &f->stat);
3476 do_deref = true;
3478 if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
3479 break;
3481 need_lstat = (err < 0
3482 ? (errno == ENOENT || errno == ELOOP)
3483 : ! S_ISDIR (f->stat.st_mode));
3484 if (!need_lstat)
3485 break;
3487 /* stat failed because of ENOENT || ELOOP, maybe indicating a
3488 non-traversable symlink. Or stat succeeded,
3489 FULL_NAME does not refer to a directory,
3490 and --dereference-command-line-symlink-to-dir is in effect.
3491 Fall through so that we call lstat instead. */
3493 FALLTHROUGH;
3495 default: /* DEREF_NEVER */
3496 err = do_lstat (full_name, &f->stat);
3497 do_deref = false;
3498 break;
3501 if (err != 0)
3503 /* Failure to stat a command line argument leads to
3504 an exit status of 2. For other files, stat failure
3505 provokes an exit status of 1. */
3506 file_failure (command_line_arg,
3507 _("cannot access %s"), full_name);
3509 f->scontext = UNKNOWN_SECURITY_CONTEXT;
3511 if (command_line_arg)
3512 return 0;
3514 f->name = xstrdup (name);
3515 cwd_n_used++;
3517 return 0;
3520 f->stat_ok = true;
3522 /* Note has_capability() adds around 30% runtime to 'ls --color' */
3523 if ((type == normal || S_ISREG (f->stat.st_mode))
3524 && print_with_color && is_colored (C_CAP))
3525 f->has_capability = has_capability_cache (full_name, f);
3527 if (format == long_format || print_scontext)
3529 bool have_scontext = false;
3530 bool have_acl = false;
3531 int attr_len = getfilecon_cache (full_name, f, do_deref);
3532 err = (attr_len < 0);
3534 if (err == 0)
3536 if (is_smack_enabled ())
3537 have_scontext = ! STREQ ("_", f->scontext);
3538 else
3539 have_scontext = ! STREQ ("unlabeled", f->scontext);
3541 else
3543 f->scontext = UNKNOWN_SECURITY_CONTEXT;
3545 /* When requesting security context information, don't make
3546 ls fail just because the file (even a command line argument)
3547 isn't on the right type of file system. I.e., a getfilecon
3548 failure isn't in the same class as a stat failure. */
3549 if (is_ENOTSUP (errno) || errno == ENODATA)
3550 err = 0;
3553 if (err == 0 && format == long_format)
3555 int n = file_has_acl_cache (full_name, f);
3556 err = (n < 0);
3557 have_acl = (0 < n);
3560 f->acl_type = (!have_scontext && !have_acl
3561 ? ACL_T_NONE
3562 : (have_scontext && !have_acl
3563 ? ACL_T_LSM_CONTEXT_ONLY
3564 : ACL_T_YES));
3565 any_has_acl |= f->acl_type != ACL_T_NONE;
3567 if (err)
3568 error (0, errno, "%s", quotef (full_name));
3571 if (S_ISLNK (f->stat.st_mode)
3572 && (format == long_format || check_symlink_mode))
3574 struct stat linkstats;
3576 get_link_name (full_name, f, command_line_arg);
3578 /* Use the slower quoting path for this entry, though
3579 don't update CWD_SOME_QUOTED since alignment not affected. */
3580 if (f->linkname && f->quoted == 0 && needs_quoting (f->linkname))
3581 f->quoted = -1;
3583 /* Avoid following symbolic links when possible, i.e., when
3584 they won't be traced and when no indicator is needed. */
3585 if (f->linkname
3586 && (file_type <= indicator_style || check_symlink_mode)
3587 && stat_for_mode (full_name, &linkstats) == 0)
3589 f->linkok = true;
3590 f->linkmode = linkstats.st_mode;
3594 if (S_ISLNK (f->stat.st_mode))
3595 f->filetype = symbolic_link;
3596 else if (S_ISDIR (f->stat.st_mode))
3598 if (command_line_arg && !immediate_dirs)
3599 f->filetype = arg_directory;
3600 else
3601 f->filetype = directory;
3603 else
3604 f->filetype = normal;
3606 blocks = STP_NBLOCKS (&f->stat);
3607 if (format == long_format || print_block_size)
3609 char buf[LONGEST_HUMAN_READABLE + 1];
3610 int len = mbswidth (human_readable (blocks, buf, human_output_opts,
3611 ST_NBLOCKSIZE, output_block_size),
3612 MBSWIDTH_FLAGS);
3613 if (block_size_width < len)
3614 block_size_width = len;
3617 if (format == long_format)
3619 if (print_owner)
3621 int len = format_user_width (f->stat.st_uid);
3622 if (owner_width < len)
3623 owner_width = len;
3626 if (print_group)
3628 int len = format_group_width (f->stat.st_gid);
3629 if (group_width < len)
3630 group_width = len;
3633 if (print_author)
3635 int len = format_user_width (f->stat.st_author);
3636 if (author_width < len)
3637 author_width = len;
3641 if (print_scontext)
3643 int len = strlen (f->scontext);
3644 if (scontext_width < len)
3645 scontext_width = len;
3648 if (format == long_format)
3650 char b[INT_BUFSIZE_BOUND (uintmax_t)];
3651 int b_len = strlen (umaxtostr (f->stat.st_nlink, b));
3652 if (nlink_width < b_len)
3653 nlink_width = b_len;
3655 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
3657 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
3658 int len = strlen (umaxtostr (major (f->stat.st_rdev), buf));
3659 if (major_device_number_width < len)
3660 major_device_number_width = len;
3661 len = strlen (umaxtostr (minor (f->stat.st_rdev), buf));
3662 if (minor_device_number_width < len)
3663 minor_device_number_width = len;
3664 len = major_device_number_width + 2 + minor_device_number_width;
3665 if (file_size_width < len)
3666 file_size_width = len;
3668 else
3670 char buf[LONGEST_HUMAN_READABLE + 1];
3671 uintmax_t size = unsigned_file_size (f->stat.st_size);
3672 int len = mbswidth (human_readable (size, buf,
3673 file_human_output_opts,
3674 1, file_output_block_size),
3675 MBSWIDTH_FLAGS);
3676 if (file_size_width < len)
3677 file_size_width = len;
3682 if (print_inode)
3684 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
3685 int len = strlen (umaxtostr (f->stat.st_ino, buf));
3686 if (inode_number_width < len)
3687 inode_number_width = len;
3690 f->name = xstrdup (name);
3691 cwd_n_used++;
3693 return blocks;
3696 /* Return true if F refers to a directory. */
3697 static bool
3698 is_directory (const struct fileinfo *f)
3700 return f->filetype == directory || f->filetype == arg_directory;
3703 /* Return true if F refers to a (symlinked) directory. */
3704 static bool
3705 is_linked_directory (const struct fileinfo *f)
3707 return f->filetype == directory || f->filetype == arg_directory
3708 || S_ISDIR (f->linkmode);
3711 /* Put the name of the file that FILENAME is a symbolic link to
3712 into the LINKNAME field of 'f'. COMMAND_LINE_ARG indicates whether
3713 FILENAME is a command-line argument. */
3715 static void
3716 get_link_name (char const *filename, struct fileinfo *f, bool command_line_arg)
3718 f->linkname = areadlink_with_size (filename, f->stat.st_size);
3719 if (f->linkname == nullptr)
3720 file_failure (command_line_arg, _("cannot read symbolic link %s"),
3721 filename);
3724 /* Return true if the last component of NAME is '.' or '..'
3725 This is so we don't try to recurse on '././././. ...' */
3727 static bool
3728 basename_is_dot_or_dotdot (char const *name)
3730 char const *base = last_component (name);
3731 return dot_or_dotdot (base);
3734 /* Remove any entries from CWD_FILE that are for directories,
3735 and queue them to be listed as directories instead.
3736 DIRNAME is the prefix to prepend to each dirname
3737 to make it correct relative to ls's working dir;
3738 if it is null, no prefix is needed and "." and ".." should not be ignored.
3739 If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
3740 This is desirable when processing directories recursively. */
3742 static void
3743 extract_dirs_from_files (char const *dirname, bool command_line_arg)
3745 size_t i;
3746 size_t j;
3747 bool ignore_dot_and_dot_dot = (dirname != nullptr);
3749 if (dirname && LOOP_DETECT)
3751 /* Insert a marker entry first. When we dequeue this marker entry,
3752 we'll know that DIRNAME has been processed and may be removed
3753 from the set of active directories. */
3754 queue_directory (nullptr, dirname, false);
3757 /* Queue the directories last one first, because queueing reverses the
3758 order. */
3759 for (i = cwd_n_used; i-- != 0; )
3761 struct fileinfo *f = sorted_file[i];
3763 if (is_directory (f)
3764 && (! ignore_dot_and_dot_dot
3765 || ! basename_is_dot_or_dotdot (f->name)))
3767 if (!dirname || f->name[0] == '/')
3768 queue_directory (f->name, f->linkname, command_line_arg);
3769 else
3771 char *name = file_name_concat (dirname, f->name, nullptr);
3772 queue_directory (name, f->linkname, command_line_arg);
3773 free (name);
3775 if (f->filetype == arg_directory)
3776 free_ent (f);
3780 /* Now delete the directories from the table, compacting all the remaining
3781 entries. */
3783 for (i = 0, j = 0; i < cwd_n_used; i++)
3785 struct fileinfo *f = sorted_file[i];
3786 sorted_file[j] = f;
3787 j += (f->filetype != arg_directory);
3789 cwd_n_used = j;
3792 /* Use strcoll to compare strings in this locale. If an error occurs,
3793 report an error and longjmp to failed_strcoll. */
3795 static jmp_buf failed_strcoll;
3797 static int
3798 xstrcoll (char const *a, char const *b)
3800 int diff;
3801 errno = 0;
3802 diff = strcoll (a, b);
3803 if (errno)
3805 error (0, errno, _("cannot compare file names %s and %s"),
3806 quote_n (0, a), quote_n (1, b));
3807 set_exit_status (false);
3808 longjmp (failed_strcoll, 1);
3810 return diff;
3813 /* Comparison routines for sorting the files. */
3815 typedef void const *V;
3816 typedef int (*qsortFunc)(V a, V b);
3818 /* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants. */
3819 static int
3820 dirfirst_check (struct fileinfo const *a, struct fileinfo const *b,
3821 int (*cmp) (V, V))
3823 int diff = is_linked_directory (b) - is_linked_directory (a);
3824 return diff ? diff : cmp (a, b);
3827 /* Define the 8 different sort function variants required for each sortkey.
3828 KEY_NAME is a token describing the sort key, e.g., ctime, atime, size.
3829 KEY_CMP_FUNC is a function to compare records based on that key, e.g.,
3830 ctime_cmp, atime_cmp, size_cmp. Append KEY_NAME to the string,
3831 '[rev_][x]str{cmp|coll}[_df]_', to create each function name. */
3832 #define DEFINE_SORT_FUNCTIONS(key_name, key_cmp_func) \
3833 /* direct, non-dirfirst versions */ \
3834 static int xstrcoll_##key_name (V a, V b) \
3835 { return key_cmp_func (a, b, xstrcoll); } \
3836 ATTRIBUTE_PURE static int strcmp_##key_name (V a, V b) \
3837 { return key_cmp_func (a, b, strcmp); } \
3839 /* reverse, non-dirfirst versions */ \
3840 static int rev_xstrcoll_##key_name (V a, V b) \
3841 { return key_cmp_func (b, a, xstrcoll); } \
3842 ATTRIBUTE_PURE static int rev_strcmp_##key_name (V a, V b) \
3843 { return key_cmp_func (b, a, strcmp); } \
3845 /* direct, dirfirst versions */ \
3846 static int xstrcoll_df_##key_name (V a, V b) \
3847 { return dirfirst_check (a, b, xstrcoll_##key_name); } \
3848 ATTRIBUTE_PURE static int strcmp_df_##key_name (V a, V b) \
3849 { return dirfirst_check (a, b, strcmp_##key_name); } \
3851 /* reverse, dirfirst versions */ \
3852 static int rev_xstrcoll_df_##key_name (V a, V b) \
3853 { return dirfirst_check (a, b, rev_xstrcoll_##key_name); } \
3854 ATTRIBUTE_PURE static int rev_strcmp_df_##key_name (V a, V b) \
3855 { return dirfirst_check (a, b, rev_strcmp_##key_name); }
3857 static int
3858 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
3859 int (*cmp) (char const *, char const *))
3861 int diff = timespec_cmp (get_stat_ctime (&b->stat),
3862 get_stat_ctime (&a->stat));
3863 return diff ? diff : cmp (a->name, b->name);
3866 static int
3867 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
3868 int (*cmp) (char const *, char const *))
3870 int diff = timespec_cmp (get_stat_mtime (&b->stat),
3871 get_stat_mtime (&a->stat));
3872 return diff ? diff : cmp (a->name, b->name);
3875 static int
3876 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
3877 int (*cmp) (char const *, char const *))
3879 int diff = timespec_cmp (get_stat_atime (&b->stat),
3880 get_stat_atime (&a->stat));
3881 return diff ? diff : cmp (a->name, b->name);
3884 static int
3885 cmp_btime (struct fileinfo const *a, struct fileinfo const *b,
3886 int (*cmp) (char const *, char const *))
3888 int diff = timespec_cmp (get_stat_btime (&b->stat),
3889 get_stat_btime (&a->stat));
3890 return diff ? diff : cmp (a->name, b->name);
3893 static int
3894 off_cmp (off_t a, off_t b)
3896 return (a > b) - (a < b);
3899 static int
3900 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
3901 int (*cmp) (char const *, char const *))
3903 int diff = off_cmp (b->stat.st_size, a->stat.st_size);
3904 return diff ? diff : cmp (a->name, b->name);
3907 static int
3908 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
3909 int (*cmp) (char const *, char const *))
3911 return cmp (a->name, b->name);
3914 /* Compare file extensions. Files with no extension are 'smallest'.
3915 If extensions are the same, compare by file names instead. */
3917 static int
3918 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
3919 int (*cmp) (char const *, char const *))
3921 char const *base1 = strrchr (a->name, '.');
3922 char const *base2 = strrchr (b->name, '.');
3923 int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
3924 return diff ? diff : cmp (a->name, b->name);
3927 /* Return the (cached) screen width,
3928 for the NAME associated with the passed fileinfo F. */
3930 static size_t
3931 fileinfo_name_width (struct fileinfo const *f)
3933 return f->width
3934 ? f->width
3935 : quote_name_width (f->name, filename_quoting_options, f->quoted);
3938 static int
3939 cmp_width (struct fileinfo const *a, struct fileinfo const *b,
3940 int (*cmp) (char const *, char const *))
3942 int diff = fileinfo_name_width (a) - fileinfo_name_width (b);
3943 return diff ? diff : cmp (a->name, b->name);
3946 DEFINE_SORT_FUNCTIONS (ctime, cmp_ctime)
3947 DEFINE_SORT_FUNCTIONS (mtime, cmp_mtime)
3948 DEFINE_SORT_FUNCTIONS (atime, cmp_atime)
3949 DEFINE_SORT_FUNCTIONS (btime, cmp_btime)
3950 DEFINE_SORT_FUNCTIONS (size, cmp_size)
3951 DEFINE_SORT_FUNCTIONS (name, cmp_name)
3952 DEFINE_SORT_FUNCTIONS (extension, cmp_extension)
3953 DEFINE_SORT_FUNCTIONS (width, cmp_width)
3955 /* Compare file versions.
3956 Unlike the other compare functions, cmp_version does not fail
3957 because filevercmp and strcmp do not fail; cmp_version uses strcmp
3958 instead of xstrcoll because filevercmp is locale-independent so
3959 strcmp is its appropriate secondary.
3961 All the other sort options need xstrcoll and strcmp variants,
3962 because they all use xstrcoll (either as the primary or secondary
3963 sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
3964 locale reasons. */
3965 static int
3966 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
3968 int diff = filevercmp (a->name, b->name);
3969 return diff ? diff : strcmp (a->name, b->name);
3972 static int
3973 xstrcoll_version (V a, V b)
3975 return cmp_version (a, b);
3977 static int
3978 rev_xstrcoll_version (V a, V b)
3980 return cmp_version (b, a);
3982 static int
3983 xstrcoll_df_version (V a, V b)
3985 return dirfirst_check (a, b, xstrcoll_version);
3987 static int
3988 rev_xstrcoll_df_version (V a, V b)
3990 return dirfirst_check (a, b, rev_xstrcoll_version);
3994 /* We have 2^3 different variants for each sort-key function
3995 (for 3 independent sort modes).
3996 The function pointers stored in this array must be dereferenced as:
3998 sort_variants[sort_key][use_strcmp][reverse][dirs_first]
4000 Note that the order in which sort keys are listed in the function pointer
4001 array below is defined by the order of the elements in the time_type and
4002 sort_type enums! */
4004 #define LIST_SORTFUNCTION_VARIANTS(key_name) \
4007 { xstrcoll_##key_name, xstrcoll_df_##key_name }, \
4008 { rev_xstrcoll_##key_name, rev_xstrcoll_df_##key_name }, \
4009 }, \
4011 { strcmp_##key_name, strcmp_df_##key_name }, \
4012 { rev_strcmp_##key_name, rev_strcmp_df_##key_name }, \
4016 static qsortFunc const sort_functions[][2][2][2] =
4018 LIST_SORTFUNCTION_VARIANTS (name),
4019 LIST_SORTFUNCTION_VARIANTS (extension),
4020 LIST_SORTFUNCTION_VARIANTS (width),
4021 LIST_SORTFUNCTION_VARIANTS (size),
4025 { xstrcoll_version, xstrcoll_df_version },
4026 { rev_xstrcoll_version, rev_xstrcoll_df_version },
4029 /* We use nullptr for the strcmp variants of version comparison
4030 since as explained in cmp_version definition, version comparison
4031 does not rely on xstrcoll, so it will never longjmp, and never
4032 need to try the strcmp fallback. */
4034 { nullptr, nullptr },
4035 { nullptr, nullptr },
4039 /* last are time sort functions */
4040 LIST_SORTFUNCTION_VARIANTS (mtime),
4041 LIST_SORTFUNCTION_VARIANTS (ctime),
4042 LIST_SORTFUNCTION_VARIANTS (atime),
4043 LIST_SORTFUNCTION_VARIANTS (btime)
4046 /* The number of sort keys is calculated as the sum of
4047 the number of elements in the sort_type enum (i.e., sort_numtypes)
4048 -2 because neither sort_time nor sort_none use entries themselves
4049 the number of elements in the time_type enum (i.e., time_numtypes)
4050 This is because when sort_type==sort_time, we have up to
4051 time_numtypes possible sort keys.
4053 This line verifies at compile-time that the array of sort functions has been
4054 initialized for all possible sort keys. */
4055 static_assert (ARRAY_CARDINALITY (sort_functions)
4056 == sort_numtypes - 2 + time_numtypes);
4058 /* Set up SORTED_FILE to point to the in-use entries in CWD_FILE, in order. */
4060 static void
4061 initialize_ordering_vector (void)
4063 for (size_t i = 0; i < cwd_n_used; i++)
4064 sorted_file[i] = &cwd_file[i];
4067 /* Cache values based on attributes global to all files. */
4069 static void
4070 update_current_files_info (void)
4072 /* Cache screen width of name, if needed multiple times. */
4073 if (sort_type == sort_width
4074 || (line_length && (format == many_per_line || format == horizontal)))
4076 size_t i;
4077 for (i = 0; i < cwd_n_used; i++)
4079 struct fileinfo *f = sorted_file[i];
4080 f->width = fileinfo_name_width (f);
4085 /* Sort the files now in the table. */
4087 static void
4088 sort_files (void)
4090 bool use_strcmp;
4092 if (sorted_file_alloc < cwd_n_used + cwd_n_used / 2)
4094 free (sorted_file);
4095 sorted_file = xnmalloc (cwd_n_used, 3 * sizeof *sorted_file);
4096 sorted_file_alloc = 3 * cwd_n_used;
4099 initialize_ordering_vector ();
4101 update_current_files_info ();
4103 if (sort_type == sort_none)
4104 return;
4106 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
4107 ignore strcoll failures, as a failing strcoll might be a
4108 comparison function that is not a total order, and if we ignored
4109 the failure this might cause qsort to dump core. */
4111 if (! setjmp (failed_strcoll))
4112 use_strcmp = false; /* strcoll() succeeded */
4113 else
4115 use_strcmp = true;
4116 affirm (sort_type != sort_version);
4117 initialize_ordering_vector ();
4120 /* When sort_type == sort_time, use time_type as subindex. */
4121 mpsort ((void const **) sorted_file, cwd_n_used,
4122 sort_functions[sort_type + (sort_type == sort_time ? time_type : 0)]
4123 [use_strcmp][sort_reverse]
4124 [directories_first]);
4127 /* List all the files now in the table. */
4129 static void
4130 print_current_files (void)
4132 size_t i;
4134 switch (format)
4136 case one_per_line:
4137 for (i = 0; i < cwd_n_used; i++)
4139 print_file_name_and_frills (sorted_file[i], 0);
4140 putchar (eolbyte);
4142 break;
4144 case many_per_line:
4145 if (! line_length)
4146 print_with_separator (' ');
4147 else
4148 print_many_per_line ();
4149 break;
4151 case horizontal:
4152 if (! line_length)
4153 print_with_separator (' ');
4154 else
4155 print_horizontal ();
4156 break;
4158 case with_commas:
4159 print_with_separator (',');
4160 break;
4162 case long_format:
4163 for (i = 0; i < cwd_n_used; i++)
4165 set_normal_color ();
4166 print_long_format (sorted_file[i]);
4167 dired_outbyte (eolbyte);
4169 break;
4173 /* Replace the first %b with precomputed aligned month names.
4174 Note on glibc-2.7 at least, this speeds up the whole 'ls -lU'
4175 process by around 17%, compared to letting strftime() handle the %b. */
4177 static size_t
4178 align_nstrftime (char *buf, size_t size, bool recent, struct tm const *tm,
4179 timezone_t tz, int ns)
4181 char const *nfmt = (use_abformat
4182 ? abformat[recent][tm->tm_mon]
4183 : long_time_format[recent]);
4184 return nstrftime (buf, size, nfmt, tm, tz, ns);
4187 /* Return the expected number of columns in a long-format timestamp,
4188 or zero if it cannot be calculated. */
4190 static int
4191 long_time_expected_width (void)
4193 static int width = -1;
4195 if (width < 0)
4197 time_t epoch = 0;
4198 struct tm tm;
4199 char buf[TIME_STAMP_LEN_MAXIMUM + 1];
4201 /* In case you're wondering if localtime_rz can fail with an input time_t
4202 value of 0, let's just say it's very unlikely, but not inconceivable.
4203 The TZ environment variable would have to specify a time zone that
4204 is 2**31-1900 years or more ahead of UTC. This could happen only on
4205 a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
4206 However, this is not possible with Solaris 10 or glibc-2.3.5, since
4207 their implementations limit the offset to 167:59 and 24:00, resp. */
4208 if (localtime_rz (localtz, &epoch, &tm))
4210 size_t len = align_nstrftime (buf, sizeof buf, false,
4211 &tm, localtz, 0);
4212 if (len != 0)
4213 width = mbsnwidth (buf, len, MBSWIDTH_FLAGS);
4216 if (width < 0)
4217 width = 0;
4220 return width;
4223 /* Print the user or group name NAME, with numeric id ID, using a
4224 print width of WIDTH columns. */
4226 static void
4227 format_user_or_group (char const *name, uintmax_t id, int width)
4229 if (name)
4231 int name_width = mbswidth (name, MBSWIDTH_FLAGS);
4232 int width_gap = name_width < 0 ? 0 : width - name_width;
4233 int pad = MAX (0, width_gap);
4234 dired_outstring (name);
4237 dired_outbyte (' ');
4238 while (pad--);
4240 else
4241 dired_pos += printf ("%*ju ", width, id);
4244 /* Print the name or id of the user with id U, using a print width of
4245 WIDTH. */
4247 static void
4248 format_user (uid_t u, int width, bool stat_ok)
4250 format_user_or_group (! stat_ok ? "?" :
4251 (numeric_ids ? nullptr : getuser (u)), u, width);
4254 /* Likewise, for groups. */
4256 static void
4257 format_group (gid_t g, int width, bool stat_ok)
4259 format_user_or_group (! stat_ok ? "?" :
4260 (numeric_ids ? nullptr : getgroup (g)), g, width);
4263 /* Return the number of columns that format_user_or_group will print,
4264 or -1 if unknown. */
4266 static int
4267 format_user_or_group_width (char const *name, uintmax_t id)
4269 return (name
4270 ? mbswidth (name, MBSWIDTH_FLAGS)
4271 : snprintf (nullptr, 0, "%ju", id));
4274 /* Return the number of columns that format_user will print,
4275 or -1 if unknown. */
4277 static int
4278 format_user_width (uid_t u)
4280 return format_user_or_group_width (numeric_ids ? nullptr : getuser (u), u);
4283 /* Likewise, for groups. */
4285 static int
4286 format_group_width (gid_t g)
4288 return format_user_or_group_width (numeric_ids ? nullptr : getgroup (g), g);
4291 /* Return a pointer to a formatted version of F->stat.st_ino,
4292 possibly using buffer, which must be at least
4293 INT_BUFSIZE_BOUND (uintmax_t) bytes. */
4294 static char *
4295 format_inode (char buf[INT_BUFSIZE_BOUND (uintmax_t)],
4296 const struct fileinfo *f)
4298 return (f->stat_ok && f->stat.st_ino != NOT_AN_INODE_NUMBER
4299 ? umaxtostr (f->stat.st_ino, buf)
4300 : (char *) "?");
4303 /* Print information about F in long format. */
4304 static void
4305 print_long_format (const struct fileinfo *f)
4307 char modebuf[12];
4308 char buf
4309 [LONGEST_HUMAN_READABLE + 1 /* inode */
4310 + LONGEST_HUMAN_READABLE + 1 /* size in blocks */
4311 + sizeof (modebuf) - 1 + 1 /* mode string */
4312 + INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
4313 + LONGEST_HUMAN_READABLE + 2 /* major device number */
4314 + LONGEST_HUMAN_READABLE + 1 /* minor device number */
4315 + TIME_STAMP_LEN_MAXIMUM + 1 /* max length of time/date */
4317 size_t s;
4318 char *p;
4319 struct timespec when_timespec;
4320 struct tm when_local;
4321 bool btime_ok = true;
4323 /* Compute the mode string, except remove the trailing space if no
4324 file in this directory has an ACL or security context. */
4325 if (f->stat_ok)
4326 filemodestring (&f->stat, modebuf);
4327 else
4329 modebuf[0] = filetype_letter[f->filetype];
4330 memset (modebuf + 1, '?', 10);
4331 modebuf[11] = '\0';
4333 if (! any_has_acl)
4334 modebuf[10] = '\0';
4335 else if (f->acl_type == ACL_T_LSM_CONTEXT_ONLY)
4336 modebuf[10] = '.';
4337 else if (f->acl_type == ACL_T_YES)
4338 modebuf[10] = '+';
4340 switch (time_type)
4342 case time_ctime:
4343 when_timespec = get_stat_ctime (&f->stat);
4344 break;
4345 case time_mtime:
4346 when_timespec = get_stat_mtime (&f->stat);
4347 break;
4348 case time_atime:
4349 when_timespec = get_stat_atime (&f->stat);
4350 break;
4351 case time_btime:
4352 when_timespec = get_stat_btime (&f->stat);
4353 if (when_timespec.tv_sec == -1 && when_timespec.tv_nsec == -1)
4354 btime_ok = false;
4355 break;
4356 default:
4357 unreachable ();
4360 p = buf;
4362 if (print_inode)
4364 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
4365 p += sprintf (p, "%*s ", inode_number_width, format_inode (hbuf, f));
4368 if (print_block_size)
4370 char hbuf[LONGEST_HUMAN_READABLE + 1];
4371 char const *blocks =
4372 (! f->stat_ok
4373 ? "?"
4374 : human_readable (STP_NBLOCKS (&f->stat), hbuf, human_output_opts,
4375 ST_NBLOCKSIZE, output_block_size));
4376 int blocks_width = mbswidth (blocks, MBSWIDTH_FLAGS);
4377 for (int pad = blocks_width < 0 ? 0 : block_size_width - blocks_width;
4378 0 < pad; pad--)
4379 *p++ = ' ';
4380 while ((*p++ = *blocks++))
4381 continue;
4382 p[-1] = ' ';
4385 /* The last byte of the mode string is the POSIX
4386 "optional alternate access method flag". */
4388 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
4389 p += sprintf (p, "%s %*s ", modebuf, nlink_width,
4390 ! f->stat_ok ? "?" : umaxtostr (f->stat.st_nlink, hbuf));
4393 dired_indent ();
4395 if (print_owner || print_group || print_author || print_scontext)
4397 dired_outbuf (buf, p - buf);
4399 if (print_owner)
4400 format_user (f->stat.st_uid, owner_width, f->stat_ok);
4402 if (print_group)
4403 format_group (f->stat.st_gid, group_width, f->stat_ok);
4405 if (print_author)
4406 format_user (f->stat.st_author, author_width, f->stat_ok);
4408 if (print_scontext)
4409 format_user_or_group (f->scontext, 0, scontext_width);
4411 p = buf;
4414 if (f->stat_ok
4415 && (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode)))
4417 char majorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
4418 char minorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
4419 int blanks_width = (file_size_width
4420 - (major_device_number_width + 2
4421 + minor_device_number_width));
4422 p += sprintf (p, "%*s, %*s ",
4423 major_device_number_width + MAX (0, blanks_width),
4424 umaxtostr (major (f->stat.st_rdev), majorbuf),
4425 minor_device_number_width,
4426 umaxtostr (minor (f->stat.st_rdev), minorbuf));
4428 else
4430 char hbuf[LONGEST_HUMAN_READABLE + 1];
4431 char const *size =
4432 (! f->stat_ok
4433 ? "?"
4434 : human_readable (unsigned_file_size (f->stat.st_size),
4435 hbuf, file_human_output_opts, 1,
4436 file_output_block_size));
4437 int size_width = mbswidth (size, MBSWIDTH_FLAGS);
4438 for (int pad = size_width < 0 ? 0 : file_size_width - size_width;
4439 0 < pad; pad--)
4440 *p++ = ' ';
4441 while ((*p++ = *size++))
4442 continue;
4443 p[-1] = ' ';
4446 s = 0;
4447 *p = '\1';
4449 if (f->stat_ok && btime_ok
4450 && localtime_rz (localtz, &when_timespec.tv_sec, &when_local))
4452 struct timespec six_months_ago;
4453 bool recent;
4455 /* If the file appears to be in the future, update the current
4456 time, in case the file happens to have been modified since
4457 the last time we checked the clock. */
4458 if (timespec_cmp (current_time, when_timespec) < 0)
4459 gettime (&current_time);
4461 /* Consider a time to be recent if it is within the past six months.
4462 A Gregorian year has 365.2425 * 24 * 60 * 60 == 31556952 seconds
4463 on the average. Write this value as an integer constant to
4464 avoid floating point hassles. */
4465 six_months_ago.tv_sec = current_time.tv_sec - 31556952 / 2;
4466 six_months_ago.tv_nsec = current_time.tv_nsec;
4468 recent = (timespec_cmp (six_months_ago, when_timespec) < 0
4469 && timespec_cmp (when_timespec, current_time) < 0);
4471 /* We assume here that all time zones are offset from UTC by a
4472 whole number of seconds. */
4473 s = align_nstrftime (p, TIME_STAMP_LEN_MAXIMUM + 1, recent,
4474 &when_local, localtz, when_timespec.tv_nsec);
4477 if (s || !*p)
4479 p += s;
4480 *p++ = ' ';
4482 else
4484 /* The time cannot be converted using the desired format, so
4485 print it as a huge integer number of seconds. */
4486 char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
4487 p += sprintf (p, "%*s ", long_time_expected_width (),
4488 (! f->stat_ok || ! btime_ok
4489 ? "?"
4490 : timetostr (when_timespec.tv_sec, hbuf)));
4491 /* FIXME: (maybe) We discarded when_timespec.tv_nsec. */
4494 dired_outbuf (buf, p - buf);
4495 size_t w = print_name_with_quoting (f, false, &dired_obstack, p - buf);
4497 if (f->filetype == symbolic_link)
4499 if (f->linkname)
4501 dired_outstring (" -> ");
4502 print_name_with_quoting (f, true, nullptr, (p - buf) + w + 4);
4503 if (indicator_style != none)
4504 print_type_indicator (true, f->linkmode, unknown);
4507 else if (indicator_style != none)
4508 print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4511 /* Write to *BUF a quoted representation of the file name NAME, if non-null,
4512 using OPTIONS to control quoting. *BUF is set to NAME if no quoting
4513 is required. *BUF is allocated if more space required (and the original
4514 *BUF is not deallocated).
4515 Store the number of screen columns occupied by NAME's quoted
4516 representation into WIDTH, if non-null.
4517 Store into PAD whether an initial space is needed for padding.
4518 Return the number of bytes in *BUF. */
4520 static size_t
4521 quote_name_buf (char **inbuf, size_t bufsize, char *name,
4522 struct quoting_options const *options,
4523 int needs_general_quoting, size_t *width, bool *pad)
4525 char *buf = *inbuf;
4526 size_t displayed_width IF_LINT ( = 0);
4527 size_t len = 0;
4528 bool quoted;
4530 enum quoting_style qs = get_quoting_style (options);
4531 bool needs_further_quoting = qmark_funny_chars
4532 && (qs == shell_quoting_style
4533 || qs == shell_always_quoting_style
4534 || qs == literal_quoting_style);
4536 if (needs_general_quoting != 0)
4538 len = quotearg_buffer (buf, bufsize, name, -1, options);
4539 if (bufsize <= len)
4541 buf = xmalloc (len + 1);
4542 quotearg_buffer (buf, len + 1, name, -1, options);
4545 quoted = (*name != *buf) || strlen (name) != len;
4547 else if (needs_further_quoting)
4549 len = strlen (name);
4550 if (bufsize <= len)
4551 buf = xmalloc (len + 1);
4552 memcpy (buf, name, len + 1);
4554 quoted = false;
4556 else
4558 len = strlen (name);
4559 buf = name;
4560 quoted = false;
4563 if (needs_further_quoting)
4565 if (MB_CUR_MAX > 1)
4567 char const *p = buf;
4568 char const *plimit = buf + len;
4569 char *q = buf;
4570 displayed_width = 0;
4572 while (p < plimit)
4573 switch (*p)
4575 case ' ': case '!': case '"': case '#': case '%':
4576 case '&': case '\'': case '(': case ')': case '*':
4577 case '+': case ',': case '-': case '.': case '/':
4578 case '0': case '1': case '2': case '3': case '4':
4579 case '5': case '6': case '7': case '8': case '9':
4580 case ':': case ';': case '<': case '=': case '>':
4581 case '?':
4582 case 'A': case 'B': case 'C': case 'D': case 'E':
4583 case 'F': case 'G': case 'H': case 'I': case 'J':
4584 case 'K': case 'L': case 'M': case 'N': case 'O':
4585 case 'P': case 'Q': case 'R': case 'S': case 'T':
4586 case 'U': case 'V': case 'W': case 'X': case 'Y':
4587 case 'Z':
4588 case '[': case '\\': case ']': case '^': case '_':
4589 case 'a': case 'b': case 'c': case 'd': case 'e':
4590 case 'f': case 'g': case 'h': case 'i': case 'j':
4591 case 'k': case 'l': case 'm': case 'n': case 'o':
4592 case 'p': case 'q': case 'r': case 's': case 't':
4593 case 'u': case 'v': case 'w': case 'x': case 'y':
4594 case 'z': case '{': case '|': case '}': case '~':
4595 /* These characters are printable ASCII characters. */
4596 *q++ = *p++;
4597 displayed_width += 1;
4598 break;
4599 default:
4600 /* If we have a multibyte sequence, copy it until we
4601 reach its end, replacing each non-printable multibyte
4602 character with a single question mark. */
4604 mbstate_t mbstate; mbszero (&mbstate);
4607 char32_t wc;
4608 size_t bytes;
4609 int w;
4611 bytes = mbrtoc32 (&wc, p, plimit - p, &mbstate);
4613 if (bytes == (size_t) -1)
4615 /* An invalid multibyte sequence was
4616 encountered. Skip one input byte, and
4617 put a question mark. */
4618 p++;
4619 *q++ = '?';
4620 displayed_width += 1;
4621 break;
4624 if (bytes == (size_t) -2)
4626 /* An incomplete multibyte character
4627 at the end. Replace it entirely with
4628 a question mark. */
4629 p = plimit;
4630 *q++ = '?';
4631 displayed_width += 1;
4632 break;
4635 if (bytes == 0)
4636 /* A null wide character was encountered. */
4637 bytes = 1;
4639 w = c32width (wc);
4640 if (w >= 0)
4642 /* A printable multibyte character.
4643 Keep it. */
4644 for (; bytes > 0; --bytes)
4645 *q++ = *p++;
4646 displayed_width += w;
4648 else
4650 /* An nonprintable multibyte character.
4651 Replace it entirely with a question
4652 mark. */
4653 p += bytes;
4654 *q++ = '?';
4655 displayed_width += 1;
4658 while (! mbsinit (&mbstate));
4660 break;
4663 /* The buffer may have shrunk. */
4664 len = q - buf;
4666 else
4668 char *p = buf;
4669 char const *plimit = buf + len;
4671 while (p < plimit)
4673 if (! isprint (to_uchar (*p)))
4674 *p = '?';
4675 p++;
4677 displayed_width = len;
4680 else if (width != nullptr)
4682 if (MB_CUR_MAX > 1)
4684 displayed_width = mbsnwidth (buf, len, MBSWIDTH_FLAGS);
4685 displayed_width = MAX (0, displayed_width);
4687 else
4689 char const *p = buf;
4690 char const *plimit = buf + len;
4692 displayed_width = 0;
4693 while (p < plimit)
4695 if (isprint (to_uchar (*p)))
4696 displayed_width++;
4697 p++;
4702 /* Set padding to better align quoted items,
4703 and also give a visual indication that quotes are
4704 not actually part of the name. */
4705 *pad = (align_variable_outer_quotes && cwd_some_quoted && ! quoted);
4707 if (width != nullptr)
4708 *width = displayed_width;
4710 *inbuf = buf;
4712 return len;
4715 static size_t
4716 quote_name_width (char const *name, struct quoting_options const *options,
4717 int needs_general_quoting)
4719 char smallbuf[BUFSIZ];
4720 char *buf = smallbuf;
4721 size_t width;
4722 bool pad;
4724 quote_name_buf (&buf, sizeof smallbuf, (char *) name, options,
4725 needs_general_quoting, &width, &pad);
4727 if (buf != smallbuf && buf != name)
4728 free (buf);
4730 width += pad;
4732 return width;
4735 /* %XX escape any input out of range as defined in RFC3986,
4736 and also if PATH, convert all path separators to '/'. */
4737 static char *
4738 file_escape (char const *str, bool path)
4740 char *esc = xnmalloc (3, strlen (str) + 1);
4741 char *p = esc;
4742 while (*str)
4744 if (path && ISSLASH (*str))
4746 *p++ = '/';
4747 str++;
4749 else if (RFC3986[to_uchar (*str)])
4750 *p++ = *str++;
4751 else
4752 p += sprintf (p, "%%%02x", to_uchar (*str++));
4754 *p = '\0';
4755 return esc;
4758 static size_t
4759 quote_name (char const *name, struct quoting_options const *options,
4760 int needs_general_quoting, const struct bin_str *color,
4761 bool allow_pad, struct obstack *stack, char const *absolute_name)
4763 char smallbuf[BUFSIZ];
4764 char *buf = smallbuf;
4765 size_t len;
4766 bool pad;
4768 len = quote_name_buf (&buf, sizeof smallbuf, (char *) name, options,
4769 needs_general_quoting, nullptr, &pad);
4771 if (pad && allow_pad)
4772 dired_outbyte (' ');
4774 if (color)
4775 print_color_indicator (color);
4777 /* If we're padding, then don't include the outer quotes in
4778 the --hyperlink, to improve the alignment of those links. */
4779 bool skip_quotes = false;
4781 if (absolute_name)
4783 if (align_variable_outer_quotes && cwd_some_quoted && ! pad)
4785 skip_quotes = true;
4786 putchar (*buf);
4788 char *h = file_escape (hostname, /* path= */ false);
4789 char *n = file_escape (absolute_name, /* path= */ true);
4790 /* TODO: It would be good to be able to define parameters
4791 to give hints to the terminal as how best to render the URI.
4792 For example since ls is outputting a dense block of URIs
4793 it would be best to not underline by default, and only
4794 do so upon hover etc. */
4795 printf ("\033]8;;file://%s%s%s\a", h, *n == '/' ? "" : "/", n);
4796 free (h);
4797 free (n);
4800 if (stack)
4801 push_current_dired_pos (stack);
4803 fwrite (buf + skip_quotes, 1, len - (skip_quotes * 2), stdout);
4805 dired_pos += len;
4807 if (stack)
4808 push_current_dired_pos (stack);
4810 if (absolute_name)
4812 fputs ("\033]8;;\a", stdout);
4813 if (skip_quotes)
4814 putchar (*(buf + len - 1));
4817 if (buf != smallbuf && buf != name)
4818 free (buf);
4820 return len + pad;
4823 static size_t
4824 print_name_with_quoting (const struct fileinfo *f,
4825 bool symlink_target,
4826 struct obstack *stack,
4827 size_t start_col)
4829 char const *name = symlink_target ? f->linkname : f->name;
4831 const struct bin_str *color
4832 = print_with_color ? get_color_indicator (f, symlink_target) : nullptr;
4834 bool used_color_this_time = (print_with_color
4835 && (color || is_colored (C_NORM)));
4837 size_t len = quote_name (name, filename_quoting_options, f->quoted,
4838 color, !symlink_target, stack, f->absolute_name);
4840 process_signals ();
4841 if (used_color_this_time)
4843 prep_non_filename_text ();
4845 /* We use the byte length rather than display width here as
4846 an optimization to avoid accurately calculating the width,
4847 because we only output the clear to EOL sequence if the name
4848 _might_ wrap to the next line. This may output a sequence
4849 unnecessarily in multi-byte locales for example,
4850 but in that case it's inconsequential to the output. */
4851 if (line_length
4852 && (start_col / line_length != (start_col + len - 1) / line_length))
4853 put_indicator (&color_indicator[C_CLR_TO_EOL]);
4856 return len;
4859 static void
4860 prep_non_filename_text (void)
4862 if (color_indicator[C_END].string != nullptr)
4863 put_indicator (&color_indicator[C_END]);
4864 else
4866 put_indicator (&color_indicator[C_LEFT]);
4867 put_indicator (&color_indicator[C_RESET]);
4868 put_indicator (&color_indicator[C_RIGHT]);
4872 /* Print the file name of 'f' with appropriate quoting.
4873 Also print file size, inode number, and filetype indicator character,
4874 as requested by switches. */
4876 static size_t
4877 print_file_name_and_frills (const struct fileinfo *f, size_t start_col)
4879 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
4881 set_normal_color ();
4883 if (print_inode)
4884 printf ("%*s ", format == with_commas ? 0 : inode_number_width,
4885 format_inode (buf, f));
4887 if (print_block_size)
4888 printf ("%*s ", format == with_commas ? 0 : block_size_width,
4889 ! f->stat_ok ? "?"
4890 : human_readable (STP_NBLOCKS (&f->stat), buf, human_output_opts,
4891 ST_NBLOCKSIZE, output_block_size));
4893 if (print_scontext)
4894 printf ("%*s ", format == with_commas ? 0 : scontext_width, f->scontext);
4896 size_t width = print_name_with_quoting (f, false, nullptr, start_col);
4898 if (indicator_style != none)
4899 width += print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4901 return width;
4904 /* Given these arguments describing a file, return the single-byte
4905 type indicator, or 0. */
4906 static char
4907 get_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
4909 char c;
4911 if (stat_ok ? S_ISREG (mode) : type == normal)
4913 if (stat_ok && indicator_style == classify && (mode & S_IXUGO))
4914 c = '*';
4915 else
4916 c = 0;
4918 else
4920 if (stat_ok ? S_ISDIR (mode) : type == directory || type == arg_directory)
4921 c = '/';
4922 else if (indicator_style == slash)
4923 c = 0;
4924 else if (stat_ok ? S_ISLNK (mode) : type == symbolic_link)
4925 c = '@';
4926 else if (stat_ok ? S_ISFIFO (mode) : type == fifo)
4927 c = '|';
4928 else if (stat_ok ? S_ISSOCK (mode) : type == sock)
4929 c = '=';
4930 else if (stat_ok && S_ISDOOR (mode))
4931 c = '>';
4932 else
4933 c = 0;
4935 return c;
4938 static bool
4939 print_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
4941 char c = get_type_indicator (stat_ok, mode, type);
4942 if (c)
4943 dired_outbyte (c);
4944 return !!c;
4947 /* Returns if color sequence was printed. */
4948 static bool
4949 print_color_indicator (const struct bin_str *ind)
4951 if (ind)
4953 /* Need to reset so not dealing with attribute combinations */
4954 if (is_colored (C_NORM))
4955 restore_default_color ();
4956 put_indicator (&color_indicator[C_LEFT]);
4957 put_indicator (ind);
4958 put_indicator (&color_indicator[C_RIGHT]);
4961 return ind != nullptr;
4964 /* Returns color indicator or nullptr if none. */
4965 ATTRIBUTE_PURE
4966 static const struct bin_str*
4967 get_color_indicator (const struct fileinfo *f, bool symlink_target)
4969 enum indicator_no type;
4970 struct color_ext_type *ext; /* Color extension */
4971 size_t len; /* Length of name */
4973 char const *name;
4974 mode_t mode;
4975 int linkok;
4976 if (symlink_target)
4978 name = f->linkname;
4979 mode = f->linkmode;
4980 linkok = f->linkok ? 0 : -1;
4982 else
4984 name = f->name;
4985 mode = file_or_link_mode (f);
4986 linkok = f->linkok;
4989 /* Is this a nonexistent file? If so, linkok == -1. */
4991 if (linkok == -1 && is_colored (C_MISSING))
4992 type = C_MISSING;
4993 else if (!f->stat_ok)
4995 static enum indicator_no filetype_indicator[] = FILETYPE_INDICATORS;
4996 type = filetype_indicator[f->filetype];
4998 else
5000 if (S_ISREG (mode))
5002 type = C_FILE;
5004 if ((mode & S_ISUID) != 0 && is_colored (C_SETUID))
5005 type = C_SETUID;
5006 else if ((mode & S_ISGID) != 0 && is_colored (C_SETGID))
5007 type = C_SETGID;
5008 else if (is_colored (C_CAP) && f->has_capability)
5009 type = C_CAP;
5010 else if ((mode & S_IXUGO) != 0 && is_colored (C_EXEC))
5011 type = C_EXEC;
5012 else if ((1 < f->stat.st_nlink) && is_colored (C_MULTIHARDLINK))
5013 type = C_MULTIHARDLINK;
5015 else if (S_ISDIR (mode))
5017 type = C_DIR;
5019 if ((mode & S_ISVTX) && (mode & S_IWOTH)
5020 && is_colored (C_STICKY_OTHER_WRITABLE))
5021 type = C_STICKY_OTHER_WRITABLE;
5022 else if ((mode & S_IWOTH) != 0 && is_colored (C_OTHER_WRITABLE))
5023 type = C_OTHER_WRITABLE;
5024 else if ((mode & S_ISVTX) != 0 && is_colored (C_STICKY))
5025 type = C_STICKY;
5027 else if (S_ISLNK (mode))
5028 type = C_LINK;
5029 else if (S_ISFIFO (mode))
5030 type = C_FIFO;
5031 else if (S_ISSOCK (mode))
5032 type = C_SOCK;
5033 else if (S_ISBLK (mode))
5034 type = C_BLK;
5035 else if (S_ISCHR (mode))
5036 type = C_CHR;
5037 else if (S_ISDOOR (mode))
5038 type = C_DOOR;
5039 else
5041 /* Classify a file of some other type as C_ORPHAN. */
5042 type = C_ORPHAN;
5046 /* Check the file's suffix only if still classified as C_FILE. */
5047 ext = nullptr;
5048 if (type == C_FILE)
5050 /* Test if NAME has a recognized suffix. */
5052 len = strlen (name);
5053 name += len; /* Pointer to final \0. */
5054 for (ext = color_ext_list; ext != nullptr; ext = ext->next)
5056 if (ext->ext.len <= len)
5058 if (ext->exact_match)
5060 if (STREQ_LEN (name - ext->ext.len, ext->ext.string,
5061 ext->ext.len))
5062 break;
5064 else
5066 if (c_strncasecmp (name - ext->ext.len, ext->ext.string,
5067 ext->ext.len) == 0)
5068 break;
5074 /* Adjust the color for orphaned symlinks. */
5075 if (type == C_LINK && !linkok)
5077 if (color_symlink_as_referent || is_colored (C_ORPHAN))
5078 type = C_ORPHAN;
5081 const struct bin_str *const s
5082 = ext ? &(ext->seq) : &color_indicator[type];
5084 return s->string ? s : nullptr;
5087 /* Output a color indicator (which may contain nulls). */
5088 static void
5089 put_indicator (const struct bin_str *ind)
5091 if (! used_color)
5093 used_color = true;
5095 /* If the standard output is a controlling terminal, watch out
5096 for signals, so that the colors can be restored to the
5097 default state if "ls" is suspended or interrupted. */
5099 if (0 <= tcgetpgrp (STDOUT_FILENO))
5100 signal_init ();
5102 prep_non_filename_text ();
5105 fwrite (ind->string, ind->len, 1, stdout);
5108 static size_t
5109 length_of_file_name_and_frills (const struct fileinfo *f)
5111 size_t len = 0;
5112 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
5114 if (print_inode)
5115 len += 1 + (format == with_commas
5116 ? strlen (umaxtostr (f->stat.st_ino, buf))
5117 : inode_number_width);
5119 if (print_block_size)
5120 len += 1 + (format == with_commas
5121 ? strlen (! f->stat_ok ? "?"
5122 : human_readable (STP_NBLOCKS (&f->stat), buf,
5123 human_output_opts, ST_NBLOCKSIZE,
5124 output_block_size))
5125 : block_size_width);
5127 if (print_scontext)
5128 len += 1 + (format == with_commas ? strlen (f->scontext) : scontext_width);
5130 len += fileinfo_name_width (f);
5132 if (indicator_style != none)
5134 char c = get_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
5135 len += (c != 0);
5138 return len;
5141 static void
5142 print_many_per_line (void)
5144 size_t row; /* Current row. */
5145 size_t cols = calculate_columns (true);
5146 struct column_info const *line_fmt = &column_info[cols - 1];
5148 /* Calculate the number of rows that will be in each column except possibly
5149 for a short column on the right. */
5150 size_t rows = cwd_n_used / cols + (cwd_n_used % cols != 0);
5152 for (row = 0; row < rows; row++)
5154 size_t col = 0;
5155 size_t filesno = row;
5156 size_t pos = 0;
5158 /* Print the next row. */
5159 while (true)
5161 struct fileinfo const *f = sorted_file[filesno];
5162 size_t name_length = length_of_file_name_and_frills (f);
5163 size_t max_name_length = line_fmt->col_arr[col++];
5164 print_file_name_and_frills (f, pos);
5166 filesno += rows;
5167 if (filesno >= cwd_n_used)
5168 break;
5170 indent (pos + name_length, pos + max_name_length);
5171 pos += max_name_length;
5173 putchar (eolbyte);
5177 static void
5178 print_horizontal (void)
5180 size_t filesno;
5181 size_t pos = 0;
5182 size_t cols = calculate_columns (false);
5183 struct column_info const *line_fmt = &column_info[cols - 1];
5184 struct fileinfo const *f = sorted_file[0];
5185 size_t name_length = length_of_file_name_and_frills (f);
5186 size_t max_name_length = line_fmt->col_arr[0];
5188 /* Print first entry. */
5189 print_file_name_and_frills (f, 0);
5191 /* Now the rest. */
5192 for (filesno = 1; filesno < cwd_n_used; ++filesno)
5194 size_t col = filesno % cols;
5196 if (col == 0)
5198 putchar (eolbyte);
5199 pos = 0;
5201 else
5203 indent (pos + name_length, pos + max_name_length);
5204 pos += max_name_length;
5207 f = sorted_file[filesno];
5208 print_file_name_and_frills (f, pos);
5210 name_length = length_of_file_name_and_frills (f);
5211 max_name_length = line_fmt->col_arr[col];
5213 putchar (eolbyte);
5216 /* Output name + SEP + ' '. */
5218 static void
5219 print_with_separator (char sep)
5221 size_t filesno;
5222 size_t pos = 0;
5224 for (filesno = 0; filesno < cwd_n_used; filesno++)
5226 struct fileinfo const *f = sorted_file[filesno];
5227 size_t len = line_length ? length_of_file_name_and_frills (f) : 0;
5229 if (filesno != 0)
5231 char separator;
5233 if (! line_length
5234 || ((pos + len + 2 < line_length)
5235 && (pos <= SIZE_MAX - len - 2)))
5237 pos += 2;
5238 separator = ' ';
5240 else
5242 pos = 0;
5243 separator = eolbyte;
5246 putchar (sep);
5247 putchar (separator);
5250 print_file_name_and_frills (f, pos);
5251 pos += len;
5253 putchar (eolbyte);
5256 /* Assuming cursor is at position FROM, indent up to position TO.
5257 Use a TAB character instead of two or more spaces whenever possible. */
5259 static void
5260 indent (size_t from, size_t to)
5262 while (from < to)
5264 if (tabsize != 0 && to / tabsize > (from + 1) / tabsize)
5266 putchar ('\t');
5267 from += tabsize - from % tabsize;
5269 else
5271 putchar (' ');
5272 from++;
5277 /* Put DIRNAME/NAME into DEST, handling '.' and '/' properly. */
5278 /* FIXME: maybe remove this function someday. See about using a
5279 non-malloc'ing version of file_name_concat. */
5281 static void
5282 attach (char *dest, char const *dirname, char const *name)
5284 char const *dirnamep = dirname;
5286 /* Copy dirname if it is not ".". */
5287 if (dirname[0] != '.' || dirname[1] != 0)
5289 while (*dirnamep)
5290 *dest++ = *dirnamep++;
5291 /* Add '/' if 'dirname' doesn't already end with it. */
5292 if (dirnamep > dirname && dirnamep[-1] != '/')
5293 *dest++ = '/';
5295 while (*name)
5296 *dest++ = *name++;
5297 *dest = 0;
5300 /* Allocate enough column info suitable for the current number of
5301 files and display columns, and initialize the info to represent the
5302 narrowest possible columns. */
5304 static void
5305 init_column_info (size_t max_cols)
5307 size_t i;
5309 /* Currently allocated columns in column_info. */
5310 static size_t column_info_alloc;
5312 if (column_info_alloc < max_cols)
5314 size_t new_column_info_alloc;
5315 size_t *p;
5317 if (!max_idx || max_cols < max_idx / 2)
5319 /* The number of columns is far less than the display width
5320 allows. Grow the allocation, but only so that it's
5321 double the current requirements. If the display is
5322 extremely wide, this avoids allocating a lot of memory
5323 that is never needed. */
5324 column_info = xnrealloc (column_info, max_cols,
5325 2 * sizeof *column_info);
5326 new_column_info_alloc = 2 * max_cols;
5328 else
5330 column_info = xnrealloc (column_info, max_idx, sizeof *column_info);
5331 new_column_info_alloc = max_idx;
5334 /* Allocate the new size_t objects by computing the triangle
5335 formula n * (n + 1) / 2, except that we don't need to
5336 allocate the part of the triangle that we've already
5337 allocated. Check for address arithmetic overflow. */
5339 size_t column_info_growth = new_column_info_alloc - column_info_alloc;
5340 size_t s = column_info_alloc + 1 + new_column_info_alloc;
5341 size_t t = s * column_info_growth;
5342 if (s < new_column_info_alloc || t / column_info_growth != s)
5343 xalloc_die ();
5344 p = xnmalloc (t / 2, sizeof *p);
5347 /* Grow the triangle by parceling out the cells just allocated. */
5348 for (i = column_info_alloc; i < new_column_info_alloc; i++)
5350 column_info[i].col_arr = p;
5351 p += i + 1;
5354 column_info_alloc = new_column_info_alloc;
5357 for (i = 0; i < max_cols; ++i)
5359 size_t j;
5361 column_info[i].valid_len = true;
5362 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
5363 for (j = 0; j <= i; ++j)
5364 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
5368 /* Calculate the number of columns needed to represent the current set
5369 of files in the current display width. */
5371 static size_t
5372 calculate_columns (bool by_columns)
5374 size_t filesno; /* Index into cwd_file. */
5375 size_t cols; /* Number of files across. */
5377 /* Normally the maximum number of columns is determined by the
5378 screen width. But if few files are available this might limit it
5379 as well. */
5380 size_t max_cols = 0 < max_idx && max_idx < cwd_n_used ? max_idx : cwd_n_used;
5382 init_column_info (max_cols);
5384 /* Compute the maximum number of possible columns. */
5385 for (filesno = 0; filesno < cwd_n_used; ++filesno)
5387 struct fileinfo const *f = sorted_file[filesno];
5388 size_t name_length = length_of_file_name_and_frills (f);
5390 for (size_t i = 0; i < max_cols; ++i)
5392 if (column_info[i].valid_len)
5394 size_t idx = (by_columns
5395 ? filesno / ((cwd_n_used + i) / (i + 1))
5396 : filesno % (i + 1));
5397 size_t real_length = name_length + (idx == i ? 0 : 2);
5399 if (column_info[i].col_arr[idx] < real_length)
5401 column_info[i].line_len += (real_length
5402 - column_info[i].col_arr[idx]);
5403 column_info[i].col_arr[idx] = real_length;
5404 column_info[i].valid_len = (column_info[i].line_len
5405 < line_length);
5411 /* Find maximum allowed columns. */
5412 for (cols = max_cols; 1 < cols; --cols)
5414 if (column_info[cols - 1].valid_len)
5415 break;
5418 return cols;
5421 void
5422 usage (int status)
5424 if (status != EXIT_SUCCESS)
5425 emit_try_help ();
5426 else
5428 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
5429 fputs (_("\
5430 List information about the FILEs (the current directory by default).\n\
5431 Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.\n\
5432 "), stdout);
5434 emit_mandatory_arg_note ();
5436 fputs (_("\
5437 -a, --all do not ignore entries starting with .\n\
5438 -A, --almost-all do not list implied . and ..\n\
5439 --author with -l, print the author of each file\n\
5440 -b, --escape print C-style escapes for nongraphic characters\n\
5441 "), stdout);
5442 fputs (_("\
5443 --block-size=SIZE with -l, scale sizes by SIZE when printing them;\n\
5444 e.g., '--block-size=M'; see SIZE format below\n\
5446 "), stdout);
5447 fputs (_("\
5448 -B, --ignore-backups do not list implied entries ending with ~\n\
5449 "), stdout);
5450 fputs (_("\
5451 -c with -lt: sort by, and show, ctime (time of last\n\
5452 change of file status information);\n\
5453 with -l: show ctime and sort by name;\n\
5454 otherwise: sort by ctime, newest first\n\
5456 "), stdout);
5457 fputs (_("\
5458 -C list entries by columns\n\
5459 --color[=WHEN] color the output WHEN; more info below\n\
5460 -d, --directory list directories themselves, not their contents\n\
5461 -D, --dired generate output designed for Emacs' dired mode\n\
5462 "), stdout);
5463 fputs (_("\
5464 -f same as -a -U\n\
5465 -F, --classify[=WHEN] append indicator (one of */=>@|) to entries WHEN\n\
5466 --file-type likewise, except do not append '*'\n\
5467 "), stdout);
5468 fputs (_("\
5469 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
5470 single-column -1, verbose -l, vertical -C\n\
5472 "), stdout);
5473 fputs (_("\
5474 --full-time like -l --time-style=full-iso\n\
5475 "), stdout);
5476 fputs (_("\
5477 -g like -l, but do not list owner\n\
5478 "), stdout);
5479 fputs (_("\
5480 --group-directories-first\n\
5481 group directories before files;\n\
5482 can be augmented with a --sort option, but any\n\
5483 use of --sort=none (-U) disables grouping\n\
5485 "), stdout);
5486 fputs (_("\
5487 -G, --no-group in a long listing, don't print group names\n\
5488 "), stdout);
5489 fputs (_("\
5490 -h, --human-readable with -l and -s, print sizes like 1K 234M 2G etc.\n\
5491 --si likewise, but use powers of 1000 not 1024\n\
5492 "), stdout);
5493 fputs (_("\
5494 -H, --dereference-command-line\n\
5495 follow symbolic links listed on the command line\n\
5496 "), stdout);
5497 fputs (_("\
5498 --dereference-command-line-symlink-to-dir\n\
5499 follow each command line symbolic link\n\
5500 that points to a directory\n\
5502 "), stdout);
5503 fputs (_("\
5504 --hide=PATTERN do not list implied entries matching shell PATTERN\
5506 (overridden by -a or -A)\n\
5508 "), stdout);
5509 fputs (_("\
5510 --hyperlink[=WHEN] hyperlink file names WHEN\n\
5511 "), stdout);
5512 fputs (_("\
5513 --indicator-style=WORD\n\
5514 append indicator with style WORD to entry names:\n\
5515 none (default), slash (-p),\n\
5516 file-type (--file-type), classify (-F)\n\
5518 "), stdout);
5519 fputs (_("\
5520 -i, --inode print the index number of each file\n\
5521 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\
5523 "), stdout);
5524 fputs (_("\
5525 -k, --kibibytes default to 1024-byte blocks for file system usage;\
5527 used only with -s and per directory totals\n\
5529 "), stdout);
5530 fputs (_("\
5531 -l use a long listing format\n\
5532 "), stdout);
5533 fputs (_("\
5534 -L, --dereference when showing file information for a symbolic\n\
5535 link, show information for the file the link\n\
5536 references rather than for the link itself\n\
5538 "), stdout);
5539 fputs (_("\
5540 -m fill width with a comma separated list of entries\
5542 "), stdout);
5543 fputs (_("\
5544 -n, --numeric-uid-gid like -l, but list numeric user and group IDs\n\
5545 -N, --literal print entry names without quoting\n\
5546 -o like -l, but do not list group information\n\
5547 -p, --indicator-style=slash\n\
5548 append / indicator to directories\n\
5549 "), stdout);
5550 fputs (_("\
5551 -q, --hide-control-chars print ? instead of nongraphic characters\n\
5552 "), stdout);
5553 fputs (_("\
5554 --show-control-chars show nongraphic characters as-is (the default,\n\
5555 unless program is 'ls' and output is a terminal)\
5558 "), stdout);
5559 fputs (_("\
5560 -Q, --quote-name enclose entry names in double quotes\n\
5561 "), stdout);
5562 fputs (_("\
5563 --quoting-style=WORD use quoting style WORD for entry names:\n\
5564 literal, locale, shell, shell-always,\n\
5565 shell-escape, shell-escape-always, c, escape\n\
5566 (overrides QUOTING_STYLE environment variable)\n\
5568 "), stdout);
5569 fputs (_("\
5570 -r, --reverse reverse order while sorting\n\
5571 -R, --recursive list subdirectories recursively\n\
5572 -s, --size print the allocated size of each file, in blocks\n\
5573 "), stdout);
5574 fputs (_("\
5575 -S sort by file size, largest first\n\
5576 "), stdout);
5577 fputs (_("\
5578 --sort=WORD sort by WORD instead of name: none (-U), size (-S)\
5579 ,\n\
5580 time (-t), version (-v), extension (-X), width\n\
5582 "), stdout);
5583 fputs (_("\
5584 --time=WORD select which timestamp used to display or sort;\n\
5585 access time (-u): atime, access, use;\n\
5586 metadata change time (-c): ctime, status;\n\
5587 modified time (default): mtime, modification;\n\
5588 birth time: birth, creation;\n\
5589 with -l, WORD determines which time to show;\n\
5590 with --sort=time, sort by WORD (newest first)\n\
5592 "), stdout);
5593 fputs (_("\
5594 --time-style=TIME_STYLE\n\
5595 time/date format with -l; see TIME_STYLE below\n\
5596 "), stdout);
5597 fputs (_("\
5598 -t sort by time, newest first; see --time\n\
5599 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
5600 "), stdout);
5601 fputs (_("\
5602 -u with -lt: sort by, and show, access time;\n\
5603 with -l: show access time and sort by name;\n\
5604 otherwise: sort by access time, newest first\n\
5606 "), stdout);
5607 fputs (_("\
5608 -U do not sort; list entries in directory order\n\
5609 "), stdout);
5610 fputs (_("\
5611 -v natural sort of (version) numbers within text\n\
5612 "), stdout);
5613 fputs (_("\
5614 -w, --width=COLS set output width to COLS. 0 means no limit\n\
5615 -x list entries by lines instead of by columns\n\
5616 -X sort alphabetically by entry extension\n\
5617 -Z, --context print any security context of each file\n\
5618 --zero end each output line with NUL, not newline\n\
5619 -1 list one file per line\n\
5620 "), stdout);
5621 fputs (HELP_OPTION_DESCRIPTION, stdout);
5622 fputs (VERSION_OPTION_DESCRIPTION, stdout);
5623 emit_size_note ();
5624 fputs (_("\
5626 The TIME_STYLE argument can be full-iso, long-iso, iso, locale, or +FORMAT.\n\
5627 FORMAT is interpreted like in date(1). If FORMAT is FORMAT1<newline>FORMAT2,\n\
5628 then FORMAT1 applies to non-recent files and FORMAT2 to recent files.\n\
5629 TIME_STYLE prefixed with 'posix-' takes effect only outside the POSIX locale.\n\
5630 Also the TIME_STYLE environment variable sets the default style to use.\n\
5631 "), stdout);
5632 fputs (_("\
5634 The WHEN argument defaults to 'always' and can also be 'auto' or 'never'.\n\
5635 "), stdout);
5636 fputs (_("\
5638 Using color to distinguish file types is disabled both by default and\n\
5639 with --color=never. With --color=auto, ls emits color codes only when\n\
5640 standard output is connected to a terminal. The LS_COLORS environment\n\
5641 variable can change the settings. Use the dircolors(1) command to set it.\n\
5642 "), stdout);
5643 fputs (_("\
5645 Exit status:\n\
5646 0 if OK,\n\
5647 1 if minor problems (e.g., cannot access subdirectory),\n\
5648 2 if serious trouble (e.g., cannot access command-line argument).\n\
5649 "), stdout);
5650 emit_ancillary_info (PROGRAM_NAME);
5652 exit (status);