1 /* `dir', `vdir' and `ls' directory listing programs for GNU.
2 Copyright (C) 85, 88, 90, 91, 1995-2007 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, or (at your option)
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, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* If ls_mode is LS_MULTI_COL,
19 the multi-column format is the default regardless
20 of the type of output device.
21 This is for the `dir' program.
23 If ls_mode is LS_LONG_FORMAT,
24 the long format is the default regardless of the
25 type of output device.
26 This is for the `vdir' program.
29 the output format depends on whether the output
31 This is for the `ls' program. */
33 /* Written by Richard Stallman and David MacKenzie. */
35 /* Color support by Peter Anvin <Peter.Anvin@linux.org> and Dennis
36 Flaherty <dennisf@denix.elk.miles.com> based on original patches by
37 Greg Lee <lee@uhunix.uhcc.hawaii.edu>. */
40 #include <sys/types.h>
49 # include <sys/ioctl.h>
52 #ifdef WINSIZE_IN_PTEM
53 # include <sys/stream.h>
54 # include <sys/ptem.h>
64 #include <selinux/selinux.h>
67 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
70 # define SA_NOCLDSTOP 0
71 # define sigprocmask(How, Set, Oset) /* empty */
73 # if ! HAVE_SIGINTERRUPT
74 # define siginterrupt(sig, flag) /* empty */
89 #include "filenamecat.h"
90 #include "hard-locale.h"
101 #include "quotearg.h"
103 #include "stat-time.h"
104 #include "strftime.h"
105 #include "strverscmp.h"
107 #include "mreadlink.h"
109 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
110 : (ls_mode == LS_MULTI_COL \
113 #define AUTHORS "Richard Stallman", "David MacKenzie"
115 #define obstack_chunk_alloc malloc
116 #define obstack_chunk_free free
118 /* Return an int indicating the result of comparing two integers.
119 Subtracting doesn't always work, due to overflow. */
120 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
122 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
123 # define st_author st_uid
140 /* Display letters and indicators for each filetype.
141 Keep these in sync with enum filetype. */
142 static char const filetype_letter[] = "?pcdb-lswd";
144 /* Ensure that filetype and filetype_letter have the same
145 number of elements. */
146 verify (sizeof filetype_letter - 1 == arg_directory + 1);
148 #define FILETYPE_INDICATORS \
150 C_ORPHAN, C_FIFO, C_CHR, C_DIR, C_BLK, C_FILE, \
151 C_LINK, C_SOCK, C_FILE, C_DIR \
160 /* For symbolic link, name of the file linked to, otherwise zero. */
165 enum filetype filetype;
167 /* For symbolic link and long listing, st_mode of file linked to, otherwise
171 /* SELinux security context. */
172 security_context_t scontext;
176 /* For symbolic link and color printing, true if linked-to file
177 exists, otherwise false. */
180 /* For long listings, true if the file has an access control list,
181 or an SELinux security context. */
185 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
187 /* Null is a valid character in a color indicator (think about Epson
188 printers, for example) so we have to use a length/buffer string
193 size_t len; /* Number of bytes */
194 const char *string; /* Pointer to the same */
201 # define tcgetpgrp(Fd) 0
204 static size_t quote_name (FILE *out, const char *name,
205 struct quoting_options const *options,
207 static char *make_link_name (char const *name, char const *linkname);
208 static int decode_switches (int argc, char **argv);
209 static bool file_ignored (char const *name);
210 static uintmax_t gobble_file (char const *name, enum filetype type,
211 ino_t inode, bool command_line_arg,
212 char const *dirname);
213 static void print_color_indicator (const char *name, mode_t mode, int linkok,
214 bool stat_ok, enum filetype type);
215 static void put_indicator (const struct bin_str *ind);
216 static void add_ignore_pattern (const char *pattern);
217 static void attach (char *dest, const char *dirname, const char *name);
218 static void clear_files (void);
219 static void extract_dirs_from_files (char const *dirname,
220 bool command_line_arg);
221 static void get_link_name (char const *filename, struct fileinfo *f,
222 bool command_line_arg);
223 static void indent (size_t from, size_t to);
224 static size_t calculate_columns (bool by_columns);
225 static void print_current_files (void);
226 static void print_dir (char const *name, char const *realname,
227 bool command_line_arg);
228 static void print_file_name_and_frills (const struct fileinfo *f);
229 static void print_horizontal (void);
230 static int format_user_width (uid_t u);
231 static int format_group_width (gid_t g);
232 static void print_long_format (const struct fileinfo *f);
233 static void print_many_per_line (void);
234 static void print_name_with_quoting (const char *p, mode_t mode,
235 int linkok, bool stat_ok,
237 struct obstack *stack);
238 static void prep_non_filename_text (void);
239 static void print_type_indicator (bool stat_ok, mode_t mode,
241 static void print_with_commas (void);
242 static void queue_directory (char const *name, char const *realname,
243 bool command_line_arg);
244 static void sort_files (void);
245 static void parse_ls_color (void);
246 void usage (int status);
248 /* The name this program was run with. */
251 /* Initial size of hash table.
252 Most hierarchies are likely to be shallower than this. */
253 #define INITIAL_TABLE_SIZE 30
255 /* The set of `active' directories, from the current command-line argument
256 to the level in the hierarchy at which files are being listed.
257 A directory is represented by its device and inode numbers (struct dev_ino).
258 A directory is added to this set when ls begins listing it or its
259 entries, and it is removed from the set just after ls has finished
260 processing it. This set is used solely to detect loops, e.g., with
261 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
262 static Hash_table *active_dir_set;
264 #define LOOP_DETECT (!!active_dir_set)
266 /* The table of files in the current directory:
268 `cwd_file' points to a vector of `struct fileinfo', one per file.
269 `cwd_n_alloc' is the number of elements space has been allocated for.
270 `cwd_n_used' is the number actually in use. */
272 /* Address of block containing the files that are described. */
273 static struct fileinfo *cwd_file;
275 /* Length of block that `cwd_file' points to, measured in files. */
276 static size_t cwd_n_alloc;
278 /* Index of first unused slot in `cwd_file'. */
279 static size_t cwd_n_used;
281 /* Vector of pointers to files, in proper sorted order, and the number
282 of entries allocated for it. */
283 static void **sorted_file;
284 static size_t sorted_file_alloc;
286 /* When true, in a color listing, color each symlink name according to the
287 type of file it points to. Otherwise, color them according to the `ln'
288 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
289 regardless. This is set when `ln=target' appears in LS_COLORS. */
291 static bool color_symlink_as_referent;
293 /* mode of appropriate file for colorization */
294 #define FILE_OR_LINK_MODE(File) \
295 ((color_symlink_as_referent & (File)->linkok) \
296 ? (File)->linkmode : (File)->stat.st_mode)
299 /* Record of one pending directory waiting to be listed. */
304 /* If the directory is actually the file pointed to by a symbolic link we
305 were told to list, `realname' will contain the name of the symbolic
306 link, otherwise zero. */
308 bool command_line_arg;
309 struct pending *next;
312 static struct pending *pending_dirs;
314 /* Current time in seconds and nanoseconds since 1970, updated as
315 needed when deciding whether a file is recent. */
317 static time_t current_time = TYPE_MINIMUM (time_t);
318 static int current_time_ns = -1;
320 static bool print_scontext;
322 /* Whether any of the files has an ACL. This affects the width of the
325 static bool any_has_acl;
327 /* The number of columns to use for columns containing inode numbers,
328 block sizes, link counts, owners, groups, authors, major device
329 numbers, minor device numbers, and file sizes, respectively. */
331 static int inode_number_width;
332 static int block_size_width;
333 static int nlink_width;
334 static int scontext_width;
335 static int owner_width;
336 static int group_width;
337 static int author_width;
338 static int major_device_number_width;
339 static int minor_device_number_width;
340 static int file_size_width;
344 /* long_format for lots of info, one per line.
345 one_per_line for just names, one per line.
346 many_per_line for just names, many per line, sorted vertically.
347 horizontal for just names, many per line, sorted horizontally.
348 with_commas for just names, many per line, separated by commas.
350 -l (and other options that imply -l), -1, -C, -x and -m control
355 long_format, /* -l and other options that imply -l */
356 one_per_line, /* -1 */
357 many_per_line, /* -C */
362 static enum format format;
364 /* `full-iso' uses full ISO-style dates and times. `long-iso' uses longer
365 ISO-style time stamps, though shorter than `full-iso'. `iso' uses shorter
366 ISO-style time stamps. `locale' uses locale-dependent time stamps. */
369 full_iso_time_style, /* --time-style=full-iso */
370 long_iso_time_style, /* --time-style=long-iso */
371 iso_time_style, /* --time-style=iso */
372 locale_time_style /* --time-style=locale */
375 static char const *const time_style_args[] =
377 "full-iso", "long-iso", "iso", "locale", NULL
379 static enum time_style const time_style_types[] =
381 full_iso_time_style, long_iso_time_style, iso_time_style,
384 ARGMATCH_VERIFY (time_style_args, time_style_types);
386 /* Type of time to print or sort by. Controlled by -c and -u.
387 The values of each item of this enum are important since they are
388 used as indices in the sort functions array (see sort_files()). */
392 time_mtime, /* default */
395 time_numtypes /* the number of elements of this enum */
398 static enum time_type time_type;
400 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v.
401 The values of each item of this enum are important since they are
402 used as indices in the sort functions array (see sort_files()). */
406 sort_none = -1, /* -U */
407 sort_name, /* default */
408 sort_extension, /* -X */
410 sort_version, /* -v */
412 sort_numtypes /* the number of elements of this enum */
415 static enum sort_type sort_type;
417 /* Direction of sort.
418 false means highest first if numeric,
419 lowest first if alphabetic;
420 these are the defaults.
421 true means the opposite order in each case. -r */
423 static bool sort_reverse;
425 /* True means to display owner information. -g turns this off. */
427 static bool print_owner = true;
429 /* True means to display author information. */
431 static bool print_author;
433 /* True means to display group information. -G and -o turn this off. */
435 static bool print_group = true;
437 /* True means print the user and group id's as numbers rather
440 static bool numeric_ids;
442 /* True means mention the size in blocks of each file. -s */
444 static bool print_block_size;
446 /* Human-readable options for output. */
447 static int human_output_opts;
449 /* The units to use when printing sizes other than file sizes. */
450 static uintmax_t output_block_size;
452 /* Likewise, but for file sizes. */
453 static uintmax_t file_output_block_size = 1;
455 /* Follow the output with a special string. Using this format,
456 Emacs' dired mode starts up twice as fast, and can handle all
457 strange characters in file names. */
460 /* `none' means don't mention the type of files.
461 `slash' means mention directories only, with a '/'.
462 `file_type' means mention file types.
463 `classify' means mention file types and mark executables.
465 Controlled by -F, -p, and --indicator-style. */
469 none, /* --indicator-style=none */
470 slash, /* -p, --indicator-style=slash */
471 file_type, /* --indicator-style=file-type */
472 classify /* -F, --indicator-style=classify */
475 static enum indicator_style indicator_style;
477 /* Names of indicator styles. */
478 static char const *const indicator_style_args[] =
480 "none", "slash", "file-type", "classify", NULL
482 static enum indicator_style const indicator_style_types[] =
484 none, slash, file_type, classify
486 ARGMATCH_VERIFY (indicator_style_args, indicator_style_types);
488 /* True means use colors to mark types. Also define the different
489 colors as well as the stuff for the LS_COLORS environment variable.
490 The LS_COLORS variable is now in a termcap-like format. */
492 static bool print_with_color;
496 color_never, /* 0: default or --color=never */
497 color_always, /* 1: --color=always */
498 color_if_tty /* 2: --color=tty */
501 enum Dereference_symlink
505 DEREF_COMMAND_LINE_ARGUMENTS, /* -H */
506 DEREF_COMMAND_LINE_SYMLINK_TO_DIR, /* the default, in certain cases */
507 DEREF_ALWAYS /* -L */
512 C_LEFT, C_RIGHT, C_END, C_NORM, C_FILE, C_DIR, C_LINK, C_FIFO, C_SOCK,
513 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR, C_SETUID, C_SETGID,
514 C_STICKY, C_OTHER_WRITABLE, C_STICKY_OTHER_WRITABLE
517 static const char *const indicator_name[]=
519 "lc", "rc", "ec", "no", "fi", "di", "ln", "pi", "so",
520 "bd", "cd", "mi", "or", "ex", "do", "su", "sg", "st",
524 struct color_ext_type
526 struct bin_str ext; /* The extension we're looking for */
527 struct bin_str seq; /* The sequence to output when we do */
528 struct color_ext_type *next; /* Next in list */
531 static struct bin_str color_indicator[] =
533 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
534 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
535 { 0, NULL }, /* ec: End color (replaces lc+no+rc) */
536 { LEN_STR_PAIR ("0") }, /* no: Normal */
537 { LEN_STR_PAIR ("0") }, /* fi: File: default */
538 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
539 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
540 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
541 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
542 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
543 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
544 { 0, NULL }, /* mi: Missing file: undefined */
545 { 0, NULL }, /* or: Orphaned symlink: undefined */
546 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
547 { LEN_STR_PAIR ("01;35") }, /* do: Door: bright magenta */
548 { LEN_STR_PAIR ("37;41") }, /* su: setuid: white on red */
549 { LEN_STR_PAIR ("30;43") }, /* sg: setgid: black on yellow */
550 { LEN_STR_PAIR ("37;44") }, /* st: sticky: black on blue */
551 { LEN_STR_PAIR ("34;42") }, /* ow: other-writable: blue on green */
552 { LEN_STR_PAIR ("30;42") }, /* tw: ow w/ sticky: black on green */
556 static struct color_ext_type *color_ext_list = NULL;
558 /* Buffer for color sequences */
559 static char *color_buf;
561 /* True means to check for orphaned symbolic link, for displaying
564 static bool check_symlink_color;
566 /* True means mention the inode number of each file. -i */
568 static bool print_inode;
570 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
571 other options that imply -l), and -L. */
573 static enum Dereference_symlink dereference;
575 /* True means when a directory is found, display info on its
578 static bool recursive;
580 /* True means when an argument is a directory name, display info
583 static bool immediate_dirs;
585 /* True means that directories are grouped before files. */
587 static bool directories_first;
589 /* Which files to ignore. */
593 /* Ignore files whose names start with `.', and files specified by
594 --hide and --ignore. */
597 /* Ignore `.', `..', and files specified by --ignore. */
598 IGNORE_DOT_AND_DOTDOT,
600 /* Ignore only files specified by --ignore. */
604 /* A linked list of shell-style globbing patterns. If a non-argument
605 file name matches any of these patterns, it is ignored.
606 Controlled by -I. Multiple -I options accumulate.
607 The -B option adds `*~' and `.*~' to this list. */
609 struct ignore_pattern
612 struct ignore_pattern *next;
615 static struct ignore_pattern *ignore_patterns;
617 /* Similar to IGNORE_PATTERNS, except that -a or -A causes this
618 variable itself to be ignored. */
619 static struct ignore_pattern *hide_patterns;
621 /* True means output nongraphic chars in file names as `?'.
622 (-q, --hide-control-chars)
623 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
624 independent. The algorithm is: first, obey the quoting style to get a
625 string representing the file name; then, if qmark_funny_chars is set,
626 replace all nonprintable chars in that string with `?'. It's necessary
627 to replace nonprintable chars even in quoted strings, because we don't
628 want to mess up the terminal if control chars get sent to it, and some
629 quoting methods pass through control chars as-is. */
630 static bool qmark_funny_chars;
632 /* Quoting options for file and dir name output. */
634 static struct quoting_options *filename_quoting_options;
635 static struct quoting_options *dirname_quoting_options;
637 /* The number of chars per hardware tab stop. Setting this to zero
638 inhibits the use of TAB characters for separating columns. -T */
639 static size_t tabsize;
641 /* True means print each directory name before listing it. */
643 static bool print_dir_name;
645 /* The line length to use for breaking lines in many-per-line format.
646 Can be set with -w. */
648 static size_t line_length;
650 /* If true, the file listing format requires that stat be called on
653 static bool format_needs_stat;
655 /* Similar to `format_needs_stat', but set if only the file type is
658 static bool format_needs_type;
660 /* An arbitrary limit on the number of bytes in a printed time stamp.
661 This is set to a relatively small value to avoid the need to worry
662 about denial-of-service attacks on servers that run "ls" on behalf
663 of remote clients. 1000 bytes should be enough for any practical
664 time stamp format. */
666 enum { TIME_STAMP_LEN_MAXIMUM = MAX (1000, INT_STRLEN_BOUND (time_t)) };
668 /* strftime formats for non-recent and recent files, respectively, in
671 static char const *long_time_format[2] =
673 /* strftime format for non-recent files (older than 6 months), in
674 -l output. This should contain the year, month and day (at
675 least), in an order that is understood by people in your
676 locale's territory. Please try to keep the number of used
677 screen columns small, because many people work in windows with
678 only 80 columns. But make this as wide as the other string
679 below, for recent files. */
681 /* strftime format for recent files (younger than 6 months), in -l
682 output. This should contain the month, day and time (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 above, for non-recent files. */
691 /* The set of signals that are caught. */
693 static sigset_t caught_signals;
695 /* If nonzero, the value of the pending fatal signal. */
697 static sig_atomic_t volatile interrupt_signal;
699 /* A count of the number of pending stop signals that have been received. */
701 static sig_atomic_t volatile stop_signal_count;
703 /* Desired exit status. */
705 static int exit_status;
710 /* "ls" had a minor problem (e.g., it could not stat a directory
712 LS_MINOR_PROBLEM = 1,
714 /* "ls" had more serious trouble. */
718 /* For long options that have no equivalent short option, use a
719 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
722 AUTHOR_OPTION = CHAR_MAX + 1,
725 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION,
726 FILE_TYPE_INDICATOR_OPTION,
729 GROUP_DIRECTORIES_FIRST_OPTION,
731 INDICATOR_STYLE_OPTION,
732 QUOTING_STYLE_OPTION,
733 SHOW_CONTROL_CHARS_OPTION,
740 static struct option const long_options[] =
742 {"all", no_argument, NULL, 'a'},
743 {"escape", no_argument, NULL, 'b'},
744 {"directory", no_argument, NULL, 'd'},
745 {"dired", no_argument, NULL, 'D'},
746 {"full-time", no_argument, NULL, FULL_TIME_OPTION},
747 {"group-directories-first", no_argument, NULL,
748 GROUP_DIRECTORIES_FIRST_OPTION},
749 {"human-readable", no_argument, NULL, 'h'},
750 {"inode", no_argument, NULL, 'i'},
751 {"numeric-uid-gid", no_argument, NULL, 'n'},
752 {"no-group", no_argument, NULL, 'G'},
753 {"hide-control-chars", no_argument, NULL, 'q'},
754 {"reverse", no_argument, NULL, 'r'},
755 {"size", no_argument, NULL, 's'},
756 {"width", required_argument, NULL, 'w'},
757 {"almost-all", no_argument, NULL, 'A'},
758 {"ignore-backups", no_argument, NULL, 'B'},
759 {"classify", no_argument, NULL, 'F'},
760 {"file-type", no_argument, NULL, FILE_TYPE_INDICATOR_OPTION},
761 {"si", no_argument, NULL, SI_OPTION},
762 {"dereference-command-line", no_argument, NULL, 'H'},
763 {"dereference-command-line-symlink-to-dir", no_argument, NULL,
764 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION},
765 {"hide", required_argument, NULL, HIDE_OPTION},
766 {"ignore", required_argument, NULL, 'I'},
767 {"indicator-style", required_argument, NULL, INDICATOR_STYLE_OPTION},
768 {"dereference", no_argument, NULL, 'L'},
769 {"literal", no_argument, NULL, 'N'},
770 {"quote-name", no_argument, NULL, 'Q'},
771 {"quoting-style", required_argument, NULL, QUOTING_STYLE_OPTION},
772 {"recursive", no_argument, NULL, 'R'},
773 {"format", required_argument, NULL, FORMAT_OPTION},
774 {"show-control-chars", no_argument, NULL, SHOW_CONTROL_CHARS_OPTION},
775 {"sort", required_argument, NULL, SORT_OPTION},
776 {"tabsize", required_argument, NULL, 'T'},
777 {"time", required_argument, NULL, TIME_OPTION},
778 {"time-style", required_argument, NULL, TIME_STYLE_OPTION},
779 {"color", optional_argument, NULL, COLOR_OPTION},
780 {"block-size", required_argument, NULL, BLOCK_SIZE_OPTION},
781 {"context", no_argument, 0, 'Z'},
782 {"author", no_argument, NULL, AUTHOR_OPTION},
783 {GETOPT_HELP_OPTION_DECL},
784 {GETOPT_VERSION_OPTION_DECL},
788 static char const *const format_args[] =
790 "verbose", "long", "commas", "horizontal", "across",
791 "vertical", "single-column", NULL
793 static enum format const format_types[] =
795 long_format, long_format, with_commas, horizontal, horizontal,
796 many_per_line, one_per_line
798 ARGMATCH_VERIFY (format_args, format_types);
800 static char const *const sort_args[] =
802 "none", "time", "size", "extension", "version", NULL
804 static enum sort_type const sort_types[] =
806 sort_none, sort_time, sort_size, sort_extension, sort_version
808 ARGMATCH_VERIFY (sort_args, sort_types);
810 static char const *const time_args[] =
812 "atime", "access", "use", "ctime", "status", NULL
814 static enum time_type const time_types[] =
816 time_atime, time_atime, time_atime, time_ctime, time_ctime
818 ARGMATCH_VERIFY (time_args, time_types);
820 static char const *const color_args[] =
822 /* force and none are for compatibility with another color-ls version */
823 "always", "yes", "force",
824 "never", "no", "none",
825 "auto", "tty", "if-tty", NULL
827 static enum color_type const color_types[] =
829 color_always, color_always, color_always,
830 color_never, color_never, color_never,
831 color_if_tty, color_if_tty, color_if_tty
833 ARGMATCH_VERIFY (color_args, color_types);
835 /* Information about filling a column. */
843 /* Array with information about column filledness. */
844 static struct column_info *column_info;
846 /* Maximum number of columns ever possible for this display. */
847 static size_t max_idx;
849 /* The minimum width of a column is 3: 1 character for the name and 2
850 for the separating white space. */
851 #define MIN_COLUMN_WIDTH 3
854 /* This zero-based index is used solely with the --dired option.
855 When that option is in effect, this counter is incremented for each
856 byte of output generated by this program so that the beginning
857 and ending indices (in that output) of every file name can be recorded
858 and later output themselves. */
859 static size_t dired_pos;
861 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
863 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
864 #define DIRED_FPUTS(s, stream, s_len) \
865 do {fputs (s, stream); dired_pos += s_len;} while (0)
867 /* Like DIRED_FPUTS, but for use when S is a literal string. */
868 #define DIRED_FPUTS_LITERAL(s, stream) \
869 do {fputs (s, stream); dired_pos += sizeof (s) - 1;} while (0)
871 #define DIRED_INDENT() \
875 DIRED_FPUTS_LITERAL (" ", stdout); \
879 /* With --dired, store pairs of beginning and ending indices of filenames. */
880 static struct obstack dired_obstack;
882 /* With --dired, store pairs of beginning and ending indices of any
883 directory names that appear as headers (just before `total' line)
884 for lists of directory entries. Such directory names are seen when
885 listing hierarchies using -R and when a directory is listed with at
886 least one other command line argument. */
887 static struct obstack subdired_obstack;
889 /* Save the current index on the specified obstack, OBS. */
890 #define PUSH_CURRENT_DIRED_POS(obs) \
894 obstack_grow (obs, &dired_pos, sizeof (dired_pos)); \
898 /* With -R, this stack is used to help detect directory cycles.
899 The device/inode pairs on this stack mirror the pairs in the
900 active_dir_set hash table. */
901 static struct obstack dev_ino_obstack;
903 /* Push a pair onto the device/inode stack. */
904 #define DEV_INO_PUSH(Dev, Ino) \
907 struct dev_ino *di; \
908 obstack_blank (&dev_ino_obstack, sizeof (struct dev_ino)); \
909 di = -1 + (struct dev_ino *) obstack_next_free (&dev_ino_obstack); \
910 di->st_dev = (Dev); \
911 di->st_ino = (Ino); \
915 /* Pop a dev/ino struct off the global dev_ino_obstack
916 and return that struct. */
917 static struct dev_ino
920 assert (sizeof (struct dev_ino) <= obstack_object_size (&dev_ino_obstack));
921 obstack_blank (&dev_ino_obstack, -(int) (sizeof (struct dev_ino)));
922 return *(struct dev_ino *) obstack_next_free (&dev_ino_obstack);
925 #define ASSERT_MATCHING_DEV_INO(Name, Di) \
930 assert (0 <= stat (Name, &sb)); \
931 assert (sb.st_dev == Di.st_dev); \
932 assert (sb.st_ino == Di.st_ino); \
937 /* Write to standard output PREFIX, followed by the quoting style and
938 a space-separated list of the integers stored in OS all on one line. */
941 dired_dump_obstack (const char *prefix, struct obstack *os)
945 n_pos = obstack_object_size (os) / sizeof (dired_pos);
951 pos = (size_t *) obstack_finish (os);
952 fputs (prefix, stdout);
953 for (i = 0; i < n_pos; i++)
954 printf (" %lu", (unsigned long int) pos[i]);
960 dev_ino_hash (void const *x, size_t table_size)
962 struct dev_ino const *p = x;
963 return (uintmax_t) p->st_ino % table_size;
967 dev_ino_compare (void const *x, void const *y)
969 struct dev_ino const *a = x;
970 struct dev_ino const *b = y;
971 return SAME_INODE (*a, *b) ? true : false;
975 dev_ino_free (void *x)
980 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
981 active directories. Return true if there is already a matching
982 entry in the table. */
985 visit_dir (dev_t dev, ino_t ino)
988 struct dev_ino *ent_from_table;
991 ent = xmalloc (sizeof *ent);
995 /* Attempt to insert this entry into the table. */
996 ent_from_table = hash_insert (active_dir_set, ent);
998 if (ent_from_table == NULL)
1000 /* Insertion failed due to lack of memory. */
1004 found_match = (ent_from_table != ent);
1008 /* ent was not inserted, so free it. */
1016 free_pending_ent (struct pending *p)
1024 is_colored (enum indicator_no type)
1026 size_t len = color_indicator[type].len;
1027 char const *s = color_indicator[type].string;
1029 || (len == 1 && strncmp (s, "0", 1) == 0)
1030 || (len == 2 && strncmp (s, "00", 2) == 0));
1034 restore_default_color (void)
1036 put_indicator (&color_indicator[C_LEFT]);
1037 put_indicator (&color_indicator[C_RIGHT]);
1040 /* An ordinary signal was received; arrange for the program to exit. */
1043 sighandler (int sig)
1046 signal (sig, SIG_IGN);
1047 if (! interrupt_signal)
1048 interrupt_signal = sig;
1051 /* A SIGTSTP was received; arrange for the program to suspend itself. */
1054 stophandler (int sig)
1057 signal (sig, stophandler);
1058 if (! interrupt_signal)
1059 stop_signal_count++;
1062 /* Process any pending signals. If signals are caught, this function
1063 should be called periodically. Ideally there should never be an
1064 unbounded amount of time when signals are not being processed.
1065 Signal handling can restore the default colors, so callers must
1066 immediately change colors after invoking this function. */
1069 process_signals (void)
1071 while (interrupt_signal | stop_signal_count)
1077 restore_default_color ();
1080 sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
1082 /* Reload interrupt_signal and stop_signal_count, in case a new
1083 signal was handled before sigprocmask took effect. */
1084 sig = interrupt_signal;
1085 stops = stop_signal_count;
1087 /* SIGTSTP is special, since the application can receive that signal
1088 more than once. In this case, don't set the signal handler to the
1089 default. Instead, just raise the uncatchable SIGSTOP. */
1092 stop_signal_count = stops - 1;
1096 signal (sig, SIG_DFL);
1098 /* Exit or suspend the program. */
1100 sigprocmask (SIG_SETMASK, &oldset, NULL);
1102 /* If execution reaches here, then the program has been
1103 continued (after being suspended). */
1108 main (int argc, char **argv)
1111 struct pending *thispend;
1114 /* The signals that are trapped, and the number of such signals. */
1115 static int const sig[] =
1117 /* This one is handled specially. */
1120 /* The usual suspects. */
1121 SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM,
1138 enum { nsigs = sizeof sig / sizeof sig[0] };
1141 bool caught_sig[nsigs];
1144 initialize_main (&argc, &argv);
1145 program_name = argv[0];
1146 setlocale (LC_ALL, "");
1147 bindtextdomain (PACKAGE, LOCALEDIR);
1148 textdomain (PACKAGE);
1150 initialize_exit_failure (LS_FAILURE);
1151 atexit (close_stdout);
1153 #define N_ENTRIES(Array) (sizeof Array / sizeof *(Array))
1154 assert (N_ENTRIES (color_indicator) + 1 == N_ENTRIES (indicator_name));
1156 exit_status = EXIT_SUCCESS;
1157 print_dir_name = true;
1158 pending_dirs = NULL;
1160 i = decode_switches (argc, argv);
1162 if (print_with_color)
1165 /* Test print_with_color again, because the call to parse_ls_color
1166 may have just reset it -- e.g., if LS_COLORS is invalid. */
1167 if (print_with_color)
1169 /* Avoid following symbolic links when possible. */
1170 if (is_colored (C_ORPHAN)
1171 || (is_colored (C_EXEC) && color_symlink_as_referent)
1172 || (is_colored (C_MISSING) && format == long_format))
1173 check_symlink_color = true;
1175 /* If the standard output is a controlling terminal, watch out
1176 for signals, so that the colors can be restored to the
1177 default state if "ls" is suspended or interrupted. */
1179 if (0 <= tcgetpgrp (STDOUT_FILENO))
1183 struct sigaction act;
1185 sigemptyset (&caught_signals);
1186 for (j = 0; j < nsigs; j++)
1188 sigaction (sig[j], NULL, &act);
1189 if (act.sa_handler != SIG_IGN)
1190 sigaddset (&caught_signals, sig[j]);
1193 act.sa_mask = caught_signals;
1194 act.sa_flags = SA_RESTART;
1196 for (j = 0; j < nsigs; j++)
1197 if (sigismember (&caught_signals, sig[j]))
1199 act.sa_handler = sig[j] == SIGTSTP ? stophandler : sighandler;
1200 sigaction (sig[j], &act, NULL);
1203 for (j = 0; j < nsigs; j++)
1205 caught_sig[j] = (signal (sig[j], SIG_IGN) != SIG_IGN);
1208 signal (sig[j], sig[j] == SIGTSTP ? stophandler : sighandler);
1209 siginterrupt (sig[j], 0);
1215 prep_non_filename_text ();
1218 if (dereference == DEREF_UNDEFINED)
1219 dereference = ((immediate_dirs
1220 || indicator_style == classify
1221 || format == long_format)
1223 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
1225 /* When using -R, initialize a data structure we'll use to
1226 detect any directory cycles. */
1229 active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, NULL,
1233 if (active_dir_set == NULL)
1236 obstack_init (&dev_ino_obstack);
1239 format_needs_stat = sort_type == sort_time || sort_type == sort_size
1240 || format == long_format
1242 || print_block_size;
1243 format_needs_type = (! format_needs_stat
1246 || indicator_style != none
1247 || directories_first));
1251 obstack_init (&dired_obstack);
1252 obstack_init (&subdired_obstack);
1256 cwd_file = xnmalloc (cwd_n_alloc, sizeof *cwd_file);
1266 gobble_file (".", directory, NOT_AN_INODE_NUMBER, true, "");
1268 queue_directory (".", NULL, true);
1272 gobble_file (argv[i++], unknown, NOT_AN_INODE_NUMBER, true, "");
1278 if (!immediate_dirs)
1279 extract_dirs_from_files (NULL, true);
1280 /* `cwd_n_used' might be zero now. */
1283 /* In the following if/else blocks, it is sufficient to test `pending_dirs'
1284 (and not pending_dirs->name) because there may be no markers in the queue
1285 at this point. A marker may be enqueued when extract_dirs_from_files is
1286 called with a non-empty string or via print_dir. */
1289 print_current_files ();
1291 DIRED_PUTCHAR ('\n');
1293 else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1294 print_dir_name = false;
1296 while (pending_dirs)
1298 thispend = pending_dirs;
1299 pending_dirs = pending_dirs->next;
1303 if (thispend->name == NULL)
1305 /* thispend->name == NULL means this is a marker entry
1306 indicating we've finished processing the directory.
1307 Use its dev/ino numbers to remove the corresponding
1308 entry from the active_dir_set hash table. */
1309 struct dev_ino di = dev_ino_pop ();
1310 struct dev_ino *found = hash_delete (active_dir_set, &di);
1311 /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
1313 dev_ino_free (found);
1314 free_pending_ent (thispend);
1319 print_dir (thispend->name, thispend->realname,
1320 thispend->command_line_arg);
1322 free_pending_ent (thispend);
1323 print_dir_name = true;
1326 if (print_with_color)
1330 restore_default_color ();
1333 /* Restore the default signal handling. */
1335 for (j = 0; j < nsigs; j++)
1336 if (sigismember (&caught_signals, sig[j]))
1337 signal (sig[j], SIG_DFL);
1339 for (j = 0; j < nsigs; j++)
1341 signal (sig[j], SIG_DFL);
1344 /* Act on any signals that arrived before the default was restored.
1345 This can process signals out of order, but there doesn't seem to
1346 be an easy way to do them in order, and the order isn't that
1347 important anyway. */
1348 for (j = stop_signal_count; j; j--)
1350 j = interrupt_signal;
1357 /* No need to free these since we're about to exit. */
1358 dired_dump_obstack ("//DIRED//", &dired_obstack);
1359 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1360 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1361 quoting_style_args[get_quoting_style (filename_quoting_options)]);
1366 assert (hash_get_n_entries (active_dir_set) == 0);
1367 hash_free (active_dir_set);
1373 /* Set all the option flags according to the switches specified.
1374 Return the index of the first non-option argument. */
1377 decode_switches (int argc, char **argv)
1380 char *time_style_option = NULL;
1382 /* Record whether there is an option specifying sort type. */
1383 bool sort_type_specified = false;
1385 qmark_funny_chars = false;
1387 /* initialize all switches to default settings */
1392 /* This is for the `dir' program. */
1393 format = many_per_line;
1394 set_quoting_style (NULL, escape_quoting_style);
1397 case LS_LONG_FORMAT:
1398 /* This is for the `vdir' program. */
1399 format = long_format;
1400 set_quoting_style (NULL, escape_quoting_style);
1404 /* This is for the `ls' program. */
1405 if (isatty (STDOUT_FILENO))
1407 format = many_per_line;
1408 /* See description of qmark_funny_chars, above. */
1409 qmark_funny_chars = true;
1413 format = one_per_line;
1414 qmark_funny_chars = false;
1422 time_type = time_mtime;
1423 sort_type = sort_name;
1424 sort_reverse = false;
1425 numeric_ids = false;
1426 print_block_size = false;
1427 indicator_style = none;
1428 print_inode = false;
1429 dereference = DEREF_UNDEFINED;
1431 immediate_dirs = false;
1432 ignore_mode = IGNORE_DEFAULT;
1433 ignore_patterns = NULL;
1434 hide_patterns = NULL;
1435 print_scontext = false;
1437 /* FIXME: put this in a function. */
1439 char const *q_style = getenv ("QUOTING_STYLE");
1442 int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
1444 set_quoting_style (NULL, quoting_style_vals[i]);
1447 _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
1448 quotearg (q_style));
1453 char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
1454 human_output_opts = human_options (ls_block_size, false,
1455 &output_block_size);
1456 if (ls_block_size || getenv ("BLOCK_SIZE"))
1457 file_output_block_size = output_block_size;
1462 char const *p = getenv ("COLUMNS");
1465 unsigned long int tmp_ulong;
1466 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1467 && 0 < tmp_ulong && tmp_ulong <= SIZE_MAX)
1469 line_length = tmp_ulong;
1474 _("ignoring invalid width in environment variable COLUMNS: %s"),
1484 if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1
1485 && 0 < ws.ws_col && ws.ws_col == (size_t) ws.ws_col)
1486 line_length = ws.ws_col;
1491 char const *p = getenv ("TABSIZE");
1495 unsigned long int tmp_ulong;
1496 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1497 && tmp_ulong <= SIZE_MAX)
1499 tabsize = tmp_ulong;
1504 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1510 while ((c = getopt_long (argc, argv,
1511 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1",
1512 long_options, NULL)) != -1)
1517 ignore_mode = IGNORE_MINIMAL;
1521 set_quoting_style (NULL, escape_quoting_style);
1525 time_type = time_ctime;
1529 immediate_dirs = true;
1533 /* Same as enabling -a -U and disabling -l -s. */
1534 ignore_mode = IGNORE_MINIMAL;
1535 sort_type = sort_none;
1536 sort_type_specified = true;
1538 if (format == long_format)
1539 format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
1540 print_block_size = false; /* disable -s */
1541 print_with_color = false; /* disable --color */
1544 case FILE_TYPE_INDICATOR_OPTION: /* --file-type */
1545 indicator_style = file_type;
1549 format = long_format;
1550 print_owner = false;
1554 human_output_opts = human_autoscale | human_SI | human_base_1024;
1555 file_output_block_size = output_block_size = 1;
1563 human_output_opts = 0;
1564 file_output_block_size = output_block_size = 1024;
1568 format = long_format;
1572 format = with_commas;
1577 format = long_format;
1580 case 'o': /* Just like -l, but don't display group info. */
1581 format = long_format;
1582 print_group = false;
1586 indicator_style = slash;
1590 qmark_funny_chars = true;
1594 sort_reverse = true;
1598 print_block_size = true;
1602 sort_type = sort_time;
1603 sort_type_specified = true;
1607 time_type = time_atime;
1611 sort_type = sort_version;
1612 sort_type_specified = true;
1617 unsigned long int tmp_ulong;
1618 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1619 || ! (0 < tmp_ulong && tmp_ulong <= SIZE_MAX))
1620 error (LS_FAILURE, 0, _("invalid line width: %s"),
1622 line_length = tmp_ulong;
1627 format = horizontal;
1631 if (ignore_mode == IGNORE_DEFAULT)
1632 ignore_mode = IGNORE_DOT_AND_DOTDOT;
1636 add_ignore_pattern ("*~");
1637 add_ignore_pattern (".*~");
1641 format = many_per_line;
1649 indicator_style = classify;
1652 case 'G': /* inhibit display of group info */
1653 print_group = false;
1657 dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1660 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
1661 dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
1665 add_ignore_pattern (optarg);
1669 dereference = DEREF_ALWAYS;
1673 set_quoting_style (NULL, literal_quoting_style);
1677 set_quoting_style (NULL, c_quoting_style);
1685 sort_type = sort_size;
1686 sort_type_specified = true;
1691 unsigned long int tmp_ulong;
1692 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1693 || SIZE_MAX < tmp_ulong)
1694 error (LS_FAILURE, 0, _("invalid tab size: %s"),
1696 tabsize = tmp_ulong;
1701 sort_type = sort_none;
1702 sort_type_specified = true;
1706 sort_type = sort_extension;
1707 sort_type_specified = true;
1711 /* -1 has no effect after -l. */
1712 if (format != long_format)
1713 format = one_per_line;
1717 print_author = true;
1722 struct ignore_pattern *hide = xmalloc (sizeof *hide);
1723 hide->pattern = optarg;
1724 hide->next = hide_patterns;
1725 hide_patterns = hide;
1730 sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1731 sort_type_specified = true;
1734 case GROUP_DIRECTORIES_FIRST_OPTION:
1735 directories_first = true;
1739 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1743 format = XARGMATCH ("--format", optarg, format_args, format_types);
1746 case FULL_TIME_OPTION:
1747 format = long_format;
1748 time_style_option = "full-iso";
1755 i = XARGMATCH ("--color", optarg, color_args, color_types);
1757 /* Using --color with no argument is equivalent to using
1761 print_with_color = (i == color_always
1762 || (i == color_if_tty
1763 && isatty (STDOUT_FILENO)));
1765 if (print_with_color)
1767 /* Don't use TAB characters in output. Some terminal
1768 emulators can't handle the combination of tabs and
1769 color codes on the same line. */
1775 case INDICATOR_STYLE_OPTION:
1776 indicator_style = XARGMATCH ("--indicator-style", optarg,
1777 indicator_style_args,
1778 indicator_style_types);
1781 case QUOTING_STYLE_OPTION:
1782 set_quoting_style (NULL,
1783 XARGMATCH ("--quoting-style", optarg,
1785 quoting_style_vals));
1788 case TIME_STYLE_OPTION:
1789 time_style_option = optarg;
1792 case SHOW_CONTROL_CHARS_OPTION:
1793 qmark_funny_chars = false;
1796 case BLOCK_SIZE_OPTION:
1797 human_output_opts = human_options (optarg, true, &output_block_size);
1798 file_output_block_size = output_block_size;
1802 human_output_opts = human_autoscale | human_SI;
1803 file_output_block_size = output_block_size = 1;
1807 print_scontext = true;
1810 case_GETOPT_HELP_CHAR;
1812 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1819 max_idx = MAX (1, line_length / MIN_COLUMN_WIDTH);
1821 filename_quoting_options = clone_quoting_options (NULL);
1822 if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1823 set_char_quoting (filename_quoting_options, ' ', 1);
1824 if (file_type <= indicator_style)
1827 for (p = "*=>@|" + indicator_style - file_type; *p; p++)
1828 set_char_quoting (filename_quoting_options, *p, 1);
1831 dirname_quoting_options = clone_quoting_options (NULL);
1832 set_char_quoting (dirname_quoting_options, ':', 1);
1834 /* --dired is meaningful only with --format=long (-l).
1835 Otherwise, ignore it. FIXME: warn about this?
1836 Alternatively, make --dired imply --format=long? */
1837 if (dired && format != long_format)
1840 /* If -c or -u is specified and not -l (or any other option that implies -l),
1841 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
1842 The behavior of ls when using either -c or -u but with neither -l nor -t
1843 appears to be unspecified by POSIX. So, with GNU ls, `-u' alone means
1844 sort by atime (this is the one that's not specified by the POSIX spec),
1845 -lu means show atime and sort by name, -lut means show atime and sort
1848 if ((time_type == time_ctime || time_type == time_atime)
1849 && !sort_type_specified && format != long_format)
1851 sort_type = sort_time;
1854 if (format == long_format)
1856 char *style = time_style_option;
1857 static char const posix_prefix[] = "posix-";
1860 if (! (style = getenv ("TIME_STYLE")))
1863 while (strncmp (style, posix_prefix, sizeof posix_prefix - 1) == 0)
1865 if (! hard_locale (LC_TIME))
1867 style += sizeof posix_prefix - 1;
1872 char *p0 = style + 1;
1873 char *p1 = strchr (p0, '\n');
1878 if (strchr (p1 + 1, '\n'))
1879 error (LS_FAILURE, 0, _("invalid time style format %s"),
1883 long_time_format[0] = p0;
1884 long_time_format[1] = p1;
1887 switch (XARGMATCH ("time style", style,
1891 case full_iso_time_style:
1892 long_time_format[0] = long_time_format[1] =
1893 "%Y-%m-%d %H:%M:%S.%N %z";
1896 case long_iso_time_style:
1897 case_long_iso_time_style:
1898 long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
1901 case iso_time_style:
1902 long_time_format[0] = "%Y-%m-%d ";
1903 long_time_format[1] = "%m-%d %H:%M";
1906 case locale_time_style:
1907 if (hard_locale (LC_TIME))
1909 /* Ensure that the locale has translations for both
1910 formats. If not, fall back on long-iso format. */
1912 for (i = 0; i < 2; i++)
1914 char const *locale_format =
1915 dcgettext (NULL, long_time_format[i], LC_TIME);
1916 if (locale_format == long_time_format[i])
1917 goto case_long_iso_time_style;
1918 long_time_format[i] = locale_format;
1927 /* Parse a string as part of the LS_COLORS variable; this may involve
1928 decoding all kinds of escape characters. If equals_end is set an
1929 unescaped equal sign ends the string, otherwise only a : or \0
1930 does. Set *OUTPUT_COUNT to the number of bytes output. Return
1933 The resulting string is *not* null-terminated, but may contain
1936 Note that both dest and src are char **; on return they point to
1937 the first free byte after the array and the character that ended
1938 the input string, respectively. */
1941 get_funky_string (char **dest, const char **src, bool equals_end,
1942 size_t *output_count)
1944 char num; /* For numerical codes */
1945 size_t count; /* Something to count with */
1947 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
1952 p = *src; /* We don't want to double-indirect */
1953 q = *dest; /* the whole darn time. */
1955 count = 0; /* No characters counted in yet. */
1958 state = ST_GND; /* Start in ground state. */
1959 while (state < ST_END)
1963 case ST_GND: /* Ground state (no escapes) */
1968 state = ST_END; /* End of string */
1971 state = ST_BACKSLASH; /* Backslash scape sequence */
1975 state = ST_CARET; /* Caret escape */
1981 state = ST_END; /* End */
1984 /* else fall through */
1992 case ST_BACKSLASH: /* Backslash escaped character */
2003 state = ST_OCTAL; /* Octal sequence */
2008 state = ST_HEX; /* Hex sequence */
2011 case 'a': /* Bell */
2014 case 'b': /* Backspace */
2017 case 'e': /* Escape */
2020 case 'f': /* Form feed */
2023 case 'n': /* Newline */
2026 case 'r': /* Carriage return */
2032 case 'v': /* Vtab */
2035 case '?': /* Delete */
2038 case '_': /* Space */
2041 case '\0': /* End of string */
2042 state = ST_ERROR; /* Error! */
2044 default: /* Escaped character like \ ^ : = */
2048 if (state == ST_BACKSLASH)
2057 case ST_OCTAL: /* Octal sequence */
2058 if (*p < '0' || *p > '7')
2065 num = (num << 3) + (*(p++) - '0');
2068 case ST_HEX: /* Hex sequence */
2081 num = (num << 4) + (*(p++) - '0');
2089 num = (num << 4) + (*(p++) - 'a') + 10;
2097 num = (num << 4) + (*(p++) - 'A') + 10;
2107 case ST_CARET: /* Caret escape */
2108 state = ST_GND; /* Should be the next state... */
2109 if (*p >= '@' && *p <= '~')
2111 *(q++) = *(p++) & 037;
2130 *output_count = count;
2132 return state != ST_ERROR;
2136 parse_ls_color (void)
2138 const char *p; /* Pointer to character being parsed */
2139 char *buf; /* color_buf buffer pointer */
2140 int state; /* State of parser */
2141 int ind_no; /* Indicator number */
2142 char label[3]; /* Indicator label */
2143 struct color_ext_type *ext; /* Extension we are working on */
2145 if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
2149 strcpy (label, "??");
2151 /* This is an overly conservative estimate, but any possible
2152 LS_COLORS string will *not* generate a color_buf longer than
2153 itself, so it is a safe way of allocating a buffer in
2155 buf = color_buf = xstrdup (p);
2162 case 1: /* First label character */
2170 /* Allocate new extension block and add to head of
2171 linked list (this way a later definition will
2172 override an earlier one, which can be useful for
2173 having terminal-specific defs override global). */
2175 ext = xmalloc (sizeof *ext);
2176 ext->next = color_ext_list;
2177 color_ext_list = ext;
2180 ext->ext.string = buf;
2182 state = (get_funky_string (&buf, &p, true, &ext->ext.len)
2187 state = 0; /* Done! */
2190 default: /* Assume it is file type label */
2197 case 2: /* Second label character */
2204 state = -1; /* Error */
2207 case 3: /* Equal sign after indicator label */
2208 state = -1; /* Assume failure... */
2209 if (*(p++) == '=')/* It *should* be... */
2211 for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
2213 if (STREQ (label, indicator_name[ind_no]))
2215 color_indicator[ind_no].string = buf;
2216 state = (get_funky_string (&buf, &p, false,
2217 &color_indicator[ind_no].len)
2223 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
2227 case 4: /* Equal sign after *.ext */
2230 ext->seq.string = buf;
2231 state = (get_funky_string (&buf, &p, false, &ext->seq.len)
2242 struct color_ext_type *e;
2243 struct color_ext_type *e2;
2246 _("unparsable value for LS_COLORS environment variable"));
2248 for (e = color_ext_list; e != NULL; /* empty */)
2254 print_with_color = false;
2257 if (color_indicator[C_LINK].len == 6
2258 && !strncmp (color_indicator[C_LINK].string, "target", 6))
2259 color_symlink_as_referent = true;
2262 /* Set the exit status to report a failure. If SERIOUS, it is a
2263 serious failure; otherwise, it is merely a minor problem. */
2266 set_exit_status (bool serious)
2269 exit_status = LS_FAILURE;
2270 else if (exit_status == EXIT_SUCCESS)
2271 exit_status = LS_MINOR_PROBLEM;
2274 /* Assuming a failure is serious if SERIOUS, use the printf-style
2275 MESSAGE to report the failure to access a file named FILE. Assume
2276 errno is set appropriately for the failure. */
2279 file_failure (bool serious, char const *message, char const *file)
2281 error (0, errno, message, quotearg_colon (file));
2282 set_exit_status (serious);
2285 /* Request that the directory named NAME have its contents listed later.
2286 If REALNAME is nonzero, it will be used instead of NAME when the
2287 directory name is printed. This allows symbolic links to directories
2288 to be treated as regular directories but still be listed under their
2289 real names. NAME == NULL is used to insert a marker entry for the
2290 directory named in REALNAME.
2291 If NAME is non-NULL, we use its dev/ino information to save
2292 a call to stat -- when doing a recursive (-R) traversal.
2293 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2296 queue_directory (char const *name, char const *realname, bool command_line_arg)
2298 struct pending *new = xmalloc (sizeof *new);
2299 new->realname = realname ? xstrdup (realname) : NULL;
2300 new->name = name ? xstrdup (name) : NULL;
2301 new->command_line_arg = command_line_arg;
2302 new->next = pending_dirs;
2306 /* Read directory NAME, and list the files in it.
2307 If REALNAME is nonzero, print its name instead of NAME;
2308 this is used for symbolic links to directories.
2309 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2312 print_dir (char const *name, char const *realname, bool command_line_arg)
2315 struct dirent *next;
2316 uintmax_t total_blocks = 0;
2317 static bool first = true;
2320 dirp = opendir (name);
2323 file_failure (command_line_arg, _("cannot open directory %s"), name);
2329 struct stat dir_stat;
2330 int fd = dirfd (dirp);
2332 /* If dirfd failed, endure the overhead of using stat. */
2334 ? fstat (fd, &dir_stat)
2335 : stat (name, &dir_stat)) < 0)
2337 file_failure (command_line_arg,
2338 _("cannot determine device and inode of %s"), name);
2343 /* If we've already visited this dev/inode pair, warn that
2344 we've found a loop, and do not process this directory. */
2345 if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
2347 error (0, 0, _("%s: not listing already-listed directory"),
2348 quotearg_colon (name));
2353 DEV_INO_PUSH (dir_stat.st_dev, dir_stat.st_ino);
2356 /* Read the directory entries, and insert the subfiles into the `cwd_file'
2363 /* Set errno to zero so we can distinguish between a readdir failure
2364 and when readdir simply finds that there are no more entries. */
2366 next = readdir (dirp);
2369 if (! file_ignored (next->d_name))
2371 enum filetype type = unknown;
2373 #if HAVE_STRUCT_DIRENT_D_TYPE
2374 switch (next->d_type)
2376 case DT_BLK: type = blockdev; break;
2377 case DT_CHR: type = chardev; break;
2378 case DT_DIR: type = directory; break;
2379 case DT_FIFO: type = fifo; break;
2380 case DT_LNK: type = symbolic_link; break;
2381 case DT_REG: type = normal; break;
2382 case DT_SOCK: type = sock; break;
2384 case DT_WHT: type = whiteout; break;
2388 total_blocks += gobble_file (next->d_name, type, D_INO (next),
2392 else if (errno != 0)
2394 file_failure (command_line_arg, _("reading directory %s"), name);
2395 if (errno != EOVERFLOW)
2402 if (closedir (dirp) != 0)
2404 file_failure (command_line_arg, _("closing directory %s"), name);
2405 /* Don't return; print whatever we got. */
2408 /* Sort the directory contents. */
2411 /* If any member files are subdirectories, perhaps they should have their
2412 contents listed rather than being mentioned here as files. */
2415 extract_dirs_from_files (name, command_line_arg);
2417 if (recursive | print_dir_name)
2420 DIRED_PUTCHAR ('\n');
2423 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2424 dired_pos += quote_name (stdout, realname ? realname : name,
2425 dirname_quoting_options, NULL);
2426 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2427 DIRED_FPUTS_LITERAL (":\n", stdout);
2430 if (format == long_format || print_block_size)
2433 char buf[LONGEST_HUMAN_READABLE + 1];
2437 DIRED_FPUTS (p, stdout, strlen (p));
2438 DIRED_PUTCHAR (' ');
2439 p = human_readable (total_blocks, buf, human_output_opts,
2440 ST_NBLOCKSIZE, output_block_size);
2441 DIRED_FPUTS (p, stdout, strlen (p));
2442 DIRED_PUTCHAR ('\n');
2446 print_current_files ();
2449 /* Add `pattern' to the list of patterns for which files that match are
2453 add_ignore_pattern (const char *pattern)
2455 struct ignore_pattern *ignore;
2457 ignore = xmalloc (sizeof *ignore);
2458 ignore->pattern = pattern;
2459 /* Add it to the head of the linked list. */
2460 ignore->next = ignore_patterns;
2461 ignore_patterns = ignore;
2464 /* Return true if one of the PATTERNS matches FILE. */
2467 patterns_match (struct ignore_pattern const *patterns, char const *file)
2469 struct ignore_pattern const *p;
2470 for (p = patterns; p; p = p->next)
2471 if (fnmatch (p->pattern, file, FNM_PERIOD) == 0)
2476 /* Return true if FILE should be ignored. */
2479 file_ignored (char const *name)
2481 return ((ignore_mode != IGNORE_MINIMAL
2483 && (ignore_mode == IGNORE_DEFAULT || ! name[1 + (name[1] == '.')]))
2484 || (ignore_mode == IGNORE_DEFAULT
2485 && patterns_match (hide_patterns, name))
2486 || patterns_match (ignore_patterns, name));
2489 /* POSIX requires that a file size be printed without a sign, even
2490 when negative. Assume the typical case where negative sizes are
2491 actually positive values that have wrapped around. */
2494 unsigned_file_size (off_t size)
2496 return size + (size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
2499 /* Enter and remove entries in the table `cwd_file'. */
2501 /* Empty the table of files. */
2508 for (i = 0; i < cwd_n_used; i++)
2510 struct fileinfo *f = sorted_file[i];
2515 freecon (f->scontext);
2521 any_has_acl = false;
2522 inode_number_width = 0;
2523 block_size_width = 0;
2529 major_device_number_width = 0;
2530 minor_device_number_width = 0;
2531 file_size_width = 0;
2534 /* Add a file to the current table of files.
2535 Verify that the file exists, and print an error message if it does not.
2536 Return the number of blocks that the file occupies. */
2539 gobble_file (char const *name, enum filetype type, ino_t inode,
2540 bool command_line_arg, char const *dirname)
2542 uintmax_t blocks = 0;
2545 /* An inode value prior to gobble_file necessarily came from readdir,
2546 which is not used for command line arguments. */
2547 assert (! command_line_arg || inode == NOT_AN_INODE_NUMBER);
2549 if (cwd_n_used == cwd_n_alloc)
2551 cwd_file = xnrealloc (cwd_file, cwd_n_alloc, 2 * sizeof *cwd_file);
2555 f = &cwd_file[cwd_n_used];
2556 memset (f, '\0', sizeof *f);
2557 f->stat.st_ino = inode;
2560 if (command_line_arg
2561 || format_needs_stat
2562 /* When coloring a directory (we may know the type from
2563 direct.d_type), we have to stat it in order to indicate
2564 sticky and/or other-writable attributes. */
2565 || (type == directory && print_with_color)
2566 /* When dereferencing symlinks, the inode and type must come from
2567 stat, but readdir provides the inode and type of lstat. */
2568 || ((print_inode || format_needs_type)
2569 && (type == symbolic_link || type == unknown)
2570 && (dereference == DEREF_ALWAYS
2571 || (command_line_arg && dereference != DEREF_NEVER)
2572 || color_symlink_as_referent || check_symlink_color))
2573 /* Command line dereferences are already taken care of by the above
2574 assertion that the inode number is not yet known. */
2575 || (print_inode && inode == NOT_AN_INODE_NUMBER)
2576 || (format_needs_type
2577 && (type == unknown || command_line_arg
2578 /* --indicator-style=classify (aka -F)
2579 requires that we stat each regular file
2580 to see if it's executable. */
2581 || (type == normal && (indicator_style == classify
2582 /* This is so that --color ends up
2583 highlighting files with the executable
2584 bit set even when options like -F are
2586 || (print_with_color
2587 && is_colored (C_EXEC))
2591 /* FIXME-c99: move this decl "down", once ls.c stabilizes. */
2592 bool file_has_security_context = false;
2593 /* Absolute name of this file. */
2594 char *absolute_name;
2598 if (name[0] == '/' || dirname[0] == 0)
2599 absolute_name = (char *) name;
2602 absolute_name = alloca (strlen (name) + strlen (dirname) + 2);
2603 attach (absolute_name, dirname, name);
2606 switch (dereference)
2609 err = stat (absolute_name, &f->stat);
2613 case DEREF_COMMAND_LINE_ARGUMENTS:
2614 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
2615 if (command_line_arg)
2618 err = stat (absolute_name, &f->stat);
2621 if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2624 need_lstat = (err < 0
2626 : ! S_ISDIR (f->stat.st_mode));
2630 /* stat failed because of ENOENT, maybe indicating a dangling
2631 symlink. Or stat succeeded, ABSOLUTE_NAME does not refer to a
2632 directory, and --dereference-command-line-symlink-to-dir is
2633 in effect. Fall through so that we call lstat instead. */
2636 default: /* DEREF_NEVER */
2637 err = lstat (absolute_name, &f->stat);
2642 if (err == 0 && print_scontext)
2644 int attr_len = (do_deref
2645 ? getfilecon (absolute_name, &f->scontext)
2646 : lgetfilecon (absolute_name, &f->scontext));
2647 err = (attr_len < 0);
2648 file_has_security_context = (err == 0);
2650 /* When requesting security context information, don't make
2651 ls fail just because the file (even a command line argument)
2652 isn't on the right type of file system. I.e., a getfilecon
2653 failure isn't in the same class as a stat failure. */
2654 if (err && (errno == ENOTSUP || errno == ENODATA))
2660 /* Failure to stat a command line argument leads to
2661 an exit status of 2. For other files, stat failure
2662 provokes an exit status of 1. */
2663 file_failure (command_line_arg,
2664 _("cannot access %s"), absolute_name);
2665 if (command_line_arg)
2668 f->name = xstrdup (name);
2676 if (format == long_format)
2678 int n = file_has_acl (absolute_name, &f->stat);
2679 f->have_acl = (0 < n || file_has_security_context);
2680 any_has_acl |= f->have_acl;
2682 error (0, errno, "%s", quotearg_colon (absolute_name));
2685 if (S_ISLNK (f->stat.st_mode)
2686 && (format == long_format || check_symlink_color))
2689 struct stat linkstats;
2691 get_link_name (absolute_name, f, command_line_arg);
2692 linkname = make_link_name (absolute_name, f->linkname);
2694 /* Avoid following symbolic links when possible, ie, when
2695 they won't be traced and when no indicator is needed. */
2697 && (file_type <= indicator_style || check_symlink_color)
2698 && stat (linkname, &linkstats) == 0)
2702 /* Symbolic links to directories that are mentioned on the
2703 command line are automatically traced if not being
2705 if (!command_line_arg || format == long_format
2706 || !S_ISDIR (linkstats.st_mode))
2708 /* Get the linked-to file's mode for the filetype indicator
2709 in long listings. */
2710 f->linkmode = linkstats.st_mode;
2716 /* When not distinguishing types of symlinks, pretend we know that
2717 it is stat'able, so that it will be colored as a regular symlink,
2718 and not as an orphan. */
2719 if (S_ISLNK (f->stat.st_mode) && !check_symlink_color)
2722 if (S_ISLNK (f->stat.st_mode))
2723 f->filetype = symbolic_link;
2724 else if (S_ISDIR (f->stat.st_mode))
2726 if (command_line_arg & !immediate_dirs)
2727 f->filetype = arg_directory;
2729 f->filetype = directory;
2732 f->filetype = normal;
2734 blocks = ST_NBLOCKS (f->stat);
2735 if (format == long_format || print_block_size)
2737 char buf[LONGEST_HUMAN_READABLE + 1];
2738 int len = mbswidth (human_readable (blocks, buf, human_output_opts,
2739 ST_NBLOCKSIZE, output_block_size),
2741 if (block_size_width < len)
2742 block_size_width = len;
2745 if (format == long_format)
2749 int len = format_user_width (f->stat.st_uid);
2750 if (owner_width < len)
2756 int len = format_group_width (f->stat.st_gid);
2757 if (group_width < len)
2763 int len = format_user_width (f->stat.st_author);
2764 if (author_width < len)
2771 int len = f->scontext ? strlen (f->scontext) : 0;
2772 if (scontext_width < len)
2773 scontext_width = len;
2776 if (format == long_format)
2778 char b[INT_BUFSIZE_BOUND (uintmax_t)];
2779 int b_len = strlen (umaxtostr (f->stat.st_nlink, b));
2780 if (nlink_width < b_len)
2781 nlink_width = b_len;
2783 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
2785 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2786 int len = strlen (umaxtostr (major (f->stat.st_rdev), buf));
2787 if (major_device_number_width < len)
2788 major_device_number_width = len;
2789 len = strlen (umaxtostr (minor (f->stat.st_rdev), buf));
2790 if (minor_device_number_width < len)
2791 minor_device_number_width = len;
2792 len = major_device_number_width + 2 + minor_device_number_width;
2793 if (file_size_width < len)
2794 file_size_width = len;
2798 char buf[LONGEST_HUMAN_READABLE + 1];
2799 uintmax_t size = unsigned_file_size (f->stat.st_size);
2800 int len = mbswidth (human_readable (size, buf, human_output_opts,
2801 1, file_output_block_size),
2803 if (file_size_width < len)
2804 file_size_width = len;
2811 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2812 int len = strlen (umaxtostr (f->stat.st_ino, buf));
2813 if (inode_number_width < len)
2814 inode_number_width = len;
2817 f->name = xstrdup (name);
2823 /* Return true if F refers to a directory. */
2825 is_directory (const struct fileinfo *f)
2827 return f->filetype == directory || f->filetype == arg_directory;
2830 /* Put the name of the file that FILENAME is a symbolic link to
2831 into the LINKNAME field of `f'. COMMAND_LINE_ARG indicates whether
2832 FILENAME is a command-line argument. */
2835 get_link_name (char const *filename, struct fileinfo *f, bool command_line_arg)
2837 f->linkname = mreadlink_with_size (filename, f->stat.st_size);
2838 if (f->linkname == NULL)
2839 file_failure (command_line_arg, _("cannot read symbolic link %s"),
2843 /* If `linkname' is a relative name and `name' contains one or more
2844 leading directories, return `linkname' with those directories
2845 prepended; otherwise, return a copy of `linkname'.
2846 If `linkname' is zero, return zero. */
2849 make_link_name (char const *name, char const *linkname)
2857 if (*linkname == '/')
2858 return xstrdup (linkname);
2860 /* The link is to a relative name. Prepend any leading directory
2861 in `name' to the link name. */
2862 linkbuf = strrchr (name, '/');
2864 return xstrdup (linkname);
2866 bufsiz = linkbuf - name + 1;
2867 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
2868 strncpy (linkbuf, name, bufsiz);
2869 strcpy (linkbuf + bufsiz, linkname);
2873 /* Return true if the last component of NAME is `.' or `..'
2874 This is so we don't try to recurse on `././././. ...' */
2877 basename_is_dot_or_dotdot (const char *name)
2879 char const *base = last_component (name);
2880 return dot_or_dotdot (base);
2883 /* Remove any entries from CWD_FILE that are for directories,
2884 and queue them to be listed as directories instead.
2885 DIRNAME is the prefix to prepend to each dirname
2886 to make it correct relative to ls's working dir;
2887 if it is null, no prefix is needed and "." and ".." should not be ignored.
2888 If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
2889 This is desirable when processing directories recursively. */
2892 extract_dirs_from_files (char const *dirname, bool command_line_arg)
2896 bool ignore_dot_and_dot_dot = (dirname != NULL);
2898 if (dirname && LOOP_DETECT)
2900 /* Insert a marker entry first. When we dequeue this marker entry,
2901 we'll know that DIRNAME has been processed and may be removed
2902 from the set of active directories. */
2903 queue_directory (NULL, dirname, false);
2906 /* Queue the directories last one first, because queueing reverses the
2908 for (i = cwd_n_used; i-- != 0; )
2910 struct fileinfo *f = sorted_file[i];
2912 if (is_directory (f)
2913 && (! ignore_dot_and_dot_dot
2914 || ! basename_is_dot_or_dotdot (f->name)))
2916 if (!dirname || f->name[0] == '/')
2917 queue_directory (f->name, f->linkname, command_line_arg);
2920 char *name = file_name_concat (dirname, f->name, NULL);
2921 queue_directory (name, f->linkname, command_line_arg);
2924 if (f->filetype == arg_directory)
2929 /* Now delete the directories from the table, compacting all the remaining
2932 for (i = 0, j = 0; i < cwd_n_used; i++)
2934 struct fileinfo *f = sorted_file[i];
2936 j += (f->filetype != arg_directory);
2941 /* Use strcoll to compare strings in this locale. If an error occurs,
2942 report an error and longjmp to failed_strcoll. */
2944 static jmp_buf failed_strcoll;
2947 xstrcoll (char const *a, char const *b)
2951 diff = strcoll (a, b);
2954 error (0, errno, _("cannot compare file names %s and %s"),
2955 quote_n (0, a), quote_n (1, b));
2956 set_exit_status (false);
2957 longjmp (failed_strcoll, 1);
2962 /* Comparison routines for sorting the files. */
2964 typedef void const *V;
2965 typedef int (*qsortFunc)(V a, V b);
2967 /* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants.
2968 The do { ... } while(0) makes it possible to use the macro more like
2969 a statement, without violating C89 rules: */
2970 #define DIRFIRST_CHECK(a, b) \
2973 bool a_is_dir = is_directory ((struct fileinfo const *) a); \
2974 bool b_is_dir = is_directory ((struct fileinfo const *) b); \
2975 if (a_is_dir && !b_is_dir) \
2976 return -1; /* a goes before b */ \
2977 if (!a_is_dir && b_is_dir) \
2978 return 1; /* b goes before a */ \
2982 /* Define the 8 different sort function variants required for each sortkey.
2983 KEY_NAME is a token describing the sort key, e.g., ctime, atime, size.
2984 KEY_CMP_FUNC is a function to compare records based on that key, e.g.,
2985 ctime_cmp, atime_cmp, size_cmp. Append KEY_NAME to the string,
2986 '[rev_][x]str{cmp|coll}[_df]_', to create each function name. */
2987 #define DEFINE_SORT_FUNCTIONS(key_name, key_cmp_func) \
2988 /* direct, non-dirfirst versions */ \
2989 static int xstrcoll_##key_name (V a, V b) \
2990 { return key_cmp_func (a, b, xstrcoll); } \
2991 static int strcmp_##key_name (V a, V b) \
2992 { return key_cmp_func (a, b, strcmp); } \
2994 /* reverse, non-dirfirst versions */ \
2995 static int rev_xstrcoll_##key_name (V a, V b) \
2996 { return key_cmp_func (b, a, xstrcoll); } \
2997 static int rev_strcmp_##key_name (V a, V b) \
2998 { return key_cmp_func (b, a, strcmp); } \
3000 /* direct, dirfirst versions */ \
3001 static int xstrcoll_df_##key_name (V a, V b) \
3002 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, xstrcoll); } \
3003 static int strcmp_df_##key_name (V a, V b) \
3004 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, strcmp); } \
3006 /* reverse, dirfirst versions */ \
3007 static int rev_xstrcoll_df_##key_name (V a, V b) \
3008 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, xstrcoll); } \
3009 static int rev_strcmp_df_##key_name (V a, V b) \
3010 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, strcmp); }
3013 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
3014 int (*cmp) (char const *, char const *))
3016 int diff = timespec_cmp (get_stat_ctime (&b->stat),
3017 get_stat_ctime (&a->stat));
3018 return diff ? diff : cmp (a->name, b->name);
3022 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
3023 int (*cmp) (char const *, char const *))
3025 int diff = timespec_cmp (get_stat_mtime (&b->stat),
3026 get_stat_mtime (&a->stat));
3027 return diff ? diff : cmp (a->name, b->name);
3031 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
3032 int (*cmp) (char const *, char const *))
3034 int diff = timespec_cmp (get_stat_atime (&b->stat),
3035 get_stat_atime (&a->stat));
3036 return diff ? diff : cmp (a->name, b->name);
3040 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
3041 int (*cmp) (char const *, char const *))
3043 int diff = longdiff (b->stat.st_size, a->stat.st_size);
3044 return diff ? diff : cmp (a->name, b->name);
3048 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
3049 int (*cmp) (char const *, char const *))
3051 return cmp (a->name, b->name);
3054 /* Compare file extensions. Files with no extension are `smallest'.
3055 If extensions are the same, compare by filenames instead. */
3058 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
3059 int (*cmp) (char const *, char const *))
3061 char const *base1 = strrchr (a->name, '.');
3062 char const *base2 = strrchr (b->name, '.');
3063 int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
3064 return diff ? diff : cmp (a->name, b->name);
3067 DEFINE_SORT_FUNCTIONS (ctime, cmp_ctime)
3068 DEFINE_SORT_FUNCTIONS (mtime, cmp_mtime)
3069 DEFINE_SORT_FUNCTIONS (atime, cmp_atime)
3070 DEFINE_SORT_FUNCTIONS (size, cmp_size)
3071 DEFINE_SORT_FUNCTIONS (name, cmp_name)
3072 DEFINE_SORT_FUNCTIONS (extension, cmp_extension)
3074 /* Compare file versions.
3075 Unlike all other compare functions above, cmp_version depends only
3076 on strverscmp, which does not fail (even for locale reasons), and does not
3077 need a secondary sort key.
3078 All the other sort options, in fact, need xstrcoll and strcmp variants,
3079 because they all use a string comparison (either as the primary or secondary
3080 sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
3081 locale reasons. Last, strverscmp is ALWAYS available in coreutils,
3082 thanks to the gnulib library. */
3084 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
3086 return strverscmp (a->name, b->name);
3089 static int xstrcoll_version (V a, V b)
3090 { return cmp_version (a, b); }
3091 static int rev_xstrcoll_version (V a, V b)
3092 { return cmp_version (b, a); }
3093 static int xstrcoll_df_version (V a, V b)
3094 { DIRFIRST_CHECK (a, b); return cmp_version (a, b); }
3095 static int rev_xstrcoll_df_version (V a, V b)
3096 { DIRFIRST_CHECK (a, b); return cmp_version (b, a); }
3099 /* We have 2^3 different variants for each sortkey function
3100 (for 3 independent sort modes).
3101 The function pointers stored in this array must be dereferenced as:
3103 sort_variants[sort_key][use_strcmp][reverse][dirs_first]
3105 Note that the order in which sortkeys are listed in the function pointer
3106 array below is defined by the order of the elements in the time_type and
3109 #define LIST_SORTFUNCTION_VARIANTS(key_name) \
3112 { xstrcoll_##key_name, xstrcoll_df_##key_name }, \
3113 { rev_xstrcoll_##key_name, rev_xstrcoll_df_##key_name }, \
3116 { strcmp_##key_name, strcmp_df_##key_name }, \
3117 { rev_strcmp_##key_name, rev_strcmp_df_##key_name }, \
3121 static qsortFunc sort_functions[][2][2][2] =
3123 LIST_SORTFUNCTION_VARIANTS (name),
3124 LIST_SORTFUNCTION_VARIANTS (extension),
3125 LIST_SORTFUNCTION_VARIANTS (size),
3129 { xstrcoll_version, xstrcoll_df_version },
3130 { rev_xstrcoll_version, rev_xstrcoll_df_version },
3133 /* We use NULL for the strcmp variants of version comparison
3134 since as explained in cmp_version definition, version comparison
3135 does not rely on xstrcoll, so it will never longjmp, and never
3136 need to try the strcmp fallback. */
3143 /* last are time sort functions */
3144 LIST_SORTFUNCTION_VARIANTS (mtime),
3145 LIST_SORTFUNCTION_VARIANTS (ctime),
3146 LIST_SORTFUNCTION_VARIANTS (atime)
3149 /* The number of sortkeys is calculated as
3150 the number of elements in the sort_type enum (i.e. sort_numtypes) +
3151 the number of elements in the time_type enum (i.e. time_numtypes) - 1
3152 This is because when sort_type==sort_time, we have up to
3153 time_numtypes possible sortkeys.
3155 This line verifies at compile-time that the array of sort functions has been
3156 initialized for all possible sortkeys. */
3157 verify (ARRAY_CARDINALITY (sort_functions)
3158 == sort_numtypes + time_numtypes - 1 );
3160 /* Set up SORTED_FILE to point to the in-use entries in CWD_FILE, in order. */
3163 initialize_ordering_vector (void)
3166 for (i = 0; i < cwd_n_used; i++)
3167 sorted_file[i] = &cwd_file[i];
3170 /* Sort the files now in the table. */
3177 if (sorted_file_alloc < cwd_n_used + cwd_n_used / 2)
3180 sorted_file = xnmalloc (cwd_n_used, 3 * sizeof *sorted_file);
3181 sorted_file_alloc = 3 * cwd_n_used;
3184 initialize_ordering_vector ();
3186 if (sort_type == sort_none)
3189 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
3190 ignore strcoll failures, as a failing strcoll might be a
3191 comparison function that is not a total order, and if we ignored
3192 the failure this might cause qsort to dump core. */
3194 if (! setjmp (failed_strcoll))
3195 use_strcmp = false; /* strcoll() succeeded */
3199 assert (sort_type != sort_version);
3200 initialize_ordering_vector ();
3203 /* When sort_type == sort_time, use time_type as subindex. */
3204 mpsort ((void const **) sorted_file, cwd_n_used,
3205 sort_functions[sort_type + (sort_type == sort_time ? time_type : 0)]
3206 [use_strcmp][sort_reverse]
3207 [directories_first]);
3210 /* List all the files now in the table. */
3213 print_current_files (void)
3220 for (i = 0; i < cwd_n_used; i++)
3222 print_file_name_and_frills (sorted_file[i]);
3228 print_many_per_line ();
3232 print_horizontal ();
3236 print_with_commas ();
3240 for (i = 0; i < cwd_n_used; i++)
3242 print_long_format (sorted_file[i]);
3243 DIRED_PUTCHAR ('\n');
3249 /* Return the expected number of columns in a long-format time stamp,
3250 or zero if it cannot be calculated. */
3253 long_time_expected_width (void)
3255 static int width = -1;
3260 struct tm const *tm = localtime (&epoch);
3261 char buf[TIME_STAMP_LEN_MAXIMUM + 1];
3263 /* In case you're wondering if localtime can fail with an input time_t
3264 value of 0, let's just say it's very unlikely, but not inconceivable.
3265 The TZ environment variable would have to specify a time zone that
3266 is 2**31-1900 years or more ahead of UTC. This could happen only on
3267 a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
3268 However, this is not possible with Solaris 10 or glibc-2.3.5, since
3269 their implementations limit the offset to 167:59 and 24:00, resp. */
3273 nstrftime (buf, sizeof buf, long_time_format[0], tm, 0, 0);
3275 width = mbsnwidth (buf, len, 0);
3285 /* Get the current time. */
3288 get_current_time (void)
3290 #if HAVE_CLOCK_GETTIME && defined CLOCK_REALTIME
3292 struct timespec timespec;
3293 if (clock_gettime (CLOCK_REALTIME, ×pec) == 0)
3295 current_time = timespec.tv_sec;
3296 current_time_ns = timespec.tv_nsec;
3302 /* The clock does not have nanosecond resolution, so get the maximum
3303 possible value for the current time that is consistent with the
3304 reported clock. That way, files are not considered to be in the
3305 future merely because their time stamps have higher resolution
3306 than the clock resolution. */
3308 #if HAVE_GETTIMEOFDAY
3310 struct timeval timeval;
3311 gettimeofday (&timeval, NULL);
3312 current_time = timeval.tv_sec;
3313 current_time_ns = timeval.tv_usec * 1000 + 999;
3316 current_time = time (NULL);
3317 current_time_ns = 999999999;
3321 /* Print the user or group name NAME, with numeric id ID, using a
3322 print width of WIDTH columns. */
3325 format_user_or_group (char const *name, unsigned long int id, int width)
3331 int width_gap = width - mbswidth (name, 0);
3332 int pad = MAX (0, width_gap);
3333 fputs (name, stdout);
3334 len = strlen (name) + pad;
3342 printf ("%*lu ", width, id);
3346 dired_pos += len + 1;
3349 /* Print the name or id of the user with id U, using a print width of
3353 format_user (uid_t u, int width, bool stat_ok)
3355 format_user_or_group (! stat_ok ? "?" :
3356 (numeric_ids ? NULL : getuser (u)), u, width);
3359 /* Likewise, for groups. */
3362 format_group (gid_t g, int width, bool stat_ok)
3364 format_user_or_group (! stat_ok ? "?" :
3365 (numeric_ids ? NULL : getgroup (g)), g, width);
3368 /* Return the number of columns that format_user_or_group will print. */
3371 format_user_or_group_width (char const *name, unsigned long int id)
3375 int len = mbswidth (name, 0);
3376 return MAX (0, len);
3380 char buf[INT_BUFSIZE_BOUND (unsigned long int)];
3381 sprintf (buf, "%lu", id);
3382 return strlen (buf);
3386 /* Return the number of columns that format_user will print. */
3389 format_user_width (uid_t u)
3391 return format_user_or_group_width (numeric_ids ? NULL : getuser (u), u);
3394 /* Likewise, for groups. */
3397 format_group_width (gid_t g)
3399 return format_user_or_group_width (numeric_ids ? NULL : getgroup (g), g);
3403 /* Print information about F in long format. */
3406 print_long_format (const struct fileinfo *f)
3410 [LONGEST_HUMAN_READABLE + 1 /* inode */
3411 + LONGEST_HUMAN_READABLE + 1 /* size in blocks */
3412 + sizeof (modebuf) - 1 + 1 /* mode string */
3413 + INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
3414 + LONGEST_HUMAN_READABLE + 2 /* major device number */
3415 + LONGEST_HUMAN_READABLE + 1 /* minor device number */
3416 + TIME_STAMP_LEN_MAXIMUM + 1 /* max length of time/date */
3422 struct timespec when_timespec;
3423 struct tm *when_local;
3425 /* Compute the mode string, except remove the trailing space if no
3426 file in this directory has an ACL or SELinux security context. */
3428 filemodestring (&f->stat, modebuf);
3431 modebuf[0] = filetype_letter[f->filetype];
3432 memset (modebuf + 1, '?', 10);
3437 else if (f->have_acl)
3443 when_timespec = get_stat_ctime (&f->stat);
3446 when_timespec = get_stat_mtime (&f->stat);
3449 when_timespec = get_stat_atime (&f->stat);
3455 when = when_timespec.tv_sec;
3456 when_ns = when_timespec.tv_nsec;
3462 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3463 sprintf (p, "%*s ", inode_number_width,
3464 (f->stat.st_ino == NOT_AN_INODE_NUMBER
3466 : umaxtostr (f->stat.st_ino, hbuf)));
3467 /* Increment by strlen (p) here, rather than by inode_number_width + 1.
3468 The latter is wrong when inode_number_width is zero. */
3472 if (print_block_size)
3474 char hbuf[LONGEST_HUMAN_READABLE + 1];
3475 char const *blocks =
3478 : human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts,
3479 ST_NBLOCKSIZE, output_block_size));
3481 for (pad = block_size_width - mbswidth (blocks, 0); 0 < pad; pad--)
3483 while ((*p++ = *blocks++))
3488 /* The last byte of the mode string is the POSIX
3489 "optional alternate access method flag". */
3491 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3492 sprintf (p, "%s %*s ", modebuf, nlink_width,
3493 ! f->stat_ok ? "?" : umaxtostr (f->stat.st_nlink, hbuf));
3495 /* Increment by strlen (p) here, rather than by, e.g.,
3496 sizeof modebuf - 2 + any_has_acl + 1 + nlink_width + 1.
3497 The latter is wrong when nlink_width is zero. */
3502 if (print_owner | print_group | print_author | print_scontext)
3504 DIRED_FPUTS (buf, stdout, p - buf);
3507 format_user (f->stat.st_uid, owner_width, f->stat_ok);
3510 format_group (f->stat.st_gid, group_width, f->stat_ok);
3513 format_user (f->stat.st_author, author_width, f->stat_ok);
3516 format_user_or_group ((f->scontext ? f->scontext : "?"),
3523 && (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode)))
3525 char majorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3526 char minorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3527 int blanks_width = (file_size_width
3528 - (major_device_number_width + 2
3529 + minor_device_number_width));
3530 sprintf (p, "%*s, %*s ",
3531 major_device_number_width + MAX (0, blanks_width),
3532 umaxtostr (major (f->stat.st_rdev), majorbuf),
3533 minor_device_number_width,
3534 umaxtostr (minor (f->stat.st_rdev), minorbuf));
3535 p += file_size_width + 1;
3539 char hbuf[LONGEST_HUMAN_READABLE + 1];
3543 : human_readable (unsigned_file_size (f->stat.st_size),
3544 hbuf, human_output_opts, 1, file_output_block_size));
3546 for (pad = file_size_width - mbswidth (size, 0); 0 < pad; pad--)
3548 while ((*p++ = *size++))
3553 when_local = localtime (&when_timespec.tv_sec);
3557 if (f->stat_ok && when_local)
3559 time_t six_months_ago;
3563 /* If the file appears to be in the future, update the current
3564 time, in case the file happens to have been modified since
3565 the last time we checked the clock. */
3566 if (current_time < when
3567 || (current_time == when && current_time_ns < when_ns))
3569 /* Note that get_current_time calls gettimeofday which, on some non-
3570 compliant systems, clobbers the buffer used for localtime's result.
3571 But it's ok here, because we use a gettimeofday wrapper that
3572 saves and restores the buffer around the gettimeofday call. */
3573 get_current_time ();
3576 /* Consider a time to be recent if it is within the past six
3577 months. A Gregorian year has 365.2425 * 24 * 60 * 60 ==
3578 31556952 seconds on the average. Write this value as an
3579 integer constant to avoid floating point hassles. */
3580 six_months_ago = current_time - 31556952 / 2;
3581 recent = (six_months_ago <= when
3582 && (when < current_time
3583 || (when == current_time && when_ns <= current_time_ns)));
3584 fmt = long_time_format[recent];
3586 s = nstrftime (p, TIME_STAMP_LEN_MAXIMUM + 1, fmt,
3587 when_local, 0, when_ns);
3595 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
3600 /* The time cannot be converted using the desired format, so
3601 print it as a huge integer number of seconds. */
3602 char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
3603 sprintf (p, "%*s ", long_time_expected_width (),
3606 : (TYPE_SIGNED (time_t)
3607 ? imaxtostr (when, hbuf)
3608 : umaxtostr (when, hbuf))));
3612 DIRED_FPUTS (buf, stdout, p - buf);
3613 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
3614 f->stat_ok, f->filetype, &dired_obstack);
3616 if (f->filetype == symbolic_link)
3620 DIRED_FPUTS_LITERAL (" -> ", stdout);
3621 print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1,
3622 f->stat_ok, f->filetype, NULL);
3623 if (indicator_style != none)
3624 print_type_indicator (true, f->linkmode, unknown);
3627 else if (indicator_style != none)
3628 print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
3631 /* Output to OUT a quoted representation of the file name NAME,
3632 using OPTIONS to control quoting. Produce no output if OUT is NULL.
3633 Store the number of screen columns occupied by NAME's quoted
3634 representation into WIDTH, if non-NULL. Return the number of bytes
3638 quote_name (FILE *out, const char *name, struct quoting_options const *options,
3641 char smallbuf[BUFSIZ];
3642 size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, name, -1, options);
3644 size_t displayed_width IF_LINT (= 0);
3646 if (len < sizeof smallbuf)
3650 buf = alloca (len + 1);
3651 quotearg_buffer (buf, len + 1, name, -1, options);
3654 if (qmark_funny_chars)
3659 char const *p = buf;
3660 char const *plimit = buf + len;
3662 displayed_width = 0;
3667 case ' ': case '!': case '"': case '#': case '%':
3668 case '&': case '\'': case '(': case ')': case '*':
3669 case '+': case ',': case '-': case '.': case '/':
3670 case '0': case '1': case '2': case '3': case '4':
3671 case '5': case '6': case '7': case '8': case '9':
3672 case ':': case ';': case '<': case '=': case '>':
3674 case 'A': case 'B': case 'C': case 'D': case 'E':
3675 case 'F': case 'G': case 'H': case 'I': case 'J':
3676 case 'K': case 'L': case 'M': case 'N': case 'O':
3677 case 'P': case 'Q': case 'R': case 'S': case 'T':
3678 case 'U': case 'V': case 'W': case 'X': case 'Y':
3680 case '[': case '\\': case ']': case '^': case '_':
3681 case 'a': case 'b': case 'c': case 'd': case 'e':
3682 case 'f': case 'g': case 'h': case 'i': case 'j':
3683 case 'k': case 'l': case 'm': case 'n': case 'o':
3684 case 'p': case 'q': case 'r': case 's': case 't':
3685 case 'u': case 'v': case 'w': case 'x': case 'y':
3686 case 'z': case '{': case '|': case '}': case '~':
3687 /* These characters are printable ASCII characters. */
3689 displayed_width += 1;
3692 /* If we have a multibyte sequence, copy it until we
3693 reach its end, replacing each non-printable multibyte
3694 character with a single question mark. */
3696 mbstate_t mbstate = { 0, };
3703 bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
3705 if (bytes == (size_t) -1)
3707 /* An invalid multibyte sequence was
3708 encountered. Skip one input byte, and
3709 put a question mark. */
3712 displayed_width += 1;
3716 if (bytes == (size_t) -2)
3718 /* An incomplete multibyte character
3719 at the end. Replace it entirely with
3723 displayed_width += 1;
3728 /* A null wide character was encountered. */
3734 /* A printable multibyte character.
3736 for (; bytes > 0; --bytes)
3738 displayed_width += w;
3742 /* An unprintable multibyte character.
3743 Replace it entirely with a question
3747 displayed_width += 1;
3750 while (! mbsinit (&mbstate));
3755 /* The buffer may have shrunk. */
3762 char const *plimit = buf + len;
3766 if (! isprint (to_uchar (*p)))
3770 displayed_width = len;
3773 else if (width != NULL)
3777 displayed_width = mbsnwidth (buf, len, 0);
3781 char const *p = buf;
3782 char const *plimit = buf + len;
3784 displayed_width = 0;
3787 if (isprint (to_uchar (*p)))
3795 fwrite (buf, 1, len, out);
3797 *width = displayed_width;
3802 print_name_with_quoting (const char *p, mode_t mode, int linkok,
3803 bool stat_ok, enum filetype type,
3804 struct obstack *stack)
3806 if (print_with_color)
3807 print_color_indicator (p, mode, linkok, stat_ok, type);
3810 PUSH_CURRENT_DIRED_POS (stack);
3812 dired_pos += quote_name (stdout, p, filename_quoting_options, NULL);
3815 PUSH_CURRENT_DIRED_POS (stack);
3817 if (print_with_color)
3820 prep_non_filename_text ();
3825 prep_non_filename_text (void)
3827 if (color_indicator[C_END].string != NULL)
3828 put_indicator (&color_indicator[C_END]);
3831 put_indicator (&color_indicator[C_LEFT]);
3832 put_indicator (&color_indicator[C_NORM]);
3833 put_indicator (&color_indicator[C_RIGHT]);
3837 /* Print the file name of `f' with appropriate quoting.
3838 Also print file size, inode number, and filetype indicator character,
3839 as requested by switches. */
3842 print_file_name_and_frills (const struct fileinfo *f)
3844 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
3847 printf ("%*s ", format == with_commas ? 0 : inode_number_width,
3848 umaxtostr (f->stat.st_ino, buf));
3850 if (print_block_size)
3851 printf ("%*s ", format == with_commas ? 0 : block_size_width,
3852 human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts,
3853 ST_NBLOCKSIZE, output_block_size));
3856 printf ("%*s ", format == with_commas ? 0 : scontext_width,
3857 (f->scontext ? f->scontext : "?"));
3859 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
3860 f->stat_ok, f->filetype, NULL);
3862 if (indicator_style != none)
3863 print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
3866 /* Given these arguments describing a file, return the single-byte
3867 type indicator, or 0. */
3869 get_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
3873 if (stat_ok ? S_ISREG (mode) : type == normal)
3875 if (stat_ok && indicator_style == classify && (mode & S_IXUGO))
3882 if (stat_ok ? S_ISDIR (mode) : type == directory || type == arg_directory)
3884 else if (indicator_style == slash)
3886 else if (stat_ok ? S_ISLNK (mode) : type == symbolic_link)
3888 else if (stat_ok ? S_ISFIFO (mode) : type == fifo)
3890 else if (stat_ok ? S_ISSOCK (mode) : type == sock)
3892 else if (stat_ok && S_ISDOOR (mode))
3901 print_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
3903 char c = get_type_indicator (stat_ok, mode, type);
3909 print_color_indicator (const char *name, mode_t mode, int linkok,
3910 bool stat_ok, enum filetype filetype)
3913 struct color_ext_type *ext; /* Color extension */
3914 size_t len; /* Length of name */
3916 /* Is this a nonexistent file? If so, linkok == -1. */
3918 if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
3922 static enum indicator_no filetype_indicator[] = FILETYPE_INDICATORS;
3923 type = filetype_indicator[filetype];
3930 if ((mode & S_ISUID) != 0)
3932 else if ((mode & S_ISGID) != 0)
3934 else if ((mode & S_IXUGO) != 0)
3937 else if (S_ISDIR (mode))
3939 if ((mode & S_ISVTX) && (mode & S_IWOTH))
3940 type = C_STICKY_OTHER_WRITABLE;
3941 else if ((mode & S_IWOTH) != 0)
3942 type = C_OTHER_WRITABLE;
3943 else if ((mode & S_ISVTX) != 0)
3948 else if (S_ISLNK (mode))
3949 type = ((!linkok && color_indicator[C_ORPHAN].string)
3950 ? C_ORPHAN : C_LINK);
3951 else if (S_ISFIFO (mode))
3953 else if (S_ISSOCK (mode))
3955 else if (S_ISBLK (mode))
3957 else if (S_ISCHR (mode))
3959 else if (S_ISDOOR (mode))
3963 /* Classify a file of some other type as C_ORPHAN. */
3968 /* Check the file's suffix only if still classified as C_FILE. */
3972 /* Test if NAME has a recognized suffix. */
3974 len = strlen (name);
3975 name += len; /* Pointer to final \0. */
3976 for (ext = color_ext_list; ext != NULL; ext = ext->next)
3978 if (ext->ext.len <= len
3979 && strncmp (name - ext->ext.len, ext->ext.string,
3985 put_indicator (&color_indicator[C_LEFT]);
3986 put_indicator (ext ? &(ext->seq) : &color_indicator[type]);
3987 put_indicator (&color_indicator[C_RIGHT]);
3990 /* Output a color indicator (which may contain nulls). */
3992 put_indicator (const struct bin_str *ind)
3999 for (i = ind->len; i != 0; --i)
4004 length_of_file_name_and_frills (const struct fileinfo *f)
4008 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
4011 len += 1 + (format == with_commas
4012 ? strlen (umaxtostr (f->stat.st_ino, buf))
4013 : inode_number_width);
4015 if (print_block_size)
4016 len += 1 + (format == with_commas
4017 ? strlen (human_readable (ST_NBLOCKS (f->stat), buf,
4018 human_output_opts, ST_NBLOCKSIZE,
4020 : block_size_width);
4023 len += 1 + (format == with_commas ? strlen (f->scontext) : scontext_width);
4025 quote_name (NULL, f->name, filename_quoting_options, &name_width);
4028 if (indicator_style != none)
4030 char c = get_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4038 print_many_per_line (void)
4040 size_t row; /* Current row. */
4041 size_t cols = calculate_columns (true);
4042 struct column_info const *line_fmt = &column_info[cols - 1];
4044 /* Calculate the number of rows that will be in each column except possibly
4045 for a short column on the right. */
4046 size_t rows = cwd_n_used / cols + (cwd_n_used % cols != 0);
4048 for (row = 0; row < rows; row++)
4051 size_t filesno = row;
4054 /* Print the next row. */
4057 struct fileinfo const *f = sorted_file[filesno];
4058 size_t name_length = length_of_file_name_and_frills (f);
4059 size_t max_name_length = line_fmt->col_arr[col++];
4060 print_file_name_and_frills (f);
4063 if (filesno >= cwd_n_used)
4066 indent (pos + name_length, pos + max_name_length);
4067 pos += max_name_length;
4074 print_horizontal (void)
4078 size_t cols = calculate_columns (false);
4079 struct column_info const *line_fmt = &column_info[cols - 1];
4080 struct fileinfo const *f = sorted_file[0];
4081 size_t name_length = length_of_file_name_and_frills (f);
4082 size_t max_name_length = line_fmt->col_arr[0];
4084 /* Print first entry. */
4085 print_file_name_and_frills (f);
4088 for (filesno = 1; filesno < cwd_n_used; ++filesno)
4090 size_t col = filesno % cols;
4099 indent (pos + name_length, pos + max_name_length);
4100 pos += max_name_length;
4103 f = sorted_file[filesno];
4104 print_file_name_and_frills (f);
4106 name_length = length_of_file_name_and_frills (f);
4107 max_name_length = line_fmt->col_arr[col];
4113 print_with_commas (void)
4118 for (filesno = 0; filesno < cwd_n_used; filesno++)
4120 struct fileinfo const *f = sorted_file[filesno];
4121 size_t len = length_of_file_name_and_frills (f);
4127 if (pos + len + 2 < line_length)
4139 putchar (separator);
4142 print_file_name_and_frills (f);
4148 /* Assuming cursor is at position FROM, indent up to position TO.
4149 Use a TAB character instead of two or more spaces whenever possible. */
4152 indent (size_t from, size_t to)
4156 if (tabsize != 0 && to / tabsize > (from + 1) / tabsize)
4159 from += tabsize - from % tabsize;
4169 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
4170 /* FIXME: maybe remove this function someday. See about using a
4171 non-malloc'ing version of file_name_concat. */
4174 attach (char *dest, const char *dirname, const char *name)
4176 const char *dirnamep = dirname;
4178 /* Copy dirname if it is not ".". */
4179 if (dirname[0] != '.' || dirname[1] != 0)
4182 *dest++ = *dirnamep++;
4183 /* Add '/' if `dirname' doesn't already end with it. */
4184 if (dirnamep > dirname && dirnamep[-1] != '/')
4192 /* Allocate enough column info suitable for the current number of
4193 files and display columns, and initialize the info to represent the
4194 narrowest possible columns. */
4197 init_column_info (void)
4200 size_t max_cols = MIN (max_idx, cwd_n_used);
4202 /* Currently allocated columns in column_info. */
4203 static size_t column_info_alloc;
4205 if (column_info_alloc < max_cols)
4207 size_t new_column_info_alloc;
4210 if (max_cols < max_idx / 2)
4212 /* The number of columns is far less than the display width
4213 allows. Grow the allocation, but only so that it's
4214 double the current requirements. If the display is
4215 extremely wide, this avoids allocating a lot of memory
4216 that is never needed. */
4217 column_info = xnrealloc (column_info, max_cols,
4218 2 * sizeof *column_info);
4219 new_column_info_alloc = 2 * max_cols;
4223 column_info = xnrealloc (column_info, max_idx, sizeof *column_info);
4224 new_column_info_alloc = max_idx;
4227 /* Allocate the new size_t objects by computing the triangle
4228 formula n * (n + 1) / 2, except that we don't need to
4229 allocate the part of the triangle that we've already
4230 allocated. Check for address arithmetic overflow. */
4232 size_t column_info_growth = new_column_info_alloc - column_info_alloc;
4233 size_t s = column_info_alloc + 1 + new_column_info_alloc;
4234 size_t t = s * column_info_growth;
4235 if (s < new_column_info_alloc || t / column_info_growth != s)
4237 p = xnmalloc (t / 2, sizeof *p);
4240 /* Grow the triangle by parceling out the cells just allocated. */
4241 for (i = column_info_alloc; i < new_column_info_alloc; i++)
4243 column_info[i].col_arr = p;
4247 column_info_alloc = new_column_info_alloc;
4250 for (i = 0; i < max_cols; ++i)
4254 column_info[i].valid_len = true;
4255 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
4256 for (j = 0; j <= i; ++j)
4257 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
4261 /* Calculate the number of columns needed to represent the current set
4262 of files in the current display width. */
4265 calculate_columns (bool by_columns)
4267 size_t filesno; /* Index into cwd_file. */
4268 size_t cols; /* Number of files across. */
4270 /* Normally the maximum number of columns is determined by the
4271 screen width. But if few files are available this might limit it
4273 size_t max_cols = MIN (max_idx, cwd_n_used);
4275 init_column_info ();
4277 /* Compute the maximum number of possible columns. */
4278 for (filesno = 0; filesno < cwd_n_used; ++filesno)
4280 struct fileinfo const *f = sorted_file[filesno];
4281 size_t name_length = length_of_file_name_and_frills (f);
4284 for (i = 0; i < max_cols; ++i)
4286 if (column_info[i].valid_len)
4288 size_t idx = (by_columns
4289 ? filesno / ((cwd_n_used + i) / (i + 1))
4290 : filesno % (i + 1));
4291 size_t real_length = name_length + (idx == i ? 0 : 2);
4293 if (column_info[i].col_arr[idx] < real_length)
4295 column_info[i].line_len += (real_length
4296 - column_info[i].col_arr[idx]);
4297 column_info[i].col_arr[idx] = real_length;
4298 column_info[i].valid_len = (column_info[i].line_len
4305 /* Find maximum allowed columns. */
4306 for (cols = max_cols; 1 < cols; --cols)
4308 if (column_info[cols - 1].valid_len)
4318 if (status != EXIT_SUCCESS)
4319 fprintf (stderr, _("Try `%s --help' for more information.\n"),
4323 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
4325 List information about the FILEs (the current directory by default).\n\
4326 Sort entries alphabetically if none of -cftuvSUX nor --sort.\n\
4330 Mandatory arguments to long options are mandatory for short options too.\n\
4333 -a, --all do not ignore entries starting with .\n\
4334 -A, --almost-all do not list implied . and ..\n\
4335 --author with -l, print the author of each file\n\
4336 -b, --escape print octal escapes for nongraphic characters\n\
4339 --block-size=SIZE use SIZE-byte blocks\n\
4340 -B, --ignore-backups do not list implied entries ending with ~\n\
4341 -c with -lt: sort by, and show, ctime (time of last\n\
4342 modification of file status information)\n\
4343 with -l: show ctime and sort by name\n\
4344 otherwise: sort by ctime\n\
4347 -C list entries by columns\n\
4348 --color[=WHEN] control whether color is used to distinguish file\n\
4349 types. WHEN may be `never', `always', or `auto'\n\
4350 -d, --directory list directory entries instead of contents,\n\
4351 and do not dereference symbolic links\n\
4352 -D, --dired generate output designed for Emacs' dired mode\n\
4355 -f do not sort, enable -aU, disable -ls --color\n\
4356 -F, --classify append indicator (one of */=>@|) to entries\n\
4357 --file-type likewise, except do not append `*'\n\
4358 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
4359 single-column -1, verbose -l, vertical -C\n\
4360 --full-time like -l --time-style=full-iso\n\
4363 -g like -l, but do not list owner\n\
4366 --group-directories-first\n\
4367 group directories before files\n\
4370 -G, --no-group in a long listing, don't print group names\n\
4371 -h, --human-readable with -l, print sizes in human readable format\n\
4372 (e.g., 1K 234M 2G)\n\
4373 --si likewise, but use powers of 1000 not 1024\n\
4376 -H, --dereference-command-line\n\
4377 follow symbolic links listed on the command line\n\
4378 --dereference-command-line-symlink-to-dir\n\
4379 follow each command line symbolic link\n\
4380 that points to a directory\n\
4381 --hide=PATTERN do not list implied entries matching shell PATTERN\n\
4382 (overridden by -a or -A)\n\
4385 --indicator-style=WORD append indicator with style WORD to entry names:\n\
4386 none (default), slash (-p),\n\
4387 file-type (--file-type), classify (-F)\n\
4388 -i, --inode print the index number of each file\n\
4389 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
4390 -k like --block-size=1K\n\
4393 -l use a long listing format\n\
4394 -L, --dereference when showing file information for a symbolic\n\
4395 link, show information for the file the link\n\
4396 references rather than for the link itself\n\
4397 -m fill width with a comma separated list of entries\n\
4400 -n, --numeric-uid-gid like -l, but list numeric user and group IDs\n\
4401 -N, --literal print raw entry names (don't treat e.g. control\n\
4402 characters specially)\n\
4403 -o like -l, but do not list group information\n\
4404 -p, --indicator-style=slash\n\
4405 append / indicator to directories\n\
4408 -q, --hide-control-chars print ? instead of non graphic characters\n\
4409 --show-control-chars show non graphic characters as-is (default\n\
4410 unless program is `ls' and output is a terminal)\n\
4411 -Q, --quote-name enclose entry names in double quotes\n\
4412 --quoting-style=WORD use quoting style WORD for entry names:\n\
4413 literal, locale, shell, shell-always, c, escape\n\
4416 -r, --reverse reverse order while sorting\n\
4417 -R, --recursive list subdirectories recursively\n\
4418 -s, --size print the size of each file, in blocks\n\
4421 -S sort by file size\n\
4422 --sort=WORD sort by WORD instead of name: none -U,\n\
4423 extension -X, size -S, time -t, version -v\n\
4424 --time=WORD with -l, show time as WORD instead of modification\n\
4425 time: atime -u, access -u, use -u, ctime -c,\n\
4426 or status -c; use specified time as sort key\n\
4430 --time-style=STYLE with -l, show times using style STYLE:\n\
4431 full-iso, long-iso, iso, locale, +FORMAT.\n\
4432 FORMAT is interpreted like `date'; if FORMAT is\n\
4433 FORMAT1<newline>FORMAT2, FORMAT1 applies to\n\
4434 non-recent files and FORMAT2 to recent files;\n\
4435 if STYLE is prefixed with `posix-', STYLE\n\
4436 takes effect only outside the POSIX locale\n\
4439 -t sort by modification time\n\
4440 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
4443 -u with -lt: sort by, and show, access time\n\
4444 with -l: show access time and sort by name\n\
4445 otherwise: sort by access time\n\
4446 -U do not sort; list entries in directory order\n\
4447 -v sort by version\n\
4450 -w, --width=COLS assume screen width instead of current value\n\
4451 -x list entries by lines instead of by columns\n\
4452 -X sort alphabetically by entry extension\n\
4453 -Z, --context print any SELinux security context of each file\n\
4454 -1 list one file per line\n\
4456 fputs (HELP_OPTION_DESCRIPTION, stdout);
4457 fputs (VERSION_OPTION_DESCRIPTION, stdout);
4459 SIZE may be (or may be an integer optionally followed by) one of following:\n\
4460 kB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
4464 By default, color is not used to distinguish types of files. That is\n\
4465 equivalent to using --color=none. Using the --color option without the\n\
4466 optional WHEN argument is equivalent to using --color=always. With\n\
4467 --color=auto, color codes are output only if standard output is connected\n\
4468 to a terminal (tty). The environment variable LS_COLORS can influence the\n\
4469 colors, and can be set easily by the dircolors command.\n\
4473 Exit status is 0 if OK, 1 if minor problems, 2 if serious trouble.\n\
4475 emit_bug_reporting_address ();