ls: reorder includes to work around broken <sys/capability.h>
[coreutils.git] / src / ls.c
blob9ef7eba21bf205aba271c0724efe7aacde700f65
1 /* `dir', `vdir' and `ls' directory listing programs for GNU.
2 Copyright (C) 1985, 1988, 1990-1991, 1995-2010 Free Software Foundation,
3 Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
18 /* If ls_mode is LS_MULTI_COL,
19 the multi-column format is the default regardless
20 of the type of output device.
21 This is for the `dir' program.
23 If ls_mode is LS_LONG_FORMAT,
24 the long format is the default regardless of the
25 type of output device.
26 This is for the `vdir' program.
28 If ls_mode is LS_LS,
29 the output format depends on whether the output
30 device is a terminal.
31 This is for the `ls' program. */
33 /* Written by Richard Stallman and David MacKenzie. */
35 /* Color support by Peter Anvin <Peter.Anvin@linux.org> and Dennis
36 Flaherty <dennisf@denix.elk.miles.com> based on original patches by
37 Greg Lee <lee@uhunix.uhcc.hawaii.edu>. */
39 #include <config.h>
40 #include <sys/types.h>
42 #if HAVE_TERMIOS_H
43 # include <termios.h>
44 #endif
45 #if HAVE_STROPTS_H
46 # include <stropts.h>
47 #endif
48 #if HAVE_SYS_IOCTL_H
49 # include <sys/ioctl.h>
50 #endif
52 #ifdef WINSIZE_IN_PTEM
53 # include <sys/stream.h>
54 # include <sys/ptem.h>
55 #endif
57 #include <stdio.h>
58 #include <assert.h>
59 #include <setjmp.h>
60 #include <grp.h>
61 #include <pwd.h>
62 #include <getopt.h>
63 #include <signal.h>
64 #include <selinux/selinux.h>
65 #include <wchar.h>
67 #if HAVE_LANGINFO_CODESET
68 # include <langinfo.h>
69 #endif
71 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
72 present. */
73 #ifndef SA_NOCLDSTOP
74 # define SA_NOCLDSTOP 0
75 # define sigprocmask(How, Set, Oset) /* empty */
76 # define sigset_t int
77 # if ! HAVE_SIGINTERRUPT
78 # define siginterrupt(sig, flag) /* empty */
79 # endif
80 #endif
81 #ifndef SA_RESTART
82 # define SA_RESTART 0
83 #endif
85 #include "system.h"
86 #include <fnmatch.h>
88 #include "acl.h"
89 #include "argmatch.h"
90 #include "dev-ino.h"
91 #include "error.h"
92 #include "filenamecat.h"
93 #include "hard-locale.h"
94 #include "hash.h"
95 #include "human.h"
96 #include "filemode.h"
97 #include "filevercmp.h"
98 #include "idcache.h"
99 #include "ls.h"
100 #include "mbswidth.h"
101 #include "mpsort.h"
102 #include "obstack.h"
103 #include "quote.h"
104 #include "quotearg.h"
105 #include "same.h"
106 #include "stat-time.h"
107 #include "strftime.h"
108 #include "xstrtol.h"
109 #include "areadlink.h"
110 #include "mbsalign.h"
112 /* Include <sys/capability.h> last to avoid a clash of <sys/types.h>
113 include guards with some premature versions of libcap.
114 For more details, see <http://bugzilla.redhat.com/483548>. */
115 #ifdef HAVE_CAP
116 # include <sys/capability.h>
117 #endif
119 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
120 : (ls_mode == LS_MULTI_COL \
121 ? "dir" : "vdir"))
123 #define AUTHORS \
124 proper_name ("Richard M. Stallman"), \
125 proper_name ("David MacKenzie")
127 #define obstack_chunk_alloc malloc
128 #define obstack_chunk_free free
130 /* Return an int indicating the result of comparing two integers.
131 Subtracting doesn't always work, due to overflow. */
132 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
134 /* Unix-based readdir implementations have historically returned a dirent.d_ino
135 value that is sometimes not equal to the stat-obtained st_ino value for
136 that same entry. This error occurs for a readdir entry that refers
137 to a mount point. readdir's error is to return the inode number of
138 the underlying directory -- one that typically cannot be stat'ed, as
139 long as a file system is mounted on that directory. RELIABLE_D_INO
140 encapsulates whether we can use the more efficient approach of relying
141 on readdir-supplied d_ino values, or whether we must incur the cost of
142 calling stat or lstat to obtain each guaranteed-valid inode number. */
144 #ifndef READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
145 # define READDIR_LIES_ABOUT_MOUNTPOINT_D_INO 1
146 #endif
148 #if READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
149 # define RELIABLE_D_INO(dp) NOT_AN_INODE_NUMBER
150 #else
151 # define RELIABLE_D_INO(dp) D_INO (dp)
152 #endif
154 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
155 # define st_author st_uid
156 #endif
158 enum filetype
160 unknown,
161 fifo,
162 chardev,
163 directory,
164 blockdev,
165 normal,
166 symbolic_link,
167 sock,
168 whiteout,
169 arg_directory
172 /* Display letters and indicators for each filetype.
173 Keep these in sync with enum filetype. */
174 static char const filetype_letter[] = "?pcdb-lswd";
176 /* Ensure that filetype and filetype_letter have the same
177 number of elements. */
178 verify (sizeof filetype_letter - 1 == arg_directory + 1);
180 #define FILETYPE_INDICATORS \
182 C_ORPHAN, C_FIFO, C_CHR, C_DIR, C_BLK, C_FILE, \
183 C_LINK, C_SOCK, C_FILE, C_DIR \
186 enum acl_type
188 ACL_T_NONE,
189 ACL_T_SELINUX_ONLY,
190 ACL_T_YES
193 struct fileinfo
195 /* The file name. */
196 char *name;
198 /* For symbolic link, name of the file linked to, otherwise zero. */
199 char *linkname;
201 struct stat stat;
203 enum filetype filetype;
205 /* For symbolic link and long listing, st_mode of file linked to, otherwise
206 zero. */
207 mode_t linkmode;
209 /* SELinux security context. */
210 security_context_t scontext;
212 bool stat_ok;
214 /* For symbolic link and color printing, true if linked-to file
215 exists, otherwise false. */
216 bool linkok;
218 /* For long listings, true if the file has an access control list,
219 or an SELinux security context. */
220 enum acl_type acl_type;
222 /* For color listings, true if a regular file has capability info. */
223 bool has_capability;
226 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
228 /* Null is a valid character in a color indicator (think about Epson
229 printers, for example) so we have to use a length/buffer string
230 type. */
232 struct bin_str
234 size_t len; /* Number of bytes */
235 const char *string; /* Pointer to the same */
238 #if ! HAVE_TCGETPGRP
239 # define tcgetpgrp(Fd) 0
240 #endif
242 static size_t quote_name (FILE *out, const char *name,
243 struct quoting_options const *options,
244 size_t *width);
245 static char *make_link_name (char const *name, char const *linkname);
246 static int decode_switches (int argc, char **argv);
247 static bool file_ignored (char const *name);
248 static uintmax_t gobble_file (char const *name, enum filetype type,
249 ino_t inode, bool command_line_arg,
250 char const *dirname);
251 static bool print_color_indicator (const struct fileinfo *f,
252 bool symlink_target);
253 static void put_indicator (const struct bin_str *ind);
254 static void add_ignore_pattern (const char *pattern);
255 static void attach (char *dest, const char *dirname, const char *name);
256 static void clear_files (void);
257 static void extract_dirs_from_files (char const *dirname,
258 bool command_line_arg);
259 static void get_link_name (char const *filename, struct fileinfo *f,
260 bool command_line_arg);
261 static void indent (size_t from, size_t to);
262 static size_t calculate_columns (bool by_columns);
263 static void print_current_files (void);
264 static void print_dir (char const *name, char const *realname,
265 bool command_line_arg);
266 static size_t print_file_name_and_frills (const struct fileinfo *f,
267 size_t start_col);
268 static void print_horizontal (void);
269 static int format_user_width (uid_t u);
270 static int format_group_width (gid_t g);
271 static void print_long_format (const struct fileinfo *f);
272 static void print_many_per_line (void);
273 static size_t print_name_with_quoting (const struct fileinfo *f,
274 bool symlink_target,
275 struct obstack *stack,
276 size_t start_col);
277 static void prep_non_filename_text (void);
278 static bool print_type_indicator (bool stat_ok, mode_t mode,
279 enum filetype type);
280 static void print_with_commas (void);
281 static void queue_directory (char const *name, char const *realname,
282 bool command_line_arg);
283 static void sort_files (void);
284 static void parse_ls_color (void);
285 void usage (int status);
287 /* Initial size of hash table.
288 Most hierarchies are likely to be shallower than this. */
289 #define INITIAL_TABLE_SIZE 30
291 /* The set of `active' directories, from the current command-line argument
292 to the level in the hierarchy at which files are being listed.
293 A directory is represented by its device and inode numbers (struct dev_ino).
294 A directory is added to this set when ls begins listing it or its
295 entries, and it is removed from the set just after ls has finished
296 processing it. This set is used solely to detect loops, e.g., with
297 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
298 static Hash_table *active_dir_set;
300 #define LOOP_DETECT (!!active_dir_set)
302 /* The table of files in the current directory:
304 `cwd_file' points to a vector of `struct fileinfo', one per file.
305 `cwd_n_alloc' is the number of elements space has been allocated for.
306 `cwd_n_used' is the number actually in use. */
308 /* Address of block containing the files that are described. */
309 static struct fileinfo *cwd_file;
311 /* Length of block that `cwd_file' points to, measured in files. */
312 static size_t cwd_n_alloc;
314 /* Index of first unused slot in `cwd_file'. */
315 static size_t cwd_n_used;
317 /* Vector of pointers to files, in proper sorted order, and the number
318 of entries allocated for it. */
319 static void **sorted_file;
320 static size_t sorted_file_alloc;
322 /* When true, in a color listing, color each symlink name according to the
323 type of file it points to. Otherwise, color them according to the `ln'
324 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
325 regardless. This is set when `ln=target' appears in LS_COLORS. */
327 static bool color_symlink_as_referent;
329 /* mode of appropriate file for colorization */
330 #define FILE_OR_LINK_MODE(File) \
331 ((color_symlink_as_referent && (File)->linkok) \
332 ? (File)->linkmode : (File)->stat.st_mode)
335 /* Record of one pending directory waiting to be listed. */
337 struct pending
339 char *name;
340 /* If the directory is actually the file pointed to by a symbolic link we
341 were told to list, `realname' will contain the name of the symbolic
342 link, otherwise zero. */
343 char *realname;
344 bool command_line_arg;
345 struct pending *next;
348 static struct pending *pending_dirs;
350 /* Current time in seconds and nanoseconds since 1970, updated as
351 needed when deciding whether a file is recent. */
353 static struct timespec current_time;
355 static bool print_scontext;
356 static char UNKNOWN_SECURITY_CONTEXT[] = "?";
358 /* Whether any of the files has an ACL. This affects the width of the
359 mode column. */
361 static bool any_has_acl;
363 /* The number of columns to use for columns containing inode numbers,
364 block sizes, link counts, owners, groups, authors, major device
365 numbers, minor device numbers, and file sizes, respectively. */
367 static int inode_number_width;
368 static int block_size_width;
369 static int nlink_width;
370 static int scontext_width;
371 static int owner_width;
372 static int group_width;
373 static int author_width;
374 static int major_device_number_width;
375 static int minor_device_number_width;
376 static int file_size_width;
378 /* Option flags */
380 /* long_format for lots of info, one per line.
381 one_per_line for just names, one per line.
382 many_per_line for just names, many per line, sorted vertically.
383 horizontal for just names, many per line, sorted horizontally.
384 with_commas for just names, many per line, separated by commas.
386 -l (and other options that imply -l), -1, -C, -x and -m control
387 this parameter. */
389 enum format
391 long_format, /* -l and other options that imply -l */
392 one_per_line, /* -1 */
393 many_per_line, /* -C */
394 horizontal, /* -x */
395 with_commas /* -m */
398 static enum format format;
400 /* `full-iso' uses full ISO-style dates and times. `long-iso' uses longer
401 ISO-style time stamps, though shorter than `full-iso'. `iso' uses shorter
402 ISO-style time stamps. `locale' uses locale-dependent time stamps. */
403 enum time_style
405 full_iso_time_style, /* --time-style=full-iso */
406 long_iso_time_style, /* --time-style=long-iso */
407 iso_time_style, /* --time-style=iso */
408 locale_time_style /* --time-style=locale */
411 static char const *const time_style_args[] =
413 "full-iso", "long-iso", "iso", "locale", NULL
415 static enum time_style const time_style_types[] =
417 full_iso_time_style, long_iso_time_style, iso_time_style,
418 locale_time_style
420 ARGMATCH_VERIFY (time_style_args, time_style_types);
422 /* Type of time to print or sort by. Controlled by -c and -u.
423 The values of each item of this enum are important since they are
424 used as indices in the sort functions array (see sort_files()). */
426 enum time_type
428 time_mtime, /* default */
429 time_ctime, /* -c */
430 time_atime, /* -u */
431 time_numtypes /* the number of elements of this enum */
434 static enum time_type time_type;
436 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v.
437 The values of each item of this enum are important since they are
438 used as indices in the sort functions array (see sort_files()). */
440 enum sort_type
442 sort_none = -1, /* -U */
443 sort_name, /* default */
444 sort_extension, /* -X */
445 sort_size, /* -S */
446 sort_version, /* -v */
447 sort_time, /* -t */
448 sort_numtypes /* the number of elements of this enum */
451 static enum sort_type sort_type;
453 /* Direction of sort.
454 false means highest first if numeric,
455 lowest first if alphabetic;
456 these are the defaults.
457 true means the opposite order in each case. -r */
459 static bool sort_reverse;
461 /* True means to display owner information. -g turns this off. */
463 static bool print_owner = true;
465 /* True means to display author information. */
467 static bool print_author;
469 /* True means to display group information. -G and -o turn this off. */
471 static bool print_group = true;
473 /* True means print the user and group id's as numbers rather
474 than as names. -n */
476 static bool numeric_ids;
478 /* True means mention the size in blocks of each file. -s */
480 static bool print_block_size;
482 /* Human-readable options for output. */
483 static int human_output_opts;
485 /* The units to use when printing sizes other than file sizes. */
486 static uintmax_t output_block_size;
488 /* Likewise, but for file sizes. */
489 static uintmax_t file_output_block_size = 1;
491 /* Follow the output with a special string. Using this format,
492 Emacs' dired mode starts up twice as fast, and can handle all
493 strange characters in file names. */
494 static bool dired;
496 /* `none' means don't mention the type of files.
497 `slash' means mention directories only, with a '/'.
498 `file_type' means mention file types.
499 `classify' means mention file types and mark executables.
501 Controlled by -F, -p, and --indicator-style. */
503 enum indicator_style
505 none, /* --indicator-style=none */
506 slash, /* -p, --indicator-style=slash */
507 file_type, /* --indicator-style=file-type */
508 classify /* -F, --indicator-style=classify */
511 static enum indicator_style indicator_style;
513 /* Names of indicator styles. */
514 static char const *const indicator_style_args[] =
516 "none", "slash", "file-type", "classify", NULL
518 static enum indicator_style const indicator_style_types[] =
520 none, slash, file_type, classify
522 ARGMATCH_VERIFY (indicator_style_args, indicator_style_types);
524 /* True means use colors to mark types. Also define the different
525 colors as well as the stuff for the LS_COLORS environment variable.
526 The LS_COLORS variable is now in a termcap-like format. */
528 static bool print_with_color;
530 /* Whether we used any colors in the output so far. If so, we will
531 need to restore the default color later. If not, we will need to
532 call prep_non_filename_text before using color for the first time. */
534 static bool used_color = false;
536 enum color_type
538 color_never, /* 0: default or --color=never */
539 color_always, /* 1: --color=always */
540 color_if_tty /* 2: --color=tty */
543 enum Dereference_symlink
545 DEREF_UNDEFINED = 1,
546 DEREF_NEVER,
547 DEREF_COMMAND_LINE_ARGUMENTS, /* -H */
548 DEREF_COMMAND_LINE_SYMLINK_TO_DIR, /* the default, in certain cases */
549 DEREF_ALWAYS /* -L */
552 enum indicator_no
554 C_LEFT, C_RIGHT, C_END, C_RESET, C_NORM, C_FILE, C_DIR, C_LINK,
555 C_FIFO, C_SOCK,
556 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR, C_SETUID, C_SETGID,
557 C_STICKY, C_OTHER_WRITABLE, C_STICKY_OTHER_WRITABLE, C_CAP, C_MULTIHARDLINK,
558 C_CLR_TO_EOL
561 static const char *const indicator_name[]=
563 "lc", "rc", "ec", "rs", "no", "fi", "di", "ln", "pi", "so",
564 "bd", "cd", "mi", "or", "ex", "do", "su", "sg", "st",
565 "ow", "tw", "ca", "mh", "cl", NULL
568 struct color_ext_type
570 struct bin_str ext; /* The extension we're looking for */
571 struct bin_str seq; /* The sequence to output when we do */
572 struct color_ext_type *next; /* Next in list */
575 static struct bin_str color_indicator[] =
577 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
578 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
579 { 0, NULL }, /* ec: End color (replaces lc+no+rc) */
580 { LEN_STR_PAIR ("0") }, /* rs: Reset to ordinary colors */
581 { 0, NULL }, /* no: Normal */
582 { 0, NULL }, /* fi: File: default */
583 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
584 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
585 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
586 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
587 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
588 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
589 { 0, NULL }, /* mi: Missing file: undefined */
590 { 0, NULL }, /* or: Orphaned symlink: undefined */
591 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
592 { LEN_STR_PAIR ("01;35") }, /* do: Door: bright magenta */
593 { LEN_STR_PAIR ("37;41") }, /* su: setuid: white on red */
594 { LEN_STR_PAIR ("30;43") }, /* sg: setgid: black on yellow */
595 { LEN_STR_PAIR ("37;44") }, /* st: sticky: black on blue */
596 { LEN_STR_PAIR ("34;42") }, /* ow: other-writable: blue on green */
597 { LEN_STR_PAIR ("30;42") }, /* tw: ow w/ sticky: black on green */
598 { LEN_STR_PAIR ("30;41") }, /* ca: black on red */
599 { 0, NULL }, /* mh: disabled by default */
600 { LEN_STR_PAIR ("\033[K") }, /* cl: clear to end of line */
603 /* FIXME: comment */
604 static struct color_ext_type *color_ext_list = NULL;
606 /* Buffer for color sequences */
607 static char *color_buf;
609 /* True means to check for orphaned symbolic link, for displaying
610 colors. */
612 static bool check_symlink_color;
614 /* True means mention the inode number of each file. -i */
616 static bool print_inode;
618 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
619 other options that imply -l), and -L. */
621 static enum Dereference_symlink dereference;
623 /* True means when a directory is found, display info on its
624 contents. -R */
626 static bool recursive;
628 /* True means when an argument is a directory name, display info
629 on it itself. -d */
631 static bool immediate_dirs;
633 /* True means that directories are grouped before files. */
635 static bool directories_first;
637 /* Which files to ignore. */
639 static enum
641 /* Ignore files whose names start with `.', and files specified by
642 --hide and --ignore. */
643 IGNORE_DEFAULT,
645 /* Ignore `.', `..', and files specified by --ignore. */
646 IGNORE_DOT_AND_DOTDOT,
648 /* Ignore only files specified by --ignore. */
649 IGNORE_MINIMAL
650 } ignore_mode;
652 /* A linked list of shell-style globbing patterns. If a non-argument
653 file name matches any of these patterns, it is ignored.
654 Controlled by -I. Multiple -I options accumulate.
655 The -B option adds `*~' and `.*~' to this list. */
657 struct ignore_pattern
659 const char *pattern;
660 struct ignore_pattern *next;
663 static struct ignore_pattern *ignore_patterns;
665 /* Similar to IGNORE_PATTERNS, except that -a or -A causes this
666 variable itself to be ignored. */
667 static struct ignore_pattern *hide_patterns;
669 /* True means output nongraphic chars in file names as `?'.
670 (-q, --hide-control-chars)
671 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
672 independent. The algorithm is: first, obey the quoting style to get a
673 string representing the file name; then, if qmark_funny_chars is set,
674 replace all nonprintable chars in that string with `?'. It's necessary
675 to replace nonprintable chars even in quoted strings, because we don't
676 want to mess up the terminal if control chars get sent to it, and some
677 quoting methods pass through control chars as-is. */
678 static bool qmark_funny_chars;
680 /* Quoting options for file and dir name output. */
682 static struct quoting_options *filename_quoting_options;
683 static struct quoting_options *dirname_quoting_options;
685 /* The number of chars per hardware tab stop. Setting this to zero
686 inhibits the use of TAB characters for separating columns. -T */
687 static size_t tabsize;
689 /* True means print each directory name before listing it. */
691 static bool print_dir_name;
693 /* The line length to use for breaking lines in many-per-line format.
694 Can be set with -w. */
696 static size_t line_length;
698 /* If true, the file listing format requires that stat be called on
699 each file. */
701 static bool format_needs_stat;
703 /* Similar to `format_needs_stat', but set if only the file type is
704 needed. */
706 static bool format_needs_type;
708 /* An arbitrary limit on the number of bytes in a printed time stamp.
709 This is set to a relatively small value to avoid the need to worry
710 about denial-of-service attacks on servers that run "ls" on behalf
711 of remote clients. 1000 bytes should be enough for any practical
712 time stamp format. */
714 enum { TIME_STAMP_LEN_MAXIMUM = MAX (1000, INT_STRLEN_BOUND (time_t)) };
716 /* strftime formats for non-recent and recent files, respectively, in
717 -l output. */
719 static char const *long_time_format[2] =
721 /* strftime format for non-recent files (older than 6 months), in
722 -l output. This should contain the year, month and day (at
723 least), in an order that is understood by people in your
724 locale's territory. Please try to keep the number of used
725 screen columns small, because many people work in windows with
726 only 80 columns. But make this as wide as the other string
727 below, for recent files. */
728 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
729 so be wary of using variable width fields from the locale.
730 Note %b is handled specially by ls and aligned correctly.
731 Note also that specifying a width as in %5b is erroneous as strftime
732 will count bytes rather than characters in multibyte locales. */
733 N_("%b %e %Y"),
734 /* strftime format for recent files (younger than 6 months), in -l
735 output. This should contain the month, day and time (at
736 least), in an order that is understood by people in your
737 locale's territory. Please try to keep the number of used
738 screen columns small, because many people work in windows with
739 only 80 columns. But make this as wide as the other string
740 above, for non-recent files. */
741 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
742 so be wary of using variable width fields from the locale.
743 Note %b is handled specially by ls and aligned correctly.
744 Note also that specifying a width as in %5b is erroneous as strftime
745 will count bytes rather than characters in multibyte locales. */
746 N_("%b %e %H:%M")
749 /* The set of signals that are caught. */
751 static sigset_t caught_signals;
753 /* If nonzero, the value of the pending fatal signal. */
755 static sig_atomic_t volatile interrupt_signal;
757 /* A count of the number of pending stop signals that have been received. */
759 static sig_atomic_t volatile stop_signal_count;
761 /* Desired exit status. */
763 static int exit_status;
765 /* Exit statuses. */
766 enum
768 /* "ls" had a minor problem. E.g., while processing a directory,
769 ls obtained the name of an entry via readdir, yet was later
770 unable to stat that name. This happens when listing a directory
771 in which entries are actively being removed or renamed. */
772 LS_MINOR_PROBLEM = 1,
774 /* "ls" had more serious trouble (e.g., memory exhausted, invalid
775 option or failure to stat a command line argument. */
776 LS_FAILURE = 2
779 /* For long options that have no equivalent short option, use a
780 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
781 enum
783 AUTHOR_OPTION = CHAR_MAX + 1,
784 BLOCK_SIZE_OPTION,
785 COLOR_OPTION,
786 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION,
787 FILE_TYPE_INDICATOR_OPTION,
788 FORMAT_OPTION,
789 FULL_TIME_OPTION,
790 GROUP_DIRECTORIES_FIRST_OPTION,
791 HIDE_OPTION,
792 INDICATOR_STYLE_OPTION,
793 QUOTING_STYLE_OPTION,
794 SHOW_CONTROL_CHARS_OPTION,
795 SI_OPTION,
796 SORT_OPTION,
797 TIME_OPTION,
798 TIME_STYLE_OPTION
801 static struct option const long_options[] =
803 {"all", no_argument, NULL, 'a'},
804 {"escape", no_argument, NULL, 'b'},
805 {"directory", no_argument, NULL, 'd'},
806 {"dired", no_argument, NULL, 'D'},
807 {"full-time", no_argument, NULL, FULL_TIME_OPTION},
808 {"group-directories-first", no_argument, NULL,
809 GROUP_DIRECTORIES_FIRST_OPTION},
810 {"human-readable", no_argument, NULL, 'h'},
811 {"inode", no_argument, NULL, 'i'},
812 {"numeric-uid-gid", no_argument, NULL, 'n'},
813 {"no-group", no_argument, NULL, 'G'},
814 {"hide-control-chars", no_argument, NULL, 'q'},
815 {"reverse", no_argument, NULL, 'r'},
816 {"size", no_argument, NULL, 's'},
817 {"width", required_argument, NULL, 'w'},
818 {"almost-all", no_argument, NULL, 'A'},
819 {"ignore-backups", no_argument, NULL, 'B'},
820 {"classify", no_argument, NULL, 'F'},
821 {"file-type", no_argument, NULL, FILE_TYPE_INDICATOR_OPTION},
822 {"si", no_argument, NULL, SI_OPTION},
823 {"dereference-command-line", no_argument, NULL, 'H'},
824 {"dereference-command-line-symlink-to-dir", no_argument, NULL,
825 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION},
826 {"hide", required_argument, NULL, HIDE_OPTION},
827 {"ignore", required_argument, NULL, 'I'},
828 {"indicator-style", required_argument, NULL, INDICATOR_STYLE_OPTION},
829 {"dereference", no_argument, NULL, 'L'},
830 {"literal", no_argument, NULL, 'N'},
831 {"quote-name", no_argument, NULL, 'Q'},
832 {"quoting-style", required_argument, NULL, QUOTING_STYLE_OPTION},
833 {"recursive", no_argument, NULL, 'R'},
834 {"format", required_argument, NULL, FORMAT_OPTION},
835 {"show-control-chars", no_argument, NULL, SHOW_CONTROL_CHARS_OPTION},
836 {"sort", required_argument, NULL, SORT_OPTION},
837 {"tabsize", required_argument, NULL, 'T'},
838 {"time", required_argument, NULL, TIME_OPTION},
839 {"time-style", required_argument, NULL, TIME_STYLE_OPTION},
840 {"color", optional_argument, NULL, COLOR_OPTION},
841 {"block-size", required_argument, NULL, BLOCK_SIZE_OPTION},
842 {"context", no_argument, 0, 'Z'},
843 {"author", no_argument, NULL, AUTHOR_OPTION},
844 {GETOPT_HELP_OPTION_DECL},
845 {GETOPT_VERSION_OPTION_DECL},
846 {NULL, 0, NULL, 0}
849 static char const *const format_args[] =
851 "verbose", "long", "commas", "horizontal", "across",
852 "vertical", "single-column", NULL
854 static enum format const format_types[] =
856 long_format, long_format, with_commas, horizontal, horizontal,
857 many_per_line, one_per_line
859 ARGMATCH_VERIFY (format_args, format_types);
861 static char const *const sort_args[] =
863 "none", "time", "size", "extension", "version", NULL
865 static enum sort_type const sort_types[] =
867 sort_none, sort_time, sort_size, sort_extension, sort_version
869 ARGMATCH_VERIFY (sort_args, sort_types);
871 static char const *const time_args[] =
873 "atime", "access", "use", "ctime", "status", NULL
875 static enum time_type const time_types[] =
877 time_atime, time_atime, time_atime, time_ctime, time_ctime
879 ARGMATCH_VERIFY (time_args, time_types);
881 static char const *const color_args[] =
883 /* force and none are for compatibility with another color-ls version */
884 "always", "yes", "force",
885 "never", "no", "none",
886 "auto", "tty", "if-tty", NULL
888 static enum color_type const color_types[] =
890 color_always, color_always, color_always,
891 color_never, color_never, color_never,
892 color_if_tty, color_if_tty, color_if_tty
894 ARGMATCH_VERIFY (color_args, color_types);
896 /* Information about filling a column. */
897 struct column_info
899 bool valid_len;
900 size_t line_len;
901 size_t *col_arr;
904 /* Array with information about column filledness. */
905 static struct column_info *column_info;
907 /* Maximum number of columns ever possible for this display. */
908 static size_t max_idx;
910 /* The minimum width of a column is 3: 1 character for the name and 2
911 for the separating white space. */
912 #define MIN_COLUMN_WIDTH 3
915 /* This zero-based index is used solely with the --dired option.
916 When that option is in effect, this counter is incremented for each
917 byte of output generated by this program so that the beginning
918 and ending indices (in that output) of every file name can be recorded
919 and later output themselves. */
920 static size_t dired_pos;
922 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
924 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
925 #define DIRED_FPUTS(s, stream, s_len) \
926 do {fputs (s, stream); dired_pos += s_len;} while (0)
928 /* Like DIRED_FPUTS, but for use when S is a literal string. */
929 #define DIRED_FPUTS_LITERAL(s, stream) \
930 do {fputs (s, stream); dired_pos += sizeof (s) - 1;} while (0)
932 #define DIRED_INDENT() \
933 do \
935 if (dired) \
936 DIRED_FPUTS_LITERAL (" ", stdout); \
938 while (0)
940 /* With --dired, store pairs of beginning and ending indices of filenames. */
941 static struct obstack dired_obstack;
943 /* With --dired, store pairs of beginning and ending indices of any
944 directory names that appear as headers (just before `total' line)
945 for lists of directory entries. Such directory names are seen when
946 listing hierarchies using -R and when a directory is listed with at
947 least one other command line argument. */
948 static struct obstack subdired_obstack;
950 /* Save the current index on the specified obstack, OBS. */
951 #define PUSH_CURRENT_DIRED_POS(obs) \
952 do \
954 if (dired) \
955 obstack_grow (obs, &dired_pos, sizeof (dired_pos)); \
957 while (0)
959 /* With -R, this stack is used to help detect directory cycles.
960 The device/inode pairs on this stack mirror the pairs in the
961 active_dir_set hash table. */
962 static struct obstack dev_ino_obstack;
964 /* Push a pair onto the device/inode stack. */
965 #define DEV_INO_PUSH(Dev, Ino) \
966 do \
968 struct dev_ino *di; \
969 obstack_blank (&dev_ino_obstack, sizeof (struct dev_ino)); \
970 di = -1 + (struct dev_ino *) obstack_next_free (&dev_ino_obstack); \
971 di->st_dev = (Dev); \
972 di->st_ino = (Ino); \
974 while (0)
976 /* Pop a dev/ino struct off the global dev_ino_obstack
977 and return that struct. */
978 static struct dev_ino
979 dev_ino_pop (void)
981 assert (sizeof (struct dev_ino) <= obstack_object_size (&dev_ino_obstack));
982 obstack_blank (&dev_ino_obstack, -(int) (sizeof (struct dev_ino)));
983 return *(struct dev_ino *) obstack_next_free (&dev_ino_obstack);
986 /* Note the use commented out below:
987 #define ASSERT_MATCHING_DEV_INO(Name, Di) \
988 do \
990 struct stat sb; \
991 assert (Name); \
992 assert (0 <= stat (Name, &sb)); \
993 assert (sb.st_dev == Di.st_dev); \
994 assert (sb.st_ino == Di.st_ino); \
996 while (0)
999 /* Write to standard output PREFIX, followed by the quoting style and
1000 a space-separated list of the integers stored in OS all on one line. */
1002 static void
1003 dired_dump_obstack (const char *prefix, struct obstack *os)
1005 size_t n_pos;
1007 n_pos = obstack_object_size (os) / sizeof (dired_pos);
1008 if (n_pos > 0)
1010 size_t i;
1011 size_t *pos;
1013 pos = (size_t *) obstack_finish (os);
1014 fputs (prefix, stdout);
1015 for (i = 0; i < n_pos; i++)
1016 printf (" %lu", (unsigned long int) pos[i]);
1017 putchar ('\n');
1021 /* Read the abbreviated month names from the locale, to align them
1022 and to determine the max width of the field and to truncate names
1023 greater than our max allowed.
1024 Note even though this handles multibyte locales correctly
1025 it's not restricted to them as single byte locales can have
1026 variable width abbreviated months and also precomputing/caching
1027 the names was seen to increase the performance of ls significantly. */
1029 /* max number of display cells to use */
1030 enum { MAX_MON_WIDTH = 5 };
1031 /* In the unlikely event that the abmon[] storage is not big enough
1032 an error message will be displayed, and we revert to using
1033 unmodified abbreviated month names from the locale database. */
1034 static char abmon[12][MAX_MON_WIDTH * 2 * MB_LEN_MAX + 1];
1035 /* minimum width needed to align %b, 0 => don't use precomputed values. */
1036 static size_t required_mon_width;
1038 static size_t
1039 abmon_init (void)
1041 #ifdef HAVE_NL_LANGINFO
1042 required_mon_width = MAX_MON_WIDTH;
1043 size_t curr_max_width;
1046 curr_max_width = required_mon_width;
1047 required_mon_width = 0;
1048 for (int i = 0; i < 12; i++)
1050 size_t width = curr_max_width;
1052 size_t req = mbsalign (nl_langinfo (ABMON_1 + i),
1053 abmon[i], sizeof (abmon[i]),
1054 &width, MBS_ALIGN_LEFT, 0);
1056 if (req == (size_t) -1 || req >= sizeof (abmon[i]))
1058 required_mon_width = 0; /* ignore precomputed strings. */
1059 return required_mon_width;
1062 required_mon_width = MAX (required_mon_width, width);
1065 while (curr_max_width > required_mon_width);
1066 #endif
1068 return required_mon_width;
1071 static size_t
1072 dev_ino_hash (void const *x, size_t table_size)
1074 struct dev_ino const *p = x;
1075 return (uintmax_t) p->st_ino % table_size;
1078 static bool
1079 dev_ino_compare (void const *x, void const *y)
1081 struct dev_ino const *a = x;
1082 struct dev_ino const *b = y;
1083 return SAME_INODE (*a, *b) ? true : false;
1086 static void
1087 dev_ino_free (void *x)
1089 free (x);
1092 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
1093 active directories. Return true if there is already a matching
1094 entry in the table. */
1096 static bool
1097 visit_dir (dev_t dev, ino_t ino)
1099 struct dev_ino *ent;
1100 struct dev_ino *ent_from_table;
1101 bool found_match;
1103 ent = xmalloc (sizeof *ent);
1104 ent->st_ino = ino;
1105 ent->st_dev = dev;
1107 /* Attempt to insert this entry into the table. */
1108 ent_from_table = hash_insert (active_dir_set, ent);
1110 if (ent_from_table == NULL)
1112 /* Insertion failed due to lack of memory. */
1113 xalloc_die ();
1116 found_match = (ent_from_table != ent);
1118 if (found_match)
1120 /* ent was not inserted, so free it. */
1121 free (ent);
1124 return found_match;
1127 static void
1128 free_pending_ent (struct pending *p)
1130 free (p->name);
1131 free (p->realname);
1132 free (p);
1135 static bool
1136 is_colored (enum indicator_no type)
1138 size_t len = color_indicator[type].len;
1139 char const *s = color_indicator[type].string;
1140 return ! (len == 0
1141 || (len == 1 && strncmp (s, "0", 1) == 0)
1142 || (len == 2 && strncmp (s, "00", 2) == 0));
1145 static void
1146 restore_default_color (void)
1148 put_indicator (&color_indicator[C_LEFT]);
1149 put_indicator (&color_indicator[C_RIGHT]);
1152 /* An ordinary signal was received; arrange for the program to exit. */
1154 static void
1155 sighandler (int sig)
1157 if (! SA_NOCLDSTOP)
1158 signal (sig, SIG_IGN);
1159 if (! interrupt_signal)
1160 interrupt_signal = sig;
1163 /* A SIGTSTP was received; arrange for the program to suspend itself. */
1165 static void
1166 stophandler (int sig)
1168 if (! SA_NOCLDSTOP)
1169 signal (sig, stophandler);
1170 if (! interrupt_signal)
1171 stop_signal_count++;
1174 /* Process any pending signals. If signals are caught, this function
1175 should be called periodically. Ideally there should never be an
1176 unbounded amount of time when signals are not being processed.
1177 Signal handling can restore the default colors, so callers must
1178 immediately change colors after invoking this function. */
1180 static void
1181 process_signals (void)
1183 while (interrupt_signal || stop_signal_count)
1185 int sig;
1186 int stops;
1187 sigset_t oldset;
1189 if (used_color)
1190 restore_default_color ();
1191 fflush (stdout);
1193 sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
1195 /* Reload interrupt_signal and stop_signal_count, in case a new
1196 signal was handled before sigprocmask took effect. */
1197 sig = interrupt_signal;
1198 stops = stop_signal_count;
1200 /* SIGTSTP is special, since the application can receive that signal
1201 more than once. In this case, don't set the signal handler to the
1202 default. Instead, just raise the uncatchable SIGSTOP. */
1203 if (stops)
1205 stop_signal_count = stops - 1;
1206 sig = SIGSTOP;
1208 else
1209 signal (sig, SIG_DFL);
1211 /* Exit or suspend the program. */
1212 raise (sig);
1213 sigprocmask (SIG_SETMASK, &oldset, NULL);
1215 /* If execution reaches here, then the program has been
1216 continued (after being suspended). */
1221 main (int argc, char **argv)
1223 int i;
1224 struct pending *thispend;
1225 int n_files;
1227 /* The signals that are trapped, and the number of such signals. */
1228 static int const sig[] =
1230 /* This one is handled specially. */
1231 SIGTSTP,
1233 /* The usual suspects. */
1234 SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM,
1235 #ifdef SIGPOLL
1236 SIGPOLL,
1237 #endif
1238 #ifdef SIGPROF
1239 SIGPROF,
1240 #endif
1241 #ifdef SIGVTALRM
1242 SIGVTALRM,
1243 #endif
1244 #ifdef SIGXCPU
1245 SIGXCPU,
1246 #endif
1247 #ifdef SIGXFSZ
1248 SIGXFSZ,
1249 #endif
1251 enum { nsigs = ARRAY_CARDINALITY (sig) };
1253 #if ! SA_NOCLDSTOP
1254 bool caught_sig[nsigs];
1255 #endif
1257 initialize_main (&argc, &argv);
1258 set_program_name (argv[0]);
1259 setlocale (LC_ALL, "");
1260 bindtextdomain (PACKAGE, LOCALEDIR);
1261 textdomain (PACKAGE);
1263 initialize_exit_failure (LS_FAILURE);
1264 atexit (close_stdout);
1266 assert (ARRAY_CARDINALITY (color_indicator) + 1
1267 == ARRAY_CARDINALITY (indicator_name));
1269 exit_status = EXIT_SUCCESS;
1270 print_dir_name = true;
1271 pending_dirs = NULL;
1273 current_time.tv_sec = TYPE_MINIMUM (time_t);
1274 current_time.tv_nsec = -1;
1276 i = decode_switches (argc, argv);
1278 if (print_with_color)
1279 parse_ls_color ();
1281 /* Test print_with_color again, because the call to parse_ls_color
1282 may have just reset it -- e.g., if LS_COLORS is invalid. */
1283 if (print_with_color)
1285 /* Avoid following symbolic links when possible. */
1286 if (is_colored (C_ORPHAN)
1287 || (is_colored (C_EXEC) && color_symlink_as_referent)
1288 || (is_colored (C_MISSING) && format == long_format))
1289 check_symlink_color = true;
1291 /* If the standard output is a controlling terminal, watch out
1292 for signals, so that the colors can be restored to the
1293 default state if "ls" is suspended or interrupted. */
1295 if (0 <= tcgetpgrp (STDOUT_FILENO))
1297 int j;
1298 #if SA_NOCLDSTOP
1299 struct sigaction act;
1301 sigemptyset (&caught_signals);
1302 for (j = 0; j < nsigs; j++)
1304 sigaction (sig[j], NULL, &act);
1305 if (act.sa_handler != SIG_IGN)
1306 sigaddset (&caught_signals, sig[j]);
1309 act.sa_mask = caught_signals;
1310 act.sa_flags = SA_RESTART;
1312 for (j = 0; j < nsigs; j++)
1313 if (sigismember (&caught_signals, sig[j]))
1315 act.sa_handler = sig[j] == SIGTSTP ? stophandler : sighandler;
1316 sigaction (sig[j], &act, NULL);
1318 #else
1319 for (j = 0; j < nsigs; j++)
1321 caught_sig[j] = (signal (sig[j], SIG_IGN) != SIG_IGN);
1322 if (caught_sig[j])
1324 signal (sig[j], sig[j] == SIGTSTP ? stophandler : sighandler);
1325 siginterrupt (sig[j], 0);
1328 #endif
1332 if (dereference == DEREF_UNDEFINED)
1333 dereference = ((immediate_dirs
1334 || indicator_style == classify
1335 || format == long_format)
1336 ? DEREF_NEVER
1337 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
1339 /* When using -R, initialize a data structure we'll use to
1340 detect any directory cycles. */
1341 if (recursive)
1343 active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, NULL,
1344 dev_ino_hash,
1345 dev_ino_compare,
1346 dev_ino_free);
1347 if (active_dir_set == NULL)
1348 xalloc_die ();
1350 obstack_init (&dev_ino_obstack);
1353 format_needs_stat = sort_type == sort_time || sort_type == sort_size
1354 || format == long_format
1355 || print_scontext
1356 || print_block_size;
1357 format_needs_type = (! format_needs_stat
1358 && (recursive
1359 || print_with_color
1360 || indicator_style != none
1361 || directories_first));
1363 if (dired)
1365 obstack_init (&dired_obstack);
1366 obstack_init (&subdired_obstack);
1369 cwd_n_alloc = 100;
1370 cwd_file = xnmalloc (cwd_n_alloc, sizeof *cwd_file);
1371 cwd_n_used = 0;
1373 clear_files ();
1375 n_files = argc - i;
1377 if (n_files <= 0)
1379 if (immediate_dirs)
1380 gobble_file (".", directory, NOT_AN_INODE_NUMBER, true, "");
1381 else
1382 queue_directory (".", NULL, true);
1384 else
1386 gobble_file (argv[i++], unknown, NOT_AN_INODE_NUMBER, true, "");
1387 while (i < argc);
1389 if (cwd_n_used)
1391 sort_files ();
1392 if (!immediate_dirs)
1393 extract_dirs_from_files (NULL, true);
1394 /* `cwd_n_used' might be zero now. */
1397 /* In the following if/else blocks, it is sufficient to test `pending_dirs'
1398 (and not pending_dirs->name) because there may be no markers in the queue
1399 at this point. A marker may be enqueued when extract_dirs_from_files is
1400 called with a non-empty string or via print_dir. */
1401 if (cwd_n_used)
1403 print_current_files ();
1404 if (pending_dirs)
1405 DIRED_PUTCHAR ('\n');
1407 else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1408 print_dir_name = false;
1410 while (pending_dirs)
1412 thispend = pending_dirs;
1413 pending_dirs = pending_dirs->next;
1415 if (LOOP_DETECT)
1417 if (thispend->name == NULL)
1419 /* thispend->name == NULL means this is a marker entry
1420 indicating we've finished processing the directory.
1421 Use its dev/ino numbers to remove the corresponding
1422 entry from the active_dir_set hash table. */
1423 struct dev_ino di = dev_ino_pop ();
1424 struct dev_ino *found = hash_delete (active_dir_set, &di);
1425 /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
1426 assert (found);
1427 dev_ino_free (found);
1428 free_pending_ent (thispend);
1429 continue;
1433 print_dir (thispend->name, thispend->realname,
1434 thispend->command_line_arg);
1436 free_pending_ent (thispend);
1437 print_dir_name = true;
1440 if (print_with_color)
1442 int j;
1444 if (used_color)
1445 restore_default_color ();
1446 fflush (stdout);
1448 /* Restore the default signal handling. */
1449 #if SA_NOCLDSTOP
1450 for (j = 0; j < nsigs; j++)
1451 if (sigismember (&caught_signals, sig[j]))
1452 signal (sig[j], SIG_DFL);
1453 #else
1454 for (j = 0; j < nsigs; j++)
1455 if (caught_sig[j])
1456 signal (sig[j], SIG_DFL);
1457 #endif
1459 /* Act on any signals that arrived before the default was restored.
1460 This can process signals out of order, but there doesn't seem to
1461 be an easy way to do them in order, and the order isn't that
1462 important anyway. */
1463 for (j = stop_signal_count; j; j--)
1464 raise (SIGSTOP);
1465 j = interrupt_signal;
1466 if (j)
1467 raise (j);
1470 if (dired)
1472 /* No need to free these since we're about to exit. */
1473 dired_dump_obstack ("//DIRED//", &dired_obstack);
1474 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1475 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1476 quoting_style_args[get_quoting_style (filename_quoting_options)]);
1479 if (LOOP_DETECT)
1481 assert (hash_get_n_entries (active_dir_set) == 0);
1482 hash_free (active_dir_set);
1485 exit (exit_status);
1488 /* Set all the option flags according to the switches specified.
1489 Return the index of the first non-option argument. */
1491 static int
1492 decode_switches (int argc, char **argv)
1494 char *time_style_option = NULL;
1496 /* Record whether there is an option specifying sort type. */
1497 bool sort_type_specified = false;
1499 qmark_funny_chars = false;
1501 /* initialize all switches to default settings */
1503 switch (ls_mode)
1505 case LS_MULTI_COL:
1506 /* This is for the `dir' program. */
1507 format = many_per_line;
1508 set_quoting_style (NULL, escape_quoting_style);
1509 break;
1511 case LS_LONG_FORMAT:
1512 /* This is for the `vdir' program. */
1513 format = long_format;
1514 set_quoting_style (NULL, escape_quoting_style);
1515 break;
1517 case LS_LS:
1518 /* This is for the `ls' program. */
1519 if (isatty (STDOUT_FILENO))
1521 format = many_per_line;
1522 /* See description of qmark_funny_chars, above. */
1523 qmark_funny_chars = true;
1525 else
1527 format = one_per_line;
1528 qmark_funny_chars = false;
1530 break;
1532 default:
1533 abort ();
1536 time_type = time_mtime;
1537 sort_type = sort_name;
1538 sort_reverse = false;
1539 numeric_ids = false;
1540 print_block_size = false;
1541 indicator_style = none;
1542 print_inode = false;
1543 dereference = DEREF_UNDEFINED;
1544 recursive = false;
1545 immediate_dirs = false;
1546 ignore_mode = IGNORE_DEFAULT;
1547 ignore_patterns = NULL;
1548 hide_patterns = NULL;
1549 print_scontext = false;
1551 /* FIXME: put this in a function. */
1553 char const *q_style = getenv ("QUOTING_STYLE");
1554 if (q_style)
1556 int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
1557 if (0 <= i)
1558 set_quoting_style (NULL, quoting_style_vals[i]);
1559 else
1560 error (0, 0,
1561 _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
1562 quotearg (q_style));
1567 char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
1568 human_options (ls_block_size,
1569 &human_output_opts, &output_block_size);
1570 if (ls_block_size || getenv ("BLOCK_SIZE"))
1571 file_output_block_size = output_block_size;
1574 line_length = 80;
1576 char const *p = getenv ("COLUMNS");
1577 if (p && *p)
1579 unsigned long int tmp_ulong;
1580 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1581 && 0 < tmp_ulong && tmp_ulong <= SIZE_MAX)
1583 line_length = tmp_ulong;
1585 else
1587 error (0, 0,
1588 _("ignoring invalid width in environment variable COLUMNS: %s"),
1589 quotearg (p));
1594 #ifdef TIOCGWINSZ
1596 struct winsize ws;
1598 if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1
1599 && 0 < ws.ws_col && ws.ws_col == (size_t) ws.ws_col)
1600 line_length = ws.ws_col;
1602 #endif
1605 char const *p = getenv ("TABSIZE");
1606 tabsize = 8;
1607 if (p)
1609 unsigned long int tmp_ulong;
1610 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1611 && tmp_ulong <= SIZE_MAX)
1613 tabsize = tmp_ulong;
1615 else
1617 error (0, 0,
1618 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1619 quotearg (p));
1624 for (;;)
1626 int oi = -1;
1627 int c = getopt_long (argc, argv,
1628 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1",
1629 long_options, &oi);
1630 if (c == -1)
1631 break;
1633 switch (c)
1635 case 'a':
1636 ignore_mode = IGNORE_MINIMAL;
1637 break;
1639 case 'b':
1640 set_quoting_style (NULL, escape_quoting_style);
1641 break;
1643 case 'c':
1644 time_type = time_ctime;
1645 break;
1647 case 'd':
1648 immediate_dirs = true;
1649 break;
1651 case 'f':
1652 /* Same as enabling -a -U and disabling -l -s. */
1653 ignore_mode = IGNORE_MINIMAL;
1654 sort_type = sort_none;
1655 sort_type_specified = true;
1656 /* disable -l */
1657 if (format == long_format)
1658 format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
1659 print_block_size = false; /* disable -s */
1660 print_with_color = false; /* disable --color */
1661 break;
1663 case FILE_TYPE_INDICATOR_OPTION: /* --file-type */
1664 indicator_style = file_type;
1665 break;
1667 case 'g':
1668 format = long_format;
1669 print_owner = false;
1670 break;
1672 case 'h':
1673 human_output_opts = human_autoscale | human_SI | human_base_1024;
1674 file_output_block_size = output_block_size = 1;
1675 break;
1677 case 'i':
1678 print_inode = true;
1679 break;
1681 case 'k':
1682 human_output_opts = 0;
1683 file_output_block_size = output_block_size = 1024;
1684 break;
1686 case 'l':
1687 format = long_format;
1688 break;
1690 case 'm':
1691 format = with_commas;
1692 break;
1694 case 'n':
1695 numeric_ids = true;
1696 format = long_format;
1697 break;
1699 case 'o': /* Just like -l, but don't display group info. */
1700 format = long_format;
1701 print_group = false;
1702 break;
1704 case 'p':
1705 indicator_style = slash;
1706 break;
1708 case 'q':
1709 qmark_funny_chars = true;
1710 break;
1712 case 'r':
1713 sort_reverse = true;
1714 break;
1716 case 's':
1717 print_block_size = true;
1718 break;
1720 case 't':
1721 sort_type = sort_time;
1722 sort_type_specified = true;
1723 break;
1725 case 'u':
1726 time_type = time_atime;
1727 break;
1729 case 'v':
1730 sort_type = sort_version;
1731 sort_type_specified = true;
1732 break;
1734 case 'w':
1736 unsigned long int tmp_ulong;
1737 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1738 || ! (0 < tmp_ulong && tmp_ulong <= SIZE_MAX))
1739 error (LS_FAILURE, 0, _("invalid line width: %s"),
1740 quotearg (optarg));
1741 line_length = tmp_ulong;
1742 break;
1745 case 'x':
1746 format = horizontal;
1747 break;
1749 case 'A':
1750 if (ignore_mode == IGNORE_DEFAULT)
1751 ignore_mode = IGNORE_DOT_AND_DOTDOT;
1752 break;
1754 case 'B':
1755 add_ignore_pattern ("*~");
1756 add_ignore_pattern (".*~");
1757 break;
1759 case 'C':
1760 format = many_per_line;
1761 break;
1763 case 'D':
1764 dired = true;
1765 break;
1767 case 'F':
1768 indicator_style = classify;
1769 break;
1771 case 'G': /* inhibit display of group info */
1772 print_group = false;
1773 break;
1775 case 'H':
1776 dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1777 break;
1779 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
1780 dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
1781 break;
1783 case 'I':
1784 add_ignore_pattern (optarg);
1785 break;
1787 case 'L':
1788 dereference = DEREF_ALWAYS;
1789 break;
1791 case 'N':
1792 set_quoting_style (NULL, literal_quoting_style);
1793 break;
1795 case 'Q':
1796 set_quoting_style (NULL, c_quoting_style);
1797 break;
1799 case 'R':
1800 recursive = true;
1801 break;
1803 case 'S':
1804 sort_type = sort_size;
1805 sort_type_specified = true;
1806 break;
1808 case 'T':
1810 unsigned long int tmp_ulong;
1811 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1812 || SIZE_MAX < tmp_ulong)
1813 error (LS_FAILURE, 0, _("invalid tab size: %s"),
1814 quotearg (optarg));
1815 tabsize = tmp_ulong;
1816 break;
1819 case 'U':
1820 sort_type = sort_none;
1821 sort_type_specified = true;
1822 break;
1824 case 'X':
1825 sort_type = sort_extension;
1826 sort_type_specified = true;
1827 break;
1829 case '1':
1830 /* -1 has no effect after -l. */
1831 if (format != long_format)
1832 format = one_per_line;
1833 break;
1835 case AUTHOR_OPTION:
1836 print_author = true;
1837 break;
1839 case HIDE_OPTION:
1841 struct ignore_pattern *hide = xmalloc (sizeof *hide);
1842 hide->pattern = optarg;
1843 hide->next = hide_patterns;
1844 hide_patterns = hide;
1846 break;
1848 case SORT_OPTION:
1849 sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1850 sort_type_specified = true;
1851 break;
1853 case GROUP_DIRECTORIES_FIRST_OPTION:
1854 directories_first = true;
1855 break;
1857 case TIME_OPTION:
1858 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1859 break;
1861 case FORMAT_OPTION:
1862 format = XARGMATCH ("--format", optarg, format_args, format_types);
1863 break;
1865 case FULL_TIME_OPTION:
1866 format = long_format;
1867 time_style_option = bad_cast ("full-iso");
1868 break;
1870 case COLOR_OPTION:
1872 int i;
1873 if (optarg)
1874 i = XARGMATCH ("--color", optarg, color_args, color_types);
1875 else
1876 /* Using --color with no argument is equivalent to using
1877 --color=always. */
1878 i = color_always;
1880 print_with_color = (i == color_always
1881 || (i == color_if_tty
1882 && isatty (STDOUT_FILENO)));
1884 if (print_with_color)
1886 /* Don't use TAB characters in output. Some terminal
1887 emulators can't handle the combination of tabs and
1888 color codes on the same line. */
1889 tabsize = 0;
1891 break;
1894 case INDICATOR_STYLE_OPTION:
1895 indicator_style = XARGMATCH ("--indicator-style", optarg,
1896 indicator_style_args,
1897 indicator_style_types);
1898 break;
1900 case QUOTING_STYLE_OPTION:
1901 set_quoting_style (NULL,
1902 XARGMATCH ("--quoting-style", optarg,
1903 quoting_style_args,
1904 quoting_style_vals));
1905 break;
1907 case TIME_STYLE_OPTION:
1908 time_style_option = optarg;
1909 break;
1911 case SHOW_CONTROL_CHARS_OPTION:
1912 qmark_funny_chars = false;
1913 break;
1915 case BLOCK_SIZE_OPTION:
1917 enum strtol_error e = human_options (optarg, &human_output_opts,
1918 &output_block_size);
1919 if (e != LONGINT_OK)
1920 xstrtol_fatal (e, oi, 0, long_options, optarg);
1921 file_output_block_size = output_block_size;
1923 break;
1925 case SI_OPTION:
1926 human_output_opts = human_autoscale | human_SI;
1927 file_output_block_size = output_block_size = 1;
1928 break;
1930 case 'Z':
1931 print_scontext = true;
1932 break;
1934 case_GETOPT_HELP_CHAR;
1936 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1938 default:
1939 usage (LS_FAILURE);
1943 max_idx = MAX (1, line_length / MIN_COLUMN_WIDTH);
1945 filename_quoting_options = clone_quoting_options (NULL);
1946 if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1947 set_char_quoting (filename_quoting_options, ' ', 1);
1948 if (file_type <= indicator_style)
1950 char const *p;
1951 for (p = "*=>@|" + indicator_style - file_type; *p; p++)
1952 set_char_quoting (filename_quoting_options, *p, 1);
1955 dirname_quoting_options = clone_quoting_options (NULL);
1956 set_char_quoting (dirname_quoting_options, ':', 1);
1958 /* --dired is meaningful only with --format=long (-l).
1959 Otherwise, ignore it. FIXME: warn about this?
1960 Alternatively, make --dired imply --format=long? */
1961 if (dired && format != long_format)
1962 dired = false;
1964 /* If -c or -u is specified and not -l (or any other option that implies -l),
1965 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
1966 The behavior of ls when using either -c or -u but with neither -l nor -t
1967 appears to be unspecified by POSIX. So, with GNU ls, `-u' alone means
1968 sort by atime (this is the one that's not specified by the POSIX spec),
1969 -lu means show atime and sort by name, -lut means show atime and sort
1970 by atime. */
1972 if ((time_type == time_ctime || time_type == time_atime)
1973 && !sort_type_specified && format != long_format)
1975 sort_type = sort_time;
1978 if (format == long_format)
1980 char *style = time_style_option;
1981 static char const posix_prefix[] = "posix-";
1983 if (! style)
1984 if (! (style = getenv ("TIME_STYLE")))
1985 style = bad_cast ("locale");
1987 while (strncmp (style, posix_prefix, sizeof posix_prefix - 1) == 0)
1989 if (! hard_locale (LC_TIME))
1990 return optind;
1991 style += sizeof posix_prefix - 1;
1994 if (*style == '+')
1996 char *p0 = style + 1;
1997 char *p1 = strchr (p0, '\n');
1998 if (! p1)
1999 p1 = p0;
2000 else
2002 if (strchr (p1 + 1, '\n'))
2003 error (LS_FAILURE, 0, _("invalid time style format %s"),
2004 quote (p0));
2005 *p1++ = '\0';
2007 long_time_format[0] = p0;
2008 long_time_format[1] = p1;
2010 else
2011 switch (XARGMATCH ("time style", style,
2012 time_style_args,
2013 time_style_types))
2015 case full_iso_time_style:
2016 long_time_format[0] = long_time_format[1] =
2017 "%Y-%m-%d %H:%M:%S.%N %z";
2018 break;
2020 case long_iso_time_style:
2021 case_long_iso_time_style:
2022 long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
2023 break;
2025 case iso_time_style:
2026 long_time_format[0] = "%Y-%m-%d ";
2027 long_time_format[1] = "%m-%d %H:%M";
2028 break;
2030 case locale_time_style:
2031 if (hard_locale (LC_TIME))
2033 /* Ensure that the locale has translations for both
2034 formats. If not, fall back on long-iso format. */
2035 int i;
2036 for (i = 0; i < 2; i++)
2038 char const *locale_format =
2039 dcgettext (NULL, long_time_format[i], LC_TIME);
2040 if (locale_format == long_time_format[i])
2041 goto case_long_iso_time_style;
2042 long_time_format[i] = locale_format;
2046 /* Note we leave %5b etc. alone so user widths/flags are honored. */
2047 if (strstr (long_time_format[0],"%b") || strstr (long_time_format[1],"%b"))
2048 if (!abmon_init ())
2049 error (0, 0, _("error initializing month strings"));
2052 return optind;
2055 /* Parse a string as part of the LS_COLORS variable; this may involve
2056 decoding all kinds of escape characters. If equals_end is set an
2057 unescaped equal sign ends the string, otherwise only a : or \0
2058 does. Set *OUTPUT_COUNT to the number of bytes output. Return
2059 true if successful.
2061 The resulting string is *not* null-terminated, but may contain
2062 embedded nulls.
2064 Note that both dest and src are char **; on return they point to
2065 the first free byte after the array and the character that ended
2066 the input string, respectively. */
2068 static bool
2069 get_funky_string (char **dest, const char **src, bool equals_end,
2070 size_t *output_count)
2072 char num; /* For numerical codes */
2073 size_t count; /* Something to count with */
2074 enum {
2075 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
2076 } state;
2077 const char *p;
2078 char *q;
2080 p = *src; /* We don't want to double-indirect */
2081 q = *dest; /* the whole darn time. */
2083 count = 0; /* No characters counted in yet. */
2084 num = 0;
2086 state = ST_GND; /* Start in ground state. */
2087 while (state < ST_END)
2089 switch (state)
2091 case ST_GND: /* Ground state (no escapes) */
2092 switch (*p)
2094 case ':':
2095 case '\0':
2096 state = ST_END; /* End of string */
2097 break;
2098 case '\\':
2099 state = ST_BACKSLASH; /* Backslash scape sequence */
2100 ++p;
2101 break;
2102 case '^':
2103 state = ST_CARET; /* Caret escape */
2104 ++p;
2105 break;
2106 case '=':
2107 if (equals_end)
2109 state = ST_END; /* End */
2110 break;
2112 /* else fall through */
2113 default:
2114 *(q++) = *(p++);
2115 ++count;
2116 break;
2118 break;
2120 case ST_BACKSLASH: /* Backslash escaped character */
2121 switch (*p)
2123 case '0':
2124 case '1':
2125 case '2':
2126 case '3':
2127 case '4':
2128 case '5':
2129 case '6':
2130 case '7':
2131 state = ST_OCTAL; /* Octal sequence */
2132 num = *p - '0';
2133 break;
2134 case 'x':
2135 case 'X':
2136 state = ST_HEX; /* Hex sequence */
2137 num = 0;
2138 break;
2139 case 'a': /* Bell */
2140 num = '\a';
2141 break;
2142 case 'b': /* Backspace */
2143 num = '\b';
2144 break;
2145 case 'e': /* Escape */
2146 num = 27;
2147 break;
2148 case 'f': /* Form feed */
2149 num = '\f';
2150 break;
2151 case 'n': /* Newline */
2152 num = '\n';
2153 break;
2154 case 'r': /* Carriage return */
2155 num = '\r';
2156 break;
2157 case 't': /* Tab */
2158 num = '\t';
2159 break;
2160 case 'v': /* Vtab */
2161 num = '\v';
2162 break;
2163 case '?': /* Delete */
2164 num = 127;
2165 break;
2166 case '_': /* Space */
2167 num = ' ';
2168 break;
2169 case '\0': /* End of string */
2170 state = ST_ERROR; /* Error! */
2171 break;
2172 default: /* Escaped character like \ ^ : = */
2173 num = *p;
2174 break;
2176 if (state == ST_BACKSLASH)
2178 *(q++) = num;
2179 ++count;
2180 state = ST_GND;
2182 ++p;
2183 break;
2185 case ST_OCTAL: /* Octal sequence */
2186 if (*p < '0' || *p > '7')
2188 *(q++) = num;
2189 ++count;
2190 state = ST_GND;
2192 else
2193 num = (num << 3) + (*(p++) - '0');
2194 break;
2196 case ST_HEX: /* Hex sequence */
2197 switch (*p)
2199 case '0':
2200 case '1':
2201 case '2':
2202 case '3':
2203 case '4':
2204 case '5':
2205 case '6':
2206 case '7':
2207 case '8':
2208 case '9':
2209 num = (num << 4) + (*(p++) - '0');
2210 break;
2211 case 'a':
2212 case 'b':
2213 case 'c':
2214 case 'd':
2215 case 'e':
2216 case 'f':
2217 num = (num << 4) + (*(p++) - 'a') + 10;
2218 break;
2219 case 'A':
2220 case 'B':
2221 case 'C':
2222 case 'D':
2223 case 'E':
2224 case 'F':
2225 num = (num << 4) + (*(p++) - 'A') + 10;
2226 break;
2227 default:
2228 *(q++) = num;
2229 ++count;
2230 state = ST_GND;
2231 break;
2233 break;
2235 case ST_CARET: /* Caret escape */
2236 state = ST_GND; /* Should be the next state... */
2237 if (*p >= '@' && *p <= '~')
2239 *(q++) = *(p++) & 037;
2240 ++count;
2242 else if (*p == '?')
2244 *(q++) = 127;
2245 ++count;
2247 else
2248 state = ST_ERROR;
2249 break;
2251 default:
2252 abort ();
2256 *dest = q;
2257 *src = p;
2258 *output_count = count;
2260 return state != ST_ERROR;
2263 static void
2264 parse_ls_color (void)
2266 const char *p; /* Pointer to character being parsed */
2267 char *buf; /* color_buf buffer pointer */
2268 int state; /* State of parser */
2269 int ind_no; /* Indicator number */
2270 char label[3]; /* Indicator label */
2271 struct color_ext_type *ext; /* Extension we are working on */
2273 if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
2274 return;
2276 ext = NULL;
2277 strcpy (label, "??");
2279 /* This is an overly conservative estimate, but any possible
2280 LS_COLORS string will *not* generate a color_buf longer than
2281 itself, so it is a safe way of allocating a buffer in
2282 advance. */
2283 buf = color_buf = xstrdup (p);
2285 state = 1;
2286 while (state > 0)
2288 switch (state)
2290 case 1: /* First label character */
2291 switch (*p)
2293 case ':':
2294 ++p;
2295 break;
2297 case '*':
2298 /* Allocate new extension block and add to head of
2299 linked list (this way a later definition will
2300 override an earlier one, which can be useful for
2301 having terminal-specific defs override global). */
2303 ext = xmalloc (sizeof *ext);
2304 ext->next = color_ext_list;
2305 color_ext_list = ext;
2307 ++p;
2308 ext->ext.string = buf;
2310 state = (get_funky_string (&buf, &p, true, &ext->ext.len)
2311 ? 4 : -1);
2312 break;
2314 case '\0':
2315 state = 0; /* Done! */
2316 break;
2318 default: /* Assume it is file type label */
2319 label[0] = *(p++);
2320 state = 2;
2321 break;
2323 break;
2325 case 2: /* Second label character */
2326 if (*p)
2328 label[1] = *(p++);
2329 state = 3;
2331 else
2332 state = -1; /* Error */
2333 break;
2335 case 3: /* Equal sign after indicator label */
2336 state = -1; /* Assume failure... */
2337 if (*(p++) == '=')/* It *should* be... */
2339 for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
2341 if (STREQ (label, indicator_name[ind_no]))
2343 color_indicator[ind_no].string = buf;
2344 state = (get_funky_string (&buf, &p, false,
2345 &color_indicator[ind_no].len)
2346 ? 1 : -1);
2347 break;
2350 if (state == -1)
2351 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
2353 break;
2355 case 4: /* Equal sign after *.ext */
2356 if (*(p++) == '=')
2358 ext->seq.string = buf;
2359 state = (get_funky_string (&buf, &p, false, &ext->seq.len)
2360 ? 1 : -1);
2362 else
2363 state = -1;
2364 break;
2368 if (state < 0)
2370 struct color_ext_type *e;
2371 struct color_ext_type *e2;
2373 error (0, 0,
2374 _("unparsable value for LS_COLORS environment variable"));
2375 free (color_buf);
2376 for (e = color_ext_list; e != NULL; /* empty */)
2378 e2 = e;
2379 e = e->next;
2380 free (e2);
2382 print_with_color = false;
2385 if (color_indicator[C_LINK].len == 6
2386 && !strncmp (color_indicator[C_LINK].string, "target", 6))
2387 color_symlink_as_referent = true;
2390 /* Set the exit status to report a failure. If SERIOUS, it is a
2391 serious failure; otherwise, it is merely a minor problem. */
2393 static void
2394 set_exit_status (bool serious)
2396 if (serious)
2397 exit_status = LS_FAILURE;
2398 else if (exit_status == EXIT_SUCCESS)
2399 exit_status = LS_MINOR_PROBLEM;
2402 /* Assuming a failure is serious if SERIOUS, use the printf-style
2403 MESSAGE to report the failure to access a file named FILE. Assume
2404 errno is set appropriately for the failure. */
2406 static void
2407 file_failure (bool serious, char const *message, char const *file)
2409 error (0, errno, message, quotearg_colon (file));
2410 set_exit_status (serious);
2413 /* Request that the directory named NAME have its contents listed later.
2414 If REALNAME is nonzero, it will be used instead of NAME when the
2415 directory name is printed. This allows symbolic links to directories
2416 to be treated as regular directories but still be listed under their
2417 real names. NAME == NULL is used to insert a marker entry for the
2418 directory named in REALNAME.
2419 If NAME is non-NULL, we use its dev/ino information to save
2420 a call to stat -- when doing a recursive (-R) traversal.
2421 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2423 static void
2424 queue_directory (char const *name, char const *realname, bool command_line_arg)
2426 struct pending *new = xmalloc (sizeof *new);
2427 new->realname = realname ? xstrdup (realname) : NULL;
2428 new->name = name ? xstrdup (name) : NULL;
2429 new->command_line_arg = command_line_arg;
2430 new->next = pending_dirs;
2431 pending_dirs = new;
2434 /* Read directory NAME, and list the files in it.
2435 If REALNAME is nonzero, print its name instead of NAME;
2436 this is used for symbolic links to directories.
2437 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2439 static void
2440 print_dir (char const *name, char const *realname, bool command_line_arg)
2442 DIR *dirp;
2443 struct dirent *next;
2444 uintmax_t total_blocks = 0;
2445 static bool first = true;
2447 errno = 0;
2448 dirp = opendir (name);
2449 if (!dirp)
2451 file_failure (command_line_arg, _("cannot open directory %s"), name);
2452 return;
2455 if (LOOP_DETECT)
2457 struct stat dir_stat;
2458 int fd = dirfd (dirp);
2460 /* If dirfd failed, endure the overhead of using stat. */
2461 if ((0 <= fd
2462 ? fstat (fd, &dir_stat)
2463 : stat (name, &dir_stat)) < 0)
2465 file_failure (command_line_arg,
2466 _("cannot determine device and inode of %s"), name);
2467 closedir (dirp);
2468 return;
2471 /* If we've already visited this dev/inode pair, warn that
2472 we've found a loop, and do not process this directory. */
2473 if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
2475 error (0, 0, _("%s: not listing already-listed directory"),
2476 quotearg_colon (name));
2477 closedir (dirp);
2478 set_exit_status (true);
2479 return;
2482 DEV_INO_PUSH (dir_stat.st_dev, dir_stat.st_ino);
2485 if (recursive || print_dir_name)
2487 if (!first)
2488 DIRED_PUTCHAR ('\n');
2489 first = false;
2490 DIRED_INDENT ();
2491 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2492 dired_pos += quote_name (stdout, realname ? realname : name,
2493 dirname_quoting_options, NULL);
2494 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2495 DIRED_FPUTS_LITERAL (":\n", stdout);
2498 /* Read the directory entries, and insert the subfiles into the `cwd_file'
2499 table. */
2501 clear_files ();
2503 while (1)
2505 /* Set errno to zero so we can distinguish between a readdir failure
2506 and when readdir simply finds that there are no more entries. */
2507 errno = 0;
2508 next = readdir (dirp);
2509 if (next)
2511 if (! file_ignored (next->d_name))
2513 enum filetype type = unknown;
2515 #if HAVE_STRUCT_DIRENT_D_TYPE
2516 switch (next->d_type)
2518 case DT_BLK: type = blockdev; break;
2519 case DT_CHR: type = chardev; break;
2520 case DT_DIR: type = directory; break;
2521 case DT_FIFO: type = fifo; break;
2522 case DT_LNK: type = symbolic_link; break;
2523 case DT_REG: type = normal; break;
2524 case DT_SOCK: type = sock; break;
2525 # ifdef DT_WHT
2526 case DT_WHT: type = whiteout; break;
2527 # endif
2529 #endif
2530 total_blocks += gobble_file (next->d_name, type,
2531 RELIABLE_D_INO (next),
2532 false, name);
2534 /* In this narrow case, print out each name right away, so
2535 ls uses constant memory while processing the entries of
2536 this directory. Useful when there are many (millions)
2537 of entries in a directory. */
2538 if (format == one_per_line && sort_type == sort_none
2539 && !print_block_size && !recursive)
2541 /* We must call sort_files in spite of
2542 "sort_type == sort_none" for its initialization
2543 of the sorted_file vector. */
2544 sort_files ();
2545 print_current_files ();
2546 clear_files ();
2550 else if (errno != 0)
2552 file_failure (command_line_arg, _("reading directory %s"), name);
2553 if (errno != EOVERFLOW)
2554 break;
2556 else
2557 break;
2560 if (closedir (dirp) != 0)
2562 file_failure (command_line_arg, _("closing directory %s"), name);
2563 /* Don't return; print whatever we got. */
2566 /* Sort the directory contents. */
2567 sort_files ();
2569 /* If any member files are subdirectories, perhaps they should have their
2570 contents listed rather than being mentioned here as files. */
2572 if (recursive)
2573 extract_dirs_from_files (name, command_line_arg);
2575 if (format == long_format || print_block_size)
2577 const char *p;
2578 char buf[LONGEST_HUMAN_READABLE + 1];
2580 DIRED_INDENT ();
2581 p = _("total");
2582 DIRED_FPUTS (p, stdout, strlen (p));
2583 DIRED_PUTCHAR (' ');
2584 p = human_readable (total_blocks, buf, human_output_opts,
2585 ST_NBLOCKSIZE, output_block_size);
2586 DIRED_FPUTS (p, stdout, strlen (p));
2587 DIRED_PUTCHAR ('\n');
2590 if (cwd_n_used)
2591 print_current_files ();
2594 /* Add `pattern' to the list of patterns for which files that match are
2595 not listed. */
2597 static void
2598 add_ignore_pattern (const char *pattern)
2600 struct ignore_pattern *ignore;
2602 ignore = xmalloc (sizeof *ignore);
2603 ignore->pattern = pattern;
2604 /* Add it to the head of the linked list. */
2605 ignore->next = ignore_patterns;
2606 ignore_patterns = ignore;
2609 /* Return true if one of the PATTERNS matches FILE. */
2611 static bool
2612 patterns_match (struct ignore_pattern const *patterns, char const *file)
2614 struct ignore_pattern const *p;
2615 for (p = patterns; p; p = p->next)
2616 if (fnmatch (p->pattern, file, FNM_PERIOD) == 0)
2617 return true;
2618 return false;
2621 /* Return true if FILE should be ignored. */
2623 static bool
2624 file_ignored (char const *name)
2626 return ((ignore_mode != IGNORE_MINIMAL
2627 && name[0] == '.'
2628 && (ignore_mode == IGNORE_DEFAULT || ! name[1 + (name[1] == '.')]))
2629 || (ignore_mode == IGNORE_DEFAULT
2630 && patterns_match (hide_patterns, name))
2631 || patterns_match (ignore_patterns, name));
2634 /* POSIX requires that a file size be printed without a sign, even
2635 when negative. Assume the typical case where negative sizes are
2636 actually positive values that have wrapped around. */
2638 static uintmax_t
2639 unsigned_file_size (off_t size)
2641 return size + (size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
2644 #ifdef HAVE_CAP
2645 /* Return true if NAME has a capability (see linux/capability.h) */
2646 static bool
2647 has_capability (char const *name)
2649 char *result;
2650 bool has_cap;
2652 cap_t cap_d = cap_get_file (name);
2653 if (cap_d == NULL)
2654 return false;
2656 result = cap_to_text (cap_d, NULL);
2657 cap_free (cap_d);
2658 if (!result)
2659 return false;
2661 /* check if human-readable capability string is empty */
2662 has_cap = !!*result;
2664 cap_free (result);
2665 return has_cap;
2667 #else
2668 static bool
2669 has_capability (char const *name ATTRIBUTE_UNUSED)
2671 return false;
2673 #endif
2675 /* Enter and remove entries in the table `cwd_file'. */
2677 /* Empty the table of files. */
2679 static void
2680 clear_files (void)
2682 size_t i;
2684 for (i = 0; i < cwd_n_used; i++)
2686 struct fileinfo *f = sorted_file[i];
2687 free (f->name);
2688 free (f->linkname);
2689 if (f->scontext != UNKNOWN_SECURITY_CONTEXT)
2690 freecon (f->scontext);
2693 cwd_n_used = 0;
2694 any_has_acl = false;
2695 inode_number_width = 0;
2696 block_size_width = 0;
2697 nlink_width = 0;
2698 owner_width = 0;
2699 group_width = 0;
2700 author_width = 0;
2701 scontext_width = 0;
2702 major_device_number_width = 0;
2703 minor_device_number_width = 0;
2704 file_size_width = 0;
2707 /* Add a file to the current table of files.
2708 Verify that the file exists, and print an error message if it does not.
2709 Return the number of blocks that the file occupies. */
2711 static uintmax_t
2712 gobble_file (char const *name, enum filetype type, ino_t inode,
2713 bool command_line_arg, char const *dirname)
2715 uintmax_t blocks = 0;
2716 struct fileinfo *f;
2718 /* An inode value prior to gobble_file necessarily came from readdir,
2719 which is not used for command line arguments. */
2720 assert (! command_line_arg || inode == NOT_AN_INODE_NUMBER);
2722 if (cwd_n_used == cwd_n_alloc)
2724 cwd_file = xnrealloc (cwd_file, cwd_n_alloc, 2 * sizeof *cwd_file);
2725 cwd_n_alloc *= 2;
2728 f = &cwd_file[cwd_n_used];
2729 memset (f, '\0', sizeof *f);
2730 f->stat.st_ino = inode;
2731 f->filetype = type;
2733 if (command_line_arg
2734 || format_needs_stat
2735 /* When coloring a directory (we may know the type from
2736 direct.d_type), we have to stat it in order to indicate
2737 sticky and/or other-writable attributes. */
2738 || (type == directory && print_with_color)
2739 /* When dereferencing symlinks, the inode and type must come from
2740 stat, but readdir provides the inode and type of lstat. */
2741 || ((print_inode || format_needs_type)
2742 && (type == symbolic_link || type == unknown)
2743 && (dereference == DEREF_ALWAYS
2744 || (command_line_arg && dereference != DEREF_NEVER)
2745 || color_symlink_as_referent || check_symlink_color))
2746 /* Command line dereferences are already taken care of by the above
2747 assertion that the inode number is not yet known. */
2748 || (print_inode && inode == NOT_AN_INODE_NUMBER)
2749 || (format_needs_type
2750 && (type == unknown || command_line_arg
2751 /* --indicator-style=classify (aka -F)
2752 requires that we stat each regular file
2753 to see if it's executable. */
2754 || (type == normal && (indicator_style == classify
2755 /* This is so that --color ends up
2756 highlighting files with these mode
2757 bits set even when options like -F are
2758 not specified. Note we do a redundant
2759 stat in the very unlikely case where
2760 C_CAP is set but not the others. */
2761 || (print_with_color
2762 && (is_colored (C_EXEC)
2763 || is_colored (C_SETUID)
2764 || is_colored (C_SETGID)
2765 || is_colored (C_CAP)))
2766 )))))
2769 /* Absolute name of this file. */
2770 char *absolute_name;
2771 bool do_deref;
2772 int err;
2774 if (name[0] == '/' || dirname[0] == 0)
2775 absolute_name = (char *) name;
2776 else
2778 absolute_name = alloca (strlen (name) + strlen (dirname) + 2);
2779 attach (absolute_name, dirname, name);
2782 switch (dereference)
2784 case DEREF_ALWAYS:
2785 err = stat (absolute_name, &f->stat);
2786 do_deref = true;
2787 break;
2789 case DEREF_COMMAND_LINE_ARGUMENTS:
2790 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
2791 if (command_line_arg)
2793 bool need_lstat;
2794 err = stat (absolute_name, &f->stat);
2795 do_deref = true;
2797 if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2798 break;
2800 need_lstat = (err < 0
2801 ? errno == ENOENT
2802 : ! S_ISDIR (f->stat.st_mode));
2803 if (!need_lstat)
2804 break;
2806 /* stat failed because of ENOENT, maybe indicating a dangling
2807 symlink. Or stat succeeded, ABSOLUTE_NAME does not refer to a
2808 directory, and --dereference-command-line-symlink-to-dir is
2809 in effect. Fall through so that we call lstat instead. */
2812 default: /* DEREF_NEVER */
2813 err = lstat (absolute_name, &f->stat);
2814 do_deref = false;
2815 break;
2818 if (err != 0)
2820 /* Failure to stat a command line argument leads to
2821 an exit status of 2. For other files, stat failure
2822 provokes an exit status of 1. */
2823 file_failure (command_line_arg,
2824 _("cannot access %s"), absolute_name);
2825 if (command_line_arg)
2826 return 0;
2828 f->name = xstrdup (name);
2829 cwd_n_used++;
2831 return 0;
2834 f->stat_ok = true;
2836 /* Note has_capability() adds around 30% runtime to `ls --color` */
2837 if ((type == normal || S_ISREG (f->stat.st_mode))
2838 && print_with_color && is_colored (C_CAP))
2839 f->has_capability = has_capability (absolute_name);
2841 if (format == long_format || print_scontext)
2843 bool have_selinux = false;
2844 bool have_acl = false;
2845 int attr_len = (do_deref
2846 ? getfilecon (absolute_name, &f->scontext)
2847 : lgetfilecon (absolute_name, &f->scontext));
2848 err = (attr_len < 0);
2850 if (err == 0)
2851 have_selinux = ! STREQ ("unlabeled", f->scontext);
2852 else
2854 f->scontext = UNKNOWN_SECURITY_CONTEXT;
2856 /* When requesting security context information, don't make
2857 ls fail just because the file (even a command line argument)
2858 isn't on the right type of file system. I.e., a getfilecon
2859 failure isn't in the same class as a stat failure. */
2860 if (errno == ENOTSUP || errno == EOPNOTSUPP || errno == ENODATA)
2861 err = 0;
2864 if (err == 0 && format == long_format)
2866 int n = file_has_acl (absolute_name, &f->stat);
2867 err = (n < 0);
2868 have_acl = (0 < n);
2871 f->acl_type = (!have_selinux && !have_acl
2872 ? ACL_T_NONE
2873 : (have_selinux && !have_acl
2874 ? ACL_T_SELINUX_ONLY
2875 : ACL_T_YES));
2876 any_has_acl |= f->acl_type != ACL_T_NONE;
2878 if (err)
2879 error (0, errno, "%s", quotearg_colon (absolute_name));
2882 if (S_ISLNK (f->stat.st_mode)
2883 && (format == long_format || check_symlink_color))
2885 char *linkname;
2886 struct stat linkstats;
2888 get_link_name (absolute_name, f, command_line_arg);
2889 linkname = make_link_name (absolute_name, f->linkname);
2891 /* Avoid following symbolic links when possible, ie, when
2892 they won't be traced and when no indicator is needed. */
2893 if (linkname
2894 && (file_type <= indicator_style || check_symlink_color)
2895 && stat (linkname, &linkstats) == 0)
2897 f->linkok = true;
2899 /* Symbolic links to directories that are mentioned on the
2900 command line are automatically traced if not being
2901 listed as files. */
2902 if (!command_line_arg || format == long_format
2903 || !S_ISDIR (linkstats.st_mode))
2905 /* Get the linked-to file's mode for the filetype indicator
2906 in long listings. */
2907 f->linkmode = linkstats.st_mode;
2910 free (linkname);
2913 /* When not distinguishing types of symlinks, pretend we know that
2914 it is stat'able, so that it will be colored as a regular symlink,
2915 and not as an orphan. */
2916 if (S_ISLNK (f->stat.st_mode) && !check_symlink_color)
2917 f->linkok = true;
2919 if (S_ISLNK (f->stat.st_mode))
2920 f->filetype = symbolic_link;
2921 else if (S_ISDIR (f->stat.st_mode))
2923 if (command_line_arg && !immediate_dirs)
2924 f->filetype = arg_directory;
2925 else
2926 f->filetype = directory;
2928 else
2929 f->filetype = normal;
2931 blocks = ST_NBLOCKS (f->stat);
2932 if (format == long_format || print_block_size)
2934 char buf[LONGEST_HUMAN_READABLE + 1];
2935 int len = mbswidth (human_readable (blocks, buf, human_output_opts,
2936 ST_NBLOCKSIZE, output_block_size),
2938 if (block_size_width < len)
2939 block_size_width = len;
2942 if (format == long_format)
2944 if (print_owner)
2946 int len = format_user_width (f->stat.st_uid);
2947 if (owner_width < len)
2948 owner_width = len;
2951 if (print_group)
2953 int len = format_group_width (f->stat.st_gid);
2954 if (group_width < len)
2955 group_width = len;
2958 if (print_author)
2960 int len = format_user_width (f->stat.st_author);
2961 if (author_width < len)
2962 author_width = len;
2966 if (print_scontext)
2968 int len = strlen (f->scontext);
2969 if (scontext_width < len)
2970 scontext_width = len;
2973 if (format == long_format)
2975 char b[INT_BUFSIZE_BOUND (uintmax_t)];
2976 int b_len = strlen (umaxtostr (f->stat.st_nlink, b));
2977 if (nlink_width < b_len)
2978 nlink_width = b_len;
2980 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
2982 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2983 int len = strlen (umaxtostr (major (f->stat.st_rdev), buf));
2984 if (major_device_number_width < len)
2985 major_device_number_width = len;
2986 len = strlen (umaxtostr (minor (f->stat.st_rdev), buf));
2987 if (minor_device_number_width < len)
2988 minor_device_number_width = len;
2989 len = major_device_number_width + 2 + minor_device_number_width;
2990 if (file_size_width < len)
2991 file_size_width = len;
2993 else
2995 char buf[LONGEST_HUMAN_READABLE + 1];
2996 uintmax_t size = unsigned_file_size (f->stat.st_size);
2997 int len = mbswidth (human_readable (size, buf, human_output_opts,
2998 1, file_output_block_size),
3000 if (file_size_width < len)
3001 file_size_width = len;
3006 if (print_inode)
3008 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
3009 int len = strlen (umaxtostr (f->stat.st_ino, buf));
3010 if (inode_number_width < len)
3011 inode_number_width = len;
3014 f->name = xstrdup (name);
3015 cwd_n_used++;
3017 return blocks;
3020 /* Return true if F refers to a directory. */
3021 static bool
3022 is_directory (const struct fileinfo *f)
3024 return f->filetype == directory || f->filetype == arg_directory;
3027 /* Put the name of the file that FILENAME is a symbolic link to
3028 into the LINKNAME field of `f'. COMMAND_LINE_ARG indicates whether
3029 FILENAME is a command-line argument. */
3031 static void
3032 get_link_name (char const *filename, struct fileinfo *f, bool command_line_arg)
3034 f->linkname = areadlink_with_size (filename, f->stat.st_size);
3035 if (f->linkname == NULL)
3036 file_failure (command_line_arg, _("cannot read symbolic link %s"),
3037 filename);
3040 /* If `linkname' is a relative name and `name' contains one or more
3041 leading directories, return `linkname' with those directories
3042 prepended; otherwise, return a copy of `linkname'.
3043 If `linkname' is zero, return zero. */
3045 static char *
3046 make_link_name (char const *name, char const *linkname)
3048 char *linkbuf;
3049 size_t bufsiz;
3051 if (!linkname)
3052 return NULL;
3054 if (*linkname == '/')
3055 return xstrdup (linkname);
3057 /* The link is to a relative name. Prepend any leading directory
3058 in `name' to the link name. */
3059 linkbuf = strrchr (name, '/');
3060 if (linkbuf == 0)
3061 return xstrdup (linkname);
3063 bufsiz = linkbuf - name + 1;
3064 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
3065 strncpy (linkbuf, name, bufsiz);
3066 strcpy (linkbuf + bufsiz, linkname);
3067 return linkbuf;
3070 /* Return true if the last component of NAME is `.' or `..'
3071 This is so we don't try to recurse on `././././. ...' */
3073 static bool
3074 basename_is_dot_or_dotdot (const char *name)
3076 char const *base = last_component (name);
3077 return dot_or_dotdot (base);
3080 /* Remove any entries from CWD_FILE that are for directories,
3081 and queue them to be listed as directories instead.
3082 DIRNAME is the prefix to prepend to each dirname
3083 to make it correct relative to ls's working dir;
3084 if it is null, no prefix is needed and "." and ".." should not be ignored.
3085 If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
3086 This is desirable when processing directories recursively. */
3088 static void
3089 extract_dirs_from_files (char const *dirname, bool command_line_arg)
3091 size_t i;
3092 size_t j;
3093 bool ignore_dot_and_dot_dot = (dirname != NULL);
3095 if (dirname && LOOP_DETECT)
3097 /* Insert a marker entry first. When we dequeue this marker entry,
3098 we'll know that DIRNAME has been processed and may be removed
3099 from the set of active directories. */
3100 queue_directory (NULL, dirname, false);
3103 /* Queue the directories last one first, because queueing reverses the
3104 order. */
3105 for (i = cwd_n_used; i-- != 0; )
3107 struct fileinfo *f = sorted_file[i];
3109 if (is_directory (f)
3110 && (! ignore_dot_and_dot_dot
3111 || ! basename_is_dot_or_dotdot (f->name)))
3113 if (!dirname || f->name[0] == '/')
3114 queue_directory (f->name, f->linkname, command_line_arg);
3115 else
3117 char *name = file_name_concat (dirname, f->name, NULL);
3118 queue_directory (name, f->linkname, command_line_arg);
3119 free (name);
3121 if (f->filetype == arg_directory)
3122 free (f->name);
3126 /* Now delete the directories from the table, compacting all the remaining
3127 entries. */
3129 for (i = 0, j = 0; i < cwd_n_used; i++)
3131 struct fileinfo *f = sorted_file[i];
3132 sorted_file[j] = f;
3133 j += (f->filetype != arg_directory);
3135 cwd_n_used = j;
3138 /* Use strcoll to compare strings in this locale. If an error occurs,
3139 report an error and longjmp to failed_strcoll. */
3141 static jmp_buf failed_strcoll;
3143 static int
3144 xstrcoll (char const *a, char const *b)
3146 int diff;
3147 errno = 0;
3148 diff = strcoll (a, b);
3149 if (errno)
3151 error (0, errno, _("cannot compare file names %s and %s"),
3152 quote_n (0, a), quote_n (1, b));
3153 set_exit_status (false);
3154 longjmp (failed_strcoll, 1);
3156 return diff;
3159 /* Comparison routines for sorting the files. */
3161 typedef void const *V;
3162 typedef int (*qsortFunc)(V a, V b);
3164 /* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants.
3165 The do { ... } while(0) makes it possible to use the macro more like
3166 a statement, without violating C89 rules: */
3167 #define DIRFIRST_CHECK(a, b) \
3168 do \
3170 bool a_is_dir = is_directory ((struct fileinfo const *) a); \
3171 bool b_is_dir = is_directory ((struct fileinfo const *) b); \
3172 if (a_is_dir && !b_is_dir) \
3173 return -1; /* a goes before b */ \
3174 if (!a_is_dir && b_is_dir) \
3175 return 1; /* b goes before a */ \
3177 while (0)
3179 /* Define the 8 different sort function variants required for each sortkey.
3180 KEY_NAME is a token describing the sort key, e.g., ctime, atime, size.
3181 KEY_CMP_FUNC is a function to compare records based on that key, e.g.,
3182 ctime_cmp, atime_cmp, size_cmp. Append KEY_NAME to the string,
3183 '[rev_][x]str{cmp|coll}[_df]_', to create each function name. */
3184 #define DEFINE_SORT_FUNCTIONS(key_name, key_cmp_func) \
3185 /* direct, non-dirfirst versions */ \
3186 static int xstrcoll_##key_name (V a, V b) \
3187 { return key_cmp_func (a, b, xstrcoll); } \
3188 static int strcmp_##key_name (V a, V b) \
3189 { return key_cmp_func (a, b, strcmp); } \
3191 /* reverse, non-dirfirst versions */ \
3192 static int rev_xstrcoll_##key_name (V a, V b) \
3193 { return key_cmp_func (b, a, xstrcoll); } \
3194 static int rev_strcmp_##key_name (V a, V b) \
3195 { return key_cmp_func (b, a, strcmp); } \
3197 /* direct, dirfirst versions */ \
3198 static int xstrcoll_df_##key_name (V a, V b) \
3199 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, xstrcoll); } \
3200 static int strcmp_df_##key_name (V a, V b) \
3201 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, strcmp); } \
3203 /* reverse, dirfirst versions */ \
3204 static int rev_xstrcoll_df_##key_name (V a, V b) \
3205 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, xstrcoll); } \
3206 static int rev_strcmp_df_##key_name (V a, V b) \
3207 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, strcmp); }
3209 static inline int
3210 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
3211 int (*cmp) (char const *, char const *))
3213 int diff = timespec_cmp (get_stat_ctime (&b->stat),
3214 get_stat_ctime (&a->stat));
3215 return diff ? diff : cmp (a->name, b->name);
3218 static inline int
3219 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
3220 int (*cmp) (char const *, char const *))
3222 int diff = timespec_cmp (get_stat_mtime (&b->stat),
3223 get_stat_mtime (&a->stat));
3224 return diff ? diff : cmp (a->name, b->name);
3227 static inline int
3228 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
3229 int (*cmp) (char const *, char const *))
3231 int diff = timespec_cmp (get_stat_atime (&b->stat),
3232 get_stat_atime (&a->stat));
3233 return diff ? diff : cmp (a->name, b->name);
3236 static inline int
3237 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
3238 int (*cmp) (char const *, char const *))
3240 int diff = longdiff (b->stat.st_size, a->stat.st_size);
3241 return diff ? diff : cmp (a->name, b->name);
3244 static inline int
3245 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
3246 int (*cmp) (char const *, char const *))
3248 return cmp (a->name, b->name);
3251 /* Compare file extensions. Files with no extension are `smallest'.
3252 If extensions are the same, compare by filenames instead. */
3254 static inline int
3255 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
3256 int (*cmp) (char const *, char const *))
3258 char const *base1 = strrchr (a->name, '.');
3259 char const *base2 = strrchr (b->name, '.');
3260 int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
3261 return diff ? diff : cmp (a->name, b->name);
3264 DEFINE_SORT_FUNCTIONS (ctime, cmp_ctime)
3265 DEFINE_SORT_FUNCTIONS (mtime, cmp_mtime)
3266 DEFINE_SORT_FUNCTIONS (atime, cmp_atime)
3267 DEFINE_SORT_FUNCTIONS (size, cmp_size)
3268 DEFINE_SORT_FUNCTIONS (name, cmp_name)
3269 DEFINE_SORT_FUNCTIONS (extension, cmp_extension)
3271 /* Compare file versions.
3272 Unlike all other compare functions above, cmp_version depends only
3273 on filevercmp, which does not fail (even for locale reasons), and does not
3274 need a secondary sort key. See lib/filevercmp.h for function description.
3276 All the other sort options, in fact, need xstrcoll and strcmp variants,
3277 because they all use a string comparison (either as the primary or secondary
3278 sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
3279 locale reasons. Lastly, filevercmp is ALWAYS available with gnulib. */
3280 static inline int
3281 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
3283 return filevercmp (a->name, b->name);
3286 static int xstrcoll_version (V a, V b)
3287 { return cmp_version (a, b); }
3288 static int rev_xstrcoll_version (V a, V b)
3289 { return cmp_version (b, a); }
3290 static int xstrcoll_df_version (V a, V b)
3291 { DIRFIRST_CHECK (a, b); return cmp_version (a, b); }
3292 static int rev_xstrcoll_df_version (V a, V b)
3293 { DIRFIRST_CHECK (a, b); return cmp_version (b, a); }
3296 /* We have 2^3 different variants for each sortkey function
3297 (for 3 independent sort modes).
3298 The function pointers stored in this array must be dereferenced as:
3300 sort_variants[sort_key][use_strcmp][reverse][dirs_first]
3302 Note that the order in which sortkeys are listed in the function pointer
3303 array below is defined by the order of the elements in the time_type and
3304 sort_type enums! */
3306 #define LIST_SORTFUNCTION_VARIANTS(key_name) \
3309 { xstrcoll_##key_name, xstrcoll_df_##key_name }, \
3310 { rev_xstrcoll_##key_name, rev_xstrcoll_df_##key_name }, \
3311 }, \
3313 { strcmp_##key_name, strcmp_df_##key_name }, \
3314 { rev_strcmp_##key_name, rev_strcmp_df_##key_name }, \
3318 static qsortFunc const sort_functions[][2][2][2] =
3320 LIST_SORTFUNCTION_VARIANTS (name),
3321 LIST_SORTFUNCTION_VARIANTS (extension),
3322 LIST_SORTFUNCTION_VARIANTS (size),
3326 { xstrcoll_version, xstrcoll_df_version },
3327 { rev_xstrcoll_version, rev_xstrcoll_df_version },
3330 /* We use NULL for the strcmp variants of version comparison
3331 since as explained in cmp_version definition, version comparison
3332 does not rely on xstrcoll, so it will never longjmp, and never
3333 need to try the strcmp fallback. */
3335 { NULL, NULL },
3336 { NULL, NULL },
3340 /* last are time sort functions */
3341 LIST_SORTFUNCTION_VARIANTS (mtime),
3342 LIST_SORTFUNCTION_VARIANTS (ctime),
3343 LIST_SORTFUNCTION_VARIANTS (atime)
3346 /* The number of sortkeys is calculated as
3347 the number of elements in the sort_type enum (i.e. sort_numtypes) +
3348 the number of elements in the time_type enum (i.e. time_numtypes) - 1
3349 This is because when sort_type==sort_time, we have up to
3350 time_numtypes possible sortkeys.
3352 This line verifies at compile-time that the array of sort functions has been
3353 initialized for all possible sortkeys. */
3354 verify (ARRAY_CARDINALITY (sort_functions)
3355 == sort_numtypes + time_numtypes - 1 );
3357 /* Set up SORTED_FILE to point to the in-use entries in CWD_FILE, in order. */
3359 static void
3360 initialize_ordering_vector (void)
3362 size_t i;
3363 for (i = 0; i < cwd_n_used; i++)
3364 sorted_file[i] = &cwd_file[i];
3367 /* Sort the files now in the table. */
3369 static void
3370 sort_files (void)
3372 bool use_strcmp;
3374 if (sorted_file_alloc < cwd_n_used + cwd_n_used / 2)
3376 free (sorted_file);
3377 sorted_file = xnmalloc (cwd_n_used, 3 * sizeof *sorted_file);
3378 sorted_file_alloc = 3 * cwd_n_used;
3381 initialize_ordering_vector ();
3383 if (sort_type == sort_none)
3384 return;
3386 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
3387 ignore strcoll failures, as a failing strcoll might be a
3388 comparison function that is not a total order, and if we ignored
3389 the failure this might cause qsort to dump core. */
3391 if (! setjmp (failed_strcoll))
3392 use_strcmp = false; /* strcoll() succeeded */
3393 else
3395 use_strcmp = true;
3396 assert (sort_type != sort_version);
3397 initialize_ordering_vector ();
3400 /* When sort_type == sort_time, use time_type as subindex. */
3401 mpsort ((void const **) sorted_file, cwd_n_used,
3402 sort_functions[sort_type + (sort_type == sort_time ? time_type : 0)]
3403 [use_strcmp][sort_reverse]
3404 [directories_first]);
3407 /* List all the files now in the table. */
3409 static void
3410 print_current_files (void)
3412 size_t i;
3414 switch (format)
3416 case one_per_line:
3417 for (i = 0; i < cwd_n_used; i++)
3419 print_file_name_and_frills (sorted_file[i], 0);
3420 putchar ('\n');
3422 break;
3424 case many_per_line:
3425 print_many_per_line ();
3426 break;
3428 case horizontal:
3429 print_horizontal ();
3430 break;
3432 case with_commas:
3433 print_with_commas ();
3434 break;
3436 case long_format:
3437 for (i = 0; i < cwd_n_used; i++)
3439 print_long_format (sorted_file[i]);
3440 DIRED_PUTCHAR ('\n');
3442 break;
3446 /* Replace the first %b with precomputed aligned month names.
3447 Note on glibc-2.7 at least, this speeds up the whole `ls -lU`
3448 process by around 17%, compared to letting strftime() handle the %b. */
3450 static size_t
3451 align_nstrftime (char *buf, size_t size, char const *fmt, struct tm const *tm,
3452 int __utc, int __ns)
3454 const char *nfmt = fmt;
3455 /* In the unlikely event that rpl_fmt below is not large enough,
3456 the replacement is not done. A malloc here slows ls down by 2% */
3457 char rpl_fmt[sizeof (abmon[0]) + 100];
3458 const char *pb;
3459 if (required_mon_width && (pb = strstr (fmt, "%b")))
3461 if (strlen (fmt) < (sizeof (rpl_fmt) - sizeof (abmon[0]) + 2))
3463 char *pfmt = rpl_fmt;
3464 nfmt = rpl_fmt;
3466 pfmt = mempcpy (pfmt, fmt, pb - fmt);
3467 pfmt = stpcpy (pfmt, abmon[tm->tm_mon]);
3468 strcpy (pfmt, pb + 2);
3471 size_t ret = nstrftime (buf, size, nfmt, tm, __utc, __ns);
3472 return ret;
3475 /* Return the expected number of columns in a long-format time stamp,
3476 or zero if it cannot be calculated. */
3478 static int
3479 long_time_expected_width (void)
3481 static int width = -1;
3483 if (width < 0)
3485 time_t epoch = 0;
3486 struct tm const *tm = localtime (&epoch);
3487 char buf[TIME_STAMP_LEN_MAXIMUM + 1];
3489 /* In case you're wondering if localtime can fail with an input time_t
3490 value of 0, let's just say it's very unlikely, but not inconceivable.
3491 The TZ environment variable would have to specify a time zone that
3492 is 2**31-1900 years or more ahead of UTC. This could happen only on
3493 a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
3494 However, this is not possible with Solaris 10 or glibc-2.3.5, since
3495 their implementations limit the offset to 167:59 and 24:00, resp. */
3496 if (tm)
3498 size_t len =
3499 align_nstrftime (buf, sizeof buf, long_time_format[0], tm, 0, 0);
3500 if (len != 0)
3501 width = mbsnwidth (buf, len, 0);
3504 if (width < 0)
3505 width = 0;
3508 return width;
3511 /* Print the user or group name NAME, with numeric id ID, using a
3512 print width of WIDTH columns. */
3514 static void
3515 format_user_or_group (char const *name, unsigned long int id, int width)
3517 size_t len;
3519 if (name)
3521 int width_gap = width - mbswidth (name, 0);
3522 int pad = MAX (0, width_gap);
3523 fputs (name, stdout);
3524 len = strlen (name) + pad;
3527 putchar (' ');
3528 while (pad--);
3530 else
3532 printf ("%*lu ", width, id);
3533 len = width;
3536 dired_pos += len + 1;
3539 /* Print the name or id of the user with id U, using a print width of
3540 WIDTH. */
3542 static void
3543 format_user (uid_t u, int width, bool stat_ok)
3545 format_user_or_group (! stat_ok ? "?" :
3546 (numeric_ids ? NULL : getuser (u)), u, width);
3549 /* Likewise, for groups. */
3551 static void
3552 format_group (gid_t g, int width, bool stat_ok)
3554 format_user_or_group (! stat_ok ? "?" :
3555 (numeric_ids ? NULL : getgroup (g)), g, width);
3558 /* Return the number of columns that format_user_or_group will print. */
3560 static int
3561 format_user_or_group_width (char const *name, unsigned long int id)
3563 if (name)
3565 int len = mbswidth (name, 0);
3566 return MAX (0, len);
3568 else
3570 char buf[INT_BUFSIZE_BOUND (unsigned long int)];
3571 sprintf (buf, "%lu", id);
3572 return strlen (buf);
3576 /* Return the number of columns that format_user will print. */
3578 static int
3579 format_user_width (uid_t u)
3581 return format_user_or_group_width (numeric_ids ? NULL : getuser (u), u);
3584 /* Likewise, for groups. */
3586 static int
3587 format_group_width (gid_t g)
3589 return format_user_or_group_width (numeric_ids ? NULL : getgroup (g), g);
3592 /* Return a pointer to a formatted version of F->stat.st_ino,
3593 possibly using buffer, BUF, of length BUFLEN, which must be at least
3594 INT_BUFSIZE_BOUND (uintmax_t) bytes. */
3595 static char *
3596 format_inode (char *buf, size_t buflen, const struct fileinfo *f)
3598 assert (INT_BUFSIZE_BOUND (uintmax_t) <= buflen);
3599 return (f->stat_ok && f->stat.st_ino != NOT_AN_INODE_NUMBER
3600 ? umaxtostr (f->stat.st_ino, buf)
3601 : (char *) "?");
3604 /* Print information about F in long format. */
3605 static void
3606 print_long_format (const struct fileinfo *f)
3608 char modebuf[12];
3609 char buf
3610 [LONGEST_HUMAN_READABLE + 1 /* inode */
3611 + LONGEST_HUMAN_READABLE + 1 /* size in blocks */
3612 + sizeof (modebuf) - 1 + 1 /* mode string */
3613 + INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
3614 + LONGEST_HUMAN_READABLE + 2 /* major device number */
3615 + LONGEST_HUMAN_READABLE + 1 /* minor device number */
3616 + TIME_STAMP_LEN_MAXIMUM + 1 /* max length of time/date */
3618 size_t s;
3619 char *p;
3620 struct timespec when_timespec;
3621 struct tm *when_local;
3623 /* Compute the mode string, except remove the trailing space if no
3624 file in this directory has an ACL or SELinux security context. */
3625 if (f->stat_ok)
3626 filemodestring (&f->stat, modebuf);
3627 else
3629 modebuf[0] = filetype_letter[f->filetype];
3630 memset (modebuf + 1, '?', 10);
3631 modebuf[11] = '\0';
3633 if (! any_has_acl)
3634 modebuf[10] = '\0';
3635 else if (f->acl_type == ACL_T_SELINUX_ONLY)
3636 modebuf[10] = '.';
3637 else if (f->acl_type == ACL_T_YES)
3638 modebuf[10] = '+';
3640 switch (time_type)
3642 case time_ctime:
3643 when_timespec = get_stat_ctime (&f->stat);
3644 break;
3645 case time_mtime:
3646 when_timespec = get_stat_mtime (&f->stat);
3647 break;
3648 case time_atime:
3649 when_timespec = get_stat_atime (&f->stat);
3650 break;
3651 default:
3652 abort ();
3655 p = buf;
3657 if (print_inode)
3659 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3660 sprintf (p, "%*s ", inode_number_width,
3661 format_inode (hbuf, sizeof hbuf, f));
3662 /* Increment by strlen (p) here, rather than by inode_number_width + 1.
3663 The latter is wrong when inode_number_width is zero. */
3664 p += strlen (p);
3667 if (print_block_size)
3669 char hbuf[LONGEST_HUMAN_READABLE + 1];
3670 char const *blocks =
3671 (! f->stat_ok
3672 ? "?"
3673 : human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts,
3674 ST_NBLOCKSIZE, output_block_size));
3675 int pad;
3676 for (pad = block_size_width - mbswidth (blocks, 0); 0 < pad; pad--)
3677 *p++ = ' ';
3678 while ((*p++ = *blocks++))
3679 continue;
3680 p[-1] = ' ';
3683 /* The last byte of the mode string is the POSIX
3684 "optional alternate access method flag". */
3686 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3687 sprintf (p, "%s %*s ", modebuf, nlink_width,
3688 ! f->stat_ok ? "?" : umaxtostr (f->stat.st_nlink, hbuf));
3690 /* Increment by strlen (p) here, rather than by, e.g.,
3691 sizeof modebuf - 2 + any_has_acl + 1 + nlink_width + 1.
3692 The latter is wrong when nlink_width is zero. */
3693 p += strlen (p);
3695 DIRED_INDENT ();
3697 if (print_owner || print_group || print_author || print_scontext)
3699 DIRED_FPUTS (buf, stdout, p - buf);
3701 if (print_owner)
3702 format_user (f->stat.st_uid, owner_width, f->stat_ok);
3704 if (print_group)
3705 format_group (f->stat.st_gid, group_width, f->stat_ok);
3707 if (print_author)
3708 format_user (f->stat.st_author, author_width, f->stat_ok);
3710 if (print_scontext)
3711 format_user_or_group (f->scontext, 0, scontext_width);
3713 p = buf;
3716 if (f->stat_ok
3717 && (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode)))
3719 char majorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3720 char minorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3721 int blanks_width = (file_size_width
3722 - (major_device_number_width + 2
3723 + minor_device_number_width));
3724 sprintf (p, "%*s, %*s ",
3725 major_device_number_width + MAX (0, blanks_width),
3726 umaxtostr (major (f->stat.st_rdev), majorbuf),
3727 minor_device_number_width,
3728 umaxtostr (minor (f->stat.st_rdev), minorbuf));
3729 p += file_size_width + 1;
3731 else
3733 char hbuf[LONGEST_HUMAN_READABLE + 1];
3734 char const *size =
3735 (! f->stat_ok
3736 ? "?"
3737 : human_readable (unsigned_file_size (f->stat.st_size),
3738 hbuf, human_output_opts, 1, file_output_block_size));
3739 int pad;
3740 for (pad = file_size_width - mbswidth (size, 0); 0 < pad; pad--)
3741 *p++ = ' ';
3742 while ((*p++ = *size++))
3743 continue;
3744 p[-1] = ' ';
3747 when_local = localtime (&when_timespec.tv_sec);
3748 s = 0;
3749 *p = '\1';
3751 if (f->stat_ok && when_local)
3753 struct timespec six_months_ago;
3754 bool recent;
3755 char const *fmt;
3757 /* If the file appears to be in the future, update the current
3758 time, in case the file happens to have been modified since
3759 the last time we checked the clock. */
3760 if (timespec_cmp (current_time, when_timespec) < 0)
3762 /* Note that gettime may call gettimeofday which, on some non-
3763 compliant systems, clobbers the buffer used for localtime's result.
3764 But it's ok here, because we use a gettimeofday wrapper that
3765 saves and restores the buffer around the gettimeofday call. */
3766 gettime (&current_time);
3769 /* Consider a time to be recent if it is within the past six
3770 months. A Gregorian year has 365.2425 * 24 * 60 * 60 ==
3771 31556952 seconds on the average. Write this value as an
3772 integer constant to avoid floating point hassles. */
3773 six_months_ago.tv_sec = current_time.tv_sec - 31556952 / 2;
3774 six_months_ago.tv_nsec = current_time.tv_nsec;
3776 recent = (timespec_cmp (six_months_ago, when_timespec) < 0
3777 && (timespec_cmp (when_timespec, current_time) < 0));
3778 fmt = long_time_format[recent];
3780 /* We assume here that all time zones are offset from UTC by a
3781 whole number of seconds. */
3782 s = align_nstrftime (p, TIME_STAMP_LEN_MAXIMUM + 1, fmt,
3783 when_local, 0, when_timespec.tv_nsec);
3786 if (s || !*p)
3788 p += s;
3789 *p++ = ' ';
3791 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
3792 *p = '\0';
3794 else
3796 /* The time cannot be converted using the desired format, so
3797 print it as a huge integer number of seconds. */
3798 char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
3799 sprintf (p, "%*s ", long_time_expected_width (),
3800 (! f->stat_ok
3801 ? "?"
3802 : timetostr (when_timespec.tv_sec, hbuf)));
3803 /* FIXME: (maybe) We discarded when_timespec.tv_nsec. */
3804 p += strlen (p);
3807 DIRED_FPUTS (buf, stdout, p - buf);
3808 size_t w = print_name_with_quoting (f, false, &dired_obstack, p - buf);
3810 if (f->filetype == symbolic_link)
3812 if (f->linkname)
3814 DIRED_FPUTS_LITERAL (" -> ", stdout);
3815 print_name_with_quoting (f, true, NULL, (p - buf) + w + 4);
3816 if (indicator_style != none)
3817 print_type_indicator (true, f->linkmode, unknown);
3820 else if (indicator_style != none)
3821 print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
3824 /* Output to OUT a quoted representation of the file name NAME,
3825 using OPTIONS to control quoting. Produce no output if OUT is NULL.
3826 Store the number of screen columns occupied by NAME's quoted
3827 representation into WIDTH, if non-NULL. Return the number of bytes
3828 produced. */
3830 static size_t
3831 quote_name (FILE *out, const char *name, struct quoting_options const *options,
3832 size_t *width)
3834 char smallbuf[BUFSIZ];
3835 size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, name, -1, options);
3836 char *buf;
3837 size_t displayed_width IF_LINT (= 0);
3839 if (len < sizeof smallbuf)
3840 buf = smallbuf;
3841 else
3843 buf = alloca (len + 1);
3844 quotearg_buffer (buf, len + 1, name, -1, options);
3847 if (qmark_funny_chars)
3849 if (MB_CUR_MAX > 1)
3851 char const *p = buf;
3852 char const *plimit = buf + len;
3853 char *q = buf;
3854 displayed_width = 0;
3856 while (p < plimit)
3857 switch (*p)
3859 case ' ': case '!': case '"': case '#': case '%':
3860 case '&': case '\'': case '(': case ')': case '*':
3861 case '+': case ',': case '-': case '.': case '/':
3862 case '0': case '1': case '2': case '3': case '4':
3863 case '5': case '6': case '7': case '8': case '9':
3864 case ':': case ';': case '<': case '=': case '>':
3865 case '?':
3866 case 'A': case 'B': case 'C': case 'D': case 'E':
3867 case 'F': case 'G': case 'H': case 'I': case 'J':
3868 case 'K': case 'L': case 'M': case 'N': case 'O':
3869 case 'P': case 'Q': case 'R': case 'S': case 'T':
3870 case 'U': case 'V': case 'W': case 'X': case 'Y':
3871 case 'Z':
3872 case '[': case '\\': case ']': case '^': case '_':
3873 case 'a': case 'b': case 'c': case 'd': case 'e':
3874 case 'f': case 'g': case 'h': case 'i': case 'j':
3875 case 'k': case 'l': case 'm': case 'n': case 'o':
3876 case 'p': case 'q': case 'r': case 's': case 't':
3877 case 'u': case 'v': case 'w': case 'x': case 'y':
3878 case 'z': case '{': case '|': case '}': case '~':
3879 /* These characters are printable ASCII characters. */
3880 *q++ = *p++;
3881 displayed_width += 1;
3882 break;
3883 default:
3884 /* If we have a multibyte sequence, copy it until we
3885 reach its end, replacing each non-printable multibyte
3886 character with a single question mark. */
3888 DECLARE_ZEROED_AGGREGATE (mbstate_t, mbstate);
3891 wchar_t wc;
3892 size_t bytes;
3893 int w;
3895 bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
3897 if (bytes == (size_t) -1)
3899 /* An invalid multibyte sequence was
3900 encountered. Skip one input byte, and
3901 put a question mark. */
3902 p++;
3903 *q++ = '?';
3904 displayed_width += 1;
3905 break;
3908 if (bytes == (size_t) -2)
3910 /* An incomplete multibyte character
3911 at the end. Replace it entirely with
3912 a question mark. */
3913 p = plimit;
3914 *q++ = '?';
3915 displayed_width += 1;
3916 break;
3919 if (bytes == 0)
3920 /* A null wide character was encountered. */
3921 bytes = 1;
3923 w = wcwidth (wc);
3924 if (w >= 0)
3926 /* A printable multibyte character.
3927 Keep it. */
3928 for (; bytes > 0; --bytes)
3929 *q++ = *p++;
3930 displayed_width += w;
3932 else
3934 /* An unprintable multibyte character.
3935 Replace it entirely with a question
3936 mark. */
3937 p += bytes;
3938 *q++ = '?';
3939 displayed_width += 1;
3942 while (! mbsinit (&mbstate));
3944 break;
3947 /* The buffer may have shrunk. */
3948 len = q - buf;
3950 else
3952 char *p = buf;
3953 char const *plimit = buf + len;
3955 while (p < plimit)
3957 if (! isprint (to_uchar (*p)))
3958 *p = '?';
3959 p++;
3961 displayed_width = len;
3964 else if (width != NULL)
3966 if (MB_CUR_MAX > 1)
3967 displayed_width = mbsnwidth (buf, len, 0);
3968 else
3970 char const *p = buf;
3971 char const *plimit = buf + len;
3973 displayed_width = 0;
3974 while (p < plimit)
3976 if (isprint (to_uchar (*p)))
3977 displayed_width++;
3978 p++;
3983 if (out != NULL)
3984 fwrite (buf, 1, len, out);
3985 if (width != NULL)
3986 *width = displayed_width;
3987 return len;
3990 static size_t
3991 print_name_with_quoting (const struct fileinfo *f,
3992 bool symlink_target,
3993 struct obstack *stack,
3994 size_t start_col)
3996 const char* name = symlink_target ? f->linkname : f->name;
3998 bool used_color_this_time
3999 = (print_with_color && print_color_indicator (f, symlink_target));
4001 if (stack)
4002 PUSH_CURRENT_DIRED_POS (stack);
4004 size_t width = quote_name (stdout, name, filename_quoting_options, NULL);
4005 dired_pos += width;
4007 if (stack)
4008 PUSH_CURRENT_DIRED_POS (stack);
4010 if (used_color_this_time)
4012 process_signals ();
4013 prep_non_filename_text ();
4014 if (start_col / line_length != (start_col + width - 1) / line_length)
4015 put_indicator (&color_indicator[C_CLR_TO_EOL]);
4018 return width;
4021 static void
4022 prep_non_filename_text (void)
4024 if (color_indicator[C_END].string != NULL)
4025 put_indicator (&color_indicator[C_END]);
4026 else
4028 put_indicator (&color_indicator[C_LEFT]);
4029 put_indicator (&color_indicator[C_RESET]);
4030 put_indicator (&color_indicator[C_RIGHT]);
4034 /* Print the file name of `f' with appropriate quoting.
4035 Also print file size, inode number, and filetype indicator character,
4036 as requested by switches. */
4038 static size_t
4039 print_file_name_and_frills (const struct fileinfo *f, size_t start_col)
4041 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
4043 if (print_inode)
4044 printf ("%*s ", format == with_commas ? 0 : inode_number_width,
4045 format_inode (buf, sizeof buf, f));
4047 if (print_block_size)
4048 printf ("%*s ", format == with_commas ? 0 : block_size_width,
4049 ! f->stat_ok ? "?"
4050 : human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts,
4051 ST_NBLOCKSIZE, output_block_size));
4053 if (print_scontext)
4054 printf ("%*s ", format == with_commas ? 0 : scontext_width, f->scontext);
4056 size_t width = print_name_with_quoting (f, false, NULL, start_col);
4058 if (indicator_style != none)
4059 width += print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4061 return width;
4064 /* Given these arguments describing a file, return the single-byte
4065 type indicator, or 0. */
4066 static char
4067 get_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
4069 char c;
4071 if (stat_ok ? S_ISREG (mode) : type == normal)
4073 if (stat_ok && indicator_style == classify && (mode & S_IXUGO))
4074 c = '*';
4075 else
4076 c = 0;
4078 else
4080 if (stat_ok ? S_ISDIR (mode) : type == directory || type == arg_directory)
4081 c = '/';
4082 else if (indicator_style == slash)
4083 c = 0;
4084 else if (stat_ok ? S_ISLNK (mode) : type == symbolic_link)
4085 c = '@';
4086 else if (stat_ok ? S_ISFIFO (mode) : type == fifo)
4087 c = '|';
4088 else if (stat_ok ? S_ISSOCK (mode) : type == sock)
4089 c = '=';
4090 else if (stat_ok && S_ISDOOR (mode))
4091 c = '>';
4092 else
4093 c = 0;
4095 return c;
4098 static bool
4099 print_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
4101 char c = get_type_indicator (stat_ok, mode, type);
4102 if (c)
4103 DIRED_PUTCHAR (c);
4104 return !!c;
4107 /* Returns whether any color sequence was printed. */
4108 static bool
4109 print_color_indicator (const struct fileinfo *f, bool symlink_target)
4111 enum indicator_no type;
4112 struct color_ext_type *ext; /* Color extension */
4113 size_t len; /* Length of name */
4115 const char* name;
4116 mode_t mode;
4117 int linkok;
4118 if (symlink_target)
4120 name = f->linkname;
4121 mode = f->linkmode;
4122 linkok = f->linkok - 1;
4124 else
4126 name = f->name;
4127 mode = FILE_OR_LINK_MODE (f);
4128 linkok = f->linkok;
4131 /* Is this a nonexistent file? If so, linkok == -1. */
4133 if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
4134 type = C_MISSING;
4135 else if (!f->stat_ok)
4137 static enum indicator_no filetype_indicator[] = FILETYPE_INDICATORS;
4138 type = filetype_indicator[f->filetype];
4140 else
4142 if (S_ISREG (mode))
4144 type = C_FILE;
4146 if ((mode & S_ISUID) != 0 && is_colored (C_SETUID))
4147 type = C_SETUID;
4148 else if ((mode & S_ISGID) != 0 && is_colored (C_SETGID))
4149 type = C_SETGID;
4150 else if (is_colored (C_CAP) && f->has_capability)
4151 type = C_CAP;
4152 else if ((mode & S_IXUGO) != 0 && is_colored (C_EXEC))
4153 type = C_EXEC;
4154 else if ((1 < f->stat.st_nlink) && is_colored (C_MULTIHARDLINK))
4155 type = C_MULTIHARDLINK;
4157 else if (S_ISDIR (mode))
4159 type = C_DIR;
4161 if ((mode & S_ISVTX) && (mode & S_IWOTH)
4162 && is_colored (C_STICKY_OTHER_WRITABLE))
4163 type = C_STICKY_OTHER_WRITABLE;
4164 else if ((mode & S_IWOTH) != 0 && is_colored (C_OTHER_WRITABLE))
4165 type = C_OTHER_WRITABLE;
4166 else if ((mode & S_ISVTX) != 0 && is_colored (C_STICKY))
4167 type = C_STICKY;
4169 else if (S_ISLNK (mode))
4170 type = ((!linkok
4171 && (!strncmp (color_indicator[C_LINK].string, "target", 6)
4172 || color_indicator[C_ORPHAN].string))
4173 ? C_ORPHAN : C_LINK);
4174 else if (S_ISFIFO (mode))
4175 type = C_FIFO;
4176 else if (S_ISSOCK (mode))
4177 type = C_SOCK;
4178 else if (S_ISBLK (mode))
4179 type = C_BLK;
4180 else if (S_ISCHR (mode))
4181 type = C_CHR;
4182 else if (S_ISDOOR (mode))
4183 type = C_DOOR;
4184 else
4186 /* Classify a file of some other type as C_ORPHAN. */
4187 type = C_ORPHAN;
4191 /* Check the file's suffix only if still classified as C_FILE. */
4192 ext = NULL;
4193 if (type == C_FILE)
4195 /* Test if NAME has a recognized suffix. */
4197 len = strlen (name);
4198 name += len; /* Pointer to final \0. */
4199 for (ext = color_ext_list; ext != NULL; ext = ext->next)
4201 if (ext->ext.len <= len
4202 && strncmp (name - ext->ext.len, ext->ext.string,
4203 ext->ext.len) == 0)
4204 break;
4209 const struct bin_str *const s
4210 = ext ? &(ext->seq) : &color_indicator[type];
4211 if (s->string != NULL)
4213 put_indicator (&color_indicator[C_LEFT]);
4214 put_indicator (s);
4215 put_indicator (&color_indicator[C_RIGHT]);
4216 return true;
4218 else
4219 return false;
4223 /* Output a color indicator (which may contain nulls). */
4224 static void
4225 put_indicator (const struct bin_str *ind)
4227 if (! used_color)
4229 used_color = true;
4230 prep_non_filename_text ();
4233 fwrite (ind->string, ind->len, 1, stdout);
4236 static size_t
4237 length_of_file_name_and_frills (const struct fileinfo *f)
4239 size_t len = 0;
4240 size_t name_width;
4241 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
4243 if (print_inode)
4244 len += 1 + (format == with_commas
4245 ? strlen (umaxtostr (f->stat.st_ino, buf))
4246 : inode_number_width);
4248 if (print_block_size)
4249 len += 1 + (format == with_commas
4250 ? strlen (! f->stat_ok ? "?"
4251 : human_readable (ST_NBLOCKS (f->stat), buf,
4252 human_output_opts, ST_NBLOCKSIZE,
4253 output_block_size))
4254 : block_size_width);
4256 if (print_scontext)
4257 len += 1 + (format == with_commas ? strlen (f->scontext) : scontext_width);
4259 quote_name (NULL, f->name, filename_quoting_options, &name_width);
4260 len += name_width;
4262 if (indicator_style != none)
4264 char c = get_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4265 len += (c != 0);
4268 return len;
4271 static void
4272 print_many_per_line (void)
4274 size_t row; /* Current row. */
4275 size_t cols = calculate_columns (true);
4276 struct column_info const *line_fmt = &column_info[cols - 1];
4278 /* Calculate the number of rows that will be in each column except possibly
4279 for a short column on the right. */
4280 size_t rows = cwd_n_used / cols + (cwd_n_used % cols != 0);
4282 for (row = 0; row < rows; row++)
4284 size_t col = 0;
4285 size_t filesno = row;
4286 size_t pos = 0;
4288 /* Print the next row. */
4289 while (1)
4291 struct fileinfo const *f = sorted_file[filesno];
4292 size_t name_length = length_of_file_name_and_frills (f);
4293 size_t max_name_length = line_fmt->col_arr[col++];
4294 print_file_name_and_frills (f, pos);
4296 filesno += rows;
4297 if (filesno >= cwd_n_used)
4298 break;
4300 indent (pos + name_length, pos + max_name_length);
4301 pos += max_name_length;
4303 putchar ('\n');
4307 static void
4308 print_horizontal (void)
4310 size_t filesno;
4311 size_t pos = 0;
4312 size_t cols = calculate_columns (false);
4313 struct column_info const *line_fmt = &column_info[cols - 1];
4314 struct fileinfo const *f = sorted_file[0];
4315 size_t name_length = length_of_file_name_and_frills (f);
4316 size_t max_name_length = line_fmt->col_arr[0];
4318 /* Print first entry. */
4319 print_file_name_and_frills (f, 0);
4321 /* Now the rest. */
4322 for (filesno = 1; filesno < cwd_n_used; ++filesno)
4324 size_t col = filesno % cols;
4326 if (col == 0)
4328 putchar ('\n');
4329 pos = 0;
4331 else
4333 indent (pos + name_length, pos + max_name_length);
4334 pos += max_name_length;
4337 f = sorted_file[filesno];
4338 print_file_name_and_frills (f, pos);
4340 name_length = length_of_file_name_and_frills (f);
4341 max_name_length = line_fmt->col_arr[col];
4343 putchar ('\n');
4346 static void
4347 print_with_commas (void)
4349 size_t filesno;
4350 size_t pos = 0;
4352 for (filesno = 0; filesno < cwd_n_used; filesno++)
4354 struct fileinfo const *f = sorted_file[filesno];
4355 size_t len = length_of_file_name_and_frills (f);
4357 if (filesno != 0)
4359 char separator;
4361 if (pos + len + 2 < line_length)
4363 pos += 2;
4364 separator = ' ';
4366 else
4368 pos = 0;
4369 separator = '\n';
4372 putchar (',');
4373 putchar (separator);
4376 print_file_name_and_frills (f, pos);
4377 pos += len;
4379 putchar ('\n');
4382 /* Assuming cursor is at position FROM, indent up to position TO.
4383 Use a TAB character instead of two or more spaces whenever possible. */
4385 static void
4386 indent (size_t from, size_t to)
4388 while (from < to)
4390 if (tabsize != 0 && to / tabsize > (from + 1) / tabsize)
4392 putchar ('\t');
4393 from += tabsize - from % tabsize;
4395 else
4397 putchar (' ');
4398 from++;
4403 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
4404 /* FIXME: maybe remove this function someday. See about using a
4405 non-malloc'ing version of file_name_concat. */
4407 static void
4408 attach (char *dest, const char *dirname, const char *name)
4410 const char *dirnamep = dirname;
4412 /* Copy dirname if it is not ".". */
4413 if (dirname[0] != '.' || dirname[1] != 0)
4415 while (*dirnamep)
4416 *dest++ = *dirnamep++;
4417 /* Add '/' if `dirname' doesn't already end with it. */
4418 if (dirnamep > dirname && dirnamep[-1] != '/')
4419 *dest++ = '/';
4421 while (*name)
4422 *dest++ = *name++;
4423 *dest = 0;
4426 /* Allocate enough column info suitable for the current number of
4427 files and display columns, and initialize the info to represent the
4428 narrowest possible columns. */
4430 static void
4431 init_column_info (void)
4433 size_t i;
4434 size_t max_cols = MIN (max_idx, cwd_n_used);
4436 /* Currently allocated columns in column_info. */
4437 static size_t column_info_alloc;
4439 if (column_info_alloc < max_cols)
4441 size_t new_column_info_alloc;
4442 size_t *p;
4444 if (max_cols < max_idx / 2)
4446 /* The number of columns is far less than the display width
4447 allows. Grow the allocation, but only so that it's
4448 double the current requirements. If the display is
4449 extremely wide, this avoids allocating a lot of memory
4450 that is never needed. */
4451 column_info = xnrealloc (column_info, max_cols,
4452 2 * sizeof *column_info);
4453 new_column_info_alloc = 2 * max_cols;
4455 else
4457 column_info = xnrealloc (column_info, max_idx, sizeof *column_info);
4458 new_column_info_alloc = max_idx;
4461 /* Allocate the new size_t objects by computing the triangle
4462 formula n * (n + 1) / 2, except that we don't need to
4463 allocate the part of the triangle that we've already
4464 allocated. Check for address arithmetic overflow. */
4466 size_t column_info_growth = new_column_info_alloc - column_info_alloc;
4467 size_t s = column_info_alloc + 1 + new_column_info_alloc;
4468 size_t t = s * column_info_growth;
4469 if (s < new_column_info_alloc || t / column_info_growth != s)
4470 xalloc_die ();
4471 p = xnmalloc (t / 2, sizeof *p);
4474 /* Grow the triangle by parceling out the cells just allocated. */
4475 for (i = column_info_alloc; i < new_column_info_alloc; i++)
4477 column_info[i].col_arr = p;
4478 p += i + 1;
4481 column_info_alloc = new_column_info_alloc;
4484 for (i = 0; i < max_cols; ++i)
4486 size_t j;
4488 column_info[i].valid_len = true;
4489 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
4490 for (j = 0; j <= i; ++j)
4491 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
4495 /* Calculate the number of columns needed to represent the current set
4496 of files in the current display width. */
4498 static size_t
4499 calculate_columns (bool by_columns)
4501 size_t filesno; /* Index into cwd_file. */
4502 size_t cols; /* Number of files across. */
4504 /* Normally the maximum number of columns is determined by the
4505 screen width. But if few files are available this might limit it
4506 as well. */
4507 size_t max_cols = MIN (max_idx, cwd_n_used);
4509 init_column_info ();
4511 /* Compute the maximum number of possible columns. */
4512 for (filesno = 0; filesno < cwd_n_used; ++filesno)
4514 struct fileinfo const *f = sorted_file[filesno];
4515 size_t name_length = length_of_file_name_and_frills (f);
4516 size_t i;
4518 for (i = 0; i < max_cols; ++i)
4520 if (column_info[i].valid_len)
4522 size_t idx = (by_columns
4523 ? filesno / ((cwd_n_used + i) / (i + 1))
4524 : filesno % (i + 1));
4525 size_t real_length = name_length + (idx == i ? 0 : 2);
4527 if (column_info[i].col_arr[idx] < real_length)
4529 column_info[i].line_len += (real_length
4530 - column_info[i].col_arr[idx]);
4531 column_info[i].col_arr[idx] = real_length;
4532 column_info[i].valid_len = (column_info[i].line_len
4533 < line_length);
4539 /* Find maximum allowed columns. */
4540 for (cols = max_cols; 1 < cols; --cols)
4542 if (column_info[cols - 1].valid_len)
4543 break;
4546 return cols;
4549 void
4550 usage (int status)
4552 if (status != EXIT_SUCCESS)
4553 fprintf (stderr, _("Try `%s --help' for more information.\n"),
4554 program_name);
4555 else
4557 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
4558 fputs (_("\
4559 List information about the FILEs (the current directory by default).\n\
4560 Sort entries alphabetically if none of -cftuvSUX nor --sort.\n\
4562 "), stdout);
4563 fputs (_("\
4564 Mandatory arguments to long options are mandatory for short options too.\n\
4565 "), stdout);
4566 fputs (_("\
4567 -a, --all do not ignore entries starting with .\n\
4568 -A, --almost-all do not list implied . and ..\n\
4569 --author with -l, print the author of each file\n\
4570 -b, --escape print octal escapes for nongraphic characters\n\
4571 "), stdout);
4572 fputs (_("\
4573 --block-size=SIZE use SIZE-byte blocks. See SIZE format below\n\
4574 -B, --ignore-backups do not list implied entries ending with ~\n\
4575 -c with -lt: sort by, and show, ctime (time of last\n\
4576 modification of file status information)\n\
4577 with -l: show ctime and sort by name\n\
4578 otherwise: sort by ctime\n\
4579 "), stdout);
4580 fputs (_("\
4581 -C list entries by columns\n\
4582 --color[=WHEN] colorize the output. WHEN defaults to `always'\n\
4583 or can be `never' or `auto'. More info below\n\
4584 -d, --directory list directory entries instead of contents,\n\
4585 and do not dereference symbolic links\n\
4586 -D, --dired generate output designed for Emacs' dired mode\n\
4587 "), stdout);
4588 fputs (_("\
4589 -f do not sort, enable -aU, disable -ls --color\n\
4590 -F, --classify append indicator (one of */=>@|) to entries\n\
4591 --file-type likewise, except do not append `*'\n\
4592 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
4593 single-column -1, verbose -l, vertical -C\n\
4594 --full-time like -l --time-style=full-iso\n\
4595 "), stdout);
4596 fputs (_("\
4597 -g like -l, but do not list owner\n\
4598 "), stdout);
4599 fputs (_("\
4600 --group-directories-first\n\
4601 group directories before files.\n\
4602 augment with a --sort option, but any\n\
4603 use of --sort=none (-U) disables grouping\n\
4604 "), stdout);
4605 fputs (_("\
4606 -G, --no-group in a long listing, don't print group names\n\
4607 -h, --human-readable with -l, print sizes in human readable format\n\
4608 (e.g., 1K 234M 2G)\n\
4609 --si likewise, but use powers of 1000 not 1024\n\
4610 "), stdout);
4611 fputs (_("\
4612 -H, --dereference-command-line\n\
4613 follow symbolic links listed on the command line\n\
4614 --dereference-command-line-symlink-to-dir\n\
4615 follow each command line symbolic link\n\
4616 that points to a directory\n\
4617 --hide=PATTERN do not list implied entries matching shell PATTERN\n\
4618 (overridden by -a or -A)\n\
4619 "), stdout);
4620 fputs (_("\
4621 --indicator-style=WORD append indicator with style WORD to entry names:\n\
4622 none (default), slash (-p),\n\
4623 file-type (--file-type), classify (-F)\n\
4624 -i, --inode print the index number of each file\n\
4625 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
4626 -k like --block-size=1K\n\
4627 "), stdout);
4628 fputs (_("\
4629 -l use a long listing format\n\
4630 -L, --dereference when showing file information for a symbolic\n\
4631 link, show information for the file the link\n\
4632 references rather than for the link itself\n\
4633 -m fill width with a comma separated list of entries\n\
4634 "), stdout);
4635 fputs (_("\
4636 -n, --numeric-uid-gid like -l, but list numeric user and group IDs\n\
4637 -N, --literal print raw entry names (don't treat e.g. control\n\
4638 characters specially)\n\
4639 -o like -l, but do not list group information\n\
4640 -p, --indicator-style=slash\n\
4641 append / indicator to directories\n\
4642 "), stdout);
4643 fputs (_("\
4644 -q, --hide-control-chars print ? instead of non graphic characters\n\
4645 --show-control-chars show non graphic characters as-is (default\n\
4646 unless program is `ls' and output is a terminal)\n\
4647 -Q, --quote-name enclose entry names in double quotes\n\
4648 --quoting-style=WORD use quoting style WORD for entry names:\n\
4649 literal, locale, shell, shell-always, c, escape\n\
4650 "), stdout);
4651 fputs (_("\
4652 -r, --reverse reverse order while sorting\n\
4653 -R, --recursive list subdirectories recursively\n\
4654 -s, --size print the allocated size of each file, in blocks\n\
4655 "), stdout);
4656 fputs (_("\
4657 -S sort by file size\n\
4658 --sort=WORD sort by WORD instead of name: none -U,\n\
4659 extension -X, size -S, time -t, version -v\n\
4660 --time=WORD with -l, show time as WORD instead of modification\n\
4661 time: atime -u, access -u, use -u, ctime -c,\n\
4662 or status -c; use specified time as sort key\n\
4663 if --sort=time\n\
4664 "), stdout);
4665 fputs (_("\
4666 --time-style=STYLE with -l, show times using style STYLE:\n\
4667 full-iso, long-iso, iso, locale, +FORMAT.\n\
4668 FORMAT is interpreted like `date'; if FORMAT is\n\
4669 FORMAT1<newline>FORMAT2, FORMAT1 applies to\n\
4670 non-recent files and FORMAT2 to recent files;\n\
4671 if STYLE is prefixed with `posix-', STYLE\n\
4672 takes effect only outside the POSIX locale\n\
4673 "), stdout);
4674 fputs (_("\
4675 -t sort by modification time\n\
4676 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
4677 "), stdout);
4678 fputs (_("\
4679 -u with -lt: sort by, and show, access time\n\
4680 with -l: show access time and sort by name\n\
4681 otherwise: sort by access time\n\
4682 -U do not sort; list entries in directory order\n\
4683 -v natural sort of (version) numbers within text\n\
4684 "), stdout);
4685 fputs (_("\
4686 -w, --width=COLS assume screen width instead of current value\n\
4687 -x list entries by lines instead of by columns\n\
4688 -X sort alphabetically by entry extension\n\
4689 -Z, --context print any SELinux security context of each file\n\
4690 -1 list one file per line\n\
4691 "), stdout);
4692 fputs (HELP_OPTION_DESCRIPTION, stdout);
4693 fputs (VERSION_OPTION_DESCRIPTION, stdout);
4694 emit_size_note ();
4695 fputs (_("\
4697 Using color to distinguish file types is disabled both by default and\n\
4698 with --color=never. With --color=auto, ls emits color codes only when\n\
4699 standard output is connected to a terminal. The LS_COLORS environment\n\
4700 variable can change the settings. Use the dircolors command to set it.\n\
4701 "), stdout);
4702 fputs (_("\
4704 Exit status:\n\
4705 0 if OK,\n\
4706 1 if minor problems (e.g., cannot access subdirectory),\n\
4707 2 if serious trouble (e.g., cannot access command-line argument).\n\
4708 "), stdout);
4709 emit_ancillary_info ();
4711 exit (status);