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