1 /* `dir', `vdir' and `ls' directory listing programs for GNU.
2 Copyright (C) 85, 88, 90, 91, 1995-2008 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* If ls_mode is LS_MULTI_COL,
18 the multi-column format is the default regardless
19 of the type of output device.
20 This is for the `dir' program.
22 If ls_mode is LS_LONG_FORMAT,
23 the long format is the default regardless of the
24 type of output device.
25 This is for the `vdir' program.
28 the output format depends on whether the output
30 This is for the `ls' program. */
32 /* Written by Richard Stallman and David MacKenzie. */
34 /* Color support by Peter Anvin <Peter.Anvin@linux.org> and Dennis
35 Flaherty <dennisf@denix.elk.miles.com> based on original patches by
36 Greg Lee <lee@uhunix.uhcc.hawaii.edu>. */
39 #include <sys/types.h>
42 # include <sys/capability.h>
52 # include <sys/ioctl.h>
55 #ifdef WINSIZE_IN_PTEM
56 # include <sys/stream.h>
57 # include <sys/ptem.h>
67 #include <selinux/selinux.h>
70 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
73 # define SA_NOCLDSTOP 0
74 # define sigprocmask(How, Set, Oset) /* empty */
76 # if ! HAVE_SIGINTERRUPT
77 # define siginterrupt(sig, flag) /* empty */
92 #include "filenamecat.h"
93 #include "hard-locale.h"
100 #include "mbswidth.h"
104 #include "quotearg.h"
106 #include "stat-time.h"
107 #include "strftime.h"
109 #include "areadlink.h"
111 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
112 : (ls_mode == LS_MULTI_COL \
116 proper_name ("Richard M. Stallman"), \
117 proper_name ("David MacKenzie")
119 #define obstack_chunk_alloc malloc
120 #define obstack_chunk_free free
122 /* Return an int indicating the result of comparing two integers.
123 Subtracting doesn't always work, due to overflow. */
124 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
126 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
127 # define st_author st_uid
144 /* Display letters and indicators for each filetype.
145 Keep these in sync with enum filetype. */
146 static char const filetype_letter[] = "?pcdb-lswd";
148 /* Ensure that filetype and filetype_letter have the same
149 number of elements. */
150 verify (sizeof filetype_letter - 1 == arg_directory + 1);
152 #define FILETYPE_INDICATORS \
154 C_ORPHAN, C_FIFO, C_CHR, C_DIR, C_BLK, C_FILE, \
155 C_LINK, C_SOCK, C_FILE, C_DIR \
164 /* For symbolic link, name of the file linked to, otherwise zero. */
169 enum filetype filetype;
171 /* For symbolic link and long listing, st_mode of file linked to, otherwise
175 /* SELinux security context. */
176 security_context_t scontext;
180 /* For symbolic link and color printing, true if linked-to file
181 exists, otherwise false. */
184 /* For long listings, true if the file has an access control list,
185 or an SELinux security context. */
189 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
191 /* Null is a valid character in a color indicator (think about Epson
192 printers, for example) so we have to use a length/buffer string
197 size_t len; /* Number of bytes */
198 const char *string; /* Pointer to the same */
202 # define tcgetpgrp(Fd) 0
205 static size_t quote_name (FILE *out, const char *name,
206 struct quoting_options const *options,
208 static char *make_link_name (char const *name, char const *linkname);
209 static int decode_switches (int argc, char **argv);
210 static bool file_ignored (char const *name);
211 static uintmax_t gobble_file (char const *name, enum filetype type,
212 ino_t inode, bool command_line_arg,
213 char const *dirname);
214 static bool print_color_indicator (const char *name, mode_t mode, int linkok,
215 bool stat_ok, enum filetype type);
216 static void put_indicator (const struct bin_str *ind);
217 static void add_ignore_pattern (const char *pattern);
218 static void attach (char *dest, const char *dirname, const char *name);
219 static void clear_files (void);
220 static void extract_dirs_from_files (char const *dirname,
221 bool command_line_arg);
222 static void get_link_name (char const *filename, struct fileinfo *f,
223 bool command_line_arg);
224 static void indent (size_t from, size_t to);
225 static size_t calculate_columns (bool by_columns);
226 static void print_current_files (void);
227 static void print_dir (char const *name, char const *realname,
228 bool command_line_arg);
229 static void print_file_name_and_frills (const struct fileinfo *f);
230 static void print_horizontal (void);
231 static int format_user_width (uid_t u);
232 static int format_group_width (gid_t g);
233 static void print_long_format (const struct fileinfo *f);
234 static void print_many_per_line (void);
235 static void print_name_with_quoting (const char *p, mode_t mode,
236 int linkok, bool stat_ok,
238 struct obstack *stack);
239 static void prep_non_filename_text (void);
240 static void print_type_indicator (bool stat_ok, mode_t mode,
242 static void print_with_commas (void);
243 static void queue_directory (char const *name, char const *realname,
244 bool command_line_arg);
245 static void sort_files (void);
246 static void parse_ls_color (void);
247 void usage (int status);
249 /* Initial size of hash table.
250 Most hierarchies are likely to be shallower than this. */
251 #define INITIAL_TABLE_SIZE 30
253 /* The set of `active' directories, from the current command-line argument
254 to the level in the hierarchy at which files are being listed.
255 A directory is represented by its device and inode numbers (struct dev_ino).
256 A directory is added to this set when ls begins listing it or its
257 entries, and it is removed from the set just after ls has finished
258 processing it. This set is used solely to detect loops, e.g., with
259 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
260 static Hash_table *active_dir_set;
262 #define LOOP_DETECT (!!active_dir_set)
264 /* The table of files in the current directory:
266 `cwd_file' points to a vector of `struct fileinfo', one per file.
267 `cwd_n_alloc' is the number of elements space has been allocated for.
268 `cwd_n_used' is the number actually in use. */
270 /* Address of block containing the files that are described. */
271 static struct fileinfo *cwd_file;
273 /* Length of block that `cwd_file' points to, measured in files. */
274 static size_t cwd_n_alloc;
276 /* Index of first unused slot in `cwd_file'. */
277 static size_t cwd_n_used;
279 /* Vector of pointers to files, in proper sorted order, and the number
280 of entries allocated for it. */
281 static void **sorted_file;
282 static size_t sorted_file_alloc;
284 /* When true, in a color listing, color each symlink name according to the
285 type of file it points to. Otherwise, color them according to the `ln'
286 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
287 regardless. This is set when `ln=target' appears in LS_COLORS. */
289 static bool color_symlink_as_referent;
291 /* mode of appropriate file for colorization */
292 #define FILE_OR_LINK_MODE(File) \
293 ((color_symlink_as_referent & (File)->linkok) \
294 ? (File)->linkmode : (File)->stat.st_mode)
297 /* Record of one pending directory waiting to be listed. */
302 /* If the directory is actually the file pointed to by a symbolic link we
303 were told to list, `realname' will contain the name of the symbolic
304 link, otherwise zero. */
306 bool command_line_arg;
307 struct pending *next;
310 static struct pending *pending_dirs;
312 /* Current time in seconds and nanoseconds since 1970, updated as
313 needed when deciding whether a file is recent. */
315 static struct timespec current_time;
317 static bool print_scontext;
318 static char UNKNOWN_SECURITY_CONTEXT[] = "?";
320 /* Whether any of the files has an ACL. This affects the width of the
323 static bool any_has_acl;
325 /* The number of columns to use for columns containing inode numbers,
326 block sizes, link counts, owners, groups, authors, major device
327 numbers, minor device numbers, and file sizes, respectively. */
329 static int inode_number_width;
330 static int block_size_width;
331 static int nlink_width;
332 static int scontext_width;
333 static int owner_width;
334 static int group_width;
335 static int author_width;
336 static int major_device_number_width;
337 static int minor_device_number_width;
338 static int file_size_width;
342 /* long_format for lots of info, one per line.
343 one_per_line for just names, one per line.
344 many_per_line for just names, many per line, sorted vertically.
345 horizontal for just names, many per line, sorted horizontally.
346 with_commas for just names, many per line, separated by commas.
348 -l (and other options that imply -l), -1, -C, -x and -m control
353 long_format, /* -l and other options that imply -l */
354 one_per_line, /* -1 */
355 many_per_line, /* -C */
360 static enum format format;
362 /* `full-iso' uses full ISO-style dates and times. `long-iso' uses longer
363 ISO-style time stamps, though shorter than `full-iso'. `iso' uses shorter
364 ISO-style time stamps. `locale' uses locale-dependent time stamps. */
367 full_iso_time_style, /* --time-style=full-iso */
368 long_iso_time_style, /* --time-style=long-iso */
369 iso_time_style, /* --time-style=iso */
370 locale_time_style /* --time-style=locale */
373 static char const *const time_style_args[] =
375 "full-iso", "long-iso", "iso", "locale", NULL
377 static enum time_style const time_style_types[] =
379 full_iso_time_style, long_iso_time_style, iso_time_style,
382 ARGMATCH_VERIFY (time_style_args, time_style_types);
384 /* Type of time to print or sort by. Controlled by -c and -u.
385 The values of each item of this enum are important since they are
386 used as indices in the sort functions array (see sort_files()). */
390 time_mtime, /* default */
393 time_numtypes /* the number of elements of this enum */
396 static enum time_type time_type;
398 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v.
399 The values of each item of this enum are important since they are
400 used as indices in the sort functions array (see sort_files()). */
404 sort_none = -1, /* -U */
405 sort_name, /* default */
406 sort_extension, /* -X */
408 sort_version, /* -v */
410 sort_numtypes /* the number of elements of this enum */
413 static enum sort_type sort_type;
415 /* Direction of sort.
416 false means highest first if numeric,
417 lowest first if alphabetic;
418 these are the defaults.
419 true means the opposite order in each case. -r */
421 static bool sort_reverse;
423 /* True means to display owner information. -g turns this off. */
425 static bool print_owner = true;
427 /* True means to display author information. */
429 static bool print_author;
431 /* True means to display group information. -G and -o turn this off. */
433 static bool print_group = true;
435 /* True means print the user and group id's as numbers rather
438 static bool numeric_ids;
440 /* True means mention the size in blocks of each file. -s */
442 static bool print_block_size;
444 /* Human-readable options for output. */
445 static int human_output_opts;
447 /* The units to use when printing sizes other than file sizes. */
448 static uintmax_t output_block_size;
450 /* Likewise, but for file sizes. */
451 static uintmax_t file_output_block_size = 1;
453 /* Follow the output with a special string. Using this format,
454 Emacs' dired mode starts up twice as fast, and can handle all
455 strange characters in file names. */
458 /* `none' means don't mention the type of files.
459 `slash' means mention directories only, with a '/'.
460 `file_type' means mention file types.
461 `classify' means mention file types and mark executables.
463 Controlled by -F, -p, and --indicator-style. */
467 none, /* --indicator-style=none */
468 slash, /* -p, --indicator-style=slash */
469 file_type, /* --indicator-style=file-type */
470 classify /* -F, --indicator-style=classify */
473 static enum indicator_style indicator_style;
475 /* Names of indicator styles. */
476 static char const *const indicator_style_args[] =
478 "none", "slash", "file-type", "classify", NULL
480 static enum indicator_style const indicator_style_types[] =
482 none, slash, file_type, classify
484 ARGMATCH_VERIFY (indicator_style_args, indicator_style_types);
486 /* True means use colors to mark types. Also define the different
487 colors as well as the stuff for the LS_COLORS environment variable.
488 The LS_COLORS variable is now in a termcap-like format. */
490 static bool print_with_color;
492 /* Whether we used any colors in the output so far. If so, we will
493 need to restore the default color later. If not, we will need to
494 call prep_non_filename_text before using color for the first time. */
496 static bool used_color = false;
500 color_never, /* 0: default or --color=never */
501 color_always, /* 1: --color=always */
502 color_if_tty /* 2: --color=tty */
505 enum Dereference_symlink
509 DEREF_COMMAND_LINE_ARGUMENTS, /* -H */
510 DEREF_COMMAND_LINE_SYMLINK_TO_DIR, /* the default, in certain cases */
511 DEREF_ALWAYS /* -L */
516 C_LEFT, C_RIGHT, C_END, C_RESET, C_NORM, C_FILE, C_DIR, C_LINK,
518 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR, C_SETUID, C_SETGID,
519 C_STICKY, C_OTHER_WRITABLE, C_STICKY_OTHER_WRITABLE, C_CAP
522 static const char *const indicator_name[]=
524 "lc", "rc", "ec", "rs", "no", "fi", "di", "ln", "pi", "so",
525 "bd", "cd", "mi", "or", "ex", "do", "su", "sg", "st",
526 "ow", "tw", "ca", NULL
529 struct color_ext_type
531 struct bin_str ext; /* The extension we're looking for */
532 struct bin_str seq; /* The sequence to output when we do */
533 struct color_ext_type *next; /* Next in list */
536 static struct bin_str color_indicator[] =
538 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
539 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
540 { 0, NULL }, /* ec: End color (replaces lc+no+rc) */
541 { LEN_STR_PAIR ("0") }, /* rs: Reset to ordinary colors */
542 { 0, NULL }, /* no: Normal */
543 { 0, NULL }, /* fi: File: default */
544 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
545 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
546 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
547 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
548 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
549 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
550 { 0, NULL }, /* mi: Missing file: undefined */
551 { 0, NULL }, /* or: Orphaned symlink: undefined */
552 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
553 { LEN_STR_PAIR ("01;35") }, /* do: Door: bright magenta */
554 { LEN_STR_PAIR ("37;41") }, /* su: setuid: white on red */
555 { LEN_STR_PAIR ("30;43") }, /* sg: setgid: black on yellow */
556 { LEN_STR_PAIR ("37;44") }, /* st: sticky: black on blue */
557 { LEN_STR_PAIR ("34;42") }, /* ow: other-writable: blue on green */
558 { LEN_STR_PAIR ("30;42") }, /* tw: ow w/ sticky: black on green */
559 { LEN_STR_PAIR ("30;41") }, /* capability: black on red */
563 static struct color_ext_type *color_ext_list = NULL;
565 /* Buffer for color sequences */
566 static char *color_buf;
568 /* True means to check for orphaned symbolic link, for displaying
571 static bool check_symlink_color;
573 /* True means mention the inode number of each file. -i */
575 static bool print_inode;
577 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
578 other options that imply -l), and -L. */
580 static enum Dereference_symlink dereference;
582 /* True means when a directory is found, display info on its
585 static bool recursive;
587 /* True means when an argument is a directory name, display info
590 static bool immediate_dirs;
592 /* True means that directories are grouped before files. */
594 static bool directories_first;
596 /* Which files to ignore. */
600 /* Ignore files whose names start with `.', and files specified by
601 --hide and --ignore. */
604 /* Ignore `.', `..', and files specified by --ignore. */
605 IGNORE_DOT_AND_DOTDOT,
607 /* Ignore only files specified by --ignore. */
611 /* A linked list of shell-style globbing patterns. If a non-argument
612 file name matches any of these patterns, it is ignored.
613 Controlled by -I. Multiple -I options accumulate.
614 The -B option adds `*~' and `.*~' to this list. */
616 struct ignore_pattern
619 struct ignore_pattern *next;
622 static struct ignore_pattern *ignore_patterns;
624 /* Similar to IGNORE_PATTERNS, except that -a or -A causes this
625 variable itself to be ignored. */
626 static struct ignore_pattern *hide_patterns;
628 /* True means output nongraphic chars in file names as `?'.
629 (-q, --hide-control-chars)
630 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
631 independent. The algorithm is: first, obey the quoting style to get a
632 string representing the file name; then, if qmark_funny_chars is set,
633 replace all nonprintable chars in that string with `?'. It's necessary
634 to replace nonprintable chars even in quoted strings, because we don't
635 want to mess up the terminal if control chars get sent to it, and some
636 quoting methods pass through control chars as-is. */
637 static bool qmark_funny_chars;
639 /* Quoting options for file and dir name output. */
641 static struct quoting_options *filename_quoting_options;
642 static struct quoting_options *dirname_quoting_options;
644 /* The number of chars per hardware tab stop. Setting this to zero
645 inhibits the use of TAB characters for separating columns. -T */
646 static size_t tabsize;
648 /* True means print each directory name before listing it. */
650 static bool print_dir_name;
652 /* The line length to use for breaking lines in many-per-line format.
653 Can be set with -w. */
655 static size_t line_length;
657 /* If true, the file listing format requires that stat be called on
660 static bool format_needs_stat;
662 /* Similar to `format_needs_stat', but set if only the file type is
665 static bool format_needs_type;
667 /* An arbitrary limit on the number of bytes in a printed time stamp.
668 This is set to a relatively small value to avoid the need to worry
669 about denial-of-service attacks on servers that run "ls" on behalf
670 of remote clients. 1000 bytes should be enough for any practical
671 time stamp format. */
673 enum { TIME_STAMP_LEN_MAXIMUM = MAX (1000, INT_STRLEN_BOUND (time_t)) };
675 /* strftime formats for non-recent and recent files, respectively, in
678 static char const *long_time_format[2] =
680 /* strftime format for non-recent files (older than 6 months), in
681 -l output. This should contain the year, month and day (at
682 least), in an order that is understood by people in your
683 locale's territory. Please try to keep the number of used
684 screen columns small, because many people work in windows with
685 only 80 columns. But make this as wide as the other string
686 below, for recent files. */
688 /* strftime format for recent files (younger than 6 months), in -l
689 output. This should contain the month, day and time (at
690 least), in an order that is understood by people in your
691 locale's territory. Please try to keep the number of used
692 screen columns small, because many people work in windows with
693 only 80 columns. But make this as wide as the other string
694 above, for non-recent files. */
698 /* The set of signals that are caught. */
700 static sigset_t caught_signals;
702 /* If nonzero, the value of the pending fatal signal. */
704 static sig_atomic_t volatile interrupt_signal;
706 /* A count of the number of pending stop signals that have been received. */
708 static sig_atomic_t volatile stop_signal_count;
710 /* Desired exit status. */
712 static int exit_status;
717 /* "ls" had a minor problem (e.g., it could not stat a directory
719 LS_MINOR_PROBLEM = 1,
721 /* "ls" had more serious trouble. */
725 /* For long options that have no equivalent short option, use a
726 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
729 AUTHOR_OPTION = CHAR_MAX + 1,
732 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION,
733 FILE_TYPE_INDICATOR_OPTION,
736 GROUP_DIRECTORIES_FIRST_OPTION,
738 INDICATOR_STYLE_OPTION,
739 QUOTING_STYLE_OPTION,
740 SHOW_CONTROL_CHARS_OPTION,
747 static struct option const long_options[] =
749 {"all", no_argument, NULL, 'a'},
750 {"escape", no_argument, NULL, 'b'},
751 {"directory", no_argument, NULL, 'd'},
752 {"dired", no_argument, NULL, 'D'},
753 {"full-time", no_argument, NULL, FULL_TIME_OPTION},
754 {"group-directories-first", no_argument, NULL,
755 GROUP_DIRECTORIES_FIRST_OPTION},
756 {"human-readable", no_argument, NULL, 'h'},
757 {"inode", no_argument, NULL, 'i'},
758 {"numeric-uid-gid", no_argument, NULL, 'n'},
759 {"no-group", no_argument, NULL, 'G'},
760 {"hide-control-chars", no_argument, NULL, 'q'},
761 {"reverse", no_argument, NULL, 'r'},
762 {"size", no_argument, NULL, 's'},
763 {"width", required_argument, NULL, 'w'},
764 {"almost-all", no_argument, NULL, 'A'},
765 {"ignore-backups", no_argument, NULL, 'B'},
766 {"classify", no_argument, NULL, 'F'},
767 {"file-type", no_argument, NULL, FILE_TYPE_INDICATOR_OPTION},
768 {"si", no_argument, NULL, SI_OPTION},
769 {"dereference-command-line", no_argument, NULL, 'H'},
770 {"dereference-command-line-symlink-to-dir", no_argument, NULL,
771 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION},
772 {"hide", required_argument, NULL, HIDE_OPTION},
773 {"ignore", required_argument, NULL, 'I'},
774 {"indicator-style", required_argument, NULL, INDICATOR_STYLE_OPTION},
775 {"dereference", no_argument, NULL, 'L'},
776 {"literal", no_argument, NULL, 'N'},
777 {"quote-name", no_argument, NULL, 'Q'},
778 {"quoting-style", required_argument, NULL, QUOTING_STYLE_OPTION},
779 {"recursive", no_argument, NULL, 'R'},
780 {"format", required_argument, NULL, FORMAT_OPTION},
781 {"show-control-chars", no_argument, NULL, SHOW_CONTROL_CHARS_OPTION},
782 {"sort", required_argument, NULL, SORT_OPTION},
783 {"tabsize", required_argument, NULL, 'T'},
784 {"time", required_argument, NULL, TIME_OPTION},
785 {"time-style", required_argument, NULL, TIME_STYLE_OPTION},
786 {"color", optional_argument, NULL, COLOR_OPTION},
787 {"block-size", required_argument, NULL, BLOCK_SIZE_OPTION},
788 {"context", no_argument, 0, 'Z'},
789 {"author", no_argument, NULL, AUTHOR_OPTION},
790 {GETOPT_HELP_OPTION_DECL},
791 {GETOPT_VERSION_OPTION_DECL},
795 static char const *const format_args[] =
797 "verbose", "long", "commas", "horizontal", "across",
798 "vertical", "single-column", NULL
800 static enum format const format_types[] =
802 long_format, long_format, with_commas, horizontal, horizontal,
803 many_per_line, one_per_line
805 ARGMATCH_VERIFY (format_args, format_types);
807 static char const *const sort_args[] =
809 "none", "time", "size", "extension", "version", NULL
811 static enum sort_type const sort_types[] =
813 sort_none, sort_time, sort_size, sort_extension, sort_version
815 ARGMATCH_VERIFY (sort_args, sort_types);
817 static char const *const time_args[] =
819 "atime", "access", "use", "ctime", "status", NULL
821 static enum time_type const time_types[] =
823 time_atime, time_atime, time_atime, time_ctime, time_ctime
825 ARGMATCH_VERIFY (time_args, time_types);
827 static char const *const color_args[] =
829 /* force and none are for compatibility with another color-ls version */
830 "always", "yes", "force",
831 "never", "no", "none",
832 "auto", "tty", "if-tty", NULL
834 static enum color_type const color_types[] =
836 color_always, color_always, color_always,
837 color_never, color_never, color_never,
838 color_if_tty, color_if_tty, color_if_tty
840 ARGMATCH_VERIFY (color_args, color_types);
842 /* Information about filling a column. */
850 /* Array with information about column filledness. */
851 static struct column_info *column_info;
853 /* Maximum number of columns ever possible for this display. */
854 static size_t max_idx;
856 /* The minimum width of a column is 3: 1 character for the name and 2
857 for the separating white space. */
858 #define MIN_COLUMN_WIDTH 3
861 /* This zero-based index is used solely with the --dired option.
862 When that option is in effect, this counter is incremented for each
863 byte of output generated by this program so that the beginning
864 and ending indices (in that output) of every file name can be recorded
865 and later output themselves. */
866 static size_t dired_pos;
868 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
870 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
871 #define DIRED_FPUTS(s, stream, s_len) \
872 do {fputs (s, stream); dired_pos += s_len;} while (0)
874 /* Like DIRED_FPUTS, but for use when S is a literal string. */
875 #define DIRED_FPUTS_LITERAL(s, stream) \
876 do {fputs (s, stream); dired_pos += sizeof (s) - 1;} while (0)
878 #define DIRED_INDENT() \
882 DIRED_FPUTS_LITERAL (" ", stdout); \
886 /* With --dired, store pairs of beginning and ending indices of filenames. */
887 static struct obstack dired_obstack;
889 /* With --dired, store pairs of beginning and ending indices of any
890 directory names that appear as headers (just before `total' line)
891 for lists of directory entries. Such directory names are seen when
892 listing hierarchies using -R and when a directory is listed with at
893 least one other command line argument. */
894 static struct obstack subdired_obstack;
896 /* Save the current index on the specified obstack, OBS. */
897 #define PUSH_CURRENT_DIRED_POS(obs) \
901 obstack_grow (obs, &dired_pos, sizeof (dired_pos)); \
905 /* With -R, this stack is used to help detect directory cycles.
906 The device/inode pairs on this stack mirror the pairs in the
907 active_dir_set hash table. */
908 static struct obstack dev_ino_obstack;
910 /* Push a pair onto the device/inode stack. */
911 #define DEV_INO_PUSH(Dev, Ino) \
914 struct dev_ino *di; \
915 obstack_blank (&dev_ino_obstack, sizeof (struct dev_ino)); \
916 di = -1 + (struct dev_ino *) obstack_next_free (&dev_ino_obstack); \
917 di->st_dev = (Dev); \
918 di->st_ino = (Ino); \
922 /* Pop a dev/ino struct off the global dev_ino_obstack
923 and return that struct. */
924 static struct dev_ino
927 assert (sizeof (struct dev_ino) <= obstack_object_size (&dev_ino_obstack));
928 obstack_blank (&dev_ino_obstack, -(int) (sizeof (struct dev_ino)));
929 return *(struct dev_ino *) obstack_next_free (&dev_ino_obstack);
932 #define ASSERT_MATCHING_DEV_INO(Name, Di) \
937 assert (0 <= stat (Name, &sb)); \
938 assert (sb.st_dev == Di.st_dev); \
939 assert (sb.st_ino == Di.st_ino); \
944 /* Write to standard output PREFIX, followed by the quoting style and
945 a space-separated list of the integers stored in OS all on one line. */
948 dired_dump_obstack (const char *prefix, struct obstack *os)
952 n_pos = obstack_object_size (os) / sizeof (dired_pos);
958 pos = (size_t *) obstack_finish (os);
959 fputs (prefix, stdout);
960 for (i = 0; i < n_pos; i++)
961 printf (" %lu", (unsigned long int) pos[i]);
967 dev_ino_hash (void const *x, size_t table_size)
969 struct dev_ino const *p = x;
970 return (uintmax_t) p->st_ino % table_size;
974 dev_ino_compare (void const *x, void const *y)
976 struct dev_ino const *a = x;
977 struct dev_ino const *b = y;
978 return SAME_INODE (*a, *b) ? true : false;
982 dev_ino_free (void *x)
987 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
988 active directories. Return true if there is already a matching
989 entry in the table. */
992 visit_dir (dev_t dev, ino_t ino)
995 struct dev_ino *ent_from_table;
998 ent = xmalloc (sizeof *ent);
1002 /* Attempt to insert this entry into the table. */
1003 ent_from_table = hash_insert (active_dir_set, ent);
1005 if (ent_from_table == NULL)
1007 /* Insertion failed due to lack of memory. */
1011 found_match = (ent_from_table != ent);
1015 /* ent was not inserted, so free it. */
1023 free_pending_ent (struct pending *p)
1031 is_colored (enum indicator_no type)
1033 size_t len = color_indicator[type].len;
1034 char const *s = color_indicator[type].string;
1036 || (len == 1 && strncmp (s, "0", 1) == 0)
1037 || (len == 2 && strncmp (s, "00", 2) == 0));
1041 restore_default_color (void)
1043 put_indicator (&color_indicator[C_LEFT]);
1044 put_indicator (&color_indicator[C_RIGHT]);
1047 /* An ordinary signal was received; arrange for the program to exit. */
1050 sighandler (int sig)
1053 signal (sig, SIG_IGN);
1054 if (! interrupt_signal)
1055 interrupt_signal = sig;
1058 /* A SIGTSTP was received; arrange for the program to suspend itself. */
1061 stophandler (int sig)
1064 signal (sig, stophandler);
1065 if (! interrupt_signal)
1066 stop_signal_count++;
1069 /* Process any pending signals. If signals are caught, this function
1070 should be called periodically. Ideally there should never be an
1071 unbounded amount of time when signals are not being processed.
1072 Signal handling can restore the default colors, so callers must
1073 immediately change colors after invoking this function. */
1076 process_signals (void)
1078 while (interrupt_signal | stop_signal_count)
1085 restore_default_color ();
1088 sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
1090 /* Reload interrupt_signal and stop_signal_count, in case a new
1091 signal was handled before sigprocmask took effect. */
1092 sig = interrupt_signal;
1093 stops = stop_signal_count;
1095 /* SIGTSTP is special, since the application can receive that signal
1096 more than once. In this case, don't set the signal handler to the
1097 default. Instead, just raise the uncatchable SIGSTOP. */
1100 stop_signal_count = stops - 1;
1104 signal (sig, SIG_DFL);
1106 /* Exit or suspend the program. */
1108 sigprocmask (SIG_SETMASK, &oldset, NULL);
1110 /* If execution reaches here, then the program has been
1111 continued (after being suspended). */
1116 main (int argc, char **argv)
1119 struct pending *thispend;
1122 /* The signals that are trapped, and the number of such signals. */
1123 static int const sig[] =
1125 /* This one is handled specially. */
1128 /* The usual suspects. */
1129 SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM,
1146 enum { nsigs = sizeof sig / sizeof sig[0] };
1149 bool caught_sig[nsigs];
1152 initialize_main (&argc, &argv);
1153 set_program_name (argv[0]);
1154 setlocale (LC_ALL, "");
1155 bindtextdomain (PACKAGE, LOCALEDIR);
1156 textdomain (PACKAGE);
1158 initialize_exit_failure (LS_FAILURE);
1159 atexit (close_stdout);
1161 #define N_ENTRIES(Array) (sizeof Array / sizeof *(Array))
1162 assert (N_ENTRIES (color_indicator) + 1 == N_ENTRIES (indicator_name));
1164 exit_status = EXIT_SUCCESS;
1165 print_dir_name = true;
1166 pending_dirs = NULL;
1168 current_time.tv_sec = TYPE_MINIMUM (time_t);
1169 current_time.tv_nsec = -1;
1171 i = decode_switches (argc, argv);
1173 if (print_with_color)
1176 /* Test print_with_color again, because the call to parse_ls_color
1177 may have just reset it -- e.g., if LS_COLORS is invalid. */
1178 if (print_with_color)
1180 /* Avoid following symbolic links when possible. */
1181 if (is_colored (C_ORPHAN)
1182 || (is_colored (C_EXEC) && color_symlink_as_referent)
1183 || (is_colored (C_MISSING) && format == long_format))
1184 check_symlink_color = true;
1186 /* If the standard output is a controlling terminal, watch out
1187 for signals, so that the colors can be restored to the
1188 default state if "ls" is suspended or interrupted. */
1190 if (0 <= tcgetpgrp (STDOUT_FILENO))
1194 struct sigaction act;
1196 sigemptyset (&caught_signals);
1197 for (j = 0; j < nsigs; j++)
1199 sigaction (sig[j], NULL, &act);
1200 if (act.sa_handler != SIG_IGN)
1201 sigaddset (&caught_signals, sig[j]);
1204 act.sa_mask = caught_signals;
1205 act.sa_flags = SA_RESTART;
1207 for (j = 0; j < nsigs; j++)
1208 if (sigismember (&caught_signals, sig[j]))
1210 act.sa_handler = sig[j] == SIGTSTP ? stophandler : sighandler;
1211 sigaction (sig[j], &act, NULL);
1214 for (j = 0; j < nsigs; j++)
1216 caught_sig[j] = (signal (sig[j], SIG_IGN) != SIG_IGN);
1219 signal (sig[j], sig[j] == SIGTSTP ? stophandler : sighandler);
1220 siginterrupt (sig[j], 0);
1227 if (dereference == DEREF_UNDEFINED)
1228 dereference = ((immediate_dirs
1229 || indicator_style == classify
1230 || format == long_format)
1232 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
1234 /* When using -R, initialize a data structure we'll use to
1235 detect any directory cycles. */
1238 active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, NULL,
1242 if (active_dir_set == NULL)
1245 obstack_init (&dev_ino_obstack);
1248 format_needs_stat = sort_type == sort_time || sort_type == sort_size
1249 || format == long_format
1251 || print_block_size;
1252 format_needs_type = (! format_needs_stat
1255 || indicator_style != none
1256 || directories_first));
1260 obstack_init (&dired_obstack);
1261 obstack_init (&subdired_obstack);
1265 cwd_file = xnmalloc (cwd_n_alloc, sizeof *cwd_file);
1275 gobble_file (".", directory, NOT_AN_INODE_NUMBER, true, "");
1277 queue_directory (".", NULL, true);
1281 gobble_file (argv[i++], unknown, NOT_AN_INODE_NUMBER, true, "");
1287 if (!immediate_dirs)
1288 extract_dirs_from_files (NULL, true);
1289 /* `cwd_n_used' might be zero now. */
1292 /* In the following if/else blocks, it is sufficient to test `pending_dirs'
1293 (and not pending_dirs->name) because there may be no markers in the queue
1294 at this point. A marker may be enqueued when extract_dirs_from_files is
1295 called with a non-empty string or via print_dir. */
1298 print_current_files ();
1300 DIRED_PUTCHAR ('\n');
1302 else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1303 print_dir_name = false;
1305 while (pending_dirs)
1307 thispend = pending_dirs;
1308 pending_dirs = pending_dirs->next;
1312 if (thispend->name == NULL)
1314 /* thispend->name == NULL means this is a marker entry
1315 indicating we've finished processing the directory.
1316 Use its dev/ino numbers to remove the corresponding
1317 entry from the active_dir_set hash table. */
1318 struct dev_ino di = dev_ino_pop ();
1319 struct dev_ino *found = hash_delete (active_dir_set, &di);
1320 /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
1322 dev_ino_free (found);
1323 free_pending_ent (thispend);
1328 print_dir (thispend->name, thispend->realname,
1329 thispend->command_line_arg);
1331 free_pending_ent (thispend);
1332 print_dir_name = true;
1335 if (print_with_color)
1340 restore_default_color ();
1343 /* Restore the default signal handling. */
1345 for (j = 0; j < nsigs; j++)
1346 if (sigismember (&caught_signals, sig[j]))
1347 signal (sig[j], SIG_DFL);
1349 for (j = 0; j < nsigs; j++)
1351 signal (sig[j], SIG_DFL);
1354 /* Act on any signals that arrived before the default was restored.
1355 This can process signals out of order, but there doesn't seem to
1356 be an easy way to do them in order, and the order isn't that
1357 important anyway. */
1358 for (j = stop_signal_count; j; j--)
1360 j = interrupt_signal;
1367 /* No need to free these since we're about to exit. */
1368 dired_dump_obstack ("//DIRED//", &dired_obstack);
1369 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1370 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1371 quoting_style_args[get_quoting_style (filename_quoting_options)]);
1376 assert (hash_get_n_entries (active_dir_set) == 0);
1377 hash_free (active_dir_set);
1383 /* Set all the option flags according to the switches specified.
1384 Return the index of the first non-option argument. */
1387 decode_switches (int argc, char **argv)
1389 char *time_style_option = NULL;
1391 /* Record whether there is an option specifying sort type. */
1392 bool sort_type_specified = false;
1394 qmark_funny_chars = false;
1396 /* initialize all switches to default settings */
1401 /* This is for the `dir' program. */
1402 format = many_per_line;
1403 set_quoting_style (NULL, escape_quoting_style);
1406 case LS_LONG_FORMAT:
1407 /* This is for the `vdir' program. */
1408 format = long_format;
1409 set_quoting_style (NULL, escape_quoting_style);
1413 /* This is for the `ls' program. */
1414 if (isatty (STDOUT_FILENO))
1416 format = many_per_line;
1417 /* See description of qmark_funny_chars, above. */
1418 qmark_funny_chars = true;
1422 format = one_per_line;
1423 qmark_funny_chars = false;
1431 time_type = time_mtime;
1432 sort_type = sort_name;
1433 sort_reverse = false;
1434 numeric_ids = false;
1435 print_block_size = false;
1436 indicator_style = none;
1437 print_inode = false;
1438 dereference = DEREF_UNDEFINED;
1440 immediate_dirs = false;
1441 ignore_mode = IGNORE_DEFAULT;
1442 ignore_patterns = NULL;
1443 hide_patterns = NULL;
1444 print_scontext = false;
1446 /* FIXME: put this in a function. */
1448 char const *q_style = getenv ("QUOTING_STYLE");
1451 int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
1453 set_quoting_style (NULL, quoting_style_vals[i]);
1456 _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
1457 quotearg (q_style));
1462 char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
1463 human_options (ls_block_size,
1464 &human_output_opts, &output_block_size);
1465 if (ls_block_size || getenv ("BLOCK_SIZE"))
1466 file_output_block_size = output_block_size;
1471 char const *p = getenv ("COLUMNS");
1474 unsigned long int tmp_ulong;
1475 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1476 && 0 < tmp_ulong && tmp_ulong <= SIZE_MAX)
1478 line_length = tmp_ulong;
1483 _("ignoring invalid width in environment variable COLUMNS: %s"),
1493 if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1
1494 && 0 < ws.ws_col && ws.ws_col == (size_t) ws.ws_col)
1495 line_length = ws.ws_col;
1500 char const *p = getenv ("TABSIZE");
1504 unsigned long int tmp_ulong;
1505 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1506 && tmp_ulong <= SIZE_MAX)
1508 tabsize = tmp_ulong;
1513 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1522 int c = getopt_long (argc, argv,
1523 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1",
1531 ignore_mode = IGNORE_MINIMAL;
1535 set_quoting_style (NULL, escape_quoting_style);
1539 time_type = time_ctime;
1543 immediate_dirs = true;
1547 /* Same as enabling -a -U and disabling -l -s. */
1548 ignore_mode = IGNORE_MINIMAL;
1549 sort_type = sort_none;
1550 sort_type_specified = true;
1552 if (format == long_format)
1553 format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
1554 print_block_size = false; /* disable -s */
1555 print_with_color = false; /* disable --color */
1558 case FILE_TYPE_INDICATOR_OPTION: /* --file-type */
1559 indicator_style = file_type;
1563 format = long_format;
1564 print_owner = false;
1568 human_output_opts = human_autoscale | human_SI | human_base_1024;
1569 file_output_block_size = output_block_size = 1;
1577 human_output_opts = 0;
1578 file_output_block_size = output_block_size = 1024;
1582 format = long_format;
1586 format = with_commas;
1591 format = long_format;
1594 case 'o': /* Just like -l, but don't display group info. */
1595 format = long_format;
1596 print_group = false;
1600 indicator_style = slash;
1604 qmark_funny_chars = true;
1608 sort_reverse = true;
1612 print_block_size = true;
1616 sort_type = sort_time;
1617 sort_type_specified = true;
1621 time_type = time_atime;
1625 sort_type = sort_version;
1626 sort_type_specified = true;
1631 unsigned long int tmp_ulong;
1632 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1633 || ! (0 < tmp_ulong && tmp_ulong <= SIZE_MAX))
1634 error (LS_FAILURE, 0, _("invalid line width: %s"),
1636 line_length = tmp_ulong;
1641 format = horizontal;
1645 if (ignore_mode == IGNORE_DEFAULT)
1646 ignore_mode = IGNORE_DOT_AND_DOTDOT;
1650 add_ignore_pattern ("*~");
1651 add_ignore_pattern (".*~");
1655 format = many_per_line;
1663 indicator_style = classify;
1666 case 'G': /* inhibit display of group info */
1667 print_group = false;
1671 dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1674 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
1675 dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
1679 add_ignore_pattern (optarg);
1683 dereference = DEREF_ALWAYS;
1687 set_quoting_style (NULL, literal_quoting_style);
1691 set_quoting_style (NULL, c_quoting_style);
1699 sort_type = sort_size;
1700 sort_type_specified = true;
1705 unsigned long int tmp_ulong;
1706 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1707 || SIZE_MAX < tmp_ulong)
1708 error (LS_FAILURE, 0, _("invalid tab size: %s"),
1710 tabsize = tmp_ulong;
1715 sort_type = sort_none;
1716 sort_type_specified = true;
1720 sort_type = sort_extension;
1721 sort_type_specified = true;
1725 /* -1 has no effect after -l. */
1726 if (format != long_format)
1727 format = one_per_line;
1731 print_author = true;
1736 struct ignore_pattern *hide = xmalloc (sizeof *hide);
1737 hide->pattern = optarg;
1738 hide->next = hide_patterns;
1739 hide_patterns = hide;
1744 sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1745 sort_type_specified = true;
1748 case GROUP_DIRECTORIES_FIRST_OPTION:
1749 directories_first = true;
1753 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1757 format = XARGMATCH ("--format", optarg, format_args, format_types);
1760 case FULL_TIME_OPTION:
1761 format = long_format;
1762 time_style_option = "full-iso";
1769 i = XARGMATCH ("--color", optarg, color_args, color_types);
1771 /* Using --color with no argument is equivalent to using
1775 print_with_color = (i == color_always
1776 || (i == color_if_tty
1777 && isatty (STDOUT_FILENO)));
1779 if (print_with_color)
1781 /* Don't use TAB characters in output. Some terminal
1782 emulators can't handle the combination of tabs and
1783 color codes on the same line. */
1789 case INDICATOR_STYLE_OPTION:
1790 indicator_style = XARGMATCH ("--indicator-style", optarg,
1791 indicator_style_args,
1792 indicator_style_types);
1795 case QUOTING_STYLE_OPTION:
1796 set_quoting_style (NULL,
1797 XARGMATCH ("--quoting-style", optarg,
1799 quoting_style_vals));
1802 case TIME_STYLE_OPTION:
1803 time_style_option = optarg;
1806 case SHOW_CONTROL_CHARS_OPTION:
1807 qmark_funny_chars = false;
1810 case BLOCK_SIZE_OPTION:
1812 enum strtol_error e = human_options (optarg, &human_output_opts,
1813 &output_block_size);
1814 if (e != LONGINT_OK)
1815 xstrtol_fatal (e, oi, 0, long_options, optarg);
1816 file_output_block_size = output_block_size;
1821 human_output_opts = human_autoscale | human_SI;
1822 file_output_block_size = output_block_size = 1;
1826 print_scontext = true;
1829 case_GETOPT_HELP_CHAR;
1831 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1838 max_idx = MAX (1, line_length / MIN_COLUMN_WIDTH);
1840 filename_quoting_options = clone_quoting_options (NULL);
1841 if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1842 set_char_quoting (filename_quoting_options, ' ', 1);
1843 if (file_type <= indicator_style)
1846 for (p = "*=>@|" + indicator_style - file_type; *p; p++)
1847 set_char_quoting (filename_quoting_options, *p, 1);
1850 dirname_quoting_options = clone_quoting_options (NULL);
1851 set_char_quoting (dirname_quoting_options, ':', 1);
1853 /* --dired is meaningful only with --format=long (-l).
1854 Otherwise, ignore it. FIXME: warn about this?
1855 Alternatively, make --dired imply --format=long? */
1856 if (dired && format != long_format)
1859 /* If -c or -u is specified and not -l (or any other option that implies -l),
1860 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
1861 The behavior of ls when using either -c or -u but with neither -l nor -t
1862 appears to be unspecified by POSIX. So, with GNU ls, `-u' alone means
1863 sort by atime (this is the one that's not specified by the POSIX spec),
1864 -lu means show atime and sort by name, -lut means show atime and sort
1867 if ((time_type == time_ctime || time_type == time_atime)
1868 && !sort_type_specified && format != long_format)
1870 sort_type = sort_time;
1873 if (format == long_format)
1875 char *style = time_style_option;
1876 static char const posix_prefix[] = "posix-";
1879 if (! (style = getenv ("TIME_STYLE")))
1882 while (strncmp (style, posix_prefix, sizeof posix_prefix - 1) == 0)
1884 if (! hard_locale (LC_TIME))
1886 style += sizeof posix_prefix - 1;
1891 char *p0 = style + 1;
1892 char *p1 = strchr (p0, '\n');
1897 if (strchr (p1 + 1, '\n'))
1898 error (LS_FAILURE, 0, _("invalid time style format %s"),
1902 long_time_format[0] = p0;
1903 long_time_format[1] = p1;
1906 switch (XARGMATCH ("time style", style,
1910 case full_iso_time_style:
1911 long_time_format[0] = long_time_format[1] =
1912 "%Y-%m-%d %H:%M:%S.%N %z";
1915 case long_iso_time_style:
1916 case_long_iso_time_style:
1917 long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
1920 case iso_time_style:
1921 long_time_format[0] = "%Y-%m-%d ";
1922 long_time_format[1] = "%m-%d %H:%M";
1925 case locale_time_style:
1926 if (hard_locale (LC_TIME))
1928 /* Ensure that the locale has translations for both
1929 formats. If not, fall back on long-iso format. */
1931 for (i = 0; i < 2; i++)
1933 char const *locale_format =
1934 dcgettext (NULL, long_time_format[i], LC_TIME);
1935 if (locale_format == long_time_format[i])
1936 goto case_long_iso_time_style;
1937 long_time_format[i] = locale_format;
1946 /* Parse a string as part of the LS_COLORS variable; this may involve
1947 decoding all kinds of escape characters. If equals_end is set an
1948 unescaped equal sign ends the string, otherwise only a : or \0
1949 does. Set *OUTPUT_COUNT to the number of bytes output. Return
1952 The resulting string is *not* null-terminated, but may contain
1955 Note that both dest and src are char **; on return they point to
1956 the first free byte after the array and the character that ended
1957 the input string, respectively. */
1960 get_funky_string (char **dest, const char **src, bool equals_end,
1961 size_t *output_count)
1963 char num; /* For numerical codes */
1964 size_t count; /* Something to count with */
1966 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
1971 p = *src; /* We don't want to double-indirect */
1972 q = *dest; /* the whole darn time. */
1974 count = 0; /* No characters counted in yet. */
1977 state = ST_GND; /* Start in ground state. */
1978 while (state < ST_END)
1982 case ST_GND: /* Ground state (no escapes) */
1987 state = ST_END; /* End of string */
1990 state = ST_BACKSLASH; /* Backslash scape sequence */
1994 state = ST_CARET; /* Caret escape */
2000 state = ST_END; /* End */
2003 /* else fall through */
2011 case ST_BACKSLASH: /* Backslash escaped character */
2022 state = ST_OCTAL; /* Octal sequence */
2027 state = ST_HEX; /* Hex sequence */
2030 case 'a': /* Bell */
2033 case 'b': /* Backspace */
2036 case 'e': /* Escape */
2039 case 'f': /* Form feed */
2042 case 'n': /* Newline */
2045 case 'r': /* Carriage return */
2051 case 'v': /* Vtab */
2054 case '?': /* Delete */
2057 case '_': /* Space */
2060 case '\0': /* End of string */
2061 state = ST_ERROR; /* Error! */
2063 default: /* Escaped character like \ ^ : = */
2067 if (state == ST_BACKSLASH)
2076 case ST_OCTAL: /* Octal sequence */
2077 if (*p < '0' || *p > '7')
2084 num = (num << 3) + (*(p++) - '0');
2087 case ST_HEX: /* Hex sequence */
2100 num = (num << 4) + (*(p++) - '0');
2108 num = (num << 4) + (*(p++) - 'a') + 10;
2116 num = (num << 4) + (*(p++) - 'A') + 10;
2126 case ST_CARET: /* Caret escape */
2127 state = ST_GND; /* Should be the next state... */
2128 if (*p >= '@' && *p <= '~')
2130 *(q++) = *(p++) & 037;
2149 *output_count = count;
2151 return state != ST_ERROR;
2155 parse_ls_color (void)
2157 const char *p; /* Pointer to character being parsed */
2158 char *buf; /* color_buf buffer pointer */
2159 int state; /* State of parser */
2160 int ind_no; /* Indicator number */
2161 char label[3]; /* Indicator label */
2162 struct color_ext_type *ext; /* Extension we are working on */
2164 if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
2168 strcpy (label, "??");
2170 /* This is an overly conservative estimate, but any possible
2171 LS_COLORS string will *not* generate a color_buf longer than
2172 itself, so it is a safe way of allocating a buffer in
2174 buf = color_buf = xstrdup (p);
2181 case 1: /* First label character */
2189 /* Allocate new extension block and add to head of
2190 linked list (this way a later definition will
2191 override an earlier one, which can be useful for
2192 having terminal-specific defs override global). */
2194 ext = xmalloc (sizeof *ext);
2195 ext->next = color_ext_list;
2196 color_ext_list = ext;
2199 ext->ext.string = buf;
2201 state = (get_funky_string (&buf, &p, true, &ext->ext.len)
2206 state = 0; /* Done! */
2209 default: /* Assume it is file type label */
2216 case 2: /* Second label character */
2223 state = -1; /* Error */
2226 case 3: /* Equal sign after indicator label */
2227 state = -1; /* Assume failure... */
2228 if (*(p++) == '=')/* It *should* be... */
2230 for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
2232 if (STREQ (label, indicator_name[ind_no]))
2234 color_indicator[ind_no].string = buf;
2235 state = (get_funky_string (&buf, &p, false,
2236 &color_indicator[ind_no].len)
2242 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
2246 case 4: /* Equal sign after *.ext */
2249 ext->seq.string = buf;
2250 state = (get_funky_string (&buf, &p, false, &ext->seq.len)
2261 struct color_ext_type *e;
2262 struct color_ext_type *e2;
2265 _("unparsable value for LS_COLORS environment variable"));
2267 for (e = color_ext_list; e != NULL; /* empty */)
2273 print_with_color = false;
2276 if (color_indicator[C_LINK].len == 6
2277 && !strncmp (color_indicator[C_LINK].string, "target", 6))
2278 color_symlink_as_referent = true;
2281 /* Set the exit status to report a failure. If SERIOUS, it is a
2282 serious failure; otherwise, it is merely a minor problem. */
2285 set_exit_status (bool serious)
2288 exit_status = LS_FAILURE;
2289 else if (exit_status == EXIT_SUCCESS)
2290 exit_status = LS_MINOR_PROBLEM;
2293 /* Assuming a failure is serious if SERIOUS, use the printf-style
2294 MESSAGE to report the failure to access a file named FILE. Assume
2295 errno is set appropriately for the failure. */
2298 file_failure (bool serious, char const *message, char const *file)
2300 error (0, errno, message, quotearg_colon (file));
2301 set_exit_status (serious);
2304 /* Request that the directory named NAME have its contents listed later.
2305 If REALNAME is nonzero, it will be used instead of NAME when the
2306 directory name is printed. This allows symbolic links to directories
2307 to be treated as regular directories but still be listed under their
2308 real names. NAME == NULL is used to insert a marker entry for the
2309 directory named in REALNAME.
2310 If NAME is non-NULL, we use its dev/ino information to save
2311 a call to stat -- when doing a recursive (-R) traversal.
2312 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2315 queue_directory (char const *name, char const *realname, bool command_line_arg)
2317 struct pending *new = xmalloc (sizeof *new);
2318 new->realname = realname ? xstrdup (realname) : NULL;
2319 new->name = name ? xstrdup (name) : NULL;
2320 new->command_line_arg = command_line_arg;
2321 new->next = pending_dirs;
2325 /* Read directory NAME, and list the files in it.
2326 If REALNAME is nonzero, print its name instead of NAME;
2327 this is used for symbolic links to directories.
2328 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2331 print_dir (char const *name, char const *realname, bool command_line_arg)
2334 struct dirent *next;
2335 uintmax_t total_blocks = 0;
2336 static bool first = true;
2339 dirp = opendir (name);
2342 file_failure (command_line_arg, _("cannot open directory %s"), name);
2348 struct stat dir_stat;
2349 int fd = dirfd (dirp);
2351 /* If dirfd failed, endure the overhead of using stat. */
2353 ? fstat (fd, &dir_stat)
2354 : stat (name, &dir_stat)) < 0)
2356 file_failure (command_line_arg,
2357 _("cannot determine device and inode of %s"), name);
2362 /* If we've already visited this dev/inode pair, warn that
2363 we've found a loop, and do not process this directory. */
2364 if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
2366 error (0, 0, _("%s: not listing already-listed directory"),
2367 quotearg_colon (name));
2372 DEV_INO_PUSH (dir_stat.st_dev, dir_stat.st_ino);
2375 /* Read the directory entries, and insert the subfiles into the `cwd_file'
2382 /* Set errno to zero so we can distinguish between a readdir failure
2383 and when readdir simply finds that there are no more entries. */
2385 next = readdir (dirp);
2388 if (! file_ignored (next->d_name))
2390 enum filetype type = unknown;
2392 #if HAVE_STRUCT_DIRENT_D_TYPE
2393 switch (next->d_type)
2395 case DT_BLK: type = blockdev; break;
2396 case DT_CHR: type = chardev; break;
2397 case DT_DIR: type = directory; break;
2398 case DT_FIFO: type = fifo; break;
2399 case DT_LNK: type = symbolic_link; break;
2400 case DT_REG: type = normal; break;
2401 case DT_SOCK: type = sock; break;
2403 case DT_WHT: type = whiteout; break;
2407 total_blocks += gobble_file (next->d_name, type, D_INO (next),
2410 /* In this narrow case, print out each name right away, so
2411 ls uses constant memory while processing the entries of
2412 this directory. Useful when there are many (millions)
2413 of entries in a directory. */
2414 if (format == one_per_line && sort_type == sort_none)
2416 /* We must call sort_files in spite of
2417 "sort_type == sort_none" for its initialization
2418 of the sorted_file vector. */
2420 print_current_files ();
2425 else if (errno != 0)
2427 file_failure (command_line_arg, _("reading directory %s"), name);
2428 if (errno != EOVERFLOW)
2435 if (closedir (dirp) != 0)
2437 file_failure (command_line_arg, _("closing directory %s"), name);
2438 /* Don't return; print whatever we got. */
2441 /* Sort the directory contents. */
2444 /* If any member files are subdirectories, perhaps they should have their
2445 contents listed rather than being mentioned here as files. */
2448 extract_dirs_from_files (name, command_line_arg);
2450 if (recursive | print_dir_name)
2453 DIRED_PUTCHAR ('\n');
2456 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2457 dired_pos += quote_name (stdout, realname ? realname : name,
2458 dirname_quoting_options, NULL);
2459 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2460 DIRED_FPUTS_LITERAL (":\n", stdout);
2463 if (format == long_format || print_block_size)
2466 char buf[LONGEST_HUMAN_READABLE + 1];
2470 DIRED_FPUTS (p, stdout, strlen (p));
2471 DIRED_PUTCHAR (' ');
2472 p = human_readable (total_blocks, buf, human_output_opts,
2473 ST_NBLOCKSIZE, output_block_size);
2474 DIRED_FPUTS (p, stdout, strlen (p));
2475 DIRED_PUTCHAR ('\n');
2479 print_current_files ();
2482 /* Add `pattern' to the list of patterns for which files that match are
2486 add_ignore_pattern (const char *pattern)
2488 struct ignore_pattern *ignore;
2490 ignore = xmalloc (sizeof *ignore);
2491 ignore->pattern = pattern;
2492 /* Add it to the head of the linked list. */
2493 ignore->next = ignore_patterns;
2494 ignore_patterns = ignore;
2497 /* Return true if one of the PATTERNS matches FILE. */
2500 patterns_match (struct ignore_pattern const *patterns, char const *file)
2502 struct ignore_pattern const *p;
2503 for (p = patterns; p; p = p->next)
2504 if (fnmatch (p->pattern, file, FNM_PERIOD) == 0)
2509 /* Return true if FILE should be ignored. */
2512 file_ignored (char const *name)
2514 return ((ignore_mode != IGNORE_MINIMAL
2516 && (ignore_mode == IGNORE_DEFAULT || ! name[1 + (name[1] == '.')]))
2517 || (ignore_mode == IGNORE_DEFAULT
2518 && patterns_match (hide_patterns, name))
2519 || patterns_match (ignore_patterns, name));
2522 /* POSIX requires that a file size be printed without a sign, even
2523 when negative. Assume the typical case where negative sizes are
2524 actually positive values that have wrapped around. */
2527 unsigned_file_size (off_t size)
2529 return size + (size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
2532 /* Enter and remove entries in the table `cwd_file'. */
2534 /* Empty the table of files. */
2541 for (i = 0; i < cwd_n_used; i++)
2543 struct fileinfo *f = sorted_file[i];
2546 if (f->scontext != UNKNOWN_SECURITY_CONTEXT)
2547 freecon (f->scontext);
2551 any_has_acl = false;
2552 inode_number_width = 0;
2553 block_size_width = 0;
2559 major_device_number_width = 0;
2560 minor_device_number_width = 0;
2561 file_size_width = 0;
2564 /* Add a file to the current table of files.
2565 Verify that the file exists, and print an error message if it does not.
2566 Return the number of blocks that the file occupies. */
2569 gobble_file (char const *name, enum filetype type, ino_t inode,
2570 bool command_line_arg, char const *dirname)
2572 uintmax_t blocks = 0;
2575 /* An inode value prior to gobble_file necessarily came from readdir,
2576 which is not used for command line arguments. */
2577 assert (! command_line_arg || inode == NOT_AN_INODE_NUMBER);
2579 if (cwd_n_used == cwd_n_alloc)
2581 cwd_file = xnrealloc (cwd_file, cwd_n_alloc, 2 * sizeof *cwd_file);
2585 f = &cwd_file[cwd_n_used];
2586 memset (f, '\0', sizeof *f);
2587 f->stat.st_ino = inode;
2590 if (command_line_arg
2591 || format_needs_stat
2592 /* When coloring a directory (we may know the type from
2593 direct.d_type), we have to stat it in order to indicate
2594 sticky and/or other-writable attributes. */
2595 || (type == directory && print_with_color)
2596 /* When dereferencing symlinks, the inode and type must come from
2597 stat, but readdir provides the inode and type of lstat. */
2598 || ((print_inode || format_needs_type)
2599 && (type == symbolic_link || type == unknown)
2600 && (dereference == DEREF_ALWAYS
2601 || (command_line_arg && dereference != DEREF_NEVER)
2602 || color_symlink_as_referent || check_symlink_color))
2603 /* Command line dereferences are already taken care of by the above
2604 assertion that the inode number is not yet known. */
2605 || (print_inode && inode == NOT_AN_INODE_NUMBER)
2606 || (format_needs_type
2607 && (type == unknown || command_line_arg
2608 /* --indicator-style=classify (aka -F)
2609 requires that we stat each regular file
2610 to see if it's executable. */
2611 || (type == normal && (indicator_style == classify
2612 /* This is so that --color ends up
2613 highlighting files with the executable
2614 bit set even when options like -F are
2616 || (print_with_color
2617 && is_colored (C_EXEC))
2621 /* Absolute name of this file. */
2622 char *absolute_name;
2626 if (name[0] == '/' || dirname[0] == 0)
2627 absolute_name = (char *) name;
2630 absolute_name = alloca (strlen (name) + strlen (dirname) + 2);
2631 attach (absolute_name, dirname, name);
2634 switch (dereference)
2637 err = stat (absolute_name, &f->stat);
2641 case DEREF_COMMAND_LINE_ARGUMENTS:
2642 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
2643 if (command_line_arg)
2646 err = stat (absolute_name, &f->stat);
2649 if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2652 need_lstat = (err < 0
2654 : ! S_ISDIR (f->stat.st_mode));
2658 /* stat failed because of ENOENT, maybe indicating a dangling
2659 symlink. Or stat succeeded, ABSOLUTE_NAME does not refer to a
2660 directory, and --dereference-command-line-symlink-to-dir is
2661 in effect. Fall through so that we call lstat instead. */
2664 default: /* DEREF_NEVER */
2665 err = lstat (absolute_name, &f->stat);
2672 /* Failure to stat a command line argument leads to
2673 an exit status of 2. For other files, stat failure
2674 provokes an exit status of 1. */
2675 file_failure (command_line_arg,
2676 _("cannot access %s"), absolute_name);
2677 if (command_line_arg)
2680 f->name = xstrdup (name);
2688 if (format == long_format || print_scontext)
2690 bool have_acl = false;
2691 int attr_len = (do_deref
2692 ? getfilecon (absolute_name, &f->scontext)
2693 : lgetfilecon (absolute_name, &f->scontext));
2694 err = (attr_len < 0);
2696 /* Contrary to its documented API, getfilecon may return 0,
2697 yet set f->scontext to NULL (on at least Debian's libselinux1
2698 2.0.15-2+b1), so work around that bug.
2699 FIXME: remove this work-around in 2011, or whenever affected
2700 versions of libselinux are long gone. */
2704 f->scontext = xstrdup ("unlabeled");
2708 have_acl = ! STREQ ("unlabeled", f->scontext);
2711 f->scontext = UNKNOWN_SECURITY_CONTEXT;
2713 /* When requesting security context information, don't make
2714 ls fail just because the file (even a command line argument)
2715 isn't on the right type of file system. I.e., a getfilecon
2716 failure isn't in the same class as a stat failure. */
2717 if (errno == ENOTSUP || errno == EOPNOTSUPP || errno == ENODATA)
2721 if (err == 0 && ! have_acl && format == long_format)
2723 int n = file_has_acl (absolute_name, &f->stat);
2728 f->have_acl = have_acl;
2729 any_has_acl |= have_acl;
2732 error (0, errno, "%s", quotearg_colon (absolute_name));
2735 if (S_ISLNK (f->stat.st_mode)
2736 && (format == long_format || check_symlink_color))
2739 struct stat linkstats;
2741 get_link_name (absolute_name, f, command_line_arg);
2742 linkname = make_link_name (absolute_name, f->linkname);
2744 /* Avoid following symbolic links when possible, ie, when
2745 they won't be traced and when no indicator is needed. */
2747 && (file_type <= indicator_style || check_symlink_color)
2748 && stat (linkname, &linkstats) == 0)
2752 /* Symbolic links to directories that are mentioned on the
2753 command line are automatically traced if not being
2755 if (!command_line_arg || format == long_format
2756 || !S_ISDIR (linkstats.st_mode))
2758 /* Get the linked-to file's mode for the filetype indicator
2759 in long listings. */
2760 f->linkmode = linkstats.st_mode;
2766 /* When not distinguishing types of symlinks, pretend we know that
2767 it is stat'able, so that it will be colored as a regular symlink,
2768 and not as an orphan. */
2769 if (S_ISLNK (f->stat.st_mode) && !check_symlink_color)
2772 if (S_ISLNK (f->stat.st_mode))
2773 f->filetype = symbolic_link;
2774 else if (S_ISDIR (f->stat.st_mode))
2776 if (command_line_arg & !immediate_dirs)
2777 f->filetype = arg_directory;
2779 f->filetype = directory;
2782 f->filetype = normal;
2784 blocks = ST_NBLOCKS (f->stat);
2785 if (format == long_format || print_block_size)
2787 char buf[LONGEST_HUMAN_READABLE + 1];
2788 int len = mbswidth (human_readable (blocks, buf, human_output_opts,
2789 ST_NBLOCKSIZE, output_block_size),
2791 if (block_size_width < len)
2792 block_size_width = len;
2795 if (format == long_format)
2799 int len = format_user_width (f->stat.st_uid);
2800 if (owner_width < len)
2806 int len = format_group_width (f->stat.st_gid);
2807 if (group_width < len)
2813 int len = format_user_width (f->stat.st_author);
2814 if (author_width < len)
2821 int len = strlen (f->scontext);
2822 if (scontext_width < len)
2823 scontext_width = len;
2826 if (format == long_format)
2828 char b[INT_BUFSIZE_BOUND (uintmax_t)];
2829 int b_len = strlen (umaxtostr (f->stat.st_nlink, b));
2830 if (nlink_width < b_len)
2831 nlink_width = b_len;
2833 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
2835 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2836 int len = strlen (umaxtostr (major (f->stat.st_rdev), buf));
2837 if (major_device_number_width < len)
2838 major_device_number_width = len;
2839 len = strlen (umaxtostr (minor (f->stat.st_rdev), buf));
2840 if (minor_device_number_width < len)
2841 minor_device_number_width = len;
2842 len = major_device_number_width + 2 + minor_device_number_width;
2843 if (file_size_width < len)
2844 file_size_width = len;
2848 char buf[LONGEST_HUMAN_READABLE + 1];
2849 uintmax_t size = unsigned_file_size (f->stat.st_size);
2850 int len = mbswidth (human_readable (size, buf, human_output_opts,
2851 1, file_output_block_size),
2853 if (file_size_width < len)
2854 file_size_width = len;
2861 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2862 int len = strlen (umaxtostr (f->stat.st_ino, buf));
2863 if (inode_number_width < len)
2864 inode_number_width = len;
2867 f->name = xstrdup (name);
2873 /* Return true if F refers to a directory. */
2875 is_directory (const struct fileinfo *f)
2877 return f->filetype == directory || f->filetype == arg_directory;
2880 /* Put the name of the file that FILENAME is a symbolic link to
2881 into the LINKNAME field of `f'. COMMAND_LINE_ARG indicates whether
2882 FILENAME is a command-line argument. */
2885 get_link_name (char const *filename, struct fileinfo *f, bool command_line_arg)
2887 f->linkname = areadlink_with_size (filename, f->stat.st_size);
2888 if (f->linkname == NULL)
2889 file_failure (command_line_arg, _("cannot read symbolic link %s"),
2893 /* If `linkname' is a relative name and `name' contains one or more
2894 leading directories, return `linkname' with those directories
2895 prepended; otherwise, return a copy of `linkname'.
2896 If `linkname' is zero, return zero. */
2899 make_link_name (char const *name, char const *linkname)
2907 if (*linkname == '/')
2908 return xstrdup (linkname);
2910 /* The link is to a relative name. Prepend any leading directory
2911 in `name' to the link name. */
2912 linkbuf = strrchr (name, '/');
2914 return xstrdup (linkname);
2916 bufsiz = linkbuf - name + 1;
2917 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
2918 strncpy (linkbuf, name, bufsiz);
2919 strcpy (linkbuf + bufsiz, linkname);
2923 /* Return true if the last component of NAME is `.' or `..'
2924 This is so we don't try to recurse on `././././. ...' */
2927 basename_is_dot_or_dotdot (const char *name)
2929 char const *base = last_component (name);
2930 return dot_or_dotdot (base);
2933 /* Remove any entries from CWD_FILE that are for directories,
2934 and queue them to be listed as directories instead.
2935 DIRNAME is the prefix to prepend to each dirname
2936 to make it correct relative to ls's working dir;
2937 if it is null, no prefix is needed and "." and ".." should not be ignored.
2938 If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
2939 This is desirable when processing directories recursively. */
2942 extract_dirs_from_files (char const *dirname, bool command_line_arg)
2946 bool ignore_dot_and_dot_dot = (dirname != NULL);
2948 if (dirname && LOOP_DETECT)
2950 /* Insert a marker entry first. When we dequeue this marker entry,
2951 we'll know that DIRNAME has been processed and may be removed
2952 from the set of active directories. */
2953 queue_directory (NULL, dirname, false);
2956 /* Queue the directories last one first, because queueing reverses the
2958 for (i = cwd_n_used; i-- != 0; )
2960 struct fileinfo *f = sorted_file[i];
2962 if (is_directory (f)
2963 && (! ignore_dot_and_dot_dot
2964 || ! basename_is_dot_or_dotdot (f->name)))
2966 if (!dirname || f->name[0] == '/')
2967 queue_directory (f->name, f->linkname, command_line_arg);
2970 char *name = file_name_concat (dirname, f->name, NULL);
2971 queue_directory (name, f->linkname, command_line_arg);
2974 if (f->filetype == arg_directory)
2979 /* Now delete the directories from the table, compacting all the remaining
2982 for (i = 0, j = 0; i < cwd_n_used; i++)
2984 struct fileinfo *f = sorted_file[i];
2986 j += (f->filetype != arg_directory);
2991 /* Use strcoll to compare strings in this locale. If an error occurs,
2992 report an error and longjmp to failed_strcoll. */
2994 static jmp_buf failed_strcoll;
2997 xstrcoll (char const *a, char const *b)
3001 diff = strcoll (a, b);
3004 error (0, errno, _("cannot compare file names %s and %s"),
3005 quote_n (0, a), quote_n (1, b));
3006 set_exit_status (false);
3007 longjmp (failed_strcoll, 1);
3012 /* Comparison routines for sorting the files. */
3014 typedef void const *V;
3015 typedef int (*qsortFunc)(V a, V b);
3017 /* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants.
3018 The do { ... } while(0) makes it possible to use the macro more like
3019 a statement, without violating C89 rules: */
3020 #define DIRFIRST_CHECK(a, b) \
3023 bool a_is_dir = is_directory ((struct fileinfo const *) a); \
3024 bool b_is_dir = is_directory ((struct fileinfo const *) b); \
3025 if (a_is_dir && !b_is_dir) \
3026 return -1; /* a goes before b */ \
3027 if (!a_is_dir && b_is_dir) \
3028 return 1; /* b goes before a */ \
3032 /* Define the 8 different sort function variants required for each sortkey.
3033 KEY_NAME is a token describing the sort key, e.g., ctime, atime, size.
3034 KEY_CMP_FUNC is a function to compare records based on that key, e.g.,
3035 ctime_cmp, atime_cmp, size_cmp. Append KEY_NAME to the string,
3036 '[rev_][x]str{cmp|coll}[_df]_', to create each function name. */
3037 #define DEFINE_SORT_FUNCTIONS(key_name, key_cmp_func) \
3038 /* direct, non-dirfirst versions */ \
3039 static int xstrcoll_##key_name (V a, V b) \
3040 { return key_cmp_func (a, b, xstrcoll); } \
3041 static int strcmp_##key_name (V a, V b) \
3042 { return key_cmp_func (a, b, strcmp); } \
3044 /* reverse, non-dirfirst versions */ \
3045 static int rev_xstrcoll_##key_name (V a, V b) \
3046 { return key_cmp_func (b, a, xstrcoll); } \
3047 static int rev_strcmp_##key_name (V a, V b) \
3048 { return key_cmp_func (b, a, strcmp); } \
3050 /* direct, dirfirst versions */ \
3051 static int xstrcoll_df_##key_name (V a, V b) \
3052 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, xstrcoll); } \
3053 static int strcmp_df_##key_name (V a, V b) \
3054 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, strcmp); } \
3056 /* reverse, dirfirst versions */ \
3057 static int rev_xstrcoll_df_##key_name (V a, V b) \
3058 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, xstrcoll); } \
3059 static int rev_strcmp_df_##key_name (V a, V b) \
3060 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, strcmp); }
3063 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
3064 int (*cmp) (char const *, char const *))
3066 int diff = timespec_cmp (get_stat_ctime (&b->stat),
3067 get_stat_ctime (&a->stat));
3068 return diff ? diff : cmp (a->name, b->name);
3072 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
3073 int (*cmp) (char const *, char const *))
3075 int diff = timespec_cmp (get_stat_mtime (&b->stat),
3076 get_stat_mtime (&a->stat));
3077 return diff ? diff : cmp (a->name, b->name);
3081 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
3082 int (*cmp) (char const *, char const *))
3084 int diff = timespec_cmp (get_stat_atime (&b->stat),
3085 get_stat_atime (&a->stat));
3086 return diff ? diff : cmp (a->name, b->name);
3090 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
3091 int (*cmp) (char const *, char const *))
3093 int diff = longdiff (b->stat.st_size, a->stat.st_size);
3094 return diff ? diff : cmp (a->name, b->name);
3098 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
3099 int (*cmp) (char const *, char const *))
3101 return cmp (a->name, b->name);
3104 /* Compare file extensions. Files with no extension are `smallest'.
3105 If extensions are the same, compare by filenames instead. */
3108 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
3109 int (*cmp) (char const *, char const *))
3111 char const *base1 = strrchr (a->name, '.');
3112 char const *base2 = strrchr (b->name, '.');
3113 int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
3114 return diff ? diff : cmp (a->name, b->name);
3117 DEFINE_SORT_FUNCTIONS (ctime, cmp_ctime)
3118 DEFINE_SORT_FUNCTIONS (mtime, cmp_mtime)
3119 DEFINE_SORT_FUNCTIONS (atime, cmp_atime)
3120 DEFINE_SORT_FUNCTIONS (size, cmp_size)
3121 DEFINE_SORT_FUNCTIONS (name, cmp_name)
3122 DEFINE_SORT_FUNCTIONS (extension, cmp_extension)
3124 /* Compare file versions.
3125 Unlike all other compare functions above, cmp_version depends only
3126 on strverscmp, which does not fail (even for locale reasons), and does not
3127 need a secondary sort key.
3128 All the other sort options, in fact, need xstrcoll and strcmp variants,
3129 because they all use a string comparison (either as the primary or secondary
3130 sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
3131 locale reasons. Last, strverscmp is ALWAYS available in coreutils,
3132 thanks to the gnulib library. */
3134 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
3136 return strverscmp (a->name, b->name);
3139 static int xstrcoll_version (V a, V b)
3140 { return cmp_version (a, b); }
3141 static int rev_xstrcoll_version (V a, V b)
3142 { return cmp_version (b, a); }
3143 static int xstrcoll_df_version (V a, V b)
3144 { DIRFIRST_CHECK (a, b); return cmp_version (a, b); }
3145 static int rev_xstrcoll_df_version (V a, V b)
3146 { DIRFIRST_CHECK (a, b); return cmp_version (b, a); }
3149 /* We have 2^3 different variants for each sortkey function
3150 (for 3 independent sort modes).
3151 The function pointers stored in this array must be dereferenced as:
3153 sort_variants[sort_key][use_strcmp][reverse][dirs_first]
3155 Note that the order in which sortkeys are listed in the function pointer
3156 array below is defined by the order of the elements in the time_type and
3159 #define LIST_SORTFUNCTION_VARIANTS(key_name) \
3162 { xstrcoll_##key_name, xstrcoll_df_##key_name }, \
3163 { rev_xstrcoll_##key_name, rev_xstrcoll_df_##key_name }, \
3166 { strcmp_##key_name, strcmp_df_##key_name }, \
3167 { rev_strcmp_##key_name, rev_strcmp_df_##key_name }, \
3171 static qsortFunc const sort_functions[][2][2][2] =
3173 LIST_SORTFUNCTION_VARIANTS (name),
3174 LIST_SORTFUNCTION_VARIANTS (extension),
3175 LIST_SORTFUNCTION_VARIANTS (size),
3179 { xstrcoll_version, xstrcoll_df_version },
3180 { rev_xstrcoll_version, rev_xstrcoll_df_version },
3183 /* We use NULL for the strcmp variants of version comparison
3184 since as explained in cmp_version definition, version comparison
3185 does not rely on xstrcoll, so it will never longjmp, and never
3186 need to try the strcmp fallback. */
3193 /* last are time sort functions */
3194 LIST_SORTFUNCTION_VARIANTS (mtime),
3195 LIST_SORTFUNCTION_VARIANTS (ctime),
3196 LIST_SORTFUNCTION_VARIANTS (atime)
3199 /* The number of sortkeys is calculated as
3200 the number of elements in the sort_type enum (i.e. sort_numtypes) +
3201 the number of elements in the time_type enum (i.e. time_numtypes) - 1
3202 This is because when sort_type==sort_time, we have up to
3203 time_numtypes possible sortkeys.
3205 This line verifies at compile-time that the array of sort functions has been
3206 initialized for all possible sortkeys. */
3207 verify (ARRAY_CARDINALITY (sort_functions)
3208 == sort_numtypes + time_numtypes - 1 );
3210 /* Set up SORTED_FILE to point to the in-use entries in CWD_FILE, in order. */
3213 initialize_ordering_vector (void)
3216 for (i = 0; i < cwd_n_used; i++)
3217 sorted_file[i] = &cwd_file[i];
3220 /* Sort the files now in the table. */
3227 if (sorted_file_alloc < cwd_n_used + cwd_n_used / 2)
3230 sorted_file = xnmalloc (cwd_n_used, 3 * sizeof *sorted_file);
3231 sorted_file_alloc = 3 * cwd_n_used;
3234 initialize_ordering_vector ();
3236 if (sort_type == sort_none)
3239 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
3240 ignore strcoll failures, as a failing strcoll might be a
3241 comparison function that is not a total order, and if we ignored
3242 the failure this might cause qsort to dump core. */
3244 if (! setjmp (failed_strcoll))
3245 use_strcmp = false; /* strcoll() succeeded */
3249 assert (sort_type != sort_version);
3250 initialize_ordering_vector ();
3253 /* When sort_type == sort_time, use time_type as subindex. */
3254 mpsort ((void const **) sorted_file, cwd_n_used,
3255 sort_functions[sort_type + (sort_type == sort_time ? time_type : 0)]
3256 [use_strcmp][sort_reverse]
3257 [directories_first]);
3260 /* List all the files now in the table. */
3263 print_current_files (void)
3270 for (i = 0; i < cwd_n_used; i++)
3272 print_file_name_and_frills (sorted_file[i]);
3278 print_many_per_line ();
3282 print_horizontal ();
3286 print_with_commas ();
3290 for (i = 0; i < cwd_n_used; i++)
3292 print_long_format (sorted_file[i]);
3293 DIRED_PUTCHAR ('\n');
3299 /* Return the expected number of columns in a long-format time stamp,
3300 or zero if it cannot be calculated. */
3303 long_time_expected_width (void)
3305 static int width = -1;
3310 struct tm const *tm = localtime (&epoch);
3311 char buf[TIME_STAMP_LEN_MAXIMUM + 1];
3313 /* In case you're wondering if localtime can fail with an input time_t
3314 value of 0, let's just say it's very unlikely, but not inconceivable.
3315 The TZ environment variable would have to specify a time zone that
3316 is 2**31-1900 years or more ahead of UTC. This could happen only on
3317 a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
3318 However, this is not possible with Solaris 10 or glibc-2.3.5, since
3319 their implementations limit the offset to 167:59 and 24:00, resp. */
3323 nstrftime (buf, sizeof buf, long_time_format[0], tm, 0, 0);
3325 width = mbsnwidth (buf, len, 0);
3335 /* Print the user or group name NAME, with numeric id ID, using a
3336 print width of WIDTH columns. */
3339 format_user_or_group (char const *name, unsigned long int id, int width)
3345 int width_gap = width - mbswidth (name, 0);
3346 int pad = MAX (0, width_gap);
3347 fputs (name, stdout);
3348 len = strlen (name) + pad;
3356 printf ("%*lu ", width, id);
3360 dired_pos += len + 1;
3363 /* Print the name or id of the user with id U, using a print width of
3367 format_user (uid_t u, int width, bool stat_ok)
3369 format_user_or_group (! stat_ok ? "?" :
3370 (numeric_ids ? NULL : getuser (u)), u, width);
3373 /* Likewise, for groups. */
3376 format_group (gid_t g, int width, bool stat_ok)
3378 format_user_or_group (! stat_ok ? "?" :
3379 (numeric_ids ? NULL : getgroup (g)), g, width);
3382 /* Return the number of columns that format_user_or_group will print. */
3385 format_user_or_group_width (char const *name, unsigned long int id)
3389 int len = mbswidth (name, 0);
3390 return MAX (0, len);
3394 char buf[INT_BUFSIZE_BOUND (unsigned long int)];
3395 sprintf (buf, "%lu", id);
3396 return strlen (buf);
3400 /* Return the number of columns that format_user will print. */
3403 format_user_width (uid_t u)
3405 return format_user_or_group_width (numeric_ids ? NULL : getuser (u), u);
3408 /* Likewise, for groups. */
3411 format_group_width (gid_t g)
3413 return format_user_or_group_width (numeric_ids ? NULL : getgroup (g), g);
3417 /* Print information about F in long format. */
3420 print_long_format (const struct fileinfo *f)
3424 [LONGEST_HUMAN_READABLE + 1 /* inode */
3425 + LONGEST_HUMAN_READABLE + 1 /* size in blocks */
3426 + sizeof (modebuf) - 1 + 1 /* mode string */
3427 + INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
3428 + LONGEST_HUMAN_READABLE + 2 /* major device number */
3429 + LONGEST_HUMAN_READABLE + 1 /* minor device number */
3430 + TIME_STAMP_LEN_MAXIMUM + 1 /* max length of time/date */
3434 struct timespec when_timespec;
3435 struct tm *when_local;
3437 /* Compute the mode string, except remove the trailing space if no
3438 file in this directory has an ACL or SELinux security context. */
3440 filemodestring (&f->stat, modebuf);
3443 modebuf[0] = filetype_letter[f->filetype];
3444 memset (modebuf + 1, '?', 10);
3449 else if (f->have_acl)
3455 when_timespec = get_stat_ctime (&f->stat);
3458 when_timespec = get_stat_mtime (&f->stat);
3461 when_timespec = get_stat_atime (&f->stat);
3471 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3472 sprintf (p, "%*s ", inode_number_width,
3473 (f->stat.st_ino == NOT_AN_INODE_NUMBER
3475 : umaxtostr (f->stat.st_ino, hbuf)));
3476 /* Increment by strlen (p) here, rather than by inode_number_width + 1.
3477 The latter is wrong when inode_number_width is zero. */
3481 if (print_block_size)
3483 char hbuf[LONGEST_HUMAN_READABLE + 1];
3484 char const *blocks =
3487 : human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts,
3488 ST_NBLOCKSIZE, output_block_size));
3490 for (pad = block_size_width - mbswidth (blocks, 0); 0 < pad; pad--)
3492 while ((*p++ = *blocks++))
3497 /* The last byte of the mode string is the POSIX
3498 "optional alternate access method flag". */
3500 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3501 sprintf (p, "%s %*s ", modebuf, nlink_width,
3502 ! f->stat_ok ? "?" : umaxtostr (f->stat.st_nlink, hbuf));
3504 /* Increment by strlen (p) here, rather than by, e.g.,
3505 sizeof modebuf - 2 + any_has_acl + 1 + nlink_width + 1.
3506 The latter is wrong when nlink_width is zero. */
3511 if (print_owner | print_group | print_author | print_scontext)
3513 DIRED_FPUTS (buf, stdout, p - buf);
3516 format_user (f->stat.st_uid, owner_width, f->stat_ok);
3519 format_group (f->stat.st_gid, group_width, f->stat_ok);
3522 format_user (f->stat.st_author, author_width, f->stat_ok);
3525 format_user_or_group (f->scontext, 0, scontext_width);
3531 && (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode)))
3533 char majorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3534 char minorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3535 int blanks_width = (file_size_width
3536 - (major_device_number_width + 2
3537 + minor_device_number_width));
3538 sprintf (p, "%*s, %*s ",
3539 major_device_number_width + MAX (0, blanks_width),
3540 umaxtostr (major (f->stat.st_rdev), majorbuf),
3541 minor_device_number_width,
3542 umaxtostr (minor (f->stat.st_rdev), minorbuf));
3543 p += file_size_width + 1;
3547 char hbuf[LONGEST_HUMAN_READABLE + 1];
3551 : human_readable (unsigned_file_size (f->stat.st_size),
3552 hbuf, human_output_opts, 1, file_output_block_size));
3554 for (pad = file_size_width - mbswidth (size, 0); 0 < pad; pad--)
3556 while ((*p++ = *size++))
3561 when_local = localtime (&when_timespec.tv_sec);
3565 if (f->stat_ok && when_local)
3567 struct timespec six_months_ago;
3571 /* If the file appears to be in the future, update the current
3572 time, in case the file happens to have been modified since
3573 the last time we checked the clock. */
3574 if (timespec_cmp (current_time, when_timespec) < 0)
3576 /* Note that gettime may call gettimeofday which, on some non-
3577 compliant systems, clobbers the buffer used for localtime's result.
3578 But it's ok here, because we use a gettimeofday wrapper that
3579 saves and restores the buffer around the gettimeofday call. */
3580 gettime (¤t_time);
3583 /* Consider a time to be recent if it is within the past six
3584 months. A Gregorian year has 365.2425 * 24 * 60 * 60 ==
3585 31556952 seconds on the average. Write this value as an
3586 integer constant to avoid floating point hassles. */
3587 six_months_ago.tv_sec = current_time.tv_sec - 31556952 / 2;
3588 six_months_ago.tv_nsec = current_time.tv_nsec;
3590 recent = (timespec_cmp (six_months_ago, when_timespec) < 0
3591 && (timespec_cmp (when_timespec, current_time) < 0));
3592 fmt = long_time_format[recent];
3594 /* We assume here that all time zones are offset from UTC by a
3595 whole number of seconds. */
3596 s = nstrftime (p, TIME_STAMP_LEN_MAXIMUM + 1, fmt,
3597 when_local, 0, when_timespec.tv_nsec);
3605 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
3610 /* The time cannot be converted using the desired format, so
3611 print it as a huge integer number of seconds. */
3612 char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
3613 sprintf (p, "%*s ", long_time_expected_width (),
3616 : timetostr (when_timespec.tv_sec, hbuf)));
3617 /* FIXME: (maybe) We discarded when_timespec.tv_nsec. */
3621 DIRED_FPUTS (buf, stdout, p - buf);
3622 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
3623 f->stat_ok, f->filetype, &dired_obstack);
3625 if (f->filetype == symbolic_link)
3629 DIRED_FPUTS_LITERAL (" -> ", stdout);
3630 print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1,
3631 f->stat_ok, f->filetype, NULL);
3632 if (indicator_style != none)
3633 print_type_indicator (true, f->linkmode, unknown);
3636 else if (indicator_style != none)
3637 print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
3640 /* Output to OUT a quoted representation of the file name NAME,
3641 using OPTIONS to control quoting. Produce no output if OUT is NULL.
3642 Store the number of screen columns occupied by NAME's quoted
3643 representation into WIDTH, if non-NULL. Return the number of bytes
3647 quote_name (FILE *out, const char *name, struct quoting_options const *options,
3650 char smallbuf[BUFSIZ];
3651 size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, name, -1, options);
3653 size_t displayed_width IF_LINT (= 0);
3655 if (len < sizeof smallbuf)
3659 buf = alloca (len + 1);
3660 quotearg_buffer (buf, len + 1, name, -1, options);
3663 if (qmark_funny_chars)
3668 char const *p = buf;
3669 char const *plimit = buf + len;
3671 displayed_width = 0;
3676 case ' ': case '!': case '"': case '#': case '%':
3677 case '&': case '\'': case '(': case ')': case '*':
3678 case '+': case ',': case '-': case '.': case '/':
3679 case '0': case '1': case '2': case '3': case '4':
3680 case '5': case '6': case '7': case '8': case '9':
3681 case ':': case ';': case '<': case '=': case '>':
3683 case 'A': case 'B': case 'C': case 'D': case 'E':
3684 case 'F': case 'G': case 'H': case 'I': case 'J':
3685 case 'K': case 'L': case 'M': case 'N': case 'O':
3686 case 'P': case 'Q': case 'R': case 'S': case 'T':
3687 case 'U': case 'V': case 'W': case 'X': case 'Y':
3689 case '[': case '\\': case ']': case '^': case '_':
3690 case 'a': case 'b': case 'c': case 'd': case 'e':
3691 case 'f': case 'g': case 'h': case 'i': case 'j':
3692 case 'k': case 'l': case 'm': case 'n': case 'o':
3693 case 'p': case 'q': case 'r': case 's': case 't':
3694 case 'u': case 'v': case 'w': case 'x': case 'y':
3695 case 'z': case '{': case '|': case '}': case '~':
3696 /* These characters are printable ASCII characters. */
3698 displayed_width += 1;
3701 /* If we have a multibyte sequence, copy it until we
3702 reach its end, replacing each non-printable multibyte
3703 character with a single question mark. */
3705 mbstate_t mbstate = { 0, };
3712 bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
3714 if (bytes == (size_t) -1)
3716 /* An invalid multibyte sequence was
3717 encountered. Skip one input byte, and
3718 put a question mark. */
3721 displayed_width += 1;
3725 if (bytes == (size_t) -2)
3727 /* An incomplete multibyte character
3728 at the end. Replace it entirely with
3732 displayed_width += 1;
3737 /* A null wide character was encountered. */
3743 /* A printable multibyte character.
3745 for (; bytes > 0; --bytes)
3747 displayed_width += w;
3751 /* An unprintable multibyte character.
3752 Replace it entirely with a question
3756 displayed_width += 1;
3759 while (! mbsinit (&mbstate));
3764 /* The buffer may have shrunk. */
3771 char const *plimit = buf + len;
3775 if (! isprint (to_uchar (*p)))
3779 displayed_width = len;
3782 else if (width != NULL)
3786 displayed_width = mbsnwidth (buf, len, 0);
3790 char const *p = buf;
3791 char const *plimit = buf + len;
3793 displayed_width = 0;
3796 if (isprint (to_uchar (*p)))
3804 fwrite (buf, 1, len, out);
3806 *width = displayed_width;
3811 print_name_with_quoting (const char *p, mode_t mode, int linkok,
3812 bool stat_ok, enum filetype type,
3813 struct obstack *stack)
3815 bool used_color_this_time
3817 && print_color_indicator (p, mode, linkok, stat_ok, type));
3820 PUSH_CURRENT_DIRED_POS (stack);
3822 dired_pos += quote_name (stdout, p, filename_quoting_options, NULL);
3825 PUSH_CURRENT_DIRED_POS (stack);
3827 if (used_color_this_time)
3830 prep_non_filename_text ();
3835 prep_non_filename_text (void)
3837 if (color_indicator[C_END].string != NULL)
3838 put_indicator (&color_indicator[C_END]);
3841 put_indicator (&color_indicator[C_LEFT]);
3842 put_indicator (&color_indicator[C_RESET]);
3843 put_indicator (&color_indicator[C_RIGHT]);
3847 /* Print the file name of `f' with appropriate quoting.
3848 Also print file size, inode number, and filetype indicator character,
3849 as requested by switches. */
3852 print_file_name_and_frills (const struct fileinfo *f)
3854 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
3857 printf ("%*s ", format == with_commas ? 0 : inode_number_width,
3858 umaxtostr (f->stat.st_ino, buf));
3860 if (print_block_size)
3861 printf ("%*s ", format == with_commas ? 0 : block_size_width,
3862 human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts,
3863 ST_NBLOCKSIZE, output_block_size));
3866 printf ("%*s ", format == with_commas ? 0 : scontext_width, f->scontext);
3868 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
3869 f->stat_ok, f->filetype, NULL);
3871 if (indicator_style != none)
3872 print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
3875 /* Given these arguments describing a file, return the single-byte
3876 type indicator, or 0. */
3878 get_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
3882 if (stat_ok ? S_ISREG (mode) : type == normal)
3884 if (stat_ok && indicator_style == classify && (mode & S_IXUGO))
3891 if (stat_ok ? S_ISDIR (mode) : type == directory || type == arg_directory)
3893 else if (indicator_style == slash)
3895 else if (stat_ok ? S_ISLNK (mode) : type == symbolic_link)
3897 else if (stat_ok ? S_ISFIFO (mode) : type == fifo)
3899 else if (stat_ok ? S_ISSOCK (mode) : type == sock)
3901 else if (stat_ok && S_ISDOOR (mode))
3910 print_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
3912 char c = get_type_indicator (stat_ok, mode, type);
3918 /* Return true if NAME has a capability (see linux/capability.h) */
3920 has_capability (char const *name)
3925 cap_t cap_d = cap_get_file (name);
3929 result = cap_to_text (cap_d, NULL);
3934 /* check if human-readable capability string is empty */
3935 has_cap = !!*result;
3942 has_capability (char const *name)
3948 /* Returns whether any color sequence was printed. */
3950 print_color_indicator (const char *name, mode_t mode, int linkok,
3951 bool stat_ok, enum filetype filetype)
3954 struct color_ext_type *ext; /* Color extension */
3955 size_t len; /* Length of name */
3957 /* Is this a nonexistent file? If so, linkok == -1. */
3959 if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
3963 static enum indicator_no filetype_indicator[] = FILETYPE_INDICATORS;
3964 type = filetype_indicator[filetype];
3971 if ((mode & S_ISUID) != 0)
3973 else if ((mode & S_ISGID) != 0)
3975 else if (has_capability (name))
3977 else if ((mode & S_IXUGO) != 0)
3980 else if (S_ISDIR (mode))
3982 if ((mode & S_ISVTX) && (mode & S_IWOTH))
3983 type = C_STICKY_OTHER_WRITABLE;
3984 else if ((mode & S_IWOTH) != 0)
3985 type = C_OTHER_WRITABLE;
3986 else if ((mode & S_ISVTX) != 0)
3991 else if (S_ISLNK (mode))
3992 type = ((!linkok && color_indicator[C_ORPHAN].string)
3993 ? C_ORPHAN : C_LINK);
3994 else if (S_ISFIFO (mode))
3996 else if (S_ISSOCK (mode))
3998 else if (S_ISBLK (mode))
4000 else if (S_ISCHR (mode))
4002 else if (S_ISDOOR (mode))
4006 /* Classify a file of some other type as C_ORPHAN. */
4011 /* Check the file's suffix only if still classified as C_FILE. */
4015 /* Test if NAME has a recognized suffix. */
4017 len = strlen (name);
4018 name += len; /* Pointer to final \0. */
4019 for (ext = color_ext_list; ext != NULL; ext = ext->next)
4021 if (ext->ext.len <= len
4022 && strncmp (name - ext->ext.len, ext->ext.string,
4029 const struct bin_str *const s
4030 = ext ? &(ext->seq) : &color_indicator[type];
4031 if (s->string != NULL)
4033 put_indicator (&color_indicator[C_LEFT]);
4035 put_indicator (&color_indicator[C_RIGHT]);
4043 /* Output a color indicator (which may contain nulls). */
4045 put_indicator (const struct bin_str *ind)
4050 prep_non_filename_text ();
4053 fwrite (ind->string, ind->len, 1, stdout);
4057 length_of_file_name_and_frills (const struct fileinfo *f)
4061 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
4064 len += 1 + (format == with_commas
4065 ? strlen (umaxtostr (f->stat.st_ino, buf))
4066 : inode_number_width);
4068 if (print_block_size)
4069 len += 1 + (format == with_commas
4070 ? strlen (human_readable (ST_NBLOCKS (f->stat), buf,
4071 human_output_opts, ST_NBLOCKSIZE,
4073 : block_size_width);
4076 len += 1 + (format == with_commas ? strlen (f->scontext) : scontext_width);
4078 quote_name (NULL, f->name, filename_quoting_options, &name_width);
4081 if (indicator_style != none)
4083 char c = get_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4091 print_many_per_line (void)
4093 size_t row; /* Current row. */
4094 size_t cols = calculate_columns (true);
4095 struct column_info const *line_fmt = &column_info[cols - 1];
4097 /* Calculate the number of rows that will be in each column except possibly
4098 for a short column on the right. */
4099 size_t rows = cwd_n_used / cols + (cwd_n_used % cols != 0);
4101 for (row = 0; row < rows; row++)
4104 size_t filesno = row;
4107 /* Print the next row. */
4110 struct fileinfo const *f = sorted_file[filesno];
4111 size_t name_length = length_of_file_name_and_frills (f);
4112 size_t max_name_length = line_fmt->col_arr[col++];
4113 print_file_name_and_frills (f);
4116 if (filesno >= cwd_n_used)
4119 indent (pos + name_length, pos + max_name_length);
4120 pos += max_name_length;
4127 print_horizontal (void)
4131 size_t cols = calculate_columns (false);
4132 struct column_info const *line_fmt = &column_info[cols - 1];
4133 struct fileinfo const *f = sorted_file[0];
4134 size_t name_length = length_of_file_name_and_frills (f);
4135 size_t max_name_length = line_fmt->col_arr[0];
4137 /* Print first entry. */
4138 print_file_name_and_frills (f);
4141 for (filesno = 1; filesno < cwd_n_used; ++filesno)
4143 size_t col = filesno % cols;
4152 indent (pos + name_length, pos + max_name_length);
4153 pos += max_name_length;
4156 f = sorted_file[filesno];
4157 print_file_name_and_frills (f);
4159 name_length = length_of_file_name_and_frills (f);
4160 max_name_length = line_fmt->col_arr[col];
4166 print_with_commas (void)
4171 for (filesno = 0; filesno < cwd_n_used; filesno++)
4173 struct fileinfo const *f = sorted_file[filesno];
4174 size_t len = length_of_file_name_and_frills (f);
4180 if (pos + len + 2 < line_length)
4192 putchar (separator);
4195 print_file_name_and_frills (f);
4201 /* Assuming cursor is at position FROM, indent up to position TO.
4202 Use a TAB character instead of two or more spaces whenever possible. */
4205 indent (size_t from, size_t to)
4209 if (tabsize != 0 && to / tabsize > (from + 1) / tabsize)
4212 from += tabsize - from % tabsize;
4222 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
4223 /* FIXME: maybe remove this function someday. See about using a
4224 non-malloc'ing version of file_name_concat. */
4227 attach (char *dest, const char *dirname, const char *name)
4229 const char *dirnamep = dirname;
4231 /* Copy dirname if it is not ".". */
4232 if (dirname[0] != '.' || dirname[1] != 0)
4235 *dest++ = *dirnamep++;
4236 /* Add '/' if `dirname' doesn't already end with it. */
4237 if (dirnamep > dirname && dirnamep[-1] != '/')
4245 /* Allocate enough column info suitable for the current number of
4246 files and display columns, and initialize the info to represent the
4247 narrowest possible columns. */
4250 init_column_info (void)
4253 size_t max_cols = MIN (max_idx, cwd_n_used);
4255 /* Currently allocated columns in column_info. */
4256 static size_t column_info_alloc;
4258 if (column_info_alloc < max_cols)
4260 size_t new_column_info_alloc;
4263 if (max_cols < max_idx / 2)
4265 /* The number of columns is far less than the display width
4266 allows. Grow the allocation, but only so that it's
4267 double the current requirements. If the display is
4268 extremely wide, this avoids allocating a lot of memory
4269 that is never needed. */
4270 column_info = xnrealloc (column_info, max_cols,
4271 2 * sizeof *column_info);
4272 new_column_info_alloc = 2 * max_cols;
4276 column_info = xnrealloc (column_info, max_idx, sizeof *column_info);
4277 new_column_info_alloc = max_idx;
4280 /* Allocate the new size_t objects by computing the triangle
4281 formula n * (n + 1) / 2, except that we don't need to
4282 allocate the part of the triangle that we've already
4283 allocated. Check for address arithmetic overflow. */
4285 size_t column_info_growth = new_column_info_alloc - column_info_alloc;
4286 size_t s = column_info_alloc + 1 + new_column_info_alloc;
4287 size_t t = s * column_info_growth;
4288 if (s < new_column_info_alloc || t / column_info_growth != s)
4290 p = xnmalloc (t / 2, sizeof *p);
4293 /* Grow the triangle by parceling out the cells just allocated. */
4294 for (i = column_info_alloc; i < new_column_info_alloc; i++)
4296 column_info[i].col_arr = p;
4300 column_info_alloc = new_column_info_alloc;
4303 for (i = 0; i < max_cols; ++i)
4307 column_info[i].valid_len = true;
4308 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
4309 for (j = 0; j <= i; ++j)
4310 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
4314 /* Calculate the number of columns needed to represent the current set
4315 of files in the current display width. */
4318 calculate_columns (bool by_columns)
4320 size_t filesno; /* Index into cwd_file. */
4321 size_t cols; /* Number of files across. */
4323 /* Normally the maximum number of columns is determined by the
4324 screen width. But if few files are available this might limit it
4326 size_t max_cols = MIN (max_idx, cwd_n_used);
4328 init_column_info ();
4330 /* Compute the maximum number of possible columns. */
4331 for (filesno = 0; filesno < cwd_n_used; ++filesno)
4333 struct fileinfo const *f = sorted_file[filesno];
4334 size_t name_length = length_of_file_name_and_frills (f);
4337 for (i = 0; i < max_cols; ++i)
4339 if (column_info[i].valid_len)
4341 size_t idx = (by_columns
4342 ? filesno / ((cwd_n_used + i) / (i + 1))
4343 : filesno % (i + 1));
4344 size_t real_length = name_length + (idx == i ? 0 : 2);
4346 if (column_info[i].col_arr[idx] < real_length)
4348 column_info[i].line_len += (real_length
4349 - column_info[i].col_arr[idx]);
4350 column_info[i].col_arr[idx] = real_length;
4351 column_info[i].valid_len = (column_info[i].line_len
4358 /* Find maximum allowed columns. */
4359 for (cols = max_cols; 1 < cols; --cols)
4361 if (column_info[cols - 1].valid_len)
4371 if (status != EXIT_SUCCESS)
4372 fprintf (stderr, _("Try `%s --help' for more information.\n"),
4376 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
4378 List information about the FILEs (the current directory by default).\n\
4379 Sort entries alphabetically if none of -cftuvSUX nor --sort.\n\
4383 Mandatory arguments to long options are mandatory for short options too.\n\
4386 -a, --all do not ignore entries starting with .\n\
4387 -A, --almost-all do not list implied . and ..\n\
4388 --author with -l, print the author of each file\n\
4389 -b, --escape print octal escapes for nongraphic characters\n\
4392 --block-size=SIZE use SIZE-byte blocks\n\
4393 -B, --ignore-backups do not list implied entries ending with ~\n\
4394 -c with -lt: sort by, and show, ctime (time of last\n\
4395 modification of file status information)\n\
4396 with -l: show ctime and sort by name\n\
4397 otherwise: sort by ctime\n\
4400 -C list entries by columns\n\
4401 --color[=WHEN] control whether color is used to distinguish file\n\
4402 types. WHEN may be `never', `always', or `auto'\n\
4403 -d, --directory list directory entries instead of contents,\n\
4404 and do not dereference symbolic links\n\
4405 -D, --dired generate output designed for Emacs' dired mode\n\
4408 -f do not sort, enable -aU, disable -ls --color\n\
4409 -F, --classify append indicator (one of */=>@|) to entries\n\
4410 --file-type likewise, except do not append `*'\n\
4411 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
4412 single-column -1, verbose -l, vertical -C\n\
4413 --full-time like -l --time-style=full-iso\n\
4416 -g like -l, but do not list owner\n\
4419 --group-directories-first\n\
4420 group directories before files.\n\
4421 augment with a --sort option, but any\n\
4422 use of --sort=none (-U) disables grouping\n\
4425 -G, --no-group in a long listing, don't print group names\n\
4426 -h, --human-readable with -l, print sizes in human readable format\n\
4427 (e.g., 1K 234M 2G)\n\
4428 --si likewise, but use powers of 1000 not 1024\n\
4431 -H, --dereference-command-line\n\
4432 follow symbolic links listed on the command line\n\
4433 --dereference-command-line-symlink-to-dir\n\
4434 follow each command line symbolic link\n\
4435 that points to a directory\n\
4436 --hide=PATTERN do not list implied entries matching shell PATTERN\n\
4437 (overridden by -a or -A)\n\
4440 --indicator-style=WORD append indicator with style WORD to entry names:\n\
4441 none (default), slash (-p),\n\
4442 file-type (--file-type), classify (-F)\n\
4443 -i, --inode print the index number of each file\n\
4444 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
4445 -k like --block-size=1K\n\
4448 -l use a long listing format\n\
4449 -L, --dereference when showing file information for a symbolic\n\
4450 link, show information for the file the link\n\
4451 references rather than for the link itself\n\
4452 -m fill width with a comma separated list of entries\n\
4455 -n, --numeric-uid-gid like -l, but list numeric user and group IDs\n\
4456 -N, --literal print raw entry names (don't treat e.g. control\n\
4457 characters specially)\n\
4458 -o like -l, but do not list group information\n\
4459 -p, --indicator-style=slash\n\
4460 append / indicator to directories\n\
4463 -q, --hide-control-chars print ? instead of non graphic characters\n\
4464 --show-control-chars show non graphic characters as-is (default\n\
4465 unless program is `ls' and output is a terminal)\n\
4466 -Q, --quote-name enclose entry names in double quotes\n\
4467 --quoting-style=WORD use quoting style WORD for entry names:\n\
4468 literal, locale, shell, shell-always, c, escape\n\
4471 -r, --reverse reverse order while sorting\n\
4472 -R, --recursive list subdirectories recursively\n\
4473 -s, --size print the size of each file, in blocks\n\
4476 -S sort by file size\n\
4477 --sort=WORD sort by WORD instead of name: none -U,\n\
4478 extension -X, size -S, time -t, version -v\n\
4479 --time=WORD with -l, show time as WORD instead of modification\n\
4480 time: atime -u, access -u, use -u, ctime -c,\n\
4481 or status -c; use specified time as sort key\n\
4485 --time-style=STYLE with -l, show times using style STYLE:\n\
4486 full-iso, long-iso, iso, locale, +FORMAT.\n\
4487 FORMAT is interpreted like `date'; if FORMAT is\n\
4488 FORMAT1<newline>FORMAT2, FORMAT1 applies to\n\
4489 non-recent files and FORMAT2 to recent files;\n\
4490 if STYLE is prefixed with `posix-', STYLE\n\
4491 takes effect only outside the POSIX locale\n\
4494 -t sort by modification time\n\
4495 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
4498 -u with -lt: sort by, and show, access time\n\
4499 with -l: show access time and sort by name\n\
4500 otherwise: sort by access time\n\
4501 -U do not sort; list entries in directory order\n\
4502 -v sort by version\n\
4505 -w, --width=COLS assume screen width instead of current value\n\
4506 -x list entries by lines instead of by columns\n\
4507 -X sort alphabetically by entry extension\n\
4508 -Z, --context print any SELinux security context of each file\n\
4509 -1 list one file per line\n\
4511 fputs (HELP_OPTION_DESCRIPTION, stdout);
4512 fputs (VERSION_OPTION_DESCRIPTION, stdout);
4514 SIZE may be (or may be an integer optionally followed by) one of following:\n\
4515 kB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
4519 By default, color is not used to distinguish types of files. That is\n\
4520 equivalent to using --color=none. Using the --color option without the\n\
4521 optional WHEN argument is equivalent to using --color=always. With\n\
4522 --color=auto, color codes are output only if standard output is connected\n\
4523 to a terminal (tty). The environment variable LS_COLORS can influence the\n\
4524 colors, and can be set easily by the dircolors command.\n\
4528 Exit status is 0 if OK, 1 if minor problems, 2 if serious trouble.\n\
4530 emit_bug_reporting_address ();