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