Avoid undefined behavior when strcoll fails,
[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-2002 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 #ifdef _AIX
40  #pragma alloca
41 #endif
42
43 #include <config.h>
44 #include <sys/types.h>
45
46 #if HAVE_INTTYPES_H
47 # include <inttypes.h>
48 #endif
49
50 #if HAVE_TERMIOS_H
51 # include <termios.h>
52 #endif
53
54 #ifdef GWINSZ_IN_SYS_IOCTL
55 # include <sys/ioctl.h>
56 #endif
57
58 #ifdef WINSIZE_IN_PTEM
59 # include <sys/stream.h>
60 # include <sys/ptem.h>
61 #endif
62
63 #if HAVE_SYS_ACL_H
64 # include <sys/acl.h>
65 #endif
66
67 #include <stdio.h>
68 #include <assert.h>
69 #include <setjmp.h>
70 #include <grp.h>
71 #include <pwd.h>
72 #include <getopt.h>
73
74 /* Get MB_CUR_MAX.  */
75 #if HAVE_STDLIB_H
76 # include <stdlib.h>
77 #endif
78
79 /* Get mbstate_t, mbrtowc(), mbsinit(), wcwidth().  */
80 #if HAVE_WCHAR_H
81 # include <wchar.h>
82 #endif
83
84 /* Get iswprint().  */
85 #if HAVE_WCTYPE_H
86 # include <wctype.h>
87 #endif
88 #if !defined iswprint && !HAVE_ISWPRINT
89 # define iswprint(wc) 1
90 #endif
91
92 #ifndef HAVE_DECL_WCWIDTH
93 "this configure-time declaration test was not run"
94 #endif
95 #if !HAVE_DECL_WCWIDTH
96 int wcwidth ();
97 #endif
98
99 /* If wcwidth() doesn't exist, assume all printable characters have
100    width 1.  */
101 #ifndef wcwidth
102 # if !HAVE_WCWIDTH
103 #  define wcwidth(wc) ((wc) == 0 ? 0 : iswprint (wc) ? 1 : -1)
104 # endif
105 #endif
106
107 #include "system.h"
108 #include <fnmatch.h>
109
110 #include "argmatch.h"
111 #include "dirname.h"
112 #include "dirfd.h"
113 #include "error.h"
114 #include "hard-locale.h"
115 #include "hash.h"
116 #include "human.h"
117 #include "filemode.h"
118 #include "ls.h"
119 #include "mbswidth.h"
120 #include "obstack.h"
121 #include "path-concat.h"
122 #include "quote.h"
123 #include "quotearg.h"
124 #include "same.h"
125 #include "strverscmp.h"
126 #include "xstrtol.h"
127 #include "xalloc.h"
128 #include "xreadlink.h"
129
130 /* Use access control lists only under all the following conditions.
131    Some systems (OSF4, Irix5, Irix6) have the acl function, but not
132    sys/acl.h or don't define the GETACLCNT macro.  */
133 #if HAVE_SYS_ACL_H && HAVE_ACL && defined GETACLCNT
134 # define USE_ACL 1
135 #endif
136
137 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
138                       : (ls_mode == LS_MULTI_COL \
139                          ? "dir" : "vdir"))
140
141 #define AUTHORS N_ ("Richard Stallman and David MacKenzie")
142
143 #define obstack_chunk_alloc malloc
144 #define obstack_chunk_free free
145
146 /* Return an int indicating the result of comparing two integers.
147    Subtracting doesn't always work, due to overflow.  */
148 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
149
150 /* The field width for inode numbers.  On some hosts inode numbers are
151    64 bits, so columns won't line up exactly when a huge inode number
152    is encountered, but in practice 7 digits is usually enough.  */
153 #ifndef INODE_DIGITS
154 # define INODE_DIGITS 7
155 #endif
156
157 #ifdef S_ISLNK
158 # define HAVE_SYMLINKS 1
159 #else
160 # define HAVE_SYMLINKS 0
161 #endif
162
163 /* If any of the S_* macros are undefined, define them here so each
164    use doesn't have to be guarded with e.g., #ifdef S_ISLNK.  */
165 #ifndef S_ISLNK
166 # define S_ISLNK(Mode) 0
167 #endif
168
169 #ifndef S_ISFIFO
170 # define S_ISFIFO(Mode) 0
171 #endif
172
173 #ifndef S_ISSOCK
174 # define S_ISSOCK(Mode) 0
175 #endif
176
177 #ifndef S_ISCHR
178 # define S_ISCHR(Mode) 0
179 #endif
180
181 #ifndef S_ISBLK
182 # define S_ISBLK(Mode) 0
183 #endif
184
185 #ifndef S_ISDOOR
186 # define S_ISDOOR(Mode) 0
187 #endif
188
189 /* Arrange to make lstat calls go through the wrapper function
190    on systems with an lstat function that does not dereference symlinks
191    that are specified with a trailing slash.  */
192 #if ! LSTAT_FOLLOWS_SLASHED_SYMLINK
193 int rpl_lstat PARAMS((const char *, struct stat *));
194 # undef lstat
195 # define lstat(Name, Stat_buf) rpl_lstat(Name, Stat_buf)
196 #endif
197
198 #if D_TYPE_IN_DIRENT && defined DTTOIF
199 # define HAVE_STRUCT_DIRENT_D_TYPE 1
200 # define DT_INIT(Val) = Val
201 #else
202 # define HAVE_STRUCT_DIRENT_D_TYPE 0
203 # define DT_INIT(Val) /* empty */
204 #endif
205
206 #ifdef ST_MTIM_NSEC
207 # define TIMESPEC_NS(timespec) ((timespec).ST_MTIM_NSEC)
208 #else
209 # define TIMESPEC_NS(timespec) 0
210 #endif
211
212 enum filetype
213   {
214     unknown DT_INIT (DT_UNKNOWN),
215     fifo DT_INIT (DT_FIFO),
216     chardev DT_INIT (DT_CHR),
217     directory DT_INIT (DT_DIR),
218     blockdev DT_INIT (DT_BLK),
219     normal DT_INIT (DT_REG),
220     symbolic_link DT_INIT (DT_LNK),
221     sock DT_INIT (DT_SOCK),
222     arg_directory DT_INIT (2 * (DT_UNKNOWN | DT_FIFO | DT_CHR | DT_DIR | DT_BLK
223                                 | DT_REG | DT_LNK | DT_SOCK))
224   };
225
226 struct fileinfo
227   {
228     /* The file name. */
229     char *name;
230
231     struct stat stat;
232
233     /* For symbolic link, name of the file linked to, otherwise zero. */
234     char *linkname;
235
236     /* For symbolic link and long listing, st_mode of file linked to, otherwise
237        zero. */
238     mode_t linkmode;
239
240     /* For symbolic link and color printing, 1 if linked-to file
241        exists, otherwise 0.  */
242     int linkok;
243
244     enum filetype filetype;
245
246 #if USE_ACL
247     /* For long listings, nonzero if the file has an access control list,
248        otherwise zero.  */
249     int have_acl;
250 #endif
251   };
252
253 #if USE_ACL
254 # define FILE_HAS_ACL(F) ((F)->have_acl)
255 #else
256 # define FILE_HAS_ACL(F) 0
257 #endif
258
259 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
260
261 /* Null is a valid character in a color indicator (think about Epson
262    printers, for example) so we have to use a length/buffer string
263    type.  */
264
265 struct bin_str
266   {
267     int len;                    /* Number of bytes */
268     const char *string;         /* Pointer to the same */
269   };
270
271 #ifndef STDC_HEADERS
272 time_t time ();
273 #endif
274
275 size_t nstrftime PARAMS ((char *, size_t, char const *,
276                           struct tm const *, int, int));
277 char *getgroup ();
278 char *getuser ();
279
280 static size_t quote_name PARAMS ((FILE *out, const char *name,
281                                   struct quoting_options const *options));
282 static char *make_link_path PARAMS ((const char *path, const char *linkname));
283 static int decode_switches PARAMS ((int argc, char **argv));
284 static int file_interesting PARAMS ((const struct dirent *next));
285 static uintmax_t gobble_file PARAMS ((const char *name, enum filetype type,
286                                       int explicit_arg, const char *dirname));
287 static void print_color_indicator PARAMS ((const char *name, mode_t mode,
288                                            int linkok));
289 static void put_indicator PARAMS ((const struct bin_str *ind));
290 static int length_of_file_name_and_frills PARAMS ((const struct fileinfo *f));
291 static void add_ignore_pattern PARAMS ((const char *pattern));
292 static void attach PARAMS ((char *dest, const char *dirname, const char *name));
293 static void clear_files PARAMS ((void));
294 static void extract_dirs_from_files PARAMS ((const char *dirname,
295                                              int ignore_dot_and_dot_dot));
296 static void get_link_name PARAMS ((const char *filename, struct fileinfo *f));
297 static void indent PARAMS ((int from, int to));
298 static void init_column_info PARAMS ((void));
299 static void print_current_files PARAMS ((void));
300 static void print_dir PARAMS ((const char *name, const char *realname));
301 static void print_file_name_and_frills PARAMS ((const struct fileinfo *f));
302 static void print_horizontal PARAMS ((void));
303 static void print_long_format PARAMS ((const struct fileinfo *f));
304 static void print_many_per_line PARAMS ((void));
305 static void print_name_with_quoting PARAMS ((const char *p, mode_t mode,
306                                              int linkok,
307                                              struct obstack *stack));
308 static void prep_non_filename_text PARAMS ((void));
309 static void print_type_indicator PARAMS ((mode_t mode));
310 static void print_with_commas PARAMS ((void));
311 static void queue_directory PARAMS ((const char *name, const char *realname));
312 static void sort_files PARAMS ((void));
313 static void parse_ls_color PARAMS ((void));
314 void usage PARAMS ((int status));
315
316 /* The name the program was run with, stripped of any leading path. */
317 char *program_name;
318
319 /* Initial size of hash table.
320    Most hierarchies are likely to be shallower than this.  */
321 #define INITIAL_TABLE_SIZE 30
322
323 /* The set of `active' directories, from the current command-line argument
324    to the level in the hierarchy at which files are being listed.
325    A directory is represented by its device and inode numbers.
326    A directory is added to this set when ls begins listing it or its
327    entries, and it is removed from the set just after ls has finished
328    processing it.  This set is used solely to detect loops, e.g., with
329    mkdir loop; cd loop; ln -s ../loop sub; ls -RL  */
330 static Hash_table *active_dir_set;
331
332 #define LOOP_DETECT (!!active_dir_set)
333
334 /* An entry in the active_dir_set.  */
335 struct dev_ino
336 {
337   dev_t st_dev;
338   ino_t st_ino;
339 };
340
341 /* The table of files in the current directory:
342
343    `files' points to a vector of `struct fileinfo', one per file.
344    `nfiles' is the number of elements space has been allocated for.
345    `files_index' is the number actually in use.  */
346
347 /* Address of block containing the files that are described.  */
348 static struct fileinfo *files;  /* FIXME: rename this to e.g. cwd_file */
349
350 /* Length of block that `files' points to, measured in files.  */
351 static int nfiles;  /* FIXME: rename this to e.g. cwd_n_alloc */
352
353 /* Index of first unused in `files'.  */
354 static int files_index;  /* FIXME: rename this to e.g. cwd_n_used */
355
356 /* When nonzero, in a color listing, color each symlink name according to the
357    type of file it points to.  Otherwise, color them according to the `ln'
358    directive in LS_COLORS.  Dangling (orphan) symlinks are treated specially,
359    regardless.  This is set when `ln=target' appears in LS_COLORS.  */
360
361 static int color_symlink_as_referent;
362
363 /* mode of appropriate file for colorization */
364 #define FILE_OR_LINK_MODE(File) \
365     ((color_symlink_as_referent && (File)->linkok) \
366      ? (File)->linkmode : (File)->stat.st_mode)
367
368
369 /* Record of one pending directory waiting to be listed.  */
370
371 struct pending
372   {
373     char *name;
374     /* If the directory is actually the file pointed to by a symbolic link we
375        were told to list, `realname' will contain the name of the symbolic
376        link, otherwise zero. */
377     char *realname;
378     struct pending *next;
379   };
380
381 static struct pending *pending_dirs;
382
383 /* Current time in seconds and nanoseconds since 1970, updated as
384    needed when deciding whether a file is recent.  */
385
386 static time_t current_time = TYPE_MINIMUM (time_t);
387 static int current_time_ns = -1;
388
389 /* The number of digits to use for block sizes.
390    4, or more if needed for bigger numbers.  */
391
392 static int block_size_size;
393
394 /* Option flags */
395
396 /* long_format for lots of info, one per line.
397    one_per_line for just names, one per line.
398    many_per_line for just names, many per line, sorted vertically.
399    horizontal for just names, many per line, sorted horizontally.
400    with_commas for just names, many per line, separated by commas.
401
402    -l (and other options that imply -l), -1, -C, -x and -m control
403    this parameter.  */
404
405 enum format
406   {
407     long_format,                /* -l and other options that imply -l */
408     one_per_line,               /* -1 */
409     many_per_line,              /* -C */
410     horizontal,                 /* -x */
411     with_commas                 /* -m */
412   };
413
414 static enum format format;
415
416 /* `full-iso' uses full ISO-style dates and times.  `iso' uses shorter
417    ISO-style time stamps.  `locale' uses locale-dependent time stamps.
418    `posix-iso' uses traditional POSIX-locale-style dates where
419    POSIX requires it, ISO-style dates otherwise.  */
420 enum time_style
421   {
422     full_iso_time_style,        /* --time-style=full-iso */
423     iso_time_style,             /* --time-style=iso */
424     locale_time_style,          /* --time-style=locale */
425     posix_iso_time_style        /* --time-style=posix-iso (default) */
426   };
427
428 static char const *const time_style_args[] =
429 {
430   "full-iso", "iso", "locale", "posix-iso", 0
431 };
432
433 static enum time_style const time_style_types[] =
434 {
435   full_iso_time_style, iso_time_style,
436   locale_time_style, posix_iso_time_style, 0
437 };
438
439 /* Type of time to print or sort by.  Controlled by -c and -u.  */
440
441 enum time_type
442   {
443     time_mtime,                 /* default */
444     time_ctime,                 /* -c */
445     time_atime                  /* -u */
446   };
447
448 static enum time_type time_type;
449
450 /* The file characteristic to sort by.  Controlled by -t, -S, -U, -X, -v. */
451
452 enum sort_type
453   {
454     sort_none,                  /* -U */
455     sort_name,                  /* default */
456     sort_extension,             /* -X */
457     sort_time,                  /* -t */
458     sort_size,                  /* -S */
459     sort_version                /* -v */
460   };
461
462 static enum sort_type sort_type;
463
464 /* Direction of sort.
465    0 means highest first if numeric,
466    lowest first if alphabetic;
467    these are the defaults.
468    1 means the opposite order in each case.  -r  */
469
470 static int sort_reverse;
471
472 /* Nonzero means to display owner information.  -g turns this off.  */
473
474 static int print_owner = 1;
475
476 /* Nonzero means to display group information.  -G and -o turn this off.  */
477
478 static int print_group = 1;
479
480 /* Nonzero means print the user and group id's as numbers rather
481    than as names.  -n  */
482
483 static int numeric_ids;
484
485 /* Nonzero means mention the size in blocks of each file.  -s  */
486
487 static int print_block_size;
488
489 /* If positive, the units to use when printing sizes;
490    if negative, the human-readable base.  */
491 static int output_block_size;
492
493 /* Precede each line of long output (per file) with a string like `m,n:'
494    where M is the number of characters after the `:' and before the
495    filename and N is the length of the filename.  Using this format,
496    Emacs' dired mode starts up twice as fast, and can handle all
497    strange characters in file names.  */
498 static int dired;
499
500 /* `none' means don't mention the type of files.
501    `classify' means mention file types and mark executables.
502    `file_type' means mention only file types.
503
504    Controlled by -F, -p, and --indicator-style.  */
505
506 enum indicator_style
507   {
508     none,       /*     --indicator-style=none */
509     classify,   /* -F, --indicator-style=classify */
510     file_type   /* -p, --indicator-style=file-type */
511   };
512
513 static enum indicator_style indicator_style;
514
515 /* Names of indicator styles.  */
516 static char const *const indicator_style_args[] =
517 {
518   "none", "classify", "file-type", 0
519 };
520
521 static enum indicator_style const indicator_style_types[]=
522 {
523   none, classify, file_type
524 };
525
526 /* Nonzero means use colors to mark types.  Also define the different
527    colors as well as the stuff for the LS_COLORS environment variable.
528    The LS_COLORS variable is now in a termcap-like format.  */
529
530 static int print_with_color;
531
532 enum color_type
533   {
534     color_never,                /* 0: default or --color=never */
535     color_always,               /* 1: --color=always */
536     color_if_tty                /* 2: --color=tty */
537   };
538
539 enum Dereference_symlink
540   {
541     DEREF_UNDEFINED = 1,
542     DEREF_NEVER,
543     DEREF_COMMAND_LINE_ARGUMENTS,       /* -H */
544     DEREF_ALWAYS                        /* -L */
545   };
546
547 enum indicator_no
548   {
549     C_LEFT, C_RIGHT, C_END, C_NORM, C_FILE, C_DIR, C_LINK, C_FIFO, C_SOCK,
550     C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR
551   };
552
553 static const char *const indicator_name[]=
554   {
555     "lc", "rc", "ec", "no", "fi", "di", "ln", "pi", "so",
556     "bd", "cd", "mi", "or", "ex", "do", NULL
557   };
558
559 struct color_ext_type
560   {
561     struct bin_str ext;         /* The extension we're looking for */
562     struct bin_str seq;         /* The sequence to output when we do */
563     struct color_ext_type *next;        /* Next in list */
564   };
565
566 static struct bin_str color_indicator[] =
567   {
568     { LEN_STR_PAIR ("\033[") },         /* lc: Left of color sequence */
569     { LEN_STR_PAIR ("m") },             /* rc: Right of color sequence */
570     { 0, NULL },                        /* ec: End color (replaces lc+no+rc) */
571     { LEN_STR_PAIR ("0") },             /* no: Normal */
572     { LEN_STR_PAIR ("0") },             /* fi: File: default */
573     { LEN_STR_PAIR ("01;34") },         /* di: Directory: bright blue */
574     { LEN_STR_PAIR ("01;36") },         /* ln: Symlink: bright cyan */
575     { LEN_STR_PAIR ("33") },            /* pi: Pipe: yellow/brown */
576     { LEN_STR_PAIR ("01;35") },         /* so: Socket: bright magenta */
577     { LEN_STR_PAIR ("01;33") },         /* bd: Block device: bright yellow */
578     { LEN_STR_PAIR ("01;33") },         /* cd: Char device: bright yellow */
579     { 0, NULL },                        /* mi: Missing file: undefined */
580     { 0, NULL },                        /* or: Orphanned symlink: undefined */
581     { LEN_STR_PAIR ("01;32") },         /* ex: Executable: bright green */
582     { LEN_STR_PAIR ("01;35") }          /* do: Door: bright magenta */
583   };
584
585 /* FIXME: comment  */
586 static struct color_ext_type *color_ext_list = NULL;
587
588 /* Buffer for color sequences */
589 static char *color_buf;
590
591 /* Nonzero means to check for orphaned symbolic link, for displaying
592    colors.  */
593
594 static int check_symlink_color;
595
596 /* Nonzero means mention the inode number of each file.  -i  */
597
598 static int print_inode;
599
600 /* What to do with symbolic links.  Affected by -d, -F, -H, -l (and
601    other options that imply -l), and -L.  */
602
603 static enum Dereference_symlink dereference;
604
605 /* Nonzero means when a directory is found, display info on its
606    contents.  -R  */
607
608 static int recursive;
609
610 /* Nonzero means when an argument is a directory name, display info
611    on it itself.  -d  */
612
613 static int immediate_dirs;
614
615 /* Nonzero means don't omit files whose names start with `.'.  -A */
616
617 static int all_files;
618
619 /* Nonzero means don't omit files `.' and `..'
620    This flag implies `all_files'.  -a  */
621
622 static int really_all_files;
623
624 /* A linked list of shell-style globbing patterns.  If a non-argument
625    file name matches any of these patterns, it is omitted.
626    Controlled by -I.  Multiple -I options accumulate.
627    The -B option adds `*~' and `.*~' to this list.  */
628
629 struct ignore_pattern
630   {
631     const char *pattern;
632     struct ignore_pattern *next;
633   };
634
635 static struct ignore_pattern *ignore_patterns;
636
637 /* Nonzero means output nongraphic chars in file names as `?'.
638    (-q, --hide-control-chars)
639    qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
640    independent.  The algorithm is: first, obey the quoting style to get a
641    string representing the file name;  then, if qmark_funny_chars is set,
642    replace all nonprintable chars in that string with `?'.  It's necessary
643    to replace nonprintable chars even in quoted strings, because we don't
644    want to mess up the terminal if control chars get sent to it, and some
645    quoting methods pass through control chars as-is.  */
646 static int qmark_funny_chars;
647
648 /* Quoting options for file and dir name output.  */
649
650 static struct quoting_options *filename_quoting_options;
651 static struct quoting_options *dirname_quoting_options;
652
653 /* The number of chars per hardware tab stop.  Setting this to zero
654    inhibits the use of TAB characters for separating columns.  -T */
655 static int tabsize;
656
657 /* Nonzero means we are listing the working directory because no
658    non-option arguments were given. */
659
660 static int dir_defaulted;
661
662 /* Nonzero means print each directory name before listing it. */
663
664 static int print_dir_name;
665
666 /* The line length to use for breaking lines in many-per-line format.
667    Can be set with -w.  */
668
669 static int line_length;
670
671 /* If nonzero, the file listing format requires that stat be called on
672    each file. */
673
674 static int format_needs_stat;
675
676 /* Similar to `format_needs_stat', but set if only the file type is
677    needed.  */
678
679 static int format_needs_type;
680
681 /* strftime formats for non-recent and recent files, respectively, in
682    -l output.  */
683
684 static char const *long_time_format[2] =
685   {
686     /* strftime format for non-recent files (older than 6 months), in
687        -l output when --time-style=locale is specified.  This should
688        contain the year, month and day (at least), in an order that is
689        understood by people in your locale's territory.
690        Please try to keep the number of used screen columns small,
691        because many people work in windows with only 80 columns.  But
692        make this as wide as the other string below, for recent files.  */
693     N_("%b %e  %Y"),
694     /* strftime format for recent files (younger than 6 months), in
695        -l output when --time-style=locale is specified.  This should
696        contain the month, day and time (at least), in an order that is
697        understood by people in your locale's territory.
698        Please try to keep the number of used screen columns small,
699        because many people work in windows with only 80 columns.  But
700        make this as wide as the other string above, for non-recent files.  */
701     N_("%b %e %H:%M")
702   };
703
704 /* The exit status to use if we don't get any fatal errors. */
705
706 static int exit_status;
707
708 /* For long options that have no equivalent short option, use a
709    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
710 enum
711 {
712   BLOCK_SIZE_OPTION = CHAR_MAX + 1,
713   COLOR_OPTION,
714   FORMAT_OPTION,
715   FULL_TIME_OPTION,
716   INDICATOR_STYLE_OPTION,
717   QUOTING_STYLE_OPTION,
718   SHOW_CONTROL_CHARS_OPTION,
719   SI_OPTION,
720   SORT_OPTION,
721   TIME_OPTION,
722   TIME_STYLE_OPTION
723 };
724
725 static struct option const long_options[] =
726 {
727   {"all", no_argument, 0, 'a'},
728   {"escape", no_argument, 0, 'b'},
729   {"directory", no_argument, 0, 'd'},
730   {"dired", no_argument, 0, 'D'},
731   {"full-time", no_argument, 0, FULL_TIME_OPTION},
732   {"human-readable", no_argument, 0, 'h'},
733   {"inode", no_argument, 0, 'i'},
734   {"kilobytes", no_argument, 0, 'k'}, /* long form is obsolescent */
735   {"numeric-uid-gid", no_argument, 0, 'n'},
736   {"no-group", no_argument, 0, 'G'},
737   {"hide-control-chars", no_argument, 0, 'q'},
738   {"reverse", no_argument, 0, 'r'},
739   {"size", no_argument, 0, 's'},
740   {"width", required_argument, 0, 'w'},
741   {"almost-all", no_argument, 0, 'A'},
742   {"ignore-backups", no_argument, 0, 'B'},
743   {"classify", no_argument, 0, 'F'},
744   {"file-type", no_argument, 0, 'p'},
745   {"si", no_argument, 0, SI_OPTION},
746   {"dereference-command-line", no_argument, 0, 'H'},
747   {"ignore", required_argument, 0, 'I'},
748   {"indicator-style", required_argument, 0, INDICATOR_STYLE_OPTION},
749   {"dereference", no_argument, 0, 'L'},
750   {"literal", no_argument, 0, 'N'},
751   {"quote-name", no_argument, 0, 'Q'},
752   {"quoting-style", required_argument, 0, QUOTING_STYLE_OPTION},
753   {"recursive", no_argument, 0, 'R'},
754   {"format", required_argument, 0, FORMAT_OPTION},
755   {"show-control-chars", no_argument, 0, SHOW_CONTROL_CHARS_OPTION},
756   {"sort", required_argument, 0, SORT_OPTION},
757   {"tabsize", required_argument, 0, 'T'},
758   {"time", required_argument, 0, TIME_OPTION},
759   {"time-style", required_argument, 0, TIME_STYLE_OPTION},
760   {"color", optional_argument, 0, COLOR_OPTION},
761   {"block-size", required_argument, 0, BLOCK_SIZE_OPTION},
762   {GETOPT_HELP_OPTION_DECL},
763   {GETOPT_VERSION_OPTION_DECL},
764   {NULL, 0, NULL, 0}
765 };
766
767 static char const *const format_args[] =
768 {
769   "verbose", "long", "commas", "horizontal", "across",
770   "vertical", "single-column", 0
771 };
772
773 static enum format const format_types[] =
774 {
775   long_format, long_format, with_commas, horizontal, horizontal,
776   many_per_line, one_per_line
777 };
778
779 static char const *const sort_args[] =
780 {
781   "none", "time", "size", "extension", "version", 0
782 };
783
784 static enum sort_type const sort_types[] =
785 {
786   sort_none, sort_time, sort_size, sort_extension, sort_version
787 };
788
789 static char const *const time_args[] =
790 {
791   "atime", "access", "use", "ctime", "status", 0
792 };
793
794 static enum time_type const time_types[] =
795 {
796   time_atime, time_atime, time_atime, time_ctime, time_ctime
797 };
798
799 static char const *const color_args[] =
800 {
801   /* force and none are for compatibility with another color-ls version */
802   "always", "yes", "force",
803   "never", "no", "none",
804   "auto", "tty", "if-tty", 0
805 };
806
807 static enum color_type const color_types[] =
808 {
809   color_always, color_always, color_always,
810   color_never, color_never, color_never,
811   color_if_tty, color_if_tty, color_if_tty
812 };
813
814 /* Information about filling a column.  */
815 struct column_info
816 {
817   int valid_len;
818   int line_len;
819   int *col_arr;
820 };
821
822 /* Array with information about column filledness.  */
823 static struct column_info *column_info;
824
825 /* Maximum number of columns ever possible for this display.  */
826 static int max_idx;
827
828 /* The minimum width of a colum is 3: 1 character for the name and 2
829    for the separating white space.  */
830 #define MIN_COLUMN_WIDTH        3
831
832
833 /* This zero-based index is used solely with the --dired option.
834    When that option is in effect, this counter is incremented for each
835    character of output generated by this program so that the beginning
836    and ending indices (in that output) of every file name can be recorded
837    and later output themselves.  */
838 static size_t dired_pos;
839
840 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
841
842 /* Write S to STREAM and increment DIRED_POS by S_LEN.  */
843 #define DIRED_FPUTS(s, stream, s_len) \
844     do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
845
846 /* Like DIRED_FPUTS, but for use when S is a literal string.  */
847 #define DIRED_FPUTS_LITERAL(s, stream) \
848     do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
849
850 #define DIRED_INDENT()                                                  \
851     do                                                                  \
852       {                                                                 \
853         /* FIXME: remove the `&& format == long_format' clause.  */     \
854         if (dired && format == long_format)                             \
855           DIRED_FPUTS_LITERAL ("  ", stdout);                           \
856       }                                                                 \
857     while (0)
858
859 /* With --dired, store pairs of beginning and ending indices of filenames.  */
860 static struct obstack dired_obstack;
861
862 /* With --dired, store pairs of beginning and ending indices of any
863    directory names that appear as headers (just before `total' line)
864    for lists of directory entries.  Such directory names are seen when
865    listing hierarchies using -R and when a directory is listed with at
866    least one other command line argument.  */
867 static struct obstack subdired_obstack;
868
869 /* Save the current index on the specified obstack, OBS.  */
870 #define PUSH_CURRENT_DIRED_POS(obs)                                     \
871   do                                                                    \
872     {                                                                   \
873       /* FIXME: remove the `&& format == long_format' clause.  */       \
874       if (dired && format == long_format)                               \
875         obstack_grow ((obs), &dired_pos, sizeof (dired_pos));           \
876     }                                                                   \
877   while (0)
878
879 /* With -R, this stack is used to help detect directory cycles.
880    The device/inode pairs on this stack mirror the pairs in the
881    active_dir_set hash table.  */
882 static struct obstack dev_ino_obstack;
883
884 /* Push a pair onto the device/inode stack.  */
885 #define DEV_INO_PUSH(Dev, Ino)                                          \
886   do                                                                    \
887     {                                                                   \
888       struct dev_ino *di;                                               \
889       obstack_blank (&dev_ino_obstack, sizeof (struct dev_ino));        \
890       di = -1 + (struct dev_ino *) obstack_next_free (&dev_ino_obstack); \
891       di->st_dev = (Dev);                                               \
892       di->st_ino = (Ino);                                               \
893     }                                                                   \
894   while (0)
895
896 /* Pop a dev/ino struct off the global dev_ino_obstack
897    and return that struct.  */
898 static struct dev_ino
899 dev_ino_pop (void)
900 {
901   assert (sizeof (struct dev_ino) <= obstack_object_size (&dev_ino_obstack));
902   obstack_blank (&dev_ino_obstack, -(int) (sizeof (struct dev_ino)));
903   return *(struct dev_ino*) obstack_next_free (&dev_ino_obstack);
904 }
905
906 #define ASSERT_MATCHING_DEV_INO(Name, Di)       \
907   do                                            \
908     {                                           \
909       struct stat sb;                           \
910       assert (Name);                            \
911       assert (0 <= stat (Name, &sb));           \
912       assert (sb.st_dev == Di.st_dev);          \
913       assert (sb.st_ino == Di.st_ino);          \
914     }                                           \
915   while (0)
916
917
918 /* Write to standard output PREFIX, followed by the quoting style and
919    a space-separated list of the integers stored in OS all on one line.  */
920
921 static void
922 dired_dump_obstack (const char *prefix, struct obstack *os)
923 {
924   int n_pos;
925
926   n_pos = obstack_object_size (os) / sizeof (dired_pos);
927   if (n_pos > 0)
928     {
929       int i;
930       size_t *pos;
931
932       pos = (size_t *) obstack_finish (os);
933       fputs (prefix, stdout);
934       for (i = 0; i < n_pos; i++)
935         printf (" %lu", (unsigned long) pos[i]);
936       fputs ("\n", stdout);
937     }
938 }
939
940 static unsigned int
941 dev_ino_hash (void const *x, unsigned int table_size)
942 {
943   struct dev_ino const *p = x;
944   return (uintmax_t) p->st_ino % table_size;
945 }
946
947 static bool
948 dev_ino_compare (void const *x, void const *y)
949 {
950   struct dev_ino const *a = x;
951   struct dev_ino const *b = y;
952   return SAME_INODE (*a, *b) ? true : false;
953 }
954
955 static void
956 dev_ino_free (void *x)
957 {
958   free (x);
959 }
960
961 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
962    active directories.  Return nonzero if there is already a matching
963    entry in the table.  Otherwise, return zero.  */
964
965 static int
966 visit_dir (dev_t dev, ino_t ino)
967 {
968   struct dev_ino *ent;
969   struct dev_ino *ent_from_table;
970   int found_match;
971
972   ent = XMALLOC (struct dev_ino, 1);
973   ent->st_ino = ino;
974   ent->st_dev = dev;
975
976   /* Attempt to insert this entry into the table.  */
977   ent_from_table = hash_insert (active_dir_set, ent);
978
979   if (ent_from_table == NULL)
980     {
981       /* Insertion failed due to lack of memory.  */
982       xalloc_die ();
983     }
984
985   found_match = (ent_from_table != ent);
986
987   if (found_match)
988     {
989       /* ent was not inserted, so free it.  */
990       free (ent);
991     }
992
993   return found_match;
994 }
995
996 static void
997 free_pending_ent (struct pending *p)
998 {
999   if (p->name)
1000     free (p->name);
1001   if (p->realname)
1002     free (p->realname);
1003   free (p);
1004 }
1005
1006 int
1007 main (int argc, char **argv)
1008 {
1009   register int i;
1010   register struct pending *thispend;
1011   unsigned int n_files;
1012
1013   program_name = argv[0];
1014   setlocale (LC_ALL, "");
1015   bindtextdomain (PACKAGE, LOCALEDIR);
1016   textdomain (PACKAGE);
1017
1018   atexit (close_stdout);
1019
1020 #define N_ENTRIES(Array) (sizeof Array / sizeof *(Array))
1021   assert (N_ENTRIES (color_indicator) + 1 == N_ENTRIES (indicator_name));
1022
1023   exit_status = 0;
1024   dir_defaulted = 1;
1025   print_dir_name = 1;
1026   pending_dirs = 0;
1027
1028   i = decode_switches (argc, argv);
1029
1030   if (print_with_color)
1031     parse_ls_color ();
1032
1033   /* Test print_with_color again, because the call to parse_ls_color
1034      may have just reset it -- e.g., if LS_COLORS is invalid.  */
1035   if (print_with_color)
1036     {
1037       prep_non_filename_text ();
1038       /* Avoid following symbolic links when possible.  */
1039       if (color_indicator[C_ORPHAN].string != NULL
1040           || (color_indicator[C_MISSING].string != NULL
1041               && format == long_format))
1042         check_symlink_color = 1;
1043     }
1044
1045   if (dereference == DEREF_UNDEFINED)
1046     dereference = ((immediate_dirs
1047                     || indicator_style == classify
1048                     || format == long_format)
1049                    ? DEREF_NEVER
1050                    : DEREF_COMMAND_LINE_ARGUMENTS);
1051
1052   /* When using -R, initialize a data structure we'll use to
1053      detect any directory cycles.  */
1054   if (recursive)
1055     {
1056       active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, NULL,
1057                                         dev_ino_hash,
1058                                         dev_ino_compare,
1059                                         dev_ino_free);
1060       if (active_dir_set == NULL)
1061         xalloc_die ();
1062
1063       obstack_init (&dev_ino_obstack);
1064     }
1065
1066   format_needs_stat = sort_type == sort_time || sort_type == sort_size
1067     || format == long_format
1068     || dereference == DEREF_ALWAYS
1069     || recursive || print_block_size || print_inode;
1070   format_needs_type = (format_needs_stat == 0
1071                        && (print_with_color || indicator_style != none));
1072
1073   if (dired && format == long_format)
1074     {
1075       obstack_init (&dired_obstack);
1076       obstack_init (&subdired_obstack);
1077     }
1078
1079   nfiles = 100;
1080   files = XMALLOC (struct fileinfo, nfiles);
1081   files_index = 0;
1082
1083   clear_files ();
1084
1085   n_files = argc - i;
1086   if (0 < n_files)
1087     dir_defaulted = 0;
1088
1089   for (; i < argc; i++)
1090     {
1091       gobble_file (argv[i], unknown, 1, "");
1092     }
1093
1094   if (dir_defaulted)
1095     {
1096       if (immediate_dirs)
1097         gobble_file (".", directory, 1, "");
1098       else
1099         queue_directory (".", 0);
1100     }
1101
1102   if (files_index)
1103     {
1104       sort_files ();
1105       if (!immediate_dirs)
1106         extract_dirs_from_files ("", 0);
1107       /* `files_index' might be zero now.  */
1108     }
1109
1110   /* In the following if/else blocks, it is sufficient to test `pending_dirs'
1111      (and not pending_dirs->name) because there may be no markers in the queue
1112      at this point.  A marker may be enqueued when extract_dirs_from_files is
1113      called with a non-empty string or via print_dir.  */
1114   if (files_index)
1115     {
1116       print_current_files ();
1117       if (pending_dirs)
1118         DIRED_PUTCHAR ('\n');
1119     }
1120   else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1121     print_dir_name = 0;
1122
1123   while (pending_dirs)
1124     {
1125       thispend = pending_dirs;
1126       pending_dirs = pending_dirs->next;
1127
1128       if (LOOP_DETECT)
1129         {
1130           if (thispend->name == NULL)
1131             {
1132               /* thispend->name == NULL means this is a marker entry
1133                  indicating we've finished processing the directory.
1134                  Use its dev/ino numbers to remove the corresponding
1135                  entry from the active_dir_set hash table.  */
1136               struct dev_ino di = dev_ino_pop ();
1137               struct dev_ino *found = hash_delete (active_dir_set, &di);
1138               /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
1139               assert (found);
1140               dev_ino_free (found);
1141               free_pending_ent (thispend);
1142               continue;
1143             }
1144         }
1145
1146       print_dir (thispend->name, thispend->realname);
1147
1148       free_pending_ent (thispend);
1149       print_dir_name = 1;
1150     }
1151
1152   if (dired && format == long_format)
1153     {
1154       /* No need to free these since we're about to exit.  */
1155       dired_dump_obstack ("//DIRED//", &dired_obstack);
1156       dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1157       printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1158               quoting_style_args[get_quoting_style (filename_quoting_options)]);
1159     }
1160
1161   /* Restore default color before exiting */
1162   if (print_with_color)
1163     {
1164       put_indicator (&color_indicator[C_LEFT]);
1165       put_indicator (&color_indicator[C_RIGHT]);
1166     }
1167
1168   if (LOOP_DETECT)
1169     {
1170       assert (hash_get_n_entries (active_dir_set) == 0);
1171       hash_free (active_dir_set);
1172     }
1173
1174   exit (exit_status);
1175 }
1176
1177 /* Set all the option flags according to the switches specified.
1178    Return the index of the first non-option argument.  */
1179
1180 static int
1181 decode_switches (int argc, char **argv)
1182 {
1183   int c;
1184   char const *time_style_option = 0;
1185
1186   /* Record whether there is an option specifying sort type.  */
1187   int sort_type_specified = 0;
1188
1189   qmark_funny_chars = 0;
1190
1191   /* initialize all switches to default settings */
1192
1193   switch (ls_mode)
1194     {
1195     case LS_MULTI_COL:
1196       /* This is for the `dir' program.  */
1197       format = many_per_line;
1198       set_quoting_style (NULL, escape_quoting_style);
1199       break;
1200
1201     case LS_LONG_FORMAT:
1202       /* This is for the `vdir' program.  */
1203       format = long_format;
1204       set_quoting_style (NULL, escape_quoting_style);
1205       break;
1206
1207     case LS_LS:
1208       /* This is for the `ls' program.  */
1209       if (isatty (STDOUT_FILENO))
1210         {
1211           format = many_per_line;
1212           /* See description of qmark_funny_chars, above.  */
1213           qmark_funny_chars = 1;
1214         }
1215       else
1216         {
1217           format = one_per_line;
1218           qmark_funny_chars = 0;
1219         }
1220       break;
1221
1222     default:
1223       abort ();
1224     }
1225
1226   time_type = time_mtime;
1227   sort_type = sort_name;
1228   sort_reverse = 0;
1229   numeric_ids = 0;
1230   print_block_size = 0;
1231   indicator_style = none;
1232   print_inode = 0;
1233   dereference = DEREF_UNDEFINED;
1234   recursive = 0;
1235   immediate_dirs = 0;
1236   all_files = 0;
1237   really_all_files = 0;
1238   ignore_patterns = 0;
1239
1240   /* FIXME: put this in a function.  */
1241   {
1242     char const *q_style = getenv ("QUOTING_STYLE");
1243     if (q_style)
1244       {
1245         int i = ARGCASEMATCH (q_style, quoting_style_args, quoting_style_vals);
1246         if (0 <= i)
1247           set_quoting_style (NULL, quoting_style_vals[i]);
1248         else
1249           error (0, 0,
1250          _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
1251                  quotearg (q_style));
1252       }
1253   }
1254
1255   human_block_size (getenv ("LS_BLOCK_SIZE"), 0, &output_block_size);
1256
1257   line_length = 80;
1258   {
1259     char const *p = getenv ("COLUMNS");
1260     if (p && *p)
1261       {
1262         long int tmp_long;
1263         if (xstrtol (p, NULL, 0, &tmp_long, NULL) == LONGINT_OK
1264             && 0 < tmp_long && tmp_long <= INT_MAX)
1265           {
1266             line_length = (int) tmp_long;
1267           }
1268         else
1269           {
1270             error (0, 0,
1271                _("ignoring invalid width in environment variable COLUMNS: %s"),
1272                    quotearg (p));
1273           }
1274       }
1275   }
1276
1277 #ifdef TIOCGWINSZ
1278   {
1279     struct winsize ws;
1280
1281     if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1 && ws.ws_col != 0)
1282       line_length = ws.ws_col;
1283   }
1284 #endif
1285
1286   /* Using the TABSIZE environment variable is not POSIX-approved.
1287      Ignore it when POSIXLY_CORRECT is set.  */
1288   {
1289     char const *p;
1290     tabsize = 8;
1291     if (!getenv ("POSIXLY_CORRECT") && (p = getenv ("TABSIZE")))
1292       {
1293         long int tmp_long;
1294         if (xstrtol (p, NULL, 0, &tmp_long, NULL) == LONGINT_OK
1295             && 0 <= tmp_long && tmp_long <= INT_MAX)
1296           {
1297             tabsize = (int) tmp_long;
1298           }
1299         else
1300           {
1301             error (0, 0,
1302              _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1303                    quotearg (p));
1304           }
1305       }
1306   }
1307
1308   while ((c = getopt_long (argc, argv,
1309                            "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UX1",
1310                            long_options, NULL)) != -1)
1311     {
1312       switch (c)
1313         {
1314         case 0:
1315           break;
1316
1317         case 'a':
1318           all_files = 1;
1319           really_all_files = 1;
1320           break;
1321
1322         case 'b':
1323           set_quoting_style (NULL, escape_quoting_style);
1324           break;
1325
1326         case 'c':
1327           time_type = time_ctime;
1328           break;
1329
1330         case 'd':
1331           immediate_dirs = 1;
1332           break;
1333
1334         case 'f':
1335           /* Same as enabling -a -U and disabling -l -s.  */
1336           all_files = 1;
1337           really_all_files = 1;
1338           sort_type = sort_none;
1339           sort_type_specified = 1;
1340           /* disable -l */
1341           if (format == long_format)
1342             format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
1343           print_block_size = 0; /* disable -s */
1344           print_with_color = 0; /* disable --color */
1345           break;
1346
1347         case 'g':
1348           format = long_format;
1349           print_owner = 0;
1350           break;
1351
1352         case 'h':
1353           output_block_size = -1024;
1354           break;
1355
1356         case 'i':
1357           print_inode = 1;
1358           break;
1359
1360         case 'k':
1361           output_block_size = 1024;
1362           break;
1363
1364         case 'l':
1365           format = long_format;
1366           break;
1367
1368         case 'm':
1369           format = with_commas;
1370           break;
1371
1372         case 'n':
1373           numeric_ids = 1;
1374           format = long_format;
1375           break;
1376
1377         case 'o':  /* Just like -l, but don't display group info.  */
1378           format = long_format;
1379           print_group = 0;
1380           break;
1381
1382         case 'p':
1383           indicator_style = file_type;
1384           break;
1385
1386         case 'q':
1387           qmark_funny_chars = 1;
1388           break;
1389
1390         case 'r':
1391           sort_reverse = 1;
1392           break;
1393
1394         case 's':
1395           print_block_size = 1;
1396           break;
1397
1398         case 't':
1399           sort_type = sort_time;
1400           sort_type_specified = 1;
1401           break;
1402
1403         case 'u':
1404           time_type = time_atime;
1405           break;
1406
1407         case 'v':
1408           sort_type = sort_version;
1409           sort_type_specified = 1;
1410           break;
1411
1412         case 'w':
1413           {
1414             long int tmp_long;
1415             if (xstrtol (optarg, NULL, 0, &tmp_long, NULL) != LONGINT_OK
1416                 || tmp_long <= 0 || tmp_long > INT_MAX)
1417               error (EXIT_FAILURE, 0, _("invalid line width: %s"),
1418                      quotearg (optarg));
1419             line_length = (int) tmp_long;
1420             break;
1421           }
1422
1423         case 'x':
1424           format = horizontal;
1425           break;
1426
1427         case 'A':
1428           really_all_files = 0;
1429           all_files = 1;
1430           break;
1431
1432         case 'B':
1433           add_ignore_pattern ("*~");
1434           add_ignore_pattern (".*~");
1435           break;
1436
1437         case 'C':
1438           format = many_per_line;
1439           break;
1440
1441         case 'D':
1442           dired = 1;
1443           break;
1444
1445         case 'F':
1446           indicator_style = classify;
1447           break;
1448
1449         case 'G':               /* inhibit display of group info */
1450           print_group = 0;
1451           break;
1452
1453         case 'H':
1454           dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1455           break;
1456
1457         case 'I':
1458           add_ignore_pattern (optarg);
1459           break;
1460
1461         case 'L':
1462           dereference = DEREF_ALWAYS;
1463           break;
1464
1465         case 'N':
1466           set_quoting_style (NULL, literal_quoting_style);
1467           break;
1468
1469         case 'Q':
1470           set_quoting_style (NULL, c_quoting_style);
1471           break;
1472
1473         case 'R':
1474           recursive = 1;
1475           break;
1476
1477         case 'S':
1478           sort_type = sort_size;
1479           sort_type_specified = 1;
1480           break;
1481
1482         case 'T':
1483           {
1484             long int tmp_long;
1485             if (xstrtol (optarg, NULL, 0, &tmp_long, NULL) != LONGINT_OK
1486                 || tmp_long < 0 || tmp_long > INT_MAX)
1487               error (EXIT_FAILURE, 0, _("invalid tab size: %s"),
1488                      quotearg (optarg));
1489             tabsize = (int) tmp_long;
1490             break;
1491           }
1492
1493         case 'U':
1494           sort_type = sort_none;
1495           sort_type_specified = 1;
1496           break;
1497
1498         case 'X':
1499           sort_type = sort_extension;
1500           sort_type_specified = 1;
1501           break;
1502
1503         case '1':
1504           /* -1 has no effect after -l.  */
1505           if (format != long_format)
1506             format = one_per_line;
1507           break;
1508
1509         case SORT_OPTION:
1510           sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1511           sort_type_specified = 1;
1512           break;
1513
1514         case TIME_OPTION:
1515           time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1516           break;
1517
1518         case FORMAT_OPTION:
1519           format = XARGMATCH ("--format", optarg, format_args, format_types);
1520           break;
1521
1522         case FULL_TIME_OPTION:
1523           format = long_format;
1524           time_style_option = "full-iso";
1525           break;
1526
1527         case COLOR_OPTION:
1528           {
1529             int i;
1530             if (optarg)
1531               i = XARGMATCH ("--color", optarg, color_args, color_types);
1532             else
1533               /* Using --color with no argument is equivalent to using
1534                  --color=always.  */
1535               i = color_always;
1536
1537             print_with_color = (i == color_always
1538                                 || (i == color_if_tty
1539                                     && isatty (STDOUT_FILENO)));
1540
1541             if (print_with_color)
1542               {
1543                 /* Don't use TAB characters in output.  Some terminal
1544                    emulators can't handle the combination of tabs and
1545                    color codes on the same line.  */
1546                 tabsize = 0;
1547               }
1548             break;
1549           }
1550
1551         case INDICATOR_STYLE_OPTION:
1552           indicator_style = XARGMATCH ("--indicator-style", optarg,
1553                                        indicator_style_args,
1554                                        indicator_style_types);
1555           break;
1556
1557         case QUOTING_STYLE_OPTION:
1558           set_quoting_style (NULL,
1559                              XARGMATCH ("--quoting-style", optarg,
1560                                         quoting_style_args,
1561                                         quoting_style_vals));
1562           break;
1563
1564         case TIME_STYLE_OPTION:
1565           time_style_option = optarg;
1566           break;
1567
1568         case SHOW_CONTROL_CHARS_OPTION:
1569           qmark_funny_chars = 0;
1570           break;
1571
1572         case BLOCK_SIZE_OPTION:
1573           human_block_size (optarg, 1, &output_block_size);
1574           break;
1575
1576         case SI_OPTION:
1577           output_block_size = -1000;
1578           break;
1579
1580         case_GETOPT_HELP_CHAR;
1581
1582         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1583
1584         default:
1585           usage (EXIT_FAILURE);
1586         }
1587     }
1588
1589   filename_quoting_options = clone_quoting_options (NULL);
1590   if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1591     set_char_quoting (filename_quoting_options, ' ', 1);
1592   if (indicator_style != none)
1593     {
1594       char const *p;
1595       for (p = "*=@|" + (int) indicator_style - 1;  *p;  p++)
1596         set_char_quoting (filename_quoting_options, *p, 1);
1597     }
1598
1599   dirname_quoting_options = clone_quoting_options (NULL);
1600   set_char_quoting (dirname_quoting_options, ':', 1);
1601
1602   /* If -c or -u is specified and not -l (or any other option that implies -l),
1603      and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
1604      The behavior of ls when using either -c or -u but with neither -l nor -t
1605      appears to be unspecified by POSIX.  So, with GNU ls, `-u' alone means
1606      sort by atime (this is the one that's not specified by the POSIX spec),
1607      -lu means show atime and sort by name, -lut means show atime and sort
1608      by atime.  */
1609
1610   if ((time_type == time_ctime || time_type == time_atime)
1611       && !sort_type_specified && format != long_format)
1612     {
1613       sort_type = sort_time;
1614     }
1615
1616   if (format == long_format)
1617     {
1618       if (! time_style_option)
1619         time_style_option = getenv ("TIME_STYLE");
1620
1621       switch (time_style_option
1622               ? XARGMATCH ("time style", time_style_option,
1623                            time_style_args,
1624                            time_style_types)
1625               : posix_iso_time_style)
1626         {
1627         case full_iso_time_style:
1628           long_time_format[0] = long_time_format[1] =
1629             "%Y-%m-%d %H:%M:%S.%N %z";
1630           break;
1631
1632         case posix_iso_time_style:
1633           if (! hard_locale (LC_TIME))
1634             break;
1635           /* Fall through.  */
1636         case iso_time_style:
1637           long_time_format[0] = "%Y-%m-%d ";
1638           long_time_format[1] = "%m-%d %H:%M";
1639           break;
1640
1641         case locale_time_style:
1642           if (hard_locale (LC_TIME))
1643             {
1644               unsigned int i;
1645               for (i = 0; i < 2; i++)
1646                 long_time_format[i] =
1647                   dcgettext (NULL, long_time_format[i], LC_TIME);
1648             }
1649         }
1650     }
1651
1652   return optind;
1653 }
1654
1655 /* Parse a string as part of the LS_COLORS variable; this may involve
1656    decoding all kinds of escape characters.  If equals_end is set an
1657    unescaped equal sign ends the string, otherwise only a : or \0
1658    does.  Returns the number of characters output, or -1 on failure.
1659
1660    The resulting string is *not* null-terminated, but may contain
1661    embedded nulls.
1662
1663    Note that both dest and src are char **; on return they point to
1664    the first free byte after the array and the character that ended
1665    the input string, respectively.  */
1666
1667 static int
1668 get_funky_string (char **dest, const char **src, int equals_end)
1669 {
1670   int num;                      /* For numerical codes */
1671   int count;                    /* Something to count with */
1672   enum {
1673     ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
1674   } state;
1675   const char *p;
1676   char *q;
1677
1678   p = *src;                     /* We don't want to double-indirect */
1679   q = *dest;                    /* the whole darn time.  */
1680
1681   count = 0;                    /* No characters counted in yet.  */
1682   num = 0;
1683
1684   state = ST_GND;               /* Start in ground state.  */
1685   while (state < ST_END)
1686     {
1687       switch (state)
1688         {
1689         case ST_GND:            /* Ground state (no escapes) */
1690           switch (*p)
1691             {
1692             case ':':
1693             case '\0':
1694               state = ST_END;   /* End of string */
1695               break;
1696             case '\\':
1697               state = ST_BACKSLASH; /* Backslash scape sequence */
1698               ++p;
1699               break;
1700             case '^':
1701               state = ST_CARET; /* Caret escape */
1702               ++p;
1703               break;
1704             case '=':
1705               if (equals_end)
1706                 {
1707                   state = ST_END; /* End */
1708                   break;
1709                 }
1710               /* else fall through */
1711             default:
1712               *(q++) = *(p++);
1713               ++count;
1714               break;
1715             }
1716           break;
1717
1718         case ST_BACKSLASH:      /* Backslash escaped character */
1719           switch (*p)
1720             {
1721             case '0':
1722             case '1':
1723             case '2':
1724             case '3':
1725             case '4':
1726             case '5':
1727             case '6':
1728             case '7':
1729               state = ST_OCTAL; /* Octal sequence */
1730               num = *p - '0';
1731               break;
1732             case 'x':
1733             case 'X':
1734               state = ST_HEX;   /* Hex sequence */
1735               num = 0;
1736               break;
1737             case 'a':           /* Bell */
1738               num = 7;          /* Not all C compilers know what \a means */
1739               break;
1740             case 'b':           /* Backspace */
1741               num = '\b';
1742               break;
1743             case 'e':           /* Escape */
1744               num = 27;
1745               break;
1746             case 'f':           /* Form feed */
1747               num = '\f';
1748               break;
1749             case 'n':           /* Newline */
1750               num = '\n';
1751               break;
1752             case 'r':           /* Carriage return */
1753               num = '\r';
1754               break;
1755             case 't':           /* Tab */
1756               num = '\t';
1757               break;
1758             case 'v':           /* Vtab */
1759               num = '\v';
1760               break;
1761             case '?':           /* Delete */
1762               num = 127;
1763               break;
1764             case '_':           /* Space */
1765               num = ' ';
1766               break;
1767             case '\0':          /* End of string */
1768               state = ST_ERROR; /* Error! */
1769               break;
1770             default:            /* Escaped character like \ ^ : = */
1771               num = *p;
1772               break;
1773             }
1774           if (state == ST_BACKSLASH)
1775             {
1776               *(q++) = num;
1777               ++count;
1778               state = ST_GND;
1779             }
1780           ++p;
1781           break;
1782
1783         case ST_OCTAL:          /* Octal sequence */
1784           if (*p < '0' || *p > '7')
1785             {
1786               *(q++) = num;
1787               ++count;
1788               state = ST_GND;
1789             }
1790           else
1791             num = (num << 3) + (*(p++) - '0');
1792           break;
1793
1794         case ST_HEX:            /* Hex sequence */
1795           switch (*p)
1796             {
1797             case '0':
1798             case '1':
1799             case '2':
1800             case '3':
1801             case '4':
1802             case '5':
1803             case '6':
1804             case '7':
1805             case '8':
1806             case '9':
1807               num = (num << 4) + (*(p++) - '0');
1808               break;
1809             case 'a':
1810             case 'b':
1811             case 'c':
1812             case 'd':
1813             case 'e':
1814             case 'f':
1815               num = (num << 4) + (*(p++) - 'a') + 10;
1816               break;
1817             case 'A':
1818             case 'B':
1819             case 'C':
1820             case 'D':
1821             case 'E':
1822             case 'F':
1823               num = (num << 4) + (*(p++) - 'A') + 10;
1824               break;
1825             default:
1826               *(q++) = num;
1827               ++count;
1828               state = ST_GND;
1829               break;
1830             }
1831           break;
1832
1833         case ST_CARET:          /* Caret escape */
1834           state = ST_GND;       /* Should be the next state... */
1835           if (*p >= '@' && *p <= '~')
1836             {
1837               *(q++) = *(p++) & 037;
1838               ++count;
1839             }
1840           else if (*p == '?')
1841             {
1842               *(q++) = 127;
1843               ++count;
1844             }
1845           else
1846             state = ST_ERROR;
1847           break;
1848
1849         default:
1850           abort ();
1851         }
1852     }
1853
1854   *dest = q;
1855   *src = p;
1856
1857   return state == ST_ERROR ? -1 : count;
1858 }
1859
1860 static void
1861 parse_ls_color (void)
1862 {
1863   const char *p;                /* Pointer to character being parsed */
1864   char *buf;                    /* color_buf buffer pointer */
1865   int state;                    /* State of parser */
1866   int ind_no;                   /* Indicator number */
1867   char label[3];                /* Indicator label */
1868   struct color_ext_type *ext;   /* Extension we are working on */
1869
1870   if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
1871     return;
1872
1873   ext = NULL;
1874   strcpy (label, "??");
1875
1876   /* This is an overly conservative estimate, but any possible
1877      LS_COLORS string will *not* generate a color_buf longer than
1878      itself, so it is a safe way of allocating a buffer in
1879      advance.  */
1880   buf = color_buf = xstrdup (p);
1881
1882   state = 1;
1883   while (state > 0)
1884     {
1885       switch (state)
1886         {
1887         case 1:         /* First label character */
1888           switch (*p)
1889             {
1890             case ':':
1891               ++p;
1892               break;
1893
1894             case '*':
1895               /* Allocate new extension block and add to head of
1896                  linked list (this way a later definition will
1897                  override an earlier one, which can be useful for
1898                  having terminal-specific defs override global).  */
1899
1900               ext = XMALLOC (struct color_ext_type, 1);
1901               ext->next = color_ext_list;
1902               color_ext_list = ext;
1903
1904               ++p;
1905               ext->ext.string = buf;
1906
1907               state = (ext->ext.len =
1908                        get_funky_string (&buf, &p, 1)) < 0 ? -1 : 4;
1909               break;
1910
1911             case '\0':
1912               state = 0;        /* Done! */
1913               break;
1914
1915             default:    /* Assume it is file type label */
1916               label[0] = *(p++);
1917               state = 2;
1918               break;
1919             }
1920           break;
1921
1922         case 2:         /* Second label character */
1923           if (*p)
1924             {
1925               label[1] = *(p++);
1926               state = 3;
1927             }
1928           else
1929             state = -1; /* Error */
1930           break;
1931
1932         case 3:         /* Equal sign after indicator label */
1933           state = -1;   /* Assume failure... */
1934           if (*(p++) == '=')/* It *should* be... */
1935             {
1936               for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
1937                 {
1938                   if (STREQ (label, indicator_name[ind_no]))
1939                     {
1940                       color_indicator[ind_no].string = buf;
1941                       state = ((color_indicator[ind_no].len =
1942                                 get_funky_string (&buf, &p, 0)) < 0 ? -1 : 1);
1943                       break;
1944                     }
1945                 }
1946               if (state == -1)
1947                 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
1948             }
1949          break;
1950
1951         case 4:         /* Equal sign after *.ext */
1952           if (*(p++) == '=')
1953             {
1954               ext->seq.string = buf;
1955               state = (ext->seq.len =
1956                        get_funky_string (&buf, &p, 0)) < 0 ? -1 : 1;
1957             }
1958           else
1959             state = -1;
1960           break;
1961         }
1962     }
1963
1964   if (state < 0)
1965     {
1966       struct color_ext_type *e;
1967       struct color_ext_type *e2;
1968
1969       error (0, 0,
1970              _("unparsable value for LS_COLORS environment variable"));
1971       free (color_buf);
1972       for (e = color_ext_list; e != NULL; /* empty */)
1973         {
1974           e2 = e;
1975           e = e->next;
1976           free (e2);
1977         }
1978       print_with_color = 0;
1979     }
1980
1981   if (color_indicator[C_LINK].len == 6
1982       && !strncmp (color_indicator[C_LINK].string, "target", 6))
1983     color_symlink_as_referent = 1;
1984 }
1985
1986 /* Request that the directory named NAME have its contents listed later.
1987    If REALNAME is nonzero, it will be used instead of NAME when the
1988    directory name is printed.  This allows symbolic links to directories
1989    to be treated as regular directories but still be listed under their
1990    real names.  NAME == NULL is used to insert a marker entry for the
1991    directory named in REALNAME.
1992    If F is non-NULL, we use its dev/ino information to save
1993    a call to stat -- when doing a recursive (-R) traversal.  */
1994
1995 static void
1996 queue_directory (const char *name, const char *realname)
1997 {
1998   struct pending *new;
1999
2000   new = XMALLOC (struct pending, 1);
2001   new->realname = realname ? xstrdup (realname) : NULL;
2002   new->name = name ? xstrdup (name) : NULL;
2003   new->next = pending_dirs;
2004   pending_dirs = new;
2005 }
2006
2007 /* Read directory `name', and list the files in it.
2008    If `realname' is nonzero, print its name instead of `name';
2009    this is used for symbolic links to directories. */
2010
2011 static void
2012 print_dir (const char *name, const char *realname)
2013 {
2014   register DIR *reading;
2015   register struct dirent *next;
2016   register uintmax_t total_blocks = 0;
2017   static int first = 1;
2018
2019   errno = 0;
2020   reading = opendir (name);
2021   if (!reading)
2022     {
2023       error (0, errno, "%s", quotearg_colon (name));
2024       exit_status = 1;
2025       return;
2026     }
2027
2028   if (LOOP_DETECT)
2029     {
2030       struct stat dir_stat;
2031       int fd = dirfd (reading);
2032
2033       /* If dirfd failed, endure the overhead of using stat.  */
2034       if ((0 <= fd
2035            ? fstat (fd, &dir_stat)
2036            : stat (name, &dir_stat)) < 0)
2037         {
2038           error (0, errno, _("cannot determine device and inode of %s"),
2039                  quotearg_colon (name));
2040           exit_status = 1;
2041           return;
2042         }
2043
2044       /* If we've already visited this dev/inode pair, warn that
2045          we've found a loop, and do not process this directory.  */
2046       if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
2047         {
2048           error (0, 0, _("not listing already-listed directory: %s"),
2049                  quotearg_colon (name));
2050           return;
2051         }
2052
2053       DEV_INO_PUSH (dir_stat.st_dev, dir_stat.st_ino);
2054     }
2055
2056   /* Read the directory entries, and insert the subfiles into the `files'
2057      table.  */
2058
2059   clear_files ();
2060
2061   while ((next = readdir (reading)) != NULL)
2062     if (file_interesting (next))
2063       {
2064         enum filetype type = unknown;
2065
2066 #if HAVE_STRUCT_DIRENT_D_TYPE
2067         if (next->d_type == DT_DIR || next->d_type == DT_CHR
2068             || next->d_type == DT_BLK || next->d_type == DT_SOCK
2069             || next->d_type == DT_FIFO)
2070           type = next->d_type;
2071 #endif
2072         total_blocks += gobble_file (next->d_name, type, 0, name);
2073       }
2074
2075   if (CLOSEDIR (reading))
2076     {
2077       error (0, errno, "%s", quotearg_colon (name));
2078       exit_status = 1;
2079       /* Don't return; print whatever we got. */
2080     }
2081
2082   /* Sort the directory contents.  */
2083   sort_files ();
2084
2085   /* If any member files are subdirectories, perhaps they should have their
2086      contents listed rather than being mentioned here as files.  */
2087
2088   if (recursive)
2089     extract_dirs_from_files (name, 1);
2090
2091   if (recursive || print_dir_name)
2092     {
2093       if (!first)
2094         DIRED_PUTCHAR ('\n');
2095       first = 0;
2096       DIRED_INDENT ();
2097       PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2098       dired_pos += quote_name (stdout, realname ? realname : name,
2099                                dirname_quoting_options);
2100       PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2101       DIRED_FPUTS_LITERAL (":\n", stdout);
2102     }
2103
2104   if (format == long_format || print_block_size)
2105     {
2106       const char *p;
2107       char buf[LONGEST_HUMAN_READABLE + 1];
2108
2109       DIRED_INDENT ();
2110       p = _("total");
2111       DIRED_FPUTS (p, stdout, strlen (p));
2112       DIRED_PUTCHAR (' ');
2113       p = human_readable_inexact (total_blocks, buf, ST_NBLOCKSIZE,
2114                                   output_block_size, human_ceiling);
2115       DIRED_FPUTS (p, stdout, strlen (p));
2116       DIRED_PUTCHAR ('\n');
2117     }
2118
2119   if (files_index)
2120     print_current_files ();
2121 }
2122
2123 /* Add `pattern' to the list of patterns for which files that match are
2124    not listed.  */
2125
2126 static void
2127 add_ignore_pattern (const char *pattern)
2128 {
2129   register struct ignore_pattern *ignore;
2130
2131   ignore = XMALLOC (struct ignore_pattern, 1);
2132   ignore->pattern = pattern;
2133   /* Add it to the head of the linked list. */
2134   ignore->next = ignore_patterns;
2135   ignore_patterns = ignore;
2136 }
2137
2138 /* Return nonzero if the file in `next' should be listed. */
2139
2140 static int
2141 file_interesting (const struct dirent *next)
2142 {
2143   register struct ignore_pattern *ignore;
2144
2145   for (ignore = ignore_patterns; ignore; ignore = ignore->next)
2146     if (fnmatch (ignore->pattern, next->d_name, FNM_PERIOD) == 0)
2147       return 0;
2148
2149   if (really_all_files
2150       || next->d_name[0] != '.'
2151       || (all_files
2152           && next->d_name[1] != '\0'
2153           && (next->d_name[1] != '.' || next->d_name[2] != '\0')))
2154     return 1;
2155
2156   return 0;
2157 }
2158
2159 /* Enter and remove entries in the table `files'.  */
2160
2161 /* Empty the table of files. */
2162
2163 static void
2164 clear_files (void)
2165 {
2166   register int i;
2167
2168   for (i = 0; i < files_index; i++)
2169     {
2170       free (files[i].name);
2171       if (files[i].linkname)
2172         free (files[i].linkname);
2173     }
2174
2175   files_index = 0;
2176   block_size_size = 4;
2177 }
2178
2179 /* Add a file to the current table of files.
2180    Verify that the file exists, and print an error message if it does not.
2181    Return the number of blocks that the file occupies.  */
2182
2183 static uintmax_t
2184 gobble_file (const char *name, enum filetype type, int explicit_arg,
2185              const char *dirname)
2186 {
2187   register uintmax_t blocks;
2188   register char *path;
2189
2190   if (files_index == nfiles)
2191     {
2192       nfiles *= 2;
2193       files = XREALLOC (files, struct fileinfo, nfiles);
2194     }
2195
2196   files[files_index].linkname = 0;
2197   files[files_index].linkmode = 0;
2198   files[files_index].linkok = 0;
2199
2200   /* FIXME: this use of ls: `mkdir a; touch a/{b,c,d}; ls -R a'
2201      shouldn't require that ls stat b, c, and d -- at least
2202      not on systems with usable d_type.  The problem is that
2203      format_needs_stat is set, because of the -R.  */
2204   if (explicit_arg || format_needs_stat
2205       || (format_needs_type && type == unknown))
2206     {
2207       /* `path' is the absolute pathname of this file. */
2208       int val;
2209
2210       if (name[0] == '/' || dirname[0] == 0)
2211         path = (char *) name;
2212       else
2213         {
2214           path = (char *) alloca (strlen (name) + strlen (dirname) + 2);
2215           attach (path, dirname, name);
2216         }
2217
2218       val = (DEREF_ALWAYS <= dereference + explicit_arg
2219              ? stat (path, &files[files_index].stat)
2220              : lstat (path, &files[files_index].stat));
2221
2222       if (val < 0)
2223         {
2224           error (0, errno, "%s", quotearg_colon (path));
2225           exit_status = 1;
2226           return 0;
2227         }
2228
2229 #if USE_ACL
2230       if (format == long_format)
2231         files[files_index].have_acl =
2232           (! S_ISLNK (files[files_index].stat.st_mode)
2233            && 4 < acl (path, GETACLCNT, 0, NULL));
2234 #endif
2235
2236       if (S_ISLNK (files[files_index].stat.st_mode)
2237           && (format == long_format || check_symlink_color))
2238         {
2239           char *linkpath;
2240           struct stat linkstats;
2241
2242           get_link_name (path, &files[files_index]);
2243           linkpath = make_link_path (path, files[files_index].linkname);
2244
2245           /* Avoid following symbolic links when possible, ie, when
2246              they won't be traced and when no indicator is needed. */
2247           if (linkpath
2248               && (indicator_style != none || check_symlink_color)
2249               && stat (linkpath, &linkstats) == 0)
2250             {
2251               files[files_index].linkok = 1;
2252
2253               /* Symbolic links to directories that are mentioned on the
2254                  command line are automatically traced if not being
2255                  listed as files.  */
2256               if (explicit_arg && format != long_format
2257                   && S_ISDIR (linkstats.st_mode))
2258                 {
2259                   /* Substitute the linked-to directory's name, but
2260                      save the real name in `linkname' for printing.  */
2261                   if (!immediate_dirs)
2262                     {
2263                       const char *tempname = name;
2264                       name = linkpath;
2265                       linkpath = files[files_index].linkname;
2266                       files[files_index].linkname = (char *) tempname;
2267                     }
2268                   files[files_index].stat = linkstats;
2269                 }
2270               else
2271                 {
2272                   /* Get the linked-to file's mode for the filetype indicator
2273                      in long listings.  */
2274                   files[files_index].linkmode = linkstats.st_mode;
2275                   files[files_index].linkok = 1;
2276                 }
2277             }
2278           if (linkpath)
2279             free (linkpath);
2280         }
2281
2282       if (S_ISLNK (files[files_index].stat.st_mode))
2283         files[files_index].filetype = symbolic_link;
2284       else if (S_ISDIR (files[files_index].stat.st_mode))
2285         {
2286           if (explicit_arg && !immediate_dirs)
2287             files[files_index].filetype = arg_directory;
2288           else
2289             files[files_index].filetype = directory;
2290         }
2291       else
2292         files[files_index].filetype = normal;
2293
2294       blocks = ST_NBLOCKS (files[files_index].stat);
2295       {
2296         char buf[LONGEST_HUMAN_READABLE + 1];
2297         int len = strlen (human_readable_inexact (blocks, buf, ST_NBLOCKSIZE,
2298                                                   output_block_size,
2299                                                   human_ceiling));
2300         if (block_size_size < len)
2301           block_size_size = len < 7 ? len : 7;
2302       }
2303     }
2304   else
2305     {
2306       files[files_index].filetype = type;
2307 #if HAVE_STRUCT_DIRENT_D_TYPE
2308       files[files_index].stat.st_mode = DTTOIF (type);
2309 #endif
2310       blocks = 0;
2311     }
2312
2313   files[files_index].name = xstrdup (name);
2314   files_index++;
2315
2316   return blocks;
2317 }
2318
2319 #if HAVE_SYMLINKS
2320
2321 /* Put the name of the file that `filename' is a symbolic link to
2322    into the `linkname' field of `f'. */
2323
2324 static void
2325 get_link_name (const char *filename, struct fileinfo *f)
2326 {
2327   f->linkname = xreadlink (filename);
2328   if (f->linkname == NULL)
2329     {
2330       error (0, errno, _("cannot read symbolic link %s"),
2331              quotearg_colon (filename));
2332       exit_status = 1;
2333     }
2334 }
2335
2336 /* If `linkname' is a relative path and `path' contains one or more
2337    leading directories, return `linkname' with those directories
2338    prepended; otherwise, return a copy of `linkname'.
2339    If `linkname' is zero, return zero. */
2340
2341 static char *
2342 make_link_path (const char *path, const char *linkname)
2343 {
2344   char *linkbuf;
2345   size_t bufsiz;
2346
2347   if (linkname == 0)
2348     return 0;
2349
2350   if (*linkname == '/')
2351     return xstrdup (linkname);
2352
2353   /* The link is to a relative path.  Prepend any leading path
2354      in `path' to the link name. */
2355   linkbuf = strrchr (path, '/');
2356   if (linkbuf == 0)
2357     return xstrdup (linkname);
2358
2359   bufsiz = linkbuf - path + 1;
2360   linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
2361   strncpy (linkbuf, path, bufsiz);
2362   strcpy (linkbuf + bufsiz, linkname);
2363   return linkbuf;
2364 }
2365 #endif
2366
2367 /* Return nonzero if base_name (NAME) ends in `.' or `..'
2368    This is so we don't try to recurse on `././././. ...' */
2369
2370 static int
2371 basename_is_dot_or_dotdot (const char *name)
2372 {
2373   char const *base = base_name (name);
2374   return DOT_OR_DOTDOT (base);
2375 }
2376
2377 /* Remove any entries from `files' that are for directories,
2378    and queue them to be listed as directories instead.
2379    `dirname' is the prefix to prepend to each dirname
2380    to make it correct relative to ls's working dir.
2381    If IGNORE_DOT_AND_DOT_DOT is nonzero don't treat `.' and `..' as dirs.
2382    This is desirable when processing directories recursively.  */
2383
2384 static void
2385 extract_dirs_from_files (const char *dirname, int ignore_dot_and_dot_dot)
2386 {
2387   register int i, j;
2388
2389   if (*dirname && LOOP_DETECT)
2390     {
2391       /* Insert a marker entry first.  When we dequeue this marker entry,
2392          we'll know that DIRNAME has been processed and may be removed
2393          from the set of active directories.  */
2394       queue_directory (NULL, dirname);
2395     }
2396
2397   /* Queue the directories last one first, because queueing reverses the
2398      order.  */
2399   for (i = files_index - 1; i >= 0; i--)
2400     if ((files[i].filetype == directory || files[i].filetype == arg_directory)
2401         && (!ignore_dot_and_dot_dot
2402             || !basename_is_dot_or_dotdot (files[i].name)))
2403       {
2404         if (files[i].name[0] == '/' || dirname[0] == 0)
2405           {
2406             queue_directory (files[i].name, files[i].linkname);
2407           }
2408         else
2409           {
2410             char *path = path_concat (dirname, files[i].name, NULL);
2411             queue_directory (path, files[i].linkname);
2412             free (path);
2413           }
2414         if (files[i].filetype == arg_directory)
2415           free (files[i].name);
2416       }
2417
2418   /* Now delete the directories from the table, compacting all the remaining
2419      entries.  */
2420
2421   for (i = 0, j = 0; i < files_index; i++)
2422     if (files[i].filetype != arg_directory)
2423       files[j++] = files[i];
2424   files_index = j;
2425 }
2426
2427 /* Use strcoll to compare strings in this locale.  If an error occurs,
2428    report an error and longjmp to failed_strcoll.  */
2429
2430 static jmp_buf failed_strcoll;
2431
2432 static int
2433 xstrcoll (char const *a, char const *b)
2434 {
2435   int diff;
2436   errno = 0;
2437   diff = strcoll (a, b);
2438   if (errno)
2439     {
2440       error (0, errno, _("cannot compare file names %s and %s"),
2441              quote_n (0, a), quote_n (1, b));
2442       exit_status = 1;
2443       longjmp (failed_strcoll, 1);
2444     }
2445   return diff;
2446 }
2447
2448 /* Comparison routines for sorting the files. */
2449
2450 typedef void const *V;
2451
2452 static inline int
2453 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
2454            int (*cmp) PARAMS ((char const *, char const *)))
2455 {
2456   int diff = CTIME_CMP (b->stat, a->stat);
2457   return diff ? diff : cmp (a->name, b->name);
2458 }
2459 static int compare_ctime (V a, V b) { return cmp_ctime (a, b, xstrcoll); }
2460 static int compstr_ctime (V a, V b) { return cmp_ctime (a, b, strcmp); }
2461 static int rev_cmp_ctime (V a, V b) { return compare_ctime (b, a); }
2462 static int rev_str_ctime (V a, V b) { return compstr_ctime (b, a); }
2463
2464 static inline int
2465 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
2466            int (*cmp) PARAMS((char const *, char const *)))
2467 {
2468   int diff = MTIME_CMP (b->stat, a->stat);
2469   return diff ? diff : cmp (a->name, b->name);
2470 }
2471 static int compare_mtime (V a, V b) { return cmp_mtime (a, b, xstrcoll); }
2472 static int compstr_mtime (V a, V b) { return cmp_mtime (a, b, strcmp); }
2473 static int rev_cmp_mtime (V a, V b) { return compare_mtime (b, a); }
2474 static int rev_str_mtime (V a, V b) { return compstr_mtime (b, a); }
2475
2476 static inline int
2477 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
2478            int (*cmp) PARAMS ((char const *, char const *)))
2479 {
2480   int diff = ATIME_CMP (b->stat, a->stat);
2481   return diff ? diff : cmp (a->name, b->name);
2482 }
2483 static int compare_atime (V a, V b) { return cmp_atime (a, b, xstrcoll); }
2484 static int compstr_atime (V a, V b) { return cmp_atime (a, b, strcmp); }
2485 static int rev_cmp_atime (V a, V b) { return compare_atime (b, a); }
2486 static int rev_str_atime (V a, V b) { return compstr_atime (b, a); }
2487
2488 static inline int
2489 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
2490           int (*cmp) PARAMS ((char const *, char const *)))
2491 {
2492   int diff = longdiff (b->stat.st_size, a->stat.st_size);
2493   return diff ? diff : cmp (a->name, b->name);
2494 }
2495 static int compare_size (V a, V b) { return cmp_size (a, b, xstrcoll); }
2496 static int compstr_size (V a, V b) { return cmp_size (a, b, strcmp); }
2497 static int rev_cmp_size (V a, V b) { return compare_size (b, a); }
2498 static int rev_str_size (V a, V b) { return compstr_size (b, a); }
2499
2500 static inline int
2501 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
2502 {
2503   return strverscmp (a->name, b->name);
2504 }
2505 static int compare_version (V a, V b) { return cmp_version (a, b); }
2506 static int rev_cmp_version (V a, V b) { return compare_version (b, a); }
2507
2508 static inline int
2509 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
2510           int (*cmp) PARAMS ((char const *, char const *)))
2511 {
2512   return cmp (a->name, b->name);
2513 }
2514 static int compare_name (V a, V b) { return cmp_name (a, b, xstrcoll); }
2515 static int compstr_name (V a, V b) { return cmp_name (a, b, strcmp); }
2516 static int rev_cmp_name (V a, V b) { return compare_name (b, a); }
2517 static int rev_str_name (V a, V b) { return compstr_name (b, a); }
2518
2519 /* Compare file extensions.  Files with no extension are `smallest'.
2520    If extensions are the same, compare by filenames instead. */
2521
2522 static inline int
2523 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
2524                int (*cmp) PARAMS ((char const *, char const *)))
2525 {
2526   char const *base1 = strrchr (a->name, '.');
2527   char const *base2 = strrchr (b->name, '.');
2528   int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
2529   return diff ? diff : cmp (a->name, b->name);
2530 }
2531 static int compare_extension (V a, V b) { return cmp_extension (a, b, xstrcoll); }
2532 static int compstr_extension (V a, V b) { return cmp_extension (a, b, strcmp); }
2533 static int rev_cmp_extension (V a, V b) { return compare_extension (b, a); }
2534 static int rev_str_extension (V a, V b) { return compstr_extension (b, a); }
2535
2536 /* Sort the files now in the table.  */
2537
2538 static void
2539 sort_files (void)
2540 {
2541   int (*func) PARAMS ((V, V));
2542
2543   switch (sort_type)
2544     {
2545     case sort_none:
2546       return;
2547     case sort_time:
2548       switch (time_type)
2549         {
2550         case time_ctime:
2551           func = sort_reverse ? rev_cmp_ctime : compare_ctime;
2552           break;
2553         case time_mtime:
2554           func = sort_reverse ? rev_cmp_mtime : compare_mtime;
2555           break;
2556         case time_atime:
2557           func = sort_reverse ? rev_cmp_atime : compare_atime;
2558           break;
2559         default:
2560           abort ();
2561         }
2562       break;
2563     case sort_name:
2564       func = sort_reverse ? rev_cmp_name : compare_name;
2565       break;
2566     case sort_extension:
2567       func = sort_reverse ? rev_cmp_extension : compare_extension;
2568       break;
2569     case sort_size:
2570       func = sort_reverse ? rev_cmp_size : compare_size;
2571       break;
2572     case sort_version:
2573       func = sort_reverse ? rev_cmp_version : compare_version;
2574       break;
2575     default:
2576       abort ();
2577     }
2578
2579   /* Try strcoll.  If it fails, fall back on strcmp.  We can't safely
2580      ignore strcoll failures, as a failing strcoll might be a
2581      comparison function that is not a total order, and if we ignored
2582      the failure this might cause qsort to dump core.  */
2583
2584   if (setjmp (failed_strcoll))
2585     {
2586       switch (sort_type)
2587         {
2588         case sort_time:
2589           switch (time_type)
2590             {
2591             case time_ctime:
2592               func = sort_reverse ? rev_str_ctime : compstr_ctime;
2593               break;
2594             case time_mtime:
2595               func = sort_reverse ? rev_str_mtime : compstr_mtime;
2596               break;
2597             case time_atime:
2598               func = sort_reverse ? rev_str_atime : compstr_atime;
2599               break;
2600             default:
2601               abort ();
2602             }
2603           break;
2604         case sort_name:
2605           func = sort_reverse ? rev_str_name : compstr_name;
2606           break;
2607         case sort_extension:
2608           func = sort_reverse ? rev_str_extension : compstr_extension;
2609           break;
2610         case sort_size:
2611           func = sort_reverse ? rev_str_size : compstr_size;
2612           break;
2613         default:
2614           abort ();
2615         }
2616     }
2617
2618   qsort (files, files_index, sizeof (struct fileinfo), func);
2619 }
2620
2621 /* List all the files now in the table.  */
2622
2623 static void
2624 print_current_files (void)
2625 {
2626   register int i;
2627
2628   switch (format)
2629     {
2630     case one_per_line:
2631       for (i = 0; i < files_index; i++)
2632         {
2633           print_file_name_and_frills (files + i);
2634           putchar ('\n');
2635         }
2636       break;
2637
2638     case many_per_line:
2639       init_column_info ();
2640       print_many_per_line ();
2641       break;
2642
2643     case horizontal:
2644       init_column_info ();
2645       print_horizontal ();
2646       break;
2647
2648     case with_commas:
2649       print_with_commas ();
2650       break;
2651
2652     case long_format:
2653       for (i = 0; i < files_index; i++)
2654         {
2655           print_long_format (files + i);
2656           DIRED_PUTCHAR ('\n');
2657         }
2658       break;
2659     }
2660 }
2661
2662 /* Return the expected number of columns in a long-format time stamp,
2663    or zero if it cannot be calculated.  */
2664
2665 static int
2666 long_time_expected_width (void)
2667 {
2668   static int width = -1;
2669
2670   if (width < 0)
2671     {
2672       time_t epoch = 0;
2673       struct tm const *tm = localtime (&epoch);
2674       char const *fmt = long_time_format[0];
2675       char initbuf[100];
2676       char *buf = initbuf;
2677       size_t bufsize = sizeof initbuf;
2678       size_t len;
2679
2680       for (;;)
2681         {
2682           *buf = '\1';
2683           len = nstrftime (buf, bufsize, fmt, tm, 0, 0);
2684           if (len || ! *buf)
2685             break;
2686           buf = alloca (bufsize *= 2);
2687         }
2688
2689       width = mbsnwidth (buf, len, 0);
2690       if (width < 0)
2691         width = 0;
2692     }
2693
2694   return width;
2695 }
2696
2697 /* Get the current time.  */
2698
2699 static void
2700 get_current_time (void)
2701 {
2702 #if HAVE_CLOCK_GETTIME && defined CLOCK_REALTIME
2703   {
2704     struct timespec timespec;
2705     if (clock_gettime (CLOCK_REALTIME, &timespec) == 0)
2706       {
2707         current_time = timespec.tv_sec;
2708         current_time_ns = timespec.tv_nsec;
2709         return;
2710       }
2711   }
2712 #endif
2713
2714   /* The clock does not have nanosecond resolution, so get the maximum
2715      possible value for the current time that is consistent with the
2716      reported clock.  That way, files are not considered to be in the
2717      future merely because their time stamps have higher resolution
2718      than the clock resolution.  */
2719
2720 #if HAVE_GETTIMEOFDAY
2721   {
2722     struct timeval timeval;
2723     if (gettimeofday (&timeval, NULL) == 0)
2724       {
2725         current_time = timeval.tv_sec;
2726         current_time_ns = timeval.tv_usec * 1000 + 999;
2727         return;
2728       }
2729   }
2730 #endif
2731
2732   current_time = time (NULL);
2733   current_time_ns = 999999999;
2734 }
2735
2736 static void
2737 print_long_format (const struct fileinfo *f)
2738 {
2739   char modebuf[12];
2740
2741   /* 7 fields that may require LONGEST_HUMAN_READABLE bytes,
2742      1 10-byte mode string,
2743      1 35-byte time string (may be longer in some locales -- see below)
2744        or LONGEST_HUMAN_READABLE integer,
2745      9 spaces, one following each of these fields, and
2746      1 trailing NUL byte.  */
2747   char init_bigbuf[7 * LONGEST_HUMAN_READABLE + 10
2748                    + MAX (35, LONGEST_HUMAN_READABLE)
2749                    + 9 + 1];
2750   char *buf = init_bigbuf;
2751   size_t bufsize = sizeof (init_bigbuf);
2752   size_t s;
2753   char *p;
2754   time_t when;
2755   int when_ns IF_LINT (= 0);
2756   struct tm *when_local;
2757
2758 #if HAVE_ST_DM_MODE
2759   /* Cray DMF: look at the file's migrated, not real, status */
2760   mode_string (f->stat.st_dm_mode, modebuf);
2761 #else
2762   mode_string (f->stat.st_mode, modebuf);
2763 #endif
2764
2765   modebuf[10] = (FILE_HAS_ACL (f) ? '+' : ' ');
2766   modebuf[11] = '\0';
2767
2768   switch (time_type)
2769     {
2770     case time_ctime:
2771       when = f->stat.st_ctime;
2772       when_ns = TIMESPEC_NS (f->stat.st_ctim);
2773       break;
2774     case time_mtime:
2775       when = f->stat.st_mtime;
2776       when_ns = TIMESPEC_NS (f->stat.st_mtim);
2777       break;
2778     case time_atime:
2779       when = f->stat.st_atime;
2780       when_ns = TIMESPEC_NS (f->stat.st_atim);
2781       break;
2782     }
2783
2784   p = buf;
2785
2786   if (print_inode)
2787     {
2788       char hbuf[LONGEST_HUMAN_READABLE + 1];
2789       sprintf (p, "%*s ", INODE_DIGITS,
2790                human_readable ((uintmax_t) f->stat.st_ino, hbuf, 1, 1));
2791       p += strlen (p);
2792     }
2793
2794   if (print_block_size)
2795     {
2796       char hbuf[LONGEST_HUMAN_READABLE + 1];
2797       sprintf (p, "%*s ", block_size_size,
2798                human_readable_inexact ((uintmax_t) ST_NBLOCKS (f->stat), hbuf,
2799                                        ST_NBLOCKSIZE, output_block_size,
2800                                        human_ceiling));
2801       p += strlen (p);
2802     }
2803
2804   /* The last byte of the mode string is the POSIX
2805      "optional alternate access method flag".  */
2806   sprintf (p, "%s %3lu ", modebuf, (unsigned long) f->stat.st_nlink);
2807   p += strlen (p);
2808
2809   if (print_owner)
2810     {
2811       char const *user_name = (numeric_ids ? NULL : getuser (f->stat.st_uid));
2812       if (user_name)
2813         sprintf (p, "%-8s ", user_name);
2814       else
2815         sprintf (p, "%-8lu ", (unsigned long) f->stat.st_uid);
2816       p += strlen (p);
2817     }
2818
2819   if (print_group)
2820     {
2821       char const *group_name = (numeric_ids ? NULL : getgroup (f->stat.st_gid));
2822       if (group_name)
2823         sprintf (p, "%-8s ", group_name);
2824       else
2825         sprintf (p, "%-8lu ", (unsigned long) f->stat.st_gid);
2826       p += strlen (p);
2827     }
2828
2829   if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
2830     sprintf (p, "%3lu, %3lu ",
2831              (unsigned long) major (f->stat.st_rdev),
2832              (unsigned long) minor (f->stat.st_rdev));
2833   else
2834     {
2835       char hbuf[LONGEST_HUMAN_READABLE + 1];
2836       uintmax_t size = f->stat.st_size;
2837
2838       /* POSIX requires that the size be printed without a sign, even
2839          when negative.  Assume the typical case where negative sizes
2840          are actually positive values that have wrapped around.  */
2841       size += (f->stat.st_size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
2842
2843       sprintf (p, "%8s ",
2844                human_readable (size, hbuf, 1,
2845                                output_block_size < 0 ? output_block_size : 1));
2846     }
2847
2848   p += strlen (p);
2849
2850   if ((when_local = localtime (&when)))
2851     {
2852       time_t six_months_ago;
2853       int recent;
2854       char const *fmt;
2855
2856       /* If the file appears to be in the future, update the current
2857          time, in case the file happens to have been modified since
2858          the last time we checked the clock.  */
2859       if (current_time < when
2860           || (current_time == when && current_time_ns < when_ns))
2861         {
2862           /* Note that get_current_time calls gettimeofday which, on some non-
2863              compliant systems, clobbers the buffer used for localtime's result.
2864              But it's ok here, because we use a gettimeofday wrapper that
2865              saves and restores the buffer around the gettimeofday call.  */
2866           get_current_time ();
2867         }
2868
2869       /* Consider a time to be recent if it is within the past six
2870          months.  A Gregorian year has 365.2425 * 24 * 60 * 60 ==
2871          31556952 seconds on the average.  Write this value as an
2872          integer constant to avoid floating point hassles.  */
2873       six_months_ago = current_time - 31556952 / 2;
2874       recent = (six_months_ago <= when
2875                 && (when < current_time
2876                     || (when == current_time && when_ns <= current_time_ns)));
2877       fmt = long_time_format[recent];
2878
2879       for (;;)
2880         {
2881           char *newbuf;
2882           *p = '\1';
2883           s = nstrftime (p, buf + bufsize - p - 1, fmt,
2884                          when_local, 0, when_ns);
2885           if (s || ! *p)
2886             break;
2887           newbuf = alloca (bufsize *= 2);
2888           memcpy (newbuf, buf, p - buf);
2889           p = newbuf + (p - buf);
2890           buf = newbuf;
2891         }
2892
2893       p += s;
2894       *p++ = ' ';
2895
2896       /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it.  */
2897       *p = '\0';
2898     }
2899   else
2900     {
2901       /* The time cannot be represented as a local time;
2902          print it as a huge integer number of seconds.  */
2903       char hbuf[LONGEST_HUMAN_READABLE + 1];
2904       int width = long_time_expected_width ();
2905
2906       if (when < 0)
2907         {
2908           const char *num = human_readable (- (uintmax_t) when, hbuf, 1, 1);
2909           int sign_width = width - strlen (num);
2910           sprintf (p, "%*s%s ", sign_width < 0 ? 0 : sign_width, "-", num);
2911         }
2912       else
2913         sprintf (p, "%*s ", width,
2914                  human_readable ((uintmax_t) when, hbuf, 1, 1));
2915
2916       p += strlen (p);
2917     }
2918
2919   DIRED_INDENT ();
2920   DIRED_FPUTS (buf, stdout, p - buf);
2921   print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
2922                            &dired_obstack);
2923
2924   if (f->filetype == symbolic_link)
2925     {
2926       if (f->linkname)
2927         {
2928           DIRED_FPUTS_LITERAL (" -> ", stdout);
2929           print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1,
2930                                    NULL);
2931           if (indicator_style != none)
2932             print_type_indicator (f->linkmode);
2933         }
2934     }
2935   else if (indicator_style != none)
2936     print_type_indicator (f->stat.st_mode);
2937 }
2938
2939 /* Output to OUT a quoted representation of the file name NAME,
2940    using OPTIONS to control quoting.  Produce no output if OUT is NULL.
2941    Return the number of screen columns occupied by NAME's quoted
2942    representation.  */
2943
2944 static size_t
2945 quote_name (FILE *out, const char *name, struct quoting_options const *options)
2946 {
2947   char smallbuf[BUFSIZ];
2948   size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, name, -1, options);
2949   char *buf;
2950   int displayed_width;
2951
2952   if (len < sizeof smallbuf)
2953     buf = smallbuf;
2954   else
2955     {
2956       buf = (char *) alloca (len + 1);
2957       quotearg_buffer (buf, len + 1, name, -1, options);
2958     }
2959
2960   if (qmark_funny_chars)
2961     {
2962 #if HAVE_MBRTOWC
2963       if (MB_CUR_MAX > 1)
2964         {
2965           char const *p = buf;
2966           char const *plimit = buf + len;
2967           char *q = buf;
2968           displayed_width = 0;
2969
2970           while (p < plimit)
2971             switch (*p)
2972               {
2973                 case ' ': case '!': case '"': case '#': case '%':
2974                 case '&': case '\'': case '(': case ')': case '*':
2975                 case '+': case ',': case '-': case '.': case '/':
2976                 case '0': case '1': case '2': case '3': case '4':
2977                 case '5': case '6': case '7': case '8': case '9':
2978                 case ':': case ';': case '<': case '=': case '>':
2979                 case '?':
2980                 case 'A': case 'B': case 'C': case 'D': case 'E':
2981                 case 'F': case 'G': case 'H': case 'I': case 'J':
2982                 case 'K': case 'L': case 'M': case 'N': case 'O':
2983                 case 'P': case 'Q': case 'R': case 'S': case 'T':
2984                 case 'U': case 'V': case 'W': case 'X': case 'Y':
2985                 case 'Z':
2986                 case '[': case '\\': case ']': case '^': case '_':
2987                 case 'a': case 'b': case 'c': case 'd': case 'e':
2988                 case 'f': case 'g': case 'h': case 'i': case 'j':
2989                 case 'k': case 'l': case 'm': case 'n': case 'o':
2990                 case 'p': case 'q': case 'r': case 's': case 't':
2991                 case 'u': case 'v': case 'w': case 'x': case 'y':
2992                 case 'z': case '{': case '|': case '}': case '~':
2993                   /* These characters are printable ASCII characters.  */
2994                   *q++ = *p++;
2995                   displayed_width += 1;
2996                   break;
2997                 default:
2998                   /* If we have a multibyte sequence, copy it until we
2999                      reach its end, replacing each non-printable multibyte
3000                      character with a single question mark.  */
3001                   {
3002                     mbstate_t mbstate;
3003                     memset (&mbstate, 0, sizeof mbstate);
3004                     do
3005                       {
3006                         wchar_t wc;
3007                         size_t bytes;
3008                         int w;
3009
3010                         bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
3011
3012                         if (bytes == (size_t) -1)
3013                           {
3014                             /* An invalid multibyte sequence was
3015                                encountered.  Skip one input byte, and
3016                                put a question mark.  */
3017                             p++;
3018                             *q++ = '?';
3019                             displayed_width += 1;
3020                             break;
3021                           }
3022
3023                         if (bytes == (size_t) -2)
3024                           {
3025                             /* An incomplete multibyte character
3026                                at the end.  Replace it entirely with
3027                                a question mark.  */
3028                             p = plimit;
3029                             *q++ = '?';
3030                             displayed_width += 1;
3031                             break;
3032                           }
3033
3034                         if (bytes == 0)
3035                           /* A null wide character was encountered.  */
3036                           bytes = 1;
3037
3038                         w = wcwidth (wc);
3039                         if (w >= 0)
3040                           {
3041                             /* A printable multibyte character.
3042                                Keep it.  */
3043                             for (; bytes > 0; --bytes)
3044                               *q++ = *p++;
3045                             displayed_width += w;
3046                           }
3047                         else
3048                           {
3049                             /* An unprintable multibyte character.
3050                                Replace it entirely with a question
3051                                mark.  */
3052                             p += bytes;
3053                             *q++ = '?';
3054                             displayed_width += 1;
3055                           }
3056                       }
3057                     while (! mbsinit (&mbstate));
3058                   }
3059                   break;
3060               }
3061
3062           /* The buffer may have shrunk.  */
3063           len = q - buf;
3064         }
3065       else
3066 #endif
3067         {
3068           char *p = buf;
3069           char const *plimit = buf + len;
3070
3071           while (p < plimit)
3072             {
3073               if (! ISPRINT ((unsigned char) *p))
3074                 *p = '?';
3075               p++;
3076             }
3077           displayed_width = len;
3078         }
3079     }
3080   else
3081     {
3082       /* Assume unprintable characters have a displayed_width of 1.  */
3083 #if HAVE_MBRTOWC
3084       if (MB_CUR_MAX > 1)
3085         displayed_width = mbsnwidth (buf, len, 0);
3086       else
3087 #endif
3088         displayed_width = len;
3089     }
3090
3091   if (out != NULL)
3092     fwrite (buf, 1, len, out);
3093   return displayed_width;
3094 }
3095
3096 static void
3097 print_name_with_quoting (const char *p, mode_t mode, int linkok,
3098                          struct obstack *stack)
3099 {
3100   if (print_with_color)
3101     print_color_indicator (p, mode, linkok);
3102
3103   if (stack)
3104     PUSH_CURRENT_DIRED_POS (stack);
3105
3106   dired_pos += quote_name (stdout, p, filename_quoting_options);
3107
3108   if (stack)
3109     PUSH_CURRENT_DIRED_POS (stack);
3110
3111   if (print_with_color)
3112     prep_non_filename_text ();
3113 }
3114
3115 static void
3116 prep_non_filename_text (void)
3117 {
3118   if (color_indicator[C_END].string != NULL)
3119     put_indicator (&color_indicator[C_END]);
3120   else
3121     {
3122       put_indicator (&color_indicator[C_LEFT]);
3123       put_indicator (&color_indicator[C_NORM]);
3124       put_indicator (&color_indicator[C_RIGHT]);
3125     }
3126 }
3127
3128 /* Print the file name of `f' with appropriate quoting.
3129    Also print file size, inode number, and filetype indicator character,
3130    as requested by switches.  */
3131
3132 static void
3133 print_file_name_and_frills (const struct fileinfo *f)
3134 {
3135   char buf[LONGEST_HUMAN_READABLE + 1];
3136
3137   if (print_inode)
3138     printf ("%*s ", INODE_DIGITS,
3139             human_readable ((uintmax_t) f->stat.st_ino, buf, 1, 1));
3140
3141   if (print_block_size)
3142     printf ("%*s ", block_size_size,
3143             human_readable_inexact ((uintmax_t) ST_NBLOCKS (f->stat), buf,
3144                                     ST_NBLOCKSIZE, output_block_size,
3145                                     human_ceiling));
3146
3147   print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok, NULL);
3148
3149   if (indicator_style != none)
3150     print_type_indicator (f->stat.st_mode);
3151 }
3152
3153 static void
3154 print_type_indicator (mode_t mode)
3155 {
3156   int c;
3157
3158   if (S_ISREG (mode))
3159     {
3160       if (indicator_style == classify && (mode & S_IXUGO))
3161         c ='*';
3162       else
3163         c = 0;
3164     }
3165   else
3166     {
3167       if (S_ISDIR (mode))
3168         c = '/';
3169       else if (S_ISLNK (mode))
3170         c = '@';
3171       else if (S_ISFIFO (mode))
3172         c = '|';
3173       else if (S_ISSOCK (mode))
3174         c = '=';
3175       else if (S_ISDOOR (mode))
3176         c = '>';
3177       else
3178         c = 0;
3179     }
3180
3181   if (c)
3182     DIRED_PUTCHAR (c);
3183 }
3184
3185 static void
3186 print_color_indicator (const char *name, mode_t mode, int linkok)
3187 {
3188   int type = C_FILE;
3189   struct color_ext_type *ext;   /* Color extension */
3190   size_t len;                   /* Length of name */
3191
3192   /* Is this a nonexistent file?  If so, linkok == -1.  */
3193
3194   if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
3195     {
3196       ext = NULL;
3197       type = C_MISSING;
3198     }
3199   else
3200     {
3201       if (S_ISDIR (mode))
3202         type = C_DIR;
3203       else if (S_ISLNK (mode))
3204         type = ((!linkok && color_indicator[C_ORPHAN].string)
3205                 ? C_ORPHAN : C_LINK);
3206       else if (S_ISFIFO (mode))
3207         type = C_FIFO;
3208       else if (S_ISSOCK (mode))
3209         type = C_SOCK;
3210       else if (S_ISBLK (mode))
3211         type = C_BLK;
3212       else if (S_ISCHR (mode))
3213         type = C_CHR;
3214       else if (S_ISDOOR (mode))
3215         type = C_DOOR;
3216
3217       if (type == C_FILE && (mode & S_IXUGO) != 0)
3218         type = C_EXEC;
3219
3220       /* Check the file's suffix only if still classified as C_FILE.  */
3221       ext = NULL;
3222       if (type == C_FILE)
3223         {
3224           /* Test if NAME has a recognized suffix.  */
3225
3226           len = strlen (name);
3227           name += len;          /* Pointer to final \0.  */
3228           for (ext = color_ext_list; ext != NULL; ext = ext->next)
3229             {
3230               if ((size_t) ext->ext.len <= len
3231                   && strncmp (name - ext->ext.len, ext->ext.string,
3232                               ext->ext.len) == 0)
3233                 break;
3234             }
3235         }
3236     }
3237
3238   put_indicator (&color_indicator[C_LEFT]);
3239   put_indicator (ext ? &(ext->seq) : &color_indicator[type]);
3240   put_indicator (&color_indicator[C_RIGHT]);
3241 }
3242
3243 /* Output a color indicator (which may contain nulls).  */
3244 static void
3245 put_indicator (const struct bin_str *ind)
3246 {
3247   register int i;
3248   register const char *p;
3249
3250   p = ind->string;
3251
3252   for (i = ind->len; i > 0; --i)
3253     putchar (*(p++));
3254 }
3255
3256 static int
3257 length_of_file_name_and_frills (const struct fileinfo *f)
3258 {
3259   register int len = 0;
3260
3261   if (print_inode)
3262     len += INODE_DIGITS + 1;
3263
3264   if (print_block_size)
3265     len += 1 + block_size_size;
3266
3267   len += quote_name (NULL, f->name, filename_quoting_options);
3268
3269   if (indicator_style != none)
3270     {
3271       mode_t filetype = f->stat.st_mode;
3272
3273       if (S_ISREG (filetype))
3274         {
3275           if (indicator_style == classify
3276               && (f->stat.st_mode & S_IXUGO))
3277             len += 1;
3278         }
3279       else if (S_ISDIR (filetype)
3280                || S_ISLNK (filetype)
3281                || S_ISFIFO (filetype)
3282                || S_ISSOCK (filetype)
3283                || S_ISDOOR (filetype)
3284                )
3285         len += 1;
3286     }
3287
3288   return len;
3289 }
3290
3291 static void
3292 print_many_per_line (void)
3293 {
3294   struct column_info *line_fmt;
3295   int filesno;                  /* Index into files. */
3296   int row;                      /* Current row. */
3297   int max_name_length;          /* Length of longest file name + frills. */
3298   int name_length;              /* Length of each file name + frills. */
3299   int pos;                      /* Current character column. */
3300   int cols;                     /* Number of files across. */
3301   int rows;                     /* Maximum number of files down. */
3302   int max_cols;
3303
3304   /* Normally the maximum number of columns is determined by the
3305      screen width.  But if few files are available this might limit it
3306      as well.  */
3307   max_cols = max_idx > files_index ? files_index : max_idx;
3308
3309   /* Compute the maximum number of possible columns.  */
3310   for (filesno = 0; filesno < files_index; ++filesno)
3311     {
3312       int i;
3313
3314       name_length = length_of_file_name_and_frills (files + filesno);
3315
3316       for (i = 0; i < max_cols; ++i)
3317         {
3318           if (column_info[i].valid_len)
3319             {
3320               int idx = filesno / ((files_index + i) / (i + 1));
3321               int real_length = name_length + (idx == i ? 0 : 2);
3322
3323               if (real_length > column_info[i].col_arr[idx])
3324                 {
3325                   column_info[i].line_len += (real_length
3326                                            - column_info[i].col_arr[idx]);
3327                   column_info[i].col_arr[idx] = real_length;
3328                   column_info[i].valid_len = column_info[i].line_len < line_length;
3329                 }
3330             }
3331         }
3332     }
3333
3334   /* Find maximum allowed columns.  */
3335   for (cols = max_cols; cols > 1; --cols)
3336     {
3337       if (column_info[cols - 1].valid_len)
3338         break;
3339     }
3340
3341   line_fmt = &column_info[cols - 1];
3342
3343   /* Calculate the number of rows that will be in each column except possibly
3344      for a short column on the right. */
3345   rows = files_index / cols + (files_index % cols != 0);
3346
3347   for (row = 0; row < rows; row++)
3348     {
3349       int col = 0;
3350       filesno = row;
3351       pos = 0;
3352       /* Print the next row.  */
3353       while (1)
3354         {
3355           print_file_name_and_frills (files + filesno);
3356           name_length = length_of_file_name_and_frills (files + filesno);
3357           max_name_length = line_fmt->col_arr[col++];
3358
3359           filesno += rows;
3360           if (filesno >= files_index)
3361             break;
3362
3363           indent (pos + name_length, pos + max_name_length);
3364           pos += max_name_length;
3365         }
3366       putchar ('\n');
3367     }
3368 }
3369
3370 static void
3371 print_horizontal (void)
3372 {
3373   struct column_info *line_fmt;
3374   int filesno;
3375   int max_name_length;
3376   int name_length;
3377   int cols;
3378   int pos;
3379   int max_cols;
3380
3381   /* Normally the maximum number of columns is determined by the
3382      screen width.  But if few files are available this might limit it
3383      as well.  */
3384   max_cols = max_idx > files_index ? files_index : max_idx;
3385
3386   /* Compute the maximum file name length.  */
3387   max_name_length = 0;
3388   for (filesno = 0; filesno < files_index; ++filesno)
3389     {
3390       int i;
3391
3392       name_length = length_of_file_name_and_frills (files + filesno);
3393
3394       for (i = 0; i < max_cols; ++i)
3395         {
3396           if (column_info[i].valid_len)
3397             {
3398               int idx = filesno % (i + 1);
3399               int real_length = name_length + (idx == i ? 0 : 2);
3400
3401               if (real_length > column_info[i].col_arr[idx])
3402                 {
3403                   column_info[i].line_len += (real_length
3404                                            - column_info[i].col_arr[idx]);
3405                   column_info[i].col_arr[idx] = real_length;
3406                   column_info[i].valid_len = column_info[i].line_len < line_length;
3407                 }
3408             }
3409         }
3410     }
3411
3412   /* Find maximum allowed columns.  */
3413   for (cols = max_cols; cols > 1; --cols)
3414     {
3415       if (column_info[cols - 1].valid_len)
3416         break;
3417     }
3418
3419   line_fmt = &column_info[cols - 1];
3420
3421   pos = 0;
3422
3423   /* Print first entry.  */
3424   print_file_name_and_frills (files);
3425   name_length = length_of_file_name_and_frills (files);
3426   max_name_length = line_fmt->col_arr[0];
3427
3428   /* Now the rest.  */
3429   for (filesno = 1; filesno < files_index; ++filesno)
3430     {
3431       int col = filesno % cols;
3432
3433       if (col == 0)
3434         {
3435           putchar ('\n');
3436           pos = 0;
3437         }
3438       else
3439         {
3440           indent (pos + name_length, pos + max_name_length);
3441           pos += max_name_length;
3442         }
3443
3444       print_file_name_and_frills (files + filesno);
3445
3446       name_length = length_of_file_name_and_frills (files + filesno);
3447       max_name_length = line_fmt->col_arr[col];
3448     }
3449   putchar ('\n');
3450 }
3451
3452 static void
3453 print_with_commas (void)
3454 {
3455   int filesno;
3456   int pos, old_pos;
3457
3458   pos = 0;
3459
3460   for (filesno = 0; filesno < files_index; filesno++)
3461     {
3462       old_pos = pos;
3463
3464       pos += length_of_file_name_and_frills (files + filesno);
3465       if (filesno + 1 < files_index)
3466         pos += 2;               /* For the comma and space */
3467
3468       if (old_pos != 0 && pos >= line_length)
3469         {
3470           putchar ('\n');
3471           pos -= old_pos;
3472         }
3473
3474       print_file_name_and_frills (files + filesno);
3475       if (filesno + 1 < files_index)
3476         {
3477           putchar (',');
3478           putchar (' ');
3479         }
3480     }
3481   putchar ('\n');
3482 }
3483
3484 /* Assuming cursor is at position FROM, indent up to position TO.
3485    Use a TAB character instead of two or more spaces whenever possible.  */
3486
3487 static void
3488 indent (int from, int to)
3489 {
3490   while (from < to)
3491     {
3492       if (tabsize > 0 && to / tabsize > (from + 1) / tabsize)
3493         {
3494           putchar ('\t');
3495           from += tabsize - from % tabsize;
3496         }
3497       else
3498         {
3499           putchar (' ');
3500           from++;
3501         }
3502     }
3503 }
3504
3505 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
3506 /* FIXME: maybe remove this function someday.  See about using a
3507    non-malloc'ing version of path_concat.  */
3508
3509 static void
3510 attach (char *dest, const char *dirname, const char *name)
3511 {
3512   const char *dirnamep = dirname;
3513
3514   /* Copy dirname if it is not ".". */
3515   if (dirname[0] != '.' || dirname[1] != 0)
3516     {
3517       while (*dirnamep)
3518         *dest++ = *dirnamep++;
3519       /* Add '/' if `dirname' doesn't already end with it. */
3520       if (dirnamep > dirname && dirnamep[-1] != '/')
3521         *dest++ = '/';
3522     }
3523   while (*name)
3524     *dest++ = *name++;
3525   *dest = 0;
3526 }
3527
3528 static void
3529 init_column_info (void)
3530 {
3531   int i;
3532   int allocate = 0;
3533
3534   max_idx = line_length / MIN_COLUMN_WIDTH;
3535   if (max_idx == 0)
3536     max_idx = 1;
3537
3538   if (column_info == NULL)
3539     {
3540       column_info = XMALLOC (struct column_info, max_idx);
3541       allocate = 1;
3542     }
3543
3544   for (i = 0; i < max_idx; ++i)
3545     {
3546       int j;
3547
3548       column_info[i].valid_len = 1;
3549       column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
3550
3551       if (allocate)
3552         column_info[i].col_arr = XMALLOC (int, i + 1);
3553
3554       for (j = 0; j <= i; ++j)
3555         column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
3556     }
3557 }
3558
3559 void
3560 usage (int status)
3561 {
3562   if (status != 0)
3563     fprintf (stderr, _("Try `%s --help' for more information.\n"),
3564              program_name);
3565   else
3566     {
3567       printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
3568       fputs (_("\
3569 List information about the FILEs (the current directory by default).\n\
3570 Sort entries alphabetically if none of -cftuSUX nor --sort.\n\
3571 \n\
3572 "), stdout);
3573       fputs (_("\
3574 Mandatory arguments to long options are mandatory for short options too.\n\
3575 "), stdout);
3576       fputs (_("\
3577   -a, --all                  do not hide entries starting with .\n\
3578   -A, --almost-all           do not list implied . and ..\n\
3579   -b, --escape               print octal escapes for nongraphic characters\n\
3580 "), stdout);
3581       fputs (_("\
3582       --block-size=SIZE      use SIZE-byte blocks\n\
3583   -B, --ignore-backups       do not list implied entries ending with ~\n\
3584   -c                         with -lt: sort by, and show, ctime (time of last\n\
3585                                modification of file status information)\n\
3586                                with -l: show ctime and sort by name\n\
3587                                otherwise: sort by ctime\n\
3588 "), stdout);
3589       fputs (_("\
3590   -C                         list entries by columns\n\
3591       --color[=WHEN]         control whether color is used to distinguish file\n\
3592                                types.  WHEN may be `never', `always', or `auto'\n\
3593   -d, --directory            list directory entries instead of contents\n\
3594   -D, --dired                generate output designed for Emacs' dired mode\n\
3595 "), stdout);
3596       fputs (_("\
3597   -f                         do not sort, enable -aU, disable -lst\n\
3598   -F, --classify             append indicator (one of */=@|) to entries\n\
3599       --format=WORD          across -x, commas -m, horizontal -x, long -l,\n\
3600                                single-column -1, verbose -l, vertical -C\n\
3601       --full-time            like -l --time-style=full-iso\n\
3602 "), stdout);
3603       fputs (_("\
3604   -g                         like -l, but do not list owner\n\
3605   -G, --no-group             inhibit display of group information\n\
3606   -h, --human-readable  print sizes in human readable format (e.g., 1K 234M 2G)\n\
3607       --si                   likewise, but use powers of 1000 not 1024\n\
3608   -H, --dereference-command-line  follow symbolic links on the command line\n\
3609 "), stdout);
3610       fputs (_("\
3611       --indicator-style=WORD append indicator with style WORD to entry names:\n\
3612                                none (default), classify (-F), file-type (-p)\n\
3613   -i, --inode                print index number of each file\n\
3614   -I, --ignore=PATTERN       do not list implied entries matching shell PATTERN\n\
3615   -k                         like --block-size=1K\n\
3616 "), stdout);
3617       fputs (_("\
3618   -l                         use a long listing format\n\
3619   -L, --dereference          when showing file information for a symbolic\n\
3620                                link, show information for the file the link\n\
3621                                references rather than for the link itself\n\
3622   -m                         fill width with a comma separated list of entries\n\
3623 "), stdout);
3624       fputs (_("\
3625   -n, --numeric-uid-gid      like -l, but list numeric UIDs and GIDs\n\
3626   -N, --literal              print raw entry names (don't treat e.g. control\n\
3627                                characters specially)\n\
3628   -o                         like -l, but do not list group information\n\
3629   -p, --file-type            append indicator (one of /=@|) to entries\n\
3630 "), stdout);
3631       fputs (_("\
3632   -q, --hide-control-chars   print ? instead of non graphic characters\n\
3633       --show-control-chars   show non graphic characters as-is (default\n\
3634                              unless program is `ls' and output is a terminal)\n\
3635   -Q, --quote-name           enclose entry names in double quotes\n\
3636       --quoting-style=WORD   use quoting style WORD for entry names:\n\
3637                                literal, locale, shell, shell-always, c, escape\n\
3638 "), stdout);
3639       fputs (_("\
3640   -r, --reverse              reverse order while sorting\n\
3641   -R, --recursive            list subdirectories recursively\n\
3642   -s, --size                 print size of each file, in blocks\n\
3643 "), stdout);
3644       fputs (_("\
3645   -S                         sort by file size\n\
3646       --sort=WORD            extension -X, none -U, size -S, time -t,\n\
3647                                version -v\n\
3648                              status -c, time -t, atime -u, access -u, use -u\n\
3649       --time=WORD            show time as WORD instead of modification time:\n\
3650                                atime, access, use, ctime or status; use\n\
3651                                specified time as sort key if --sort=time\n\
3652 "), stdout);
3653       fputs (_("\
3654       --time-style=WORD      show times using style WORD:\n\
3655                                full-iso, iso, locale, posix-iso\n\
3656   -t                         sort by modification time\n\
3657   -T, --tabsize=COLS         assume tab stops at each COLS instead of 8\n\
3658 "), stdout);
3659       fputs (_("\
3660   -u                         with -lt: sort by, and show, access time\n\
3661                                with -l: show access time and sort by name\n\
3662                                otherwise: sort by access time\n\
3663   -U                         do not sort; list entries in directory order\n\
3664   -v                         sort by version\n\
3665 "), stdout);
3666       fputs (_("\
3667   -w, --width=COLS           assume screen width instead of current value\n\
3668   -x                         list entries by lines instead of by columns\n\
3669   -X                         sort alphabetically by entry extension\n\
3670   -1                         list one file per line\n\
3671 "), stdout);
3672       fputs (HELP_OPTION_DESCRIPTION, stdout);
3673       fputs (VERSION_OPTION_DESCRIPTION, stdout);
3674       fputs (_("\n\
3675 SIZE may be (or may be an integer optionally followed by) one of following:\n\
3676 kB 1000, K 1024, MB 1,000,000, M 1,048,576, and so on for G, T, P, E, Z, Y.\n\
3677 "), stdout);
3678       fputs (_("\
3679 \n\
3680 By default, color is not used to distinguish types of files.  That is\n\
3681 equivalent to using --color=none.  Using the --color option without the\n\
3682 optional WHEN argument is equivalent to using --color=always.  With\n\
3683 --color=auto, color codes are output only if standard output is connected\n\
3684 to a terminal (tty).\n\
3685 "), stdout);
3686       puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
3687     }
3688   exit (status);
3689 }