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