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"
108 #include "strverscmp.h"
110 #include "areadlink.h"
112 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
113 : (ls_mode == LS_MULTI_COL \
117 proper_name ("Richard M. Stallman"), \
118 proper_name ("David MacKenzie")
120 #define obstack_chunk_alloc malloc
121 #define obstack_chunk_free free
123 /* Return an int indicating the result of comparing two integers.
124 Subtracting doesn't always work, due to overflow. */
125 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
127 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
128 # define st_author st_uid
145 /* Display letters and indicators for each filetype.
146 Keep these in sync with enum filetype. */
147 static char const filetype_letter[] = "?pcdb-lswd";
149 /* Ensure that filetype and filetype_letter have the same
150 number of elements. */
151 verify (sizeof filetype_letter - 1 == arg_directory + 1);
153 #define FILETYPE_INDICATORS \
155 C_ORPHAN, C_FIFO, C_CHR, C_DIR, C_BLK, C_FILE, \
156 C_LINK, C_SOCK, C_FILE, C_DIR \
165 /* For symbolic link, name of the file linked to, otherwise zero. */
170 enum filetype filetype;
172 /* For symbolic link and long listing, st_mode of file linked to, otherwise
176 /* SELinux security context. */
177 security_context_t scontext;
181 /* For symbolic link and color printing, true if linked-to file
182 exists, otherwise false. */
185 /* For long listings, true if the file has an access control list,
186 or an SELinux security context. */
190 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
192 /* Null is a valid character in a color indicator (think about Epson
193 printers, for example) so we have to use a length/buffer string
198 size_t len; /* Number of bytes */
199 const char *string; /* Pointer to the same */
203 # define tcgetpgrp(Fd) 0
206 static size_t quote_name (FILE *out, const char *name,
207 struct quoting_options const *options,
209 static char *make_link_name (char const *name, char const *linkname);
210 static int decode_switches (int argc, char **argv);
211 static bool file_ignored (char const *name);
212 static uintmax_t gobble_file (char const *name, enum filetype type,
213 ino_t inode, bool command_line_arg,
214 char const *dirname);
215 static bool print_color_indicator (const char *name, mode_t mode, int linkok,
216 bool stat_ok, enum filetype type);
217 static void put_indicator (const struct bin_str *ind);
218 static void add_ignore_pattern (const char *pattern);
219 static void attach (char *dest, const char *dirname, const char *name);
220 static void clear_files (void);
221 static void extract_dirs_from_files (char const *dirname,
222 bool command_line_arg);
223 static void get_link_name (char const *filename, struct fileinfo *f,
224 bool command_line_arg);
225 static void indent (size_t from, size_t to);
226 static size_t calculate_columns (bool by_columns);
227 static void print_current_files (void);
228 static void print_dir (char const *name, char const *realname,
229 bool command_line_arg);
230 static void print_file_name_and_frills (const struct fileinfo *f);
231 static void print_horizontal (void);
232 static int format_user_width (uid_t u);
233 static int format_group_width (gid_t g);
234 static void print_long_format (const struct fileinfo *f);
235 static void print_many_per_line (void);
236 static void print_name_with_quoting (const char *p, mode_t mode,
237 int linkok, bool stat_ok,
239 struct obstack *stack);
240 static void prep_non_filename_text (void);
241 static void print_type_indicator (bool stat_ok, mode_t mode,
243 static void print_with_commas (void);
244 static void queue_directory (char const *name, char const *realname,
245 bool command_line_arg);
246 static void sort_files (void);
247 static void parse_ls_color (void);
248 void usage (int status);
250 /* Initial size of hash table.
251 Most hierarchies are likely to be shallower than this. */
252 #define INITIAL_TABLE_SIZE 30
254 /* The set of `active' directories, from the current command-line argument
255 to the level in the hierarchy at which files are being listed.
256 A directory is represented by its device and inode numbers (struct dev_ino).
257 A directory is added to this set when ls begins listing it or its
258 entries, and it is removed from the set just after ls has finished
259 processing it. This set is used solely to detect loops, e.g., with
260 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
261 static Hash_table *active_dir_set;
263 #define LOOP_DETECT (!!active_dir_set)
265 /* The table of files in the current directory:
267 `cwd_file' points to a vector of `struct fileinfo', one per file.
268 `cwd_n_alloc' is the number of elements space has been allocated for.
269 `cwd_n_used' is the number actually in use. */
271 /* Address of block containing the files that are described. */
272 static struct fileinfo *cwd_file;
274 /* Length of block that `cwd_file' points to, measured in files. */
275 static size_t cwd_n_alloc;
277 /* Index of first unused slot in `cwd_file'. */
278 static size_t cwd_n_used;
280 /* Vector of pointers to files, in proper sorted order, and the number
281 of entries allocated for it. */
282 static void **sorted_file;
283 static size_t sorted_file_alloc;
285 /* When true, in a color listing, color each symlink name according to the
286 type of file it points to. Otherwise, color them according to the `ln'
287 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
288 regardless. This is set when `ln=target' appears in LS_COLORS. */
290 static bool color_symlink_as_referent;
292 /* mode of appropriate file for colorization */
293 #define FILE_OR_LINK_MODE(File) \
294 ((color_symlink_as_referent & (File)->linkok) \
295 ? (File)->linkmode : (File)->stat.st_mode)
298 /* Record of one pending directory waiting to be listed. */
303 /* If the directory is actually the file pointed to by a symbolic link we
304 were told to list, `realname' will contain the name of the symbolic
305 link, otherwise zero. */
307 bool command_line_arg;
308 struct pending *next;
311 static struct pending *pending_dirs;
313 /* Current time in seconds and nanoseconds since 1970, updated as
314 needed when deciding whether a file is recent. */
316 static struct timespec current_time;
318 static bool print_scontext;
319 static char UNKNOWN_SECURITY_CONTEXT[] = "?";
321 /* Whether any of the files has an ACL. This affects the width of the
324 static bool any_has_acl;
326 /* The number of columns to use for columns containing inode numbers,
327 block sizes, link counts, owners, groups, authors, major device
328 numbers, minor device numbers, and file sizes, respectively. */
330 static int inode_number_width;
331 static int block_size_width;
332 static int nlink_width;
333 static int scontext_width;
334 static int owner_width;
335 static int group_width;
336 static int author_width;
337 static int major_device_number_width;
338 static int minor_device_number_width;
339 static int file_size_width;
343 /* long_format for lots of info, one per line.
344 one_per_line for just names, one per line.
345 many_per_line for just names, many per line, sorted vertically.
346 horizontal for just names, many per line, sorted horizontally.
347 with_commas for just names, many per line, separated by commas.
349 -l (and other options that imply -l), -1, -C, -x and -m control
354 long_format, /* -l and other options that imply -l */
355 one_per_line, /* -1 */
356 many_per_line, /* -C */
361 static enum format format;
363 /* `full-iso' uses full ISO-style dates and times. `long-iso' uses longer
364 ISO-style time stamps, though shorter than `full-iso'. `iso' uses shorter
365 ISO-style time stamps. `locale' uses locale-dependent time stamps. */
368 full_iso_time_style, /* --time-style=full-iso */
369 long_iso_time_style, /* --time-style=long-iso */
370 iso_time_style, /* --time-style=iso */
371 locale_time_style /* --time-style=locale */
374 static char const *const time_style_args[] =
376 "full-iso", "long-iso", "iso", "locale", NULL
378 static enum time_style const time_style_types[] =
380 full_iso_time_style, long_iso_time_style, iso_time_style,
383 ARGMATCH_VERIFY (time_style_args, time_style_types);
385 /* Type of time to print or sort by. Controlled by -c and -u.
386 The values of each item of this enum are important since they are
387 used as indices in the sort functions array (see sort_files()). */
391 time_mtime, /* default */
394 time_numtypes /* the number of elements of this enum */
397 static enum time_type time_type;
399 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v.
400 The values of each item of this enum are important since they are
401 used as indices in the sort functions array (see sort_files()). */
405 sort_none = -1, /* -U */
406 sort_name, /* default */
407 sort_extension, /* -X */
409 sort_version, /* -v */
411 sort_numtypes /* the number of elements of this enum */
414 static enum sort_type sort_type;
416 /* Direction of sort.
417 false means highest first if numeric,
418 lowest first if alphabetic;
419 these are the defaults.
420 true means the opposite order in each case. -r */
422 static bool sort_reverse;
424 /* True means to display owner information. -g turns this off. */
426 static bool print_owner = true;
428 /* True means to display author information. */
430 static bool print_author;
432 /* True means to display group information. -G and -o turn this off. */
434 static bool print_group = true;
436 /* True means print the user and group id's as numbers rather
439 static bool numeric_ids;
441 /* True means mention the size in blocks of each file. -s */
443 static bool print_block_size;
445 /* Human-readable options for output. */
446 static int human_output_opts;
448 /* The units to use when printing sizes other than file sizes. */
449 static uintmax_t output_block_size;
451 /* Likewise, but for file sizes. */
452 static uintmax_t file_output_block_size = 1;
454 /* Follow the output with a special string. Using this format,
455 Emacs' dired mode starts up twice as fast, and can handle all
456 strange characters in file names. */
459 /* `none' means don't mention the type of files.
460 `slash' means mention directories only, with a '/'.
461 `file_type' means mention file types.
462 `classify' means mention file types and mark executables.
464 Controlled by -F, -p, and --indicator-style. */
468 none, /* --indicator-style=none */
469 slash, /* -p, --indicator-style=slash */
470 file_type, /* --indicator-style=file-type */
471 classify /* -F, --indicator-style=classify */
474 static enum indicator_style indicator_style;
476 /* Names of indicator styles. */
477 static char const *const indicator_style_args[] =
479 "none", "slash", "file-type", "classify", NULL
481 static enum indicator_style const indicator_style_types[] =
483 none, slash, file_type, classify
485 ARGMATCH_VERIFY (indicator_style_args, indicator_style_types);
487 /* True means use colors to mark types. Also define the different
488 colors as well as the stuff for the LS_COLORS environment variable.
489 The LS_COLORS variable is now in a termcap-like format. */
491 static bool print_with_color;
493 /* Whether we used any colors in the output so far. If so, we will
494 need to restore the default color later. If not, we will need to
495 call prep_non_filename_text before using color for the first time. */
497 static bool used_color = false;
501 color_never, /* 0: default or --color=never */
502 color_always, /* 1: --color=always */
503 color_if_tty /* 2: --color=tty */
506 enum Dereference_symlink
510 DEREF_COMMAND_LINE_ARGUMENTS, /* -H */
511 DEREF_COMMAND_LINE_SYMLINK_TO_DIR, /* the default, in certain cases */
512 DEREF_ALWAYS /* -L */
517 C_LEFT, C_RIGHT, C_END, C_RESET, C_NORM, C_FILE, C_DIR, C_LINK,
519 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR, C_SETUID, C_SETGID,
520 C_STICKY, C_OTHER_WRITABLE, C_STICKY_OTHER_WRITABLE, C_CAP
523 static const char *const indicator_name[]=
525 "lc", "rc", "ec", "rs", "no", "fi", "di", "ln", "pi", "so",
526 "bd", "cd", "mi", "or", "ex", "do", "su", "sg", "st",
527 "ow", "tw", "ca", NULL
530 struct color_ext_type
532 struct bin_str ext; /* The extension we're looking for */
533 struct bin_str seq; /* The sequence to output when we do */
534 struct color_ext_type *next; /* Next in list */
537 static struct bin_str color_indicator[] =
539 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
540 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
541 { 0, NULL }, /* ec: End color (replaces lc+no+rc) */
542 { LEN_STR_PAIR ("0") }, /* rs: Reset to ordinary colors */
543 { 0, NULL }, /* no: Normal */
544 { 0, NULL }, /* fi: File: default */
545 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
546 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
547 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
548 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
549 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
550 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
551 { 0, NULL }, /* mi: Missing file: undefined */
552 { 0, NULL }, /* or: Orphaned symlink: undefined */
553 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
554 { LEN_STR_PAIR ("01;35") }, /* do: Door: bright magenta */
555 { LEN_STR_PAIR ("37;41") }, /* su: setuid: white on red */
556 { LEN_STR_PAIR ("30;43") }, /* sg: setgid: black on yellow */
557 { LEN_STR_PAIR ("37;44") }, /* st: sticky: black on blue */
558 { LEN_STR_PAIR ("34;42") }, /* ow: other-writable: blue on green */
559 { LEN_STR_PAIR ("30;42") }, /* tw: ow w/ sticky: black on green */
560 { LEN_STR_PAIR ("30;41") }, /* capability: black on red */
564 static struct color_ext_type *color_ext_list = NULL;
566 /* Buffer for color sequences */
567 static char *color_buf;
569 /* True means to check for orphaned symbolic link, for displaying
572 static bool check_symlink_color;
574 /* True means mention the inode number of each file. -i */
576 static bool print_inode;
578 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
579 other options that imply -l), and -L. */
581 static enum Dereference_symlink dereference;
583 /* True means when a directory is found, display info on its
586 static bool recursive;
588 /* True means when an argument is a directory name, display info
591 static bool immediate_dirs;
593 /* True means that directories are grouped before files. */
595 static bool directories_first;
597 /* Which files to ignore. */
601 /* Ignore files whose names start with `.', and files specified by
602 --hide and --ignore. */
605 /* Ignore `.', `..', and files specified by --ignore. */
606 IGNORE_DOT_AND_DOTDOT,
608 /* Ignore only files specified by --ignore. */
612 /* A linked list of shell-style globbing patterns. If a non-argument
613 file name matches any of these patterns, it is ignored.
614 Controlled by -I. Multiple -I options accumulate.
615 The -B option adds `*~' and `.*~' to this list. */
617 struct ignore_pattern
620 struct ignore_pattern *next;
623 static struct ignore_pattern *ignore_patterns;
625 /* Similar to IGNORE_PATTERNS, except that -a or -A causes this
626 variable itself to be ignored. */
627 static struct ignore_pattern *hide_patterns;
629 /* True means output nongraphic chars in file names as `?'.
630 (-q, --hide-control-chars)
631 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
632 independent. The algorithm is: first, obey the quoting style to get a
633 string representing the file name; then, if qmark_funny_chars is set,
634 replace all nonprintable chars in that string with `?'. It's necessary
635 to replace nonprintable chars even in quoted strings, because we don't
636 want to mess up the terminal if control chars get sent to it, and some
637 quoting methods pass through control chars as-is. */
638 static bool qmark_funny_chars;
640 /* Quoting options for file and dir name output. */
642 static struct quoting_options *filename_quoting_options;
643 static struct quoting_options *dirname_quoting_options;
645 /* The number of chars per hardware tab stop. Setting this to zero
646 inhibits the use of TAB characters for separating columns. -T */
647 static size_t tabsize;
649 /* True means print each directory name before listing it. */
651 static bool print_dir_name;
653 /* The line length to use for breaking lines in many-per-line format.
654 Can be set with -w. */
656 static size_t line_length;
658 /* If true, the file listing format requires that stat be called on
661 static bool format_needs_stat;
663 /* Similar to `format_needs_stat', but set if only the file type is
666 static bool format_needs_type;
668 /* An arbitrary limit on the number of bytes in a printed time stamp.
669 This is set to a relatively small value to avoid the need to worry
670 about denial-of-service attacks on servers that run "ls" on behalf
671 of remote clients. 1000 bytes should be enough for any practical
672 time stamp format. */
674 enum { TIME_STAMP_LEN_MAXIMUM = MAX (1000, INT_STRLEN_BOUND (time_t)) };
676 /* strftime formats for non-recent and recent files, respectively, in
679 static char const *long_time_format[2] =
681 /* strftime format for non-recent files (older than 6 months), in
682 -l output. This should contain the year, month and day (at
683 least), in an order that is understood by people in your
684 locale's territory. Please try to keep the number of used
685 screen columns small, because many people work in windows with
686 only 80 columns. But make this as wide as the other string
687 below, for recent files. */
689 /* strftime format for recent files (younger than 6 months), in -l
690 output. This should contain the month, day and time (at
691 least), in an order that is understood by people in your
692 locale's territory. Please try to keep the number of used
693 screen columns small, because many people work in windows with
694 only 80 columns. But make this as wide as the other string
695 above, for non-recent files. */
699 /* The set of signals that are caught. */
701 static sigset_t caught_signals;
703 /* If nonzero, the value of the pending fatal signal. */
705 static sig_atomic_t volatile interrupt_signal;
707 /* A count of the number of pending stop signals that have been received. */
709 static sig_atomic_t volatile stop_signal_count;
711 /* Desired exit status. */
713 static int exit_status;
718 /* "ls" had a minor problem (e.g., it could not stat a directory
720 LS_MINOR_PROBLEM = 1,
722 /* "ls" had more serious trouble. */
726 /* For long options that have no equivalent short option, use a
727 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
730 AUTHOR_OPTION = CHAR_MAX + 1,
733 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION,
734 FILE_TYPE_INDICATOR_OPTION,
737 GROUP_DIRECTORIES_FIRST_OPTION,
739 INDICATOR_STYLE_OPTION,
740 QUOTING_STYLE_OPTION,
741 SHOW_CONTROL_CHARS_OPTION,
748 static struct option const long_options[] =
750 {"all", no_argument, NULL, 'a'},
751 {"escape", no_argument, NULL, 'b'},
752 {"directory", no_argument, NULL, 'd'},
753 {"dired", no_argument, NULL, 'D'},
754 {"full-time", no_argument, NULL, FULL_TIME_OPTION},
755 {"group-directories-first", no_argument, NULL,
756 GROUP_DIRECTORIES_FIRST_OPTION},
757 {"human-readable", no_argument, NULL, 'h'},
758 {"inode", no_argument, NULL, 'i'},
759 {"numeric-uid-gid", no_argument, NULL, 'n'},
760 {"no-group", no_argument, NULL, 'G'},
761 {"hide-control-chars", no_argument, NULL, 'q'},
762 {"reverse", no_argument, NULL, 'r'},
763 {"size", no_argument, NULL, 's'},
764 {"width", required_argument, NULL, 'w'},
765 {"almost-all", no_argument, NULL, 'A'},
766 {"ignore-backups", no_argument, NULL, 'B'},
767 {"classify", no_argument, NULL, 'F'},
768 {"file-type", no_argument, NULL, FILE_TYPE_INDICATOR_OPTION},
769 {"si", no_argument, NULL, SI_OPTION},
770 {"dereference-command-line", no_argument, NULL, 'H'},
771 {"dereference-command-line-symlink-to-dir", no_argument, NULL,
772 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION},
773 {"hide", required_argument, NULL, HIDE_OPTION},
774 {"ignore", required_argument, NULL, 'I'},
775 {"indicator-style", required_argument, NULL, INDICATOR_STYLE_OPTION},
776 {"dereference", no_argument, NULL, 'L'},
777 {"literal", no_argument, NULL, 'N'},
778 {"quote-name", no_argument, NULL, 'Q'},
779 {"quoting-style", required_argument, NULL, QUOTING_STYLE_OPTION},
780 {"recursive", no_argument, NULL, 'R'},
781 {"format", required_argument, NULL, FORMAT_OPTION},
782 {"show-control-chars", no_argument, NULL, SHOW_CONTROL_CHARS_OPTION},
783 {"sort", required_argument, NULL, SORT_OPTION},
784 {"tabsize", required_argument, NULL, 'T'},
785 {"time", required_argument, NULL, TIME_OPTION},
786 {"time-style", required_argument, NULL, TIME_STYLE_OPTION},
787 {"color", optional_argument, NULL, COLOR_OPTION},
788 {"block-size", required_argument, NULL, BLOCK_SIZE_OPTION},
789 {"context", no_argument, 0, 'Z'},
790 {"author", no_argument, NULL, AUTHOR_OPTION},
791 {GETOPT_HELP_OPTION_DECL},
792 {GETOPT_VERSION_OPTION_DECL},
796 static char const *const format_args[] =
798 "verbose", "long", "commas", "horizontal", "across",
799 "vertical", "single-column", NULL
801 static enum format const format_types[] =
803 long_format, long_format, with_commas, horizontal, horizontal,
804 many_per_line, one_per_line
806 ARGMATCH_VERIFY (format_args, format_types);
808 static char const *const sort_args[] =
810 "none", "time", "size", "extension", "version", NULL
812 static enum sort_type const sort_types[] =
814 sort_none, sort_time, sort_size, sort_extension, sort_version
816 ARGMATCH_VERIFY (sort_args, sort_types);
818 static char const *const time_args[] =
820 "atime", "access", "use", "ctime", "status", NULL
822 static enum time_type const time_types[] =
824 time_atime, time_atime, time_atime, time_ctime, time_ctime
826 ARGMATCH_VERIFY (time_args, time_types);
828 static char const *const color_args[] =
830 /* force and none are for compatibility with another color-ls version */
831 "always", "yes", "force",
832 "never", "no", "none",
833 "auto", "tty", "if-tty", NULL
835 static enum color_type const color_types[] =
837 color_always, color_always, color_always,
838 color_never, color_never, color_never,
839 color_if_tty, color_if_tty, color_if_tty
841 ARGMATCH_VERIFY (color_args, color_types);
843 /* Information about filling a column. */
851 /* Array with information about column filledness. */
852 static struct column_info *column_info;
854 /* Maximum number of columns ever possible for this display. */
855 static size_t max_idx;
857 /* The minimum width of a column is 3: 1 character for the name and 2
858 for the separating white space. */
859 #define MIN_COLUMN_WIDTH 3
862 /* This zero-based index is used solely with the --dired option.
863 When that option is in effect, this counter is incremented for each
864 byte of output generated by this program so that the beginning
865 and ending indices (in that output) of every file name can be recorded
866 and later output themselves. */
867 static size_t dired_pos;
869 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
871 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
872 #define DIRED_FPUTS(s, stream, s_len) \
873 do {fputs (s, stream); dired_pos += s_len;} while (0)
875 /* Like DIRED_FPUTS, but for use when S is a literal string. */
876 #define DIRED_FPUTS_LITERAL(s, stream) \
877 do {fputs (s, stream); dired_pos += sizeof (s) - 1;} while (0)
879 #define DIRED_INDENT() \
883 DIRED_FPUTS_LITERAL (" ", stdout); \
887 /* With --dired, store pairs of beginning and ending indices of filenames. */
888 static struct obstack dired_obstack;
890 /* With --dired, store pairs of beginning and ending indices of any
891 directory names that appear as headers (just before `total' line)
892 for lists of directory entries. Such directory names are seen when
893 listing hierarchies using -R and when a directory is listed with at
894 least one other command line argument. */
895 static struct obstack subdired_obstack;
897 /* Save the current index on the specified obstack, OBS. */
898 #define PUSH_CURRENT_DIRED_POS(obs) \
902 obstack_grow (obs, &dired_pos, sizeof (dired_pos)); \
906 /* With -R, this stack is used to help detect directory cycles.
907 The device/inode pairs on this stack mirror the pairs in the
908 active_dir_set hash table. */
909 static struct obstack dev_ino_obstack;
911 /* Push a pair onto the device/inode stack. */
912 #define DEV_INO_PUSH(Dev, Ino) \
915 struct dev_ino *di; \
916 obstack_blank (&dev_ino_obstack, sizeof (struct dev_ino)); \
917 di = -1 + (struct dev_ino *) obstack_next_free (&dev_ino_obstack); \
918 di->st_dev = (Dev); \
919 di->st_ino = (Ino); \
923 /* Pop a dev/ino struct off the global dev_ino_obstack
924 and return that struct. */
925 static struct dev_ino
928 assert (sizeof (struct dev_ino) <= obstack_object_size (&dev_ino_obstack));
929 obstack_blank (&dev_ino_obstack, -(int) (sizeof (struct dev_ino)));
930 return *(struct dev_ino *) obstack_next_free (&dev_ino_obstack);
933 #define ASSERT_MATCHING_DEV_INO(Name, Di) \
938 assert (0 <= stat (Name, &sb)); \
939 assert (sb.st_dev == Di.st_dev); \
940 assert (sb.st_ino == Di.st_ino); \
945 /* Write to standard output PREFIX, followed by the quoting style and
946 a space-separated list of the integers stored in OS all on one line. */
949 dired_dump_obstack (const char *prefix, struct obstack *os)
953 n_pos = obstack_object_size (os) / sizeof (dired_pos);
959 pos = (size_t *) obstack_finish (os);
960 fputs (prefix, stdout);
961 for (i = 0; i < n_pos; i++)
962 printf (" %lu", (unsigned long int) pos[i]);
968 dev_ino_hash (void const *x, size_t table_size)
970 struct dev_ino const *p = x;
971 return (uintmax_t) p->st_ino % table_size;
975 dev_ino_compare (void const *x, void const *y)
977 struct dev_ino const *a = x;
978 struct dev_ino const *b = y;
979 return SAME_INODE (*a, *b) ? true : false;
983 dev_ino_free (void *x)
988 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
989 active directories. Return true if there is already a matching
990 entry in the table. */
993 visit_dir (dev_t dev, ino_t ino)
996 struct dev_ino *ent_from_table;
999 ent = xmalloc (sizeof *ent);
1003 /* Attempt to insert this entry into the table. */
1004 ent_from_table = hash_insert (active_dir_set, ent);
1006 if (ent_from_table == NULL)
1008 /* Insertion failed due to lack of memory. */
1012 found_match = (ent_from_table != ent);
1016 /* ent was not inserted, so free it. */
1024 free_pending_ent (struct pending *p)
1032 is_colored (enum indicator_no type)
1034 size_t len = color_indicator[type].len;
1035 char const *s = color_indicator[type].string;
1037 || (len == 1 && strncmp (s, "0", 1) == 0)
1038 || (len == 2 && strncmp (s, "00", 2) == 0));
1042 restore_default_color (void)
1044 put_indicator (&color_indicator[C_LEFT]);
1045 put_indicator (&color_indicator[C_RIGHT]);
1048 /* An ordinary signal was received; arrange for the program to exit. */
1051 sighandler (int sig)
1054 signal (sig, SIG_IGN);
1055 if (! interrupt_signal)
1056 interrupt_signal = sig;
1059 /* A SIGTSTP was received; arrange for the program to suspend itself. */
1062 stophandler (int sig)
1065 signal (sig, stophandler);
1066 if (! interrupt_signal)
1067 stop_signal_count++;
1070 /* Process any pending signals. If signals are caught, this function
1071 should be called periodically. Ideally there should never be an
1072 unbounded amount of time when signals are not being processed.
1073 Signal handling can restore the default colors, so callers must
1074 immediately change colors after invoking this function. */
1077 process_signals (void)
1079 while (interrupt_signal | stop_signal_count)
1086 restore_default_color ();
1089 sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
1091 /* Reload interrupt_signal and stop_signal_count, in case a new
1092 signal was handled before sigprocmask took effect. */
1093 sig = interrupt_signal;
1094 stops = stop_signal_count;
1096 /* SIGTSTP is special, since the application can receive that signal
1097 more than once. In this case, don't set the signal handler to the
1098 default. Instead, just raise the uncatchable SIGSTOP. */
1101 stop_signal_count = stops - 1;
1105 signal (sig, SIG_DFL);
1107 /* Exit or suspend the program. */
1109 sigprocmask (SIG_SETMASK, &oldset, NULL);
1111 /* If execution reaches here, then the program has been
1112 continued (after being suspended). */
1117 main (int argc, char **argv)
1120 struct pending *thispend;
1123 /* The signals that are trapped, and the number of such signals. */
1124 static int const sig[] =
1126 /* This one is handled specially. */
1129 /* The usual suspects. */
1130 SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM,
1147 enum { nsigs = sizeof sig / sizeof sig[0] };
1150 bool caught_sig[nsigs];
1153 initialize_main (&argc, &argv);
1154 set_program_name (argv[0]);
1155 setlocale (LC_ALL, "");
1156 bindtextdomain (PACKAGE, LOCALEDIR);
1157 textdomain (PACKAGE);
1159 initialize_exit_failure (LS_FAILURE);
1160 atexit (close_stdout);
1162 #define N_ENTRIES(Array) (sizeof Array / sizeof *(Array))
1163 assert (N_ENTRIES (color_indicator) + 1 == N_ENTRIES (indicator_name));
1165 exit_status = EXIT_SUCCESS;
1166 print_dir_name = true;
1167 pending_dirs = NULL;
1169 current_time.tv_sec = TYPE_MINIMUM (time_t);
1170 current_time.tv_nsec = -1;
1172 i = decode_switches (argc, argv);
1174 if (print_with_color)
1177 /* Test print_with_color again, because the call to parse_ls_color
1178 may have just reset it -- e.g., if LS_COLORS is invalid. */
1179 if (print_with_color)
1181 /* Avoid following symbolic links when possible. */
1182 if (is_colored (C_ORPHAN)
1183 || (is_colored (C_EXEC) && color_symlink_as_referent)
1184 || (is_colored (C_MISSING) && format == long_format))
1185 check_symlink_color = true;
1187 /* If the standard output is a controlling terminal, watch out
1188 for signals, so that the colors can be restored to the
1189 default state if "ls" is suspended or interrupted. */
1191 if (0 <= tcgetpgrp (STDOUT_FILENO))
1195 struct sigaction act;
1197 sigemptyset (&caught_signals);
1198 for (j = 0; j < nsigs; j++)
1200 sigaction (sig[j], NULL, &act);
1201 if (act.sa_handler != SIG_IGN)
1202 sigaddset (&caught_signals, sig[j]);
1205 act.sa_mask = caught_signals;
1206 act.sa_flags = SA_RESTART;
1208 for (j = 0; j < nsigs; j++)
1209 if (sigismember (&caught_signals, sig[j]))
1211 act.sa_handler = sig[j] == SIGTSTP ? stophandler : sighandler;
1212 sigaction (sig[j], &act, NULL);
1215 for (j = 0; j < nsigs; j++)
1217 caught_sig[j] = (signal (sig[j], SIG_IGN) != SIG_IGN);
1220 signal (sig[j], sig[j] == SIGTSTP ? stophandler : sighandler);
1221 siginterrupt (sig[j], 0);
1228 if (dereference == DEREF_UNDEFINED)
1229 dereference = ((immediate_dirs
1230 || indicator_style == classify
1231 || format == long_format)
1233 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
1235 /* When using -R, initialize a data structure we'll use to
1236 detect any directory cycles. */
1239 active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, NULL,
1243 if (active_dir_set == NULL)
1246 obstack_init (&dev_ino_obstack);
1249 format_needs_stat = sort_type == sort_time || sort_type == sort_size
1250 || format == long_format
1252 || print_block_size;
1253 format_needs_type = (! format_needs_stat
1256 || indicator_style != none
1257 || directories_first));
1261 obstack_init (&dired_obstack);
1262 obstack_init (&subdired_obstack);
1266 cwd_file = xnmalloc (cwd_n_alloc, sizeof *cwd_file);
1276 gobble_file (".", directory, NOT_AN_INODE_NUMBER, true, "");
1278 queue_directory (".", NULL, true);
1282 gobble_file (argv[i++], unknown, NOT_AN_INODE_NUMBER, true, "");
1288 if (!immediate_dirs)
1289 extract_dirs_from_files (NULL, true);
1290 /* `cwd_n_used' might be zero now. */
1293 /* In the following if/else blocks, it is sufficient to test `pending_dirs'
1294 (and not pending_dirs->name) because there may be no markers in the queue
1295 at this point. A marker may be enqueued when extract_dirs_from_files is
1296 called with a non-empty string or via print_dir. */
1299 print_current_files ();
1301 DIRED_PUTCHAR ('\n');
1303 else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1304 print_dir_name = false;
1306 while (pending_dirs)
1308 thispend = pending_dirs;
1309 pending_dirs = pending_dirs->next;
1313 if (thispend->name == NULL)
1315 /* thispend->name == NULL means this is a marker entry
1316 indicating we've finished processing the directory.
1317 Use its dev/ino numbers to remove the corresponding
1318 entry from the active_dir_set hash table. */
1319 struct dev_ino di = dev_ino_pop ();
1320 struct dev_ino *found = hash_delete (active_dir_set, &di);
1321 /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
1323 dev_ino_free (found);
1324 free_pending_ent (thispend);
1329 print_dir (thispend->name, thispend->realname,
1330 thispend->command_line_arg);
1332 free_pending_ent (thispend);
1333 print_dir_name = true;
1336 if (print_with_color)
1341 restore_default_color ();
1344 /* Restore the default signal handling. */
1346 for (j = 0; j < nsigs; j++)
1347 if (sigismember (&caught_signals, sig[j]))
1348 signal (sig[j], SIG_DFL);
1350 for (j = 0; j < nsigs; j++)
1352 signal (sig[j], SIG_DFL);
1355 /* Act on any signals that arrived before the default was restored.
1356 This can process signals out of order, but there doesn't seem to
1357 be an easy way to do them in order, and the order isn't that
1358 important anyway. */
1359 for (j = stop_signal_count; j; j--)
1361 j = interrupt_signal;
1368 /* No need to free these since we're about to exit. */
1369 dired_dump_obstack ("//DIRED//", &dired_obstack);
1370 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1371 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1372 quoting_style_args[get_quoting_style (filename_quoting_options)]);
1377 assert (hash_get_n_entries (active_dir_set) == 0);
1378 hash_free (active_dir_set);
1384 /* Set all the option flags according to the switches specified.
1385 Return the index of the first non-option argument. */
1388 decode_switches (int argc, char **argv)
1390 char *time_style_option = NULL;
1392 /* Record whether there is an option specifying sort type. */
1393 bool sort_type_specified = false;
1395 qmark_funny_chars = false;
1397 /* initialize all switches to default settings */
1402 /* This is for the `dir' program. */
1403 format = many_per_line;
1404 set_quoting_style (NULL, escape_quoting_style);
1407 case LS_LONG_FORMAT:
1408 /* This is for the `vdir' program. */
1409 format = long_format;
1410 set_quoting_style (NULL, escape_quoting_style);
1414 /* This is for the `ls' program. */
1415 if (isatty (STDOUT_FILENO))
1417 format = many_per_line;
1418 /* See description of qmark_funny_chars, above. */
1419 qmark_funny_chars = true;
1423 format = one_per_line;
1424 qmark_funny_chars = false;
1432 time_type = time_mtime;
1433 sort_type = sort_name;
1434 sort_reverse = false;
1435 numeric_ids = false;
1436 print_block_size = false;
1437 indicator_style = none;
1438 print_inode = false;
1439 dereference = DEREF_UNDEFINED;
1441 immediate_dirs = false;
1442 ignore_mode = IGNORE_DEFAULT;
1443 ignore_patterns = NULL;
1444 hide_patterns = NULL;
1445 print_scontext = false;
1447 /* FIXME: put this in a function. */
1449 char const *q_style = getenv ("QUOTING_STYLE");
1452 int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
1454 set_quoting_style (NULL, quoting_style_vals[i]);
1457 _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
1458 quotearg (q_style));
1463 char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
1464 human_options (ls_block_size,
1465 &human_output_opts, &output_block_size);
1466 if (ls_block_size || getenv ("BLOCK_SIZE"))
1467 file_output_block_size = output_block_size;
1472 char const *p = getenv ("COLUMNS");
1475 unsigned long int tmp_ulong;
1476 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1477 && 0 < tmp_ulong && tmp_ulong <= SIZE_MAX)
1479 line_length = tmp_ulong;
1484 _("ignoring invalid width in environment variable COLUMNS: %s"),
1494 if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1
1495 && 0 < ws.ws_col && ws.ws_col == (size_t) ws.ws_col)
1496 line_length = ws.ws_col;
1501 char const *p = getenv ("TABSIZE");
1505 unsigned long int tmp_ulong;
1506 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1507 && tmp_ulong <= SIZE_MAX)
1509 tabsize = tmp_ulong;
1514 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1523 int c = getopt_long (argc, argv,
1524 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1",
1532 ignore_mode = IGNORE_MINIMAL;
1536 set_quoting_style (NULL, escape_quoting_style);
1540 time_type = time_ctime;
1544 immediate_dirs = true;
1548 /* Same as enabling -a -U and disabling -l -s. */
1549 ignore_mode = IGNORE_MINIMAL;
1550 sort_type = sort_none;
1551 sort_type_specified = true;
1553 if (format == long_format)
1554 format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
1555 print_block_size = false; /* disable -s */
1556 print_with_color = false; /* disable --color */
1559 case FILE_TYPE_INDICATOR_OPTION: /* --file-type */
1560 indicator_style = file_type;
1564 format = long_format;
1565 print_owner = false;
1569 human_output_opts = human_autoscale | human_SI | human_base_1024;
1570 file_output_block_size = output_block_size = 1;
1578 human_output_opts = 0;
1579 file_output_block_size = output_block_size = 1024;
1583 format = long_format;
1587 format = with_commas;
1592 format = long_format;
1595 case 'o': /* Just like -l, but don't display group info. */
1596 format = long_format;
1597 print_group = false;
1601 indicator_style = slash;
1605 qmark_funny_chars = true;
1609 sort_reverse = true;
1613 print_block_size = true;
1617 sort_type = sort_time;
1618 sort_type_specified = true;
1622 time_type = time_atime;
1626 sort_type = sort_version;
1627 sort_type_specified = true;
1632 unsigned long int tmp_ulong;
1633 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1634 || ! (0 < tmp_ulong && tmp_ulong <= SIZE_MAX))
1635 error (LS_FAILURE, 0, _("invalid line width: %s"),
1637 line_length = tmp_ulong;
1642 format = horizontal;
1646 if (ignore_mode == IGNORE_DEFAULT)
1647 ignore_mode = IGNORE_DOT_AND_DOTDOT;
1651 add_ignore_pattern ("*~");
1652 add_ignore_pattern (".*~");
1656 format = many_per_line;
1664 indicator_style = classify;
1667 case 'G': /* inhibit display of group info */
1668 print_group = false;
1672 dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1675 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
1676 dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
1680 add_ignore_pattern (optarg);
1684 dereference = DEREF_ALWAYS;
1688 set_quoting_style (NULL, literal_quoting_style);
1692 set_quoting_style (NULL, c_quoting_style);
1700 sort_type = sort_size;
1701 sort_type_specified = true;
1706 unsigned long int tmp_ulong;
1707 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1708 || SIZE_MAX < tmp_ulong)
1709 error (LS_FAILURE, 0, _("invalid tab size: %s"),
1711 tabsize = tmp_ulong;
1716 sort_type = sort_none;
1717 sort_type_specified = true;
1721 sort_type = sort_extension;
1722 sort_type_specified = true;
1726 /* -1 has no effect after -l. */
1727 if (format != long_format)
1728 format = one_per_line;
1732 print_author = true;
1737 struct ignore_pattern *hide = xmalloc (sizeof *hide);
1738 hide->pattern = optarg;
1739 hide->next = hide_patterns;
1740 hide_patterns = hide;
1745 sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1746 sort_type_specified = true;
1749 case GROUP_DIRECTORIES_FIRST_OPTION:
1750 directories_first = true;
1754 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1758 format = XARGMATCH ("--format", optarg, format_args, format_types);
1761 case FULL_TIME_OPTION:
1762 format = long_format;
1763 time_style_option = "full-iso";
1770 i = XARGMATCH ("--color", optarg, color_args, color_types);
1772 /* Using --color with no argument is equivalent to using
1776 print_with_color = (i == color_always
1777 || (i == color_if_tty
1778 && isatty (STDOUT_FILENO)));
1780 if (print_with_color)
1782 /* Don't use TAB characters in output. Some terminal
1783 emulators can't handle the combination of tabs and
1784 color codes on the same line. */
1790 case INDICATOR_STYLE_OPTION:
1791 indicator_style = XARGMATCH ("--indicator-style", optarg,
1792 indicator_style_args,
1793 indicator_style_types);
1796 case QUOTING_STYLE_OPTION:
1797 set_quoting_style (NULL,
1798 XARGMATCH ("--quoting-style", optarg,
1800 quoting_style_vals));
1803 case TIME_STYLE_OPTION:
1804 time_style_option = optarg;
1807 case SHOW_CONTROL_CHARS_OPTION:
1808 qmark_funny_chars = false;
1811 case BLOCK_SIZE_OPTION:
1813 enum strtol_error e = human_options (optarg, &human_output_opts,
1814 &output_block_size);
1815 if (e != LONGINT_OK)
1816 xstrtol_fatal (e, oi, 0, long_options, optarg);
1817 file_output_block_size = output_block_size;
1822 human_output_opts = human_autoscale | human_SI;
1823 file_output_block_size = output_block_size = 1;
1827 print_scontext = true;
1830 case_GETOPT_HELP_CHAR;
1832 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1839 max_idx = MAX (1, line_length / MIN_COLUMN_WIDTH);
1841 filename_quoting_options = clone_quoting_options (NULL);
1842 if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1843 set_char_quoting (filename_quoting_options, ' ', 1);
1844 if (file_type <= indicator_style)
1847 for (p = "*=>@|" + indicator_style - file_type; *p; p++)
1848 set_char_quoting (filename_quoting_options, *p, 1);
1851 dirname_quoting_options = clone_quoting_options (NULL);
1852 set_char_quoting (dirname_quoting_options, ':', 1);
1854 /* --dired is meaningful only with --format=long (-l).
1855 Otherwise, ignore it. FIXME: warn about this?
1856 Alternatively, make --dired imply --format=long? */
1857 if (dired && format != long_format)
1860 /* If -c or -u is specified and not -l (or any other option that implies -l),
1861 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
1862 The behavior of ls when using either -c or -u but with neither -l nor -t
1863 appears to be unspecified by POSIX. So, with GNU ls, `-u' alone means
1864 sort by atime (this is the one that's not specified by the POSIX spec),
1865 -lu means show atime and sort by name, -lut means show atime and sort
1868 if ((time_type == time_ctime || time_type == time_atime)
1869 && !sort_type_specified && format != long_format)
1871 sort_type = sort_time;
1874 if (format == long_format)
1876 char *style = time_style_option;
1877 static char const posix_prefix[] = "posix-";
1880 if (! (style = getenv ("TIME_STYLE")))
1883 while (strncmp (style, posix_prefix, sizeof posix_prefix - 1) == 0)
1885 if (! hard_locale (LC_TIME))
1887 style += sizeof posix_prefix - 1;
1892 char *p0 = style + 1;
1893 char *p1 = strchr (p0, '\n');
1898 if (strchr (p1 + 1, '\n'))
1899 error (LS_FAILURE, 0, _("invalid time style format %s"),
1903 long_time_format[0] = p0;
1904 long_time_format[1] = p1;
1907 switch (XARGMATCH ("time style", style,
1911 case full_iso_time_style:
1912 long_time_format[0] = long_time_format[1] =
1913 "%Y-%m-%d %H:%M:%S.%N %z";
1916 case long_iso_time_style:
1917 case_long_iso_time_style:
1918 long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
1921 case iso_time_style:
1922 long_time_format[0] = "%Y-%m-%d ";
1923 long_time_format[1] = "%m-%d %H:%M";
1926 case locale_time_style:
1927 if (hard_locale (LC_TIME))
1929 /* Ensure that the locale has translations for both
1930 formats. If not, fall back on long-iso format. */
1932 for (i = 0; i < 2; i++)
1934 char const *locale_format =
1935 dcgettext (NULL, long_time_format[i], LC_TIME);
1936 if (locale_format == long_time_format[i])
1937 goto case_long_iso_time_style;
1938 long_time_format[i] = locale_format;
1947 /* Parse a string as part of the LS_COLORS variable; this may involve
1948 decoding all kinds of escape characters. If equals_end is set an
1949 unescaped equal sign ends the string, otherwise only a : or \0
1950 does. Set *OUTPUT_COUNT to the number of bytes output. Return
1953 The resulting string is *not* null-terminated, but may contain
1956 Note that both dest and src are char **; on return they point to
1957 the first free byte after the array and the character that ended
1958 the input string, respectively. */
1961 get_funky_string (char **dest, const char **src, bool equals_end,
1962 size_t *output_count)
1964 char num; /* For numerical codes */
1965 size_t count; /* Something to count with */
1967 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
1972 p = *src; /* We don't want to double-indirect */
1973 q = *dest; /* the whole darn time. */
1975 count = 0; /* No characters counted in yet. */
1978 state = ST_GND; /* Start in ground state. */
1979 while (state < ST_END)
1983 case ST_GND: /* Ground state (no escapes) */
1988 state = ST_END; /* End of string */
1991 state = ST_BACKSLASH; /* Backslash scape sequence */
1995 state = ST_CARET; /* Caret escape */
2001 state = ST_END; /* End */
2004 /* else fall through */
2012 case ST_BACKSLASH: /* Backslash escaped character */
2023 state = ST_OCTAL; /* Octal sequence */
2028 state = ST_HEX; /* Hex sequence */
2031 case 'a': /* Bell */
2034 case 'b': /* Backspace */
2037 case 'e': /* Escape */
2040 case 'f': /* Form feed */
2043 case 'n': /* Newline */
2046 case 'r': /* Carriage return */
2052 case 'v': /* Vtab */
2055 case '?': /* Delete */
2058 case '_': /* Space */
2061 case '\0': /* End of string */
2062 state = ST_ERROR; /* Error! */
2064 default: /* Escaped character like \ ^ : = */
2068 if (state == ST_BACKSLASH)
2077 case ST_OCTAL: /* Octal sequence */
2078 if (*p < '0' || *p > '7')
2085 num = (num << 3) + (*(p++) - '0');
2088 case ST_HEX: /* Hex sequence */
2101 num = (num << 4) + (*(p++) - '0');
2109 num = (num << 4) + (*(p++) - 'a') + 10;
2117 num = (num << 4) + (*(p++) - 'A') + 10;
2127 case ST_CARET: /* Caret escape */
2128 state = ST_GND; /* Should be the next state... */
2129 if (*p >= '@' && *p <= '~')
2131 *(q++) = *(p++) & 037;
2150 *output_count = count;
2152 return state != ST_ERROR;
2156 parse_ls_color (void)
2158 const char *p; /* Pointer to character being parsed */
2159 char *buf; /* color_buf buffer pointer */
2160 int state; /* State of parser */
2161 int ind_no; /* Indicator number */
2162 char label[3]; /* Indicator label */
2163 struct color_ext_type *ext; /* Extension we are working on */
2165 if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
2169 strcpy (label, "??");
2171 /* This is an overly conservative estimate, but any possible
2172 LS_COLORS string will *not* generate a color_buf longer than
2173 itself, so it is a safe way of allocating a buffer in
2175 buf = color_buf = xstrdup (p);
2182 case 1: /* First label character */
2190 /* Allocate new extension block and add to head of
2191 linked list (this way a later definition will
2192 override an earlier one, which can be useful for
2193 having terminal-specific defs override global). */
2195 ext = xmalloc (sizeof *ext);
2196 ext->next = color_ext_list;
2197 color_ext_list = ext;
2200 ext->ext.string = buf;
2202 state = (get_funky_string (&buf, &p, true, &ext->ext.len)
2207 state = 0; /* Done! */
2210 default: /* Assume it is file type label */
2217 case 2: /* Second label character */
2224 state = -1; /* Error */
2227 case 3: /* Equal sign after indicator label */
2228 state = -1; /* Assume failure... */
2229 if (*(p++) == '=')/* It *should* be... */
2231 for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
2233 if (STREQ (label, indicator_name[ind_no]))
2235 color_indicator[ind_no].string = buf;
2236 state = (get_funky_string (&buf, &p, false,
2237 &color_indicator[ind_no].len)
2243 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
2247 case 4: /* Equal sign after *.ext */
2250 ext->seq.string = buf;
2251 state = (get_funky_string (&buf, &p, false, &ext->seq.len)
2262 struct color_ext_type *e;
2263 struct color_ext_type *e2;
2266 _("unparsable value for LS_COLORS environment variable"));
2268 for (e = color_ext_list; e != NULL; /* empty */)
2274 print_with_color = false;
2277 if (color_indicator[C_LINK].len == 6
2278 && !strncmp (color_indicator[C_LINK].string, "target", 6))
2279 color_symlink_as_referent = true;
2282 /* Set the exit status to report a failure. If SERIOUS, it is a
2283 serious failure; otherwise, it is merely a minor problem. */
2286 set_exit_status (bool serious)
2289 exit_status = LS_FAILURE;
2290 else if (exit_status == EXIT_SUCCESS)
2291 exit_status = LS_MINOR_PROBLEM;
2294 /* Assuming a failure is serious if SERIOUS, use the printf-style
2295 MESSAGE to report the failure to access a file named FILE. Assume
2296 errno is set appropriately for the failure. */
2299 file_failure (bool serious, char const *message, char const *file)
2301 error (0, errno, message, quotearg_colon (file));
2302 set_exit_status (serious);
2305 /* Request that the directory named NAME have its contents listed later.
2306 If REALNAME is nonzero, it will be used instead of NAME when the
2307 directory name is printed. This allows symbolic links to directories
2308 to be treated as regular directories but still be listed under their
2309 real names. NAME == NULL is used to insert a marker entry for the
2310 directory named in REALNAME.
2311 If NAME is non-NULL, we use its dev/ino information to save
2312 a call to stat -- when doing a recursive (-R) traversal.
2313 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2316 queue_directory (char const *name, char const *realname, bool command_line_arg)
2318 struct pending *new = xmalloc (sizeof *new);
2319 new->realname = realname ? xstrdup (realname) : NULL;
2320 new->name = name ? xstrdup (name) : NULL;
2321 new->command_line_arg = command_line_arg;
2322 new->next = pending_dirs;
2326 /* Read directory NAME, and list the files in it.
2327 If REALNAME is nonzero, print its name instead of NAME;
2328 this is used for symbolic links to directories.
2329 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2332 print_dir (char const *name, char const *realname, bool command_line_arg)
2335 struct dirent *next;
2336 uintmax_t total_blocks = 0;
2337 static bool first = true;
2340 dirp = opendir (name);
2343 file_failure (command_line_arg, _("cannot open directory %s"), name);
2349 struct stat dir_stat;
2350 int fd = dirfd (dirp);
2352 /* If dirfd failed, endure the overhead of using stat. */
2354 ? fstat (fd, &dir_stat)
2355 : stat (name, &dir_stat)) < 0)
2357 file_failure (command_line_arg,
2358 _("cannot determine device and inode of %s"), name);
2363 /* If we've already visited this dev/inode pair, warn that
2364 we've found a loop, and do not process this directory. */
2365 if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
2367 error (0, 0, _("%s: not listing already-listed directory"),
2368 quotearg_colon (name));
2373 DEV_INO_PUSH (dir_stat.st_dev, dir_stat.st_ino);
2376 /* Read the directory entries, and insert the subfiles into the `cwd_file'
2383 /* Set errno to zero so we can distinguish between a readdir failure
2384 and when readdir simply finds that there are no more entries. */
2386 next = readdir (dirp);
2389 if (! file_ignored (next->d_name))
2391 enum filetype type = unknown;
2393 #if HAVE_STRUCT_DIRENT_D_TYPE
2394 switch (next->d_type)
2396 case DT_BLK: type = blockdev; break;
2397 case DT_CHR: type = chardev; break;
2398 case DT_DIR: type = directory; break;
2399 case DT_FIFO: type = fifo; break;
2400 case DT_LNK: type = symbolic_link; break;
2401 case DT_REG: type = normal; break;
2402 case DT_SOCK: type = sock; break;
2404 case DT_WHT: type = whiteout; break;
2408 total_blocks += gobble_file (next->d_name, type, D_INO (next),
2411 /* In this narrow case, print out each name right away, so
2412 ls uses constant memory while processing the entries of
2413 this directory. Useful when there are many (millions)
2414 of entries in a directory. */
2415 if (format == one_per_line && sort_type == sort_none)
2417 /* We must call sort_files in spite of
2418 "sort_type == sort_none" for its initialization
2419 of the sorted_file vector. */
2421 print_current_files ();
2426 else if (errno != 0)
2428 file_failure (command_line_arg, _("reading directory %s"), name);
2429 if (errno != EOVERFLOW)
2436 if (closedir (dirp) != 0)
2438 file_failure (command_line_arg, _("closing directory %s"), name);
2439 /* Don't return; print whatever we got. */
2442 /* Sort the directory contents. */
2445 /* If any member files are subdirectories, perhaps they should have their
2446 contents listed rather than being mentioned here as files. */
2449 extract_dirs_from_files (name, command_line_arg);
2451 if (recursive | print_dir_name)
2454 DIRED_PUTCHAR ('\n');
2457 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2458 dired_pos += quote_name (stdout, realname ? realname : name,
2459 dirname_quoting_options, NULL);
2460 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2461 DIRED_FPUTS_LITERAL (":\n", stdout);
2464 if (format == long_format || print_block_size)
2467 char buf[LONGEST_HUMAN_READABLE + 1];
2471 DIRED_FPUTS (p, stdout, strlen (p));
2472 DIRED_PUTCHAR (' ');
2473 p = human_readable (total_blocks, buf, human_output_opts,
2474 ST_NBLOCKSIZE, output_block_size);
2475 DIRED_FPUTS (p, stdout, strlen (p));
2476 DIRED_PUTCHAR ('\n');
2480 print_current_files ();
2483 /* Add `pattern' to the list of patterns for which files that match are
2487 add_ignore_pattern (const char *pattern)
2489 struct ignore_pattern *ignore;
2491 ignore = xmalloc (sizeof *ignore);
2492 ignore->pattern = pattern;
2493 /* Add it to the head of the linked list. */
2494 ignore->next = ignore_patterns;
2495 ignore_patterns = ignore;
2498 /* Return true if one of the PATTERNS matches FILE. */
2501 patterns_match (struct ignore_pattern const *patterns, char const *file)
2503 struct ignore_pattern const *p;
2504 for (p = patterns; p; p = p->next)
2505 if (fnmatch (p->pattern, file, FNM_PERIOD) == 0)
2510 /* Return true if FILE should be ignored. */
2513 file_ignored (char const *name)
2515 return ((ignore_mode != IGNORE_MINIMAL
2517 && (ignore_mode == IGNORE_DEFAULT || ! name[1 + (name[1] == '.')]))
2518 || (ignore_mode == IGNORE_DEFAULT
2519 && patterns_match (hide_patterns, name))
2520 || patterns_match (ignore_patterns, name));
2523 /* POSIX requires that a file size be printed without a sign, even
2524 when negative. Assume the typical case where negative sizes are
2525 actually positive values that have wrapped around. */
2528 unsigned_file_size (off_t size)
2530 return size + (size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
2533 /* Enter and remove entries in the table `cwd_file'. */
2535 /* Empty the table of files. */
2542 for (i = 0; i < cwd_n_used; i++)
2544 struct fileinfo *f = sorted_file[i];
2547 if (f->scontext != UNKNOWN_SECURITY_CONTEXT)
2548 freecon (f->scontext);
2552 any_has_acl = false;
2553 inode_number_width = 0;
2554 block_size_width = 0;
2560 major_device_number_width = 0;
2561 minor_device_number_width = 0;
2562 file_size_width = 0;
2565 /* Add a file to the current table of files.
2566 Verify that the file exists, and print an error message if it does not.
2567 Return the number of blocks that the file occupies. */
2570 gobble_file (char const *name, enum filetype type, ino_t inode,
2571 bool command_line_arg, char const *dirname)
2573 uintmax_t blocks = 0;
2576 /* An inode value prior to gobble_file necessarily came from readdir,
2577 which is not used for command line arguments. */
2578 assert (! command_line_arg || inode == NOT_AN_INODE_NUMBER);
2580 if (cwd_n_used == cwd_n_alloc)
2582 cwd_file = xnrealloc (cwd_file, cwd_n_alloc, 2 * sizeof *cwd_file);
2586 f = &cwd_file[cwd_n_used];
2587 memset (f, '\0', sizeof *f);
2588 f->stat.st_ino = inode;
2591 if (command_line_arg
2592 || format_needs_stat
2593 /* When coloring a directory (we may know the type from
2594 direct.d_type), we have to stat it in order to indicate
2595 sticky and/or other-writable attributes. */
2596 || (type == directory && print_with_color)
2597 /* When dereferencing symlinks, the inode and type must come from
2598 stat, but readdir provides the inode and type of lstat. */
2599 || ((print_inode || format_needs_type)
2600 && (type == symbolic_link || type == unknown)
2601 && (dereference == DEREF_ALWAYS
2602 || (command_line_arg && dereference != DEREF_NEVER)
2603 || color_symlink_as_referent || check_symlink_color))
2604 /* Command line dereferences are already taken care of by the above
2605 assertion that the inode number is not yet known. */
2606 || (print_inode && inode == NOT_AN_INODE_NUMBER)
2607 || (format_needs_type
2608 && (type == unknown || command_line_arg
2609 /* --indicator-style=classify (aka -F)
2610 requires that we stat each regular file
2611 to see if it's executable. */
2612 || (type == normal && (indicator_style == classify
2613 /* This is so that --color ends up
2614 highlighting files with the executable
2615 bit set even when options like -F are
2617 || (print_with_color
2618 && is_colored (C_EXEC))
2622 /* Absolute name of this file. */
2623 char *absolute_name;
2627 if (name[0] == '/' || dirname[0] == 0)
2628 absolute_name = (char *) name;
2631 absolute_name = alloca (strlen (name) + strlen (dirname) + 2);
2632 attach (absolute_name, dirname, name);
2635 switch (dereference)
2638 err = stat (absolute_name, &f->stat);
2642 case DEREF_COMMAND_LINE_ARGUMENTS:
2643 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
2644 if (command_line_arg)
2647 err = stat (absolute_name, &f->stat);
2650 if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2653 need_lstat = (err < 0
2655 : ! S_ISDIR (f->stat.st_mode));
2659 /* stat failed because of ENOENT, maybe indicating a dangling
2660 symlink. Or stat succeeded, ABSOLUTE_NAME does not refer to a
2661 directory, and --dereference-command-line-symlink-to-dir is
2662 in effect. Fall through so that we call lstat instead. */
2665 default: /* DEREF_NEVER */
2666 err = lstat (absolute_name, &f->stat);
2673 /* Failure to stat a command line argument leads to
2674 an exit status of 2. For other files, stat failure
2675 provokes an exit status of 1. */
2676 file_failure (command_line_arg,
2677 _("cannot access %s"), absolute_name);
2678 if (command_line_arg)
2681 f->name = xstrdup (name);
2689 if (format == long_format || print_scontext)
2691 bool have_acl = false;
2692 int attr_len = (do_deref
2693 ? getfilecon (absolute_name, &f->scontext)
2694 : lgetfilecon (absolute_name, &f->scontext));
2695 err = (attr_len < 0);
2697 /* Contrary to its documented API, getfilecon may return 0,
2698 yet set f->scontext to NULL (on at least Debian's libselinux1
2699 2.0.15-2+b1), so work around that bug.
2700 FIXME: remove this work-around in 2011, or whenever affected
2701 versions of libselinux are long gone. */
2705 f->scontext = xstrdup ("unlabeled");
2709 have_acl = ! STREQ ("unlabeled", f->scontext);
2712 f->scontext = UNKNOWN_SECURITY_CONTEXT;
2714 /* When requesting security context information, don't make
2715 ls fail just because the file (even a command line argument)
2716 isn't on the right type of file system. I.e., a getfilecon
2717 failure isn't in the same class as a stat failure. */
2718 if (errno == ENOTSUP || errno == EOPNOTSUPP || errno == ENODATA)
2722 if (err == 0 && ! have_acl && format == long_format)
2724 int n = file_has_acl (absolute_name, &f->stat);
2729 f->have_acl = have_acl;
2730 any_has_acl |= have_acl;
2733 error (0, errno, "%s", quotearg_colon (absolute_name));
2736 if (S_ISLNK (f->stat.st_mode)
2737 && (format == long_format || check_symlink_color))
2740 struct stat linkstats;
2742 get_link_name (absolute_name, f, command_line_arg);
2743 linkname = make_link_name (absolute_name, f->linkname);
2745 /* Avoid following symbolic links when possible, ie, when
2746 they won't be traced and when no indicator is needed. */
2748 && (file_type <= indicator_style || check_symlink_color)
2749 && stat (linkname, &linkstats) == 0)
2753 /* Symbolic links to directories that are mentioned on the
2754 command line are automatically traced if not being
2756 if (!command_line_arg || format == long_format
2757 || !S_ISDIR (linkstats.st_mode))
2759 /* Get the linked-to file's mode for the filetype indicator
2760 in long listings. */
2761 f->linkmode = linkstats.st_mode;
2767 /* When not distinguishing types of symlinks, pretend we know that
2768 it is stat'able, so that it will be colored as a regular symlink,
2769 and not as an orphan. */
2770 if (S_ISLNK (f->stat.st_mode) && !check_symlink_color)
2773 if (S_ISLNK (f->stat.st_mode))
2774 f->filetype = symbolic_link;
2775 else if (S_ISDIR (f->stat.st_mode))
2777 if (command_line_arg & !immediate_dirs)
2778 f->filetype = arg_directory;
2780 f->filetype = directory;
2783 f->filetype = normal;
2785 blocks = ST_NBLOCKS (f->stat);
2786 if (format == long_format || print_block_size)
2788 char buf[LONGEST_HUMAN_READABLE + 1];
2789 int len = mbswidth (human_readable (blocks, buf, human_output_opts,
2790 ST_NBLOCKSIZE, output_block_size),
2792 if (block_size_width < len)
2793 block_size_width = len;
2796 if (format == long_format)
2800 int len = format_user_width (f->stat.st_uid);
2801 if (owner_width < len)
2807 int len = format_group_width (f->stat.st_gid);
2808 if (group_width < len)
2814 int len = format_user_width (f->stat.st_author);
2815 if (author_width < len)
2822 int len = strlen (f->scontext);
2823 if (scontext_width < len)
2824 scontext_width = len;
2827 if (format == long_format)
2829 char b[INT_BUFSIZE_BOUND (uintmax_t)];
2830 int b_len = strlen (umaxtostr (f->stat.st_nlink, b));
2831 if (nlink_width < b_len)
2832 nlink_width = b_len;
2834 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
2836 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2837 int len = strlen (umaxtostr (major (f->stat.st_rdev), buf));
2838 if (major_device_number_width < len)
2839 major_device_number_width = len;
2840 len = strlen (umaxtostr (minor (f->stat.st_rdev), buf));
2841 if (minor_device_number_width < len)
2842 minor_device_number_width = len;
2843 len = major_device_number_width + 2 + minor_device_number_width;
2844 if (file_size_width < len)
2845 file_size_width = len;
2849 char buf[LONGEST_HUMAN_READABLE + 1];
2850 uintmax_t size = unsigned_file_size (f->stat.st_size);
2851 int len = mbswidth (human_readable (size, buf, human_output_opts,
2852 1, file_output_block_size),
2854 if (file_size_width < len)
2855 file_size_width = len;
2862 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2863 int len = strlen (umaxtostr (f->stat.st_ino, buf));
2864 if (inode_number_width < len)
2865 inode_number_width = len;
2868 f->name = xstrdup (name);
2874 /* Return true if F refers to a directory. */
2876 is_directory (const struct fileinfo *f)
2878 return f->filetype == directory || f->filetype == arg_directory;
2881 /* Put the name of the file that FILENAME is a symbolic link to
2882 into the LINKNAME field of `f'. COMMAND_LINE_ARG indicates whether
2883 FILENAME is a command-line argument. */
2886 get_link_name (char const *filename, struct fileinfo *f, bool command_line_arg)
2888 f->linkname = areadlink_with_size (filename, f->stat.st_size);
2889 if (f->linkname == NULL)
2890 file_failure (command_line_arg, _("cannot read symbolic link %s"),
2894 /* If `linkname' is a relative name and `name' contains one or more
2895 leading directories, return `linkname' with those directories
2896 prepended; otherwise, return a copy of `linkname'.
2897 If `linkname' is zero, return zero. */
2900 make_link_name (char const *name, char const *linkname)
2908 if (*linkname == '/')
2909 return xstrdup (linkname);
2911 /* The link is to a relative name. Prepend any leading directory
2912 in `name' to the link name. */
2913 linkbuf = strrchr (name, '/');
2915 return xstrdup (linkname);
2917 bufsiz = linkbuf - name + 1;
2918 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
2919 strncpy (linkbuf, name, bufsiz);
2920 strcpy (linkbuf + bufsiz, linkname);
2924 /* Return true if the last component of NAME is `.' or `..'
2925 This is so we don't try to recurse on `././././. ...' */
2928 basename_is_dot_or_dotdot (const char *name)
2930 char const *base = last_component (name);
2931 return dot_or_dotdot (base);
2934 /* Remove any entries from CWD_FILE that are for directories,
2935 and queue them to be listed as directories instead.
2936 DIRNAME is the prefix to prepend to each dirname
2937 to make it correct relative to ls's working dir;
2938 if it is null, no prefix is needed and "." and ".." should not be ignored.
2939 If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
2940 This is desirable when processing directories recursively. */
2943 extract_dirs_from_files (char const *dirname, bool command_line_arg)
2947 bool ignore_dot_and_dot_dot = (dirname != NULL);
2949 if (dirname && LOOP_DETECT)
2951 /* Insert a marker entry first. When we dequeue this marker entry,
2952 we'll know that DIRNAME has been processed and may be removed
2953 from the set of active directories. */
2954 queue_directory (NULL, dirname, false);
2957 /* Queue the directories last one first, because queueing reverses the
2959 for (i = cwd_n_used; i-- != 0; )
2961 struct fileinfo *f = sorted_file[i];
2963 if (is_directory (f)
2964 && (! ignore_dot_and_dot_dot
2965 || ! basename_is_dot_or_dotdot (f->name)))
2967 if (!dirname || f->name[0] == '/')
2968 queue_directory (f->name, f->linkname, command_line_arg);
2971 char *name = file_name_concat (dirname, f->name, NULL);
2972 queue_directory (name, f->linkname, command_line_arg);
2975 if (f->filetype == arg_directory)
2980 /* Now delete the directories from the table, compacting all the remaining
2983 for (i = 0, j = 0; i < cwd_n_used; i++)
2985 struct fileinfo *f = sorted_file[i];
2987 j += (f->filetype != arg_directory);
2992 /* Use strcoll to compare strings in this locale. If an error occurs,
2993 report an error and longjmp to failed_strcoll. */
2995 static jmp_buf failed_strcoll;
2998 xstrcoll (char const *a, char const *b)
3002 diff = strcoll (a, b);
3005 error (0, errno, _("cannot compare file names %s and %s"),
3006 quote_n (0, a), quote_n (1, b));
3007 set_exit_status (false);
3008 longjmp (failed_strcoll, 1);
3013 /* Comparison routines for sorting the files. */
3015 typedef void const *V;
3016 typedef int (*qsortFunc)(V a, V b);
3018 /* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants.
3019 The do { ... } while(0) makes it possible to use the macro more like
3020 a statement, without violating C89 rules: */
3021 #define DIRFIRST_CHECK(a, b) \
3024 bool a_is_dir = is_directory ((struct fileinfo const *) a); \
3025 bool b_is_dir = is_directory ((struct fileinfo const *) b); \
3026 if (a_is_dir && !b_is_dir) \
3027 return -1; /* a goes before b */ \
3028 if (!a_is_dir && b_is_dir) \
3029 return 1; /* b goes before a */ \
3033 /* Define the 8 different sort function variants required for each sortkey.
3034 KEY_NAME is a token describing the sort key, e.g., ctime, atime, size.
3035 KEY_CMP_FUNC is a function to compare records based on that key, e.g.,
3036 ctime_cmp, atime_cmp, size_cmp. Append KEY_NAME to the string,
3037 '[rev_][x]str{cmp|coll}[_df]_', to create each function name. */
3038 #define DEFINE_SORT_FUNCTIONS(key_name, key_cmp_func) \
3039 /* direct, non-dirfirst versions */ \
3040 static int xstrcoll_##key_name (V a, V b) \
3041 { return key_cmp_func (a, b, xstrcoll); } \
3042 static int strcmp_##key_name (V a, V b) \
3043 { return key_cmp_func (a, b, strcmp); } \
3045 /* reverse, non-dirfirst versions */ \
3046 static int rev_xstrcoll_##key_name (V a, V b) \
3047 { return key_cmp_func (b, a, xstrcoll); } \
3048 static int rev_strcmp_##key_name (V a, V b) \
3049 { return key_cmp_func (b, a, strcmp); } \
3051 /* direct, dirfirst versions */ \
3052 static int xstrcoll_df_##key_name (V a, V b) \
3053 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, xstrcoll); } \
3054 static int strcmp_df_##key_name (V a, V b) \
3055 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, strcmp); } \
3057 /* reverse, dirfirst versions */ \
3058 static int rev_xstrcoll_df_##key_name (V a, V b) \
3059 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, xstrcoll); } \
3060 static int rev_strcmp_df_##key_name (V a, V b) \
3061 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, strcmp); }
3064 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
3065 int (*cmp) (char const *, char const *))
3067 int diff = timespec_cmp (get_stat_ctime (&b->stat),
3068 get_stat_ctime (&a->stat));
3069 return diff ? diff : cmp (a->name, b->name);
3073 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
3074 int (*cmp) (char const *, char const *))
3076 int diff = timespec_cmp (get_stat_mtime (&b->stat),
3077 get_stat_mtime (&a->stat));
3078 return diff ? diff : cmp (a->name, b->name);
3082 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
3083 int (*cmp) (char const *, char const *))
3085 int diff = timespec_cmp (get_stat_atime (&b->stat),
3086 get_stat_atime (&a->stat));
3087 return diff ? diff : cmp (a->name, b->name);
3091 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
3092 int (*cmp) (char const *, char const *))
3094 int diff = longdiff (b->stat.st_size, a->stat.st_size);
3095 return diff ? diff : cmp (a->name, b->name);
3099 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
3100 int (*cmp) (char const *, char const *))
3102 return cmp (a->name, b->name);
3105 /* Compare file extensions. Files with no extension are `smallest'.
3106 If extensions are the same, compare by filenames instead. */
3109 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
3110 int (*cmp) (char const *, char const *))
3112 char const *base1 = strrchr (a->name, '.');
3113 char const *base2 = strrchr (b->name, '.');
3114 int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
3115 return diff ? diff : cmp (a->name, b->name);
3118 DEFINE_SORT_FUNCTIONS (ctime, cmp_ctime)
3119 DEFINE_SORT_FUNCTIONS (mtime, cmp_mtime)
3120 DEFINE_SORT_FUNCTIONS (atime, cmp_atime)
3121 DEFINE_SORT_FUNCTIONS (size, cmp_size)
3122 DEFINE_SORT_FUNCTIONS (name, cmp_name)
3123 DEFINE_SORT_FUNCTIONS (extension, cmp_extension)
3125 /* Compare file versions.
3126 Unlike all other compare functions above, cmp_version depends only
3127 on strverscmp, which does not fail (even for locale reasons), and does not
3128 need a secondary sort key.
3129 All the other sort options, in fact, need xstrcoll and strcmp variants,
3130 because they all use a string comparison (either as the primary or secondary
3131 sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
3132 locale reasons. Last, strverscmp is ALWAYS available in coreutils,
3133 thanks to the gnulib library. */
3135 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
3137 return strverscmp (a->name, b->name);
3140 static int xstrcoll_version (V a, V b)
3141 { return cmp_version (a, b); }
3142 static int rev_xstrcoll_version (V a, V b)
3143 { return cmp_version (b, a); }
3144 static int xstrcoll_df_version (V a, V b)
3145 { DIRFIRST_CHECK (a, b); return cmp_version (a, b); }
3146 static int rev_xstrcoll_df_version (V a, V b)
3147 { DIRFIRST_CHECK (a, b); return cmp_version (b, a); }
3150 /* We have 2^3 different variants for each sortkey function
3151 (for 3 independent sort modes).
3152 The function pointers stored in this array must be dereferenced as:
3154 sort_variants[sort_key][use_strcmp][reverse][dirs_first]
3156 Note that the order in which sortkeys are listed in the function pointer
3157 array below is defined by the order of the elements in the time_type and
3160 #define LIST_SORTFUNCTION_VARIANTS(key_name) \
3163 { xstrcoll_##key_name, xstrcoll_df_##key_name }, \
3164 { rev_xstrcoll_##key_name, rev_xstrcoll_df_##key_name }, \
3167 { strcmp_##key_name, strcmp_df_##key_name }, \
3168 { rev_strcmp_##key_name, rev_strcmp_df_##key_name }, \
3172 static qsortFunc const sort_functions[][2][2][2] =
3174 LIST_SORTFUNCTION_VARIANTS (name),
3175 LIST_SORTFUNCTION_VARIANTS (extension),
3176 LIST_SORTFUNCTION_VARIANTS (size),
3180 { xstrcoll_version, xstrcoll_df_version },
3181 { rev_xstrcoll_version, rev_xstrcoll_df_version },
3184 /* We use NULL for the strcmp variants of version comparison
3185 since as explained in cmp_version definition, version comparison
3186 does not rely on xstrcoll, so it will never longjmp, and never
3187 need to try the strcmp fallback. */
3194 /* last are time sort functions */
3195 LIST_SORTFUNCTION_VARIANTS (mtime),
3196 LIST_SORTFUNCTION_VARIANTS (ctime),
3197 LIST_SORTFUNCTION_VARIANTS (atime)
3200 /* The number of sortkeys is calculated as
3201 the number of elements in the sort_type enum (i.e. sort_numtypes) +
3202 the number of elements in the time_type enum (i.e. time_numtypes) - 1
3203 This is because when sort_type==sort_time, we have up to
3204 time_numtypes possible sortkeys.
3206 This line verifies at compile-time that the array of sort functions has been
3207 initialized for all possible sortkeys. */
3208 verify (ARRAY_CARDINALITY (sort_functions)
3209 == sort_numtypes + time_numtypes - 1 );
3211 /* Set up SORTED_FILE to point to the in-use entries in CWD_FILE, in order. */
3214 initialize_ordering_vector (void)
3217 for (i = 0; i < cwd_n_used; i++)
3218 sorted_file[i] = &cwd_file[i];
3221 /* Sort the files now in the table. */
3228 if (sorted_file_alloc < cwd_n_used + cwd_n_used / 2)
3231 sorted_file = xnmalloc (cwd_n_used, 3 * sizeof *sorted_file);
3232 sorted_file_alloc = 3 * cwd_n_used;
3235 initialize_ordering_vector ();
3237 if (sort_type == sort_none)
3240 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
3241 ignore strcoll failures, as a failing strcoll might be a
3242 comparison function that is not a total order, and if we ignored
3243 the failure this might cause qsort to dump core. */
3245 if (! setjmp (failed_strcoll))
3246 use_strcmp = false; /* strcoll() succeeded */
3250 assert (sort_type != sort_version);
3251 initialize_ordering_vector ();
3254 /* When sort_type == sort_time, use time_type as subindex. */
3255 mpsort ((void const **) sorted_file, cwd_n_used,
3256 sort_functions[sort_type + (sort_type == sort_time ? time_type : 0)]
3257 [use_strcmp][sort_reverse]
3258 [directories_first]);
3261 /* List all the files now in the table. */
3264 print_current_files (void)
3271 for (i = 0; i < cwd_n_used; i++)
3273 print_file_name_and_frills (sorted_file[i]);
3279 print_many_per_line ();
3283 print_horizontal ();
3287 print_with_commas ();
3291 for (i = 0; i < cwd_n_used; i++)
3293 print_long_format (sorted_file[i]);
3294 DIRED_PUTCHAR ('\n');
3300 /* Return the expected number of columns in a long-format time stamp,
3301 or zero if it cannot be calculated. */
3304 long_time_expected_width (void)
3306 static int width = -1;
3311 struct tm const *tm = localtime (&epoch);
3312 char buf[TIME_STAMP_LEN_MAXIMUM + 1];
3314 /* In case you're wondering if localtime can fail with an input time_t
3315 value of 0, let's just say it's very unlikely, but not inconceivable.
3316 The TZ environment variable would have to specify a time zone that
3317 is 2**31-1900 years or more ahead of UTC. This could happen only on
3318 a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
3319 However, this is not possible with Solaris 10 or glibc-2.3.5, since
3320 their implementations limit the offset to 167:59 and 24:00, resp. */
3324 nstrftime (buf, sizeof buf, long_time_format[0], tm, 0, 0);
3326 width = mbsnwidth (buf, len, 0);
3336 /* Print the user or group name NAME, with numeric id ID, using a
3337 print width of WIDTH columns. */
3340 format_user_or_group (char const *name, unsigned long int id, int width)
3346 int width_gap = width - mbswidth (name, 0);
3347 int pad = MAX (0, width_gap);
3348 fputs (name, stdout);
3349 len = strlen (name) + pad;
3357 printf ("%*lu ", width, id);
3361 dired_pos += len + 1;
3364 /* Print the name or id of the user with id U, using a print width of
3368 format_user (uid_t u, int width, bool stat_ok)
3370 format_user_or_group (! stat_ok ? "?" :
3371 (numeric_ids ? NULL : getuser (u)), u, width);
3374 /* Likewise, for groups. */
3377 format_group (gid_t g, int width, bool stat_ok)
3379 format_user_or_group (! stat_ok ? "?" :
3380 (numeric_ids ? NULL : getgroup (g)), g, width);
3383 /* Return the number of columns that format_user_or_group will print. */
3386 format_user_or_group_width (char const *name, unsigned long int id)
3390 int len = mbswidth (name, 0);
3391 return MAX (0, len);
3395 char buf[INT_BUFSIZE_BOUND (unsigned long int)];
3396 sprintf (buf, "%lu", id);
3397 return strlen (buf);
3401 /* Return the number of columns that format_user will print. */
3404 format_user_width (uid_t u)
3406 return format_user_or_group_width (numeric_ids ? NULL : getuser (u), u);
3409 /* Likewise, for groups. */
3412 format_group_width (gid_t g)
3414 return format_user_or_group_width (numeric_ids ? NULL : getgroup (g), g);
3418 /* Print information about F in long format. */
3421 print_long_format (const struct fileinfo *f)
3425 [LONGEST_HUMAN_READABLE + 1 /* inode */
3426 + LONGEST_HUMAN_READABLE + 1 /* size in blocks */
3427 + sizeof (modebuf) - 1 + 1 /* mode string */
3428 + INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
3429 + LONGEST_HUMAN_READABLE + 2 /* major device number */
3430 + LONGEST_HUMAN_READABLE + 1 /* minor device number */
3431 + TIME_STAMP_LEN_MAXIMUM + 1 /* max length of time/date */
3435 struct timespec when_timespec;
3436 struct tm *when_local;
3438 /* Compute the mode string, except remove the trailing space if no
3439 file in this directory has an ACL or SELinux security context. */
3441 filemodestring (&f->stat, modebuf);
3444 modebuf[0] = filetype_letter[f->filetype];
3445 memset (modebuf + 1, '?', 10);
3450 else if (f->have_acl)
3456 when_timespec = get_stat_ctime (&f->stat);
3459 when_timespec = get_stat_mtime (&f->stat);
3462 when_timespec = get_stat_atime (&f->stat);
3472 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3473 sprintf (p, "%*s ", inode_number_width,
3474 (f->stat.st_ino == NOT_AN_INODE_NUMBER
3476 : umaxtostr (f->stat.st_ino, hbuf)));
3477 /* Increment by strlen (p) here, rather than by inode_number_width + 1.
3478 The latter is wrong when inode_number_width is zero. */
3482 if (print_block_size)
3484 char hbuf[LONGEST_HUMAN_READABLE + 1];
3485 char const *blocks =
3488 : human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts,
3489 ST_NBLOCKSIZE, output_block_size));
3491 for (pad = block_size_width - mbswidth (blocks, 0); 0 < pad; pad--)
3493 while ((*p++ = *blocks++))
3498 /* The last byte of the mode string is the POSIX
3499 "optional alternate access method flag". */
3501 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3502 sprintf (p, "%s %*s ", modebuf, nlink_width,
3503 ! f->stat_ok ? "?" : umaxtostr (f->stat.st_nlink, hbuf));
3505 /* Increment by strlen (p) here, rather than by, e.g.,
3506 sizeof modebuf - 2 + any_has_acl + 1 + nlink_width + 1.
3507 The latter is wrong when nlink_width is zero. */
3512 if (print_owner | print_group | print_author | print_scontext)
3514 DIRED_FPUTS (buf, stdout, p - buf);
3517 format_user (f->stat.st_uid, owner_width, f->stat_ok);
3520 format_group (f->stat.st_gid, group_width, f->stat_ok);
3523 format_user (f->stat.st_author, author_width, f->stat_ok);
3526 format_user_or_group (f->scontext, 0, scontext_width);
3532 && (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode)))
3534 char majorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3535 char minorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3536 int blanks_width = (file_size_width
3537 - (major_device_number_width + 2
3538 + minor_device_number_width));
3539 sprintf (p, "%*s, %*s ",
3540 major_device_number_width + MAX (0, blanks_width),
3541 umaxtostr (major (f->stat.st_rdev), majorbuf),
3542 minor_device_number_width,
3543 umaxtostr (minor (f->stat.st_rdev), minorbuf));
3544 p += file_size_width + 1;
3548 char hbuf[LONGEST_HUMAN_READABLE + 1];
3552 : human_readable (unsigned_file_size (f->stat.st_size),
3553 hbuf, human_output_opts, 1, file_output_block_size));
3555 for (pad = file_size_width - mbswidth (size, 0); 0 < pad; pad--)
3557 while ((*p++ = *size++))
3562 when_local = localtime (&when_timespec.tv_sec);
3566 if (f->stat_ok && when_local)
3568 struct timespec six_months_ago;
3572 /* If the file appears to be in the future, update the current
3573 time, in case the file happens to have been modified since
3574 the last time we checked the clock. */
3575 if (timespec_cmp (current_time, when_timespec) < 0)
3577 /* Note that gettime may call gettimeofday which, on some non-
3578 compliant systems, clobbers the buffer used for localtime's result.
3579 But it's ok here, because we use a gettimeofday wrapper that
3580 saves and restores the buffer around the gettimeofday call. */
3581 gettime (¤t_time);
3584 /* Consider a time to be recent if it is within the past six
3585 months. A Gregorian year has 365.2425 * 24 * 60 * 60 ==
3586 31556952 seconds on the average. Write this value as an
3587 integer constant to avoid floating point hassles. */
3588 six_months_ago.tv_sec = current_time.tv_sec - 31556952 / 2;
3589 six_months_ago.tv_nsec = current_time.tv_nsec;
3591 recent = (timespec_cmp (six_months_ago, when_timespec) < 0
3592 && (timespec_cmp (when_timespec, current_time) < 0));
3593 fmt = long_time_format[recent];
3595 /* We assume here that all time zones are offset from UTC by a
3596 whole number of seconds. */
3597 s = nstrftime (p, TIME_STAMP_LEN_MAXIMUM + 1, fmt,
3598 when_local, 0, when_timespec.tv_nsec);
3606 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
3611 /* The time cannot be converted using the desired format, so
3612 print it as a huge integer number of seconds. */
3613 char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
3614 sprintf (p, "%*s ", long_time_expected_width (),
3617 : timetostr (when_timespec.tv_sec, hbuf)));
3618 /* FIXME: (maybe) We discarded when_timespec.tv_nsec. */
3622 DIRED_FPUTS (buf, stdout, p - buf);
3623 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
3624 f->stat_ok, f->filetype, &dired_obstack);
3626 if (f->filetype == symbolic_link)
3630 DIRED_FPUTS_LITERAL (" -> ", stdout);
3631 print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1,
3632 f->stat_ok, f->filetype, NULL);
3633 if (indicator_style != none)
3634 print_type_indicator (true, f->linkmode, unknown);
3637 else if (indicator_style != none)
3638 print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
3641 /* Output to OUT a quoted representation of the file name NAME,
3642 using OPTIONS to control quoting. Produce no output if OUT is NULL.
3643 Store the number of screen columns occupied by NAME's quoted
3644 representation into WIDTH, if non-NULL. Return the number of bytes
3648 quote_name (FILE *out, const char *name, struct quoting_options const *options,
3651 char smallbuf[BUFSIZ];
3652 size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, name, -1, options);
3654 size_t displayed_width IF_LINT (= 0);
3656 if (len < sizeof smallbuf)
3660 buf = alloca (len + 1);
3661 quotearg_buffer (buf, len + 1, name, -1, options);
3664 if (qmark_funny_chars)
3669 char const *p = buf;
3670 char const *plimit = buf + len;
3672 displayed_width = 0;
3677 case ' ': case '!': case '"': case '#': case '%':
3678 case '&': case '\'': case '(': case ')': case '*':
3679 case '+': case ',': case '-': case '.': case '/':
3680 case '0': case '1': case '2': case '3': case '4':
3681 case '5': case '6': case '7': case '8': case '9':
3682 case ':': case ';': case '<': case '=': case '>':
3684 case 'A': case 'B': case 'C': case 'D': case 'E':
3685 case 'F': case 'G': case 'H': case 'I': case 'J':
3686 case 'K': case 'L': case 'M': case 'N': case 'O':
3687 case 'P': case 'Q': case 'R': case 'S': case 'T':
3688 case 'U': case 'V': case 'W': case 'X': case 'Y':
3690 case '[': case '\\': case ']': case '^': case '_':
3691 case 'a': case 'b': case 'c': case 'd': case 'e':
3692 case 'f': case 'g': case 'h': case 'i': case 'j':
3693 case 'k': case 'l': case 'm': case 'n': case 'o':
3694 case 'p': case 'q': case 'r': case 's': case 't':
3695 case 'u': case 'v': case 'w': case 'x': case 'y':
3696 case 'z': case '{': case '|': case '}': case '~':
3697 /* These characters are printable ASCII characters. */
3699 displayed_width += 1;
3702 /* If we have a multibyte sequence, copy it until we
3703 reach its end, replacing each non-printable multibyte
3704 character with a single question mark. */
3706 mbstate_t mbstate = { 0, };
3713 bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
3715 if (bytes == (size_t) -1)
3717 /* An invalid multibyte sequence was
3718 encountered. Skip one input byte, and
3719 put a question mark. */
3722 displayed_width += 1;
3726 if (bytes == (size_t) -2)
3728 /* An incomplete multibyte character
3729 at the end. Replace it entirely with
3733 displayed_width += 1;
3738 /* A null wide character was encountered. */
3744 /* A printable multibyte character.
3746 for (; bytes > 0; --bytes)
3748 displayed_width += w;
3752 /* An unprintable multibyte character.
3753 Replace it entirely with a question
3757 displayed_width += 1;
3760 while (! mbsinit (&mbstate));
3765 /* The buffer may have shrunk. */
3772 char const *plimit = buf + len;
3776 if (! isprint (to_uchar (*p)))
3780 displayed_width = len;
3783 else if (width != NULL)
3787 displayed_width = mbsnwidth (buf, len, 0);
3791 char const *p = buf;
3792 char const *plimit = buf + len;
3794 displayed_width = 0;
3797 if (isprint (to_uchar (*p)))
3805 fwrite (buf, 1, len, out);
3807 *width = displayed_width;
3812 print_name_with_quoting (const char *p, mode_t mode, int linkok,
3813 bool stat_ok, enum filetype type,
3814 struct obstack *stack)
3816 bool used_color_this_time
3818 && print_color_indicator (p, mode, linkok, stat_ok, type));
3821 PUSH_CURRENT_DIRED_POS (stack);
3823 dired_pos += quote_name (stdout, p, filename_quoting_options, NULL);
3826 PUSH_CURRENT_DIRED_POS (stack);
3828 if (used_color_this_time)
3831 prep_non_filename_text ();
3836 prep_non_filename_text (void)
3838 if (color_indicator[C_END].string != NULL)
3839 put_indicator (&color_indicator[C_END]);
3842 put_indicator (&color_indicator[C_LEFT]);
3843 put_indicator (&color_indicator[C_RESET]);
3844 put_indicator (&color_indicator[C_RIGHT]);
3848 /* Print the file name of `f' with appropriate quoting.
3849 Also print file size, inode number, and filetype indicator character,
3850 as requested by switches. */
3853 print_file_name_and_frills (const struct fileinfo *f)
3855 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
3858 printf ("%*s ", format == with_commas ? 0 : inode_number_width,
3859 umaxtostr (f->stat.st_ino, buf));
3861 if (print_block_size)
3862 printf ("%*s ", format == with_commas ? 0 : block_size_width,
3863 human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts,
3864 ST_NBLOCKSIZE, output_block_size));
3867 printf ("%*s ", format == with_commas ? 0 : scontext_width, f->scontext);
3869 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
3870 f->stat_ok, f->filetype, NULL);
3872 if (indicator_style != none)
3873 print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
3876 /* Given these arguments describing a file, return the single-byte
3877 type indicator, or 0. */
3879 get_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
3883 if (stat_ok ? S_ISREG (mode) : type == normal)
3885 if (stat_ok && indicator_style == classify && (mode & S_IXUGO))
3892 if (stat_ok ? S_ISDIR (mode) : type == directory || type == arg_directory)
3894 else if (indicator_style == slash)
3896 else if (stat_ok ? S_ISLNK (mode) : type == symbolic_link)
3898 else if (stat_ok ? S_ISFIFO (mode) : type == fifo)
3900 else if (stat_ok ? S_ISSOCK (mode) : type == sock)
3902 else if (stat_ok && S_ISDOOR (mode))
3911 print_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
3913 char c = get_type_indicator (stat_ok, mode, type);
3919 /* Return true if NAME has a capability (see linux/capability.h) */
3921 has_capability (char const *name)
3926 cap_t cap_d = cap_get_file (name);
3930 result = cap_to_text (cap_d, NULL);
3935 /* check if human-readable capability string is empty */
3936 has_cap = !!*result;
3943 has_capability (char const *name)
3949 /* Returns whether any color sequence was printed. */
3951 print_color_indicator (const char *name, mode_t mode, int linkok,
3952 bool stat_ok, enum filetype filetype)
3955 struct color_ext_type *ext; /* Color extension */
3956 size_t len; /* Length of name */
3958 /* Is this a nonexistent file? If so, linkok == -1. */
3960 if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
3964 static enum indicator_no filetype_indicator[] = FILETYPE_INDICATORS;
3965 type = filetype_indicator[filetype];
3972 if ((mode & S_ISUID) != 0)
3974 else if ((mode & S_ISGID) != 0)
3976 else if (has_capability (name))
3978 else if ((mode & S_IXUGO) != 0)
3981 else if (S_ISDIR (mode))
3983 if ((mode & S_ISVTX) && (mode & S_IWOTH))
3984 type = C_STICKY_OTHER_WRITABLE;
3985 else if ((mode & S_IWOTH) != 0)
3986 type = C_OTHER_WRITABLE;
3987 else if ((mode & S_ISVTX) != 0)
3992 else if (S_ISLNK (mode))
3993 type = ((!linkok && color_indicator[C_ORPHAN].string)
3994 ? C_ORPHAN : C_LINK);
3995 else if (S_ISFIFO (mode))
3997 else if (S_ISSOCK (mode))
3999 else if (S_ISBLK (mode))
4001 else if (S_ISCHR (mode))
4003 else if (S_ISDOOR (mode))
4007 /* Classify a file of some other type as C_ORPHAN. */
4012 /* Check the file's suffix only if still classified as C_FILE. */
4016 /* Test if NAME has a recognized suffix. */
4018 len = strlen (name);
4019 name += len; /* Pointer to final \0. */
4020 for (ext = color_ext_list; ext != NULL; ext = ext->next)
4022 if (ext->ext.len <= len
4023 && strncmp (name - ext->ext.len, ext->ext.string,
4030 const struct bin_str *const s
4031 = ext ? &(ext->seq) : &color_indicator[type];
4032 if (s->string != NULL)
4034 put_indicator (&color_indicator[C_LEFT]);
4036 put_indicator (&color_indicator[C_RIGHT]);
4044 /* Output a color indicator (which may contain nulls). */
4046 put_indicator (const struct bin_str *ind)
4051 prep_non_filename_text ();
4054 fwrite (ind->string, ind->len, 1, stdout);
4058 length_of_file_name_and_frills (const struct fileinfo *f)
4062 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
4065 len += 1 + (format == with_commas
4066 ? strlen (umaxtostr (f->stat.st_ino, buf))
4067 : inode_number_width);
4069 if (print_block_size)
4070 len += 1 + (format == with_commas
4071 ? strlen (human_readable (ST_NBLOCKS (f->stat), buf,
4072 human_output_opts, ST_NBLOCKSIZE,
4074 : block_size_width);
4077 len += 1 + (format == with_commas ? strlen (f->scontext) : scontext_width);
4079 quote_name (NULL, f->name, filename_quoting_options, &name_width);
4082 if (indicator_style != none)
4084 char c = get_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4092 print_many_per_line (void)
4094 size_t row; /* Current row. */
4095 size_t cols = calculate_columns (true);
4096 struct column_info const *line_fmt = &column_info[cols - 1];
4098 /* Calculate the number of rows that will be in each column except possibly
4099 for a short column on the right. */
4100 size_t rows = cwd_n_used / cols + (cwd_n_used % cols != 0);
4102 for (row = 0; row < rows; row++)
4105 size_t filesno = row;
4108 /* Print the next row. */
4111 struct fileinfo const *f = sorted_file[filesno];
4112 size_t name_length = length_of_file_name_and_frills (f);
4113 size_t max_name_length = line_fmt->col_arr[col++];
4114 print_file_name_and_frills (f);
4117 if (filesno >= cwd_n_used)
4120 indent (pos + name_length, pos + max_name_length);
4121 pos += max_name_length;
4128 print_horizontal (void)
4132 size_t cols = calculate_columns (false);
4133 struct column_info const *line_fmt = &column_info[cols - 1];
4134 struct fileinfo const *f = sorted_file[0];
4135 size_t name_length = length_of_file_name_and_frills (f);
4136 size_t max_name_length = line_fmt->col_arr[0];
4138 /* Print first entry. */
4139 print_file_name_and_frills (f);
4142 for (filesno = 1; filesno < cwd_n_used; ++filesno)
4144 size_t col = filesno % cols;
4153 indent (pos + name_length, pos + max_name_length);
4154 pos += max_name_length;
4157 f = sorted_file[filesno];
4158 print_file_name_and_frills (f);
4160 name_length = length_of_file_name_and_frills (f);
4161 max_name_length = line_fmt->col_arr[col];
4167 print_with_commas (void)
4172 for (filesno = 0; filesno < cwd_n_used; filesno++)
4174 struct fileinfo const *f = sorted_file[filesno];
4175 size_t len = length_of_file_name_and_frills (f);
4181 if (pos + len + 2 < line_length)
4193 putchar (separator);
4196 print_file_name_and_frills (f);
4202 /* Assuming cursor is at position FROM, indent up to position TO.
4203 Use a TAB character instead of two or more spaces whenever possible. */
4206 indent (size_t from, size_t to)
4210 if (tabsize != 0 && to / tabsize > (from + 1) / tabsize)
4213 from += tabsize - from % tabsize;
4223 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
4224 /* FIXME: maybe remove this function someday. See about using a
4225 non-malloc'ing version of file_name_concat. */
4228 attach (char *dest, const char *dirname, const char *name)
4230 const char *dirnamep = dirname;
4232 /* Copy dirname if it is not ".". */
4233 if (dirname[0] != '.' || dirname[1] != 0)
4236 *dest++ = *dirnamep++;
4237 /* Add '/' if `dirname' doesn't already end with it. */
4238 if (dirnamep > dirname && dirnamep[-1] != '/')
4246 /* Allocate enough column info suitable for the current number of
4247 files and display columns, and initialize the info to represent the
4248 narrowest possible columns. */
4251 init_column_info (void)
4254 size_t max_cols = MIN (max_idx, cwd_n_used);
4256 /* Currently allocated columns in column_info. */
4257 static size_t column_info_alloc;
4259 if (column_info_alloc < max_cols)
4261 size_t new_column_info_alloc;
4264 if (max_cols < max_idx / 2)
4266 /* The number of columns is far less than the display width
4267 allows. Grow the allocation, but only so that it's
4268 double the current requirements. If the display is
4269 extremely wide, this avoids allocating a lot of memory
4270 that is never needed. */
4271 column_info = xnrealloc (column_info, max_cols,
4272 2 * sizeof *column_info);
4273 new_column_info_alloc = 2 * max_cols;
4277 column_info = xnrealloc (column_info, max_idx, sizeof *column_info);
4278 new_column_info_alloc = max_idx;
4281 /* Allocate the new size_t objects by computing the triangle
4282 formula n * (n + 1) / 2, except that we don't need to
4283 allocate the part of the triangle that we've already
4284 allocated. Check for address arithmetic overflow. */
4286 size_t column_info_growth = new_column_info_alloc - column_info_alloc;
4287 size_t s = column_info_alloc + 1 + new_column_info_alloc;
4288 size_t t = s * column_info_growth;
4289 if (s < new_column_info_alloc || t / column_info_growth != s)
4291 p = xnmalloc (t / 2, sizeof *p);
4294 /* Grow the triangle by parceling out the cells just allocated. */
4295 for (i = column_info_alloc; i < new_column_info_alloc; i++)
4297 column_info[i].col_arr = p;
4301 column_info_alloc = new_column_info_alloc;
4304 for (i = 0; i < max_cols; ++i)
4308 column_info[i].valid_len = true;
4309 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
4310 for (j = 0; j <= i; ++j)
4311 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
4315 /* Calculate the number of columns needed to represent the current set
4316 of files in the current display width. */
4319 calculate_columns (bool by_columns)
4321 size_t filesno; /* Index into cwd_file. */
4322 size_t cols; /* Number of files across. */
4324 /* Normally the maximum number of columns is determined by the
4325 screen width. But if few files are available this might limit it
4327 size_t max_cols = MIN (max_idx, cwd_n_used);
4329 init_column_info ();
4331 /* Compute the maximum number of possible columns. */
4332 for (filesno = 0; filesno < cwd_n_used; ++filesno)
4334 struct fileinfo const *f = sorted_file[filesno];
4335 size_t name_length = length_of_file_name_and_frills (f);
4338 for (i = 0; i < max_cols; ++i)
4340 if (column_info[i].valid_len)
4342 size_t idx = (by_columns
4343 ? filesno / ((cwd_n_used + i) / (i + 1))
4344 : filesno % (i + 1));
4345 size_t real_length = name_length + (idx == i ? 0 : 2);
4347 if (column_info[i].col_arr[idx] < real_length)
4349 column_info[i].line_len += (real_length
4350 - column_info[i].col_arr[idx]);
4351 column_info[i].col_arr[idx] = real_length;
4352 column_info[i].valid_len = (column_info[i].line_len
4359 /* Find maximum allowed columns. */
4360 for (cols = max_cols; 1 < cols; --cols)
4362 if (column_info[cols - 1].valid_len)
4372 if (status != EXIT_SUCCESS)
4373 fprintf (stderr, _("Try `%s --help' for more information.\n"),
4377 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
4379 List information about the FILEs (the current directory by default).\n\
4380 Sort entries alphabetically if none of -cftuvSUX nor --sort.\n\
4384 Mandatory arguments to long options are mandatory for short options too.\n\
4387 -a, --all do not ignore entries starting with .\n\
4388 -A, --almost-all do not list implied . and ..\n\
4389 --author with -l, print the author of each file\n\
4390 -b, --escape print octal escapes for nongraphic characters\n\
4393 --block-size=SIZE use SIZE-byte blocks\n\
4394 -B, --ignore-backups do not list implied entries ending with ~\n\
4395 -c with -lt: sort by, and show, ctime (time of last\n\
4396 modification of file status information)\n\
4397 with -l: show ctime and sort by name\n\
4398 otherwise: sort by ctime\n\
4401 -C list entries by columns\n\
4402 --color[=WHEN] control whether color is used to distinguish file\n\
4403 types. WHEN may be `never', `always', or `auto'\n\
4404 -d, --directory list directory entries instead of contents,\n\
4405 and do not dereference symbolic links\n\
4406 -D, --dired generate output designed for Emacs' dired mode\n\
4409 -f do not sort, enable -aU, disable -ls --color\n\
4410 -F, --classify append indicator (one of */=>@|) to entries\n\
4411 --file-type likewise, except do not append `*'\n\
4412 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
4413 single-column -1, verbose -l, vertical -C\n\
4414 --full-time like -l --time-style=full-iso\n\
4417 -g like -l, but do not list owner\n\
4420 --group-directories-first\n\
4421 group directories before files.\n\
4422 augment with a --sort option, but any\n\
4423 use of --sort=none (-U) disables grouping\n\
4426 -G, --no-group in a long listing, don't print group names\n\
4427 -h, --human-readable with -l, print sizes in human readable format\n\
4428 (e.g., 1K 234M 2G)\n\
4429 --si likewise, but use powers of 1000 not 1024\n\
4432 -H, --dereference-command-line\n\
4433 follow symbolic links listed on the command line\n\
4434 --dereference-command-line-symlink-to-dir\n\
4435 follow each command line symbolic link\n\
4436 that points to a directory\n\
4437 --hide=PATTERN do not list implied entries matching shell PATTERN\n\
4438 (overridden by -a or -A)\n\
4441 --indicator-style=WORD append indicator with style WORD to entry names:\n\
4442 none (default), slash (-p),\n\
4443 file-type (--file-type), classify (-F)\n\
4444 -i, --inode print the index number of each file\n\
4445 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
4446 -k like --block-size=1K\n\
4449 -l use a long listing format\n\
4450 -L, --dereference when showing file information for a symbolic\n\
4451 link, show information for the file the link\n\
4452 references rather than for the link itself\n\
4453 -m fill width with a comma separated list of entries\n\
4456 -n, --numeric-uid-gid like -l, but list numeric user and group IDs\n\
4457 -N, --literal print raw entry names (don't treat e.g. control\n\
4458 characters specially)\n\
4459 -o like -l, but do not list group information\n\
4460 -p, --indicator-style=slash\n\
4461 append / indicator to directories\n\
4464 -q, --hide-control-chars print ? instead of non graphic characters\n\
4465 --show-control-chars show non graphic characters as-is (default\n\
4466 unless program is `ls' and output is a terminal)\n\
4467 -Q, --quote-name enclose entry names in double quotes\n\
4468 --quoting-style=WORD use quoting style WORD for entry names:\n\
4469 literal, locale, shell, shell-always, c, escape\n\
4472 -r, --reverse reverse order while sorting\n\
4473 -R, --recursive list subdirectories recursively\n\
4474 -s, --size print the size of each file, in blocks\n\
4477 -S sort by file size\n\
4478 --sort=WORD sort by WORD instead of name: none -U,\n\
4479 extension -X, size -S, time -t, version -v\n\
4480 --time=WORD with -l, show time as WORD instead of modification\n\
4481 time: atime -u, access -u, use -u, ctime -c,\n\
4482 or status -c; use specified time as sort key\n\
4486 --time-style=STYLE with -l, show times using style STYLE:\n\
4487 full-iso, long-iso, iso, locale, +FORMAT.\n\
4488 FORMAT is interpreted like `date'; if FORMAT is\n\
4489 FORMAT1<newline>FORMAT2, FORMAT1 applies to\n\
4490 non-recent files and FORMAT2 to recent files;\n\
4491 if STYLE is prefixed with `posix-', STYLE\n\
4492 takes effect only outside the POSIX locale\n\
4495 -t sort by modification time\n\
4496 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
4499 -u with -lt: sort by, and show, access time\n\
4500 with -l: show access time and sort by name\n\
4501 otherwise: sort by access time\n\
4502 -U do not sort; list entries in directory order\n\
4503 -v sort by version\n\
4506 -w, --width=COLS assume screen width instead of current value\n\
4507 -x list entries by lines instead of by columns\n\
4508 -X sort alphabetically by entry extension\n\
4509 -Z, --context print any SELinux security context of each file\n\
4510 -1 list one file per line\n\
4512 fputs (HELP_OPTION_DESCRIPTION, stdout);
4513 fputs (VERSION_OPTION_DESCRIPTION, stdout);
4515 SIZE may be (or may be an integer optionally followed by) one of following:\n\
4516 kB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
4520 By default, color is not used to distinguish types of files. That is\n\
4521 equivalent to using --color=none. Using the --color option without the\n\
4522 optional WHEN argument is equivalent to using --color=always. With\n\
4523 --color=auto, color codes are output only if standard output is connected\n\
4524 to a terminal (tty). The environment variable LS_COLORS can influence the\n\
4525 colors, and can be set easily by the dircolors command.\n\
4529 Exit status is 0 if OK, 1 if minor problems, 2 if serious trouble.\n\
4531 emit_bug_reporting_address ();