maint: refactor SMACK interface to a separate module
[coreutils.git] / src / ls.c
blobe341c6799dc6dcfd32c9ebead205c8174b0141db
1 /* 'dir', 'vdir' and 'ls' directory listing programs for GNU.
2 Copyright (C) 1985-2013 Free Software Foundation, Inc.
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.
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.
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/>. */
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.
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.
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. */
32 /* Written by Richard Stallman and David MacKenzie. */
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>. */
38 #include <config.h>
39 #include <sys/types.h>
41 #include <termios.h>
42 #if HAVE_STROPTS_H
43 # include <stropts.h>
44 #endif
45 #include <sys/ioctl.h>
47 #ifdef WINSIZE_IN_PTEM
48 # include <sys/stream.h>
49 # include <sys/ptem.h>
50 #endif
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>
61 #if HAVE_LANGINFO_CODESET
62 # include <langinfo.h>
63 #endif
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
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
84 #include "system.h"
85 #include <fnmatch.h>
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"
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
119 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
120 : (ls_mode == LS_MULTI_COL \
121 ? "dir" : "vdir"))
123 #define AUTHORS \
124 proper_name ("Richard M. Stallman"), \
125 proper_name ("David MacKenzie")
127 #define obstack_chunk_alloc malloc
128 #define obstack_chunk_free free
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))
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. */
144 #ifndef READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
145 # define READDIR_LIES_ABOUT_MOUNTPOINT_D_INO 1
146 #endif
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
154 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
155 # define st_author st_uid
156 #endif
158 enum filetype
160 unknown,
161 fifo,
162 chardev,
163 directory,
164 blockdev,
165 normal,
166 symbolic_link,
167 sock,
168 whiteout,
169 arg_directory
172 /* Display letters and indicators for each filetype.
173 Keep these in sync with enum filetype. */
174 static char const filetype_letter[] = "?pcdb-lswd";
176 /* Ensure that filetype and filetype_letter have the same
177 number of elements. */
178 verify (sizeof filetype_letter - 1 == arg_directory + 1);
180 #define FILETYPE_INDICATORS \
182 C_ORPHAN, C_FIFO, C_CHR, C_DIR, C_BLK, C_FILE, \
183 C_LINK, C_SOCK, C_FILE, C_DIR \
186 enum acl_type
188 ACL_T_NONE,
189 ACL_T_SELINUX_ONLY,
190 ACL_T_YES
193 struct fileinfo
195 /* The file name. */
196 char *name;
198 /* For symbolic link, name of the file linked to, otherwise zero. */
199 char *linkname;
201 struct stat stat;
203 enum filetype filetype;
205 /* For symbolic link and long listing, st_mode of file linked to, otherwise
206 zero. */
207 mode_t linkmode;
209 /* SELinux security context. */
210 security_context_t scontext;
212 bool stat_ok;
214 /* For symbolic link and color printing, true if linked-to file
215 exists, otherwise false. */
216 bool linkok;
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;
222 /* For color listings, true if a regular file has capability info. */
223 bool has_capability;
226 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
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. */
232 struct bin_str
234 size_t len; /* Number of bytes */
235 const char *string; /* Pointer to the same */
238 #if ! HAVE_TCGETPGRP
239 # define tcgetpgrp(Fd) 0
240 #endif
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);
286 /* Initial size of hash table.
287 Most hierarchies are likely to be shallower than this. */
288 #define INITIAL_TABLE_SIZE 30
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;
299 #define LOOP_DETECT (!!active_dir_set)
301 /* The table of files in the current directory:
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. */
307 /* Address of block containing the files that are described. */
308 static struct fileinfo *cwd_file;
310 /* Length of block that 'cwd_file' points to, measured in files. */
311 static size_t cwd_n_alloc;
313 /* Index of first unused slot in 'cwd_file'. */
314 static size_t cwd_n_used;
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;
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. */
326 static bool color_symlink_as_referent;
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)
334 /* Record of one pending directory waiting to be listed. */
336 struct pending
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;
347 static struct pending *pending_dirs;
349 /* Current time in seconds and nanoseconds since 1970, updated as
350 needed when deciding whether a file is recent. */
352 static struct timespec current_time;
354 static bool print_scontext;
355 static char UNKNOWN_SECURITY_CONTEXT[] = "?";
357 /* Whether any of the files has an ACL. This affects the width of the
358 mode column. */
360 static bool any_has_acl;
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. */
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;
377 /* Option flags */
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.
385 -l (and other options that imply -l), -1, -C, -x and -m control
386 this parameter. */
388 enum format
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 */
397 static enum format format;
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
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 */
410 static char const *const time_style_args[] =
412 "full-iso", "long-iso", "iso", "locale", NULL
414 static enum time_style const time_style_types[] =
416 full_iso_time_style, long_iso_time_style, iso_time_style,
417 locale_time_style
419 ARGMATCH_VERIFY (time_style_args, time_style_types);
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()). */
425 enum time_type
427 time_mtime, /* default */
428 time_ctime, /* -c */
429 time_atime, /* -u */
430 time_numtypes /* the number of elements of this enum */
433 static enum time_type time_type;
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()). */
439 enum sort_type
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 */
450 static enum sort_type sort_type;
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 */
458 static bool sort_reverse;
460 /* True means to display owner information. -g turns this off. */
462 static bool print_owner = true;
464 /* True means to display author information. */
466 static bool print_author;
468 /* True means to display group information. -G and -o turn this off. */
470 static bool print_group = true;
472 /* True means print the user and group id's as numbers rather
473 than as names. -n */
475 static bool numeric_ids;
477 /* True means mention the size in blocks of each file. -s */
479 static bool print_block_size;
481 /* Human-readable options for output, when printing block counts. */
482 static int human_output_opts;
484 /* The units to use when printing block counts. */
485 static uintmax_t output_block_size;
487 /* Likewise, but for file sizes. */
488 static int file_human_output_opts;
489 static uintmax_t file_output_block_size = 1;
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;
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.
501 Controlled by -F, -p, and --indicator-style. */
503 enum indicator_style
505 none, /* --indicator-style=none */
506 slash, /* -p, --indicator-style=slash */
507 file_type, /* --indicator-style=file-type */
508 classify /* -F, --indicator-style=classify */
511 static enum indicator_style indicator_style;
513 /* Names of indicator styles. */
514 static char const *const indicator_style_args[] =
516 "none", "slash", "file-type", "classify", NULL
518 static enum indicator_style const indicator_style_types[] =
520 none, slash, file_type, classify
522 ARGMATCH_VERIFY (indicator_style_args, indicator_style_types);
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. */
528 static bool print_with_color;
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. */
534 static bool used_color = false;
536 enum color_type
538 color_never, /* 0: default or --color=never */
539 color_always, /* 1: --color=always */
540 color_if_tty /* 2: --color=tty */
543 enum Dereference_symlink
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 */
552 enum indicator_no
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
561 static const char *const indicator_name[]=
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
568 struct color_ext_type
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 */
575 static struct bin_str color_indicator[] =
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 */
603 /* FIXME: comment */
604 static struct color_ext_type *color_ext_list = NULL;
606 /* Buffer for color sequences */
607 static char *color_buf;
609 /* True means to check for orphaned symbolic link, for displaying
610 colors. */
612 static bool check_symlink_color;
614 /* True means mention the inode number of each file. -i */
616 static bool print_inode;
618 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
619 other options that imply -l), and -L. */
621 static enum Dereference_symlink dereference;
623 /* True means when a directory is found, display info on its
624 contents. -R */
626 static bool recursive;
628 /* True means when an argument is a directory name, display info
629 on it itself. -d */
631 static bool immediate_dirs;
633 /* True means that directories are grouped before files. */
635 static bool directories_first;
637 /* Which files to ignore. */
639 static enum
641 /* Ignore files whose names start with '.', and files specified by
642 --hide and --ignore. */
643 IGNORE_DEFAULT,
645 /* Ignore '.', '..', and files specified by --ignore. */
646 IGNORE_DOT_AND_DOTDOT,
648 /* Ignore only files specified by --ignore. */
649 IGNORE_MINIMAL
650 } ignore_mode;
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. */
657 struct ignore_pattern
659 const char *pattern;
660 struct ignore_pattern *next;
663 static struct ignore_pattern *ignore_patterns;
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;
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;
680 /* Quoting options for file and dir name output. */
682 static struct quoting_options *filename_quoting_options;
683 static struct quoting_options *dirname_quoting_options;
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;
689 /* True means print each directory name before listing it. */
691 static bool print_dir_name;
693 /* The line length to use for breaking lines in many-per-line format.
694 Can be set with -w. */
696 static size_t line_length;
698 /* If true, the file listing format requires that stat be called on
699 each file. */
701 static bool format_needs_stat;
703 /* Similar to 'format_needs_stat', but set if only the file type is
704 needed. */
706 static bool format_needs_type;
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. */
714 enum { TIME_STAMP_LEN_MAXIMUM = MAX (1000, INT_STRLEN_BOUND (time_t)) };
716 /* strftime formats for non-recent and recent files, respectively, in
717 -l output. */
719 static char const *long_time_format[2] =
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")
749 /* The set of signals that are caught. */
751 static sigset_t caught_signals;
753 /* If nonzero, the value of the pending fatal signal. */
755 static sig_atomic_t volatile interrupt_signal;
757 /* A count of the number of pending stop signals that have been received. */
759 static sig_atomic_t volatile stop_signal_count;
761 /* Desired exit status. */
763 static int exit_status;
765 /* Exit statuses. */
766 enum
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,
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
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
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
801 static struct option const long_options[] =
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}
850 static char const *const format_args[] =
852 "verbose", "long", "commas", "horizontal", "across",
853 "vertical", "single-column", NULL
855 static enum format const format_types[] =
857 long_format, long_format, with_commas, horizontal, horizontal,
858 many_per_line, one_per_line
860 ARGMATCH_VERIFY (format_args, format_types);
862 static char const *const sort_args[] =
864 "none", "time", "size", "extension", "version", NULL
866 static enum sort_type const sort_types[] =
868 sort_none, sort_time, sort_size, sort_extension, sort_version
870 ARGMATCH_VERIFY (sort_args, sort_types);
872 static char const *const time_args[] =
874 "atime", "access", "use", "ctime", "status", NULL
876 static enum time_type const time_types[] =
878 time_atime, time_atime, time_atime, time_ctime, time_ctime
880 ARGMATCH_VERIFY (time_args, time_types);
882 static char const *const color_args[] =
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
889 static enum color_type const color_types[] =
891 color_always, color_always, color_always,
892 color_never, color_never, color_never,
893 color_if_tty, color_if_tty, color_if_tty
895 ARGMATCH_VERIFY (color_args, color_types);
897 /* Information about filling a column. */
898 struct column_info
900 bool valid_len;
901 size_t line_len;
902 size_t *col_arr;
905 /* Array with information about column filledness. */
906 static struct column_info *column_info;
908 /* Maximum number of columns ever possible for this display. */
909 static size_t max_idx;
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
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;
923 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
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)
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)
933 #define DIRED_INDENT() \
934 do \
936 if (dired) \
937 DIRED_FPUTS_LITERAL (" ", stdout); \
939 while (0)
941 /* With --dired, store pairs of beginning and ending indices of filenames. */
942 static struct obstack dired_obstack;
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;
951 /* Save the current index on the specified obstack, OBS. */
952 #define PUSH_CURRENT_DIRED_POS(obs) \
953 do \
955 if (dired) \
956 obstack_grow (obs, &dired_pos, sizeof (dired_pos)); \
958 while (0)
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;
965 /* Push a pair onto the device/inode stack. */
966 static void
967 dev_ino_push (dev_t dev, ino_t ino)
969 void *vdi;
970 struct dev_ino *di;
971 int dev_ino_size = sizeof *di;
972 obstack_blank (&dev_ino_obstack, dev_ino_size);
973 vdi = obstack_next_free (&dev_ino_obstack);
974 di = vdi;
975 di--;
976 di->st_dev = dev;
977 di->st_ino = ino;
980 /* Pop a dev/ino struct off the global dev_ino_obstack
981 and return that struct. */
982 static struct dev_ino
983 dev_ino_pop (void)
985 void *vdi;
986 struct dev_ino *di;
987 int dev_ino_size = sizeof *di;
988 assert (dev_ino_size <= obstack_object_size (&dev_ino_obstack));
989 obstack_blank (&dev_ino_obstack, -dev_ino_size);
990 vdi = obstack_next_free (&dev_ino_obstack);
991 di = vdi;
992 return *di;
995 /* Note the use commented out below:
996 #define ASSERT_MATCHING_DEV_INO(Name, Di) \
997 do \
999 struct stat sb; \
1000 assert (Name); \
1001 assert (0 <= stat (Name, &sb)); \
1002 assert (sb.st_dev == Di.st_dev); \
1003 assert (sb.st_ino == Di.st_ino); \
1005 while (0)
1008 /* Write to standard output PREFIX, followed by the quoting style and
1009 a space-separated list of the integers stored in OS all on one line. */
1011 static void
1012 dired_dump_obstack (const char *prefix, struct obstack *os)
1014 size_t n_pos;
1016 n_pos = obstack_object_size (os) / sizeof (dired_pos);
1017 if (n_pos > 0)
1019 size_t i;
1020 size_t *pos;
1022 pos = (size_t *) obstack_finish (os);
1023 fputs (prefix, stdout);
1024 for (i = 0; i < n_pos; i++)
1025 printf (" %lu", (unsigned long int) pos[i]);
1026 putchar ('\n');
1030 /* Read the abbreviated month names from the locale, to align them
1031 and to determine the max width of the field and to truncate names
1032 greater than our max allowed.
1033 Note even though this handles multibyte locales correctly
1034 it's not restricted to them as single byte locales can have
1035 variable width abbreviated months and also precomputing/caching
1036 the names was seen to increase the performance of ls significantly. */
1038 /* max number of display cells to use */
1039 enum { MAX_MON_WIDTH = 5 };
1040 /* In the unlikely event that the abmon[] storage is not big enough
1041 an error message will be displayed, and we revert to using
1042 unmodified abbreviated month names from the locale database. */
1043 static char abmon[12][MAX_MON_WIDTH * 2 * MB_LEN_MAX + 1];
1044 /* minimum width needed to align %b, 0 => don't use precomputed values. */
1045 static size_t required_mon_width;
1047 static size_t
1048 abmon_init (void)
1050 #ifdef HAVE_NL_LANGINFO
1051 required_mon_width = MAX_MON_WIDTH;
1052 size_t curr_max_width;
1055 curr_max_width = required_mon_width;
1056 required_mon_width = 0;
1057 for (int i = 0; i < 12; i++)
1059 size_t width = curr_max_width;
1061 size_t req = mbsalign (nl_langinfo (ABMON_1 + i),
1062 abmon[i], sizeof (abmon[i]),
1063 &width, MBS_ALIGN_LEFT, 0);
1065 if (req == (size_t) -1 || req >= sizeof (abmon[i]))
1067 required_mon_width = 0; /* ignore precomputed strings. */
1068 return required_mon_width;
1071 required_mon_width = MAX (required_mon_width, width);
1074 while (curr_max_width > required_mon_width);
1075 #endif
1077 return required_mon_width;
1080 static size_t
1081 dev_ino_hash (void const *x, size_t table_size)
1083 struct dev_ino const *p = x;
1084 return (uintmax_t) p->st_ino % table_size;
1087 static bool
1088 dev_ino_compare (void const *x, void const *y)
1090 struct dev_ino const *a = x;
1091 struct dev_ino const *b = y;
1092 return SAME_INODE (*a, *b) ? true : false;
1095 static void
1096 dev_ino_free (void *x)
1098 free (x);
1101 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
1102 active directories. Return true if there is already a matching
1103 entry in the table. */
1105 static bool
1106 visit_dir (dev_t dev, ino_t ino)
1108 struct dev_ino *ent;
1109 struct dev_ino *ent_from_table;
1110 bool found_match;
1112 ent = xmalloc (sizeof *ent);
1113 ent->st_ino = ino;
1114 ent->st_dev = dev;
1116 /* Attempt to insert this entry into the table. */
1117 ent_from_table = hash_insert (active_dir_set, ent);
1119 if (ent_from_table == NULL)
1121 /* Insertion failed due to lack of memory. */
1122 xalloc_die ();
1125 found_match = (ent_from_table != ent);
1127 if (found_match)
1129 /* ent was not inserted, so free it. */
1130 free (ent);
1133 return found_match;
1136 static void
1137 free_pending_ent (struct pending *p)
1139 free (p->name);
1140 free (p->realname);
1141 free (p);
1144 static bool
1145 is_colored (enum indicator_no type)
1147 size_t len = color_indicator[type].len;
1148 char const *s = color_indicator[type].string;
1149 return ! (len == 0
1150 || (len == 1 && STRNCMP_LIT (s, "0") == 0)
1151 || (len == 2 && STRNCMP_LIT (s, "00") == 0));
1154 static void
1155 restore_default_color (void)
1157 put_indicator (&color_indicator[C_LEFT]);
1158 put_indicator (&color_indicator[C_RIGHT]);
1161 static void
1162 set_normal_color (void)
1164 if (print_with_color && is_colored (C_NORM))
1166 put_indicator (&color_indicator[C_LEFT]);
1167 put_indicator (&color_indicator[C_NORM]);
1168 put_indicator (&color_indicator[C_RIGHT]);
1172 /* An ordinary signal was received; arrange for the program to exit. */
1174 static void
1175 sighandler (int sig)
1177 if (! SA_NOCLDSTOP)
1178 signal (sig, SIG_IGN);
1179 if (! interrupt_signal)
1180 interrupt_signal = sig;
1183 /* A SIGTSTP was received; arrange for the program to suspend itself. */
1185 static void
1186 stophandler (int sig)
1188 if (! SA_NOCLDSTOP)
1189 signal (sig, stophandler);
1190 if (! interrupt_signal)
1191 stop_signal_count++;
1194 /* Process any pending signals. If signals are caught, this function
1195 should be called periodically. Ideally there should never be an
1196 unbounded amount of time when signals are not being processed.
1197 Signal handling can restore the default colors, so callers must
1198 immediately change colors after invoking this function. */
1200 static void
1201 process_signals (void)
1203 while (interrupt_signal || stop_signal_count)
1205 int sig;
1206 int stops;
1207 sigset_t oldset;
1209 if (used_color)
1210 restore_default_color ();
1211 fflush (stdout);
1213 sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
1215 /* Reload interrupt_signal and stop_signal_count, in case a new
1216 signal was handled before sigprocmask took effect. */
1217 sig = interrupt_signal;
1218 stops = stop_signal_count;
1220 /* SIGTSTP is special, since the application can receive that signal
1221 more than once. In this case, don't set the signal handler to the
1222 default. Instead, just raise the uncatchable SIGSTOP. */
1223 if (stops)
1225 stop_signal_count = stops - 1;
1226 sig = SIGSTOP;
1228 else
1229 signal (sig, SIG_DFL);
1231 /* Exit or suspend the program. */
1232 raise (sig);
1233 sigprocmask (SIG_SETMASK, &oldset, NULL);
1235 /* If execution reaches here, then the program has been
1236 continued (after being suspended). */
1241 main (int argc, char **argv)
1243 int i;
1244 struct pending *thispend;
1245 int n_files;
1247 /* The signals that are trapped, and the number of such signals. */
1248 static int const sig[] =
1250 /* This one is handled specially. */
1251 SIGTSTP,
1253 /* The usual suspects. */
1254 SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM,
1255 #ifdef SIGPOLL
1256 SIGPOLL,
1257 #endif
1258 #ifdef SIGPROF
1259 SIGPROF,
1260 #endif
1261 #ifdef SIGVTALRM
1262 SIGVTALRM,
1263 #endif
1264 #ifdef SIGXCPU
1265 SIGXCPU,
1266 #endif
1267 #ifdef SIGXFSZ
1268 SIGXFSZ,
1269 #endif
1271 enum { nsigs = ARRAY_CARDINALITY (sig) };
1273 #if ! SA_NOCLDSTOP
1274 bool caught_sig[nsigs];
1275 #endif
1277 initialize_main (&argc, &argv);
1278 set_program_name (argv[0]);
1279 setlocale (LC_ALL, "");
1280 bindtextdomain (PACKAGE, LOCALEDIR);
1281 textdomain (PACKAGE);
1283 initialize_exit_failure (LS_FAILURE);
1284 atexit (close_stdout);
1286 assert (ARRAY_CARDINALITY (color_indicator) + 1
1287 == ARRAY_CARDINALITY (indicator_name));
1289 exit_status = EXIT_SUCCESS;
1290 print_dir_name = true;
1291 pending_dirs = NULL;
1293 current_time.tv_sec = TYPE_MINIMUM (time_t);
1294 current_time.tv_nsec = -1;
1296 i = decode_switches (argc, argv);
1298 if (print_with_color)
1299 parse_ls_color ();
1301 /* Test print_with_color again, because the call to parse_ls_color
1302 may have just reset it -- e.g., if LS_COLORS is invalid. */
1303 if (print_with_color)
1305 /* Avoid following symbolic links when possible. */
1306 if (is_colored (C_ORPHAN)
1307 || (is_colored (C_EXEC) && color_symlink_as_referent)
1308 || (is_colored (C_MISSING) && format == long_format))
1309 check_symlink_color = true;
1311 /* If the standard output is a controlling terminal, watch out
1312 for signals, so that the colors can be restored to the
1313 default state if "ls" is suspended or interrupted. */
1315 if (0 <= tcgetpgrp (STDOUT_FILENO))
1317 int j;
1318 #if SA_NOCLDSTOP
1319 struct sigaction act;
1321 sigemptyset (&caught_signals);
1322 for (j = 0; j < nsigs; j++)
1324 sigaction (sig[j], NULL, &act);
1325 if (act.sa_handler != SIG_IGN)
1326 sigaddset (&caught_signals, sig[j]);
1329 act.sa_mask = caught_signals;
1330 act.sa_flags = SA_RESTART;
1332 for (j = 0; j < nsigs; j++)
1333 if (sigismember (&caught_signals, sig[j]))
1335 act.sa_handler = sig[j] == SIGTSTP ? stophandler : sighandler;
1336 sigaction (sig[j], &act, NULL);
1338 #else
1339 for (j = 0; j < nsigs; j++)
1341 caught_sig[j] = (signal (sig[j], SIG_IGN) != SIG_IGN);
1342 if (caught_sig[j])
1344 signal (sig[j], sig[j] == SIGTSTP ? stophandler : sighandler);
1345 siginterrupt (sig[j], 0);
1348 #endif
1352 if (dereference == DEREF_UNDEFINED)
1353 dereference = ((immediate_dirs
1354 || indicator_style == classify
1355 || format == long_format)
1356 ? DEREF_NEVER
1357 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
1359 /* When using -R, initialize a data structure we'll use to
1360 detect any directory cycles. */
1361 if (recursive)
1363 active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, NULL,
1364 dev_ino_hash,
1365 dev_ino_compare,
1366 dev_ino_free);
1367 if (active_dir_set == NULL)
1368 xalloc_die ();
1370 obstack_init (&dev_ino_obstack);
1373 format_needs_stat = sort_type == sort_time || sort_type == sort_size
1374 || format == long_format
1375 || print_scontext
1376 || print_block_size;
1377 format_needs_type = (! format_needs_stat
1378 && (recursive
1379 || print_with_color
1380 || indicator_style != none
1381 || directories_first));
1383 if (dired)
1385 obstack_init (&dired_obstack);
1386 obstack_init (&subdired_obstack);
1389 cwd_n_alloc = 100;
1390 cwd_file = xnmalloc (cwd_n_alloc, sizeof *cwd_file);
1391 cwd_n_used = 0;
1393 clear_files ();
1395 n_files = argc - i;
1397 if (n_files <= 0)
1399 if (immediate_dirs)
1400 gobble_file (".", directory, NOT_AN_INODE_NUMBER, true, "");
1401 else
1402 queue_directory (".", NULL, true);
1404 else
1406 gobble_file (argv[i++], unknown, NOT_AN_INODE_NUMBER, true, "");
1407 while (i < argc);
1409 if (cwd_n_used)
1411 sort_files ();
1412 if (!immediate_dirs)
1413 extract_dirs_from_files (NULL, true);
1414 /* 'cwd_n_used' might be zero now. */
1417 /* In the following if/else blocks, it is sufficient to test 'pending_dirs'
1418 (and not pending_dirs->name) because there may be no markers in the queue
1419 at this point. A marker may be enqueued when extract_dirs_from_files is
1420 called with a non-empty string or via print_dir. */
1421 if (cwd_n_used)
1423 print_current_files ();
1424 if (pending_dirs)
1425 DIRED_PUTCHAR ('\n');
1427 else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1428 print_dir_name = false;
1430 while (pending_dirs)
1432 thispend = pending_dirs;
1433 pending_dirs = pending_dirs->next;
1435 if (LOOP_DETECT)
1437 if (thispend->name == NULL)
1439 /* thispend->name == NULL means this is a marker entry
1440 indicating we've finished processing the directory.
1441 Use its dev/ino numbers to remove the corresponding
1442 entry from the active_dir_set hash table. */
1443 struct dev_ino di = dev_ino_pop ();
1444 struct dev_ino *found = hash_delete (active_dir_set, &di);
1445 /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
1446 assert (found);
1447 dev_ino_free (found);
1448 free_pending_ent (thispend);
1449 continue;
1453 print_dir (thispend->name, thispend->realname,
1454 thispend->command_line_arg);
1456 free_pending_ent (thispend);
1457 print_dir_name = true;
1460 if (print_with_color)
1462 int j;
1464 if (used_color)
1466 /* Skip the restore when it would be a no-op, i.e.,
1467 when left is "\033[" and right is "m". */
1468 if (!(color_indicator[C_LEFT].len == 2
1469 && memcmp (color_indicator[C_LEFT].string, "\033[", 2) == 0
1470 && color_indicator[C_RIGHT].len == 1
1471 && color_indicator[C_RIGHT].string[0] == 'm'))
1472 restore_default_color ();
1474 fflush (stdout);
1476 /* Restore the default signal handling. */
1477 #if SA_NOCLDSTOP
1478 for (j = 0; j < nsigs; j++)
1479 if (sigismember (&caught_signals, sig[j]))
1480 signal (sig[j], SIG_DFL);
1481 #else
1482 for (j = 0; j < nsigs; j++)
1483 if (caught_sig[j])
1484 signal (sig[j], SIG_DFL);
1485 #endif
1487 /* Act on any signals that arrived before the default was restored.
1488 This can process signals out of order, but there doesn't seem to
1489 be an easy way to do them in order, and the order isn't that
1490 important anyway. */
1491 for (j = stop_signal_count; j; j--)
1492 raise (SIGSTOP);
1493 j = interrupt_signal;
1494 if (j)
1495 raise (j);
1498 if (dired)
1500 /* No need to free these since we're about to exit. */
1501 dired_dump_obstack ("//DIRED//", &dired_obstack);
1502 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1503 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1504 quoting_style_args[get_quoting_style (filename_quoting_options)]);
1507 if (LOOP_DETECT)
1509 assert (hash_get_n_entries (active_dir_set) == 0);
1510 hash_free (active_dir_set);
1513 exit (exit_status);
1516 /* Set all the option flags according to the switches specified.
1517 Return the index of the first non-option argument. */
1519 static int
1520 decode_switches (int argc, char **argv)
1522 char *time_style_option = NULL;
1524 bool sort_type_specified = false;
1525 bool kibibytes_specified = false;
1527 qmark_funny_chars = false;
1529 /* initialize all switches to default settings */
1531 switch (ls_mode)
1533 case LS_MULTI_COL:
1534 /* This is for the 'dir' program. */
1535 format = many_per_line;
1536 set_quoting_style (NULL, escape_quoting_style);
1537 break;
1539 case LS_LONG_FORMAT:
1540 /* This is for the 'vdir' program. */
1541 format = long_format;
1542 set_quoting_style (NULL, escape_quoting_style);
1543 break;
1545 case LS_LS:
1546 /* This is for the 'ls' program. */
1547 if (isatty (STDOUT_FILENO))
1549 format = many_per_line;
1550 /* See description of qmark_funny_chars, above. */
1551 qmark_funny_chars = true;
1553 else
1555 format = one_per_line;
1556 qmark_funny_chars = false;
1558 break;
1560 default:
1561 abort ();
1564 time_type = time_mtime;
1565 sort_type = sort_name;
1566 sort_reverse = false;
1567 numeric_ids = false;
1568 print_block_size = false;
1569 indicator_style = none;
1570 print_inode = false;
1571 dereference = DEREF_UNDEFINED;
1572 recursive = false;
1573 immediate_dirs = false;
1574 ignore_mode = IGNORE_DEFAULT;
1575 ignore_patterns = NULL;
1576 hide_patterns = NULL;
1577 print_scontext = false;
1579 /* FIXME: put this in a function. */
1581 char const *q_style = getenv ("QUOTING_STYLE");
1582 if (q_style)
1584 int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
1585 if (0 <= i)
1586 set_quoting_style (NULL, quoting_style_vals[i]);
1587 else
1588 error (0, 0,
1589 _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
1590 quotearg (q_style));
1594 line_length = 80;
1596 char const *p = getenv ("COLUMNS");
1597 if (p && *p)
1599 unsigned long int tmp_ulong;
1600 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1601 && 0 < tmp_ulong && tmp_ulong <= SIZE_MAX)
1603 line_length = tmp_ulong;
1605 else
1607 error (0, 0,
1608 _("ignoring invalid width in environment variable COLUMNS: %s"),
1609 quotearg (p));
1614 #ifdef TIOCGWINSZ
1616 struct winsize ws;
1618 if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1
1619 && 0 < ws.ws_col && ws.ws_col == (size_t) ws.ws_col)
1620 line_length = ws.ws_col;
1622 #endif
1625 char const *p = getenv ("TABSIZE");
1626 tabsize = 8;
1627 if (p)
1629 unsigned long int tmp_ulong;
1630 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1631 && tmp_ulong <= SIZE_MAX)
1633 tabsize = tmp_ulong;
1635 else
1637 error (0, 0,
1638 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1639 quotearg (p));
1644 while (true)
1646 int oi = -1;
1647 int c = getopt_long (argc, argv,
1648 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1",
1649 long_options, &oi);
1650 if (c == -1)
1651 break;
1653 switch (c)
1655 case 'a':
1656 ignore_mode = IGNORE_MINIMAL;
1657 break;
1659 case 'b':
1660 set_quoting_style (NULL, escape_quoting_style);
1661 break;
1663 case 'c':
1664 time_type = time_ctime;
1665 break;
1667 case 'd':
1668 immediate_dirs = true;
1669 break;
1671 case 'f':
1672 /* Same as enabling -a -U and disabling -l -s. */
1673 ignore_mode = IGNORE_MINIMAL;
1674 sort_type = sort_none;
1675 sort_type_specified = true;
1676 /* disable -l */
1677 if (format == long_format)
1678 format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
1679 print_block_size = false; /* disable -s */
1680 print_with_color = false; /* disable --color */
1681 break;
1683 case FILE_TYPE_INDICATOR_OPTION: /* --file-type */
1684 indicator_style = file_type;
1685 break;
1687 case 'g':
1688 format = long_format;
1689 print_owner = false;
1690 break;
1692 case 'h':
1693 file_human_output_opts = human_output_opts =
1694 human_autoscale | human_SI | human_base_1024;
1695 file_output_block_size = output_block_size = 1;
1696 break;
1698 case 'i':
1699 print_inode = true;
1700 break;
1702 case 'k':
1703 kibibytes_specified = true;
1704 break;
1706 case 'l':
1707 format = long_format;
1708 break;
1710 case 'm':
1711 format = with_commas;
1712 break;
1714 case 'n':
1715 numeric_ids = true;
1716 format = long_format;
1717 break;
1719 case 'o': /* Just like -l, but don't display group info. */
1720 format = long_format;
1721 print_group = false;
1722 break;
1724 case 'p':
1725 indicator_style = slash;
1726 break;
1728 case 'q':
1729 qmark_funny_chars = true;
1730 break;
1732 case 'r':
1733 sort_reverse = true;
1734 break;
1736 case 's':
1737 print_block_size = true;
1738 break;
1740 case 't':
1741 sort_type = sort_time;
1742 sort_type_specified = true;
1743 break;
1745 case 'u':
1746 time_type = time_atime;
1747 break;
1749 case 'v':
1750 sort_type = sort_version;
1751 sort_type_specified = true;
1752 break;
1754 case 'w':
1756 unsigned long int tmp_ulong;
1757 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1758 || ! (0 < tmp_ulong && tmp_ulong <= SIZE_MAX))
1759 error (LS_FAILURE, 0, _("invalid line width: %s"),
1760 quotearg (optarg));
1761 line_length = tmp_ulong;
1762 break;
1765 case 'x':
1766 format = horizontal;
1767 break;
1769 case 'A':
1770 if (ignore_mode == IGNORE_DEFAULT)
1771 ignore_mode = IGNORE_DOT_AND_DOTDOT;
1772 break;
1774 case 'B':
1775 add_ignore_pattern ("*~");
1776 add_ignore_pattern (".*~");
1777 break;
1779 case 'C':
1780 format = many_per_line;
1781 break;
1783 case 'D':
1784 dired = true;
1785 break;
1787 case 'F':
1788 indicator_style = classify;
1789 break;
1791 case 'G': /* inhibit display of group info */
1792 print_group = false;
1793 break;
1795 case 'H':
1796 dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1797 break;
1799 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
1800 dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
1801 break;
1803 case 'I':
1804 add_ignore_pattern (optarg);
1805 break;
1807 case 'L':
1808 dereference = DEREF_ALWAYS;
1809 break;
1811 case 'N':
1812 set_quoting_style (NULL, literal_quoting_style);
1813 break;
1815 case 'Q':
1816 set_quoting_style (NULL, c_quoting_style);
1817 break;
1819 case 'R':
1820 recursive = true;
1821 break;
1823 case 'S':
1824 sort_type = sort_size;
1825 sort_type_specified = true;
1826 break;
1828 case 'T':
1830 unsigned long int tmp_ulong;
1831 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1832 || SIZE_MAX < tmp_ulong)
1833 error (LS_FAILURE, 0, _("invalid tab size: %s"),
1834 quotearg (optarg));
1835 tabsize = tmp_ulong;
1836 break;
1839 case 'U':
1840 sort_type = sort_none;
1841 sort_type_specified = true;
1842 break;
1844 case 'X':
1845 sort_type = sort_extension;
1846 sort_type_specified = true;
1847 break;
1849 case '1':
1850 /* -1 has no effect after -l. */
1851 if (format != long_format)
1852 format = one_per_line;
1853 break;
1855 case AUTHOR_OPTION:
1856 print_author = true;
1857 break;
1859 case HIDE_OPTION:
1861 struct ignore_pattern *hide = xmalloc (sizeof *hide);
1862 hide->pattern = optarg;
1863 hide->next = hide_patterns;
1864 hide_patterns = hide;
1866 break;
1868 case SORT_OPTION:
1869 sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1870 sort_type_specified = true;
1871 break;
1873 case GROUP_DIRECTORIES_FIRST_OPTION:
1874 directories_first = true;
1875 break;
1877 case TIME_OPTION:
1878 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1879 break;
1881 case FORMAT_OPTION:
1882 format = XARGMATCH ("--format", optarg, format_args, format_types);
1883 break;
1885 case FULL_TIME_OPTION:
1886 format = long_format;
1887 time_style_option = bad_cast ("full-iso");
1888 break;
1890 case COLOR_OPTION:
1892 int i;
1893 if (optarg)
1894 i = XARGMATCH ("--color", optarg, color_args, color_types);
1895 else
1896 /* Using --color with no argument is equivalent to using
1897 --color=always. */
1898 i = color_always;
1900 print_with_color = (i == color_always
1901 || (i == color_if_tty
1902 && isatty (STDOUT_FILENO)));
1904 if (print_with_color)
1906 /* Don't use TAB characters in output. Some terminal
1907 emulators can't handle the combination of tabs and
1908 color codes on the same line. */
1909 tabsize = 0;
1911 break;
1914 case INDICATOR_STYLE_OPTION:
1915 indicator_style = XARGMATCH ("--indicator-style", optarg,
1916 indicator_style_args,
1917 indicator_style_types);
1918 break;
1920 case QUOTING_STYLE_OPTION:
1921 set_quoting_style (NULL,
1922 XARGMATCH ("--quoting-style", optarg,
1923 quoting_style_args,
1924 quoting_style_vals));
1925 break;
1927 case TIME_STYLE_OPTION:
1928 time_style_option = optarg;
1929 break;
1931 case SHOW_CONTROL_CHARS_OPTION:
1932 qmark_funny_chars = false;
1933 break;
1935 case BLOCK_SIZE_OPTION:
1937 enum strtol_error e = human_options (optarg, &human_output_opts,
1938 &output_block_size);
1939 if (e != LONGINT_OK)
1940 xstrtol_fatal (e, oi, 0, long_options, optarg);
1941 file_human_output_opts = human_output_opts;
1942 file_output_block_size = output_block_size;
1944 break;
1946 case SI_OPTION:
1947 file_human_output_opts = human_output_opts =
1948 human_autoscale | human_SI;
1949 file_output_block_size = output_block_size = 1;
1950 break;
1952 case 'Z':
1953 print_scontext = true;
1954 break;
1956 case_GETOPT_HELP_CHAR;
1958 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1960 default:
1961 usage (LS_FAILURE);
1965 if (! output_block_size)
1967 char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
1968 human_options (ls_block_size,
1969 &human_output_opts, &output_block_size);
1970 if (ls_block_size || getenv ("BLOCK_SIZE"))
1972 file_human_output_opts = human_output_opts;
1973 file_output_block_size = output_block_size;
1975 if (kibibytes_specified)
1977 human_output_opts = 0;
1978 output_block_size = 1024;
1982 max_idx = MAX (1, line_length / MIN_COLUMN_WIDTH);
1984 filename_quoting_options = clone_quoting_options (NULL);
1985 if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1986 set_char_quoting (filename_quoting_options, ' ', 1);
1987 if (file_type <= indicator_style)
1989 char const *p;
1990 for (p = &"*=>@|"[indicator_style - file_type]; *p; p++)
1991 set_char_quoting (filename_quoting_options, *p, 1);
1994 dirname_quoting_options = clone_quoting_options (NULL);
1995 set_char_quoting (dirname_quoting_options, ':', 1);
1997 /* --dired is meaningful only with --format=long (-l).
1998 Otherwise, ignore it. FIXME: warn about this?
1999 Alternatively, make --dired imply --format=long? */
2000 if (dired && format != long_format)
2001 dired = false;
2003 /* If -c or -u is specified and not -l (or any other option that implies -l),
2004 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
2005 The behavior of ls when using either -c or -u but with neither -l nor -t
2006 appears to be unspecified by POSIX. So, with GNU ls, '-u' alone means
2007 sort by atime (this is the one that's not specified by the POSIX spec),
2008 -lu means show atime and sort by name, -lut means show atime and sort
2009 by atime. */
2011 if ((time_type == time_ctime || time_type == time_atime)
2012 && !sort_type_specified && format != long_format)
2014 sort_type = sort_time;
2017 if (format == long_format)
2019 char *style = time_style_option;
2020 static char const posix_prefix[] = "posix-";
2022 if (! style)
2023 if (! (style = getenv ("TIME_STYLE")))
2024 style = bad_cast ("locale");
2026 while (STREQ_LEN (style, posix_prefix, sizeof posix_prefix - 1))
2028 if (! hard_locale (LC_TIME))
2029 return optind;
2030 style += sizeof posix_prefix - 1;
2033 if (*style == '+')
2035 char *p0 = style + 1;
2036 char *p1 = strchr (p0, '\n');
2037 if (! p1)
2038 p1 = p0;
2039 else
2041 if (strchr (p1 + 1, '\n'))
2042 error (LS_FAILURE, 0, _("invalid time style format %s"),
2043 quote (p0));
2044 *p1++ = '\0';
2046 long_time_format[0] = p0;
2047 long_time_format[1] = p1;
2049 else
2051 ptrdiff_t res = argmatch (style, time_style_args,
2052 (char const *) time_style_types,
2053 sizeof (*time_style_types));
2054 if (res < 0)
2056 /* This whole block used to be a simple use of XARGMATCH.
2057 but that didn't print the "posix-"-prefixed variants or
2058 the "+"-prefixed format string option upon failure. */
2059 argmatch_invalid ("time style", style, res);
2061 /* The following is a manual expansion of argmatch_valid,
2062 but with the added "+ ..." description and the [posix-]
2063 prefixes prepended. Note that this simplification works
2064 only because all four existing time_style_types values
2065 are distinct. */
2066 fputs (_("Valid arguments are:\n"), stderr);
2067 char const *const *p = time_style_args;
2068 while (*p)
2069 fprintf (stderr, " - [posix-]%s\n", *p++);
2070 fputs (_(" - +FORMAT (e.g., +%H:%M) for a 'date'-style"
2071 " format\n"), stderr);
2072 usage (LS_FAILURE);
2074 switch (res)
2076 case full_iso_time_style:
2077 long_time_format[0] = long_time_format[1] =
2078 "%Y-%m-%d %H:%M:%S.%N %z";
2079 break;
2081 case long_iso_time_style:
2082 long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
2083 break;
2085 case iso_time_style:
2086 long_time_format[0] = "%Y-%m-%d ";
2087 long_time_format[1] = "%m-%d %H:%M";
2088 break;
2090 case locale_time_style:
2091 if (hard_locale (LC_TIME))
2093 int i;
2094 for (i = 0; i < 2; i++)
2095 long_time_format[i] =
2096 dcgettext (NULL, long_time_format[i], LC_TIME);
2101 /* Note we leave %5b etc. alone so user widths/flags are honored. */
2102 if (strstr (long_time_format[0], "%b")
2103 || strstr (long_time_format[1], "%b"))
2104 if (!abmon_init ())
2105 error (0, 0, _("error initializing month strings"));
2108 return optind;
2111 /* Parse a string as part of the LS_COLORS variable; this may involve
2112 decoding all kinds of escape characters. If equals_end is set an
2113 unescaped equal sign ends the string, otherwise only a : or \0
2114 does. Set *OUTPUT_COUNT to the number of bytes output. Return
2115 true if successful.
2117 The resulting string is *not* null-terminated, but may contain
2118 embedded nulls.
2120 Note that both dest and src are char **; on return they point to
2121 the first free byte after the array and the character that ended
2122 the input string, respectively. */
2124 static bool
2125 get_funky_string (char **dest, const char **src, bool equals_end,
2126 size_t *output_count)
2128 char num; /* For numerical codes */
2129 size_t count; /* Something to count with */
2130 enum {
2131 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
2132 } state;
2133 const char *p;
2134 char *q;
2136 p = *src; /* We don't want to double-indirect */
2137 q = *dest; /* the whole darn time. */
2139 count = 0; /* No characters counted in yet. */
2140 num = 0;
2142 state = ST_GND; /* Start in ground state. */
2143 while (state < ST_END)
2145 switch (state)
2147 case ST_GND: /* Ground state (no escapes) */
2148 switch (*p)
2150 case ':':
2151 case '\0':
2152 state = ST_END; /* End of string */
2153 break;
2154 case '\\':
2155 state = ST_BACKSLASH; /* Backslash scape sequence */
2156 ++p;
2157 break;
2158 case '^':
2159 state = ST_CARET; /* Caret escape */
2160 ++p;
2161 break;
2162 case '=':
2163 if (equals_end)
2165 state = ST_END; /* End */
2166 break;
2168 /* else fall through */
2169 default:
2170 *(q++) = *(p++);
2171 ++count;
2172 break;
2174 break;
2176 case ST_BACKSLASH: /* Backslash escaped character */
2177 switch (*p)
2179 case '0':
2180 case '1':
2181 case '2':
2182 case '3':
2183 case '4':
2184 case '5':
2185 case '6':
2186 case '7':
2187 state = ST_OCTAL; /* Octal sequence */
2188 num = *p - '0';
2189 break;
2190 case 'x':
2191 case 'X':
2192 state = ST_HEX; /* Hex sequence */
2193 num = 0;
2194 break;
2195 case 'a': /* Bell */
2196 num = '\a';
2197 break;
2198 case 'b': /* Backspace */
2199 num = '\b';
2200 break;
2201 case 'e': /* Escape */
2202 num = 27;
2203 break;
2204 case 'f': /* Form feed */
2205 num = '\f';
2206 break;
2207 case 'n': /* Newline */
2208 num = '\n';
2209 break;
2210 case 'r': /* Carriage return */
2211 num = '\r';
2212 break;
2213 case 't': /* Tab */
2214 num = '\t';
2215 break;
2216 case 'v': /* Vtab */
2217 num = '\v';
2218 break;
2219 case '?': /* Delete */
2220 num = 127;
2221 break;
2222 case '_': /* Space */
2223 num = ' ';
2224 break;
2225 case '\0': /* End of string */
2226 state = ST_ERROR; /* Error! */
2227 break;
2228 default: /* Escaped character like \ ^ : = */
2229 num = *p;
2230 break;
2232 if (state == ST_BACKSLASH)
2234 *(q++) = num;
2235 ++count;
2236 state = ST_GND;
2238 ++p;
2239 break;
2241 case ST_OCTAL: /* Octal sequence */
2242 if (*p < '0' || *p > '7')
2244 *(q++) = num;
2245 ++count;
2246 state = ST_GND;
2248 else
2249 num = (num << 3) + (*(p++) - '0');
2250 break;
2252 case ST_HEX: /* Hex sequence */
2253 switch (*p)
2255 case '0':
2256 case '1':
2257 case '2':
2258 case '3':
2259 case '4':
2260 case '5':
2261 case '6':
2262 case '7':
2263 case '8':
2264 case '9':
2265 num = (num << 4) + (*(p++) - '0');
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 case 'A':
2276 case 'B':
2277 case 'C':
2278 case 'D':
2279 case 'E':
2280 case 'F':
2281 num = (num << 4) + (*(p++) - 'A') + 10;
2282 break;
2283 default:
2284 *(q++) = num;
2285 ++count;
2286 state = ST_GND;
2287 break;
2289 break;
2291 case ST_CARET: /* Caret escape */
2292 state = ST_GND; /* Should be the next state... */
2293 if (*p >= '@' && *p <= '~')
2295 *(q++) = *(p++) & 037;
2296 ++count;
2298 else if (*p == '?')
2300 *(q++) = 127;
2301 ++count;
2303 else
2304 state = ST_ERROR;
2305 break;
2307 default:
2308 abort ();
2312 *dest = q;
2313 *src = p;
2314 *output_count = count;
2316 return state != ST_ERROR;
2319 enum parse_state
2321 PS_START = 1,
2322 PS_2,
2323 PS_3,
2324 PS_4,
2325 PS_DONE,
2326 PS_FAIL
2329 static void
2330 parse_ls_color (void)
2332 const char *p; /* Pointer to character being parsed */
2333 char *buf; /* color_buf buffer pointer */
2334 int ind_no; /* Indicator number */
2335 char label[3]; /* Indicator label */
2336 struct color_ext_type *ext; /* Extension we are working on */
2338 if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
2339 return;
2341 ext = NULL;
2342 strcpy (label, "??");
2344 /* This is an overly conservative estimate, but any possible
2345 LS_COLORS string will *not* generate a color_buf longer than
2346 itself, so it is a safe way of allocating a buffer in
2347 advance. */
2348 buf = color_buf = xstrdup (p);
2350 enum parse_state state = PS_START;
2351 while (true)
2353 switch (state)
2355 case PS_START: /* First label character */
2356 switch (*p)
2358 case ':':
2359 ++p;
2360 break;
2362 case '*':
2363 /* Allocate new extension block and add to head of
2364 linked list (this way a later definition will
2365 override an earlier one, which can be useful for
2366 having terminal-specific defs override global). */
2368 ext = xmalloc (sizeof *ext);
2369 ext->next = color_ext_list;
2370 color_ext_list = ext;
2372 ++p;
2373 ext->ext.string = buf;
2375 state = (get_funky_string (&buf, &p, true, &ext->ext.len)
2376 ? PS_4 : PS_FAIL);
2377 break;
2379 case '\0':
2380 state = PS_DONE; /* Done! */
2381 goto done;
2383 default: /* Assume it is file type label */
2384 label[0] = *(p++);
2385 state = PS_2;
2386 break;
2388 break;
2390 case PS_2: /* Second label character */
2391 if (*p)
2393 label[1] = *(p++);
2394 state = PS_3;
2396 else
2397 state = PS_FAIL; /* Error */
2398 break;
2400 case PS_3: /* Equal sign after indicator label */
2401 state = PS_FAIL; /* Assume failure... */
2402 if (*(p++) == '=')/* It *should* be... */
2404 for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
2406 if (STREQ (label, indicator_name[ind_no]))
2408 color_indicator[ind_no].string = buf;
2409 state = (get_funky_string (&buf, &p, false,
2410 &color_indicator[ind_no].len)
2411 ? PS_START : PS_FAIL);
2412 break;
2415 if (state == PS_FAIL)
2416 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
2418 break;
2420 case PS_4: /* Equal sign after *.ext */
2421 if (*(p++) == '=')
2423 ext->seq.string = buf;
2424 state = (get_funky_string (&buf, &p, false, &ext->seq.len)
2425 ? PS_START : PS_FAIL);
2427 else
2428 state = PS_FAIL;
2429 break;
2431 case PS_FAIL:
2432 goto done;
2434 default:
2435 abort ();
2438 done:
2440 if (state == PS_FAIL)
2442 struct color_ext_type *e;
2443 struct color_ext_type *e2;
2445 error (0, 0,
2446 _("unparsable value for LS_COLORS environment variable"));
2447 free (color_buf);
2448 for (e = color_ext_list; e != NULL; /* empty */)
2450 e2 = e;
2451 e = e->next;
2452 free (e2);
2454 print_with_color = false;
2457 if (color_indicator[C_LINK].len == 6
2458 && !STRNCMP_LIT (color_indicator[C_LINK].string, "target"))
2459 color_symlink_as_referent = true;
2462 /* Set the exit status to report a failure. If SERIOUS, it is a
2463 serious failure; otherwise, it is merely a minor problem. */
2465 static void
2466 set_exit_status (bool serious)
2468 if (serious)
2469 exit_status = LS_FAILURE;
2470 else if (exit_status == EXIT_SUCCESS)
2471 exit_status = LS_MINOR_PROBLEM;
2474 /* Assuming a failure is serious if SERIOUS, use the printf-style
2475 MESSAGE to report the failure to access a file named FILE. Assume
2476 errno is set appropriately for the failure. */
2478 static void
2479 file_failure (bool serious, char const *message, char const *file)
2481 error (0, errno, message, quotearg_colon (file));
2482 set_exit_status (serious);
2485 /* Request that the directory named NAME have its contents listed later.
2486 If REALNAME is nonzero, it will be used instead of NAME when the
2487 directory name is printed. This allows symbolic links to directories
2488 to be treated as regular directories but still be listed under their
2489 real names. NAME == NULL is used to insert a marker entry for the
2490 directory named in REALNAME.
2491 If NAME is non-NULL, we use its dev/ino information to save
2492 a call to stat -- when doing a recursive (-R) traversal.
2493 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2495 static void
2496 queue_directory (char const *name, char const *realname, bool command_line_arg)
2498 struct pending *new = xmalloc (sizeof *new);
2499 new->realname = realname ? xstrdup (realname) : NULL;
2500 new->name = name ? xstrdup (name) : NULL;
2501 new->command_line_arg = command_line_arg;
2502 new->next = pending_dirs;
2503 pending_dirs = new;
2506 /* Read directory NAME, and list the files in it.
2507 If REALNAME is nonzero, print its name instead of NAME;
2508 this is used for symbolic links to directories.
2509 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2511 static void
2512 print_dir (char const *name, char const *realname, bool command_line_arg)
2514 DIR *dirp;
2515 struct dirent *next;
2516 uintmax_t total_blocks = 0;
2517 static bool first = true;
2519 errno = 0;
2520 dirp = opendir (name);
2521 if (!dirp)
2523 file_failure (command_line_arg, _("cannot open directory %s"), name);
2524 return;
2527 if (LOOP_DETECT)
2529 struct stat dir_stat;
2530 int fd = dirfd (dirp);
2532 /* If dirfd failed, endure the overhead of using stat. */
2533 if ((0 <= fd
2534 ? fstat (fd, &dir_stat)
2535 : stat (name, &dir_stat)) < 0)
2537 file_failure (command_line_arg,
2538 _("cannot determine device and inode of %s"), name);
2539 closedir (dirp);
2540 return;
2543 /* If we've already visited this dev/inode pair, warn that
2544 we've found a loop, and do not process this directory. */
2545 if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
2547 error (0, 0, _("%s: not listing already-listed directory"),
2548 quotearg_colon (name));
2549 closedir (dirp);
2550 set_exit_status (true);
2551 return;
2554 dev_ino_push (dir_stat.st_dev, dir_stat.st_ino);
2557 if (recursive || print_dir_name)
2559 if (!first)
2560 DIRED_PUTCHAR ('\n');
2561 first = false;
2562 DIRED_INDENT ();
2563 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2564 dired_pos += quote_name (stdout, realname ? realname : name,
2565 dirname_quoting_options, NULL);
2566 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2567 DIRED_FPUTS_LITERAL (":\n", stdout);
2570 /* Read the directory entries, and insert the subfiles into the 'cwd_file'
2571 table. */
2573 clear_files ();
2575 while (1)
2577 /* Set errno to zero so we can distinguish between a readdir failure
2578 and when readdir simply finds that there are no more entries. */
2579 errno = 0;
2580 next = readdir (dirp);
2581 if (next)
2583 if (! file_ignored (next->d_name))
2585 enum filetype type = unknown;
2587 #if HAVE_STRUCT_DIRENT_D_TYPE
2588 switch (next->d_type)
2590 case DT_BLK: type = blockdev; break;
2591 case DT_CHR: type = chardev; break;
2592 case DT_DIR: type = directory; break;
2593 case DT_FIFO: type = fifo; break;
2594 case DT_LNK: type = symbolic_link; break;
2595 case DT_REG: type = normal; break;
2596 case DT_SOCK: type = sock; break;
2597 # ifdef DT_WHT
2598 case DT_WHT: type = whiteout; break;
2599 # endif
2601 #endif
2602 total_blocks += gobble_file (next->d_name, type,
2603 RELIABLE_D_INO (next),
2604 false, name);
2606 /* In this narrow case, print out each name right away, so
2607 ls uses constant memory while processing the entries of
2608 this directory. Useful when there are many (millions)
2609 of entries in a directory. */
2610 if (format == one_per_line && sort_type == sort_none
2611 && !print_block_size && !recursive)
2613 /* We must call sort_files in spite of
2614 "sort_type == sort_none" for its initialization
2615 of the sorted_file vector. */
2616 sort_files ();
2617 print_current_files ();
2618 clear_files ();
2622 else if (errno != 0)
2624 file_failure (command_line_arg, _("reading directory %s"), name);
2625 if (errno != EOVERFLOW)
2626 break;
2628 else
2629 break;
2631 /* When processing a very large directory, and since we've inhibited
2632 interrupts, this loop would take so long that ls would be annoyingly
2633 uninterruptible. This ensures that it handles signals promptly. */
2634 process_signals ();
2637 if (closedir (dirp) != 0)
2639 file_failure (command_line_arg, _("closing directory %s"), name);
2640 /* Don't return; print whatever we got. */
2643 /* Sort the directory contents. */
2644 sort_files ();
2646 /* If any member files are subdirectories, perhaps they should have their
2647 contents listed rather than being mentioned here as files. */
2649 if (recursive)
2650 extract_dirs_from_files (name, command_line_arg);
2652 if (format == long_format || print_block_size)
2654 const char *p;
2655 char buf[LONGEST_HUMAN_READABLE + 1];
2657 DIRED_INDENT ();
2658 p = _("total");
2659 DIRED_FPUTS (p, stdout, strlen (p));
2660 DIRED_PUTCHAR (' ');
2661 p = human_readable (total_blocks, buf, human_output_opts,
2662 ST_NBLOCKSIZE, output_block_size);
2663 DIRED_FPUTS (p, stdout, strlen (p));
2664 DIRED_PUTCHAR ('\n');
2667 if (cwd_n_used)
2668 print_current_files ();
2671 /* Add 'pattern' to the list of patterns for which files that match are
2672 not listed. */
2674 static void
2675 add_ignore_pattern (const char *pattern)
2677 struct ignore_pattern *ignore;
2679 ignore = xmalloc (sizeof *ignore);
2680 ignore->pattern = pattern;
2681 /* Add it to the head of the linked list. */
2682 ignore->next = ignore_patterns;
2683 ignore_patterns = ignore;
2686 /* Return true if one of the PATTERNS matches FILE. */
2688 static bool
2689 patterns_match (struct ignore_pattern const *patterns, char const *file)
2691 struct ignore_pattern const *p;
2692 for (p = patterns; p; p = p->next)
2693 if (fnmatch (p->pattern, file, FNM_PERIOD) == 0)
2694 return true;
2695 return false;
2698 /* Return true if FILE should be ignored. */
2700 static bool
2701 file_ignored (char const *name)
2703 return ((ignore_mode != IGNORE_MINIMAL
2704 && name[0] == '.'
2705 && (ignore_mode == IGNORE_DEFAULT || ! name[1 + (name[1] == '.')]))
2706 || (ignore_mode == IGNORE_DEFAULT
2707 && patterns_match (hide_patterns, name))
2708 || patterns_match (ignore_patterns, name));
2711 /* POSIX requires that a file size be printed without a sign, even
2712 when negative. Assume the typical case where negative sizes are
2713 actually positive values that have wrapped around. */
2715 static uintmax_t
2716 unsigned_file_size (off_t size)
2718 return size + (size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
2721 #ifdef HAVE_CAP
2722 /* Return true if NAME has a capability (see linux/capability.h) */
2723 static bool
2724 has_capability (char const *name)
2726 char *result;
2727 bool has_cap;
2729 cap_t cap_d = cap_get_file (name);
2730 if (cap_d == NULL)
2731 return false;
2733 result = cap_to_text (cap_d, NULL);
2734 cap_free (cap_d);
2735 if (!result)
2736 return false;
2738 /* check if human-readable capability string is empty */
2739 has_cap = !!*result;
2741 cap_free (result);
2742 return has_cap;
2744 #else
2745 static bool
2746 has_capability (char const *name _GL_UNUSED)
2748 errno = ENOTSUP;
2749 return false;
2751 #endif
2753 /* Enter and remove entries in the table 'cwd_file'. */
2755 static void
2756 free_ent (struct fileinfo *f)
2758 free (f->name);
2759 free (f->linkname);
2760 if (f->scontext != UNKNOWN_SECURITY_CONTEXT)
2762 if (is_smack_enabled ())
2763 free (f->scontext);
2764 else
2765 freecon (f->scontext);
2769 /* Empty the table of files. */
2770 static void
2771 clear_files (void)
2773 size_t i;
2775 for (i = 0; i < cwd_n_used; i++)
2777 struct fileinfo *f = sorted_file[i];
2778 free_ent (f);
2781 cwd_n_used = 0;
2782 any_has_acl = false;
2783 inode_number_width = 0;
2784 block_size_width = 0;
2785 nlink_width = 0;
2786 owner_width = 0;
2787 group_width = 0;
2788 author_width = 0;
2789 scontext_width = 0;
2790 major_device_number_width = 0;
2791 minor_device_number_width = 0;
2792 file_size_width = 0;
2795 /* Return true if ERR implies lack-of-support failure by a
2796 getxattr-calling function like getfilecon or file_has_acl. */
2797 static bool
2798 errno_unsupported (int err)
2800 return (err == EINVAL
2801 || err == ENOSYS
2802 || err == ENOTSUP
2803 || err == EOPNOTSUPP);
2806 /* Cache *getfilecon failure, when it's trivial to do so.
2807 Like getfilecon/lgetfilecon, but when F's st_dev says it's on a known-
2808 SELinux-challenged file system, fail with ENOTSUP immediately. */
2809 static int
2810 getfilecon_cache (char const *file, struct fileinfo *f, bool deref)
2812 /* st_dev of the most recently processed device for which we've
2813 found that [l]getfilecon fails indicating lack of support. */
2814 static dev_t unsupported_device;
2816 if (f->stat.st_dev == unsupported_device)
2818 errno = ENOTSUP;
2819 return -1;
2821 int r = 0;
2822 #ifdef HAVE_SMACK
2823 if (is_smack_enabled ())
2824 r = smack_new_label_from_path (file, "security.SMACK64", deref,
2825 &f->scontext);
2826 else
2827 #endif
2828 r = (deref
2829 ? getfilecon (file, &f->scontext)
2830 : lgetfilecon (file, &f->scontext));
2831 if (r < 0 && errno_unsupported (errno))
2832 unsupported_device = f->stat.st_dev;
2833 return r;
2836 /* Cache file_has_acl failure, when it's trivial to do.
2837 Like file_has_acl, but when F's st_dev says it's on a file
2838 system lacking ACL support, return 0 with ENOTSUP immediately. */
2839 static int
2840 file_has_acl_cache (char const *file, struct fileinfo *f)
2842 /* st_dev of the most recently processed device for which we've
2843 found that file_has_acl fails indicating lack of support. */
2844 static dev_t unsupported_device;
2846 if (f->stat.st_dev == unsupported_device)
2848 errno = ENOTSUP;
2849 return 0;
2852 /* Zero errno so that we can distinguish between two 0-returning cases:
2853 "has-ACL-support, but only a default ACL" and "no ACL support". */
2854 errno = 0;
2855 int n = file_has_acl (file, &f->stat);
2856 if (n <= 0 && errno_unsupported (errno))
2857 unsupported_device = f->stat.st_dev;
2858 return n;
2861 /* Cache has_capability failure, when it's trivial to do.
2862 Like has_capability, but when F's st_dev says it's on a file
2863 system lacking capability support, return 0 with ENOTSUP immediately. */
2864 static bool
2865 has_capability_cache (char const *file, struct fileinfo *f)
2867 /* st_dev of the most recently processed device for which we've
2868 found that has_capability fails indicating lack of support. */
2869 static dev_t unsupported_device;
2871 if (f->stat.st_dev == unsupported_device)
2873 errno = ENOTSUP;
2874 return 0;
2877 bool b = has_capability (file);
2878 if ( !b && errno_unsupported (errno))
2879 unsupported_device = f->stat.st_dev;
2880 return b;
2883 /* Add a file to the current table of files.
2884 Verify that the file exists, and print an error message if it does not.
2885 Return the number of blocks that the file occupies. */
2886 static uintmax_t
2887 gobble_file (char const *name, enum filetype type, ino_t inode,
2888 bool command_line_arg, char const *dirname)
2890 uintmax_t blocks = 0;
2891 struct fileinfo *f;
2893 /* An inode value prior to gobble_file necessarily came from readdir,
2894 which is not used for command line arguments. */
2895 assert (! command_line_arg || inode == NOT_AN_INODE_NUMBER);
2897 if (cwd_n_used == cwd_n_alloc)
2899 cwd_file = xnrealloc (cwd_file, cwd_n_alloc, 2 * sizeof *cwd_file);
2900 cwd_n_alloc *= 2;
2903 f = &cwd_file[cwd_n_used];
2904 memset (f, '\0', sizeof *f);
2905 f->stat.st_ino = inode;
2906 f->filetype = type;
2908 if (command_line_arg
2909 || format_needs_stat
2910 /* When coloring a directory (we may know the type from
2911 direct.d_type), we have to stat it in order to indicate
2912 sticky and/or other-writable attributes. */
2913 || (type == directory && print_with_color
2914 && (is_colored (C_OTHER_WRITABLE)
2915 || is_colored (C_STICKY)
2916 || is_colored (C_STICKY_OTHER_WRITABLE)))
2917 /* When dereferencing symlinks, the inode and type must come from
2918 stat, but readdir provides the inode and type of lstat. */
2919 || ((print_inode || format_needs_type)
2920 && (type == symbolic_link || type == unknown)
2921 && (dereference == DEREF_ALWAYS
2922 || (command_line_arg && dereference != DEREF_NEVER)
2923 || color_symlink_as_referent || check_symlink_color))
2924 /* Command line dereferences are already taken care of by the above
2925 assertion that the inode number is not yet known. */
2926 || (print_inode && inode == NOT_AN_INODE_NUMBER)
2927 || (format_needs_type
2928 && (type == unknown || command_line_arg
2929 /* --indicator-style=classify (aka -F)
2930 requires that we stat each regular file
2931 to see if it's executable. */
2932 || (type == normal && (indicator_style == classify
2933 /* This is so that --color ends up
2934 highlighting files with these mode
2935 bits set even when options like -F are
2936 not specified. Note we do a redundant
2937 stat in the very unlikely case where
2938 C_CAP is set but not the others. */
2939 || (print_with_color
2940 && (is_colored (C_EXEC)
2941 || is_colored (C_SETUID)
2942 || is_colored (C_SETGID)
2943 || is_colored (C_CAP)))
2944 )))))
2947 /* Absolute name of this file. */
2948 char *absolute_name;
2949 bool do_deref;
2950 int err;
2952 if (name[0] == '/' || dirname[0] == 0)
2953 absolute_name = (char *) name;
2954 else
2956 absolute_name = alloca (strlen (name) + strlen (dirname) + 2);
2957 attach (absolute_name, dirname, name);
2960 switch (dereference)
2962 case DEREF_ALWAYS:
2963 err = stat (absolute_name, &f->stat);
2964 do_deref = true;
2965 break;
2967 case DEREF_COMMAND_LINE_ARGUMENTS:
2968 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
2969 if (command_line_arg)
2971 bool need_lstat;
2972 err = stat (absolute_name, &f->stat);
2973 do_deref = true;
2975 if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2976 break;
2978 need_lstat = (err < 0
2979 ? errno == ENOENT
2980 : ! S_ISDIR (f->stat.st_mode));
2981 if (!need_lstat)
2982 break;
2984 /* stat failed because of ENOENT, maybe indicating a dangling
2985 symlink. Or stat succeeded, ABSOLUTE_NAME does not refer to a
2986 directory, and --dereference-command-line-symlink-to-dir is
2987 in effect. Fall through so that we call lstat instead. */
2990 default: /* DEREF_NEVER */
2991 err = lstat (absolute_name, &f->stat);
2992 do_deref = false;
2993 break;
2996 if (err != 0)
2998 /* Failure to stat a command line argument leads to
2999 an exit status of 2. For other files, stat failure
3000 provokes an exit status of 1. */
3001 file_failure (command_line_arg,
3002 _("cannot access %s"), absolute_name);
3003 if (command_line_arg)
3004 return 0;
3006 f->name = xstrdup (name);
3007 cwd_n_used++;
3009 return 0;
3012 f->stat_ok = true;
3014 /* Note has_capability() adds around 30% runtime to 'ls --color' */
3015 if ((type == normal || S_ISREG (f->stat.st_mode))
3016 && print_with_color && is_colored (C_CAP))
3017 f->has_capability = has_capability_cache (absolute_name, f);
3019 if (format == long_format || print_scontext)
3021 bool have_scontext = false;
3022 bool have_acl = false;
3023 int attr_len = getfilecon_cache (absolute_name, f, do_deref);
3024 err = (attr_len < 0);
3026 if (err == 0)
3028 if (is_smack_enabled ())
3029 have_scontext = ! STREQ ("_", f->scontext);
3030 else
3031 have_scontext = ! STREQ ("unlabeled", f->scontext);
3033 else
3035 f->scontext = UNKNOWN_SECURITY_CONTEXT;
3037 /* When requesting security context information, don't make
3038 ls fail just because the file (even a command line argument)
3039 isn't on the right type of file system. I.e., a getfilecon
3040 failure isn't in the same class as a stat failure. */
3041 if (errno == ENOTSUP || errno == EOPNOTSUPP || errno == ENODATA)
3042 err = 0;
3045 if (err == 0 && format == long_format)
3047 int n = file_has_acl_cache (absolute_name, f);
3048 err = (n < 0);
3049 have_acl = (0 < n);
3052 f->acl_type = (!have_scontext && !have_acl
3053 ? ACL_T_NONE
3054 : (have_scontext && !have_acl
3055 ? ACL_T_SELINUX_ONLY
3056 : ACL_T_YES));
3057 any_has_acl |= f->acl_type != ACL_T_NONE;
3059 if (err)
3060 error (0, errno, "%s", quotearg_colon (absolute_name));
3063 if (S_ISLNK (f->stat.st_mode)
3064 && (format == long_format || check_symlink_color))
3066 struct stat linkstats;
3068 get_link_name (absolute_name, f, command_line_arg);
3069 char *linkname = make_link_name (absolute_name, f->linkname);
3071 /* Avoid following symbolic links when possible, ie, when
3072 they won't be traced and when no indicator is needed. */
3073 if (linkname
3074 && (file_type <= indicator_style || check_symlink_color)
3075 && stat (linkname, &linkstats) == 0)
3077 f->linkok = true;
3079 /* Symbolic links to directories that are mentioned on the
3080 command line are automatically traced if not being
3081 listed as files. */
3082 if (!command_line_arg || format == long_format
3083 || !S_ISDIR (linkstats.st_mode))
3085 /* Get the linked-to file's mode for the filetype indicator
3086 in long listings. */
3087 f->linkmode = linkstats.st_mode;
3090 free (linkname);
3093 if (S_ISLNK (f->stat.st_mode))
3094 f->filetype = symbolic_link;
3095 else if (S_ISDIR (f->stat.st_mode))
3097 if (command_line_arg && !immediate_dirs)
3098 f->filetype = arg_directory;
3099 else
3100 f->filetype = directory;
3102 else
3103 f->filetype = normal;
3105 blocks = ST_NBLOCKS (f->stat);
3106 if (format == long_format || print_block_size)
3108 char buf[LONGEST_HUMAN_READABLE + 1];
3109 int len = mbswidth (human_readable (blocks, buf, human_output_opts,
3110 ST_NBLOCKSIZE, output_block_size),
3112 if (block_size_width < len)
3113 block_size_width = len;
3116 if (format == long_format)
3118 if (print_owner)
3120 int len = format_user_width (f->stat.st_uid);
3121 if (owner_width < len)
3122 owner_width = len;
3125 if (print_group)
3127 int len = format_group_width (f->stat.st_gid);
3128 if (group_width < len)
3129 group_width = len;
3132 if (print_author)
3134 int len = format_user_width (f->stat.st_author);
3135 if (author_width < len)
3136 author_width = len;
3140 if (print_scontext)
3142 int len = strlen (f->scontext);
3143 if (scontext_width < len)
3144 scontext_width = len;
3147 if (format == long_format)
3149 char b[INT_BUFSIZE_BOUND (uintmax_t)];
3150 int b_len = strlen (umaxtostr (f->stat.st_nlink, b));
3151 if (nlink_width < b_len)
3152 nlink_width = b_len;
3154 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
3156 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
3157 int len = strlen (umaxtostr (major (f->stat.st_rdev), buf));
3158 if (major_device_number_width < len)
3159 major_device_number_width = len;
3160 len = strlen (umaxtostr (minor (f->stat.st_rdev), buf));
3161 if (minor_device_number_width < len)
3162 minor_device_number_width = len;
3163 len = major_device_number_width + 2 + minor_device_number_width;
3164 if (file_size_width < len)
3165 file_size_width = len;
3167 else
3169 char buf[LONGEST_HUMAN_READABLE + 1];
3170 uintmax_t size = unsigned_file_size (f->stat.st_size);
3171 int len = mbswidth (human_readable (size, buf,
3172 file_human_output_opts,
3173 1, file_output_block_size),
3175 if (file_size_width < len)
3176 file_size_width = len;
3181 if (print_inode)
3183 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
3184 int len = strlen (umaxtostr (f->stat.st_ino, buf));
3185 if (inode_number_width < len)
3186 inode_number_width = len;
3189 f->name = xstrdup (name);
3190 cwd_n_used++;
3192 return blocks;
3195 /* Return true if F refers to a directory. */
3196 static bool
3197 is_directory (const struct fileinfo *f)
3199 return f->filetype == directory || f->filetype == arg_directory;
3202 /* Put the name of the file that FILENAME is a symbolic link to
3203 into the LINKNAME field of 'f'. COMMAND_LINE_ARG indicates whether
3204 FILENAME is a command-line argument. */
3206 static void
3207 get_link_name (char const *filename, struct fileinfo *f, bool command_line_arg)
3209 f->linkname = areadlink_with_size (filename, f->stat.st_size);
3210 if (f->linkname == NULL)
3211 file_failure (command_line_arg, _("cannot read symbolic link %s"),
3212 filename);
3215 /* If LINKNAME is a relative name and NAME contains one or more
3216 leading directories, return LINKNAME with those directories
3217 prepended; otherwise, return a copy of LINKNAME.
3218 If LINKNAME is NULL, return NULL. */
3220 static char *
3221 make_link_name (char const *name, char const *linkname)
3223 if (!linkname)
3224 return NULL;
3226 if (IS_ABSOLUTE_FILE_NAME (linkname))
3227 return xstrdup (linkname);
3229 /* The link is to a relative name. Prepend any leading directory
3230 in 'name' to the link name. */
3231 size_t prefix_len = dir_len (name);
3232 if (prefix_len == 0)
3233 return xstrdup (linkname);
3235 char *p = xmalloc (prefix_len + 1 + strlen (linkname) + 1);
3237 /* PREFIX_LEN usually specifies a string not ending in slash.
3238 In that case, extend it by one, since the next byte *is* a slash.
3239 Otherwise, the prefix is "/", so leave the length unchanged. */
3240 if ( ! ISSLASH (name[prefix_len - 1]))
3241 ++prefix_len;
3243 stpcpy (stpncpy (p, name, prefix_len), linkname);
3244 return p;
3247 /* Return true if the last component of NAME is '.' or '..'
3248 This is so we don't try to recurse on '././././. ...' */
3250 static bool
3251 basename_is_dot_or_dotdot (const char *name)
3253 char const *base = last_component (name);
3254 return dot_or_dotdot (base);
3257 /* Remove any entries from CWD_FILE that are for directories,
3258 and queue them to be listed as directories instead.
3259 DIRNAME is the prefix to prepend to each dirname
3260 to make it correct relative to ls's working dir;
3261 if it is null, no prefix is needed and "." and ".." should not be ignored.
3262 If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
3263 This is desirable when processing directories recursively. */
3265 static void
3266 extract_dirs_from_files (char const *dirname, bool command_line_arg)
3268 size_t i;
3269 size_t j;
3270 bool ignore_dot_and_dot_dot = (dirname != NULL);
3272 if (dirname && LOOP_DETECT)
3274 /* Insert a marker entry first. When we dequeue this marker entry,
3275 we'll know that DIRNAME has been processed and may be removed
3276 from the set of active directories. */
3277 queue_directory (NULL, dirname, false);
3280 /* Queue the directories last one first, because queueing reverses the
3281 order. */
3282 for (i = cwd_n_used; i-- != 0; )
3284 struct fileinfo *f = sorted_file[i];
3286 if (is_directory (f)
3287 && (! ignore_dot_and_dot_dot
3288 || ! basename_is_dot_or_dotdot (f->name)))
3290 if (!dirname || f->name[0] == '/')
3291 queue_directory (f->name, f->linkname, command_line_arg);
3292 else
3294 char *name = file_name_concat (dirname, f->name, NULL);
3295 queue_directory (name, f->linkname, command_line_arg);
3296 free (name);
3298 if (f->filetype == arg_directory)
3299 free_ent (f);
3303 /* Now delete the directories from the table, compacting all the remaining
3304 entries. */
3306 for (i = 0, j = 0; i < cwd_n_used; i++)
3308 struct fileinfo *f = sorted_file[i];
3309 sorted_file[j] = f;
3310 j += (f->filetype != arg_directory);
3312 cwd_n_used = j;
3315 /* Use strcoll to compare strings in this locale. If an error occurs,
3316 report an error and longjmp to failed_strcoll. */
3318 static jmp_buf failed_strcoll;
3320 static int
3321 xstrcoll (char const *a, char const *b)
3323 int diff;
3324 errno = 0;
3325 diff = strcoll (a, b);
3326 if (errno)
3328 error (0, errno, _("cannot compare file names %s and %s"),
3329 quote_n (0, a), quote_n (1, b));
3330 set_exit_status (false);
3331 longjmp (failed_strcoll, 1);
3333 return diff;
3336 /* Comparison routines for sorting the files. */
3338 typedef void const *V;
3339 typedef int (*qsortFunc)(V a, V b);
3341 /* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants.
3342 The do { ... } while(0) makes it possible to use the macro more like
3343 a statement, without violating C89 rules: */
3344 #define DIRFIRST_CHECK(a, b) \
3345 do \
3347 bool a_is_dir = is_directory ((struct fileinfo const *) a); \
3348 bool b_is_dir = is_directory ((struct fileinfo const *) b); \
3349 if (a_is_dir && !b_is_dir) \
3350 return -1; /* a goes before b */ \
3351 if (!a_is_dir && b_is_dir) \
3352 return 1; /* b goes before a */ \
3354 while (0)
3356 /* Define the 8 different sort function variants required for each sortkey.
3357 KEY_NAME is a token describing the sort key, e.g., ctime, atime, size.
3358 KEY_CMP_FUNC is a function to compare records based on that key, e.g.,
3359 ctime_cmp, atime_cmp, size_cmp. Append KEY_NAME to the string,
3360 '[rev_][x]str{cmp|coll}[_df]_', to create each function name. */
3361 #define DEFINE_SORT_FUNCTIONS(key_name, key_cmp_func) \
3362 /* direct, non-dirfirst versions */ \
3363 static int xstrcoll_##key_name (V a, V b) \
3364 { return key_cmp_func (a, b, xstrcoll); } \
3365 static int strcmp_##key_name (V a, V b) \
3366 { return key_cmp_func (a, b, strcmp); } \
3368 /* reverse, non-dirfirst versions */ \
3369 static int rev_xstrcoll_##key_name (V a, V b) \
3370 { return key_cmp_func (b, a, xstrcoll); } \
3371 static int rev_strcmp_##key_name (V a, V b) \
3372 { return key_cmp_func (b, a, strcmp); } \
3374 /* direct, dirfirst versions */ \
3375 static int xstrcoll_df_##key_name (V a, V b) \
3376 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, xstrcoll); } \
3377 static int strcmp_df_##key_name (V a, V b) \
3378 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, strcmp); } \
3380 /* reverse, dirfirst versions */ \
3381 static int rev_xstrcoll_df_##key_name (V a, V b) \
3382 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, xstrcoll); } \
3383 static int rev_strcmp_df_##key_name (V a, V b) \
3384 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, strcmp); }
3386 static inline int
3387 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
3388 int (*cmp) (char const *, char const *))
3390 int diff = timespec_cmp (get_stat_ctime (&b->stat),
3391 get_stat_ctime (&a->stat));
3392 return diff ? diff : cmp (a->name, b->name);
3395 static inline int
3396 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
3397 int (*cmp) (char const *, char const *))
3399 int diff = timespec_cmp (get_stat_mtime (&b->stat),
3400 get_stat_mtime (&a->stat));
3401 return diff ? diff : cmp (a->name, b->name);
3404 static inline int
3405 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
3406 int (*cmp) (char const *, char const *))
3408 int diff = timespec_cmp (get_stat_atime (&b->stat),
3409 get_stat_atime (&a->stat));
3410 return diff ? diff : cmp (a->name, b->name);
3413 static inline int
3414 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
3415 int (*cmp) (char const *, char const *))
3417 int diff = longdiff (b->stat.st_size, a->stat.st_size);
3418 return diff ? diff : cmp (a->name, b->name);
3421 static inline int
3422 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
3423 int (*cmp) (char const *, char const *))
3425 return cmp (a->name, b->name);
3428 /* Compare file extensions. Files with no extension are 'smallest'.
3429 If extensions are the same, compare by filenames instead. */
3431 static inline int
3432 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
3433 int (*cmp) (char const *, char const *))
3435 char const *base1 = strrchr (a->name, '.');
3436 char const *base2 = strrchr (b->name, '.');
3437 int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
3438 return diff ? diff : cmp (a->name, b->name);
3441 DEFINE_SORT_FUNCTIONS (ctime, cmp_ctime)
3442 DEFINE_SORT_FUNCTIONS (mtime, cmp_mtime)
3443 DEFINE_SORT_FUNCTIONS (atime, cmp_atime)
3444 DEFINE_SORT_FUNCTIONS (size, cmp_size)
3445 DEFINE_SORT_FUNCTIONS (name, cmp_name)
3446 DEFINE_SORT_FUNCTIONS (extension, cmp_extension)
3448 /* Compare file versions.
3449 Unlike all other compare functions above, cmp_version depends only
3450 on filevercmp, which does not fail (even for locale reasons), and does not
3451 need a secondary sort key. See lib/filevercmp.h for function description.
3453 All the other sort options, in fact, need xstrcoll and strcmp variants,
3454 because they all use a string comparison (either as the primary or secondary
3455 sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
3456 locale reasons. Lastly, filevercmp is ALWAYS available with gnulib. */
3457 static inline int
3458 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
3460 return filevercmp (a->name, b->name);
3463 static int xstrcoll_version (V a, V b)
3464 { return cmp_version (a, b); }
3465 static int rev_xstrcoll_version (V a, V b)
3466 { return cmp_version (b, a); }
3467 static int xstrcoll_df_version (V a, V b)
3468 { DIRFIRST_CHECK (a, b); return cmp_version (a, b); }
3469 static int rev_xstrcoll_df_version (V a, V b)
3470 { DIRFIRST_CHECK (a, b); return cmp_version (b, a); }
3473 /* We have 2^3 different variants for each sort-key function
3474 (for 3 independent sort modes).
3475 The function pointers stored in this array must be dereferenced as:
3477 sort_variants[sort_key][use_strcmp][reverse][dirs_first]
3479 Note that the order in which sort keys are listed in the function pointer
3480 array below is defined by the order of the elements in the time_type and
3481 sort_type enums! */
3483 #define LIST_SORTFUNCTION_VARIANTS(key_name) \
3486 { xstrcoll_##key_name, xstrcoll_df_##key_name }, \
3487 { rev_xstrcoll_##key_name, rev_xstrcoll_df_##key_name }, \
3488 }, \
3490 { strcmp_##key_name, strcmp_df_##key_name }, \
3491 { rev_strcmp_##key_name, rev_strcmp_df_##key_name }, \
3495 static qsortFunc const sort_functions[][2][2][2] =
3497 LIST_SORTFUNCTION_VARIANTS (name),
3498 LIST_SORTFUNCTION_VARIANTS (extension),
3499 LIST_SORTFUNCTION_VARIANTS (size),
3503 { xstrcoll_version, xstrcoll_df_version },
3504 { rev_xstrcoll_version, rev_xstrcoll_df_version },
3507 /* We use NULL for the strcmp variants of version comparison
3508 since as explained in cmp_version definition, version comparison
3509 does not rely on xstrcoll, so it will never longjmp, and never
3510 need to try the strcmp fallback. */
3512 { NULL, NULL },
3513 { NULL, NULL },
3517 /* last are time sort functions */
3518 LIST_SORTFUNCTION_VARIANTS (mtime),
3519 LIST_SORTFUNCTION_VARIANTS (ctime),
3520 LIST_SORTFUNCTION_VARIANTS (atime)
3523 /* The number of sort keys is calculated as the sum of
3524 the number of elements in the sort_type enum (i.e. sort_numtypes)
3525 the number of elements in the time_type enum (i.e. time_numtypes) - 1
3526 This is because when sort_type==sort_time, we have up to
3527 time_numtypes possible sort keys.
3529 This line verifies at compile-time that the array of sort functions has been
3530 initialized for all possible sort keys. */
3531 verify (ARRAY_CARDINALITY (sort_functions)
3532 == sort_numtypes + time_numtypes - 1 );
3534 /* Set up SORTED_FILE to point to the in-use entries in CWD_FILE, in order. */
3536 static void
3537 initialize_ordering_vector (void)
3539 size_t i;
3540 for (i = 0; i < cwd_n_used; i++)
3541 sorted_file[i] = &cwd_file[i];
3544 /* Sort the files now in the table. */
3546 static void
3547 sort_files (void)
3549 bool use_strcmp;
3551 if (sorted_file_alloc < cwd_n_used + cwd_n_used / 2)
3553 free (sorted_file);
3554 sorted_file = xnmalloc (cwd_n_used, 3 * sizeof *sorted_file);
3555 sorted_file_alloc = 3 * cwd_n_used;
3558 initialize_ordering_vector ();
3560 if (sort_type == sort_none)
3561 return;
3563 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
3564 ignore strcoll failures, as a failing strcoll might be a
3565 comparison function that is not a total order, and if we ignored
3566 the failure this might cause qsort to dump core. */
3568 if (! setjmp (failed_strcoll))
3569 use_strcmp = false; /* strcoll() succeeded */
3570 else
3572 use_strcmp = true;
3573 assert (sort_type != sort_version);
3574 initialize_ordering_vector ();
3577 /* When sort_type == sort_time, use time_type as subindex. */
3578 mpsort ((void const **) sorted_file, cwd_n_used,
3579 sort_functions[sort_type + (sort_type == sort_time ? time_type : 0)]
3580 [use_strcmp][sort_reverse]
3581 [directories_first]);
3584 /* List all the files now in the table. */
3586 static void
3587 print_current_files (void)
3589 size_t i;
3591 switch (format)
3593 case one_per_line:
3594 for (i = 0; i < cwd_n_used; i++)
3596 print_file_name_and_frills (sorted_file[i], 0);
3597 putchar ('\n');
3599 break;
3601 case many_per_line:
3602 print_many_per_line ();
3603 break;
3605 case horizontal:
3606 print_horizontal ();
3607 break;
3609 case with_commas:
3610 print_with_commas ();
3611 break;
3613 case long_format:
3614 for (i = 0; i < cwd_n_used; i++)
3616 set_normal_color ();
3617 print_long_format (sorted_file[i]);
3618 DIRED_PUTCHAR ('\n');
3620 break;
3624 /* Replace the first %b with precomputed aligned month names.
3625 Note on glibc-2.7 at least, this speeds up the whole 'ls -lU'
3626 process by around 17%, compared to letting strftime() handle the %b. */
3628 static size_t
3629 align_nstrftime (char *buf, size_t size, char const *fmt, struct tm const *tm,
3630 int __utc, int __ns)
3632 const char *nfmt = fmt;
3633 /* In the unlikely event that rpl_fmt below is not large enough,
3634 the replacement is not done. A malloc here slows ls down by 2% */
3635 char rpl_fmt[sizeof (abmon[0]) + 100];
3636 const char *pb;
3637 if (required_mon_width && (pb = strstr (fmt, "%b")))
3639 if (strlen (fmt) < (sizeof (rpl_fmt) - sizeof (abmon[0]) + 2))
3641 char *pfmt = rpl_fmt;
3642 nfmt = rpl_fmt;
3644 pfmt = mempcpy (pfmt, fmt, pb - fmt);
3645 pfmt = stpcpy (pfmt, abmon[tm->tm_mon]);
3646 strcpy (pfmt, pb + 2);
3649 size_t ret = nstrftime (buf, size, nfmt, tm, __utc, __ns);
3650 return ret;
3653 /* Return the expected number of columns in a long-format time stamp,
3654 or zero if it cannot be calculated. */
3656 static int
3657 long_time_expected_width (void)
3659 static int width = -1;
3661 if (width < 0)
3663 time_t epoch = 0;
3664 struct tm const *tm = localtime (&epoch);
3665 char buf[TIME_STAMP_LEN_MAXIMUM + 1];
3667 /* In case you're wondering if localtime can fail with an input time_t
3668 value of 0, let's just say it's very unlikely, but not inconceivable.
3669 The TZ environment variable would have to specify a time zone that
3670 is 2**31-1900 years or more ahead of UTC. This could happen only on
3671 a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
3672 However, this is not possible with Solaris 10 or glibc-2.3.5, since
3673 their implementations limit the offset to 167:59 and 24:00, resp. */
3674 if (tm)
3676 size_t len =
3677 align_nstrftime (buf, sizeof buf, long_time_format[0], tm, 0, 0);
3678 if (len != 0)
3679 width = mbsnwidth (buf, len, 0);
3682 if (width < 0)
3683 width = 0;
3686 return width;
3689 /* Print the user or group name NAME, with numeric id ID, using a
3690 print width of WIDTH columns. */
3692 static void
3693 format_user_or_group (char const *name, unsigned long int id, int width)
3695 size_t len;
3697 if (name)
3699 int width_gap = width - mbswidth (name, 0);
3700 int pad = MAX (0, width_gap);
3701 fputs (name, stdout);
3702 len = strlen (name) + pad;
3705 putchar (' ');
3706 while (pad--);
3708 else
3710 printf ("%*lu ", width, id);
3711 len = width;
3714 dired_pos += len + 1;
3717 /* Print the name or id of the user with id U, using a print width of
3718 WIDTH. */
3720 static void
3721 format_user (uid_t u, int width, bool stat_ok)
3723 format_user_or_group (! stat_ok ? "?" :
3724 (numeric_ids ? NULL : getuser (u)), u, width);
3727 /* Likewise, for groups. */
3729 static void
3730 format_group (gid_t g, int width, bool stat_ok)
3732 format_user_or_group (! stat_ok ? "?" :
3733 (numeric_ids ? NULL : getgroup (g)), g, width);
3736 /* Return the number of columns that format_user_or_group will print. */
3738 static int
3739 format_user_or_group_width (char const *name, unsigned long int id)
3741 if (name)
3743 int len = mbswidth (name, 0);
3744 return MAX (0, len);
3746 else
3748 char buf[INT_BUFSIZE_BOUND (id)];
3749 sprintf (buf, "%lu", id);
3750 return strlen (buf);
3754 /* Return the number of columns that format_user will print. */
3756 static int
3757 format_user_width (uid_t u)
3759 return format_user_or_group_width (numeric_ids ? NULL : getuser (u), u);
3762 /* Likewise, for groups. */
3764 static int
3765 format_group_width (gid_t g)
3767 return format_user_or_group_width (numeric_ids ? NULL : getgroup (g), g);
3770 /* Return a pointer to a formatted version of F->stat.st_ino,
3771 possibly using buffer, BUF, of length BUFLEN, which must be at least
3772 INT_BUFSIZE_BOUND (uintmax_t) bytes. */
3773 static char *
3774 format_inode (char *buf, size_t buflen, const struct fileinfo *f)
3776 assert (INT_BUFSIZE_BOUND (uintmax_t) <= buflen);
3777 return (f->stat_ok && f->stat.st_ino != NOT_AN_INODE_NUMBER
3778 ? umaxtostr (f->stat.st_ino, buf)
3779 : (char *) "?");
3782 /* Print information about F in long format. */
3783 static void
3784 print_long_format (const struct fileinfo *f)
3786 char modebuf[12];
3787 char buf
3788 [LONGEST_HUMAN_READABLE + 1 /* inode */
3789 + LONGEST_HUMAN_READABLE + 1 /* size in blocks */
3790 + sizeof (modebuf) - 1 + 1 /* mode string */
3791 + INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
3792 + LONGEST_HUMAN_READABLE + 2 /* major device number */
3793 + LONGEST_HUMAN_READABLE + 1 /* minor device number */
3794 + TIME_STAMP_LEN_MAXIMUM + 1 /* max length of time/date */
3796 size_t s;
3797 char *p;
3798 struct timespec when_timespec;
3799 struct tm *when_local;
3801 /* Compute the mode string, except remove the trailing space if no
3802 file in this directory has an ACL or SELinux security context. */
3803 if (f->stat_ok)
3804 filemodestring (&f->stat, modebuf);
3805 else
3807 modebuf[0] = filetype_letter[f->filetype];
3808 memset (modebuf + 1, '?', 10);
3809 modebuf[11] = '\0';
3811 if (! any_has_acl)
3812 modebuf[10] = '\0';
3813 else if (f->acl_type == ACL_T_SELINUX_ONLY)
3814 modebuf[10] = '.';
3815 else if (f->acl_type == ACL_T_YES)
3816 modebuf[10] = '+';
3818 switch (time_type)
3820 case time_ctime:
3821 when_timespec = get_stat_ctime (&f->stat);
3822 break;
3823 case time_mtime:
3824 when_timespec = get_stat_mtime (&f->stat);
3825 break;
3826 case time_atime:
3827 when_timespec = get_stat_atime (&f->stat);
3828 break;
3829 default:
3830 abort ();
3833 p = buf;
3835 if (print_inode)
3837 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3838 sprintf (p, "%*s ", inode_number_width,
3839 format_inode (hbuf, sizeof hbuf, f));
3840 /* Increment by strlen (p) here, rather than by inode_number_width + 1.
3841 The latter is wrong when inode_number_width is zero. */
3842 p += strlen (p);
3845 if (print_block_size)
3847 char hbuf[LONGEST_HUMAN_READABLE + 1];
3848 char const *blocks =
3849 (! f->stat_ok
3850 ? "?"
3851 : human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts,
3852 ST_NBLOCKSIZE, output_block_size));
3853 int pad;
3854 for (pad = block_size_width - mbswidth (blocks, 0); 0 < pad; pad--)
3855 *p++ = ' ';
3856 while ((*p++ = *blocks++))
3857 continue;
3858 p[-1] = ' ';
3861 /* The last byte of the mode string is the POSIX
3862 "optional alternate access method flag". */
3864 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3865 sprintf (p, "%s %*s ", modebuf, nlink_width,
3866 ! f->stat_ok ? "?" : umaxtostr (f->stat.st_nlink, hbuf));
3868 /* Increment by strlen (p) here, rather than by, e.g.,
3869 sizeof modebuf - 2 + any_has_acl + 1 + nlink_width + 1.
3870 The latter is wrong when nlink_width is zero. */
3871 p += strlen (p);
3873 DIRED_INDENT ();
3875 if (print_owner || print_group || print_author || print_scontext)
3877 DIRED_FPUTS (buf, stdout, p - buf);
3879 if (print_owner)
3880 format_user (f->stat.st_uid, owner_width, f->stat_ok);
3882 if (print_group)
3883 format_group (f->stat.st_gid, group_width, f->stat_ok);
3885 if (print_author)
3886 format_user (f->stat.st_author, author_width, f->stat_ok);
3888 if (print_scontext)
3889 format_user_or_group (f->scontext, 0, scontext_width);
3891 p = buf;
3894 if (f->stat_ok
3895 && (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode)))
3897 char majorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3898 char minorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3899 int blanks_width = (file_size_width
3900 - (major_device_number_width + 2
3901 + minor_device_number_width));
3902 sprintf (p, "%*s, %*s ",
3903 major_device_number_width + MAX (0, blanks_width),
3904 umaxtostr (major (f->stat.st_rdev), majorbuf),
3905 minor_device_number_width,
3906 umaxtostr (minor (f->stat.st_rdev), minorbuf));
3907 p += file_size_width + 1;
3909 else
3911 char hbuf[LONGEST_HUMAN_READABLE + 1];
3912 char const *size =
3913 (! f->stat_ok
3914 ? "?"
3915 : human_readable (unsigned_file_size (f->stat.st_size),
3916 hbuf, file_human_output_opts, 1,
3917 file_output_block_size));
3918 int pad;
3919 for (pad = file_size_width - mbswidth (size, 0); 0 < pad; pad--)
3920 *p++ = ' ';
3921 while ((*p++ = *size++))
3922 continue;
3923 p[-1] = ' ';
3926 when_local = localtime (&when_timespec.tv_sec);
3927 s = 0;
3928 *p = '\1';
3930 if (f->stat_ok && when_local)
3932 struct timespec six_months_ago;
3933 bool recent;
3934 char const *fmt;
3936 /* If the file appears to be in the future, update the current
3937 time, in case the file happens to have been modified since
3938 the last time we checked the clock. */
3939 if (timespec_cmp (current_time, when_timespec) < 0)
3941 /* Note that gettime may call gettimeofday which, on some non-
3942 compliant systems, clobbers the buffer used for localtime's result.
3943 But it's ok here, because we use a gettimeofday wrapper that
3944 saves and restores the buffer around the gettimeofday call. */
3945 gettime (&current_time);
3948 /* Consider a time to be recent if it is within the past six months.
3949 A Gregorian year has 365.2425 * 24 * 60 * 60 == 31556952 seconds
3950 on the average. Write this value as an integer constant to
3951 avoid floating point hassles. */
3952 six_months_ago.tv_sec = current_time.tv_sec - 31556952 / 2;
3953 six_months_ago.tv_nsec = current_time.tv_nsec;
3955 recent = (timespec_cmp (six_months_ago, when_timespec) < 0
3956 && (timespec_cmp (when_timespec, current_time) < 0));
3957 fmt = long_time_format[recent];
3959 /* We assume here that all time zones are offset from UTC by a
3960 whole number of seconds. */
3961 s = align_nstrftime (p, TIME_STAMP_LEN_MAXIMUM + 1, fmt,
3962 when_local, 0, when_timespec.tv_nsec);
3965 if (s || !*p)
3967 p += s;
3968 *p++ = ' ';
3970 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
3971 *p = '\0';
3973 else
3975 /* The time cannot be converted using the desired format, so
3976 print it as a huge integer number of seconds. */
3977 char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
3978 sprintf (p, "%*s ", long_time_expected_width (),
3979 (! f->stat_ok
3980 ? "?"
3981 : timetostr (when_timespec.tv_sec, hbuf)));
3982 /* FIXME: (maybe) We discarded when_timespec.tv_nsec. */
3983 p += strlen (p);
3986 DIRED_FPUTS (buf, stdout, p - buf);
3987 size_t w = print_name_with_quoting (f, false, &dired_obstack, p - buf);
3989 if (f->filetype == symbolic_link)
3991 if (f->linkname)
3993 DIRED_FPUTS_LITERAL (" -> ", stdout);
3994 print_name_with_quoting (f, true, NULL, (p - buf) + w + 4);
3995 if (indicator_style != none)
3996 print_type_indicator (true, f->linkmode, unknown);
3999 else if (indicator_style != none)
4000 print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4003 /* Output to OUT a quoted representation of the file name NAME,
4004 using OPTIONS to control quoting. Produce no output if OUT is NULL.
4005 Store the number of screen columns occupied by NAME's quoted
4006 representation into WIDTH, if non-NULL. Return the number of bytes
4007 produced. */
4009 static size_t
4010 quote_name (FILE *out, const char *name, struct quoting_options const *options,
4011 size_t *width)
4013 char smallbuf[BUFSIZ];
4014 size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, name, -1, options);
4015 char *buf;
4016 size_t displayed_width IF_LINT ( = 0);
4018 if (len < sizeof smallbuf)
4019 buf = smallbuf;
4020 else
4022 buf = alloca (len + 1);
4023 quotearg_buffer (buf, len + 1, name, -1, options);
4026 if (qmark_funny_chars)
4028 if (MB_CUR_MAX > 1)
4030 char const *p = buf;
4031 char const *plimit = buf + len;
4032 char *q = buf;
4033 displayed_width = 0;
4035 while (p < plimit)
4036 switch (*p)
4038 case ' ': case '!': case '"': case '#': case '%':
4039 case '&': case '\'': case '(': case ')': case '*':
4040 case '+': case ',': case '-': case '.': case '/':
4041 case '0': case '1': case '2': case '3': case '4':
4042 case '5': case '6': case '7': case '8': case '9':
4043 case ':': case ';': case '<': case '=': case '>':
4044 case '?':
4045 case 'A': case 'B': case 'C': case 'D': case 'E':
4046 case 'F': case 'G': case 'H': case 'I': case 'J':
4047 case 'K': case 'L': case 'M': case 'N': case 'O':
4048 case 'P': case 'Q': case 'R': case 'S': case 'T':
4049 case 'U': case 'V': case 'W': case 'X': case 'Y':
4050 case 'Z':
4051 case '[': case '\\': case ']': case '^': case '_':
4052 case 'a': case 'b': case 'c': case 'd': case 'e':
4053 case 'f': case 'g': case 'h': case 'i': case 'j':
4054 case 'k': case 'l': case 'm': case 'n': case 'o':
4055 case 'p': case 'q': case 'r': case 's': case 't':
4056 case 'u': case 'v': case 'w': case 'x': case 'y':
4057 case 'z': case '{': case '|': case '}': case '~':
4058 /* These characters are printable ASCII characters. */
4059 *q++ = *p++;
4060 displayed_width += 1;
4061 break;
4062 default:
4063 /* If we have a multibyte sequence, copy it until we
4064 reach its end, replacing each non-printable multibyte
4065 character with a single question mark. */
4067 mbstate_t mbstate = { 0, };
4070 wchar_t wc;
4071 size_t bytes;
4072 int w;
4074 bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
4076 if (bytes == (size_t) -1)
4078 /* An invalid multibyte sequence was
4079 encountered. Skip one input byte, and
4080 put a question mark. */
4081 p++;
4082 *q++ = '?';
4083 displayed_width += 1;
4084 break;
4087 if (bytes == (size_t) -2)
4089 /* An incomplete multibyte character
4090 at the end. Replace it entirely with
4091 a question mark. */
4092 p = plimit;
4093 *q++ = '?';
4094 displayed_width += 1;
4095 break;
4098 if (bytes == 0)
4099 /* A null wide character was encountered. */
4100 bytes = 1;
4102 w = wcwidth (wc);
4103 if (w >= 0)
4105 /* A printable multibyte character.
4106 Keep it. */
4107 for (; bytes > 0; --bytes)
4108 *q++ = *p++;
4109 displayed_width += w;
4111 else
4113 /* An unprintable multibyte character.
4114 Replace it entirely with a question
4115 mark. */
4116 p += bytes;
4117 *q++ = '?';
4118 displayed_width += 1;
4121 while (! mbsinit (&mbstate));
4123 break;
4126 /* The buffer may have shrunk. */
4127 len = q - buf;
4129 else
4131 char *p = buf;
4132 char const *plimit = buf + len;
4134 while (p < plimit)
4136 if (! isprint (to_uchar (*p)))
4137 *p = '?';
4138 p++;
4140 displayed_width = len;
4143 else if (width != NULL)
4145 if (MB_CUR_MAX > 1)
4146 displayed_width = mbsnwidth (buf, len, 0);
4147 else
4149 char const *p = buf;
4150 char const *plimit = buf + len;
4152 displayed_width = 0;
4153 while (p < plimit)
4155 if (isprint (to_uchar (*p)))
4156 displayed_width++;
4157 p++;
4162 if (out != NULL)
4163 fwrite (buf, 1, len, out);
4164 if (width != NULL)
4165 *width = displayed_width;
4166 return len;
4169 static size_t
4170 print_name_with_quoting (const struct fileinfo *f,
4171 bool symlink_target,
4172 struct obstack *stack,
4173 size_t start_col)
4175 const char* name = symlink_target ? f->linkname : f->name;
4177 bool used_color_this_time
4178 = (print_with_color
4179 && (print_color_indicator (f, symlink_target)
4180 || is_colored (C_NORM)));
4182 if (stack)
4183 PUSH_CURRENT_DIRED_POS (stack);
4185 size_t width = quote_name (stdout, name, filename_quoting_options, NULL);
4186 dired_pos += width;
4188 if (stack)
4189 PUSH_CURRENT_DIRED_POS (stack);
4191 process_signals ();
4192 if (used_color_this_time)
4194 prep_non_filename_text ();
4195 if (start_col / line_length != (start_col + width - 1) / line_length)
4196 put_indicator (&color_indicator[C_CLR_TO_EOL]);
4199 return width;
4202 static void
4203 prep_non_filename_text (void)
4205 if (color_indicator[C_END].string != NULL)
4206 put_indicator (&color_indicator[C_END]);
4207 else
4209 put_indicator (&color_indicator[C_LEFT]);
4210 put_indicator (&color_indicator[C_RESET]);
4211 put_indicator (&color_indicator[C_RIGHT]);
4215 /* Print the file name of 'f' with appropriate quoting.
4216 Also print file size, inode number, and filetype indicator character,
4217 as requested by switches. */
4219 static size_t
4220 print_file_name_and_frills (const struct fileinfo *f, size_t start_col)
4222 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
4224 set_normal_color ();
4226 if (print_inode)
4227 printf ("%*s ", format == with_commas ? 0 : inode_number_width,
4228 format_inode (buf, sizeof buf, f));
4230 if (print_block_size)
4231 printf ("%*s ", format == with_commas ? 0 : block_size_width,
4232 ! f->stat_ok ? "?"
4233 : human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts,
4234 ST_NBLOCKSIZE, output_block_size));
4236 if (print_scontext)
4237 printf ("%*s ", format == with_commas ? 0 : scontext_width, f->scontext);
4239 size_t width = print_name_with_quoting (f, false, NULL, start_col);
4241 if (indicator_style != none)
4242 width += print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4244 return width;
4247 /* Given these arguments describing a file, return the single-byte
4248 type indicator, or 0. */
4249 static char
4250 get_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
4252 char c;
4254 if (stat_ok ? S_ISREG (mode) : type == normal)
4256 if (stat_ok && indicator_style == classify && (mode & S_IXUGO))
4257 c = '*';
4258 else
4259 c = 0;
4261 else
4263 if (stat_ok ? S_ISDIR (mode) : type == directory || type == arg_directory)
4264 c = '/';
4265 else if (indicator_style == slash)
4266 c = 0;
4267 else if (stat_ok ? S_ISLNK (mode) : type == symbolic_link)
4268 c = '@';
4269 else if (stat_ok ? S_ISFIFO (mode) : type == fifo)
4270 c = '|';
4271 else if (stat_ok ? S_ISSOCK (mode) : type == sock)
4272 c = '=';
4273 else if (stat_ok && S_ISDOOR (mode))
4274 c = '>';
4275 else
4276 c = 0;
4278 return c;
4281 static bool
4282 print_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
4284 char c = get_type_indicator (stat_ok, mode, type);
4285 if (c)
4286 DIRED_PUTCHAR (c);
4287 return !!c;
4290 /* Returns whether any color sequence was printed. */
4291 static bool
4292 print_color_indicator (const struct fileinfo *f, bool symlink_target)
4294 enum indicator_no type;
4295 struct color_ext_type *ext; /* Color extension */
4296 size_t len; /* Length of name */
4298 const char* name;
4299 mode_t mode;
4300 int linkok;
4301 if (symlink_target)
4303 name = f->linkname;
4304 mode = f->linkmode;
4305 linkok = f->linkok ? 0 : -1;
4307 else
4309 name = f->name;
4310 mode = FILE_OR_LINK_MODE (f);
4311 linkok = f->linkok;
4314 /* Is this a nonexistent file? If so, linkok == -1. */
4316 if (linkok == -1 && is_colored (C_MISSING))
4317 type = C_MISSING;
4318 else if (!f->stat_ok)
4320 static enum indicator_no filetype_indicator[] = FILETYPE_INDICATORS;
4321 type = filetype_indicator[f->filetype];
4323 else
4325 if (S_ISREG (mode))
4327 type = C_FILE;
4329 if ((mode & S_ISUID) != 0 && is_colored (C_SETUID))
4330 type = C_SETUID;
4331 else if ((mode & S_ISGID) != 0 && is_colored (C_SETGID))
4332 type = C_SETGID;
4333 else if (is_colored (C_CAP) && f->has_capability)
4334 type = C_CAP;
4335 else if ((mode & S_IXUGO) != 0 && is_colored (C_EXEC))
4336 type = C_EXEC;
4337 else if ((1 < f->stat.st_nlink) && is_colored (C_MULTIHARDLINK))
4338 type = C_MULTIHARDLINK;
4340 else if (S_ISDIR (mode))
4342 type = C_DIR;
4344 if ((mode & S_ISVTX) && (mode & S_IWOTH)
4345 && is_colored (C_STICKY_OTHER_WRITABLE))
4346 type = C_STICKY_OTHER_WRITABLE;
4347 else if ((mode & S_IWOTH) != 0 && is_colored (C_OTHER_WRITABLE))
4348 type = C_OTHER_WRITABLE;
4349 else if ((mode & S_ISVTX) != 0 && is_colored (C_STICKY))
4350 type = C_STICKY;
4352 else if (S_ISLNK (mode))
4353 type = C_LINK;
4354 else if (S_ISFIFO (mode))
4355 type = C_FIFO;
4356 else if (S_ISSOCK (mode))
4357 type = C_SOCK;
4358 else if (S_ISBLK (mode))
4359 type = C_BLK;
4360 else if (S_ISCHR (mode))
4361 type = C_CHR;
4362 else if (S_ISDOOR (mode))
4363 type = C_DOOR;
4364 else
4366 /* Classify a file of some other type as C_ORPHAN. */
4367 type = C_ORPHAN;
4371 /* Check the file's suffix only if still classified as C_FILE. */
4372 ext = NULL;
4373 if (type == C_FILE)
4375 /* Test if NAME has a recognized suffix. */
4377 len = strlen (name);
4378 name += len; /* Pointer to final \0. */
4379 for (ext = color_ext_list; ext != NULL; ext = ext->next)
4381 if (ext->ext.len <= len
4382 && STREQ_LEN (name - ext->ext.len, ext->ext.string,
4383 ext->ext.len))
4384 break;
4388 /* Adjust the color for orphaned symlinks. */
4389 if (type == C_LINK && !linkok)
4391 if (color_symlink_as_referent || is_colored (C_ORPHAN))
4392 type = C_ORPHAN;
4396 const struct bin_str *const s
4397 = ext ? &(ext->seq) : &color_indicator[type];
4398 if (s->string != NULL)
4400 /* Need to reset so not dealing with attribute combinations */
4401 if (is_colored (C_NORM))
4402 restore_default_color ();
4403 put_indicator (&color_indicator[C_LEFT]);
4404 put_indicator (s);
4405 put_indicator (&color_indicator[C_RIGHT]);
4406 return true;
4408 else
4409 return false;
4413 /* Output a color indicator (which may contain nulls). */
4414 static void
4415 put_indicator (const struct bin_str *ind)
4417 if (! used_color)
4419 used_color = true;
4420 prep_non_filename_text ();
4423 fwrite (ind->string, ind->len, 1, stdout);
4426 static size_t
4427 length_of_file_name_and_frills (const struct fileinfo *f)
4429 size_t len = 0;
4430 size_t name_width;
4431 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
4433 if (print_inode)
4434 len += 1 + (format == with_commas
4435 ? strlen (umaxtostr (f->stat.st_ino, buf))
4436 : inode_number_width);
4438 if (print_block_size)
4439 len += 1 + (format == with_commas
4440 ? strlen (! f->stat_ok ? "?"
4441 : human_readable (ST_NBLOCKS (f->stat), buf,
4442 human_output_opts, ST_NBLOCKSIZE,
4443 output_block_size))
4444 : block_size_width);
4446 if (print_scontext)
4447 len += 1 + (format == with_commas ? strlen (f->scontext) : scontext_width);
4449 quote_name (NULL, f->name, filename_quoting_options, &name_width);
4450 len += name_width;
4452 if (indicator_style != none)
4454 char c = get_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4455 len += (c != 0);
4458 return len;
4461 static void
4462 print_many_per_line (void)
4464 size_t row; /* Current row. */
4465 size_t cols = calculate_columns (true);
4466 struct column_info const *line_fmt = &column_info[cols - 1];
4468 /* Calculate the number of rows that will be in each column except possibly
4469 for a short column on the right. */
4470 size_t rows = cwd_n_used / cols + (cwd_n_used % cols != 0);
4472 for (row = 0; row < rows; row++)
4474 size_t col = 0;
4475 size_t filesno = row;
4476 size_t pos = 0;
4478 /* Print the next row. */
4479 while (1)
4481 struct fileinfo const *f = sorted_file[filesno];
4482 size_t name_length = length_of_file_name_and_frills (f);
4483 size_t max_name_length = line_fmt->col_arr[col++];
4484 print_file_name_and_frills (f, pos);
4486 filesno += rows;
4487 if (filesno >= cwd_n_used)
4488 break;
4490 indent (pos + name_length, pos + max_name_length);
4491 pos += max_name_length;
4493 putchar ('\n');
4497 static void
4498 print_horizontal (void)
4500 size_t filesno;
4501 size_t pos = 0;
4502 size_t cols = calculate_columns (false);
4503 struct column_info const *line_fmt = &column_info[cols - 1];
4504 struct fileinfo const *f = sorted_file[0];
4505 size_t name_length = length_of_file_name_and_frills (f);
4506 size_t max_name_length = line_fmt->col_arr[0];
4508 /* Print first entry. */
4509 print_file_name_and_frills (f, 0);
4511 /* Now the rest. */
4512 for (filesno = 1; filesno < cwd_n_used; ++filesno)
4514 size_t col = filesno % cols;
4516 if (col == 0)
4518 putchar ('\n');
4519 pos = 0;
4521 else
4523 indent (pos + name_length, pos + max_name_length);
4524 pos += max_name_length;
4527 f = sorted_file[filesno];
4528 print_file_name_and_frills (f, pos);
4530 name_length = length_of_file_name_and_frills (f);
4531 max_name_length = line_fmt->col_arr[col];
4533 putchar ('\n');
4536 static void
4537 print_with_commas (void)
4539 size_t filesno;
4540 size_t pos = 0;
4542 for (filesno = 0; filesno < cwd_n_used; filesno++)
4544 struct fileinfo const *f = sorted_file[filesno];
4545 size_t len = length_of_file_name_and_frills (f);
4547 if (filesno != 0)
4549 char separator;
4551 if (pos + len + 2 < line_length)
4553 pos += 2;
4554 separator = ' ';
4556 else
4558 pos = 0;
4559 separator = '\n';
4562 putchar (',');
4563 putchar (separator);
4566 print_file_name_and_frills (f, pos);
4567 pos += len;
4569 putchar ('\n');
4572 /* Assuming cursor is at position FROM, indent up to position TO.
4573 Use a TAB character instead of two or more spaces whenever possible. */
4575 static void
4576 indent (size_t from, size_t to)
4578 while (from < to)
4580 if (tabsize != 0 && to / tabsize > (from + 1) / tabsize)
4582 putchar ('\t');
4583 from += tabsize - from % tabsize;
4585 else
4587 putchar (' ');
4588 from++;
4593 /* Put DIRNAME/NAME into DEST, handling '.' and '/' properly. */
4594 /* FIXME: maybe remove this function someday. See about using a
4595 non-malloc'ing version of file_name_concat. */
4597 static void
4598 attach (char *dest, const char *dirname, const char *name)
4600 const char *dirnamep = dirname;
4602 /* Copy dirname if it is not ".". */
4603 if (dirname[0] != '.' || dirname[1] != 0)
4605 while (*dirnamep)
4606 *dest++ = *dirnamep++;
4607 /* Add '/' if 'dirname' doesn't already end with it. */
4608 if (dirnamep > dirname && dirnamep[-1] != '/')
4609 *dest++ = '/';
4611 while (*name)
4612 *dest++ = *name++;
4613 *dest = 0;
4616 /* Allocate enough column info suitable for the current number of
4617 files and display columns, and initialize the info to represent the
4618 narrowest possible columns. */
4620 static void
4621 init_column_info (void)
4623 size_t i;
4624 size_t max_cols = MIN (max_idx, cwd_n_used);
4626 /* Currently allocated columns in column_info. */
4627 static size_t column_info_alloc;
4629 if (column_info_alloc < max_cols)
4631 size_t new_column_info_alloc;
4632 size_t *p;
4634 if (max_cols < max_idx / 2)
4636 /* The number of columns is far less than the display width
4637 allows. Grow the allocation, but only so that it's
4638 double the current requirements. If the display is
4639 extremely wide, this avoids allocating a lot of memory
4640 that is never needed. */
4641 column_info = xnrealloc (column_info, max_cols,
4642 2 * sizeof *column_info);
4643 new_column_info_alloc = 2 * max_cols;
4645 else
4647 column_info = xnrealloc (column_info, max_idx, sizeof *column_info);
4648 new_column_info_alloc = max_idx;
4651 /* Allocate the new size_t objects by computing the triangle
4652 formula n * (n + 1) / 2, except that we don't need to
4653 allocate the part of the triangle that we've already
4654 allocated. Check for address arithmetic overflow. */
4656 size_t column_info_growth = new_column_info_alloc - column_info_alloc;
4657 size_t s = column_info_alloc + 1 + new_column_info_alloc;
4658 size_t t = s * column_info_growth;
4659 if (s < new_column_info_alloc || t / column_info_growth != s)
4660 xalloc_die ();
4661 p = xnmalloc (t / 2, sizeof *p);
4664 /* Grow the triangle by parceling out the cells just allocated. */
4665 for (i = column_info_alloc; i < new_column_info_alloc; i++)
4667 column_info[i].col_arr = p;
4668 p += i + 1;
4671 column_info_alloc = new_column_info_alloc;
4674 for (i = 0; i < max_cols; ++i)
4676 size_t j;
4678 column_info[i].valid_len = true;
4679 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
4680 for (j = 0; j <= i; ++j)
4681 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
4685 /* Calculate the number of columns needed to represent the current set
4686 of files in the current display width. */
4688 static size_t
4689 calculate_columns (bool by_columns)
4691 size_t filesno; /* Index into cwd_file. */
4692 size_t cols; /* Number of files across. */
4694 /* Normally the maximum number of columns is determined by the
4695 screen width. But if few files are available this might limit it
4696 as well. */
4697 size_t max_cols = MIN (max_idx, cwd_n_used);
4699 init_column_info ();
4701 /* Compute the maximum number of possible columns. */
4702 for (filesno = 0; filesno < cwd_n_used; ++filesno)
4704 struct fileinfo const *f = sorted_file[filesno];
4705 size_t name_length = length_of_file_name_and_frills (f);
4706 size_t i;
4708 for (i = 0; i < max_cols; ++i)
4710 if (column_info[i].valid_len)
4712 size_t idx = (by_columns
4713 ? filesno / ((cwd_n_used + i) / (i + 1))
4714 : filesno % (i + 1));
4715 size_t real_length = name_length + (idx == i ? 0 : 2);
4717 if (column_info[i].col_arr[idx] < real_length)
4719 column_info[i].line_len += (real_length
4720 - column_info[i].col_arr[idx]);
4721 column_info[i].col_arr[idx] = real_length;
4722 column_info[i].valid_len = (column_info[i].line_len
4723 < line_length);
4729 /* Find maximum allowed columns. */
4730 for (cols = max_cols; 1 < cols; --cols)
4732 if (column_info[cols - 1].valid_len)
4733 break;
4736 return cols;
4739 void
4740 usage (int status)
4742 if (status != EXIT_SUCCESS)
4743 emit_try_help ();
4744 else
4746 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
4747 fputs (_("\
4748 List information about the FILEs (the current directory by default).\n\
4749 Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.\n\
4750 "), stdout);
4752 emit_mandatory_arg_note ();
4754 fputs (_("\
4755 -a, --all do not ignore entries starting with .\n\
4756 -A, --almost-all do not list implied . and ..\n\
4757 --author with -l, print the author of each file\n\
4758 -b, --escape print C-style escapes for nongraphic characters\n\
4759 "), stdout);
4760 fputs (_("\
4761 --block-size=SIZE scale sizes by SIZE before printing them. E.g.,\n\
4762 '--block-size=M' prints sizes in units of\n\
4763 1,048,576 bytes. See SIZE format below.\n\
4764 -B, --ignore-backups do not list implied entries ending with ~\n\
4765 -c with -lt: sort by, and show, ctime (time of last\n\
4766 modification of file status information)\n\
4767 with -l: show ctime and sort by name\n\
4768 otherwise: sort by ctime, newest first\n\
4769 "), stdout);
4770 fputs (_("\
4771 -C list entries by columns\n\
4772 --color[=WHEN] colorize the output. WHEN defaults to 'always'\n\
4773 or can be 'never' or 'auto'. More info below\n\
4774 -d, --directory list directory entries instead of contents,\n\
4775 and do not dereference symbolic links\n\
4776 -D, --dired generate output designed for Emacs' dired mode\n\
4777 "), stdout);
4778 fputs (_("\
4779 -f do not sort, enable -aU, disable -ls --color\n\
4780 -F, --classify append indicator (one of */=>@|) to entries\n\
4781 --file-type likewise, except do not append '*'\n\
4782 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
4783 single-column -1, verbose -l, vertical -C\n\
4784 --full-time like -l --time-style=full-iso\n\
4785 "), stdout);
4786 fputs (_("\
4787 -g like -l, but do not list owner\n\
4788 "), stdout);
4789 fputs (_("\
4790 --group-directories-first\n\
4791 group directories before files.\n\
4792 augment with a --sort option, but any\n\
4793 use of --sort=none (-U) disables grouping\n\
4794 "), stdout);
4795 fputs (_("\
4796 -G, --no-group in a long listing, don't print group names\n\
4797 -h, --human-readable with -l, print sizes in human readable format\n\
4798 (e.g., 1K 234M 2G)\n\
4799 --si likewise, but use powers of 1000 not 1024\n\
4800 "), stdout);
4801 fputs (_("\
4802 -H, --dereference-command-line\n\
4803 follow symbolic links listed on the command line\n\
4804 --dereference-command-line-symlink-to-dir\n\
4805 follow each command line symbolic link\n\
4806 that points to a directory\n\
4807 --hide=PATTERN do not list implied entries matching shell PATTERN\
4809 (overridden by -a or -A)\n\
4810 "), stdout);
4811 fputs (_("\
4812 --indicator-style=WORD append indicator with style WORD to entry names:\
4814 none (default), slash (-p),\n\
4815 file-type (--file-type), classify (-F)\n\
4816 -i, --inode print the index number of each file\n\
4817 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\
4819 -k, --kibibytes use 1024-byte blocks\n\
4820 "), stdout);
4821 fputs (_("\
4822 -l use a long listing format\n\
4823 -L, --dereference when showing file information for a symbolic\n\
4824 link, show information for the file the link\n\
4825 references rather than for the link itself\n\
4826 -m fill width with a comma separated list of entries\
4828 "), stdout);
4829 fputs (_("\
4830 -n, --numeric-uid-gid like -l, but list numeric user and group IDs\n\
4831 -N, --literal print raw entry names (don't treat e.g. control\n\
4832 characters specially)\n\
4833 -o like -l, but do not list group information\n\
4834 -p, --indicator-style=slash\n\
4835 append / indicator to directories\n\
4836 "), stdout);
4837 fputs (_("\
4838 -q, --hide-control-chars print ? instead of non graphic characters\n\
4839 --show-control-chars show non graphic characters as-is (default\n\
4840 unless program is 'ls' and output is a terminal)\n\
4841 -Q, --quote-name enclose entry names in double quotes\n\
4842 --quoting-style=WORD use quoting style WORD for entry names:\n\
4843 literal, locale, shell, shell-always, c, escape\
4845 "), stdout);
4846 fputs (_("\
4847 -r, --reverse reverse order while sorting\n\
4848 -R, --recursive list subdirectories recursively\n\
4849 -s, --size print the allocated size of each file, in blocks\n\
4850 "), stdout);
4851 fputs (_("\
4852 -S sort by file size\n\
4853 --sort=WORD sort by WORD instead of name: none -U,\n\
4854 extension -X, size -S, time -t, version -v\n\
4855 --time=WORD with -l, show time as WORD instead of modification\
4857 time: atime -u, access -u, use -u, ctime -c,\n\
4858 or status -c; use specified time as sort key\n\
4859 if --sort=time\n\
4860 "), stdout);
4861 fputs (_("\
4862 --time-style=STYLE with -l, show times using style STYLE:\n\
4863 full-iso, long-iso, iso, locale, +FORMAT.\n\
4864 FORMAT is interpreted like 'date'; if FORMAT is\n\
4865 FORMAT1<newline>FORMAT2, FORMAT1 applies to\n\
4866 non-recent files and FORMAT2 to recent files;\n\
4867 if STYLE is prefixed with 'posix-', STYLE\n\
4868 takes effect only outside the POSIX locale\n\
4869 "), stdout);
4870 fputs (_("\
4871 -t sort by modification time, newest first\n\
4872 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
4873 "), stdout);
4874 fputs (_("\
4875 -u with -lt: sort by, and show, access time\n\
4876 with -l: show access time and sort by name\n\
4877 otherwise: sort by access time\n\
4878 -U do not sort; list entries in directory order\n\
4879 -v natural sort of (version) numbers within text\n\
4880 "), stdout);
4881 fputs (_("\
4882 -w, --width=COLS assume screen width instead of current value\n\
4883 -x list entries by lines instead of by columns\n\
4884 -X sort alphabetically by entry extension\n\
4885 -Z, --context print any SELinux security context of each file\n\
4886 -1 list one file per line\n\
4887 "), stdout);
4888 fputs (HELP_OPTION_DESCRIPTION, stdout);
4889 fputs (VERSION_OPTION_DESCRIPTION, stdout);
4890 emit_size_note ();
4891 fputs (_("\
4893 Using color to distinguish file types is disabled both by default and\n\
4894 with --color=never. With --color=auto, ls emits color codes only when\n\
4895 standard output is connected to a terminal. The LS_COLORS environment\n\
4896 variable can change the settings. Use the dircolors command to set it.\n\
4897 "), stdout);
4898 fputs (_("\
4900 Exit status:\n\
4901 0 if OK,\n\
4902 1 if minor problems (e.g., cannot access subdirectory),\n\
4903 2 if serious trouble (e.g., cannot access command-line argument).\n\
4904 "), stdout);
4905 emit_ancillary_info ();
4907 exit (status);