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