ls --color: do not colorize files with multiple hard links by default
[coreutils.git] / src / ls.c
blob48bc47e904080725b6ef2272c326931a1c1675f8
1 /* `dir', `vdir' and `ls' directory listing programs for GNU.
2 Copyright (C) 85, 88, 90, 91, 1995-2009 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 #ifdef HAVE_CAP
42 # include <sys/capability.h>
43 #endif
45 #if HAVE_TERMIOS_H
46 # include <termios.h>
47 #endif
48 #if HAVE_STROPTS_H
49 # include <stropts.h>
50 #endif
51 #if HAVE_SYS_IOCTL_H
52 # include <sys/ioctl.h>
53 #endif
55 #ifdef WINSIZE_IN_PTEM
56 # include <sys/stream.h>
57 # include <sys/ptem.h>
58 #endif
60 #include <stdio.h>
61 #include <assert.h>
62 #include <setjmp.h>
63 #include <grp.h>
64 #include <pwd.h>
65 #include <getopt.h>
66 #include <signal.h>
67 #include <selinux/selinux.h>
68 #include <wchar.h>
70 #if HAVE_LANGINFO_CODESET
71 # include <langinfo.h>
72 #endif
74 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
75 present. */
76 #ifndef SA_NOCLDSTOP
77 # define SA_NOCLDSTOP 0
78 # define sigprocmask(How, Set, Oset) /* empty */
79 # define sigset_t int
80 # if ! HAVE_SIGINTERRUPT
81 # define siginterrupt(sig, flag) /* empty */
82 # endif
83 #endif
84 #ifndef SA_RESTART
85 # define SA_RESTART 0
86 #endif
88 #include "system.h"
89 #include <fnmatch.h>
91 #include "acl.h"
92 #include "argmatch.h"
93 #include "dev-ino.h"
94 #include "error.h"
95 #include "filenamecat.h"
96 #include "hash.h"
97 #include "human.h"
98 #include "filemode.h"
99 #include "filevercmp.h"
100 #include "idcache.h"
101 #include "ls.h"
102 #include "mbswidth.h"
103 #include "mpsort.h"
104 #include "obstack.h"
105 #include "quote.h"
106 #include "quotearg.h"
107 #include "same.h"
108 #include "stat-time.h"
109 #include "strftime.h"
110 #include "xstrtol.h"
111 #include "areadlink.h"
112 #include "mbsalign.h"
114 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
115 : (ls_mode == LS_MULTI_COL \
116 ? "dir" : "vdir"))
118 #define AUTHORS \
119 proper_name ("Richard M. Stallman"), \
120 proper_name ("David MacKenzie")
122 #define obstack_chunk_alloc malloc
123 #define obstack_chunk_free free
125 /* Return an int indicating the result of comparing two integers.
126 Subtracting doesn't always work, due to overflow. */
127 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
129 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
130 # define st_author st_uid
131 #endif
133 enum filetype
135 unknown,
136 fifo,
137 chardev,
138 directory,
139 blockdev,
140 normal,
141 symbolic_link,
142 sock,
143 whiteout,
144 arg_directory
147 /* Display letters and indicators for each filetype.
148 Keep these in sync with enum filetype. */
149 static char const filetype_letter[] = "?pcdb-lswd";
151 /* Ensure that filetype and filetype_letter have the same
152 number of elements. */
153 verify (sizeof filetype_letter - 1 == arg_directory + 1);
155 #define FILETYPE_INDICATORS \
157 C_ORPHAN, C_FIFO, C_CHR, C_DIR, C_BLK, C_FILE, \
158 C_LINK, C_SOCK, C_FILE, C_DIR \
161 enum acl_type
163 ACL_T_NONE,
164 ACL_T_SELINUX_ONLY,
165 ACL_T_YES
168 struct fileinfo
170 /* The file name. */
171 char *name;
173 /* For symbolic link, name of the file linked to, otherwise zero. */
174 char *linkname;
176 struct stat stat;
178 enum filetype filetype;
180 /* For symbolic link and long listing, st_mode of file linked to, otherwise
181 zero. */
182 mode_t linkmode;
184 /* SELinux security context. */
185 security_context_t scontext;
187 bool stat_ok;
189 /* For symbolic link and color printing, true if linked-to file
190 exists, otherwise false. */
191 bool linkok;
193 /* For long listings, true if the file has an access control list,
194 or an SELinux security context. */
195 enum acl_type acl_type;
198 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
200 /* Null is a valid character in a color indicator (think about Epson
201 printers, for example) so we have to use a length/buffer string
202 type. */
204 struct bin_str
206 size_t len; /* Number of bytes */
207 const char *string; /* Pointer to the same */
210 #if ! HAVE_TCGETPGRP
211 # define tcgetpgrp(Fd) 0
212 #endif
214 static size_t quote_name (FILE *out, const char *name,
215 struct quoting_options const *options,
216 size_t *width);
217 static char *make_link_name (char const *name, char const *linkname);
218 static int decode_switches (int argc, char **argv);
219 static bool file_ignored (char const *name);
220 static uintmax_t gobble_file (char const *name, enum filetype type,
221 ino_t inode, bool command_line_arg,
222 char const *dirname);
223 static bool print_color_indicator (const char *name, mode_t mode, int linkok,
224 bool stat_ok, enum filetype type,
225 nlink_t nlink);
226 static void put_indicator (const struct bin_str *ind);
227 static void add_ignore_pattern (const char *pattern);
228 static void attach (char *dest, const char *dirname, const char *name);
229 static void clear_files (void);
230 static void extract_dirs_from_files (char const *dirname,
231 bool command_line_arg);
232 static void get_link_name (char const *filename, struct fileinfo *f,
233 bool command_line_arg);
234 static void indent (size_t from, size_t to);
235 static size_t calculate_columns (bool by_columns);
236 static void print_current_files (void);
237 static void print_dir (char const *name, char const *realname,
238 bool command_line_arg);
239 static size_t print_file_name_and_frills (const struct fileinfo *f,
240 size_t start_col);
241 static void print_horizontal (void);
242 static int format_user_width (uid_t u);
243 static int format_group_width (gid_t g);
244 static void print_long_format (const struct fileinfo *f);
245 static void print_many_per_line (void);
246 static size_t print_name_with_quoting (const char *p, mode_t mode,
247 int linkok, bool stat_ok,
248 enum filetype type,
249 struct obstack *stack,
250 nlink_t nlink,
251 size_t start_col);
252 static void prep_non_filename_text (void);
253 static bool print_type_indicator (bool stat_ok, mode_t mode,
254 enum filetype type);
255 static void print_with_commas (void);
256 static void queue_directory (char const *name, char const *realname,
257 bool command_line_arg);
258 static void sort_files (void);
259 static void parse_ls_color (void);
260 void usage (int status);
262 /* Initial size of hash table.
263 Most hierarchies are likely to be shallower than this. */
264 #define INITIAL_TABLE_SIZE 30
266 /* The set of `active' directories, from the current command-line argument
267 to the level in the hierarchy at which files are being listed.
268 A directory is represented by its device and inode numbers (struct dev_ino).
269 A directory is added to this set when ls begins listing it or its
270 entries, and it is removed from the set just after ls has finished
271 processing it. This set is used solely to detect loops, e.g., with
272 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
273 static Hash_table *active_dir_set;
275 #define LOOP_DETECT (!!active_dir_set)
277 /* The table of files in the current directory:
279 `cwd_file' points to a vector of `struct fileinfo', one per file.
280 `cwd_n_alloc' is the number of elements space has been allocated for.
281 `cwd_n_used' is the number actually in use. */
283 /* Address of block containing the files that are described. */
284 static struct fileinfo *cwd_file;
286 /* Length of block that `cwd_file' points to, measured in files. */
287 static size_t cwd_n_alloc;
289 /* Index of first unused slot in `cwd_file'. */
290 static size_t cwd_n_used;
292 /* Vector of pointers to files, in proper sorted order, and the number
293 of entries allocated for it. */
294 static void **sorted_file;
295 static size_t sorted_file_alloc;
297 /* When true, in a color listing, color each symlink name according to the
298 type of file it points to. Otherwise, color them according to the `ln'
299 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
300 regardless. This is set when `ln=target' appears in LS_COLORS. */
302 static bool color_symlink_as_referent;
304 /* mode of appropriate file for colorization */
305 #define FILE_OR_LINK_MODE(File) \
306 ((color_symlink_as_referent & (File)->linkok) \
307 ? (File)->linkmode : (File)->stat.st_mode)
310 /* Record of one pending directory waiting to be listed. */
312 struct pending
314 char *name;
315 /* If the directory is actually the file pointed to by a symbolic link we
316 were told to list, `realname' will contain the name of the symbolic
317 link, otherwise zero. */
318 char *realname;
319 bool command_line_arg;
320 struct pending *next;
323 static struct pending *pending_dirs;
325 /* Current time in seconds and nanoseconds since 1970, updated as
326 needed when deciding whether a file is recent. */
328 static struct timespec current_time;
330 static bool print_scontext;
331 static char UNKNOWN_SECURITY_CONTEXT[] = "?";
333 /* Whether any of the files has an ACL. This affects the width of the
334 mode column. */
336 static bool any_has_acl;
338 /* The number of columns to use for columns containing inode numbers,
339 block sizes, link counts, owners, groups, authors, major device
340 numbers, minor device numbers, and file sizes, respectively. */
342 static int inode_number_width;
343 static int block_size_width;
344 static int nlink_width;
345 static int scontext_width;
346 static int owner_width;
347 static int group_width;
348 static int author_width;
349 static int major_device_number_width;
350 static int minor_device_number_width;
351 static int file_size_width;
353 /* Option flags */
355 /* long_format for lots of info, one per line.
356 one_per_line for just names, one per line.
357 many_per_line for just names, many per line, sorted vertically.
358 horizontal for just names, many per line, sorted horizontally.
359 with_commas for just names, many per line, separated by commas.
361 -l (and other options that imply -l), -1, -C, -x and -m control
362 this parameter. */
364 enum format
366 long_format, /* -l and other options that imply -l */
367 one_per_line, /* -1 */
368 many_per_line, /* -C */
369 horizontal, /* -x */
370 with_commas /* -m */
373 static enum format format;
375 /* `full-iso' uses full ISO-style dates and times. `long-iso' uses longer
376 ISO-style time stamps, though shorter than `full-iso'. `iso' uses shorter
377 ISO-style time stamps. `locale' uses locale-dependent time stamps. */
378 enum time_style
380 full_iso_time_style, /* --time-style=full-iso */
381 long_iso_time_style, /* --time-style=long-iso */
382 iso_time_style, /* --time-style=iso */
383 locale_time_style /* --time-style=locale */
386 static char const *const time_style_args[] =
388 "full-iso", "long-iso", "iso", "locale", NULL
390 static enum time_style const time_style_types[] =
392 full_iso_time_style, long_iso_time_style, iso_time_style,
393 locale_time_style
395 ARGMATCH_VERIFY (time_style_args, time_style_types);
397 /* Type of time to print or sort by. Controlled by -c and -u.
398 The values of each item of this enum are important since they are
399 used as indices in the sort functions array (see sort_files()). */
401 enum time_type
403 time_mtime, /* default */
404 time_ctime, /* -c */
405 time_atime, /* -u */
406 time_numtypes /* the number of elements of this enum */
409 static enum time_type time_type;
411 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v.
412 The values of each item of this enum are important since they are
413 used as indices in the sort functions array (see sort_files()). */
415 enum sort_type
417 sort_none = -1, /* -U */
418 sort_name, /* default */
419 sort_extension, /* -X */
420 sort_size, /* -S */
421 sort_version, /* -v */
422 sort_time, /* -t */
423 sort_numtypes /* the number of elements of this enum */
426 static enum sort_type sort_type;
428 /* Direction of sort.
429 false means highest first if numeric,
430 lowest first if alphabetic;
431 these are the defaults.
432 true means the opposite order in each case. -r */
434 static bool sort_reverse;
436 /* True means to display owner information. -g turns this off. */
438 static bool print_owner = true;
440 /* True means to display author information. */
442 static bool print_author;
444 /* True means to display group information. -G and -o turn this off. */
446 static bool print_group = true;
448 /* True means print the user and group id's as numbers rather
449 than as names. -n */
451 static bool numeric_ids;
453 /* True means mention the size in blocks of each file. -s */
455 static bool print_block_size;
457 /* Human-readable options for output. */
458 static int human_output_opts;
460 /* The units to use when printing sizes other than file sizes. */
461 static uintmax_t output_block_size;
463 /* Likewise, but for file sizes. */
464 static uintmax_t file_output_block_size = 1;
466 /* Follow the output with a special string. Using this format,
467 Emacs' dired mode starts up twice as fast, and can handle all
468 strange characters in file names. */
469 static bool dired;
471 /* `none' means don't mention the type of files.
472 `slash' means mention directories only, with a '/'.
473 `file_type' means mention file types.
474 `classify' means mention file types and mark executables.
476 Controlled by -F, -p, and --indicator-style. */
478 enum indicator_style
480 none, /* --indicator-style=none */
481 slash, /* -p, --indicator-style=slash */
482 file_type, /* --indicator-style=file-type */
483 classify /* -F, --indicator-style=classify */
486 static enum indicator_style indicator_style;
488 /* Names of indicator styles. */
489 static char const *const indicator_style_args[] =
491 "none", "slash", "file-type", "classify", NULL
493 static enum indicator_style const indicator_style_types[] =
495 none, slash, file_type, classify
497 ARGMATCH_VERIFY (indicator_style_args, indicator_style_types);
499 /* True means use colors to mark types. Also define the different
500 colors as well as the stuff for the LS_COLORS environment variable.
501 The LS_COLORS variable is now in a termcap-like format. */
503 static bool print_with_color;
505 /* Whether we used any colors in the output so far. If so, we will
506 need to restore the default color later. If not, we will need to
507 call prep_non_filename_text before using color for the first time. */
509 static bool used_color = false;
511 enum color_type
513 color_never, /* 0: default or --color=never */
514 color_always, /* 1: --color=always */
515 color_if_tty /* 2: --color=tty */
518 enum Dereference_symlink
520 DEREF_UNDEFINED = 1,
521 DEREF_NEVER,
522 DEREF_COMMAND_LINE_ARGUMENTS, /* -H */
523 DEREF_COMMAND_LINE_SYMLINK_TO_DIR, /* the default, in certain cases */
524 DEREF_ALWAYS /* -L */
527 enum indicator_no
529 C_LEFT, C_RIGHT, C_END, C_RESET, C_NORM, C_FILE, C_DIR, C_LINK,
530 C_FIFO, C_SOCK,
531 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR, C_SETUID, C_SETGID,
532 C_STICKY, C_OTHER_WRITABLE, C_STICKY_OTHER_WRITABLE, C_CAP, C_MULTIHARDLINK,
533 C_CLR_TO_EOL
536 static const char *const indicator_name[]=
538 "lc", "rc", "ec", "rs", "no", "fi", "di", "ln", "pi", "so",
539 "bd", "cd", "mi", "or", "ex", "do", "su", "sg", "st",
540 "ow", "tw", "ca", "mh", "cl", NULL
543 struct color_ext_type
545 struct bin_str ext; /* The extension we're looking for */
546 struct bin_str seq; /* The sequence to output when we do */
547 struct color_ext_type *next; /* Next in list */
550 static struct bin_str color_indicator[] =
552 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
553 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
554 { 0, NULL }, /* ec: End color (replaces lc+no+rc) */
555 { LEN_STR_PAIR ("0") }, /* rs: Reset to ordinary colors */
556 { 0, NULL }, /* no: Normal */
557 { 0, NULL }, /* fi: File: default */
558 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
559 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
560 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
561 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
562 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
563 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
564 { 0, NULL }, /* mi: Missing file: undefined */
565 { 0, NULL }, /* or: Orphaned symlink: undefined */
566 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
567 { LEN_STR_PAIR ("01;35") }, /* do: Door: bright magenta */
568 { LEN_STR_PAIR ("37;41") }, /* su: setuid: white on red */
569 { LEN_STR_PAIR ("30;43") }, /* sg: setgid: black on yellow */
570 { LEN_STR_PAIR ("37;44") }, /* st: sticky: black on blue */
571 { LEN_STR_PAIR ("34;42") }, /* ow: other-writable: blue on green */
572 { LEN_STR_PAIR ("30;42") }, /* tw: ow w/ sticky: black on green */
573 { LEN_STR_PAIR ("30;41") }, /* ca: black on red */
574 { 0, NULL }, /* mh: disabled by default */
575 { LEN_STR_PAIR ("\033[K") }, /* cl: clear to end of line */
578 /* FIXME: comment */
579 static struct color_ext_type *color_ext_list = NULL;
581 /* Buffer for color sequences */
582 static char *color_buf;
584 /* True means to check for orphaned symbolic link, for displaying
585 colors. */
587 static bool check_symlink_color;
589 /* True means mention the inode number of each file. -i */
591 static bool print_inode;
593 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
594 other options that imply -l), and -L. */
596 static enum Dereference_symlink dereference;
598 /* True means when a directory is found, display info on its
599 contents. -R */
601 static bool recursive;
603 /* True means when an argument is a directory name, display info
604 on it itself. -d */
606 static bool immediate_dirs;
608 /* True means that directories are grouped before files. */
610 static bool directories_first;
612 /* Which files to ignore. */
614 static enum
616 /* Ignore files whose names start with `.', and files specified by
617 --hide and --ignore. */
618 IGNORE_DEFAULT,
620 /* Ignore `.', `..', and files specified by --ignore. */
621 IGNORE_DOT_AND_DOTDOT,
623 /* Ignore only files specified by --ignore. */
624 IGNORE_MINIMAL
625 } ignore_mode;
627 /* A linked list of shell-style globbing patterns. If a non-argument
628 file name matches any of these patterns, it is ignored.
629 Controlled by -I. Multiple -I options accumulate.
630 The -B option adds `*~' and `.*~' to this list. */
632 struct ignore_pattern
634 const char *pattern;
635 struct ignore_pattern *next;
638 static struct ignore_pattern *ignore_patterns;
640 /* Similar to IGNORE_PATTERNS, except that -a or -A causes this
641 variable itself to be ignored. */
642 static struct ignore_pattern *hide_patterns;
644 /* True means output nongraphic chars in file names as `?'.
645 (-q, --hide-control-chars)
646 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
647 independent. The algorithm is: first, obey the quoting style to get a
648 string representing the file name; then, if qmark_funny_chars is set,
649 replace all nonprintable chars in that string with `?'. It's necessary
650 to replace nonprintable chars even in quoted strings, because we don't
651 want to mess up the terminal if control chars get sent to it, and some
652 quoting methods pass through control chars as-is. */
653 static bool qmark_funny_chars;
655 /* Quoting options for file and dir name output. */
657 static struct quoting_options *filename_quoting_options;
658 static struct quoting_options *dirname_quoting_options;
660 /* The number of chars per hardware tab stop. Setting this to zero
661 inhibits the use of TAB characters for separating columns. -T */
662 static size_t tabsize;
664 /* True means print each directory name before listing it. */
666 static bool print_dir_name;
668 /* The line length to use for breaking lines in many-per-line format.
669 Can be set with -w. */
671 static size_t line_length;
673 /* If true, the file listing format requires that stat be called on
674 each file. */
676 static bool format_needs_stat;
678 /* Similar to `format_needs_stat', but set if only the file type is
679 needed. */
681 static bool format_needs_type;
683 /* An arbitrary limit on the number of bytes in a printed time stamp.
684 This is set to a relatively small value to avoid the need to worry
685 about denial-of-service attacks on servers that run "ls" on behalf
686 of remote clients. 1000 bytes should be enough for any practical
687 time stamp format. */
689 enum { TIME_STAMP_LEN_MAXIMUM = MAX (1000, INT_STRLEN_BOUND (time_t)) };
691 /* strftime formats for non-recent and recent files, respectively, in
692 -l output. */
694 static char const *long_time_format[2] =
696 /* strftime format for non-recent files (older than 6 months), in
697 -l output. This should contain the year, month and day (at
698 least), in an order that is understood by people in your
699 locale's territory. Please try to keep the number of used
700 screen columns small, because many people work in windows with
701 only 80 columns. But make this as wide as the other string
702 below, for recent files. */
703 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
704 so be wary of using variable width fields from the locale.
705 Note %b is handled specially by ls and aligned correctly.
706 Note also that specifying a width as in %5b is erroneous as strftime
707 will count bytes rather than characters in multibyte locales. */
708 N_("%b %e %Y"),
709 /* strftime format for recent files (younger than 6 months), in -l
710 output. This should contain the month, day and time (at
711 least), in an order that is understood by people in your
712 locale's territory. Please try to keep the number of used
713 screen columns small, because many people work in windows with
714 only 80 columns. But make this as wide as the other string
715 above, for non-recent files. */
716 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
717 so be wary of using variable width fields from the locale.
718 Note %b is handled specially by ls and aligned correctly.
719 Note also that specifying a width as in %5b is erroneous as strftime
720 will count bytes rather than characters in multibyte locales. */
721 N_("%b %e %H:%M")
724 /* The set of signals that are caught. */
726 static sigset_t caught_signals;
728 /* If nonzero, the value of the pending fatal signal. */
730 static sig_atomic_t volatile interrupt_signal;
732 /* A count of the number of pending stop signals that have been received. */
734 static sig_atomic_t volatile stop_signal_count;
736 /* Desired exit status. */
738 static int exit_status;
740 /* Exit statuses. */
741 enum
743 /* "ls" had a minor problem. E.g., while processing a directory,
744 ls obtained the name of an entry via readdir, yet was later
745 unable to stat that name. This happens when listing a directory
746 in which entries are actively being removed or renamed. */
747 LS_MINOR_PROBLEM = 1,
749 /* "ls" had more serious trouble (e.g., memory exhausted, invalid
750 option or failure to stat a command line argument. */
751 LS_FAILURE = 2
754 /* For long options that have no equivalent short option, use a
755 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
756 enum
758 AUTHOR_OPTION = CHAR_MAX + 1,
759 BLOCK_SIZE_OPTION,
760 COLOR_OPTION,
761 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION,
762 FILE_TYPE_INDICATOR_OPTION,
763 FORMAT_OPTION,
764 FULL_TIME_OPTION,
765 GROUP_DIRECTORIES_FIRST_OPTION,
766 HIDE_OPTION,
767 INDICATOR_STYLE_OPTION,
768 QUOTING_STYLE_OPTION,
769 SHOW_CONTROL_CHARS_OPTION,
770 SI_OPTION,
771 SORT_OPTION,
772 TIME_OPTION,
773 TIME_STYLE_OPTION
776 static struct option const long_options[] =
778 {"all", no_argument, NULL, 'a'},
779 {"escape", no_argument, NULL, 'b'},
780 {"directory", no_argument, NULL, 'd'},
781 {"dired", no_argument, NULL, 'D'},
782 {"full-time", no_argument, NULL, FULL_TIME_OPTION},
783 {"group-directories-first", no_argument, NULL,
784 GROUP_DIRECTORIES_FIRST_OPTION},
785 {"human-readable", no_argument, NULL, 'h'},
786 {"inode", no_argument, NULL, 'i'},
787 {"numeric-uid-gid", no_argument, NULL, 'n'},
788 {"no-group", no_argument, NULL, 'G'},
789 {"hide-control-chars", no_argument, NULL, 'q'},
790 {"reverse", no_argument, NULL, 'r'},
791 {"size", no_argument, NULL, 's'},
792 {"width", required_argument, NULL, 'w'},
793 {"almost-all", no_argument, NULL, 'A'},
794 {"ignore-backups", no_argument, NULL, 'B'},
795 {"classify", no_argument, NULL, 'F'},
796 {"file-type", no_argument, NULL, FILE_TYPE_INDICATOR_OPTION},
797 {"si", no_argument, NULL, SI_OPTION},
798 {"dereference-command-line", no_argument, NULL, 'H'},
799 {"dereference-command-line-symlink-to-dir", no_argument, NULL,
800 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION},
801 {"hide", required_argument, NULL, HIDE_OPTION},
802 {"ignore", required_argument, NULL, 'I'},
803 {"indicator-style", required_argument, NULL, INDICATOR_STYLE_OPTION},
804 {"dereference", no_argument, NULL, 'L'},
805 {"literal", no_argument, NULL, 'N'},
806 {"quote-name", no_argument, NULL, 'Q'},
807 {"quoting-style", required_argument, NULL, QUOTING_STYLE_OPTION},
808 {"recursive", no_argument, NULL, 'R'},
809 {"format", required_argument, NULL, FORMAT_OPTION},
810 {"show-control-chars", no_argument, NULL, SHOW_CONTROL_CHARS_OPTION},
811 {"sort", required_argument, NULL, SORT_OPTION},
812 {"tabsize", required_argument, NULL, 'T'},
813 {"time", required_argument, NULL, TIME_OPTION},
814 {"time-style", required_argument, NULL, TIME_STYLE_OPTION},
815 {"color", optional_argument, NULL, COLOR_OPTION},
816 {"block-size", required_argument, NULL, BLOCK_SIZE_OPTION},
817 {"context", no_argument, 0, 'Z'},
818 {"author", no_argument, NULL, AUTHOR_OPTION},
819 {GETOPT_HELP_OPTION_DECL},
820 {GETOPT_VERSION_OPTION_DECL},
821 {NULL, 0, NULL, 0}
824 static char const *const format_args[] =
826 "verbose", "long", "commas", "horizontal", "across",
827 "vertical", "single-column", NULL
829 static enum format const format_types[] =
831 long_format, long_format, with_commas, horizontal, horizontal,
832 many_per_line, one_per_line
834 ARGMATCH_VERIFY (format_args, format_types);
836 static char const *const sort_args[] =
838 "none", "time", "size", "extension", "version", NULL
840 static enum sort_type const sort_types[] =
842 sort_none, sort_time, sort_size, sort_extension, sort_version
844 ARGMATCH_VERIFY (sort_args, sort_types);
846 static char const *const time_args[] =
848 "atime", "access", "use", "ctime", "status", NULL
850 static enum time_type const time_types[] =
852 time_atime, time_atime, time_atime, time_ctime, time_ctime
854 ARGMATCH_VERIFY (time_args, time_types);
856 static char const *const color_args[] =
858 /* force and none are for compatibility with another color-ls version */
859 "always", "yes", "force",
860 "never", "no", "none",
861 "auto", "tty", "if-tty", NULL
863 static enum color_type const color_types[] =
865 color_always, color_always, color_always,
866 color_never, color_never, color_never,
867 color_if_tty, color_if_tty, color_if_tty
869 ARGMATCH_VERIFY (color_args, color_types);
871 /* Information about filling a column. */
872 struct column_info
874 bool valid_len;
875 size_t line_len;
876 size_t *col_arr;
879 /* Array with information about column filledness. */
880 static struct column_info *column_info;
882 /* Maximum number of columns ever possible for this display. */
883 static size_t max_idx;
885 /* The minimum width of a column is 3: 1 character for the name and 2
886 for the separating white space. */
887 #define MIN_COLUMN_WIDTH 3
890 /* This zero-based index is used solely with the --dired option.
891 When that option is in effect, this counter is incremented for each
892 byte of output generated by this program so that the beginning
893 and ending indices (in that output) of every file name can be recorded
894 and later output themselves. */
895 static size_t dired_pos;
897 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
899 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
900 #define DIRED_FPUTS(s, stream, s_len) \
901 do {fputs (s, stream); dired_pos += s_len;} while (0)
903 /* Like DIRED_FPUTS, but for use when S is a literal string. */
904 #define DIRED_FPUTS_LITERAL(s, stream) \
905 do {fputs (s, stream); dired_pos += sizeof (s) - 1;} while (0)
907 #define DIRED_INDENT() \
908 do \
910 if (dired) \
911 DIRED_FPUTS_LITERAL (" ", stdout); \
913 while (0)
915 /* With --dired, store pairs of beginning and ending indices of filenames. */
916 static struct obstack dired_obstack;
918 /* With --dired, store pairs of beginning and ending indices of any
919 directory names that appear as headers (just before `total' line)
920 for lists of directory entries. Such directory names are seen when
921 listing hierarchies using -R and when a directory is listed with at
922 least one other command line argument. */
923 static struct obstack subdired_obstack;
925 /* Save the current index on the specified obstack, OBS. */
926 #define PUSH_CURRENT_DIRED_POS(obs) \
927 do \
929 if (dired) \
930 obstack_grow (obs, &dired_pos, sizeof (dired_pos)); \
932 while (0)
934 /* With -R, this stack is used to help detect directory cycles.
935 The device/inode pairs on this stack mirror the pairs in the
936 active_dir_set hash table. */
937 static struct obstack dev_ino_obstack;
939 /* Push a pair onto the device/inode stack. */
940 #define DEV_INO_PUSH(Dev, Ino) \
941 do \
943 struct dev_ino *di; \
944 obstack_blank (&dev_ino_obstack, sizeof (struct dev_ino)); \
945 di = -1 + (struct dev_ino *) obstack_next_free (&dev_ino_obstack); \
946 di->st_dev = (Dev); \
947 di->st_ino = (Ino); \
949 while (0)
951 /* Pop a dev/ino struct off the global dev_ino_obstack
952 and return that struct. */
953 static struct dev_ino
954 dev_ino_pop (void)
956 assert (sizeof (struct dev_ino) <= obstack_object_size (&dev_ino_obstack));
957 obstack_blank (&dev_ino_obstack, -(int) (sizeof (struct dev_ino)));
958 return *(struct dev_ino *) obstack_next_free (&dev_ino_obstack);
961 /* Note the use commented out below:
962 #define ASSERT_MATCHING_DEV_INO(Name, Di) \
963 do \
965 struct stat sb; \
966 assert (Name); \
967 assert (0 <= stat (Name, &sb)); \
968 assert (sb.st_dev == Di.st_dev); \
969 assert (sb.st_ino == Di.st_ino); \
971 while (0)
974 /* Write to standard output PREFIX, followed by the quoting style and
975 a space-separated list of the integers stored in OS all on one line. */
977 static void
978 dired_dump_obstack (const char *prefix, struct obstack *os)
980 size_t n_pos;
982 n_pos = obstack_object_size (os) / sizeof (dired_pos);
983 if (n_pos > 0)
985 size_t i;
986 size_t *pos;
988 pos = (size_t *) obstack_finish (os);
989 fputs (prefix, stdout);
990 for (i = 0; i < n_pos; i++)
991 printf (" %lu", (unsigned long int) pos[i]);
992 putchar ('\n');
996 /* Read the abbreviated month names from the locale, to align them
997 and to determine the max width of the field and to truncate names
998 greater than our max allowed.
999 Note even though this handles multibyte locales correctly
1000 it's not restricted to them as single byte locales can have
1001 variable width abbreviated months and also precomputing/caching
1002 the names was seen to increase the performance of ls significantly. */
1004 /* max number of display cells to use */
1005 enum { MAX_MON_WIDTH = 5 };
1006 /* In the unlikely event that the abmon[] storage is not big enough
1007 an error message will be displayed, and we revert to using
1008 unmodified abbreviated month names from the locale database. */
1009 static char abmon[12][MAX_MON_WIDTH * 2 * MB_LEN_MAX + 1];
1010 /* minimum width needed to align %b, 0 => don't use precomputed values. */
1011 static size_t required_mon_width;
1013 static size_t
1014 abmon_init (void)
1016 #ifdef HAVE_NL_LANGINFO
1017 required_mon_width = MAX_MON_WIDTH;
1018 size_t curr_max_width;
1021 curr_max_width = required_mon_width;
1022 required_mon_width = 0;
1023 for (int i = 0; i < 12; i++)
1025 size_t width = curr_max_width;
1027 size_t req = mbsalign (nl_langinfo (ABMON_1 + i),
1028 abmon[i], sizeof (abmon[i]),
1029 &width, MBS_ALIGN_LEFT, 0);
1031 if (req == (size_t) -1 || req >= sizeof (abmon[i]))
1033 required_mon_width = 0; /* ignore precomputed strings. */
1034 return required_mon_width;
1037 required_mon_width = MAX (required_mon_width, width);
1040 while (curr_max_width > required_mon_width);
1041 #endif
1043 return required_mon_width;
1046 static size_t
1047 dev_ino_hash (void const *x, size_t table_size)
1049 struct dev_ino const *p = x;
1050 return (uintmax_t) p->st_ino % table_size;
1053 static bool
1054 dev_ino_compare (void const *x, void const *y)
1056 struct dev_ino const *a = x;
1057 struct dev_ino const *b = y;
1058 return SAME_INODE (*a, *b) ? true : false;
1061 static void
1062 dev_ino_free (void *x)
1064 free (x);
1067 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
1068 active directories. Return true if there is already a matching
1069 entry in the table. */
1071 static bool
1072 visit_dir (dev_t dev, ino_t ino)
1074 struct dev_ino *ent;
1075 struct dev_ino *ent_from_table;
1076 bool found_match;
1078 ent = xmalloc (sizeof *ent);
1079 ent->st_ino = ino;
1080 ent->st_dev = dev;
1082 /* Attempt to insert this entry into the table. */
1083 ent_from_table = hash_insert (active_dir_set, ent);
1085 if (ent_from_table == NULL)
1087 /* Insertion failed due to lack of memory. */
1088 xalloc_die ();
1091 found_match = (ent_from_table != ent);
1093 if (found_match)
1095 /* ent was not inserted, so free it. */
1096 free (ent);
1099 return found_match;
1102 static void
1103 free_pending_ent (struct pending *p)
1105 free (p->name);
1106 free (p->realname);
1107 free (p);
1110 static bool
1111 is_colored (enum indicator_no type)
1113 size_t len = color_indicator[type].len;
1114 char const *s = color_indicator[type].string;
1115 return ! (len == 0
1116 || (len == 1 && strncmp (s, "0", 1) == 0)
1117 || (len == 2 && strncmp (s, "00", 2) == 0));
1120 static void
1121 restore_default_color (void)
1123 put_indicator (&color_indicator[C_LEFT]);
1124 put_indicator (&color_indicator[C_RIGHT]);
1127 /* An ordinary signal was received; arrange for the program to exit. */
1129 static void
1130 sighandler (int sig)
1132 if (! SA_NOCLDSTOP)
1133 signal (sig, SIG_IGN);
1134 if (! interrupt_signal)
1135 interrupt_signal = sig;
1138 /* A SIGTSTP was received; arrange for the program to suspend itself. */
1140 static void
1141 stophandler (int sig)
1143 if (! SA_NOCLDSTOP)
1144 signal (sig, stophandler);
1145 if (! interrupt_signal)
1146 stop_signal_count++;
1149 /* Process any pending signals. If signals are caught, this function
1150 should be called periodically. Ideally there should never be an
1151 unbounded amount of time when signals are not being processed.
1152 Signal handling can restore the default colors, so callers must
1153 immediately change colors after invoking this function. */
1155 static void
1156 process_signals (void)
1158 while (interrupt_signal | stop_signal_count)
1160 int sig;
1161 int stops;
1162 sigset_t oldset;
1164 if (used_color)
1165 restore_default_color ();
1166 fflush (stdout);
1168 sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
1170 /* Reload interrupt_signal and stop_signal_count, in case a new
1171 signal was handled before sigprocmask took effect. */
1172 sig = interrupt_signal;
1173 stops = stop_signal_count;
1175 /* SIGTSTP is special, since the application can receive that signal
1176 more than once. In this case, don't set the signal handler to the
1177 default. Instead, just raise the uncatchable SIGSTOP. */
1178 if (stops)
1180 stop_signal_count = stops - 1;
1181 sig = SIGSTOP;
1183 else
1184 signal (sig, SIG_DFL);
1186 /* Exit or suspend the program. */
1187 raise (sig);
1188 sigprocmask (SIG_SETMASK, &oldset, NULL);
1190 /* If execution reaches here, then the program has been
1191 continued (after being suspended). */
1196 main (int argc, char **argv)
1198 int i;
1199 struct pending *thispend;
1200 int n_files;
1202 /* The signals that are trapped, and the number of such signals. */
1203 static int const sig[] =
1205 /* This one is handled specially. */
1206 SIGTSTP,
1208 /* The usual suspects. */
1209 SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM,
1210 #ifdef SIGPOLL
1211 SIGPOLL,
1212 #endif
1213 #ifdef SIGPROF
1214 SIGPROF,
1215 #endif
1216 #ifdef SIGVTALRM
1217 SIGVTALRM,
1218 #endif
1219 #ifdef SIGXCPU
1220 SIGXCPU,
1221 #endif
1222 #ifdef SIGXFSZ
1223 SIGXFSZ,
1224 #endif
1226 enum { nsigs = ARRAY_CARDINALITY (sig) };
1228 #if ! SA_NOCLDSTOP
1229 bool caught_sig[nsigs];
1230 #endif
1232 initialize_main (&argc, &argv);
1233 set_program_name (argv[0]);
1234 setlocale (LC_ALL, "");
1235 bindtextdomain (PACKAGE, LOCALEDIR);
1236 textdomain (PACKAGE);
1238 initialize_exit_failure (LS_FAILURE);
1239 atexit (close_stdout);
1241 assert (ARRAY_CARDINALITY (color_indicator) + 1
1242 == ARRAY_CARDINALITY (indicator_name));
1244 exit_status = EXIT_SUCCESS;
1245 print_dir_name = true;
1246 pending_dirs = NULL;
1248 current_time.tv_sec = TYPE_MINIMUM (time_t);
1249 current_time.tv_nsec = -1;
1251 i = decode_switches (argc, argv);
1253 if (print_with_color)
1254 parse_ls_color ();
1256 /* Test print_with_color again, because the call to parse_ls_color
1257 may have just reset it -- e.g., if LS_COLORS is invalid. */
1258 if (print_with_color)
1260 /* Avoid following symbolic links when possible. */
1261 if (is_colored (C_ORPHAN)
1262 || (is_colored (C_EXEC) && color_symlink_as_referent)
1263 || (is_colored (C_MISSING) && format == long_format))
1264 check_symlink_color = true;
1266 /* If the standard output is a controlling terminal, watch out
1267 for signals, so that the colors can be restored to the
1268 default state if "ls" is suspended or interrupted. */
1270 if (0 <= tcgetpgrp (STDOUT_FILENO))
1272 int j;
1273 #if SA_NOCLDSTOP
1274 struct sigaction act;
1276 sigemptyset (&caught_signals);
1277 for (j = 0; j < nsigs; j++)
1279 sigaction (sig[j], NULL, &act);
1280 if (act.sa_handler != SIG_IGN)
1281 sigaddset (&caught_signals, sig[j]);
1284 act.sa_mask = caught_signals;
1285 act.sa_flags = SA_RESTART;
1287 for (j = 0; j < nsigs; j++)
1288 if (sigismember (&caught_signals, sig[j]))
1290 act.sa_handler = sig[j] == SIGTSTP ? stophandler : sighandler;
1291 sigaction (sig[j], &act, NULL);
1293 #else
1294 for (j = 0; j < nsigs; j++)
1296 caught_sig[j] = (signal (sig[j], SIG_IGN) != SIG_IGN);
1297 if (caught_sig[j])
1299 signal (sig[j], sig[j] == SIGTSTP ? stophandler : sighandler);
1300 siginterrupt (sig[j], 0);
1303 #endif
1307 if (dereference == DEREF_UNDEFINED)
1308 dereference = ((immediate_dirs
1309 || indicator_style == classify
1310 || format == long_format)
1311 ? DEREF_NEVER
1312 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
1314 /* When using -R, initialize a data structure we'll use to
1315 detect any directory cycles. */
1316 if (recursive)
1318 active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, NULL,
1319 dev_ino_hash,
1320 dev_ino_compare,
1321 dev_ino_free);
1322 if (active_dir_set == NULL)
1323 xalloc_die ();
1325 obstack_init (&dev_ino_obstack);
1328 format_needs_stat = sort_type == sort_time || sort_type == sort_size
1329 || format == long_format
1330 || print_scontext
1331 || print_block_size;
1332 format_needs_type = (! format_needs_stat
1333 && (recursive
1334 || print_with_color
1335 || indicator_style != none
1336 || directories_first));
1338 if (dired)
1340 obstack_init (&dired_obstack);
1341 obstack_init (&subdired_obstack);
1344 cwd_n_alloc = 100;
1345 cwd_file = xnmalloc (cwd_n_alloc, sizeof *cwd_file);
1346 cwd_n_used = 0;
1348 clear_files ();
1350 n_files = argc - i;
1352 if (n_files <= 0)
1354 if (immediate_dirs)
1355 gobble_file (".", directory, NOT_AN_INODE_NUMBER, true, "");
1356 else
1357 queue_directory (".", NULL, true);
1359 else
1361 gobble_file (argv[i++], unknown, NOT_AN_INODE_NUMBER, true, "");
1362 while (i < argc);
1364 if (cwd_n_used)
1366 sort_files ();
1367 if (!immediate_dirs)
1368 extract_dirs_from_files (NULL, true);
1369 /* `cwd_n_used' might be zero now. */
1372 /* In the following if/else blocks, it is sufficient to test `pending_dirs'
1373 (and not pending_dirs->name) because there may be no markers in the queue
1374 at this point. A marker may be enqueued when extract_dirs_from_files is
1375 called with a non-empty string or via print_dir. */
1376 if (cwd_n_used)
1378 print_current_files ();
1379 if (pending_dirs)
1380 DIRED_PUTCHAR ('\n');
1382 else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1383 print_dir_name = false;
1385 while (pending_dirs)
1387 thispend = pending_dirs;
1388 pending_dirs = pending_dirs->next;
1390 if (LOOP_DETECT)
1392 if (thispend->name == NULL)
1394 /* thispend->name == NULL means this is a marker entry
1395 indicating we've finished processing the directory.
1396 Use its dev/ino numbers to remove the corresponding
1397 entry from the active_dir_set hash table. */
1398 struct dev_ino di = dev_ino_pop ();
1399 struct dev_ino *found = hash_delete (active_dir_set, &di);
1400 /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
1401 assert (found);
1402 dev_ino_free (found);
1403 free_pending_ent (thispend);
1404 continue;
1408 print_dir (thispend->name, thispend->realname,
1409 thispend->command_line_arg);
1411 free_pending_ent (thispend);
1412 print_dir_name = true;
1415 if (print_with_color)
1417 int j;
1419 if (used_color)
1420 restore_default_color ();
1421 fflush (stdout);
1423 /* Restore the default signal handling. */
1424 #if SA_NOCLDSTOP
1425 for (j = 0; j < nsigs; j++)
1426 if (sigismember (&caught_signals, sig[j]))
1427 signal (sig[j], SIG_DFL);
1428 #else
1429 for (j = 0; j < nsigs; j++)
1430 if (caught_sig[j])
1431 signal (sig[j], SIG_DFL);
1432 #endif
1434 /* Act on any signals that arrived before the default was restored.
1435 This can process signals out of order, but there doesn't seem to
1436 be an easy way to do them in order, and the order isn't that
1437 important anyway. */
1438 for (j = stop_signal_count; j; j--)
1439 raise (SIGSTOP);
1440 j = interrupt_signal;
1441 if (j)
1442 raise (j);
1445 if (dired)
1447 /* No need to free these since we're about to exit. */
1448 dired_dump_obstack ("//DIRED//", &dired_obstack);
1449 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1450 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1451 quoting_style_args[get_quoting_style (filename_quoting_options)]);
1454 if (LOOP_DETECT)
1456 assert (hash_get_n_entries (active_dir_set) == 0);
1457 hash_free (active_dir_set);
1460 exit (exit_status);
1463 /* Set all the option flags according to the switches specified.
1464 Return the index of the first non-option argument. */
1466 static int
1467 decode_switches (int argc, char **argv)
1469 char *time_style_option = NULL;
1471 /* Record whether there is an option specifying sort type. */
1472 bool sort_type_specified = false;
1474 qmark_funny_chars = false;
1476 /* initialize all switches to default settings */
1478 switch (ls_mode)
1480 case LS_MULTI_COL:
1481 /* This is for the `dir' program. */
1482 format = many_per_line;
1483 set_quoting_style (NULL, escape_quoting_style);
1484 break;
1486 case LS_LONG_FORMAT:
1487 /* This is for the `vdir' program. */
1488 format = long_format;
1489 set_quoting_style (NULL, escape_quoting_style);
1490 break;
1492 case LS_LS:
1493 /* This is for the `ls' program. */
1494 if (isatty (STDOUT_FILENO))
1496 format = many_per_line;
1497 /* See description of qmark_funny_chars, above. */
1498 qmark_funny_chars = true;
1500 else
1502 format = one_per_line;
1503 qmark_funny_chars = false;
1505 break;
1507 default:
1508 abort ();
1511 time_type = time_mtime;
1512 sort_type = sort_name;
1513 sort_reverse = false;
1514 numeric_ids = false;
1515 print_block_size = false;
1516 indicator_style = none;
1517 print_inode = false;
1518 dereference = DEREF_UNDEFINED;
1519 recursive = false;
1520 immediate_dirs = false;
1521 ignore_mode = IGNORE_DEFAULT;
1522 ignore_patterns = NULL;
1523 hide_patterns = NULL;
1524 print_scontext = false;
1526 /* FIXME: put this in a function. */
1528 char const *q_style = getenv ("QUOTING_STYLE");
1529 if (q_style)
1531 int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
1532 if (0 <= i)
1533 set_quoting_style (NULL, quoting_style_vals[i]);
1534 else
1535 error (0, 0,
1536 _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
1537 quotearg (q_style));
1542 char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
1543 human_options (ls_block_size,
1544 &human_output_opts, &output_block_size);
1545 if (ls_block_size || getenv ("BLOCK_SIZE"))
1546 file_output_block_size = output_block_size;
1549 line_length = 80;
1551 char const *p = getenv ("COLUMNS");
1552 if (p && *p)
1554 unsigned long int tmp_ulong;
1555 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1556 && 0 < tmp_ulong && tmp_ulong <= SIZE_MAX)
1558 line_length = tmp_ulong;
1560 else
1562 error (0, 0,
1563 _("ignoring invalid width in environment variable COLUMNS: %s"),
1564 quotearg (p));
1569 #ifdef TIOCGWINSZ
1571 struct winsize ws;
1573 if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1
1574 && 0 < ws.ws_col && ws.ws_col == (size_t) ws.ws_col)
1575 line_length = ws.ws_col;
1577 #endif
1580 char const *p = getenv ("TABSIZE");
1581 tabsize = 8;
1582 if (p)
1584 unsigned long int tmp_ulong;
1585 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1586 && tmp_ulong <= SIZE_MAX)
1588 tabsize = tmp_ulong;
1590 else
1592 error (0, 0,
1593 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1594 quotearg (p));
1599 for (;;)
1601 int oi = -1;
1602 int c = getopt_long (argc, argv,
1603 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1",
1604 long_options, &oi);
1605 if (c == -1)
1606 break;
1608 switch (c)
1610 case 'a':
1611 ignore_mode = IGNORE_MINIMAL;
1612 break;
1614 case 'b':
1615 set_quoting_style (NULL, escape_quoting_style);
1616 break;
1618 case 'c':
1619 time_type = time_ctime;
1620 break;
1622 case 'd':
1623 immediate_dirs = true;
1624 break;
1626 case 'f':
1627 /* Same as enabling -a -U and disabling -l -s. */
1628 ignore_mode = IGNORE_MINIMAL;
1629 sort_type = sort_none;
1630 sort_type_specified = true;
1631 /* disable -l */
1632 if (format == long_format)
1633 format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
1634 print_block_size = false; /* disable -s */
1635 print_with_color = false; /* disable --color */
1636 break;
1638 case FILE_TYPE_INDICATOR_OPTION: /* --file-type */
1639 indicator_style = file_type;
1640 break;
1642 case 'g':
1643 format = long_format;
1644 print_owner = false;
1645 break;
1647 case 'h':
1648 human_output_opts = human_autoscale | human_SI | human_base_1024;
1649 file_output_block_size = output_block_size = 1;
1650 break;
1652 case 'i':
1653 print_inode = true;
1654 break;
1656 case 'k':
1657 human_output_opts = 0;
1658 file_output_block_size = output_block_size = 1024;
1659 break;
1661 case 'l':
1662 format = long_format;
1663 break;
1665 case 'm':
1666 format = with_commas;
1667 break;
1669 case 'n':
1670 numeric_ids = true;
1671 format = long_format;
1672 break;
1674 case 'o': /* Just like -l, but don't display group info. */
1675 format = long_format;
1676 print_group = false;
1677 break;
1679 case 'p':
1680 indicator_style = slash;
1681 break;
1683 case 'q':
1684 qmark_funny_chars = true;
1685 break;
1687 case 'r':
1688 sort_reverse = true;
1689 break;
1691 case 's':
1692 print_block_size = true;
1693 break;
1695 case 't':
1696 sort_type = sort_time;
1697 sort_type_specified = true;
1698 break;
1700 case 'u':
1701 time_type = time_atime;
1702 break;
1704 case 'v':
1705 sort_type = sort_version;
1706 sort_type_specified = true;
1707 break;
1709 case 'w':
1711 unsigned long int tmp_ulong;
1712 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1713 || ! (0 < tmp_ulong && tmp_ulong <= SIZE_MAX))
1714 error (LS_FAILURE, 0, _("invalid line width: %s"),
1715 quotearg (optarg));
1716 line_length = tmp_ulong;
1717 break;
1720 case 'x':
1721 format = horizontal;
1722 break;
1724 case 'A':
1725 if (ignore_mode == IGNORE_DEFAULT)
1726 ignore_mode = IGNORE_DOT_AND_DOTDOT;
1727 break;
1729 case 'B':
1730 add_ignore_pattern ("*~");
1731 add_ignore_pattern (".*~");
1732 break;
1734 case 'C':
1735 format = many_per_line;
1736 break;
1738 case 'D':
1739 dired = true;
1740 break;
1742 case 'F':
1743 indicator_style = classify;
1744 break;
1746 case 'G': /* inhibit display of group info */
1747 print_group = false;
1748 break;
1750 case 'H':
1751 dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1752 break;
1754 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
1755 dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
1756 break;
1758 case 'I':
1759 add_ignore_pattern (optarg);
1760 break;
1762 case 'L':
1763 dereference = DEREF_ALWAYS;
1764 break;
1766 case 'N':
1767 set_quoting_style (NULL, literal_quoting_style);
1768 break;
1770 case 'Q':
1771 set_quoting_style (NULL, c_quoting_style);
1772 break;
1774 case 'R':
1775 recursive = true;
1776 break;
1778 case 'S':
1779 sort_type = sort_size;
1780 sort_type_specified = true;
1781 break;
1783 case 'T':
1785 unsigned long int tmp_ulong;
1786 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1787 || SIZE_MAX < tmp_ulong)
1788 error (LS_FAILURE, 0, _("invalid tab size: %s"),
1789 quotearg (optarg));
1790 tabsize = tmp_ulong;
1791 break;
1794 case 'U':
1795 sort_type = sort_none;
1796 sort_type_specified = true;
1797 break;
1799 case 'X':
1800 sort_type = sort_extension;
1801 sort_type_specified = true;
1802 break;
1804 case '1':
1805 /* -1 has no effect after -l. */
1806 if (format != long_format)
1807 format = one_per_line;
1808 break;
1810 case AUTHOR_OPTION:
1811 print_author = true;
1812 break;
1814 case HIDE_OPTION:
1816 struct ignore_pattern *hide = xmalloc (sizeof *hide);
1817 hide->pattern = optarg;
1818 hide->next = hide_patterns;
1819 hide_patterns = hide;
1821 break;
1823 case SORT_OPTION:
1824 sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1825 sort_type_specified = true;
1826 break;
1828 case GROUP_DIRECTORIES_FIRST_OPTION:
1829 directories_first = true;
1830 break;
1832 case TIME_OPTION:
1833 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1834 break;
1836 case FORMAT_OPTION:
1837 format = XARGMATCH ("--format", optarg, format_args, format_types);
1838 break;
1840 case FULL_TIME_OPTION:
1841 format = long_format;
1842 time_style_option = bad_cast ("full-iso");
1843 break;
1845 case COLOR_OPTION:
1847 int i;
1848 if (optarg)
1849 i = XARGMATCH ("--color", optarg, color_args, color_types);
1850 else
1851 /* Using --color with no argument is equivalent to using
1852 --color=always. */
1853 i = color_always;
1855 print_with_color = (i == color_always
1856 || (i == color_if_tty
1857 && isatty (STDOUT_FILENO)));
1859 if (print_with_color)
1861 /* Don't use TAB characters in output. Some terminal
1862 emulators can't handle the combination of tabs and
1863 color codes on the same line. */
1864 tabsize = 0;
1866 break;
1869 case INDICATOR_STYLE_OPTION:
1870 indicator_style = XARGMATCH ("--indicator-style", optarg,
1871 indicator_style_args,
1872 indicator_style_types);
1873 break;
1875 case QUOTING_STYLE_OPTION:
1876 set_quoting_style (NULL,
1877 XARGMATCH ("--quoting-style", optarg,
1878 quoting_style_args,
1879 quoting_style_vals));
1880 break;
1882 case TIME_STYLE_OPTION:
1883 time_style_option = optarg;
1884 break;
1886 case SHOW_CONTROL_CHARS_OPTION:
1887 qmark_funny_chars = false;
1888 break;
1890 case BLOCK_SIZE_OPTION:
1892 enum strtol_error e = human_options (optarg, &human_output_opts,
1893 &output_block_size);
1894 if (e != LONGINT_OK)
1895 xstrtol_fatal (e, oi, 0, long_options, optarg);
1896 file_output_block_size = output_block_size;
1898 break;
1900 case SI_OPTION:
1901 human_output_opts = human_autoscale | human_SI;
1902 file_output_block_size = output_block_size = 1;
1903 break;
1905 case 'Z':
1906 print_scontext = true;
1907 break;
1909 case_GETOPT_HELP_CHAR;
1911 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1913 default:
1914 usage (LS_FAILURE);
1918 max_idx = MAX (1, line_length / MIN_COLUMN_WIDTH);
1920 filename_quoting_options = clone_quoting_options (NULL);
1921 if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1922 set_char_quoting (filename_quoting_options, ' ', 1);
1923 if (file_type <= indicator_style)
1925 char const *p;
1926 for (p = "*=>@|" + indicator_style - file_type; *p; p++)
1927 set_char_quoting (filename_quoting_options, *p, 1);
1930 dirname_quoting_options = clone_quoting_options (NULL);
1931 set_char_quoting (dirname_quoting_options, ':', 1);
1933 /* --dired is meaningful only with --format=long (-l).
1934 Otherwise, ignore it. FIXME: warn about this?
1935 Alternatively, make --dired imply --format=long? */
1936 if (dired && format != long_format)
1937 dired = false;
1939 /* If -c or -u is specified and not -l (or any other option that implies -l),
1940 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
1941 The behavior of ls when using either -c or -u but with neither -l nor -t
1942 appears to be unspecified by POSIX. So, with GNU ls, `-u' alone means
1943 sort by atime (this is the one that's not specified by the POSIX spec),
1944 -lu means show atime and sort by name, -lut means show atime and sort
1945 by atime. */
1947 if ((time_type == time_ctime || time_type == time_atime)
1948 && !sort_type_specified && format != long_format)
1950 sort_type = sort_time;
1953 if (format == long_format)
1955 char *style = time_style_option;
1956 static char const posix_prefix[] = "posix-";
1958 if (! style)
1959 if (! (style = getenv ("TIME_STYLE")))
1960 style = bad_cast ("locale");
1962 while (strncmp (style, posix_prefix, sizeof posix_prefix - 1) == 0)
1964 if (! hard_locale (LC_TIME))
1965 return optind;
1966 style += sizeof posix_prefix - 1;
1969 if (*style == '+')
1971 char *p0 = style + 1;
1972 char *p1 = strchr (p0, '\n');
1973 if (! p1)
1974 p1 = p0;
1975 else
1977 if (strchr (p1 + 1, '\n'))
1978 error (LS_FAILURE, 0, _("invalid time style format %s"),
1979 quote (p0));
1980 *p1++ = '\0';
1982 long_time_format[0] = p0;
1983 long_time_format[1] = p1;
1985 else
1986 switch (XARGMATCH ("time style", style,
1987 time_style_args,
1988 time_style_types))
1990 case full_iso_time_style:
1991 long_time_format[0] = long_time_format[1] =
1992 "%Y-%m-%d %H:%M:%S.%N %z";
1993 break;
1995 case long_iso_time_style:
1996 case_long_iso_time_style:
1997 long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
1998 break;
2000 case iso_time_style:
2001 long_time_format[0] = "%Y-%m-%d ";
2002 long_time_format[1] = "%m-%d %H:%M";
2003 break;
2005 case locale_time_style:
2006 if (hard_locale (LC_TIME))
2008 /* Ensure that the locale has translations for both
2009 formats. If not, fall back on long-iso format. */
2010 int i;
2011 for (i = 0; i < 2; i++)
2013 char const *locale_format =
2014 dcgettext (NULL, long_time_format[i], LC_TIME);
2015 if (locale_format == long_time_format[i])
2016 goto case_long_iso_time_style;
2017 long_time_format[i] = locale_format;
2021 /* Note we leave %5b etc. alone so user widths/flags are honored. */
2022 if (strstr (long_time_format[0],"%b") || strstr (long_time_format[1],"%b"))
2023 if (!abmon_init ())
2024 error (0, 0, _("error initializing month strings"));
2027 return optind;
2030 /* Parse a string as part of the LS_COLORS variable; this may involve
2031 decoding all kinds of escape characters. If equals_end is set an
2032 unescaped equal sign ends the string, otherwise only a : or \0
2033 does. Set *OUTPUT_COUNT to the number of bytes output. Return
2034 true if successful.
2036 The resulting string is *not* null-terminated, but may contain
2037 embedded nulls.
2039 Note that both dest and src are char **; on return they point to
2040 the first free byte after the array and the character that ended
2041 the input string, respectively. */
2043 static bool
2044 get_funky_string (char **dest, const char **src, bool equals_end,
2045 size_t *output_count)
2047 char num; /* For numerical codes */
2048 size_t count; /* Something to count with */
2049 enum {
2050 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
2051 } state;
2052 const char *p;
2053 char *q;
2055 p = *src; /* We don't want to double-indirect */
2056 q = *dest; /* the whole darn time. */
2058 count = 0; /* No characters counted in yet. */
2059 num = 0;
2061 state = ST_GND; /* Start in ground state. */
2062 while (state < ST_END)
2064 switch (state)
2066 case ST_GND: /* Ground state (no escapes) */
2067 switch (*p)
2069 case ':':
2070 case '\0':
2071 state = ST_END; /* End of string */
2072 break;
2073 case '\\':
2074 state = ST_BACKSLASH; /* Backslash scape sequence */
2075 ++p;
2076 break;
2077 case '^':
2078 state = ST_CARET; /* Caret escape */
2079 ++p;
2080 break;
2081 case '=':
2082 if (equals_end)
2084 state = ST_END; /* End */
2085 break;
2087 /* else fall through */
2088 default:
2089 *(q++) = *(p++);
2090 ++count;
2091 break;
2093 break;
2095 case ST_BACKSLASH: /* Backslash escaped character */
2096 switch (*p)
2098 case '0':
2099 case '1':
2100 case '2':
2101 case '3':
2102 case '4':
2103 case '5':
2104 case '6':
2105 case '7':
2106 state = ST_OCTAL; /* Octal sequence */
2107 num = *p - '0';
2108 break;
2109 case 'x':
2110 case 'X':
2111 state = ST_HEX; /* Hex sequence */
2112 num = 0;
2113 break;
2114 case 'a': /* Bell */
2115 num = '\a';
2116 break;
2117 case 'b': /* Backspace */
2118 num = '\b';
2119 break;
2120 case 'e': /* Escape */
2121 num = 27;
2122 break;
2123 case 'f': /* Form feed */
2124 num = '\f';
2125 break;
2126 case 'n': /* Newline */
2127 num = '\n';
2128 break;
2129 case 'r': /* Carriage return */
2130 num = '\r';
2131 break;
2132 case 't': /* Tab */
2133 num = '\t';
2134 break;
2135 case 'v': /* Vtab */
2136 num = '\v';
2137 break;
2138 case '?': /* Delete */
2139 num = 127;
2140 break;
2141 case '_': /* Space */
2142 num = ' ';
2143 break;
2144 case '\0': /* End of string */
2145 state = ST_ERROR; /* Error! */
2146 break;
2147 default: /* Escaped character like \ ^ : = */
2148 num = *p;
2149 break;
2151 if (state == ST_BACKSLASH)
2153 *(q++) = num;
2154 ++count;
2155 state = ST_GND;
2157 ++p;
2158 break;
2160 case ST_OCTAL: /* Octal sequence */
2161 if (*p < '0' || *p > '7')
2163 *(q++) = num;
2164 ++count;
2165 state = ST_GND;
2167 else
2168 num = (num << 3) + (*(p++) - '0');
2169 break;
2171 case ST_HEX: /* Hex sequence */
2172 switch (*p)
2174 case '0':
2175 case '1':
2176 case '2':
2177 case '3':
2178 case '4':
2179 case '5':
2180 case '6':
2181 case '7':
2182 case '8':
2183 case '9':
2184 num = (num << 4) + (*(p++) - '0');
2185 break;
2186 case 'a':
2187 case 'b':
2188 case 'c':
2189 case 'd':
2190 case 'e':
2191 case 'f':
2192 num = (num << 4) + (*(p++) - 'a') + 10;
2193 break;
2194 case 'A':
2195 case 'B':
2196 case 'C':
2197 case 'D':
2198 case 'E':
2199 case 'F':
2200 num = (num << 4) + (*(p++) - 'A') + 10;
2201 break;
2202 default:
2203 *(q++) = num;
2204 ++count;
2205 state = ST_GND;
2206 break;
2208 break;
2210 case ST_CARET: /* Caret escape */
2211 state = ST_GND; /* Should be the next state... */
2212 if (*p >= '@' && *p <= '~')
2214 *(q++) = *(p++) & 037;
2215 ++count;
2217 else if (*p == '?')
2219 *(q++) = 127;
2220 ++count;
2222 else
2223 state = ST_ERROR;
2224 break;
2226 default:
2227 abort ();
2231 *dest = q;
2232 *src = p;
2233 *output_count = count;
2235 return state != ST_ERROR;
2238 static void
2239 parse_ls_color (void)
2241 const char *p; /* Pointer to character being parsed */
2242 char *buf; /* color_buf buffer pointer */
2243 int state; /* State of parser */
2244 int ind_no; /* Indicator number */
2245 char label[3]; /* Indicator label */
2246 struct color_ext_type *ext; /* Extension we are working on */
2248 if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
2249 return;
2251 ext = NULL;
2252 strcpy (label, "??");
2254 /* This is an overly conservative estimate, but any possible
2255 LS_COLORS string will *not* generate a color_buf longer than
2256 itself, so it is a safe way of allocating a buffer in
2257 advance. */
2258 buf = color_buf = xstrdup (p);
2260 state = 1;
2261 while (state > 0)
2263 switch (state)
2265 case 1: /* First label character */
2266 switch (*p)
2268 case ':':
2269 ++p;
2270 break;
2272 case '*':
2273 /* Allocate new extension block and add to head of
2274 linked list (this way a later definition will
2275 override an earlier one, which can be useful for
2276 having terminal-specific defs override global). */
2278 ext = xmalloc (sizeof *ext);
2279 ext->next = color_ext_list;
2280 color_ext_list = ext;
2282 ++p;
2283 ext->ext.string = buf;
2285 state = (get_funky_string (&buf, &p, true, &ext->ext.len)
2286 ? 4 : -1);
2287 break;
2289 case '\0':
2290 state = 0; /* Done! */
2291 break;
2293 default: /* Assume it is file type label */
2294 label[0] = *(p++);
2295 state = 2;
2296 break;
2298 break;
2300 case 2: /* Second label character */
2301 if (*p)
2303 label[1] = *(p++);
2304 state = 3;
2306 else
2307 state = -1; /* Error */
2308 break;
2310 case 3: /* Equal sign after indicator label */
2311 state = -1; /* Assume failure... */
2312 if (*(p++) == '=')/* It *should* be... */
2314 for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
2316 if (STREQ (label, indicator_name[ind_no]))
2318 color_indicator[ind_no].string = buf;
2319 state = (get_funky_string (&buf, &p, false,
2320 &color_indicator[ind_no].len)
2321 ? 1 : -1);
2322 break;
2325 if (state == -1)
2326 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
2328 break;
2330 case 4: /* Equal sign after *.ext */
2331 if (*(p++) == '=')
2333 ext->seq.string = buf;
2334 state = (get_funky_string (&buf, &p, false, &ext->seq.len)
2335 ? 1 : -1);
2337 else
2338 state = -1;
2339 break;
2343 if (state < 0)
2345 struct color_ext_type *e;
2346 struct color_ext_type *e2;
2348 error (0, 0,
2349 _("unparsable value for LS_COLORS environment variable"));
2350 free (color_buf);
2351 for (e = color_ext_list; e != NULL; /* empty */)
2353 e2 = e;
2354 e = e->next;
2355 free (e2);
2357 print_with_color = false;
2360 if (color_indicator[C_LINK].len == 6
2361 && !strncmp (color_indicator[C_LINK].string, "target", 6))
2362 color_symlink_as_referent = true;
2365 /* Set the exit status to report a failure. If SERIOUS, it is a
2366 serious failure; otherwise, it is merely a minor problem. */
2368 static void
2369 set_exit_status (bool serious)
2371 if (serious)
2372 exit_status = LS_FAILURE;
2373 else if (exit_status == EXIT_SUCCESS)
2374 exit_status = LS_MINOR_PROBLEM;
2377 /* Assuming a failure is serious if SERIOUS, use the printf-style
2378 MESSAGE to report the failure to access a file named FILE. Assume
2379 errno is set appropriately for the failure. */
2381 static void
2382 file_failure (bool serious, char const *message, char const *file)
2384 error (0, errno, message, quotearg_colon (file));
2385 set_exit_status (serious);
2388 /* Request that the directory named NAME have its contents listed later.
2389 If REALNAME is nonzero, it will be used instead of NAME when the
2390 directory name is printed. This allows symbolic links to directories
2391 to be treated as regular directories but still be listed under their
2392 real names. NAME == NULL is used to insert a marker entry for the
2393 directory named in REALNAME.
2394 If NAME is non-NULL, we use its dev/ino information to save
2395 a call to stat -- when doing a recursive (-R) traversal.
2396 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2398 static void
2399 queue_directory (char const *name, char const *realname, bool command_line_arg)
2401 struct pending *new = xmalloc (sizeof *new);
2402 new->realname = realname ? xstrdup (realname) : NULL;
2403 new->name = name ? xstrdup (name) : NULL;
2404 new->command_line_arg = command_line_arg;
2405 new->next = pending_dirs;
2406 pending_dirs = new;
2409 /* Read directory NAME, and list the files in it.
2410 If REALNAME is nonzero, print its name instead of NAME;
2411 this is used for symbolic links to directories.
2412 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2414 static void
2415 print_dir (char const *name, char const *realname, bool command_line_arg)
2417 DIR *dirp;
2418 struct dirent *next;
2419 uintmax_t total_blocks = 0;
2420 static bool first = true;
2422 errno = 0;
2423 dirp = opendir (name);
2424 if (!dirp)
2426 file_failure (command_line_arg, _("cannot open directory %s"), name);
2427 return;
2430 if (LOOP_DETECT)
2432 struct stat dir_stat;
2433 int fd = dirfd (dirp);
2435 /* If dirfd failed, endure the overhead of using stat. */
2436 if ((0 <= fd
2437 ? fstat (fd, &dir_stat)
2438 : stat (name, &dir_stat)) < 0)
2440 file_failure (command_line_arg,
2441 _("cannot determine device and inode of %s"), name);
2442 closedir (dirp);
2443 return;
2446 /* If we've already visited this dev/inode pair, warn that
2447 we've found a loop, and do not process this directory. */
2448 if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
2450 error (0, 0, _("%s: not listing already-listed directory"),
2451 quotearg_colon (name));
2452 closedir (dirp);
2453 return;
2456 DEV_INO_PUSH (dir_stat.st_dev, dir_stat.st_ino);
2459 /* Read the directory entries, and insert the subfiles into the `cwd_file'
2460 table. */
2462 clear_files ();
2464 while (1)
2466 /* Set errno to zero so we can distinguish between a readdir failure
2467 and when readdir simply finds that there are no more entries. */
2468 errno = 0;
2469 next = readdir (dirp);
2470 if (next)
2472 if (! file_ignored (next->d_name))
2474 enum filetype type = unknown;
2476 #if HAVE_STRUCT_DIRENT_D_TYPE
2477 switch (next->d_type)
2479 case DT_BLK: type = blockdev; break;
2480 case DT_CHR: type = chardev; break;
2481 case DT_DIR: type = directory; break;
2482 case DT_FIFO: type = fifo; break;
2483 case DT_LNK: type = symbolic_link; break;
2484 case DT_REG: type = normal; break;
2485 case DT_SOCK: type = sock; break;
2486 # ifdef DT_WHT
2487 case DT_WHT: type = whiteout; break;
2488 # endif
2490 #endif
2491 total_blocks += gobble_file (next->d_name, type, D_INO (next),
2492 false, name);
2494 /* In this narrow case, print out each name right away, so
2495 ls uses constant memory while processing the entries of
2496 this directory. Useful when there are many (millions)
2497 of entries in a directory. */
2498 if (format == one_per_line && sort_type == sort_none)
2500 /* We must call sort_files in spite of
2501 "sort_type == sort_none" for its initialization
2502 of the sorted_file vector. */
2503 sort_files ();
2504 print_current_files ();
2505 clear_files ();
2509 else if (errno != 0)
2511 file_failure (command_line_arg, _("reading directory %s"), name);
2512 if (errno != EOVERFLOW)
2513 break;
2515 else
2516 break;
2519 if (closedir (dirp) != 0)
2521 file_failure (command_line_arg, _("closing directory %s"), name);
2522 /* Don't return; print whatever we got. */
2525 /* Sort the directory contents. */
2526 sort_files ();
2528 /* If any member files are subdirectories, perhaps they should have their
2529 contents listed rather than being mentioned here as files. */
2531 if (recursive)
2532 extract_dirs_from_files (name, command_line_arg);
2534 if (recursive | print_dir_name)
2536 if (!first)
2537 DIRED_PUTCHAR ('\n');
2538 first = false;
2539 DIRED_INDENT ();
2540 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2541 dired_pos += quote_name (stdout, realname ? realname : name,
2542 dirname_quoting_options, NULL);
2543 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2544 DIRED_FPUTS_LITERAL (":\n", stdout);
2547 if (format == long_format || print_block_size)
2549 const char *p;
2550 char buf[LONGEST_HUMAN_READABLE + 1];
2552 DIRED_INDENT ();
2553 p = _("total");
2554 DIRED_FPUTS (p, stdout, strlen (p));
2555 DIRED_PUTCHAR (' ');
2556 p = human_readable (total_blocks, buf, human_output_opts,
2557 ST_NBLOCKSIZE, output_block_size);
2558 DIRED_FPUTS (p, stdout, strlen (p));
2559 DIRED_PUTCHAR ('\n');
2562 if (cwd_n_used)
2563 print_current_files ();
2566 /* Add `pattern' to the list of patterns for which files that match are
2567 not listed. */
2569 static void
2570 add_ignore_pattern (const char *pattern)
2572 struct ignore_pattern *ignore;
2574 ignore = xmalloc (sizeof *ignore);
2575 ignore->pattern = pattern;
2576 /* Add it to the head of the linked list. */
2577 ignore->next = ignore_patterns;
2578 ignore_patterns = ignore;
2581 /* Return true if one of the PATTERNS matches FILE. */
2583 static bool
2584 patterns_match (struct ignore_pattern const *patterns, char const *file)
2586 struct ignore_pattern const *p;
2587 for (p = patterns; p; p = p->next)
2588 if (fnmatch (p->pattern, file, FNM_PERIOD) == 0)
2589 return true;
2590 return false;
2593 /* Return true if FILE should be ignored. */
2595 static bool
2596 file_ignored (char const *name)
2598 return ((ignore_mode != IGNORE_MINIMAL
2599 && name[0] == '.'
2600 && (ignore_mode == IGNORE_DEFAULT || ! name[1 + (name[1] == '.')]))
2601 || (ignore_mode == IGNORE_DEFAULT
2602 && patterns_match (hide_patterns, name))
2603 || patterns_match (ignore_patterns, name));
2606 /* POSIX requires that a file size be printed without a sign, even
2607 when negative. Assume the typical case where negative sizes are
2608 actually positive values that have wrapped around. */
2610 static uintmax_t
2611 unsigned_file_size (off_t size)
2613 return size + (size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
2616 /* Enter and remove entries in the table `cwd_file'. */
2618 /* Empty the table of files. */
2620 static void
2621 clear_files (void)
2623 size_t i;
2625 for (i = 0; i < cwd_n_used; i++)
2627 struct fileinfo *f = sorted_file[i];
2628 free (f->name);
2629 free (f->linkname);
2630 if (f->scontext != UNKNOWN_SECURITY_CONTEXT)
2631 freecon (f->scontext);
2634 cwd_n_used = 0;
2635 any_has_acl = false;
2636 inode_number_width = 0;
2637 block_size_width = 0;
2638 nlink_width = 0;
2639 owner_width = 0;
2640 group_width = 0;
2641 author_width = 0;
2642 scontext_width = 0;
2643 major_device_number_width = 0;
2644 minor_device_number_width = 0;
2645 file_size_width = 0;
2648 /* Add a file to the current table of files.
2649 Verify that the file exists, and print an error message if it does not.
2650 Return the number of blocks that the file occupies. */
2652 static uintmax_t
2653 gobble_file (char const *name, enum filetype type, ino_t inode,
2654 bool command_line_arg, char const *dirname)
2656 uintmax_t blocks = 0;
2657 struct fileinfo *f;
2659 /* An inode value prior to gobble_file necessarily came from readdir,
2660 which is not used for command line arguments. */
2661 assert (! command_line_arg || inode == NOT_AN_INODE_NUMBER);
2663 if (cwd_n_used == cwd_n_alloc)
2665 cwd_file = xnrealloc (cwd_file, cwd_n_alloc, 2 * sizeof *cwd_file);
2666 cwd_n_alloc *= 2;
2669 f = &cwd_file[cwd_n_used];
2670 memset (f, '\0', sizeof *f);
2671 f->stat.st_ino = inode;
2672 f->filetype = type;
2674 if (command_line_arg
2675 || format_needs_stat
2676 /* When coloring a directory (we may know the type from
2677 direct.d_type), we have to stat it in order to indicate
2678 sticky and/or other-writable attributes. */
2679 || (type == directory && print_with_color)
2680 /* When dereferencing symlinks, the inode and type must come from
2681 stat, but readdir provides the inode and type of lstat. */
2682 || ((print_inode || format_needs_type)
2683 && (type == symbolic_link || type == unknown)
2684 && (dereference == DEREF_ALWAYS
2685 || (command_line_arg && dereference != DEREF_NEVER)
2686 || color_symlink_as_referent || check_symlink_color))
2687 /* Command line dereferences are already taken care of by the above
2688 assertion that the inode number is not yet known. */
2689 || (print_inode && inode == NOT_AN_INODE_NUMBER)
2690 || (format_needs_type
2691 && (type == unknown || command_line_arg
2692 /* --indicator-style=classify (aka -F)
2693 requires that we stat each regular file
2694 to see if it's executable. */
2695 || (type == normal && (indicator_style == classify
2696 /* This is so that --color ends up
2697 highlighting files with the executable
2698 bit set even when options like -F are
2699 not specified. */
2700 || (print_with_color
2701 && is_colored (C_EXEC))
2702 )))))
2705 /* Absolute name of this file. */
2706 char *absolute_name;
2707 bool do_deref;
2708 int err;
2710 if (name[0] == '/' || dirname[0] == 0)
2711 absolute_name = (char *) name;
2712 else
2714 absolute_name = alloca (strlen (name) + strlen (dirname) + 2);
2715 attach (absolute_name, dirname, name);
2718 switch (dereference)
2720 case DEREF_ALWAYS:
2721 err = stat (absolute_name, &f->stat);
2722 do_deref = true;
2723 break;
2725 case DEREF_COMMAND_LINE_ARGUMENTS:
2726 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
2727 if (command_line_arg)
2729 bool need_lstat;
2730 err = stat (absolute_name, &f->stat);
2731 do_deref = true;
2733 if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2734 break;
2736 need_lstat = (err < 0
2737 ? errno == ENOENT
2738 : ! S_ISDIR (f->stat.st_mode));
2739 if (!need_lstat)
2740 break;
2742 /* stat failed because of ENOENT, maybe indicating a dangling
2743 symlink. Or stat succeeded, ABSOLUTE_NAME does not refer to a
2744 directory, and --dereference-command-line-symlink-to-dir is
2745 in effect. Fall through so that we call lstat instead. */
2748 default: /* DEREF_NEVER */
2749 err = lstat (absolute_name, &f->stat);
2750 do_deref = false;
2751 break;
2754 if (err != 0)
2756 /* Failure to stat a command line argument leads to
2757 an exit status of 2. For other files, stat failure
2758 provokes an exit status of 1. */
2759 file_failure (command_line_arg,
2760 _("cannot access %s"), absolute_name);
2761 if (command_line_arg)
2762 return 0;
2764 f->name = xstrdup (name);
2765 cwd_n_used++;
2767 return 0;
2770 f->stat_ok = true;
2772 if (format == long_format || print_scontext)
2774 bool have_selinux = false;
2775 bool have_acl = false;
2776 int attr_len = (do_deref
2777 ? getfilecon (absolute_name, &f->scontext)
2778 : lgetfilecon (absolute_name, &f->scontext));
2779 err = (attr_len < 0);
2781 /* Contrary to its documented API, getfilecon may return 0,
2782 yet set f->scontext to NULL (on at least Debian's libselinux1
2783 2.0.15-2+b1), so work around that bug.
2784 FIXME: remove this work-around in 2011, or whenever affected
2785 versions of libselinux are long gone. */
2786 if (attr_len == 0)
2788 err = 0;
2789 f->scontext = xstrdup ("unlabeled");
2792 if (err == 0)
2793 have_selinux = ! STREQ ("unlabeled", f->scontext);
2794 else
2796 f->scontext = UNKNOWN_SECURITY_CONTEXT;
2798 /* When requesting security context information, don't make
2799 ls fail just because the file (even a command line argument)
2800 isn't on the right type of file system. I.e., a getfilecon
2801 failure isn't in the same class as a stat failure. */
2802 if (errno == ENOTSUP || errno == EOPNOTSUPP || errno == ENODATA)
2803 err = 0;
2806 if (err == 0 && format == long_format)
2808 int n = file_has_acl (absolute_name, &f->stat);
2809 err = (n < 0);
2810 have_acl = (0 < n);
2813 f->acl_type = (!have_selinux && !have_acl
2814 ? ACL_T_NONE
2815 : (have_selinux && !have_acl
2816 ? ACL_T_SELINUX_ONLY
2817 : ACL_T_YES));
2818 any_has_acl |= f->acl_type != ACL_T_NONE;
2820 if (err)
2821 error (0, errno, "%s", quotearg_colon (absolute_name));
2824 if (S_ISLNK (f->stat.st_mode)
2825 && (format == long_format || check_symlink_color))
2827 char *linkname;
2828 struct stat linkstats;
2830 get_link_name (absolute_name, f, command_line_arg);
2831 linkname = make_link_name (absolute_name, f->linkname);
2833 /* Avoid following symbolic links when possible, ie, when
2834 they won't be traced and when no indicator is needed. */
2835 if (linkname
2836 && (file_type <= indicator_style || check_symlink_color)
2837 && stat (linkname, &linkstats) == 0)
2839 f->linkok = true;
2841 /* Symbolic links to directories that are mentioned on the
2842 command line are automatically traced if not being
2843 listed as files. */
2844 if (!command_line_arg || format == long_format
2845 || !S_ISDIR (linkstats.st_mode))
2847 /* Get the linked-to file's mode for the filetype indicator
2848 in long listings. */
2849 f->linkmode = linkstats.st_mode;
2852 free (linkname);
2855 /* When not distinguishing types of symlinks, pretend we know that
2856 it is stat'able, so that it will be colored as a regular symlink,
2857 and not as an orphan. */
2858 if (S_ISLNK (f->stat.st_mode) && !check_symlink_color)
2859 f->linkok = true;
2861 if (S_ISLNK (f->stat.st_mode))
2862 f->filetype = symbolic_link;
2863 else if (S_ISDIR (f->stat.st_mode))
2865 if (command_line_arg & !immediate_dirs)
2866 f->filetype = arg_directory;
2867 else
2868 f->filetype = directory;
2870 else
2871 f->filetype = normal;
2873 blocks = ST_NBLOCKS (f->stat);
2874 if (format == long_format || print_block_size)
2876 char buf[LONGEST_HUMAN_READABLE + 1];
2877 int len = mbswidth (human_readable (blocks, buf, human_output_opts,
2878 ST_NBLOCKSIZE, output_block_size),
2880 if (block_size_width < len)
2881 block_size_width = len;
2884 if (format == long_format)
2886 if (print_owner)
2888 int len = format_user_width (f->stat.st_uid);
2889 if (owner_width < len)
2890 owner_width = len;
2893 if (print_group)
2895 int len = format_group_width (f->stat.st_gid);
2896 if (group_width < len)
2897 group_width = len;
2900 if (print_author)
2902 int len = format_user_width (f->stat.st_author);
2903 if (author_width < len)
2904 author_width = len;
2908 if (print_scontext)
2910 int len = strlen (f->scontext);
2911 if (scontext_width < len)
2912 scontext_width = len;
2915 if (format == long_format)
2917 char b[INT_BUFSIZE_BOUND (uintmax_t)];
2918 int b_len = strlen (umaxtostr (f->stat.st_nlink, b));
2919 if (nlink_width < b_len)
2920 nlink_width = b_len;
2922 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
2924 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2925 int len = strlen (umaxtostr (major (f->stat.st_rdev), buf));
2926 if (major_device_number_width < len)
2927 major_device_number_width = len;
2928 len = strlen (umaxtostr (minor (f->stat.st_rdev), buf));
2929 if (minor_device_number_width < len)
2930 minor_device_number_width = len;
2931 len = major_device_number_width + 2 + minor_device_number_width;
2932 if (file_size_width < len)
2933 file_size_width = len;
2935 else
2937 char buf[LONGEST_HUMAN_READABLE + 1];
2938 uintmax_t size = unsigned_file_size (f->stat.st_size);
2939 int len = mbswidth (human_readable (size, buf, human_output_opts,
2940 1, file_output_block_size),
2942 if (file_size_width < len)
2943 file_size_width = len;
2948 if (print_inode)
2950 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2951 int len = strlen (umaxtostr (f->stat.st_ino, buf));
2952 if (inode_number_width < len)
2953 inode_number_width = len;
2956 f->name = xstrdup (name);
2957 cwd_n_used++;
2959 return blocks;
2962 /* Return true if F refers to a directory. */
2963 static bool
2964 is_directory (const struct fileinfo *f)
2966 return f->filetype == directory || f->filetype == arg_directory;
2969 /* Put the name of the file that FILENAME is a symbolic link to
2970 into the LINKNAME field of `f'. COMMAND_LINE_ARG indicates whether
2971 FILENAME is a command-line argument. */
2973 static void
2974 get_link_name (char const *filename, struct fileinfo *f, bool command_line_arg)
2976 f->linkname = areadlink_with_size (filename, f->stat.st_size);
2977 if (f->linkname == NULL)
2978 file_failure (command_line_arg, _("cannot read symbolic link %s"),
2979 filename);
2982 /* If `linkname' is a relative name and `name' contains one or more
2983 leading directories, return `linkname' with those directories
2984 prepended; otherwise, return a copy of `linkname'.
2985 If `linkname' is zero, return zero. */
2987 static char *
2988 make_link_name (char const *name, char const *linkname)
2990 char *linkbuf;
2991 size_t bufsiz;
2993 if (!linkname)
2994 return NULL;
2996 if (*linkname == '/')
2997 return xstrdup (linkname);
2999 /* The link is to a relative name. Prepend any leading directory
3000 in `name' to the link name. */
3001 linkbuf = strrchr (name, '/');
3002 if (linkbuf == 0)
3003 return xstrdup (linkname);
3005 bufsiz = linkbuf - name + 1;
3006 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
3007 strncpy (linkbuf, name, bufsiz);
3008 strcpy (linkbuf + bufsiz, linkname);
3009 return linkbuf;
3012 /* Return true if the last component of NAME is `.' or `..'
3013 This is so we don't try to recurse on `././././. ...' */
3015 static bool
3016 basename_is_dot_or_dotdot (const char *name)
3018 char const *base = last_component (name);
3019 return dot_or_dotdot (base);
3022 /* Remove any entries from CWD_FILE that are for directories,
3023 and queue them to be listed as directories instead.
3024 DIRNAME is the prefix to prepend to each dirname
3025 to make it correct relative to ls's working dir;
3026 if it is null, no prefix is needed and "." and ".." should not be ignored.
3027 If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
3028 This is desirable when processing directories recursively. */
3030 static void
3031 extract_dirs_from_files (char const *dirname, bool command_line_arg)
3033 size_t i;
3034 size_t j;
3035 bool ignore_dot_and_dot_dot = (dirname != NULL);
3037 if (dirname && LOOP_DETECT)
3039 /* Insert a marker entry first. When we dequeue this marker entry,
3040 we'll know that DIRNAME has been processed and may be removed
3041 from the set of active directories. */
3042 queue_directory (NULL, dirname, false);
3045 /* Queue the directories last one first, because queueing reverses the
3046 order. */
3047 for (i = cwd_n_used; i-- != 0; )
3049 struct fileinfo *f = sorted_file[i];
3051 if (is_directory (f)
3052 && (! ignore_dot_and_dot_dot
3053 || ! basename_is_dot_or_dotdot (f->name)))
3055 if (!dirname || f->name[0] == '/')
3056 queue_directory (f->name, f->linkname, command_line_arg);
3057 else
3059 char *name = file_name_concat (dirname, f->name, NULL);
3060 queue_directory (name, f->linkname, command_line_arg);
3061 free (name);
3063 if (f->filetype == arg_directory)
3064 free (f->name);
3068 /* Now delete the directories from the table, compacting all the remaining
3069 entries. */
3071 for (i = 0, j = 0; i < cwd_n_used; i++)
3073 struct fileinfo *f = sorted_file[i];
3074 sorted_file[j] = f;
3075 j += (f->filetype != arg_directory);
3077 cwd_n_used = j;
3080 /* Use strcoll to compare strings in this locale. If an error occurs,
3081 report an error and longjmp to failed_strcoll. */
3083 static jmp_buf failed_strcoll;
3085 static int
3086 xstrcoll (char const *a, char const *b)
3088 int diff;
3089 errno = 0;
3090 diff = strcoll (a, b);
3091 if (errno)
3093 error (0, errno, _("cannot compare file names %s and %s"),
3094 quote_n (0, a), quote_n (1, b));
3095 set_exit_status (false);
3096 longjmp (failed_strcoll, 1);
3098 return diff;
3101 /* Comparison routines for sorting the files. */
3103 typedef void const *V;
3104 typedef int (*qsortFunc)(V a, V b);
3106 /* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants.
3107 The do { ... } while(0) makes it possible to use the macro more like
3108 a statement, without violating C89 rules: */
3109 #define DIRFIRST_CHECK(a, b) \
3110 do \
3112 bool a_is_dir = is_directory ((struct fileinfo const *) a); \
3113 bool b_is_dir = is_directory ((struct fileinfo const *) b); \
3114 if (a_is_dir && !b_is_dir) \
3115 return -1; /* a goes before b */ \
3116 if (!a_is_dir && b_is_dir) \
3117 return 1; /* b goes before a */ \
3119 while (0)
3121 /* Define the 8 different sort function variants required for each sortkey.
3122 KEY_NAME is a token describing the sort key, e.g., ctime, atime, size.
3123 KEY_CMP_FUNC is a function to compare records based on that key, e.g.,
3124 ctime_cmp, atime_cmp, size_cmp. Append KEY_NAME to the string,
3125 '[rev_][x]str{cmp|coll}[_df]_', to create each function name. */
3126 #define DEFINE_SORT_FUNCTIONS(key_name, key_cmp_func) \
3127 /* direct, non-dirfirst versions */ \
3128 static int xstrcoll_##key_name (V a, V b) \
3129 { return key_cmp_func (a, b, xstrcoll); } \
3130 static int strcmp_##key_name (V a, V b) \
3131 { return key_cmp_func (a, b, strcmp); } \
3133 /* reverse, non-dirfirst versions */ \
3134 static int rev_xstrcoll_##key_name (V a, V b) \
3135 { return key_cmp_func (b, a, xstrcoll); } \
3136 static int rev_strcmp_##key_name (V a, V b) \
3137 { return key_cmp_func (b, a, strcmp); } \
3139 /* direct, dirfirst versions */ \
3140 static int xstrcoll_df_##key_name (V a, V b) \
3141 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, xstrcoll); } \
3142 static int strcmp_df_##key_name (V a, V b) \
3143 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, strcmp); } \
3145 /* reverse, dirfirst versions */ \
3146 static int rev_xstrcoll_df_##key_name (V a, V b) \
3147 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, xstrcoll); } \
3148 static int rev_strcmp_df_##key_name (V a, V b) \
3149 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, strcmp); }
3151 static inline int
3152 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
3153 int (*cmp) (char const *, char const *))
3155 int diff = timespec_cmp (get_stat_ctime (&b->stat),
3156 get_stat_ctime (&a->stat));
3157 return diff ? diff : cmp (a->name, b->name);
3160 static inline int
3161 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
3162 int (*cmp) (char const *, char const *))
3164 int diff = timespec_cmp (get_stat_mtime (&b->stat),
3165 get_stat_mtime (&a->stat));
3166 return diff ? diff : cmp (a->name, b->name);
3169 static inline int
3170 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
3171 int (*cmp) (char const *, char const *))
3173 int diff = timespec_cmp (get_stat_atime (&b->stat),
3174 get_stat_atime (&a->stat));
3175 return diff ? diff : cmp (a->name, b->name);
3178 static inline int
3179 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
3180 int (*cmp) (char const *, char const *))
3182 int diff = longdiff (b->stat.st_size, a->stat.st_size);
3183 return diff ? diff : cmp (a->name, b->name);
3186 static inline int
3187 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
3188 int (*cmp) (char const *, char const *))
3190 return cmp (a->name, b->name);
3193 /* Compare file extensions. Files with no extension are `smallest'.
3194 If extensions are the same, compare by filenames instead. */
3196 static inline int
3197 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
3198 int (*cmp) (char const *, char const *))
3200 char const *base1 = strrchr (a->name, '.');
3201 char const *base2 = strrchr (b->name, '.');
3202 int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
3203 return diff ? diff : cmp (a->name, b->name);
3206 DEFINE_SORT_FUNCTIONS (ctime, cmp_ctime)
3207 DEFINE_SORT_FUNCTIONS (mtime, cmp_mtime)
3208 DEFINE_SORT_FUNCTIONS (atime, cmp_atime)
3209 DEFINE_SORT_FUNCTIONS (size, cmp_size)
3210 DEFINE_SORT_FUNCTIONS (name, cmp_name)
3211 DEFINE_SORT_FUNCTIONS (extension, cmp_extension)
3213 /* Compare file versions.
3214 Unlike all other compare functions above, cmp_version depends only
3215 on filevercmp, which does not fail (even for locale reasons), and does not
3216 need a secondary sort key. See lib/filevercmp.h for function description.
3218 All the other sort options, in fact, need xstrcoll and strcmp variants,
3219 because they all use a string comparison (either as the primary or secondary
3220 sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
3221 locale reasons. Last, strverscmp is ALWAYS available in coreutils,
3222 thanks to the gnulib library. */
3223 static inline int
3224 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
3226 return filevercmp (a->name, b->name);
3229 static int xstrcoll_version (V a, V b)
3230 { return cmp_version (a, b); }
3231 static int rev_xstrcoll_version (V a, V b)
3232 { return cmp_version (b, a); }
3233 static int xstrcoll_df_version (V a, V b)
3234 { DIRFIRST_CHECK (a, b); return cmp_version (a, b); }
3235 static int rev_xstrcoll_df_version (V a, V b)
3236 { DIRFIRST_CHECK (a, b); return cmp_version (b, a); }
3239 /* We have 2^3 different variants for each sortkey function
3240 (for 3 independent sort modes).
3241 The function pointers stored in this array must be dereferenced as:
3243 sort_variants[sort_key][use_strcmp][reverse][dirs_first]
3245 Note that the order in which sortkeys are listed in the function pointer
3246 array below is defined by the order of the elements in the time_type and
3247 sort_type enums! */
3249 #define LIST_SORTFUNCTION_VARIANTS(key_name) \
3252 { xstrcoll_##key_name, xstrcoll_df_##key_name }, \
3253 { rev_xstrcoll_##key_name, rev_xstrcoll_df_##key_name }, \
3254 }, \
3256 { strcmp_##key_name, strcmp_df_##key_name }, \
3257 { rev_strcmp_##key_name, rev_strcmp_df_##key_name }, \
3261 static qsortFunc const sort_functions[][2][2][2] =
3263 LIST_SORTFUNCTION_VARIANTS (name),
3264 LIST_SORTFUNCTION_VARIANTS (extension),
3265 LIST_SORTFUNCTION_VARIANTS (size),
3269 { xstrcoll_version, xstrcoll_df_version },
3270 { rev_xstrcoll_version, rev_xstrcoll_df_version },
3273 /* We use NULL for the strcmp variants of version comparison
3274 since as explained in cmp_version definition, version comparison
3275 does not rely on xstrcoll, so it will never longjmp, and never
3276 need to try the strcmp fallback. */
3278 { NULL, NULL },
3279 { NULL, NULL },
3283 /* last are time sort functions */
3284 LIST_SORTFUNCTION_VARIANTS (mtime),
3285 LIST_SORTFUNCTION_VARIANTS (ctime),
3286 LIST_SORTFUNCTION_VARIANTS (atime)
3289 /* The number of sortkeys is calculated as
3290 the number of elements in the sort_type enum (i.e. sort_numtypes) +
3291 the number of elements in the time_type enum (i.e. time_numtypes) - 1
3292 This is because when sort_type==sort_time, we have up to
3293 time_numtypes possible sortkeys.
3295 This line verifies at compile-time that the array of sort functions has been
3296 initialized for all possible sortkeys. */
3297 verify (ARRAY_CARDINALITY (sort_functions)
3298 == sort_numtypes + time_numtypes - 1 );
3300 /* Set up SORTED_FILE to point to the in-use entries in CWD_FILE, in order. */
3302 static void
3303 initialize_ordering_vector (void)
3305 size_t i;
3306 for (i = 0; i < cwd_n_used; i++)
3307 sorted_file[i] = &cwd_file[i];
3310 /* Sort the files now in the table. */
3312 static void
3313 sort_files (void)
3315 bool use_strcmp;
3317 if (sorted_file_alloc < cwd_n_used + cwd_n_used / 2)
3319 free (sorted_file);
3320 sorted_file = xnmalloc (cwd_n_used, 3 * sizeof *sorted_file);
3321 sorted_file_alloc = 3 * cwd_n_used;
3324 initialize_ordering_vector ();
3326 if (sort_type == sort_none)
3327 return;
3329 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
3330 ignore strcoll failures, as a failing strcoll might be a
3331 comparison function that is not a total order, and if we ignored
3332 the failure this might cause qsort to dump core. */
3334 if (! setjmp (failed_strcoll))
3335 use_strcmp = false; /* strcoll() succeeded */
3336 else
3338 use_strcmp = true;
3339 assert (sort_type != sort_version);
3340 initialize_ordering_vector ();
3343 /* When sort_type == sort_time, use time_type as subindex. */
3344 mpsort ((void const **) sorted_file, cwd_n_used,
3345 sort_functions[sort_type + (sort_type == sort_time ? time_type : 0)]
3346 [use_strcmp][sort_reverse]
3347 [directories_first]);
3350 /* List all the files now in the table. */
3352 static void
3353 print_current_files (void)
3355 size_t i;
3357 switch (format)
3359 case one_per_line:
3360 for (i = 0; i < cwd_n_used; i++)
3362 print_file_name_and_frills (sorted_file[i], 0);
3363 putchar ('\n');
3365 break;
3367 case many_per_line:
3368 print_many_per_line ();
3369 break;
3371 case horizontal:
3372 print_horizontal ();
3373 break;
3375 case with_commas:
3376 print_with_commas ();
3377 break;
3379 case long_format:
3380 for (i = 0; i < cwd_n_used; i++)
3382 print_long_format (sorted_file[i]);
3383 DIRED_PUTCHAR ('\n');
3385 break;
3389 /* Replace the first %b with precomputed aligned month names.
3390 Note on glibc-2.7 at least, this speeds up the whole `ls -lU`
3391 process by around 17%, compared to letting strftime() handle the %b. */
3393 static size_t
3394 align_nstrftime (char *buf, size_t size, char const *fmt, struct tm const *tm,
3395 int __utc, int __ns)
3397 const char *nfmt = fmt;
3398 /* In the unlikely event that rpl_fmt below is not large enough,
3399 the replacement is not done. A malloc here slows ls down by 2% */
3400 char rpl_fmt[sizeof (abmon[0]) + 100];
3401 const char *pb;
3402 if (required_mon_width && (pb = strstr (fmt, "%b")))
3404 if (strlen (fmt) < (sizeof (rpl_fmt) - sizeof (abmon[0]) + 2))
3406 char *pfmt = rpl_fmt;
3407 nfmt = rpl_fmt;
3409 pfmt = mempcpy (pfmt, fmt, pb - fmt);
3410 pfmt = stpcpy (pfmt, abmon[tm->tm_mon]);
3411 strcpy (pfmt, pb + 2);
3414 size_t ret = nstrftime (buf, size, nfmt, tm, __utc, __ns);
3415 return ret;
3418 /* Return the expected number of columns in a long-format time stamp,
3419 or zero if it cannot be calculated. */
3421 static int
3422 long_time_expected_width (void)
3424 static int width = -1;
3426 if (width < 0)
3428 time_t epoch = 0;
3429 struct tm const *tm = localtime (&epoch);
3430 char buf[TIME_STAMP_LEN_MAXIMUM + 1];
3432 /* In case you're wondering if localtime can fail with an input time_t
3433 value of 0, let's just say it's very unlikely, but not inconceivable.
3434 The TZ environment variable would have to specify a time zone that
3435 is 2**31-1900 years or more ahead of UTC. This could happen only on
3436 a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
3437 However, this is not possible with Solaris 10 or glibc-2.3.5, since
3438 their implementations limit the offset to 167:59 and 24:00, resp. */
3439 if (tm)
3441 size_t len =
3442 align_nstrftime (buf, sizeof buf, long_time_format[0], tm, 0, 0);
3443 if (len != 0)
3444 width = mbsnwidth (buf, len, 0);
3447 if (width < 0)
3448 width = 0;
3451 return width;
3454 /* Print the user or group name NAME, with numeric id ID, using a
3455 print width of WIDTH columns. */
3457 static void
3458 format_user_or_group (char const *name, unsigned long int id, int width)
3460 size_t len;
3462 if (name)
3464 int width_gap = width - mbswidth (name, 0);
3465 int pad = MAX (0, width_gap);
3466 fputs (name, stdout);
3467 len = strlen (name) + pad;
3470 putchar (' ');
3471 while (pad--);
3473 else
3475 printf ("%*lu ", width, id);
3476 len = width;
3479 dired_pos += len + 1;
3482 /* Print the name or id of the user with id U, using a print width of
3483 WIDTH. */
3485 static void
3486 format_user (uid_t u, int width, bool stat_ok)
3488 format_user_or_group (! stat_ok ? "?" :
3489 (numeric_ids ? NULL : getuser (u)), u, width);
3492 /* Likewise, for groups. */
3494 static void
3495 format_group (gid_t g, int width, bool stat_ok)
3497 format_user_or_group (! stat_ok ? "?" :
3498 (numeric_ids ? NULL : getgroup (g)), g, width);
3501 /* Return the number of columns that format_user_or_group will print. */
3503 static int
3504 format_user_or_group_width (char const *name, unsigned long int id)
3506 if (name)
3508 int len = mbswidth (name, 0);
3509 return MAX (0, len);
3511 else
3513 char buf[INT_BUFSIZE_BOUND (unsigned long int)];
3514 sprintf (buf, "%lu", id);
3515 return strlen (buf);
3519 /* Return the number of columns that format_user will print. */
3521 static int
3522 format_user_width (uid_t u)
3524 return format_user_or_group_width (numeric_ids ? NULL : getuser (u), u);
3527 /* Likewise, for groups. */
3529 static int
3530 format_group_width (gid_t g)
3532 return format_user_or_group_width (numeric_ids ? NULL : getgroup (g), g);
3536 /* Print information about F in long format. */
3538 static void
3539 print_long_format (const struct fileinfo *f)
3541 char modebuf[12];
3542 char buf
3543 [LONGEST_HUMAN_READABLE + 1 /* inode */
3544 + LONGEST_HUMAN_READABLE + 1 /* size in blocks */
3545 + sizeof (modebuf) - 1 + 1 /* mode string */
3546 + INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
3547 + LONGEST_HUMAN_READABLE + 2 /* major device number */
3548 + LONGEST_HUMAN_READABLE + 1 /* minor device number */
3549 + TIME_STAMP_LEN_MAXIMUM + 1 /* max length of time/date */
3551 size_t s;
3552 char *p;
3553 struct timespec when_timespec;
3554 struct tm *when_local;
3556 /* Compute the mode string, except remove the trailing space if no
3557 file in this directory has an ACL or SELinux security context. */
3558 if (f->stat_ok)
3559 filemodestring (&f->stat, modebuf);
3560 else
3562 modebuf[0] = filetype_letter[f->filetype];
3563 memset (modebuf + 1, '?', 10);
3564 modebuf[11] = '\0';
3566 if (! any_has_acl)
3567 modebuf[10] = '\0';
3568 else if (f->acl_type == ACL_T_SELINUX_ONLY)
3569 modebuf[10] = '.';
3570 else if (f->acl_type == ACL_T_YES)
3571 modebuf[10] = '+';
3573 switch (time_type)
3575 case time_ctime:
3576 when_timespec = get_stat_ctime (&f->stat);
3577 break;
3578 case time_mtime:
3579 when_timespec = get_stat_mtime (&f->stat);
3580 break;
3581 case time_atime:
3582 when_timespec = get_stat_atime (&f->stat);
3583 break;
3584 default:
3585 abort ();
3588 p = buf;
3590 if (print_inode)
3592 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3593 sprintf (p, "%*s ", inode_number_width,
3594 (f->stat.st_ino == NOT_AN_INODE_NUMBER
3595 ? "?"
3596 : umaxtostr (f->stat.st_ino, hbuf)));
3597 /* Increment by strlen (p) here, rather than by inode_number_width + 1.
3598 The latter is wrong when inode_number_width is zero. */
3599 p += strlen (p);
3602 if (print_block_size)
3604 char hbuf[LONGEST_HUMAN_READABLE + 1];
3605 char const *blocks =
3606 (! f->stat_ok
3607 ? "?"
3608 : human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts,
3609 ST_NBLOCKSIZE, output_block_size));
3610 int pad;
3611 for (pad = block_size_width - mbswidth (blocks, 0); 0 < pad; pad--)
3612 *p++ = ' ';
3613 while ((*p++ = *blocks++))
3614 continue;
3615 p[-1] = ' ';
3618 /* The last byte of the mode string is the POSIX
3619 "optional alternate access method flag". */
3621 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3622 sprintf (p, "%s %*s ", modebuf, nlink_width,
3623 ! f->stat_ok ? "?" : umaxtostr (f->stat.st_nlink, hbuf));
3625 /* Increment by strlen (p) here, rather than by, e.g.,
3626 sizeof modebuf - 2 + any_has_acl + 1 + nlink_width + 1.
3627 The latter is wrong when nlink_width is zero. */
3628 p += strlen (p);
3630 DIRED_INDENT ();
3632 if (print_owner | print_group | print_author | print_scontext)
3634 DIRED_FPUTS (buf, stdout, p - buf);
3636 if (print_owner)
3637 format_user (f->stat.st_uid, owner_width, f->stat_ok);
3639 if (print_group)
3640 format_group (f->stat.st_gid, group_width, f->stat_ok);
3642 if (print_author)
3643 format_user (f->stat.st_author, author_width, f->stat_ok);
3645 if (print_scontext)
3646 format_user_or_group (f->scontext, 0, scontext_width);
3648 p = buf;
3651 if (f->stat_ok
3652 && (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode)))
3654 char majorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3655 char minorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3656 int blanks_width = (file_size_width
3657 - (major_device_number_width + 2
3658 + minor_device_number_width));
3659 sprintf (p, "%*s, %*s ",
3660 major_device_number_width + MAX (0, blanks_width),
3661 umaxtostr (major (f->stat.st_rdev), majorbuf),
3662 minor_device_number_width,
3663 umaxtostr (minor (f->stat.st_rdev), minorbuf));
3664 p += file_size_width + 1;
3666 else
3668 char hbuf[LONGEST_HUMAN_READABLE + 1];
3669 char const *size =
3670 (! f->stat_ok
3671 ? "?"
3672 : human_readable (unsigned_file_size (f->stat.st_size),
3673 hbuf, human_output_opts, 1, file_output_block_size));
3674 int pad;
3675 for (pad = file_size_width - mbswidth (size, 0); 0 < pad; pad--)
3676 *p++ = ' ';
3677 while ((*p++ = *size++))
3678 continue;
3679 p[-1] = ' ';
3682 when_local = localtime (&when_timespec.tv_sec);
3683 s = 0;
3684 *p = '\1';
3686 if (f->stat_ok && when_local)
3688 struct timespec six_months_ago;
3689 bool recent;
3690 char const *fmt;
3692 /* If the file appears to be in the future, update the current
3693 time, in case the file happens to have been modified since
3694 the last time we checked the clock. */
3695 if (timespec_cmp (current_time, when_timespec) < 0)
3697 /* Note that gettime may call gettimeofday which, on some non-
3698 compliant systems, clobbers the buffer used for localtime's result.
3699 But it's ok here, because we use a gettimeofday wrapper that
3700 saves and restores the buffer around the gettimeofday call. */
3701 gettime (&current_time);
3704 /* Consider a time to be recent if it is within the past six
3705 months. A Gregorian year has 365.2425 * 24 * 60 * 60 ==
3706 31556952 seconds on the average. Write this value as an
3707 integer constant to avoid floating point hassles. */
3708 six_months_ago.tv_sec = current_time.tv_sec - 31556952 / 2;
3709 six_months_ago.tv_nsec = current_time.tv_nsec;
3711 recent = (timespec_cmp (six_months_ago, when_timespec) < 0
3712 && (timespec_cmp (when_timespec, current_time) < 0));
3713 fmt = long_time_format[recent];
3715 /* We assume here that all time zones are offset from UTC by a
3716 whole number of seconds. */
3717 s = align_nstrftime (p, TIME_STAMP_LEN_MAXIMUM + 1, fmt,
3718 when_local, 0, when_timespec.tv_nsec);
3721 if (s || !*p)
3723 p += s;
3724 *p++ = ' ';
3726 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
3727 *p = '\0';
3729 else
3731 /* The time cannot be converted using the desired format, so
3732 print it as a huge integer number of seconds. */
3733 char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
3734 sprintf (p, "%*s ", long_time_expected_width (),
3735 (! f->stat_ok
3736 ? "?"
3737 : timetostr (when_timespec.tv_sec, hbuf)));
3738 /* FIXME: (maybe) We discarded when_timespec.tv_nsec. */
3739 p += strlen (p);
3742 DIRED_FPUTS (buf, stdout, p - buf);
3743 size_t w = print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
3744 f->stat_ok, f->filetype, &dired_obstack,
3745 f->stat.st_nlink, p - buf);
3747 if (f->filetype == symbolic_link)
3749 if (f->linkname)
3751 DIRED_FPUTS_LITERAL (" -> ", stdout);
3752 print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1,
3753 f->stat_ok, f->filetype, NULL,
3754 f->stat.st_nlink, (p - buf) + w + 4);
3755 if (indicator_style != none)
3756 print_type_indicator (true, f->linkmode, unknown);
3759 else if (indicator_style != none)
3760 print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
3763 /* Output to OUT a quoted representation of the file name NAME,
3764 using OPTIONS to control quoting. Produce no output if OUT is NULL.
3765 Store the number of screen columns occupied by NAME's quoted
3766 representation into WIDTH, if non-NULL. Return the number of bytes
3767 produced. */
3769 static size_t
3770 quote_name (FILE *out, const char *name, struct quoting_options const *options,
3771 size_t *width)
3773 char smallbuf[BUFSIZ];
3774 size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, name, -1, options);
3775 char *buf;
3776 size_t displayed_width IF_LINT (= 0);
3778 if (len < sizeof smallbuf)
3779 buf = smallbuf;
3780 else
3782 buf = alloca (len + 1);
3783 quotearg_buffer (buf, len + 1, name, -1, options);
3786 if (qmark_funny_chars)
3788 if (MB_CUR_MAX > 1)
3790 char const *p = buf;
3791 char const *plimit = buf + len;
3792 char *q = buf;
3793 displayed_width = 0;
3795 while (p < plimit)
3796 switch (*p)
3798 case ' ': case '!': case '"': case '#': case '%':
3799 case '&': case '\'': case '(': case ')': case '*':
3800 case '+': case ',': case '-': case '.': case '/':
3801 case '0': case '1': case '2': case '3': case '4':
3802 case '5': case '6': case '7': case '8': case '9':
3803 case ':': case ';': case '<': case '=': case '>':
3804 case '?':
3805 case 'A': case 'B': case 'C': case 'D': case 'E':
3806 case 'F': case 'G': case 'H': case 'I': case 'J':
3807 case 'K': case 'L': case 'M': case 'N': case 'O':
3808 case 'P': case 'Q': case 'R': case 'S': case 'T':
3809 case 'U': case 'V': case 'W': case 'X': case 'Y':
3810 case 'Z':
3811 case '[': case '\\': case ']': case '^': case '_':
3812 case 'a': case 'b': case 'c': case 'd': case 'e':
3813 case 'f': case 'g': case 'h': case 'i': case 'j':
3814 case 'k': case 'l': case 'm': case 'n': case 'o':
3815 case 'p': case 'q': case 'r': case 's': case 't':
3816 case 'u': case 'v': case 'w': case 'x': case 'y':
3817 case 'z': case '{': case '|': case '}': case '~':
3818 /* These characters are printable ASCII characters. */
3819 *q++ = *p++;
3820 displayed_width += 1;
3821 break;
3822 default:
3823 /* If we have a multibyte sequence, copy it until we
3824 reach its end, replacing each non-printable multibyte
3825 character with a single question mark. */
3827 DECLARE_ZEROED_AGGREGATE (mbstate_t, mbstate);
3830 wchar_t wc;
3831 size_t bytes;
3832 int w;
3834 bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
3836 if (bytes == (size_t) -1)
3838 /* An invalid multibyte sequence was
3839 encountered. Skip one input byte, and
3840 put a question mark. */
3841 p++;
3842 *q++ = '?';
3843 displayed_width += 1;
3844 break;
3847 if (bytes == (size_t) -2)
3849 /* An incomplete multibyte character
3850 at the end. Replace it entirely with
3851 a question mark. */
3852 p = plimit;
3853 *q++ = '?';
3854 displayed_width += 1;
3855 break;
3858 if (bytes == 0)
3859 /* A null wide character was encountered. */
3860 bytes = 1;
3862 w = wcwidth (wc);
3863 if (w >= 0)
3865 /* A printable multibyte character.
3866 Keep it. */
3867 for (; bytes > 0; --bytes)
3868 *q++ = *p++;
3869 displayed_width += w;
3871 else
3873 /* An unprintable multibyte character.
3874 Replace it entirely with a question
3875 mark. */
3876 p += bytes;
3877 *q++ = '?';
3878 displayed_width += 1;
3881 while (! mbsinit (&mbstate));
3883 break;
3886 /* The buffer may have shrunk. */
3887 len = q - buf;
3889 else
3891 char *p = buf;
3892 char const *plimit = buf + len;
3894 while (p < plimit)
3896 if (! isprint (to_uchar (*p)))
3897 *p = '?';
3898 p++;
3900 displayed_width = len;
3903 else if (width != NULL)
3905 if (MB_CUR_MAX > 1)
3906 displayed_width = mbsnwidth (buf, len, 0);
3907 else
3909 char const *p = buf;
3910 char const *plimit = buf + len;
3912 displayed_width = 0;
3913 while (p < plimit)
3915 if (isprint (to_uchar (*p)))
3916 displayed_width++;
3917 p++;
3922 if (out != NULL)
3923 fwrite (buf, 1, len, out);
3924 if (width != NULL)
3925 *width = displayed_width;
3926 return len;
3929 static size_t
3930 print_name_with_quoting (const char *p, mode_t mode, int linkok,
3931 bool stat_ok, enum filetype type,
3932 struct obstack *stack, nlink_t nlink,
3933 size_t start_col)
3935 bool used_color_this_time
3936 = (print_with_color
3937 && print_color_indicator (p, mode, linkok, stat_ok, type, nlink));
3939 if (stack)
3940 PUSH_CURRENT_DIRED_POS (stack);
3942 size_t width = quote_name (stdout, p, filename_quoting_options, NULL);
3943 dired_pos += width;
3945 if (stack)
3946 PUSH_CURRENT_DIRED_POS (stack);
3948 if (used_color_this_time)
3950 process_signals ();
3951 prep_non_filename_text ();
3952 if (start_col / line_length != (start_col + width - 1) / line_length)
3953 put_indicator (&color_indicator[C_CLR_TO_EOL]);
3956 return width;
3959 static void
3960 prep_non_filename_text (void)
3962 if (color_indicator[C_END].string != NULL)
3963 put_indicator (&color_indicator[C_END]);
3964 else
3966 put_indicator (&color_indicator[C_LEFT]);
3967 put_indicator (&color_indicator[C_RESET]);
3968 put_indicator (&color_indicator[C_RIGHT]);
3972 /* Print the file name of `f' with appropriate quoting.
3973 Also print file size, inode number, and filetype indicator character,
3974 as requested by switches. */
3976 static size_t
3977 print_file_name_and_frills (const struct fileinfo *f, size_t start_col)
3979 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
3981 if (print_inode)
3982 printf ("%*s ", format == with_commas ? 0 : inode_number_width,
3983 umaxtostr (f->stat.st_ino, buf));
3985 if (print_block_size)
3986 printf ("%*s ", format == with_commas ? 0 : block_size_width,
3987 human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts,
3988 ST_NBLOCKSIZE, output_block_size));
3990 if (print_scontext)
3991 printf ("%*s ", format == with_commas ? 0 : scontext_width, f->scontext);
3993 size_t width = print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f),
3994 f->linkok, f->stat_ok, f->filetype,
3995 NULL, f->stat.st_nlink, start_col);
3997 if (indicator_style != none)
3998 width += print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4000 return width;
4003 /* Given these arguments describing a file, return the single-byte
4004 type indicator, or 0. */
4005 static char
4006 get_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
4008 char c;
4010 if (stat_ok ? S_ISREG (mode) : type == normal)
4012 if (stat_ok && indicator_style == classify && (mode & S_IXUGO))
4013 c = '*';
4014 else
4015 c = 0;
4017 else
4019 if (stat_ok ? S_ISDIR (mode) : type == directory || type == arg_directory)
4020 c = '/';
4021 else if (indicator_style == slash)
4022 c = 0;
4023 else if (stat_ok ? S_ISLNK (mode) : type == symbolic_link)
4024 c = '@';
4025 else if (stat_ok ? S_ISFIFO (mode) : type == fifo)
4026 c = '|';
4027 else if (stat_ok ? S_ISSOCK (mode) : type == sock)
4028 c = '=';
4029 else if (stat_ok && S_ISDOOR (mode))
4030 c = '>';
4031 else
4032 c = 0;
4034 return c;
4037 static bool
4038 print_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
4040 char c = get_type_indicator (stat_ok, mode, type);
4041 if (c)
4042 DIRED_PUTCHAR (c);
4043 return !!c;
4046 #ifdef HAVE_CAP
4047 /* Return true if NAME has a capability (see linux/capability.h) */
4048 static bool
4049 has_capability (char const *name)
4051 char *result;
4052 bool has_cap;
4054 cap_t cap_d = cap_get_file (name);
4055 if (cap_d == NULL)
4056 return false;
4058 result = cap_to_text (cap_d, NULL);
4059 cap_free (cap_d);
4060 if (!result)
4061 return false;
4063 /* check if human-readable capability string is empty */
4064 has_cap = !!*result;
4066 cap_free (result);
4067 return has_cap;
4069 #else
4070 static bool
4071 has_capability (char const *name ATTRIBUTE_UNUSED)
4073 return false;
4075 #endif
4077 /* Returns whether any color sequence was printed. */
4078 static bool
4079 print_color_indicator (const char *name, mode_t mode, int linkok,
4080 bool stat_ok, enum filetype filetype,
4081 nlink_t nlink)
4083 int type;
4084 struct color_ext_type *ext; /* Color extension */
4085 size_t len; /* Length of name */
4087 /* Is this a nonexistent file? If so, linkok == -1. */
4089 if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
4090 type = C_MISSING;
4091 else if (! stat_ok)
4093 static enum indicator_no filetype_indicator[] = FILETYPE_INDICATORS;
4094 type = filetype_indicator[filetype];
4096 else
4098 if (S_ISREG (mode))
4100 type = C_FILE;
4101 if ((mode & S_ISUID) != 0)
4102 type = C_SETUID;
4103 else if ((mode & S_ISGID) != 0)
4104 type = C_SETGID;
4105 else if (is_colored (C_CAP) && has_capability (name))
4106 type = C_CAP;
4107 else if ((mode & S_IXUGO) != 0)
4108 type = C_EXEC;
4109 else if (is_colored (C_MULTIHARDLINK) && (1 < nlink))
4110 type = C_MULTIHARDLINK;
4112 else if (S_ISDIR (mode))
4114 if ((mode & S_ISVTX) && (mode & S_IWOTH))
4115 type = C_STICKY_OTHER_WRITABLE;
4116 else if ((mode & S_IWOTH) != 0)
4117 type = C_OTHER_WRITABLE;
4118 else if ((mode & S_ISVTX) != 0)
4119 type = C_STICKY;
4120 else
4121 type = C_DIR;
4123 else if (S_ISLNK (mode))
4124 type = ((!linkok && color_indicator[C_ORPHAN].string)
4125 ? C_ORPHAN : C_LINK);
4126 else if (S_ISFIFO (mode))
4127 type = C_FIFO;
4128 else if (S_ISSOCK (mode))
4129 type = C_SOCK;
4130 else if (S_ISBLK (mode))
4131 type = C_BLK;
4132 else if (S_ISCHR (mode))
4133 type = C_CHR;
4134 else if (S_ISDOOR (mode))
4135 type = C_DOOR;
4136 else
4138 /* Classify a file of some other type as C_ORPHAN. */
4139 type = C_ORPHAN;
4143 /* Check the file's suffix only if still classified as C_FILE. */
4144 ext = NULL;
4145 if (type == C_FILE)
4147 /* Test if NAME has a recognized suffix. */
4149 len = strlen (name);
4150 name += len; /* Pointer to final \0. */
4151 for (ext = color_ext_list; ext != NULL; ext = ext->next)
4153 if (ext->ext.len <= len
4154 && strncmp (name - ext->ext.len, ext->ext.string,
4155 ext->ext.len) == 0)
4156 break;
4161 const struct bin_str *const s
4162 = ext ? &(ext->seq) : &color_indicator[type];
4163 if (s->string != NULL)
4165 put_indicator (&color_indicator[C_LEFT]);
4166 put_indicator (s);
4167 put_indicator (&color_indicator[C_RIGHT]);
4168 return true;
4170 else
4171 return false;
4175 /* Output a color indicator (which may contain nulls). */
4176 static void
4177 put_indicator (const struct bin_str *ind)
4179 if (! used_color)
4181 used_color = true;
4182 prep_non_filename_text ();
4185 fwrite (ind->string, ind->len, 1, stdout);
4188 static size_t
4189 length_of_file_name_and_frills (const struct fileinfo *f)
4191 size_t len = 0;
4192 size_t name_width;
4193 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
4195 if (print_inode)
4196 len += 1 + (format == with_commas
4197 ? strlen (umaxtostr (f->stat.st_ino, buf))
4198 : inode_number_width);
4200 if (print_block_size)
4201 len += 1 + (format == with_commas
4202 ? strlen (human_readable (ST_NBLOCKS (f->stat), buf,
4203 human_output_opts, ST_NBLOCKSIZE,
4204 output_block_size))
4205 : block_size_width);
4207 if (print_scontext)
4208 len += 1 + (format == with_commas ? strlen (f->scontext) : scontext_width);
4210 quote_name (NULL, f->name, filename_quoting_options, &name_width);
4211 len += name_width;
4213 if (indicator_style != none)
4215 char c = get_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4216 len += (c != 0);
4219 return len;
4222 static void
4223 print_many_per_line (void)
4225 size_t row; /* Current row. */
4226 size_t cols = calculate_columns (true);
4227 struct column_info const *line_fmt = &column_info[cols - 1];
4229 /* Calculate the number of rows that will be in each column except possibly
4230 for a short column on the right. */
4231 size_t rows = cwd_n_used / cols + (cwd_n_used % cols != 0);
4233 for (row = 0; row < rows; row++)
4235 size_t col = 0;
4236 size_t filesno = row;
4237 size_t pos = 0;
4239 /* Print the next row. */
4240 while (1)
4242 struct fileinfo const *f = sorted_file[filesno];
4243 size_t name_length = length_of_file_name_and_frills (f);
4244 size_t max_name_length = line_fmt->col_arr[col++];
4245 print_file_name_and_frills (f, pos);
4247 filesno += rows;
4248 if (filesno >= cwd_n_used)
4249 break;
4251 indent (pos + name_length, pos + max_name_length);
4252 pos += max_name_length;
4254 putchar ('\n');
4258 static void
4259 print_horizontal (void)
4261 size_t filesno;
4262 size_t pos = 0;
4263 size_t cols = calculate_columns (false);
4264 struct column_info const *line_fmt = &column_info[cols - 1];
4265 struct fileinfo const *f = sorted_file[0];
4266 size_t name_length = length_of_file_name_and_frills (f);
4267 size_t max_name_length = line_fmt->col_arr[0];
4269 /* Print first entry. */
4270 print_file_name_and_frills (f, 0);
4272 /* Now the rest. */
4273 for (filesno = 1; filesno < cwd_n_used; ++filesno)
4275 size_t col = filesno % cols;
4277 if (col == 0)
4279 putchar ('\n');
4280 pos = 0;
4282 else
4284 indent (pos + name_length, pos + max_name_length);
4285 pos += max_name_length;
4288 f = sorted_file[filesno];
4289 print_file_name_and_frills (f, pos);
4291 name_length = length_of_file_name_and_frills (f);
4292 max_name_length = line_fmt->col_arr[col];
4294 putchar ('\n');
4297 static void
4298 print_with_commas (void)
4300 size_t filesno;
4301 size_t pos = 0;
4303 for (filesno = 0; filesno < cwd_n_used; filesno++)
4305 struct fileinfo const *f = sorted_file[filesno];
4306 size_t len = length_of_file_name_and_frills (f);
4308 if (filesno != 0)
4310 char separator;
4312 if (pos + len + 2 < line_length)
4314 pos += 2;
4315 separator = ' ';
4317 else
4319 pos = 0;
4320 separator = '\n';
4323 putchar (',');
4324 putchar (separator);
4327 print_file_name_and_frills (f, pos);
4328 pos += len;
4330 putchar ('\n');
4333 /* Assuming cursor is at position FROM, indent up to position TO.
4334 Use a TAB character instead of two or more spaces whenever possible. */
4336 static void
4337 indent (size_t from, size_t to)
4339 while (from < to)
4341 if (tabsize != 0 && to / tabsize > (from + 1) / tabsize)
4343 putchar ('\t');
4344 from += tabsize - from % tabsize;
4346 else
4348 putchar (' ');
4349 from++;
4354 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
4355 /* FIXME: maybe remove this function someday. See about using a
4356 non-malloc'ing version of file_name_concat. */
4358 static void
4359 attach (char *dest, const char *dirname, const char *name)
4361 const char *dirnamep = dirname;
4363 /* Copy dirname if it is not ".". */
4364 if (dirname[0] != '.' || dirname[1] != 0)
4366 while (*dirnamep)
4367 *dest++ = *dirnamep++;
4368 /* Add '/' if `dirname' doesn't already end with it. */
4369 if (dirnamep > dirname && dirnamep[-1] != '/')
4370 *dest++ = '/';
4372 while (*name)
4373 *dest++ = *name++;
4374 *dest = 0;
4377 /* Allocate enough column info suitable for the current number of
4378 files and display columns, and initialize the info to represent the
4379 narrowest possible columns. */
4381 static void
4382 init_column_info (void)
4384 size_t i;
4385 size_t max_cols = MIN (max_idx, cwd_n_used);
4387 /* Currently allocated columns in column_info. */
4388 static size_t column_info_alloc;
4390 if (column_info_alloc < max_cols)
4392 size_t new_column_info_alloc;
4393 size_t *p;
4395 if (max_cols < max_idx / 2)
4397 /* The number of columns is far less than the display width
4398 allows. Grow the allocation, but only so that it's
4399 double the current requirements. If the display is
4400 extremely wide, this avoids allocating a lot of memory
4401 that is never needed. */
4402 column_info = xnrealloc (column_info, max_cols,
4403 2 * sizeof *column_info);
4404 new_column_info_alloc = 2 * max_cols;
4406 else
4408 column_info = xnrealloc (column_info, max_idx, sizeof *column_info);
4409 new_column_info_alloc = max_idx;
4412 /* Allocate the new size_t objects by computing the triangle
4413 formula n * (n + 1) / 2, except that we don't need to
4414 allocate the part of the triangle that we've already
4415 allocated. Check for address arithmetic overflow. */
4417 size_t column_info_growth = new_column_info_alloc - column_info_alloc;
4418 size_t s = column_info_alloc + 1 + new_column_info_alloc;
4419 size_t t = s * column_info_growth;
4420 if (s < new_column_info_alloc || t / column_info_growth != s)
4421 xalloc_die ();
4422 p = xnmalloc (t / 2, sizeof *p);
4425 /* Grow the triangle by parceling out the cells just allocated. */
4426 for (i = column_info_alloc; i < new_column_info_alloc; i++)
4428 column_info[i].col_arr = p;
4429 p += i + 1;
4432 column_info_alloc = new_column_info_alloc;
4435 for (i = 0; i < max_cols; ++i)
4437 size_t j;
4439 column_info[i].valid_len = true;
4440 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
4441 for (j = 0; j <= i; ++j)
4442 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
4446 /* Calculate the number of columns needed to represent the current set
4447 of files in the current display width. */
4449 static size_t
4450 calculate_columns (bool by_columns)
4452 size_t filesno; /* Index into cwd_file. */
4453 size_t cols; /* Number of files across. */
4455 /* Normally the maximum number of columns is determined by the
4456 screen width. But if few files are available this might limit it
4457 as well. */
4458 size_t max_cols = MIN (max_idx, cwd_n_used);
4460 init_column_info ();
4462 /* Compute the maximum number of possible columns. */
4463 for (filesno = 0; filesno < cwd_n_used; ++filesno)
4465 struct fileinfo const *f = sorted_file[filesno];
4466 size_t name_length = length_of_file_name_and_frills (f);
4467 size_t i;
4469 for (i = 0; i < max_cols; ++i)
4471 if (column_info[i].valid_len)
4473 size_t idx = (by_columns
4474 ? filesno / ((cwd_n_used + i) / (i + 1))
4475 : filesno % (i + 1));
4476 size_t real_length = name_length + (idx == i ? 0 : 2);
4478 if (column_info[i].col_arr[idx] < real_length)
4480 column_info[i].line_len += (real_length
4481 - column_info[i].col_arr[idx]);
4482 column_info[i].col_arr[idx] = real_length;
4483 column_info[i].valid_len = (column_info[i].line_len
4484 < line_length);
4490 /* Find maximum allowed columns. */
4491 for (cols = max_cols; 1 < cols; --cols)
4493 if (column_info[cols - 1].valid_len)
4494 break;
4497 return cols;
4500 void
4501 usage (int status)
4503 if (status != EXIT_SUCCESS)
4504 fprintf (stderr, _("Try `%s --help' for more information.\n"),
4505 program_name);
4506 else
4508 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
4509 fputs (_("\
4510 List information about the FILEs (the current directory by default).\n\
4511 Sort entries alphabetically if none of -cftuvSUX nor --sort.\n\
4513 "), stdout);
4514 fputs (_("\
4515 Mandatory arguments to long options are mandatory for short options too.\n\
4516 "), stdout);
4517 fputs (_("\
4518 -a, --all do not ignore entries starting with .\n\
4519 -A, --almost-all do not list implied . and ..\n\
4520 --author with -l, print the author of each file\n\
4521 -b, --escape print octal escapes for nongraphic characters\n\
4522 "), stdout);
4523 fputs (_("\
4524 --block-size=SIZE use SIZE-byte blocks\n\
4525 -B, --ignore-backups do not list implied entries ending with ~\n\
4526 -c with -lt: sort by, and show, ctime (time of last\n\
4527 modification of file status information)\n\
4528 with -l: show ctime and sort by name\n\
4529 otherwise: sort by ctime\n\
4530 "), stdout);
4531 fputs (_("\
4532 -C list entries by columns\n\
4533 --color[=WHEN] control whether color is used to distinguish file\n\
4534 types. WHEN may be `never', `always', or `auto'\n\
4535 -d, --directory list directory entries instead of contents,\n\
4536 and do not dereference symbolic links\n\
4537 -D, --dired generate output designed for Emacs' dired mode\n\
4538 "), stdout);
4539 fputs (_("\
4540 -f do not sort, enable -aU, disable -ls --color\n\
4541 -F, --classify append indicator (one of */=>@|) to entries\n\
4542 --file-type likewise, except do not append `*'\n\
4543 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
4544 single-column -1, verbose -l, vertical -C\n\
4545 --full-time like -l --time-style=full-iso\n\
4546 "), stdout);
4547 fputs (_("\
4548 -g like -l, but do not list owner\n\
4549 "), stdout);
4550 fputs (_("\
4551 --group-directories-first\n\
4552 group directories before files.\n\
4553 augment with a --sort option, but any\n\
4554 use of --sort=none (-U) disables grouping\n\
4555 "), stdout);
4556 fputs (_("\
4557 -G, --no-group in a long listing, don't print group names\n\
4558 -h, --human-readable with -l, print sizes in human readable format\n\
4559 (e.g., 1K 234M 2G)\n\
4560 --si likewise, but use powers of 1000 not 1024\n\
4561 "), stdout);
4562 fputs (_("\
4563 -H, --dereference-command-line\n\
4564 follow symbolic links listed on the command line\n\
4565 --dereference-command-line-symlink-to-dir\n\
4566 follow each command line symbolic link\n\
4567 that points to a directory\n\
4568 --hide=PATTERN do not list implied entries matching shell PATTERN\n\
4569 (overridden by -a or -A)\n\
4570 "), stdout);
4571 fputs (_("\
4572 --indicator-style=WORD append indicator with style WORD to entry names:\n\
4573 none (default), slash (-p),\n\
4574 file-type (--file-type), classify (-F)\n\
4575 -i, --inode print the index number of each file\n\
4576 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
4577 -k like --block-size=1K\n\
4578 "), stdout);
4579 fputs (_("\
4580 -l use a long listing format\n\
4581 -L, --dereference when showing file information for a symbolic\n\
4582 link, show information for the file the link\n\
4583 references rather than for the link itself\n\
4584 -m fill width with a comma separated list of entries\n\
4585 "), stdout);
4586 fputs (_("\
4587 -n, --numeric-uid-gid like -l, but list numeric user and group IDs\n\
4588 -N, --literal print raw entry names (don't treat e.g. control\n\
4589 characters specially)\n\
4590 -o like -l, but do not list group information\n\
4591 -p, --indicator-style=slash\n\
4592 append / indicator to directories\n\
4593 "), stdout);
4594 fputs (_("\
4595 -q, --hide-control-chars print ? instead of non graphic characters\n\
4596 --show-control-chars show non graphic characters as-is (default\n\
4597 unless program is `ls' and output is a terminal)\n\
4598 -Q, --quote-name enclose entry names in double quotes\n\
4599 --quoting-style=WORD use quoting style WORD for entry names:\n\
4600 literal, locale, shell, shell-always, c, escape\n\
4601 "), stdout);
4602 fputs (_("\
4603 -r, --reverse reverse order while sorting\n\
4604 -R, --recursive list subdirectories recursively\n\
4605 -s, --size print the allocated size of each file, in blocks\n\
4606 "), stdout);
4607 fputs (_("\
4608 -S sort by file size\n\
4609 --sort=WORD sort by WORD instead of name: none -U,\n\
4610 extension -X, size -S, time -t, version -v\n\
4611 --time=WORD with -l, show time as WORD instead of modification\n\
4612 time: atime -u, access -u, use -u, ctime -c,\n\
4613 or status -c; use specified time as sort key\n\
4614 if --sort=time\n\
4615 "), stdout);
4616 fputs (_("\
4617 --time-style=STYLE with -l, show times using style STYLE:\n\
4618 full-iso, long-iso, iso, locale, +FORMAT.\n\
4619 FORMAT is interpreted like `date'; if FORMAT is\n\
4620 FORMAT1<newline>FORMAT2, FORMAT1 applies to\n\
4621 non-recent files and FORMAT2 to recent files;\n\
4622 if STYLE is prefixed with `posix-', STYLE\n\
4623 takes effect only outside the POSIX locale\n\
4624 "), stdout);
4625 fputs (_("\
4626 -t sort by modification time\n\
4627 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
4628 "), stdout);
4629 fputs (_("\
4630 -u with -lt: sort by, and show, access time\n\
4631 with -l: show access time and sort by name\n\
4632 otherwise: sort by access time\n\
4633 -U do not sort; list entries in directory order\n\
4634 -v natural sort of (version) numbers within text\n\
4635 "), stdout);
4636 fputs (_("\
4637 -w, --width=COLS assume screen width instead of current value\n\
4638 -x list entries by lines instead of by columns\n\
4639 -X sort alphabetically by entry extension\n\
4640 -Z, --context print any SELinux security context of each file\n\
4641 -1 list one file per line\n\
4642 "), stdout);
4643 fputs (HELP_OPTION_DESCRIPTION, stdout);
4644 fputs (VERSION_OPTION_DESCRIPTION, stdout);
4645 fputs (_("\n\
4646 SIZE may be (or may be an integer optionally followed by) one of following:\n\
4647 kB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
4648 "), stdout);
4649 fputs (_("\
4651 By default, color is not used to distinguish types of files. That is\n\
4652 equivalent to using --color=none. Using the --color option without the\n\
4653 optional WHEN argument is equivalent to using --color=always. With\n\
4654 --color=auto, color codes are output only if standard output is connected\n\
4655 to a terminal (tty). The environment variable LS_COLORS can influence the\n\
4656 colors, and can be set easily by the dircolors command.\n\
4657 "), stdout);
4658 fputs (_("\
4660 Exit status:\n\
4661 0 if OK,\n\
4662 1 if minor problems (e.g., cannot access subdirectory),\n\
4663 2 if serious trouble (e.g., cannot access command-line argument).\n\
4664 "), stdout);
4665 emit_bug_reporting_address ();
4667 exit (status);