TODO: add an item for a chmod optimization
[platform/upstream/coreutils.git] / src / ls.c
1 /* `dir', `vdir' and `ls' directory listing programs for GNU.
2    Copyright (C) 85, 88, 90, 91, 1995-2008 Free Software Foundation, Inc.
3
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.
8
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.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
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.
21
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.
26
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.  */
31
32 /* Written by Richard Stallman and David MacKenzie.  */
33
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>.  */
37
38 #include <config.h>
39 #include <sys/types.h>
40
41 #ifdef HAVE_CAP
42 # include <sys/capability.h>
43 #endif
44
45 #if HAVE_TERMIOS_H
46 # include <termios.h>
47 #endif
48 #if HAVE_STROPTS_H
49 # include <stropts.h>
50 #endif
51 #if HAVE_SYS_IOCTL_H
52 # include <sys/ioctl.h>
53 #endif
54
55 #ifdef WINSIZE_IN_PTEM
56 # include <sys/stream.h>
57 # include <sys/ptem.h>
58 #endif
59
60 #include <stdio.h>
61 #include <assert.h>
62 #include <setjmp.h>
63 #include <grp.h>
64 #include <pwd.h>
65 #include <getopt.h>
66 #include <signal.h>
67 #include <selinux/selinux.h>
68 #include <wchar.h>
69
70 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
71    present.  */
72 #ifndef SA_NOCLDSTOP
73 # define SA_NOCLDSTOP 0
74 # define sigprocmask(How, Set, Oset) /* empty */
75 # define sigset_t int
76 # if ! HAVE_SIGINTERRUPT
77 #  define siginterrupt(sig, flag) /* empty */
78 # endif
79 #endif
80 #ifndef SA_RESTART
81 # define SA_RESTART 0
82 #endif
83
84 #include "system.h"
85 #include <fnmatch.h>
86
87 #include "acl.h"
88 #include "argmatch.h"
89 #include "dev-ino.h"
90 #include "dirfd.h"
91 #include "error.h"
92 #include "filenamecat.h"
93 #include "hard-locale.h"
94 #include "hash.h"
95 #include "human.h"
96 #include "filemode.h"
97 #include "idcache.h"
98 #include "ls.h"
99 #include "lstat.h"
100 #include "mbswidth.h"
101 #include "mpsort.h"
102 #include "obstack.h"
103 #include "quote.h"
104 #include "quotearg.h"
105 #include "same.h"
106 #include "stat-time.h"
107 #include "strftime.h"
108 #include "xstrtol.h"
109 #include "areadlink.h"
110
111 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
112                       : (ls_mode == LS_MULTI_COL \
113                          ? "dir" : "vdir"))
114
115 #define AUTHORS \
116   proper_name ("Richard M. Stallman"), \
117   proper_name ("David MacKenzie")
118
119 #define obstack_chunk_alloc malloc
120 #define obstack_chunk_free free
121
122 /* Return an int indicating the result of comparing two integers.
123    Subtracting doesn't always work, due to overflow.  */
124 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
125
126 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
127 # define st_author st_uid
128 #endif
129
130 enum filetype
131   {
132     unknown,
133     fifo,
134     chardev,
135     directory,
136     blockdev,
137     normal,
138     symbolic_link,
139     sock,
140     whiteout,
141     arg_directory
142   };
143
144 /* Display letters and indicators for each filetype.
145    Keep these in sync with enum filetype.  */
146 static char const filetype_letter[] = "?pcdb-lswd";
147
148 /* Ensure that filetype and filetype_letter have the same
149    number of elements.  */
150 verify (sizeof filetype_letter - 1 == arg_directory + 1);
151
152 #define FILETYPE_INDICATORS                             \
153   {                                                     \
154     C_ORPHAN, C_FIFO, C_CHR, C_DIR, C_BLK, C_FILE,      \
155     C_LINK, C_SOCK, C_FILE, C_DIR                       \
156   }
157
158
159 struct fileinfo
160   {
161     /* The file name.  */
162     char *name;
163
164     /* For symbolic link, name of the file linked to, otherwise zero.  */
165     char *linkname;
166
167     struct stat stat;
168
169     enum filetype filetype;
170
171     /* For symbolic link and long listing, st_mode of file linked to, otherwise
172        zero.  */
173     mode_t linkmode;
174
175     /* SELinux security context.  */
176     security_context_t scontext;
177
178     bool stat_ok;
179
180     /* For symbolic link and color printing, true if linked-to file
181        exists, otherwise false.  */
182     bool linkok;
183
184     /* For long listings, true if the file has an access control list,
185        or an SELinux security context.  */
186     bool have_acl;
187   };
188
189 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
190
191 /* Null is a valid character in a color indicator (think about Epson
192    printers, for example) so we have to use a length/buffer string
193    type.  */
194
195 struct bin_str
196   {
197     size_t len;                 /* Number of bytes */
198     const char *string;         /* Pointer to the same */
199   };
200
201 #if ! HAVE_TCGETPGRP
202 # define tcgetpgrp(Fd) 0
203 #endif
204
205 static size_t quote_name (FILE *out, const char *name,
206                           struct quoting_options const *options,
207                           size_t *width);
208 static char *make_link_name (char const *name, char const *linkname);
209 static int decode_switches (int argc, char **argv);
210 static bool file_ignored (char const *name);
211 static uintmax_t gobble_file (char const *name, enum filetype type,
212                               ino_t inode, bool command_line_arg,
213                               char const *dirname);
214 static bool print_color_indicator (const char *name, mode_t mode, int linkok,
215                                    bool stat_ok, enum filetype type);
216 static void put_indicator (const struct bin_str *ind);
217 static void add_ignore_pattern (const char *pattern);
218 static void attach (char *dest, const char *dirname, const char *name);
219 static void clear_files (void);
220 static void extract_dirs_from_files (char const *dirname,
221                                      bool command_line_arg);
222 static void get_link_name (char const *filename, struct fileinfo *f,
223                            bool command_line_arg);
224 static void indent (size_t from, size_t to);
225 static size_t calculate_columns (bool by_columns);
226 static void print_current_files (void);
227 static void print_dir (char const *name, char const *realname,
228                        bool command_line_arg);
229 static void print_file_name_and_frills (const struct fileinfo *f);
230 static void print_horizontal (void);
231 static int format_user_width (uid_t u);
232 static int format_group_width (gid_t g);
233 static void print_long_format (const struct fileinfo *f);
234 static void print_many_per_line (void);
235 static void print_name_with_quoting (const char *p, mode_t mode,
236                                      int linkok, bool stat_ok,
237                                      enum filetype type,
238                                      struct obstack *stack);
239 static void prep_non_filename_text (void);
240 static void print_type_indicator (bool stat_ok, mode_t mode,
241                                   enum filetype type);
242 static void print_with_commas (void);
243 static void queue_directory (char const *name, char const *realname,
244                              bool command_line_arg);
245 static void sort_files (void);
246 static void parse_ls_color (void);
247 void usage (int status);
248
249 /* Initial size of hash table.
250    Most hierarchies are likely to be shallower than this.  */
251 #define INITIAL_TABLE_SIZE 30
252
253 /* The set of `active' directories, from the current command-line argument
254    to the level in the hierarchy at which files are being listed.
255    A directory is represented by its device and inode numbers (struct dev_ino).
256    A directory is added to this set when ls begins listing it or its
257    entries, and it is removed from the set just after ls has finished
258    processing it.  This set is used solely to detect loops, e.g., with
259    mkdir loop; cd loop; ln -s ../loop sub; ls -RL  */
260 static Hash_table *active_dir_set;
261
262 #define LOOP_DETECT (!!active_dir_set)
263
264 /* The table of files in the current directory:
265
266    `cwd_file' points to a vector of `struct fileinfo', one per file.
267    `cwd_n_alloc' is the number of elements space has been allocated for.
268    `cwd_n_used' is the number actually in use.  */
269
270 /* Address of block containing the files that are described.  */
271 static struct fileinfo *cwd_file;
272
273 /* Length of block that `cwd_file' points to, measured in files.  */
274 static size_t cwd_n_alloc;
275
276 /* Index of first unused slot in `cwd_file'.  */
277 static size_t cwd_n_used;
278
279 /* Vector of pointers to files, in proper sorted order, and the number
280    of entries allocated for it.  */
281 static void **sorted_file;
282 static size_t sorted_file_alloc;
283
284 /* When true, in a color listing, color each symlink name according to the
285    type of file it points to.  Otherwise, color them according to the `ln'
286    directive in LS_COLORS.  Dangling (orphan) symlinks are treated specially,
287    regardless.  This is set when `ln=target' appears in LS_COLORS.  */
288
289 static bool color_symlink_as_referent;
290
291 /* mode of appropriate file for colorization */
292 #define FILE_OR_LINK_MODE(File) \
293     ((color_symlink_as_referent & (File)->linkok) \
294      ? (File)->linkmode : (File)->stat.st_mode)
295
296
297 /* Record of one pending directory waiting to be listed.  */
298
299 struct pending
300   {
301     char *name;
302     /* If the directory is actually the file pointed to by a symbolic link we
303        were told to list, `realname' will contain the name of the symbolic
304        link, otherwise zero.  */
305     char *realname;
306     bool command_line_arg;
307     struct pending *next;
308   };
309
310 static struct pending *pending_dirs;
311
312 /* Current time in seconds and nanoseconds since 1970, updated as
313    needed when deciding whether a file is recent.  */
314
315 static struct timespec current_time;
316
317 static bool print_scontext;
318 static char UNKNOWN_SECURITY_CONTEXT[] = "?";
319
320 /* Whether any of the files has an ACL.  This affects the width of the
321    mode column.  */
322
323 static bool any_has_acl;
324
325 /* The number of columns to use for columns containing inode numbers,
326    block sizes, link counts, owners, groups, authors, major device
327    numbers, minor device numbers, and file sizes, respectively.  */
328
329 static int inode_number_width;
330 static int block_size_width;
331 static int nlink_width;
332 static int scontext_width;
333 static int owner_width;
334 static int group_width;
335 static int author_width;
336 static int major_device_number_width;
337 static int minor_device_number_width;
338 static int file_size_width;
339
340 /* Option flags */
341
342 /* long_format for lots of info, one per line.
343    one_per_line for just names, one per line.
344    many_per_line for just names, many per line, sorted vertically.
345    horizontal for just names, many per line, sorted horizontally.
346    with_commas for just names, many per line, separated by commas.
347
348    -l (and other options that imply -l), -1, -C, -x and -m control
349    this parameter.  */
350
351 enum format
352   {
353     long_format,                /* -l and other options that imply -l */
354     one_per_line,               /* -1 */
355     many_per_line,              /* -C */
356     horizontal,                 /* -x */
357     with_commas                 /* -m */
358   };
359
360 static enum format format;
361
362 /* `full-iso' uses full ISO-style dates and times.  `long-iso' uses longer
363    ISO-style time stamps, though shorter than `full-iso'.  `iso' uses shorter
364    ISO-style time stamps.  `locale' uses locale-dependent time stamps.  */
365 enum time_style
366   {
367     full_iso_time_style,        /* --time-style=full-iso */
368     long_iso_time_style,        /* --time-style=long-iso */
369     iso_time_style,             /* --time-style=iso */
370     locale_time_style           /* --time-style=locale */
371   };
372
373 static char const *const time_style_args[] =
374 {
375   "full-iso", "long-iso", "iso", "locale", NULL
376 };
377 static enum time_style const time_style_types[] =
378 {
379   full_iso_time_style, long_iso_time_style, iso_time_style,
380   locale_time_style
381 };
382 ARGMATCH_VERIFY (time_style_args, time_style_types);
383
384 /* Type of time to print or sort by.  Controlled by -c and -u.
385    The values of each item of this enum are important since they are
386    used as indices in the sort functions array (see sort_files()).  */
387
388 enum time_type
389   {
390     time_mtime,                 /* default */
391     time_ctime,                 /* -c */
392     time_atime,                 /* -u */
393     time_numtypes               /* the number of elements of this enum */
394   };
395
396 static enum time_type time_type;
397
398 /* The file characteristic to sort by.  Controlled by -t, -S, -U, -X, -v.
399    The values of each item of this enum are important since they are
400    used as indices in the sort functions array (see sort_files()).  */
401
402 enum sort_type
403   {
404     sort_none = -1,             /* -U */
405     sort_name,                  /* default */
406     sort_extension,             /* -X */
407     sort_size,                  /* -S */
408     sort_version,               /* -v */
409     sort_time,                  /* -t */
410     sort_numtypes               /* the number of elements of this enum */
411   };
412
413 static enum sort_type sort_type;
414
415 /* Direction of sort.
416    false means highest first if numeric,
417    lowest first if alphabetic;
418    these are the defaults.
419    true means the opposite order in each case.  -r  */
420
421 static bool sort_reverse;
422
423 /* True means to display owner information.  -g turns this off.  */
424
425 static bool print_owner = true;
426
427 /* True means to display author information.  */
428
429 static bool print_author;
430
431 /* True means to display group information.  -G and -o turn this off.  */
432
433 static bool print_group = true;
434
435 /* True means print the user and group id's as numbers rather
436    than as names.  -n  */
437
438 static bool numeric_ids;
439
440 /* True means mention the size in blocks of each file.  -s  */
441
442 static bool print_block_size;
443
444 /* Human-readable options for output.  */
445 static int human_output_opts;
446
447 /* The units to use when printing sizes other than file sizes.  */
448 static uintmax_t output_block_size;
449
450 /* Likewise, but for file sizes.  */
451 static uintmax_t file_output_block_size = 1;
452
453 /* Follow the output with a special string.  Using this format,
454    Emacs' dired mode starts up twice as fast, and can handle all
455    strange characters in file names.  */
456 static bool dired;
457
458 /* `none' means don't mention the type of files.
459    `slash' means mention directories only, with a '/'.
460    `file_type' means mention file types.
461    `classify' means mention file types and mark executables.
462
463    Controlled by -F, -p, and --indicator-style.  */
464
465 enum indicator_style
466   {
467     none,       /*     --indicator-style=none */
468     slash,      /* -p, --indicator-style=slash */
469     file_type,  /*     --indicator-style=file-type */
470     classify    /* -F, --indicator-style=classify */
471   };
472
473 static enum indicator_style indicator_style;
474
475 /* Names of indicator styles.  */
476 static char const *const indicator_style_args[] =
477 {
478   "none", "slash", "file-type", "classify", NULL
479 };
480 static enum indicator_style const indicator_style_types[] =
481 {
482   none, slash, file_type, classify
483 };
484 ARGMATCH_VERIFY (indicator_style_args, indicator_style_types);
485
486 /* True means use colors to mark types.  Also define the different
487    colors as well as the stuff for the LS_COLORS environment variable.
488    The LS_COLORS variable is now in a termcap-like format.  */
489
490 static bool print_with_color;
491
492 /* Whether we used any colors in the output so far.  If so, we will
493    need to restore the default color later.  If not, we will need to
494    call prep_non_filename_text before using color for the first time. */
495
496 static bool used_color = false;
497
498 enum color_type
499   {
500     color_never,                /* 0: default or --color=never */
501     color_always,               /* 1: --color=always */
502     color_if_tty                /* 2: --color=tty */
503   };
504
505 enum Dereference_symlink
506   {
507     DEREF_UNDEFINED = 1,
508     DEREF_NEVER,
509     DEREF_COMMAND_LINE_ARGUMENTS,       /* -H */
510     DEREF_COMMAND_LINE_SYMLINK_TO_DIR,  /* the default, in certain cases */
511     DEREF_ALWAYS                        /* -L */
512   };
513
514 enum indicator_no
515   {
516     C_LEFT, C_RIGHT, C_END, C_RESET, C_NORM, C_FILE, C_DIR, C_LINK,
517     C_FIFO, C_SOCK,
518     C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR, C_SETUID, C_SETGID,
519     C_STICKY, C_OTHER_WRITABLE, C_STICKY_OTHER_WRITABLE, C_CAP
520   };
521
522 static const char *const indicator_name[]=
523   {
524     "lc", "rc", "ec", "rs", "no", "fi", "di", "ln", "pi", "so",
525     "bd", "cd", "mi", "or", "ex", "do", "su", "sg", "st",
526     "ow", "tw", "ca", NULL
527   };
528
529 struct color_ext_type
530   {
531     struct bin_str ext;         /* The extension we're looking for */
532     struct bin_str seq;         /* The sequence to output when we do */
533     struct color_ext_type *next;        /* Next in list */
534   };
535
536 static struct bin_str color_indicator[] =
537   {
538     { LEN_STR_PAIR ("\033[") },         /* lc: Left of color sequence */
539     { LEN_STR_PAIR ("m") },             /* rc: Right of color sequence */
540     { 0, NULL },                        /* ec: End color (replaces lc+no+rc) */
541     { LEN_STR_PAIR ("0") },             /* rs: Reset to ordinary colors */
542     { 0, NULL },                        /* no: Normal */
543     { 0, NULL },                        /* fi: File: default */
544     { LEN_STR_PAIR ("01;34") },         /* di: Directory: bright blue */
545     { LEN_STR_PAIR ("01;36") },         /* ln: Symlink: bright cyan */
546     { LEN_STR_PAIR ("33") },            /* pi: Pipe: yellow/brown */
547     { LEN_STR_PAIR ("01;35") },         /* so: Socket: bright magenta */
548     { LEN_STR_PAIR ("01;33") },         /* bd: Block device: bright yellow */
549     { LEN_STR_PAIR ("01;33") },         /* cd: Char device: bright yellow */
550     { 0, NULL },                        /* mi: Missing file: undefined */
551     { 0, NULL },                        /* or: Orphaned symlink: undefined */
552     { LEN_STR_PAIR ("01;32") },         /* ex: Executable: bright green */
553     { LEN_STR_PAIR ("01;35") },         /* do: Door: bright magenta */
554     { LEN_STR_PAIR ("37;41") },         /* su: setuid: white on red */
555     { LEN_STR_PAIR ("30;43") },         /* sg: setgid: black on yellow */
556     { LEN_STR_PAIR ("37;44") },         /* st: sticky: black on blue */
557     { LEN_STR_PAIR ("34;42") },         /* ow: other-writable: blue on green */
558     { LEN_STR_PAIR ("30;42") },         /* tw: ow w/ sticky: black on green */
559     { LEN_STR_PAIR ("30;41") },         /* capability: black on red */
560   };
561
562 /* FIXME: comment  */
563 static struct color_ext_type *color_ext_list = NULL;
564
565 /* Buffer for color sequences */
566 static char *color_buf;
567
568 /* True means to check for orphaned symbolic link, for displaying
569    colors.  */
570
571 static bool check_symlink_color;
572
573 /* True means mention the inode number of each file.  -i  */
574
575 static bool print_inode;
576
577 /* What to do with symbolic links.  Affected by -d, -F, -H, -l (and
578    other options that imply -l), and -L.  */
579
580 static enum Dereference_symlink dereference;
581
582 /* True means when a directory is found, display info on its
583    contents.  -R  */
584
585 static bool recursive;
586
587 /* True means when an argument is a directory name, display info
588    on it itself.  -d  */
589
590 static bool immediate_dirs;
591
592 /* True means that directories are grouped before files. */
593
594 static bool directories_first;
595
596 /* Which files to ignore.  */
597
598 static enum
599 {
600   /* Ignore files whose names start with `.', and files specified by
601      --hide and --ignore.  */
602   IGNORE_DEFAULT,
603
604   /* Ignore `.', `..', and files specified by --ignore.  */
605   IGNORE_DOT_AND_DOTDOT,
606
607   /* Ignore only files specified by --ignore.  */
608   IGNORE_MINIMAL
609 } ignore_mode;
610
611 /* A linked list of shell-style globbing patterns.  If a non-argument
612    file name matches any of these patterns, it is ignored.
613    Controlled by -I.  Multiple -I options accumulate.
614    The -B option adds `*~' and `.*~' to this list.  */
615
616 struct ignore_pattern
617   {
618     const char *pattern;
619     struct ignore_pattern *next;
620   };
621
622 static struct ignore_pattern *ignore_patterns;
623
624 /* Similar to IGNORE_PATTERNS, except that -a or -A causes this
625    variable itself to be ignored.  */
626 static struct ignore_pattern *hide_patterns;
627
628 /* True means output nongraphic chars in file names as `?'.
629    (-q, --hide-control-chars)
630    qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
631    independent.  The algorithm is: first, obey the quoting style to get a
632    string representing the file name;  then, if qmark_funny_chars is set,
633    replace all nonprintable chars in that string with `?'.  It's necessary
634    to replace nonprintable chars even in quoted strings, because we don't
635    want to mess up the terminal if control chars get sent to it, and some
636    quoting methods pass through control chars as-is.  */
637 static bool qmark_funny_chars;
638
639 /* Quoting options for file and dir name output.  */
640
641 static struct quoting_options *filename_quoting_options;
642 static struct quoting_options *dirname_quoting_options;
643
644 /* The number of chars per hardware tab stop.  Setting this to zero
645    inhibits the use of TAB characters for separating columns.  -T */
646 static size_t tabsize;
647
648 /* True means print each directory name before listing it.  */
649
650 static bool print_dir_name;
651
652 /* The line length to use for breaking lines in many-per-line format.
653    Can be set with -w.  */
654
655 static size_t line_length;
656
657 /* If true, the file listing format requires that stat be called on
658    each file.  */
659
660 static bool format_needs_stat;
661
662 /* Similar to `format_needs_stat', but set if only the file type is
663    needed.  */
664
665 static bool format_needs_type;
666
667 /* An arbitrary limit on the number of bytes in a printed time stamp.
668    This is set to a relatively small value to avoid the need to worry
669    about denial-of-service attacks on servers that run "ls" on behalf
670    of remote clients.  1000 bytes should be enough for any practical
671    time stamp format.  */
672
673 enum { TIME_STAMP_LEN_MAXIMUM = MAX (1000, INT_STRLEN_BOUND (time_t)) };
674
675 /* strftime formats for non-recent and recent files, respectively, in
676    -l output.  */
677
678 static char const *long_time_format[2] =
679   {
680     /* strftime format for non-recent files (older than 6 months), in
681        -l output.  This should contain the year, month and day (at
682        least), in an order that is understood by people in your
683        locale's territory.  Please try to keep the number of used
684        screen columns small, because many people work in windows with
685        only 80 columns.  But make this as wide as the other string
686        below, for recent files.  */
687     N_("%b %e  %Y"),
688     /* strftime format for recent files (younger than 6 months), in -l
689        output.  This should contain the month, day and time (at
690        least), in an order that is understood by people in your
691        locale's territory.  Please try to keep the number of used
692        screen columns small, because many people work in windows with
693        only 80 columns.  But make this as wide as the other string
694        above, for non-recent files.  */
695     N_("%b %e %H:%M")
696   };
697
698 /* The set of signals that are caught.  */
699
700 static sigset_t caught_signals;
701
702 /* If nonzero, the value of the pending fatal signal.  */
703
704 static sig_atomic_t volatile interrupt_signal;
705
706 /* A count of the number of pending stop signals that have been received.  */
707
708 static sig_atomic_t volatile stop_signal_count;
709
710 /* Desired exit status.  */
711
712 static int exit_status;
713
714 /* Exit statuses.  */
715 enum
716   {
717     /* "ls" had a minor problem (e.g., it could not stat a directory
718        entry).  */
719     LS_MINOR_PROBLEM = 1,
720
721     /* "ls" had more serious trouble.  */
722     LS_FAILURE = 2
723   };
724
725 /* For long options that have no equivalent short option, use a
726    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
727 enum
728 {
729   AUTHOR_OPTION = CHAR_MAX + 1,
730   BLOCK_SIZE_OPTION,
731   COLOR_OPTION,
732   DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION,
733   FILE_TYPE_INDICATOR_OPTION,
734   FORMAT_OPTION,
735   FULL_TIME_OPTION,
736   GROUP_DIRECTORIES_FIRST_OPTION,
737   HIDE_OPTION,
738   INDICATOR_STYLE_OPTION,
739   QUOTING_STYLE_OPTION,
740   SHOW_CONTROL_CHARS_OPTION,
741   SI_OPTION,
742   SORT_OPTION,
743   TIME_OPTION,
744   TIME_STYLE_OPTION
745 };
746
747 static struct option const long_options[] =
748 {
749   {"all", no_argument, NULL, 'a'},
750   {"escape", no_argument, NULL, 'b'},
751   {"directory", no_argument, NULL, 'd'},
752   {"dired", no_argument, NULL, 'D'},
753   {"full-time", no_argument, NULL, FULL_TIME_OPTION},
754   {"group-directories-first", no_argument, NULL,
755    GROUP_DIRECTORIES_FIRST_OPTION},
756   {"human-readable", no_argument, NULL, 'h'},
757   {"inode", no_argument, NULL, 'i'},
758   {"numeric-uid-gid", no_argument, NULL, 'n'},
759   {"no-group", no_argument, NULL, 'G'},
760   {"hide-control-chars", no_argument, NULL, 'q'},
761   {"reverse", no_argument, NULL, 'r'},
762   {"size", no_argument, NULL, 's'},
763   {"width", required_argument, NULL, 'w'},
764   {"almost-all", no_argument, NULL, 'A'},
765   {"ignore-backups", no_argument, NULL, 'B'},
766   {"classify", no_argument, NULL, 'F'},
767   {"file-type", no_argument, NULL, FILE_TYPE_INDICATOR_OPTION},
768   {"si", no_argument, NULL, SI_OPTION},
769   {"dereference-command-line", no_argument, NULL, 'H'},
770   {"dereference-command-line-symlink-to-dir", no_argument, NULL,
771    DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION},
772   {"hide", required_argument, NULL, HIDE_OPTION},
773   {"ignore", required_argument, NULL, 'I'},
774   {"indicator-style", required_argument, NULL, INDICATOR_STYLE_OPTION},
775   {"dereference", no_argument, NULL, 'L'},
776   {"literal", no_argument, NULL, 'N'},
777   {"quote-name", no_argument, NULL, 'Q'},
778   {"quoting-style", required_argument, NULL, QUOTING_STYLE_OPTION},
779   {"recursive", no_argument, NULL, 'R'},
780   {"format", required_argument, NULL, FORMAT_OPTION},
781   {"show-control-chars", no_argument, NULL, SHOW_CONTROL_CHARS_OPTION},
782   {"sort", required_argument, NULL, SORT_OPTION},
783   {"tabsize", required_argument, NULL, 'T'},
784   {"time", required_argument, NULL, TIME_OPTION},
785   {"time-style", required_argument, NULL, TIME_STYLE_OPTION},
786   {"color", optional_argument, NULL, COLOR_OPTION},
787   {"block-size", required_argument, NULL, BLOCK_SIZE_OPTION},
788   {"context", no_argument, 0, 'Z'},
789   {"author", no_argument, NULL, AUTHOR_OPTION},
790   {GETOPT_HELP_OPTION_DECL},
791   {GETOPT_VERSION_OPTION_DECL},
792   {NULL, 0, NULL, 0}
793 };
794
795 static char const *const format_args[] =
796 {
797   "verbose", "long", "commas", "horizontal", "across",
798   "vertical", "single-column", NULL
799 };
800 static enum format const format_types[] =
801 {
802   long_format, long_format, with_commas, horizontal, horizontal,
803   many_per_line, one_per_line
804 };
805 ARGMATCH_VERIFY (format_args, format_types);
806
807 static char const *const sort_args[] =
808 {
809   "none", "time", "size", "extension", "version", NULL
810 };
811 static enum sort_type const sort_types[] =
812 {
813   sort_none, sort_time, sort_size, sort_extension, sort_version
814 };
815 ARGMATCH_VERIFY (sort_args, sort_types);
816
817 static char const *const time_args[] =
818 {
819   "atime", "access", "use", "ctime", "status", NULL
820 };
821 static enum time_type const time_types[] =
822 {
823   time_atime, time_atime, time_atime, time_ctime, time_ctime
824 };
825 ARGMATCH_VERIFY (time_args, time_types);
826
827 static char const *const color_args[] =
828 {
829   /* force and none are for compatibility with another color-ls version */
830   "always", "yes", "force",
831   "never", "no", "none",
832   "auto", "tty", "if-tty", NULL
833 };
834 static enum color_type const color_types[] =
835 {
836   color_always, color_always, color_always,
837   color_never, color_never, color_never,
838   color_if_tty, color_if_tty, color_if_tty
839 };
840 ARGMATCH_VERIFY (color_args, color_types);
841
842 /* Information about filling a column.  */
843 struct column_info
844 {
845   bool valid_len;
846   size_t line_len;
847   size_t *col_arr;
848 };
849
850 /* Array with information about column filledness.  */
851 static struct column_info *column_info;
852
853 /* Maximum number of columns ever possible for this display.  */
854 static size_t max_idx;
855
856 /* The minimum width of a column is 3: 1 character for the name and 2
857    for the separating white space.  */
858 #define MIN_COLUMN_WIDTH        3
859
860
861 /* This zero-based index is used solely with the --dired option.
862    When that option is in effect, this counter is incremented for each
863    byte of output generated by this program so that the beginning
864    and ending indices (in that output) of every file name can be recorded
865    and later output themselves.  */
866 static size_t dired_pos;
867
868 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
869
870 /* Write S to STREAM and increment DIRED_POS by S_LEN.  */
871 #define DIRED_FPUTS(s, stream, s_len) \
872     do {fputs (s, stream); dired_pos += s_len;} while (0)
873
874 /* Like DIRED_FPUTS, but for use when S is a literal string.  */
875 #define DIRED_FPUTS_LITERAL(s, stream) \
876     do {fputs (s, stream); dired_pos += sizeof (s) - 1;} while (0)
877
878 #define DIRED_INDENT()                                                  \
879     do                                                                  \
880       {                                                                 \
881         if (dired)                                                      \
882           DIRED_FPUTS_LITERAL ("  ", stdout);                           \
883       }                                                                 \
884     while (0)
885
886 /* With --dired, store pairs of beginning and ending indices of filenames.  */
887 static struct obstack dired_obstack;
888
889 /* With --dired, store pairs of beginning and ending indices of any
890    directory names that appear as headers (just before `total' line)
891    for lists of directory entries.  Such directory names are seen when
892    listing hierarchies using -R and when a directory is listed with at
893    least one other command line argument.  */
894 static struct obstack subdired_obstack;
895
896 /* Save the current index on the specified obstack, OBS.  */
897 #define PUSH_CURRENT_DIRED_POS(obs)                                     \
898   do                                                                    \
899     {                                                                   \
900       if (dired)                                                        \
901         obstack_grow (obs, &dired_pos, sizeof (dired_pos));             \
902     }                                                                   \
903   while (0)
904
905 /* With -R, this stack is used to help detect directory cycles.
906    The device/inode pairs on this stack mirror the pairs in the
907    active_dir_set hash table.  */
908 static struct obstack dev_ino_obstack;
909
910 /* Push a pair onto the device/inode stack.  */
911 #define DEV_INO_PUSH(Dev, Ino)                                          \
912   do                                                                    \
913     {                                                                   \
914       struct dev_ino *di;                                               \
915       obstack_blank (&dev_ino_obstack, sizeof (struct dev_ino));        \
916       di = -1 + (struct dev_ino *) obstack_next_free (&dev_ino_obstack); \
917       di->st_dev = (Dev);                                               \
918       di->st_ino = (Ino);                                               \
919     }                                                                   \
920   while (0)
921
922 /* Pop a dev/ino struct off the global dev_ino_obstack
923    and return that struct.  */
924 static struct dev_ino
925 dev_ino_pop (void)
926 {
927   assert (sizeof (struct dev_ino) <= obstack_object_size (&dev_ino_obstack));
928   obstack_blank (&dev_ino_obstack, -(int) (sizeof (struct dev_ino)));
929   return *(struct dev_ino *) obstack_next_free (&dev_ino_obstack);
930 }
931
932 #define ASSERT_MATCHING_DEV_INO(Name, Di)       \
933   do                                            \
934     {                                           \
935       struct stat sb;                           \
936       assert (Name);                            \
937       assert (0 <= stat (Name, &sb));           \
938       assert (sb.st_dev == Di.st_dev);          \
939       assert (sb.st_ino == Di.st_ino);          \
940     }                                           \
941   while (0)
942
943
944 /* Write to standard output PREFIX, followed by the quoting style and
945    a space-separated list of the integers stored in OS all on one line.  */
946
947 static void
948 dired_dump_obstack (const char *prefix, struct obstack *os)
949 {
950   size_t n_pos;
951
952   n_pos = obstack_object_size (os) / sizeof (dired_pos);
953   if (n_pos > 0)
954     {
955       size_t i;
956       size_t *pos;
957
958       pos = (size_t *) obstack_finish (os);
959       fputs (prefix, stdout);
960       for (i = 0; i < n_pos; i++)
961         printf (" %lu", (unsigned long int) pos[i]);
962       putchar ('\n');
963     }
964 }
965
966 static size_t
967 dev_ino_hash (void const *x, size_t table_size)
968 {
969   struct dev_ino const *p = x;
970   return (uintmax_t) p->st_ino % table_size;
971 }
972
973 static bool
974 dev_ino_compare (void const *x, void const *y)
975 {
976   struct dev_ino const *a = x;
977   struct dev_ino const *b = y;
978   return SAME_INODE (*a, *b) ? true : false;
979 }
980
981 static void
982 dev_ino_free (void *x)
983 {
984   free (x);
985 }
986
987 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
988    active directories.  Return true if there is already a matching
989    entry in the table.  */
990
991 static bool
992 visit_dir (dev_t dev, ino_t ino)
993 {
994   struct dev_ino *ent;
995   struct dev_ino *ent_from_table;
996   bool found_match;
997
998   ent = xmalloc (sizeof *ent);
999   ent->st_ino = ino;
1000   ent->st_dev = dev;
1001
1002   /* Attempt to insert this entry into the table.  */
1003   ent_from_table = hash_insert (active_dir_set, ent);
1004
1005   if (ent_from_table == NULL)
1006     {
1007       /* Insertion failed due to lack of memory.  */
1008       xalloc_die ();
1009     }
1010
1011   found_match = (ent_from_table != ent);
1012
1013   if (found_match)
1014     {
1015       /* ent was not inserted, so free it.  */
1016       free (ent);
1017     }
1018
1019   return found_match;
1020 }
1021
1022 static void
1023 free_pending_ent (struct pending *p)
1024 {
1025   free (p->name);
1026   free (p->realname);
1027   free (p);
1028 }
1029
1030 static bool
1031 is_colored (enum indicator_no type)
1032 {
1033   size_t len = color_indicator[type].len;
1034   char const *s = color_indicator[type].string;
1035   return ! (len == 0
1036             || (len == 1 && strncmp (s, "0", 1) == 0)
1037             || (len == 2 && strncmp (s, "00", 2) == 0));
1038 }
1039
1040 static void
1041 restore_default_color (void)
1042 {
1043   put_indicator (&color_indicator[C_LEFT]);
1044   put_indicator (&color_indicator[C_RIGHT]);
1045 }
1046
1047 /* An ordinary signal was received; arrange for the program to exit.  */
1048
1049 static void
1050 sighandler (int sig)
1051 {
1052   if (! SA_NOCLDSTOP)
1053     signal (sig, SIG_IGN);
1054   if (! interrupt_signal)
1055     interrupt_signal = sig;
1056 }
1057
1058 /* A SIGTSTP was received; arrange for the program to suspend itself.  */
1059
1060 static void
1061 stophandler (int sig)
1062 {
1063   if (! SA_NOCLDSTOP)
1064     signal (sig, stophandler);
1065   if (! interrupt_signal)
1066     stop_signal_count++;
1067 }
1068
1069 /* Process any pending signals.  If signals are caught, this function
1070    should be called periodically.  Ideally there should never be an
1071    unbounded amount of time when signals are not being processed.
1072    Signal handling can restore the default colors, so callers must
1073    immediately change colors after invoking this function.  */
1074
1075 static void
1076 process_signals (void)
1077 {
1078   while (interrupt_signal | stop_signal_count)
1079     {
1080       int sig;
1081       int stops;
1082       sigset_t oldset;
1083
1084       if (used_color)
1085         restore_default_color ();
1086       fflush (stdout);
1087
1088       sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
1089
1090       /* Reload interrupt_signal and stop_signal_count, in case a new
1091          signal was handled before sigprocmask took effect.  */
1092       sig = interrupt_signal;
1093       stops = stop_signal_count;
1094
1095       /* SIGTSTP is special, since the application can receive that signal
1096          more than once.  In this case, don't set the signal handler to the
1097          default.  Instead, just raise the uncatchable SIGSTOP.  */
1098       if (stops)
1099         {
1100           stop_signal_count = stops - 1;
1101           sig = SIGSTOP;
1102         }
1103       else
1104         signal (sig, SIG_DFL);
1105
1106       /* Exit or suspend the program.  */
1107       raise (sig);
1108       sigprocmask (SIG_SETMASK, &oldset, NULL);
1109
1110       /* If execution reaches here, then the program has been
1111          continued (after being suspended).  */
1112     }
1113 }
1114
1115 int
1116 main (int argc, char **argv)
1117 {
1118   int i;
1119   struct pending *thispend;
1120   int n_files;
1121
1122   /* The signals that are trapped, and the number of such signals.  */
1123   static int const sig[] =
1124     {
1125       /* This one is handled specially.  */
1126       SIGTSTP,
1127
1128       /* The usual suspects.  */
1129       SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM,
1130 #ifdef SIGPOLL
1131       SIGPOLL,
1132 #endif
1133 #ifdef SIGPROF
1134       SIGPROF,
1135 #endif
1136 #ifdef SIGVTALRM
1137       SIGVTALRM,
1138 #endif
1139 #ifdef SIGXCPU
1140       SIGXCPU,
1141 #endif
1142 #ifdef SIGXFSZ
1143       SIGXFSZ,
1144 #endif
1145     };
1146   enum { nsigs = sizeof sig / sizeof sig[0] };
1147
1148 #if ! SA_NOCLDSTOP
1149   bool caught_sig[nsigs];
1150 #endif
1151
1152   initialize_main (&argc, &argv);
1153   set_program_name (argv[0]);
1154   setlocale (LC_ALL, "");
1155   bindtextdomain (PACKAGE, LOCALEDIR);
1156   textdomain (PACKAGE);
1157
1158   initialize_exit_failure (LS_FAILURE);
1159   atexit (close_stdout);
1160
1161 #define N_ENTRIES(Array) (sizeof Array / sizeof *(Array))
1162   assert (N_ENTRIES (color_indicator) + 1 == N_ENTRIES (indicator_name));
1163
1164   exit_status = EXIT_SUCCESS;
1165   print_dir_name = true;
1166   pending_dirs = NULL;
1167
1168   current_time.tv_sec = TYPE_MINIMUM (time_t);
1169   current_time.tv_nsec = -1;
1170
1171   i = decode_switches (argc, argv);
1172
1173   if (print_with_color)
1174     parse_ls_color ();
1175
1176   /* Test print_with_color again, because the call to parse_ls_color
1177      may have just reset it -- e.g., if LS_COLORS is invalid.  */
1178   if (print_with_color)
1179     {
1180       /* Avoid following symbolic links when possible.  */
1181       if (is_colored (C_ORPHAN)
1182           || (is_colored (C_EXEC) && color_symlink_as_referent)
1183           || (is_colored (C_MISSING) && format == long_format))
1184         check_symlink_color = true;
1185
1186       /* If the standard output is a controlling terminal, watch out
1187          for signals, so that the colors can be restored to the
1188          default state if "ls" is suspended or interrupted.  */
1189
1190       if (0 <= tcgetpgrp (STDOUT_FILENO))
1191         {
1192           int j;
1193 #if SA_NOCLDSTOP
1194           struct sigaction act;
1195
1196           sigemptyset (&caught_signals);
1197           for (j = 0; j < nsigs; j++)
1198             {
1199               sigaction (sig[j], NULL, &act);
1200               if (act.sa_handler != SIG_IGN)
1201                 sigaddset (&caught_signals, sig[j]);
1202             }
1203
1204           act.sa_mask = caught_signals;
1205           act.sa_flags = SA_RESTART;
1206
1207           for (j = 0; j < nsigs; j++)
1208             if (sigismember (&caught_signals, sig[j]))
1209               {
1210                 act.sa_handler = sig[j] == SIGTSTP ? stophandler : sighandler;
1211                 sigaction (sig[j], &act, NULL);
1212               }
1213 #else
1214           for (j = 0; j < nsigs; j++)
1215             {
1216               caught_sig[j] = (signal (sig[j], SIG_IGN) != SIG_IGN);
1217               if (caught_sig[j])
1218                 {
1219                   signal (sig[j], sig[j] == SIGTSTP ? stophandler : sighandler);
1220                   siginterrupt (sig[j], 0);
1221                 }
1222             }
1223 #endif
1224         }
1225     }
1226
1227   if (dereference == DEREF_UNDEFINED)
1228     dereference = ((immediate_dirs
1229                     || indicator_style == classify
1230                     || format == long_format)
1231                    ? DEREF_NEVER
1232                    : DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
1233
1234   /* When using -R, initialize a data structure we'll use to
1235      detect any directory cycles.  */
1236   if (recursive)
1237     {
1238       active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, NULL,
1239                                         dev_ino_hash,
1240                                         dev_ino_compare,
1241                                         dev_ino_free);
1242       if (active_dir_set == NULL)
1243         xalloc_die ();
1244
1245       obstack_init (&dev_ino_obstack);
1246     }
1247
1248   format_needs_stat = sort_type == sort_time || sort_type == sort_size
1249     || format == long_format
1250     || print_scontext
1251     || print_block_size;
1252   format_needs_type = (! format_needs_stat
1253                        && (recursive
1254                            || print_with_color
1255                            || indicator_style != none
1256                            || directories_first));
1257
1258   if (dired)
1259     {
1260       obstack_init (&dired_obstack);
1261       obstack_init (&subdired_obstack);
1262     }
1263
1264   cwd_n_alloc = 100;
1265   cwd_file = xnmalloc (cwd_n_alloc, sizeof *cwd_file);
1266   cwd_n_used = 0;
1267
1268   clear_files ();
1269
1270   n_files = argc - i;
1271
1272   if (n_files <= 0)
1273     {
1274       if (immediate_dirs)
1275         gobble_file (".", directory, NOT_AN_INODE_NUMBER, true, "");
1276       else
1277         queue_directory (".", NULL, true);
1278     }
1279   else
1280     do
1281       gobble_file (argv[i++], unknown, NOT_AN_INODE_NUMBER, true, "");
1282     while (i < argc);
1283
1284   if (cwd_n_used)
1285     {
1286       sort_files ();
1287       if (!immediate_dirs)
1288         extract_dirs_from_files (NULL, true);
1289       /* `cwd_n_used' might be zero now.  */
1290     }
1291
1292   /* In the following if/else blocks, it is sufficient to test `pending_dirs'
1293      (and not pending_dirs->name) because there may be no markers in the queue
1294      at this point.  A marker may be enqueued when extract_dirs_from_files is
1295      called with a non-empty string or via print_dir.  */
1296   if (cwd_n_used)
1297     {
1298       print_current_files ();
1299       if (pending_dirs)
1300         DIRED_PUTCHAR ('\n');
1301     }
1302   else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1303     print_dir_name = false;
1304
1305   while (pending_dirs)
1306     {
1307       thispend = pending_dirs;
1308       pending_dirs = pending_dirs->next;
1309
1310       if (LOOP_DETECT)
1311         {
1312           if (thispend->name == NULL)
1313             {
1314               /* thispend->name == NULL means this is a marker entry
1315                  indicating we've finished processing the directory.
1316                  Use its dev/ino numbers to remove the corresponding
1317                  entry from the active_dir_set hash table.  */
1318               struct dev_ino di = dev_ino_pop ();
1319               struct dev_ino *found = hash_delete (active_dir_set, &di);
1320               /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
1321               assert (found);
1322               dev_ino_free (found);
1323               free_pending_ent (thispend);
1324               continue;
1325             }
1326         }
1327
1328       print_dir (thispend->name, thispend->realname,
1329                  thispend->command_line_arg);
1330
1331       free_pending_ent (thispend);
1332       print_dir_name = true;
1333     }
1334
1335   if (print_with_color)
1336     {
1337       int j;
1338
1339       if (used_color)
1340         restore_default_color ();
1341       fflush (stdout);
1342
1343       /* Restore the default signal handling.  */
1344 #if SA_NOCLDSTOP
1345       for (j = 0; j < nsigs; j++)
1346         if (sigismember (&caught_signals, sig[j]))
1347           signal (sig[j], SIG_DFL);
1348 #else
1349       for (j = 0; j < nsigs; j++)
1350         if (caught_sig[j])
1351           signal (sig[j], SIG_DFL);
1352 #endif
1353
1354       /* Act on any signals that arrived before the default was restored.
1355          This can process signals out of order, but there doesn't seem to
1356          be an easy way to do them in order, and the order isn't that
1357          important anyway.  */
1358       for (j = stop_signal_count; j; j--)
1359         raise (SIGSTOP);
1360       j = interrupt_signal;
1361       if (j)
1362         raise (j);
1363     }
1364
1365   if (dired)
1366     {
1367       /* No need to free these since we're about to exit.  */
1368       dired_dump_obstack ("//DIRED//", &dired_obstack);
1369       dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1370       printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1371               quoting_style_args[get_quoting_style (filename_quoting_options)]);
1372     }
1373
1374   if (LOOP_DETECT)
1375     {
1376       assert (hash_get_n_entries (active_dir_set) == 0);
1377       hash_free (active_dir_set);
1378     }
1379
1380   exit (exit_status);
1381 }
1382
1383 /* Set all the option flags according to the switches specified.
1384    Return the index of the first non-option argument.  */
1385
1386 static int
1387 decode_switches (int argc, char **argv)
1388 {
1389   char *time_style_option = NULL;
1390
1391   /* Record whether there is an option specifying sort type.  */
1392   bool sort_type_specified = false;
1393
1394   qmark_funny_chars = false;
1395
1396   /* initialize all switches to default settings */
1397
1398   switch (ls_mode)
1399     {
1400     case LS_MULTI_COL:
1401       /* This is for the `dir' program.  */
1402       format = many_per_line;
1403       set_quoting_style (NULL, escape_quoting_style);
1404       break;
1405
1406     case LS_LONG_FORMAT:
1407       /* This is for the `vdir' program.  */
1408       format = long_format;
1409       set_quoting_style (NULL, escape_quoting_style);
1410       break;
1411
1412     case LS_LS:
1413       /* This is for the `ls' program.  */
1414       if (isatty (STDOUT_FILENO))
1415         {
1416           format = many_per_line;
1417           /* See description of qmark_funny_chars, above.  */
1418           qmark_funny_chars = true;
1419         }
1420       else
1421         {
1422           format = one_per_line;
1423           qmark_funny_chars = false;
1424         }
1425       break;
1426
1427     default:
1428       abort ();
1429     }
1430
1431   time_type = time_mtime;
1432   sort_type = sort_name;
1433   sort_reverse = false;
1434   numeric_ids = false;
1435   print_block_size = false;
1436   indicator_style = none;
1437   print_inode = false;
1438   dereference = DEREF_UNDEFINED;
1439   recursive = false;
1440   immediate_dirs = false;
1441   ignore_mode = IGNORE_DEFAULT;
1442   ignore_patterns = NULL;
1443   hide_patterns = NULL;
1444   print_scontext = false;
1445
1446   /* FIXME: put this in a function.  */
1447   {
1448     char const *q_style = getenv ("QUOTING_STYLE");
1449     if (q_style)
1450       {
1451         int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
1452         if (0 <= i)
1453           set_quoting_style (NULL, quoting_style_vals[i]);
1454         else
1455           error (0, 0,
1456          _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
1457                  quotearg (q_style));
1458       }
1459   }
1460
1461   {
1462     char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
1463     human_options (ls_block_size,
1464                    &human_output_opts, &output_block_size);
1465     if (ls_block_size || getenv ("BLOCK_SIZE"))
1466       file_output_block_size = output_block_size;
1467   }
1468
1469   line_length = 80;
1470   {
1471     char const *p = getenv ("COLUMNS");
1472     if (p && *p)
1473       {
1474         unsigned long int tmp_ulong;
1475         if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1476             && 0 < tmp_ulong && tmp_ulong <= SIZE_MAX)
1477           {
1478             line_length = tmp_ulong;
1479           }
1480         else
1481           {
1482             error (0, 0,
1483                _("ignoring invalid width in environment variable COLUMNS: %s"),
1484                    quotearg (p));
1485           }
1486       }
1487   }
1488
1489 #ifdef TIOCGWINSZ
1490   {
1491     struct winsize ws;
1492
1493     if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1
1494         && 0 < ws.ws_col && ws.ws_col == (size_t) ws.ws_col)
1495       line_length = ws.ws_col;
1496   }
1497 #endif
1498
1499   {
1500     char const *p = getenv ("TABSIZE");
1501     tabsize = 8;
1502     if (p)
1503       {
1504         unsigned long int tmp_ulong;
1505         if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1506             && tmp_ulong <= SIZE_MAX)
1507           {
1508             tabsize = tmp_ulong;
1509           }
1510         else
1511           {
1512             error (0, 0,
1513              _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1514                    quotearg (p));
1515           }
1516       }
1517   }
1518
1519   for (;;)
1520     {
1521       int oi = -1;
1522       int c = getopt_long (argc, argv,
1523                            "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1",
1524                            long_options, &oi);
1525       if (c == -1)
1526         break;
1527
1528       switch (c)
1529         {
1530         case 'a':
1531           ignore_mode = IGNORE_MINIMAL;
1532           break;
1533
1534         case 'b':
1535           set_quoting_style (NULL, escape_quoting_style);
1536           break;
1537
1538         case 'c':
1539           time_type = time_ctime;
1540           break;
1541
1542         case 'd':
1543           immediate_dirs = true;
1544           break;
1545
1546         case 'f':
1547           /* Same as enabling -a -U and disabling -l -s.  */
1548           ignore_mode = IGNORE_MINIMAL;
1549           sort_type = sort_none;
1550           sort_type_specified = true;
1551           /* disable -l */
1552           if (format == long_format)
1553             format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
1554           print_block_size = false;     /* disable -s */
1555           print_with_color = false;     /* disable --color */
1556           break;
1557
1558         case FILE_TYPE_INDICATOR_OPTION: /* --file-type */
1559           indicator_style = file_type;
1560           break;
1561
1562         case 'g':
1563           format = long_format;
1564           print_owner = false;
1565           break;
1566
1567         case 'h':
1568           human_output_opts = human_autoscale | human_SI | human_base_1024;
1569           file_output_block_size = output_block_size = 1;
1570           break;
1571
1572         case 'i':
1573           print_inode = true;
1574           break;
1575
1576         case 'k':
1577           human_output_opts = 0;
1578           file_output_block_size = output_block_size = 1024;
1579           break;
1580
1581         case 'l':
1582           format = long_format;
1583           break;
1584
1585         case 'm':
1586           format = with_commas;
1587           break;
1588
1589         case 'n':
1590           numeric_ids = true;
1591           format = long_format;
1592           break;
1593
1594         case 'o':  /* Just like -l, but don't display group info.  */
1595           format = long_format;
1596           print_group = false;
1597           break;
1598
1599         case 'p':
1600           indicator_style = slash;
1601           break;
1602
1603         case 'q':
1604           qmark_funny_chars = true;
1605           break;
1606
1607         case 'r':
1608           sort_reverse = true;
1609           break;
1610
1611         case 's':
1612           print_block_size = true;
1613           break;
1614
1615         case 't':
1616           sort_type = sort_time;
1617           sort_type_specified = true;
1618           break;
1619
1620         case 'u':
1621           time_type = time_atime;
1622           break;
1623
1624         case 'v':
1625           sort_type = sort_version;
1626           sort_type_specified = true;
1627           break;
1628
1629         case 'w':
1630           {
1631             unsigned long int tmp_ulong;
1632             if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1633                 || ! (0 < tmp_ulong && tmp_ulong <= SIZE_MAX))
1634               error (LS_FAILURE, 0, _("invalid line width: %s"),
1635                      quotearg (optarg));
1636             line_length = tmp_ulong;
1637             break;
1638           }
1639
1640         case 'x':
1641           format = horizontal;
1642           break;
1643
1644         case 'A':
1645           if (ignore_mode == IGNORE_DEFAULT)
1646             ignore_mode = IGNORE_DOT_AND_DOTDOT;
1647           break;
1648
1649         case 'B':
1650           add_ignore_pattern ("*~");
1651           add_ignore_pattern (".*~");
1652           break;
1653
1654         case 'C':
1655           format = many_per_line;
1656           break;
1657
1658         case 'D':
1659           dired = true;
1660           break;
1661
1662         case 'F':
1663           indicator_style = classify;
1664           break;
1665
1666         case 'G':               /* inhibit display of group info */
1667           print_group = false;
1668           break;
1669
1670         case 'H':
1671           dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1672           break;
1673
1674         case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
1675           dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
1676           break;
1677
1678         case 'I':
1679           add_ignore_pattern (optarg);
1680           break;
1681
1682         case 'L':
1683           dereference = DEREF_ALWAYS;
1684           break;
1685
1686         case 'N':
1687           set_quoting_style (NULL, literal_quoting_style);
1688           break;
1689
1690         case 'Q':
1691           set_quoting_style (NULL, c_quoting_style);
1692           break;
1693
1694         case 'R':
1695           recursive = true;
1696           break;
1697
1698         case 'S':
1699           sort_type = sort_size;
1700           sort_type_specified = true;
1701           break;
1702
1703         case 'T':
1704           {
1705             unsigned long int tmp_ulong;
1706             if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1707                 || SIZE_MAX < tmp_ulong)
1708               error (LS_FAILURE, 0, _("invalid tab size: %s"),
1709                      quotearg (optarg));
1710             tabsize = tmp_ulong;
1711             break;
1712           }
1713
1714         case 'U':
1715           sort_type = sort_none;
1716           sort_type_specified = true;
1717           break;
1718
1719         case 'X':
1720           sort_type = sort_extension;
1721           sort_type_specified = true;
1722           break;
1723
1724         case '1':
1725           /* -1 has no effect after -l.  */
1726           if (format != long_format)
1727             format = one_per_line;
1728           break;
1729
1730         case AUTHOR_OPTION:
1731           print_author = true;
1732           break;
1733
1734         case HIDE_OPTION:
1735           {
1736             struct ignore_pattern *hide = xmalloc (sizeof *hide);
1737             hide->pattern = optarg;
1738             hide->next = hide_patterns;
1739             hide_patterns = hide;
1740           }
1741           break;
1742
1743         case SORT_OPTION:
1744           sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1745           sort_type_specified = true;
1746           break;
1747
1748         case GROUP_DIRECTORIES_FIRST_OPTION:
1749           directories_first = true;
1750           break;
1751
1752         case TIME_OPTION:
1753           time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1754           break;
1755
1756         case FORMAT_OPTION:
1757           format = XARGMATCH ("--format", optarg, format_args, format_types);
1758           break;
1759
1760         case FULL_TIME_OPTION:
1761           format = long_format;
1762           time_style_option = "full-iso";
1763           break;
1764
1765         case COLOR_OPTION:
1766           {
1767             int i;
1768             if (optarg)
1769               i = XARGMATCH ("--color", optarg, color_args, color_types);
1770             else
1771               /* Using --color with no argument is equivalent to using
1772                  --color=always.  */
1773               i = color_always;
1774
1775             print_with_color = (i == color_always
1776                                 || (i == color_if_tty
1777                                     && isatty (STDOUT_FILENO)));
1778
1779             if (print_with_color)
1780               {
1781                 /* Don't use TAB characters in output.  Some terminal
1782                    emulators can't handle the combination of tabs and
1783                    color codes on the same line.  */
1784                 tabsize = 0;
1785               }
1786             break;
1787           }
1788
1789         case INDICATOR_STYLE_OPTION:
1790           indicator_style = XARGMATCH ("--indicator-style", optarg,
1791                                        indicator_style_args,
1792                                        indicator_style_types);
1793           break;
1794
1795         case QUOTING_STYLE_OPTION:
1796           set_quoting_style (NULL,
1797                              XARGMATCH ("--quoting-style", optarg,
1798                                         quoting_style_args,
1799                                         quoting_style_vals));
1800           break;
1801
1802         case TIME_STYLE_OPTION:
1803           time_style_option = optarg;
1804           break;
1805
1806         case SHOW_CONTROL_CHARS_OPTION:
1807           qmark_funny_chars = false;
1808           break;
1809
1810         case BLOCK_SIZE_OPTION:
1811           {
1812             enum strtol_error e = human_options (optarg, &human_output_opts,
1813                                                  &output_block_size);
1814             if (e != LONGINT_OK)
1815               xstrtol_fatal (e, oi, 0, long_options, optarg);
1816             file_output_block_size = output_block_size;
1817           }
1818           break;
1819
1820         case SI_OPTION:
1821           human_output_opts = human_autoscale | human_SI;
1822           file_output_block_size = output_block_size = 1;
1823           break;
1824
1825         case 'Z':
1826           print_scontext = true;
1827           break;
1828
1829         case_GETOPT_HELP_CHAR;
1830
1831         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1832
1833         default:
1834           usage (LS_FAILURE);
1835         }
1836     }
1837
1838   max_idx = MAX (1, line_length / MIN_COLUMN_WIDTH);
1839
1840   filename_quoting_options = clone_quoting_options (NULL);
1841   if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1842     set_char_quoting (filename_quoting_options, ' ', 1);
1843   if (file_type <= indicator_style)
1844     {
1845       char const *p;
1846       for (p = "*=>@|" + indicator_style - file_type; *p; p++)
1847         set_char_quoting (filename_quoting_options, *p, 1);
1848     }
1849
1850   dirname_quoting_options = clone_quoting_options (NULL);
1851   set_char_quoting (dirname_quoting_options, ':', 1);
1852
1853   /* --dired is meaningful only with --format=long (-l).
1854      Otherwise, ignore it.  FIXME: warn about this?
1855      Alternatively, make --dired imply --format=long?  */
1856   if (dired && format != long_format)
1857     dired = false;
1858
1859   /* If -c or -u is specified and not -l (or any other option that implies -l),
1860      and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
1861      The behavior of ls when using either -c or -u but with neither -l nor -t
1862      appears to be unspecified by POSIX.  So, with GNU ls, `-u' alone means
1863      sort by atime (this is the one that's not specified by the POSIX spec),
1864      -lu means show atime and sort by name, -lut means show atime and sort
1865      by atime.  */
1866
1867   if ((time_type == time_ctime || time_type == time_atime)
1868       && !sort_type_specified && format != long_format)
1869     {
1870       sort_type = sort_time;
1871     }
1872
1873   if (format == long_format)
1874     {
1875       char *style = time_style_option;
1876       static char const posix_prefix[] = "posix-";
1877
1878       if (! style)
1879         if (! (style = getenv ("TIME_STYLE")))
1880           style = "locale";
1881
1882       while (strncmp (style, posix_prefix, sizeof posix_prefix - 1) == 0)
1883         {
1884           if (! hard_locale (LC_TIME))
1885             return optind;
1886           style += sizeof posix_prefix - 1;
1887         }
1888
1889       if (*style == '+')
1890         {
1891           char *p0 = style + 1;
1892           char *p1 = strchr (p0, '\n');
1893           if (! p1)
1894             p1 = p0;
1895           else
1896             {
1897               if (strchr (p1 + 1, '\n'))
1898                 error (LS_FAILURE, 0, _("invalid time style format %s"),
1899                        quote (p0));
1900               *p1++ = '\0';
1901             }
1902           long_time_format[0] = p0;
1903           long_time_format[1] = p1;
1904         }
1905       else
1906         switch (XARGMATCH ("time style", style,
1907                            time_style_args,
1908                            time_style_types))
1909           {
1910           case full_iso_time_style:
1911             long_time_format[0] = long_time_format[1] =
1912               "%Y-%m-%d %H:%M:%S.%N %z";
1913             break;
1914
1915           case long_iso_time_style:
1916           case_long_iso_time_style:
1917             long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
1918             break;
1919
1920           case iso_time_style:
1921             long_time_format[0] = "%Y-%m-%d ";
1922             long_time_format[1] = "%m-%d %H:%M";
1923             break;
1924
1925           case locale_time_style:
1926             if (hard_locale (LC_TIME))
1927               {
1928                 /* Ensure that the locale has translations for both
1929                    formats.  If not, fall back on long-iso format.  */
1930                 int i;
1931                 for (i = 0; i < 2; i++)
1932                   {
1933                     char const *locale_format =
1934                       dcgettext (NULL, long_time_format[i], LC_TIME);
1935                     if (locale_format == long_time_format[i])
1936                       goto case_long_iso_time_style;
1937                     long_time_format[i] = locale_format;
1938                   }
1939               }
1940           }
1941     }
1942
1943   return optind;
1944 }
1945
1946 /* Parse a string as part of the LS_COLORS variable; this may involve
1947    decoding all kinds of escape characters.  If equals_end is set an
1948    unescaped equal sign ends the string, otherwise only a : or \0
1949    does.  Set *OUTPUT_COUNT to the number of bytes output.  Return
1950    true if successful.
1951
1952    The resulting string is *not* null-terminated, but may contain
1953    embedded nulls.
1954
1955    Note that both dest and src are char **; on return they point to
1956    the first free byte after the array and the character that ended
1957    the input string, respectively.  */
1958
1959 static bool
1960 get_funky_string (char **dest, const char **src, bool equals_end,
1961                   size_t *output_count)
1962 {
1963   char num;                     /* For numerical codes */
1964   size_t count;                 /* Something to count with */
1965   enum {
1966     ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
1967   } state;
1968   const char *p;
1969   char *q;
1970
1971   p = *src;                     /* We don't want to double-indirect */
1972   q = *dest;                    /* the whole darn time.  */
1973
1974   count = 0;                    /* No characters counted in yet.  */
1975   num = 0;
1976
1977   state = ST_GND;               /* Start in ground state.  */
1978   while (state < ST_END)
1979     {
1980       switch (state)
1981         {
1982         case ST_GND:            /* Ground state (no escapes) */
1983           switch (*p)
1984             {
1985             case ':':
1986             case '\0':
1987               state = ST_END;   /* End of string */
1988               break;
1989             case '\\':
1990               state = ST_BACKSLASH; /* Backslash scape sequence */
1991               ++p;
1992               break;
1993             case '^':
1994               state = ST_CARET; /* Caret escape */
1995               ++p;
1996               break;
1997             case '=':
1998               if (equals_end)
1999                 {
2000                   state = ST_END; /* End */
2001                   break;
2002                 }
2003               /* else fall through */
2004             default:
2005               *(q++) = *(p++);
2006               ++count;
2007               break;
2008             }
2009           break;
2010
2011         case ST_BACKSLASH:      /* Backslash escaped character */
2012           switch (*p)
2013             {
2014             case '0':
2015             case '1':
2016             case '2':
2017             case '3':
2018             case '4':
2019             case '5':
2020             case '6':
2021             case '7':
2022               state = ST_OCTAL; /* Octal sequence */
2023               num = *p - '0';
2024               break;
2025             case 'x':
2026             case 'X':
2027               state = ST_HEX;   /* Hex sequence */
2028               num = 0;
2029               break;
2030             case 'a':           /* Bell */
2031               num = '\a';
2032               break;
2033             case 'b':           /* Backspace */
2034               num = '\b';
2035               break;
2036             case 'e':           /* Escape */
2037               num = 27;
2038               break;
2039             case 'f':           /* Form feed */
2040               num = '\f';
2041               break;
2042             case 'n':           /* Newline */
2043               num = '\n';
2044               break;
2045             case 'r':           /* Carriage return */
2046               num = '\r';
2047               break;
2048             case 't':           /* Tab */
2049               num = '\t';
2050               break;
2051             case 'v':           /* Vtab */
2052               num = '\v';
2053               break;
2054             case '?':           /* Delete */
2055               num = 127;
2056               break;
2057             case '_':           /* Space */
2058               num = ' ';
2059               break;
2060             case '\0':          /* End of string */
2061               state = ST_ERROR; /* Error! */
2062               break;
2063             default:            /* Escaped character like \ ^ : = */
2064               num = *p;
2065               break;
2066             }
2067           if (state == ST_BACKSLASH)
2068             {
2069               *(q++) = num;
2070               ++count;
2071               state = ST_GND;
2072             }
2073           ++p;
2074           break;
2075
2076         case ST_OCTAL:          /* Octal sequence */
2077           if (*p < '0' || *p > '7')
2078             {
2079               *(q++) = num;
2080               ++count;
2081               state = ST_GND;
2082             }
2083           else
2084             num = (num << 3) + (*(p++) - '0');
2085           break;
2086
2087         case ST_HEX:            /* Hex sequence */
2088           switch (*p)
2089             {
2090             case '0':
2091             case '1':
2092             case '2':
2093             case '3':
2094             case '4':
2095             case '5':
2096             case '6':
2097             case '7':
2098             case '8':
2099             case '9':
2100               num = (num << 4) + (*(p++) - '0');
2101               break;
2102             case 'a':
2103             case 'b':
2104             case 'c':
2105             case 'd':
2106             case 'e':
2107             case 'f':
2108               num = (num << 4) + (*(p++) - 'a') + 10;
2109               break;
2110             case 'A':
2111             case 'B':
2112             case 'C':
2113             case 'D':
2114             case 'E':
2115             case 'F':
2116               num = (num << 4) + (*(p++) - 'A') + 10;
2117               break;
2118             default:
2119               *(q++) = num;
2120               ++count;
2121               state = ST_GND;
2122               break;
2123             }
2124           break;
2125
2126         case ST_CARET:          /* Caret escape */
2127           state = ST_GND;       /* Should be the next state... */
2128           if (*p >= '@' && *p <= '~')
2129             {
2130               *(q++) = *(p++) & 037;
2131               ++count;
2132             }
2133           else if (*p == '?')
2134             {
2135               *(q++) = 127;
2136               ++count;
2137             }
2138           else
2139             state = ST_ERROR;
2140           break;
2141
2142         default:
2143           abort ();
2144         }
2145     }
2146
2147   *dest = q;
2148   *src = p;
2149   *output_count = count;
2150
2151   return state != ST_ERROR;
2152 }
2153
2154 static void
2155 parse_ls_color (void)
2156 {
2157   const char *p;                /* Pointer to character being parsed */
2158   char *buf;                    /* color_buf buffer pointer */
2159   int state;                    /* State of parser */
2160   int ind_no;                   /* Indicator number */
2161   char label[3];                /* Indicator label */
2162   struct color_ext_type *ext;   /* Extension we are working on */
2163
2164   if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
2165     return;
2166
2167   ext = NULL;
2168   strcpy (label, "??");
2169
2170   /* This is an overly conservative estimate, but any possible
2171      LS_COLORS string will *not* generate a color_buf longer than
2172      itself, so it is a safe way of allocating a buffer in
2173      advance.  */
2174   buf = color_buf = xstrdup (p);
2175
2176   state = 1;
2177   while (state > 0)
2178     {
2179       switch (state)
2180         {
2181         case 1:         /* First label character */
2182           switch (*p)
2183             {
2184             case ':':
2185               ++p;
2186               break;
2187
2188             case '*':
2189               /* Allocate new extension block and add to head of
2190                  linked list (this way a later definition will
2191                  override an earlier one, which can be useful for
2192                  having terminal-specific defs override global).  */
2193
2194               ext = xmalloc (sizeof *ext);
2195               ext->next = color_ext_list;
2196               color_ext_list = ext;
2197
2198               ++p;
2199               ext->ext.string = buf;
2200
2201               state = (get_funky_string (&buf, &p, true, &ext->ext.len)
2202                        ? 4 : -1);
2203               break;
2204
2205             case '\0':
2206               state = 0;        /* Done! */
2207               break;
2208
2209             default:    /* Assume it is file type label */
2210               label[0] = *(p++);
2211               state = 2;
2212               break;
2213             }
2214           break;
2215
2216         case 2:         /* Second label character */
2217           if (*p)
2218             {
2219               label[1] = *(p++);
2220               state = 3;
2221             }
2222           else
2223             state = -1; /* Error */
2224           break;
2225
2226         case 3:         /* Equal sign after indicator label */
2227           state = -1;   /* Assume failure...  */
2228           if (*(p++) == '=')/* It *should* be...  */
2229             {
2230               for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
2231                 {
2232                   if (STREQ (label, indicator_name[ind_no]))
2233                     {
2234                       color_indicator[ind_no].string = buf;
2235                       state = (get_funky_string (&buf, &p, false,
2236                                                  &color_indicator[ind_no].len)
2237                                ? 1 : -1);
2238                       break;
2239                     }
2240                 }
2241               if (state == -1)
2242                 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
2243             }
2244           break;
2245
2246         case 4:         /* Equal sign after *.ext */
2247           if (*(p++) == '=')
2248             {
2249               ext->seq.string = buf;
2250               state = (get_funky_string (&buf, &p, false, &ext->seq.len)
2251                        ? 1 : -1);
2252             }
2253           else
2254             state = -1;
2255           break;
2256         }
2257     }
2258
2259   if (state < 0)
2260     {
2261       struct color_ext_type *e;
2262       struct color_ext_type *e2;
2263
2264       error (0, 0,
2265              _("unparsable value for LS_COLORS environment variable"));
2266       free (color_buf);
2267       for (e = color_ext_list; e != NULL; /* empty */)
2268         {
2269           e2 = e;
2270           e = e->next;
2271           free (e2);
2272         }
2273       print_with_color = false;
2274     }
2275
2276   if (color_indicator[C_LINK].len == 6
2277       && !strncmp (color_indicator[C_LINK].string, "target", 6))
2278     color_symlink_as_referent = true;
2279 }
2280
2281 /* Set the exit status to report a failure.  If SERIOUS, it is a
2282    serious failure; otherwise, it is merely a minor problem.  */
2283
2284 static void
2285 set_exit_status (bool serious)
2286 {
2287   if (serious)
2288     exit_status = LS_FAILURE;
2289   else if (exit_status == EXIT_SUCCESS)
2290     exit_status = LS_MINOR_PROBLEM;
2291 }
2292
2293 /* Assuming a failure is serious if SERIOUS, use the printf-style
2294    MESSAGE to report the failure to access a file named FILE.  Assume
2295    errno is set appropriately for the failure.  */
2296
2297 static void
2298 file_failure (bool serious, char const *message, char const *file)
2299 {
2300   error (0, errno, message, quotearg_colon (file));
2301   set_exit_status (serious);
2302 }
2303
2304 /* Request that the directory named NAME have its contents listed later.
2305    If REALNAME is nonzero, it will be used instead of NAME when the
2306    directory name is printed.  This allows symbolic links to directories
2307    to be treated as regular directories but still be listed under their
2308    real names.  NAME == NULL is used to insert a marker entry for the
2309    directory named in REALNAME.
2310    If NAME is non-NULL, we use its dev/ino information to save
2311    a call to stat -- when doing a recursive (-R) traversal.
2312    COMMAND_LINE_ARG means this directory was mentioned on the command line.  */
2313
2314 static void
2315 queue_directory (char const *name, char const *realname, bool command_line_arg)
2316 {
2317   struct pending *new = xmalloc (sizeof *new);
2318   new->realname = realname ? xstrdup (realname) : NULL;
2319   new->name = name ? xstrdup (name) : NULL;
2320   new->command_line_arg = command_line_arg;
2321   new->next = pending_dirs;
2322   pending_dirs = new;
2323 }
2324
2325 /* Read directory NAME, and list the files in it.
2326    If REALNAME is nonzero, print its name instead of NAME;
2327    this is used for symbolic links to directories.
2328    COMMAND_LINE_ARG means this directory was mentioned on the command line.  */
2329
2330 static void
2331 print_dir (char const *name, char const *realname, bool command_line_arg)
2332 {
2333   DIR *dirp;
2334   struct dirent *next;
2335   uintmax_t total_blocks = 0;
2336   static bool first = true;
2337
2338   errno = 0;
2339   dirp = opendir (name);
2340   if (!dirp)
2341     {
2342       file_failure (command_line_arg, _("cannot open directory %s"), name);
2343       return;
2344     }
2345
2346   if (LOOP_DETECT)
2347     {
2348       struct stat dir_stat;
2349       int fd = dirfd (dirp);
2350
2351       /* If dirfd failed, endure the overhead of using stat.  */
2352       if ((0 <= fd
2353            ? fstat (fd, &dir_stat)
2354            : stat (name, &dir_stat)) < 0)
2355         {
2356           file_failure (command_line_arg,
2357                         _("cannot determine device and inode of %s"), name);
2358           closedir (dirp);
2359           return;
2360         }
2361
2362       /* If we've already visited this dev/inode pair, warn that
2363          we've found a loop, and do not process this directory.  */
2364       if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
2365         {
2366           error (0, 0, _("%s: not listing already-listed directory"),
2367                  quotearg_colon (name));
2368           closedir (dirp);
2369           return;
2370         }
2371
2372       DEV_INO_PUSH (dir_stat.st_dev, dir_stat.st_ino);
2373     }
2374
2375   /* Read the directory entries, and insert the subfiles into the `cwd_file'
2376      table.  */
2377
2378   clear_files ();
2379
2380   while (1)
2381     {
2382       /* Set errno to zero so we can distinguish between a readdir failure
2383          and when readdir simply finds that there are no more entries.  */
2384       errno = 0;
2385       next = readdir (dirp);
2386       if (next)
2387         {
2388           if (! file_ignored (next->d_name))
2389             {
2390               enum filetype type = unknown;
2391
2392 #if HAVE_STRUCT_DIRENT_D_TYPE
2393               switch (next->d_type)
2394                 {
2395                 case DT_BLK:  type = blockdev;          break;
2396                 case DT_CHR:  type = chardev;           break;
2397                 case DT_DIR:  type = directory;         break;
2398                 case DT_FIFO: type = fifo;              break;
2399                 case DT_LNK:  type = symbolic_link;     break;
2400                 case DT_REG:  type = normal;            break;
2401                 case DT_SOCK: type = sock;              break;
2402 # ifdef DT_WHT
2403                 case DT_WHT:  type = whiteout;          break;
2404 # endif
2405                 }
2406 #endif
2407               total_blocks += gobble_file (next->d_name, type, D_INO (next),
2408                                            false, name);
2409
2410               /* In this narrow case, print out each name right away, so
2411                  ls uses constant memory while processing the entries of
2412                  this directory.  Useful when there are many (millions)
2413                  of entries in a directory.  */
2414               if (format == one_per_line && sort_type == sort_none)
2415                 {
2416                   /* We must call sort_files in spite of
2417                      "sort_type == sort_none" for its initialization
2418                      of the sorted_file vector.  */
2419                   sort_files ();
2420                   print_current_files ();
2421                   clear_files ();
2422                 }
2423             }
2424         }
2425       else if (errno != 0)
2426         {
2427           file_failure (command_line_arg, _("reading directory %s"), name);
2428           if (errno != EOVERFLOW)
2429             break;
2430         }
2431       else
2432         break;
2433     }
2434
2435   if (closedir (dirp) != 0)
2436     {
2437       file_failure (command_line_arg, _("closing directory %s"), name);
2438       /* Don't return; print whatever we got.  */
2439     }
2440
2441   /* Sort the directory contents.  */
2442   sort_files ();
2443
2444   /* If any member files are subdirectories, perhaps they should have their
2445      contents listed rather than being mentioned here as files.  */
2446
2447   if (recursive)
2448     extract_dirs_from_files (name, command_line_arg);
2449
2450   if (recursive | print_dir_name)
2451     {
2452       if (!first)
2453         DIRED_PUTCHAR ('\n');
2454       first = false;
2455       DIRED_INDENT ();
2456       PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2457       dired_pos += quote_name (stdout, realname ? realname : name,
2458                                dirname_quoting_options, NULL);
2459       PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2460       DIRED_FPUTS_LITERAL (":\n", stdout);
2461     }
2462
2463   if (format == long_format || print_block_size)
2464     {
2465       const char *p;
2466       char buf[LONGEST_HUMAN_READABLE + 1];
2467
2468       DIRED_INDENT ();
2469       p = _("total");
2470       DIRED_FPUTS (p, stdout, strlen (p));
2471       DIRED_PUTCHAR (' ');
2472       p = human_readable (total_blocks, buf, human_output_opts,
2473                           ST_NBLOCKSIZE, output_block_size);
2474       DIRED_FPUTS (p, stdout, strlen (p));
2475       DIRED_PUTCHAR ('\n');
2476     }
2477
2478   if (cwd_n_used)
2479     print_current_files ();
2480 }
2481
2482 /* Add `pattern' to the list of patterns for which files that match are
2483    not listed.  */
2484
2485 static void
2486 add_ignore_pattern (const char *pattern)
2487 {
2488   struct ignore_pattern *ignore;
2489
2490   ignore = xmalloc (sizeof *ignore);
2491   ignore->pattern = pattern;
2492   /* Add it to the head of the linked list.  */
2493   ignore->next = ignore_patterns;
2494   ignore_patterns = ignore;
2495 }
2496
2497 /* Return true if one of the PATTERNS matches FILE.  */
2498
2499 static bool
2500 patterns_match (struct ignore_pattern const *patterns, char const *file)
2501 {
2502   struct ignore_pattern const *p;
2503   for (p = patterns; p; p = p->next)
2504     if (fnmatch (p->pattern, file, FNM_PERIOD) == 0)
2505       return true;
2506   return false;
2507 }
2508
2509 /* Return true if FILE should be ignored.  */
2510
2511 static bool
2512 file_ignored (char const *name)
2513 {
2514   return ((ignore_mode != IGNORE_MINIMAL
2515            && name[0] == '.'
2516            && (ignore_mode == IGNORE_DEFAULT || ! name[1 + (name[1] == '.')]))
2517           || (ignore_mode == IGNORE_DEFAULT
2518               && patterns_match (hide_patterns, name))
2519           || patterns_match (ignore_patterns, name));
2520 }
2521
2522 /* POSIX requires that a file size be printed without a sign, even
2523    when negative.  Assume the typical case where negative sizes are
2524    actually positive values that have wrapped around.  */
2525
2526 static uintmax_t
2527 unsigned_file_size (off_t size)
2528 {
2529   return size + (size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
2530 }
2531
2532 /* Enter and remove entries in the table `cwd_file'.  */
2533
2534 /* Empty the table of files.  */
2535
2536 static void
2537 clear_files (void)
2538 {
2539   size_t i;
2540
2541   for (i = 0; i < cwd_n_used; i++)
2542     {
2543       struct fileinfo *f = sorted_file[i];
2544       free (f->name);
2545       free (f->linkname);
2546       if (f->scontext != UNKNOWN_SECURITY_CONTEXT)
2547         freecon (f->scontext);
2548     }
2549
2550   cwd_n_used = 0;
2551   any_has_acl = false;
2552   inode_number_width = 0;
2553   block_size_width = 0;
2554   nlink_width = 0;
2555   owner_width = 0;
2556   group_width = 0;
2557   author_width = 0;
2558   scontext_width = 0;
2559   major_device_number_width = 0;
2560   minor_device_number_width = 0;
2561   file_size_width = 0;
2562 }
2563
2564 /* Add a file to the current table of files.
2565    Verify that the file exists, and print an error message if it does not.
2566    Return the number of blocks that the file occupies.  */
2567
2568 static uintmax_t
2569 gobble_file (char const *name, enum filetype type, ino_t inode,
2570              bool command_line_arg, char const *dirname)
2571 {
2572   uintmax_t blocks = 0;
2573   struct fileinfo *f;
2574
2575   /* An inode value prior to gobble_file necessarily came from readdir,
2576      which is not used for command line arguments.  */
2577   assert (! command_line_arg || inode == NOT_AN_INODE_NUMBER);
2578
2579   if (cwd_n_used == cwd_n_alloc)
2580     {
2581       cwd_file = xnrealloc (cwd_file, cwd_n_alloc, 2 * sizeof *cwd_file);
2582       cwd_n_alloc *= 2;
2583     }
2584
2585   f = &cwd_file[cwd_n_used];
2586   memset (f, '\0', sizeof *f);
2587   f->stat.st_ino = inode;
2588   f->filetype = type;
2589
2590   if (command_line_arg
2591       || format_needs_stat
2592       /* When coloring a directory (we may know the type from
2593          direct.d_type), we have to stat it in order to indicate
2594          sticky and/or other-writable attributes.  */
2595       || (type == directory && print_with_color)
2596       /* When dereferencing symlinks, the inode and type must come from
2597          stat, but readdir provides the inode and type of lstat.  */
2598       || ((print_inode || format_needs_type)
2599           && (type == symbolic_link || type == unknown)
2600           && (dereference == DEREF_ALWAYS
2601               || (command_line_arg && dereference != DEREF_NEVER)
2602               || color_symlink_as_referent || check_symlink_color))
2603       /* Command line dereferences are already taken care of by the above
2604          assertion that the inode number is not yet known.  */
2605       || (print_inode && inode == NOT_AN_INODE_NUMBER)
2606       || (format_needs_type
2607           && (type == unknown || command_line_arg
2608               /* --indicator-style=classify (aka -F)
2609                  requires that we stat each regular file
2610                  to see if it's executable.  */
2611               || (type == normal && (indicator_style == classify
2612                                      /* This is so that --color ends up
2613                                         highlighting files with the executable
2614                                         bit set even when options like -F are
2615                                         not specified.  */
2616                                      || (print_with_color
2617                                          && is_colored (C_EXEC))
2618                                      )))))
2619
2620     {
2621       /* Absolute name of this file.  */
2622       char *absolute_name;
2623       bool do_deref;
2624       int err;
2625
2626       if (name[0] == '/' || dirname[0] == 0)
2627         absolute_name = (char *) name;
2628       else
2629         {
2630           absolute_name = alloca (strlen (name) + strlen (dirname) + 2);
2631           attach (absolute_name, dirname, name);
2632         }
2633
2634       switch (dereference)
2635         {
2636         case DEREF_ALWAYS:
2637           err = stat (absolute_name, &f->stat);
2638           do_deref = true;
2639           break;
2640
2641         case DEREF_COMMAND_LINE_ARGUMENTS:
2642         case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
2643           if (command_line_arg)
2644             {
2645               bool need_lstat;
2646               err = stat (absolute_name, &f->stat);
2647               do_deref = true;
2648
2649               if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2650                 break;
2651
2652               need_lstat = (err < 0
2653                             ? errno == ENOENT
2654                             : ! S_ISDIR (f->stat.st_mode));
2655               if (!need_lstat)
2656                 break;
2657
2658               /* stat failed because of ENOENT, maybe indicating a dangling
2659                  symlink.  Or stat succeeded, ABSOLUTE_NAME does not refer to a
2660                  directory, and --dereference-command-line-symlink-to-dir is
2661                  in effect.  Fall through so that we call lstat instead.  */
2662             }
2663
2664         default: /* DEREF_NEVER */
2665           err = lstat (absolute_name, &f->stat);
2666           do_deref = false;
2667           break;
2668         }
2669
2670       if (err != 0)
2671         {
2672           /* Failure to stat a command line argument leads to
2673              an exit status of 2.  For other files, stat failure
2674              provokes an exit status of 1.  */
2675           file_failure (command_line_arg,
2676                         _("cannot access %s"), absolute_name);
2677           if (command_line_arg)
2678             return 0;
2679
2680           f->name = xstrdup (name);
2681           cwd_n_used++;
2682
2683           return 0;
2684         }
2685
2686       f->stat_ok = true;
2687
2688       if (format == long_format || print_scontext)
2689         {
2690           bool have_acl = false;
2691           int attr_len = (do_deref
2692                           ?  getfilecon (absolute_name, &f->scontext)
2693                           : lgetfilecon (absolute_name, &f->scontext));
2694           err = (attr_len < 0);
2695
2696           /* Contrary to its documented API, getfilecon may return 0,
2697              yet set f->scontext to NULL (on at least Debian's libselinux1
2698              2.0.15-2+b1), so work around that bug.
2699              FIXME: remove this work-around in 2011, or whenever affected
2700              versions of libselinux are long gone.  */
2701           if (attr_len == 0)
2702             {
2703               err = 0;
2704               f->scontext = xstrdup ("unlabeled");
2705             }
2706
2707           if (err == 0)
2708             have_acl = ! STREQ ("unlabeled", f->scontext);
2709           else
2710             {
2711               f->scontext = UNKNOWN_SECURITY_CONTEXT;
2712
2713               /* When requesting security context information, don't make
2714                  ls fail just because the file (even a command line argument)
2715                  isn't on the right type of file system.  I.e., a getfilecon
2716                  failure isn't in the same class as a stat failure.  */
2717               if (errno == ENOTSUP || errno == EOPNOTSUPP || errno == ENODATA)
2718                 err = 0;
2719             }
2720
2721           if (err == 0 && ! have_acl && format == long_format)
2722             {
2723               int n = file_has_acl (absolute_name, &f->stat);
2724               err = (n < 0);
2725               have_acl = (0 < n);
2726             }
2727
2728           f->have_acl = have_acl;
2729           any_has_acl |= have_acl;
2730
2731           if (err)
2732             error (0, errno, "%s", quotearg_colon (absolute_name));
2733         }
2734
2735       if (S_ISLNK (f->stat.st_mode)
2736           && (format == long_format || check_symlink_color))
2737         {
2738           char *linkname;
2739           struct stat linkstats;
2740
2741           get_link_name (absolute_name, f, command_line_arg);
2742           linkname = make_link_name (absolute_name, f->linkname);
2743
2744           /* Avoid following symbolic links when possible, ie, when
2745              they won't be traced and when no indicator is needed.  */
2746           if (linkname
2747               && (file_type <= indicator_style || check_symlink_color)
2748               && stat (linkname, &linkstats) == 0)
2749             {
2750               f->linkok = true;
2751
2752               /* Symbolic links to directories that are mentioned on the
2753                  command line are automatically traced if not being
2754                  listed as files.  */
2755               if (!command_line_arg || format == long_format
2756                   || !S_ISDIR (linkstats.st_mode))
2757                 {
2758                   /* Get the linked-to file's mode for the filetype indicator
2759                      in long listings.  */
2760                   f->linkmode = linkstats.st_mode;
2761                 }
2762             }
2763           free (linkname);
2764         }
2765
2766       /* When not distinguishing types of symlinks, pretend we know that
2767          it is stat'able, so that it will be colored as a regular symlink,
2768          and not as an orphan.  */
2769       if (S_ISLNK (f->stat.st_mode) && !check_symlink_color)
2770         f->linkok = true;
2771
2772       if (S_ISLNK (f->stat.st_mode))
2773         f->filetype = symbolic_link;
2774       else if (S_ISDIR (f->stat.st_mode))
2775         {
2776           if (command_line_arg & !immediate_dirs)
2777             f->filetype = arg_directory;
2778           else
2779             f->filetype = directory;
2780         }
2781       else
2782         f->filetype = normal;
2783
2784       blocks = ST_NBLOCKS (f->stat);
2785       if (format == long_format || print_block_size)
2786         {
2787           char buf[LONGEST_HUMAN_READABLE + 1];
2788           int len = mbswidth (human_readable (blocks, buf, human_output_opts,
2789                                               ST_NBLOCKSIZE, output_block_size),
2790                               0);
2791           if (block_size_width < len)
2792             block_size_width = len;
2793         }
2794
2795       if (format == long_format)
2796         {
2797           if (print_owner)
2798             {
2799               int len = format_user_width (f->stat.st_uid);
2800               if (owner_width < len)
2801                 owner_width = len;
2802             }
2803
2804           if (print_group)
2805             {
2806               int len = format_group_width (f->stat.st_gid);
2807               if (group_width < len)
2808                 group_width = len;
2809             }
2810
2811           if (print_author)
2812             {
2813               int len = format_user_width (f->stat.st_author);
2814               if (author_width < len)
2815                 author_width = len;
2816             }
2817         }
2818
2819       if (print_scontext)
2820         {
2821           int len = strlen (f->scontext);
2822           if (scontext_width < len)
2823             scontext_width = len;
2824         }
2825
2826       if (format == long_format)
2827         {
2828           char b[INT_BUFSIZE_BOUND (uintmax_t)];
2829           int b_len = strlen (umaxtostr (f->stat.st_nlink, b));
2830           if (nlink_width < b_len)
2831             nlink_width = b_len;
2832
2833           if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
2834             {
2835               char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2836               int len = strlen (umaxtostr (major (f->stat.st_rdev), buf));
2837               if (major_device_number_width < len)
2838                 major_device_number_width = len;
2839               len = strlen (umaxtostr (minor (f->stat.st_rdev), buf));
2840               if (minor_device_number_width < len)
2841                 minor_device_number_width = len;
2842               len = major_device_number_width + 2 + minor_device_number_width;
2843               if (file_size_width < len)
2844                 file_size_width = len;
2845             }
2846           else
2847             {
2848               char buf[LONGEST_HUMAN_READABLE + 1];
2849               uintmax_t size = unsigned_file_size (f->stat.st_size);
2850               int len = mbswidth (human_readable (size, buf, human_output_opts,
2851                                                   1, file_output_block_size),
2852                                   0);
2853               if (file_size_width < len)
2854                 file_size_width = len;
2855             }
2856         }
2857     }
2858
2859   if (print_inode)
2860     {
2861       char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2862       int len = strlen (umaxtostr (f->stat.st_ino, buf));
2863       if (inode_number_width < len)
2864         inode_number_width = len;
2865     }
2866
2867   f->name = xstrdup (name);
2868   cwd_n_used++;
2869
2870   return blocks;
2871 }
2872
2873 /* Return true if F refers to a directory.  */
2874 static bool
2875 is_directory (const struct fileinfo *f)
2876 {
2877   return f->filetype == directory || f->filetype == arg_directory;
2878 }
2879
2880 /* Put the name of the file that FILENAME is a symbolic link to
2881    into the LINKNAME field of `f'.  COMMAND_LINE_ARG indicates whether
2882    FILENAME is a command-line argument.  */
2883
2884 static void
2885 get_link_name (char const *filename, struct fileinfo *f, bool command_line_arg)
2886 {
2887   f->linkname = areadlink_with_size (filename, f->stat.st_size);
2888   if (f->linkname == NULL)
2889     file_failure (command_line_arg, _("cannot read symbolic link %s"),
2890                   filename);
2891 }
2892
2893 /* If `linkname' is a relative name and `name' contains one or more
2894    leading directories, return `linkname' with those directories
2895    prepended; otherwise, return a copy of `linkname'.
2896    If `linkname' is zero, return zero.  */
2897
2898 static char *
2899 make_link_name (char const *name, char const *linkname)
2900 {
2901   char *linkbuf;
2902   size_t bufsiz;
2903
2904   if (!linkname)
2905     return NULL;
2906
2907   if (*linkname == '/')
2908     return xstrdup (linkname);
2909
2910   /* The link is to a relative name.  Prepend any leading directory
2911      in `name' to the link name.  */
2912   linkbuf = strrchr (name, '/');
2913   if (linkbuf == 0)
2914     return xstrdup (linkname);
2915
2916   bufsiz = linkbuf - name + 1;
2917   linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
2918   strncpy (linkbuf, name, bufsiz);
2919   strcpy (linkbuf + bufsiz, linkname);
2920   return linkbuf;
2921 }
2922
2923 /* Return true if the last component of NAME is `.' or `..'
2924    This is so we don't try to recurse on `././././. ...' */
2925
2926 static bool
2927 basename_is_dot_or_dotdot (const char *name)
2928 {
2929   char const *base = last_component (name);
2930   return dot_or_dotdot (base);
2931 }
2932
2933 /* Remove any entries from CWD_FILE that are for directories,
2934    and queue them to be listed as directories instead.
2935    DIRNAME is the prefix to prepend to each dirname
2936    to make it correct relative to ls's working dir;
2937    if it is null, no prefix is needed and "." and ".." should not be ignored.
2938    If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
2939    This is desirable when processing directories recursively.  */
2940
2941 static void
2942 extract_dirs_from_files (char const *dirname, bool command_line_arg)
2943 {
2944   size_t i;
2945   size_t j;
2946   bool ignore_dot_and_dot_dot = (dirname != NULL);
2947
2948   if (dirname && LOOP_DETECT)
2949     {
2950       /* Insert a marker entry first.  When we dequeue this marker entry,
2951          we'll know that DIRNAME has been processed and may be removed
2952          from the set of active directories.  */
2953       queue_directory (NULL, dirname, false);
2954     }
2955
2956   /* Queue the directories last one first, because queueing reverses the
2957      order.  */
2958   for (i = cwd_n_used; i-- != 0; )
2959     {
2960       struct fileinfo *f = sorted_file[i];
2961
2962       if (is_directory (f)
2963           && (! ignore_dot_and_dot_dot
2964               || ! basename_is_dot_or_dotdot (f->name)))
2965         {
2966           if (!dirname || f->name[0] == '/')
2967             queue_directory (f->name, f->linkname, command_line_arg);
2968           else
2969             {
2970               char *name = file_name_concat (dirname, f->name, NULL);
2971               queue_directory (name, f->linkname, command_line_arg);
2972               free (name);
2973             }
2974           if (f->filetype == arg_directory)
2975             free (f->name);
2976         }
2977     }
2978
2979   /* Now delete the directories from the table, compacting all the remaining
2980      entries.  */
2981
2982   for (i = 0, j = 0; i < cwd_n_used; i++)
2983     {
2984       struct fileinfo *f = sorted_file[i];
2985       sorted_file[j] = f;
2986       j += (f->filetype != arg_directory);
2987     }
2988   cwd_n_used = j;
2989 }
2990
2991 /* Use strcoll to compare strings in this locale.  If an error occurs,
2992    report an error and longjmp to failed_strcoll.  */
2993
2994 static jmp_buf failed_strcoll;
2995
2996 static int
2997 xstrcoll (char const *a, char const *b)
2998 {
2999   int diff;
3000   errno = 0;
3001   diff = strcoll (a, b);
3002   if (errno)
3003     {
3004       error (0, errno, _("cannot compare file names %s and %s"),
3005              quote_n (0, a), quote_n (1, b));
3006       set_exit_status (false);
3007       longjmp (failed_strcoll, 1);
3008     }
3009   return diff;
3010 }
3011
3012 /* Comparison routines for sorting the files.  */
3013
3014 typedef void const *V;
3015 typedef int (*qsortFunc)(V a, V b);
3016
3017 /* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants.
3018    The do { ... } while(0) makes it possible to use the macro more like
3019    a statement, without violating C89 rules: */
3020 #define DIRFIRST_CHECK(a, b)                                            \
3021   do                                                                    \
3022     {                                                                   \
3023       bool a_is_dir = is_directory ((struct fileinfo const *) a);       \
3024       bool b_is_dir = is_directory ((struct fileinfo const *) b);       \
3025       if (a_is_dir && !b_is_dir)                                        \
3026         return -1;         /* a goes before b */                        \
3027       if (!a_is_dir && b_is_dir)                                        \
3028         return 1;          /* b goes before a */                        \
3029     }                                                                   \
3030   while (0)
3031
3032 /* Define the 8 different sort function variants required for each sortkey.
3033    KEY_NAME is a token describing the sort key, e.g., ctime, atime, size.
3034    KEY_CMP_FUNC is a function to compare records based on that key, e.g.,
3035    ctime_cmp, atime_cmp, size_cmp.  Append KEY_NAME to the string,
3036    '[rev_][x]str{cmp|coll}[_df]_', to create each function name.  */
3037 #define DEFINE_SORT_FUNCTIONS(key_name, key_cmp_func)                   \
3038   /* direct, non-dirfirst versions */                                   \
3039   static int xstrcoll_##key_name (V a, V b)                             \
3040   { return key_cmp_func (a, b, xstrcoll); }                             \
3041   static int strcmp_##key_name (V a, V b)                               \
3042   { return key_cmp_func (a, b, strcmp); }                               \
3043                                                                         \
3044   /* reverse, non-dirfirst versions */                                  \
3045   static int rev_xstrcoll_##key_name (V a, V b)                         \
3046   { return key_cmp_func (b, a, xstrcoll); }                             \
3047   static int rev_strcmp_##key_name (V a, V b)                           \
3048   { return key_cmp_func (b, a, strcmp); }                               \
3049                                                                         \
3050   /* direct, dirfirst versions */                                       \
3051   static int xstrcoll_df_##key_name (V a, V b)                          \
3052   { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, xstrcoll); }      \
3053   static int strcmp_df_##key_name (V a, V b)                            \
3054   { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, strcmp); }        \
3055                                                                         \
3056   /* reverse, dirfirst versions */                                      \
3057   static int rev_xstrcoll_df_##key_name (V a, V b)                      \
3058   { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, xstrcoll); }      \
3059   static int rev_strcmp_df_##key_name (V a, V b)                        \
3060   { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, strcmp); }
3061
3062 static inline int
3063 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
3064            int (*cmp) (char const *, char const *))
3065 {
3066   int diff = timespec_cmp (get_stat_ctime (&b->stat),
3067                            get_stat_ctime (&a->stat));
3068   return diff ? diff : cmp (a->name, b->name);
3069 }
3070
3071 static inline int
3072 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
3073            int (*cmp) (char const *, char const *))
3074 {
3075   int diff = timespec_cmp (get_stat_mtime (&b->stat),
3076                            get_stat_mtime (&a->stat));
3077   return diff ? diff : cmp (a->name, b->name);
3078 }
3079
3080 static inline int
3081 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
3082            int (*cmp) (char const *, char const *))
3083 {
3084   int diff = timespec_cmp (get_stat_atime (&b->stat),
3085                            get_stat_atime (&a->stat));
3086   return diff ? diff : cmp (a->name, b->name);
3087 }
3088
3089 static inline int
3090 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
3091           int (*cmp) (char const *, char const *))
3092 {
3093   int diff = longdiff (b->stat.st_size, a->stat.st_size);
3094   return diff ? diff : cmp (a->name, b->name);
3095 }
3096
3097 static inline int
3098 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
3099           int (*cmp) (char const *, char const *))
3100 {
3101   return cmp (a->name, b->name);
3102 }
3103
3104 /* Compare file extensions.  Files with no extension are `smallest'.
3105    If extensions are the same, compare by filenames instead.  */
3106
3107 static inline int
3108 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
3109                int (*cmp) (char const *, char const *))
3110 {
3111   char const *base1 = strrchr (a->name, '.');
3112   char const *base2 = strrchr (b->name, '.');
3113   int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
3114   return diff ? diff : cmp (a->name, b->name);
3115 }
3116
3117 DEFINE_SORT_FUNCTIONS (ctime, cmp_ctime)
3118 DEFINE_SORT_FUNCTIONS (mtime, cmp_mtime)
3119 DEFINE_SORT_FUNCTIONS (atime, cmp_atime)
3120 DEFINE_SORT_FUNCTIONS (size, cmp_size)
3121 DEFINE_SORT_FUNCTIONS (name, cmp_name)
3122 DEFINE_SORT_FUNCTIONS (extension, cmp_extension)
3123
3124 /* Compare file versions.
3125    Unlike all other compare functions above, cmp_version depends only
3126    on strverscmp, which does not fail (even for locale reasons), and does not
3127    need a secondary sort key.
3128    All the other sort options, in fact, need xstrcoll and strcmp variants,
3129    because they all use a string comparison (either as the primary or secondary
3130    sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
3131    locale reasons.  Last, strverscmp is ALWAYS available in coreutils,
3132    thanks to the gnulib library. */
3133 static inline int
3134 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
3135 {
3136   return strverscmp (a->name, b->name);
3137 }
3138
3139 static int xstrcoll_version (V a, V b)
3140 { return cmp_version (a, b); }
3141 static int rev_xstrcoll_version (V a, V b)
3142 { return cmp_version (b, a); }
3143 static int xstrcoll_df_version (V a, V b)
3144 { DIRFIRST_CHECK (a, b); return cmp_version (a, b); }
3145 static int rev_xstrcoll_df_version (V a, V b)
3146 { DIRFIRST_CHECK (a, b); return cmp_version (b, a); }
3147
3148
3149 /* We have 2^3 different variants for each sortkey function
3150    (for 3 independent sort modes).
3151    The function pointers stored in this array must be dereferenced as:
3152
3153     sort_variants[sort_key][use_strcmp][reverse][dirs_first]
3154
3155    Note that the order in which sortkeys are listed in the function pointer
3156    array below is defined by the order of the elements in the time_type and
3157    sort_type enums!  */
3158
3159 #define LIST_SORTFUNCTION_VARIANTS(key_name)                        \
3160   {                                                                 \
3161     {                                                               \
3162       { xstrcoll_##key_name, xstrcoll_df_##key_name },              \
3163       { rev_xstrcoll_##key_name, rev_xstrcoll_df_##key_name },      \
3164     },                                                              \
3165     {                                                               \
3166       { strcmp_##key_name, strcmp_df_##key_name },                  \
3167       { rev_strcmp_##key_name, rev_strcmp_df_##key_name },          \
3168     }                                                               \
3169   }
3170
3171 static qsortFunc const sort_functions[][2][2][2] =
3172   {
3173     LIST_SORTFUNCTION_VARIANTS (name),
3174     LIST_SORTFUNCTION_VARIANTS (extension),
3175     LIST_SORTFUNCTION_VARIANTS (size),
3176
3177     {
3178       {
3179         { xstrcoll_version, xstrcoll_df_version },
3180         { rev_xstrcoll_version, rev_xstrcoll_df_version },
3181       },
3182
3183       /* We use NULL for the strcmp variants of version comparison
3184          since as explained in cmp_version definition, version comparison
3185          does not rely on xstrcoll, so it will never longjmp, and never
3186          need to try the strcmp fallback. */
3187       {
3188         { NULL, NULL },
3189         { NULL, NULL },
3190       }
3191     },
3192
3193     /* last are time sort functions */
3194     LIST_SORTFUNCTION_VARIANTS (mtime),
3195     LIST_SORTFUNCTION_VARIANTS (ctime),
3196     LIST_SORTFUNCTION_VARIANTS (atime)
3197   };
3198
3199 /* The number of sortkeys is calculated as
3200      the number of elements in the sort_type enum (i.e. sort_numtypes) +
3201      the number of elements in the time_type enum (i.e. time_numtypes) - 1
3202    This is because when sort_type==sort_time, we have up to
3203    time_numtypes possible sortkeys.
3204
3205    This line verifies at compile-time that the array of sort functions has been
3206    initialized for all possible sortkeys. */
3207 verify (ARRAY_CARDINALITY (sort_functions)
3208         == sort_numtypes + time_numtypes - 1 );
3209
3210 /* Set up SORTED_FILE to point to the in-use entries in CWD_FILE, in order.  */
3211
3212 static void
3213 initialize_ordering_vector (void)
3214 {
3215   size_t i;
3216   for (i = 0; i < cwd_n_used; i++)
3217     sorted_file[i] = &cwd_file[i];
3218 }
3219
3220 /* Sort the files now in the table.  */
3221
3222 static void
3223 sort_files (void)
3224 {
3225   bool use_strcmp;
3226
3227   if (sorted_file_alloc < cwd_n_used + cwd_n_used / 2)
3228     {
3229       free (sorted_file);
3230       sorted_file = xnmalloc (cwd_n_used, 3 * sizeof *sorted_file);
3231       sorted_file_alloc = 3 * cwd_n_used;
3232     }
3233
3234   initialize_ordering_vector ();
3235
3236   if (sort_type == sort_none)
3237     return;
3238
3239   /* Try strcoll.  If it fails, fall back on strcmp.  We can't safely
3240      ignore strcoll failures, as a failing strcoll might be a
3241      comparison function that is not a total order, and if we ignored
3242      the failure this might cause qsort to dump core.  */
3243
3244   if (! setjmp (failed_strcoll))
3245     use_strcmp = false;      /* strcoll() succeeded */
3246   else
3247     {
3248       use_strcmp = true;
3249       assert (sort_type != sort_version);
3250       initialize_ordering_vector ();
3251     }
3252
3253   /* When sort_type == sort_time, use time_type as subindex.  */
3254   mpsort ((void const **) sorted_file, cwd_n_used,
3255           sort_functions[sort_type + (sort_type == sort_time ? time_type : 0)]
3256                         [use_strcmp][sort_reverse]
3257                         [directories_first]);
3258 }
3259
3260 /* List all the files now in the table.  */
3261
3262 static void
3263 print_current_files (void)
3264 {
3265   size_t i;
3266
3267   switch (format)
3268     {
3269     case one_per_line:
3270       for (i = 0; i < cwd_n_used; i++)
3271         {
3272           print_file_name_and_frills (sorted_file[i]);
3273           putchar ('\n');
3274         }
3275       break;
3276
3277     case many_per_line:
3278       print_many_per_line ();
3279       break;
3280
3281     case horizontal:
3282       print_horizontal ();
3283       break;
3284
3285     case with_commas:
3286       print_with_commas ();
3287       break;
3288
3289     case long_format:
3290       for (i = 0; i < cwd_n_used; i++)
3291         {
3292           print_long_format (sorted_file[i]);
3293           DIRED_PUTCHAR ('\n');
3294         }
3295       break;
3296     }
3297 }
3298
3299 /* Return the expected number of columns in a long-format time stamp,
3300    or zero if it cannot be calculated.  */
3301
3302 static int
3303 long_time_expected_width (void)
3304 {
3305   static int width = -1;
3306
3307   if (width < 0)
3308     {
3309       time_t epoch = 0;
3310       struct tm const *tm = localtime (&epoch);
3311       char buf[TIME_STAMP_LEN_MAXIMUM + 1];
3312
3313       /* In case you're wondering if localtime can fail with an input time_t
3314          value of 0, let's just say it's very unlikely, but not inconceivable.
3315          The TZ environment variable would have to specify a time zone that
3316          is 2**31-1900 years or more ahead of UTC.  This could happen only on
3317          a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
3318          However, this is not possible with Solaris 10 or glibc-2.3.5, since
3319          their implementations limit the offset to 167:59 and 24:00, resp.  */
3320       if (tm)
3321         {
3322           size_t len =
3323             nstrftime (buf, sizeof buf, long_time_format[0], tm, 0, 0);
3324           if (len != 0)
3325             width = mbsnwidth (buf, len, 0);
3326         }
3327
3328       if (width < 0)
3329         width = 0;
3330     }
3331
3332   return width;
3333 }
3334
3335 /* Print the user or group name NAME, with numeric id ID, using a
3336    print width of WIDTH columns.  */
3337
3338 static void
3339 format_user_or_group (char const *name, unsigned long int id, int width)
3340 {
3341   size_t len;
3342
3343   if (name)
3344     {
3345       int width_gap = width - mbswidth (name, 0);
3346       int pad = MAX (0, width_gap);
3347       fputs (name, stdout);
3348       len = strlen (name) + pad;
3349
3350       do
3351         putchar (' ');
3352       while (pad--);
3353     }
3354   else
3355     {
3356       printf ("%*lu ", width, id);
3357       len = width;
3358     }
3359
3360   dired_pos += len + 1;
3361 }
3362
3363 /* Print the name or id of the user with id U, using a print width of
3364    WIDTH.  */
3365
3366 static void
3367 format_user (uid_t u, int width, bool stat_ok)
3368 {
3369   format_user_or_group (! stat_ok ? "?" :
3370                         (numeric_ids ? NULL : getuser (u)), u, width);
3371 }
3372
3373 /* Likewise, for groups.  */
3374
3375 static void
3376 format_group (gid_t g, int width, bool stat_ok)
3377 {
3378   format_user_or_group (! stat_ok ? "?" :
3379                         (numeric_ids ? NULL : getgroup (g)), g, width);
3380 }
3381
3382 /* Return the number of columns that format_user_or_group will print.  */
3383
3384 static int
3385 format_user_or_group_width (char const *name, unsigned long int id)
3386 {
3387   if (name)
3388     {
3389       int len = mbswidth (name, 0);
3390       return MAX (0, len);
3391     }
3392   else
3393     {
3394       char buf[INT_BUFSIZE_BOUND (unsigned long int)];
3395       sprintf (buf, "%lu", id);
3396       return strlen (buf);
3397     }
3398 }
3399
3400 /* Return the number of columns that format_user will print.  */
3401
3402 static int
3403 format_user_width (uid_t u)
3404 {
3405   return format_user_or_group_width (numeric_ids ? NULL : getuser (u), u);
3406 }
3407
3408 /* Likewise, for groups.  */
3409
3410 static int
3411 format_group_width (gid_t g)
3412 {
3413   return format_user_or_group_width (numeric_ids ? NULL : getgroup (g), g);
3414 }
3415
3416
3417 /* Print information about F in long format.  */
3418
3419 static void
3420 print_long_format (const struct fileinfo *f)
3421 {
3422   char modebuf[12];
3423   char buf
3424     [LONGEST_HUMAN_READABLE + 1         /* inode */
3425      + LONGEST_HUMAN_READABLE + 1       /* size in blocks */
3426      + sizeof (modebuf) - 1 + 1         /* mode string */
3427      + INT_BUFSIZE_BOUND (uintmax_t)    /* st_nlink */
3428      + LONGEST_HUMAN_READABLE + 2       /* major device number */
3429      + LONGEST_HUMAN_READABLE + 1       /* minor device number */
3430      + TIME_STAMP_LEN_MAXIMUM + 1       /* max length of time/date */
3431      ];
3432   size_t s;
3433   char *p;
3434   struct timespec when_timespec;
3435   struct tm *when_local;
3436
3437   /* Compute the mode string, except remove the trailing space if no
3438      file in this directory has an ACL or SELinux security context.  */
3439   if (f->stat_ok)
3440     filemodestring (&f->stat, modebuf);
3441   else
3442     {
3443       modebuf[0] = filetype_letter[f->filetype];
3444       memset (modebuf + 1, '?', 10);
3445       modebuf[11] = '\0';
3446     }
3447   if (! any_has_acl)
3448     modebuf[10] = '\0';
3449   else if (f->have_acl)
3450     modebuf[10] = '+';
3451
3452   switch (time_type)
3453     {
3454     case time_ctime:
3455       when_timespec = get_stat_ctime (&f->stat);
3456       break;
3457     case time_mtime:
3458       when_timespec = get_stat_mtime (&f->stat);
3459       break;
3460     case time_atime:
3461       when_timespec = get_stat_atime (&f->stat);
3462       break;
3463     default:
3464       abort ();
3465     }
3466
3467   p = buf;
3468
3469   if (print_inode)
3470     {
3471       char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3472       sprintf (p, "%*s ", inode_number_width,
3473                (f->stat.st_ino == NOT_AN_INODE_NUMBER
3474                 ? "?"
3475                 : umaxtostr (f->stat.st_ino, hbuf)));
3476       /* Increment by strlen (p) here, rather than by inode_number_width + 1.
3477          The latter is wrong when inode_number_width is zero.  */
3478       p += strlen (p);
3479     }
3480
3481   if (print_block_size)
3482     {
3483       char hbuf[LONGEST_HUMAN_READABLE + 1];
3484       char const *blocks =
3485         (! f->stat_ok
3486          ? "?"
3487          : human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts,
3488                            ST_NBLOCKSIZE, output_block_size));
3489       int pad;
3490       for (pad = block_size_width - mbswidth (blocks, 0); 0 < pad; pad--)
3491         *p++ = ' ';
3492       while ((*p++ = *blocks++))
3493         continue;
3494       p[-1] = ' ';
3495     }
3496
3497   /* The last byte of the mode string is the POSIX
3498      "optional alternate access method flag".  */
3499   {
3500     char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3501     sprintf (p, "%s %*s ", modebuf, nlink_width,
3502              ! f->stat_ok ? "?" : umaxtostr (f->stat.st_nlink, hbuf));
3503   }
3504   /* Increment by strlen (p) here, rather than by, e.g.,
3505      sizeof modebuf - 2 + any_has_acl + 1 + nlink_width + 1.
3506      The latter is wrong when nlink_width is zero.  */
3507   p += strlen (p);
3508
3509   DIRED_INDENT ();
3510
3511   if (print_owner | print_group | print_author | print_scontext)
3512     {
3513       DIRED_FPUTS (buf, stdout, p - buf);
3514
3515       if (print_owner)
3516         format_user (f->stat.st_uid, owner_width, f->stat_ok);
3517
3518       if (print_group)
3519         format_group (f->stat.st_gid, group_width, f->stat_ok);
3520
3521       if (print_author)
3522         format_user (f->stat.st_author, author_width, f->stat_ok);
3523
3524       if (print_scontext)
3525         format_user_or_group (f->scontext, 0, scontext_width);
3526
3527       p = buf;
3528     }
3529
3530   if (f->stat_ok
3531       && (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode)))
3532     {
3533       char majorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3534       char minorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3535       int blanks_width = (file_size_width
3536                           - (major_device_number_width + 2
3537                              + minor_device_number_width));
3538       sprintf (p, "%*s, %*s ",
3539                major_device_number_width + MAX (0, blanks_width),
3540                umaxtostr (major (f->stat.st_rdev), majorbuf),
3541                minor_device_number_width,
3542                umaxtostr (minor (f->stat.st_rdev), minorbuf));
3543       p += file_size_width + 1;
3544     }
3545   else
3546     {
3547       char hbuf[LONGEST_HUMAN_READABLE + 1];
3548       char const *size =
3549         (! f->stat_ok
3550          ? "?"
3551          : human_readable (unsigned_file_size (f->stat.st_size),
3552                            hbuf, human_output_opts, 1, file_output_block_size));
3553       int pad;
3554       for (pad = file_size_width - mbswidth (size, 0); 0 < pad; pad--)
3555         *p++ = ' ';
3556       while ((*p++ = *size++))
3557         continue;
3558       p[-1] = ' ';
3559     }
3560
3561   when_local = localtime (&when_timespec.tv_sec);
3562   s = 0;
3563   *p = '\1';
3564
3565   if (f->stat_ok && when_local)
3566     {
3567       struct timespec six_months_ago;
3568       bool recent;
3569       char const *fmt;
3570
3571       /* If the file appears to be in the future, update the current
3572          time, in case the file happens to have been modified since
3573          the last time we checked the clock.  */
3574       if (timespec_cmp (current_time, when_timespec) < 0)
3575         {
3576           /* Note that gettime may call gettimeofday which, on some non-
3577              compliant systems, clobbers the buffer used for localtime's result.
3578              But it's ok here, because we use a gettimeofday wrapper that
3579              saves and restores the buffer around the gettimeofday call.  */
3580           gettime (&current_time);
3581         }
3582
3583       /* Consider a time to be recent if it is within the past six
3584          months.  A Gregorian year has 365.2425 * 24 * 60 * 60 ==
3585          31556952 seconds on the average.  Write this value as an
3586          integer constant to avoid floating point hassles.  */
3587       six_months_ago.tv_sec = current_time.tv_sec - 31556952 / 2;
3588       six_months_ago.tv_nsec = current_time.tv_nsec;
3589
3590       recent = (timespec_cmp (six_months_ago, when_timespec) < 0
3591                 && (timespec_cmp (when_timespec, current_time) < 0));
3592       fmt = long_time_format[recent];
3593
3594       /* We assume here that all time zones are offset from UTC by a
3595          whole number of seconds.  */
3596       s = nstrftime (p, TIME_STAMP_LEN_MAXIMUM + 1, fmt,
3597                      when_local, 0, when_timespec.tv_nsec);
3598     }
3599
3600   if (s || !*p)
3601     {
3602       p += s;
3603       *p++ = ' ';
3604
3605       /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it.  */
3606       *p = '\0';
3607     }
3608   else
3609     {
3610       /* The time cannot be converted using the desired format, so
3611          print it as a huge integer number of seconds.  */
3612       char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
3613       sprintf (p, "%*s ", long_time_expected_width (),
3614                (! f->stat_ok
3615                 ? "?"
3616                 : timetostr (when_timespec.tv_sec, hbuf)));
3617       /* FIXME: (maybe) We discarded when_timespec.tv_nsec. */
3618       p += strlen (p);
3619     }
3620
3621   DIRED_FPUTS (buf, stdout, p - buf);
3622   print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
3623                            f->stat_ok, f->filetype, &dired_obstack);
3624
3625   if (f->filetype == symbolic_link)
3626     {
3627       if (f->linkname)
3628         {
3629           DIRED_FPUTS_LITERAL (" -> ", stdout);
3630           print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1,
3631                                    f->stat_ok, f->filetype, NULL);
3632           if (indicator_style != none)
3633             print_type_indicator (true, f->linkmode, unknown);
3634         }
3635     }
3636   else if (indicator_style != none)
3637     print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
3638 }
3639
3640 /* Output to OUT a quoted representation of the file name NAME,
3641    using OPTIONS to control quoting.  Produce no output if OUT is NULL.
3642    Store the number of screen columns occupied by NAME's quoted
3643    representation into WIDTH, if non-NULL.  Return the number of bytes
3644    produced.  */
3645
3646 static size_t
3647 quote_name (FILE *out, const char *name, struct quoting_options const *options,
3648             size_t *width)
3649 {
3650   char smallbuf[BUFSIZ];
3651   size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, name, -1, options);
3652   char *buf;
3653   size_t displayed_width IF_LINT (= 0);
3654
3655   if (len < sizeof smallbuf)
3656     buf = smallbuf;
3657   else
3658     {
3659       buf = alloca (len + 1);
3660       quotearg_buffer (buf, len + 1, name, -1, options);
3661     }
3662
3663   if (qmark_funny_chars)
3664     {
3665 #if HAVE_MBRTOWC
3666       if (MB_CUR_MAX > 1)
3667         {
3668           char const *p = buf;
3669           char const *plimit = buf + len;
3670           char *q = buf;
3671           displayed_width = 0;
3672
3673           while (p < plimit)
3674             switch (*p)
3675               {
3676                 case ' ': case '!': case '"': case '#': case '%':
3677                 case '&': case '\'': case '(': case ')': case '*':
3678                 case '+': case ',': case '-': case '.': case '/':
3679                 case '0': case '1': case '2': case '3': case '4':
3680                 case '5': case '6': case '7': case '8': case '9':
3681                 case ':': case ';': case '<': case '=': case '>':
3682                 case '?':
3683                 case 'A': case 'B': case 'C': case 'D': case 'E':
3684                 case 'F': case 'G': case 'H': case 'I': case 'J':
3685                 case 'K': case 'L': case 'M': case 'N': case 'O':
3686                 case 'P': case 'Q': case 'R': case 'S': case 'T':
3687                 case 'U': case 'V': case 'W': case 'X': case 'Y':
3688                 case 'Z':
3689                 case '[': case '\\': case ']': case '^': case '_':
3690                 case 'a': case 'b': case 'c': case 'd': case 'e':
3691                 case 'f': case 'g': case 'h': case 'i': case 'j':
3692                 case 'k': case 'l': case 'm': case 'n': case 'o':
3693                 case 'p': case 'q': case 'r': case 's': case 't':
3694                 case 'u': case 'v': case 'w': case 'x': case 'y':
3695                 case 'z': case '{': case '|': case '}': case '~':
3696                   /* These characters are printable ASCII characters.  */
3697                   *q++ = *p++;
3698                   displayed_width += 1;
3699                   break;
3700                 default:
3701                   /* If we have a multibyte sequence, copy it until we
3702                      reach its end, replacing each non-printable multibyte
3703                      character with a single question mark.  */
3704                   {
3705                     mbstate_t mbstate = { 0, };
3706                     do
3707                       {
3708                         wchar_t wc;
3709                         size_t bytes;
3710                         int w;
3711
3712                         bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
3713
3714                         if (bytes == (size_t) -1)
3715                           {
3716                             /* An invalid multibyte sequence was
3717                                encountered.  Skip one input byte, and
3718                                put a question mark.  */
3719                             p++;
3720                             *q++ = '?';
3721                             displayed_width += 1;
3722                             break;
3723                           }
3724
3725                         if (bytes == (size_t) -2)
3726                           {
3727                             /* An incomplete multibyte character
3728                                at the end.  Replace it entirely with
3729                                a question mark.  */
3730                             p = plimit;
3731                             *q++ = '?';
3732                             displayed_width += 1;
3733                             break;
3734                           }
3735
3736                         if (bytes == 0)
3737                           /* A null wide character was encountered.  */
3738                           bytes = 1;
3739
3740                         w = wcwidth (wc);
3741                         if (w >= 0)
3742                           {
3743                             /* A printable multibyte character.
3744                                Keep it.  */
3745                             for (; bytes > 0; --bytes)
3746                               *q++ = *p++;
3747                             displayed_width += w;
3748                           }
3749                         else
3750                           {
3751                             /* An unprintable multibyte character.
3752                                Replace it entirely with a question
3753                                mark.  */
3754                             p += bytes;
3755                             *q++ = '?';
3756                             displayed_width += 1;
3757                           }
3758                       }
3759                     while (! mbsinit (&mbstate));
3760                   }
3761                   break;
3762               }
3763
3764           /* The buffer may have shrunk.  */
3765           len = q - buf;
3766         }
3767       else
3768 #endif
3769         {
3770           char *p = buf;
3771           char const *plimit = buf + len;
3772
3773           while (p < plimit)
3774             {
3775               if (! isprint (to_uchar (*p)))
3776                 *p = '?';
3777               p++;
3778             }
3779           displayed_width = len;
3780         }
3781     }
3782   else if (width != NULL)
3783     {
3784 #if HAVE_MBRTOWC
3785       if (MB_CUR_MAX > 1)
3786         displayed_width = mbsnwidth (buf, len, 0);
3787       else
3788 #endif
3789         {
3790           char const *p = buf;
3791           char const *plimit = buf + len;
3792
3793           displayed_width = 0;
3794           while (p < plimit)
3795             {
3796               if (isprint (to_uchar (*p)))
3797                 displayed_width++;
3798               p++;
3799             }
3800         }
3801     }
3802
3803   if (out != NULL)
3804     fwrite (buf, 1, len, out);
3805   if (width != NULL)
3806     *width = displayed_width;
3807   return len;
3808 }
3809
3810 static void
3811 print_name_with_quoting (const char *p, mode_t mode, int linkok,
3812                          bool stat_ok, enum filetype type,
3813                          struct obstack *stack)
3814 {
3815   bool used_color_this_time
3816     = (print_with_color
3817        && print_color_indicator (p, mode, linkok, stat_ok, type));
3818
3819   if (stack)
3820     PUSH_CURRENT_DIRED_POS (stack);
3821
3822   dired_pos += quote_name (stdout, p, filename_quoting_options, NULL);
3823
3824   if (stack)
3825     PUSH_CURRENT_DIRED_POS (stack);
3826
3827   if (used_color_this_time)
3828     {
3829       process_signals ();
3830       prep_non_filename_text ();
3831     }
3832 }
3833
3834 static void
3835 prep_non_filename_text (void)
3836 {
3837   if (color_indicator[C_END].string != NULL)
3838     put_indicator (&color_indicator[C_END]);
3839   else
3840     {
3841       put_indicator (&color_indicator[C_LEFT]);
3842       put_indicator (&color_indicator[C_RESET]);
3843       put_indicator (&color_indicator[C_RIGHT]);
3844     }
3845 }
3846
3847 /* Print the file name of `f' with appropriate quoting.
3848    Also print file size, inode number, and filetype indicator character,
3849    as requested by switches.  */
3850
3851 static void
3852 print_file_name_and_frills (const struct fileinfo *f)
3853 {
3854   char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
3855
3856   if (print_inode)
3857     printf ("%*s ", format == with_commas ? 0 : inode_number_width,
3858             umaxtostr (f->stat.st_ino, buf));
3859
3860   if (print_block_size)
3861     printf ("%*s ", format == with_commas ? 0 : block_size_width,
3862             human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts,
3863                             ST_NBLOCKSIZE, output_block_size));
3864
3865   if (print_scontext)
3866     printf ("%*s ", format == with_commas ? 0 : scontext_width, f->scontext);
3867
3868   print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
3869                            f->stat_ok, f->filetype, NULL);
3870
3871   if (indicator_style != none)
3872     print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
3873 }
3874
3875 /* Given these arguments describing a file, return the single-byte
3876    type indicator, or 0.  */
3877 static char
3878 get_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
3879 {
3880   char c;
3881
3882   if (stat_ok ? S_ISREG (mode) : type == normal)
3883     {
3884       if (stat_ok && indicator_style == classify && (mode & S_IXUGO))
3885         c = '*';
3886       else
3887         c = 0;
3888     }
3889   else
3890     {
3891       if (stat_ok ? S_ISDIR (mode) : type == directory || type == arg_directory)
3892         c = '/';
3893       else if (indicator_style == slash)
3894         c = 0;
3895       else if (stat_ok ? S_ISLNK (mode) : type == symbolic_link)
3896         c = '@';
3897       else if (stat_ok ? S_ISFIFO (mode) : type == fifo)
3898         c = '|';
3899       else if (stat_ok ? S_ISSOCK (mode) : type == sock)
3900         c = '=';
3901       else if (stat_ok && S_ISDOOR (mode))
3902         c = '>';
3903       else
3904         c = 0;
3905     }
3906   return c;
3907 }
3908
3909 static void
3910 print_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
3911 {
3912   char c = get_type_indicator (stat_ok, mode, type);
3913   if (c)
3914     DIRED_PUTCHAR (c);
3915 }
3916
3917 #ifdef HAVE_CAP
3918 /* Return true if NAME has a capability (see linux/capability.h) */
3919 static bool
3920 has_capability (char const *name)
3921 {
3922   char *result;
3923   bool has_cap;
3924
3925   cap_t cap_d = cap_get_file (name);
3926   if (cap_d == NULL)
3927     return false;
3928
3929   result = cap_to_text (cap_d, NULL);
3930   cap_free (cap_d);
3931   if (!result)
3932     return false;
3933
3934   /* check if human-readable capability string is empty */
3935   has_cap = !!*result;
3936
3937   cap_free (result);
3938   return has_cap;
3939 }
3940 #else
3941 static bool
3942 has_capability (char const *name)
3943 {
3944   return false;
3945 }
3946 #endif
3947
3948 /* Returns whether any color sequence was printed. */
3949 static bool
3950 print_color_indicator (const char *name, mode_t mode, int linkok,
3951                        bool stat_ok, enum filetype filetype)
3952 {
3953   int type;
3954   struct color_ext_type *ext;   /* Color extension */
3955   size_t len;                   /* Length of name */
3956
3957   /* Is this a nonexistent file?  If so, linkok == -1.  */
3958
3959   if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
3960     type = C_MISSING;
3961   else if (! stat_ok)
3962     {
3963       static enum indicator_no filetype_indicator[] = FILETYPE_INDICATORS;
3964       type = filetype_indicator[filetype];
3965     }
3966   else
3967     {
3968       if (S_ISREG (mode))
3969         {
3970           type = C_FILE;
3971           if ((mode & S_ISUID) != 0)
3972             type = C_SETUID;
3973           else if ((mode & S_ISGID) != 0)
3974             type = C_SETGID;
3975           else if (has_capability (name))
3976             type = C_CAP;
3977           else if ((mode & S_IXUGO) != 0)
3978             type = C_EXEC;
3979         }
3980       else if (S_ISDIR (mode))
3981         {
3982           if ((mode & S_ISVTX) && (mode & S_IWOTH))
3983             type = C_STICKY_OTHER_WRITABLE;
3984           else if ((mode & S_IWOTH) != 0)
3985             type = C_OTHER_WRITABLE;
3986           else if ((mode & S_ISVTX) != 0)
3987             type = C_STICKY;
3988           else
3989             type = C_DIR;
3990         }
3991       else if (S_ISLNK (mode))
3992         type = ((!linkok && color_indicator[C_ORPHAN].string)
3993                 ? C_ORPHAN : C_LINK);
3994       else if (S_ISFIFO (mode))
3995         type = C_FIFO;
3996       else if (S_ISSOCK (mode))
3997         type = C_SOCK;
3998       else if (S_ISBLK (mode))
3999         type = C_BLK;
4000       else if (S_ISCHR (mode))
4001         type = C_CHR;
4002       else if (S_ISDOOR (mode))
4003         type = C_DOOR;
4004       else
4005         {
4006           /* Classify a file of some other type as C_ORPHAN.  */
4007           type = C_ORPHAN;
4008         }
4009     }
4010
4011   /* Check the file's suffix only if still classified as C_FILE.  */
4012   ext = NULL;
4013   if (type == C_FILE)
4014     {
4015       /* Test if NAME has a recognized suffix.  */
4016
4017       len = strlen (name);
4018       name += len;              /* Pointer to final \0.  */
4019       for (ext = color_ext_list; ext != NULL; ext = ext->next)
4020         {
4021           if (ext->ext.len <= len
4022               && strncmp (name - ext->ext.len, ext->ext.string,
4023                           ext->ext.len) == 0)
4024             break;
4025         }
4026     }
4027
4028   {
4029     const struct bin_str *const s
4030       = ext ? &(ext->seq) : &color_indicator[type];
4031     if (s->string != NULL)
4032       {
4033         put_indicator (&color_indicator[C_LEFT]);
4034         put_indicator (s);
4035         put_indicator (&color_indicator[C_RIGHT]);
4036         return true;
4037       }
4038     else
4039       return false;
4040   }
4041 }
4042
4043 /* Output a color indicator (which may contain nulls).  */
4044 static void
4045 put_indicator (const struct bin_str *ind)
4046 {
4047   if (! used_color)
4048     {
4049       used_color = true;
4050       prep_non_filename_text ();
4051     }
4052
4053   fwrite (ind->string, ind->len, 1, stdout);
4054 }
4055
4056 static size_t
4057 length_of_file_name_and_frills (const struct fileinfo *f)
4058 {
4059   size_t len = 0;
4060   size_t name_width;
4061   char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
4062
4063   if (print_inode)
4064     len += 1 + (format == with_commas
4065                 ? strlen (umaxtostr (f->stat.st_ino, buf))
4066                 : inode_number_width);
4067
4068   if (print_block_size)
4069     len += 1 + (format == with_commas
4070                 ? strlen (human_readable (ST_NBLOCKS (f->stat), buf,
4071                                           human_output_opts, ST_NBLOCKSIZE,
4072                                           output_block_size))
4073                 : block_size_width);
4074
4075   if (print_scontext)
4076     len += 1 + (format == with_commas ? strlen (f->scontext) : scontext_width);
4077
4078   quote_name (NULL, f->name, filename_quoting_options, &name_width);
4079   len += name_width;
4080
4081   if (indicator_style != none)
4082     {
4083       char c = get_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4084       len += (c != 0);
4085     }
4086
4087   return len;
4088 }
4089
4090 static void
4091 print_many_per_line (void)
4092 {
4093   size_t row;                   /* Current row.  */
4094   size_t cols = calculate_columns (true);
4095   struct column_info const *line_fmt = &column_info[cols - 1];
4096
4097   /* Calculate the number of rows that will be in each column except possibly
4098      for a short column on the right.  */
4099   size_t rows = cwd_n_used / cols + (cwd_n_used % cols != 0);
4100
4101   for (row = 0; row < rows; row++)
4102     {
4103       size_t col = 0;
4104       size_t filesno = row;
4105       size_t pos = 0;
4106
4107       /* Print the next row.  */
4108       while (1)
4109         {
4110           struct fileinfo const *f = sorted_file[filesno];
4111           size_t name_length = length_of_file_name_and_frills (f);
4112           size_t max_name_length = line_fmt->col_arr[col++];
4113           print_file_name_and_frills (f);
4114
4115           filesno += rows;
4116           if (filesno >= cwd_n_used)
4117             break;
4118
4119           indent (pos + name_length, pos + max_name_length);
4120           pos += max_name_length;
4121         }
4122       putchar ('\n');
4123     }
4124 }
4125
4126 static void
4127 print_horizontal (void)
4128 {
4129   size_t filesno;
4130   size_t pos = 0;
4131   size_t cols = calculate_columns (false);
4132   struct column_info const *line_fmt = &column_info[cols - 1];
4133   struct fileinfo const *f = sorted_file[0];
4134   size_t name_length = length_of_file_name_and_frills (f);
4135   size_t max_name_length = line_fmt->col_arr[0];
4136
4137   /* Print first entry.  */
4138   print_file_name_and_frills (f);
4139
4140   /* Now the rest.  */
4141   for (filesno = 1; filesno < cwd_n_used; ++filesno)
4142     {
4143       size_t col = filesno % cols;
4144
4145       if (col == 0)
4146         {
4147           putchar ('\n');
4148           pos = 0;
4149         }
4150       else
4151         {
4152           indent (pos + name_length, pos + max_name_length);
4153           pos += max_name_length;
4154         }
4155
4156       f = sorted_file[filesno];
4157       print_file_name_and_frills (f);
4158
4159       name_length = length_of_file_name_and_frills (f);
4160       max_name_length = line_fmt->col_arr[col];
4161     }
4162   putchar ('\n');
4163 }
4164
4165 static void
4166 print_with_commas (void)
4167 {
4168   size_t filesno;
4169   size_t pos = 0;
4170
4171   for (filesno = 0; filesno < cwd_n_used; filesno++)
4172     {
4173       struct fileinfo const *f = sorted_file[filesno];
4174       size_t len = length_of_file_name_and_frills (f);
4175
4176       if (filesno != 0)
4177         {
4178           char separator;
4179
4180           if (pos + len + 2 < line_length)
4181             {
4182               pos += 2;
4183               separator = ' ';
4184             }
4185           else
4186             {
4187               pos = 0;
4188               separator = '\n';
4189             }
4190
4191           putchar (',');
4192           putchar (separator);
4193         }
4194
4195       print_file_name_and_frills (f);
4196       pos += len;
4197     }
4198   putchar ('\n');
4199 }
4200
4201 /* Assuming cursor is at position FROM, indent up to position TO.
4202    Use a TAB character instead of two or more spaces whenever possible.  */
4203
4204 static void
4205 indent (size_t from, size_t to)
4206 {
4207   while (from < to)
4208     {
4209       if (tabsize != 0 && to / tabsize > (from + 1) / tabsize)
4210         {
4211           putchar ('\t');
4212           from += tabsize - from % tabsize;
4213         }
4214       else
4215         {
4216           putchar (' ');
4217           from++;
4218         }
4219     }
4220 }
4221
4222 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly.  */
4223 /* FIXME: maybe remove this function someday.  See about using a
4224    non-malloc'ing version of file_name_concat.  */
4225
4226 static void
4227 attach (char *dest, const char *dirname, const char *name)
4228 {
4229   const char *dirnamep = dirname;
4230
4231   /* Copy dirname if it is not ".".  */
4232   if (dirname[0] != '.' || dirname[1] != 0)
4233     {
4234       while (*dirnamep)
4235         *dest++ = *dirnamep++;
4236       /* Add '/' if `dirname' doesn't already end with it.  */
4237       if (dirnamep > dirname && dirnamep[-1] != '/')
4238         *dest++ = '/';
4239     }
4240   while (*name)
4241     *dest++ = *name++;
4242   *dest = 0;
4243 }
4244
4245 /* Allocate enough column info suitable for the current number of
4246    files and display columns, and initialize the info to represent the
4247    narrowest possible columns.  */
4248
4249 static void
4250 init_column_info (void)
4251 {
4252   size_t i;
4253   size_t max_cols = MIN (max_idx, cwd_n_used);
4254
4255   /* Currently allocated columns in column_info.  */
4256   static size_t column_info_alloc;
4257
4258   if (column_info_alloc < max_cols)
4259     {
4260       size_t new_column_info_alloc;
4261       size_t *p;
4262
4263       if (max_cols < max_idx / 2)
4264         {
4265           /* The number of columns is far less than the display width
4266              allows.  Grow the allocation, but only so that it's
4267              double the current requirements.  If the display is
4268              extremely wide, this avoids allocating a lot of memory
4269              that is never needed.  */
4270           column_info = xnrealloc (column_info, max_cols,
4271                                    2 * sizeof *column_info);
4272           new_column_info_alloc = 2 * max_cols;
4273         }
4274       else
4275         {
4276           column_info = xnrealloc (column_info, max_idx, sizeof *column_info);
4277           new_column_info_alloc = max_idx;
4278         }
4279
4280       /* Allocate the new size_t objects by computing the triangle
4281          formula n * (n + 1) / 2, except that we don't need to
4282          allocate the part of the triangle that we've already
4283          allocated.  Check for address arithmetic overflow.  */
4284       {
4285         size_t column_info_growth = new_column_info_alloc - column_info_alloc;
4286         size_t s = column_info_alloc + 1 + new_column_info_alloc;
4287         size_t t = s * column_info_growth;
4288         if (s < new_column_info_alloc || t / column_info_growth != s)
4289           xalloc_die ();
4290         p = xnmalloc (t / 2, sizeof *p);
4291       }
4292
4293       /* Grow the triangle by parceling out the cells just allocated.  */
4294       for (i = column_info_alloc; i < new_column_info_alloc; i++)
4295         {
4296           column_info[i].col_arr = p;
4297           p += i + 1;
4298         }
4299
4300       column_info_alloc = new_column_info_alloc;
4301     }
4302
4303   for (i = 0; i < max_cols; ++i)
4304     {
4305       size_t j;
4306
4307       column_info[i].valid_len = true;
4308       column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
4309       for (j = 0; j <= i; ++j)
4310         column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
4311     }
4312 }
4313
4314 /* Calculate the number of columns needed to represent the current set
4315    of files in the current display width.  */
4316
4317 static size_t
4318 calculate_columns (bool by_columns)
4319 {
4320   size_t filesno;               /* Index into cwd_file.  */
4321   size_t cols;                  /* Number of files across.  */
4322
4323   /* Normally the maximum number of columns is determined by the
4324      screen width.  But if few files are available this might limit it
4325      as well.  */
4326   size_t max_cols = MIN (max_idx, cwd_n_used);
4327
4328   init_column_info ();
4329
4330   /* Compute the maximum number of possible columns.  */
4331   for (filesno = 0; filesno < cwd_n_used; ++filesno)
4332     {
4333       struct fileinfo const *f = sorted_file[filesno];
4334       size_t name_length = length_of_file_name_and_frills (f);
4335       size_t i;
4336
4337       for (i = 0; i < max_cols; ++i)
4338         {
4339           if (column_info[i].valid_len)
4340             {
4341               size_t idx = (by_columns
4342                             ? filesno / ((cwd_n_used + i) / (i + 1))
4343                             : filesno % (i + 1));
4344               size_t real_length = name_length + (idx == i ? 0 : 2);
4345
4346               if (column_info[i].col_arr[idx] < real_length)
4347                 {
4348                   column_info[i].line_len += (real_length
4349                                               - column_info[i].col_arr[idx]);
4350                   column_info[i].col_arr[idx] = real_length;
4351                   column_info[i].valid_len = (column_info[i].line_len
4352                                               < line_length);
4353                 }
4354             }
4355         }
4356     }
4357
4358   /* Find maximum allowed columns.  */
4359   for (cols = max_cols; 1 < cols; --cols)
4360     {
4361       if (column_info[cols - 1].valid_len)
4362         break;
4363     }
4364
4365   return cols;
4366 }
4367
4368 void
4369 usage (int status)
4370 {
4371   if (status != EXIT_SUCCESS)
4372     fprintf (stderr, _("Try `%s --help' for more information.\n"),
4373              program_name);
4374   else
4375     {
4376       printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
4377       fputs (_("\
4378 List information about the FILEs (the current directory by default).\n\
4379 Sort entries alphabetically if none of -cftuvSUX nor --sort.\n\
4380 \n\
4381 "), stdout);
4382       fputs (_("\
4383 Mandatory arguments to long options are mandatory for short options too.\n\
4384 "), stdout);
4385       fputs (_("\
4386   -a, --all                  do not ignore entries starting with .\n\
4387   -A, --almost-all           do not list implied . and ..\n\
4388       --author               with -l, print the author of each file\n\
4389   -b, --escape               print octal escapes for nongraphic characters\n\
4390 "), stdout);
4391       fputs (_("\
4392       --block-size=SIZE      use SIZE-byte blocks\n\
4393   -B, --ignore-backups       do not list implied entries ending with ~\n\
4394   -c                         with -lt: sort by, and show, ctime (time of last\n\
4395                                modification of file status information)\n\
4396                                with -l: show ctime and sort by name\n\
4397                                otherwise: sort by ctime\n\
4398 "), stdout);
4399       fputs (_("\
4400   -C                         list entries by columns\n\
4401       --color[=WHEN]         control whether color is used to distinguish file\n\
4402                                types.  WHEN may be `never', `always', or `auto'\n\
4403   -d, --directory            list directory entries instead of contents,\n\
4404                                and do not dereference symbolic links\n\
4405   -D, --dired                generate output designed for Emacs' dired mode\n\
4406 "), stdout);
4407       fputs (_("\
4408   -f                         do not sort, enable -aU, disable -ls --color\n\
4409   -F, --classify             append indicator (one of */=>@|) to entries\n\
4410       --file-type            likewise, except do not append `*'\n\
4411       --format=WORD          across -x, commas -m, horizontal -x, long -l,\n\
4412                                single-column -1, verbose -l, vertical -C\n\
4413       --full-time            like -l --time-style=full-iso\n\
4414 "), stdout);
4415       fputs (_("\
4416   -g                         like -l, but do not list owner\n\
4417 "), stdout);
4418       fputs (_("\
4419       --group-directories-first\n\
4420                              group directories before files.\n\
4421                                augment with a --sort option, but any\n\
4422                                use of --sort=none (-U) disables grouping\n\
4423 "), stdout);
4424       fputs (_("\
4425   -G, --no-group             in a long listing, don't print group names\n\
4426   -h, --human-readable       with -l, print sizes in human readable format\n\
4427                                (e.g., 1K 234M 2G)\n\
4428       --si                   likewise, but use powers of 1000 not 1024\n\
4429 "), stdout);
4430       fputs (_("\
4431   -H, --dereference-command-line\n\
4432                              follow symbolic links listed on the command line\n\
4433       --dereference-command-line-symlink-to-dir\n\
4434                              follow each command line symbolic link\n\
4435                              that points to a directory\n\
4436       --hide=PATTERN         do not list implied entries matching shell PATTERN\n\
4437                                (overridden by -a or -A)\n\
4438 "), stdout);
4439       fputs (_("\
4440       --indicator-style=WORD  append indicator with style WORD to entry names:\n\
4441                                none (default), slash (-p),\n\
4442                                file-type (--file-type), classify (-F)\n\
4443   -i, --inode                print the index number of each file\n\
4444   -I, --ignore=PATTERN       do not list implied entries matching shell PATTERN\n\
4445   -k                         like --block-size=1K\n\
4446 "), stdout);
4447       fputs (_("\
4448   -l                         use a long listing format\n\
4449   -L, --dereference          when showing file information for a symbolic\n\
4450                                link, show information for the file the link\n\
4451                                references rather than for the link itself\n\
4452   -m                         fill width with a comma separated list of entries\n\
4453 "), stdout);
4454       fputs (_("\
4455   -n, --numeric-uid-gid      like -l, but list numeric user and group IDs\n\
4456   -N, --literal              print raw entry names (don't treat e.g. control\n\
4457                                characters specially)\n\
4458   -o                         like -l, but do not list group information\n\
4459   -p, --indicator-style=slash\n\
4460                              append / indicator to directories\n\
4461 "), stdout);
4462       fputs (_("\
4463   -q, --hide-control-chars   print ? instead of non graphic characters\n\
4464       --show-control-chars   show non graphic characters as-is (default\n\
4465                              unless program is `ls' and output is a terminal)\n\
4466   -Q, --quote-name           enclose entry names in double quotes\n\
4467       --quoting-style=WORD   use quoting style WORD for entry names:\n\
4468                                literal, locale, shell, shell-always, c, escape\n\
4469 "), stdout);
4470       fputs (_("\
4471   -r, --reverse              reverse order while sorting\n\
4472   -R, --recursive            list subdirectories recursively\n\
4473   -s, --size                 print the size of each file, in blocks\n\
4474 "), stdout);
4475       fputs (_("\
4476   -S                         sort by file size\n\
4477       --sort=WORD            sort by WORD instead of name: none -U,\n\
4478                              extension -X, size -S, time -t, version -v\n\
4479       --time=WORD            with -l, show time as WORD instead of modification\n\
4480                              time: atime -u, access -u, use -u, ctime -c,\n\
4481                              or status -c; use specified time as sort key\n\
4482                              if --sort=time\n\
4483 "), stdout);
4484       fputs (_("\
4485       --time-style=STYLE     with -l, show times using style STYLE:\n\
4486                              full-iso, long-iso, iso, locale, +FORMAT.\n\
4487                              FORMAT is interpreted like `date'; if FORMAT is\n\
4488                              FORMAT1<newline>FORMAT2, FORMAT1 applies to\n\
4489                              non-recent files and FORMAT2 to recent files;\n\
4490                              if STYLE is prefixed with `posix-', STYLE\n\
4491                              takes effect only outside the POSIX locale\n\
4492 "), stdout);
4493       fputs (_("\
4494   -t                         sort by modification time\n\
4495   -T, --tabsize=COLS         assume tab stops at each COLS instead of 8\n\
4496 "), stdout);
4497       fputs (_("\
4498   -u                         with -lt: sort by, and show, access time\n\
4499                                with -l: show access time and sort by name\n\
4500                                otherwise: sort by access time\n\
4501   -U                         do not sort; list entries in directory order\n\
4502   -v                         sort by version\n\
4503 "), stdout);
4504       fputs (_("\
4505   -w, --width=COLS           assume screen width instead of current value\n\
4506   -x                         list entries by lines instead of by columns\n\
4507   -X                         sort alphabetically by entry extension\n\
4508   -Z, --context              print any SELinux security context of each file\n\
4509   -1                         list one file per line\n\
4510 "), stdout);
4511       fputs (HELP_OPTION_DESCRIPTION, stdout);
4512       fputs (VERSION_OPTION_DESCRIPTION, stdout);
4513       fputs (_("\n\
4514 SIZE may be (or may be an integer optionally followed by) one of following:\n\
4515 kB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
4516 "), stdout);
4517       fputs (_("\
4518 \n\
4519 By default, color is not used to distinguish types of files.  That is\n\
4520 equivalent to using --color=none.  Using the --color option without the\n\
4521 optional WHEN argument is equivalent to using --color=always.  With\n\
4522 --color=auto, color codes are output only if standard output is connected\n\
4523 to a terminal (tty).  The environment variable LS_COLORS can influence the\n\
4524 colors, and can be set easily by the dircolors command.\n\
4525 "), stdout);
4526       fputs (_("\
4527 \n\
4528 Exit status is 0 if OK, 1 if minor problems, 2 if serious trouble.\n\
4529 "), stdout);
4530       emit_bug_reporting_address ();
4531     }
4532   exit (status);
4533 }