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