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