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