maint: regularize struct initializers
[coreutils.git] / src / ls.c
blob900d993161565ed9f000cd02a69e0df1c3ee1ec9
1 /* 'dir', 'vdir' and 'ls' directory listing programs for GNU.
2 Copyright (C) 1985-2023 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 <sys/types.h>
41 #include <termios.h>
42 #if HAVE_STROPTS_H
43 # include <stropts.h>
44 #endif
45 #include <sys/ioctl.h>
47 #ifdef WINSIZE_IN_PTEM
48 # include <sys/stream.h>
49 # include <sys/ptem.h>
50 #endif
52 #include <stdio.h>
53 #include <setjmp.h>
54 #include <pwd.h>
55 #include <getopt.h>
56 #include <signal.h>
57 #include <selinux/selinux.h>
58 #include <wchar.h>
60 #if HAVE_LANGINFO_CODESET
61 # include <langinfo.h>
62 #endif
64 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
65 present. */
66 #ifndef SA_NOCLDSTOP
67 # define SA_NOCLDSTOP 0
68 # define sigprocmask(How, Set, Oset) /* empty */
69 # define sigset_t int
70 # if ! HAVE_SIGINTERRUPT
71 # define siginterrupt(sig, flag) /* empty */
72 # endif
73 #endif
75 /* NonStop circa 2011 lacks both SA_RESTART and siginterrupt, so don't
76 restart syscalls after a signal handler fires. This may cause
77 colors to get messed up on the screen if 'ls' is interrupted, but
78 that's the best we can do on such a platform. */
79 #ifndef SA_RESTART
80 # define SA_RESTART 0
81 #endif
83 #include "system.h"
84 #include <fnmatch.h>
86 #include "acl.h"
87 #include "argmatch.h"
88 #include "assure.h"
89 #include "c-strcase.h"
90 #include "dev-ino.h"
91 #include "filenamecat.h"
92 #include "hard-locale.h"
93 #include "hash.h"
94 #include "human.h"
95 #include "filemode.h"
96 #include "filevercmp.h"
97 #include "idcache.h"
98 #include "ls.h"
99 #include "mbswidth.h"
100 #include "mpsort.h"
101 #include "obstack.h"
102 #include "quote.h"
103 #include "smack.h"
104 #include "stat-size.h"
105 #include "stat-time.h"
106 #include "strftime.h"
107 #include "xdectoint.h"
108 #include "xstrtol.h"
109 #include "xstrtol-error.h"
110 #include "areadlink.h"
111 #include "dircolors.h"
112 #include "xgethostname.h"
113 #include "c-ctype.h"
114 #include "canonicalize.h"
115 #include "statx.h"
117 /* Include <sys/capability.h> last to avoid a clash of <sys/types.h>
118 include guards with some premature versions of libcap.
119 For more details, see <https://bugzilla.redhat.com/483548>. */
120 #ifdef HAVE_CAP
121 # include <sys/capability.h>
122 #endif
124 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
125 : (ls_mode == LS_MULTI_COL \
126 ? "dir" : "vdir"))
128 #define AUTHORS \
129 proper_name ("Richard M. Stallman"), \
130 proper_name ("David MacKenzie")
132 #define obstack_chunk_alloc malloc
133 #define obstack_chunk_free free
135 /* Unix-based readdir implementations have historically returned a dirent.d_ino
136 value that is sometimes not equal to the stat-obtained st_ino value for
137 that same entry. This error occurs for a readdir entry that refers
138 to a mount point. readdir's error is to return the inode number of
139 the underlying directory -- one that typically cannot be stat'ed, as
140 long as a file system is mounted on that directory. RELIABLE_D_INO
141 encapsulates whether we can use the more efficient approach of relying
142 on readdir-supplied d_ino values, or whether we must incur the cost of
143 calling stat or lstat to obtain each guaranteed-valid inode number. */
145 #ifndef READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
146 # define READDIR_LIES_ABOUT_MOUNTPOINT_D_INO 1
147 #endif
149 #if READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
150 # define RELIABLE_D_INO(dp) NOT_AN_INODE_NUMBER
151 #else
152 # define RELIABLE_D_INO(dp) D_INO (dp)
153 #endif
155 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
156 # define st_author st_uid
157 #endif
159 enum filetype
161 unknown,
162 fifo,
163 chardev,
164 directory,
165 blockdev,
166 normal,
167 symbolic_link,
168 sock,
169 whiteout,
170 arg_directory
173 /* Display letters and indicators for each filetype.
174 Keep these in sync with enum filetype. */
175 static char const filetype_letter[] = "?pcdb-lswd";
177 /* Ensure that filetype and filetype_letter have the same
178 number of elements. */
179 static_assert (sizeof filetype_letter - 1 == arg_directory + 1);
181 #define FILETYPE_INDICATORS \
183 C_ORPHAN, C_FIFO, C_CHR, C_DIR, C_BLK, C_FILE, \
184 C_LINK, C_SOCK, C_FILE, C_DIR \
187 enum acl_type
189 ACL_T_NONE,
190 ACL_T_LSM_CONTEXT_ONLY,
191 ACL_T_YES
194 struct fileinfo
196 /* The file name. */
197 char *name;
199 /* For symbolic link, name of the file linked to, otherwise zero. */
200 char *linkname;
202 /* For terminal hyperlinks. */
203 char *absolute_name;
205 struct stat stat;
207 enum filetype filetype;
209 /* For symbolic link and long listing, st_mode of file linked to, otherwise
210 zero. */
211 mode_t linkmode;
213 /* security context. */
214 char *scontext;
216 bool stat_ok;
218 /* For symbolic link and color printing, true if linked-to file
219 exists, otherwise false. */
220 bool linkok;
222 /* For long listings, true if the file has an access control list,
223 or a security context. */
224 enum acl_type acl_type;
226 /* For color listings, true if a regular file has capability info. */
227 bool has_capability;
229 /* Whether file name needs quoting. tri-state with -1 == unknown. */
230 int quoted;
232 /* Cached screen width (including quoting). */
233 size_t width;
236 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
238 /* Null is a valid character in a color indicator (think about Epson
239 printers, for example) so we have to use a length/buffer string
240 type. */
242 struct bin_str
244 size_t len; /* Number of bytes */
245 char const *string; /* Pointer to the same */
248 #if ! HAVE_TCGETPGRP
249 # define tcgetpgrp(Fd) 0
250 #endif
252 static size_t quote_name (char const *name,
253 struct quoting_options const *options,
254 int needs_general_quoting,
255 const struct bin_str *color,
256 bool allow_pad, struct obstack *stack,
257 char const *absolute_name);
258 static size_t quote_name_buf (char **inbuf, size_t bufsize, char *name,
259 struct quoting_options const *options,
260 int needs_general_quoting, size_t *width,
261 bool *pad);
262 static int decode_switches (int argc, char **argv);
263 static bool file_ignored (char const *name);
264 static uintmax_t gobble_file (char const *name, enum filetype type,
265 ino_t inode, bool command_line_arg,
266 char const *dirname);
267 static const struct bin_str * get_color_indicator (const struct fileinfo *f,
268 bool symlink_target);
269 static bool print_color_indicator (const struct bin_str *ind);
270 static void put_indicator (const struct bin_str *ind);
271 static void add_ignore_pattern (char const *pattern);
272 static void attach (char *dest, char const *dirname, char const *name);
273 static void clear_files (void);
274 static void extract_dirs_from_files (char const *dirname,
275 bool command_line_arg);
276 static void get_link_name (char const *filename, struct fileinfo *f,
277 bool command_line_arg);
278 static void indent (size_t from, size_t to);
279 static size_t calculate_columns (bool by_columns);
280 static void print_current_files (void);
281 static void print_dir (char const *name, char const *realname,
282 bool command_line_arg);
283 static size_t print_file_name_and_frills (const struct fileinfo *f,
284 size_t start_col);
285 static void print_horizontal (void);
286 static int format_user_width (uid_t u);
287 static int format_group_width (gid_t g);
288 static void print_long_format (const struct fileinfo *f);
289 static void print_many_per_line (void);
290 static size_t print_name_with_quoting (const struct fileinfo *f,
291 bool symlink_target,
292 struct obstack *stack,
293 size_t start_col);
294 static void prep_non_filename_text (void);
295 static bool print_type_indicator (bool stat_ok, mode_t mode,
296 enum filetype type);
297 static void print_with_separator (char sep);
298 static void queue_directory (char const *name, char const *realname,
299 bool command_line_arg);
300 static void sort_files (void);
301 static void parse_ls_color (void);
303 static int getenv_quoting_style (void);
305 static size_t quote_name_width (char const *name,
306 struct quoting_options const *options,
307 int needs_general_quoting);
309 /* Initial size of hash table.
310 Most hierarchies are likely to be shallower than this. */
311 enum { INITIAL_TABLE_SIZE = 30 };
313 /* The set of 'active' directories, from the current command-line argument
314 to the level in the hierarchy at which files are being listed.
315 A directory is represented by its device and inode numbers (struct dev_ino).
316 A directory is added to this set when ls begins listing it or its
317 entries, and it is removed from the set just after ls has finished
318 processing it. This set is used solely to detect loops, e.g., with
319 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
320 static Hash_table *active_dir_set;
322 #define LOOP_DETECT (!!active_dir_set)
324 /* The table of files in the current directory:
326 'cwd_file' points to a vector of 'struct fileinfo', one per file.
327 'cwd_n_alloc' is the number of elements space has been allocated for.
328 'cwd_n_used' is the number actually in use. */
330 /* Address of block containing the files that are described. */
331 static struct fileinfo *cwd_file;
333 /* Length of block that 'cwd_file' points to, measured in files. */
334 static size_t cwd_n_alloc;
336 /* Index of first unused slot in 'cwd_file'. */
337 static size_t cwd_n_used;
339 /* Whether files needs may need padding due to quoting. */
340 static bool cwd_some_quoted;
342 /* Whether quoting style _may_ add outer quotes,
343 and whether aligning those is useful. */
344 static bool align_variable_outer_quotes;
346 /* Vector of pointers to files, in proper sorted order, and the number
347 of entries allocated for it. */
348 static void **sorted_file;
349 static size_t sorted_file_alloc;
351 /* When true, in a color listing, color each symlink name according to the
352 type of file it points to. Otherwise, color them according to the 'ln'
353 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
354 regardless. This is set when 'ln=target' appears in LS_COLORS. */
356 static bool color_symlink_as_referent;
358 static char const *hostname;
360 /* Mode of appropriate file for coloring. */
361 static mode_t
362 file_or_link_mode (struct fileinfo const *file)
364 return (color_symlink_as_referent && file->linkok
365 ? file->linkmode : file->stat.st_mode);
369 /* Record of one pending directory waiting to be listed. */
371 struct pending
373 char *name;
374 /* If the directory is actually the file pointed to by a symbolic link we
375 were told to list, 'realname' will contain the name of the symbolic
376 link, otherwise zero. */
377 char *realname;
378 bool command_line_arg;
379 struct pending *next;
382 static struct pending *pending_dirs;
384 /* Current time in seconds and nanoseconds since 1970, updated as
385 needed when deciding whether a file is recent. */
387 static struct timespec current_time;
389 static bool print_scontext;
390 static char UNKNOWN_SECURITY_CONTEXT[] = "?";
392 /* Whether any of the files has an ACL. This affects the width of the
393 mode column. */
395 static bool any_has_acl;
397 /* The number of columns to use for columns containing inode numbers,
398 block sizes, link counts, owners, groups, authors, major device
399 numbers, minor device numbers, and file sizes, respectively. */
401 static int inode_number_width;
402 static int block_size_width;
403 static int nlink_width;
404 static int scontext_width;
405 static int owner_width;
406 static int group_width;
407 static int author_width;
408 static int major_device_number_width;
409 static int minor_device_number_width;
410 static int file_size_width;
412 /* Option flags */
414 /* long_format for lots of info, one per line.
415 one_per_line for just names, one per line.
416 many_per_line for just names, many per line, sorted vertically.
417 horizontal for just names, many per line, sorted horizontally.
418 with_commas for just names, many per line, separated by commas.
420 -l (and other options that imply -l), -1, -C, -x and -m control
421 this parameter. */
423 enum format
425 long_format, /* -l and other options that imply -l */
426 one_per_line, /* -1 */
427 many_per_line, /* -C */
428 horizontal, /* -x */
429 with_commas /* -m */
432 static enum format format;
434 /* 'full-iso' uses full ISO-style dates and times. 'long-iso' uses longer
435 ISO-style timestamps, though shorter than 'full-iso'. 'iso' uses shorter
436 ISO-style timestamps. 'locale' uses locale-dependent timestamps. */
437 enum time_style
439 full_iso_time_style, /* --time-style=full-iso */
440 long_iso_time_style, /* --time-style=long-iso */
441 iso_time_style, /* --time-style=iso */
442 locale_time_style /* --time-style=locale */
445 static char const *const time_style_args[] =
447 "full-iso", "long-iso", "iso", "locale", nullptr
449 static enum time_style const time_style_types[] =
451 full_iso_time_style, long_iso_time_style, iso_time_style,
452 locale_time_style
454 ARGMATCH_VERIFY (time_style_args, time_style_types);
456 /* Type of time to print or sort by. Controlled by -c and -u.
457 The values of each item of this enum are important since they are
458 used as indices in the sort functions array (see sort_files()). */
460 enum time_type
462 time_mtime = 0, /* default */
463 time_ctime, /* -c */
464 time_atime, /* -u */
465 time_btime, /* birth time */
466 time_numtypes /* the number of elements of this enum */
469 static enum time_type time_type;
471 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v.
472 The values of each item of this enum are important since they are
473 used as indices in the sort functions array (see sort_files()). */
475 enum sort_type
477 sort_name = 0, /* default */
478 sort_extension, /* -X */
479 sort_width,
480 sort_size, /* -S */
481 sort_version, /* -v */
482 sort_time, /* -t; must be second to last */
483 sort_none, /* -U; must be last */
484 sort_numtypes /* the number of elements of this enum */
487 static enum sort_type sort_type;
489 /* Direction of sort.
490 false means highest first if numeric,
491 lowest first if alphabetic;
492 these are the defaults.
493 true means the opposite order in each case. -r */
495 static bool sort_reverse;
497 /* True means to display owner information. -g turns this off. */
499 static bool print_owner = true;
501 /* True means to display author information. */
503 static bool print_author;
505 /* True means to display group information. -G and -o turn this off. */
507 static bool print_group = true;
509 /* True means print the user and group id's as numbers rather
510 than as names. -n */
512 static bool numeric_ids;
514 /* True means mention the size in blocks of each file. -s */
516 static bool print_block_size;
518 /* Human-readable options for output, when printing block counts. */
519 static int human_output_opts;
521 /* The units to use when printing block counts. */
522 static uintmax_t output_block_size;
524 /* Likewise, but for file sizes. */
525 static int file_human_output_opts;
526 static uintmax_t file_output_block_size = 1;
528 /* Follow the output with a special string. Using this format,
529 Emacs' dired mode starts up twice as fast, and can handle all
530 strange characters in file names. */
531 static bool dired;
533 /* 'none' means don't mention the type of files.
534 'slash' means mention directories only, with a '/'.
535 'file_type' means mention file types.
536 'classify' means mention file types and mark executables.
538 Controlled by -F, -p, and --indicator-style. */
540 enum indicator_style
542 none = 0, /* --indicator-style=none (default) */
543 slash, /* -p, --indicator-style=slash */
544 file_type, /* --indicator-style=file-type */
545 classify /* -F, --indicator-style=classify */
548 static enum indicator_style indicator_style;
550 /* Names of indicator styles. */
551 static char const *const indicator_style_args[] =
553 "none", "slash", "file-type", "classify", nullptr
555 static enum indicator_style const indicator_style_types[] =
557 none, slash, file_type, classify
559 ARGMATCH_VERIFY (indicator_style_args, indicator_style_types);
561 /* True means use colors to mark types. Also define the different
562 colors as well as the stuff for the LS_COLORS environment variable.
563 The LS_COLORS variable is now in a termcap-like format. */
565 static bool print_with_color;
567 static bool print_hyperlink;
569 /* Whether we used any colors in the output so far. If so, we will
570 need to restore the default color later. If not, we will need to
571 call prep_non_filename_text before using color for the first time. */
573 static bool used_color = false;
575 enum when_type
577 when_never, /* 0: default or --color=never */
578 when_always, /* 1: --color=always */
579 when_if_tty /* 2: --color=tty */
582 enum Dereference_symlink
584 DEREF_UNDEFINED = 0, /* default */
585 DEREF_NEVER,
586 DEREF_COMMAND_LINE_ARGUMENTS, /* -H */
587 DEREF_COMMAND_LINE_SYMLINK_TO_DIR, /* the default, in certain cases */
588 DEREF_ALWAYS /* -L */
591 enum indicator_no
593 C_LEFT, C_RIGHT, C_END, C_RESET, C_NORM, C_FILE, C_DIR, C_LINK,
594 C_FIFO, C_SOCK,
595 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR, C_SETUID, C_SETGID,
596 C_STICKY, C_OTHER_WRITABLE, C_STICKY_OTHER_WRITABLE, C_CAP, C_MULTIHARDLINK,
597 C_CLR_TO_EOL
600 static char const *const indicator_name[]=
602 "lc", "rc", "ec", "rs", "no", "fi", "di", "ln", "pi", "so",
603 "bd", "cd", "mi", "or", "ex", "do", "su", "sg", "st",
604 "ow", "tw", "ca", "mh", "cl", nullptr
607 struct color_ext_type
609 struct bin_str ext; /* The extension we're looking for */
610 struct bin_str seq; /* The sequence to output when we do */
611 bool exact_match; /* Whether to compare case insensitively */
612 struct color_ext_type *next; /* Next in list */
615 static struct bin_str color_indicator[] =
617 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
618 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
619 { 0, nullptr }, /* ec: End color (replaces lc+rs+rc) */
620 { LEN_STR_PAIR ("0") }, /* rs: Reset to ordinary colors */
621 { 0, nullptr }, /* no: Normal */
622 { 0, nullptr }, /* fi: File: default */
623 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
624 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
625 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
626 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
627 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
628 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
629 { 0, nullptr }, /* mi: Missing file: undefined */
630 { 0, nullptr }, /* or: Orphaned symlink: undefined */
631 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
632 { LEN_STR_PAIR ("01;35") }, /* do: Door: bright magenta */
633 { LEN_STR_PAIR ("37;41") }, /* su: setuid: white on red */
634 { LEN_STR_PAIR ("30;43") }, /* sg: setgid: black on yellow */
635 { LEN_STR_PAIR ("37;44") }, /* st: sticky: black on blue */
636 { LEN_STR_PAIR ("34;42") }, /* ow: other-writable: blue on green */
637 { LEN_STR_PAIR ("30;42") }, /* tw: ow w/ sticky: black on green */
638 { 0, nullptr }, /* ca: disabled by default */
639 { 0, nullptr }, /* mh: disabled by default */
640 { LEN_STR_PAIR ("\033[K") }, /* cl: clear to end of line */
643 /* A list mapping file extensions to corresponding display sequence. */
644 static struct color_ext_type *color_ext_list = nullptr;
646 /* Buffer for color sequences */
647 static char *color_buf;
649 /* True means to check for orphaned symbolic link, for displaying
650 colors, or to group symlink to directories with other dirs. */
652 static bool check_symlink_mode;
654 /* True means mention the inode number of each file. -i */
656 static bool print_inode;
658 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
659 other options that imply -l), and -L. */
661 static enum Dereference_symlink dereference;
663 /* True means when a directory is found, display info on its
664 contents. -R */
666 static bool recursive;
668 /* True means when an argument is a directory name, display info
669 on it itself. -d */
671 static bool immediate_dirs;
673 /* True means that directories are grouped before files. */
675 static bool directories_first;
677 /* Which files to ignore. */
679 static enum
681 /* Ignore files whose names start with '.', and files specified by
682 --hide and --ignore. */
683 IGNORE_DEFAULT = 0,
685 /* Ignore '.', '..', and files specified by --ignore. */
686 IGNORE_DOT_AND_DOTDOT,
688 /* Ignore only files specified by --ignore. */
689 IGNORE_MINIMAL
690 } ignore_mode;
692 /* A linked list of shell-style globbing patterns. If a non-argument
693 file name matches any of these patterns, it is ignored.
694 Controlled by -I. Multiple -I options accumulate.
695 The -B option adds '*~' and '.*~' to this list. */
697 struct ignore_pattern
699 char const *pattern;
700 struct ignore_pattern *next;
703 static struct ignore_pattern *ignore_patterns;
705 /* Similar to IGNORE_PATTERNS, except that -a or -A causes this
706 variable itself to be ignored. */
707 static struct ignore_pattern *hide_patterns;
709 /* True means output nongraphic chars in file names as '?'.
710 (-q, --hide-control-chars)
711 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
712 independent. The algorithm is: first, obey the quoting style to get a
713 string representing the file name; then, if qmark_funny_chars is set,
714 replace all nonprintable chars in that string with '?'. It's necessary
715 to replace nonprintable chars even in quoted strings, because we don't
716 want to mess up the terminal if control chars get sent to it, and some
717 quoting methods pass through control chars as-is. */
718 static bool qmark_funny_chars;
720 /* Quoting options for file and dir name output. */
722 static struct quoting_options *filename_quoting_options;
723 static struct quoting_options *dirname_quoting_options;
725 /* The number of chars per hardware tab stop. Setting this to zero
726 inhibits the use of TAB characters for separating columns. -T */
727 static size_t tabsize;
729 /* True means print each directory name before listing it. */
731 static bool print_dir_name;
733 /* The line length to use for breaking lines in many-per-line format.
734 Can be set with -w. If zero, there is no limit. */
736 static size_t line_length;
738 /* The local time zone rules, as per the TZ environment variable. */
740 static timezone_t localtz;
742 /* If true, the file listing format requires that stat be called on
743 each file. */
745 static bool format_needs_stat;
747 /* Similar to 'format_needs_stat', but set if only the file type is
748 needed. */
750 static bool format_needs_type;
752 /* An arbitrary limit on the number of bytes in a printed timestamp.
753 This is set to a relatively small value to avoid the need to worry
754 about denial-of-service attacks on servers that run "ls" on behalf
755 of remote clients. 1000 bytes should be enough for any practical
756 timestamp format. */
758 enum { TIME_STAMP_LEN_MAXIMUM = MAX (1000, INT_STRLEN_BOUND (time_t)) };
760 /* strftime formats for non-recent and recent files, respectively, in
761 -l output. */
763 static char const *long_time_format[2] =
765 /* strftime format for non-recent files (older than 6 months), in
766 -l output. This should contain the year, month and day (at
767 least), in an order that is understood by people in your
768 locale's territory. Please try to keep the number of used
769 screen columns small, because many people work in windows with
770 only 80 columns. But make this as wide as the other string
771 below, for recent files. */
772 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
773 so be wary of using variable width fields from the locale.
774 Note %b is handled specially by ls and aligned correctly.
775 Note also that specifying a width as in %5b is erroneous as strftime
776 will count bytes rather than characters in multibyte locales. */
777 N_("%b %e %Y"),
778 /* strftime format for recent files (younger than 6 months), in -l
779 output. This should contain the month, day and time (at
780 least), in an order that is understood by people in your
781 locale's territory. Please try to keep the number of used
782 screen columns small, because many people work in windows with
783 only 80 columns. But make this as wide as the other string
784 above, for non-recent files. */
785 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
786 so be wary of using variable width fields from the locale.
787 Note %b is handled specially by ls and aligned correctly.
788 Note also that specifying a width as in %5b is erroneous as strftime
789 will count bytes rather than characters in multibyte locales. */
790 N_("%b %e %H:%M")
793 /* The set of signals that are caught. */
795 static sigset_t caught_signals;
797 /* If nonzero, the value of the pending fatal signal. */
799 static sig_atomic_t volatile interrupt_signal;
801 /* A count of the number of pending stop signals that have been received. */
803 static sig_atomic_t volatile stop_signal_count;
805 /* Desired exit status. */
807 static int exit_status;
809 /* Exit statuses. */
810 enum
812 /* "ls" had a minor problem. E.g., while processing a directory,
813 ls obtained the name of an entry via readdir, yet was later
814 unable to stat that name. This happens when listing a directory
815 in which entries are actively being removed or renamed. */
816 LS_MINOR_PROBLEM = 1,
818 /* "ls" had more serious trouble (e.g., memory exhausted, invalid
819 option or failure to stat a command line argument. */
820 LS_FAILURE = 2
823 /* For long options that have no equivalent short option, use a
824 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
825 enum
827 AUTHOR_OPTION = CHAR_MAX + 1,
828 BLOCK_SIZE_OPTION,
829 COLOR_OPTION,
830 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION,
831 FILE_TYPE_INDICATOR_OPTION,
832 FORMAT_OPTION,
833 FULL_TIME_OPTION,
834 GROUP_DIRECTORIES_FIRST_OPTION,
835 HIDE_OPTION,
836 HYPERLINK_OPTION,
837 INDICATOR_STYLE_OPTION,
838 QUOTING_STYLE_OPTION,
839 SHOW_CONTROL_CHARS_OPTION,
840 SI_OPTION,
841 SORT_OPTION,
842 TIME_OPTION,
843 TIME_STYLE_OPTION,
844 ZERO_OPTION,
847 static struct option const long_options[] =
849 {"all", no_argument, nullptr, 'a'},
850 {"escape", no_argument, nullptr, 'b'},
851 {"directory", no_argument, nullptr, 'd'},
852 {"dired", no_argument, nullptr, 'D'},
853 {"full-time", no_argument, nullptr, FULL_TIME_OPTION},
854 {"group-directories-first", no_argument, nullptr,
855 GROUP_DIRECTORIES_FIRST_OPTION},
856 {"human-readable", no_argument, nullptr, 'h'},
857 {"inode", no_argument, nullptr, 'i'},
858 {"kibibytes", no_argument, nullptr, 'k'},
859 {"numeric-uid-gid", no_argument, nullptr, 'n'},
860 {"no-group", no_argument, nullptr, 'G'},
861 {"hide-control-chars", no_argument, nullptr, 'q'},
862 {"reverse", no_argument, nullptr, 'r'},
863 {"size", no_argument, nullptr, 's'},
864 {"width", required_argument, nullptr, 'w'},
865 {"almost-all", no_argument, nullptr, 'A'},
866 {"ignore-backups", no_argument, nullptr, 'B'},
867 {"classify", optional_argument, nullptr, 'F'},
868 {"file-type", no_argument, nullptr, FILE_TYPE_INDICATOR_OPTION},
869 {"si", no_argument, nullptr, SI_OPTION},
870 {"dereference-command-line", no_argument, nullptr, 'H'},
871 {"dereference-command-line-symlink-to-dir", no_argument, nullptr,
872 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION},
873 {"hide", required_argument, nullptr, HIDE_OPTION},
874 {"ignore", required_argument, nullptr, 'I'},
875 {"indicator-style", required_argument, nullptr, INDICATOR_STYLE_OPTION},
876 {"dereference", no_argument, nullptr, 'L'},
877 {"literal", no_argument, nullptr, 'N'},
878 {"quote-name", no_argument, nullptr, 'Q'},
879 {"quoting-style", required_argument, nullptr, QUOTING_STYLE_OPTION},
880 {"recursive", no_argument, nullptr, 'R'},
881 {"format", required_argument, nullptr, FORMAT_OPTION},
882 {"show-control-chars", no_argument, nullptr, SHOW_CONTROL_CHARS_OPTION},
883 {"sort", required_argument, nullptr, SORT_OPTION},
884 {"tabsize", required_argument, nullptr, 'T'},
885 {"time", required_argument, nullptr, TIME_OPTION},
886 {"time-style", required_argument, nullptr, TIME_STYLE_OPTION},
887 {"zero", no_argument, nullptr, ZERO_OPTION},
888 {"color", optional_argument, nullptr, COLOR_OPTION},
889 {"hyperlink", optional_argument, nullptr, HYPERLINK_OPTION},
890 {"block-size", required_argument, nullptr, BLOCK_SIZE_OPTION},
891 {"context", no_argument, 0, 'Z'},
892 {"author", no_argument, nullptr, AUTHOR_OPTION},
893 {GETOPT_HELP_OPTION_DECL},
894 {GETOPT_VERSION_OPTION_DECL},
895 {nullptr, 0, nullptr, 0}
898 static char const *const format_args[] =
900 "verbose", "long", "commas", "horizontal", "across",
901 "vertical", "single-column", nullptr
903 static enum format const format_types[] =
905 long_format, long_format, with_commas, horizontal, horizontal,
906 many_per_line, one_per_line
908 ARGMATCH_VERIFY (format_args, format_types);
910 static char const *const sort_args[] =
912 "none", "time", "size", "extension", "version", "width", nullptr
914 static enum sort_type const sort_types[] =
916 sort_none, sort_time, sort_size, sort_extension, sort_version, sort_width
918 ARGMATCH_VERIFY (sort_args, sort_types);
920 static char const *const time_args[] =
922 "atime", "access", "use",
923 "ctime", "status",
924 "mtime", "modification",
925 "birth", "creation",
926 nullptr
928 static enum time_type const time_types[] =
930 time_atime, time_atime, time_atime,
931 time_ctime, time_ctime,
932 time_mtime, time_mtime,
933 time_btime, time_btime,
935 ARGMATCH_VERIFY (time_args, time_types);
937 static char const *const when_args[] =
939 /* force and none are for compatibility with another color-ls version */
940 "always", "yes", "force",
941 "never", "no", "none",
942 "auto", "tty", "if-tty", nullptr
944 static enum when_type const when_types[] =
946 when_always, when_always, when_always,
947 when_never, when_never, when_never,
948 when_if_tty, when_if_tty, when_if_tty
950 ARGMATCH_VERIFY (when_args, when_types);
952 /* Information about filling a column. */
953 struct column_info
955 bool valid_len;
956 size_t line_len;
957 size_t *col_arr;
960 /* Array with information about column fullness. */
961 static struct column_info *column_info;
963 /* Maximum number of columns ever possible for this display. */
964 static size_t max_idx;
966 /* The minimum width of a column is 3: 1 character for the name and 2
967 for the separating white space. */
968 enum { MIN_COLUMN_WIDTH = 3 };
971 /* This zero-based index is for the --dired option. It is incremented
972 for each byte of output generated by this program so that the beginning
973 and ending indices (in that output) of every file name can be recorded
974 and later output themselves. */
975 static off_t dired_pos;
977 static void
978 dired_outbyte (char c)
980 dired_pos++;
981 putchar (c);
984 /* Output the buffer S, of length S_LEN, and increment DIRED_POS by S_LEN. */
985 static void
986 dired_outbuf (char const *s, size_t s_len)
988 dired_pos += s_len;
989 fwrite (s, sizeof *s, s_len, stdout);
992 /* Output the string S, and increment DIRED_POS by its length. */
993 static void
994 dired_outstring (char const *s)
996 dired_outbuf (s, strlen (s));
999 static void
1000 dired_indent (void)
1002 if (dired)
1003 dired_outstring (" ");
1006 /* With --dired, store pairs of beginning and ending indices of file names. */
1007 static struct obstack dired_obstack;
1009 /* With --dired, store pairs of beginning and ending indices of any
1010 directory names that appear as headers (just before 'total' line)
1011 for lists of directory entries. Such directory names are seen when
1012 listing hierarchies using -R and when a directory is listed with at
1013 least one other command line argument. */
1014 static struct obstack subdired_obstack;
1016 /* Save the current index on the specified obstack, OBS. */
1017 static void
1018 push_current_dired_pos (struct obstack *obs)
1020 if (dired)
1021 obstack_grow (obs, &dired_pos, sizeof dired_pos);
1024 /* With -R, this stack is used to help detect directory cycles.
1025 The device/inode pairs on this stack mirror the pairs in the
1026 active_dir_set hash table. */
1027 static struct obstack dev_ino_obstack;
1029 /* Push a pair onto the device/inode stack. */
1030 static void
1031 dev_ino_push (dev_t dev, ino_t ino)
1033 void *vdi;
1034 struct dev_ino *di;
1035 int dev_ino_size = sizeof *di;
1036 obstack_blank (&dev_ino_obstack, dev_ino_size);
1037 vdi = obstack_next_free (&dev_ino_obstack);
1038 di = vdi;
1039 di--;
1040 di->st_dev = dev;
1041 di->st_ino = ino;
1044 /* Pop a dev/ino struct off the global dev_ino_obstack
1045 and return that struct. */
1046 static struct dev_ino
1047 dev_ino_pop (void)
1049 void *vdi;
1050 struct dev_ino *di;
1051 int dev_ino_size = sizeof *di;
1052 affirm (dev_ino_size <= obstack_object_size (&dev_ino_obstack));
1053 obstack_blank_fast (&dev_ino_obstack, -dev_ino_size);
1054 vdi = obstack_next_free (&dev_ino_obstack);
1055 di = vdi;
1056 return *di;
1059 static void
1060 assert_matching_dev_ino (char const *name, struct dev_ino di)
1062 MAYBE_UNUSED struct stat sb;
1063 assure (0 <= stat (name, &sb));
1064 assure (sb.st_dev == di.st_dev);
1065 assure (sb.st_ino == di.st_ino);
1068 static char eolbyte = '\n';
1070 /* Write to standard output PREFIX, followed by the quoting style and
1071 a space-separated list of the integers stored in OS all on one line. */
1073 static void
1074 dired_dump_obstack (char const *prefix, struct obstack *os)
1076 size_t n_pos;
1078 n_pos = obstack_object_size (os) / sizeof (dired_pos);
1079 if (n_pos > 0)
1081 off_t *pos = obstack_finish (os);
1082 fputs (prefix, stdout);
1083 for (size_t i = 0; i < n_pos; i++)
1085 intmax_t p = pos[i];
1086 printf (" %"PRIdMAX, p);
1088 putchar ('\n');
1092 /* Return the platform birthtime member of the stat structure,
1093 or fallback to the mtime member, which we have populated
1094 from the statx structure or reset to an invalid timestamp
1095 where birth time is not supported. */
1096 static struct timespec
1097 get_stat_btime (struct stat const *st)
1099 struct timespec btimespec;
1101 #if HAVE_STATX && defined STATX_INO
1102 btimespec = get_stat_mtime (st);
1103 #else
1104 btimespec = get_stat_birthtime (st);
1105 #endif
1107 return btimespec;
1110 #if HAVE_STATX && defined STATX_INO
1111 ATTRIBUTE_PURE
1112 static unsigned int
1113 time_type_to_statx (void)
1115 switch (time_type)
1117 case time_ctime:
1118 return STATX_CTIME;
1119 case time_mtime:
1120 return STATX_MTIME;
1121 case time_atime:
1122 return STATX_ATIME;
1123 case time_btime:
1124 return STATX_BTIME;
1125 default:
1126 unreachable ();
1128 return 0;
1131 ATTRIBUTE_PURE
1132 static unsigned int
1133 calc_req_mask (void)
1135 unsigned int mask = STATX_MODE;
1137 if (print_inode)
1138 mask |= STATX_INO;
1140 if (print_block_size)
1141 mask |= STATX_BLOCKS;
1143 if (format == long_format) {
1144 mask |= STATX_NLINK | STATX_SIZE | time_type_to_statx ();
1145 if (print_owner || print_author)
1146 mask |= STATX_UID;
1147 if (print_group)
1148 mask |= STATX_GID;
1151 switch (sort_type)
1153 case sort_none:
1154 case sort_name:
1155 case sort_version:
1156 case sort_extension:
1157 case sort_width:
1158 break;
1159 case sort_time:
1160 mask |= time_type_to_statx ();
1161 break;
1162 case sort_size:
1163 mask |= STATX_SIZE;
1164 break;
1165 default:
1166 unreachable ();
1169 return mask;
1172 static int
1173 do_statx (int fd, char const *name, struct stat *st, int flags,
1174 unsigned int mask)
1176 struct statx stx;
1177 bool want_btime = mask & STATX_BTIME;
1178 int ret = statx (fd, name, flags | AT_NO_AUTOMOUNT, mask, &stx);
1179 if (ret >= 0)
1181 statx_to_stat (&stx, st);
1182 /* Since we only need one timestamp type,
1183 store birth time in st_mtim. */
1184 if (want_btime)
1186 if (stx.stx_mask & STATX_BTIME)
1187 st->st_mtim = statx_timestamp_to_timespec (stx.stx_btime);
1188 else
1189 st->st_mtim.tv_sec = st->st_mtim.tv_nsec = -1;
1193 return ret;
1196 static int
1197 do_stat (char const *name, struct stat *st)
1199 return do_statx (AT_FDCWD, name, st, 0, calc_req_mask ());
1202 static int
1203 do_lstat (char const *name, struct stat *st)
1205 return do_statx (AT_FDCWD, name, st, AT_SYMLINK_NOFOLLOW, calc_req_mask ());
1208 static int
1209 stat_for_mode (char const *name, struct stat *st)
1211 return do_statx (AT_FDCWD, name, st, 0, STATX_MODE);
1214 /* dev+ino should be static, so no need to sync with backing store */
1215 static int
1216 stat_for_ino (char const *name, struct stat *st)
1218 return do_statx (AT_FDCWD, name, st, 0, STATX_INO);
1221 static int
1222 fstat_for_ino (int fd, struct stat *st)
1224 return do_statx (fd, "", st, AT_EMPTY_PATH, STATX_INO);
1226 #else
1227 static int
1228 do_stat (char const *name, struct stat *st)
1230 return stat (name, st);
1233 static int
1234 do_lstat (char const *name, struct stat *st)
1236 return lstat (name, st);
1239 static int
1240 stat_for_mode (char const *name, struct stat *st)
1242 return stat (name, st);
1245 static int
1246 stat_for_ino (char const *name, struct stat *st)
1248 return stat (name, st);
1251 static int
1252 fstat_for_ino (int fd, struct stat *st)
1254 return fstat (fd, st);
1256 #endif
1258 /* Return the address of the first plain %b spec in FMT, or nullptr if
1259 there is no such spec. %5b etc. do not match, so that user
1260 widths/flags are honored. */
1262 ATTRIBUTE_PURE
1263 static char const *
1264 first_percent_b (char const *fmt)
1266 for (; *fmt; fmt++)
1267 if (fmt[0] == '%')
1268 switch (fmt[1])
1270 case 'b': return fmt;
1271 case '%': fmt++; break;
1273 return nullptr;
1276 static char RFC3986[256];
1277 static void
1278 file_escape_init (void)
1280 for (int i = 0; i < 256; i++)
1281 RFC3986[i] |= c_isalnum (i) || i == '~' || i == '-' || i == '.' || i == '_';
1284 enum { MBSWIDTH_FLAGS = MBSW_REJECT_INVALID | MBSW_REJECT_UNPRINTABLE };
1286 /* Read the abbreviated month names from the locale, to align them
1287 and to determine the max width of the field and to truncate names
1288 greater than our max allowed.
1289 Note even though this handles multibyte locales correctly
1290 it's not restricted to them as single byte locales can have
1291 variable width abbreviated months and also precomputing/caching
1292 the names was seen to increase the performance of ls significantly. */
1294 /* abformat[RECENT][MON] is the format to use for timestamps with
1295 recentness RECENT and month MON. */
1296 enum { ABFORMAT_SIZE = 128 };
1297 static char abformat[2][12][ABFORMAT_SIZE];
1298 /* True if precomputed formats should be used. This can be false if
1299 nl_langinfo fails, if a format or month abbreviation is unusually
1300 long, or if a month abbreviation contains '%'. */
1301 static bool use_abformat;
1303 /* Store into ABMON the abbreviated month names, suitably aligned.
1304 Return true if successful. */
1306 static bool
1307 abmon_init (char abmon[12][ABFORMAT_SIZE])
1309 #ifndef HAVE_NL_LANGINFO
1310 return false;
1311 #else
1312 int max_mon_width = 0;
1313 int mon_width[12];
1314 int mon_len[12];
1316 for (int i = 0; i < 12; i++)
1318 char const *abbr = nl_langinfo (ABMON_1 + i);
1319 mon_len[i] = strnlen (abbr, ABFORMAT_SIZE);
1320 if (mon_len[i] == ABFORMAT_SIZE)
1321 return false;
1322 if (strchr (abbr, '%'))
1323 return false;
1324 mon_width[i] = mbswidth (strcpy (abmon[i], abbr), MBSWIDTH_FLAGS);
1325 if (mon_width[i] < 0)
1326 return false;
1327 max_mon_width = MAX (max_mon_width, mon_width[i]);
1330 for (int i = 0; i < 12; i++)
1332 int fill = max_mon_width - mon_width[i];
1333 if (ABFORMAT_SIZE - mon_len[i] <= fill)
1334 return false;
1335 bool align_left = !isdigit (to_uchar (abmon[i][0]));
1336 int fill_offset;
1337 if (align_left)
1338 fill_offset = mon_len[i];
1339 else
1341 memmove (abmon[i] + fill, abmon[i], mon_len[i]);
1342 fill_offset = 0;
1344 memset (abmon[i] + fill_offset, ' ', fill);
1345 abmon[i][mon_len[i] + fill] = '\0';
1348 return true;
1349 #endif
1352 /* Initialize ABFORMAT and USE_ABFORMAT. */
1354 static void
1355 abformat_init (void)
1357 char const *pb[2];
1358 for (int recent = 0; recent < 2; recent++)
1359 pb[recent] = first_percent_b (long_time_format[recent]);
1360 if (! (pb[0] || pb[1]))
1361 return;
1363 char abmon[12][ABFORMAT_SIZE];
1364 if (! abmon_init (abmon))
1365 return;
1367 for (int recent = 0; recent < 2; recent++)
1369 char const *fmt = long_time_format[recent];
1370 for (int i = 0; i < 12; i++)
1372 char *nfmt = abformat[recent][i];
1373 int nbytes;
1375 if (! pb[recent])
1376 nbytes = snprintf (nfmt, ABFORMAT_SIZE, "%s", fmt);
1377 else
1379 if (! (pb[recent] - fmt <= MIN (ABFORMAT_SIZE, INT_MAX)))
1380 return;
1381 int prefix_len = pb[recent] - fmt;
1382 nbytes = snprintf (nfmt, ABFORMAT_SIZE, "%.*s%s%s",
1383 prefix_len, fmt, abmon[i], pb[recent] + 2);
1386 if (! (0 <= nbytes && nbytes < ABFORMAT_SIZE))
1387 return;
1391 use_abformat = true;
1394 static size_t
1395 dev_ino_hash (void const *x, size_t table_size)
1397 struct dev_ino const *p = x;
1398 return (uintmax_t) p->st_ino % table_size;
1401 static bool
1402 dev_ino_compare (void const *x, void const *y)
1404 struct dev_ino const *a = x;
1405 struct dev_ino const *b = y;
1406 return SAME_INODE (*a, *b) ? true : false;
1409 static void
1410 dev_ino_free (void *x)
1412 free (x);
1415 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
1416 active directories. Return true if there is already a matching
1417 entry in the table. */
1419 static bool
1420 visit_dir (dev_t dev, ino_t ino)
1422 struct dev_ino *ent;
1423 struct dev_ino *ent_from_table;
1424 bool found_match;
1426 ent = xmalloc (sizeof *ent);
1427 ent->st_ino = ino;
1428 ent->st_dev = dev;
1430 /* Attempt to insert this entry into the table. */
1431 ent_from_table = hash_insert (active_dir_set, ent);
1433 if (ent_from_table == nullptr)
1435 /* Insertion failed due to lack of memory. */
1436 xalloc_die ();
1439 found_match = (ent_from_table != ent);
1441 if (found_match)
1443 /* ent was not inserted, so free it. */
1444 free (ent);
1447 return found_match;
1450 static void
1451 free_pending_ent (struct pending *p)
1453 free (p->name);
1454 free (p->realname);
1455 free (p);
1458 static bool
1459 is_colored (enum indicator_no type)
1461 size_t len = color_indicator[type].len;
1462 char const *s = color_indicator[type].string;
1463 return ! (len == 0
1464 || (len == 1 && STRNCMP_LIT (s, "0") == 0)
1465 || (len == 2 && STRNCMP_LIT (s, "00") == 0));
1468 static void
1469 restore_default_color (void)
1471 put_indicator (&color_indicator[C_LEFT]);
1472 put_indicator (&color_indicator[C_RIGHT]);
1475 static void
1476 set_normal_color (void)
1478 if (print_with_color && is_colored (C_NORM))
1480 put_indicator (&color_indicator[C_LEFT]);
1481 put_indicator (&color_indicator[C_NORM]);
1482 put_indicator (&color_indicator[C_RIGHT]);
1486 /* An ordinary signal was received; arrange for the program to exit. */
1488 static void
1489 sighandler (int sig)
1491 if (! SA_NOCLDSTOP)
1492 signal (sig, SIG_IGN);
1493 if (! interrupt_signal)
1494 interrupt_signal = sig;
1497 /* A SIGTSTP was received; arrange for the program to suspend itself. */
1499 static void
1500 stophandler (int sig)
1502 if (! SA_NOCLDSTOP)
1503 signal (sig, stophandler);
1504 if (! interrupt_signal)
1505 stop_signal_count++;
1508 /* Process any pending signals. If signals are caught, this function
1509 should be called periodically. Ideally there should never be an
1510 unbounded amount of time when signals are not being processed.
1511 Signal handling can restore the default colors, so callers must
1512 immediately change colors after invoking this function. */
1514 static void
1515 process_signals (void)
1517 while (interrupt_signal || stop_signal_count)
1519 int sig;
1520 int stops;
1521 sigset_t oldset;
1523 if (used_color)
1524 restore_default_color ();
1525 fflush (stdout);
1527 sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
1529 /* Reload interrupt_signal and stop_signal_count, in case a new
1530 signal was handled before sigprocmask took effect. */
1531 sig = interrupt_signal;
1532 stops = stop_signal_count;
1534 /* SIGTSTP is special, since the application can receive that signal
1535 more than once. In this case, don't set the signal handler to the
1536 default. Instead, just raise the uncatchable SIGSTOP. */
1537 if (stops)
1539 stop_signal_count = stops - 1;
1540 sig = SIGSTOP;
1542 else
1543 signal (sig, SIG_DFL);
1545 /* Exit or suspend the program. */
1546 raise (sig);
1547 sigprocmask (SIG_SETMASK, &oldset, nullptr);
1549 /* If execution reaches here, then the program has been
1550 continued (after being suspended). */
1554 /* Setup signal handlers if INIT is true,
1555 otherwise restore to the default. */
1557 static void
1558 signal_setup (bool init)
1560 /* The signals that are trapped, and the number of such signals. */
1561 static int const sig[] =
1563 /* This one is handled specially. */
1564 SIGTSTP,
1566 /* The usual suspects. */
1567 SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM,
1568 #ifdef SIGPOLL
1569 SIGPOLL,
1570 #endif
1571 #ifdef SIGPROF
1572 SIGPROF,
1573 #endif
1574 #ifdef SIGVTALRM
1575 SIGVTALRM,
1576 #endif
1577 #ifdef SIGXCPU
1578 SIGXCPU,
1579 #endif
1580 #ifdef SIGXFSZ
1581 SIGXFSZ,
1582 #endif
1584 enum { nsigs = ARRAY_CARDINALITY (sig) };
1586 #if ! SA_NOCLDSTOP
1587 static bool caught_sig[nsigs];
1588 #endif
1590 int j;
1592 if (init)
1594 #if SA_NOCLDSTOP
1595 struct sigaction act;
1597 sigemptyset (&caught_signals);
1598 for (j = 0; j < nsigs; j++)
1600 sigaction (sig[j], nullptr, &act);
1601 if (act.sa_handler != SIG_IGN)
1602 sigaddset (&caught_signals, sig[j]);
1605 act.sa_mask = caught_signals;
1606 act.sa_flags = SA_RESTART;
1608 for (j = 0; j < nsigs; j++)
1609 if (sigismember (&caught_signals, sig[j]))
1611 act.sa_handler = sig[j] == SIGTSTP ? stophandler : sighandler;
1612 sigaction (sig[j], &act, nullptr);
1614 #else
1615 for (j = 0; j < nsigs; j++)
1617 caught_sig[j] = (signal (sig[j], SIG_IGN) != SIG_IGN);
1618 if (caught_sig[j])
1620 signal (sig[j], sig[j] == SIGTSTP ? stophandler : sighandler);
1621 siginterrupt (sig[j], 0);
1624 #endif
1626 else /* restore. */
1628 #if SA_NOCLDSTOP
1629 for (j = 0; j < nsigs; j++)
1630 if (sigismember (&caught_signals, sig[j]))
1631 signal (sig[j], SIG_DFL);
1632 #else
1633 for (j = 0; j < nsigs; j++)
1634 if (caught_sig[j])
1635 signal (sig[j], SIG_DFL);
1636 #endif
1640 static void
1641 signal_init (void)
1643 signal_setup (true);
1646 static void
1647 signal_restore (void)
1649 signal_setup (false);
1653 main (int argc, char **argv)
1655 int i;
1656 struct pending *thispend;
1657 int n_files;
1659 initialize_main (&argc, &argv);
1660 set_program_name (argv[0]);
1661 setlocale (LC_ALL, "");
1662 bindtextdomain (PACKAGE, LOCALEDIR);
1663 textdomain (PACKAGE);
1665 initialize_exit_failure (LS_FAILURE);
1666 atexit (close_stdout);
1668 static_assert (ARRAY_CARDINALITY (color_indicator) + 1
1669 == ARRAY_CARDINALITY (indicator_name));
1671 exit_status = EXIT_SUCCESS;
1672 print_dir_name = true;
1673 pending_dirs = nullptr;
1675 current_time.tv_sec = TYPE_MINIMUM (time_t);
1676 current_time.tv_nsec = -1;
1678 i = decode_switches (argc, argv);
1680 if (print_with_color)
1681 parse_ls_color ();
1683 /* Test print_with_color again, because the call to parse_ls_color
1684 may have just reset it -- e.g., if LS_COLORS is invalid. */
1686 if (print_with_color)
1688 /* Don't use TAB characters in output. Some terminal
1689 emulators can't handle the combination of tabs and
1690 color codes on the same line. */
1691 tabsize = 0;
1694 if (directories_first)
1695 check_symlink_mode = true;
1696 else if (print_with_color)
1698 /* Avoid following symbolic links when possible. */
1699 if (is_colored (C_ORPHAN)
1700 || (is_colored (C_EXEC) && color_symlink_as_referent)
1701 || (is_colored (C_MISSING) && format == long_format))
1702 check_symlink_mode = true;
1705 if (dereference == DEREF_UNDEFINED)
1706 dereference = ((immediate_dirs
1707 || indicator_style == classify
1708 || format == long_format)
1709 ? DEREF_NEVER
1710 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
1712 /* When using -R, initialize a data structure we'll use to
1713 detect any directory cycles. */
1714 if (recursive)
1716 active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, nullptr,
1717 dev_ino_hash,
1718 dev_ino_compare,
1719 dev_ino_free);
1720 if (active_dir_set == nullptr)
1721 xalloc_die ();
1723 obstack_init (&dev_ino_obstack);
1726 localtz = tzalloc (getenv ("TZ"));
1728 format_needs_stat = sort_type == sort_time || sort_type == sort_size
1729 || format == long_format
1730 || print_scontext
1731 || print_block_size;
1732 format_needs_type = (! format_needs_stat
1733 && (recursive
1734 || print_with_color
1735 || indicator_style != none
1736 || directories_first));
1738 if (dired)
1740 obstack_init (&dired_obstack);
1741 obstack_init (&subdired_obstack);
1744 if (print_hyperlink)
1746 file_escape_init ();
1748 hostname = xgethostname ();
1749 /* The hostname is generally ignored,
1750 so ignore failures obtaining it. */
1751 if (! hostname)
1752 hostname = "";
1755 cwd_n_alloc = 100;
1756 cwd_file = xnmalloc (cwd_n_alloc, sizeof *cwd_file);
1757 cwd_n_used = 0;
1759 clear_files ();
1761 n_files = argc - i;
1763 if (n_files <= 0)
1765 if (immediate_dirs)
1766 gobble_file (".", directory, NOT_AN_INODE_NUMBER, true, "");
1767 else
1768 queue_directory (".", nullptr, true);
1770 else
1772 gobble_file (argv[i++], unknown, NOT_AN_INODE_NUMBER, true, "");
1773 while (i < argc);
1775 if (cwd_n_used)
1777 sort_files ();
1778 if (!immediate_dirs)
1779 extract_dirs_from_files (nullptr, true);
1780 /* 'cwd_n_used' might be zero now. */
1783 /* In the following if/else blocks, it is sufficient to test 'pending_dirs'
1784 (and not pending_dirs->name) because there may be no markers in the queue
1785 at this point. A marker may be enqueued when extract_dirs_from_files is
1786 called with a non-empty string or via print_dir. */
1787 if (cwd_n_used)
1789 print_current_files ();
1790 if (pending_dirs)
1791 dired_outbyte ('\n');
1793 else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1794 print_dir_name = false;
1796 while (pending_dirs)
1798 thispend = pending_dirs;
1799 pending_dirs = pending_dirs->next;
1801 if (LOOP_DETECT)
1803 if (thispend->name == nullptr)
1805 /* thispend->name == nullptr means this is a marker entry
1806 indicating we've finished processing the directory.
1807 Use its dev/ino numbers to remove the corresponding
1808 entry from the active_dir_set hash table. */
1809 struct dev_ino di = dev_ino_pop ();
1810 struct dev_ino *found = hash_remove (active_dir_set, &di);
1811 if (false)
1812 assert_matching_dev_ino (thispend->realname, di);
1813 affirm (found);
1814 dev_ino_free (found);
1815 free_pending_ent (thispend);
1816 continue;
1820 print_dir (thispend->name, thispend->realname,
1821 thispend->command_line_arg);
1823 free_pending_ent (thispend);
1824 print_dir_name = true;
1827 if (print_with_color && used_color)
1829 int j;
1831 /* Skip the restore when it would be a no-op, i.e.,
1832 when left is "\033[" and right is "m". */
1833 if (!(color_indicator[C_LEFT].len == 2
1834 && memcmp (color_indicator[C_LEFT].string, "\033[", 2) == 0
1835 && color_indicator[C_RIGHT].len == 1
1836 && color_indicator[C_RIGHT].string[0] == 'm'))
1837 restore_default_color ();
1839 fflush (stdout);
1841 signal_restore ();
1843 /* Act on any signals that arrived before the default was restored.
1844 This can process signals out of order, but there doesn't seem to
1845 be an easy way to do them in order, and the order isn't that
1846 important anyway. */
1847 for (j = stop_signal_count; j; j--)
1848 raise (SIGSTOP);
1849 j = interrupt_signal;
1850 if (j)
1851 raise (j);
1854 if (dired)
1856 /* No need to free these since we're about to exit. */
1857 dired_dump_obstack ("//DIRED//", &dired_obstack);
1858 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1859 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1860 quoting_style_args[get_quoting_style (filename_quoting_options)]);
1863 if (LOOP_DETECT)
1865 assure (hash_get_n_entries (active_dir_set) == 0);
1866 hash_free (active_dir_set);
1869 return exit_status;
1872 /* Return the line length indicated by the value given by SPEC, or -1
1873 if unsuccessful. 0 means no limit on line length. */
1875 static ptrdiff_t
1876 decode_line_length (char const *spec)
1878 uintmax_t val;
1880 /* Treat too-large values as if they were 0, which is
1881 effectively infinity. */
1882 switch (xstrtoumax (spec, nullptr, 0, &val, ""))
1884 case LONGINT_OK:
1885 return val <= MIN (PTRDIFF_MAX, SIZE_MAX) ? val : 0;
1887 case LONGINT_OVERFLOW:
1888 return 0;
1890 default:
1891 return -1;
1895 /* Return true if standard output is a tty, caching the result. */
1897 static bool
1898 stdout_isatty (void)
1900 static signed char out_tty = -1;
1901 if (out_tty < 0)
1902 out_tty = isatty (STDOUT_FILENO);
1903 assume (out_tty == 0 || out_tty == 1);
1904 return out_tty;
1907 /* Set all the option flags according to the switches specified.
1908 Return the index of the first non-option argument. */
1910 static int
1911 decode_switches (int argc, char **argv)
1913 char *time_style_option = nullptr;
1915 /* These variables are false or -1 unless a switch says otherwise. */
1916 bool kibibytes_specified = false;
1917 int format_opt = -1;
1918 int hide_control_chars_opt = -1;
1919 int quoting_style_opt = -1;
1920 int sort_opt = -1;
1921 ptrdiff_t tabsize_opt = -1;
1922 ptrdiff_t width_opt = -1;
1924 while (true)
1926 int oi = -1;
1927 int c = getopt_long (argc, argv,
1928 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1",
1929 long_options, &oi);
1930 if (c == -1)
1931 break;
1933 switch (c)
1935 case 'a':
1936 ignore_mode = IGNORE_MINIMAL;
1937 break;
1939 case 'b':
1940 quoting_style_opt = escape_quoting_style;
1941 break;
1943 case 'c':
1944 time_type = time_ctime;
1945 break;
1947 case 'd':
1948 immediate_dirs = true;
1949 break;
1951 case 'f':
1952 /* Same as -a -U -1 --color=none --hyperlink=none,
1953 while disabling -s. */
1954 ignore_mode = IGNORE_MINIMAL;
1955 sort_opt = sort_none;
1956 if (format_opt == long_format)
1957 format_opt = -1;
1958 print_with_color = false;
1959 print_hyperlink = false;
1960 print_block_size = false;
1961 break;
1963 case FILE_TYPE_INDICATOR_OPTION: /* --file-type */
1964 indicator_style = file_type;
1965 break;
1967 case 'g':
1968 format_opt = long_format;
1969 print_owner = false;
1970 break;
1972 case 'h':
1973 file_human_output_opts = human_output_opts =
1974 human_autoscale | human_SI | human_base_1024;
1975 file_output_block_size = output_block_size = 1;
1976 break;
1978 case 'i':
1979 print_inode = true;
1980 break;
1982 case 'k':
1983 kibibytes_specified = true;
1984 break;
1986 case 'l':
1987 format_opt = long_format;
1988 break;
1990 case 'm':
1991 format_opt = with_commas;
1992 break;
1994 case 'n':
1995 numeric_ids = true;
1996 format_opt = long_format;
1997 break;
1999 case 'o': /* Just like -l, but don't display group info. */
2000 format_opt = long_format;
2001 print_group = false;
2002 break;
2004 case 'p':
2005 indicator_style = slash;
2006 break;
2008 case 'q':
2009 hide_control_chars_opt = true;
2010 break;
2012 case 'r':
2013 sort_reverse = true;
2014 break;
2016 case 's':
2017 print_block_size = true;
2018 break;
2020 case 't':
2021 sort_opt = sort_time;
2022 break;
2024 case 'u':
2025 time_type = time_atime;
2026 break;
2028 case 'v':
2029 sort_opt = sort_version;
2030 break;
2032 case 'w':
2033 width_opt = decode_line_length (optarg);
2034 if (width_opt < 0)
2035 error (LS_FAILURE, 0, "%s: %s", _("invalid line width"),
2036 quote (optarg));
2037 break;
2039 case 'x':
2040 format_opt = horizontal;
2041 break;
2043 case 'A':
2044 ignore_mode = IGNORE_DOT_AND_DOTDOT;
2045 break;
2047 case 'B':
2048 add_ignore_pattern ("*~");
2049 add_ignore_pattern (".*~");
2050 break;
2052 case 'C':
2053 format_opt = many_per_line;
2054 break;
2056 case 'D':
2057 dired = true;
2058 break;
2060 case 'F':
2062 int i;
2063 if (optarg)
2064 i = XARGMATCH ("--classify", optarg, when_args, when_types);
2065 else
2066 /* Using --classify with no argument is equivalent to using
2067 --classify=always. */
2068 i = when_always;
2070 if (i == when_always || (i == when_if_tty && stdout_isatty ()))
2071 indicator_style = classify;
2072 break;
2075 case 'G': /* inhibit display of group info */
2076 print_group = false;
2077 break;
2079 case 'H':
2080 dereference = DEREF_COMMAND_LINE_ARGUMENTS;
2081 break;
2083 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
2084 dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
2085 break;
2087 case 'I':
2088 add_ignore_pattern (optarg);
2089 break;
2091 case 'L':
2092 dereference = DEREF_ALWAYS;
2093 break;
2095 case 'N':
2096 quoting_style_opt = literal_quoting_style;
2097 break;
2099 case 'Q':
2100 quoting_style_opt = c_quoting_style;
2101 break;
2103 case 'R':
2104 recursive = true;
2105 break;
2107 case 'S':
2108 sort_opt = sort_size;
2109 break;
2111 case 'T':
2112 tabsize_opt = xnumtoumax (optarg, 0, 0, MIN (PTRDIFF_MAX, SIZE_MAX),
2113 "", _("invalid tab size"), LS_FAILURE);
2114 break;
2116 case 'U':
2117 sort_opt = sort_none;
2118 break;
2120 case 'X':
2121 sort_opt = sort_extension;
2122 break;
2124 case '1':
2125 /* -1 has no effect after -l. */
2126 if (format_opt != long_format)
2127 format_opt = one_per_line;
2128 break;
2130 case AUTHOR_OPTION:
2131 print_author = true;
2132 break;
2134 case HIDE_OPTION:
2136 struct ignore_pattern *hide = xmalloc (sizeof *hide);
2137 hide->pattern = optarg;
2138 hide->next = hide_patterns;
2139 hide_patterns = hide;
2141 break;
2143 case SORT_OPTION:
2144 sort_opt = XARGMATCH ("--sort", optarg, sort_args, sort_types);
2145 break;
2147 case GROUP_DIRECTORIES_FIRST_OPTION:
2148 directories_first = true;
2149 break;
2151 case TIME_OPTION:
2152 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
2153 break;
2155 case FORMAT_OPTION:
2156 format_opt = XARGMATCH ("--format", optarg, format_args,
2157 format_types);
2158 break;
2160 case FULL_TIME_OPTION:
2161 format_opt = long_format;
2162 time_style_option = bad_cast ("full-iso");
2163 break;
2165 case COLOR_OPTION:
2167 int i;
2168 if (optarg)
2169 i = XARGMATCH ("--color", optarg, when_args, when_types);
2170 else
2171 /* Using --color with no argument is equivalent to using
2172 --color=always. */
2173 i = when_always;
2175 print_with_color = (i == when_always
2176 || (i == when_if_tty && stdout_isatty ()));
2177 break;
2180 case HYPERLINK_OPTION:
2182 int i;
2183 if (optarg)
2184 i = XARGMATCH ("--hyperlink", optarg, when_args, when_types);
2185 else
2186 /* Using --hyperlink with no argument is equivalent to using
2187 --hyperlink=always. */
2188 i = when_always;
2190 print_hyperlink = (i == when_always
2191 || (i == when_if_tty && stdout_isatty ()));
2192 break;
2195 case INDICATOR_STYLE_OPTION:
2196 indicator_style = XARGMATCH ("--indicator-style", optarg,
2197 indicator_style_args,
2198 indicator_style_types);
2199 break;
2201 case QUOTING_STYLE_OPTION:
2202 quoting_style_opt = XARGMATCH ("--quoting-style", optarg,
2203 quoting_style_args,
2204 quoting_style_vals);
2205 break;
2207 case TIME_STYLE_OPTION:
2208 time_style_option = optarg;
2209 break;
2211 case SHOW_CONTROL_CHARS_OPTION:
2212 hide_control_chars_opt = false;
2213 break;
2215 case BLOCK_SIZE_OPTION:
2217 enum strtol_error e = human_options (optarg, &human_output_opts,
2218 &output_block_size);
2219 if (e != LONGINT_OK)
2220 xstrtol_fatal (e, oi, 0, long_options, optarg);
2221 file_human_output_opts = human_output_opts;
2222 file_output_block_size = output_block_size;
2224 break;
2226 case SI_OPTION:
2227 file_human_output_opts = human_output_opts =
2228 human_autoscale | human_SI;
2229 file_output_block_size = output_block_size = 1;
2230 break;
2232 case 'Z':
2233 print_scontext = true;
2234 break;
2236 case ZERO_OPTION:
2237 eolbyte = 0;
2238 hide_control_chars_opt = false;
2239 if (format_opt != long_format)
2240 format_opt = one_per_line;
2241 print_with_color = false;
2242 quoting_style_opt = literal_quoting_style;
2243 break;
2245 case_GETOPT_HELP_CHAR;
2247 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
2249 default:
2250 usage (LS_FAILURE);
2254 if (! output_block_size)
2256 char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
2257 human_options (ls_block_size,
2258 &human_output_opts, &output_block_size);
2259 if (ls_block_size || getenv ("BLOCK_SIZE"))
2261 file_human_output_opts = human_output_opts;
2262 file_output_block_size = output_block_size;
2264 if (kibibytes_specified)
2266 human_output_opts = 0;
2267 output_block_size = 1024;
2271 format = (0 <= format_opt ? format_opt
2272 : ls_mode == LS_LS ? (stdout_isatty ()
2273 ? many_per_line : one_per_line)
2274 : ls_mode == LS_MULTI_COL ? many_per_line
2275 : /* ls_mode == LS_LONG_FORMAT */ long_format);
2277 /* If the line length was not set by a switch but is needed to determine
2278 output, go to the work of obtaining it from the environment. */
2279 ptrdiff_t linelen = width_opt;
2280 if (format == many_per_line || format == horizontal || format == with_commas
2281 || print_with_color)
2283 #ifdef TIOCGWINSZ
2284 if (linelen < 0)
2286 /* Suppress bogus warning re comparing ws.ws_col to big integer. */
2287 # if 4 < __GNUC__ + (6 <= __GNUC_MINOR__)
2288 # pragma GCC diagnostic push
2289 # pragma GCC diagnostic ignored "-Wtype-limits"
2290 # endif
2291 struct winsize ws;
2292 if (stdout_isatty ()
2293 && 0 <= ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws)
2294 && 0 < ws.ws_col)
2295 linelen = ws.ws_col <= MIN (PTRDIFF_MAX, SIZE_MAX) ? ws.ws_col : 0;
2296 # if 4 < __GNUC__ + (6 <= __GNUC_MINOR__)
2297 # pragma GCC diagnostic pop
2298 # endif
2300 #endif
2301 if (linelen < 0)
2303 char const *p = getenv ("COLUMNS");
2304 if (p && *p)
2306 linelen = decode_line_length (p);
2307 if (linelen < 0)
2308 error (0, 0,
2309 _("ignoring invalid width"
2310 " in environment variable COLUMNS: %s"),
2311 quote (p));
2316 line_length = linelen < 0 ? 80 : linelen;
2318 /* Determine the max possible number of display columns. */
2319 max_idx = line_length / MIN_COLUMN_WIDTH;
2320 /* Account for first display column not having a separator,
2321 or line_lengths shorter than MIN_COLUMN_WIDTH. */
2322 max_idx += line_length % MIN_COLUMN_WIDTH != 0;
2324 if (format == many_per_line || format == horizontal || format == with_commas)
2326 if (0 <= tabsize_opt)
2327 tabsize = tabsize_opt;
2328 else
2330 tabsize = 8;
2331 char const *p = getenv ("TABSIZE");
2332 if (p)
2334 uintmax_t tmp;
2335 if (xstrtoumax (p, nullptr, 0, &tmp, "") == LONGINT_OK
2336 && tmp <= SIZE_MAX)
2337 tabsize = tmp;
2338 else
2339 error (0, 0,
2340 _("ignoring invalid tab size"
2341 " in environment variable TABSIZE: %s"),
2342 quote (p));
2347 qmark_funny_chars = (hide_control_chars_opt < 0
2348 ? ls_mode == LS_LS && stdout_isatty ()
2349 : hide_control_chars_opt);
2351 int qs = quoting_style_opt;
2352 if (qs < 0)
2353 qs = getenv_quoting_style ();
2354 if (qs < 0)
2355 qs = (ls_mode == LS_LS
2356 ? (stdout_isatty () ? shell_escape_quoting_style : -1)
2357 : escape_quoting_style);
2358 if (0 <= qs)
2359 set_quoting_style (nullptr, qs);
2360 qs = get_quoting_style (nullptr);
2361 align_variable_outer_quotes
2362 = ((format == long_format
2363 || ((format == many_per_line || format == horizontal) && line_length))
2364 && (qs == shell_quoting_style
2365 || qs == shell_escape_quoting_style
2366 || qs == c_maybe_quoting_style));
2367 filename_quoting_options = clone_quoting_options (nullptr);
2368 if (qs == escape_quoting_style)
2369 set_char_quoting (filename_quoting_options, ' ', 1);
2370 if (file_type <= indicator_style)
2372 char const *p;
2373 for (p = &"*=>@|"[indicator_style - file_type]; *p; p++)
2374 set_char_quoting (filename_quoting_options, *p, 1);
2377 dirname_quoting_options = clone_quoting_options (nullptr);
2378 set_char_quoting (dirname_quoting_options, ':', 1);
2380 /* --dired is meaningful only with --format=long (-l) and sans --hyperlink.
2381 Otherwise, ignore it. FIXME: warn about this?
2382 Alternatively, make --dired imply --format=long? */
2383 dired &= (format == long_format) & !print_hyperlink;
2385 if (eolbyte < dired)
2386 error (LS_FAILURE, 0, _("--dired and --zero are incompatible"));
2388 /* If -c or -u is specified and not -l (or any other option that implies -l),
2389 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
2390 The behavior of ls when using either -c or -u but with neither -l nor -t
2391 appears to be unspecified by POSIX. So, with GNU ls, '-u' alone means
2392 sort by atime (this is the one that's not specified by the POSIX spec),
2393 -lu means show atime and sort by name, -lut means show atime and sort
2394 by atime. */
2396 sort_type = (0 <= sort_opt ? sort_opt
2397 : (format != long_format
2398 && (time_type == time_ctime || time_type == time_atime
2399 || time_type == time_btime))
2400 ? sort_time : sort_name);
2402 if (format == long_format)
2404 char *style = time_style_option;
2405 static char const posix_prefix[] = "posix-";
2407 if (! style)
2408 if (! (style = getenv ("TIME_STYLE")))
2409 style = bad_cast ("locale");
2411 while (STREQ_LEN (style, posix_prefix, sizeof posix_prefix - 1))
2413 if (! hard_locale (LC_TIME))
2414 return optind;
2415 style += sizeof posix_prefix - 1;
2418 if (*style == '+')
2420 char *p0 = style + 1;
2421 char *p1 = strchr (p0, '\n');
2422 if (! p1)
2423 p1 = p0;
2424 else
2426 if (strchr (p1 + 1, '\n'))
2427 error (LS_FAILURE, 0, _("invalid time style format %s"),
2428 quote (p0));
2429 *p1++ = '\0';
2431 long_time_format[0] = p0;
2432 long_time_format[1] = p1;
2434 else
2436 ptrdiff_t res = argmatch (style, time_style_args,
2437 (char const *) time_style_types,
2438 sizeof (*time_style_types));
2439 if (res < 0)
2441 /* This whole block used to be a simple use of XARGMATCH.
2442 but that didn't print the "posix-"-prefixed variants or
2443 the "+"-prefixed format string option upon failure. */
2444 argmatch_invalid ("time style", style, res);
2446 /* The following is a manual expansion of argmatch_valid,
2447 but with the added "+ ..." description and the [posix-]
2448 prefixes prepended. Note that this simplification works
2449 only because all four existing time_style_types values
2450 are distinct. */
2451 fputs (_("Valid arguments are:\n"), stderr);
2452 char const *const *p = time_style_args;
2453 while (*p)
2454 fprintf (stderr, " - [posix-]%s\n", *p++);
2455 fputs (_(" - +FORMAT (e.g., +%H:%M) for a 'date'-style"
2456 " format\n"), stderr);
2457 usage (LS_FAILURE);
2459 switch (res)
2461 case full_iso_time_style:
2462 long_time_format[0] = long_time_format[1] =
2463 "%Y-%m-%d %H:%M:%S.%N %z";
2464 break;
2466 case long_iso_time_style:
2467 long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
2468 break;
2470 case iso_time_style:
2471 long_time_format[0] = "%Y-%m-%d ";
2472 long_time_format[1] = "%m-%d %H:%M";
2473 break;
2475 case locale_time_style:
2476 if (hard_locale (LC_TIME))
2478 for (int i = 0; i < 2; i++)
2479 long_time_format[i] =
2480 dcgettext (nullptr, long_time_format[i], LC_TIME);
2485 abformat_init ();
2488 return optind;
2491 /* Parse a string as part of the LS_COLORS variable; this may involve
2492 decoding all kinds of escape characters. If equals_end is set an
2493 unescaped equal sign ends the string, otherwise only a : or \0
2494 does. Set *OUTPUT_COUNT to the number of bytes output. Return
2495 true if successful.
2497 The resulting string is *not* null-terminated, but may contain
2498 embedded nulls.
2500 Note that both dest and src are char **; on return they point to
2501 the first free byte after the array and the character that ended
2502 the input string, respectively. */
2504 static bool
2505 get_funky_string (char **dest, char const **src, bool equals_end,
2506 size_t *output_count)
2508 char num; /* For numerical codes */
2509 size_t count; /* Something to count with */
2510 enum {
2511 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
2512 } state;
2513 char const *p;
2514 char *q;
2516 p = *src; /* We don't want to double-indirect */
2517 q = *dest; /* the whole darn time. */
2519 count = 0; /* No characters counted in yet. */
2520 num = 0;
2522 state = ST_GND; /* Start in ground state. */
2523 while (state < ST_END)
2525 switch (state)
2527 case ST_GND: /* Ground state (no escapes) */
2528 switch (*p)
2530 case ':':
2531 case '\0':
2532 state = ST_END; /* End of string */
2533 break;
2534 case '\\':
2535 state = ST_BACKSLASH; /* Backslash escape sequence */
2536 ++p;
2537 break;
2538 case '^':
2539 state = ST_CARET; /* Caret escape */
2540 ++p;
2541 break;
2542 case '=':
2543 if (equals_end)
2545 state = ST_END; /* End */
2546 break;
2548 FALLTHROUGH;
2549 default:
2550 *(q++) = *(p++);
2551 ++count;
2552 break;
2554 break;
2556 case ST_BACKSLASH: /* Backslash escaped character */
2557 switch (*p)
2559 case '0':
2560 case '1':
2561 case '2':
2562 case '3':
2563 case '4':
2564 case '5':
2565 case '6':
2566 case '7':
2567 state = ST_OCTAL; /* Octal sequence */
2568 num = *p - '0';
2569 break;
2570 case 'x':
2571 case 'X':
2572 state = ST_HEX; /* Hex sequence */
2573 num = 0;
2574 break;
2575 case 'a': /* Bell */
2576 num = '\a';
2577 break;
2578 case 'b': /* Backspace */
2579 num = '\b';
2580 break;
2581 case 'e': /* Escape */
2582 num = 27;
2583 break;
2584 case 'f': /* Form feed */
2585 num = '\f';
2586 break;
2587 case 'n': /* Newline */
2588 num = '\n';
2589 break;
2590 case 'r': /* Carriage return */
2591 num = '\r';
2592 break;
2593 case 't': /* Tab */
2594 num = '\t';
2595 break;
2596 case 'v': /* Vtab */
2597 num = '\v';
2598 break;
2599 case '?': /* Delete */
2600 num = 127;
2601 break;
2602 case '_': /* Space */
2603 num = ' ';
2604 break;
2605 case '\0': /* End of string */
2606 state = ST_ERROR; /* Error! */
2607 break;
2608 default: /* Escaped character like \ ^ : = */
2609 num = *p;
2610 break;
2612 if (state == ST_BACKSLASH)
2614 *(q++) = num;
2615 ++count;
2616 state = ST_GND;
2618 ++p;
2619 break;
2621 case ST_OCTAL: /* Octal sequence */
2622 if (*p < '0' || *p > '7')
2624 *(q++) = num;
2625 ++count;
2626 state = ST_GND;
2628 else
2629 num = (num << 3) + (*(p++) - '0');
2630 break;
2632 case ST_HEX: /* Hex sequence */
2633 switch (*p)
2635 case '0':
2636 case '1':
2637 case '2':
2638 case '3':
2639 case '4':
2640 case '5':
2641 case '6':
2642 case '7':
2643 case '8':
2644 case '9':
2645 num = (num << 4) + (*(p++) - '0');
2646 break;
2647 case 'a':
2648 case 'b':
2649 case 'c':
2650 case 'd':
2651 case 'e':
2652 case 'f':
2653 num = (num << 4) + (*(p++) - 'a') + 10;
2654 break;
2655 case 'A':
2656 case 'B':
2657 case 'C':
2658 case 'D':
2659 case 'E':
2660 case 'F':
2661 num = (num << 4) + (*(p++) - 'A') + 10;
2662 break;
2663 default:
2664 *(q++) = num;
2665 ++count;
2666 state = ST_GND;
2667 break;
2669 break;
2671 case ST_CARET: /* Caret escape */
2672 state = ST_GND; /* Should be the next state... */
2673 if (*p >= '@' && *p <= '~')
2675 *(q++) = *(p++) & 037;
2676 ++count;
2678 else if (*p == '?')
2680 *(q++) = 127;
2681 ++count;
2683 else
2684 state = ST_ERROR;
2685 break;
2687 default:
2688 unreachable ();
2692 *dest = q;
2693 *src = p;
2694 *output_count = count;
2696 return state != ST_ERROR;
2699 enum parse_state
2701 PS_START = 1,
2702 PS_2,
2703 PS_3,
2704 PS_4,
2705 PS_DONE,
2706 PS_FAIL
2710 /* Check if the content of TERM is a valid name in dircolors. */
2712 static bool
2713 known_term_type (void)
2715 char const *term = getenv ("TERM");
2716 if (! term || ! *term)
2717 return false;
2719 char const *line = G_line;
2720 while (line - G_line < sizeof (G_line))
2722 if (STRNCMP_LIT (line, "TERM ") == 0)
2724 if (fnmatch (line + 5, term, 0) == 0)
2725 return true;
2727 line += strlen (line) + 1;
2730 return false;
2733 static void
2734 parse_ls_color (void)
2736 char const *p; /* Pointer to character being parsed */
2737 char *buf; /* color_buf buffer pointer */
2738 int ind_no; /* Indicator number */
2739 char label[3]; /* Indicator label */
2740 struct color_ext_type *ext; /* Extension we are working on */
2742 if ((p = getenv ("LS_COLORS")) == nullptr || *p == '\0')
2744 /* LS_COLORS takes precedence, but if that's not set then
2745 honor the COLORTERM and TERM env variables so that
2746 we only go with the internal ANSI color codes if the
2747 former is non empty or the latter is set to a known value. */
2748 char const *colorterm = getenv ("COLORTERM");
2749 if (! (colorterm && *colorterm) && ! known_term_type ())
2750 print_with_color = false;
2751 return;
2754 ext = nullptr;
2755 strcpy (label, "??");
2757 /* This is an overly conservative estimate, but any possible
2758 LS_COLORS string will *not* generate a color_buf longer than
2759 itself, so it is a safe way of allocating a buffer in
2760 advance. */
2761 buf = color_buf = xstrdup (p);
2763 enum parse_state state = PS_START;
2764 while (true)
2766 switch (state)
2768 case PS_START: /* First label character */
2769 switch (*p)
2771 case ':':
2772 ++p;
2773 break;
2775 case '*':
2776 /* Allocate new extension block and add to head of
2777 linked list (this way a later definition will
2778 override an earlier one, which can be useful for
2779 having terminal-specific defs override global). */
2781 ext = xmalloc (sizeof *ext);
2782 ext->next = color_ext_list;
2783 color_ext_list = ext;
2784 ext->exact_match = false;
2786 ++p;
2787 ext->ext.string = buf;
2789 state = (get_funky_string (&buf, &p, true, &ext->ext.len)
2790 ? PS_4 : PS_FAIL);
2791 break;
2793 case '\0':
2794 state = PS_DONE; /* Done! */
2795 goto done;
2797 default: /* Assume it is file type label */
2798 label[0] = *(p++);
2799 state = PS_2;
2800 break;
2802 break;
2804 case PS_2: /* Second label character */
2805 if (*p)
2807 label[1] = *(p++);
2808 state = PS_3;
2810 else
2811 state = PS_FAIL; /* Error */
2812 break;
2814 case PS_3: /* Equal sign after indicator label */
2815 state = PS_FAIL; /* Assume failure... */
2816 if (*(p++) == '=')/* It *should* be... */
2818 for (ind_no = 0; indicator_name[ind_no] != nullptr; ++ind_no)
2820 if (STREQ (label, indicator_name[ind_no]))
2822 color_indicator[ind_no].string = buf;
2823 state = (get_funky_string (&buf, &p, false,
2824 &color_indicator[ind_no].len)
2825 ? PS_START : PS_FAIL);
2826 break;
2829 if (state == PS_FAIL)
2830 error (0, 0, _("unrecognized prefix: %s"), quote (label));
2832 break;
2834 case PS_4: /* Equal sign after *.ext */
2835 if (*(p++) == '=')
2837 ext->seq.string = buf;
2838 state = (get_funky_string (&buf, &p, false, &ext->seq.len)
2839 ? PS_START : PS_FAIL);
2841 else
2842 state = PS_FAIL;
2843 break;
2845 case PS_FAIL:
2846 goto done;
2848 default:
2849 affirm (false);
2852 done:
2854 if (state == PS_FAIL)
2856 struct color_ext_type *e;
2857 struct color_ext_type *e2;
2859 error (0, 0,
2860 _("unparsable value for LS_COLORS environment variable"));
2861 free (color_buf);
2862 for (e = color_ext_list; e != nullptr; /* empty */)
2864 e2 = e;
2865 e = e->next;
2866 free (e2);
2868 print_with_color = false;
2870 else
2872 /* Postprocess list to set EXACT_MATCH on entries where there are
2873 different cased extensions with separate sequences defined.
2874 Also set ext.len to SIZE_MAX on any entries that can't
2875 match due to precedence, to avoid redundant string compares. */
2876 struct color_ext_type *e1;
2878 for (e1 = color_ext_list; e1 != nullptr; e1 = e1->next)
2880 struct color_ext_type *e2;
2881 bool case_ignored = false;
2883 for (e2 = e1->next; e2 != nullptr; e2 = e2->next)
2885 if (e2->ext.len < SIZE_MAX && e1->ext.len == e2->ext.len)
2887 if (memcmp (e1->ext.string, e2->ext.string, e1->ext.len) == 0)
2888 e2->ext.len = SIZE_MAX; /* Ignore */
2889 else if (c_strncasecmp (e1->ext.string, e2->ext.string,
2890 e1->ext.len) == 0)
2892 if (case_ignored)
2894 e2->ext.len = SIZE_MAX; /* Ignore */
2896 else if (e1->seq.len == e2->seq.len
2897 && memcmp (e1->seq.string, e2->seq.string,
2898 e1->seq.len) == 0)
2900 e2->ext.len = SIZE_MAX; /* Ignore */
2901 case_ignored = true; /* Ignore all subsequent */
2903 else
2905 e1->exact_match = true;
2906 e2->exact_match = true;
2914 if (color_indicator[C_LINK].len == 6
2915 && !STRNCMP_LIT (color_indicator[C_LINK].string, "target"))
2916 color_symlink_as_referent = true;
2919 /* Return the quoting style specified by the environment variable
2920 QUOTING_STYLE if set and valid, -1 otherwise. */
2922 static int
2923 getenv_quoting_style (void)
2925 char const *q_style = getenv ("QUOTING_STYLE");
2926 if (!q_style)
2927 return -1;
2928 int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
2929 if (i < 0)
2931 error (0, 0,
2932 _("ignoring invalid value"
2933 " of environment variable QUOTING_STYLE: %s"),
2934 quote (q_style));
2935 return -1;
2937 return quoting_style_vals[i];
2940 /* Set the exit status to report a failure. If SERIOUS, it is a
2941 serious failure; otherwise, it is merely a minor problem. */
2943 static void
2944 set_exit_status (bool serious)
2946 if (serious)
2947 exit_status = LS_FAILURE;
2948 else if (exit_status == EXIT_SUCCESS)
2949 exit_status = LS_MINOR_PROBLEM;
2952 /* Assuming a failure is serious if SERIOUS, use the printf-style
2953 MESSAGE to report the failure to access a file named FILE. Assume
2954 errno is set appropriately for the failure. */
2956 static void
2957 file_failure (bool serious, char const *message, char const *file)
2959 error (0, errno, message, quoteaf (file));
2960 set_exit_status (serious);
2963 /* Request that the directory named NAME have its contents listed later.
2964 If REALNAME is nonzero, it will be used instead of NAME when the
2965 directory name is printed. This allows symbolic links to directories
2966 to be treated as regular directories but still be listed under their
2967 real names. NAME == nullptr is used to insert a marker entry for the
2968 directory named in REALNAME.
2969 If NAME is non-null, we use its dev/ino information to save
2970 a call to stat -- when doing a recursive (-R) traversal.
2971 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2973 static void
2974 queue_directory (char const *name, char const *realname, bool command_line_arg)
2976 struct pending *new = xmalloc (sizeof *new);
2977 new->realname = realname ? xstrdup (realname) : nullptr;
2978 new->name = name ? xstrdup (name) : nullptr;
2979 new->command_line_arg = command_line_arg;
2980 new->next = pending_dirs;
2981 pending_dirs = new;
2984 /* Read directory NAME, and list the files in it.
2985 If REALNAME is nonzero, print its name instead of NAME;
2986 this is used for symbolic links to directories.
2987 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2989 static void
2990 print_dir (char const *name, char const *realname, bool command_line_arg)
2992 DIR *dirp;
2993 struct dirent *next;
2994 uintmax_t total_blocks = 0;
2995 static bool first = true;
2997 errno = 0;
2998 dirp = opendir (name);
2999 if (!dirp)
3001 file_failure (command_line_arg, _("cannot open directory %s"), name);
3002 return;
3005 if (LOOP_DETECT)
3007 struct stat dir_stat;
3008 int fd = dirfd (dirp);
3010 /* If dirfd failed, endure the overhead of stat'ing by path */
3011 if ((0 <= fd
3012 ? fstat_for_ino (fd, &dir_stat)
3013 : stat_for_ino (name, &dir_stat)) < 0)
3015 file_failure (command_line_arg,
3016 _("cannot determine device and inode of %s"), name);
3017 closedir (dirp);
3018 return;
3021 /* If we've already visited this dev/inode pair, warn that
3022 we've found a loop, and do not process this directory. */
3023 if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
3025 error (0, 0, _("%s: not listing already-listed directory"),
3026 quotef (name));
3027 closedir (dirp);
3028 set_exit_status (true);
3029 return;
3032 dev_ino_push (dir_stat.st_dev, dir_stat.st_ino);
3035 clear_files ();
3037 if (recursive || print_dir_name)
3039 if (!first)
3040 dired_outbyte ('\n');
3041 first = false;
3042 dired_indent ();
3044 char *absolute_name = nullptr;
3045 if (print_hyperlink)
3047 absolute_name = canonicalize_filename_mode (name, CAN_MISSING);
3048 if (! absolute_name)
3049 file_failure (command_line_arg,
3050 _("error canonicalizing %s"), name);
3052 quote_name (realname ? realname : name, dirname_quoting_options, -1,
3053 nullptr, true, &subdired_obstack, absolute_name);
3055 free (absolute_name);
3057 dired_outstring (":\n");
3060 /* Read the directory entries, and insert the subfiles into the 'cwd_file'
3061 table. */
3063 while (true)
3065 /* Set errno to zero so we can distinguish between a readdir failure
3066 and when readdir simply finds that there are no more entries. */
3067 errno = 0;
3068 next = readdir (dirp);
3069 if (next)
3071 if (! file_ignored (next->d_name))
3073 enum filetype type = unknown;
3075 #if HAVE_STRUCT_DIRENT_D_TYPE
3076 switch (next->d_type)
3078 case DT_BLK: type = blockdev; break;
3079 case DT_CHR: type = chardev; break;
3080 case DT_DIR: type = directory; break;
3081 case DT_FIFO: type = fifo; break;
3082 case DT_LNK: type = symbolic_link; break;
3083 case DT_REG: type = normal; break;
3084 case DT_SOCK: type = sock; break;
3085 # ifdef DT_WHT
3086 case DT_WHT: type = whiteout; break;
3087 # endif
3089 #endif
3090 total_blocks += gobble_file (next->d_name, type,
3091 RELIABLE_D_INO (next),
3092 false, name);
3094 /* In this narrow case, print out each name right away, so
3095 ls uses constant memory while processing the entries of
3096 this directory. Useful when there are many (millions)
3097 of entries in a directory. */
3098 if (format == one_per_line && sort_type == sort_none
3099 && !print_block_size && !recursive)
3101 /* We must call sort_files in spite of
3102 "sort_type == sort_none" for its initialization
3103 of the sorted_file vector. */
3104 sort_files ();
3105 print_current_files ();
3106 clear_files ();
3110 else if (errno != 0)
3112 file_failure (command_line_arg, _("reading directory %s"), name);
3113 if (errno != EOVERFLOW)
3114 break;
3116 else
3117 break;
3119 /* When processing a very large directory, and since we've inhibited
3120 interrupts, this loop would take so long that ls would be annoyingly
3121 uninterruptible. This ensures that it handles signals promptly. */
3122 process_signals ();
3125 if (closedir (dirp) != 0)
3127 file_failure (command_line_arg, _("closing directory %s"), name);
3128 /* Don't return; print whatever we got. */
3131 /* Sort the directory contents. */
3132 sort_files ();
3134 /* If any member files are subdirectories, perhaps they should have their
3135 contents listed rather than being mentioned here as files. */
3137 if (recursive)
3138 extract_dirs_from_files (name, false);
3140 if (format == long_format || print_block_size)
3142 char buf[LONGEST_HUMAN_READABLE + 3];
3143 char *p = human_readable (total_blocks, buf + 1, human_output_opts,
3144 ST_NBLOCKSIZE, output_block_size);
3145 char *pend = p + strlen (p);
3146 *--p = ' ';
3147 *pend++ = eolbyte;
3148 dired_indent ();
3149 dired_outstring (_("total"));
3150 dired_outbuf (p, pend - p);
3153 if (cwd_n_used)
3154 print_current_files ();
3157 /* Add 'pattern' to the list of patterns for which files that match are
3158 not listed. */
3160 static void
3161 add_ignore_pattern (char const *pattern)
3163 struct ignore_pattern *ignore;
3165 ignore = xmalloc (sizeof *ignore);
3166 ignore->pattern = pattern;
3167 /* Add it to the head of the linked list. */
3168 ignore->next = ignore_patterns;
3169 ignore_patterns = ignore;
3172 /* Return true if one of the PATTERNS matches FILE. */
3174 static bool
3175 patterns_match (struct ignore_pattern const *patterns, char const *file)
3177 struct ignore_pattern const *p;
3178 for (p = patterns; p; p = p->next)
3179 if (fnmatch (p->pattern, file, FNM_PERIOD) == 0)
3180 return true;
3181 return false;
3184 /* Return true if FILE should be ignored. */
3186 static bool
3187 file_ignored (char const *name)
3189 return ((ignore_mode != IGNORE_MINIMAL
3190 && name[0] == '.'
3191 && (ignore_mode == IGNORE_DEFAULT || ! name[1 + (name[1] == '.')]))
3192 || (ignore_mode == IGNORE_DEFAULT
3193 && patterns_match (hide_patterns, name))
3194 || patterns_match (ignore_patterns, name));
3197 /* POSIX requires that a file size be printed without a sign, even
3198 when negative. Assume the typical case where negative sizes are
3199 actually positive values that have wrapped around. */
3201 static uintmax_t
3202 unsigned_file_size (off_t size)
3204 return size + (size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
3207 #ifdef HAVE_CAP
3208 /* Return true if NAME has a capability (see linux/capability.h) */
3209 static bool
3210 has_capability (char const *name)
3212 char *result;
3213 bool has_cap;
3215 cap_t cap_d = cap_get_file (name);
3216 if (cap_d == nullptr)
3217 return false;
3219 result = cap_to_text (cap_d, nullptr);
3220 cap_free (cap_d);
3221 if (!result)
3222 return false;
3224 /* check if human-readable capability string is empty */
3225 has_cap = !!*result;
3227 cap_free (result);
3228 return has_cap;
3230 #else
3231 static bool
3232 has_capability (MAYBE_UNUSED char const *name)
3234 errno = ENOTSUP;
3235 return false;
3237 #endif
3239 /* Enter and remove entries in the table 'cwd_file'. */
3241 static void
3242 free_ent (struct fileinfo *f)
3244 free (f->name);
3245 free (f->linkname);
3246 free (f->absolute_name);
3247 if (f->scontext != UNKNOWN_SECURITY_CONTEXT)
3249 if (is_smack_enabled ())
3250 free (f->scontext);
3251 else
3252 freecon (f->scontext);
3256 /* Empty the table of files. */
3257 static void
3258 clear_files (void)
3260 for (size_t i = 0; i < cwd_n_used; i++)
3262 struct fileinfo *f = sorted_file[i];
3263 free_ent (f);
3266 cwd_n_used = 0;
3267 cwd_some_quoted = false;
3268 any_has_acl = false;
3269 inode_number_width = 0;
3270 block_size_width = 0;
3271 nlink_width = 0;
3272 owner_width = 0;
3273 group_width = 0;
3274 author_width = 0;
3275 scontext_width = 0;
3276 major_device_number_width = 0;
3277 minor_device_number_width = 0;
3278 file_size_width = 0;
3281 /* Return true if ERR implies lack-of-support failure by a
3282 getxattr-calling function like getfilecon or file_has_acl. */
3283 static bool
3284 errno_unsupported (int err)
3286 return (err == EINVAL || err == ENOSYS || is_ENOTSUP (err));
3289 /* Cache *getfilecon failure, when it's trivial to do so.
3290 Like getfilecon/lgetfilecon, but when F's st_dev says it's doesn't
3291 support getting the security context, fail with ENOTSUP immediately. */
3292 static int
3293 getfilecon_cache (char const *file, struct fileinfo *f, bool deref)
3295 /* st_dev of the most recently processed device for which we've
3296 found that [l]getfilecon fails indicating lack of support. */
3297 static dev_t unsupported_device;
3299 if (f->stat.st_dev == unsupported_device)
3301 errno = ENOTSUP;
3302 return -1;
3304 int r = 0;
3305 #ifdef HAVE_SMACK
3306 if (is_smack_enabled ())
3307 r = smack_new_label_from_path (file, "security.SMACK64", deref,
3308 &f->scontext);
3309 else
3310 #endif
3311 r = (deref
3312 ? getfilecon (file, &f->scontext)
3313 : lgetfilecon (file, &f->scontext));
3314 if (r < 0 && errno_unsupported (errno))
3315 unsupported_device = f->stat.st_dev;
3316 return r;
3319 /* Cache file_has_acl failure, when it's trivial to do.
3320 Like file_has_acl, but when F's st_dev says it's on a file
3321 system lacking ACL support, return 0 with ENOTSUP immediately. */
3322 static int
3323 file_has_acl_cache (char const *file, struct fileinfo *f)
3325 /* st_dev of the most recently processed device for which we've
3326 found that file_has_acl fails indicating lack of support. */
3327 static dev_t unsupported_device;
3329 if (f->stat.st_dev == unsupported_device)
3331 errno = ENOTSUP;
3332 return 0;
3335 /* Zero errno so that we can distinguish between two 0-returning cases:
3336 "has-ACL-support, but only a default ACL" and "no ACL support". */
3337 errno = 0;
3338 int n = file_has_acl (file, &f->stat);
3339 if (n <= 0 && errno_unsupported (errno))
3340 unsupported_device = f->stat.st_dev;
3341 return n;
3344 /* Cache has_capability failure, when it's trivial to do.
3345 Like has_capability, but when F's st_dev says it's on a file
3346 system lacking capability support, return 0 with ENOTSUP immediately. */
3347 static bool
3348 has_capability_cache (char const *file, struct fileinfo *f)
3350 /* st_dev of the most recently processed device for which we've
3351 found that has_capability fails indicating lack of support. */
3352 static dev_t unsupported_device;
3354 if (f->stat.st_dev == unsupported_device)
3356 errno = ENOTSUP;
3357 return 0;
3360 bool b = has_capability (file);
3361 if ( !b && errno_unsupported (errno))
3362 unsupported_device = f->stat.st_dev;
3363 return b;
3366 static bool
3367 needs_quoting (char const *name)
3369 char test[2];
3370 size_t len = quotearg_buffer (test, sizeof test , name, -1,
3371 filename_quoting_options);
3372 return *name != *test || strlen (name) != len;
3375 /* Add a file to the current table of files.
3376 Verify that the file exists, and print an error message if it does not.
3377 Return the number of blocks that the file occupies. */
3378 static uintmax_t
3379 gobble_file (char const *name, enum filetype type, ino_t inode,
3380 bool command_line_arg, char const *dirname)
3382 uintmax_t blocks = 0;
3383 struct fileinfo *f;
3385 /* An inode value prior to gobble_file necessarily came from readdir,
3386 which is not used for command line arguments. */
3387 affirm (! command_line_arg || inode == NOT_AN_INODE_NUMBER);
3389 if (cwd_n_used == cwd_n_alloc)
3391 cwd_file = xnrealloc (cwd_file, cwd_n_alloc, 2 * sizeof *cwd_file);
3392 cwd_n_alloc *= 2;
3395 f = &cwd_file[cwd_n_used];
3396 memset (f, '\0', sizeof *f);
3397 f->stat.st_ino = inode;
3398 f->filetype = type;
3400 f->quoted = -1;
3401 if ((! cwd_some_quoted) && align_variable_outer_quotes)
3403 /* Determine if any quoted for padding purposes. */
3404 f->quoted = needs_quoting (name);
3405 if (f->quoted)
3406 cwd_some_quoted = 1;
3409 if (command_line_arg
3410 || print_hyperlink
3411 || format_needs_stat
3412 /* When coloring a directory (we may know the type from
3413 direct.d_type), we have to stat it in order to indicate
3414 sticky and/or other-writable attributes. */
3415 || (type == directory && print_with_color
3416 && (is_colored (C_OTHER_WRITABLE)
3417 || is_colored (C_STICKY)
3418 || is_colored (C_STICKY_OTHER_WRITABLE)))
3419 /* When dereferencing symlinks, the inode and type must come from
3420 stat, but readdir provides the inode and type of lstat. */
3421 || ((print_inode || format_needs_type)
3422 && (type == symbolic_link || type == unknown)
3423 && (dereference == DEREF_ALWAYS
3424 || color_symlink_as_referent || check_symlink_mode))
3425 /* Command line dereferences are already taken care of by the above
3426 assertion that the inode number is not yet known. */
3427 || (print_inode && inode == NOT_AN_INODE_NUMBER)
3428 || (format_needs_type
3429 && (type == unknown || command_line_arg
3430 /* --indicator-style=classify (aka -F)
3431 requires that we stat each regular file
3432 to see if it's executable. */
3433 || (type == normal && (indicator_style == classify
3434 /* This is so that --color ends up
3435 highlighting files with these mode
3436 bits set even when options like -F are
3437 not specified. Note we do a redundant
3438 stat in the very unlikely case where
3439 C_CAP is set but not the others. */
3440 || (print_with_color
3441 && (is_colored (C_EXEC)
3442 || is_colored (C_SETUID)
3443 || is_colored (C_SETGID)
3444 || is_colored (C_CAP)))
3445 )))))
3448 /* Absolute name of this file. */
3449 char *full_name;
3450 bool do_deref;
3451 int err;
3453 if (name[0] == '/' || dirname[0] == 0)
3454 full_name = (char *) name;
3455 else
3457 full_name = alloca (strlen (name) + strlen (dirname) + 2);
3458 attach (full_name, dirname, name);
3461 if (print_hyperlink)
3463 f->absolute_name = canonicalize_filename_mode (full_name,
3464 CAN_MISSING);
3465 if (! f->absolute_name)
3466 file_failure (command_line_arg,
3467 _("error canonicalizing %s"), full_name);
3470 switch (dereference)
3472 case DEREF_ALWAYS:
3473 err = do_stat (full_name, &f->stat);
3474 do_deref = true;
3475 break;
3477 case DEREF_COMMAND_LINE_ARGUMENTS:
3478 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
3479 if (command_line_arg)
3481 bool need_lstat;
3482 err = do_stat (full_name, &f->stat);
3483 do_deref = true;
3485 if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
3486 break;
3488 need_lstat = (err < 0
3489 ? (errno == ENOENT || errno == ELOOP)
3490 : ! S_ISDIR (f->stat.st_mode));
3491 if (!need_lstat)
3492 break;
3494 /* stat failed because of ENOENT || ELOOP, maybe indicating a
3495 non-traversable symlink. Or stat succeeded,
3496 FULL_NAME does not refer to a directory,
3497 and --dereference-command-line-symlink-to-dir is in effect.
3498 Fall through so that we call lstat instead. */
3500 FALLTHROUGH;
3502 default: /* DEREF_NEVER */
3503 err = do_lstat (full_name, &f->stat);
3504 do_deref = false;
3505 break;
3508 if (err != 0)
3510 /* Failure to stat a command line argument leads to
3511 an exit status of 2. For other files, stat failure
3512 provokes an exit status of 1. */
3513 file_failure (command_line_arg,
3514 _("cannot access %s"), full_name);
3516 f->scontext = UNKNOWN_SECURITY_CONTEXT;
3518 if (command_line_arg)
3519 return 0;
3521 f->name = xstrdup (name);
3522 cwd_n_used++;
3524 return 0;
3527 f->stat_ok = true;
3529 /* Note has_capability() adds around 30% runtime to 'ls --color' */
3530 if ((type == normal || S_ISREG (f->stat.st_mode))
3531 && print_with_color && is_colored (C_CAP))
3532 f->has_capability = has_capability_cache (full_name, f);
3534 if (format == long_format || print_scontext)
3536 bool have_scontext = false;
3537 bool have_acl = false;
3538 int attr_len = getfilecon_cache (full_name, f, do_deref);
3539 err = (attr_len < 0);
3541 if (err == 0)
3543 if (is_smack_enabled ())
3544 have_scontext = ! STREQ ("_", f->scontext);
3545 else
3546 have_scontext = ! STREQ ("unlabeled", f->scontext);
3548 else
3550 f->scontext = UNKNOWN_SECURITY_CONTEXT;
3552 /* When requesting security context information, don't make
3553 ls fail just because the file (even a command line argument)
3554 isn't on the right type of file system. I.e., a getfilecon
3555 failure isn't in the same class as a stat failure. */
3556 if (is_ENOTSUP (errno) || errno == ENODATA)
3557 err = 0;
3560 if (err == 0 && format == long_format)
3562 int n = file_has_acl_cache (full_name, f);
3563 err = (n < 0);
3564 have_acl = (0 < n);
3567 f->acl_type = (!have_scontext && !have_acl
3568 ? ACL_T_NONE
3569 : (have_scontext && !have_acl
3570 ? ACL_T_LSM_CONTEXT_ONLY
3571 : ACL_T_YES));
3572 any_has_acl |= f->acl_type != ACL_T_NONE;
3574 if (err)
3575 error (0, errno, "%s", quotef (full_name));
3578 if (S_ISLNK (f->stat.st_mode)
3579 && (format == long_format || check_symlink_mode))
3581 struct stat linkstats;
3583 get_link_name (full_name, f, command_line_arg);
3585 /* Use the slower quoting path for this entry, though
3586 don't update CWD_SOME_QUOTED since alignment not affected. */
3587 if (f->linkname && f->quoted == 0 && needs_quoting (f->linkname))
3588 f->quoted = -1;
3590 /* Avoid following symbolic links when possible, i.e., when
3591 they won't be traced and when no indicator is needed. */
3592 if (f->linkname
3593 && (file_type <= indicator_style || check_symlink_mode)
3594 && stat_for_mode (full_name, &linkstats) == 0)
3596 f->linkok = true;
3597 f->linkmode = linkstats.st_mode;
3601 if (S_ISLNK (f->stat.st_mode))
3602 f->filetype = symbolic_link;
3603 else if (S_ISDIR (f->stat.st_mode))
3605 if (command_line_arg && !immediate_dirs)
3606 f->filetype = arg_directory;
3607 else
3608 f->filetype = directory;
3610 else
3611 f->filetype = normal;
3613 blocks = ST_NBLOCKS (f->stat);
3614 if (format == long_format || print_block_size)
3616 char buf[LONGEST_HUMAN_READABLE + 1];
3617 int len = mbswidth (human_readable (blocks, buf, human_output_opts,
3618 ST_NBLOCKSIZE, output_block_size),
3619 MBSWIDTH_FLAGS);
3620 if (block_size_width < len)
3621 block_size_width = len;
3624 if (format == long_format)
3626 if (print_owner)
3628 int len = format_user_width (f->stat.st_uid);
3629 if (owner_width < len)
3630 owner_width = len;
3633 if (print_group)
3635 int len = format_group_width (f->stat.st_gid);
3636 if (group_width < len)
3637 group_width = len;
3640 if (print_author)
3642 int len = format_user_width (f->stat.st_author);
3643 if (author_width < len)
3644 author_width = len;
3648 if (print_scontext)
3650 int len = strlen (f->scontext);
3651 if (scontext_width < len)
3652 scontext_width = len;
3655 if (format == long_format)
3657 char b[INT_BUFSIZE_BOUND (uintmax_t)];
3658 int b_len = strlen (umaxtostr (f->stat.st_nlink, b));
3659 if (nlink_width < b_len)
3660 nlink_width = b_len;
3662 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
3664 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
3665 int len = strlen (umaxtostr (major (f->stat.st_rdev), buf));
3666 if (major_device_number_width < len)
3667 major_device_number_width = len;
3668 len = strlen (umaxtostr (minor (f->stat.st_rdev), buf));
3669 if (minor_device_number_width < len)
3670 minor_device_number_width = len;
3671 len = major_device_number_width + 2 + minor_device_number_width;
3672 if (file_size_width < len)
3673 file_size_width = len;
3675 else
3677 char buf[LONGEST_HUMAN_READABLE + 1];
3678 uintmax_t size = unsigned_file_size (f->stat.st_size);
3679 int len = mbswidth (human_readable (size, buf,
3680 file_human_output_opts,
3681 1, file_output_block_size),
3682 MBSWIDTH_FLAGS);
3683 if (file_size_width < len)
3684 file_size_width = len;
3689 if (print_inode)
3691 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
3692 int len = strlen (umaxtostr (f->stat.st_ino, buf));
3693 if (inode_number_width < len)
3694 inode_number_width = len;
3697 f->name = xstrdup (name);
3698 cwd_n_used++;
3700 return blocks;
3703 /* Return true if F refers to a directory. */
3704 static bool
3705 is_directory (const struct fileinfo *f)
3707 return f->filetype == directory || f->filetype == arg_directory;
3710 /* Return true if F refers to a (symlinked) directory. */
3711 static bool
3712 is_linked_directory (const struct fileinfo *f)
3714 return f->filetype == directory || f->filetype == arg_directory
3715 || S_ISDIR (f->linkmode);
3718 /* Put the name of the file that FILENAME is a symbolic link to
3719 into the LINKNAME field of 'f'. COMMAND_LINE_ARG indicates whether
3720 FILENAME is a command-line argument. */
3722 static void
3723 get_link_name (char const *filename, struct fileinfo *f, bool command_line_arg)
3725 f->linkname = areadlink_with_size (filename, f->stat.st_size);
3726 if (f->linkname == nullptr)
3727 file_failure (command_line_arg, _("cannot read symbolic link %s"),
3728 filename);
3731 /* Return true if the last component of NAME is '.' or '..'
3732 This is so we don't try to recurse on '././././. ...' */
3734 static bool
3735 basename_is_dot_or_dotdot (char const *name)
3737 char const *base = last_component (name);
3738 return dot_or_dotdot (base);
3741 /* Remove any entries from CWD_FILE that are for directories,
3742 and queue them to be listed as directories instead.
3743 DIRNAME is the prefix to prepend to each dirname
3744 to make it correct relative to ls's working dir;
3745 if it is null, no prefix is needed and "." and ".." should not be ignored.
3746 If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
3747 This is desirable when processing directories recursively. */
3749 static void
3750 extract_dirs_from_files (char const *dirname, bool command_line_arg)
3752 size_t i;
3753 size_t j;
3754 bool ignore_dot_and_dot_dot = (dirname != nullptr);
3756 if (dirname && LOOP_DETECT)
3758 /* Insert a marker entry first. When we dequeue this marker entry,
3759 we'll know that DIRNAME has been processed and may be removed
3760 from the set of active directories. */
3761 queue_directory (nullptr, dirname, false);
3764 /* Queue the directories last one first, because queueing reverses the
3765 order. */
3766 for (i = cwd_n_used; i-- != 0; )
3768 struct fileinfo *f = sorted_file[i];
3770 if (is_directory (f)
3771 && (! ignore_dot_and_dot_dot
3772 || ! basename_is_dot_or_dotdot (f->name)))
3774 if (!dirname || f->name[0] == '/')
3775 queue_directory (f->name, f->linkname, command_line_arg);
3776 else
3778 char *name = file_name_concat (dirname, f->name, nullptr);
3779 queue_directory (name, f->linkname, command_line_arg);
3780 free (name);
3782 if (f->filetype == arg_directory)
3783 free_ent (f);
3787 /* Now delete the directories from the table, compacting all the remaining
3788 entries. */
3790 for (i = 0, j = 0; i < cwd_n_used; i++)
3792 struct fileinfo *f = sorted_file[i];
3793 sorted_file[j] = f;
3794 j += (f->filetype != arg_directory);
3796 cwd_n_used = j;
3799 /* Use strcoll to compare strings in this locale. If an error occurs,
3800 report an error and longjmp to failed_strcoll. */
3802 static jmp_buf failed_strcoll;
3804 static int
3805 xstrcoll (char const *a, char const *b)
3807 int diff;
3808 errno = 0;
3809 diff = strcoll (a, b);
3810 if (errno)
3812 error (0, errno, _("cannot compare file names %s and %s"),
3813 quote_n (0, a), quote_n (1, b));
3814 set_exit_status (false);
3815 longjmp (failed_strcoll, 1);
3817 return diff;
3820 /* Comparison routines for sorting the files. */
3822 typedef void const *V;
3823 typedef int (*qsortFunc)(V a, V b);
3825 /* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants. */
3826 static int
3827 dirfirst_check (struct fileinfo const *a, struct fileinfo const *b,
3828 int (*cmp) (V, V))
3830 int diff = is_linked_directory (b) - is_linked_directory (a);
3831 return diff ? diff : cmp (a, b);
3834 /* Define the 8 different sort function variants required for each sortkey.
3835 KEY_NAME is a token describing the sort key, e.g., ctime, atime, size.
3836 KEY_CMP_FUNC is a function to compare records based on that key, e.g.,
3837 ctime_cmp, atime_cmp, size_cmp. Append KEY_NAME to the string,
3838 '[rev_][x]str{cmp|coll}[_df]_', to create each function name. */
3839 #define DEFINE_SORT_FUNCTIONS(key_name, key_cmp_func) \
3840 /* direct, non-dirfirst versions */ \
3841 static int xstrcoll_##key_name (V a, V b) \
3842 { return key_cmp_func (a, b, xstrcoll); } \
3843 ATTRIBUTE_PURE static int strcmp_##key_name (V a, V b) \
3844 { return key_cmp_func (a, b, strcmp); } \
3846 /* reverse, non-dirfirst versions */ \
3847 static int rev_xstrcoll_##key_name (V a, V b) \
3848 { return key_cmp_func (b, a, xstrcoll); } \
3849 ATTRIBUTE_PURE static int rev_strcmp_##key_name (V a, V b) \
3850 { return key_cmp_func (b, a, strcmp); } \
3852 /* direct, dirfirst versions */ \
3853 static int xstrcoll_df_##key_name (V a, V b) \
3854 { return dirfirst_check (a, b, xstrcoll_##key_name); } \
3855 ATTRIBUTE_PURE static int strcmp_df_##key_name (V a, V b) \
3856 { return dirfirst_check (a, b, strcmp_##key_name); } \
3858 /* reverse, dirfirst versions */ \
3859 static int rev_xstrcoll_df_##key_name (V a, V b) \
3860 { return dirfirst_check (a, b, rev_xstrcoll_##key_name); } \
3861 ATTRIBUTE_PURE static int rev_strcmp_df_##key_name (V a, V b) \
3862 { return dirfirst_check (a, b, rev_strcmp_##key_name); }
3864 static int
3865 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
3866 int (*cmp) (char const *, char const *))
3868 int diff = timespec_cmp (get_stat_ctime (&b->stat),
3869 get_stat_ctime (&a->stat));
3870 return diff ? diff : cmp (a->name, b->name);
3873 static int
3874 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
3875 int (*cmp) (char const *, char const *))
3877 int diff = timespec_cmp (get_stat_mtime (&b->stat),
3878 get_stat_mtime (&a->stat));
3879 return diff ? diff : cmp (a->name, b->name);
3882 static int
3883 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
3884 int (*cmp) (char const *, char const *))
3886 int diff = timespec_cmp (get_stat_atime (&b->stat),
3887 get_stat_atime (&a->stat));
3888 return diff ? diff : cmp (a->name, b->name);
3891 static int
3892 cmp_btime (struct fileinfo const *a, struct fileinfo const *b,
3893 int (*cmp) (char const *, char const *))
3895 int diff = timespec_cmp (get_stat_btime (&b->stat),
3896 get_stat_btime (&a->stat));
3897 return diff ? diff : cmp (a->name, b->name);
3900 static int
3901 off_cmp (off_t a, off_t b)
3903 return (a > b) - (a < b);
3906 static int
3907 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
3908 int (*cmp) (char const *, char const *))
3910 int diff = off_cmp (b->stat.st_size, a->stat.st_size);
3911 return diff ? diff : cmp (a->name, b->name);
3914 static int
3915 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
3916 int (*cmp) (char const *, char const *))
3918 return cmp (a->name, b->name);
3921 /* Compare file extensions. Files with no extension are 'smallest'.
3922 If extensions are the same, compare by file names instead. */
3924 static int
3925 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
3926 int (*cmp) (char const *, char const *))
3928 char const *base1 = strrchr (a->name, '.');
3929 char const *base2 = strrchr (b->name, '.');
3930 int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
3931 return diff ? diff : cmp (a->name, b->name);
3934 /* Return the (cached) screen width,
3935 for the NAME associated with the passed fileinfo F. */
3937 static size_t
3938 fileinfo_name_width (struct fileinfo const *f)
3940 return f->width
3941 ? f->width
3942 : quote_name_width (f->name, filename_quoting_options, f->quoted);
3945 static int
3946 cmp_width (struct fileinfo const *a, struct fileinfo const *b,
3947 int (*cmp) (char const *, char const *))
3949 int diff = fileinfo_name_width (a) - fileinfo_name_width (b);
3950 return diff ? diff : cmp (a->name, b->name);
3953 DEFINE_SORT_FUNCTIONS (ctime, cmp_ctime)
3954 DEFINE_SORT_FUNCTIONS (mtime, cmp_mtime)
3955 DEFINE_SORT_FUNCTIONS (atime, cmp_atime)
3956 DEFINE_SORT_FUNCTIONS (btime, cmp_btime)
3957 DEFINE_SORT_FUNCTIONS (size, cmp_size)
3958 DEFINE_SORT_FUNCTIONS (name, cmp_name)
3959 DEFINE_SORT_FUNCTIONS (extension, cmp_extension)
3960 DEFINE_SORT_FUNCTIONS (width, cmp_width)
3962 /* Compare file versions.
3963 Unlike the other compare functions, cmp_version does not fail
3964 because filevercmp and strcmp do not fail; cmp_version uses strcmp
3965 instead of xstrcoll because filevercmp is locale-independent so
3966 strcmp is its appropriate secondary.
3968 All the other sort options need xstrcoll and strcmp variants,
3969 because they all use xstrcoll (either as the primary or secondary
3970 sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
3971 locale reasons. */
3972 static int
3973 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
3975 int diff = filevercmp (a->name, b->name);
3976 return diff ? diff : strcmp (a->name, b->name);
3979 static int
3980 xstrcoll_version (V a, V b)
3982 return cmp_version (a, b);
3984 static int
3985 rev_xstrcoll_version (V a, V b)
3987 return cmp_version (b, a);
3989 static int
3990 xstrcoll_df_version (V a, V b)
3992 return dirfirst_check (a, b, xstrcoll_version);
3994 static int
3995 rev_xstrcoll_df_version (V a, V b)
3997 return dirfirst_check (a, b, rev_xstrcoll_version);
4001 /* We have 2^3 different variants for each sort-key function
4002 (for 3 independent sort modes).
4003 The function pointers stored in this array must be dereferenced as:
4005 sort_variants[sort_key][use_strcmp][reverse][dirs_first]
4007 Note that the order in which sort keys are listed in the function pointer
4008 array below is defined by the order of the elements in the time_type and
4009 sort_type enums! */
4011 #define LIST_SORTFUNCTION_VARIANTS(key_name) \
4014 { xstrcoll_##key_name, xstrcoll_df_##key_name }, \
4015 { rev_xstrcoll_##key_name, rev_xstrcoll_df_##key_name }, \
4016 }, \
4018 { strcmp_##key_name, strcmp_df_##key_name }, \
4019 { rev_strcmp_##key_name, rev_strcmp_df_##key_name }, \
4023 static qsortFunc const sort_functions[][2][2][2] =
4025 LIST_SORTFUNCTION_VARIANTS (name),
4026 LIST_SORTFUNCTION_VARIANTS (extension),
4027 LIST_SORTFUNCTION_VARIANTS (width),
4028 LIST_SORTFUNCTION_VARIANTS (size),
4032 { xstrcoll_version, xstrcoll_df_version },
4033 { rev_xstrcoll_version, rev_xstrcoll_df_version },
4036 /* We use nullptr for the strcmp variants of version comparison
4037 since as explained in cmp_version definition, version comparison
4038 does not rely on xstrcoll, so it will never longjmp, and never
4039 need to try the strcmp fallback. */
4041 { nullptr, nullptr },
4042 { nullptr, nullptr },
4046 /* last are time sort functions */
4047 LIST_SORTFUNCTION_VARIANTS (mtime),
4048 LIST_SORTFUNCTION_VARIANTS (ctime),
4049 LIST_SORTFUNCTION_VARIANTS (atime),
4050 LIST_SORTFUNCTION_VARIANTS (btime)
4053 /* The number of sort keys is calculated as the sum of
4054 the number of elements in the sort_type enum (i.e., sort_numtypes)
4055 -2 because neither sort_time nor sort_none use entries themselves
4056 the number of elements in the time_type enum (i.e., time_numtypes)
4057 This is because when sort_type==sort_time, we have up to
4058 time_numtypes possible sort keys.
4060 This line verifies at compile-time that the array of sort functions has been
4061 initialized for all possible sort keys. */
4062 static_assert (ARRAY_CARDINALITY (sort_functions)
4063 == sort_numtypes - 2 + time_numtypes);
4065 /* Set up SORTED_FILE to point to the in-use entries in CWD_FILE, in order. */
4067 static void
4068 initialize_ordering_vector (void)
4070 for (size_t i = 0; i < cwd_n_used; i++)
4071 sorted_file[i] = &cwd_file[i];
4074 /* Cache values based on attributes global to all files. */
4076 static void
4077 update_current_files_info (void)
4079 /* Cache screen width of name, if needed multiple times. */
4080 if (sort_type == sort_width
4081 || (line_length && (format == many_per_line || format == horizontal)))
4083 size_t i;
4084 for (i = 0; i < cwd_n_used; i++)
4086 struct fileinfo *f = sorted_file[i];
4087 f->width = fileinfo_name_width (f);
4092 /* Sort the files now in the table. */
4094 static void
4095 sort_files (void)
4097 bool use_strcmp;
4099 if (sorted_file_alloc < cwd_n_used + cwd_n_used / 2)
4101 free (sorted_file);
4102 sorted_file = xnmalloc (cwd_n_used, 3 * sizeof *sorted_file);
4103 sorted_file_alloc = 3 * cwd_n_used;
4106 initialize_ordering_vector ();
4108 update_current_files_info ();
4110 if (sort_type == sort_none)
4111 return;
4113 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
4114 ignore strcoll failures, as a failing strcoll might be a
4115 comparison function that is not a total order, and if we ignored
4116 the failure this might cause qsort to dump core. */
4118 if (! setjmp (failed_strcoll))
4119 use_strcmp = false; /* strcoll() succeeded */
4120 else
4122 use_strcmp = true;
4123 affirm (sort_type != sort_version);
4124 initialize_ordering_vector ();
4127 /* When sort_type == sort_time, use time_type as subindex. */
4128 mpsort ((void const **) sorted_file, cwd_n_used,
4129 sort_functions[sort_type + (sort_type == sort_time ? time_type : 0)]
4130 [use_strcmp][sort_reverse]
4131 [directories_first]);
4134 /* List all the files now in the table. */
4136 static void
4137 print_current_files (void)
4139 size_t i;
4141 switch (format)
4143 case one_per_line:
4144 for (i = 0; i < cwd_n_used; i++)
4146 print_file_name_and_frills (sorted_file[i], 0);
4147 putchar (eolbyte);
4149 break;
4151 case many_per_line:
4152 if (! line_length)
4153 print_with_separator (' ');
4154 else
4155 print_many_per_line ();
4156 break;
4158 case horizontal:
4159 if (! line_length)
4160 print_with_separator (' ');
4161 else
4162 print_horizontal ();
4163 break;
4165 case with_commas:
4166 print_with_separator (',');
4167 break;
4169 case long_format:
4170 for (i = 0; i < cwd_n_used; i++)
4172 set_normal_color ();
4173 print_long_format (sorted_file[i]);
4174 dired_outbyte (eolbyte);
4176 break;
4180 /* Replace the first %b with precomputed aligned month names.
4181 Note on glibc-2.7 at least, this speeds up the whole 'ls -lU'
4182 process by around 17%, compared to letting strftime() handle the %b. */
4184 static size_t
4185 align_nstrftime (char *buf, size_t size, bool recent, struct tm const *tm,
4186 timezone_t tz, int ns)
4188 char const *nfmt = (use_abformat
4189 ? abformat[recent][tm->tm_mon]
4190 : long_time_format[recent]);
4191 return nstrftime (buf, size, nfmt, tm, tz, ns);
4194 /* Return the expected number of columns in a long-format timestamp,
4195 or zero if it cannot be calculated. */
4197 static int
4198 long_time_expected_width (void)
4200 static int width = -1;
4202 if (width < 0)
4204 time_t epoch = 0;
4205 struct tm tm;
4206 char buf[TIME_STAMP_LEN_MAXIMUM + 1];
4208 /* In case you're wondering if localtime_rz can fail with an input time_t
4209 value of 0, let's just say it's very unlikely, but not inconceivable.
4210 The TZ environment variable would have to specify a time zone that
4211 is 2**31-1900 years or more ahead of UTC. This could happen only on
4212 a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
4213 However, this is not possible with Solaris 10 or glibc-2.3.5, since
4214 their implementations limit the offset to 167:59 and 24:00, resp. */
4215 if (localtime_rz (localtz, &epoch, &tm))
4217 size_t len = align_nstrftime (buf, sizeof buf, false,
4218 &tm, localtz, 0);
4219 if (len != 0)
4220 width = mbsnwidth (buf, len, MBSWIDTH_FLAGS);
4223 if (width < 0)
4224 width = 0;
4227 return width;
4230 /* Print the user or group name NAME, with numeric id ID, using a
4231 print width of WIDTH columns. */
4233 static void
4234 format_user_or_group (char const *name, uintmax_t id, int width)
4236 if (name)
4238 int name_width = mbswidth (name, MBSWIDTH_FLAGS);
4239 int width_gap = name_width < 0 ? 0 : width - name_width;
4240 int pad = MAX (0, width_gap);
4241 dired_outstring (name);
4244 dired_outbyte (' ');
4245 while (pad--);
4247 else
4248 dired_pos += printf ("%*"PRIuMAX" ", width, id);
4251 /* Print the name or id of the user with id U, using a print width of
4252 WIDTH. */
4254 static void
4255 format_user (uid_t u, int width, bool stat_ok)
4257 format_user_or_group (! stat_ok ? "?" :
4258 (numeric_ids ? nullptr : getuser (u)), u, width);
4261 /* Likewise, for groups. */
4263 static void
4264 format_group (gid_t g, int width, bool stat_ok)
4266 format_user_or_group (! stat_ok ? "?" :
4267 (numeric_ids ? nullptr : getgroup (g)), g, width);
4270 /* Return the number of columns that format_user_or_group will print,
4271 or -1 if unknown. */
4273 static int
4274 format_user_or_group_width (char const *name, uintmax_t id)
4276 return (name
4277 ? mbswidth (name, MBSWIDTH_FLAGS)
4278 : snprintf (nullptr, 0, "%"PRIuMAX, id));
4281 /* Return the number of columns that format_user will print,
4282 or -1 if unknown. */
4284 static int
4285 format_user_width (uid_t u)
4287 return format_user_or_group_width (numeric_ids ? nullptr : getuser (u), u);
4290 /* Likewise, for groups. */
4292 static int
4293 format_group_width (gid_t g)
4295 return format_user_or_group_width (numeric_ids ? nullptr : getgroup (g), g);
4298 /* Return a pointer to a formatted version of F->stat.st_ino,
4299 possibly using buffer, which must be at least
4300 INT_BUFSIZE_BOUND (uintmax_t) bytes. */
4301 static char *
4302 format_inode (char buf[INT_BUFSIZE_BOUND (uintmax_t)],
4303 const struct fileinfo *f)
4305 return (f->stat_ok && f->stat.st_ino != NOT_AN_INODE_NUMBER
4306 ? umaxtostr (f->stat.st_ino, buf)
4307 : (char *) "?");
4310 /* Print information about F in long format. */
4311 static void
4312 print_long_format (const struct fileinfo *f)
4314 char modebuf[12];
4315 char buf
4316 [LONGEST_HUMAN_READABLE + 1 /* inode */
4317 + LONGEST_HUMAN_READABLE + 1 /* size in blocks */
4318 + sizeof (modebuf) - 1 + 1 /* mode string */
4319 + INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
4320 + LONGEST_HUMAN_READABLE + 2 /* major device number */
4321 + LONGEST_HUMAN_READABLE + 1 /* minor device number */
4322 + TIME_STAMP_LEN_MAXIMUM + 1 /* max length of time/date */
4324 size_t s;
4325 char *p;
4326 struct timespec when_timespec;
4327 struct tm when_local;
4328 bool btime_ok = true;
4330 /* Compute the mode string, except remove the trailing space if no
4331 file in this directory has an ACL or security context. */
4332 if (f->stat_ok)
4333 filemodestring (&f->stat, modebuf);
4334 else
4336 modebuf[0] = filetype_letter[f->filetype];
4337 memset (modebuf + 1, '?', 10);
4338 modebuf[11] = '\0';
4340 if (! any_has_acl)
4341 modebuf[10] = '\0';
4342 else if (f->acl_type == ACL_T_LSM_CONTEXT_ONLY)
4343 modebuf[10] = '.';
4344 else if (f->acl_type == ACL_T_YES)
4345 modebuf[10] = '+';
4347 switch (time_type)
4349 case time_ctime:
4350 when_timespec = get_stat_ctime (&f->stat);
4351 break;
4352 case time_mtime:
4353 when_timespec = get_stat_mtime (&f->stat);
4354 break;
4355 case time_atime:
4356 when_timespec = get_stat_atime (&f->stat);
4357 break;
4358 case time_btime:
4359 when_timespec = get_stat_btime (&f->stat);
4360 if (when_timespec.tv_sec == -1 && when_timespec.tv_nsec == -1)
4361 btime_ok = false;
4362 break;
4363 default:
4364 unreachable ();
4367 p = buf;
4369 if (print_inode)
4371 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
4372 p += sprintf (p, "%*s ", inode_number_width, format_inode (hbuf, f));
4375 if (print_block_size)
4377 char hbuf[LONGEST_HUMAN_READABLE + 1];
4378 char const *blocks =
4379 (! f->stat_ok
4380 ? "?"
4381 : human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts,
4382 ST_NBLOCKSIZE, output_block_size));
4383 int blocks_width = mbswidth (blocks, MBSWIDTH_FLAGS);
4384 for (int pad = blocks_width < 0 ? 0 : block_size_width - blocks_width;
4385 0 < pad; pad--)
4386 *p++ = ' ';
4387 while ((*p++ = *blocks++))
4388 continue;
4389 p[-1] = ' ';
4392 /* The last byte of the mode string is the POSIX
4393 "optional alternate access method flag". */
4395 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
4396 p += sprintf (p, "%s %*s ", modebuf, nlink_width,
4397 ! f->stat_ok ? "?" : umaxtostr (f->stat.st_nlink, hbuf));
4400 dired_indent ();
4402 if (print_owner || print_group || print_author || print_scontext)
4404 dired_outbuf (buf, p - buf);
4406 if (print_owner)
4407 format_user (f->stat.st_uid, owner_width, f->stat_ok);
4409 if (print_group)
4410 format_group (f->stat.st_gid, group_width, f->stat_ok);
4412 if (print_author)
4413 format_user (f->stat.st_author, author_width, f->stat_ok);
4415 if (print_scontext)
4416 format_user_or_group (f->scontext, 0, scontext_width);
4418 p = buf;
4421 if (f->stat_ok
4422 && (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode)))
4424 char majorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
4425 char minorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
4426 int blanks_width = (file_size_width
4427 - (major_device_number_width + 2
4428 + minor_device_number_width));
4429 p += sprintf (p, "%*s, %*s ",
4430 major_device_number_width + MAX (0, blanks_width),
4431 umaxtostr (major (f->stat.st_rdev), majorbuf),
4432 minor_device_number_width,
4433 umaxtostr (minor (f->stat.st_rdev), minorbuf));
4435 else
4437 char hbuf[LONGEST_HUMAN_READABLE + 1];
4438 char const *size =
4439 (! f->stat_ok
4440 ? "?"
4441 : human_readable (unsigned_file_size (f->stat.st_size),
4442 hbuf, file_human_output_opts, 1,
4443 file_output_block_size));
4444 int size_width = mbswidth (size, MBSWIDTH_FLAGS);
4445 for (int pad = size_width < 0 ? 0 : block_size_width - size_width;
4446 0 < pad; pad--)
4447 *p++ = ' ';
4448 while ((*p++ = *size++))
4449 continue;
4450 p[-1] = ' ';
4453 s = 0;
4454 *p = '\1';
4456 if (f->stat_ok && btime_ok
4457 && localtime_rz (localtz, &when_timespec.tv_sec, &when_local))
4459 struct timespec six_months_ago;
4460 bool recent;
4462 /* If the file appears to be in the future, update the current
4463 time, in case the file happens to have been modified since
4464 the last time we checked the clock. */
4465 if (timespec_cmp (current_time, when_timespec) < 0)
4466 gettime (&current_time);
4468 /* Consider a time to be recent if it is within the past six months.
4469 A Gregorian year has 365.2425 * 24 * 60 * 60 == 31556952 seconds
4470 on the average. Write this value as an integer constant to
4471 avoid floating point hassles. */
4472 six_months_ago.tv_sec = current_time.tv_sec - 31556952 / 2;
4473 six_months_ago.tv_nsec = current_time.tv_nsec;
4475 recent = (timespec_cmp (six_months_ago, when_timespec) < 0
4476 && timespec_cmp (when_timespec, current_time) < 0);
4478 /* We assume here that all time zones are offset from UTC by a
4479 whole number of seconds. */
4480 s = align_nstrftime (p, TIME_STAMP_LEN_MAXIMUM + 1, recent,
4481 &when_local, localtz, when_timespec.tv_nsec);
4484 if (s || !*p)
4486 p += s;
4487 *p++ = ' ';
4489 else
4491 /* The time cannot be converted using the desired format, so
4492 print it as a huge integer number of seconds. */
4493 char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
4494 p += sprintf (p, "%*s ", long_time_expected_width (),
4495 (! f->stat_ok || ! btime_ok
4496 ? "?"
4497 : timetostr (when_timespec.tv_sec, hbuf)));
4498 /* FIXME: (maybe) We discarded when_timespec.tv_nsec. */
4501 dired_outbuf (buf, p - buf);
4502 size_t w = print_name_with_quoting (f, false, &dired_obstack, p - buf);
4504 if (f->filetype == symbolic_link)
4506 if (f->linkname)
4508 dired_outstring (" -> ");
4509 print_name_with_quoting (f, true, nullptr, (p - buf) + w + 4);
4510 if (indicator_style != none)
4511 print_type_indicator (true, f->linkmode, unknown);
4514 else if (indicator_style != none)
4515 print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4518 /* Write to *BUF a quoted representation of the file name NAME, if non-null,
4519 using OPTIONS to control quoting. *BUF is set to NAME if no quoting
4520 is required. *BUF is allocated if more space required (and the original
4521 *BUF is not deallocated).
4522 Store the number of screen columns occupied by NAME's quoted
4523 representation into WIDTH, if non-null.
4524 Store into PAD whether an initial space is needed for padding.
4525 Return the number of bytes in *BUF. */
4527 static size_t
4528 quote_name_buf (char **inbuf, size_t bufsize, char *name,
4529 struct quoting_options const *options,
4530 int needs_general_quoting, size_t *width, bool *pad)
4532 char *buf = *inbuf;
4533 size_t displayed_width IF_LINT ( = 0);
4534 size_t len = 0;
4535 bool quoted;
4537 enum quoting_style qs = get_quoting_style (options);
4538 bool needs_further_quoting = qmark_funny_chars
4539 && (qs == shell_quoting_style
4540 || qs == shell_always_quoting_style
4541 || qs == literal_quoting_style);
4543 if (needs_general_quoting != 0)
4545 len = quotearg_buffer (buf, bufsize, name, -1, options);
4546 if (bufsize <= len)
4548 buf = xmalloc (len + 1);
4549 quotearg_buffer (buf, len + 1, name, -1, options);
4552 quoted = (*name != *buf) || strlen (name) != len;
4554 else if (needs_further_quoting)
4556 len = strlen (name);
4557 if (bufsize <= len)
4558 buf = xmalloc (len + 1);
4559 memcpy (buf, name, len + 1);
4561 quoted = false;
4563 else
4565 len = strlen (name);
4566 buf = name;
4567 quoted = false;
4570 if (needs_further_quoting)
4572 if (MB_CUR_MAX > 1)
4574 char const *p = buf;
4575 char const *plimit = buf + len;
4576 char *q = buf;
4577 displayed_width = 0;
4579 while (p < plimit)
4580 switch (*p)
4582 case ' ': case '!': case '"': case '#': case '%':
4583 case '&': case '\'': case '(': case ')': case '*':
4584 case '+': case ',': case '-': case '.': case '/':
4585 case '0': case '1': case '2': case '3': case '4':
4586 case '5': case '6': case '7': case '8': case '9':
4587 case ':': case ';': case '<': case '=': case '>':
4588 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':
4595 case '[': case '\\': case ']': case '^': case '_':
4596 case 'a': case 'b': case 'c': case 'd': case 'e':
4597 case 'f': case 'g': case 'h': case 'i': case 'j':
4598 case 'k': case 'l': case 'm': case 'n': case 'o':
4599 case 'p': case 'q': case 'r': case 's': case 't':
4600 case 'u': case 'v': case 'w': case 'x': case 'y':
4601 case 'z': case '{': case '|': case '}': case '~':
4602 /* These characters are printable ASCII characters. */
4603 *q++ = *p++;
4604 displayed_width += 1;
4605 break;
4606 default:
4607 /* If we have a multibyte sequence, copy it until we
4608 reach its end, replacing each non-printable multibyte
4609 character with a single question mark. */
4611 mbstate_t mbstate = {0};
4614 wchar_t wc;
4615 size_t bytes;
4616 int w;
4618 bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
4620 if (bytes == (size_t) -1)
4622 /* An invalid multibyte sequence was
4623 encountered. Skip one input byte, and
4624 put a question mark. */
4625 p++;
4626 *q++ = '?';
4627 displayed_width += 1;
4628 break;
4631 if (bytes == (size_t) -2)
4633 /* An incomplete multibyte character
4634 at the end. Replace it entirely with
4635 a question mark. */
4636 p = plimit;
4637 *q++ = '?';
4638 displayed_width += 1;
4639 break;
4642 if (bytes == 0)
4643 /* A null wide character was encountered. */
4644 bytes = 1;
4646 w = wcwidth (wc);
4647 if (w >= 0)
4649 /* A printable multibyte character.
4650 Keep it. */
4651 for (; bytes > 0; --bytes)
4652 *q++ = *p++;
4653 displayed_width += w;
4655 else
4657 /* An nonprintable multibyte character.
4658 Replace it entirely with a question
4659 mark. */
4660 p += bytes;
4661 *q++ = '?';
4662 displayed_width += 1;
4665 while (! mbsinit (&mbstate));
4667 break;
4670 /* The buffer may have shrunk. */
4671 len = q - buf;
4673 else
4675 char *p = buf;
4676 char const *plimit = buf + len;
4678 while (p < plimit)
4680 if (! isprint (to_uchar (*p)))
4681 *p = '?';
4682 p++;
4684 displayed_width = len;
4687 else if (width != nullptr)
4689 if (MB_CUR_MAX > 1)
4691 displayed_width = mbsnwidth (buf, len, MBSWIDTH_FLAGS);
4692 displayed_width = MAX (0, displayed_width);
4694 else
4696 char const *p = buf;
4697 char const *plimit = buf + len;
4699 displayed_width = 0;
4700 while (p < plimit)
4702 if (isprint (to_uchar (*p)))
4703 displayed_width++;
4704 p++;
4709 /* Set padding to better align quoted items,
4710 and also give a visual indication that quotes are
4711 not actually part of the name. */
4712 *pad = (align_variable_outer_quotes && cwd_some_quoted && ! quoted);
4714 if (width != nullptr)
4715 *width = displayed_width;
4717 *inbuf = buf;
4719 return len;
4722 static size_t
4723 quote_name_width (char const *name, struct quoting_options const *options,
4724 int needs_general_quoting)
4726 char smallbuf[BUFSIZ];
4727 char *buf = smallbuf;
4728 size_t width;
4729 bool pad;
4731 quote_name_buf (&buf, sizeof smallbuf, (char *) name, options,
4732 needs_general_quoting, &width, &pad);
4734 if (buf != smallbuf && buf != name)
4735 free (buf);
4737 width += pad;
4739 return width;
4742 /* %XX escape any input out of range as defined in RFC3986,
4743 and also if PATH, convert all path separators to '/'. */
4744 static char *
4745 file_escape (char const *str, bool path)
4747 char *esc = xnmalloc (3, strlen (str) + 1);
4748 char *p = esc;
4749 while (*str)
4751 if (path && ISSLASH (*str))
4753 *p++ = '/';
4754 str++;
4756 else if (RFC3986[to_uchar (*str)])
4757 *p++ = *str++;
4758 else
4759 p += sprintf (p, "%%%02x", to_uchar (*str++));
4761 *p = '\0';
4762 return esc;
4765 static size_t
4766 quote_name (char const *name, struct quoting_options const *options,
4767 int needs_general_quoting, const struct bin_str *color,
4768 bool allow_pad, struct obstack *stack, char const *absolute_name)
4770 char smallbuf[BUFSIZ];
4771 char *buf = smallbuf;
4772 size_t len;
4773 bool pad;
4775 len = quote_name_buf (&buf, sizeof smallbuf, (char *) name, options,
4776 needs_general_quoting, nullptr, &pad);
4778 if (pad && allow_pad)
4779 dired_outbyte (' ');
4781 if (color)
4782 print_color_indicator (color);
4784 /* If we're padding, then don't include the outer quotes in
4785 the --hyperlink, to improve the alignment of those links. */
4786 bool skip_quotes = false;
4788 if (absolute_name)
4790 if (align_variable_outer_quotes && cwd_some_quoted && ! pad)
4792 skip_quotes = true;
4793 putchar (*buf);
4795 char *h = file_escape (hostname, /* path= */ false);
4796 char *n = file_escape (absolute_name, /* path= */ true);
4797 /* TODO: It would be good to be able to define parameters
4798 to give hints to the terminal as how best to render the URI.
4799 For example since ls is outputting a dense block of URIs
4800 it would be best to not underline by default, and only
4801 do so upon hover etc. */
4802 printf ("\033]8;;file://%s%s%s\a", h, *n == '/' ? "" : "/", n);
4803 free (h);
4804 free (n);
4807 if (stack)
4808 push_current_dired_pos (stack);
4810 fwrite (buf + skip_quotes, 1, len - (skip_quotes * 2), stdout);
4812 dired_pos += len;
4814 if (stack)
4815 push_current_dired_pos (stack);
4817 if (absolute_name)
4819 fputs ("\033]8;;\a", stdout);
4820 if (skip_quotes)
4821 putchar (*(buf + len - 1));
4824 if (buf != smallbuf && buf != name)
4825 free (buf);
4827 return len + pad;
4830 static size_t
4831 print_name_with_quoting (const struct fileinfo *f,
4832 bool symlink_target,
4833 struct obstack *stack,
4834 size_t start_col)
4836 char const *name = symlink_target ? f->linkname : f->name;
4838 const struct bin_str *color
4839 = print_with_color ? get_color_indicator (f, symlink_target) : nullptr;
4841 bool used_color_this_time = (print_with_color
4842 && (color || is_colored (C_NORM)));
4844 size_t len = quote_name (name, filename_quoting_options, f->quoted,
4845 color, !symlink_target, stack, f->absolute_name);
4847 process_signals ();
4848 if (used_color_this_time)
4850 prep_non_filename_text ();
4852 /* We use the byte length rather than display width here as
4853 an optimization to avoid accurately calculating the width,
4854 because we only output the clear to EOL sequence if the name
4855 _might_ wrap to the next line. This may output a sequence
4856 unnecessarily in multi-byte locales for example,
4857 but in that case it's inconsequential to the output. */
4858 if (line_length
4859 && (start_col / line_length != (start_col + len - 1) / line_length))
4860 put_indicator (&color_indicator[C_CLR_TO_EOL]);
4863 return len;
4866 static void
4867 prep_non_filename_text (void)
4869 if (color_indicator[C_END].string != nullptr)
4870 put_indicator (&color_indicator[C_END]);
4871 else
4873 put_indicator (&color_indicator[C_LEFT]);
4874 put_indicator (&color_indicator[C_RESET]);
4875 put_indicator (&color_indicator[C_RIGHT]);
4879 /* Print the file name of 'f' with appropriate quoting.
4880 Also print file size, inode number, and filetype indicator character,
4881 as requested by switches. */
4883 static size_t
4884 print_file_name_and_frills (const struct fileinfo *f, size_t start_col)
4886 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
4888 set_normal_color ();
4890 if (print_inode)
4891 printf ("%*s ", format == with_commas ? 0 : inode_number_width,
4892 format_inode (buf, f));
4894 if (print_block_size)
4895 printf ("%*s ", format == with_commas ? 0 : block_size_width,
4896 ! f->stat_ok ? "?"
4897 : human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts,
4898 ST_NBLOCKSIZE, output_block_size));
4900 if (print_scontext)
4901 printf ("%*s ", format == with_commas ? 0 : scontext_width, f->scontext);
4903 size_t width = print_name_with_quoting (f, false, nullptr, start_col);
4905 if (indicator_style != none)
4906 width += print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4908 return width;
4911 /* Given these arguments describing a file, return the single-byte
4912 type indicator, or 0. */
4913 static char
4914 get_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
4916 char c;
4918 if (stat_ok ? S_ISREG (mode) : type == normal)
4920 if (stat_ok && indicator_style == classify && (mode & S_IXUGO))
4921 c = '*';
4922 else
4923 c = 0;
4925 else
4927 if (stat_ok ? S_ISDIR (mode) : type == directory || type == arg_directory)
4928 c = '/';
4929 else if (indicator_style == slash)
4930 c = 0;
4931 else if (stat_ok ? S_ISLNK (mode) : type == symbolic_link)
4932 c = '@';
4933 else if (stat_ok ? S_ISFIFO (mode) : type == fifo)
4934 c = '|';
4935 else if (stat_ok ? S_ISSOCK (mode) : type == sock)
4936 c = '=';
4937 else if (stat_ok && S_ISDOOR (mode))
4938 c = '>';
4939 else
4940 c = 0;
4942 return c;
4945 static bool
4946 print_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
4948 char c = get_type_indicator (stat_ok, mode, type);
4949 if (c)
4950 dired_outbyte (c);
4951 return !!c;
4954 /* Returns if color sequence was printed. */
4955 static bool
4956 print_color_indicator (const struct bin_str *ind)
4958 if (ind)
4960 /* Need to reset so not dealing with attribute combinations */
4961 if (is_colored (C_NORM))
4962 restore_default_color ();
4963 put_indicator (&color_indicator[C_LEFT]);
4964 put_indicator (ind);
4965 put_indicator (&color_indicator[C_RIGHT]);
4968 return ind != nullptr;
4971 /* Returns color indicator or nullptr if none. */
4972 ATTRIBUTE_PURE
4973 static const struct bin_str*
4974 get_color_indicator (const struct fileinfo *f, bool symlink_target)
4976 enum indicator_no type;
4977 struct color_ext_type *ext; /* Color extension */
4978 size_t len; /* Length of name */
4980 char const *name;
4981 mode_t mode;
4982 int linkok;
4983 if (symlink_target)
4985 name = f->linkname;
4986 mode = f->linkmode;
4987 linkok = f->linkok ? 0 : -1;
4989 else
4991 name = f->name;
4992 mode = file_or_link_mode (f);
4993 linkok = f->linkok;
4996 /* Is this a nonexistent file? If so, linkok == -1. */
4998 if (linkok == -1 && is_colored (C_MISSING))
4999 type = C_MISSING;
5000 else if (!f->stat_ok)
5002 static enum indicator_no filetype_indicator[] = FILETYPE_INDICATORS;
5003 type = filetype_indicator[f->filetype];
5005 else
5007 if (S_ISREG (mode))
5009 type = C_FILE;
5011 if ((mode & S_ISUID) != 0 && is_colored (C_SETUID))
5012 type = C_SETUID;
5013 else if ((mode & S_ISGID) != 0 && is_colored (C_SETGID))
5014 type = C_SETGID;
5015 else if (is_colored (C_CAP) && f->has_capability)
5016 type = C_CAP;
5017 else if ((mode & S_IXUGO) != 0 && is_colored (C_EXEC))
5018 type = C_EXEC;
5019 else if ((1 < f->stat.st_nlink) && is_colored (C_MULTIHARDLINK))
5020 type = C_MULTIHARDLINK;
5022 else if (S_ISDIR (mode))
5024 type = C_DIR;
5026 if ((mode & S_ISVTX) && (mode & S_IWOTH)
5027 && is_colored (C_STICKY_OTHER_WRITABLE))
5028 type = C_STICKY_OTHER_WRITABLE;
5029 else if ((mode & S_IWOTH) != 0 && is_colored (C_OTHER_WRITABLE))
5030 type = C_OTHER_WRITABLE;
5031 else if ((mode & S_ISVTX) != 0 && is_colored (C_STICKY))
5032 type = C_STICKY;
5034 else if (S_ISLNK (mode))
5035 type = C_LINK;
5036 else if (S_ISFIFO (mode))
5037 type = C_FIFO;
5038 else if (S_ISSOCK (mode))
5039 type = C_SOCK;
5040 else if (S_ISBLK (mode))
5041 type = C_BLK;
5042 else if (S_ISCHR (mode))
5043 type = C_CHR;
5044 else if (S_ISDOOR (mode))
5045 type = C_DOOR;
5046 else
5048 /* Classify a file of some other type as C_ORPHAN. */
5049 type = C_ORPHAN;
5053 /* Check the file's suffix only if still classified as C_FILE. */
5054 ext = nullptr;
5055 if (type == C_FILE)
5057 /* Test if NAME has a recognized suffix. */
5059 len = strlen (name);
5060 name += len; /* Pointer to final \0. */
5061 for (ext = color_ext_list; ext != nullptr; ext = ext->next)
5063 if (ext->ext.len <= len)
5065 if (ext->exact_match)
5067 if (STREQ_LEN (name - ext->ext.len, ext->ext.string,
5068 ext->ext.len))
5069 break;
5071 else
5073 if (c_strncasecmp (name - ext->ext.len, ext->ext.string,
5074 ext->ext.len) == 0)
5075 break;
5081 /* Adjust the color for orphaned symlinks. */
5082 if (type == C_LINK && !linkok)
5084 if (color_symlink_as_referent || is_colored (C_ORPHAN))
5085 type = C_ORPHAN;
5088 const struct bin_str *const s
5089 = ext ? &(ext->seq) : &color_indicator[type];
5091 return s->string ? s : nullptr;
5094 /* Output a color indicator (which may contain nulls). */
5095 static void
5096 put_indicator (const struct bin_str *ind)
5098 if (! used_color)
5100 used_color = true;
5102 /* If the standard output is a controlling terminal, watch out
5103 for signals, so that the colors can be restored to the
5104 default state if "ls" is suspended or interrupted. */
5106 if (0 <= tcgetpgrp (STDOUT_FILENO))
5107 signal_init ();
5109 prep_non_filename_text ();
5112 fwrite (ind->string, ind->len, 1, stdout);
5115 static size_t
5116 length_of_file_name_and_frills (const struct fileinfo *f)
5118 size_t len = 0;
5119 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
5121 if (print_inode)
5122 len += 1 + (format == with_commas
5123 ? strlen (umaxtostr (f->stat.st_ino, buf))
5124 : inode_number_width);
5126 if (print_block_size)
5127 len += 1 + (format == with_commas
5128 ? strlen (! f->stat_ok ? "?"
5129 : human_readable (ST_NBLOCKS (f->stat), buf,
5130 human_output_opts, ST_NBLOCKSIZE,
5131 output_block_size))
5132 : block_size_width);
5134 if (print_scontext)
5135 len += 1 + (format == with_commas ? strlen (f->scontext) : scontext_width);
5137 len += fileinfo_name_width (f);
5139 if (indicator_style != none)
5141 char c = get_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
5142 len += (c != 0);
5145 return len;
5148 static void
5149 print_many_per_line (void)
5151 size_t row; /* Current row. */
5152 size_t cols = calculate_columns (true);
5153 struct column_info const *line_fmt = &column_info[cols - 1];
5155 /* Calculate the number of rows that will be in each column except possibly
5156 for a short column on the right. */
5157 size_t rows = cwd_n_used / cols + (cwd_n_used % cols != 0);
5159 for (row = 0; row < rows; row++)
5161 size_t col = 0;
5162 size_t filesno = row;
5163 size_t pos = 0;
5165 /* Print the next row. */
5166 while (true)
5168 struct fileinfo const *f = sorted_file[filesno];
5169 size_t name_length = length_of_file_name_and_frills (f);
5170 size_t max_name_length = line_fmt->col_arr[col++];
5171 print_file_name_and_frills (f, pos);
5173 filesno += rows;
5174 if (filesno >= cwd_n_used)
5175 break;
5177 indent (pos + name_length, pos + max_name_length);
5178 pos += max_name_length;
5180 putchar (eolbyte);
5184 static void
5185 print_horizontal (void)
5187 size_t filesno;
5188 size_t pos = 0;
5189 size_t cols = calculate_columns (false);
5190 struct column_info const *line_fmt = &column_info[cols - 1];
5191 struct fileinfo const *f = sorted_file[0];
5192 size_t name_length = length_of_file_name_and_frills (f);
5193 size_t max_name_length = line_fmt->col_arr[0];
5195 /* Print first entry. */
5196 print_file_name_and_frills (f, 0);
5198 /* Now the rest. */
5199 for (filesno = 1; filesno < cwd_n_used; ++filesno)
5201 size_t col = filesno % cols;
5203 if (col == 0)
5205 putchar (eolbyte);
5206 pos = 0;
5208 else
5210 indent (pos + name_length, pos + max_name_length);
5211 pos += max_name_length;
5214 f = sorted_file[filesno];
5215 print_file_name_and_frills (f, pos);
5217 name_length = length_of_file_name_and_frills (f);
5218 max_name_length = line_fmt->col_arr[col];
5220 putchar (eolbyte);
5223 /* Output name + SEP + ' '. */
5225 static void
5226 print_with_separator (char sep)
5228 size_t filesno;
5229 size_t pos = 0;
5231 for (filesno = 0; filesno < cwd_n_used; filesno++)
5233 struct fileinfo const *f = sorted_file[filesno];
5234 size_t len = line_length ? length_of_file_name_and_frills (f) : 0;
5236 if (filesno != 0)
5238 char separator;
5240 if (! line_length
5241 || ((pos + len + 2 < line_length)
5242 && (pos <= SIZE_MAX - len - 2)))
5244 pos += 2;
5245 separator = ' ';
5247 else
5249 pos = 0;
5250 separator = eolbyte;
5253 putchar (sep);
5254 putchar (separator);
5257 print_file_name_and_frills (f, pos);
5258 pos += len;
5260 putchar (eolbyte);
5263 /* Assuming cursor is at position FROM, indent up to position TO.
5264 Use a TAB character instead of two or more spaces whenever possible. */
5266 static void
5267 indent (size_t from, size_t to)
5269 while (from < to)
5271 if (tabsize != 0 && to / tabsize > (from + 1) / tabsize)
5273 putchar ('\t');
5274 from += tabsize - from % tabsize;
5276 else
5278 putchar (' ');
5279 from++;
5284 /* Put DIRNAME/NAME into DEST, handling '.' and '/' properly. */
5285 /* FIXME: maybe remove this function someday. See about using a
5286 non-malloc'ing version of file_name_concat. */
5288 static void
5289 attach (char *dest, char const *dirname, char const *name)
5291 char const *dirnamep = dirname;
5293 /* Copy dirname if it is not ".". */
5294 if (dirname[0] != '.' || dirname[1] != 0)
5296 while (*dirnamep)
5297 *dest++ = *dirnamep++;
5298 /* Add '/' if 'dirname' doesn't already end with it. */
5299 if (dirnamep > dirname && dirnamep[-1] != '/')
5300 *dest++ = '/';
5302 while (*name)
5303 *dest++ = *name++;
5304 *dest = 0;
5307 /* Allocate enough column info suitable for the current number of
5308 files and display columns, and initialize the info to represent the
5309 narrowest possible columns. */
5311 static void
5312 init_column_info (size_t max_cols)
5314 size_t i;
5316 /* Currently allocated columns in column_info. */
5317 static size_t column_info_alloc;
5319 if (column_info_alloc < max_cols)
5321 size_t new_column_info_alloc;
5322 size_t *p;
5324 if (!max_idx || max_cols < max_idx / 2)
5326 /* The number of columns is far less than the display width
5327 allows. Grow the allocation, but only so that it's
5328 double the current requirements. If the display is
5329 extremely wide, this avoids allocating a lot of memory
5330 that is never needed. */
5331 column_info = xnrealloc (column_info, max_cols,
5332 2 * sizeof *column_info);
5333 new_column_info_alloc = 2 * max_cols;
5335 else
5337 column_info = xnrealloc (column_info, max_idx, sizeof *column_info);
5338 new_column_info_alloc = max_idx;
5341 /* Allocate the new size_t objects by computing the triangle
5342 formula n * (n + 1) / 2, except that we don't need to
5343 allocate the part of the triangle that we've already
5344 allocated. Check for address arithmetic overflow. */
5346 size_t column_info_growth = new_column_info_alloc - column_info_alloc;
5347 size_t s = column_info_alloc + 1 + new_column_info_alloc;
5348 size_t t = s * column_info_growth;
5349 if (s < new_column_info_alloc || t / column_info_growth != s)
5350 xalloc_die ();
5351 p = xnmalloc (t / 2, sizeof *p);
5354 /* Grow the triangle by parceling out the cells just allocated. */
5355 for (i = column_info_alloc; i < new_column_info_alloc; i++)
5357 column_info[i].col_arr = p;
5358 p += i + 1;
5361 column_info_alloc = new_column_info_alloc;
5364 for (i = 0; i < max_cols; ++i)
5366 size_t j;
5368 column_info[i].valid_len = true;
5369 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
5370 for (j = 0; j <= i; ++j)
5371 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
5375 /* Calculate the number of columns needed to represent the current set
5376 of files in the current display width. */
5378 static size_t
5379 calculate_columns (bool by_columns)
5381 size_t filesno; /* Index into cwd_file. */
5382 size_t cols; /* Number of files across. */
5384 /* Normally the maximum number of columns is determined by the
5385 screen width. But if few files are available this might limit it
5386 as well. */
5387 size_t max_cols = 0 < max_idx && max_idx < cwd_n_used ? max_idx : cwd_n_used;
5389 init_column_info (max_cols);
5391 /* Compute the maximum number of possible columns. */
5392 for (filesno = 0; filesno < cwd_n_used; ++filesno)
5394 struct fileinfo const *f = sorted_file[filesno];
5395 size_t name_length = length_of_file_name_and_frills (f);
5397 for (size_t i = 0; i < max_cols; ++i)
5399 if (column_info[i].valid_len)
5401 size_t idx = (by_columns
5402 ? filesno / ((cwd_n_used + i) / (i + 1))
5403 : filesno % (i + 1));
5404 size_t real_length = name_length + (idx == i ? 0 : 2);
5406 if (column_info[i].col_arr[idx] < real_length)
5408 column_info[i].line_len += (real_length
5409 - column_info[i].col_arr[idx]);
5410 column_info[i].col_arr[idx] = real_length;
5411 column_info[i].valid_len = (column_info[i].line_len
5412 < line_length);
5418 /* Find maximum allowed columns. */
5419 for (cols = max_cols; 1 < cols; --cols)
5421 if (column_info[cols - 1].valid_len)
5422 break;
5425 return cols;
5428 void
5429 usage (int status)
5431 if (status != EXIT_SUCCESS)
5432 emit_try_help ();
5433 else
5435 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
5436 fputs (_("\
5437 List information about the FILEs (the current directory by default).\n\
5438 Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.\n\
5439 "), stdout);
5441 emit_mandatory_arg_note ();
5443 fputs (_("\
5444 -a, --all do not ignore entries starting with .\n\
5445 -A, --almost-all do not list implied . and ..\n\
5446 --author with -l, print the author of each file\n\
5447 -b, --escape print C-style escapes for nongraphic characters\n\
5448 "), stdout);
5449 fputs (_("\
5450 --block-size=SIZE with -l, scale sizes by SIZE when printing them;\n\
5451 e.g., '--block-size=M'; see SIZE format below\n\
5453 "), stdout);
5454 fputs (_("\
5455 -B, --ignore-backups do not list implied entries ending with ~\n\
5456 "), stdout);
5457 fputs (_("\
5458 -c with -lt: sort by, and show, ctime (time of last\n\
5459 change of file status information);\n\
5460 with -l: show ctime and sort by name;\n\
5461 otherwise: sort by ctime, newest first\n\
5463 "), stdout);
5464 fputs (_("\
5465 -C list entries by columns\n\
5466 --color[=WHEN] color the output WHEN; more info below\n\
5467 -d, --directory list directories themselves, not their contents\n\
5468 -D, --dired generate output designed for Emacs' dired mode\n\
5469 "), stdout);
5470 fputs (_("\
5471 -f list all entries in directory order\n\
5472 -F, --classify[=WHEN] append indicator (one of */=>@|) to entries WHEN\n\
5473 --file-type likewise, except do not append '*'\n\
5474 "), stdout);
5475 fputs (_("\
5476 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
5477 single-column -1, verbose -l, vertical -C\n\
5479 "), stdout);
5480 fputs (_("\
5481 --full-time like -l --time-style=full-iso\n\
5482 "), stdout);
5483 fputs (_("\
5484 -g like -l, but do not list owner\n\
5485 "), stdout);
5486 fputs (_("\
5487 --group-directories-first\n\
5488 group directories before files;\n\
5489 can be augmented with a --sort option, but any\n\
5490 use of --sort=none (-U) disables grouping\n\
5492 "), stdout);
5493 fputs (_("\
5494 -G, --no-group in a long listing, don't print group names\n\
5495 "), stdout);
5496 fputs (_("\
5497 -h, --human-readable with -l and -s, print sizes like 1K 234M 2G etc.\n\
5498 --si likewise, but use powers of 1000 not 1024\n\
5499 "), stdout);
5500 fputs (_("\
5501 -H, --dereference-command-line\n\
5502 follow symbolic links listed on the command line\n\
5503 "), stdout);
5504 fputs (_("\
5505 --dereference-command-line-symlink-to-dir\n\
5506 follow each command line symbolic link\n\
5507 that points to a directory\n\
5509 "), stdout);
5510 fputs (_("\
5511 --hide=PATTERN do not list implied entries matching shell PATTERN\
5513 (overridden by -a or -A)\n\
5515 "), stdout);
5516 fputs (_("\
5517 --hyperlink[=WHEN] hyperlink file names WHEN\n\
5518 "), stdout);
5519 fputs (_("\
5520 --indicator-style=WORD\n\
5521 append indicator with style WORD to entry names:\n\
5522 none (default), slash (-p),\n\
5523 file-type (--file-type), classify (-F)\n\
5525 "), stdout);
5526 fputs (_("\
5527 -i, --inode print the index number of each file\n\
5528 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\
5530 "), stdout);
5531 fputs (_("\
5532 -k, --kibibytes default to 1024-byte blocks for file system usage;\
5534 used only with -s and per directory totals\n\
5536 "), stdout);
5537 fputs (_("\
5538 -l use a long listing format\n\
5539 "), stdout);
5540 fputs (_("\
5541 -L, --dereference when showing file information for a symbolic\n\
5542 link, show information for the file the link\n\
5543 references rather than for the link itself\n\
5545 "), stdout);
5546 fputs (_("\
5547 -m fill width with a comma separated list of entries\
5549 "), stdout);
5550 fputs (_("\
5551 -n, --numeric-uid-gid like -l, but list numeric user and group IDs\n\
5552 -N, --literal print entry names without quoting\n\
5553 -o like -l, but do not list group information\n\
5554 -p, --indicator-style=slash\n\
5555 append / indicator to directories\n\
5556 "), stdout);
5557 fputs (_("\
5558 -q, --hide-control-chars print ? instead of nongraphic characters\n\
5559 "), stdout);
5560 fputs (_("\
5561 --show-control-chars show nongraphic characters as-is (the default,\n\
5562 unless program is 'ls' and output is a terminal)\
5565 "), stdout);
5566 fputs (_("\
5567 -Q, --quote-name enclose entry names in double quotes\n\
5568 "), stdout);
5569 fputs (_("\
5570 --quoting-style=WORD use quoting style WORD for entry names:\n\
5571 literal, locale, shell, shell-always,\n\
5572 shell-escape, shell-escape-always, c, escape\n\
5573 (overrides QUOTING_STYLE environment variable)\n\
5575 "), stdout);
5576 fputs (_("\
5577 -r, --reverse reverse order while sorting\n\
5578 -R, --recursive list subdirectories recursively\n\
5579 -s, --size print the allocated size of each file, in blocks\n\
5580 "), stdout);
5581 fputs (_("\
5582 -S sort by file size, largest first\n\
5583 "), stdout);
5584 fputs (_("\
5585 --sort=WORD sort by WORD instead of name: none (-U), size (-S)\
5586 ,\n\
5587 time (-t), version (-v), extension (-X), width\n\
5589 "), stdout);
5590 fputs (_("\
5591 --time=WORD select which timestamp used to display or sort;\n\
5592 access time (-u): atime, access, use;\n\
5593 metadata change time (-c): ctime, status;\n\
5594 modified time (default): mtime, modification;\n\
5595 birth time: birth, creation;\n\
5596 with -l, WORD determines which time to show;\n\
5597 with --sort=time, sort by WORD (newest first)\n\
5599 "), stdout);
5600 fputs (_("\
5601 --time-style=TIME_STYLE\n\
5602 time/date format with -l; see TIME_STYLE below\n\
5603 "), stdout);
5604 fputs (_("\
5605 -t sort by time, newest first; see --time\n\
5606 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
5607 "), stdout);
5608 fputs (_("\
5609 -u with -lt: sort by, and show, access time;\n\
5610 with -l: show access time and sort by name;\n\
5611 otherwise: sort by access time, newest first\n\
5613 "), stdout);
5614 fputs (_("\
5615 -U do not sort; list entries in directory order\n\
5616 "), stdout);
5617 fputs (_("\
5618 -v natural sort of (version) numbers within text\n\
5619 "), stdout);
5620 fputs (_("\
5621 -w, --width=COLS set output width to COLS. 0 means no limit\n\
5622 -x list entries by lines instead of by columns\n\
5623 -X sort alphabetically by entry extension\n\
5624 -Z, --context print any security context of each file\n\
5625 --zero end each output line with NUL, not newline\n\
5626 -1 list one file per line\n\
5627 "), stdout);
5628 fputs (HELP_OPTION_DESCRIPTION, stdout);
5629 fputs (VERSION_OPTION_DESCRIPTION, stdout);
5630 emit_size_note ();
5631 fputs (_("\
5633 The TIME_STYLE argument can be full-iso, long-iso, iso, locale, or +FORMAT.\n\
5634 FORMAT is interpreted like in date(1). If FORMAT is FORMAT1<newline>FORMAT2,\n\
5635 then FORMAT1 applies to non-recent files and FORMAT2 to recent files.\n\
5636 TIME_STYLE prefixed with 'posix-' takes effect only outside the POSIX locale.\n\
5637 Also the TIME_STYLE environment variable sets the default style to use.\n\
5638 "), stdout);
5639 fputs (_("\
5641 The WHEN argument defaults to 'always' and can also be 'auto' or 'never'.\n\
5642 "), stdout);
5643 fputs (_("\
5645 Using color to distinguish file types is disabled both by default and\n\
5646 with --color=never. With --color=auto, ls emits color codes only when\n\
5647 standard output is connected to a terminal. The LS_COLORS environment\n\
5648 variable can change the settings. Use the dircolors(1) command to set it.\n\
5649 "), stdout);
5650 fputs (_("\
5652 Exit status:\n\
5653 0 if OK,\n\
5654 1 if minor problems (e.g., cannot access subdirectory),\n\
5655 2 if serious trouble (e.g., cannot access command-line argument).\n\
5656 "), stdout);
5657 emit_ancillary_info (PROGRAM_NAME);
5659 exit (status);